openpiv

Particle Image Velocimetry (PIV) analysis with OpenPIV. Use when extracting velocity fields from PIV image pairs, analyzing fluid dynamics or flow visualization experiments, cross-correlating interrogation windows, validating and replacing spurious PIV vectors, or computing vorticity, strain rate, a

By k-dense-ai · 467 installs

npx skills add k-dense-ai/scientific-agent-skills --skill openpiv

Source repository · Upstream listing

OpenPIV Overview OpenPIV (Open Particle Image Velocimetry) analyzes fluid flow from PIV image pairs. It covers preprocessing, cross correlation, vector validation, outlier replacement, smoothing, and scaling to physical units. Targets openpiv 0.26.1 . Synthetic checks ran on Python 3.13, NumPy 2.5.3, SciPy 1.18.1, scikit image 0.26.0, and Matplotlib 3.11.2. Rust was not installed; use backend="scipy" for the tested path. See [review evidence](references/advanced algorithms.md review sources and verification). When to use Use this skill when working with experimental PIV or flow visualization image pairs: measuring 2D velocity fields, tuning interrogation window parameters, validating vectors, or deriving vorticity, strain rate, and turbulence statistics. For simulating flow rather than measuring it, use a CFD skill instead. Quick Start Install OpenPIV: Run PIV analysis on an image pair: Or use the bundled CLI, which also checks inputs and preserves masks and processing parameters: Core Concepts PIV Fundamentals Particle Image Velocimetry is an optical method for measuring fluid velocity by tracking illuminated tracer particles between two images. Process flow: 1. Capture an image pair ( frame a , frame b ) separated by a known time dt . 2. Divide the images into interrogation windows. 3. Cross correlate matching windows to find peak displacement. 4. Validate vectors (signal to noise, global range, local median). 5. Replace spurious vectors with interpolated values. 6. Scale pixel displacements to physical units. Interrogation Window Parameters window size — correlation window in pixels (typically 16–128). Larger windows give better correlation but coarser spatial resolution. overlap — pixels shared between adjacent windows (typically 50–75% of window size ). Higher overlap raises vector density and cost, but adjacent vectors become correlated rather than independent. search area size — the window searched in the second frame. Must be ≥ window size ; a few pixels larger accommodates larger displacements. Both "circular" and "linear" support extended search. The CLI chooses zero padded "linear" with normalized correlation=True for it; this does not recover arbitrary displacement or eliminate spurious peaks. Grid stride is search area size overlap , so overlap must be smaller than the search area. Rules of thumb: keep the largest displacement under about a quarter of window size , and aim for 5–10 particles per window. Signal to Noise Ratio s2n measures how distinct the correlation peak is. sig2noise method controls how it is computed — "peak2mean" (the function default) or "peak2peak" . The two are on different scales , so a threshold tuned for one is meaningless for the other. Typical peak2peak thresholds are 1.05–1.3. Common Operations Dynamic Masking Masking lives in openpiv.preprocess and returns (image, mask) . Use floating point copies to avoid unsigned subtraction artifacts. Inspect masks on both frames before analysis. Preserve the union mask a mask b as excluded physical regions. The CLI samples it at interrogation centers, saves it, and keeps those velocities NaN after replacement. Windows straddling an object can still be biased: inspect/dilate masks for the experiment. In 0.26.1 method="edges" indexes with uint8 instead of bool, potentially corrupting the image or failing. The CLI refuses it; use intensity masking or a verified boolean mask in a custom workflow. Multi Pass Processing Multi pass (window deformation) lives in openpiv.windef , driven by a PIVSettings dataclass. pyprocess has no multi pass entry point. simple multipass validates, replaces outliers, fills remaining NaNs with zeros, and transforms coordinates. Keep its flags: repaired/zero filled output is not an independent measurement. Always pass settings: its no settings path has two window sizes but three iterations in 0.26.1. Units trap: simple multipass and its alias multigrid windef ignore settings.dt and settings.scaling factor ; convert their arrays as above. Batch windef.piv(settings) applies both before saving — do not scale its files again. The simple wrapper does not honor all batch preprocessing/output switches. For control over individual passes, windef.first pass and windef.multipass img deform are the lower level building blocks. Validation and Post Processing Validation Methods Every validator returns a boolean array where True marks a spurious vector . Also reject nonfinite u , v , and s2n : sig2noise val alone does not flag NaN. Set these thresholds in the units of u and v , not in pixels per frame. extended search area piv divides by dt , so with dt=0.02 a 3 px/frame displacement arrives as 150 px/s. The thresholds above suit that case; the ( 30, 30) figure that PIV literature and PIVSettings.min max u disp use is a px/frame limit, and applying it to px/s output rejects the entire field. Correlate with dt=1 to validate displacements before conversion, or adjust thresholds to the actual velocity units (including both time and calibration factors). Outlier Replacement method accepts "localmean" , "disk" , or "distance" ; an invalid name raises ValueError when filling missing cells. Use kernel size =2 for "distance" : size 1 truncates all neighbor weights to zero in 0.26.1 and leaves holes. Replacement fills the flagged positions with interpolated values — if you then overwrite them with NaN, the replacement was wasted. Choose one or the other: Smoothing Smoothing is openpiv.smoothn.smoothn ; there is no openpiv.smooth module. It returns a tuple whose first element is the smoothed field. NaN/Inf are missing observations; supply a copy because it can modify input. Zero filling holes first incorrectly treats them as measured zeros. Visualization Vector Field Plotting display vector field reads a saved vectors file and calls plt.show() internally, so select a non interactive backend for batch runs. Set image extents explicitly: the helper's on img=True infers them from the last vector and can stretch overlays when windows leave unused margins. The CLI plots with the actual image bounds. Custom Visualization Analysis Functions scripts/analyze.py bundles these against a params.npz written by runner.py . It infers the physical grid spacing from the saved coordinates, so the derivatives come out per unit length: The standalone forms, if you would rather compute them inline: Vorticity For the single pass extended search grid, spacing is (search area size overlap) / scaling factor in physical units; it reduces to (window size overlap) / scaling factor only when the two window sizes match. Prefer differences of the saved x and y coordinates, especially after multipass processing. Leaving dx=1.0 yields vorticity per grid cell, not per unit length. See [OpenPIV coordinate generation](https://openpiv.readthedocs.io/en/stable/src/tutorial1.html). Sign convention: the CLI writes y = image height / scaling factor y and negates v , keeping rows in image order. Saved y decreases down the array. The standalone forms need signed dy (negative here), or use PIVAnalyzer , which reads orientation. Positive dy changes the y derivative contribution and can even cancel real rotation. Strain Rate Turbulence Statistics Caveat: subtracting the spatial mean of one frame measures spatial variance, which equals turbulent intensity only under justified homogeneity/ergodicity assumptions. Reynolds decomposition needs an ensemble: subtract its mean field from each realization. The legacy tke key is only two component spatial variance energy, not full turbulent kinetic energy. The analyzer excludes flagged vectors by default; compute statistics(include interpolated=True) includes repaired ones. CLI Usage CLI Options Option Default Description image required Image file; specify exactly twice for the pair output dir results Output directory (created if absent) window size 32 Interrogation window size (px) overlap 12 Search grid overlap (px), nonnegative and less than search area search area 38 Search area size (px), must be ≥ window size dt 0.02 Time between frames (s) scaling 96.52 Scaling factor, pixels per physical unit (e.g. px/mm) threshold 1.05 peak2peak signal to noise threshold mask none none or dynamic ( openpiv.preprocess.dynamic masking ) mask method intensity Only intensity is usable in 0.26.1; edges is refused backend scipy scipy , auto , or rust ; Rust requires its extension drop invalid off NaN out flagged vectors instead of keeping interpolated values verbose off Print progress messages Verify an install end to end against OpenPIV's own bundled image pair: Output Files vectors.txt — tab delimited, %.4e formatted, with a x y u v flags mask comment header params.npz — x , y , u , v , flags , mask , s2n , timing/calibration/window parameters, requested backend, and OpenPIV version. Coordinates use physical units; velocity uses units/s. vector field.png — vector field drawn over the first frame flags is float, 0 for valid and 1 for flagged. mask=1 marks an excluded object region, independently of flags. Preserve both with the measured field. Best Practices Parameter Selection 1. Window size — 32×32 suits most cases. 64/128 for better correlation at coarser resolution; 16/24 for finer resolution at the cost of noise. 2. Overlap — 50–75% of window size. 3. Threshold — raise it to reject more vectors; always re tune after switching sig2noise method . 4. Scaling factor — calibrate against a known reference such as a calibration grid, and keep the units straight ( 96.52 in OpenPIV's test1 tutorial data is px/mm). Image Quality Particles visible and evenly distributed, 5–10 per interrogation window No saturated or overexposed regions Minimal background noise; consider background subtraction across a run Processing Tips 1. Start from the defaults, then tune against the vector field you get. 2. Inspect the s2n distribution — a low median means poor correlation, not a bad threshold. 3. Visualize early; obvious problems (uniform vectors, edge artifacts) show up immediately. 4. Use multi pass ( windef ) for flows with large velocity gradients or displacements. 5. Mask reflections and solid boundaries rather than letting them generate vectors. Resources references/ advanced algorithms.md — correlation and subpixel methods, multi pass window deformation, PIVSettings fields, 3D and phase separation modules Load the reference when detailed algorithm or settings information is needed.