API reference¶
This is a complete api reference to the PIVPy package.
The pivpy.io module¶
pivpy.io
I/O utilities and readers for PIV datasets.
This module provides: - Backward-compatible helpers (e.g. load_vec, load_openpiv_txt, load_directory) - A plugin architecture for auto-detecting file formats (PIVReaderRegistry) - Convenience creators for synthetic datasets used across the test suite.
The core data model is an xarray.Dataset with: - dims: (‘y’, ‘x’, ‘t’) - coords: 1D x, 1D y, 1D t - variables: u, v, and chc (validity / mask)
- class pivpy.io.PIVMetadata(pos_units: 'str' = 'pix', vel_units: 'str' = 'pix', time_units: 'str' = 'frame', delta_t: 'float' = 0.0, variables: 'list[str]' = <factory>, rows: 'Optional[int]' = None, cols: 'Optional[int]' = None, frame: 'int' = 0)[source]¶
- pivpy.io.batchf(filename, fun, *args, nodisp=True, **kwargs)[source]¶
Execute a function over a series of files (PIVMAT-style).
This is inspired by PIVMAT’s
batchf: it processes fields from disk one-by-one (no big in-memory list of Datasets), applyingfunto each.- Parameters:
filename – File pattern or path. Supports glob wildcards (e.g.
*) and a safe subset of PIVMAT-style bracket expansion viapivpy.pivmat_compat.expandstr()(e.g.'Run[1:10,6].vec').fun – Either a callable
fun(ds, *args, **kwargs)or a string naming a PIV accessor method (e.g.'azprofile'will callds.piv.azprofile).nodisp – If False, prints each call.
*args – Passed through to
fun.**kwargs – Passed through to
fun.
- Returns:
List of per-file results.
- Return type:
- pivpy.io.getattribute(f, attrname=None)[source]¶
Get metadata/attributes for a field or file (PIVMAT-inspired).
- pivpy.io.getfilenum(name, pat, opt='filedir')[source]¶
Extract numeric indices from matching file/dir names (PIVMAT-inspired).
- pivpy.io.getframedt(filename)[source]¶
Compute time interval(s) between frames for IMX/IM7 (PIVMAT-inspired).
This requires
lvpyioand DaVis time series metadata. If unavailable, returnsarray([0.0]).
- pivpy.io.getimx(A, frame=0)[source]¶
PIVMAT
getimxequivalent.In PIVPy, if
Ais anxarray.Dataset, this returns the 2D coordinate meshes and the scalar/vector arrays for the selected frame.
- pivpy.io.getpivtime(f, *args)[source]¶
Return acquisition times in seconds for dataset(s) or files (PIVMAT-inspired).
For PIVPy datasets, this uses
ds['t']andds.attrs['delta_t']. If the option ‘0’ is provided, the first time is shifted to 0.
- pivpy.io.getvar(s, reqname=None, mode=None)[source]¶
Parse variables encoded in a string like
p1=v1_p2=v2_...(PIVMAT-inspired).
- pivpy.io.im2pivmat(im, *, x=None, y=None, namew='I', unit='au', dtype=<class 'numpy.float32'>)[source]¶
Convert an image into a PIVPy scalar Dataset (PIVMAT-inspired).
This is the xarray equivalent of PIVMAT’s
im2pivmat.m.The result is a single-frame Dataset with dims
('y','x','t')and a scalar variablew.- Parameters:
im – 2D image array (interpreted as
(y, x)).x – Optional 1D coordinate vectors. Defaults are 1..N (MATLAB-like).
y – Optional 1D coordinate vectors. Defaults are 1..N (MATLAB-like).
namew – Display name for the scalar (stored in
w.attrs['long_name']).unit – Unit string for coordinates and intensity (default:
'au').dtype – Output dtype for
w(default:numpy.float32).
- Returns:
Dataset with variable
wand coordinatesx,y,t.- Return type:
- pivpy.io.loadarrayvec(pathname, fname, *opts)[source]¶
PIVMAT
loadarrayvecequivalent.Loads a 2D array of vector fields: directories matched by
pathnameand files matched byfnameinside each directory.Returns a nested list
out[i][j]whereiindexes directories andjindexes files.
- pivpy.io.loadpivtxt(fname)[source]¶
PIVMAT
loadpivtxtcompatible loader.Reads a text export containing at least 4 columns: x y u v. Header lines starting with non-numeric characters are preserved in
ds.attrs['Attributes'].
- pivpy.io.loadvec(filename=None, *args, **kwargs)[source]¶
PIVMAT-compatible loader (wrapper over
read_piv()).This is a Python port of the user-facing behavior of PIVMAT’s
loadvec.m. It supports file patterns (glob + bracket expansion) and can load multiple files at once.- Parameters:
filename – Path/pattern, a sequence of paths, or a 1-based numeric index selecting from files in the current directory (PIVMAT behavior).
frame – Optional frame override passed through to
read_piv().verbose – If True, prints each file being loaded.
- Returns:
Single dataset if one file is matched, otherwise a list of datasets.
- Return type:
- pivpy.io.multivortex(nfield=1, nsize=128, numvortex=8, *opts)[source]¶
Generate random Burgers vortices (PIVMAT-compatible).
Port of PIVMAT’s
multivortex.m.- Returns:
Dataset with dims
(y, x, t)wheretindexes fields.- Return type:
- pivpy.io.openim7(filename, **kwargs)[source]¶
PIVMAT
openim7equivalent (loads a DaVis IM7 image as a scalar Dataset).This requires
lvpyioat runtime. If it is not available, aImportErroris raised.
- pivpy.io.openimg(filename, **kwargs)[source]¶
PIVMAT
openimgequivalent (loads a DaVis IMG image as a scalar Dataset).This requires
lvpyioat runtime.
- pivpy.io.openimx(filename, **kwargs)[source]¶
PIVMAT
openimxequivalent (loads a DaVis IMX image as a scalar Dataset).This requires
lvpyioat runtime.
- pivpy.io.openset(filename)[source]¶
PIVMAT
opensetequivalent.PIVMAT loads all files in the directory associated with a .set. In Python, this loads the directory adjacent to the .set file that shares its base name (if present), otherwise loads the parent directory.
- pivpy.io.openvec(filename)[source]¶
PIVMAT
openvecequivalent.In MATLAB, this is used by the file browser to populate the workspace. In Python, this simply calls
loadvec()and returns the dataset(s).
- pivpy.io.parse_header(filepath)[source]¶
Parse basic metadata.
Returns a 7-tuple for the test suite: (variables, units, rows, cols, delta_t, frame, header)
- pivpy.io.randvec(n=256, nf=1, slope=1.6666666666666667, nc=3.0, nl=None, *, seed=0)[source]¶
Generate a synthetic 2D divergence-free random vector field (PIVMAT-compatible).
Port of PIVMAT’s
randvec.m.The field is constructed in Fourier space with random phase, a prescribed power-law slope, and an incompressibility constraint (2D divergence-free).
- Parameters:
n – Grid size (produces an
n x nfield). PIVMAT assumes evenn.nf – Number of independent fields (time frames).
slope – Spectral slope $k^{-mathrm{slope}}$ (default $5/3$).
nc – Small-scale cut-off (in units of the vector mesh). For $k > nc$ the spectrum decays Gaussianly.
nl – Large-scale cut-off (in units of the vector mesh). For $k < nl$ the spectrum behaves as $k^2$. Defaults to
n/3.seed – RNG seed used for deterministic synthesis.
- Returns:
Dataset with variables
u,vandchcand dims(y, x, t).- Return type:
- pivpy.io.readsetfile(filename, attrname=None)[source]¶
Read attributes from a DaVis .set or .exp file (PIVMAT-inspired).
This is a pragmatic parser intended for typical DaVis key/value content. It returns a flat dict of attributes.
If
attrnameis provided, returns only that value (case-insensitive, ignoring underscores).
- pivpy.io.readvec(name, comments=1, columns=5)[source]¶
Read a DaVis .vec text export into a numeric array (PIVMAT-inspired).
This is a light-weight port of PIVMAT’s
readvec.m.- Returns:
(header, data)wheredatahas shape(j, i, columns).- Return type:
- pivpy.io.set_default_attrs(dataset)[source]¶
Apply default units and common attributes (sets missing only).
- pivpy.io.vec2mat(f, filename, key='v', squeeze=True)[source]¶
Export a vector/scalar dataset to a MATLAB
.matfile (PIVMAT-compatible helper).This is a pragmatic Python equivalent of PIVMAT’s
vec2mat.- Parameters:
f – Dataset containing coords
x,yand variablesu,vorw.filename – Output path. If it does not end with
.matit will be appended.key – Top-level MATLAB variable name.
squeeze – If True, singleton dimensions are removed in the saved arrays.
- Returns:
The written filename.
- Return type:
The pivpy.compute_funcs module¶
- pivpy.compute_funcs.bwfilter2d(arr2, filtsize, order)[source]¶
2D Butterworth filter in Fourier space (PIVMAT-inspired).
- Parameters:
arr2 – 2D array.
filtsize – Cutoff size in grid units. If 0, returns input.
order – Butterworth order. Positive -> low-pass. Negative -> high-pass.
Notes
This follows the PIVMAT convention: - k is measured in index space on the FFT-shifted grid. - kc = n / filtsize, where n = min(nx, ny). - Transfer: T(k)=1/(1+(k/kc)^(order/2)).
- pivpy.compute_funcs.corrf(x, dim='x', *, normalize=False, nan_as_zero=True, nowarning=False, r_dim='r')[source]¶
Spatial correlation function and integral scales (PIVMAT-inspired).
This is a Python/xarray equivalent of PIVMAT’s
corrf.mfor a scalar field.The correlation along a direction is defined (conceptually) as: f(r) = < F(x,y) F(x+r,y) > where <..> denotes spatial averaging over the orthogonal direction and ensemble averaging over any remaining dimensions (e.g. time).
- Parameters:
x – Scalar field as an
xarray.DataArray(typically with dims including'x'and'y', and optionally't').dim – Direction of separation:
'x'/'y'(recommended) or MATLAB-like1/2.normalize – If True, normalize the correlation so that
f(0)=1.nan_as_zero – If True, treat NaNs as missing data and replace by 0 before correlating. (Missing values encoded as 0 are handled by the PIVMAT-style weighting in
corrx/corrm.)nowarning – If True, suppress warnings when crossover radii are undefined.
r_dim – Name of the separation-length coordinate in the returned Dataset.
- Returns:
Dataset with 1D variable
fover coordinaterand scalar variablesisinf, r0, is0, r1, is1, r2, is2, r5, is5.- Return type:
- pivpy.compute_funcs.corrm(x, dim=1, *, half=False, nan_as_zero=True, lag_dim='lag')[source]¶
Matrix correlation along one dimension (PIVMAT-compatible).
For a 2D matrix shaped (M, N): -
dim=1correlates each column vector -> output shape (2*M-1, N) -dim=2correlates each row vector -> output shape (M, 2*N-1)For xarray objects,
dimmay be a dimension name and the function generalizes to N-D by correlating along that dimension.
- pivpy.compute_funcs.corrx(x, y=None, *, half=False, nan_as_zero=True)[source]¶
Vector correlation (PIVMAT-compatible).
This ports the behavior of PIVMAT’s
corrx.m. Zero-padding is used outside the signal support, and each lag is normalized by the number of non-zero products (so missing data encoded as zeros does not bias the result).- Parameters:
x – 1D vectors. If
yis None, autocorrelation is computed.y – 1D vectors. If
yis None, autocorrelation is computed.half – If True, return only non-negative lags (including zero-lag).
nan_as_zero – If True, NaNs are treated as missing data and replaced by 0.
- Returns:
Correlation vector of length
2*N-1(orNifhalf=True).- Return type:
- pivpy.compute_funcs.filter2d(arr2, filtsize=1.0, method='gauss', *, mode='valid')[source]¶
2D spatial filter by normalized convolution (PIVMAT-inspired).
- Parameters:
arr2 – 2D field to filter.
filtsize – Filter size in mesh units (Gaussian sigma-like scale).
method – ‘gauss’, ‘flat’, or ‘igauss’ (integrated Gaussian).
mode – ‘valid’ (default) or ‘same’. Matches Matlab conv2 modes.
Notes
Missing values are treated as NaN and excluded from the convolution by using a weight-mask normalization.
- pivpy.compute_funcs.filter2d_kernel(filtsize=1.0, method='gauss')[source]¶
Return the normalized 2D kernel used by
filter2d().- Parameters:
filtsize – Filter size in mesh units.
method – ‘gauss’, ‘flat’, or ‘igauss’.
- pivpy.compute_funcs.gradientf(scalar)[source]¶
Gradient of a scalar field (PIVMAT-inspired).
This is a Python/xarray equivalent of PIVMAT’s
gradientf.m.- Parameters:
scalar – Scalar field as an
xarray.DataArraywith dims includingxandy. A time dimension (typicallyt) is allowed and is preserved.- Returns:
Dataset with variables
uandvcontaining the partial derivativesd(scalar)/dxandd(scalar)/dy.- Return type:
Notes
Coordinates are taken from the input DataArray.
Units are propagated if both the scalar and coordinate units are available.
- pivpy.compute_funcs.histf(scalar, bin=None, opt='')[source]¶
Histogram of a scalar field (PIVMAT-inspired).
This is a Python/xarray equivalent of PIVMAT’s
histf.mfor scalar fields. Values are stacked over all dimensions.- Parameters:
scalar – Scalar field as an
xarray.DataArray.bin – Optional 1D array of bin centers. If not provided, a default binning is estimated from the mean and standard deviation of the first frame (if a
tdimension exists) or from the full field otherwise.opt – Option string. If it contains
'0', zero values are included.
- Returns:
Dataset with coordinate
binand variableh.- Return type:
- pivpy.compute_funcs.inpaint_missing_2d(a2, *, method=0, missing='0nan')[source]¶
Inpaint missing values in a 2D array (PIVMAT
interpf-style).Missing values are defined as NaNs and/or zeros.
- Parameters:
a2 – 2D array.
method –
Integer method selector (PIVMAT-inspired):
0: Laplacian (harmonic) inpainting via sparse linear solve.1: Nearest-neighbor fill (fast, robust).2: Linear interpolation viascipy.interpolate.griddata.
missing – Missing-value definition: -
"0nan"(default): treat both0andNaNas missing. -"nan": treat only NaNs as missing. -"0": treat only zeros as missing.
- Returns:
Filled array (float).
- Return type:
- pivpy.compute_funcs.interpf(data, *, method=0, variables=None, missing='0nan')[source]¶
Interpolate missing data in a Dataset (PIVMAT
interpfport).Missing data are values equal to 0 and/or NaN (configurable via
missing). The interpolation is applied frame-by-frame alongtif present.- Parameters:
data – Input Dataset.
method – See
inpaint_missing_2d().variables – Variables to process. Default: [‘u’,’v’] if present, else [‘w’] if present, else all data variables.
missing – See
inpaint_missing_2d().
- Returns:
New Dataset with missing values filled.
- Return type:
- pivpy.compute_funcs.interpolat_zeros_2d(m, *, fill=False, max_iter=None, nan_as_zero=True)[source]¶
Interpolate zeros in a 2D field using 4-neighbor averaging.
This mirrors the behavior of PIVMAT’s legacy
interpolat.m: - Replaces zero entries by the mean of their nonzero 4-neighbors. - Iffill=True, repeats until no zeros remain (ormax_iter).- Parameters:
m – 2D array (or xarray DataArray with at least two dims).
fill – Iterate until no zeros remain.
max_iter – Optional hard stop for iterations (recommended when fill=True).
nan_as_zero – If True, NaNs are treated as 0 (missing/invalid).
- pivpy.compute_funcs.jpdfscal(s1, s2, *, nbin=101)[source]¶
Joint histogram (“joint PDF” in PIVMAT terminology) of two scalar fields.
This ports the behavior of PIVMAT’s
jpdfscal. The output is a 2D count matrix over symmetric bin centers spanning[-max(abs(s)), +max(abs(s))]for each scalar.- Parameters:
s1 – Scalar fields as DataArrays. They must be broadcastable to the same shape; non-finite pairs are ignored.
s2 – Scalar fields as DataArrays. They must be broadcastable to the same shape; non-finite pairs are ignored.
nbin – Number of bin centers per axis (default: 101).
- Returns:
Dataset with coordinates
bin1andbin2and a 2D variablehicontaining counts.- Return type:
- pivpy.compute_funcs.meannz(x, dim=None, *, keep_attrs=True)[source]¶
Mean of nonzero elements (PIVMAT-compatible).
Matches the intent of PIVMAT’s
meannz.m: normalize by the number of nonzero samples instead of the total number of samples.Notes
For xarray inputs, zeros are excluded but NaNs are skipped.
Where a reduction slice has no nonzero samples, the result is 0.
- pivpy.compute_funcs.operf(op, f1, f2=None)[source]¶
Perform algebraic/elementwise operations on vector/scalar fields.
This is a pragmatic, PIVMAT-inspired helper similar to MATLAB’s
operf.- Parameters:
op – Operation string (e.g.
'+','-','.*','./', comparisons like'>=', or unary ops like'abs').f1 – A vector Dataset (contains
uandv) or scalar Dataset (containsw), or a list of such datasets.f2 – Optional second operand: a Dataset (or list), or a scalar/array.
- pivpy.compute_funcs.probeaverf(ds, rect, *, variables=None, skipna=True)[source]¶
Time series averaged over a rectangular area (PIVMAT-inspired).
- Parameters:
ds – Input dataset with spatial coordinates
xandy.rect – Rectangle as
[x1, y1, x2, y2]in physical units.variables – Variables to average. If None, defaults to
['u','v']when present, otherwise tries['w'].skipna – If True (default), NaNs are ignored in the mean.
- Returns:
Dataset containing the spatially averaged time series.
- Return type:
- pivpy.compute_funcs.probef(ds, x0, y0, *, variables=None, method='linear')[source]¶
Record the time evolution of probe point(s) in a dataset (PIVMAT-inspired).
This samples one or more variables at one or more probe points (x0, y0) using xarray’s interpolation along the spatial coordinates.
- Parameters:
ds – Input dataset with spatial coordinates
xandy.x0 – Probe coordinates in physical units. Scalars or 1D arrays of equal length.
y0 – Probe coordinates in physical units. Scalars or 1D arrays of equal length.
variables – Variables to sample. If None, defaults to
['u','v']when present, otherwise tries['w'].method – Interpolation method, passed to
DataArray.interp(e.g. ‘linear’, ‘nearest’).
- Returns:
Dataset of sampled time series. If multiple probe points are given, the result has a
probedimension.- Return type:
- pivpy.compute_funcs.setoriginf(f, P0)[source]¶
Set the origin (0,0) of a vector/scalar field (PIVMAT-compatible).
Port of PIVMAT’s
setoriginf.m.- Parameters:
f – Vector/scalar dataset (or list of datasets).
P0 – New origin as
[x0, y0]in the same units as the coords.
- pivpy.compute_funcs.shiftf(f, opt='bottomleft')[source]¶
Shift the axis of a vector/scalar field (PIVMAT-compatible).
Port of PIVMAT’s
shiftf.m.- Parameters:
opt – One of: ‘bottomleft’/’bl’ (default), ‘bottomright’/’br’, ‘topleft’/’tl’, ‘topright’/’tr’, ‘center’/’c’/’middle’.
- pivpy.compute_funcs.smoothf(f, n=3, opt='')[source]¶
Temporal running-average smoothing (PIVMAT-compatible).
Port of PIVMAT’s
smoothf.m.Notes
For a time series of length $L$ and window length $n$, the output length is $L-2lfloor n/2 rfloor$ (PIVMAT behavior).
- pivpy.compute_funcs.spatiotempcorrf(f, *opts)[source]¶
Spatio-temporal correlation function for a scalar time series (PIVMAT-compatible).
Port of PIVMAT’s
spatiotempcorrf.m.Input must be a scalar dataset with variable
wand dims(y,x,t).Options¶
‘full’: use all possible X and T (noisy for large lags)
‘verbose’: print progress
- pivpy.compute_funcs.spatiotempf(ds, X, Y, *, var='w', n=None, method='linear')[source]¶
Spatio-temporal diagram along one (or more) line segments (PIVMAT-inspired).
This samples a scalar field along line segment(s) defined by endpoints
(X[i,0], Y[i,0]) -> (X[i,1], Y[i,1])and returns the sampled values as a function of time and curvilinear coordinate.- Parameters:
ds – Input dataset with coordinates
xandy.X –
Endpoints in physical units.
Single line:
X=[x0,x1],Y=[y0,y1].Multiple lines:
X=[[x0,x1],[...]],Y=[[y0,y1],[...]].
Y –
Endpoints in physical units.
Single line:
X=[x0,x1],Y=[y0,y1].Multiple lines:
X=[[x0,x1],[...]],Y=[[y0,y1],[...]].
var – Scalar variable name to sample.
n – Number of sample points along each line. If None, a heuristic based on grid spacing is used.
method – Interpolation method for
DataArray.interp.
- Returns:
Dataset with variable
st.dims:
('t','s')for a single line, or('line','t','s')for multiple.coords:
sis the distance along the line (same units as x/y).x_lineandy_linegive the sampled coordinates along the line.
- Return type:
- pivpy.compute_funcs.specf(f, *opts)[source]¶
1D power spectrum of vector/scalar fields (PIVMAT-inspired).
This follows PIVMAT’s conventions: - Requires even x/y sizes (drops last row/col if odd) - Optional Hann apodization via the option
'hann'- Normalization such that$$int E(k),dk pprox langle s^2 rangle$$
Returns an
xarray.Datasetwith coordinateskxandky. For vector fields, returnsexvx, exvy, eyvx, eyvy. For scalar fields, returnsex, ey. If the field is square, also returns isotropic componentskande.
- pivpy.compute_funcs.ssf(s, dim=1, *opts)[source]¶
Structure functions of a scalar field (PIVMAT-inspired).
- pivpy.compute_funcs.statf(s, maxorder=6)[source]¶
Statistics of a vector/scalar field (PIVMAT-compatible).
Port of PIVMAT’s
statf.m.Zeros are treated as invalid and excluded.
For vector datasets, returns one dict per component (u, v).
- pivpy.compute_funcs.stresstensor(v)[source]¶
Reynolds stress tensor (PIVMAT-compatible).
Port of PIVMAT’s
stresstensor.mfor 2-component vector datasets.- Returns:
(t, b)wheretis the stress tensor andbthe deviatoric tensor.- Return type:
- pivpy.compute_funcs.subsbr(f, r0=None)[source]¶
Subtract the mean solid-body rotation (PIVMAT-compatible).
- pivpy.compute_funcs.subsbr2(f, dt=1.0, r0=None)[source]¶
Subtract mean rotation and compensate integrated camera rotation (PIVMAT-compatible).
- pivpy.compute_funcs.surfheight(dr, h0, H=inf, n=1.33, ctr=None, *opts)[source]¶
Surface height reconstruction for FS-SS (PIVMAT-compatible, simplified).
Port of PIVMAT’s
surfheight.m.This implementation reconstructs height from gradients using a Fourier Poisson solver (periodic boundary assumption). It supports the main options: - ‘submean’ - ‘nosetzero’ - ‘remap’ (requires SciPy)
- pivpy.compute_funcs.tempcorrf(ds, *, variables=None, opt='', normalize=False)[source]¶
Temporal correlation function of vector or scalar fields (PIVMAT-inspired).
For a scalar field
w(t), computes a time-lag correlationC(T) = < w(t) w(t+T) >where the average is taken over space and over time pairs.For a vector field, returns the sum of the correlations of each component.
- Parameters:
ds – Input dataset with time dimension
t.variables – Variables to include. If None, defaults to
['u','v']when both present, otherwise['w']if present.opt – If opt contains
'0', zeros are included as valid values. Otherwise (default), zeros are treated as missing and ignored.normalize – If True, normalizes by the zero-lag value so that
C(0)=1.
- Returns:
Dataset with coords
t(lag, integer) and variablef.- Return type:
- pivpy.compute_funcs.tempfilterf(v, indexpos, *opts)[source]¶
Fourier temporal filter of a vector/scalar time series (PIVMAT-compatible).
Port of PIVMAT’s
tempfilterf.m.- Parameters:
indexpos – Integer frequency index/indices (PIVMAT/Matlab 1-based indexing into FFT bins).
Options
-------
'remove' (-)
'complex' (-)
'phaseaverf' (-)
- pivpy.compute_funcs.tempspecf(v, freq=1.0, *opts)[source]¶
Temporal power spectrum averaged over space (PIVMAT-inspired).
- pivpy.compute_funcs.timederivativef(f, order=2)[source]¶
Time derivative by finite differences (PIVMAT-compatible).
Port of PIVMAT’s
timederivativef.m.The time unit is not applied here (matches PIVMAT). Divide by $Delta t$ externally if needed.
- pivpy.compute_funcs.truncf(f, cut=0.0, *opts)[source]¶
Truncate a field to the largest centered square (PIVMAT-compatible).
Supports: -
truncf(f): centered square -truncf(f, cut, 'phys'): cut specified in physical units -truncf(f, 'nonzero'): smallest rectangle excluding zeros
- pivpy.compute_funcs.zeropadf(f)[source]¶
Zero-pad a rectangular field to a square (PIVMAT-compatible).
- pivpy.compute_funcs.zerotonanfield(f)[source]¶
Convert 0 elements to NaNs in fields (PIVMAT-compatible).
- pivpy.compute_funcs.Γ1_moving_window_function(fWin, n)[source]¶
This is the implementation of Γ1 function given by equation 9 in L.Graftieaux, M. Michard, N. Grosjean, “Combining PIV, POD and vortex identification algorithms for the study of unsteady turbulent swirling flows”, Meas.Sci.Technol., 12(2001), p.1422-1429. Γ1 function is used to identify the locations of the centers of the vortices (which are given by the Γ1 peak values within the velocity field). IMPORTANT NOTICE: even though this function, theoretically, can be used on its own, it is not supposed to. It is designed to be used with Dask for big PIV datasets. The recomendation is not to use this function on its own, but rather use Γ1 attribute of piv class of PIVPY package (example of usage in this case would be: ds.piv.Γ1()) This function accepts a (2*n+1)x(2*n+1) neighborhood of one velocity vector from the entire velocity field in the form of Xarray dataset. And for this neighborhood only, it calculates the value of Γ1. Also, note this function is designed in a way that assumes point P (see the referenced article) to coincide with the center for fWin. This function works only for 2D velocity field.
- Parameters:
fWin (xarray.Dataset) – A moving-window view of the dataset.
n (int) – Rolling window radius. The window size is
(2*n+1) x (2*n+1).
- Returns:
Γ1 value for the given rolling window.
- Return type:
- pivpy.compute_funcs.Γ2_moving_window_function(fWin, n)[source]¶
This is the implementation of Γ2 function given by equation 11 in L.Graftieaux, M. Michard, N. Grosjean, “Combining PIV, POD and vortex identification algorithms for the study of unsteady turbulent swirling flows”, Meas.Sci.Technol., 12(2001), p.1422-1429. Γ2 function is used to identify the boundaries of the vortices in a velocity field. IMPORTANT NOTICE: even though this function, theoretically, can be used on its own, it is not supposed to. It is designed to be used with Dask for big PIV datasets. The recomendation is not to use this function on its own, but rather use Γ2 attribute of piv class of PIVPY package (example of usage in this case would be: ds.piv.Γ2()) This function accepts a (2*n+1)x(2*n+1) neighborhood of one velocity vector from the entire velocity field in the form of Xarray dataset. And for this neighborhood only, it calculates the value of Γ2. Also, note this function is designed in a way that assumes point P (see the referenced article) to coincide with the center for fWin. And finally, the choice of convective velocity (see the referenced article) is made in the article: it is the average velocity within fWin. This function works only for 2D velocity field.
- Parameters:
fWin (xarray.Dataset) – A moving-window view of the dataset.
n (int) – Rolling window radius. The window size is
(2*n+1) x (2*n+1).
- Returns:
Γ2 value for the given rolling window.
- Return type:
The pivpy.pivmat_compat module¶
- pivpy.pivmat_compat.expandstr(pattern)[source]¶
Expand indexed bracket strings (PIVMAT-compatible subset).
Port of PIVMAT’s
expandstr.mwith a safety constraint: only a restricted range grammar is supported (no arbitrary eval).Examples
expandstr('DSC[2:2:8,4].JPG')-> [‘DSC0002.JPG’, …]expandstr('dt=[1:0.5:2,2.3]s')-> [‘dt=1.000s’, …]Multiple brackets are expanded recursively.
The pivpy.update module¶
- class pivpy.update.UpdateCheckResult(status, installed, latest)[source]¶
Result of a package update check against PyPI.
- pivpy.update.check_update(package='pivpy', *, dist_name=None, timeout=3.0, verbose=False)[source]¶
Check whether a newer version of pivpy exists on PyPI.
- Status codes (mirrors the PIVMat convention):
0: server unavailable / request failed 1: no new version available (installed == latest) 2: a new version is available online (installed < latest) 3: the online version is older than installed (installed > latest)
- Parameters:
package – PyPI package name to query (defaults to “pivpy”).
dist_name – Installed distribution name (defaults to package).
timeout – Network timeout (seconds).
verbose – If True, prints a short human-readable message.
- Returns:
UpdateCheckResult with status + installed/latest strings.
The pivpy.graphics module¶
pivpy.graphics
Plotting helpers used by the test suite and the xarray accessor in
pivpy/pivpy.py.
Important behavioral expectations (tests rely on these):
quiver()andstreamplot()return(fig, ax)showf()existsshowscal()acceptsflow_property=as an alias and can compute a scalarvia the
.piv.vec2scal()accessor when needed
- pivpy.graphics.autocorrelation_plot(data, variable='u', spatial_average=True, ax=None, **kwargs)[source]¶
Plot a simple temporal autocorrelation for a variable.
If spatial_average=True and t exists, average over x/y before correlating. Otherwise, flatten all dimensions.
- pivpy.graphics.contour_plot(data, property='mag', ax=None, **kwargs)[source]¶
Contour/heatmap style plot for notebooks (compat shim).
Many legacy notebooks call
graphics.contour_plot(ds, colorbar=True). This helper defaults to plotting the vector magnitudemagcomputed fromuandv.- Parameters:
data – Dataset containing at least
uandv.property – Variable to plot. Special value
"mag"plotssqrt(u^2+v^2).ax – Optional matplotlib axis.
**kwargs – Passed through to matplotlib. Recognized compat kwargs:
colorbar(bool),colorbar_orient(“vertical”/”horizontal”),cmap,levels.
- pivpy.graphics.display_vector_field(data, arrowColor='k', arrowScale=1.0, arrowWidth=0.002)[source]¶
display_vector_field is a wrapper for quiver() for backwards compatibility
- Parameters:
data (xarray.Dataset) – dataset with u, v, x, y
arrowColor (str) – color of the arrows, by default “k”
arrowScale (float) – scaling factor for the arrows, by default 1.0
arrowWidth (float) – width factor for the arrows, by default 0.002
- Returns:
The figure and axes used for plotting.
- Return type:
Examples
>>> from pivpy import io, graphics >>> d = io.loadvec("test.vec") >>> graphics.display_vector_field(d)
- pivpy.graphics.histogram(data, bins=50, ax=None, **kwargs)[source]¶
Plot histograms of u and v for quick diagnostics.
- pivpy.graphics.histscal_disp(data, smooth=0, bin=None, opt='ngl', *, variable='w', ax=None)[source]¶
Display histogram(s) for a scalar field (PIVMAT-inspired).
- Parameters:
data – Dataset containing the scalar variable.
smooth – Number of consecutive frames to average. Use
0to average over all frames (default). Ifsmooth>1, returns a list of figures (one per chunk).bin – Optional bin centers.
opt – Option string. Supported letters:
n(normalize to PDF),g(Gaussian fit),l(log y-axis). To include zeros in the underlying histogram computation, include'0'inopt.variable – Scalar variable name (default:
'w'). If missing and'u'exists, falls back to'u'for convenience.ax – Optional axes to plot into (only used when producing a single plot).
- Returns:
(fig, ax)or a list of(fig, ax)when multiple chunks are plotted.- Return type:
- pivpy.graphics.histvec_disp(data, smooth=0, bin=None, opt='ngl', *, ax=None)[source]¶
Display histogram(s) for a 2D vector field (PIVMAT-inspired).
Vector components are taken from
('u','v')if present, otherwise('vx','vy').- Parameters:
data – Dataset containing vector components.
smooth – Same semantics as
histscal_disp().bin – Same semantics as
histscal_disp().opt – Same semantics as
histscal_disp().ax – Same semantics as
histscal_disp().
- Returns:
(fig, ax)or a list of(fig, ax)when multiple chunks are plotted.- Return type:
- pivpy.graphics.imvectomovie(filename, output, *, format=None, show='auto', background=None, scalar='w', fps=10, dpi=150, writer=None, codec=None, title=None, clim=None, cmap=None, verbose=False, return_frames=False, close=True, ax=None, **kwargs)[source]¶
Convert a series of vector/scalar files into a movie (PIVMAT-inspired).
This is the Python analogue of PIVMAT’s
imvectomovie: it loads files one-by-one from disk (no big in-memory list) and writes each frame directly to the movie writer.- Parameters:
filename – File pattern (glob) or list of patterns/paths.
output – Output movie file (e.g.
.mp4/.gif). IfNoneandreturn_frames=True, returns a list of RGBA frames.format – Optional explicit format for
pivpy.io.read_piv.verbose – If True, prints each file loaded.
Notes
Other parameters match
to_movie().
- pivpy.graphics.jpdfscal_disp(jpdf, *, ax=None)[source]¶
Display a joint PDF computed by
pivpy.compute_funcs.jpdfscal().This mimics PIVMAT’s
jpdfscal_disp: it plotslog10(hi)as filled contours and draws dashed zero lines.- Parameters:
jpdf – Dataset produced by
jpdfscalwith coordsbin1/bin2and data variablehi.ax – Optional axes.
- Returns:
The figure and axes.
- Return type:
- pivpy.graphics.quiver(data, quiverKey='Q', scalingFactor=1.0, widthFactor=0.002, ax=None, arrowColor='k', **kwargs)[source]¶
Creates a quiver plot from the dataset
- Parameters:
data (xarray.Dataset) – dataset with u, v, x, y
quiverKey (str) – key for the quiver plot, by default “Q”
scalingFactor (float) – scaling factor for the arrows, by default 1.0
widthFactor (float) – width factor for the arrows, by default 0.002
ax (matplotlib.axes.Axes | None) – matplotlib axes, by default None
arrowColor (str) – color of the arrows, by default “k”
- Returns:
The figure and axes used for plotting.
- Return type:
Examples
>>> from pivpy import io, graphics >>> d = io.loadvec("test.vec") >>> graphics.quiver(d)
- pivpy.graphics.showf(data, **kwargs)[source]¶
Display a vector or scalar field (PIVMAT-inspired dispatcher).
This is a lightweight Python analogue of PIVMAT’s
showf:If the dataset contains
uandv, it displays a vector field.Otherwise, it displays a scalar field (default variable
w).
- Parameters:
data – Dataset to display.
background –
Optional scalar background shown behind vectors.
Use
None/''/'off'for no background. Ifbackgroundmatches an existing variable name, that variable is displayed. Otherwise, it is interpreted as a vector-derived flow property and computed usingdata.piv.vec2scal(background, name='w').scalar – Scalar variable to display if the dataset is scalar-only.
ax – Optional axes.
**kwargs – Forwarded to
quiver()(vector mode) or matplotlib pcolormesh (scalar mode). Recognized scalar kwargs:cmap,clim.
- Returns:
Figure and axes used for plotting.
- Return type:
- pivpy.graphics.showscal(data, property='w', **kwargs)[source]¶
showscal plots the scalar field
- Parameters:
data (xarray.Dataset) – dataset with u, v, x, y
property (str) – property to plot, by default “w”
**kwargs – additional keyword arguments for pcolormesh
Examples
>>> from pivpy import io, graphics >>> d = io.loadvec("test.vec") >>> graphics.showscal(d, "chc")
- pivpy.graphics.statvec_disp(stat_u, stat_v, ax=None, title=None)[source]¶
Display vector statistics returned by
statf(PIVMAT-style helper).
- pivpy.graphics.streamplot(data, density=1.0, linewidth=1.0, arrowsize=1.0, ax=None, **kwargs)[source]¶
streamplot plots the streamlines of the vector field
- Parameters:
data (xarray.Dataset) – dataset with u, v, x, y
density (float) – density of the streamlines, by default 1.0
linewidth (float) – linewidth of the streamlines, by default 1.0
arrowsize (float) – size of the arrows, by default 1.0
ax (matplotlib.axes.Axes) – Matplotlib axes (or None), by default None
**kwargs – additional keyword arguments for streamplot
Examples
>>> from pivpy import io, graphics >>> d = io.loadvec("test.vec") >>> graphics.streamplot(d)
- pivpy.graphics.to_movie(data, output, *, show='auto', background=None, scalar='w', fps=10, dpi=150, writer=None, codec=None, title=None, clim=None, cmap=None, return_frames=False, close=True, ax=None, **kwargs)[source]¶
Save an in-memory Dataset as a movie (fast artist-updating renderer).
- Parameters:
data – Dataset to render. If it contains a
tdimension, eachtstep is rendered as one frame.output – Output path (e.g.
'movie.mp4','movie.gif'). IfNoneandreturn_frames=True, returns a list of RGBA frames.show –
'auto'(default),'vector', or'scalar'.background – In vector mode, optionally draw a scalar background behind vectors. See
showf().scalar – Variable name to render in scalar mode.
writer –
None(infer from extension),'ffmpeg', or'pillow'.clim – Either a fixed
(vmin, vmax)tuple, or'each'to auto-scale per frame.return_frames – If True, returns a list of RGBA arrays (uint8) for each frame.
Notes
MP4/AVI writing requires FFmpeg. GIF writing requires Pillow.
- pivpy.graphics.vectorplot(data, arrowColor='k', arrowScale=1.0, arrowWidth=0.002)[source]¶
vectorplot plots the vector field
- Parameters:
data (xarray.Dataset) – dataset with u, v, x, y
arrowColor (str) – color of the arrows, by default “k”
arrowScale (float) – scaling factor for the arrows, by default 1.0
arrowWidth (float) – width factor for the arrows, by default 0.002
- Returns:
The figure and axes used for plotting.
- Return type:
Examples
>>> from pivpy import io, graphics >>> d = io.loadvec("test.vec") >>> graphics.vectorplot(d)
The pivpy.pivpy module¶
This script extends the functionality of xarray.Dataset by adding a new accessor called piv. The accessor adds several properties and methods that are useful for working with particle image velocimetry (PIV) data. The properties include average, which returns the mean flow field, and delta_t, which returns the time step used in the PIV measurement. The methods include crop, which allows the user to crop the data by a given number of rows and columns from the boundaries, vec2scal, which converts vector data to scalar data, pan, which pans the data by a given number of pixels, and rotate, which rotates the data by a given angle.
@author: Ron, Alex
- class pivpy.pivpy.PIVAccessor(xarray_obj)[source]¶
extends xarray Dataset with PIVPy properties
- acceleration(name='w')[source]¶
Calculates material derivative or acceleration of the data array (single frame)
- Parameters:
name (str) – Name for the output scalar field. Defaults to “w”. Use different names to store multiple scalar fields in one dataset.
- Input:
xarray with the variables u,v and dimensions x,y
- Output:
xarray with the estimated acceleration as a scalar field data[name]
Example
>>> data.piv.acceleration() # Creates data["w"] with acceleration >>> data.piv.acceleration(name="accel") # Creates data["accel"]
- addnoisef(eps=0.1, opt='add', nc=0.0, seed=None)[source]¶
Adds normally-distributed white noise to velocity fields.
This method is inspired by PIVMat’s addnoisef.
- Parameters:
eps – Noise level. For additive mode, noise std is eps * std(u,v). For multiplicative mode, velocity is multiplied by (1 + eps * noise).
opt – ‘add’ for additive noise or ‘mul’ for multiplicative noise.
nc – Optional Gaussian smoothing length scale for the noise, in the same units as the dataset coordinates (“mesh units”). If 0, no smoothing.
seed – Optional RNG seed for reproducibility.
- Returns:
Dataset with noisy u/v.
- Return type:
- autocorrelation_plot(variable='u', spatial_average=True, **kwargs)[source]¶
Creates autocorrelation plot of a specified variable
- Parameters:
variable (str) – Variable name to plot autocorrelation for (e.g., ‘u’, ‘v’, ‘w’, ‘c’, or any other data variable). Defaults to “u”.
spatial_average (bool) – If True and time dimension exists, compute spatial average before temporal autocorrelation. If False, flatten all dimensions. Defaults to True for proper temporal analysis.
**kwargs – Additional keyword arguments passed to graphics.autocorrelation_plot
- Returns:
The axes object containing the autocorrelation plot
- Return type:
Example
>>> data.piv.autocorrelation_plot(variable='u') >>> data.piv.autocorrelation_plot(variable='v', spatial_average=False)
- property average¶
Return the mean flow field .
- averf(opt='', *, return_std_rms=False)[source]¶
Average (and optionally std/rms) of vector/scalar fields over time.
This method is inspired by PIVMat’s averf.
By default, zero elements are treated as invalid and are excluded from the computations. To include zeros, pass opt containing ‘0’.
- Parameters:
opt – Option string. If it contains ‘0’, zeros are included.
return_std_rms – If True, also returns (std, rms) as scalar fields.
- Returns:
Averaged dataset (single-frame, t=0) if
return_std_rms=False. tuple:(avg, std, rms)ifreturn_std_rms=True.- Return type:
- azaverf(x0=0.0, y0=0.0, *, center_units='phys', rmax=None, keepzero=False, return_profiles=False, var=None, frame=None)[source]¶
Azimuthal average of a vector/scalar field.
Inspired by PIVMAT’s
azaverf.- Parameters:
x0 – Center location.
y0 – Center location.
center_units – ‘phys’ (default) for coordinate units or ‘mesh’ for index units (0-based indices in x/y arrays).
rmax – Optional maximum radius.
keepzero – If False (default), zero elements are treated as invalid and excluded.
return_profiles – If True, return radial profiles instead of an averaged field.
var – Scalar variable name to average. If None, uses vector mode (u, v).
frame – Optional integer time index to process a single frame.
- Returns:
xarray.Dataset – If
return_profilesis False, returns an averaged dataset.tuple – If
return_profilesis True: - Vector mode:(r, ur, ut)- Scalar mode:(r, p)
- azprofile(x0=0.0, y0=0.0, r=1.0, na=None, *, var=None, frame=None, angle_dim='angle')[source]¶
Azimuthal profile sampled along a circle (PIVMAT-style).
This is a port of PIVMAT’s
azprofile: samples a scalar or vector field along the circle(x, y) = (x0 + r*cos(a), y0 + r*sin(a)).- Parameters:
x0 – Circle center in the same units as coordinates
xandy.y0 – Circle center in the same units as coordinates
xandy.r – Circle radius.
na – Number of angular samples. If None, uses PIVMAT’s default heuristic
round(4*r/abs(dx))wheredxis the x-grid spacing.var – Scalar variable to sample. If None, samples vector components
uandvand returns (angle, ur, ut).frame – Optional time index. If provided, samples only that frame.
angle_dim – Name of the angular dimension.
- Returns:
tuple – Scalar mode:
(angle, p).tuple – Vector mode:
(angle, ur, ut).
Notes
Returned arrays are NumPy arrays. If the dataset has a time dimension and
frameis None, the profiles have shape(na, nt).
- bwfilterf(filtsize=3.0, order=8.0, *, mode='low', trunc=False, var=None, variables=None)[source]¶
Butterworth spatial filter for vector/scalar fields (PIVMAT-inspired).
Applies a low-pass (default) or high-pass Butterworth filter in Fourier space along the spatial dimensions (y, x). Implemented via fast NumPy FFT inside xarray.apply_ufunc, vectorized over any remaining dimensions (e.g. t).
- Parameters:
filtsize – Cutoff size in grid units. If 0, returns the dataset unchanged.
order – Filter order (typical range 2..10). Larger means sharper cutoff.
mode – ‘low’ or ‘high’. High-pass is implemented by flipping the sign of order.
trunc – If True, truncates borders of width floor(filtsize) after filtering.
var – Scalar variable name to filter. If None, defaults to vector mode (u, v) unless variables is provided.
variables – Explicit list of variables to filter.
- bwfilterf_pm(filtsize, order, *opts, var=None, variables=None)[source]¶
PIVMAT-compatible wrapper for
bwfilterf().Accepts option strings like PIVMAT: - ‘low’ (default) - ‘high’ - ‘trunc’
Examples
ds.piv.bwfilterf_pm(3, 8)ds.piv.bwfilterf_pm(3, 8, 'high')ds.piv.bwfilterf_pm(3, 8, 'high', 'trunc')
- clip(min=None, max=None, *, by=None, keep_attrs=True)[source]¶
Clips values in the dataset based on specified thresholds
This method limits values in the dataset to fall within [min, max] range. It can clip the entire dataset or filter based on specific variables (U, V, or scalar properties like magnitude).
- Parameters:
min (float or None) – Minimum value threshold. Values below this will be masked/removed. If None, no lower clipping is performed. Defaults to None.
max (float or None) – Maximum value threshold. Values above this will be masked/removed. If None, no upper clipping is performed. Defaults to None.
by (str or None) – Variable name to use for clipping criterion. Common values include ‘u’, ‘v’, or ‘magnitude’, but any scalar property name in the dataset is valid (e.g., ‘w’ for vorticity, ‘tke’, etc.). If None, clips all variables independently. If ‘magnitude’, computes velocity magnitude and uses it for filtering. Defaults to None.
keep_attrs (bool) – If True, attributes will be preserved. Defaults to True.
- Returns:
- Dataset with clipped values. If ‘by’ is specified, returns
dataset with locations that don’t meet the criteria set to NaN.
- Return type:
- Raises:
ValueError – If neither min nor max is provided
ValueError – If ‘by’ variable doesn’t exist in the dataset and isn’t ‘magnitude’
Examples
>>> # Clip all variables to [-10, 10] range >>> data = data.piv.clip(min=-10, max=10)
>>> # Filter based on U velocity component >>> data = data.piv.clip(min=-5, max=5, by='u')
>>> # Filter based on velocity magnitude >>> data = data.piv.clip(max=10, by='magnitude')
>>> # Filter based on vorticity (after computing it) >>> data = data.piv.vorticity(name='w') >>> data = data.piv.clip(min=-100, max=100, by='w')
See also
xarray.Dataset.clip : Similar method in xarray numpy.clip : Equivalent function in NumPy
- corrf(variable='u', dim='x', *, normalize=False, nan_as_zero=True, nowarning=False)[source]¶
PIVMAT-style spatial correlation and integral scales for a scalar variable.
This wraps
pivpy.compute_funcs.corrf()and returns a Dataset with coordinaterand variablefplus scalar outputs (isinf,r5, …).
- corrm(variable='u', dim='x', *, half=False, nan_as_zero=True, lag_dim='lag')[source]¶
PIVMAT-style matrix correlation for a variable.
- Parameters:
variable – Name of the DataArray variable in the Dataset.
dim – Dimension name (recommended) or 1/2 like MATLAB for 2D arrays.
half – If True, return only non-negative lags (including zero-lag).
nan_as_zero – If True, treat NaNs as missing data and replace by 0 before correlating.
lag_dim – Name of the lag dimension in the returned DataArray.
- crop(crop_vector=None)[source]¶
Crops xarray Dataset to specified spatial boundaries
- Parameters:
crop_vector (list) – List of [xmin, xmax, ymin, ymax] values to define cropping boundaries. Use None for any value to keep the original boundary. Defaults to None (no cropping).
- Returns:
Cropped dataset
- Return type:
- Raises:
ValueError – If crop_vector has wrong length or invalid bounds
Example
>>> data = data.piv.crop([5, 15, -5, -15]) # Crop to x:[5,15], y:[-5,-15] >>> data = data.piv.crop([None, 20, None, None]) # Crop only xmax to 20
- property delta_t¶
receives the delta_t from the set
- divergence(name='w')[source]¶
Calculates divergence field
- Parameters:
name (str) – Name for the output scalar field. Defaults to “w”. Use different names to store multiple scalar fields in one dataset.
- Returns:
Dataset with the new property [name] = divergence
- Return type:
Example
>>> data.piv.divergence() # Creates data["w"] with divergence >>> data.piv.divergence(name="div") # Creates data["div"] with divergence
- extractf(rect, opt='phys', *, return_rect=False)[source]¶
Extract a rectangular area from the dataset (PIVMAT-inspired).
- Parameters:
rect –
Rectangle as
[x1, y1, x2, y2].If
opt='phys'(default), coordinates are in physical units and the selection is expanded to the nearest grid points (start behaves like a floor, end behaves like a ceil) before clamping.If
opt='mesh', coordinates are mesh indices (1-based, inclusive, MATLAB-like) before clamping.opt – ‘phys’ (default) or ‘mesh’.
return_rect – If True, also returns the effective rectangle in mesh indices
[ix1, iy1, ix2, iy2](1-based, inclusive) after clamping.
- Returns:
xarray.Dataset – Extracted dataset.
tuple – If
return_rect=True, returns(dataset, rect_mesh)whererect_meshis[ix1, iy1, ix2, iy2](1-based, inclusive).
Notes
Interactive rectangle selection (PIVMAT’s ‘draw’) is not supported.
- fill_nans(method='nearest')[source]¶
This method uses scipy.interpolate.griddata to interpolate missing data. :param src_data: Input data array. :type src_data: Any :param method: The method to use for interpolation in scipy.interpolate.griddata. :type method: {‘linear’, ‘nearest’, ‘cubic’}
- Returns:
An interpolated
numpy.ndarray.- Return type:
- fill_zeros(*, fill=False, max_iter=None, variables=None)[source]¶
Fill zero-valued holes using 4-neighbor interpolation.
This is a PIVMAT
interpolat-style helper, useful when invalid vectors are encoded as zeros.- Parameters:
fill – If True, iterate until no zeros remain (or until max_iter).
max_iter – Optional iteration cap.
variables – Variables to process. Default: [‘u’, ‘v’] if present; otherwise all data_vars.
- filterf(sigma=[1.0, 1.0, 0.0], method='gauss', *opts, **kwargs)[source]¶
Apply a spatial filter to a vector/scalar field (PIVMAT-inspired).
This method supports two calling conventions:
Legacy PIVPy Gaussian smoothing (kept for backward compatibility):
ds = ds.piv.filterf([sigma_y, sigma_x, sigma_t], **gaussian_kwargs) This uses SciPy's ``gaussian_filter`` on ``u`` and ``v``.
PIVMAT-style normalized 2D convolution (NaN-aware):
ds = ds.piv.filterf(filtsize, method, 'same') ds = ds.piv.filterf(filtsize, method) # default is 'valid'
where
methodis one of:'gauss'(default),'flat','igauss'. The option'same'keeps the original shape; otherwise the result is smaller (Matlabconv2(...,'valid')behavior) and the x/y coordinates are truncated accordingly.
- flipf(dir='x')[source]¶
Flip vector/scalar fields about vertical or horizontal axis (PIVMAT-inspired).
- Parameters:
dir –
Direction to flip:
’x’: left-right mirror (flip along x; negate
u)’y’: top-bottom mirror (flip along y; negate
v)’xy’ or ‘yx’: both flips
’’: do nothing
Notes
The x/y coordinate values are left unchanged (only the data are mirrored), matching PIVMAT behavior.
- gradientf(variable='w')[source]¶
PIVMAT-style gradient of a scalar variable.
This wraps
pivpy.compute_funcs.gradientf()and returns a new Dataset containing gradient components as variablesuandv.- Parameters:
variable – Name of the scalar variable in the Dataset (default:
'w').- Returns:
Dataset with variables
uandv.- Return type:
- histf(variable=None, bin=None, opt='')[source]¶
PIVMAT-style histogram of a vector/scalar field.
Scalar mode: pass
variable='w'(or any scalar var name) to get a Dataset with coordinatebinand variableh.Vector mode: pass
variable=None(default) to compute histograms for both components (u/vorvx/vy), returning variableshxandhy.
By default, zero values are treated as invalid and excluded. Pass
optcontaining'0'to include zeros.
- interpf(method=0, *, variables=None, missing='0nan')[source]¶
Interpolate missing data (PIVMAT-style
interpf).Missing values are defined as 0 and/or NaN (see
missing). The interpolation is applied frame-by-frame alongtif present.- Parameters:
method – Interpolation method selector:
0Laplacian inpainting (sparse solve),1nearest-neighbor fill,2linear interpolation with nearest fallback.variables – Variables to process. Default: [‘u’,’v’] if present; otherwise [‘w’] if present; otherwise all data variables.
missing – Missing-value definition:
'0nan'(default),'nan', or'0'.
- Returns:
Filled dataset.
- Return type:
- jpdfscal(var1, var2, nbin=101)[source]¶
Joint PDF (2D histogram) of two scalar variables (PIVMAT-style).
- Parameters:
var1 – Names of scalar variables in the Dataset.
var2 – Names of scalar variables in the Dataset.
nbin – Number of bins per axis (odd integer, default 101).
- jpdfscal_disp(var1, var2, nbin=101, **kwargs)[source]¶
Compute and display the joint PDF of two scalar variables.
- kinetic_energy(name='w')[source]¶
Estimates kinetic energy
- Parameters:
name (str) – Name for the output scalar field. Defaults to “w”. Use different names to store multiple scalar fields in one dataset.
- Returns:
Dataset with kinetic energy field
- Return type:
Example
>>> data.piv.kinetic_energy() # Creates data["w"] with KE >>> data.piv.kinetic_energy(name="ke") # Creates data["ke"]
- pan(shift_x=0.0, shift_y=0.0)[source]¶
Shifts the coordinate system by specified amounts
- Parameters:
- Returns:
Dataset with shifted coordinates
- Return type:
Example
>>> data = data.piv.pan(10.0, -5.0) # Shift x by +10, y by -5
- phaseaverf(period, *, opt='', method='linear')[source]¶
Phase-average a vector/scalar dataset over a period.
Inspired by PIVMAT’s
phaseaverf.- Parameters:
period – If integer P: returns P phase-averaged fields, where phase i is the average of frames i, i+P, i+2P, … If non-integer float: resamples linearly in time and averages. The result has length floor(period). If sequence: performs loop averaging with step=period[-1].
opt – Passed to
averf. By default, zeros are excluded; pass ‘0’ to include.method – Interpolation method used for non-integer periods.
- Returns:
Phase-averaged dataset with dim ‘t’ == n_phases.
- Return type:
- probeaverf(rect, *, variables=None, skipna=True)[source]¶
Time series averaged over a rectangular area (PIVMAT-inspired).
- Parameters:
rect – Rectangle
[x1, y1, x2, y2]in physical units.variables – Variables to average. If None, defaults to
['u','v']when present, otherwise['w'].skipna – If True (default), NaNs are ignored.
- Returns:
Spatially averaged time series.
- Return type:
- probef(x0, y0, *, variables=None, method='linear')[source]¶
Record the time evolution of probe point(s) (PIVMAT-inspired).
This samples variable(s) at point(s)
(x0, y0)using spatial interpolation.- Parameters:
x0 – Probe location(s) in physical units. Scalars or 1D arrays.
y0 – Probe location(s) in physical units. Scalars or 1D arrays.
variables – Variables to sample. If None, defaults to
['u','v']when present, otherwise['w'].method – Interpolation method (‘linear’ or ‘nearest’ are typical).
- Returns:
Sampled time series. For multiple probe points, includes a
probedim and coordinatesx_probe/y_probe.- Return type:
- resamplef(tini, tfin, *, method='linear')[source]¶
(Temporal) re-sampling of vector/scalar fields.
This method is inspired by PIVMat’s resamplef.
The dataset is re-sampled from initial times tini to new times tfin using interpolation along the time dimension.
Requirements (as in PIVMat): - len(tini) == len(ds.t) - tini is strictly increasing - all tfin values are within [tini[0], tini[-1]]
- Parameters:
tini – 1D sequence of initial times (length == number of frames).
tfin – 1D sequence of target times.
method – Interpolation method.
- Returns:
resampled dataset with dim ‘t’ == len(tfin) and coords ‘t’ == tfin.
- Return type:
- reynolds_stress(name='w')[source]¶
Calculates Reynolds stress from velocity fluctuations
- Parameters:
name (str) – Name for the output scalar field. Defaults to “w”. Use different names to store multiple scalar fields in one dataset.
- Returns:
Dataset with Reynolds stress field (-<u’v’>)
- Return type:
- Raises:
ValueError – If dataset has less than 2 time frames
Example
>>> data.piv.reynolds_stress() # Creates data["w"] with Reynolds stress >>> data.piv.reynolds_stress(name="rey_stress") # Creates data["rey_stress"]
- rms(name='w')[source]¶
Root mean square of velocity fluctuations
- Parameters:
name (str) – Name for the output scalar field. Defaults to “w”. Use different names to store multiple scalar fields in one dataset.
- Returns:
Dataset with RMS field (sqrt of TKE)
- Return type:
Example
>>> data.piv.rms() # Creates data["w"] with RMS >>> data.piv.rms(name="rms") # Creates data["rms"]
- rotate(theta=0.0)[source]¶
Rotates the coordinate system and velocity field
- Parameters:
theta (float) – Rotation angle in degrees (clockwise). Defaults to 0.0.
- Returns:
Rotated dataset
- Return type:
Note
This method works best for cases with equal grid spacing in x and y directions. The rotation is performed in-place on coordinates and velocity components.
Example
>>> data = data.piv.rotate(45.0) # Rotate by 45 degrees clockwise
- set_delta_t(delta_t=0.0)[source]¶
Sets the time interval attribute for PIV measurements
- Parameters:
delta_t (float) – Time interval between frame A and B. Defaults to 0.0.
- Returns:
Dataset with updated delta_t attribute
- Return type:
- Raises:
ValueError – If delta_t is negative
Example
>>> data = data.piv.set_delta_t(0.001) # Set dt to 1 millisecond
- set_scale(scale=1.0)[source]¶
Scales all spatial coordinates and velocities by a factor
- Parameters:
scale (float) – Scaling factor. Defaults to 1.0.
- Returns:
Dataset with scaled coordinates and velocities
- Return type:
- Raises:
ValueError – If scale is zero or negative
Example
>>> data = data.piv.set_scale(0.001) # Convert from pixels to mm if 1 pix = 0.001 mm
- spatiotempf(X, Y, *, var='w', n=None, method='linear')[source]¶
Spatio-temporal diagram along line segment(s) (PIVMAT-inspired).
- Parameters:
X – Endpoints in physical units. Single line:
X=[x0,x1],Y=[y0,y1]. Multiple lines:X=[[x0,x1],[...]], same forY.Y – Endpoints in physical units. Single line:
X=[x0,x1],Y=[y0,y1]. Multiple lines:X=[[x0,x1],[...]], same forY.var – Scalar variable name to sample.
n – Number of sample points along each line (None -> heuristic).
method – Interpolation method (‘linear’ or ‘nearest’ are typical).
- Returns:
Dataset containing variable
st.- Return type:
- spaverf(opt='xy', *, var=None)[source]¶
Spatial average over X and/or Y of a vector/scalar field.
This method is inspired by PIVMat’s spaverf.
- Parameters:
opt – ‘x’, ‘y’, or ‘xy’ (default). If opt contains ‘0’, zeros are included in the mean; otherwise zeros are excluded (treated as invalid). Examples: ‘xy’, ‘x0’, ‘y0’, ‘xy0’.
var – Scalar variable name to average (e.g. ‘w’). If None, averages vector components ‘u’ and ‘v’.
- Returns:
Dataset with spatially-averaged variable(s), broadcast back to the original shape.
- Return type:
- strain(name='w')[source]¶
Calculates rate of strain of a two component field
- Parameters:
name (str) – Name for the output scalar field. Defaults to “w”. Use different names to store multiple scalar fields in one dataset.
- Returns:
Dataset with added scalar field = du_dx^2 + dv_dy^2 + 0.5*(du_dy+dv_dx)^2
- Return type:
Example
>>> data.piv.strain() # Creates data["w"] with strain >>> data.piv.strain(name="strain_rate") # Creates data["strain_rate"]
- subaverf(opt='e', *, var=None)[source]¶
Subtract an ensemble (temporal) or spatial average from a field.
This method is inspired by PIVMat’s subaverf.
If opt contains ‘e’ (default): subtract the ensemble/temporal mean computed by averf.
Otherwise: subtract a spatial mean computed by spaverf using opt as the axis selector (‘x’, ‘y’, ‘xy’, optionally with ‘0’).
By default, the subtraction preserves invalid zeros: locations that are exactly zero in the original data remain zero after subtraction.
- Parameters:
opt – Option string. Default ‘e’.
var – Scalar variable name (e.g. ‘w’). If None, operates on ‘u’ and ‘v’.
- Returns:
Dataset with mean-subtracted variable(s).
- Return type:
- tempcorrf(*, variables=None, opt='', normalize=False)[source]¶
Temporal correlation function (PIVMAT-inspired).
- Parameters:
variables – Variables to include. Default is
['u','v']if present, otherwise['w'].opt – Include zeros if opt contains
'0'(default excludes zeros).normalize – If True, normalizes so that
f(t=0)=1.
- tke(name='w')[source]¶
Estimates turbulent kinetic energy
- Parameters:
name (str) – Name for the output scalar field. Defaults to “w”. Use different names to store multiple scalar fields in one dataset.
- Returns:
New dataset with TKE field (based on fluctuations from mean)
- Return type:
- Raises:
ValueError – If dataset has less than 2 time frames
Example
>>> data.piv.tke() # Creates data["w"] with TKE >>> data.piv.tke(name="tke") # Creates data["tke"]
- to_movie(output, **kwargs)[source]¶
Save the Dataset as a movie (fast artist-updating renderer).
This is a convenience wrapper around
pivpy.graphics.to_movie().- Parameters:
output – Output path (e.g.
'movie.mp4'/'movie.gif'). IfNoneandreturn_frames=Trueis passed, returns a list of RGBA frames.**kwargs – Passed through to
pivpy.graphics.to_movie().
- vec2scal(flow_property='curl', name='w')[source]¶
Creates a scalar flow property field from velocity data
- Parameters:
flow_property (str) – Name of the flow property to compute. Valid options: ‘curl’/’vorticity’/’vort’, ‘ke’/’ken’/’kinetic_energy’, ‘strain’, ‘divergence’, ‘acceleration’, ‘tke’, ‘reynolds_stress’, ‘rms’. Defaults to “curl”.
name (str) – Name for the output scalar field. Defaults to “w”. Use different names to store multiple scalar fields in one dataset.
- Returns:
Dataset with computed scalar field
- Return type:
- Raises:
AttributeError – If the specified flow property method doesn’t exist
Example
>>> data = data.piv.vec2scal('vorticity') # Compute vorticity in data["w"] >>> data = data.piv.vec2scal('ke', name='ke') # Compute KE in data["ke"] >>> # Store multiple scalars in one dataset: >>> data = data.piv.vec2scal('vorticity', name='vort') >>> data = data.piv.vec2scal('tke', name='tke') >>> data = data.piv.vec2scal('reynolds_stress', name='rey_stress')
- vorticity(name='w')[source]¶
Calculates vorticity of the data array (at one time instance) and adds it to the dataset
- Parameters:
name (str) – Name for the output scalar field. Defaults to “w”. Use different names to store multiple scalar fields in one dataset.
- Input:
xarray with the variables u,v and dimensions x,y
- Output:
xarray with the estimated vorticity as a scalar field with same dimensions
Example
>>> data.piv.vorticity() # Creates data["w"] with vorticity >>> data.piv.vorticity(name="vort") # Creates data["vort"] with vorticity
- Γ1(n, convCoords=True)[source]¶
- Makes use of Dask (kind of) to run Γ1_moving_window_function via Γ1_pad.
It takes an Xarray dataset, applies rolling window to it, groups rolling windows and applyies custom Γ1-calculating function to it in a parallel manner.
- Parameters:
self._obj (xarray.Dataset) – Must contain at least
u,v,x,yandt.n (int) – Rolling window radius. Window size is
(2*n+1) x (2*n+1).convCoords (bool) – Convert coordinates. if True - create two new data arrays within self._obj with the names “xCoordiantes” and “yCoordiantes” that store x and y coordinates as data arrays; always keep it “True” unless you have already created “xCoordiantes” and “yCoordiantes” somehow (say, by running Γ1 or Γ2 functions before)
- Returns:
self._obj (xarray.Dataset) - the argument with the Γ1 data array
- Γ2(n, convCoords=True)[source]¶
- Makes use of Dask (kind of) to run Γ2_moving_window_function via Γ2_pad.
It takes an Xarray dataset, applies rolling window to it, groups rolling windows and applyies custom Γ2-calculating function to it in a parallel manner.
- Parameters:
self._obj (xarray.Dataset) – Must contain at least
u,v,x,yandt.n (int) – Rolling window radius. Window size is
(2*n+1) x (2*n+1).convCoords (bool) – Convert coordinates. if True - create two new data arrays within self._obj with the names “xCoordiantes” and “yCoordiantes” that store x and y coordinates as data arrays; always keep it “True” unless you have already created “xCoordiantes” and “yCoordiantes” somehow (say, by running Γ1 or Γ2 functions before)
- Returns:
self._obj (xarray.Dataset) - the argument with the Γ2 data array
The pivpy.interfacing module¶
“inter” stands for “intefacing”. This module provides a function that allows to go convert PIVPY datasets to the VortexFitting datasets. Here is the link to the VortexFitting article: https://www.sciencedirect.com/science/article/pii/S2352711020303174?via%3Dihub .
- pivpy.interfacing.pivpyTOvf(field, ncFilePath)[source]¶
Convert a PIVPy xarray Dataset into a VortexFitting
VelocityField.Notes
VortexFitting’s
VelocityFieldexpects to read from a NetCDF file, so this function writes a temporary NetCDF file atncFilePathand then loads it.- Parameters:
field – PIVPy xarray Dataset containing at least
uandvvariables and a single time frame.ncFilePath – Path to the NetCDF file to write (it does not need to exist yet).
- Returns:
The VortexFitting velocity field loaded from the written NetCDF file.
- Return type:
vortexfitting.VelocityField
The pivpy.inter module (deprecated)¶
Backward-compatible alias for the pivpy.interfacing module.
The original interop helpers lived in pivpy.inter. The canonical location is now pivpy.interfacing.