Skip to content

API reference

This is a complete API reference to the PIVPy package.

pivpy.synthetic

pivpy.synthetic

Analytical and stochastic velocity vector field generators for PIVPy.

This module provides exact analytical and synthetic flow fields formatted as canonical PIVPy xarray.Datasets (with dims ('y', 'x', 't'), coords x, y, t, and variables u, v, chc, optional w).

Supported flow models: - vortex: Lamb-Oseen, Burgers, Rankine, and Vatistas vortices - multivortex: 2D synthetic turbulence from multiple random Burgers/Lamb vortices - randvec: Divergence-free random velocity fields with prescribed power spectrum - channel: Analytical laminar Poiseuille channel flow - shear_layer: Analytical hyperbolic tangent shear/mixing layer

channel(rows=64, cols=64, u_max=1.0, dx=1.0, dy=1.0, frame=0)

Generate an analytical laminar Poiseuille channel flow velocity field.

Profile: $u(y) = U_{\max} \left[1 - \left(\frac{y - y_c}{H}\right)^2\right]$, $v(y) = 0$.

Parameters:

Name Type Description Default
rows int

Grid dimensions (default 64x64).

64
cols int

Grid dimensions (default 64x64).

64
u_max float

Centerline maximum velocity (default 1.0).

1.0
dx float

Grid spacing (default 1.0).

1.0
dy float

Grid spacing (default 1.0).

1.0
frame int

Time frame index (default 0).

0

Returns:

Type Description
Dataset

Canonical PIVPy dataset with analytical Poiseuille flow.

Source code in pivpy/synthetic.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
def channel(
    rows: int = 64,
    cols: int = 64,
    u_max: float = 1.0,
    dx: float = 1.0,
    dy: float = 1.0,
    frame: int = 0,
) -> xr.Dataset:
    """Generate an analytical laminar Poiseuille channel flow velocity field.

    Profile: $u(y) = U_{\\max} \\left[1 - \\left(\\frac{y - y_c}{H}\\right)^2\\right]$, $v(y) = 0$.

    Parameters
    ----------
    rows, cols : int
        Grid dimensions (default 64x64).
    u_max : float
        Centerline maximum velocity (default 1.0).
    dx, dy : float
        Grid spacing (default 1.0).
    frame : int
        Time frame index (default 0).

    Returns
    -------
    xr.Dataset
        Canonical PIVPy dataset with analytical Poiseuille flow.
    """
    x_coords = np.arange(cols, dtype=float) * dx
    y_coords = np.arange(rows, dtype=float) * dy
    x2d, y2d = np.meshgrid(x_coords, y_coords)

    y_min = y_coords[0]
    y_max = y_coords[-1]
    y_c = (y_min + y_max) / 2.0
    h = (y_max - y_min) / 2.0

    u = u_max * (1.0 - ((y2d - y_c) / h) ** 2)
    v = np.zeros_like(u, dtype=float)
    chc = np.ones_like(u, dtype=float)

    ds = build_dataset(
        x=x_coords,
        y=y_coords,
        t=np.array([float(frame)], dtype=float),
        u=u[:, :, np.newaxis],
        v=v[:, :, np.newaxis],
        chc=chc[:, :, np.newaxis],
        delta_t=float(DELTA_T),
    )
    ds.attrs["flow_model"] = "poiseuille_channel"
    return ds

multivortex(n_frames=1, n=128, n_vortices=8, two_d=True, asym=False, dx=1.0, dy=1.0, seed=None)

Generate 2D synthetic turbulence fields composed of multiple random Burgers vortices.

Parameters:

Name Type Description Default
n_frames int

Number of time frames to generate (default 1).

1
n int or tuple of (rows, cols)

Grid dimension (default 128).

128
n_vortices int

Average number of vortices per frame (default 8).

8
two_d bool

If True, enforces 2D zero-divergence (gamma = 0). Default True.

True
asym bool

If True, generates only positive vorticity (cyclonic). Default False.

False
dx float

Grid spacing (default 1.0).

1.0
dy float

Grid spacing (default 1.0).

1.0
seed int

Random seed for reproducible realizations.

None

Returns:

Type Description
Dataset

Canonical PIVPy dataset with multi-frame turbulent flow field.

Source code in pivpy/synthetic.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def multivortex(
    n_frames: int = 1,
    n: Union[int, Tuple[int, int]] = 128,
    n_vortices: int = 8,
    two_d: bool = True,
    asym: bool = False,
    dx: float = 1.0,
    dy: float = 1.0,
    seed: Optional[int] = None,
) -> xr.Dataset:
    """Generate 2D synthetic turbulence fields composed of multiple random Burgers vortices.

    Parameters
    ----------
    n_frames : int
        Number of time frames to generate (default 1).
    n : int or tuple of (rows, cols)
        Grid dimension (default 128).
    n_vortices : int
        Average number of vortices per frame (default 8).
    two_d : bool
        If True, enforces 2D zero-divergence (gamma = 0). Default True.
    asym : bool
        If True, generates only positive vorticity (cyclonic). Default False.
    dx, dy : float
        Grid spacing (default 1.0).
    seed : int, optional
        Random seed for reproducible realizations.

    Returns
    -------
    xr.Dataset
        Canonical PIVPy dataset with multi-frame turbulent flow field.
    """
    if isinstance(n, int):
        rows, cols = n, n
    else:
        rows, cols = n

    rng = np.random.default_rng(seed)
    x_coords = np.arange(cols, dtype=float) * dx
    y_coords = np.arange(rows, dtype=float) * dy
    x2d, y2d = np.meshgrid(x_coords, y_coords)

    domain_w = float(x_coords[-1] - x_coords[0])
    domain_h = float(y_coords[-1] - y_coords[0])
    diag = np.sqrt(domain_w**2 + domain_h**2)

    n_total_vortices = int(np.ceil(n_vortices * 9))
    frames = []

    for t_idx in range(n_frames):
        u_frame = np.zeros((rows, cols), dtype=float)
        v_frame = np.zeros((rows, cols), dtype=float)

        xc = x_coords[0] + domain_w * (3.0 * rng.random(n_total_vortices) - 1.0)
        yc = y_coords[0] + domain_h * (3.0 * rng.random(n_total_vortices) - 1.0)

        omega = rng.choice([-1.0, 1.0], size=n_total_vortices) * (2.0 + rng.standard_normal(n_total_vortices))
        if asym:
            omega = np.abs(omega)

        div = np.zeros(n_total_vortices, dtype=float) if two_d else 0.5 * rng.standard_normal(n_total_vortices)
        core = 0.015 * (4.0 + rng.standard_normal(n_total_vortices)) * diag
        core = np.maximum(core, 2.0 * min(dx, dy))

        for k in range(n_total_vortices):
            rx = x2d - xc[k]
            ry = y2d - yc[k]
            r2 = rx**2 + ry**2
            safe_r2 = np.where(r2 == 0.0, 1e-12, r2)
            c2 = core[k] ** 2

            decay = (1.0 - np.exp(-r2 / c2)) / safe_r2
            ampl_rot = omega[k] * c2 / 2.0 * decay
            ampl_div = div[k] * c2 / 2.0 * decay

            u_frame += -ampl_rot * ry + ampl_div * rx
            v_frame += ampl_rot * rx + ampl_div * ry

        chc_frame = np.ones_like(u_frame, dtype=float)
        ds_t = build_dataset(
            x=x_coords,
            y=y_coords,
            t=np.array([float(t_idx)], dtype=float),
            u=u_frame[:, :, np.newaxis],
            v=v_frame[:, :, np.newaxis],
            chc=chc_frame[:, :, np.newaxis],
            delta_t=float(DELTA_T),
        )
        frames.append(ds_t)

    ds = xr.concat(frames, dim="t") if len(frames) > 1 else frames[0]
    ds.attrs["flow_model"] = "multivortex"
    return ds

randvec(n=128, n_frames=1, slope=5.0 / 3.0, nc=3.0, nl=None, dx=1.0, dy=1.0, seed=None)

Generate divergence-free 2D random velocity fields with prescribed power spectrum.

Parameters:

Name Type Description Default
n int or tuple of (rows, cols)

Grid dimension (default 128).

128
n_frames int

Number of independent realization frames along 't' (default 1).

1
slope float

Spectral decay exponent $E(k) \propto k^{-\text{slope}}$ (default 5/3).

5.0 / 3.0
nc float

Small scale cutoff in grid units (default 3.0).

3.0
nl float

Large scale cutoff in grid units. Default is n/3.

None
dx float

Grid spacing (default 1.0).

1.0
dy float

Grid spacing (default 1.0).

1.0
seed int

Random seed for reproducibility.

None

Returns:

Type Description
Dataset

Canonical PIVPy dataset with divergence-free random velocity fields.

Source code in pivpy/synthetic.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
def randvec(
    n: Union[int, Tuple[int, int]] = 128,
    n_frames: int = 1,
    slope: float = 5.0 / 3.0,
    nc: float = 3.0,
    nl: Optional[float] = None,
    dx: float = 1.0,
    dy: float = 1.0,
    seed: Optional[int] = None,
) -> xr.Dataset:
    """Generate divergence-free 2D random velocity fields with prescribed power spectrum.

    Parameters
    ----------
    n : int or tuple of (rows, cols)
        Grid dimension (default 128).
    n_frames : int
        Number of independent realization frames along 't' (default 1).
    slope : float
        Spectral decay exponent $E(k) \\propto k^{-\\text{slope}}$ (default 5/3).
    nc : float
        Small scale cutoff in grid units (default 3.0).
    nl : float, optional
        Large scale cutoff in grid units. Default is n/3.
    dx, dy : float
        Grid spacing (default 1.0).
    seed : int, optional
        Random seed for reproducibility.

    Returns
    -------
    xr.Dataset
        Canonical PIVPy dataset with divergence-free random velocity fields.
    """
    if isinstance(n, int):
        rows, cols = n, n
    else:
        rows, cols = n

    if nl is None:
        nl = float(min(rows, cols)) / 3.0

    rng = np.random.default_rng(seed)
    x_coords = np.arange(cols, dtype=float) * dx
    y_coords = np.arange(rows, dtype=float) * dy

    kx = np.fft.fftfreq(cols, d=dx) * 2.0 * np.pi
    ky = np.fft.fftfreq(rows, d=dy) * 2.0 * np.pi
    kx_2d, ky_2d = np.meshgrid(kx, ky)
    k_mag = np.sqrt(kx_2d**2 + ky_2d**2)
    safe_k = np.where(k_mag == 0.0, 1.0, k_mag)

    k_c = 2.0 * np.pi / (nc * max(dx, dy))
    k_l = 2.0 * np.pi / (nl * min(dx, dy))

    spec = np.exp(-((k_mag / k_c) ** 2)) * (k_mag**2) / np.sqrt(1.0 + (k_mag / k_l) ** (2.0 * slope + 4.0)) / safe_k
    spec[k_mag == 0.0] = 0.0
    amp = np.sqrt(spec)

    frames = []
    for t_idx in range(n_frames):
        phase = rng.uniform(0.0, 2.0 * np.pi, size=(rows, cols))
        complex_noise = np.exp(1j * phase)

        psi_hat = amp * complex_noise / safe_k
        psi_hat[k_mag == 0.0] = 0.0

        u_hat = 1j * ky_2d * psi_hat
        v_hat = -1j * kx_2d * psi_hat

        u_real = np.real(np.fft.ifft2(u_hat))
        v_real = np.real(np.fft.ifft2(v_hat))

        u_real -= np.mean(u_real)
        v_real -= np.mean(v_real)

        chc = np.ones_like(u_real, dtype=float)
        ds_t = build_dataset(
            x=x_coords,
            y=y_coords,
            t=np.array([float(t_idx)], dtype=float),
            u=u_real[:, :, np.newaxis],
            v=v_real[:, :, np.newaxis],
            chc=chc[:, :, np.newaxis],
            delta_t=float(DELTA_T),
        )
        frames.append(ds_t)

    ds = xr.concat(frames, dim="t") if len(frames) > 1 else frames[0]
    ds.attrs["flow_model"] = "randvec"
    return ds

shear_layer(rows=64, cols=64, u0=1.0, delta=5.0, perturbation=0.05, dx=1.0, dy=1.0, frame=0)

Generate an analytical hyperbolic tangent shear/mixing layer with Kelvin-Helmholtz perturbation.

Parameters:

Name Type Description Default
rows int

Grid dimensions (default 64x64).

64
cols int

Grid dimensions (default 64x64).

64
u0 float

Free-stream velocity magnitude (default 1.0).

1.0
delta float

Shear layer thickness in coordinate units (default 5.0).

5.0
perturbation float

Relative amplitude of transverse periodic Kelvin-Helmholtz disturbance (default 0.05).

0.05
dx float

Grid spacing (default 1.0).

1.0
dy float

Grid spacing (default 1.0).

1.0
frame int

Time frame index (default 0).

0

Returns:

Type Description
Dataset

Canonical PIVPy dataset with analytical shear layer.

Source code in pivpy/synthetic.py
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
def shear_layer(
    rows: int = 64,
    cols: int = 64,
    u0: float = 1.0,
    delta: float = 5.0,
    perturbation: float = 0.05,
    dx: float = 1.0,
    dy: float = 1.0,
    frame: int = 0,
) -> xr.Dataset:
    """Generate an analytical hyperbolic tangent shear/mixing layer with Kelvin-Helmholtz perturbation.

    Parameters
    ----------
    rows, cols : int
        Grid dimensions (default 64x64).
    u0 : float
        Free-stream velocity magnitude (default 1.0).
    delta : float
        Shear layer thickness in coordinate units (default 5.0).
    perturbation : float
        Relative amplitude of transverse periodic Kelvin-Helmholtz disturbance (default 0.05).
    dx, dy : float
        Grid spacing (default 1.0).
    frame : int
        Time frame index (default 0).

    Returns
    -------
    xr.Dataset
        Canonical PIVPy dataset with analytical shear layer.
    """
    x_coords = np.arange(cols, dtype=float) * dx
    y_coords = np.arange(rows, dtype=float) * dy
    x2d, y2d = np.meshgrid(x_coords, y_coords)

    y_c = (y_coords[0] + y_coords[-1]) / 2.0
    domain_w = x_coords[-1] - x_coords[0]
    k_pert = 2.0 * np.pi / domain_w

    u = u0 * np.tanh((y2d - y_c) / delta)
    v = np.zeros_like(u, dtype=float)

    if perturbation > 0.0:
        pert_v = perturbation * u0 * np.sin(k_pert * x2d) * np.exp(-(((y2d - y_c) / (2.0 * delta)) ** 2))
        pert_u = -perturbation * u0 * np.cos(k_pert * x2d) * ((y2d - y_c) / delta) * np.exp(-(((y2d - y_c) / (2.0 * delta)) ** 2))
        u += pert_u
        v += pert_v

    chc = np.ones_like(u, dtype=float)
    ds = build_dataset(
        x=x_coords,
        y=y_coords,
        t=np.array([float(frame)], dtype=float),
        u=u[:, :, np.newaxis],
        v=v[:, :, np.newaxis],
        chc=chc[:, :, np.newaxis],
        delta_t=float(DELTA_T),
    )
    ds.attrs["flow_model"] = "shear_layer"
    return ds

vortex(n=128, r0=10.0, vorticity=1.0, mode='burgers', diver=0.0, center=None, dx=1.0, dy=1.0, frame=0, n_vatistas=2.0)

Generate an analytical 2D vector field containing a centered or offset vortex.

Parameters:

Name Type Description Default
n int or tuple of (rows, cols)

Grid dimension. If int, creates an (n, n) grid.

128
r0 float

Vortex core radius in coordinate units (default 10.0).

10.0
vorticity float

Peak vorticity / circulation parameter $\omega_0$ in $s^{-1}$ (default 1.0).

1.0
mode ('burgers', 'lamb', 'rankine', 'vatistas')

Vortex profile type: - 'burgers' or 'lamb': Lamb-Oseen / Burgers Gaussian vorticity profile - 'rankine': Solid-body rotation inside core, potential vortex outside - 'vatistas': Generalized algebraic vortex profile

'burgers'
diver float

Radial divergence / suction parameter $\gamma$ (default 0.0).

0.0
center tuple of (x0, y0)

Vortex center coordinates. Default is domain center.

None
dx float

Grid spacing in x and y directions (default 1.0).

1.0
dy float

Grid spacing in x and y directions (default 1.0).

1.0
frame int

Time frame index (default 0).

0
n_vatistas float

Exponent parameter for Vatistas vortex (default 2.0).

2.0

Returns:

Type Description
Dataset

Canonical PIVPy dataset with variables u, v, chc, coords (x, y, t).

Source code in pivpy/synthetic.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def vortex(
    n: Union[int, Tuple[int, int]] = 128,
    r0: float = 10.0,
    vorticity: float = 1.0,
    mode: Literal["burgers", "lamb", "rankine", "vatistas"] = "burgers",
    diver: float = 0.0,
    center: Optional[Tuple[float, float]] = None,
    dx: float = 1.0,
    dy: float = 1.0,
    frame: int = 0,
    n_vatistas: float = 2.0,
) -> xr.Dataset:
    """Generate an analytical 2D vector field containing a centered or offset vortex.

    Parameters
    ----------
    n : int or tuple of (rows, cols)
        Grid dimension. If int, creates an (n, n) grid.
    r0 : float
        Vortex core radius in coordinate units (default 10.0).
    vorticity : float
        Peak vorticity / circulation parameter $\\omega_0$ in $s^{-1}$ (default 1.0).
    mode : {'burgers', 'lamb', 'rankine', 'vatistas'}
        Vortex profile type:
        - 'burgers' or 'lamb': Lamb-Oseen / Burgers Gaussian vorticity profile
        - 'rankine': Solid-body rotation inside core, potential vortex outside
        - 'vatistas': Generalized algebraic vortex profile
    diver : float
        Radial divergence / suction parameter $\\gamma$ (default 0.0).
    center : tuple of (x0, y0), optional
        Vortex center coordinates. Default is domain center.
    dx, dy : float
        Grid spacing in x and y directions (default 1.0).
    frame : int
        Time frame index (default 0).
    n_vatistas : float
        Exponent parameter for Vatistas vortex (default 2.0).

    Returns
    -------
    xr.Dataset
        Canonical PIVPy dataset with variables u, v, chc, coords (x, y, t).
    """
    if isinstance(n, int):
        rows, cols = n, n
    else:
        rows, cols = n

    x_coords = np.arange(cols, dtype=float) * dx
    y_coords = np.arange(rows, dtype=float) * dy
    x2d, y2d = np.meshgrid(x_coords, y_coords)

    if center is None:
        x0 = float(x_coords[-1] + x_coords[0]) / 2.0
        y0 = float(y_coords[-1] + y_coords[0]) / 2.0
    else:
        x0, y0 = center

    rx = x2d - x0
    ry = y2d - y0
    radius = np.sqrt(rx**2 + ry**2)

    # Angular velocity & divergence scales
    omega = float(vorticity) / 2.0
    gamma = float(diver) / 2.0

    u = np.zeros_like(radius, dtype=float)
    v = np.zeros_like(radius, dtype=float)

    mode_lower = mode.lower()
    safe_radius = np.where(radius == 0.0, 1e-12, radius)

    if mode_lower in ("burgers", "lamb"):
        decay = 1.0 - np.exp(-((radius / r0) ** 2))
        circ_factor = omega * (r0**2) / (safe_radius**2) * decay
        u = -circ_factor * ry
        v = circ_factor * rx

        if gamma != 0.0:
            div_factor = gamma * (r0**2) / (safe_radius**2) * decay
            u += div_factor * rx
            v += div_factor * ry

        u[radius == 0.0] = 0.0
        v[radius == 0.0] = 0.0

    elif mode_lower == "rankine":
        inside = radius <= r0
        outside = ~inside

        u[inside] = -omega * ry[inside]
        v[inside] = omega * rx[inside]

        circ_factor = omega * (r0**2) / (safe_radius[outside] ** 2)
        u[outside] = -circ_factor * ry[outside]
        v[outside] = circ_factor * rx[outside]

    elif mode_lower == "vatistas":
        factor = omega / ((1.0 + (radius / r0) ** (2.0 * n_vatistas)) ** (1.0 / n_vatistas))
        u = -factor * ry
        v = factor * rx

    else:
        raise ValueError(f"Unknown vortex mode '{mode}'. Choose from 'burgers', 'lamb', 'rankine', 'vatistas'.")

    chc = np.ones_like(u, dtype=float)

    u_3d = u[:, :, np.newaxis]
    v_3d = v[:, :, np.newaxis]
    chc_3d = chc[:, :, np.newaxis]
    t_coords = np.array([float(frame)], dtype=float)

    ds = build_dataset(
        x=x_coords,
        y=y_coords,
        t=t_coords,
        u=u_3d,
        v=v_3d,
        chc=chc_3d,
        delta_t=float(DELTA_T),
    )
    ds.attrs["flow_model"] = f"vortex_{mode_lower}"
    return ds

vortex_pair(n_frames=30, n=128, r0=None, dx=1.0, dy=1.0)

Generate a time-series dataset of an interacting counter-rotating vortex pair (dipole).

Two vortices (positive cyclonic and negative anticyclonic) translate from left to right. As they advance, the negative (blue) vortex strengthens and approaches the positive (red) one.

Parameters:

Name Type Description Default
n_frames int

Number of time frames to generate.

30
n int or tuple of (rows, cols)

Spatial grid dimension.

128
r0 float

Vortex core radius in coordinate units. Defaults to 8% of domain height.

None
dx float

Grid spacing in x and y.

1.0
dy float

Grid spacing in x and y.

1.0

Returns:

Type Description
Dataset

Canonical multi-frame PIVPy dataset with variables ('u', 'v', 'chc') and coords ('x', 'y', 't').

Source code in pivpy/synthetic.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def vortex_pair(
    n_frames: int = 30,
    n: Union[int, Tuple[int, int]] = 128,
    r0: Optional[float] = None,
    dx: float = 1.0,
    dy: float = 1.0,
) -> xr.Dataset:
    """Generate a time-series dataset of an interacting counter-rotating vortex pair (dipole).

    Two vortices (positive cyclonic and negative anticyclonic) translate from left to right.
    As they advance, the negative (blue) vortex strengthens and approaches the positive (red) one.

    Parameters
    ----------
    n_frames : int, default 30
        Number of time frames to generate.
    n : int or tuple of (rows, cols), default 128
        Spatial grid dimension.
    r0 : float, optional
        Vortex core radius in coordinate units. Defaults to 8% of domain height.
    dx, dy : float, default 1.0
        Grid spacing in x and y.

    Returns
    -------
    xr.Dataset
        Canonical multi-frame PIVPy dataset with variables ('u', 'v', 'chc') and coords ('x', 'y', 't').
    """
    if isinstance(n, int):
        rows, cols = n, n
    else:
        rows, cols = n

    x_coords = np.arange(cols, dtype=float) * dx
    y_coords = np.arange(rows, dtype=float) * dy
    x2d, y2d = np.meshgrid(x_coords, y_coords)

    x_min, x_max = x_coords[0], x_coords[-1]
    y_min, y_max = y_coords[0], y_coords[-1]
    y_center = (y_min + y_max) / 2.0
    domain_width = max(1e-6, x_max - x_min)
    domain_height = max(1e-6, y_max - y_min)

    core_radius = float(r0) if r0 is not None else 0.085 * domain_height
    frames = []

    for t_idx in range(n_frames):
        tau = float(t_idx) / max(1, n_frames - 1)  # Normalized time progress 0.0 -> 1.0

        # Positive / Red vortex (upper path, steady circulation)
        x_red = x_min + 0.22 * domain_width + 0.56 * domain_width * tau
        y_red = y_center + 0.18 * domain_height - 0.04 * domain_height * tau
        omega_red = 2.4

        # Negative / Blue vortex (lower path, strengthens and gets closer to red vortex)
        x_blue = x_min + 0.18 * domain_width + 0.60 * domain_width * tau
        y_blue = y_center - 0.26 * domain_height + 0.20 * domain_height * tau
        omega_blue = -(1.6 + 2.4 * tau)

        u_frame = np.zeros((rows, cols), dtype=float)
        v_frame = np.zeros((rows, cols), dtype=float)

        for xc, yc, omega in [(x_red, y_red, omega_red), (x_blue, y_blue, omega_blue)]:
            rx = x2d - xc
            ry = y2d - yc
            r2 = rx**2 + ry**2
            safe_r2 = np.where(r2 == 0.0, 1e-12, r2)
            c2 = core_radius**2
            decay = (1.0 - np.exp(-r2 / c2)) / safe_r2
            ampl = omega * c2 / 2.0 * decay
            u_frame += -ampl * ry
            v_frame += ampl * rx

        chc_frame = np.ones_like(u_frame, dtype=float)
        ds_t = build_dataset(
            x=x_coords,
            y=y_coords,
            t=np.array([float(t_idx)], dtype=float),
            u=u_frame[:, :, np.newaxis],
            v=v_frame[:, :, np.newaxis],
            chc=chc_frame[:, :, np.newaxis],
            delta_t=float(DELTA_T),
        )
        frames.append(ds_t)

    ds = xr.concat(frames, dim="t") if len(frames) > 1 else frames[0]
    ds.attrs["flow_model"] = "vortex_pair"
    return ds

pivpy.io

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)

PIVReaderRegistry

Source code in pivpy/io.py
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
class PIVReaderRegistry:
    def __init__(self):
        self._readers: list[PIVReader] = []
        self._register_builtin_readers()

    def _register_builtin_readers(self) -> None:
        self._readers = [InsightVECReader(), OpenPIVReader(), Davis8Reader(), LaVisionVC7Reader(), PIVLabReader(), NetCDFReader(), ZarrReader(), CSVReader()]

    def register(self, reader: PIVReader) -> None:
        self._readers.insert(0, reader)

    def get_readers(self) -> list[PIVReader]:
        return list(self._readers)

    def find_reader(self, filepath: Any) -> Optional[PIVReader]:
        path = _to_path(filepath)
        if not path.exists():
            return None
        for reader in self._readers:
            try:
                if reader.can_read(path):
                    return reader
            except Exception:
                continue
        return None

    def get_by_name(self, fmt: str) -> Optional[PIVReader]:
        """Look up a registered reader (builtin or custom) by its `name`,
        so `register_reader()` covers explicit `format=` dispatch too, not
        just auto-detection."""
        name = _FORMAT_ALIASES.get(fmt.lower(), fmt.lower())
        for reader in self._readers:
            if reader.name == name:
                return reader
        return None

get_by_name(fmt)

Look up a registered reader (builtin or custom) by its name, so register_reader() covers explicit format= dispatch too, not just auto-detection.

Source code in pivpy/io.py
919
920
921
922
923
924
925
926
927
def get_by_name(self, fmt: str) -> Optional[PIVReader]:
    """Look up a registered reader (builtin or custom) by its `name`,
    so `register_reader()` covers explicit `format=` dispatch too, not
    just auto-detection."""
    name = _FORMAT_ALIASES.get(fmt.lower(), fmt.lower())
    for reader in self._readers:
        if reader.name == name:
            return reader
    return None

batchf(filename, fun, *args, nodisp=True, **kwargs)

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), applying fun to each.

Parameters:

Name Type Description Default
filename Any

File pattern or path. Supports glob wildcards (e.g. *) and a safe subset of PIVMAT-style bracket expansion via :func:pivpy.pivmat_compat.expandstr (e.g. 'Run[1:10,6].vec').

required
fun str | Callable[..., Any]

Either a callable fun(ds, *args, **kwargs) or a string naming a PIV accessor method (e.g. 'azprofile' will call ds.piv.azprofile).

required
nodisp bool

If False, prints each call.

True
*args Any

Passed through to fun.

()
**kwargs Any

Passed through to fun.

()

Returns:

Type Description
list

List of per-file results.

Source code in pivpy/io.py
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
def batchf(
    filename: Any,
    fun: str | Callable[..., Any],
    *args: Any,
    nodisp: bool = True,
    **kwargs: Any,
) -> list[Any]:
    """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), applying ``fun`` to each.

    Parameters
    ----------
    filename:
        File pattern or path. Supports glob wildcards (e.g. ``*``) and a safe
        subset of PIVMAT-style bracket expansion via
        :func:`pivpy.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 call ``ds.piv.azprofile``).
    nodisp:
        If False, prints each call.
    *args, **kwargs:
        Passed through to ``fun``.

    Returns
    -------
    list
        List of per-file results.
    """

    # Expand bracket patterns (safe subset) if present.
    patterns: list[str]
    if isinstance(filename, (list, tuple)):
        patterns = [str(f) for f in filename]
    else:
        patterns = [str(filename)]

    expanded: list[str] = []
    for pat in patterns:
        if "[" in pat and "]" in pat:
            try:
                from pivpy.pivmat_compat import expandstr

                expanded.extend(expandstr(pat))
            except Exception:
                # If parsing fails, fall back to raw glob pattern.
                expanded.append(pat)
        else:
            expanded.append(pat)

    # Resolve files.
    files: list[str] = []
    for pat in expanded:
        files.extend(glob.glob(pat, recursive=True))
    files = sorted(set(files))
    if not files:
        raise FileNotFoundError("No file match")

    def _apply(ds: xr.Dataset) -> Any:
        if callable(fun):
            return fun(ds, *args, **kwargs)

        name = str(fun)
        # Prefer xarray accessor methods (PIVPy idiom).
        if hasattr(ds, "piv") and hasattr(ds.piv, name):
            return getattr(ds.piv, name)(*args, **kwargs)

        # Fallback: module-level functions that accept (ds, ...)
        # Keep scope limited to pivpy modules.
        import pivpy

        for mod_name in ("graphics", "compute_funcs", "io"):
            mod = getattr(pivpy, mod_name, None)
            if mod is not None and hasattr(mod, name):
                return getattr(mod, name)(ds, *args, **kwargs)

        raise ValueError(f"Unknown function '{name}'. Pass a callable or a ds.piv method name.")

    results: list[Any] = []
    for fp in files:
        if not nodisp:
            arg_s = ", ".join([repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()])
            print(f"{fun}({fp!r}{', ' if arg_s else ''}{arg_s})")
        ds = read_piv(fp)
        results.append(_apply(ds))
    return results

convert_directory_to_zarr(directory, zarr_path, pattern='*', ext=None, chunks=None)

Stream a directory of per-frame PIV files into one chunked Zarr store.

Unlike read_directory(), this never holds more than one frame in memory: each frame is read, appended to the Zarr store on disk, and discarded. This is the out-of-core path for directories with thousands of frames (e.g. Davis VC7 exports) -- convert once with this function, then use read_directory_lazy()/read_piv(..., format="zarr") to open the result without materializing every frame.

Source code in pivpy/io.py
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
def convert_directory_to_zarr(
    directory: Any,
    zarr_path: Any,
    pattern: str = "*",
    ext: Optional[str] = None,
    chunks: Optional[dict] = None,
) -> None:
    """Stream a directory of per-frame PIV files into one chunked Zarr store.

    Unlike read_directory(), this never holds more than one frame in memory:
    each frame is read, appended to the Zarr store on disk, and discarded.
    This is the out-of-core path for directories with thousands of frames
    (e.g. Davis VC7 exports) -- convert once with this function, then use
    read_directory_lazy()/read_piv(..., format="zarr") to open the result
    without materializing every frame.
    """
    dirpath = _to_path(directory)
    if not dirpath.exists() or not dirpath.is_dir():
        raise FileNotFoundError(str(dirpath))
    glob_pattern = pattern
    if ext is not None and not glob_pattern.endswith(ext):
        glob_pattern = f"{pattern}{ext}"
    files = sorted(dirpath.glob(glob_pattern))
    if not files:
        raise IOError("No files")

    zpath = _to_path(zarr_path)
    chunk_spec = chunks or {"t": 1}
    for i, fp in enumerate(files):
        frame_ds = read_piv(fp, frame=i).chunk(chunk_spec)
        frame_ds.to_zarr(zpath, mode="w" if i == 0 else "a", append_dim=None if i == 0 else "t")

create_vortex_dataset(n=128, r0=10.0, vorticity=1.0, mode='burgers', diver=0.0)

Create a synthetic vortex dataset (convenience wrapper around pivpy.synthetic.vortex).

Source code in pivpy/io.py
284
285
286
287
288
289
290
291
292
293
def create_vortex_dataset(
    n: int = 128,
    r0: float = 10.0,
    vorticity: float = 1.0,
    mode: str = "burgers",
    diver: float = 0.0,
) -> xr.Dataset:
    """Create a synthetic vortex dataset (convenience wrapper around pivpy.synthetic.vortex)."""
    from pivpy.synthetic import vortex
    return vortex(n=n, r0=r0, vorticity=vorticity, mode=mode, diver=diver)

getattribute(f, attrname=None)

Get metadata/attributes for a field or file (PIVMAT-inspired).

Source code in pivpy/io.py
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
def getattribute(f: Any, attrname: str | None = None) -> Any:
    """Get metadata/attributes for a field or file (PIVMAT-inspired)."""

    if isinstance(f, xr.Dataset):
        attrs = dict(f.attrs)
    else:
        paths = _expand_pivmat_file_patterns(f)
        if not paths:
            raise FileNotFoundError("No file match")
        # Return attributes for the first match (common usage).
        p = paths[0]
        if p.suffix.lower() in {".set", ".exp"}:
            attrs = readsetfile(p)
        else:
            reader = _REGISTRY.find_reader(p)
            if reader is None:
                raise ValueError("Unsupported file format")
            md = reader.read_metadata(p)
            attrs = {"frame": md.frame, "variables": md.variables}

    if attrname is None:
        return attrs
    needle = re.sub(r"_+", "", str(attrname)).lower()
    for k, v in attrs.items():
        kk = re.sub(r"_+", "", str(k)).lower()
        if kk == needle:
            return v
    raise KeyError(attrname)

getfilenum(name, pat, opt='filedir')

Extract numeric indices from matching file/dir names (PIVMAT-inspired).

Source code in pivpy/io.py
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
def getfilenum(name: Any, pat: str, opt: str = "filedir") -> list[float]:
    """Extract numeric indices from matching file/dir names (PIVMAT-inspired)."""

    paths = _expand_pivmat_file_patterns(name)
    if not paths:
        raise FileNotFoundError("No file match")

    opt_l = str(opt).lower()
    nums: list[float] = []
    for p in paths:
        hay: str
        if opt_l == "dironly":
            hay = str(p.parent)
        elif opt_l == "fileonly":
            hay = p.name
        else:
            hay = str(p)
        idx = hay.find(pat)
        if idx < 0:
            continue
        s = hay[idx + len(pat) :]
        m = re.search(r"^[+-]?[0-9]+(?:\.[0-9]+)?", s)
        if m:
            nums.append(float(m.group(0)))
    return nums

getframedt(filename)

Compute time interval(s) between frames for IMX/IM7 (PIVMAT-inspired).

This requires lvpyio and DaVis time series metadata. If unavailable, returns array([0.0]).

Source code in pivpy/io.py
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
def getframedt(filename: Any) -> np.ndarray:
    """Compute time interval(s) between frames for IMX/IM7 (PIVMAT-inspired).

    This requires ``lvpyio`` and DaVis time series metadata. If unavailable,
    returns ``array([0.0])``.
    """

    path = _to_path(filename)
    try:
        from lvpyio import read_buffer  # type: ignore
    except Exception:
        return np.asarray([0.0], dtype=float)

    try:
        buf = read_buffer(str(path))
        data = buf[0]
        # Best-effort: try common attribute locations.
        ats = None
        if hasattr(data, "attributes"):
            ats = getattr(data, "attributes")
        if ats and isinstance(ats, dict):
            # Some exports may store AcqTimeSeries0 as list of timestamps.
            for key in ("AcqTimeSeries0", "AcqTimeSeries"):
                if key in ats:
                    ts = np.asarray(ats[key], dtype=float)
                    if ts.size <= 1:
                        return np.asarray([0.0], dtype=float)
                    return np.diff(ts) * 1e-3  # ms -> s
    except Exception:
        pass
    return np.asarray([0.0], dtype=float)

getimx(A, frame=0)

PIVMAT getimx equivalent.

In PIVPy, if A is an :class:xarray.Dataset, this returns the 2D coordinate meshes and the scalar/vector arrays for the selected frame.

Source code in pivpy/io.py
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
def getimx(A: Any, frame: int = 0):
    """PIVMAT ``getimx`` equivalent.

    In PIVPy, if ``A`` is an :class:`xarray.Dataset`, this returns the 2D
    coordinate meshes and the scalar/vector arrays for the selected frame.
    """

    if not isinstance(A, xr.Dataset):
        raise TypeError("getimx currently supports xarray.Dataset inputs")
    ds = A
    if "t" in ds.dims:
        ds = ds.isel(t=int(frame))
    x = np.asarray(ds["x"].values, dtype=float)
    y = np.asarray(ds["y"].values, dtype=float)
    x2d, y2d = np.meshgrid(x, y)
    if "w" in ds:
        return x2d, y2d, np.asarray(ds["w"].values, dtype=float)
    u = np.asarray(ds["u"].values, dtype=float)
    v = np.asarray(ds["v"].values, dtype=float)
    chc = np.asarray(ds["chc"].values, dtype=float) if "chc" in ds else np.ones_like(u)
    return x2d, y2d, u, v, chc

getpivtime(f, *args)

Return acquisition times in seconds for dataset(s) or files (PIVMAT-inspired).

For PIVPy datasets, this uses ds['t'] and ds.attrs['delta_t']. If the option '0' is provided, the first time is shifted to 0.

Source code in pivpy/io.py
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
def getpivtime(f: Any, *args: str) -> np.ndarray:
    """Return acquisition times in seconds for dataset(s) or files (PIVMAT-inspired).

    For PIVPy datasets, this uses ``ds['t']`` and ``ds.attrs['delta_t']``.
    If the option `'0'` is provided, the first time is shifted to 0.
    """

    start_at_zero = any(str(a) == "0" for a in args)
    if isinstance(f, xr.Dataset):
        ds = f
        dt = float(ds.attrs.get("delta_t", 0.0))
        t = np.asarray(ds["t"].values, dtype=float) * dt
        if start_at_zero and t.size:
            t = t - float(t[0])
        return t

    paths = _expand_pivmat_file_patterns(f)
    if not paths:
        raise FileNotFoundError("No file match")
    times: list[float] = []
    for p in paths:
        ds = read_piv(p)
        t = getpivtime(ds, *args)
        # PIVMAT returns one time per field; use first time for per-file.
        times.append(float(t[0]) if t.size else 0.0)
    return np.asarray(times, dtype=float)

getsetname(curdir=None)

Return the last element of a path (PIVMAT-inspired).

Source code in pivpy/io.py
1829
1830
1831
1832
1833
def getsetname(curdir: Any = None) -> str:
    """Return the last element of a path (PIVMAT-inspired)."""

    p = pathlib.Path.cwd() if curdir is None else _to_path(curdir)
    return p.name

getvar(s, reqname=None, mode=None)

Parse variables encoded in a string like p1=v1_p2=v2_... (PIVMAT-inspired).

Source code in pivpy/io.py
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
def getvar(s: Any, reqname: str | int | None = None, mode: str | None = None) -> Any:
    """Parse variables encoded in a string like ``p1=v1_p2=v2_...`` (PIVMAT-inspired)."""

    if isinstance(s, (list, tuple)):
        return [getvar(x, reqname=reqname, mode=mode) for x in s]

    text = str(s)
    keep_strings = (str(mode).lower().startswith("str") if mode is not None else False)

    parts = [p for p in re.split(r"_+", text) if p]
    out: dict[str, Any] = {}
    auto = 1
    for part in parts:
        if "=" in part:
            k, v = part.split("=", 1)
            key = k
            val_s = v
        else:
            m = re.match(r"^([A-Za-z]+)(.*)$", part)
            if m:
                key = m.group(1)
                val_s = m.group(2)
            else:
                key = f"var{auto}"
                val_s = part
                auto += 1

        val: Any = val_s
        if not keep_strings:
            try:
                if re.match(r"^[+-]?[0-9]+$", val_s):
                    val = int(val_s)
                else:
                    val = float(val_s)
            except Exception:
                val = val_s
        out[key] = val

    if reqname is None:
        return out
    if isinstance(reqname, int):
        keys = list(out.keys())
        return out[keys[int(reqname) - 1]]
    # name lookup (ignore underscores, case-insensitive)
    needle = re.sub(r"_+", "", str(reqname)).lower()
    for k, v in out.items():
        kk = re.sub(r"_+", "", str(k)).lower()
        if kk == needle:
            return v
    raise KeyError(reqname)

im2pivmat(im, *, x=None, y=None, namew='I', unit='au', dtype=np.float32)

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 variable w.

Parameters:

Name Type Description Default
im ArrayLike

2D image array (interpreted as (y, x)).

required
x ArrayLike | None

Optional 1D coordinate vectors. Defaults are 1..N (MATLAB-like).

None
y ArrayLike | None

Optional 1D coordinate vectors. Defaults are 1..N (MATLAB-like).

None
namew str

Display name for the scalar (stored in w.attrs['long_name']).

'I'
unit str

Unit string for coordinates and intensity (default: 'au').

'au'
dtype Any

Output dtype for w (default: numpy.float32).

float32

Returns:

Type Description
Dataset

Dataset with variable w and coordinates x, y, t.

Source code in pivpy/io.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def im2pivmat(
    im: ArrayLike,
    *,
    x: ArrayLike | None = None,
    y: ArrayLike | None = None,
    namew: str = "I",
    unit: str = "au",
    dtype: Any = np.float32,
) -> xr.Dataset:
    """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 variable ``w``.

    Parameters
    ----------
    im:
        2D image array (interpreted as ``(y, x)``).
    x, 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
    -------
    xarray.Dataset
        Dataset with variable ``w`` and coordinates ``x``, ``y``, ``t``.
    """

    arr = np.asarray(im)
    if arr.ndim != 2:
        raise ValueError("im2pivmat expects a 2D image array")

    ny, nx = int(arr.shape[0]), int(arr.shape[1])

    if x is None:
        x1 = np.arange(1, nx + 1, dtype=float)
    else:
        x1 = np.asarray(x, dtype=float)
        if x1.ndim != 1 or x1.size != nx:
            raise ValueError("x must be a 1D array with length equal to image width")

    if y is None:
        y1 = np.arange(1, ny + 1, dtype=float)
    else:
        y1 = np.asarray(y, dtype=float)
        if y1.ndim != 1 or y1.size != ny:
            raise ValueError("y must be a 1D array with length equal to image height")

    w = np.asarray(arr, dtype=dtype)
    ds = xr.Dataset(
        data_vars={"w": (("y", "x", "t"), w[:, :, None])},
        coords={
            "x": ("x", x1),
            "y": ("y", y1),
            "t": ("t", np.asarray([0.0], dtype=float)),
        },
    )

    ds["x"].attrs.setdefault("units", unit)
    ds["y"].attrs.setdefault("units", unit)
    ds["t"].attrs.setdefault("units", TIME_UNITS)
    ds["w"].attrs.setdefault("units", unit)
    ds["w"].attrs.setdefault("long_name", str(namew))
    ds.attrs.setdefault("source", "image")
    ds.attrs.setdefault("delta_t", float(DELTA_T))
    ds.attrs.setdefault("files", [])
    return ds

loadarrayvec(pathname, fname, *opts)

PIVMAT loadarrayvec equivalent.

Loads a 2D array of vector fields: directories matched by pathname and files matched by fname inside each directory.

Returns a nested list out[i][j] where i indexes directories and j indexes files.

Source code in pivpy/io.py
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
def loadarrayvec(pathname: Any, fname: Any, *opts: str) -> list[list[xr.Dataset]]:
    """PIVMAT ``loadarrayvec`` equivalent.

    Loads a 2D array of vector fields: directories matched by ``pathname`` and
    files matched by ``fname`` inside each directory.

    Returns a nested list ``out[i][j]`` where ``i`` indexes directories and
    ``j`` indexes files.
    """

    verbose = any(str(o).lower().startswith("verb") for o in opts)
    dirs = _expand_pivmat_file_patterns(pathname)
    dirs = [p for p in dirs if p.is_dir()]
    if not dirs:
        raise FileNotFoundError("No directory match")

    out: list[list[xr.Dataset]] = []
    for d in dirs:
        # match files inside directory
        files = _expand_pivmat_file_patterns(str(d / str(fname)))
        if verbose:
            print(f"Directory: {str(d)} ({len(files)} files)")
        out.append([read_piv(fp) for fp in files])
    return out

loadpivtxt(fname)

PIVMAT loadpivtxt compatible 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'].

Source code in pivpy/io.py
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
def loadpivtxt(fname: Any) -> xr.Dataset:
    """PIVMAT ``loadpivtxt`` compatible 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']``.
    """

    path = _to_path(fname)
    if not path.exists():
        raise FileNotFoundError(str(path))

    header: list[str] = []
    data_lines: list[str] = []
    with path.open("r", errors="ignore") as f:
        for line in f:
            s = line.strip()
            if not s:
                continue
            # numeric line? allow leading sign/dot/digit
            if re.match(r"^[\s,]*[+-]?(\d|\.)", s):
                data_lines.append(s)
            else:
                header.append(s)

    if not data_lines:
        raise ValueError("No numeric data found in file")

    # Normalize commas to spaces and parse floats.
    rows: list[list[float]] = []
    for l in data_lines:
        l2 = l.replace(",", " ")
        vals = [float(v) for v in l2.split() if v]
        if len(vals) < 4:
            continue
        rows.append(vals[:6])

    arr = np.asarray(rows, dtype=float)
    x, y, u, v = (arr[:, 0], arr[:, 1], arr[:, 2], arr[:, 3])
    mask = arr[:, 4] if arr.shape[1] >= 5 else None

    # Infer grid
    xu, xi = unsorted_unique(x)
    yu, yi = unsorted_unique(y)
    cols = len(xu)
    rows_n = len(yu)
    if cols * rows_n != len(x):
        raise ValueError("Unsupported TXT layout (not a full rectilinear grid)")

    # Reconstruct meshes in row-major order.
    x2d, y2d = np.meshgrid(xu, yu)
    u2 = u.reshape((rows_n, cols))
    v2 = v.reshape((rows_n, cols))
    if mask is not None:
        m2 = mask.reshape((rows_n, cols))
    else:
        m2 = np.ones_like(u2, dtype=float)

    ds = from_arrays(x2d, y2d, u2, v2, mask=m2, frame=_extract_frame_number(path))
    ds.attrs["files"] = [str(path)]
    if header:
        ds.attrs["Attributes"] = "\n".join(header)
    return ds

loadvec(filename=None, *args, **kwargs)

PIVMAT-compatible loader (wrapper over :func: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:

Name Type Description Default
filename Any

Path/pattern, a sequence of paths, or a 1-based numeric index selecting from files in the current directory (PIVMAT behavior).

None
frame

Optional frame override passed through to :func:read_piv.

required
verbose

If True, prints each file being loaded.

required

Returns:

Type Description
Dataset | list[Dataset]

Single dataset if one file is matched, otherwise a list of datasets.

Source code in pivpy/io.py
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
def loadvec(filename: Any = None, *args: Any, **kwargs: Any) -> xr.Dataset | list[xr.Dataset]:
    """PIVMAT-compatible loader (wrapper over :func:`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 :func:`read_piv`.
    verbose:
        If True, prints each file being loaded.

    Returns
    -------
    xarray.Dataset | list[xarray.Dataset]
        Single dataset if one file is matched, otherwise a list of datasets.
    """

    frame = kwargs.pop("frame", None)
    verbose = bool(kwargs.pop("verbose", False))
    if kwargs:
        raise TypeError(f"Unsupported keyword arguments: {sorted(kwargs)}")

    if filename is None:
        raise ValueError("loadvec requires a filename/pattern (no GUI picker in Python)")

    # Numeric index selects from common PIVMAT extensions in cwd.
    if isinstance(filename, (int, np.integer)):
        cwd = pathlib.Path.cwd()
        exts = {".vec", ".vc7", ".imx", ".img", ".im7", ".cm0", ".uwo", ".txt", ".mat", ".nc"}
        files = sorted([p for p in cwd.iterdir() if p.is_file() and p.suffix.lower() in exts])
        idx = int(filename) - 1  # PIVMAT is 1-based
        if idx < 0 or idx >= len(files):
            raise IndexError("loadvec numeric index out of range")
        paths = [files[idx]]
    else:
        paths = _expand_pivmat_file_patterns(filename)
        if not paths:
            raise FileNotFoundError("No file match")

    out: list[xr.Dataset] = []
    for i, p in enumerate(paths, start=1):
        if verbose:
            print(f"  Loading file #{i}/{len(paths)}: {str(p)!r}")
        out.append(read_piv(p, frame=frame) if frame is not None else read_piv(p))

    return out[0] if len(out) == 1 else out

multivortex(nfield=1, nsize=128, numvortex=8, *opts)

Generate random Burgers vortices (PIVMAT-compatible).

Port of PIVMAT's multivortex.m.

Returns:

Type Description
Dataset

Dataset with dims (y, x, t) where t indexes fields.

Source code in pivpy/io.py
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
def multivortex(
    nfield: int = 1,
    nsize: int = 128,
    numvortex: float = 8,
    *opts: str,
) -> xr.Dataset:
    """Generate random Burgers vortices (PIVMAT-compatible).

    Port of PIVMAT's ``multivortex.m``.

    Returns
    -------
    xarray.Dataset
        Dataset with dims ``(y, x, t)`` where ``t`` indexes fields.
    """

    nfield = int(nfield)
    nsize = int(nsize)
    numvortex_i = int(np.ceil(float(numvortex) * 9.0))
    opt_l = {str(o).lower() for o in opts}

    rng = np.random.default_rng(0)
    fields: list[xr.Dataset] = []
    for k in range(nfield):
        vx = np.zeros((nsize, nsize), dtype=float)
        vy = np.zeros((nsize, nsize), dtype=float)

        icenter = 1.0 + nsize * (3.0 * rng.random(numvortex_i) - 1.0)
        jcenter = 1.0 + nsize * (3.0 * rng.random(numvortex_i) - 1.0)
        omega = np.sign(rng.random(numvortex_i) - 0.5) * (2.0 + rng.standard_normal(numvortex_i))
        if "asym" in opt_l:
            omega = np.abs(omega)
        if "2d" in opt_l:
            div = np.zeros(numvortex_i, dtype=float)
        else:
            div = rng.standard_normal(numvortex_i) / 2.0
        core = 0.015 * (4.0 + rng.standard_normal(numvortex_i)) * nsize

        i = np.arange(1, nsize + 1, dtype=float)
        j = np.arange(1, nsize + 1, dtype=float)
        ii, jj = np.meshgrid(i, j, indexing="ij")

        for num in range(numvortex_i):
            dx = ii - icenter[num]
            dy = jj - jcenter[num]
            radius = np.sqrt(dx * dx + dy * dy)
            safe_r2 = np.where(radius == 0, np.inf, radius * radius)
            ampl = (core[num] ** 2) / safe_r2 * (1.0 - np.exp(-((radius / core[num]) ** 2))) / 1000.0
            vx = vx + ampl * (-omega[num] * dy + div[num] * dx)
            vy = vy + ampl * (omega[num] * dx + div[num] * dy)

        x = np.arange(0, nsize, dtype=float)
        y = np.arange(0, nsize, dtype=float)
        x2d, y2d = np.meshgrid(x, y)
        ds = from_arrays(x2d, y2d, vx.T, vy.T, mask=np.ones((nsize, nsize), dtype=float), frame=k)
        ds["x"].attrs["units"] = "mm"
        ds["y"].attrs["units"] = "mm"
        ds["u"].attrs["units"] = "m/s"
        ds["v"].attrs["units"] = "m/s"
        ds.attrs["name"] = "Multivortex"
        ds.attrs["setname"] = "-"
        ds.attrs["history"] = ["multivortex"]
        fields.append(ds)

    return xr.concat(fields, dim="t")

openim7(filename, **kwargs)

PIVMAT openim7 equivalent (loads a DaVis IM7 image as a scalar Dataset).

This requires lvpyio at runtime. If it is not available, a :class:ImportError is raised.

Source code in pivpy/io.py
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
def openim7(filename: Any, **kwargs: Any) -> xr.Dataset:
    """PIVMAT ``openim7`` equivalent (loads a DaVis IM7 image as a scalar Dataset).

    This requires ``lvpyio`` at runtime. If it is not available, a
    :class:`ImportError` is raised.
    """

    path = _to_path(filename)
    try:
        from lvpyio import read_buffer  # type: ignore
    except Exception as e:
        raise ImportError("Reading .im7 requires the optional dependency 'lvpyio'") from e

    buf = read_buffer(str(path))
    data = buf[0]
    # Heuristic: if image plane exists, expose as scalar 'w'.
    # lvpyio naming may vary across versions; keep this conservative.
    if hasattr(data, "images") and data.images:
        img = data.images[0]
        im = np.asarray(img, dtype=float)
        return im2pivmat(im, namew="I", unit="pix")
    raise ValueError("Unsupported IM7 content (no image planes found)")

openimg(filename, **kwargs)

PIVMAT openimg equivalent (loads a DaVis IMG image as a scalar Dataset).

This requires lvpyio at runtime.

Source code in pivpy/io.py
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
def openimg(filename: Any, **kwargs: Any) -> xr.Dataset:
    """PIVMAT ``openimg`` equivalent (loads a DaVis IMG image as a scalar Dataset).

    This requires ``lvpyio`` at runtime.
    """

    path = _to_path(filename)
    try:
        from lvpyio import read_buffer  # type: ignore
    except Exception as e:
        raise ImportError("Reading .img requires the optional dependency 'lvpyio'") from e

    buf = read_buffer(str(path))
    data = buf[0]
    if hasattr(data, "images") and data.images:
        img = data.images[0]
        im = np.asarray(img, dtype=float)
        return im2pivmat(im, namew="I", unit="pix")
    raise ValueError("Unsupported IMG content (no image planes found)")

openimx(filename, **kwargs)

PIVMAT openimx equivalent (loads a DaVis IMX image as a scalar Dataset).

This requires lvpyio at runtime.

Source code in pivpy/io.py
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
def openimx(filename: Any, **kwargs: Any) -> xr.Dataset:
    """PIVMAT ``openimx`` equivalent (loads a DaVis IMX image as a scalar Dataset).

    This requires ``lvpyio`` at runtime.
    """

    path = _to_path(filename)
    try:
        from lvpyio import read_buffer  # type: ignore
    except Exception as e:
        raise ImportError("Reading .imx requires the optional dependency 'lvpyio'") from e

    buf = read_buffer(str(path))
    data = buf[0]
    if hasattr(data, "images") and data.images:
        img = data.images[0]
        im = np.asarray(img, dtype=float)
        return im2pivmat(im, namew="I", unit="pix")
    raise ValueError("Unsupported IMX content (no image planes found)")

openset(filename)

PIVMAT openset equivalent.

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.

Source code in pivpy/io.py
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
def openset(filename: Any) -> xr.Dataset:
    """PIVMAT ``openset`` equivalent.

    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.
    """

    path = _to_path(filename)
    if path.suffix.lower() not in {".set", ".exp"}:
        raise ValueError("openset expects a .set or .exp file")

    candidate = path.with_suffix("")
    directory = candidate if candidate.exists() and candidate.is_dir() else path.parent
    return read_directory(directory)

openvc7(filename)

PIVMAT openvc7 equivalent (loads a single VC7 file).

Source code in pivpy/io.py
1452
1453
1454
1455
1456
def openvc7(filename: Any) -> xr.Dataset:
    """PIVMAT ``openvc7`` equivalent (loads a single VC7 file)."""

    ds = load_vc7(filename)
    return ds

openvec(filename)

PIVMAT openvec equivalent.

In MATLAB, this is used by the file browser to populate the workspace. In Python, this simply calls :func:loadvec and returns the dataset(s).

Source code in pivpy/io.py
1442
1443
1444
1445
1446
1447
1448
1449
def openvec(filename: Any) -> xr.Dataset | list[xr.Dataset]:
    """PIVMAT ``openvec`` equivalent.

    In MATLAB, this is used by the file browser to populate the workspace.
    In Python, this simply calls :func:`loadvec` and returns the dataset(s).
    """

    return loadvec(filename)

parse_header(filepath)

Parse basic metadata.

Returns a 7-tuple for the test suite: (variables, units, rows, cols, delta_t, frame, header)

Source code in pivpy/io.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
def parse_header(filepath: Any):
    """Parse basic metadata.

    Returns a 7-tuple for the test suite:
    (variables, units, rows, cols, delta_t, frame, header)
    """
    path = _to_path(filepath)
    if not path.exists():
        raise FileNotFoundError(str(path))

    header_line = ""
    with path.open("r", errors="ignore") as f:
        for line in f:
            if line.strip() == "":
                continue
            header_line = line.rstrip("\n")
            break

    frame = _extract_frame_number(path)

    if "TITLE=" in header_line and "ZONE" in header_line:
        var_segments = re.findall(r"\"([^\"]+)\"", header_line)
        variables: list[str] = []
        units: list[str] = []
        for seg in var_segments:
            parts = seg.split()
            if not parts:
                continue
            variables.append(parts[0])
            units.append(parts[1] if len(parts) > 1 else "")
        m = re.search(r"ZONE\s+I=(\d+),\s*J=(\d+)", header_line)
        cols = int(m.group(1)) if m else None
        rows = int(m.group(2)) if m else None
        m = re.search(r"MicrosecondsPerDeltaT=\"([0-9.]+)\"", header_line)
        delta_t = float(m.group(1)) if m else float(DELTA_T)
        return variables, units, rows, cols, delta_t, frame, header_line

    if header_line.lstrip().startswith("#DaVis"):
        nums = re.findall(r"\b(\d+)\b", header_line)
        rows = cols = None
        if len(nums) >= 2:
            cols = int(nums[-2])
            rows = int(nums[-1])
        return ["x", "y", "u", "v"], ["mm", "mm", "m/s", "m/s"], rows, cols, float(DELTA_T), frame, header_line

    first_data = header_line
    if first_data.lstrip().startswith("#"):
        with path.open("r", errors="ignore") as f:
            for line in f:
                if line.lstrip().startswith("#") or line.strip() == "":
                    continue
                first_data = line
                break
    ncols = len(first_data.split())
    try:
        data = np.loadtxt(path, comments="#")
        if data.ndim == 1:
            data = data[None, :]
    except Exception:
        data = np.empty((0, ncols))
    rows = cols = None
    if data.size:
        cols = len(np.unique(data[:, 0]))
        rows = len(np.unique(data[:, 1]))
    variables = ["x", "y", "u", "v"]
    units = [POS_UNITS, POS_UNITS, VEL_UNITS, VEL_UNITS]
    if ncols >= 5:
        variables.append("chc")
        units.append("")
    if ncols >= 6:
        variables.append("mask")
        units.append("")
    return variables, units, rows, cols, float(DELTA_T), frame, header_line

randvec(n=256, nf=1, slope=5.0 / 3.0, nc=3.0, nl=None, *, seed=0)

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:

Name Type Description Default
n int

Grid size (produces an n x n field). PIVMAT assumes even n.

256
nf int

Number of independent fields (time frames).

1
slope float

Spectral slope $k^{-\mathrm{slope}}$ (default $5/3$).

5.0 / 3.0
nc float

Small-scale cut-off (in units of the vector mesh). For $k > nc$ the spectrum decays Gaussianly.

3.0
nl float | None

Large-scale cut-off (in units of the vector mesh). For $k < nl$ the spectrum behaves as $k^2$. Defaults to n/3.

None
seed int

RNG seed used for deterministic synthesis.

0

Returns:

Type Description
Dataset

Dataset with variables u, v and chc and dims (y, x, t).

Source code in pivpy/io.py
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
def randvec(
    n: int = 256,
    nf: int = 1,
    slope: float = 5.0 / 3.0,
    nc: float = 3.0,
    nl: float | None = None,
    *,
    seed: int = 0,
) -> xr.Dataset:
    r"""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 n`` field). PIVMAT assumes even ``n``.
    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
    -------
    xarray.Dataset
        Dataset with variables ``u``, ``v`` and ``chc`` and dims ``(y, x, t)``.
    """

    n = int(n)
    nf = int(nf)
    slope = float(slope)
    nc = float(nc)
    if nl is None:
        nl = float(n) / 3.0
    nl = float(nl)

    if n <= 0 or nf <= 0:
        raise ValueError("n and nf must be positive")
    if n % 2 != 0:
        raise ValueError("randvec currently requires even n (PIVMAT convention)")
    if nc <= 0.0 or nl <= 0.0:
        raise ValueError("nc and nl must be positive")

    k0_idx = n // 2  # 0-based index of the zero mode (PIVMAT: k0 = n/2 + 1)
    rng = np.random.default_rng(int(seed))
    fields: list[xr.Dataset] = []

    x = np.arange(1, n + 1, dtype=float)
    y = np.arange(1, n + 1, dtype=float)
    x2d, y2d = np.meshgrid(x, y)

    small_scale = float(n) / nc
    large_scale = float(n) / nl

    # Frequencies in numpy's unshifted FFT ordering.
    kx = (np.fft.fftfreq(n) * n).astype(float)
    ky = (np.fft.fftfreq(n) * n).astype(float)

    for frame in range(nf):
        tux = np.zeros((n, n), dtype=np.complex128)
        tuy = np.zeros((n, n), dtype=np.complex128)

        for iy in range(n):
            kyv = float(ky[iy])
            for ix in range(n):
                kxv = float(kx[ix])
                ip = (-iy) % n
                jp = (-ix) % n

                # Only fill one representative per conjugate pair.
                if (iy > ip) or (iy == ip and ix > jp):
                    continue

                k = float(np.hypot(kxv, kyv))
                if k == 0.0:
                    tux[iy, ix] = 0.0
                    tuy[iy, ix] = 0.0
                    continue

                # PIVMAT energy prescription (see randvec.m).
                e = (
                    np.exp(-((k / small_scale) ** 2))
                    * (k**2)
                    / np.sqrt(1.0 + (k / large_scale) ** (2.0 * slope + 4.0))
                ) / k
                amp = float(np.sqrt(float(e)))

                # Self-conjugate modes must be real to keep real-valued fields.
                if iy == ip and ix == jp:
                    phase = -1.0 if int(np.round(2.0 * rng.random())) else 1.0
                else:
                    phase = np.exp(1j * (rng.random() * 2.0 * np.pi))

                costheta = kxv / k
                sintheta = kyv / k
                tux[iy, ix] = -amp * sintheta * phase
                tuy[iy, ix] = amp * costheta * phase

                if not (iy == ip and ix == jp):
                    tux[ip, jp] = np.conj(tux[iy, ix])
                    tuy[ip, jp] = np.conj(tuy[iy, ix])

        vx = np.fft.ifft2(tux).real * (n**2)
        vy = np.fft.ifft2(tuy).real * (n**2)

        ds = from_arrays(x2d, y2d, vx, vy, mask=np.ones((n, n), dtype=float), frame=frame)
        ds["x"].attrs["units"] = "au"
        ds["y"].attrs["units"] = "au"
        ds["u"].attrs["units"] = "au"
        ds["v"].attrs["units"] = "au"
        ds.attrs["ysign"] = "Y axis downward"
        ds.attrs["name"] = "randvec"
        ds.attrs["setname"] = ""
        ds.attrs["history"] = [f"randvec({n},{nf},{slope},{nc},{nl})"]
        fields.append(ds)

    return xr.concat(fields, dim="t")

read_directory_lazy(directory, chunks='auto')

Open a Zarr store (as written by convert_directory_to_zarr) as one dask-backed, lazily-loaded Dataset.

Source code in pivpy/io.py
1180
1181
1182
1183
def read_directory_lazy(directory: Any, chunks: Any = "auto") -> xr.Dataset:
    """Open a Zarr store (as written by convert_directory_to_zarr) as one
    dask-backed, lazily-loaded Dataset."""
    return read_piv(directory, format="zarr", chunks=chunks)

readsetfile(filename, attrname=None)

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 attrname is provided, returns only that value (case-insensitive, ignoring underscores).

Source code in pivpy/io.py
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
def readsetfile(filename: Any, attrname: str | None = None) -> dict[str, Any] | Any:
    """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 ``attrname`` is provided, returns only that value (case-insensitive,
    ignoring underscores).
    """

    path = _to_path(filename)
    if not path.exists():
        raise FileNotFoundError(str(path))

    txt = path.read_text(errors="ignore")
    attrs: dict[str, Any] = {}
    for line in txt.splitlines():
        s = line.strip()
        if not s or s.startswith("#") or s.startswith(";"):
            continue
        # try key=value or key: value
        if "=" in s:
            k, v = s.split("=", 1)
        elif ":" in s:
            k, v = s.split(":", 1)
        else:
            continue
        key = k.strip()
        val = v.strip().strip('"')
        # numeric conversion when possible
        try:
            if re.match(r"^[+-]?[0-9]+$", val):
                val2: Any = int(val)
            else:
                val2 = float(val)
            attrs[key] = val2
        except Exception:
            attrs[key] = val

    if attrname is None:
        return attrs

    needle = re.sub(r"_+", "", str(attrname)).lower()
    for k, v in attrs.items():
        kk = re.sub(r"_+", "", str(k)).lower()
        if kk == needle:
            return v
    raise KeyError(attrname)

readvec(name, comments=1, columns=5)

Read a DaVis .vec text export into a numeric array (PIVMAT-inspired).

This is a light-weight port of PIVMAT's readvec.m.

Returns:

Type Description
tuple

(header, data) where data has shape (j, i, columns).

Source code in pivpy/io.py
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
def readvec(name: Any, comments: int = 1, columns: int = 5) -> tuple[str, np.ndarray]:
    """Read a DaVis `.vec` text export into a numeric array (PIVMAT-inspired).

    This is a light-weight port of PIVMAT's ``readvec.m``.

    Returns
    -------
    tuple
        ``(header, data)`` where ``data`` has shape ``(j, i, columns)``.
    """

    path = _to_path(name)
    if path.suffix.lower() != ".vec":
        path = path.with_suffix(".vec")
    if not path.exists():
        raise FileNotFoundError(str(path))

    raw = path.read_text(errors="ignore")
    # Normalize newlines and commas.
    raw = raw.replace("\r\n", "\n").replace("\r", "\n").replace(",", " ")
    lines = raw.split("\n")
    comments = int(comments)
    if comments < 0:
        comments = 0
    header_lines = lines[:comments] if comments else []
    header = "\n".join(header_lines).lower()
    body = "\n".join(lines[comments:])

    # Attempt to infer columns and units from header.
    x_units = ""
    u_units = ""
    m = re.search(r"variables=([^\n]+)", header)
    if m:
        variables = m.group(1)
        # crude parsing of quoted strings
        quoted = re.findall(r'"([^"]*)"', variables)
        if len(quoted) >= 2:
            x_units = quoted[1]
        if len(quoted) >= 6:
            u_units = quoted[5]
        if quoted:
            columns = max(4, len(quoted) // 2)
    else:
        columns = int(columns)

    # Parse data values.
    data = np.fromstring(body, sep=" ")
    if data.size % columns != 0:
        # best-effort truncation
        data = data[: (data.size // columns) * columns]
    data = data.reshape((-1, columns))
    data[data > 9e9] = 0.0

    mi = re.search(r"\bi=\s*([0-9]+)", header)
    mj = re.search(r"\bj=\s*([0-9]+)", header)
    if not mi or not mj:
        raise ValueError("Could not determine i/j dimensions from header")
    i_dim = int(mi.group(1))
    j_dim = int(mj.group(1))

    data3 = data.reshape((i_dim, j_dim, columns)).transpose((1, 0, 2))
    return header, data3

stream_statistics(source, pattern='*', ext=None, name_mean='mean', name_prime='prime')

Computes online streaming temporal mean, normal Reynolds stresses, shear stress, TKE, and turbulence intensities across large multi-frame PIV data with O(1) memory.

Accepts: - An xr.Dataset (eager or lazy Dask-backed) - A directory path (pathlib.Path or str) containing per-frame PIV files - A Zarr store path - A Sequence/list of file paths or Datasets

Uses the online Welford accumulation algorithm across time 't', holding only 2D grid arrays in memory.

Parameters:

Name Type Description Default
source xr.Dataset, Path, str, or Sequence[Path | str]

PIV data source.

required
pattern str

Glob pattern when source is a directory (default '*').

'*'
ext str

File extension filter (e.g. '.txt', '.vec', '.vc7').

None
name_mean str

Prefix for mean velocity variables (default 'mean').

'mean'
name_prime str

Suffix for fluctuating velocity variables (default 'prime').

'prime'

Returns:

Type Description
Dataset

Single 2D grid dataset containing: - u_mean, v_mean - uu_prime, vv_prime, uv_prime - tke - intensity_u, intensity_v

Source code in pivpy/io.py
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
def stream_statistics(
    source: Any,
    pattern: str = "*",
    ext: Optional[str] = None,
    name_mean: str = "mean",
    name_prime: str = "prime",
) -> xr.Dataset:
    r"""Computes online streaming temporal mean, normal Reynolds stresses, shear stress,
    TKE, and turbulence intensities across large multi-frame PIV data with O(1) memory.

    Accepts:
    - An ``xr.Dataset`` (eager or lazy Dask-backed)
    - A directory path (``pathlib.Path`` or ``str``) containing per-frame PIV files
    - A Zarr store path
    - A Sequence/list of file paths or Datasets

    Uses the online Welford accumulation algorithm across time 't', holding only 2D grid
    arrays in memory.

    Parameters
    ----------
    source : xr.Dataset, Path, str, or Sequence[Path | str]
        PIV data source.
    pattern : str
        Glob pattern when source is a directory (default '*').
    ext : str, optional
        File extension filter (e.g. '.txt', '.vec', '.vc7').
    name_mean : str
        Prefix for mean velocity variables (default 'mean').
    name_prime : str
        Suffix for fluctuating velocity variables (default 'prime').

    Returns
    -------
    xr.Dataset
        Single 2D grid dataset containing:
        - ``u_mean``, ``v_mean``
        - ``uu_prime``, ``vv_prime``, ``uv_prime``
        - ``tke``
        - ``intensity_u``, ``intensity_v``
    """
    coords = None
    attrs = {}
    u_mean: Optional[np.ndarray] = None
    v_mean: Optional[np.ndarray] = None
    M2_xx: Optional[np.ndarray] = None
    M2_yy: Optional[np.ndarray] = None
    M2_xy: Optional[np.ndarray] = None
    n_frames = 0

    def _process_frame(u_k: np.ndarray, v_k: np.ndarray, k: int):
        nonlocal u_mean, v_mean, M2_xx, M2_yy, M2_xy, n_frames
        count = k + 1
        n_frames = count
        if u_mean is None:
            u_mean = np.zeros_like(u_k, dtype=float)
            v_mean = np.zeros_like(v_k, dtype=float)
            M2_xx = np.zeros_like(u_k, dtype=float)
            M2_yy = np.zeros_like(v_k, dtype=float)
            M2_xy = np.zeros_like(u_k, dtype=float)

        delta_u = u_k - u_mean
        delta_v = v_k - v_mean

        u_mean += delta_u / count
        v_mean += delta_v / count

        M2_xx += delta_u * (u_k - u_mean)
        M2_yy += delta_v * (v_k - v_mean)
        M2_xy += delta_u * (v_k - v_mean)

    if isinstance(source, xr.Dataset):
        has_t = "t" in source.dims and source.sizes["t"] > 1
        n_t = source.sizes["t"] if has_t else 1
        coords = {"y": source["y"], "x": source["x"]}
        attrs = source.attrs.copy()

        for k in range(n_t):
            u_k = source["u"].isel(t=k).to_numpy().squeeze() if has_t else source["u"].to_numpy().squeeze()
            v_k = source["v"].isel(t=k).to_numpy().squeeze() if has_t else source["v"].to_numpy().squeeze()
            _process_frame(u_k, v_k, k)

    elif isinstance(source, (str, pathlib.Path)):
        p = _to_path(source)
        if p.is_dir() and (p / ".zmetadata").exists() or p.name.endswith(".zarr"):
            # Zarr store
            ds_lazy = read_directory_lazy(p)
            return stream_statistics(ds_lazy, name_mean=name_mean, name_prime=name_prime)
        elif p.is_dir():
            # Directory of files
            glob_pattern = pattern
            if ext is not None and not glob_pattern.endswith(ext):
                glob_pattern = f"{pattern}{ext}"
            files = sorted(p.glob(glob_pattern))
            if not files:
                raise IOError(f"No matching PIV files found in {p}")
            for k, fp in enumerate(files):
                frame_ds = read_piv(fp, frame=k)
                if coords is None:
                    coords = {"y": frame_ds["y"], "x": frame_ds["x"]}
                    attrs = frame_ds.attrs.copy()
                u_k = frame_ds["u"].to_numpy().squeeze()
                v_k = frame_ds["v"].to_numpy().squeeze()
                _process_frame(u_k, v_k, k)
        else:
            frame_ds = read_piv(p)
            return stream_statistics(frame_ds, name_mean=name_mean, name_prime=name_prime)

    elif isinstance(source, Sequence):
        for k, item in enumerate(source):
            if isinstance(item, xr.Dataset):
                frame_ds = item
            else:
                frame_ds = read_piv(item, frame=k)
            if coords is None:
                coords = {"y": frame_ds["y"], "x": frame_ds["x"]}
                attrs = frame_ds.attrs.copy()
            u_k = frame_ds["u"].to_numpy().squeeze()
            v_k = frame_ds["v"].to_numpy().squeeze()
            _process_frame(u_k, v_k, k)
    else:
        raise ValueError(f"Unsupported source type: {type(source)}")

    if n_frames == 0 or u_mean is None or v_mean is None:
        raise ValueError("No frames processed during stream statistics accumulation.")

    uu_prime = M2_xx / n_frames
    vv_prime = M2_yy / n_frames
    uv_prime = -M2_xy / n_frames
    tke = 0.5 * (uu_prime + vv_prime)

    u_mag_mean = np.sqrt(u_mean**2 + v_mean**2)
    eps_denom = 1e-12
    intensity_u = np.sqrt(uu_prime) / np.maximum(u_mag_mean, eps_denom)
    intensity_v = np.sqrt(vv_prime) / np.maximum(u_mag_mean, eps_denom)

    out = xr.Dataset(
        data_vars={
            f"u_{name_mean}": (("y", "x"), u_mean),
            f"v_{name_mean}": (("y", "x"), v_mean),
            "uu_prime": (("y", "x"), uu_prime),
            "vv_prime": (("y", "x"), vv_prime),
            "uv_prime": (("y", "x"), uv_prime),
            "tke": (("y", "x"), tke),
            "intensity_u": (("y", "x"), intensity_u),
            "intensity_v": (("y", "x"), intensity_v),
        },
        coords=coords,
        attrs=attrs,
    )
    out[f"u_{name_mean}"].attrs["units"] = "m/s"
    out[f"v_{name_mean}"].attrs["units"] = "m/s"
    out["uu_prime"].attrs["units"] = "(m/s)^2"
    out["vv_prime"].attrs["units"] = "(m/s)^2"
    out["uv_prime"].attrs["units"] = "(m/s)^2"
    out["tke"].attrs["units"] = "(m/s)^2"
    out["intensity_u"].attrs["units"] = "1"
    out["intensity_v"].attrs["units"] = "1"

    return out

unsorted_unique(arr)

Return unique values preserving first-seen order.

Source code in pivpy/io.py
55
56
57
58
59
def unsorted_unique(arr: ArrayLike) -> tuple[np.ndarray, np.ndarray]:
    """Return unique values preserving first-seen order."""
    arr1, indices = np.unique(arr, return_index=True)
    order = indices.argsort()
    return arr1[order], indices[order]

vec2mat(f, filename, key='v', squeeze=True)

Export a vector/scalar dataset to a MATLAB .mat file (PIVMAT-compatible helper).

This is a pragmatic Python equivalent of PIVMAT's vec2mat.

Parameters:

Name Type Description Default
f Dataset

Dataset containing coords x, y and variables u,v or w.

required
filename str

Output path. If it does not end with .mat it will be appended.

required
key str

Top-level MATLAB variable name.

'v'
squeeze bool

If True, singleton dimensions are removed in the saved arrays.

True

Returns:

Type Description
str

The written filename.

Source code in pivpy/io.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def vec2mat(
    f: xr.Dataset,
    filename: str,
    key: str = "v",
    squeeze: bool = True,
) -> str:
    """Export a vector/scalar dataset to a MATLAB ``.mat`` file (PIVMAT-compatible helper).

    This is a pragmatic Python equivalent of PIVMAT's ``vec2mat``.

    Parameters
    ----------
    f:
        Dataset containing coords ``x``, ``y`` and variables ``u,v`` or ``w``.
    filename:
        Output path. If it does not end with ``.mat`` it will be appended.
    key:
        Top-level MATLAB variable name.
    squeeze:
        If True, singleton dimensions are removed in the saved arrays.

    Returns
    -------
    str
        The written filename.
    """

    if _sp_savemat is None:
        raise ImportError("vec2mat requires SciPy (scipy.io.savemat)")

    outname = filename if filename.lower().endswith(".mat") else f"{filename}.mat"

    mdict: dict[str, object] = {
        "x": np.asarray(f["x"].values),
        "y": np.asarray(f["y"].values),
    }
    if "t" in f.coords:
        mdict["t"] = np.asarray(f["t"].values)

    if "u" in f.data_vars and "v" in f.data_vars:
        mdict["u"] = np.asarray(f["u"].values)
        mdict["v"] = np.asarray(f["v"].values)
    elif "w" in f.data_vars:
        mdict["w"] = np.asarray(f["w"].values)
    else:
        raise ValueError("vec2mat expects variables (u,v) for vector fields or (w) for scalar fields")

    if "chc" in f.data_vars:
        mdict["chc"] = np.asarray(f["chc"].values)

    if squeeze:
        for k, v in list(mdict.items()):
            if isinstance(v, np.ndarray):
                mdict[k] = np.squeeze(v)

    _sp_savemat(outname, {key: mdict}, do_compression=True)
    return outname

vortex(n=128, r0=10.0, vorticity=1.0, mode='burgers', diver=None)

Generate a centered vortex field (PIVMAT-compatible).

Port of PIVMAT's vortex.m.

Returns an xarray.Dataset with variables u and v.

Source code in pivpy/io.py
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
def vortex(
    n: int = 128,
    r0: float = 10.0,
    vorticity: float = 1.0,
    mode: str = "burgers",
    diver: float | None = None,
) -> xr.Dataset:
    """Generate a centered vortex field (PIVMAT-compatible).

    Port of PIVMAT's ``vortex.m``.

    Returns an xarray.Dataset with variables ``u`` and ``v``.
    """

    n = int(n)
    if diver is None:
        diver = float(vorticity)

    mid = n / 2.0 + 1.0
    omega = float(vorticity) / (2.0 * 1000.0)  # m/s/mm
    gamma = float(diver) / (2.0 * 1000.0)  # m/s/mm

    i = np.arange(1, n + 1, dtype=float)
    j = np.arange(1, n + 1, dtype=float)
    ii, jj = np.meshgrid(i, j, indexing="ij")
    dx = ii - mid
    dy = jj - mid
    radius = np.sqrt(dx * dx + dy * dy)

    u = np.zeros((n, n), dtype=float)
    v = np.zeros((n, n), dtype=float)

    mode_l = str(mode).lower()
    if "rankine" in mode_l:
        inside = radius <= float(r0)
        # solid body inside
        u[inside] = omega * dy[inside]
        v[inside] = -omega * dx[inside]
        # irrotational outside
        outside = ~inside
        r2 = np.where(outside, radius * radius, 1.0)
        u[outside] = omega * float(r0) ** 2 * dy[outside] / r2[outside]
        v[outside] = -omega * float(r0) ** 2 * dx[outside] / r2[outside]
    elif "burgers" in mode_l:
        safe_r2 = np.where(radius == 0, np.inf, radius * radius)
        factor = float(r0) ** 2 / safe_r2 * (1.0 - np.exp(-((radius / float(r0)) ** 2)))
        u = omega * factor * dy
        v = -omega * factor * dx
        if gamma != 0.0:
            u = u + gamma * factor * dx
            v = v + gamma * factor * dy
    else:
        raise ValueError("mode must contain 'burgers' or 'rankine'")

    # Avoid a "false" zero (PIVMAT behavior).
    u = u + np.max(np.abs(u)) * 1e-10
    v = v + np.max(np.abs(v)) * 1e-10

    x = np.arange(0, n, dtype=float)
    y = np.arange(0, n, dtype=float)
    x2d, y2d = np.meshgrid(x, y)
    ds = from_arrays(x2d, y2d, u.T, v.T, mask=np.ones((n, n), dtype=float), frame=0)
    ds["x"].attrs["units"] = "mm"
    ds["y"].attrs["units"] = "mm"
    ds["u"].attrs["units"] = "m/s"
    ds["v"].attrs["units"] = "m/s"
    ds.attrs["name"] = "Vortex"
    ds.attrs["setname"] = "-"
    ds.attrs["history"] = ["vortex"]
    return ds

pivpy.compute_funcs

bwfilter2d(arr2, filtsize, order)

2D Butterworth filter in Fourier space (PIVMAT-inspired).

Parameters:

Name Type Description Default
arr2 ndarray

2D array.

required
filtsize float

Cutoff size in grid units. If 0, returns input.

required
order float

Butterworth order. Positive -> low-pass. Negative -> high-pass.

required
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)).

Source code in pivpy/compute_funcs.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def bwfilter2d(arr2: np.ndarray, filtsize: float, order: float) -> np.ndarray:
    """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)).
    """

    a = np.asarray(arr2, dtype=float)
    if a.ndim != 2:
        raise ValueError("bwfilter2d expects a 2D array")

    fs = float(filtsize)
    if fs == 0.0:
        return a

    ny, nx = a.shape
    # PIVMAT behavior: if odd, discard last row/col.
    if nx % 2 == 1:
        a = a[:, :-1]
        nx -= 1
    if ny % 2 == 1:
        a = a[:-1, :]
        ny -= 1

    n = float(min(nx, ny))
    kc = n / fs
    if not np.isfinite(kc) or kc == 0.0:
        return a

    # Integer-like wavenumbers on the shifted FFT grid: [-N/2 .. N/2-1]
    kx = np.fft.fftshift(np.fft.fftfreq(nx) * nx)
    ky = np.fft.fftshift(np.fft.fftfreq(ny) * ny)
    KX, KY = np.meshgrid(kx, ky)
    k = np.sqrt(KX * KX + KY * KY)

    p = float(order) / 2.0
    with np.errstate(divide="ignore", invalid="ignore", over="ignore"):
        powterm = np.power(k / kc, p)
        T = 1.0 / (1.0 + powterm)

    # Fix the zero-mode explicitly for numerical stability.
    if order < 0:
        T[k == 0] = 0.0
    else:
        T[k == 0] = 1.0

    sp = np.fft.fftshift(np.fft.fft2(a))
    out = np.fft.ifft2(np.fft.ifftshift(sp * T)).real
    return out

clean(ds, method='normalized_median', threshold=2.0, epsilon=0.1, inpaint_method=0, radius=1)

Detects spurious velocity outliers and inpaints missing/flagged vectors.

Parameters:

Name Type Description Default
ds Dataset

PIV velocity dataset.

required
method str

Outlier detection method: 'normalized_median' (default) or 'mask' (existing chc <= 0 or NaNs).

'normalized_median'
threshold float

Outlier threshold for normalized median test (default 2.0).

2.0
epsilon float

Noise floor parameter for normalized median test (default 0.1).

0.1
inpaint_method int or str

Inpainting scheme passed to inpaint_missing_2d (0=harmonic/Laplacian, 1=nearest, 2=linear).

0
radius int

Stencil radius for median test (default 1).

1

Returns:

Type Description
Dataset

Cleaned dataset with outliers replaced by smooth interpolation.

Source code in pivpy/compute_funcs.py
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
def clean(
    ds: xr.Dataset,
    method: str = "normalized_median",
    threshold: float = 2.0,
    epsilon: float = 0.1,
    inpaint_method: int | str = 0,
    radius: int = 1,
) -> xr.Dataset:
    """Detects spurious velocity outliers and inpaints missing/flagged vectors.

    Parameters
    ----------
    ds : xr.Dataset
        PIV velocity dataset.
    method : str
        Outlier detection method: 'normalized_median' (default) or 'mask' (existing chc <= 0 or NaNs).
    threshold : float
        Outlier threshold for normalized median test (default 2.0).
    epsilon : float
        Noise floor parameter for normalized median test (default 0.1).
    inpaint_method : int or str
        Inpainting scheme passed to `inpaint_missing_2d` (0=harmonic/Laplacian, 1=nearest, 2=linear).
    radius : int
        Stencil radius for median test (default 1).

    Returns
    -------
    xr.Dataset
        Cleaned dataset with outliers replaced by smooth interpolation.
    """
    m_str = str(method).lower()
    if m_str in ("normalized_median", "nmt", "median"):
        flagged_ds = normalized_median_test(ds, radius=radius, threshold=threshold, epsilon=epsilon)
    else:
        flagged_ds = ds.copy(deep=True)

    method_int = 0
    if isinstance(inpaint_method, str):
        inpaint_s = inpaint_method.lower()
        if inpaint_s.startswith("near"):
            method_int = 1
        elif inpaint_s.startswith("lin"):
            method_int = 2
        else:
            method_int = 0
    else:
        method_int = int(inpaint_method)

    out = flagged_ds.copy(deep=True)
    has_t = "t" in out.dims

    def _inpaint_slice(u_2d: np.ndarray, v_2d: np.ndarray, chc_2d: np.ndarray | None) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        u_corrupt = u_2d.astype(float, copy=True)
        v_corrupt = v_2d.astype(float, copy=True)
        if chc_2d is not None:
            bad = (chc_2d <= 0) | ~np.isfinite(u_corrupt) | ~np.isfinite(v_corrupt)
        else:
            bad = ~np.isfinite(u_corrupt) | ~np.isfinite(v_corrupt)

        u_corrupt[bad] = np.nan
        v_corrupt[bad] = np.nan

        u_clean = inpaint_missing_2d(u_corrupt, method=method_int, missing="nan")
        v_clean = inpaint_missing_2d(v_corrupt, method=method_int, missing="nan")

        chc_clean = np.ones_like(u_2d, dtype=float)
        return u_clean, v_clean, chc_clean

    if has_t:
        n_frames = out.sizes["t"]
        for i in range(n_frames):
            u_i = out["u"].isel(t=i).to_numpy()
            v_i = out["v"].isel(t=i).to_numpy()
            chc_i = out["chc"].isel(t=i).to_numpy() if "chc" in out.data_vars else None
            u_c, v_c, chc_c = _inpaint_slice(u_i, v_i, chc_i)
            out["u"].values[:, :, i] = u_c
            out["v"].values[:, :, i] = v_c
            if "chc" in out.data_vars:
                out["chc"].values[:, :, i] = chc_c
    else:
        u_2d = out["u"].to_numpy()
        v_2d = out["v"].to_numpy()
        chc_2d = out["chc"].to_numpy() if "chc" in out.data_vars else None
        u_c, v_c, chc_c = _inpaint_slice(u_2d, v_2d, chc_2d)
        out["u"].values = u_c
        out["v"].values = v_c
        if "chc" in out.data_vars:
            out["chc"].values = chc_c

    return out

corrf(x, dim='x', *, normalize=False, nan_as_zero=True, nowarning=False, r_dim='r')

Spatial correlation function and integral scales (PIVMAT-inspired).

This is a Python/xarray equivalent of PIVMAT's corrf.m for 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:

Name Type Description Default
x DataArray

Scalar field as an xarray.DataArray (typically with dims including 'x' and 'y', and optionally 't').

required
dim int | str

Direction of separation: 'x'/'y' (recommended) or MATLAB-like 1/2.

'x'
normalize bool

If True, normalize the correlation so that f(0)=1.

False
nan_as_zero bool

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.)

True
nowarning bool

If True, suppress warnings when crossover radii are undefined.

False
r_dim str

Name of the separation-length coordinate in the returned Dataset.

'r'

Returns:

Type Description
Dataset

Dataset with 1D variable f over coordinate r and scalar variables isinf, r0, is0, r1, is1, r2, is2, r5, is5.

Source code in pivpy/compute_funcs.py
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
def corrf(
    x: xr.DataArray,
    dim: int | str = "x",
    *,
    normalize: bool = False,
    nan_as_zero: bool = True,
    nowarning: bool = False,
    r_dim: str = "r",
) -> xr.Dataset:
    """Spatial correlation function and integral scales (PIVMAT-inspired).

    This is a Python/xarray equivalent of PIVMAT's ``corrf.m`` for 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-like
        ``1``/``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
    -------
    xarray.Dataset
        Dataset with 1D variable ``f`` over coordinate ``r`` and scalar
        variables ``isinf, r0, is0, r1, is1, r2, is2, r5, is5``.
    """

    if not isinstance(x, xr.DataArray):
        raise TypeError("corrf expects an xarray.DataArray")

    # Resolve the dimension name for coordinate spacing.
    if isinstance(dim, str):
        dim_name = dim
        if dim_name in ("x", "y") and dim_name not in x.dims:
            # Allow 'x'/'y' mapping only if present; otherwise let corrm raise.
            pass
    else:
        if dim not in (1, 2):
            raise ValueError("dim must be 'x', 'y', 1 or 2")
        if x.ndim < dim:
            raise ValueError(f"Input has only {x.ndim} dims; cannot use dim={dim}.")
        dim_name = x.dims[dim - 1]

    c = corrm(x, dim=dim, half=True, nan_as_zero=nan_as_zero, lag_dim="lag")

    # Average over all dimensions except lag.
    mean_dims = [d for d in c.dims if d != "lag"]
    f_da = c.mean(dim=mean_dims, skipna=True)

    # Separation length: lag index (0..N-1) times grid spacing.
    if dim_name in x.coords and x.sizes.get(dim_name, 0) >= 2:
        coord = x[dim_name].values
        diffs = np.diff(coord.astype(float))
        dr = float(np.abs(diffs[0])) if diffs.size else 1.0
        if diffs.size and not np.allclose(diffs, diffs[0]):
            if not nowarning:
                warnings.warn(
                    f"Non-uniform spacing detected along '{dim_name}'; using first step for dr.",
                    UserWarning,
                    stacklevel=2,
                )
    else:
        dr = 1.0

    lag = f_da["lag"].values.astype(float)
    r = lag * dr
    f = f_da.values.astype(float)

    if normalize and f.size:
        if f[0] != 0.0:
            f = f / float(f[0])

    scales = _corrf_scales(r, f, nowarning=nowarning)

    out = xr.Dataset(coords={r_dim: r})
    out["f"] = (r_dim, f)
    for k, v in scales.items():
        out[k] = xr.DataArray(v)

    out.attrs["dim"] = str(dim)
    out.attrs["dr"] = float(dr)
    out.attrs["normalized"] = bool(normalize)
    out.attrs["variable"] = str(x.name) if x.name is not None else ""

    return out

corrm(x, dim=1, *, half=False, nan_as_zero=True, lag_dim='lag')

Matrix correlation along one dimension (PIVMAT-compatible).

For a 2D matrix shaped (M, N): - dim=1 correlates each column vector -> output shape (2M-1, N) - dim=2 correlates each row vector -> output shape (M, 2N-1)

For xarray objects, dim may be a dimension name and the function generalizes to N-D by correlating along that dimension.

Source code in pivpy/compute_funcs.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
def corrm(
    x: xr.DataArray | np.ndarray,
    dim: int | str = 1,
    *,
    half: bool = False,
    nan_as_zero: bool = True,
    lag_dim: str = "lag",
) -> xr.DataArray | np.ndarray:
    """Matrix correlation along one dimension (PIVMAT-compatible).

    For a 2D matrix shaped (M, N):
    - ``dim=1`` correlates each column vector -> output shape (2*M-1, N)
    - ``dim=2`` correlates each row vector    -> output shape (M, 2*N-1)

    For xarray objects, ``dim`` may be a dimension name and the function
    generalizes to N-D by correlating along that dimension.
    """

    if isinstance(x, xr.DataArray):
        if isinstance(dim, int):
            if dim not in (1, 2):
                raise ValueError("For xarray inputs, dim as int must be 1 or 2.")
            if x.ndim < dim:
                raise ValueError(f"Input has only {x.ndim} dims; cannot use dim={dim}.")
            dim_name = x.dims[dim - 1]
        else:
            dim_name = dim
            if dim_name not in x.dims:
                raise ValueError(f"Dimension '{dim_name}' not found in DataArray dims {x.dims}.")

        n = int(x.sizes[dim_name])
        if n == 0:
            out = xr.full_like(x.isel({dim_name: slice(0, 0)}), np.nan)
            return out

        def _corrx_1d(vec: np.ndarray) -> np.ndarray:
            return corrx(vec, half=False, nan_as_zero=nan_as_zero)

        out = xr.apply_ufunc(
            _corrx_1d,
            x,
            input_core_dims=[[dim_name]],
            output_core_dims=[[lag_dim]],
            vectorize=True,
            dask="parallelized",
            output_dtypes=[float],
        )

        # Put the lag dimension where the original dim was.
        dim_index = list(x.dims).index(dim_name)
        desired_order = list(x.dims)
        desired_order[dim_index] = lag_dim
        out = out.transpose(*desired_order)

        lag = np.arange(-(n - 1), n, dtype=int)
        out = out.assign_coords({lag_dim: lag})

        if half:
            out = out.sel({lag_dim: slice(0, None)})

        return out

    # NumPy path (expects 2D for PIVMAT-like behavior)
    arr = np.asarray(x)
    if arr.ndim != 2:
        raise ValueError("NumPy corrm expects a 2D array; for N-D use xarray DataArray.")

    m, n = arr.shape
    if dim == 2:
        c = np.zeros((m, 2 * n - 1), dtype=float)
        for i in range(m):
            c[i, :] = corrx(arr[i, :], half=False, nan_as_zero=nan_as_zero)
        if half:
            c = c[:, (n - 1) :]
        return c
    if dim == 1:
        c = np.zeros((2 * m - 1, n), dtype=float)
        for j in range(n):
            c[:, j] = corrx(arr[:, j], half=False, nan_as_zero=nan_as_zero)
        if half:
            c = c[(m - 1) :, :]
        return c

    raise ValueError("dim must be 1 or 2 (NumPy inputs) or a valid xarray dim name.")

corrx(x, y=None, *, half=False, nan_as_zero=True)

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:

Name Type Description Default
x ndarray

1D vectors. If y is None, autocorrelation is computed.

required
y ndarray

1D vectors. If y is None, autocorrelation is computed.

required
half bool

If True, return only non-negative lags (including zero-lag).

False
nan_as_zero bool

If True, NaNs are treated as missing data and replaced by 0.

True

Returns:

Type Description
ndarray

Correlation vector of length 2*N-1 (or N if half=True).

Source code in pivpy/compute_funcs.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
def corrx(
    x: np.ndarray,
    y: np.ndarray | None = None,
    *,
    half: bool = False,
    nan_as_zero: bool = True,
) -> np.ndarray:
    """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, y:
        1D vectors. If ``y`` is 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
    -------
    numpy.ndarray
        Correlation vector of length ``2*N-1`` (or ``N`` if ``half=True``).
    """

    x_arr = np.asarray(x)
    if x_arr.ndim != 1:
        x_arr = x_arr.reshape(-1)

    y_arr = x_arr if y is None else np.asarray(y)
    if y_arr.ndim != 1:
        y_arr = y_arr.reshape(-1)

    if x_arr.shape[0] != y_arr.shape[0]:
        raise ValueError("Vectors lengths must agree.")

    x_arr = x_arr.astype(float, copy=False)
    y_arr = y_arr.astype(float, copy=False)
    if nan_as_zero:
        x_arr = np.nan_to_num(x_arr, nan=0.0)
        y_arr = np.nan_to_num(y_arr, nan=0.0)

    n = int(x_arr.shape[0])
    if n == 0:
        return np.array([], dtype=float)

    y_pad = np.concatenate([np.zeros(n - 1, dtype=float), y_arr, np.zeros(n - 1, dtype=float)])

    c = np.zeros(2 * n - 1, dtype=float)
    # MATLAB: for i=(-n+1):(n-1)
    # Python: i in [-(n-1), ..., (n-1)]
    for i in range(-(n - 1), n):
        start = (n - i - 1)
        stop = (2 * n - i - 1)
        segment = y_pad[start:stop]
        prod = x_arr * segment
        weight = int(np.count_nonzero(prod))
        if weight == 0:
            weight = 1
        c[(n - 1) + i] = float(np.sum(prod) / weight)

    if half:
        c = c[(n - 1) :]

    return c

dissipation(ds, method='direct', nu=1.5e-05, name='w')

Estimates turbulent kinetic energy dissipation rate epsilon.

Surrogate estimation methods:

  • 'direct': In-plane 2D surrogate with continuity substitution for out-of-plane gradients:

.. math::

  \varepsilon = \nu \left[ 2 \overline{\left(\frac{\partial u'}{\partial x}\right)^2} + 2 \overline{\left(\frac{\partial v'}{\partial y}\right)^2} + 2 \overline{\left(\frac{\partial u'}{\partial x} + \frac{\partial v'}{\partial y}\right)^2} + \overline{\left(\frac{\partial u'}{\partial y} + \frac{\partial v'}{\partial x}\right)^2} \right]
  • 'isotropic': Homogeneous isotropic turbulence surrogate:

.. math::

  \varepsilon = 15 \nu \overline{\left(\frac{\partial u'}{\partial x}\right)^2}
  • 'smagorinsky': Subgrid-scale eddy viscosity model for coarse PIV grids:

.. math::

  \varepsilon_{\text{sgs}} = (C_s \Delta)^2 \left(2 \bar{S}_{ij} \bar{S}_{ij}\right)^{3/2}

Parameters:

Name Type Description Default
ds Dataset

PIV velocity dataset.

required
method ('direct', 'isotropic', 'smagorinsky')

Dissipation rate estimation model (default 'direct').

'direct'
nu float

Kinematic viscosity in m^2/s (default 1.5e-5 for air).

1.5e-05
name str

Name for output scalar variable (default 'w').

'w'

Returns:

Type Description
Dataset

Dataset with computed dissipation rate field.

Source code in pivpy/compute_funcs.py
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
def dissipation(
    ds: xr.Dataset,
    method: str = "direct",
    nu: float = 1.5e-5,
    name: str = "w",
) -> xr.Dataset:
    r"""Estimates turbulent kinetic energy dissipation rate epsilon.

    Surrogate estimation methods:

    - ``'direct'``: In-plane 2D surrogate with continuity substitution for out-of-plane gradients:

      .. math::

          \varepsilon = \nu \left[ 2 \overline{\left(\frac{\partial u'}{\partial x}\right)^2} + 2 \overline{\left(\frac{\partial v'}{\partial y}\right)^2} + 2 \overline{\left(\frac{\partial u'}{\partial x} + \frac{\partial v'}{\partial y}\right)^2} + \overline{\left(\frac{\partial u'}{\partial y} + \frac{\partial v'}{\partial x}\right)^2} \right]

    - ``'isotropic'``: Homogeneous isotropic turbulence surrogate:

      .. math::

          \varepsilon = 15 \nu \overline{\left(\frac{\partial u'}{\partial x}\right)^2}

    - ``'smagorinsky'``: Subgrid-scale eddy viscosity model for coarse PIV grids:

      .. math::

          \varepsilon_{\text{sgs}} = (C_s \Delta)^2 \left(2 \bar{S}_{ij} \bar{S}_{ij}\right)^{3/2}

    Parameters
    ----------
    ds : xr.Dataset
        PIV velocity dataset.
    method : {'direct', 'isotropic', 'smagorinsky'}
        Dissipation rate estimation model (default 'direct').
    nu : float
        Kinematic viscosity in m^2/s (default 1.5e-5 for air).
    name : str
        Name for output scalar variable (default 'w').

    Returns
    -------
    xr.Dataset
        Dataset with computed dissipation rate field.
    """
    m = str(method).lower()
    has_t = "t" in ds.dims and ds.sizes["t"] > 1

    u = ds["u"] - ds["u"].mean(dim="t") if has_t else ds["u"] - ds["u"].mean()
    v = ds["v"] - ds["v"].mean(dim="t") if has_t else ds["v"] - ds["v"].mean()

    du_dx = u.differentiate("x")
    du_dy = u.differentiate("y")
    dv_dx = v.differentiate("x")
    dv_dy = v.differentiate("y")

    if m.startswith("iso"):
        eps = 15.0 * nu * (du_dx**2)
    elif m.startswith("smag"):
        dx = float(np.mean(np.diff(ds["x"].values))) if ds.sizes["x"] > 1 else 1.0
        dy = float(np.mean(np.diff(ds["y"].values))) if ds.sizes["y"] > 1 else 1.0
        delta = np.sqrt(dx * dy)
        Cs = 0.17
        s_xx = du_dx
        s_yy = dv_dy
        s_xy = 0.5 * (du_dy + dv_dx)
        S_mag = np.sqrt(2.0 * (s_xx**2 + s_yy**2 + 2.0 * s_xy**2))
        eps = (Cs * delta) ** 2 * (S_mag**3)
    else:  # 'direct' 2D surrogate
        term_xx = 2.0 * (du_dx**2)
        term_yy = 2.0 * (dv_dy**2)
        term_cont = 2.0 * ((du_dx + dv_dy)**2)
        term_cross = (du_dy + dv_dx)**2
        eps = nu * (term_xx + term_yy + term_cont + term_cross)

    if has_t:
        eps_field = eps.mean(dim="t")
    else:
        eps_field = eps

    out = ds.copy(deep=False)
    warn_if_overwriting_scalar(out, name)
    out[name] = eps_field
    out[name].attrs["units"] = "m^2/s^3"
    out[name].attrs["standard_name"] = f"turbulent_dissipation_rate_{method}"

    return out

energy_spectrum(ds, window='hann', detrend=True, radial=True)

Computes 2D and radial wavenumber energy spectra from velocity fields.

Calculates the 2D energy spectrum:

.. math::

E_{2D}(k_x, k_y) = \frac{1}{2} \left( |\hat{u}(k_x, k_y)|^2 + |\hat{v}(k_x, k_y)|^2 \right)

and the azimuthally integrated radial energy spectrum :math:E(k) such that:

.. math::

\int E(k)\,dk = \text{TKE}

Parameters:

Name Type Description Default
ds Dataset

PIV velocity dataset.

required
window ('hann', 'hamming', 'boxcar', 'none')

Windowing apodization function (default 'hann').

'hann'
detrend bool

If True, removes the spatial mean velocity before Fourier transform.

True
radial bool

If True, includes azimuthally integrated 1D radial spectrum E(k).

True

Returns:

Type Description
Dataset

Dataset with 2D spectrum E2D(ky, kx), 1D spectra E_kx(kx), E_ky(ky), and optionally radial spectrum E_radial(k).

Source code in pivpy/compute_funcs.py
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
def energy_spectrum(
    ds: xr.Dataset,
    window: str = "hann",
    detrend: bool = True,
    radial: bool = True,
) -> xr.Dataset:
    r"""Computes 2D and radial wavenumber energy spectra from velocity fields.

    Calculates the 2D energy spectrum:

    .. math::

        E_{2D}(k_x, k_y) = \frac{1}{2} \left( |\hat{u}(k_x, k_y)|^2 + |\hat{v}(k_x, k_y)|^2 \right)

    and the azimuthally integrated radial energy spectrum :math:`E(k)` such that:

    .. math::

        \int E(k)\,dk = \text{TKE}

    Parameters
    ----------
    ds : xr.Dataset
        PIV velocity dataset.
    window : {'hann', 'hamming', 'boxcar', 'none'}
        Windowing apodization function (default 'hann').
    detrend : bool
        If True, removes the spatial mean velocity before Fourier transform.
    radial : bool
        If True, includes azimuthally integrated 1D radial spectrum E(k).

    Returns
    -------
    xr.Dataset
        Dataset with 2D spectrum ``E2D(ky, kx)``, 1D spectra ``E_kx(kx)``, ``E_ky(ky)``,
        and optionally radial spectrum ``E_radial(k)``.
    """
    x = np.asarray(ds["x"].values, dtype=float)
    y = np.asarray(ds["y"].values, dtype=float)
    nx = len(x)
    ny = len(y)

    dx = float(np.mean(np.diff(x))) if nx > 1 else 1.0
    dy = float(np.mean(np.diff(y))) if ny > 1 else 1.0

    # Build window
    w_name = str(window).lower()
    if w_name.startswith("hann"):
        wx = np.hanning(nx)
        wy = np.hanning(ny)
        W = np.outer(wy, wx)
        w_norm = np.mean(W**2)
    elif w_name.startswith("hamm"):
        wx = np.hamming(nx)
        wy = np.hamming(ny)
        W = np.outer(wy, wx)
        w_norm = np.mean(W**2)
    else:
        W = np.ones((ny, nx))
        w_norm = 1.0

    has_t = "t" in ds.dims and ds.sizes["t"] > 1
    n_frames = ds.sizes["t"] if has_t else 1

    kx = np.fft.fftfreq(nx, d=dx) * 2.0 * np.pi
    ky = np.fft.fftfreq(ny, d=dy) * 2.0 * np.pi

    kx_shift = np.fft.fftshift(kx)
    ky_shift = np.fft.fftshift(ky)

    KX, KY = np.meshgrid(kx_shift, ky_shift)
    K = np.sqrt(KX**2 + KY**2)

    E2d_sum = np.zeros((ny, nx), dtype=float)

    for i in range(n_frames):
        u_slice = ds["u"].isel(t=i).to_numpy().squeeze() if has_t else ds["u"].to_numpy().squeeze()
        v_slice = ds["v"].isel(t=i).to_numpy().squeeze() if has_t else ds["v"].to_numpy().squeeze()

        if detrend:
            u_slice = u_slice - np.nanmean(u_slice)
            v_slice = v_slice - np.nanmean(v_slice)

        u_win = np.nan_to_num(u_slice) * W
        v_win = np.nan_to_num(v_slice) * W

        u_hat = np.fft.fft2(u_win) / (nx * ny)
        v_hat = np.fft.fft2(v_win) / (nx * ny)

        E2d = 0.5 * (np.abs(u_hat)**2 + np.abs(v_hat)**2) / w_norm
        E2d_shift = np.fft.fftshift(E2d)
        E2d_sum += E2d_shift

    E2D_mean = E2d_sum / n_frames

    # 1D slice spectra
    E_kx = np.sum(E2D_mean, axis=0)
    E_ky = np.sum(E2D_mean, axis=1)

    data_vars = {
        "E2D": (("ky", "kx"), E2D_mean),
        "E_kx": (("kx",), E_kx),
        "E_ky": (("ky",), E_ky),
    }
    coords = {"kx": kx_shift, "ky": ky_shift}

    if radial:
        dk = min(2.0 * np.pi / (nx * dx), 2.0 * np.pi / (ny * dy))
        k_max = np.max(K)
        k_bins = np.arange(0, k_max + dk, dk)
        k_centers = 0.5 * (k_bins[:-1] + k_bins[1:])
        E_rad = np.zeros(len(k_centers), dtype=float)

        for b in range(len(k_centers)):
            mask = (K >= k_bins[b]) & (K < k_bins[b + 1])
            if np.any(mask):
                E_rad[b] = np.sum(E2D_mean[mask]) / dk

        data_vars["E_radial"] = (("k",), E_rad)
        coords["k"] = k_centers

    out = xr.Dataset(data_vars=data_vars, coords=coords)
    out["E2D"].attrs["units"] = "(m/s)^2 / (rad/m)^2"
    out["E_kx"].attrs["units"] = "(m/s)^2 / (rad/m)"
    out["E_ky"].attrs["units"] = "(m/s)^2 / (rad/m)"
    if radial:
        out["E_radial"].attrs["units"] = "(m/s)^2 / (rad/m)"
        out["E_radial"].attrs["standard_name"] = "radial_energy_spectrum"

    return out

filter2d(arr2, filtsize=1.0, method='gauss', *, mode='valid')

2D spatial filter by normalized convolution (PIVMAT-inspired).

Parameters:

Name Type Description Default
arr2 ArrayLike

2D field to filter.

required
filtsize float

Filter size in mesh units (Gaussian sigma-like scale).

1.0
method str

'gauss', 'flat', or 'igauss' (integrated Gaussian).

'gauss'
mode str

'valid' (default) or 'same'. Matches Matlab conv2 modes.

'valid'
Notes

Missing values are treated as NaN and excluded from the convolution by using a weight-mask normalization.

Source code in pivpy/compute_funcs.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def filter2d(
    arr2: ArrayLike,
    filtsize: float = 1.0,
    method: str = "gauss",
    *,
    mode: str = "valid",
) -> np.ndarray:
    """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.
    """

    a = np.asarray(arr2, dtype=float)
    if a.ndim != 2:
        raise ValueError("filter2d expects a 2D array")

    fs = float(filtsize)
    if fs == 0.0:
        return a

    m = str(method).lower()
    if m.startswith("flat"):
        k = _kernel_flat(fs)
    elif m.startswith("igauss"):
        k = _kernel_gauss(fs, integrated=True)
    else:
        k = _kernel_gauss(fs, integrated=False)

    if _signal_convolve2d is None:  # pragma: no cover
        raise ImportError("filter2d requires scipy.signal.convolve2d")

    finite = np.isfinite(a)
    a0 = np.where(finite, a, 0.0)
    w = finite.astype(float)

    mode_l = str(mode).lower()
    if mode_l not in ("valid", "same"):
        raise ValueError("mode must be 'valid' or 'same'")

    num = _signal_convolve2d(a0, k, mode=mode_l, boundary="fill", fillvalue=0.0)
    den = _signal_convolve2d(w, k, mode=mode_l, boundary="fill", fillvalue=0.0)

    out = np.full_like(num, np.nan, dtype=float)
    good = den > 0
    out[good] = num[good] / den[good]
    return out

filter2d_kernel(filtsize=1.0, method='gauss')

Return the normalized 2D kernel used by :func:filter2d.

Parameters:

Name Type Description Default
filtsize float

Filter size in mesh units.

1.0
method str

'gauss', 'flat', or 'igauss'.

'gauss'
Source code in pivpy/compute_funcs.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def filter2d_kernel(filtsize: float = 1.0, method: str = "gauss") -> np.ndarray:
    """Return the normalized 2D kernel used by :func:`filter2d`.

    Parameters
    ----------
    filtsize:
        Filter size in mesh units.
    method:
        'gauss', 'flat', or 'igauss'.
    """

    m = str(method).lower()
    fs = float(filtsize)
    if m.startswith("flat"):
        return _kernel_flat(fs)
    if m.startswith("igauss"):
        return _kernel_gauss(fs, integrated=True)
    return _kernel_gauss(fs, integrated=False)

gamma1(ds, radius=3, name='gamma1')

Calculates the Gamma1 vortex criterion (normalized angular momentum).

Gamma1 identifies vortex centers where abs(Gamma1) >= 2/pi (~0.6366), reaching +/-1 at ideal vortex cores.

Args: ds (xr.Dataset): Velocity field containing 'u', 'v', 'x', 'y' (and optional 't'). radius (int): Stencil radius in grid points. Defaults to 3. name (str): Variable name for the output field. Defaults to 'gamma1'.

Returns: xr.Dataset: Dataset with new Gamma1 variable.

Source code in pivpy/compute_funcs.py
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
def gamma1(ds: xr.Dataset, radius: int = 3, name: str = "gamma1") -> xr.Dataset:
    """Calculates the Gamma1 vortex criterion (normalized angular momentum).

    Gamma1 identifies vortex centers where abs(Gamma1) >= 2/pi (~0.6366),
    reaching +/-1 at ideal vortex cores.

    Args:
        ds (xr.Dataset): Velocity field containing 'u', 'v', 'x', 'y' (and optional 't').
        radius (int): Stencil radius in grid points. Defaults to 3.
        name (str): Variable name for the output field. Defaults to 'gamma1'.

    Returns:
        xr.Dataset: Dataset with new Gamma1 variable.
    """
    warn_if_overwriting_scalar(ds, name)
    out_arr = _apply_2d_slices(ds, _gamma1_2d, radius=radius)
    out = ds.copy(deep=False)
    dims = ("y", "x", "t") if "t" in ds.dims else ("y", "x")
    out[name] = xr.DataArray(out_arr, dims=dims, coords=ds.coords)
    out[name].attrs["standard_name"] = "Gamma 1"
    out[name].attrs["units"] = "dimensionless"
    out[name].attrs["radius"] = radius
    return out

gamma2(ds, radius=3, name='gamma2')

Calculates the Galilean-invariant Gamma2 vortex identification criterion.

Gamma2 identifies vortex core boundaries where abs(Gamma2) >= 2/pi (~0.6366), remaining invariant under uniform background convection.

Args: ds (xr.Dataset): Velocity field containing 'u', 'v', 'x', 'y' (and optional 't'). radius (int): Stencil radius in grid points. Defaults to 3. name (str): Variable name for the output field. Defaults to 'gamma2'.

Returns: xr.Dataset: Dataset with new Gamma2 variable.

Source code in pivpy/compute_funcs.py
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
def gamma2(ds: xr.Dataset, radius: int = 3, name: str = "gamma2") -> xr.Dataset:
    """Calculates the Galilean-invariant Gamma2 vortex identification criterion.

    Gamma2 identifies vortex core boundaries where abs(Gamma2) >= 2/pi (~0.6366),
    remaining invariant under uniform background convection.

    Args:
        ds (xr.Dataset): Velocity field containing 'u', 'v', 'x', 'y' (and optional 't').
        radius (int): Stencil radius in grid points. Defaults to 3.
        name (str): Variable name for the output field. Defaults to 'gamma2'.

    Returns:
        xr.Dataset: Dataset with new Gamma2 variable.
    """
    warn_if_overwriting_scalar(ds, name)
    out_arr = _apply_2d_slices(ds, _gamma2_2d, radius=radius)
    out = ds.copy(deep=False)
    dims = ("y", "x", "t") if "t" in ds.dims else ("y", "x")
    out[name] = xr.DataArray(out_arr, dims=dims, coords=ds.coords)
    out[name].attrs["standard_name"] = "Gamma 2"
    out[name].attrs["units"] = "dimensionless"
    out[name].attrs["radius"] = radius
    return out

gradient_tensor(ds, return_components=False)

Calculates velocity gradient tensor J, strain-rate tensor S, and principal strains.

Computes: - Normal strain rates: s_xx = du/dx, s_yy = dv/dy - Shear strain rate: s_xy = 0.5 * (du/dy + dv/dx) - Principal strain rates: lambda_1, lambda_2 - Maximum shear strain rate: max_shear = 0.5 * (lambda_1 - lambda_2) - Principal strain angle: strain_angle = 0.5 * atan2(2*s_xy, s_xx - s_yy)

Parameters:

Name Type Description Default
ds Dataset

PIV velocity dataset.

required
return_components bool

If True, returns a new dataset containing only tensor components. If False (default), augments ds with tensor quantities.

False

Returns:

Type Description
Dataset
Source code in pivpy/compute_funcs.py
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
def gradient_tensor(ds: xr.Dataset, return_components: bool = False) -> xr.Dataset:
    """Calculates velocity gradient tensor J, strain-rate tensor S, and principal strains.

    Computes:
    - Normal strain rates: s_xx = du/dx, s_yy = dv/dy
    - Shear strain rate: s_xy = 0.5 * (du/dy + dv/dx)
    - Principal strain rates: lambda_1, lambda_2
    - Maximum shear strain rate: max_shear = 0.5 * (lambda_1 - lambda_2)
    - Principal strain angle: strain_angle = 0.5 * atan2(2*s_xy, s_xx - s_yy)

    Parameters
    ----------
    ds : xr.Dataset
        PIV velocity dataset.
    return_components : bool
        If True, returns a new dataset containing only tensor components.
        If False (default), augments `ds` with tensor quantities.

    Returns
    -------
    xr.Dataset
    """
    dx = float(ds["x"][1] - ds["x"][0]) if len(ds["x"]) > 1 else 1.0
    dy = float(ds["y"][1] - ds["y"][0]) if len(ds["y"]) > 1 else 1.0

    has_t = "t" in ds.dims

    def _calc_2d(u_2d: np.ndarray, v_2d: np.ndarray) -> dict[str, np.ndarray]:
        dudx = np.gradient(u_2d, dx, axis=1)
        dudy = np.gradient(u_2d, dy, axis=0)
        dvdx = np.gradient(v_2d, dx, axis=1)
        dvdy = np.gradient(v_2d, dy, axis=0)

        s_xx = dudx
        s_yy = dvdy
        s_xy = 0.5 * (dudy + dvdx)

        diff = 0.5 * (s_xx - s_yy)
        rad = np.sqrt(diff**2 + s_xy**2)
        mean_s = 0.5 * (s_xx + s_yy)

        lambda_1 = mean_s + rad
        lambda_2 = mean_s - rad
        max_shear = rad
        strain_angle = 0.5 * np.arctan2(2.0 * s_xy, s_xx - s_yy)

        return {
            "s_xx": s_xx,
            "s_yy": s_yy,
            "s_xy": s_xy,
            "lambda_1": lambda_1,
            "lambda_2": lambda_2,
            "max_shear": max_shear,
            "strain_angle": strain_angle,
        }

    dims = ("y", "x", "t") if has_t else ("y", "x")

    if has_t:
        n_frames = ds.sizes["t"]
        ny, nx = ds.sizes["y"], ds.sizes["x"]
        comp_dict = {
            k: np.zeros((ny, nx, n_frames), dtype=float)
            for k in ["s_xx", "s_yy", "s_xy", "lambda_1", "lambda_2", "max_shear", "strain_angle"]
        }
        for i in range(n_frames):
            u_i = ds["u"].isel(t=i).to_numpy()
            v_i = ds["v"].isel(t=i).to_numpy()
            res_i = _calc_2d(u_i, v_i)
            for k, val in res_i.items():
                comp_dict[k][:, :, i] = val
    else:
        u_2d = ds["u"].to_numpy()
        v_2d = ds["v"].to_numpy()
        comp_dict = _calc_2d(u_2d, v_2d)

    out = xr.Dataset(coords=ds.coords) if return_components else ds.copy(deep=False)
    for k, val in comp_dict.items():
        out[k] = xr.DataArray(val, dims=dims, coords=ds.coords)
        out[k].attrs["units"] = "1/delta_t" if k != "strain_angle" else "rad"
        out[k].attrs["standard_name"] = k

    return out

gradientf(scalar)

Gradient of a scalar field (PIVMAT-inspired).

This is a Python/xarray equivalent of PIVMAT's gradientf.m.

Parameters:

Name Type Description Default
scalar DataArray

Scalar field as an xarray.DataArray with dims including x and y. A time dimension (typically t) is allowed and is preserved.

required

Returns:

Type Description
Dataset

Dataset with variables u and v containing the partial derivatives d(scalar)/dx and d(scalar)/dy.

Notes
  • Coordinates are taken from the input DataArray.
  • Units are propagated if both the scalar and coordinate units are available.
Source code in pivpy/compute_funcs.py
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
def gradientf(scalar: xr.DataArray) -> xr.Dataset:
    """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.DataArray`` with dims including ``x`` and ``y``.
        A time dimension (typically ``t``) is allowed and is preserved.

    Returns
    -------
    xarray.Dataset
        Dataset with variables ``u`` and ``v`` containing the partial derivatives
        ``d(scalar)/dx`` and ``d(scalar)/dy``.

    Notes
    -----
    - Coordinates are taken from the input DataArray.
    - Units are propagated if both the scalar and coordinate units are available.
    """

    if not isinstance(scalar, xr.DataArray):
        raise TypeError("gradientf expects an xarray.DataArray")

    if "x" not in scalar.dims or "y" not in scalar.dims:
        raise ValueError("gradientf requires dims 'x' and 'y'")

    gx = scalar.differentiate("x")
    gy = scalar.differentiate("y")

    out = xr.Dataset({"u": gx, "v": gy})

    # Best-effort metadata propagation.
    w_units = str(scalar.attrs.get("units", ""))
    x_units = str(getattr(scalar.coords.get("x", None), "attrs", {}).get("units", ""))
    y_units = str(getattr(scalar.coords.get("y", None), "attrs", {}).get("units", ""))

    name = scalar.name or "scalar"
    out["u"].attrs = dict(gx.attrs)
    out["v"].attrs = dict(gy.attrs)
    out["u"].attrs.setdefault("long_name", f"d/dx({name})")
    out["v"].attrs.setdefault("long_name", f"d/dy({name})")

    if w_units and x_units:
        out["u"].attrs["units"] = f"{w_units}/{x_units}"
    if w_units and y_units:
        out["v"].attrs["units"] = f"{w_units}/{y_units}"

    return out

histf(scalar, bin=None, opt='')

Histogram of a scalar field (PIVMAT-inspired).

This is a Python/xarray equivalent of PIVMAT's histf.m for scalar fields. Values are stacked over all dimensions.

Parameters:

Name Type Description Default
scalar DataArray

Scalar field as an xarray.DataArray.

required
bin ndarray | None

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 t dimension exists) or from the full field otherwise.

None
opt str

Option string. If it contains '0', zero values are included.

''

Returns:

Type Description
Dataset

Dataset with coordinate bin and variable h.

Source code in pivpy/compute_funcs.py
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
def histf(
    scalar: xr.DataArray,
    bin: np.ndarray | None = None,
    opt: str = "",
) -> xr.Dataset:
    """Histogram of a scalar field (PIVMAT-inspired).

    This is a Python/xarray equivalent of PIVMAT's ``histf.m`` for 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 ``t`` dimension exists) or from the full field otherwise.
    opt:
        Option string. If it contains ``'0'``, zero values are included.

    Returns
    -------
    xarray.Dataset
        Dataset with coordinate ``bin`` and variable ``h``.
    """

    if not isinstance(scalar, xr.DataArray):
        raise TypeError("histf expects an xarray.DataArray")

    include_zeros = "0" in str(opt)

    da0 = scalar
    if "t" in scalar.dims:
        try:
            da0 = scalar.isel(t=0)
        except Exception:
            da0 = scalar

    ref = np.asarray(da0.values, dtype=float).ravel()
    ref = ref[np.isfinite(ref)]
    if not include_zeros:
        ref = ref[ref != 0]

    if bin is None:
        if ref.size == 0:
            centers = np.linspace(-1.0, 1.0, 200)
        else:
            mean = float(np.mean(ref))
            std = float(np.std(ref))
            if not np.isfinite(std) or std == 0.0:
                std = 1.0
            if mean < std:
                centers = np.linspace(-20.0 * std, 20.0 * std, 200)
            else:
                centers = np.linspace(mean - 20.0 * std, mean + 20.0 * std, 200)
    else:
        centers = np.asarray(bin, dtype=float).ravel()

    vals = np.asarray(scalar.values, dtype=float).ravel()
    vals = vals[np.isfinite(vals)]
    if not include_zeros:
        vals = vals[vals != 0]

    h = _hist_counts(vals, centers)
    out = xr.Dataset({"h": ("bin", h)}, coords={"bin": centers})
    out["h"].attrs["long_name"] = "histogram"
    return out

inpaint_missing_2d(a2, *, method=0, missing='0nan')

Inpaint missing values in a 2D array (PIVMAT interpf-style).

Missing values are defined as NaNs and/or zeros.

Parameters:

Name Type Description Default
a2 ArrayLike

2D array.

required
method int

Integer method selector (PIVMAT-inspired):

  • 0: Laplacian (harmonic) inpainting via sparse linear solve.
  • 1: Nearest-neighbor fill (fast, robust).
  • 2: Linear interpolation via scipy.interpolate.griddata.
0
missing str

Missing-value definition: - "0nan" (default): treat both 0 and NaN as missing. - "nan": treat only NaNs as missing. - "0": treat only zeros as missing.

'0nan'

Returns:

Type Description
ndarray

Filled array (float).

Source code in pivpy/compute_funcs.py
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
def inpaint_missing_2d(
    a2: ArrayLike,
    *,
    method: int = 0,
    missing: str = "0nan",
) -> np.ndarray:
    """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 via ``scipy.interpolate.griddata``.
    missing:
        Missing-value definition:
        - ``"0nan"`` (default): treat both ``0`` and ``NaN`` as missing.
        - ``"nan"``: treat only NaNs as missing.
        - ``"0"``: treat only zeros as missing.

    Returns
    -------
    numpy.ndarray
        Filled array (float).
    """

    a = np.asarray(a2, dtype=float)
    if a.ndim != 2:
        raise ValueError("inpaint_missing_2d expects a 2D array")

    missing_l = str(missing).lower()
    if missing_l not in {"0nan", "nan", "0"}:
        raise ValueError("missing must be one of: '0nan', 'nan', '0'")

    mask_nan = ~np.isfinite(a)
    mask_zero = a == 0.0
    if missing_l == "0nan":
        miss = mask_nan | mask_zero
    elif missing_l == "nan":
        miss = mask_nan
    else:
        miss = mask_zero

    if not np.any(miss):
        return a

    # If everything is missing, return zeros to match common PIV conventions.
    if np.all(miss):
        return np.zeros_like(a, dtype=float)

    m = int(method)
    if m == 1:
        # Nearest-neighbor fill via distance transform.
        try:
            from scipy.ndimage import distance_transform_edt  # type: ignore
        except Exception as exc:  # pragma: no cover
            raise ImportError("method=1 requires SciPy (scipy.ndimage.distance_transform_edt)") from exc

        valid = ~miss
        # distance_transform_edt expects False for features; compute indices of nearest valid.
        _, (iy, ix) = distance_transform_edt(~valid, return_indices=True)
        out = a.copy()
        out[miss] = out[iy[miss], ix[miss]]
        out[~np.isfinite(out)] = 0.0
        return out

    if m == 2:
        try:
            from scipy.interpolate import griddata  # type: ignore
        except Exception as exc:  # pragma: no cover
            raise ImportError("method=2 requires SciPy (scipy.interpolate.griddata)") from exc

        ny, nx = a.shape
        yy, xx = np.mgrid[0:ny, 0:nx]
        pts = np.column_stack([yy[~miss].ravel(), xx[~miss].ravel()])
        vals = a[~miss].ravel()
        xi = (yy[miss], xx[miss])
        out = a.copy()
        filled = griddata(pts, vals, xi, method="linear")
        # griddata returns NaN outside convex hull; fall back to nearest for those.
        if np.any(~np.isfinite(filled)):
            filled2 = griddata(pts, vals, xi, method="nearest")
            filled = np.where(np.isfinite(filled), filled, filled2)
        out[miss] = filled
        out[~np.isfinite(out)] = 0.0
        return out

    if m != 0:
        raise ValueError("Unsupported method. Supported: 0, 1, 2")

    # Method 0: solve Laplace equation on missing nodes with Dirichlet boundary on known nodes.
    try:
        from scipy.sparse import lil_matrix  # type: ignore
        from scipy.sparse.linalg import spsolve  # type: ignore
    except Exception as exc:  # pragma: no cover
        raise ImportError("method=0 requires SciPy sparse (scipy.sparse, scipy.sparse.linalg)") from exc

    ny, nx = a.shape
    idx = -np.ones((ny, nx), dtype=int)
    unknown_positions = np.argwhere(miss)
    n_unknown = int(unknown_positions.shape[0])
    for k, (iy, ix) in enumerate(unknown_positions):
        idx[iy, ix] = k

    A = lil_matrix((n_unknown, n_unknown), dtype=float)
    b = np.zeros(n_unknown, dtype=float)

    # 4-neighbor Laplacian stencil; adjust at borders.
    for k, (iy, ix) in enumerate(unknown_positions):
        coeff_center = 0.0
        for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            y2 = iy + dy
            x2 = ix + dx
            if y2 < 0 or y2 >= ny or x2 < 0 or x2 >= nx:
                continue
            coeff_center += 1.0
            if miss[y2, x2]:
                A[k, idx[y2, x2]] = -1.0
            else:
                b[k] += float(a[y2, x2])
        A[k, k] = float(coeff_center)

    sol = spsolve(A.tocsr(), b)
    out = a.copy()
    out[miss] = sol
    out[~np.isfinite(out)] = 0.0
    return out

integral_length_scale(ds, component='u', dim='x')

Calculates integral length scale L by integrating spatial autocorrelation R(r).

.. math::

L = \int_0^{r_0} R(r)\,dr

where :math:r_0 is the location of the first zero-crossing (:math:R(r_0) \le 0).

Parameters:

Name Type Description Default
ds Dataset

PIV velocity dataset.

required
component ('u', 'v')

Velocity component (default 'u').

'u'
dim ('x', 'y')

Spatial dimension (default 'x').

'x'

Returns:

Type Description
float

Integral length scale in physical length units.

Source code in pivpy/compute_funcs.py
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
def integral_length_scale(
    ds: xr.Dataset,
    component: str = "u",
    dim: str = "x",
) -> float:
    r"""Calculates integral length scale L by integrating spatial autocorrelation R(r).

    .. math::

        L = \int_0^{r_0} R(r)\,dr

    where :math:`r_0` is the location of the first zero-crossing (:math:`R(r_0) \le 0`).

    Parameters
    ----------
    ds : xr.Dataset
        PIV velocity dataset.
    component : {'u', 'v'}
        Velocity component (default 'u').
    dim : {'x', 'y'}
        Spatial dimension (default 'x').

    Returns
    -------
    float
        Integral length scale in physical length units.
    """
    corr_ds = spatial_correlation(ds, component=component, dim=dim, normalize=True)
    r = corr_ds["r"].values
    R = corr_ds["R"].values

    zero_crossings = np.where(R <= 0.0)[0]
    idx_zero = int(zero_crossings[0]) if len(zero_crossings) > 0 else len(R)

    if idx_zero <= 1:
        return float(r[1] if len(r) > 1 else 0.0)

    # Trapezoidal integration up to first zero crossing
    from scipy.integrate import trapezoid
    L = float(trapezoid(R[:idx_zero], r[:idx_zero]))
    return max(0.0, L)

interpf(data, *, method=0, variables=None, missing='0nan')

Interpolate missing data in a Dataset (PIVMAT interpf port).

Missing data are values equal to 0 and/or NaN (configurable via missing). The interpolation is applied frame-by-frame along t if present.

Parameters:

Name Type Description Default
data Dataset

Input Dataset.

required
method int

See :func:inpaint_missing_2d.

0
variables list[str] | None

Variables to process. Default: ['u','v'] if present, else ['w'] if present, else all data variables.

None
missing str

See :func:inpaint_missing_2d.

'0nan'

Returns:

Type Description
Dataset

New Dataset with missing values filled.

Source code in pivpy/compute_funcs.py
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
def interpf(
    data: xr.Dataset,
    *,
    method: int = 0,
    variables: list[str] | None = None,
    missing: str = "0nan",
) -> xr.Dataset:
    """Interpolate missing data in a Dataset (PIVMAT ``interpf`` port).

    Missing data are values equal to 0 and/or NaN (configurable via ``missing``).
    The interpolation is applied frame-by-frame along ``t`` if present.

    Parameters
    ----------
    data:
        Input Dataset.
    method:
        See :func:`inpaint_missing_2d`.
    variables:
        Variables to process. Default: ['u','v'] if present, else ['w'] if present,
        else all data variables.
    missing:
        See :func:`inpaint_missing_2d`.

    Returns
    -------
    xarray.Dataset
        New Dataset with missing values filled.
    """

    ds = data
    if variables is None:
        if "u" in ds.data_vars and "v" in ds.data_vars:
            variables = ["u", "v"]
        elif "w" in ds.data_vars:
            variables = ["w"]
        else:
            variables = list(ds.data_vars)

    out = ds.copy(deep=True)
    for name in variables:
        if name not in out.data_vars:
            raise KeyError(f"Variable {name} not found in dataset")
        da = out[name]
        if da.ndim < 2:
            continue

        # Determine the 2D core dims (y,x) and keep remaining dims vectorized.
        y_dim, x_dim = da.dims[0], da.dims[1]

        def _core(arr2: np.ndarray) -> np.ndarray:
            return inpaint_missing_2d(arr2, method=method, missing=missing)

        filled = xr.apply_ufunc(
            _core,
            da,
            input_core_dims=[[y_dim, x_dim]],
            output_core_dims=[[y_dim, x_dim]],
            vectorize=True,
            dask="parallelized",
            output_dtypes=[float],
        )
        # apply_ufunc may reorder non-core dims; restore original dim order.
        try:
            filled = filled.transpose(*da.dims)
        except Exception:
            pass
        filled = filled.assign_coords({y_dim: da[y_dim], x_dim: da[x_dim]})
        filled.attrs = dict(ds[name].attrs)
        out[name] = filled

    out.attrs = dict(ds.attrs)
    return out

interpolat_zeros_2d(m, *, fill=False, max_iter=None, nan_as_zero=True)

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. - If fill=True, repeats until no zeros remain (or max_iter).

Parameters:

Name Type Description Default
m DataArray | ndarray

2D array (or xarray DataArray with at least two dims).

required
fill bool

Iterate until no zeros remain.

False
max_iter int | None

Optional hard stop for iterations (recommended when fill=True).

None
nan_as_zero bool

If True, NaNs are treated as 0 (missing/invalid).

True
Source code in pivpy/compute_funcs.py
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
def interpolat_zeros_2d(
    m: xr.DataArray | np.ndarray,
    *,
    fill: bool = False,
    max_iter: int | None = None,
    nan_as_zero: bool = True,
) -> xr.DataArray | np.ndarray:
    """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.
    - If ``fill=True``, repeats until no zeros remain (or ``max_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).
    """

    def _interp_pass(a2: np.ndarray) -> np.ndarray:
        if _nd_convolve is None:
            raise ImportError("scipy is required for interpolat_zeros_2d")

        a2 = a2.astype(float, copy=True)
        if nan_as_zero:
            a2 = np.nan_to_num(a2, nan=0.0)

        zero_mask = a2 == 0
        if not np.any(zero_mask):
            return a2

        kernel = np.array(
            [
                [0.0, 1.0, 0.0],
                [1.0, 0.0, 1.0],
                [0.0, 1.0, 0.0],
            ],
            dtype=float,
        )
        nonzero = (~zero_mask).astype(float)
        neigh_sum = _nd_convolve(a2, kernel, mode="nearest")
        neigh_cnt = _nd_convolve(nonzero, kernel, mode="nearest")

        # Only update zeros where at least one nonzero neighbor exists.
        update = zero_mask & (neigh_cnt > 0)
        a2[update] = neigh_sum[update] / neigh_cnt[update]
        return a2

    if isinstance(m, xr.DataArray):
        if m.ndim < 2:
            raise ValueError("interpolat_zeros_2d requires at least 2D input")
        y_dim, x_dim = m.dims[0], m.dims[1]

        def _core(arr2: np.ndarray) -> np.ndarray:
            out = arr2
            it = 0
            while True:
                new = _interp_pass(out)
                it += 1
                if not fill:
                    return new
                if not np.any(new == 0):
                    return new
                if max_iter is not None and it >= int(max_iter):
                    return new
                if np.array_equal(new, out):
                    return new
                out = new

        out = xr.apply_ufunc(
            _core,
            m,
            input_core_dims=[[y_dim, x_dim]],
            output_core_dims=[[y_dim, x_dim]],
            vectorize=True,
            dask="parallelized",
            output_dtypes=[float],
        )
        out = out.assign_coords({y_dim: m[y_dim], x_dim: m[x_dim]})
        out.attrs = dict(m.attrs)
        return out

    arr = np.asarray(m)
    if arr.ndim != 2:
        raise ValueError("interpolat_zeros_2d expects a 2D NumPy array")
    out = arr.astype(float, copy=True)
    it = 0
    while True:
        new = _interp_pass(out)
        it += 1
        if not fill:
            return new
        if not np.any(new == 0):
            return new
        if max_iter is not None and it >= int(max_iter):
            return new
        if np.array_equal(new, out):
            return new
        out = new

jpdfscal(s1, s2, *, nbin=101)

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:

Name Type Description Default
s1 DataArray

Scalar fields as DataArrays. They must be broadcastable to the same shape; non-finite pairs are ignored.

required
s2 DataArray

Scalar fields as DataArrays. They must be broadcastable to the same shape; non-finite pairs are ignored.

required
nbin int

Number of bin centers per axis (default: 101).

101

Returns:

Type Description
Dataset

Dataset with coordinates bin1 and bin2 and a 2D variable hi containing counts.

Source code in pivpy/compute_funcs.py
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
def jpdfscal(
    s1: xr.DataArray,
    s2: xr.DataArray,
    *,
    nbin: int = 101,
) -> xr.Dataset:
    """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, 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
    -------
    xarray.Dataset
        Dataset with coordinates ``bin1`` and ``bin2`` and a 2D variable ``hi``
        containing counts.
    """

    if not isinstance(s1, xr.DataArray) or not isinstance(s2, xr.DataArray):
        raise TypeError("jpdfscal expects two xarray.DataArray inputs")

    n = int(nbin)
    if n < 3 or n % 2 == 0:
        # PIVMAT uses odd default (101). Odd makes the center bin land at 0.
        raise ValueError("nbin must be an odd integer >= 3")

    a1, a2 = xr.align(s1, s2, join="exact")
    v1 = np.asarray(a1.values, dtype=float).ravel()
    v2 = np.asarray(a2.values, dtype=float).ravel()

    finite = np.isfinite(v1) & np.isfinite(v2)
    v1 = v1[finite]
    v2 = v2[finite]

    if v1.size == 0:
        max1 = 0.0
    else:
        max1 = float(np.max(np.abs(v1)))
    if v2.size == 0:
        max2 = 0.0
    else:
        max2 = float(np.max(np.abs(v2)))

    bin1 = np.linspace(-max1, max1, n, dtype=float) if max1 > 0 else np.linspace(-1.0, 1.0, n, dtype=float)
    bin2 = np.linspace(-max2, max2, n, dtype=float) if max2 > 0 else np.linspace(-1.0, 1.0, n, dtype=float)

    rg = (n - 1) / 2.0

    def _to_index(v: np.ndarray, vmax: float) -> np.ndarray:
        if vmax <= 0.0 or not np.isfinite(vmax):
            return np.full_like(v, int(rg), dtype=int)
        idx = np.rint(rg * (1.0 + (v / vmax))).astype(int)
        return np.clip(idx, 0, n - 1)

    i1 = _to_index(v1, max1)
    i2 = _to_index(v2, max2)

    hi = np.zeros((n, n), dtype=float)
    # Vectorized 2D bincount
    flat = i1 * n + i2
    bc = np.bincount(flat, minlength=n * n)
    hi[:, :] = bc.reshape((n, n))

    ds = xr.Dataset(
        data_vars={"hi": (("bin1", "bin2"), hi)},
        coords={"bin1": ("bin1", bin1), "bin2": ("bin2", bin2)},
    )

    ds["hi"].attrs["long_name"] = "joint histogram"
    # Carry basic metadata if present.
    ds.attrs["namew1"] = str(a1.attrs.get("long_name", a1.name or "s1"))
    ds.attrs["namew2"] = str(a2.attrs.get("long_name", a2.name or "s2"))
    ds.attrs["unitw1"] = str(a1.attrs.get("units", ""))
    ds.attrs["unitw2"] = str(a2.attrs.get("units", ""))
    return ds

material_acceleration(ds, name='accel', unsteady=True, return_vector=False)

Calculates material acceleration D(u)/Dt = d(u)/dt + (u . grad)u.

Parameters:

Name Type Description Default
ds Dataset

PIV velocity dataset.

required
name str

Output variable name for acceleration magnitude (default 'accel').

'accel'
unsteady bool

If True and time dimension 't' is present with multiple frames, includes local acceleration d(u)/dt.

True
return_vector bool

If True, returns vector components 'ax' and 'ay' instead of magnitude.

False

Returns:

Type Description
Dataset
Source code in pivpy/compute_funcs.py
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
def material_acceleration(
    ds: xr.Dataset,
    name: str = "accel",
    unsteady: bool = True,
    return_vector: bool = False,
) -> xr.Dataset:
    """Calculates material acceleration D(u)/Dt = d(u)/dt + (u . grad)u.

    Parameters
    ----------
    ds : xr.Dataset
        PIV velocity dataset.
    name : str
        Output variable name for acceleration magnitude (default 'accel').
    unsteady : bool
        If True and time dimension 't' is present with multiple frames, includes local acceleration d(u)/dt.
    return_vector : bool
        If True, returns vector components 'ax' and 'ay' instead of magnitude.

    Returns
    -------
    xr.Dataset
    """
    dx = float(ds["x"][1] - ds["x"][0]) if len(ds["x"]) > 1 else 1.0
    dy = float(ds["y"][1] - ds["y"][0]) if len(ds["y"]) > 1 else 1.0

    u = ds["u"]
    v = ds["v"]

    # Spatial convective derivatives
    du_dx = u.differentiate("x")
    du_dy = u.differentiate("y")
    dv_dx = v.differentiate("x")
    dv_dy = v.differentiate("y")

    ax_conv = u * du_dx + v * du_dy
    ay_conv = u * dv_dx + v * dv_dy

    if unsteady and "t" in ds.dims and ds.sizes["t"] > 1:
        dt = float(ds["t"][1] - ds["t"][0]) if len(ds["t"]) > 1 else 1.0
        ax_local = u.differentiate("t")
        ay_local = v.differentiate("t")
        ax = ax_local + ax_conv
        ay = ay_local + ay_conv
    else:
        ax = ax_conv
        ay = ay_conv

    out = ds.copy(deep=False)
    if return_vector:
        out["ax"] = ax
        out["ay"] = ay
        out["ax"].attrs["units"] = "1/delta_t^2"
        out["ay"].attrs["units"] = "1/delta_t^2"
        out["ax"].attrs["standard_name"] = "material_acceleration_x"
        out["ay"].attrs["standard_name"] = "material_acceleration_y"
    else:
        warn_if_overwriting_scalar(out, name)
        mag = np.sqrt(ax**2 + ay**2)
        out[name] = mag
        out[name].attrs["units"] = "1/delta_t^2"
        out[name].attrs["standard_name"] = "material_acceleration"

    return out

meannz(x, dim=None, *, keep_attrs=True)

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.
Source code in pivpy/compute_funcs.py
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
def meannz(
    x: xr.DataArray | np.ndarray,
    dim: int | str | None = None,
    *,
    keep_attrs: bool = True,
) -> xr.DataArray | np.ndarray:
    """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.
    """

    if isinstance(x, xr.DataArray):
        if dim is None:
            # First non-singleton dimension (Matlab-like).
            dim_name = next((d for d in x.dims if x.sizes[d] != 1), x.dims[0])
        elif isinstance(dim, int):
            dim_name = x.dims[int(dim)]
        else:
            dim_name = dim

        nz = x.where(x != 0)
        summed = nz.sum(dim=dim_name, skipna=True)
        count = (x != 0).sum(dim=dim_name)
        out = summed / count.where(count != 0)
        out = out.fillna(0.0)
        if keep_attrs:
            out.attrs = dict(x.attrs)
        return out

    arr = np.asarray(x)
    if dim is None:
        dim = next((i for i, s in enumerate(arr.shape) if s != 1), 0)
    if not isinstance(dim, int):
        raise ValueError("For NumPy inputs, dim must be an int or None.")

    arr_f = arr.astype(float, copy=False)
    mask = arr_f != 0
    summed = np.sum(np.where(mask, arr_f, 0.0), axis=dim)
    count = np.sum(mask, axis=dim)
    out = np.divide(summed, count, out=np.zeros_like(summed, dtype=float), where=(count != 0))
    out = np.nan_to_num(out, nan=0.0)
    return out

normalized_median_test(ds, radius=1, threshold=2.0, epsilon=0.1, name_mask=None)

Applies the Westerweel & Scarano (2005) Normalized Median Test to detect outliers.

Flags detected spurious vectors by setting chc = 0 (or updating name_mask).

Parameters:

Name Type Description Default
ds Dataset

Canonical velocity field containing 'u', 'v', 'x', 'y' (and optional 't', 'chc').

required
radius int

Neighborhood radius in grid units (default 1 for 3x3 neighborhood).

1
threshold float

Outlier threshold (default 2.0).

2.0
epsilon float

Noise floor parameter in velocity units (default 0.1).

0.1
name_mask str

Optional variable name to store boolean outlier mask in the dataset.

None

Returns:

Type Description
Dataset

Updated dataset with flagged vectors in 'chc' (and optional mask variable).

Source code in pivpy/compute_funcs.py
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
def normalized_median_test(
    ds: xr.Dataset,
    radius: int = 1,
    threshold: float = 2.0,
    epsilon: float = 0.1,
    name_mask: str | None = None,
) -> xr.Dataset:
    """Applies the Westerweel & Scarano (2005) Normalized Median Test to detect outliers.

    Flags detected spurious vectors by setting `chc = 0` (or updating `name_mask`).

    Parameters
    ----------
    ds : xr.Dataset
        Canonical velocity field containing 'u', 'v', 'x', 'y' (and optional 't', 'chc').
    radius : int
        Neighborhood radius in grid units (default 1 for 3x3 neighborhood).
    threshold : float
        Outlier threshold (default 2.0).
    epsilon : float
        Noise floor parameter in velocity units (default 0.1).
    name_mask : str, optional
        Optional variable name to store boolean outlier mask in the dataset.

    Returns
    -------
    xr.Dataset
        Updated dataset with flagged vectors in 'chc' (and optional mask variable).
    """
    out = ds.copy(deep=True)
    has_t = "t" in out.dims

    def _process_2d(u_2d: np.ndarray, v_2d: np.ndarray, chc_2d: np.ndarray | None) -> tuple[np.ndarray, np.ndarray]:
        valid_mask = (chc_2d > 0) if chc_2d is not None else np.isfinite(u_2d) & np.isfinite(v_2d)
        is_outlier = _normalized_median_test_2d(
            u_2d, v_2d, radius=radius, threshold=threshold, epsilon=epsilon, valid_mask=valid_mask
        )
        new_chc = (chc_2d.copy() if chc_2d is not None else np.ones_like(u_2d, dtype=float))
        new_chc[is_outlier] = 0.0
        return is_outlier, new_chc

    if has_t:
        n_frames = out.sizes["t"]
        outlier_arr = np.zeros(out["u"].shape, dtype=bool)
        chc_arr = np.ones(out["u"].shape, dtype=float)
        has_chc = "chc" in out.data_vars
        for i in range(n_frames):
            u_i = out["u"].isel(t=i).to_numpy()
            v_i = out["v"].isel(t=i).to_numpy()
            chc_i = out["chc"].isel(t=i).to_numpy() if has_chc else None
            outl_i, chc_i_new = _process_2d(u_i, v_i, chc_i)
            outlier_arr[:, :, i] = outl_i
            chc_arr[:, :, i] = chc_i_new
        dims = ("y", "x", "t")
    else:
        u_2d = out["u"].to_numpy()
        v_2d = out["v"].to_numpy()
        chc_2d = out["chc"].to_numpy() if "chc" in out.data_vars else None
        outlier_arr, chc_arr = _process_2d(u_2d, v_2d, chc_2d)
        dims = ("y", "x")

    out["chc"] = xr.DataArray(chc_arr, dims=dims, coords=out.coords)
    out["chc"].attrs["standard_name"] = "confidence_flag"
    if name_mask:
        out[name_mask] = xr.DataArray(outlier_arr, dims=dims, coords=out.coords)
        out[name_mask].attrs["standard_name"] = "outlier_mask"
    return out

okubo_weiss(ds, name='Q_ow')

Calculates the Okubo-Weiss criterion for vortex identification.

Regions with Q_ow < 0 indicate vortex cores dominated by rotation over strain.

Args: ds (xr.Dataset): Velocity field containing 'u', 'v', 'x', 'y' (and optional 't'). name (str): Variable name for the output field. Defaults to 'Q_ow'.

Returns: xr.Dataset: Dataset with Okubo-Weiss scalar field.

Source code in pivpy/compute_funcs.py
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
def okubo_weiss(ds: xr.Dataset, name: str = "Q_ow") -> xr.Dataset:
    """Calculates the Okubo-Weiss criterion for vortex identification.

    Regions with Q_ow < 0 indicate vortex cores dominated by rotation over strain.

    Args:
        ds (xr.Dataset): Velocity field containing 'u', 'v', 'x', 'y' (and optional 't').
        name (str): Variable name for the output field. Defaults to 'Q_ow'.

    Returns:
        xr.Dataset: Dataset with Okubo-Weiss scalar field.
    """
    warn_if_overwriting_scalar(ds, name)
    out_arr = _apply_2d_slices(ds, _okubo_weiss_2d)
    out = ds.copy(deep=False)
    dims = ("y", "x", "t") if "t" in ds.dims else ("y", "x")
    out[name] = xr.DataArray(out_arr, dims=dims, coords=ds.coords)
    out[name].attrs["standard_name"] = "okubo_weiss"
    out[name].attrs["units"] = "1/s^2"
    return out

operf(op, f1, f2=None)

Perform algebraic/elementwise operations on vector/scalar fields.

This is a pragmatic, PIVMAT-inspired helper similar to MATLAB's operf.

Parameters:

Name Type Description Default
op str

Operation string (e.g. '+', '-', '.*', './', comparisons like '>=', or unary ops like 'abs').

required
f1 Dataset | list[Dataset]

A vector Dataset (contains u and v) or scalar Dataset (contains w), or a list of such datasets.

required
f2 Dataset | list[Dataset] | float | int | ndarray | None

Optional second operand: a Dataset (or list), or a scalar/array.

None
Source code in pivpy/compute_funcs.py
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
def operf(
    op: str,
    f1: xr.Dataset | list[xr.Dataset],
    f2: xr.Dataset | list[xr.Dataset] | float | int | np.ndarray | None = None,
):
    """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 ``u`` and ``v``) or scalar Dataset (contains ``w``),
        or a list of such datasets.
    f2:
        Optional second operand: a Dataset (or list), or a scalar/array.
    """

    def _is_vector(ds: xr.Dataset) -> bool:
        return "u" in ds.data_vars and "v" in ds.data_vars

    def _is_scalar(ds: xr.Dataset) -> bool:
        return "w" in ds.data_vars and not _is_vector(ds)

    def _with_history(ds: xr.Dataset, entry: str) -> xr.Dataset:
        hist = list(ds.attrs.get("history", []))
        hist.append(entry)
        ds.attrs["history"] = hist
        return ds

    def _apply_unary(ds: xr.Dataset) -> xr.Dataset:
        op_s = str(op)
        op_l = op_s.lower()

        if op_s in ("+", "-"):
            out = ds.copy(deep=True)
            if _is_vector(out):
                sgn = 1.0 if op_s == "+" else -1.0
                out["u"] = (out["u"] * sgn).astype(float)
                out["v"] = (out["v"] * sgn).astype(float)
            elif _is_scalar(out):
                sgn = 1.0 if op_s == "+" else -1.0
                out["w"] = (out["w"] * sgn).astype(float)
            else:
                raise ValueError("operf: expected a vector (u,v) or scalar (w) Dataset")
            return _with_history(out, f"operf('{op_s}', ans)")

        unary_map: dict[str, object] = {
            "log": np.log,
            "exp": np.exp,
            "abs": np.abs,
            "real": np.real,
            "imag": np.imag,
            "conj": np.conj,
            "angle": np.angle,
            "sin": np.sin,
            "cos": np.cos,
            "tan": np.tan,
            "asin": np.arcsin,
            "acos": np.arccos,
            "atan": np.arctan,
        }

        if op_l == "logabs":
            func = lambda a: np.log(np.abs(a))  # noqa: E731
        elif op_l in unary_map:
            func = unary_map[op_l]
        else:
            if not _is_vector(ds):
                raise ValueError("operf: invalid unary operation for scalar field")
            if not hasattr(ds, "piv"):
                raise ValueError("operf: xarray accessor 'piv' not available")
            out = ds.piv.vec2scal(op)  # type: ignore[attr-defined]
            if not isinstance(out, xr.Dataset):
                raise ValueError("operf: vec2scal returned unexpected type")
            return _with_history(out, f"operf('{op}', ans)")

        out = ds.copy(deep=True)
        if _is_vector(out):
            out["u"] = xr.apply_ufunc(func, out["u"])  # type: ignore[arg-type]
            out["v"] = xr.apply_ufunc(func, out["v"])  # type: ignore[arg-type]
        elif _is_scalar(out):
            out["w"] = xr.apply_ufunc(func, out["w"])  # type: ignore[arg-type]
        else:
            raise ValueError("operf: expected a vector (u,v) or scalar (w) Dataset")
        return _with_history(out, f"operf('{op}', ans)")

    def _apply_binary(ds: xr.Dataset, rhs: xr.Dataset | float | int | np.ndarray) -> xr.Dataset:
        op_s = str(op)
        op_l = op_s.lower()

        # Normalize operator aliases
        if op_s in (".*",):
            op_s = "*"
        if op_s in ("./",):
            op_s = "/"
        if op_s == "=":
            op_s = "=="

        # Field-field
        if isinstance(rhs, xr.Dataset):
            if _is_vector(ds) != _is_vector(rhs) or _is_scalar(ds) != _is_scalar(rhs):
                raise ValueError("operf: f1 and f2 must be of the same type")
            if op_s not in ("+", "-", "*", "/"):
                raise ValueError("operf: invalid binary operation for fields")
            a, b = xr.align(ds, rhs, join="exact")
            out = a.copy(deep=True)
            if _is_vector(out):
                if op_s == "+":
                    out["u"] = out["u"] + b["u"]
                    out["v"] = out["v"] + b["v"]
                elif op_s == "-":
                    out["u"] = out["u"] - b["u"]
                    out["v"] = out["v"] - b["v"]
                elif op_s == "*":
                    out["u"] = out["u"] * b["u"]
                    out["v"] = out["v"] * b["v"]
                else:
                    out["u"] = out["u"] / b["u"]
                    out["v"] = out["v"] / b["v"]
            else:
                if op_s == "+":
                    out["w"] = out["w"] + b["w"]
                elif op_s == "-":
                    out["w"] = out["w"] - b["w"]
                elif op_s == "*":
                    out["w"] = out["w"] * b["w"]
                else:
                    out["w"] = out["w"] / b["w"]
            return _with_history(out, f"operf('{op}', ans1, ans2)")

        out = ds.copy(deep=True)
        rhs_arr = np.asarray(rhs)

        binarize = op_l.startswith("b")
        cmp_op = op_l[1:] if binarize else op_l
        if cmp_op == "=":
            cmp_op = "=="

        def _cmp(a: xr.DataArray, thr: float) -> xr.DataArray:
            if cmp_op == ">":
                return a > thr
            if cmp_op == "<":
                return a < thr
            if cmp_op == ">=":
                return a >= thr
            if cmp_op == "<=":
                return a <= thr
            if cmp_op == "==":
                return a == thr
            raise ValueError("operf: invalid operation")

        # Field-number (vector)
        if _is_vector(out):
            if op_s in ("+", "-"):
                if rhs_arr.size == 1:
                    ru, rv = float(rhs_arr), float(rhs_arr)
                elif rhs_arr.size >= 2:
                    ru, rv = float(rhs_arr.flat[0]), float(rhs_arr.flat[1])
                else:
                    raise ValueError("operf: invalid numeric operand")
                if op_s == "+":
                    out["u"] = out["u"] + ru
                    out["v"] = out["v"] + rv
                else:
                    out["u"] = out["u"] - ru
                    out["v"] = out["v"] - rv
                return _with_history(out, f"operf('{op}', ans, {rhs_arr})")
            if op_s in ("*", "/"):
                r = float(rhs_arr.flat[0])
                out["u"] = (out["u"] * r) if op_s == "*" else (out["u"] / r)
                out["v"] = (out["v"] * r) if op_s == "*" else (out["v"] / r)
                return _with_history(out, f"operf('{op}', ans, {r})")
            if op_s in (".^", "^"):
                r = float(rhs_arr.flat[0])
                out["u"] = out["u"] ** r
                out["v"] = out["v"] ** r
                return _with_history(out, f"operf('{op}', ans, {r})")

            thr = float(rhs_arr.flat[0])
            m_u = _cmp(out["u"], thr)
            m_v = _cmp(out["v"], thr)
            if binarize:
                out["u"] = m_u.astype(float)
                out["v"] = m_v.astype(float)
            else:
                out["u"] = m_u.astype(float) * out["u"]
                out["v"] = m_v.astype(float) * out["v"]
            return _with_history(out, f"operf('{op}', ans, {thr})")

        # Field-number (scalar)
        if not _is_scalar(out):
            raise ValueError("operf: expected a vector (u,v) or scalar (w) Dataset")

        if op_s in ("+", "-", "*", "/", ".^", "^"):
            r = float(rhs_arr.flat[0])
            if op_s == "+":
                out["w"] = out["w"] + r
            elif op_s == "-":
                out["w"] = out["w"] - r
            elif op_s == "*":
                out["w"] = out["w"] * r
            elif op_s == "/":
                out["w"] = out["w"] / r
            else:
                out["w"] = out["w"] ** r
            return _with_history(out, f"operf('{op}', ans, {r})")

        thr = float(rhs_arr.flat[0])
        m = _cmp(out["w"], thr)
        if binarize:
            out["w"] = m.astype(float)
        else:
            out["w"] = m.astype(float) * out["w"]
        return _with_history(out, f"operf('{op}', ans, {thr})")

    f1_list = f1 if isinstance(f1, list) else [f1]
    if f2 is None:
        out_list = [_apply_unary(ds) for ds in f1_list]
        return out_list if isinstance(f1, list) else out_list[0]

    if isinstance(f2, list):
        out_list: list[xr.Dataset] = []
        for i, ds in enumerate(f1_list):
            rhs = f2[min(i, len(f2) - 1)]
            out_list.append(_apply_binary(ds, rhs))
        return out_list if isinstance(f1, list) else out_list[0]

    out_list = [_apply_binary(ds, f2) for ds in f1_list]
    return out_list if isinstance(f1, list) else out_list[0]

probeaverf(ds, rect, *, variables=None, skipna=True)

Time series averaged over a rectangular area (PIVMAT-inspired).

Parameters:

Name Type Description Default
ds Dataset

Input dataset with spatial coordinates x and y.

required
rect

Rectangle as [x1, y1, x2, y2] in physical units.

required
variables list[str] | None

Variables to average. If None, defaults to ['u','v'] when present, otherwise tries ['w'].

None
skipna bool

If True (default), NaNs are ignored in the mean.

True

Returns:

Type Description
Dataset

Dataset containing the spatially averaged time series.

Source code in pivpy/compute_funcs.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
def probeaverf(
    ds: xr.Dataset,
    rect,
    *,
    variables: list[str] | None = None,
    skipna: bool = True,
) -> xr.Dataset:
    """Time series averaged over a rectangular area (PIVMAT-inspired).

    Parameters
    ----------
    ds:
        Input dataset with spatial coordinates ``x`` and ``y``.
    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
    -------
    xarray.Dataset
        Dataset containing the spatially averaged time series.
    """

    if rect is None or not hasattr(rect, "__len__") or len(rect) != 4:
        raise ValueError("rect must be [x1, y1, x2, y2]")

    if variables is None:
        if "u" in ds and "v" in ds:
            variables = ["u", "v"]
        elif "w" in ds:
            variables = ["w"]
        else:
            if not ds.data_vars:
                raise ValueError("probeaverf: dataset has no data variables")
            variables = [next(iter(ds.data_vars))]

    variables = list(variables)
    for name in variables:
        if name not in ds:
            raise KeyError(f"Variable '{name}' not found in dataset")

    x1, y1, x2, y2 = [float(v) for v in rect]
    sub = _sel_coord_range(ds, "x", x1, x2)
    sub = _sel_coord_range(sub, "y", y1, y2)

    out_vars: dict[str, xr.DataArray] = {}
    for name in variables:
        da = sub[name]
        if "x" not in da.dims or "y" not in da.dims:
            raise ValueError(f"Variable '{name}' must have dims including 'x' and 'y'")
        out_vars[name] = da.mean(dim=("y", "x"), skipna=bool(skipna))

    out = xr.Dataset(out_vars)
    out.attrs = dict(ds.attrs)
    return out

probef(ds, x0, y0, *, variables=None, method='linear')

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:

Name Type Description Default
ds Dataset

Input dataset with spatial coordinates x and y.

required
x0

Probe coordinates in physical units. Scalars or 1D arrays of equal length.

required
y0

Probe coordinates in physical units. Scalars or 1D arrays of equal length.

required
variables list[str] | None

Variables to sample. If None, defaults to ['u','v'] when present, otherwise tries ['w'].

None
method str

Interpolation method, passed to DataArray.interp (e.g. 'linear', 'nearest').

'linear'

Returns:

Type Description
Dataset

Dataset of sampled time series. If multiple probe points are given, the result has a probe dimension.

Source code in pivpy/compute_funcs.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
def probef(
    ds: xr.Dataset,
    x0,
    y0,
    *,
    variables: list[str] | None = None,
    method: str = "linear",
) -> xr.Dataset:
    """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 ``x`` and ``y``.
    x0, 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
    -------
    xarray.Dataset
        Dataset of sampled time series. If multiple probe points are given,
        the result has a ``probe`` dimension.
    """

    if "x" not in ds.coords or "y" not in ds.coords:
        raise ValueError("probef requires coordinates 'x' and 'y'")

    if variables is None:
        if "u" in ds and "v" in ds:
            variables = ["u", "v"]
        elif "w" in ds:
            variables = ["w"]
        else:
            # Fall back to first data_var if any.
            if not ds.data_vars:
                raise ValueError("probef: dataset has no data variables")
            variables = [next(iter(ds.data_vars))]

    variables = list(variables)
    for name in variables:
        if name not in ds:
            raise KeyError(f"Variable '{name}' not found in dataset")

    x_arr = np.asarray(x0, dtype=float)
    y_arr = np.asarray(y0, dtype=float)
    if x_arr.ndim == 0 and y_arr.ndim == 0:
        # Single probe point
        x_da: xr.DataArray | float = float(x_arr)
        y_da: xr.DataArray | float = float(y_arr)
        probe_coord = None
    else:
        x_arr = np.atleast_1d(x_arr).astype(float)
        y_arr = np.atleast_1d(y_arr).astype(float)
        if x_arr.shape != y_arr.shape:
            raise ValueError("x0 and y0 must have the same shape")
        probe = np.arange(int(x_arr.size), dtype=int)
        x_da = xr.DataArray(x_arr.reshape(-1), dims=("probe",), coords={"probe": probe})
        y_da = xr.DataArray(y_arr.reshape(-1), dims=("probe",), coords={"probe": probe})
        probe_coord = probe

    out_vars: dict[str, xr.DataArray] = {}
    for name in variables:
        da = ds[name]
        if "x" not in da.dims or "y" not in da.dims:
            raise ValueError(f"Variable '{name}' must have dims including 'x' and 'y'")
        sampled = da.interp(x=x_da, y=y_da, method=method)
        out_vars[name] = sampled

    out = xr.Dataset(out_vars)
    if probe_coord is not None:
        out = out.assign_coords(
            x_probe=("probe", np.asarray(x_arr.reshape(-1), dtype=float)),
            y_probe=("probe", np.asarray(y_arr.reshape(-1), dtype=float)),
        )
    out.attrs = dict(ds.attrs)
    return out

q_criterion(ds, name='Q')

Calculates Hunt's Q-criterion for vortex core identification.

Regions with Q > 0 indicate rotation-dominated vortex cores.

Args: ds (xr.Dataset): Velocity field containing 'u', 'v', 'x', 'y' (and optional 't'). name (str): Variable name for the output field. Defaults to 'Q'.

Returns: xr.Dataset: Dataset with Q-criterion scalar field.

Source code in pivpy/compute_funcs.py
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
def q_criterion(ds: xr.Dataset, name: str = "Q") -> xr.Dataset:
    """Calculates Hunt's Q-criterion for vortex core identification.

    Regions with Q > 0 indicate rotation-dominated vortex cores.

    Args:
        ds (xr.Dataset): Velocity field containing 'u', 'v', 'x', 'y' (and optional 't').
        name (str): Variable name for the output field. Defaults to 'Q'.

    Returns:
        xr.Dataset: Dataset with Q-criterion scalar field.
    """
    warn_if_overwriting_scalar(ds, name)
    out_arr = _apply_2d_slices(ds, _q_criterion_2d)
    out = ds.copy(deep=False)
    dims = ("y", "x", "t") if "t" in ds.dims else ("y", "x")
    out[name] = xr.DataArray(out_arr, dims=dims, coords=ds.coords)
    out[name].attrs["standard_name"] = "Q_criterion"
    out[name].attrs["units"] = "1/s^2"
    return out

reynolds_decomposition(ds, name_mean='mean', name_prime='prime')

Performs Reynolds decomposition on a time-series velocity dataset.

Splits velocity vectors into temporal mean and turbulent fluctuations:

.. math::

\mathbf{u}(\mathbf{x}, t) = \overline{\mathbf{u}}(\mathbf{x}) + \mathbf{u}'(\mathbf{x}, t)

Parameters:

Name Type Description Default
ds Dataset

Multi-frame velocity dataset with time dimension 't'.

required
name_mean str

Prefix for mean variables (default 'mean').

'mean'
name_prime str

Suffix for fluctuation variables (default 'prime').

'prime'

Returns:

Type Description
Dataset

Dataset containing: - u_mean, v_mean: Temporal mean velocity components. - u_prime, v_prime: Fluctuating velocity components along 't'. - uu_prime: Normal Reynolds stress . - vv_prime: Normal Reynolds stress . - uv_prime: Shear Reynolds stress -. - tke: Turbulent kinetic energy 0.5*( + ). - intensity_u, intensity_v: Turbulence intensities.

Raises:

Type Description
ValueError

If dataset has no 't' dimension or fewer than 2 frames.

Source code in pivpy/compute_funcs.py
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
def reynolds_decomposition(
    ds: xr.Dataset,
    name_mean: str = "mean",
    name_prime: str = "prime",
) -> xr.Dataset:
    r"""Performs Reynolds decomposition on a time-series velocity dataset.

    Splits velocity vectors into temporal mean and turbulent fluctuations:

    .. math::

        \mathbf{u}(\mathbf{x}, t) = \overline{\mathbf{u}}(\mathbf{x}) + \mathbf{u}'(\mathbf{x}, t)

    Parameters
    ----------
    ds : xr.Dataset
        Multi-frame velocity dataset with time dimension 't'.
    name_mean : str
        Prefix for mean variables (default 'mean').
    name_prime : str
        Suffix for fluctuation variables (default 'prime').

    Returns
    -------
    xr.Dataset
        Dataset containing:
        - ``u_mean``, ``v_mean``: Temporal mean velocity components.
        - ``u_prime``, ``v_prime``: Fluctuating velocity components along 't'.
        - ``uu_prime``: Normal Reynolds stress <u'^2>.
        - ``vv_prime``: Normal Reynolds stress <v'^2>.
        - ``uv_prime``: Shear Reynolds stress -<u' v'>.
        - ``tke``: Turbulent kinetic energy 0.5*(<u'^2> + <v'^2>).
        - ``intensity_u``, ``intensity_v``: Turbulence intensities.

    Raises
    ------
    ValueError
        If dataset has no 't' dimension or fewer than 2 frames.
    """
    if "t" not in ds.dims or ds.sizes["t"] < 2:
        raise ValueError("Reynolds decomposition requires a multi-frame dataset with at least 2 time steps along 't'.")

    u_mean = ds["u"].mean(dim="t")
    v_mean = ds["v"].mean(dim="t")

    u_prime = ds["u"] - u_mean
    v_prime = ds["v"] - v_mean

    uu_prime = (u_prime**2).mean(dim="t")
    vv_prime = (v_prime**2).mean(dim="t")
    uv_prime = -(u_prime * v_prime).mean(dim="t")
    tke = 0.5 * (uu_prime + vv_prime)

    u_mag_mean = np.sqrt(u_mean**2 + v_mean**2)
    eps_denom = 1e-12
    intensity_u = np.sqrt(uu_prime) / np.maximum(u_mag_mean, eps_denom)
    intensity_v = np.sqrt(vv_prime) / np.maximum(u_mag_mean, eps_denom)

    out = xr.Dataset(
        data_vars={
            f"u_{name_mean}": u_mean,
            f"v_{name_mean}": v_mean,
            f"u_{name_prime}": u_prime,
            f"v_{name_prime}": v_prime,
            "uu_prime": uu_prime,
            "vv_prime": vv_prime,
            "uv_prime": uv_prime,
            "tke": tke,
            "intensity_u": intensity_u,
            "intensity_v": intensity_v,
        },
        coords=ds.coords,
        attrs=ds.attrs.copy(),
    )

    out[f"u_{name_mean}"].attrs["units"] = ds["u"].attrs.get("units", "m/s")
    out[f"v_{name_mean}"].attrs["units"] = ds["v"].attrs.get("units", "m/s")
    out[f"u_{name_prime}"].attrs["units"] = ds["u"].attrs.get("units", "m/s")
    out[f"v_{name_prime}"].attrs["units"] = ds["v"].attrs.get("units", "m/s")
    out["uu_prime"].attrs["units"] = "(m/s)^2"
    out["vv_prime"].attrs["units"] = "(m/s)^2"
    out["uv_prime"].attrs["units"] = "(m/s)^2"
    out["tke"].attrs["units"] = "(m/s)^2"
    out["intensity_u"].attrs["units"] = "1"
    out["intensity_v"].attrs["units"] = "1"

    return out

setoriginf(f, P0)

Set the origin (0,0) of a vector/scalar field (PIVMAT-compatible).

Port of PIVMAT's setoriginf.m.

Parameters:

Name Type Description Default
f Dataset | list[Dataset]

Vector/scalar dataset (or list of datasets).

required
P0 ArrayLike

New origin as [x0, y0] in the same units as the coords.

required
Source code in pivpy/compute_funcs.py
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
def setoriginf(f: xr.Dataset | list[xr.Dataset], P0: ArrayLike) -> xr.Dataset | list[xr.Dataset]:
    """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.
    """

    p = np.asarray(P0, dtype=float).ravel()
    if p.size < 2:
        raise ValueError("P0 must be a 2-element sequence [x0, y0]")
    x0, y0 = float(p[0]), float(p[1])

    out_list: list[xr.Dataset] = []
    for ds in _as_field_list(f):
        out = ds.assign_coords(x=ds["x"] - x0, y=ds["y"] - y0)
        out_list.append(_with_history(out, f"setoriginf(ans, [{x0}, {y0}])"))
    return out_list if isinstance(f, list) else out_list[0]

shiftf(f, opt='bottomleft')

Shift the axis of a vector/scalar field (PIVMAT-compatible).

Port of PIVMAT's shiftf.m.

Parameters:

Name Type Description Default
opt str

One of: 'bottomleft'/'bl' (default), 'bottomright'/'br', 'topleft'/'tl', 'topright'/'tr', 'center'/'c'/'middle'.

'bottomleft'
Source code in pivpy/compute_funcs.py
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
def shiftf(f: xr.Dataset | list[xr.Dataset], opt: str = "bottomleft") -> xr.Dataset | list[xr.Dataset]:
    """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'.
    """

    opt_l = str(opt).lower()
    out_list: list[xr.Dataset] = []
    for ds in _as_field_list(f):
        x = np.asarray(ds["x"].values, dtype=float)
        y = np.asarray(ds["y"].values, dtype=float)
        if x.size == 0 or y.size == 0:
            out_list.append(ds)
            continue

        if opt_l in {"center", "c", "middle"}:
            sx = 0.5 * (float(x[0]) + float(x[-1]))
            sy = 0.5 * (float(y[0]) + float(y[-1]))
        elif opt_l in {"bottomleft", "bl"}:
            sx = float(x[0])
            sy = float(y[0])
        elif opt_l in {"bottomright", "br"}:
            sx = float(x[-1])
            sy = float(y[0])
        elif opt_l in {"topleft", "tl"}:
            sx = float(x[0])
            sy = float(y[-1])
        elif opt_l in {"topright", "tr"}:
            sx = float(x[-1])
            sy = float(y[-1])
        else:
            raise ValueError("opt must be one of: center/c/middle, bottomleft/bl, bottomright/br, topleft/tl, topright/tr")

        out = ds.assign_coords(x=ds["x"] - sx, y=ds["y"] - sy)
        out_list.append(_with_history(out, f"shiftf(ans, '{opt}')"))
    return out_list if isinstance(f, list) else out_list[0]

smooth(ds, sigma=1.0, method='gaussian', **kwargs)

Applies spatial smoothing to velocity vector fields.

Parameters:

Name Type Description Default
ds Dataset

PIV velocity dataset.

required
sigma float or sequence of floats

Filter kernel size (sigma for Gaussian, window size for median/boxcar, cutoff size for Butterworth).

1.0
method ('gaussian', 'median', 'boxcar', 'butterworth')

Smoothing algorithm (default 'gaussian').

'gaussian'
**kwargs dict

Additional arguments passed to filtering backend (e.g., order=2 for Butterworth).

{}

Returns:

Type Description
Dataset

Smoothed dataset.

Source code in pivpy/compute_funcs.py
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
def smooth(
    ds: xr.Dataset,
    sigma: float | Sequence[float] = 1.0,
    method: str = "gaussian",
    **kwargs,
) -> xr.Dataset:
    """Applies spatial smoothing to velocity vector fields.

    Parameters
    ----------
    ds : xr.Dataset
        PIV velocity dataset.
    sigma : float or sequence of floats
        Filter kernel size (sigma for Gaussian, window size for median/boxcar, cutoff size for Butterworth).
    method : {'gaussian', 'median', 'boxcar', 'butterworth'}
        Smoothing algorithm (default 'gaussian').
    **kwargs : dict
        Additional arguments passed to filtering backend (e.g., order=2 for Butterworth).

    Returns
    -------
    xr.Dataset
        Smoothed dataset.
    """
    try:
        from scipy.ndimage import gaussian_filter, median_filter, uniform_filter
    except ImportError as exc:
        raise ImportError("smooth requires scipy.ndimage") from exc

    m = str(method).lower()
    out = ds.copy(deep=True)
    has_t = "t" in out.dims

    def _filter_2d(arr2: np.ndarray) -> np.ndarray:
        if m.startswith("gauss"):
            fs = float(sigma) if not isinstance(sigma, (list, tuple)) else float(sigma[0])
            return gaussian_filter(arr2, sigma=fs, **kwargs)
        elif m.startswith("med"):
            size = int(np.round(float(sigma))) if not isinstance(sigma, (list, tuple)) else int(sigma[0])
            if size % 2 == 0:
                size += 1
            return median_filter(arr2, size=max(1, size))
        elif m.startswith("box") or m.startswith("uni") or m.startswith("flat"):
            size = int(np.round(float(sigma))) if not isinstance(sigma, (list, tuple)) else int(sigma[0])
            return uniform_filter(arr2, size=max(1, size))
        elif m.startswith("butter"):
            fs = float(sigma) if not isinstance(sigma, (list, tuple)) else float(sigma[0])
            order = float(kwargs.get("order", 2.0))
            ny, nx = arr2.shape
            pad_y = 1 if ny % 2 != 0 else 0
            pad_x = 1 if nx % 2 != 0 else 0
            if pad_y or pad_x:
                arr_pad = np.pad(arr2, ((0, pad_y), (0, pad_x)), mode="edge")
                res = bwfilter2d(arr_pad, filtsize=fs, order=order)
                return res[:ny, :nx]
            return bwfilter2d(arr2, filtsize=fs, order=order)
        else:
            raise ValueError(f"Unknown smoothing method: {method!r}")

    for var in ["u", "v"]:
        if var not in out.data_vars:
            continue
        if has_t:
            n_frames = out.sizes["t"]
            for i in range(n_frames):
                slice_arr = out[var].isel(t=i).to_numpy()
                out[var].values[:, :, i] = _filter_2d(slice_arr)
        else:
            slice_arr = out[var].to_numpy()
            out[var].values = _filter_2d(slice_arr)

    return out

smoothf(f, n=3, opt='')

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-2\lfloor n/2 \rfloor$ (PIVMAT behavior).

Source code in pivpy/compute_funcs.py
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
def smoothf(f: xr.Dataset | list[xr.Dataset], n: int = 3, opt: str = "") -> xr.Dataset | list[xr.Dataset]:
    r"""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-2\lfloor n/2 \rfloor$ (PIVMAT behavior).
    """

    n = int(n)
    if n <= 0:
        raise ValueError("n must be positive")

    out_list: list[xr.Dataset] = []
    for ds in _as_field_list(f):
        if "t" not in ds.dims:
            raise ValueError("smoothf requires a time dimension 't'")
        nt = int(ds.sizes["t"])
        cn = n // 2
        if nt < n:
            raise ValueError("smoothf requires len(t) >= n")

        frames: list[xr.Dataset] = []
        t_out = np.asarray(ds["t"].values, dtype=float)[cn : nt - cn]
        # Smoothing should not treat 0 as missing by default.
        opt_eff = str(opt)
        if "0" not in opt_eff:
            opt_eff = opt_eff + "0"

        for i in range(0, nt - n + 1):
            sub = ds.isel(t=slice(i, i + n))
            avg = sub.piv.averf(opt_eff)  # type: ignore[attr-defined]
            # Ensure each window-average has a unique time coordinate so concat stacks,
            # rather than aligning on identical t=0 values.
            avg = avg.assign_coords(t=np.asarray([t_out[i]], dtype=float))
            frames.append(avg)

        out = xr.concat(frames, dim="t")
        out.attrs = dict(ds.attrs)
        out_list.append(_with_history(out, f"smoothf(ans, {n}, '{opt}')"))
    return out_list if isinstance(f, list) else out_list[0]

spatial_correlation(ds, component='u', dim='x', normalize=True)

Calculates spatial two-point autocorrelation function R_ij(r).

Computes:

.. math::

R(r) = \frac{\langle u'(\mathbf{x}) u'(\mathbf{x} + r\hat{\mathbf{e}}) \rangle}{\sqrt{\langle u'(\mathbf{x})^2 \rangle \langle u'(\mathbf{x} + r\hat{\mathbf{e}})^2 \rangle}}

Parameters:

Name Type Description Default
ds Dataset

PIV velocity dataset (single-frame or multi-frame ensemble).

required
component ('u', 'v')

Velocity component to correlate (default 'u').

'u'
dim ('x', 'y')

Spatial dimension along which separation lag r is evaluated (default 'x').

'x'
normalize bool

If True, normalizes such that R(0) = 1.0 (default True).

True

Returns:

Type Description
Dataset

Dataset with coordinate r (separation distance) and correlation variable R.

Source code in pivpy/compute_funcs.py
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
def spatial_correlation(
    ds: xr.Dataset,
    component: str = "u",
    dim: str = "x",
    normalize: bool = True,
) -> xr.Dataset:
    r"""Calculates spatial two-point autocorrelation function R_ij(r).

    Computes:

    .. math::

        R(r) = \frac{\langle u'(\mathbf{x}) u'(\mathbf{x} + r\hat{\mathbf{e}}) \rangle}{\sqrt{\langle u'(\mathbf{x})^2 \rangle \langle u'(\mathbf{x} + r\hat{\mathbf{e}})^2 \rangle}}

    Parameters
    ----------
    ds : xr.Dataset
        PIV velocity dataset (single-frame or multi-frame ensemble).
    component : {'u', 'v'}
        Velocity component to correlate (default 'u').
    dim : {'x', 'y'}
        Spatial dimension along which separation lag r is evaluated (default 'x').
    normalize : bool
        If True, normalizes such that R(0) = 1.0 (default True).

    Returns
    -------
    xr.Dataset
        Dataset with coordinate ``r`` (separation distance) and correlation variable ``R``.
    """
    comp = str(component).lower()
    if comp not in ds.data_vars:
        raise ValueError(f"Component {component!r} not found in dataset data variables.")

    val = ds[comp].to_numpy()
    has_t = "t" in ds.dims and ds.sizes["t"] > 1

    # Subtract mean
    if has_t:
        mean_field = np.nanmean(val, axis=-1, keepdims=True)
        fluc = val - mean_field
    else:
        fluc = val - np.nanmean(val)

    if dim.lower() == "x":
        # Correlate along axis 1 (x)
        nx = ds.sizes["x"]
        dx = float(np.mean(np.diff(ds["x"].values))) if nx > 1 else 1.0
        r_coords = np.arange(nx, dtype=float) * dx
        auto = np.zeros(nx, dtype=float)

        for r_idx in range(nx):
            if has_t:
                s1 = fluc[:, : nx - r_idx, :]
                s2 = fluc[:, r_idx:, :]
            else:
                s1 = fluc[:, : nx - r_idx]
                s2 = fluc[:, r_idx:]
            cov = np.nanmean(s1 * s2)
            if normalize:
                denom = np.sqrt(np.nanmean(s1**2) * np.nanmean(s2**2))
                auto[r_idx] = cov / max(1e-12, denom)
            else:
                auto[r_idx] = cov

    elif dim.lower() == "y":
        # Correlate along axis 0 (y)
        ny = ds.sizes["y"]
        dy = float(np.mean(np.diff(ds["y"].values))) if ny > 1 else 1.0
        r_coords = np.arange(ny, dtype=float) * dy
        auto = np.zeros(ny, dtype=float)

        for r_idx in range(ny):
            if has_t:
                s1 = fluc[: ny - r_idx, :, :]
                s2 = fluc[r_idx:, :, :]
            else:
                s1 = fluc[: ny - r_idx, :]
                s2 = fluc[r_idx:, :]
            cov = np.nanmean(s1 * s2)
            if normalize:
                denom = np.sqrt(np.nanmean(s1**2) * np.nanmean(s2**2))
                auto[r_idx] = cov / max(1e-12, denom)
            else:
                auto[r_idx] = cov
    else:
        raise ValueError(f"dim must be 'x' or 'y', got {dim!r}")

    R = auto

    out = xr.Dataset(
        data_vars={"R": (("r",), R)},
        coords={"r": r_coords},
    )
    out["R"].attrs["units"] = "1" if normalize else "(m/s)^2"
    out["R"].attrs["standard_name"] = f"spatial_autocorrelation_{comp}_{dim}"
    out["r"].attrs["units"] = ds[dim].attrs.get("units", "m")
    return out

spatiotempcorrf(f, *opts)

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 w and dims (y,x,t).

Options
  • 'full': use all possible X and T (noisy for large lags)
  • 'verbose': print progress
Source code in pivpy/compute_funcs.py
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
def spatiotempcorrf(f: xr.Dataset, *opts: str) -> xr.Dataset:
    """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 ``w`` and dims ``(y,x,t)``.

    Options
    -------
    - 'full': use all possible X and T (noisy for large lags)
    - 'verbose': print progress
    """

    opt_l = {str(o).lower() for o in opts}
    verbose = any(o.startswith("verb") for o in opt_l)
    full = any(o.startswith("full") for o in opt_l)

    if not _is_scalar(f):
        raise ValueError("spatiotempcorrf requires a scalar dataset with variable 'w'")
    if "t" not in f.dims:
        raise ValueError("spatiotempcorrf requires a time dimension 't'")

    w = np.asarray(f["w"].values, dtype=float)
    ny, nx, nt = w.shape
    x = np.asarray(f["x"].values, dtype=float)
    dx = float(x[1] - x[0]) if x.size >= 2 else 1.0

    if full:
        T = np.arange(nt, dtype=int)
        X = np.arange(nx, dtype=int)
    else:
        T = np.arange(nt // 2 + 1, dtype=int)
        X = np.arange(nx // 2 + 1, dtype=int)

    corpos = np.zeros((X.size, T.size), dtype=float)
    corneg = np.zeros((X.size, T.size), dtype=float)

    for it, lagT in enumerate(T):
        if verbose:
            print(f"{(it + 1) / max(1, T.size) * 100:.1f}%", end=", ")
        for ix, lagX in enumerate(X):
            acc_p = 0.0
            acc_n = 0.0
            for j in range(0, nt - lagT):
                a = w[:, : nx - lagX, j]
                b = w[:, lagX:, j + lagT]
                acc_p += float(np.mean(a * b))

                a2 = w[:, lagX:, j]
                b2 = w[:, : nx - lagX, j + lagT]
                acc_n += float(np.mean(a2 * b2))
            corpos[ix, it] = acc_p
            corneg[ix, it] = acc_n
    if verbose:
        print("\n")

    cor = np.vstack([corneg[:0:-1, :], corpos])
    # Normalize by C(0,0)
    cor = cor / float(cor[X.size - 1, 0])
    Xlags = dx * np.concatenate([-X[:0:-1], X]).astype(float)

    return xr.Dataset(
        data_vars={"cor": (("X", "T"), cor)},
        coords={"X": ("X", Xlags), "T": ("T", T.astype(float))},
        attrs={"unitX": f["x"].attrs.get("units", ""), "unitcor": f"({f['w'].attrs.get('units','')})^2"},
    )

spatiotempf(ds, X, Y, *, var='w', n=None, method='linear')

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:

Name Type Description Default
ds Dataset

Input dataset with coordinates x and y.

required
X

Endpoints in physical units.

  • Single line: X=[x0,x1], Y=[y0,y1].
  • Multiple lines: X=[[x0,x1],[...]], Y=[[y0,y1],[...]].
required
Y

Endpoints in physical units.

  • Single line: X=[x0,x1], Y=[y0,y1].
  • Multiple lines: X=[[x0,x1],[...]], Y=[[y0,y1],[...]].
required
var str

Scalar variable name to sample.

'w'
n int | None

Number of sample points along each line. If None, a heuristic based on grid spacing is used.

None
method str

Interpolation method for DataArray.interp.

'linear'

Returns:

Type Description
Dataset

Dataset with variable st.

  • dims: ('t','s') for a single line, or ('line','t','s') for multiple.
  • coords: s is the distance along the line (same units as x/y). x_line and y_line give the sampled coordinates along the line.
Source code in pivpy/compute_funcs.py
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
def spatiotempf(
    ds: xr.Dataset,
    X,
    Y,
    *,
    var: str = "w",
    n: int | None = None,
    method: str = "linear",
) -> xr.Dataset:
    """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 ``x`` and ``y``.
    X, 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
    -------
    xarray.Dataset
        Dataset with variable ``st``.

        - dims: ``('t','s')`` for a single line, or ``('line','t','s')`` for multiple.
        - coords: ``s`` is the distance along the line (same units as x/y).
          ``x_line`` and ``y_line`` give the sampled coordinates along the line.
    """

    if "x" not in ds.coords or "y" not in ds.coords:
        raise ValueError("spatiotempf requires coordinates 'x' and 'y'")
    if var not in ds:
        raise KeyError(f"Variable '{var}' not found in dataset")

    da = ds[var]
    if "x" not in da.dims or "y" not in da.dims:
        raise ValueError(f"Variable '{var}' must have dims including 'x' and 'y'")
    if "t" not in da.dims:
        raise ValueError("spatiotempf requires a time dimension 't'")

    X_arr = np.asarray(X, dtype=float)
    Y_arr = np.asarray(Y, dtype=float)

    # Normalize to (nlines, 2)
    if X_arr.ndim == 1:
        if X_arr.size != 2 or Y_arr.ndim != 1 or Y_arr.size != 2:
            raise ValueError("For a single line, X and Y must be length-2 sequences")
        X_arr = X_arr.reshape(1, 2)
        Y_arr = Y_arr.reshape(1, 2)
        single_line = True
    else:
        if X_arr.ndim != 2 or Y_arr.ndim != 2 or X_arr.shape != Y_arr.shape or X_arr.shape[1] != 2:
            raise ValueError("For multiple lines, X and Y must be shaped (nlines, 2)")
        single_line = X_arr.shape[0] == 1

    # Heuristic for n based on average grid spacing
    if n is None:
        xvals = np.asarray(ds["x"].values, dtype=float)
        yvals = np.asarray(ds["y"].values, dtype=float)
        dx = float(np.nanmedian(np.abs(np.diff(xvals)))) if xvals.size >= 2 else 1.0
        dy = float(np.nanmedian(np.abs(np.diff(yvals)))) if yvals.size >= 2 else 1.0
        d = float(np.nanmin([dx, dy])) if np.isfinite(dx) and np.isfinite(dy) else 1.0
        if not np.isfinite(d) or d <= 0:
            d = 1.0
        lengths = np.sqrt((X_arr[:, 1] - X_arr[:, 0]) ** 2 + (Y_arr[:, 1] - Y_arr[:, 0]) ** 2)
        maxlen = float(np.nanmax(lengths)) if lengths.size else 0.0
        n = int(max(2, min(4096, np.ceil(maxlen / d) + 1)))
    else:
        n = int(n)
        if n < 2:
            raise ValueError("n must be >= 2")

    s = np.linspace(0.0, 1.0, n, dtype=float)

    # We keep a normalized s in [0,1] as the dimension for robust concatenation.
    # Physical distance along the line is provided as coordinate ``s_phys``.
    line_lengths = np.sqrt((X_arr[:, 1] - X_arr[:, 0]) ** 2 + (Y_arr[:, 1] - Y_arr[:, 0]) ** 2)
    line_lengths = np.asarray(line_lengths, dtype=float)

    out_list: list[xr.DataArray] = []
    for i in range(int(X_arr.shape[0])):
        x_line = X_arr[i, 0] + s * (X_arr[i, 1] - X_arr[i, 0])
        y_line = Y_arr[i, 0] + s * (Y_arr[i, 1] - Y_arr[i, 0])

        x_da = xr.DataArray(x_line, dims=("s",), coords={"s": s})
        y_da = xr.DataArray(y_line, dims=("s",), coords={"s": s})
        sampled = da.interp(x=x_da, y=y_da, method=method)
        # sampled dims: (t, s) plus any others (but var should be scalar).
        sampled = sampled.transpose("t", "s", ...)
        sampled = sampled.assign_coords(
            x_line=("s", np.asarray(x_line, dtype=float)),
            y_line=("s", np.asarray(y_line, dtype=float)),
            s_phys=("s", np.asarray(s * float(line_lengths[i]), dtype=float)),
        )
        out_list.append(sampled)

    if len(out_list) == 1:
        st = out_list[0]
        # For single-line case, promote s_phys to be the primary coordinate values
        # while keeping the dimension name 's'.
        st = st.assign_coords(s=np.asarray(st["s_phys"].values, dtype=float))
        st.name = "st"
        out = xr.Dataset({"st": st})
        out.attrs = dict(ds.attrs)
        return out

    st_all = xr.concat(out_list, dim="line")
    st_all = st_all.assign_coords(line=np.arange(st_all.sizes["line"], dtype=int))
    st_all.name = "st"
    out = xr.Dataset({"st": st_all})
    out.attrs = dict(ds.attrs)
    return out

spec2f(f, *opts)

2D power spectrum (PIVMAT-inspired).

Source code in pivpy/compute_funcs.py
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
def spec2f(f: xr.Dataset | xr.DataArray, *opts: str) -> xr.Dataset:
    """2D power spectrum (PIVMAT-inspired)."""

    use_hann = any(str(o).lower().startswith("hann") for o in opts)
    frames = _as_frames(f)
    first = frames[0]

    if isinstance(first, xr.Dataset):
        is_vector = ("u" in first.data_vars and "v" in first.data_vars)
        is_scalar = ("w" in first.data_vars) and not is_vector
        x = np.asarray(first["x"].values, dtype=float)
        y = np.asarray(first["y"].values, dtype=float)
        ny = int(first.sizes["y"])
        nx = int(first.sizes["x"])
    else:
        is_vector = False
        is_scalar = True
        x = np.asarray(first["x"].values, dtype=float)
        y = np.asarray(first["y"].values, dtype=float)
        ny = int(first.sizes["y"])
        nx = int(first.sizes["x"])

    nx2 = nx - (nx % 2)
    ny2 = ny - (ny % 2)
    if nx2 != nx or ny2 != ny:
        frames = [fr.isel(x=slice(0, nx2), y=slice(0, ny2)) for fr in frames]
        nx, ny = nx2, ny2
        x = x[:nx]
        y = y[:ny]

    nkx = nx // 2
    nky = ny // 2
    kx, ky = _kx_ky_from_coords(x, y, nx, ny)
    dkx = float(kx[1]) if kx.size >= 2 else 1.0
    dky = float(ky[1]) if ky.size >= 2 else 1.0

    if use_hann:
        hann_x = _hann(nx)[None, :]
        hann_y = _hann(ny)[:, None]

    def _spec2(a2: np.ndarray) -> np.ndarray:
        aa = a2
        if use_hann:
            aa = (aa * hann_x) * hann_y
        # Full shifted spectrum is (ny, nx). PIVMAT-style outputs are typically
        # reported on the positive (one-sided) wavenumber grid only.
        ft = np.fft.fftshift(np.abs(np.fft.fft2(aa)) ** 2)
        return ft[ny // 2 : ny, nx // 2 : nx]

    if is_vector:
        ex_i = []
        ey_i = []
        for fr in frames:
            assert isinstance(fr, xr.Dataset)
            ex_i.append(_spec2(np.asarray(fr["u"].values, dtype=float)))
            ey_i.append(_spec2(np.asarray(fr["v"].values, dtype=float)))
        ex = np.mean(np.stack(ex_i, axis=0), axis=0)
        ey = np.mean(np.stack(ey_i, axis=0), axis=0)

        ex = ex / (nx * ny) ** 2 / dkx
        ey = ey / (nx * ny) ** 2 / dky
        e = ex + ey
        ds = xr.Dataset(
            data_vars={"ex": (("ky", "kx"), ex), "ey": (("ky", "kx"), ey), "e": (("ky", "kx"), e)},
            coords={"kx": ("kx", kx), "ky": ("ky", ky)},
        )
        ds.attrs["appod"] = "Hann" if use_hann else "None"
    else:
        if not is_scalar:
            raise ValueError("spec2f expects a scalar DataArray or a Dataset with 'w'")
        e_i = []
        for fr in frames:
            if isinstance(fr, xr.Dataset):
                a2 = np.asarray(fr["w"].values, dtype=float)
            else:
                a2 = np.asarray(fr.values, dtype=float)
            e_i.append(_spec2(a2))
        e = np.mean(np.stack(e_i, axis=0), axis=0)
        e = e / (nx * ny) ** 2 / dkx
        ds = xr.Dataset(data_vars={"e": (("ky", "kx"), e)}, coords={"kx": ("kx", kx), "ky": ("ky", ky)})
        ds.attrs["appod"] = "Hann" if use_hann else "None"

    # Azimuthal average for square domains
    if nx == ny:
        kk, ep = _azimuthal_average_square(np.asarray(ds["e"].values))
        ds["k"] = ("k", kk * float(np.abs(kx[1] - kx[0])))
        ds["ep"] = ("k", ep)

    return ds

specf(f, *opts)

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 :class:xarray.Dataset with coordinates kx and ky. For vector fields, returns exvx, exvy, eyvx, eyvy. For scalar fields, returns ex, ey. If the field is square, also returns isotropic components k and e.

Source code in pivpy/compute_funcs.py
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
def specf(f: xr.Dataset | xr.DataArray, *opts: str) -> xr.Dataset:
    """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 \n\n
    $$\\int E(k)\\,dk \approx \\langle s^2 \\rangle$$

    Returns an :class:`xarray.Dataset` with coordinates ``kx`` and ``ky``.
    For vector fields, returns ``exvx, exvy, eyvx, eyvy``.
    For scalar fields, returns ``ex, ey``.
    If the field is square, also returns isotropic components ``k`` and ``e``.
    """

    use_hann = any(str(o).lower().startswith("hann") for o in opts)

    frames = _as_frames(f)
    first = frames[0]

    if isinstance(first, xr.Dataset):
        is_vector = ("u" in first.data_vars and "v" in first.data_vars)
        is_scalar = ("w" in first.data_vars) and not is_vector
    else:
        # DataArray treated as scalar
        is_vector = False
        is_scalar = True

    # Extract coords and sizes
    if isinstance(first, xr.Dataset):
        x = np.asarray(first["x"].values, dtype=float)
        y = np.asarray(first["y"].values, dtype=float)
        ny = int(first.sizes["y"])
        nx = int(first.sizes["x"])
    else:
        # DataArray
        if "x" not in first.dims or "y" not in first.dims:
            raise ValueError("specf expects DataArray with dims ('y','x')")
        x = np.asarray(first["x"].values, dtype=float)
        y = np.asarray(first["y"].values, dtype=float)
        ny = int(first.sizes["y"])
        nx = int(first.sizes["x"])

    # Enforce even sizes (PIVMAT behavior)
    nx2 = nx - (nx % 2)
    ny2 = ny - (ny % 2)
    if nx2 != nx or ny2 != ny:
        frames2: list[xr.Dataset | xr.DataArray] = []
        for fr in frames:
            frames2.append(fr.isel(x=slice(0, nx2), y=slice(0, ny2)))
        frames = frames2
        nx, ny = nx2, ny2
        x = x[:nx]
        y = y[:ny]

    nkx = nx // 2
    nky = ny // 2
    kx, ky = _kx_ky_from_coords(x, y, nx, ny)

    # Hann windows
    if use_hann:
        hann_x = _hann(nx)[None, :]  # along x
        hann_y = _hann(ny)[:, None]  # along y

    def _fft_power_x(a2: np.ndarray) -> np.ndarray:
        # mean(|fft(a, axis=x)|^2, over y)
        aa = a2
        if use_hann:
            aa = aa * hann_x
        fx = np.fft.fft(aa, axis=1)
        return np.mean(np.abs(fx) ** 2, axis=0)

    def _fft_power_y(a2: np.ndarray) -> np.ndarray:
        aa = a2
        if use_hann:
            aa = aa * hann_y
        fy = np.fft.fft(aa, axis=0)
        return np.mean(np.abs(fy) ** 2, axis=1)

    if is_vector:
        exvx_i = []
        exvy_i = []
        eyvx_i = []
        eyvy_i = []
        for fr in frames:
            assert isinstance(fr, xr.Dataset)
            u2 = np.asarray(fr["u"].values, dtype=float)
            v2 = np.asarray(fr["v"].values, dtype=float)
            exvx_i.append(_fft_power_x(u2))
            exvy_i.append(_fft_power_x(v2))
            eyvx_i.append(_fft_power_y(u2))
            eyvy_i.append(_fft_power_y(v2))

        exvx = np.mean(np.stack(exvx_i, axis=0), axis=0)
        exvy = np.mean(np.stack(exvy_i, axis=0), axis=0)
        eyvx = np.mean(np.stack(eyvx_i, axis=0), axis=0)
        eyvy = np.mean(np.stack(eyvy_i, axis=0), axis=0)

        # PIVMAT normalization
        dkx = float(kx[1]) if kx.size >= 2 else 1.0
        dky = float(ky[1]) if ky.size >= 2 else 1.0
        exvx = 2.0 * exvx[:nkx] / (nx * ny) / dkx
        exvy = 2.0 * exvy[:nkx] / (nx * ny) / dkx
        eyvx = 2.0 * eyvx[:nky] / (nx * ny) / dky
        eyvy = 2.0 * eyvy[:nky] / (nx * ny) / dky
        exvx[0] /= 2.0
        exvy[0] /= 2.0
        eyvx[0] /= 2.0
        eyvy[0] /= 2.0

        ds = xr.Dataset(
            data_vars={
                "exvx": ("kx", exvx),
                "exvy": ("kx", exvy),
                "eyvx": ("ky", eyvx),
                "eyvy": ("ky", eyvy),
            },
            coords={"kx": ("kx", kx), "ky": ("ky", ky)},
        )
        ds.attrs["appod"] = "Hann" if use_hann else "None"
    else:
        # scalar
        ex_i = []
        ey_i = []
        for fr in frames:
            if isinstance(fr, xr.Dataset):
                if "w" not in fr.data_vars:
                    raise ValueError("specf scalar path expects variable 'w'")
                a2 = np.asarray(fr["w"].values, dtype=float)
            else:
                a2 = np.asarray(fr.values, dtype=float)
            ex_i.append(_fft_power_x(a2))
            ey_i.append(_fft_power_y(a2))
        ex = np.mean(np.stack(ex_i, axis=0), axis=0)
        ey = np.mean(np.stack(ey_i, axis=0), axis=0)

        dkx = float(kx[1]) if kx.size >= 2 else 1.0
        dky = float(ky[1]) if ky.size >= 2 else 1.0
        ex = 2.0 * ex[:nkx] / (nx * ny) / dkx
        ey = 2.0 * ey[:nky] / (nx * ny) / dky
        ex[0] /= 2.0
        ey[0] /= 2.0

        ds = xr.Dataset(data_vars={"ex": ("kx", ex), "ey": ("ky", ey)}, coords={"kx": ("kx", kx), "ky": ("ky", ky)})
        ds.attrs["appod"] = "Hann" if use_hann else "None"

    # isotropic spectrum for square domain
    # NOTE: xarray will broadcast (kx + ky) into 2D if we add DataArrays
    # with different dimension names. Keep this explicitly 1D.
    if nx == ny:
        k = 0.5 * (np.asarray(ds["kx"].values, dtype=float) + np.asarray(ds["ky"].values, dtype=float))
        ds = ds.assign_coords({"k": ("k", k)})
        if is_vector:
            el = 0.5 * (np.asarray(ds["exvx"].values, dtype=float) + np.asarray(ds["eyvy"].values, dtype=float))
            et = 0.5 * (np.asarray(ds["exvy"].values, dtype=float) + np.asarray(ds["eyvx"].values, dtype=float))
            e = el + et
            ds["el"] = ("k", el)
            ds["et"] = ("k", et)
            ds["e"] = ("k", e)
        else:
            e = 0.5 * (np.asarray(ds["ex"].values, dtype=float) + np.asarray(ds["ey"].values, dtype=float))
            ds["e"] = ("k", e)

    return ds

ssf(s, dim=1, *opts)

Structure functions of a scalar field (PIVMAT-inspired).

Source code in pivpy/compute_funcs.py
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
def ssf(s: xr.Dataset, dim: int | str = 1, *opts: str) -> xr.Dataset:
    """Structure functions of a scalar field (PIVMAT-inspired)."""

    if "w" not in s:
        raise ValueError("ssf expects a scalar Dataset with variable 'w'")

    # options
    include_zero = any(str(o) == "0" for o in opts)
    maxorder = 4
    if any(str(o).lower().startswith("maxorder") for o in opts):
        # accept ('maxorder', N) style
        try:
            idx = [i for i, o in enumerate(opts) if str(o).lower().startswith("maxorder")][-1]
            maxorder = max(4, int(opts[idx + 1]))
        except Exception:
            raise ValueError("ssf: expected integer after 'maxorder'")
    if maxorder > 30:
        raise ValueError("Maximum order too large")

    if isinstance(dim, str):
        dim_l = dim.lower()
        if dim_l == "x":
            dim_i = 1
        elif dim_l == "y":
            dim_i = 2
        else:
            raise ValueError("dim must be 1,2,'x','y'")
    else:
        dim_i = int(dim)

    w0 = s["w"].isel(t=0) if "t" in s.dims else s["w"]
    rms = float(np.nanstd(w0.values))
    bin_centers = None
    if any(str(o).lower().startswith("bin") for o in opts):
        idx = [i for i, o in enumerate(opts) if str(o).lower().startswith("bin")][-1]
        try:
            bin_centers = np.asarray(opts[idx + 1], dtype=float)
        except Exception:
            raise ValueError("ssf: expected a numeric bin vector after 'bin'")
    if bin_centers is None:
        maxbin = 10.0 * rms
        bin_centers = np.linspace(-maxbin, maxbin, 1000)
    binwidth = float(np.abs(bin_centers[1] - bin_centers[0]))
    edges = _bin_centers_to_edges(bin_centers)

    r_list = None
    if any(str(o).lower() == "r" for o in opts):
        idx = [i for i, o in enumerate(opts) if str(o).lower() == "r"][-1]
        r_list = np.asarray(opts[idx + 1], dtype=int)
    if r_list is None:
        default_r = np.asarray(
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 26, 28, 30, 32, 36, 40, 44, 48, 52, 56, 60, 64, 72, 80, 96, 112, 128, 142, 160, 176, 192, 224, 256],
            dtype=int,
        )
        maxdr = min(int(s.sizes["x"]), int(s.sizes["y"]))
        r_list = default_r[default_r < maxdr]

    frames = _as_frames(s)
    hsi = np.zeros((r_list.size, bin_centers.size), dtype=float)

    for fr in frames:
        assert isinstance(fr, xr.Dataset)
        a = np.asarray(fr["w"].values, dtype=float)
        nx = a.shape[1]
        ny = a.shape[0]
        for ir, rr in enumerate(r_list):
            if dim_i == 1:
                if rr >= nx:
                    continue
                dsx = a[:, rr:] - a[:, : nx - rr]
                if not include_zero:
                    valid = (a[:, rr:] != 0) & (a[:, : nx - rr] != 0) & np.isfinite(dsx)
                    dsx = np.where(valid, dsx, 0.0)
                vals = dsx.ravel()
            else:
                if rr >= ny:
                    continue
                dsy = a[rr:, :] - a[: ny - rr, :]
                if not include_zero:
                    valid = (a[rr:, :] != 0) & (a[: ny - rr, :] != 0) & np.isfinite(dsy)
                    dsy = np.where(valid, dsy, 0.0)
                vals = dsy.ravel()
            vals = vals[(vals != 0.0) & np.isfinite(vals)]
            if vals.size:
                hist, _ = np.histogram(vals, bins=edges)
                hsi[ir, :] += hist

    pdfsi = np.zeros_like(hsi)
    sf = np.zeros((r_list.size, maxorder), dtype=float)
    sfabs = np.zeros((r_list.size, maxorder), dtype=float)
    skew = np.zeros(r_list.size, dtype=float)
    flat = np.zeros(r_list.size, dtype=float)
    n_used = np.zeros(r_list.size, dtype=float)

    for ir in range(r_list.size):
        nsi = float(np.sum(hsi[ir, :]))
        n_used[ir] = nsi
        if nsi > 0:
            pdfsi[ir, :] = hsi[ir, :] / (nsi * binwidth)
        for order in range(1, maxorder + 1):
            sf[ir, order - 1] = float(np.sum(pdfsi[ir, :] * (bin_centers**order)) * binwidth)
            sfabs[ir, order - 1] = float(np.sum(pdfsi[ir, :] * (np.abs(bin_centers) ** order)) * binwidth)
        if sf[ir, 1] != 0:
            skew[ir] = sf[ir, 2] / (sf[ir, 1] ** 1.5)
            flat[ir] = sf[ir, 3] / (sf[ir, 1] ** 2)

    scaler = float(np.abs(s["x"].values[1] - s["x"].values[0])) if s["x"].size >= 2 else 1.0

    return xr.Dataset(
        data_vars={
            "hsi": (("r", "bin"), hsi),
            "pdfsi": (("r", "bin"), pdfsi),
            "sf": (("r", "order"), sf),
            "sfabs": (("r", "order"), sfabs),
            "skew": ("r", skew),
            "flat": ("r", flat),
            "n": ("r", n_used),
        },
        coords={
            "r": ("r", r_list.astype(float)),
            "bin": ("bin", bin_centers),
            "order": ("order", np.arange(1, maxorder + 1, dtype=int)),
        },
        attrs={"scaler": scaler, "binwidth": binwidth},
    )

statf(s, maxorder=6)

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).
Source code in pivpy/compute_funcs.py
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
def statf(s: xr.Dataset | list[xr.Dataset], maxorder: int = 6):
    """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).
    """

    maxorder = int(maxorder)
    if maxorder <= 0:
        raise ValueError("maxorder must be positive")

    fields = _as_field_list(s)
    if len(fields) == 0:
        raise ValueError("Empty input")

    ds0 = fields[0]
    if _is_vector(ds0):
        su = statf([d[["u"]].rename({"u": "w"}) for d in fields], maxorder)
        sv = statf([d[["v"]].rename({"v": "w"}) for d in fields], maxorder)
        return su, sv

    if not _is_scalar(ds0):
        raise ValueError("statf expects a vector (u,v) or scalar (w) Dataset")

    # Stack all samples across space and time.
    vecs: list[np.ndarray] = []
    zeros = 0
    for ds in fields:
        w = np.asarray(ds["w"].values, dtype=float)
        vec = w.ravel()
        zeros += int(np.sum(vec == 0))
        vecs.append(vec)
    f_vect = np.concatenate(vecs)
    nz = f_vect != 0
    f_vect = f_vect[nz]
    if f_vect.size == 0:
        f_vect = np.asarray([0.0], dtype=float)

    mean = float(np.mean(f_vect))
    std = float(np.std(f_vect, ddof=0))
    rms = float(np.sqrt(np.mean(f_vect**2)))
    stat: dict[str, object] = {
        "mean": mean,
        "std": std,
        "rms": rms,
        "min": float(np.min(f_vect)),
        "max": float(np.max(f_vect)),
        "nfields": len(fields),
        "n": int(f_vect.size),
        "zeros": int(zeros),
        "mom": np.zeros(maxorder, dtype=float),
        "momabs": np.zeros(maxorder, dtype=float),
        "cmom": np.zeros(maxorder, dtype=float),
        "cmomabs": np.zeros(maxorder, dtype=float),
    }

    for order in range(1, maxorder + 1):
        stat["cmom"][order - 1] = float(np.mean((f_vect - mean) ** order))
        stat["cmomabs"][order - 1] = float(np.mean(np.abs(f_vect - mean) ** order))
        stat["mom"][order - 1] = float(np.mean(f_vect**order))
        stat["momabs"][order - 1] = float(np.mean(np.abs(f_vect) ** order))

    if maxorder >= 3 and float(stat["mom"][1]) != 0.0:
        stat["skewness"] = float(stat["mom"][2] / (stat["mom"][1] ** 1.5))
        stat["flatness"] = float(stat["mom"][3] / (stat["mom"][1] ** 2))
        stat["skewnessc"] = float(stat["cmom"][2] / (stat["cmom"][1] ** 1.5))
        stat["flatnessc"] = float(stat["cmom"][3] / (stat["cmom"][1] ** 2))

    stat["history"] = ["statf(ans)"]
    return stat

stresstensor(v)

Reynolds stress tensor (PIVMAT-compatible).

Port of PIVMAT's stresstensor.m for 2-component vector datasets.

Returns:

Type Description
tuple

(t, b) where t is the stress tensor and b the deviatoric tensor.

Source code in pivpy/compute_funcs.py
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
def stresstensor(v: xr.Dataset | list[xr.Dataset]):
    """Reynolds stress tensor (PIVMAT-compatible).

    Port of PIVMAT's ``stresstensor.m`` for 2-component vector datasets.

    Returns
    -------
    tuple
        ``(t, b)`` where ``t`` is the stress tensor and ``b`` the deviatoric tensor.
    """

    fields = _as_field_list(v)
    if len(fields) == 0:
        raise ValueError("Empty input")
    ds0 = fields[0]
    if not _is_vector(ds0):
        raise ValueError("stresstensor requires a vector dataset with variables 'u' and 'v'")

    u = np.concatenate([np.asarray(d["u"].values, dtype=float).ravel() for d in fields])
    w = np.concatenate([np.asarray(d["v"].values, dtype=float).ravel() for d in fields])
    valid = (u != 0) & (w != 0) & np.isfinite(u) & np.isfinite(w)
    if not np.any(valid):
        t = np.zeros((2, 2), dtype=float)
        b = np.zeros((2, 2), dtype=float)
        return t, b
    u = u[valid]
    w = w[valid]
    t = np.zeros((2, 2), dtype=float)
    t[0, 0] = float(np.mean(u * u))
    t[1, 1] = float(np.mean(w * w))
    t[0, 1] = t[1, 0] = float(np.mean(u * w))
    tr = float(np.trace(t))
    if tr == 0.0:
        b = np.zeros_like(t)
    else:
        b = t / tr - np.eye(2) / 2.0
    return t, b

subsbr(f, r0=None)

Subtract the mean solid-body rotation (PIVMAT-compatible).

Source code in pivpy/compute_funcs.py
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
def subsbr(f: xr.Dataset | list[xr.Dataset], r0: ArrayLike | None = None) -> xr.Dataset | list[xr.Dataset]:
    """Subtract the mean solid-body rotation (PIVMAT-compatible)."""

    out_list: list[xr.Dataset] = []
    for ds in _as_field_list(f):
        if not _is_vector(ds):
            raise ValueError("subsbr requires a vector dataset with variables 'u' and 'v'")

        x = np.asarray(ds["x"].values, dtype=float)
        y = np.asarray(ds["y"].values, dtype=float)
        if r0 is None:
            r0x = 0.5 * (float(x[0]) + float(x[-1]))
            r0y = 0.5 * (float(y[0]) + float(y[-1]))
        else:
            rr = np.asarray(r0, dtype=float).ravel()
            r0x, r0y = float(rr[0]), float(rr[1])

        # Mean vorticity over space/time
        u = np.asarray(ds["u"].values, dtype=float)
        v = np.asarray(ds["v"].values, dtype=float)
        dx = float(x[1] - x[0]) if x.size >= 2 else 1.0
        dy = float(y[1] - y[0]) if y.size >= 2 else 1.0
        x_units = str(ds["x"].attrs.get("units", "")).lower()
        scale = 1000.0 if "mm" in x_units else 1.0
        dx_m = dx / scale
        dy_m = dy / scale
        dvdx = np.gradient(v, dx_m, axis=1, edge_order=1)
        dudy = np.gradient(u, dy_m, axis=0, edge_order=1)
        rot = dvdx - dudy
        meanrot = float(np.nanmean(rot))

        ycol = ((y[:, None] - r0y) / scale).astype(float)  # (ny,1)
        xrow = ((x[None, :] - r0x) / scale).astype(float)  # (1,nx)
        sbr_u = np.broadcast_to(-ycol * meanrot / 2.0, (y.size, x.size))
        sbr_v = np.broadcast_to(+xrow * meanrot / 2.0, (y.size, x.size))

        out = ds.copy(deep=True)
        out["u"] = out["u"] - xr.DataArray(sbr_u[:, :, None], dims=("y", "x", "t"))
        out["v"] = out["v"] - xr.DataArray(sbr_v[:, :, None], dims=("y", "x", "t"))
        out_list.append(_with_history(out, f"subsbr(ans, [{r0x}, {r0y}])"))
    return out_list if isinstance(f, list) else out_list[0]

subsbr2(f, dt=1.0, r0=None)

Subtract mean rotation and compensate integrated camera rotation (PIVMAT-compatible).

Source code in pivpy/compute_funcs.py
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
def subsbr2(
    f: xr.Dataset | list[xr.Dataset],
    dt: float = 1.0,
    r0: ArrayLike | None = None,
) -> xr.Dataset | list[xr.Dataset]:
    """Subtract mean rotation and compensate integrated camera rotation (PIVMAT-compatible)."""

    dt = float(dt)
    out_list: list[xr.Dataset] = []
    theta = 0.0

    for ds in _as_field_list(f):
        out = subsbr(ds, r0=r0)
        assert isinstance(out, xr.Dataset)

        # Recompute mean vorticity after subtraction (to match PIVMAT's integrated omega estimate).
        x = np.asarray(out["x"].values, dtype=float)
        y = np.asarray(out["y"].values, dtype=float)
        u = np.asarray(out["u"].values, dtype=float)
        v = np.asarray(out["v"].values, dtype=float)
        dx = float(x[1] - x[0]) if x.size >= 2 else 1.0
        dy = float(y[1] - y[0]) if y.size >= 2 else 1.0
        x_units = str(out["x"].attrs.get("units", "")).lower()
        scale = 1000.0 if "mm" in x_units else 1.0
        dx_m = dx / scale
        dy_m = dy / scale
        dvdx = (np.roll(v, -1, axis=1) - np.roll(v, 1, axis=1)) / (2.0 * dx_m)
        dudy = (np.roll(u, -1, axis=0) - np.roll(u, 1, axis=0)) / (2.0 * dy_m)
        meanrot = float(np.nanmean(dvdx - dudy))

        theta += (meanrot / 2.0) * dt

        if r0 is None:
            r0x = 0.5 * (float(x[0]) + float(x[-1]))
            r0y = 0.5 * (float(y[0]) + float(y[-1]))
        else:
            rr = np.asarray(r0, dtype=float).ravel()
            r0x, r0y = float(rr[0]), float(rr[1])

        out = _rotate_about(out, theta_rad=theta, x0=r0x, y0=r0y)
        out_list.append(_with_history(out, f"subsbr2(ans, {dt}, [{r0x}, {r0y}])"))

    return out_list if isinstance(f, list) else out_list[0]

surfheight(dr, h0, H=np.inf, n=1.33, ctr=None, *opts)

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)

Source code in pivpy/compute_funcs.py
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
def surfheight(
    dr: xr.Dataset | list[xr.Dataset],
    h0: float,
    H: float = np.inf,
    n: float = 1.33,
    ctr: ArrayLike | None = None,
    *opts: str,
) -> xr.Dataset | list[xr.Dataset]:
    """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)
    """

    h0 = float(h0)
    H = float(H)
    n = float(n)
    opts_l = {str(o).lower() for o in opts}
    submean = any(o.startswith("subm") for o in opts_l)
    nosetzero = any(o.startswith("nose") for o in opts_l)
    remap = any(o.startswith("rema") for o in opts_l)

    def _integrate_grad_fft(dhdx: np.ndarray, dhdy: np.ndarray, dx: float, dy: float) -> np.ndarray:
        # Solve Laplacian(h) = d/dx dhdx + d/dy dhdy in Fourier space.
        ny, nx = dhdx.shape
        kx = 2.0 * np.pi * np.fft.fftfreq(nx, d=dx)
        ky = 2.0 * np.pi * np.fft.fftfreq(ny, d=dy)
        kx2d, ky2d = np.meshgrid(kx, ky)
        denom = kx2d * kx2d + ky2d * ky2d

        F = np.fft.fft2(dhdx)
        G = np.fft.fft2(dhdy)
        rhs = 1j * kx2d * F + 1j * ky2d * G
        Hhat = np.zeros_like(rhs)
        mask = denom != 0
        Hhat[mask] = -rhs[mask] / denom[mask]
        h = np.fft.ifft2(Hhat).real
        return h

    out_fields: list[xr.Dataset] = []
    for ds in _as_field_list(dr):
        if not _is_vector(ds):
            raise ValueError("surfheight expects a vector dataset with variables 'u' and 'v' (displacements)")

        x = np.asarray(ds["x"].values, dtype=float)
        y = np.asarray(ds["y"].values, dtype=float)
        dx = abs(float(x[1] - x[0])) if x.size >= 2 else 1.0
        dy = abs(float(y[1] - y[0])) if y.size >= 2 else 1.0

        if ctr is None:
            ctrx = float(np.mean(x))
            ctry = float(np.mean(y))
        else:
            cc = np.asarray(ctr, dtype=float).ravel()
            ctrx, ctry = float(cc[0]), float(cc[1])

        alpha = 1.0 - 1.0 / n
        factor = 1.0 / H - 1.0 / (alpha * h0)

        out = ds.isel(t=[0]).copy(deep=True)
        out = out.drop_vars([v for v in out.data_vars if v not in {"u", "v", "chc"}], errors="ignore")

        # Subtract mean displacement if requested.
        u = np.asarray(ds["u"].isel(t=0).values, dtype=float)
        v = np.asarray(ds["v"].isel(t=0).values, dtype=float)
        if submean:
            u = u - float(np.mean(u))
            v = v - float(np.mean(v))

        dhdx = u * factor
        dhdy = v * factor

        if remap:
            if _sp_griddata is None:
                raise ImportError("surfheight(...,'remap') requires SciPy (scipy.interpolate.griddata)")
            yy, xx = np.meshgrid(y, x, indexing="ij")
            xxmes = (1.0 - h0 / H) * (xx + u - ctrx) + ctrx
            yymes = (1.0 - h0 / H) * (yy + v - ctry) + ctry
            pts = np.column_stack([xxmes.ravel(), yymes.ravel()])
            grid = (xx.ravel(), yy.ravel())
            dhdx = _sp_griddata(pts, dhdx.ravel(), grid, method="cubic").reshape(dhdx.shape)
            dhdy = _sp_griddata(pts, dhdy.ravel(), grid, method="cubic").reshape(dhdy.shape)
            dhdx = np.nan_to_num(dhdx, nan=0.0)
            dhdy = np.nan_to_num(dhdy, nan=0.0)

        h = _integrate_grad_fft(dhdx, dhdy, dx=dx, dy=dy)
        if not nosetzero:
            h = h - float(np.mean(h)) + h0

        # Return scalar dataset with 'w'
        out = out.drop_vars(["u", "v"], errors="ignore")
        out["w"] = xr.DataArray(h[:, :, None], dims=("y", "x", "t"), attrs={"units": ds["x"].attrs.get("units", ""), "standard_name": "height"})
        out.attrs = dict(ds.attrs)
        out_fields.append(_with_history(out, f"surfheight(ans,{h0},{H},{n})"))

    return out_fields if isinstance(dr, list) else out_fields[0]

taylor_microscale(ds, component='u', dim='x', method='curvature')

Estimates the Taylor microscale lambda_T from velocity fluctuations.

Parameters:

Name Type Description Default
ds Dataset

PIV velocity dataset.

required
component ('u', 'v')

Velocity component (default 'u').

'u'
dim ('x', 'y')

Spatial dimension (default 'x').

'x'
method ('curvature', 'parabolic', 'gradient')
  • 'curvature' / 'parabolic': Fits osculating parabola :math:R(r) \approx 1 - (r/\lambda_T)^2 at :math:r \to 0.
  • 'gradient': Uses definition :math:\lambda_T = \sqrt{\langle u'^2 \rangle / \langle (\partial u'/\partial x)^2 \rangle}.
'curvature'

Returns:

Type Description
float

Taylor microscale lambda_T in physical length units.

Source code in pivpy/compute_funcs.py
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
def taylor_microscale(
    ds: xr.Dataset,
    component: str = "u",
    dim: str = "x",
    method: str = "curvature",
) -> float:
    r"""Estimates the Taylor microscale lambda_T from velocity fluctuations.

    Parameters
    ----------
    ds : xr.Dataset
        PIV velocity dataset.
    component : {'u', 'v'}
        Velocity component (default 'u').
    dim : {'x', 'y'}
        Spatial dimension (default 'x').
    method : {'curvature', 'parabolic', 'gradient'}
        - ``'curvature'`` / ``'parabolic'``: Fits osculating parabola :math:`R(r) \approx 1 - (r/\lambda_T)^2` at :math:`r \to 0`.
        - ``'gradient'``: Uses definition :math:`\lambda_T = \sqrt{\langle u'^2 \rangle / \langle (\partial u'/\partial x)^2 \rangle}`.

    Returns
    -------
    float
        Taylor microscale lambda_T in physical length units.
    """
    m = str(method).lower()
    comp = str(component).lower()

    if m.startswith("grad"):
        val = ds[comp]
        has_t = "t" in ds.dims and ds.sizes["t"] > 1
        u_prime = val - val.mean(dim="t") if has_t else val - val.mean()
        grad = u_prime.differentiate(dim)
        var_fluc = float((u_prime**2).mean().values)
        var_grad = float((grad**2).mean().values)
        return float(np.sqrt(var_fluc / max(1e-12, var_grad)))

    # Default: Curvature at origin via spatial correlation
    corr_ds = spatial_correlation(ds, component=component, dim=dim, normalize=True)
    r = corr_ds["r"].values
    R = corr_ds["R"].values

    if len(r) < 2:
        return 0.0

    # Fit R(r) = 1 - a * r^2 using first points
    r1 = float(r[1])
    R1 = float(R[1])
    diff = max(1e-12, 1.0 - R1)
    lambda_T = r1 / np.sqrt(diff)
    return float(lambda_T)

tempcorrf(ds, *, variables=None, opt='', normalize=False)

Temporal correlation function of vector or scalar fields (PIVMAT-inspired).

For a scalar field w(t), computes a time-lag correlation C(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:

Name Type Description Default
ds Dataset

Input dataset with time dimension t.

required
variables list[str] | None

Variables to include. If None, defaults to ['u','v'] when both present, otherwise ['w'] if present.

None
opt str

If opt contains '0', zeros are included as valid values. Otherwise (default), zeros are treated as missing and ignored.

''
normalize bool

If True, normalizes by the zero-lag value so that C(0)=1.

False

Returns:

Type Description
Dataset

Dataset with coords t (lag, integer) and variable f.

Source code in pivpy/compute_funcs.py
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
def tempcorrf(
    ds: xr.Dataset,
    *,
    variables: list[str] | None = None,
    opt: str = "",
    normalize: bool = False,
) -> xr.Dataset:
    """Temporal correlation function of vector or scalar fields (PIVMAT-inspired).

    For a scalar field ``w(t)``, computes a time-lag correlation
    ``C(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
    -------
    xarray.Dataset
        Dataset with coords ``t`` (lag, integer) and variable ``f``.
    """

    if "t" not in ds.dims:
        raise ValueError("tempcorrf requires a time dimension 't'")

    if variables is None:
        if "u" in ds and "v" in ds:
            variables = ["u", "v"]
        elif "w" in ds:
            variables = ["w"]
        else:
            if not ds.data_vars:
                raise ValueError("tempcorrf: dataset has no data variables")
            variables = [next(iter(ds.data_vars))]

    variables = list(variables)
    for name in variables:
        if name not in ds:
            raise KeyError(f"Variable '{name}' not found in dataset")

    include_zeros = "0" in str(opt).lower()

    n = int(ds.sizes.get("t", 0) or 0)
    if n <= 0:
        raise ValueError("Empty time dimension")

    lags = np.arange(n, dtype=int)
    cor = np.zeros(n, dtype=float)

    # Compute correlation per lag, summing over variables.
    # IMPORTANT: use NumPy arrays to avoid xarray coordinate alignment when
    # multiplying time-shifted views (isel preserves time coordinates).
    for k in range(n):
        num_total = 0.0
        den_total = 0.0
        for name in variables:
            da = ds[name]
            a0 = np.asarray(da.isel(t=slice(0, n - k)).data, dtype=float)
            a1 = np.asarray(da.isel(t=slice(k, n)).data, dtype=float)

            finite = np.isfinite(a0) & np.isfinite(a1)
            if not include_zeros:
                finite &= (a0 != 0.0) & (a1 != 0.0)

            prod = a0 * a1
            num = float(np.nansum(np.where(finite, prod, np.nan)))
            den = float(np.sum(finite))
            num_total += num
            den_total += den

        cor[k] = (num_total / den_total) if den_total > 0 else np.nan

    if normalize:
        c0 = cor[0]
        if np.isfinite(c0) and c0 != 0.0:
            cor = cor / c0
        else:
            cor = cor * np.nan

    out = xr.Dataset(
        {
            "f": ("t", cor),
        },
        coords={"t": lags.astype(float)},
    )
    out["t"].attrs["long_name"] = "time lag"
    out.attrs = dict(ds.attrs)
    return out

tempfilterf(v, indexpos, *opts)

Fourier temporal filter of a vector/scalar time series (PIVMAT-compatible).

Port of PIVMAT's tempfilterf.m.

Parameters:

Name Type Description Default
indexpos ArrayLike

Integer frequency index/indices (PIVMAT/Matlab 1-based indexing into FFT bins).

required
Options
  • 'remove': remove specified indices instead of keeping them
  • 'complex': keep only positive frequencies (output may be complex)
  • 'phaseaverf': for single frequency index, phase-average one period
Source code in pivpy/compute_funcs.py
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
def tempfilterf(v: xr.Dataset, indexpos: ArrayLike, *opts: str) -> xr.Dataset:
    """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': remove specified indices instead of keeping them
    - 'complex': keep only positive frequencies (output may be complex)
    - 'phaseaverf': for single frequency index, phase-average one period
    """

    if "t" not in v.dims:
        raise ValueError("tempfilterf requires a time dimension 't'")

    nt = int(v.sizes["t"])
    if nt <= 0:
        raise ValueError("Empty time dimension")

    idx = np.asarray(indexpos, dtype=int).ravel()
    if idx.size == 0:
        raise ValueError("indexpos must be non-empty")
    if np.any(idx < 1) or np.any(idx > nt):
        raise ValueError("indexpos values must be in [1, len(t)]")

    opts_l = {str(o).lower() for o in opts}
    complex_mode = any(o.startswith("comp") for o in opts_l)
    remove = any(o.startswith("rem") for o in opts_l)

    idx0 = (idx - 1).astype(int)
    mask = np.zeros(nt, dtype=bool)
    if complex_mode:
        mask[idx0] = True
    else:
        neg = (-idx0) % nt
        mask[idx0] = True
        mask[neg] = True
    if remove:
        mask = ~mask

    def _filt(a: np.ndarray) -> np.ndarray:
        A = np.fft.fft(a, axis=2)
        A *= mask[None, None, :]
        out = np.fft.ifft(A, axis=2)
        return out if complex_mode else out.real

    out = v.copy(deep=True)
    if _is_vector(out):
        out["u"] = xr.DataArray(_filt(np.asarray(v["u"].values)), dims=("y", "x", "t"), attrs=v["u"].attrs)
        out["v"] = xr.DataArray(_filt(np.asarray(v["v"].values)), dims=("y", "x", "t"), attrs=v["v"].attrs)
    elif _is_scalar(out):
        out["w"] = xr.DataArray(_filt(np.asarray(v["w"].values)), dims=("y", "x", "t"), attrs=v["w"].attrs)
    else:
        raise ValueError("tempfilterf expects a vector (u,v) or scalar (w) Dataset")

    # Phase average option for a single index.
    if any(o.startswith("phase") for o in opts_l):
        if idx.size != 1:
            raise ValueError("Option 'phaseaverf' works only with a scalar frequency index")
        period = float(nt) / float(idx[0] - 1) if idx[0] > 1 else float(nt)
        out = out.piv.phaseaverf(period)  # type: ignore[attr-defined]

        if complex_mode:
            omega = 2.0 * np.pi / period
            t = np.arange(out.sizes["t"], dtype=float)
            ph = np.exp(-1j * omega * t)
            if _is_vector(out):
                out["u"] = out["u"] * xr.DataArray(ph, dims=("t",))
                out["v"] = out["v"] * xr.DataArray(ph, dims=("t",))
                out = out.isel(t=[0]).copy(deep=True)
                out["u"] = out["u"].mean(dim="t")
                out["v"] = out["v"].mean(dim="t")
            else:
                out["w"] = out["w"] * xr.DataArray(ph, dims=("t",))
                out = out.isel(t=[0]).copy(deep=True)
                out["w"] = out["w"].mean(dim="t")

    return _with_history(out, f"tempfilterf(ans, {idx.tolist()})")

tempspecf(v, freq=1.0, *opts)

Temporal power spectrum averaged over space (PIVMAT-inspired).

Source code in pivpy/compute_funcs.py
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
def tempspecf(v: xr.Dataset | xr.DataArray, freq: float = 1.0, *opts: str) -> xr.Dataset:
    """Temporal power spectrum averaged over space (PIVMAT-inspired)."""

    if isinstance(v, xr.Dataset):
        if "t" not in v.dims:
            raise ValueError("tempspecf expects a time series Dataset with dim 't'")
        is_vector = ("u" in v and "v" in v)
        is_scalar = ("w" in v) and not is_vector
    else:
        if "t" not in v.dims:
            raise ValueError("tempspecf expects a DataArray with dim 't'")
        is_vector = False
        is_scalar = True

    if int(v.sizes["t"]) < 4:
        raise ValueError("Sample size too small")

    use_hann = any(str(o).lower().startswith("hann") for o in opts)
    include_zero = any(str(o).lower().startswith("zero") for o in opts)
    doublex = any(str(o).lower().startswith("doublex") for o in opts)
    doubley = any(str(o).lower().startswith("doubley") for o in opts)

    nt = int(v.sizes["t"])
    # match PIVMAT: length floor(nt/2) (exclude DC)
    nfreq = nt // 2
    f_hz = (np.arange(1, nfreq + 1, dtype=float) * float(freq) / float(nt))
    w = 2.0 * np.pi * f_hz
    df = float(freq) / float(nt)

    win = np.ones(nt, dtype=float)
    if use_hann:
        win = _hann(nt)

    def _one_series_psd(x: np.ndarray) -> np.ndarray | None:
        x = np.asarray(x, dtype=float)
        if not include_zero:
            if np.any(x == 0.0) or np.any(~np.isfinite(x)):
                return None
        if np.any(~np.isfinite(x)):
            x = np.nan_to_num(x, nan=0.0)
        x = x - float(np.mean(x))
        x = x * win
        X = np.fft.rfft(x)
        # one-sided density (exclude DC at k=0)
        # Parseval: mean(x^2) ~= sum(S(f))*df
        S = (2.0 * (np.abs(X[1 : nfreq + 1]) ** 2)) / (nt * nt) / df
        # Nyquist term (if present) should not be doubled
        if nt % 2 == 0:
            S[-1] /= 2.0
        return S

    if isinstance(v, xr.Dataset) and is_vector:
        u = np.asarray(v["u"].values, dtype=float)
        vv = np.asarray(v["v"].values, dtype=float)
        # shapes: (y,x,t)
        # iterate all points
        acc = np.zeros(nfreq, dtype=float)
        nnz = 0
        for iy in range(u.shape[0]):
            for ix in range(u.shape[1]):
                su = _one_series_psd(u[iy, ix, :])
                sv = _one_series_psd(vv[iy, ix, :])
                if su is None or sv is None:
                    continue
                if doublex:
                    acc += 2.0 * su + sv
                elif doubley:
                    acc += su + 2.0 * sv
                else:
                    acc += su + sv
                nnz += 1
        etot = acc / float(nnz if nnz else 1)
    else:
        # scalar
        if isinstance(v, xr.Dataset):
            a = np.asarray(v["w"].values, dtype=float)
        else:
            a = np.asarray(v.values, dtype=float)
        acc = np.zeros(nfreq, dtype=float)
        nnz = 0
        for iy in range(a.shape[0]):
            for ix in range(a.shape[1]):
                s = _one_series_psd(a[iy, ix, :])
                if s is None:
                    continue
                acc += s
                nnz += 1
        etot = acc / float(nnz if nnz else 1)

    # Return density vs w (rad/s) to match the signature.
    # Convert from per-Hz to per-(rad/s): E(w) = E(f) / (2*pi)
    etot_w = etot / (2.0 * np.pi)
    return xr.Dataset(data_vars={"e": ("w", etot_w)}, coords={"w": ("w", w)})

timederivativef(f, order=2)

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.

Source code in pivpy/compute_funcs.py
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
def timederivativef(f: xr.Dataset | list[xr.Dataset], order: int = 2) -> xr.Dataset | list[xr.Dataset]:
    r"""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.
    """

    order = int(order)
    if order not in (1, 2):
        raise ValueError("order must be 1 or 2")

    def _diff_arr(a: np.ndarray) -> np.ndarray:
        if a.ndim != 3:
            raise ValueError("Expected arrays with dims (y,x,t)")
        if order == 1:
            return np.diff(a, axis=2)
        # order 2
        out = np.empty_like(a)
        if a.shape[2] == 1:
            out[...] = 0.0
            return out
        out[:, :, 1:-1] = (a[:, :, 2:] - a[:, :, :-2]) / 2.0
        out[:, :, 0] = a[:, :, 1] - a[:, :, 0]
        out[:, :, -1] = a[:, :, -1] - a[:, :, -2]
        return out

    out_list: list[xr.Dataset] = []
    for ds in _as_field_list(f):
        if "t" not in ds.dims:
            raise ValueError("timederivativef requires a time dimension 't'")

        if order == 1:
            out = ds.isel(t=slice(0, -1)).copy(deep=True)
            t_out = np.asarray(ds["t"].values, dtype=float)[:-1]
            out = out.assign_coords(t=("t", t_out))
        else:
            out = ds.copy(deep=True)

        if _is_vector(out):
            out["u"] = xr.DataArray(_diff_arr(np.asarray(ds["u"].values, dtype=float)), dims=("y", "x", "t"), attrs=ds["u"].attrs)
            out["v"] = xr.DataArray(_diff_arr(np.asarray(ds["v"].values, dtype=float)), dims=("y", "x", "t"), attrs=ds["v"].attrs)
        elif _is_scalar(out):
            out["w"] = xr.DataArray(_diff_arr(np.asarray(ds["w"].values, dtype=float)), dims=("y", "x", "t"), attrs=ds["w"].attrs)
        else:
            raise ValueError("timederivativef: expected a vector (u,v) or scalar (w) Dataset")

        out_list.append(_with_history(out, f"timederivativef(ans,{order})"))
    return out_list if isinstance(f, list) else out_list[0]

truncf(f, cut=0.0, *opts)

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

Source code in pivpy/compute_funcs.py
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
def truncf(
    f: xr.Dataset | list[xr.Dataset],
    cut: float | str = 0.0,
    *opts: str,
) -> xr.Dataset | list[xr.Dataset]:
    """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
    """

    # PIVMAT allows calling truncf(f,'nonzero') with the option in place of `cut`.
    if isinstance(cut, str):
        opts = (cut,) + opts
        cut = 0.0

    opts_l = {str(o).lower() for o in opts}

    def _to_mesh_cut(ds: xr.Dataset, c: float) -> int:
        if "phys" not in opts_l:
            return int(round(float(c)))
        x = np.asarray(ds["x"].values, dtype=float)
        dx = abs(float(x[1] - x[0])) if x.size >= 2 else 1.0
        if dx == 0:
            dx = 1.0
        return int(round(float(c) / dx))

    def _nonzero_crop(ds: xr.Dataset) -> xr.Dataset:
        if _is_vector(ds):
            a = np.asarray(ds["u"].values, dtype=float)
            b = np.asarray(ds["v"].values, dtype=float)
            # any nonzero over time
            m = (a != 0) | (b != 0)
        elif _is_scalar(ds):
            w = np.asarray(ds["w"].values, dtype=float)
            m = w != 0
        else:
            raise ValueError("truncf: expected a vector (u,v) or scalar (w) Dataset")
        if m.ndim == 3:
            m2 = np.any(m, axis=2)
        else:
            m2 = m
        rows = np.where(np.any(m2, axis=1))[0]
        cols = np.where(np.any(m2, axis=0))[0]
        if rows.size == 0 or cols.size == 0:
            return ds.isel(y=slice(0, 0), x=slice(0, 0))
        return ds.isel(y=slice(int(rows[0]), int(rows[-1]) + 1), x=slice(int(cols[0]), int(cols[-1]) + 1))

    out_list: list[xr.Dataset] = []
    for ds in _as_field_list(f):
        if "nonzero" in opts_l and float(cut) == 0.0:
            out = _nonzero_crop(ds)
            out_list.append(_with_history(out, "truncf(ans, 'nonzero')"))
            continue

        ny = int(ds.sizes.get("y", 0))
        nx = int(ds.sizes.get("x", 0))
        if ny == 0 or nx == 0:
            out_list.append(ds)
            continue

        cut_m = _to_mesh_cut(ds, cut)
        side = min(nx, ny)
        x0 = (nx - side) // 2
        y0 = (ny - side) // 2
        x1 = x0 + side
        y1 = y0 + side

        x0 += cut_m
        y0 += cut_m
        x1 -= cut_m
        y1 -= cut_m
        x0 = max(0, x0)
        y0 = max(0, y0)
        x1 = min(nx, x1)
        y1 = min(ny, y1)
        if x1 < x0:
            x1 = x0
        if y1 < y0:
            y1 = y0

        out = ds.isel(x=slice(x0, x1), y=slice(y0, y1))
        out_list.append(_with_history(out, f"truncf(ans, {cut}, {opts})"))
    return out_list if isinstance(f, list) else out_list[0]

vorticity_circulation(ds, radius=1, name='w')

Calculates noise-robust vorticity via closed contour circulation integral.

Args: ds (xr.Dataset): Velocity field containing 'u', 'v', 'x', 'y' (and optional 't'). radius (int): Integration loop radius in grid points. Defaults to 1. name (str): Variable name for the output field. Defaults to 'w'.

Returns: xr.Dataset: Dataset with circulation-based vorticity scalar field.

Source code in pivpy/compute_funcs.py
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
def vorticity_circulation(ds: xr.Dataset, radius: int = 1, name: str = "w") -> xr.Dataset:
    """Calculates noise-robust vorticity via closed contour circulation integral.

    Args:
        ds (xr.Dataset): Velocity field containing 'u', 'v', 'x', 'y' (and optional 't').
        radius (int): Integration loop radius in grid points. Defaults to 1.
        name (str): Variable name for the output field. Defaults to 'w'.

    Returns:
        xr.Dataset: Dataset with circulation-based vorticity scalar field.
    """
    warn_if_overwriting_scalar(ds, name)
    out_arr = _apply_2d_slices(ds, _vorticity_circulation_2d, radius=radius)
    out = ds.copy(deep=False)
    dims = ("y", "x", "t") if "t" in ds.dims else ("y", "x")
    out[name] = xr.DataArray(out_arr, dims=dims, coords=ds.coords)
    out[name].attrs["standard_name"] = "vorticity_circulation"
    out[name].attrs["units"] = "1/s"
    out[name].attrs["radius"] = radius
    return out

vsf(v, *opts)

Structure functions of a vector field (PIVMAT-inspired).

Source code in pivpy/compute_funcs.py
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
def vsf(v: xr.Dataset, *opts: str) -> xr.Dataset:
    """Structure functions of a vector field (PIVMAT-inspired)."""

    if "u" not in v or "v" not in v:
        raise ValueError("vsf expects a vector Dataset with variables 'u' and 'v'")

    include_zero = any(str(o) == "0" for o in opts)
    maxorder = 4
    if any(str(o).lower().startswith("maxorder") for o in opts):
        idx = [i for i, o in enumerate(opts) if str(o).lower().startswith("maxorder")][-1]
        try:
            maxorder = max(4, int(opts[idx + 1]))
        except Exception:
            raise ValueError("vsf: expected integer after 'maxorder'")
    if maxorder > 30:
        raise ValueError("Maximum order too large")

    # default bins based on rms of u component
    u0 = v["u"].isel(t=0) if "t" in v.dims else v["u"]
    rms = float(np.nanstd(u0.values))
    bin_centers = None
    if any(str(o).lower().startswith("bin") for o in opts):
        idx = [i for i, o in enumerate(opts) if str(o).lower().startswith("bin")][-1]
        try:
            bin_centers = np.asarray(opts[idx + 1], dtype=float)
        except Exception:
            raise ValueError("vsf: expected a numeric bin vector after 'bin'")
    if bin_centers is None:
        maxbin = 10.0 * rms
        bin_centers = np.linspace(-maxbin, maxbin, 1000)
    binwidth = float(np.abs(bin_centers[1] - bin_centers[0]))
    edges = _bin_centers_to_edges(bin_centers)

    r_list = None
    if any(str(o).lower() == "r" for o in opts):
        idx = [i for i, o in enumerate(opts) if str(o).lower() == "r"][-1]
        r_list = np.asarray(opts[idx + 1], dtype=int)
    if r_list is None:
        default_r = np.asarray(
            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 26, 28, 30, 32, 36, 40, 44, 48, 52, 56, 60, 64, 72, 80, 96, 112, 128, 142, 160, 176, 192, 224, 256],
            dtype=int,
        )
        maxdr = min(int(v.sizes["x"]), int(v.sizes["y"]))
        r_list = default_r[default_r < maxdr]

    frames = _as_frames(v)
    hlvi = np.zeros((r_list.size, bin_centers.size), dtype=float)
    htvi = np.zeros((r_list.size, bin_centers.size), dtype=float)

    for fr in frames:
        assert isinstance(fr, xr.Dataset)
        u = np.asarray(fr["u"].values, dtype=float)
        w = np.asarray(fr["v"].values, dtype=float)
        ny, nx = u.shape
        for ir, rr in enumerate(r_list):
            # along x: longitudinal uses u, transverse uses v
            if rr < nx:
                dvlx = u[:, rr:] - u[:, : nx - rr]
                dvty = w[:, rr:] - w[:, : nx - rr]
                if not include_zero:
                    vmask = (u[:, rr:] != 0) & (u[:, : nx - rr] != 0)
                    tmask = (w[:, rr:] != 0) & (w[:, : nx - rr] != 0)
                    dvlx = np.where(vmask, dvlx, 0.0)
                    dvty = np.where(tmask, dvty, 0.0)
                vals_lx = dvlx.ravel()
                vals_ty = dvty.ravel()
                vals_lx = vals_lx[(vals_lx != 0.0) & np.isfinite(vals_lx)]
                vals_ty = vals_ty[(vals_ty != 0.0) & np.isfinite(vals_ty)]
                if vals_lx.size:
                    h, _ = np.histogram(vals_lx, bins=edges)
                    hlvi[ir, :] += h
                if vals_ty.size:
                    h, _ = np.histogram(vals_ty, bins=edges)
                    htvi[ir, :] += h

            # along y: longitudinal uses v, transverse uses -u
            if rr < ny:
                dvly = w[rr:, :] - w[: ny - rr, :]
                dvtx = -u[rr:, :] + u[: ny - rr, :]
                if not include_zero:
                    lmask = (w[rr:, :] != 0) & (w[: ny - rr, :] != 0)
                    tmask = (u[rr:, :] != 0) & (u[: ny - rr, :] != 0)
                    dvly = np.where(lmask, dvly, 0.0)
                    dvtx = np.where(tmask, dvtx, 0.0)
                vals_ly = dvly.ravel()
                vals_tx = dvtx.ravel()
                vals_ly = vals_ly[(vals_ly != 0.0) & np.isfinite(vals_ly)]
                vals_tx = vals_tx[(vals_tx != 0.0) & np.isfinite(vals_tx)]
                if vals_ly.size:
                    h, _ = np.histogram(vals_ly, bins=edges)
                    hlvi[ir, :] += h
                if vals_tx.size:
                    h, _ = np.histogram(vals_tx, bins=edges)
                    htvi[ir, :] += h

    pdflvi = np.zeros_like(hlvi)
    pdftvi = np.zeros_like(htvi)
    lsf = np.zeros((r_list.size, maxorder), dtype=float)
    tsf = np.zeros((r_list.size, maxorder), dtype=float)
    lsfabs = np.zeros((r_list.size, maxorder), dtype=float)
    tsfabs = np.zeros((r_list.size, maxorder), dtype=float)
    skew_long = np.zeros(r_list.size, dtype=float)
    skew_trans = np.zeros(r_list.size, dtype=float)
    flat_long = np.zeros(r_list.size, dtype=float)
    flat_trans = np.zeros(r_list.size, dtype=float)
    n_l = np.zeros(r_list.size, dtype=float)
    n_t = np.zeros(r_list.size, dtype=float)

    # centered structure functions (PIVMAT default)
    for ir in range(r_list.size):
        nl = float(np.sum(hlvi[ir, :]))
        nt = float(np.sum(htvi[ir, :]))
        n_l[ir] = nl
        n_t[ir] = nt
        if nl > 0:
            pdflvi[ir, :] = hlvi[ir, :] / (nl * binwidth)
        if nt > 0:
            pdftvi[ir, :] = htvi[ir, :] / (nt * binwidth)

        meanl = float(np.sum(pdflvi[ir, :] * bin_centers) * binwidth)
        meant = float(np.sum(pdftvi[ir, :] * bin_centers) * binwidth)
        for order in range(1, maxorder + 1):
            lsf[ir, order - 1] = float(np.sum(pdflvi[ir, :] * ((bin_centers - meanl) ** order)) * binwidth)
            tsf[ir, order - 1] = float(np.sum(pdftvi[ir, :] * ((bin_centers - meant) ** order)) * binwidth)
            lsfabs[ir, order - 1] = float(np.sum(pdflvi[ir, :] * (np.abs(bin_centers - meanl) ** order)) * binwidth)
            tsfabs[ir, order - 1] = float(np.sum(pdftvi[ir, :] * (np.abs(bin_centers - meant) ** order)) * binwidth)

        if lsf[ir, 1] != 0:
            skew_long[ir] = lsf[ir, 2] / (lsf[ir, 1] ** 1.5)
            flat_long[ir] = lsf[ir, 3] / (lsf[ir, 1] ** 2)
        if tsf[ir, 1] != 0:
            skew_trans[ir] = tsf[ir, 2] / (tsf[ir, 1] ** 1.5)
            flat_trans[ir] = tsf[ir, 3] / (tsf[ir, 1] ** 2)

    scaler = float(np.abs(v["x"].values[1] - v["x"].values[0])) if v["x"].size >= 2 else 1.0

    return xr.Dataset(
        data_vars={
            "hlvi": (("r", "bin"), hlvi),
            "htvi": (("r", "bin"), htvi),
            "pdflvi": (("r", "bin"), pdflvi),
            "pdftvi": (("r", "bin"), pdftvi),
            "lsf": (("r", "order"), lsf),
            "tsf": (("r", "order"), tsf),
            "lsfabs": (("r", "order"), lsfabs),
            "tsfabs": (("r", "order"), tsfabs),
            "skew_long": ("r", skew_long),
            "skew_trans": ("r", skew_trans),
            "flat_long": ("r", flat_long),
            "flat_trans": ("r", flat_trans),
            "n_long": ("r", n_l),
            "n_trans": ("r", n_t),
        },
        coords={
            "r": ("r", r_list.astype(float)),
            "bin": ("bin", bin_centers),
            "order": ("order", np.arange(1, maxorder + 1, dtype=int)),
        },
        attrs={"scaler": scaler, "binwidth": binwidth},
    )

warn_if_overwriting_scalar(ds, name)

Warn when a scalar-producing accessor method (vorticity, strain, ...) is about to silently overwrite an existing variable of the same name.

All such methods default to name="w", so calling more than one without an explicit name= silently discards the previous result -- this doesn't change that default (kept for backward compatibility), it just makes the footgun visible instead of silent.

Source code in pivpy/compute_funcs.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def warn_if_overwriting_scalar(ds: xr.Dataset, name: str) -> None:
    """Warn when a scalar-producing accessor method (vorticity, strain, ...)
    is about to silently overwrite an existing variable of the same name.

    All such methods default to name="w", so calling more than one without
    an explicit name= silently discards the previous result -- this doesn't
    change that default (kept for backward compatibility), it just makes the
    footgun visible instead of silent.
    """
    if name in ds.data_vars:
        warnings.warn(
            f"piv accessor: '{name}' already exists in this dataset and will "
            f"be overwritten. Pass a different name= to keep both fields "
            f"(e.g. name='{name}2').",
            UserWarning,
            stacklevel=3,
        )

zeropadf(f)

Zero-pad a rectangular field to a square (PIVMAT-compatible).

Source code in pivpy/compute_funcs.py
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
def zeropadf(f: xr.Dataset | list[xr.Dataset]) -> xr.Dataset | list[xr.Dataset]:
    """Zero-pad a rectangular field to a square (PIVMAT-compatible)."""

    def _pad(ds: xr.Dataset) -> xr.Dataset:
        ny = int(ds.sizes.get("y", 0))
        nx = int(ds.sizes.get("x", 0))
        if nx == ny:
            return ds
        x = np.asarray(ds["x"].values, dtype=float)
        y = np.asarray(ds["y"].values, dtype=float)
        dx = float(x[1] - x[0]) if x.size >= 2 else 1.0
        dy = float(y[1] - y[0]) if y.size >= 2 else 1.0

        out = ds.copy(deep=True)
        if nx > ny:
            pad = nx - ny
            y_new = y[0] + dy * np.arange(nx, dtype=float)
            out = out.reindex(y=y_new, fill_value=0.0)
        else:
            pad = ny - nx
            x_new = x[0] + dx * np.arange(ny, dtype=float)
            out = out.reindex(x=x_new, fill_value=0.0)
        return out

    out_list: list[xr.Dataset] = []
    for ds in _as_field_list(f):
        out_list.append(_with_history(_pad(ds), "zeropadf(ans)"))
    return out_list if isinstance(f, list) else out_list[0]

zerotonanfield(f)

Convert 0 elements to NaNs in fields (PIVMAT-compatible).

Source code in pivpy/compute_funcs.py
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
def zerotonanfield(f: xr.Dataset | list[xr.Dataset]) -> xr.Dataset | list[xr.Dataset]:
    """Convert 0 elements to NaNs in fields (PIVMAT-compatible)."""

    out_list: list[xr.Dataset] = []
    for ds in _as_field_list(f):
        out = ds.copy(deep=True)
        if _is_vector(out):
            out["u"] = out["u"].where(out["u"] != 0)
            out["v"] = out["v"].where(out["v"] != 0)
        elif _is_scalar(out):
            out["w"] = out["w"].where(out["w"] != 0)
        else:
            raise ValueError("zerotonanfield: expected a vector (u,v) or scalar (w) Dataset")
        out_list.append(_with_history(out, "zerotonanfield(ans)"))
    return out_list if isinstance(f, list) else out_list[0]

Γ1_moving_window_function(fWin, n)

Legacy moving-window function for Γ1 calculation.

Source code in pivpy/compute_funcs.py
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
def Γ1_moving_window_function(
        fWin: xr.Dataset,
        n: int,
) -> xr.DataArray:
    """Legacy moving-window function for Γ1 calculation."""
    xcoords = fWin.get('xCoordinates', fWin.get('x'))
    ycoords = fWin.get('yCoordinates', fWin.get('y'))

    def _center_scalar(arr: xr.DataArray) -> float:
        if arr is None:
            return 0.0
        if 'rollWx' in arr.dims and 'rollWy' in arr.dims:
            sel = arr.isel(rollWx=n, rollWy=n)
        elif len(arr.dims) >= 2:
            sel = arr.isel({arr.dims[0]: min(n, arr.shape[0]-1), arr.dims[1]: min(n, arr.shape[1]-1)})
        else:
            sel = arr
        for d in list(sel.dims):
            sel = sel.isel({d: 0})
        return float(np.asarray(sel.values).reshape(-1)[0])

    cx = _center_scalar(xcoords)
    cy = _center_scalar(ycoords)

    PMx = np.subtract(np.asarray(xcoords.to_numpy(), dtype=float), cx) if xcoords is not None else 0.0
    PMy = np.subtract(np.asarray(ycoords.to_numpy(), dtype=float), cy) if ycoords is not None else 0.0
    u = np.asarray(fWin['u'].to_numpy(), dtype=float)
    v = np.asarray(fWin['v'].to_numpy(), dtype=float)

    num = PMx * v - PMy * u
    denom = np.hypot(PMx, PMy) * np.hypot(u, v)
    with np.errstate(divide='ignore', invalid='ignore'):
        values = np.divide(
            num,
            denom,
            out=np.full_like(num, np.nan, dtype=float),
            where=(denom != 0),
        )

    valid = np.isfinite(values)
    val = float(values[valid].mean()) if np.any(valid) else 0.0
    return xr.DataArray(val).fillna(0.0)

Γ2_moving_window_function(fWin, n)

Legacy moving-window function for Γ2 calculation.

Source code in pivpy/compute_funcs.py
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
def Γ2_moving_window_function(
        fWin: xr.Dataset,
        n: int,
) -> xr.DataArray:
    """Legacy moving-window function for Γ2 calculation."""
    xcoords = fWin.get('xCoordinates', fWin.get('x'))
    ycoords = fWin.get('yCoordinates', fWin.get('y'))

    def _center_scalar(arr: xr.DataArray) -> float:
        if arr is None:
            return 0.0
        if 'rollWx' in arr.dims and 'rollWy' in arr.dims:
            sel = arr.isel(rollWx=n, rollWy=n)
        elif len(arr.dims) >= 2:
            sel = arr.isel({arr.dims[0]: min(n, arr.shape[0]-1), arr.dims[1]: min(n, arr.shape[1]-1)})
        else:
            sel = arr
        for d in list(sel.dims):
            sel = sel.isel({d: 0})
        return float(np.asarray(sel.values).reshape(-1)[0])

    cx = _center_scalar(xcoords)
    cy = _center_scalar(ycoords)

    PMx = np.subtract(np.asarray(xcoords.to_numpy(), dtype=float), cx) if xcoords is not None else 0.0
    PMy = np.subtract(np.asarray(ycoords.to_numpy(), dtype=float), cy) if ycoords is not None else 0.0
    u = np.asarray(fWin['u'].to_numpy(), dtype=float)
    v = np.asarray(fWin['v'].to_numpy(), dtype=float)

    finite_u = np.isfinite(u)
    finite_v = np.isfinite(v)
    u_mean = float(u[finite_u].mean()) if np.any(finite_u) else 0.0
    v_mean = float(v[finite_v].mean()) if np.any(finite_v) else 0.0
    uDif = u - u_mean
    vDif = v - v_mean

    num = PMx * vDif - PMy * uDif
    denom = np.hypot(PMx, PMy) * np.hypot(uDif, vDif)
    with np.errstate(divide='ignore', invalid='ignore'):
        values = np.divide(
            num,
            denom,
            out=np.full_like(num, np.nan, dtype=float),
            where=(denom != 0),
        )

    valid = np.isfinite(values)
    val = float(values[valid].mean()) if np.any(valid) else 0.0
    return xr.DataArray(val).fillna(0.0)

pivpy.pivmat_compat

expandstr(pattern)

Expand indexed bracket strings (PIVMAT-compatible subset).

Port of PIVMAT's expandstr.m with 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.
Source code in pivpy/pivmat_compat.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def expandstr(pattern: str) -> list[str]:
    """Expand indexed bracket strings (PIVMAT-compatible subset).

    Port of PIVMAT's ``expandstr.m`` with 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.
    """

    spec = _split_first_bracket(str(pattern))
    if spec is None:
        return [str(pattern)]

    nums = _parse_range_expr(spec.expr)
    out = [f"{spec.prefix}{spec.fmt.format(v)}{spec.suffix}" for v in nums]

    # Recurse if there are remaining brackets in the suffix.
    if "[" in spec.suffix:
        expanded: list[str] = []
        for s in out:
            expanded.extend(expandstr(s))
        return expanded

    return out

multivortex(n_frames=1, n=128, n_vortices=8, two_d=True, asym=False, dx=1.0, dy=1.0, seed=None)

Generate 2D synthetic turbulence fields composed of multiple random Burgers vortices.

Parameters:

Name Type Description Default
n_frames int

Number of time frames to generate (default 1).

1
n int or tuple of (rows, cols)

Grid dimension (default 128).

128
n_vortices int

Average number of vortices per frame (default 8).

8
two_d bool

If True, enforces 2D zero-divergence (gamma = 0). Default True.

True
asym bool

If True, generates only positive vorticity (cyclonic). Default False.

False
dx float

Grid spacing (default 1.0).

1.0
dy float

Grid spacing (default 1.0).

1.0
seed int

Random seed for reproducible realizations.

None

Returns:

Type Description
Dataset

Canonical PIVPy dataset with multi-frame turbulent flow field.

Source code in pivpy/synthetic.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def multivortex(
    n_frames: int = 1,
    n: Union[int, Tuple[int, int]] = 128,
    n_vortices: int = 8,
    two_d: bool = True,
    asym: bool = False,
    dx: float = 1.0,
    dy: float = 1.0,
    seed: Optional[int] = None,
) -> xr.Dataset:
    """Generate 2D synthetic turbulence fields composed of multiple random Burgers vortices.

    Parameters
    ----------
    n_frames : int
        Number of time frames to generate (default 1).
    n : int or tuple of (rows, cols)
        Grid dimension (default 128).
    n_vortices : int
        Average number of vortices per frame (default 8).
    two_d : bool
        If True, enforces 2D zero-divergence (gamma = 0). Default True.
    asym : bool
        If True, generates only positive vorticity (cyclonic). Default False.
    dx, dy : float
        Grid spacing (default 1.0).
    seed : int, optional
        Random seed for reproducible realizations.

    Returns
    -------
    xr.Dataset
        Canonical PIVPy dataset with multi-frame turbulent flow field.
    """
    if isinstance(n, int):
        rows, cols = n, n
    else:
        rows, cols = n

    rng = np.random.default_rng(seed)
    x_coords = np.arange(cols, dtype=float) * dx
    y_coords = np.arange(rows, dtype=float) * dy
    x2d, y2d = np.meshgrid(x_coords, y_coords)

    domain_w = float(x_coords[-1] - x_coords[0])
    domain_h = float(y_coords[-1] - y_coords[0])
    diag = np.sqrt(domain_w**2 + domain_h**2)

    n_total_vortices = int(np.ceil(n_vortices * 9))
    frames = []

    for t_idx in range(n_frames):
        u_frame = np.zeros((rows, cols), dtype=float)
        v_frame = np.zeros((rows, cols), dtype=float)

        xc = x_coords[0] + domain_w * (3.0 * rng.random(n_total_vortices) - 1.0)
        yc = y_coords[0] + domain_h * (3.0 * rng.random(n_total_vortices) - 1.0)

        omega = rng.choice([-1.0, 1.0], size=n_total_vortices) * (2.0 + rng.standard_normal(n_total_vortices))
        if asym:
            omega = np.abs(omega)

        div = np.zeros(n_total_vortices, dtype=float) if two_d else 0.5 * rng.standard_normal(n_total_vortices)
        core = 0.015 * (4.0 + rng.standard_normal(n_total_vortices)) * diag
        core = np.maximum(core, 2.0 * min(dx, dy))

        for k in range(n_total_vortices):
            rx = x2d - xc[k]
            ry = y2d - yc[k]
            r2 = rx**2 + ry**2
            safe_r2 = np.where(r2 == 0.0, 1e-12, r2)
            c2 = core[k] ** 2

            decay = (1.0 - np.exp(-r2 / c2)) / safe_r2
            ampl_rot = omega[k] * c2 / 2.0 * decay
            ampl_div = div[k] * c2 / 2.0 * decay

            u_frame += -ampl_rot * ry + ampl_div * rx
            v_frame += ampl_rot * rx + ampl_div * ry

        chc_frame = np.ones_like(u_frame, dtype=float)
        ds_t = build_dataset(
            x=x_coords,
            y=y_coords,
            t=np.array([float(t_idx)], dtype=float),
            u=u_frame[:, :, np.newaxis],
            v=v_frame[:, :, np.newaxis],
            chc=chc_frame[:, :, np.newaxis],
            delta_t=float(DELTA_T),
        )
        frames.append(ds_t)

    ds = xr.concat(frames, dim="t") if len(frames) > 1 else frames[0]
    ds.attrs["flow_model"] = "multivortex"
    return ds

randvec(n=128, n_frames=1, slope=5.0 / 3.0, nc=3.0, nl=None, dx=1.0, dy=1.0, seed=None)

Generate divergence-free 2D random velocity fields with prescribed power spectrum.

Parameters:

Name Type Description Default
n int or tuple of (rows, cols)

Grid dimension (default 128).

128
n_frames int

Number of independent realization frames along 't' (default 1).

1
slope float

Spectral decay exponent $E(k) \propto k^{-\text{slope}}$ (default 5/3).

5.0 / 3.0
nc float

Small scale cutoff in grid units (default 3.0).

3.0
nl float

Large scale cutoff in grid units. Default is n/3.

None
dx float

Grid spacing (default 1.0).

1.0
dy float

Grid spacing (default 1.0).

1.0
seed int

Random seed for reproducibility.

None

Returns:

Type Description
Dataset

Canonical PIVPy dataset with divergence-free random velocity fields.

Source code in pivpy/synthetic.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
def randvec(
    n: Union[int, Tuple[int, int]] = 128,
    n_frames: int = 1,
    slope: float = 5.0 / 3.0,
    nc: float = 3.0,
    nl: Optional[float] = None,
    dx: float = 1.0,
    dy: float = 1.0,
    seed: Optional[int] = None,
) -> xr.Dataset:
    """Generate divergence-free 2D random velocity fields with prescribed power spectrum.

    Parameters
    ----------
    n : int or tuple of (rows, cols)
        Grid dimension (default 128).
    n_frames : int
        Number of independent realization frames along 't' (default 1).
    slope : float
        Spectral decay exponent $E(k) \\propto k^{-\\text{slope}}$ (default 5/3).
    nc : float
        Small scale cutoff in grid units (default 3.0).
    nl : float, optional
        Large scale cutoff in grid units. Default is n/3.
    dx, dy : float
        Grid spacing (default 1.0).
    seed : int, optional
        Random seed for reproducibility.

    Returns
    -------
    xr.Dataset
        Canonical PIVPy dataset with divergence-free random velocity fields.
    """
    if isinstance(n, int):
        rows, cols = n, n
    else:
        rows, cols = n

    if nl is None:
        nl = float(min(rows, cols)) / 3.0

    rng = np.random.default_rng(seed)
    x_coords = np.arange(cols, dtype=float) * dx
    y_coords = np.arange(rows, dtype=float) * dy

    kx = np.fft.fftfreq(cols, d=dx) * 2.0 * np.pi
    ky = np.fft.fftfreq(rows, d=dy) * 2.0 * np.pi
    kx_2d, ky_2d = np.meshgrid(kx, ky)
    k_mag = np.sqrt(kx_2d**2 + ky_2d**2)
    safe_k = np.where(k_mag == 0.0, 1.0, k_mag)

    k_c = 2.0 * np.pi / (nc * max(dx, dy))
    k_l = 2.0 * np.pi / (nl * min(dx, dy))

    spec = np.exp(-((k_mag / k_c) ** 2)) * (k_mag**2) / np.sqrt(1.0 + (k_mag / k_l) ** (2.0 * slope + 4.0)) / safe_k
    spec[k_mag == 0.0] = 0.0
    amp = np.sqrt(spec)

    frames = []
    for t_idx in range(n_frames):
        phase = rng.uniform(0.0, 2.0 * np.pi, size=(rows, cols))
        complex_noise = np.exp(1j * phase)

        psi_hat = amp * complex_noise / safe_k
        psi_hat[k_mag == 0.0] = 0.0

        u_hat = 1j * ky_2d * psi_hat
        v_hat = -1j * kx_2d * psi_hat

        u_real = np.real(np.fft.ifft2(u_hat))
        v_real = np.real(np.fft.ifft2(v_hat))

        u_real -= np.mean(u_real)
        v_real -= np.mean(v_real)

        chc = np.ones_like(u_real, dtype=float)
        ds_t = build_dataset(
            x=x_coords,
            y=y_coords,
            t=np.array([float(t_idx)], dtype=float),
            u=u_real[:, :, np.newaxis],
            v=v_real[:, :, np.newaxis],
            chc=chc[:, :, np.newaxis],
            delta_t=float(DELTA_T),
        )
        frames.append(ds_t)

    ds = xr.concat(frames, dim="t") if len(frames) > 1 else frames[0]
    ds.attrs["flow_model"] = "randvec"
    return ds

vortex(n=128, r0=10.0, vorticity=1.0, mode='burgers', diver=0.0, center=None, dx=1.0, dy=1.0, frame=0, n_vatistas=2.0)

Generate an analytical 2D vector field containing a centered or offset vortex.

Parameters:

Name Type Description Default
n int or tuple of (rows, cols)

Grid dimension. If int, creates an (n, n) grid.

128
r0 float

Vortex core radius in coordinate units (default 10.0).

10.0
vorticity float

Peak vorticity / circulation parameter $\omega_0$ in $s^{-1}$ (default 1.0).

1.0
mode ('burgers', 'lamb', 'rankine', 'vatistas')

Vortex profile type: - 'burgers' or 'lamb': Lamb-Oseen / Burgers Gaussian vorticity profile - 'rankine': Solid-body rotation inside core, potential vortex outside - 'vatistas': Generalized algebraic vortex profile

'burgers'
diver float

Radial divergence / suction parameter $\gamma$ (default 0.0).

0.0
center tuple of (x0, y0)

Vortex center coordinates. Default is domain center.

None
dx float

Grid spacing in x and y directions (default 1.0).

1.0
dy float

Grid spacing in x and y directions (default 1.0).

1.0
frame int

Time frame index (default 0).

0
n_vatistas float

Exponent parameter for Vatistas vortex (default 2.0).

2.0

Returns:

Type Description
Dataset

Canonical PIVPy dataset with variables u, v, chc, coords (x, y, t).

Source code in pivpy/synthetic.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def vortex(
    n: Union[int, Tuple[int, int]] = 128,
    r0: float = 10.0,
    vorticity: float = 1.0,
    mode: Literal["burgers", "lamb", "rankine", "vatistas"] = "burgers",
    diver: float = 0.0,
    center: Optional[Tuple[float, float]] = None,
    dx: float = 1.0,
    dy: float = 1.0,
    frame: int = 0,
    n_vatistas: float = 2.0,
) -> xr.Dataset:
    """Generate an analytical 2D vector field containing a centered or offset vortex.

    Parameters
    ----------
    n : int or tuple of (rows, cols)
        Grid dimension. If int, creates an (n, n) grid.
    r0 : float
        Vortex core radius in coordinate units (default 10.0).
    vorticity : float
        Peak vorticity / circulation parameter $\\omega_0$ in $s^{-1}$ (default 1.0).
    mode : {'burgers', 'lamb', 'rankine', 'vatistas'}
        Vortex profile type:
        - 'burgers' or 'lamb': Lamb-Oseen / Burgers Gaussian vorticity profile
        - 'rankine': Solid-body rotation inside core, potential vortex outside
        - 'vatistas': Generalized algebraic vortex profile
    diver : float
        Radial divergence / suction parameter $\\gamma$ (default 0.0).
    center : tuple of (x0, y0), optional
        Vortex center coordinates. Default is domain center.
    dx, dy : float
        Grid spacing in x and y directions (default 1.0).
    frame : int
        Time frame index (default 0).
    n_vatistas : float
        Exponent parameter for Vatistas vortex (default 2.0).

    Returns
    -------
    xr.Dataset
        Canonical PIVPy dataset with variables u, v, chc, coords (x, y, t).
    """
    if isinstance(n, int):
        rows, cols = n, n
    else:
        rows, cols = n

    x_coords = np.arange(cols, dtype=float) * dx
    y_coords = np.arange(rows, dtype=float) * dy
    x2d, y2d = np.meshgrid(x_coords, y_coords)

    if center is None:
        x0 = float(x_coords[-1] + x_coords[0]) / 2.0
        y0 = float(y_coords[-1] + y_coords[0]) / 2.0
    else:
        x0, y0 = center

    rx = x2d - x0
    ry = y2d - y0
    radius = np.sqrt(rx**2 + ry**2)

    # Angular velocity & divergence scales
    omega = float(vorticity) / 2.0
    gamma = float(diver) / 2.0

    u = np.zeros_like(radius, dtype=float)
    v = np.zeros_like(radius, dtype=float)

    mode_lower = mode.lower()
    safe_radius = np.where(radius == 0.0, 1e-12, radius)

    if mode_lower in ("burgers", "lamb"):
        decay = 1.0 - np.exp(-((radius / r0) ** 2))
        circ_factor = omega * (r0**2) / (safe_radius**2) * decay
        u = -circ_factor * ry
        v = circ_factor * rx

        if gamma != 0.0:
            div_factor = gamma * (r0**2) / (safe_radius**2) * decay
            u += div_factor * rx
            v += div_factor * ry

        u[radius == 0.0] = 0.0
        v[radius == 0.0] = 0.0

    elif mode_lower == "rankine":
        inside = radius <= r0
        outside = ~inside

        u[inside] = -omega * ry[inside]
        v[inside] = omega * rx[inside]

        circ_factor = omega * (r0**2) / (safe_radius[outside] ** 2)
        u[outside] = -circ_factor * ry[outside]
        v[outside] = circ_factor * rx[outside]

    elif mode_lower == "vatistas":
        factor = omega / ((1.0 + (radius / r0) ** (2.0 * n_vatistas)) ** (1.0 / n_vatistas))
        u = -factor * ry
        v = factor * rx

    else:
        raise ValueError(f"Unknown vortex mode '{mode}'. Choose from 'burgers', 'lamb', 'rankine', 'vatistas'.")

    chc = np.ones_like(u, dtype=float)

    u_3d = u[:, :, np.newaxis]
    v_3d = v[:, :, np.newaxis]
    chc_3d = chc[:, :, np.newaxis]
    t_coords = np.array([float(frame)], dtype=float)

    ds = build_dataset(
        x=x_coords,
        y=y_coords,
        t=t_coords,
        u=u_3d,
        v=v_3d,
        chc=chc_3d,
        delta_t=float(DELTA_T),
    )
    ds.attrs["flow_model"] = f"vortex_{mode_lower}"
    return ds

pivpy.update

UpdateCheckResult dataclass

Result of a package update check against PyPI.

Source code in pivpy/update.py
11
12
13
14
15
16
17
@dataclass(frozen=True)
class UpdateCheckResult:
    """Result of a package update check against PyPI."""

    status: int
    installed: str
    latest: str

check_update(package='pivpy', *, dist_name=None, timeout=3.0, verbose=False)

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)

Args: 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.

Source code in pivpy/update.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def check_update(
    package: str = "pivpy",
    *,
    dist_name: Optional[str] = None,
    timeout: float = 3.0,
    verbose: bool = False,
) -> UpdateCheckResult:
    """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)

    Args:
        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.
    """

    dist = dist_name or package
    installed = _get_installed_version_str(dist)

    try:
        latest = _get_pypi_version_str(package, timeout=timeout)
    except Exception:
        if verbose:
            print("Update check failed: server unavailable.")
        return UpdateCheckResult(status=0, installed=installed, latest="")

    cmp = _compare_versions(installed, latest)
    if cmp < 0:
        status = 2
        if verbose:
            print(f"New version available: {package} {latest} (installed: {installed}).")
    elif cmp > 0:
        status = 3
        if verbose:
            print(f"Installed version ({installed}) is newer than PyPI ({latest}).")
    else:
        status = 1
        if verbose:
            print(f"{package} is up to date ({installed}).")

    return UpdateCheckResult(status=status, installed=installed, latest=latest)

pivpy.graphics

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() and streamplot() return (fig, ax)
  • showf() exists
  • showscal() accepts flow_property= as an alias and can compute a scalar via the .piv.vec2scal() accessor when needed

animate(data, *, background='vorticity', quiver=True, blur=1.5, skip=None, arrow_scale=None, arrow_width=0.0065, arrow_color='#1a1a1a', arrow_alpha=0.75, cmap=None, clim=None, interval=80, repeat=True, blit=False, ax=None, title_fmt='Flow Field (t = {t:.2f})', image=None, image_extent=None, image_alpha=0.6, image_cmap='gray', color_by=None, **kwargs)

Create a high-performance, beautiful Matplotlib FuncAnimation for time-series flow fields.

Dynamically updates both background scalar fields (e.g. vorticity contours) and quiver velocity vectors in-place (quiver.set_UVC) for smooth, high-fps animation.

Parameters:

Name Type Description Default
data Dataset

Dataset with time dimension 't' and velocity components ('u', 'v').

required
background str, bool, or None

Background scalar field ('vorticity', 'mag', 'ke', 'divergence', or variable name).

"vorticity"
quiver bool

Whether to draw velocity vectors.

True
blur float

Gaussian filter smoothing sigma for background.

1.5
skip int or (skip_rows, skip_cols)

Arrow subsampling step, or an independent (skip_rows, skip_cols) pair (see plot()). Default ~16 arrows per axis.

None
arrow_scale float

Arrow scaling factor.

None
arrow_width float

Shaft width factor for arrows.

0.0065
arrow_color str

Arrow color.

"#1a1a1a"
arrow_alpha float

Arrow opacity.

0.75
cmap str

Colormap for background scalar.

None
clim tuple[float, float]

Global colorbar limits (vmin, vmax). If None, calculated robustly across all frames.

None
interval int

Delay between frames in milliseconds (~12.5 fps).

80
repeat bool

Whether the animation loops.

True
blit bool

Whether blitting is used.

False
ax Axes

Existing axes to draw on.

None
title_fmt str

Format string for dynamic frame title.

"Flow Field (t = {t:.2f})"
image ndarray

Static raw camera frame drawn via imshow (same for every frame) when background="image", PIVlab-style.

None
image_extent tuple[float, float, float, float] | None

As in plot(), for the background="image" frame.

None
image_alpha tuple[float, float, float, float] | None

As in plot(), for the background="image" frame.

None
image_cmap tuple[float, float, float, float] | None

As in plot(), for the background="image" frame.

None
color_by str

Color the quiver arrows per-frame by this field ("mag"/"speed", or a variable name in data) instead of a flat arrow_color.

None

Returns:

Type Description
FuncAnimation

The animation object (viewable in Jupyter/Marimo or saved via anim.save('flow.gif')).

Source code in pivpy/graphics.py
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
def animate(
    data: xr.Dataset,
    *,
    background: str | bool | None = "vorticity",
    quiver: bool = True,
    blur: float = 1.5,
    skip: int | None = None,
    arrow_scale: float | None = None,
    arrow_width: float = 0.0065,
    arrow_color: str = "#1a1a1a",
    arrow_alpha: float = 0.75,
    cmap: str | None = None,
    clim: tuple[float, float] | None = None,
    interval: int = 80,
    repeat: bool = True,
    blit: bool = False,
    ax: Axes | None = None,
    title_fmt: str = "Flow Field (t = {t:.2f})",
    image: np.ndarray | None = None,
    image_extent: tuple[float, float, float, float] | None = None,
    image_alpha: float = 0.6,
    image_cmap: str = "gray",
    color_by: str | None = None,
    **kwargs,
):
    """Create a high-performance, beautiful Matplotlib FuncAnimation for time-series flow fields.

    Dynamically updates both background scalar fields (e.g. vorticity contours) and
    quiver velocity vectors in-place (``quiver.set_UVC``) for smooth, high-fps animation.

    Parameters
    ----------
    data : xr.Dataset
        Dataset with time dimension 't' and velocity components ('u', 'v').
    background : str, bool, or None, default "vorticity"
        Background scalar field ('vorticity', 'mag', 'ke', 'divergence', or variable name).
    quiver : bool, default True
        Whether to draw velocity vectors.
    blur : float, default 1.5
        Gaussian filter smoothing sigma for background.
    skip : int or (skip_rows, skip_cols), optional
        Arrow subsampling step, or an independent (skip_rows, skip_cols)
        pair (see plot()). Default ~16 arrows per axis.
    arrow_scale : float, optional
        Arrow scaling factor.
    arrow_width : float, default 0.0065
        Shaft width factor for arrows.
    arrow_color : str, default "#1a1a1a"
        Arrow color.
    arrow_alpha : float, default 0.75
        Arrow opacity.
    cmap : str, optional
        Colormap for background scalar.
    clim : tuple[float, float], optional
        Global colorbar limits (vmin, vmax). If None, calculated robustly across all frames.
    interval : int, default 80
        Delay between frames in milliseconds (~12.5 fps).
    repeat : bool, default True
        Whether the animation loops.
    blit : bool, default False
        Whether blitting is used.
    ax : Axes, optional
        Existing axes to draw on.
    title_fmt : str, default "Flow Field (t = {t:.2f})"
        Format string for dynamic frame title.
    image : numpy.ndarray, optional
        Static raw camera frame drawn via imshow (same for every frame) when
        background="image", PIVlab-style.
    image_extent, image_alpha, image_cmap :
        As in plot(), for the background="image" frame.
    color_by : str, optional
        Color the quiver arrows per-frame by this field ("mag"/"speed", or a
        variable name in `data`) instead of a flat `arrow_color`.

    Returns
    -------
    matplotlib.animation.FuncAnimation
        The animation object (viewable in Jupyter/Marimo or saved via ``anim.save('flow.gif')``).
    """
    from matplotlib.animation import FuncAnimation
    import matplotlib.pyplot as plt
    from scipy.ndimage import gaussian_filter

    n_frames = int(data.sizes.get("t", 1))

    if ax is None:
        fig, target_ax = plt.subplots(figsize=(6.5, 5.2), dpi=120)
    else:
        target_ax = ax
        fig = ax.figure

    x_arr = np.asarray(data["x"].values, dtype=float)
    y_arr = np.asarray(data["y"].values, dtype=float)
    x2d, y2d = np.meshgrid(x_arr, y_arr)

    # Pre-extract or compute scalar background for all frames
    bg_str = str(background).lower() if (background is not None and not isinstance(background, bool)) else ("vorticity" if background is True or background == "vorticity" else None)
    has_bg = bg_str is not None and bg_str not in {"none", "false", "off"}

    if bg_str == "image" and image is not None:
        extent = image_extent if image_extent is not None else (
            float(x_arr.min()), float(x_arr.max()), float(y_arr.min()), float(y_arr.max())
        )
        target_ax.imshow(image, cmap=image_cmap, extent=extent, origin="upper",
                          alpha=float(image_alpha), zorder=1)
        has_bg = False  # static image, not a per-frame pcolormesh

    bg_frames = []
    use_cmap = cmap
    if has_bg:
        dx = abs(float(x_arr[1] - x_arr[0])) if len(x_arr) > 1 else 1.0
        dy = abs(float(y_arr[1] - y_arr[0])) if len(y_arr) > 1 else 1.0
        for fi in range(n_frames):
            ds_fi = data.isel(t=fi) if "t" in data.dims else data
            u_fi = np.asarray(ds_fi["u"].values, dtype=float)
            v_fi = np.asarray(ds_fi["v"].values, dtype=float)

            if bg_str in {"vorticity", "curl", "w"}:
                if "w" in ds_fi:
                    sc = np.asarray(ds_fi["w"].values, dtype=float)
                else:
                    dudx, dudy = np.gradient(u_fi, dx, dy, axis=(1, 0))
                    dvdx, dvdy = np.gradient(v_fi, dx, dy, axis=(1, 0))
                    sc = dvdx - dudy
                if use_cmap is None:
                    use_cmap = "RdBu_r"
            elif bg_str in {"mag", "speed"}:
                sc = np.sqrt(u_fi**2 + v_fi**2)
                if use_cmap is None:
                    use_cmap = "viridis"
            elif bg_str in {"ke", "energy"}:
                sc = 0.5 * (u_fi**2 + v_fi**2)
                if use_cmap is None:
                    use_cmap = "plasma"
            elif bg_str in {"divergence", "div"}:
                dudx, _ = np.gradient(u_fi, dx, axis=1)
                _, dvdy = np.gradient(v_fi, dy, axis=0)
                sc = dudx + dvdy
                if use_cmap is None:
                    use_cmap = "RdBu_r"
            elif bg_str in ds_fi:
                sc = np.asarray(ds_fi[bg_str].values, dtype=float)
                if use_cmap is None:
                    use_cmap = "viridis"
            else:
                sc = np.zeros_like(u_fi)
                if use_cmap is None:
                    use_cmap = "viridis"

            if blur and float(blur) > 0.0:
                sc = gaussian_filter(sc, sigma=float(blur))
            bg_frames.append(sc)

        if clim is not None:
            vmin, vmax = float(clim[0]), float(clim[1])
        elif use_cmap == "RdBu_r":
            all_finite = np.concatenate([f[np.isfinite(f)] for f in bg_frames if f.size])
            v_max = float(np.nanpercentile(np.abs(all_finite), 99)) if all_finite.size else 1.0
            v_max = max(v_max, 1e-9)
            vmin, vmax = -v_max, v_max
        else:
            all_finite = np.concatenate([f[np.isfinite(f)] for f in bg_frames if f.size])
            vmin = float(np.nanmin(all_finite)) if all_finite.size else 0.0
            vmax = float(np.nanpercentile(all_finite, 99)) if all_finite.size else 1.0

        bg_mesh = target_ax.pcolormesh(
            x2d, y2d, bg_frames[0], cmap=use_cmap, shading="gouraud", vmin=vmin, vmax=vmax, zorder=1
        )
        cbar = fig.colorbar(bg_mesh, ax=target_ax, fraction=0.046, pad=0.04)
        if bg_str in {"vorticity", "curl", "w"}:
            cbar.set_label(r"$\omega_z\ [\mathrm{s}^{-1}]$", fontsize=10)
        elif bg_str in {"mag", "speed"}:
            cbar.set_label(r"$\|\mathbf{u}\|\ [\mathrm{m/s}]$", fontsize=10)
    else:
        bg_mesh = None

    # Quiver Vector Layer
    ny, nx = y2d.shape
    if skip is None:
        step_y = step_x = max(1, int(round(max(nx, ny) / 16)))
    elif isinstance(skip, (tuple, list)):
        step_y, step_x = max(1, int(skip[0])), max(1, int(skip[1]))
    else:
        step_y = step_x = max(1, int(skip))
    dx_step = abs(float(x_arr[1] - x_arr[0])) if len(x_arr) > 1 else 1.0
    dy_step = abs(float(y_arr[1] - y_arr[0])) if len(y_arr) > 1 else 1.0

    def _apply_chc_mask(ds_t, *arrs):
        if "chc" not in ds_t:
            return arrs
        invalid = np.asarray(ds_t["chc"].values, dtype=float) == 0
        return tuple(np.where(invalid, np.nan, a) for a in arrs)

    ds0 = data.isel(t=0) if "t" in data.dims else data
    u0 = np.asarray(ds0["u"].values, dtype=float)
    v0 = np.asarray(ds0["v"].values, dtype=float)
    u0, v0 = _apply_chc_mask(ds0, u0, v0)
    med_speed = float(np.nanmedian(np.sqrt(u0**2 + v0**2)))
    if med_speed == 0.0:
        med_speed = 1.0

    if arrow_scale is None:
        target_len = 0.85 * min(step_x * dx_step, step_y * dy_step)
        auto_scale = (med_speed / target_len) if target_len > 0 else 1.0
    else:
        auto_scale = float(arrow_scale)

    def color_frame(ds_t, u_t, v_t):
        cb_str = str(color_by).lower()
        if cb_str in ("mag", "magnitude", "speed"):
            arr = np.sqrt(u_t**2 + v_t**2)
        elif str(color_by) in ds_t:
            arr = np.asarray(ds_t[str(color_by)].values, dtype=float)
            arr, = _apply_chc_mask(ds_t, arr)
        else:
            warnings.warn(f"color_by={color_by!r} not found in dataset; using arrow_color instead")
            return None
        return arr

    color0 = color_frame(ds0, u0, v0) if color_by is not None else None
    quiver_extra = {"color": arrow_color} if color0 is None else {
        "cmap": use_cmap if use_cmap is not None else "viridis",
    }

    if quiver:
        Q = target_ax.quiver(
            x2d[::step_y, ::step_x],
            y2d[::step_y, ::step_x],
            u0[::step_y, ::step_x],
            v0[::step_y, ::step_x],
            *(() if color0 is None else (color0[::step_y, ::step_x],)),
            angles="xy",
            scale_units="xy",
            scale=auto_scale,
            width=float(arrow_width),
            headwidth=4.0,
            headlength=5.0,
            headaxislength=4.5,
            minshaft=1.5,
            pivot="mid",
            alpha=float(arrow_alpha),
            zorder=2,
            **quiver_extra,
        )
        if color0 is not None:
            fig.colorbar(Q, ax=target_ax, fraction=0.046, pad=0.04).set_label(str(color_by), fontsize=10)
    else:
        Q = None

    target_ax.set_aspect("equal")
    x_units = str(data.attrs.get("spatial_units", data.coords.get("x", {}).attrs.get("units", "mm")))
    y_units = str(data.attrs.get("spatial_units", data.coords.get("y", {}).attrs.get("units", "mm")))
    target_ax.set_xlabel(f"x [{x_units}]", fontsize=10)
    target_ax.set_ylabel(f"y [{y_units}]", fontsize=10)

    t0_val = float(ds0["t"].values) if ("t" in ds0.coords and ds0["t"].size) else 0.0
    target_ax.set_title(title_fmt.format(t=t0_val, i=0), fontsize=11, fontweight="bold")
    fig.tight_layout()

    def update_frame(frame_i):
        artists = []
        if bg_mesh is not None and frame_i < len(bg_frames):
            bg_mesh.set_array(bg_frames[frame_i].ravel())
            artists.append(bg_mesh)

        ds_t = data.isel(t=frame_i) if "t" in data.dims else data
        if Q is not None:
            u_t = np.asarray(ds_t["u"].values, dtype=float)
            v_t = np.asarray(ds_t["v"].values, dtype=float)
            u_t, v_t = _apply_chc_mask(ds_t, u_t, v_t)
            if color0 is not None:
                c_t = color_frame(ds_t, u_t, v_t)
                Q.set_UVC(u_t[::step_y, ::step_x], v_t[::step_y, ::step_x], c_t[::step_y, ::step_x])
            else:
                Q.set_UVC(u_t[::step_y, ::step_x], v_t[::step_y, ::step_x])
            artists.append(Q)

        t_coord = float(ds_t["t"].values) if ("t" in ds_t.coords and ds_t["t"].size) else float(frame_i)
        target_ax.set_title(title_fmt.format(t=t_coord, i=frame_i), fontsize=11, fontweight="bold")
        return artists if blit else []

    anim = FuncAnimation(
        fig,
        update_frame,
        frames=n_frames,
        interval=interval,
        repeat=repeat,
        blit=blit,
    )
    return anim

autocorrelation_plot(data, variable='u', spatial_average=True, ax=None, **kwargs)

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.

Source code in pivpy/graphics.py
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
def autocorrelation_plot(
    data: xr.Dataset,
    variable: str = "u",
    spatial_average: bool = True,
    ax: plt.Axes | None = None,
    **kwargs,
) -> plt.Axes:
    """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.
    """

    if ax is None:
        _, ax = plt.subplots()

    if variable not in data:
        raise KeyError(f"Variable {variable} not in dataset")

    da = data[variable]
    if "t" in da.dims:
        if spatial_average:
            series = da.mean(dim=[d for d in da.dims if d != "t"]).values
        else:
            series = da.values.reshape((-1, da.sizes["t"]))
            series = series.reshape(-1)
    else:
        series = da.values.reshape(-1)

    series = np.asarray(series, dtype=float)
    series = series[~np.isnan(series)]
    if series.size == 0:
        return ax

    series = series - np.mean(series)
    corr = np.correlate(series, series, mode="full")
    corr = corr[corr.size // 2 :]
    corr = corr / (corr[0] if corr[0] != 0 else 1.0)

    ax.plot(corr, **kwargs)
    ax.set_title(f"Autocorrelation: {variable}")
    ax.set_xlabel("lag")
    ax.set_ylabel("corr")
    return ax

contour_plot(data, property='mag', ax=None, **kwargs)

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 magnitude mag computed from u and v.

Parameters:

Name Type Description Default
data Dataset

Dataset containing at least u and v.

required
property str

Variable to plot. Special value "mag" plots sqrt(u^2+v^2).

'mag'
ax Axes | None

Optional matplotlib axis.

None
**kwargs

Passed through to matplotlib. Recognized compat kwargs: colorbar (bool), colorbar_orient ("vertical"/"horizontal"), cmap, levels.

{}
Source code in pivpy/graphics.py
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
def contour_plot(
    data: xr.Dataset,
    property: str = "mag",
    ax: plt.Axes | None = None,
    **kwargs,
) -> tuple[plt.Figure, plt.Axes]:
    """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 magnitude ``mag`` computed from
    ``u`` and ``v``.

    Parameters
    ----------
    data:
        Dataset containing at least ``u`` and ``v``.
    property:
        Variable to plot. Special value ``"mag"`` plots ``sqrt(u^2+v^2)``.
    ax:
        Optional matplotlib axis.
    **kwargs:
        Passed through to matplotlib. Recognized compat kwargs:
        ``colorbar`` (bool), ``colorbar_orient`` ("vertical"/"horizontal"),
        ``cmap``, ``levels``.
    """

    from pivpy.graphics_utils import dataset_to_array

    colorbar = bool(kwargs.pop("colorbar", False))
    colorbar_orient = kwargs.pop("colorbar_orient", "vertical")
    cmap = kwargs.pop("cmap", None)
    levels = kwargs.pop("levels", None)

    if ax is None:
        fig, ax = plt.subplots()
    else:
        fig = ax.figure

    x, y, u, v = dataset_to_array(data)

    if property == "mag":
        z = np.sqrt(u**2 + v**2)
    elif property in data:
        da = data[property]
        z = np.asarray(da.isel(t=0).values if "t" in da.dims else da.values)
    else:
        raise KeyError(f"Property {property} not found in dataset")

    plot_kwargs: dict = {}
    if cmap is not None:
        plot_kwargs["cmap"] = cmap
    if levels is not None:
        plot_kwargs["levels"] = levels

    # Use contourf if levels provided, otherwise pcolormesh.
    if levels is not None:
        m = ax.contourf(x, y, z, **plot_kwargs, **kwargs)
    else:
        m = ax.pcolormesh(x, y, z, shading="auto", **plot_kwargs, **kwargs)

    if colorbar:
        plt.colorbar(m, ax=ax, orientation=colorbar_orient)

    ax.set_aspect("equal")
    return fig, ax

display_vector_field(data, arrowColor='k', arrowScale=1.0, arrowWidth=0.002)

display_vector_field is a wrapper for quiver() for backwards compatibility

Parameters:

Name Type Description Default
data Dataset

dataset with u, v, x, y

required
arrowColor str

color of the arrows, by default "k"

'k'
arrowScale float

scaling factor for the arrows, by default 1.0

1.0
arrowWidth float

width factor for the arrows, by default 0.002

0.002

Returns:

Type Description
tuple[Figure, Axes]

The figure and axes used for plotting.

Examples:

>>> from pivpy import io, graphics
>>> d = io.loadvec("test.vec")
>>> graphics.display_vector_field(d)
Source code in pivpy/graphics.py
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
def display_vector_field(
    data: xr.Dataset,
    arrowColor: str = "k",
    arrowScale: float = 1.0,
    arrowWidth: float = 0.002,
) -> tuple["Figure", "Axes"]:
    """
    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
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        The figure and axes used for plotting.

    Examples
    --------
    >>> from pivpy import io, graphics
    >>> d = io.loadvec("test.vec")
    >>> graphics.display_vector_field(d)
    """
    return quiver(
        data,
        arrowColor=arrowColor,
        scalingFactor=arrowScale,
        widthFactor=arrowWidth,
    )

histogram(data, bins=50, ax=None, **kwargs)

Plot histograms of u and v for quick diagnostics.

Source code in pivpy/graphics.py
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
def histogram(data: xr.Dataset, bins: int = 50, ax: plt.Axes | None = None, **kwargs) -> tuple[plt.Figure, plt.Axes]:
    """Plot histograms of u and v for quick diagnostics."""

    # Backwards compatibility: matplotlib removed `normed` in favor of `density`.
    if "normed" in kwargs and "density" not in kwargs:
        kwargs["density"] = kwargs.pop("normed")

    ds = data.isel(t=0) if "t" in data.dims else data
    u = np.asarray(ds["u"].values).ravel()
    v = np.asarray(ds["v"].values).ravel()

    if ax is None:
        fig, ax = plt.subplots()
    else:
        fig = ax.figure

    ax.hist(u[~np.isnan(u)], bins=bins, alpha=0.5, label="u", **kwargs)
    ax.hist(v[~np.isnan(v)], bins=bins, alpha=0.5, label="v", **kwargs)
    ax.legend()

    return fig, ax

histscal_disp(data, smooth=0, bin=None, opt='ngl', *, variable='w', ax=None)

Display histogram(s) for a scalar field (PIVMAT-inspired).

Parameters:

Name Type Description Default
data Dataset

Dataset containing the scalar variable.

required
smooth int

Number of consecutive frames to average. Use 0 to average over all frames (default). If smooth>1, returns a list of figures (one per chunk).

0
bin ndarray | None

Optional bin centers.

None
opt str

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' in opt.

'ngl'
variable str

Scalar variable name (default: 'w'). If missing and 'u' exists, falls back to 'u' for convenience.

'w'
ax Axes | None

Optional axes to plot into (only used when producing a single plot).

None

Returns:

Type Description
tuple or list of tuple

(fig, ax) or a list of (fig, ax) when multiple chunks are plotted.

Source code in pivpy/graphics.py
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
def histscal_disp(
    data: xr.Dataset,
    smooth: int = 0,
    bin: np.ndarray | None = None,
    opt: str = "ngl",
    *,
    variable: str = "w",
    ax: plt.Axes | None = None,
) -> tuple[plt.Figure, plt.Axes] | list[tuple[plt.Figure, plt.Axes]]:
    """Display histogram(s) for a scalar field (PIVMAT-inspired).

    Parameters
    ----------
    data:
        Dataset containing the scalar variable.
    smooth:
        Number of consecutive frames to average. Use ``0`` to average over all
        frames (default). If ``smooth>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'`` in ``opt``.
    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
    -------
    tuple or list of tuple
        ``(fig, ax)`` or a list of ``(fig, ax)`` when multiple chunks are plotted.
    """

    ds = data
    if variable not in ds and "u" in ds and variable == "w":
        variable = "u"
    if variable not in ds:
        raise KeyError(f"Variable {variable} not found in dataset")

    opt_l = str(opt).lower() if opt is not None else ""
    normalize = "n" in opt_l
    gaussian = "g" in opt_l
    logy = "l" in opt_l
    include_zeros = "0" in opt_l

    if "t" in ds.dims:
        nframe = int(ds.sizes.get("t", 1))
    else:
        nframe = 1

    if smooth is None:
        smooth = 0
    smooth_i = int(smooth)
    if smooth_i <= 0:
        smooth_i = nframe

    results: list[tuple[plt.Figure, plt.Axes]] = []
    n_chunks = max(1, nframe // smooth_i)

    for chunk in range(n_chunks):
        t0 = chunk * smooth_i
        t1 = (chunk + 1) * smooth_i
        sub = ds.isel(t=slice(t0, t1)) if "t" in ds.dims else ds

        hds = sub.piv.histf(variable=variable, bin=bin, opt="0" if include_zeros else "")
        centers = np.asarray(hds["bin"].values, dtype=float)
        counts = np.asarray(hds["h"].values, dtype=float)

        delta = float(centers[1] - centers[0]) if centers.size >= 2 else 1.0
        y = counts.copy()
        if normalize:
            denom = float(np.sum(y)) * delta
            if denom != 0:
                y = y / denom

        # Stats for axis limits and Gaussian overlay.
        vals = np.asarray(sub[variable].values, dtype=float).ravel()
        vals = vals[np.isfinite(vals)]
        if not include_zeros:
            vals = vals[vals != 0]
        mean = float(np.mean(vals)) if vals.size else 0.0
        std = float(np.std(vals)) if vals.size else 1.0
        if not np.isfinite(std) or std == 0.0:
            std = 1.0

        if ax is not None and n_chunks == 1:
            fig = ax.figure
            use_ax = ax
        else:
            fig, use_ax = plt.subplots()

        use_ax.plot(centers, y, "ro", label="hist")
        use_ax.axvline(0.0, color="k", linewidth=1.0)
        use_ax.set_xlabel(variable)
        use_ax.set_ylabel("pdf" if normalize else "Histogram")

        if logy:
            # Matplotlib warns if attempting log scale with no positive values.
            if np.any(y > 0):
                use_ax.set_yscale("log")

        # x-limits like PIVMAT: +/- 15*std around 0 or around mean.
        if mean < std:
            use_ax.set_xlim(-15.0 * std, 15.0 * std)
        else:
            use_ax.set_xlim(mean - 15.0 * std, mean + 15.0 * std)

        if gaussian:
            xg = np.linspace(float(centers[0]), float(centers[-1]), 2000)
            gauss = 1.0 / (np.sqrt(2.0 * np.pi) * std) * np.exp(-0.5 * (xg**2) / (std**2))
            use_ax.plot(xg, gauss, "b-", label="gauss")

        if "t" in ds.dims:
            use_ax.set_title(f"{variable}: frames {t0}..{t1-1}")
        else:
            use_ax.set_title(f"{variable} histogram")

        if gaussian:
            use_ax.legend()

        results.append((fig, use_ax))

    return results[0] if len(results) == 1 else results

histvec_disp(data, smooth=0, bin=None, opt='ngl', *, ax=None)

Display histogram(s) for a 2D vector field (PIVMAT-inspired).

Vector components are taken from ('u','v') if present, otherwise ('vx','vy').

Parameters:

Name Type Description Default
data Dataset

Dataset containing vector components.

required
smooth int

Same semantics as :func:histscal_disp.

0
bin int

Same semantics as :func:histscal_disp.

0
opt int

Same semantics as :func:histscal_disp.

0
ax int

Same semantics as :func:histscal_disp.

0

Returns:

Type Description
tuple or list of tuple

(fig, ax) or a list of (fig, ax) when multiple chunks are plotted.

Source code in pivpy/graphics.py
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
def histvec_disp(
    data: xr.Dataset,
    smooth: int = 0,
    bin: np.ndarray | None = None,
    opt: str = "ngl",
    *,
    ax: plt.Axes | None = None,
) -> tuple[plt.Figure, plt.Axes] | list[tuple[plt.Figure, plt.Axes]]:
    """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, bin, opt, ax:
        Same semantics as :func:`histscal_disp`.

    Returns
    -------
    tuple or list of tuple
        ``(fig, ax)`` or a list of ``(fig, ax)`` when multiple chunks are plotted.
    """

    ds = data
    if "u" in ds and "v" in ds:
        xname, yname = "u", "v"
    elif "vx" in ds and "vy" in ds:
        xname, yname = "vx", "vy"
    else:
        raise KeyError("histvec_disp requires ('u','v') or ('vx','vy')")

    opt_l = str(opt).lower() if opt is not None else ""
    normalize = "n" in opt_l
    gaussian = "g" in opt_l
    logy = "l" in opt_l
    include_zeros = "0" in opt_l

    if "t" in ds.dims:
        nframe = int(ds.sizes.get("t", 1))
    else:
        nframe = 1

    if smooth is None:
        smooth = 0
    smooth_i = int(smooth)
    if smooth_i <= 0:
        smooth_i = nframe

    results: list[tuple[plt.Figure, plt.Axes]] = []
    n_chunks = max(1, nframe // smooth_i)

    for chunk in range(n_chunks):
        t0 = chunk * smooth_i
        t1 = (chunk + 1) * smooth_i
        sub = ds.isel(t=slice(t0, t1)) if "t" in ds.dims else ds

        hds = sub.piv.histf(variable=None, bin=bin, opt="0" if include_zeros else "")
        centers = np.asarray(hds["bin"].values, dtype=float)
        hx = np.asarray(hds["hx"].values, dtype=float)
        hy = np.asarray(hds["hy"].values, dtype=float)

        delta = float(centers[1] - centers[0]) if centers.size >= 2 else 1.0
        if normalize:
            sx = float(np.sum(hx)) * delta
            sy = float(np.sum(hy)) * delta
            if sx != 0:
                hx = hx / sx
            if sy != 0:
                hy = hy / sy

        # Stats for Gaussian overlay.
        def _stats(arr: xr.DataArray) -> tuple[float, float]:
            v = np.asarray(arr.values, dtype=float).ravel()
            v = v[np.isfinite(v)]
            if not include_zeros:
                v = v[v != 0]
            if v.size == 0:
                return 0.0, 1.0
            m = float(np.mean(v))
            s = float(np.std(v))
            if not np.isfinite(s) or s == 0.0:
                s = 1.0
            return m, s

        mx, sx = _stats(sub[xname])
        my, sy = _stats(sub[yname])

        if ax is not None and n_chunks == 1:
            fig = ax.figure
            use_ax = ax
        else:
            fig, use_ax = plt.subplots()

        use_ax.plot(centers, hx, "ro", label=xname)
        use_ax.plot(centers, hy, "bs", label=yname)
        use_ax.axvline(0.0, color="k", linewidth=1.0)
        use_ax.set_xlabel("value")
        use_ax.set_ylabel("pdf" if normalize else "Histogram")
        use_ax.legend()

        if logy:
            # Matplotlib warns if attempting log scale with no positive values.
            if np.any(hx > 0) or np.any(hy > 0):
                use_ax.set_yscale("log")

        if gaussian:
            xg = np.linspace(float(centers[0]), float(centers[-1]), 2000)
            gx = float(np.max(hx)) * np.exp(-0.5 * ((xg - mx) ** 2) / (sx**2))
            gy = float(np.max(hy)) * np.exp(-0.5 * ((xg - my) ** 2) / (sy**2))
            use_ax.plot(xg, gx, "r-", linewidth=1.0)
            use_ax.plot(xg, gy, "b-", linewidth=1.0)

        if "t" in ds.dims:
            use_ax.set_title(f"vector hist: frames {t0}..{t1-1}")
        else:
            use_ax.set_title("vector histogram")

        results.append((fig, use_ax))

    return results[0] if len(results) == 1 else results

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)

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:

Name Type Description Default
filename str | list[str] | tuple[str, ...]

File pattern (glob) or list of patterns/paths.

required
output str | Path | None

Output movie file (e.g. .mp4 / .gif). If None and return_frames=True, returns a list of RGBA frames.

required
format str | None

Optional explicit format for pivpy.io.read_piv.

None
verbose bool

If True, prints each file loaded.

False
Notes

Other parameters match :func:to_movie.

Source code in pivpy/graphics.py
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
def imvectomovie(
    filename: str | list[str] | tuple[str, ...],
    output: str | pathlib.Path | None,
    *,
    format: str | None = None,
    show: str = "auto",
    background: str | None = None,
    scalar: str = "w",
    fps: int = 10,
    dpi: int = 150,
    writer: str | None = None,
    codec: str | None = None,
    title: str | None = None,
    clim: tuple[float, float] | str | None = None,
    cmap: str | None = None,
    verbose: bool = False,
    return_frames: bool = False,
    close: bool = True,
    ax: Axes | None = None,
    **kwargs,
) -> list[np.ndarray] | None:
    """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``). If ``None`` and
        ``return_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 :func:`to_movie`.
    """

    import pivpy.io as pio

    files = _resolve_files(filename)
    if not files:
        raise FileNotFoundError("No files matched the given pattern")

    def gen():
        for i, fp in enumerate(files):
            if verbose:
                print(f"Loading file #{i + 1}/{len(files)}: {fp}")
            ds = pio.read_piv(fp, format=format, frame=i)
            yield ds, str(fp)

    return _movie_from_iter(
        gen(),
        output=output,
        show=show,
        background=background,
        scalar=scalar,
        fps=fps,
        dpi=dpi,
        writer=writer,
        codec=codec,
        title=title,
        clim=clim,
        cmap=cmap,
        return_frames=return_frames,
        close=close,
        ax=ax,
        **kwargs,
    )

jpdfscal_disp(jpdf, *, ax=None)

Display a joint PDF computed by :func:pivpy.compute_funcs.jpdfscal.

This mimics PIVMAT's jpdfscal_disp: it plots log10(hi) as filled contours and draws dashed zero lines.

Parameters:

Name Type Description Default
jpdf Dataset

Dataset produced by jpdfscal with coords bin1/bin2 and data variable hi.

required
ax Axes | None

Optional axes.

None

Returns:

Type Description
tuple[Figure, Axes]

The figure and axes.

Source code in pivpy/graphics.py
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
def jpdfscal_disp(
    jpdf: xr.Dataset,
    *,
    ax: Axes | None = None,
) -> tuple[Figure, Axes]:
    """Display a joint PDF computed by :func:`pivpy.compute_funcs.jpdfscal`.

    This mimics PIVMAT's ``jpdfscal_disp``: it plots ``log10(hi)`` as filled
    contours and draws dashed zero lines.

    Parameters
    ----------
    jpdf:
        Dataset produced by ``jpdfscal`` with coords ``bin1``/``bin2`` and data
        variable ``hi``.
    ax:
        Optional axes.

    Returns
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        The figure and axes.
    """

    if ax is None:
        fig, ax = plt.subplots()
    else:
        fig = ax.figure

    if "hi" not in jpdf:
        raise KeyError("jpdf dataset must contain variable 'hi'")
    if "bin1" not in jpdf.coords or "bin2" not in jpdf.coords:
        raise KeyError("jpdf dataset must contain coords 'bin1' and 'bin2'")

    bin1 = np.asarray(jpdf["bin1"].values, dtype=float)
    bin2 = np.asarray(jpdf["bin2"].values, dtype=float)
    hi = np.asarray(jpdf["hi"].values, dtype=float)

    # Avoid log10(0) warnings by masking zeros.
    with np.errstate(divide="ignore", invalid="ignore"):
        z = np.where(hi > 0, np.log10(hi), np.nan)

    levels = [0, 1, 2, 3, 4, 5, 6]
    m = ax.contourf(bin1, bin2, z.T, levels=levels)

    namew1 = str(jpdf.attrs.get("namew1", "s1"))
    namew2 = str(jpdf.attrs.get("namew2", "s2"))
    unitw1 = str(jpdf.attrs.get("unitw1", ""))
    unitw2 = str(jpdf.attrs.get("unitw2", ""))

    xlab = f"{namew1} ({unitw1})" if unitw1 else namew1
    ylab = f"{namew2} ({unitw2})" if unitw2 else namew2
    ax.set_xlabel(xlab)
    ax.set_ylabel(ylab)
    ax.set_title(f"Log joint PDF of {namew1} and {namew2}")

    ax.plot([bin1[0], bin1[-1]], [0, 0], "k--")
    ax.plot([0, 0], [bin2[0], bin2[-1]], "k--")
    plt.colorbar(m, ax=ax)
    return fig, ax

plot(data, *, background='vorticity', quiver=True, streamlines=True, blur=1.5, cmap=None, clim=None, levels=80, skip=None, arrow_scale=None, arrow_width=0.0065, arrow_color='#1a1a1a', arrow_alpha=0.75, streamline_density=1.1, streamline_color=None, streamline_alpha=0.55, streamline_linewidth=0.75, streamline_arrowsize=0.8, quiver_key=True, colorbar=True, cbar_label=None, title=None, ax=None, aspect='equal', t_idx=0, image=None, image_extent=None, image_alpha=0.6, image_cmap='gray', color_by=None, **kwargs)

High-level, publication-quality plotting function for PIV datasets.

Zero-effort out-of-the-box defaults: - Automatically calculates and renders smooth vorticity background with perceptual colormap. - Adds subtle streamlines tracing flow trajectories. - Overlays clean, auto-scaled, perfectly proportioned velocity vector arrows. - Adds colorbar, coordinate labels, and reference arrow key.

All visual elements can be customized, overridden, or toggled on/off.

Parameters:

Name Type Description Default
data Dataset

PIV Dataset containing spatial coords ('x', 'y') and variables ('u', 'v') or scalars.

required
background str, bool, or None

Scalar background to display behind vectors. - "vorticity" / "curl" / "w": vorticity field with RdBu_r diverging colormap. - "mag" / "speed": velocity magnitude ||u|| with viridis colormap. - "ke": kinetic energy with plasma colormap. - "divergence" / "div": 2D divergence field with RdBu_r. - Variable name in data (e.g. "chc", "tke"): plots that variable. - "image": the raw frame passed via image=, PIVlab-style (needs image=). - None / False / 'off': no scalar background (quiver/streamlines only).

"vorticity"
image ndarray

Raw camera frame to draw via imshow when background="image".

None
image_extent (left, right, bottom, top)

Physical-coordinate extent for image. If None, uses the data's x/y range.

None
image_alpha float

Transparency of the background image.

0.6
image_cmap str

Colormap for the background image when background="image".

"gray"
color_by str

Color the quiver arrows continuously by this field instead of a flat arrow_color — "mag"/"speed" for velocity magnitude, or any variable name in data (e.g. "v" for streamwise velocity). Draws a colorbar.

None
quiver bool

Whether to draw velocity vector arrows.

True
streamlines bool

Whether to draw flow streamlines.

True
blur float

Gaussian filter sigma applied to background scalar field for smooth fluid appearance. Set to 0 to disable smoothing.

1.5
cmap str or Colormap

Matplotlib colormap. If None, chosen automatically based on background type.

None
clim tuple[float, float]

Color limits (vmin, vmax). If None, computed robustly via 99th percentile.

None
levels int

Number of contour levels for background contourf.

80
skip int or (skip_rows, skip_cols)

Vector arrow subsampling step (e.g. skip=4 plots every 4th arrow in both directions). Pass a (skip_rows, skip_cols) pair for independent row/column subsampling - e.g. skip=(6, 1) keeps every column dense while spacing rows apart, for a profile-like view. If None, auto-calculated based on grid dimensions (~25-35 arrows per axis).

None
arrow_scale float

Scaling factor for vector arrows in matplotlib quiver. If None, auto-calculated based on grid spacing and median velocity magnitude.

None
arrow_width float

Shaft width factor for vector arrows.

0.005
arrow_color str

Color for vector arrows.

"#0a0a0a"
arrow_alpha float

Transparency for vector arrows.

0.9
streamline_density float

Density of streamlines.

1.1
streamline_color str

Color of streamlines (defaults to "white" when background is active, "#333333" otherwise).

None
streamline_alpha float

Transparency of streamlines.

0.55
streamline_linewidth float

Line width of streamlines.

0.75
streamline_arrowsize float

Arrow size of streamlines.

0.8
quiver_key bool, str, or float

Whether to display a reference quiver key in the top right.

True
colorbar bool

Whether to display a colorbar when a background scalar is plotted.

True
cbar_label str

Custom colorbar label. If None, a LaTeX math label is generated automatically.

None
title str

Custom plot title.

None
ax Axes

Existing axes to draw on. If None, creates a new figure and axes.

None
aspect str or float

Aspect ratio of the axes.

"equal"
t_idx int

Time index to plot if dataset has a time dimension 't'.

0
**kwargs dict

Additional keyword arguments passed to matplotlib contourf/quiver.

{}

Returns:

Type Description
tuple[Figure, Axes]

Figure and axes objects containing the plot.

Source code in pivpy/graphics.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def plot(
    data: xr.Dataset,
    *,
    background: str | bool | None = "vorticity",
    quiver: bool = True,
    streamlines: bool = True,
    blur: float = 1.5,
    cmap: str | None = None,
    clim: tuple[float, float] | None = None,
    levels: int = 80,
    skip: int | None = None,
    arrow_scale: float | None = None,
    arrow_width: float = 0.0065,
    arrow_color: str = "#1a1a1a",
    arrow_alpha: float = 0.75,
    streamline_density: float = 1.1,
    streamline_color: str | None = None,
    streamline_alpha: float = 0.55,
    streamline_linewidth: float = 0.75,
    streamline_arrowsize: float = 0.8,
    quiver_key: bool | str | float = True,
    colorbar: bool = True,
    cbar_label: str | None = None,
    title: str | None = None,
    ax: Axes | None = None,
    aspect: str | float = "equal",
    t_idx: int = 0,
    image: np.ndarray | None = None,
    image_extent: tuple[float, float, float, float] | None = None,
    image_alpha: float = 0.6,
    image_cmap: str = "gray",
    color_by: str | None = None,
    **kwargs,
) -> tuple[Figure, Axes]:
    """High-level, publication-quality plotting function for PIV datasets.

    Zero-effort out-of-the-box defaults:
    - Automatically calculates and renders smooth vorticity background with perceptual colormap.
    - Adds subtle streamlines tracing flow trajectories.
    - Overlays clean, auto-scaled, perfectly proportioned velocity vector arrows.
    - Adds colorbar, coordinate labels, and reference arrow key.

    All visual elements can be customized, overridden, or toggled on/off.

    Parameters
    ----------
    data : xr.Dataset
        PIV Dataset containing spatial coords ('x', 'y') and variables ('u', 'v') or scalars.
    background : str, bool, or None, default "vorticity"
        Scalar background to display behind vectors.
        - "vorticity" / "curl" / "w": vorticity field with RdBu_r diverging colormap.
        - "mag" / "speed": velocity magnitude ||u|| with viridis colormap.
        - "ke": kinetic energy with plasma colormap.
        - "divergence" / "div": 2D divergence field with RdBu_r.
        - Variable name in data (e.g. "chc", "tke"): plots that variable.
        - "image": the raw frame passed via `image=`, PIVlab-style (needs `image=`).
        - None / False / 'off': no scalar background (quiver/streamlines only).
    image : numpy.ndarray, optional
        Raw camera frame to draw via imshow when background="image".
    image_extent : (left, right, bottom, top), optional
        Physical-coordinate extent for `image`. If None, uses the data's x/y range.
    image_alpha : float, default 0.6
        Transparency of the background image.
    image_cmap : str, default "gray"
        Colormap for the background image when background="image".
    color_by : str, optional
        Color the quiver arrows continuously by this field instead of a flat
        `arrow_color` — "mag"/"speed" for velocity magnitude, or any variable
        name in `data` (e.g. "v" for streamwise velocity). Draws a colorbar.
    quiver : bool, default True
        Whether to draw velocity vector arrows.
    streamlines : bool, default True
        Whether to draw flow streamlines.
    blur : float, default 1.5
        Gaussian filter sigma applied to background scalar field for smooth fluid appearance.
        Set to 0 to disable smoothing.
    cmap : str or Colormap, optional
        Matplotlib colormap. If None, chosen automatically based on background type.
    clim : tuple[float, float], optional
        Color limits (vmin, vmax). If None, computed robustly via 99th percentile.
    levels : int, default 80
        Number of contour levels for background contourf.
    skip : int or (skip_rows, skip_cols), optional
        Vector arrow subsampling step (e.g. skip=4 plots every 4th arrow in
        both directions). Pass a (skip_rows, skip_cols) pair for independent
        row/column subsampling - e.g. skip=(6, 1) keeps every column dense
        while spacing rows apart, for a profile-like view. If None,
        auto-calculated based on grid dimensions (~25-35 arrows per axis).
    arrow_scale : float, optional
        Scaling factor for vector arrows in matplotlib quiver.
        If None, auto-calculated based on grid spacing and median velocity magnitude.
    arrow_width : float, default 0.005
        Shaft width factor for vector arrows.
    arrow_color : str, default "#0a0a0a"
        Color for vector arrows.
    arrow_alpha : float, default 0.9
        Transparency for vector arrows.
    streamline_density : float, default 1.1
        Density of streamlines.
    streamline_color : str, optional
        Color of streamlines (defaults to "white" when background is active, "#333333" otherwise).
    streamline_alpha : float, default 0.55
        Transparency of streamlines.
    streamline_linewidth : float, default 0.75
        Line width of streamlines.
    streamline_arrowsize : float, default 0.8
        Arrow size of streamlines.
    quiver_key : bool, str, or float, default True
        Whether to display a reference quiver key in the top right.
    colorbar : bool, default True
        Whether to display a colorbar when a background scalar is plotted.
    cbar_label : str, optional
        Custom colorbar label. If None, a LaTeX math label is generated automatically.
    title : str, optional
        Custom plot title.
    ax : matplotlib.axes.Axes, optional
        Existing axes to draw on. If None, creates a new figure and axes.
    aspect : str or float, default "equal"
        Aspect ratio of the axes.
    t_idx : int, default 0
        Time index to plot if dataset has a time dimension 't'.
    **kwargs : dict
        Additional keyword arguments passed to matplotlib contourf/quiver.

    Returns
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        Figure and axes objects containing the plot.
    """
    data_slice = data.isel(t=t_idx) if ("t" in data.dims and data.sizes.get("t", 1) > 1) else (data.isel(t=0) if "t" in data.dims else data)

    x_arr = np.asarray(data_slice["x"].values, dtype=float)
    y_arr = np.asarray(data_slice["y"].values, dtype=float)
    X, Y = np.meshgrid(x_arr, y_arr)
    xUnits = str(getattr(data_slice.get("x", None), "attrs", {}).get("units", "mm") or "mm")
    yUnits = str(getattr(data_slice.get("y", None), "attrs", {}).get("units", "mm") or "mm")

    if ax is None:
        fig, ax = plt.subplots(figsize=(8.5, 6.8))
    else:
        fig = ax.figure

    is_vector = "u" in data_slice and "v" in data_slice

    if is_vector:
        u_arr = np.asarray(data_slice["u"].values, dtype=float)
        v_arr = np.asarray(data_slice["v"].values, dtype=float)
        if "chc" in data_slice:
            invalid = np.asarray(data_slice["chc"].values, dtype=float) == 0
            u_arr = np.where(invalid, np.nan, u_arr)
            v_arr = np.where(invalid, np.nan, v_arr)

        bg_drawn = False
        # Background Layer
        if background is not None and background is not False and str(background).lower() not in ("off", "none", ""):
            bg_str = str(background).lower() if isinstance(background, str) else "vorticity"
            bg_val = None
            default_cmap = "RdBu_r"
            default_cbar_label = ""
            symmetric_clim = True

            if bg_str == "image" and image is not None:
                extent = image_extent if image_extent is not None else (
                    float(x_arr.min()), float(x_arr.max()), float(y_arr.min()), float(y_arr.max())
                )
                ax.imshow(image, cmap=image_cmap, extent=extent, origin="upper", alpha=float(image_alpha))
                bg_drawn = True

            elif bg_str in ("vorticity", "vort", "curl", "w"):
                if "w" in data_slice:
                    bg_val = np.asarray(data_slice["w"].values, dtype=float)
                elif "vorticity" in data_slice:
                    bg_val = np.asarray(data_slice["vorticity"].values, dtype=float)
                else:
                    import pivpy.pivpy
                    ds_temp = data_slice.piv.vorticity(name="__bg_w")
                    bg_val = np.asarray(ds_temp["__bg_w"].values, dtype=float)
                default_cmap = "RdBu_r"
                default_cbar_label = r"Vorticity $\omega_z = \frac{\partial v}{\partial x} - \frac{\partial u}{\partial y}\; [\mathrm{s}^{-1}]$"
                symmetric_clim = True

            elif bg_str in ("mag", "magnitude", "speed"):
                bg_val = np.sqrt(u_arr**2 + v_arr**2)
                default_cmap = "viridis"
                default_cbar_label = r"Velocity Magnitude $||\mathbf{u}||\; [\mathrm{m/s}]$"
                symmetric_clim = False

            elif bg_str in ("ke", "ken", "kinetic_energy"):
                bg_val = 0.5 * (u_arr**2 + v_arr**2)
                default_cmap = "plasma"
                default_cbar_label = r"Kinetic Energy $k = \frac{1}{2}(u^2 + v^2)$"
                symmetric_clim = False

            elif bg_str in ("divergence", "div"):
                import pivpy.pivpy
                ds_temp = data_slice.piv.divergence(name="__bg_div")
                bg_val = np.asarray(ds_temp["__bg_div"].values, dtype=float)
                default_cmap = "RdBu_r"
                default_cbar_label = r"Divergence $\nabla \cdot \mathbf{u}\; [\mathrm{s}^{-1}]$"
                symmetric_clim = True

            elif str(background) in data_slice:
                bg_val = np.asarray(data_slice[str(background)].values, dtype=float)
                default_cmap = "viridis"
                default_cbar_label = str(background)
                symmetric_clim = False

            if bg_val is not None:
                # Apply Gaussian filter smoothing if requested
                if blur and float(blur) > 0.0:
                    if np.any(np.isnan(bg_val)):
                        bg_val_clean = np.nan_to_num(bg_val, nan=float(np.nanmedian(bg_val)))
                        bg_val = gaussian_filter(bg_val_clean, sigma=float(blur))
                    else:
                        bg_val = gaussian_filter(bg_val, sigma=float(blur))

                use_cmap = cmap if cmap is not None else default_cmap
                if clim is not None:
                    vmin, vmax = float(clim[0]), float(clim[1])
                elif symmetric_clim:
                    finite_vals = bg_val[np.isfinite(bg_val)]
                    val_max = float(np.nanpercentile(np.abs(finite_vals), 99)) if finite_vals.size else 1.0
                    val_max = max(val_max, 1e-9)
                    vmin, vmax = -val_max, val_max
                else:
                    finite_vals = bg_val[np.isfinite(bg_val)]
                    vmin = float(np.nanmin(finite_vals)) if finite_vals.size else 0.0
                    vmax = float(np.nanpercentile(finite_vals, 99)) if finite_vals.size else 1.0
                    if vmin == vmax:
                        vmax = vmin + 1.0

                cf = ax.contourf(X, Y, bg_val, levels=int(levels), cmap=use_cmap, vmin=vmin, vmax=vmax, extend="both")
                if colorbar:
                    cbar = fig.colorbar(cf, ax=ax, pad=0.03, shrink=0.92)
                    cbar_lbl = cbar_label if cbar_label is not None else default_cbar_label
                    if cbar_lbl:
                        cbar.set_label(cbar_lbl, fontsize=11, labelpad=10)
                    cbar.ax.tick_params(labelsize=9)
                bg_drawn = True

        # Streamlines Layer
        if streamlines:
            strm_color = streamline_color if streamline_color is not None else ("white" if bg_drawn else "#333333")
            try:
                x_s = x_arr.copy()
                y_s = y_arr.copy()
                u_s = u_arr.copy()
                v_s = v_arr.copy()
                if y_s.size >= 2 and y_s[0] > y_s[-1]:
                    y_s = y_s[::-1]
                    u_s = u_s[::-1, :]
                    v_s = v_s[::-1, :]
                if x_s.size >= 2 and x_s[0] > x_s[-1]:
                    x_s = x_s[::-1]
                    u_s = u_s[:, ::-1]
                    v_s = v_s[:, ::-1]

                strm = ax.streamplot(
                    x_s,
                    y_s,
                    u_s,
                    v_s,
                    color=strm_color,
                    linewidth=float(streamline_linewidth),
                    density=float(streamline_density),
                    arrowsize=float(streamline_arrowsize),
                    arrowstyle="->",
                )
                strm.lines.set_alpha(float(streamline_alpha))
                for patch in ax.patches:
                    patch.set_alpha(float(streamline_alpha))
            except Exception:
                pass

        # Quiver Vector Layer
        if quiver:
            ny, nx = u_arr.shape
            if skip is None:
                step_y = step_x = max(1, int(round(max(nx, ny) / 16)))
            elif isinstance(skip, (tuple, list)):
                step_y, step_x = max(1, int(skip[0])), max(1, int(skip[1]))
            else:
                step_y = step_x = max(1, int(skip))

            dx = abs(float(x_arr[1] - x_arr[0])) if len(x_arr) > 1 else 1.0
            dy = abs(float(y_arr[1] - y_arr[0])) if len(y_arr) > 1 else 1.0
            speed_arr = np.sqrt(u_arr**2 + v_arr**2)
            finite_speed = speed_arr[np.isfinite(speed_arr)]
            med_speed = float(np.nanmedian(finite_speed)) if finite_speed.size else 1.0
            if med_speed == 0.0:
                med_speed = float(np.nanmax(finite_speed)) if finite_speed.size else 1.0
            if med_speed == 0.0:
                med_speed = 1.0

            if arrow_scale is None:
                # Constrain to the denser axis so neighboring arrows don't overlap.
                target_len = 0.85 * min(step_x * dx, step_y * dy)
                auto_scale = (med_speed / target_len) if target_len > 0 else 1.0
            else:
                auto_scale = float(arrow_scale)

            color_arr = None
            if color_by is not None:
                cb_str = str(color_by).lower()
                if cb_str in ("mag", "magnitude", "speed"):
                    color_arr = speed_arr
                elif str(color_by) in data_slice:
                    color_arr = np.asarray(data_slice[str(color_by)].values, dtype=float)
                    if "chc" in data_slice:
                        color_arr = np.where(invalid, np.nan, color_arr)
                else:
                    warnings.warn(f"color_by={color_by!r} not found in dataset; using arrow_color instead")

            quiver_extra = {"color": arrow_color} if color_arr is None else {
                "cmap": cmap if cmap is not None else "viridis",
            }
            Q = ax.quiver(
                X[::step_y, ::step_x],
                Y[::step_y, ::step_x],
                u_arr[::step_y, ::step_x],
                v_arr[::step_y, ::step_x],
                *(() if color_arr is None else (color_arr[::step_y, ::step_x],)),
                angles="xy",
                scale_units="xy",
                scale=auto_scale,
                width=float(arrow_width),
                headwidth=4.0,
                headlength=5.0,
                headaxislength=4.5,
                minshaft=1.5,
                pivot="mid",
                alpha=float(arrow_alpha),
                **quiver_extra,
            )
            if color_arr is not None and colorbar:
                cbar = fig.colorbar(Q, ax=ax, pad=0.03, shrink=0.92)
                cbar.set_label(cbar_label if cbar_label is not None else str(color_by), fontsize=11, labelpad=10)
                cbar.ax.tick_params(labelsize=9)

            if quiver_key:
                key_val = round(med_speed, 1) if med_speed >= 1.0 else round(med_speed, 2)
                if key_val == 0.0:
                    key_val = 1.0
                if isinstance(quiver_key, (int, float)):
                    key_val = float(quiver_key)
                key_label = f"${key_val}\\,\\mathrm{{m/s}}$" if quiver_key is True else str(quiver_key)
                ax.quiverkey(
                    Q,
                    X=0.82,
                    Y=1.04,
                    U=key_val,
                    label=key_label,
                    labelpos="E",
                    coordinates="axes",
                    fontproperties={"size": 10, "weight": "bold"},
                )

    else:
        # Scalar Dataset
        scalar_name = str(background) if (background and str(background) in data_slice) else ("w" if "w" in data_slice else list(data_slice.data_vars.keys())[0])
        sc_val = np.asarray(data_slice[scalar_name].values, dtype=float)
        if blur and float(blur) > 0.0:
            sc_val = gaussian_filter(sc_val, sigma=float(blur))
        use_cmap = cmap if cmap is not None else ("RdBu_r" if scalar_name in ("w", "vorticity", "curl", "div", "divergence") else "viridis")
        finite_vals = sc_val[np.isfinite(sc_val)]
        if clim is not None:
            vmin, vmax = float(clim[0]), float(clim[1])
        elif use_cmap == "RdBu_r":
            val_max = float(np.nanpercentile(np.abs(finite_vals), 99)) if finite_vals.size else 1.0
            val_max = max(val_max, 1e-9)
            vmin, vmax = -val_max, val_max
        else:
            vmin = float(np.nanmin(finite_vals)) if finite_vals.size else 0.0
            vmax = float(np.nanpercentile(finite_vals, 99)) if finite_vals.size else 1.0

        cf = ax.contourf(X, Y, sc_val, levels=int(levels), cmap=use_cmap, vmin=vmin, vmax=vmax, extend="both")
        if colorbar:
            cbar = fig.colorbar(cf, ax=ax, pad=0.03, shrink=0.92)
            cbar.set_label(cbar_label if cbar_label is not None else scalar_name, fontsize=11, labelpad=10)

    ax.set_aspect(aspect)
    ax.set_xlabel(f"x [{xUnits}]", fontsize=11)
    ax.set_ylabel(f"y [{yUnits}]", fontsize=11)
    if title is not None:
        ax.set_title(title, fontsize=12, fontweight="bold", pad=14)

    return fig, ax

quiver(data, quiverKey='Q', scalingFactor=1.0, widthFactor=0.002, ax=None, arrowColor='k', **kwargs)

Creates a quiver plot from the dataset

Parameters:

Name Type Description Default
data Dataset

dataset with u, v, x, y

required
quiverKey str

key for the quiver plot, by default "Q"

'Q'
scalingFactor float

scaling factor for the arrows, by default 1.0

1.0
widthFactor float

width factor for the arrows, by default 0.002

0.002
ax Axes | None

matplotlib axes, by default None

None
arrowColor str

color of the arrows, by default "k"

'k'

Returns:

Type Description
tuple[Figure, Axes]

The figure and axes used for plotting.

Examples:

>>> from pivpy import io, graphics
>>> d = io.loadvec("test.vec")
>>> graphics.quiver(d)
Source code in pivpy/graphics.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
def quiver(
    data: xr.Dataset,
    quiverKey: str | float | int = "Q",
    scalingFactor: float = 1.0,
    widthFactor: float = 0.002,
    ax: Axes | None = None,
    arrowColor: str = "k",
    **kwargs,
) -> tuple[Figure, Axes]:
    """
    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
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        The figure and axes used for plotting.

    Examples
    --------
    >>> from pivpy import io, graphics
    >>> d = io.loadvec("test.vec")
    >>> graphics.quiver(d)
    """
    from pivpy.graphics_utils import dataset_to_array

    # ------------------------------------------------------------------
    # Backwards-compatible API shims (for older notebooks/examples)
    # ------------------------------------------------------------------
    # Old signature patterns commonly used:
    # - quiver(ds, arrScale=10, nthArr=2, aspectratio=0.5, add_guide=False)
    # - quiver(ds, 5)  # positional arrScale
    # - quiver(ds, colorbar=True, cmap='Reds', width=0.0075, streamlines=True)
    if isinstance(quiverKey, (int, float)):
        # Treat the 2nd positional argument as arrScale.
        if scalingFactor == 1.0 and "arrScale" not in kwargs:
            scalingFactor = float(quiverKey)
        quiverKey = "Q"

    # Legacy aliases
    if "arrScale" in kwargs and scalingFactor == 1.0:
        scalingFactor = float(kwargs.pop("arrScale"))
    if "width" in kwargs and widthFactor == 0.002:
        widthFactor = float(kwargs.pop("width"))

    nthArr = kwargs.pop("nthArr", None)
    aspectratio = kwargs.pop("aspectratio", None)
    add_guide = kwargs.pop("add_guide", True)
    streamlines = bool(kwargs.pop("streamlines", False))
    colorbar = bool(kwargs.pop("colorbar", False))
    colorbar_orient = kwargs.pop("colorbar_orient", "vertical")
    cmap = kwargs.pop("cmap", None)
    units = kwargs.pop("units", None)

    if ax is None:
        fig, ax = plt.subplots()
    else:
        fig = ax.figure

    x, y, u, v = dataset_to_array(data)

    # Subsample vectors for display
    if nthArr is not None:
        try:
            step = int(nthArr)
        except Exception:
            step = 1
        if step and step > 1:
            x = x[::step, ::step]
            y = y[::step, ::step]
            u = u[::step, ::step]
            v = v[::step, ::step]

    # Prefer xarray attrs if present; otherwise use empty strings.
    xUnits = str(getattr(data.get("x", None), "attrs", {}).get("units", ""))
    yUnits = str(getattr(data.get("y", None), "attrs", {}).get("units", ""))
    if units and isinstance(units, (list, tuple)) and len(units) >= 2:
        xUnits = str(units[0])
        yUnits = str(units[1])

    quiver_kwargs: dict = {
        "scale": scalingFactor,
        "width": widthFactor,
    }

    # If colorbar requested, color by vector magnitude
    if colorbar:
        mag = np.sqrt(u**2 + v**2)
        Q = ax.quiver(x, y, u, v, mag, cmap=cmap, **quiver_kwargs, **kwargs)
        plt.colorbar(Q, ax=ax, orientation=colorbar_orient)
    else:
        Q = ax.quiver(x, y, u, v, color=arrowColor, **quiver_kwargs, **kwargs)

    # Aspect handling
    if aspectratio is None:
        ax.set_aspect("equal")
    elif isinstance(aspectratio, str) and aspectratio.lower() == "auto":
        ax.set_aspect("auto")
    else:
        try:
            ax.set_aspect(float(aspectratio))
        except Exception:
            ax.set_aspect("equal")

    if add_guide:
        ax.quiverkey(
            Q,
            0.9,
            0.9,
            1,
            str(quiverKey),
            labelpos="E",
            coordinates="figure",
        )
    ax.set_xlabel(f"x [{xUnits}]")
    ax.set_ylabel(f"y [{yUnits}]")

    if streamlines:
        try:
            # Use any remaining streamplot-like kwargs if provided.
            sp_density = float(kwargs.pop("density", 1.0)) if "density" in kwargs else 1.0
            sp_linewidth = float(kwargs.pop("linewidth", 1.0)) if "linewidth" in kwargs else 1.0
            sp_arrowsize = float(kwargs.pop("arrowsize", 1.0)) if "arrowsize" in kwargs else 1.0
            streamplot(data, density=sp_density, linewidth=sp_linewidth, arrowsize=sp_arrowsize, ax=ax)
        except Exception:
            # Keep quiver usable even if streamplot fails.
            pass

    return fig, ax

showf(data, **kwargs)

Display a vector or scalar field (PIVMAT-inspired dispatcher).

This is a lightweight Python analogue of PIVMAT's showf:

  • If the dataset contains u and v, it displays a vector field.
  • Otherwise, it displays a scalar field (default variable w).

Parameters:

Name Type Description Default
data Dataset

Dataset to display.

required
background

Optional scalar background shown behind vectors.

Use None/''/'off' for no background. If background matches an existing variable name, that variable is displayed. Otherwise, it is interpreted as a vector-derived flow property and computed using data.piv.vec2scal(background, name='w').

required
scalar

Scalar variable to display if the dataset is scalar-only.

required
ax

Optional axes.

required
**kwargs

Forwarded to :func:quiver (vector mode) or matplotlib pcolormesh (scalar mode). Recognized scalar kwargs: cmap, clim.

{}

Returns:

Type Description
(Figure, Axes)

Figure and axes used for plotting.

Source code in pivpy/graphics.py
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
def showf(data: xr.Dataset, **kwargs) -> tuple[plt.Figure, plt.Axes]:
    """Display a vector or scalar field (PIVMAT-inspired dispatcher).

    This is a lightweight Python analogue of PIVMAT's ``showf``:

    - If the dataset contains ``u`` and ``v``, 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. If ``background`` matches
        an existing variable name, that variable is displayed. Otherwise, it is
        interpreted as a vector-derived flow property and computed using
        ``data.piv.vec2scal(background, name='w')``.
    scalar:
        Scalar variable to display if the dataset is scalar-only.
    ax:
        Optional axes.
    **kwargs:
        Forwarded to :func:`quiver` (vector mode) or matplotlib pcolormesh
        (scalar mode). Recognized scalar kwargs: ``cmap``, ``clim``.

    Returns
    -------
    matplotlib.figure.Figure, matplotlib.axes.Axes
        Figure and axes used for plotting.
    """

    background = kwargs.pop("background", None)
    scalar = kwargs.pop("scalar", "w")
    ax = kwargs.pop("ax", None)

    is_vector = "u" in data and "v" in data
    if is_vector:
        if background is None or str(background).strip() == "" or str(background).lower() == "off":
            return quiver(data, ax=ax, **kwargs)
        # Vector field with scalar background
        fig, ax = quiver(data, ax=ax, **kwargs)
        try:
            _plot_scalar_background(ax, data, background=background, clim=kwargs.get("clim", None), cmap=kwargs.get("cmap", None))
        except Exception:
            # Keep showf usable even if background fails.
            pass
        return fig, ax

    # Scalar field
    return _showscal_axes(data, property=str(scalar), ax=ax, **kwargs)

showscal(data, property='w', **kwargs)

showscal plots the scalar field

Parameters:

Name Type Description Default
data Dataset

dataset with u, v, x, y

required
property str

property to plot, by default "w"

'w'
**kwargs

additional keyword arguments for pcolormesh

{}

Examples:

>>> from pivpy import io, graphics
>>> d = io.loadvec("test.vec")
>>> graphics.showscal(d, "chc")
Source code in pivpy/graphics.py
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
def showscal(
    data: xr.Dataset,
    property: str = "w",
    **kwargs,
) -> None:
    """
    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")
    """
    from pivpy.graphics_utils import dataset_to_array

    # Backwards-compat: tests call showscal(..., flow_property="curl")
    flow_property = kwargs.pop("flow_property", None)

    ds = data
    if flow_property is not None and property not in ds:
        try:
            ds = ds.piv.vec2scal(flow_property)
        except Exception:
            # Fall back to plotting what we have.
            ds = data

    x, y, _, _ = dataset_to_array(ds)
    if property in ds:
        plt.pcolormesh(x, y, ds[property].isel(t=0) if "t" in ds[property].dims else ds[property], **kwargs)
        plt.colorbar(label=property)
        plt.axis("equal")
    else:
        warnings.warn(f"Property {property} not found in dataset")

statvec_disp(stat_u, stat_v, ax=None, title=None)

Display vector statistics returned by statf (PIVMAT-style helper).

Source code in pivpy/graphics.py
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
def statvec_disp(stat_u: dict, stat_v: dict, ax=None, title: str | None = None):
    """Display vector statistics returned by ``statf`` (PIVMAT-style helper)."""

    import matplotlib.pyplot as plt

    if ax is None:
        fig, ax = plt.subplots(1, 1)
    else:
        fig = ax.figure

    labels = ["mean", "std", "rms", "min", "max"]
    uvals = [float(stat_u.get(k, np.nan)) for k in labels]
    vvals = [float(stat_v.get(k, np.nan)) for k in labels]

    x = np.arange(len(labels))
    ax.plot(x, uvals, "o-", label="u")
    ax.plot(x, vvals, "o-", label="v")
    ax.set_xticks(x)
    ax.set_xticklabels(labels, rotation=30, ha="right")
    ax.set_ylabel("value")
    if title is not None:
        ax.set_title(title)
    ax.legend()
    fig.tight_layout()
    return fig, ax

streamplot(data, density=1.0, linewidth=1.0, arrowsize=1.0, ax=None, **kwargs)

streamplot plots the streamlines of the vector field

Parameters:

Name Type Description Default
data Dataset

dataset with u, v, x, y

required
density float

density of the streamlines, by default 1.0

1.0
linewidth float

linewidth of the streamlines, by default 1.0

1.0
arrowsize float

size of the arrows, by default 1.0

1.0
ax Axes

Matplotlib axes (or None), by default None

None
**kwargs

additional keyword arguments for streamplot

{}

Examples:

>>> from pivpy import io, graphics
>>> d = io.loadvec("test.vec")
>>> graphics.streamplot(d)
Source code in pivpy/graphics.py
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
def streamplot(
    data: xr.Dataset,
    density: float = 1.0,
    linewidth: float = 1.0,
    arrowsize: float = 1.0,
    ax: plt.Axes | None = None,
    **kwargs,
) -> tuple["Figure", "Axes"]:
    """
    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)
    """
    from pivpy.graphics_utils import dataset_to_array

    x, y, u, v = dataset_to_array(data)

    if ax is None:
        fig, ax = plt.subplots()
    else:
        fig = ax.figure

    xUnits = str(getattr(data.get("x", None), "attrs", {}).get("units", ""))
    yUnits = str(getattr(data.get("y", None), "attrs", {}).get("units", ""))

    # Matplotlib requires strictly increasing x and y.
    x1 = x[0, :]
    y1 = y[:, 0]
    u2 = u
    v2 = v

    if y1.size >= 2 and y1[0] > y1[-1]:
        y1 = y1[::-1]
        u2 = u2[::-1, :]
        v2 = v2[::-1, :]

    if x1.size >= 2 and x1[0] > x1[-1]:
        x1 = x1[::-1]
        u2 = u2[:, ::-1]
        v2 = v2[:, ::-1]

    ax.streamplot(
        x1,
        y1,
        u2,
        v2,
        density=density,
        linewidth=linewidth,
        arrowsize=arrowsize,
        **kwargs,
    )
    ax.set_aspect("equal")
    ax.set_xlabel(f"x [{xUnits}]")
    ax.set_ylabel(f"y [{yUnits}]")

    return fig, ax

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)

Save an in-memory Dataset as a movie (fast artist-updating renderer).

Parameters:

Name Type Description Default
data Dataset

Dataset to render. If it contains a t dimension, each t step is rendered as one frame.

required
output str | Path | None

Output path (e.g. 'movie.mp4', 'movie.gif'). If None and return_frames=True, returns a list of RGBA frames.

required
show str

'auto' (default), 'vector', or 'scalar'.

'auto'
background str | None

In vector mode, optionally draw a scalar background behind vectors. See :func:showf.

None
scalar str

Variable name to render in scalar mode.

'w'
writer str | None

None (infer from extension), 'ffmpeg', or 'pillow'.

None
clim tuple[float, float] | str | None

Either a fixed (vmin, vmax) tuple, or 'each' to auto-scale per frame.

None
return_frames bool

If True, returns a list of RGBA arrays (uint8) for each frame.

False
Notes

MP4/AVI writing requires FFmpeg. GIF writing requires Pillow.

Source code in pivpy/graphics.py
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
def to_movie(
    data: xr.Dataset,
    output: str | pathlib.Path | None,
    *,
    show: str = "auto",
    background: str | None = None,
    scalar: str = "w",
    fps: int = 10,
    dpi: int = 150,
    writer: str | None = None,
    codec: str | None = None,
    title: str | None = None,
    clim: tuple[float, float] | str | None = None,
    cmap: str | None = None,
    return_frames: bool = False,
    close: bool = True,
    ax: Axes | None = None,
    **kwargs,
) -> list[np.ndarray] | None:
    """Save an in-memory Dataset as a movie (fast artist-updating renderer).

    Parameters
    ----------
    data:
        Dataset to render. If it contains a ``t`` dimension, each ``t`` step is
        rendered as one frame.
    output:
        Output path (e.g. ``'movie.mp4'``, ``'movie.gif'``). If ``None`` and
        ``return_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 :func:`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.
    """

    ds = data
    if "t" in ds.dims:
        datasets = ((ds.isel(t=i), None) for i in range(int(ds.sizes["t"])))
    else:
        datasets = ((ds, None),)

    return _movie_from_iter(
        datasets,
        output=output,
        show=show,
        background=background,
        scalar=scalar,
        fps=fps,
        dpi=dpi,
        writer=writer,
        codec=codec,
        title=title,
        clim=clim,
        cmap=cmap,
        return_frames=return_frames,
        close=close,
        ax=ax,
        **kwargs,
    )

vectorplot(data, arrowColor='k', arrowScale=1.0, arrowWidth=0.002)

vectorplot plots the vector field

Parameters:

Name Type Description Default
data Dataset

dataset with u, v, x, y

required
arrowColor str

color of the arrows, by default "k"

'k'
arrowScale float

scaling factor for the arrows, by default 1.0

1.0
arrowWidth float

width factor for the arrows, by default 0.002

0.002

Returns:

Type Description
tuple[Figure, Axes]

The figure and axes used for plotting.

Examples:

>>> from pivpy import io, graphics
>>> d = io.loadvec("test.vec")
>>> graphics.vectorplot(d)
Source code in pivpy/graphics.py
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
def vectorplot(
    data: xr.Dataset,
    arrowColor: str = "k",
    arrowScale: float = 1.0,
    arrowWidth: float = 0.002,
) -> tuple[Figure, Axes]:
    """
    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
    -------
    tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
        The figure and axes used for plotting.

    Examples
    --------
    >>> from pivpy import io, graphics
    >>> d = io.loadvec("test.vec")
    >>> graphics.vectorplot(d)
    """
    return quiver(
        data,
        arrowColor=arrowColor,
        scalingFactor=arrowScale,
        widthFactor=arrowWidth,
    )

vsf_disp(vsf, ax=None, title=None)

Display vector structure function results (PIVMAT-style helper).

Source code in pivpy/graphics.py
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
def vsf_disp(vsf: xr.Dataset, ax=None, title: str | None = None):
    """Display vector structure function results (PIVMAT-style helper)."""

    import matplotlib.pyplot as plt

    if ax is None:
        fig, ax = plt.subplots(1, 1)
    else:
        fig = ax.figure

    if "r" in vsf.coords:
        r = np.asarray(vsf["r"].values)
    else:
        raise ValueError("vsf_disp expects a Dataset with coordinate 'r'")

    for name in ["SLL", "SNN", "STT", "S2", "S3"]:
        if name in vsf.data_vars:
            ax.loglog(r, np.asarray(vsf[name].values), label=name)

    ax.set_xlabel("r")
    ax.set_ylabel("VSF")
    if title is not None:
        ax.set_title(title)
    ax.legend()
    fig.tight_layout()
    return fig, ax

pivpy.pivpy

PIVAccessor

Bases: object

extends xarray Dataset with PIVPy properties

Return-type contract, by method category (documentation of an existing, deliberate split -- not something you need to guess at):

  • Field-transform methods (crop, filterf, flipf, vorticity, averf, ...) return an xr.Dataset.
  • Plotting methods (quiver, streamplot, showf, showscal, to_movie) return (matplotlib.figure.Figure, matplotlib.axes.Axes).
  • azprofile returns a raw tuple of arrays (angle, ur, ut), not a Dataset or a plot -- it's a numerical-profile method, grouped with neither of the above.
Source code in pivpy/pivpy.py
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
@xr.register_dataset_accessor("piv")
class PIVAccessor(object):
    """extends xarray Dataset with PIVPy properties

    Return-type contract, by method category (documentation of an existing,
    deliberate split -- not something you need to guess at):

    - Field-transform methods (crop, filterf, flipf, vorticity, averf, ...)
      return an ``xr.Dataset``.
    - Plotting methods (quiver, streamplot, showf, showscal, to_movie)
      return ``(matplotlib.figure.Figure, matplotlib.axes.Axes)``.
    - ``azprofile`` returns a raw tuple of arrays (angle, ur, ut), not a
      Dataset or a plot -- it's a numerical-profile method, grouped with
      neither of the above.
    """

    def __init__(self, xarray_obj):
        """
        Arguments:
            data : xarray Dataset:
            x,y,t are coordinates
            u,v,chc are the data arrays

        We add few shortcuts (properties):
            data.piv.average is the time average (data.mean(dim='t'))
            data.piv.delta_t is the shortcut to get $\\Delta t$
            data.piv.vorticity
            data.piv.tke
            data.piv.shear

        and a few methods:
            data.piv.vec2scal()
            data.piv.pan
            data.piv.rotate

        """
        self._obj = xarray_obj
        self._average = None
        self._delta_t = None

    @property
    def average(self):
        """Return the mean flow field ."""
        if self._average is None:  # only first time
            self._average = self._obj.mean(dim="t")
            self._average.attrs = self._obj.attrs  # we need units in quiver
            self._average.assign_coords({"t": 0})

        return self._average

    def crop(self, crop_vector=None):
        """Crops xarray Dataset to specified spatial boundaries

        Args:
            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:
            xarray.Dataset: Cropped dataset

        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
        """
        if crop_vector is None:
            crop_vector = 4 * [None]

        if len(crop_vector) != 4:
            raise ValueError(
                f"crop_vector must have 4 elements [xmin, xmax, ymin, ymax], "
                f"got {len(crop_vector)} elements"
            )

        xmin, xmax, ymin, ymax = crop_vector

        xmin = self._obj.x.min() if xmin is None else xmin
        xmax = self._obj.x.max() if xmax is None else xmax
        ymin = self._obj.y.min() if ymin is None else ymin
        ymax = self._obj.y.max() if ymax is None else ymax

        # Note: We don't validate xmin < xmax or ymin < ymax because coordinates
        # might be in reverse order (e.g., negative y-axis pointing down)

        warnings.warn(
            "piv.crop() currently rebinds this accessor's internal dataset "
            "reference as a side effect; a future release will make it a pure "
            "function that only returns the cropped dataset. Always use the "
            "return value (`ds = ds.piv.crop(...)`) rather than relying on "
            "in-place state.",
            DeprecationWarning,
            stacklevel=2,
        )
        self._obj = self._obj.sel(x=slice(xmin, xmax), y=slice(ymin, ymax))

        return self._obj

    def extractf(
        self,
        rect,
        opt: str = "phys",
        *,
        return_rect: bool = False,
    ):
        """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)`` where
            ``rect_mesh`` is ``[ix1, iy1, ix2, iy2]`` (1-based, inclusive).

        Notes
        -----
        Interactive rectangle selection (PIVMAT's 'draw') is not supported.
        """

        ds = self._obj
        if rect is None:
            raise ValueError("extractf requires rect=[x1, y1, x2, y2]")
        if isinstance(rect, str) and rect.lower().startswith("draw"):
            raise NotImplementedError("Interactive rectangle selection is not supported; pass rect explicitly.")

        if not hasattr(rect, "__len__") or len(rect) != 4:
            raise ValueError("rect must be a sequence of 4 values: [x1, y1, x2, y2]")

        x1, y1, x2, y2 = rect

        if "x" not in ds.dims or "y" not in ds.dims:
            raise ValueError("extractf requires dataset dims 'x' and 'y'")

        def _bounds_from_phys(coord_vals: np.ndarray, a: float, b: float) -> tuple[int, int]:
            vals = np.asarray(coord_vals, dtype=float)
            n = int(vals.shape[0])
            if n == 0:
                return 0, -1
            if n == 1:
                return 0, 0

            lo = float(min(a, b))
            hi = float(max(a, b))

            reversed_axis = bool(vals[1] < vals[0])
            sorted_vals = vals[::-1] if reversed_axis else vals

            i1 = int(np.searchsorted(sorted_vals, lo, side="right") - 1)
            i2 = int(np.searchsorted(sorted_vals, hi, side="left"))

            if i1 < 0:
                i1 = 0
            if i2 < 0:
                i2 = 0
            if i1 > n - 1:
                i1 = n - 1
            if i2 > n - 1:
                i2 = n - 1

            if reversed_axis:
                start = (n - 1) - i2
                stop = (n - 1) - i1
            else:
                start = i1
                stop = i2

            if start > stop:
                # Degenerate selection: choose nearest index.
                target = 0.5 * (lo + hi)
                nearest = int(np.argmin(np.abs(vals - target)))
                return nearest, nearest

            return int(start), int(stop)

        def _bounds_from_mesh(n: int, a: float, b: float) -> tuple[int, int]:
            if n <= 0:
                return 0, -1
            lo = int(np.floor(min(a, b))) - 1
            hi = int(np.ceil(max(a, b))) - 1
            lo = max(lo, 0)
            hi = min(hi, n - 1)
            if lo > hi:
                lo = hi
            return lo, hi

        opt_l = str(opt).lower()
        if opt_l.startswith("phys"):
            xs, xe = _bounds_from_phys(ds["x"].values, float(x1), float(x2))
            ys, ye = _bounds_from_phys(ds["y"].values, float(y1), float(y2))
        elif opt_l.startswith("mesh"):
            xs, xe = _bounds_from_mesh(int(ds.sizes["x"]), float(x1), float(x2))
            ys, ye = _bounds_from_mesh(int(ds.sizes["y"]), float(y1), float(y2))
        else:
            raise ValueError("opt must be 'phys' or 'mesh'")

        out = ds.isel(x=slice(xs, xe + 1), y=slice(ys, ye + 1))
        out.attrs = dict(ds.attrs)
        self._obj = out

        mesh_rect = [xs + 1, ys + 1, xe + 1, ye + 1]
        if return_rect:
            return out, mesh_rect
        return out

    def pan(self, shift_x=0.0, shift_y=0.0):
        """Shifts the coordinate system by specified amounts

        Args:
            shift_x (float): Amount to shift in x direction. Defaults to 0.0.
            shift_y (float): Amount to shift in y direction. Defaults to 0.0.

        Returns:
            xarray.Dataset: Dataset with shifted coordinates

        Example:
            >>> data = data.piv.pan(10.0, -5.0)  # Shift x by +10, y by -5
        """
        self._obj = self._obj.assign_coords(
            {"x": self._obj.x + shift_x, "y": self._obj.y + shift_y}
        )
        return self._obj

    def clip(
        self,
        min=None,
        max=None,
        *,
        by: str = None,
        keep_attrs: bool = True,
    ):
        """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).

        Args:
            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:
            xarray.Dataset: Dataset with clipped values. If 'by' is specified, returns
                dataset with locations that don't meet the criteria set to NaN.

        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
        """
        if min is None and max is None:
            raise ValueError("At least one of 'min' or 'max' must be provided")

        if by is None:
            # Clip all variables independently using xarray's built-in clip
            return self._obj.clip(min=min, max=max, keep_attrs=keep_attrs)

        # Clip based on a specific variable
        if by == "magnitude":
            # Compute magnitude if not already in dataset
            criterion = np.sqrt(self._obj["u"] ** 2 + self._obj["v"] ** 2)
        else:
            # Use existing variable
            if by not in self._obj:
                raise ValueError(
                    f"Variable '{by}' not found in dataset. "
                    f"Available variables: {list(self._obj.data_vars)}"
                )
            criterion = self._obj[by]

        # Create mask based on criterion
        mask = xr.ones_like(criterion, dtype=bool)
        if min is not None:
            mask = mask & (criterion >= min)
        if max is not None:
            mask = mask & (criterion <= max)

        # Apply mask to all data variables (set non-matching locations to NaN)
        result = self._obj.copy()
        for var in result.data_vars:
            result[var] = result[var].where(mask)

        if not keep_attrs:
            result.attrs = {}
            for var in result.data_vars:
                result[var].attrs = {}

        return result

    def filterf(self, sigma: List[float] | float = [1.0, 1.0, 0.0], method: str = "gauss", *opts: str, **kwargs):
        """Apply a spatial filter to a vector/scalar field (PIVMAT-inspired).

        This method supports two calling conventions:

        1) 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``.

        2) PIVMAT-style normalized 2D convolution (NaN-aware)::

             ds = ds.piv.filterf(filtsize, method, 'same')
             ds = ds.piv.filterf(filtsize, method)         # default is 'valid'

           where ``method`` is one of: ``'gauss'`` (default), ``'flat'``, ``'igauss'``.
           The option ``'same'`` keeps the original shape; otherwise the result is
           smaller (Matlab ``conv2(...,'valid')`` behavior) and the x/y coordinates are
           truncated accordingly.
        """

        # --- Legacy path: sigma is a 3-vector
        if isinstance(sigma, (list, tuple, np.ndarray)):
            sigma_list = list(sigma)
            if len(sigma_list) != 3:
                raise ValueError(
                    f"sigma must have 3 elements [sigma_y, sigma_x, sigma_t], got {len(sigma_list)} elements"
                )
            if any(float(s) < 0 for s in sigma_list):
                raise ValueError(f"All sigma values must be non-negative, got {sigma_list}")

            self._obj["u"] = xr.DataArray(
                gaussian_filter(self._obj["u"].values, sigma_list, **kwargs),
                dims=("y", "x", "t"),
                attrs=self._obj["u"].attrs,
            )
            self._obj["v"] = xr.DataArray(
                gaussian_filter(self._obj["v"].values, sigma_list, **kwargs),
                dims=("y", "x", "t"),
                attrs=self._obj["v"].attrs,
            )
            return self._obj

        # --- PIVMAT-style path: sigma is actually filtsize (float)
        if kwargs:
            raise TypeError(
                "PIVMAT-style filterf(filtsize, ...) does not accept **kwargs. "
                "Pass a 3-element sigma list for gaussian_filter kwargs."
            )

        ds = self._obj
        if "x" not in ds.dims or "y" not in ds.dims:
            raise ValueError("filterf requires spatial dims 'y' and 'x'")

        fs = float(sigma)
        if fs == 0.0:
            return ds

        mode = "valid"
        for opt in opts:
            o = str(opt).lower()
            if o.startswith("same"):
                mode = "same"
            elif o.startswith("valid"):
                mode = "valid"
            elif o == "":
                continue
            else:
                raise ValueError(f"Unknown filterf option: {opt!r}")

        k = filter2d_kernel(fs, method)
        ky, kx = (int(k.shape[0]), int(k.shape[1]))
        ny = int(ds.sizes["y"])
        nx = int(ds.sizes["x"])
        if mode == "same":
            ny_out, nx_out = ny, nx
            base = ds
        else:
            ny_out = ny - ky + 1
            nx_out = nx - kx + 1
            if ny_out <= 0 or nx_out <= 0:
                raise ValueError("filter kernel larger than input")

            ly = (ky - 1) // 2
            ry = (ky - 1) - ly
            lx = (kx - 1) // 2
            rx = (kx - 1) - lx
            base = ds.isel(y=slice(ly, ny - ry), x=slice(lx, nx - rx))

        def _core(a2: np.ndarray) -> np.ndarray:
            return filter2d(a2, fs, method, mode=mode)

        out = base.copy(deep=True)
        for name in ("u", "v"):
            if name not in out.data_vars:
                continue
            da_in = ds[name]
            da_out_template = out[name]
            if "y" not in da_in.dims or "x" not in da_in.dims:
                continue
            filtered = xr.apply_ufunc(
                _core,
                da_in,
                input_core_dims=[["y", "x"]],
                output_core_dims=[["y", "x"]],
                exclude_dims={"y", "x"},
                vectorize=True,
                dask="parallelized",
                dask_gufunc_kwargs={"output_sizes": {"y": ny_out, "x": nx_out}},
                output_dtypes=[float],
            )
            # Preserve original dim order (typically ('y','x','t')).
            filtered = filtered.transpose(*da_in.dims)
            # Attach the truncated coordinates from the base dataset.
            filtered = filtered.assign_coords({"y": base["y"], "x": base["x"]})
            out[name] = filtered
            out[name].attrs = dict(ds[name].attrs)

        out.attrs = dict(ds.attrs)
        self._obj = out
        return out

    def bwfilterf(
        self,
        filtsize: float = 3.0,
        order: float = 8.0,
        *,
        mode: Literal["low", "high"] = "low",
        trunc: bool = False,
        var: Optional[str] = None,
        variables: Optional[List[str]] = None,
    ) -> xr.Dataset:
        """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.
        """

        fs = float(filtsize)
        if fs == 0.0:
            return self._obj

        ds = self._obj
        if "x" not in ds.dims or "y" not in ds.dims:
            raise ValueError("bwfilterf requires spatial dims 'y' and 'x'")

        ord_eff = float(order)
        if str(mode).lower().startswith("high"):
            ord_eff = -abs(ord_eff)
        else:
            ord_eff = abs(ord_eff)

        # PIVMAT behavior: enforce even spatial sizes by dropping last row/col.
        out = ds
        if int(out.sizes["x"]) % 2 == 1:
            out = out.isel(x=slice(0, -1))
        if int(out.sizes["y"]) % 2 == 1:
            out = out.isel(y=slice(0, -1))

        if variables is None:
            if var is not None:
                variables = [var]
            else:
                variables = [v for v in ("u", "v") if v in out.data_vars]
                if not variables:
                    raise ValueError("bwfilterf: no variables to filter (expected 'u'/'v' or var=...)")
        else:
            variables = list(variables)
            for v in variables:
                if v not in out.data_vars:
                    raise ValueError(f"Variable '{v}' not found in dataset")

        def _bw_core(a2: np.ndarray) -> np.ndarray:
            return bwfilter2d(a2, fs, ord_eff)

        out2 = out.copy(deep=True)
        for name in variables:
            da = out2[name]
            if "y" not in da.dims or "x" not in da.dims:
                continue
            out2[name] = xr.apply_ufunc(
                _bw_core,
                da,
                input_core_dims=[["y", "x"]],
                output_core_dims=[["y", "x"]],
                vectorize=True,
                dask="parallelized",
                output_dtypes=[float],
            )
            out2[name].attrs = dict(out[name].attrs)

        if trunc:
            ntr = int(np.floor(fs))
            if ntr > 0:
                ny = int(out2.sizes["y"])
                nx = int(out2.sizes["x"])
                if 2 * ntr >= ny or 2 * ntr >= nx:
                    raise ValueError("truncation too large for field size")
                out2 = out2.isel(y=slice(ntr, -ntr), x=slice(ntr, -ntr))

        out2.attrs = dict(out.attrs)
        self._obj = out2
        return out2

    def bwfilterf_pm(
        self,
        filtsize: float,
        order: float,
        *opts: str,
        var: Optional[str] = None,
        variables: Optional[List[str]] = None,
    ) -> xr.Dataset:
        """PIVMAT-compatible wrapper for :meth:`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')``
        """

        mode: Literal["low", "high"] = "low"
        trunc = False
        for opt in opts:
            o = str(opt).lower()
            if o.startswith("high"):
                mode = "high"
            elif o.startswith("low"):
                mode = "low"
            elif o.startswith("trunc"):
                trunc = True
            elif o == "":
                continue
            else:
                raise ValueError(f"Unknown bwfilterf option: {opt!r}")

        return self.bwfilterf(
            filtsize=float(filtsize),
            order=float(order),
            mode=mode,
            trunc=trunc,
            var=var,
            variables=variables,
        )

    def flipf(self, dir: str = "x") -> xr.Dataset:
        """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.
        """

        ds = self._obj
        d = str(dir)
        dl = d.lower()
        if dl in ("", "none"):
            return ds

        if dl not in ("x", "y", "xy", "yx"):
            raise ValueError("dir must be one of: 'x', 'y', 'xy', 'yx', ''")

        flip_x = "x" in dl
        flip_y = "y" in dl

        if (flip_x and "x" not in ds.dims) or (flip_y and "y" not in ds.dims):
            raise ValueError("flipf requires spatial dims 'x' and 'y'")

        out = ds.copy(deep=True)
        if flip_x:
            rev_x = np.arange(int(ds.sizes["x"]) - 1, -1, -1)
        if flip_y:
            rev_y = np.arange(int(ds.sizes["y"]) - 1, -1, -1)

        for name, da in ds.data_vars.items():
            flipped = da
            if flip_x and "x" in da.dims:
                flipped = flipped.isel(x=rev_x).assign_coords(x=ds["x"])
            if flip_y and "y" in da.dims:
                flipped = flipped.isel(y=rev_y).assign_coords(y=ds["y"])

            # Velocity sign convention: u is x-component, v is y-component.
            if flip_x and name in ("u", "vx"):
                flipped = -flipped
            if flip_y and name in ("v", "vy"):
                flipped = -flipped

            flipped.attrs = dict(da.attrs)
            out[name] = flipped

        out.attrs = dict(ds.attrs)
        self._obj = out
        return out

    def addnoisef(
        self,
        eps: float = 0.1,
        opt: Literal["add", "mul"] = "add",
        nc: float = 0.0,
        seed: Optional[int] = None,
    ):
        """Adds normally-distributed white noise to velocity fields.

        This method is inspired by PIVMat's `addnoisef`.

        Args:
            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:
            xarray.Dataset: Dataset with noisy u/v.
        """

        if eps is None or float(eps) == 0.0:
            return self._obj

        opt_l = str(opt).lower()
        if not (opt_l.startswith("add") or opt_l.startswith("mul")):
            raise ValueError("opt must be 'add' or 'mul'")

        if "u" not in self._obj or "v" not in self._obj:
            raise ValueError("Dataset must contain 'u' and 'v' variables")

        u0 = np.asarray(self._obj["u"].values)
        v0 = np.asarray(self._obj["v"].values)
        if u0.ndim != 3 or v0.ndim != 3:
            raise ValueError("Expected 'u' and 'v' to have dims ('y','x','t')")

        # Use a single reference scale for both components.
        ref_std = float(np.nanstd(np.stack([u0, v0], axis=0)))
        if not np.isfinite(ref_std) or ref_std == 0.0:
            ref_std = 1.0

        rng = np.random.default_rng(seed)

        # Convert smoothing length (in coordinate units) to gaussian sigma (in grid points).
        sigma_yx = None
        if nc is not None and float(nc) != 0.0:
            try:
                x = np.asarray(self._obj.coords["x"].values, dtype=float)
                y = np.asarray(self._obj.coords["y"].values, dtype=float)
                dx = float(np.nanmedian(np.diff(x))) if x.size >= 2 else 1.0
                dy = float(np.nanmedian(np.diff(y))) if y.size >= 2 else 1.0
                dx = abs(dx) if dx != 0 else 1.0
                dy = abs(dy) if dy != 0 else 1.0
                sigma_yx = (abs(float(nc)) / dy, abs(float(nc)) / dx)
            except Exception:
                sigma_yx = (abs(float(nc)), abs(float(nc)))

        u = u0.copy()
        v = v0.copy()

        for ti in range(u.shape[2]):
            nu = rng.standard_normal(size=u.shape[:2])
            nv = rng.standard_normal(size=v.shape[:2])

            if sigma_yx is not None:
                nu = gaussian_filter(nu, sigma=sigma_yx, mode="nearest")
                nv = gaussian_filter(nv, sigma=sigma_yx, mode="nearest")
                # Keep noise level roughly independent of smoothing.
                s_nu = float(np.nanstd(nu))
                s_nv = float(np.nanstd(nv))
                if s_nu > 0:
                    nu = nu / s_nu
                if s_nv > 0:
                    nv = nv / s_nv

            if opt_l.startswith("add"):
                u[:, :, ti] = u[:, :, ti] + nu * float(eps) * ref_std
                v[:, :, ti] = v[:, :, ti] + nv * float(eps) * ref_std
            else:
                u[:, :, ti] = u[:, :, ti] * (1.0 + nu * float(eps))
                v[:, :, ti] = v[:, :, ti] * (1.0 + nv * float(eps))

        self._obj["u"].values[...] = u
        self._obj["v"].values[...] = v
        return self._obj

    def averf(
        self,
        opt: str = "",
        *,
        return_std_rms: bool = False,
    ):
        """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'.

        Args:
            opt: Option string. If it contains '0', zeros are included.
            return_std_rms: If True, also returns (std, rms) as scalar fields.

        Returns:
            xarray.Dataset: Averaged dataset (single-frame, t=0) if ``return_std_rms=False``.
            tuple: ``(avg, std, rms)`` if ``return_std_rms=True``.
        """

        include_zeros = "0" in str(opt)

        ds = self._obj
        if "t" not in ds.dims:
            raise ValueError("averf requires a time dimension 't'")

        def _mean_excluding_zeros(arr: np.ndarray) -> np.ndarray:
            # arr is (y, x, t)
            valid = np.isfinite(arr)
            if not include_zeros:
                valid = valid & (arr != 0)
            out = np.zeros(arr.shape[:2], dtype=float)
            if include_zeros:
                out = np.nanmean(arr, axis=2)
                out = np.nan_to_num(out, nan=0.0)
                return out
            denom = valid.sum(axis=2)
            num = np.where(valid, arr, 0.0).sum(axis=2)
            with np.errstate(divide="ignore", invalid="ignore"):
                out = num / denom
            out = np.nan_to_num(out, nan=0.0, posinf=0.0, neginf=0.0)
            return out

        # Vector field mode if u/v exist, else scalar mode if w exists.
        if "u" in ds and "v" in ds:
            u0 = np.asarray(ds["u"].values, dtype=float)
            v0 = np.asarray(ds["v"].values, dtype=float)
            if u0.ndim != 3 or v0.ndim != 3:
                raise ValueError("Expected 'u' and 'v' to have dims ('y','x','t')")

            u_mean = _mean_excluding_zeros(u0)
            v_mean = _mean_excluding_zeros(v0)

            avg = ds.isel(t=[0]).copy(deep=True)
            avg = avg.drop_vars([v for v in avg.data_vars if v not in {"u", "v", "chc", "mask"}], errors="ignore")
            avg["u"] = xr.DataArray(u_mean[:, :, None], dims=("y", "x", "t"), attrs=ds["u"].attrs)
            avg["v"] = xr.DataArray(v_mean[:, :, None], dims=("y", "x", "t"), attrs=ds["v"].attrs)
            avg = avg.assign_coords(t=np.asarray([0.0], dtype=float))
            avg.attrs = dict(ds.attrs)

            if not return_std_rms:
                return avg

            # STD and RMS as scalar fields (combined magnitude) like PIVMat.
            finite = np.isfinite(u0) & np.isfinite(v0)
            if include_zeros:
                valid = finite
            else:
                valid = finite & (u0 != 0) & (v0 != 0)

            denom = valid.sum(axis=2).astype(float)
            denom_safe = np.where(denom == 0, np.nan, denom)

            du = u0 - u_mean[:, :, None]
            dv = v0 - v_mean[:, :, None]

            std_sq = np.where(valid, du * du + dv * dv, 0.0).sum(axis=2) / denom_safe
            rms_sq = np.where(valid, u0 * u0 + v0 * v0, 0.0).sum(axis=2) / denom_safe
            std_field = np.sqrt(std_sq)
            rms_field = np.sqrt(rms_sq)
            std_field = np.nan_to_num(std_field, nan=0.0)
            rms_field = np.nan_to_num(rms_field, nan=0.0)

            std_ds = ds.isel(t=[0]).copy(deep=True)
            rms_ds = ds.isel(t=[0]).copy(deep=True)
            std_ds = std_ds.drop_vars(list(std_ds.data_vars), errors="ignore")
            rms_ds = rms_ds.drop_vars(list(rms_ds.data_vars), errors="ignore")

            units = ds["u"].attrs.get("units", "")
            std_ds["w"] = xr.DataArray(std_field[:, :, None], dims=("y", "x", "t"), attrs={"standard_name": "standard_deviation", "units": units})
            rms_ds["w"] = xr.DataArray(rms_field[:, :, None], dims=("y", "x", "t"), attrs={"standard_name": "root_mean_square", "units": units})
            std_ds = std_ds.assign_coords(t=np.asarray([0.0], dtype=float))
            rms_ds = rms_ds.assign_coords(t=np.asarray([0.0], dtype=float))
            std_ds.attrs = dict(ds.attrs)
            rms_ds.attrs = dict(ds.attrs)
            return avg, std_ds, rms_ds

        if "w" in ds:
            w0 = np.asarray(ds["w"].values, dtype=float)
            if w0.ndim != 3:
                raise ValueError("Expected 'w' to have dims ('y','x','t')")
            w_mean = _mean_excluding_zeros(w0)
            avg = ds.isel(t=[0]).copy(deep=True)
            avg = avg.drop_vars([v for v in avg.data_vars if v != "w"], errors="ignore")
            avg["w"] = xr.DataArray(w_mean[:, :, None], dims=("y", "x", "t"), attrs=ds["w"].attrs)
            avg = avg.assign_coords(t=np.asarray([0.0], dtype=float))
            avg.attrs = dict(ds.attrs)
            if not return_std_rms:
                return avg

            finite = np.isfinite(w0)
            valid = finite if include_zeros else (finite & (w0 != 0))
            denom = valid.sum(axis=2).astype(float)
            denom_safe = np.where(denom == 0, np.nan, denom)
            dw = w0 - w_mean[:, :, None]
            std_sq = np.where(valid, dw * dw, 0.0).sum(axis=2) / denom_safe
            rms_sq = np.where(valid, w0 * w0, 0.0).sum(axis=2) / denom_safe
            std_field = np.nan_to_num(np.sqrt(std_sq), nan=0.0)
            rms_field = np.nan_to_num(np.sqrt(rms_sq), nan=0.0)

            units = ds["w"].attrs.get("units", "")
            std_ds = ds.isel(t=[0]).copy(deep=True)
            rms_ds = ds.isel(t=[0]).copy(deep=True)
            std_ds = std_ds.drop_vars(list(std_ds.data_vars), errors="ignore")
            rms_ds = rms_ds.drop_vars(list(rms_ds.data_vars), errors="ignore")
            std_ds["w"] = xr.DataArray(std_field[:, :, None], dims=("y", "x", "t"), attrs={"standard_name": "standard_deviation", "units": units})
            rms_ds["w"] = xr.DataArray(rms_field[:, :, None], dims=("y", "x", "t"), attrs={"standard_name": "root_mean_square", "units": units})
            std_ds = std_ds.assign_coords(t=np.asarray([0.0], dtype=float))
            rms_ds = rms_ds.assign_coords(t=np.asarray([0.0], dtype=float))
            std_ds.attrs = dict(ds.attrs)
            rms_ds.attrs = dict(ds.attrs)
            return avg, std_ds, rms_ds

        raise ValueError("Dataset must contain either ('u','v') or 'w' to use averf")

    def azaverf(
        self,
        x0: float = 0.0,
        y0: float = 0.0,
        *,
        center_units: Literal["phys", "mesh"] = "phys",
        rmax: Optional[float] = None,
        keepzero: bool = False,
        return_profiles: bool = False,
        var: Optional[str] = None,
        frame: Optional[int] = None,
    ):
        """Azimuthal average of a vector/scalar field.

        Inspired by PIVMAT's ``azaverf``.

        Parameters
        ----------
        x0, 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_profiles`` is False, returns an averaged dataset.

        tuple
            If ``return_profiles`` is True:
            - Vector mode: ``(r, ur, ut)``
            - Scalar mode: ``(r, p)``
        """

        ds = self._obj
        if "x" not in ds.coords or "y" not in ds.coords:
            raise ValueError("azaverf requires 'x' and 'y' coordinates")

        x = np.asarray(ds.coords["x"].values, dtype=float)
        y = np.asarray(ds.coords["y"].values, dtype=float)
        if x.size < 2 or y.size < 2:
            raise ValueError("azaverf requires at least 2 points in x and y")

        dx = float(np.nanmedian(np.diff(x)))
        dy = float(np.nanmedian(np.diff(y)))
        dx_abs = abs(dx) if dx != 0 else 1.0
        dy_abs = abs(dy) if dy != 0 else 1.0
        dr = dx_abs
        if not np.isfinite(dr) or dr == 0.0:
            dr = 1.0

        if center_units == "mesh":
            # x0/y0 are 0-based indices into x/y.
            x0_phys = float(x[0] + x0 * dx)
            y0_phys = float(y[0] + y0 * dy)
            rmax_phys = None if rmax is None else float(rmax) * dr
        elif center_units == "phys":
            x0_phys = float(x0)
            y0_phys = float(y0)
            rmax_phys = None if rmax is None else float(rmax)
        else:
            raise ValueError("center_units must be 'phys' or 'mesh'")

        X, Y = np.meshgrid(x, y)
        dX = X - x0_phys
        dY = Y - y0_phys
        R = np.sqrt(dX * dX + dY * dY)
        if rmax_phys is not None:
            Rmask = R <= rmax_phys
        else:
            Rmask = np.ones_like(R, dtype=bool)

        # Bin index: 0 corresponds to r in [0, dr)
        bin_idx = np.floor(R / dr).astype(int)
        # Exclude center where projections are undefined.
        not_center = R > 0

        if "t" in ds.dims:
            t_indices = list(range(int(ds.sizes["t"])))
        else:
            # Treat as single frame.
            t_indices = [0]

        if frame is not None:
            frame_i = int(frame)
            t_indices = [frame_i]

        # Decide scalar vs vector mode.
        scalar_mode = var is not None
        if scalar_mode:
            if var not in ds:
                raise ValueError(f"Scalar variable '{var}' not found in dataset")
        else:
            if "u" not in ds or "v" not in ds:
                raise ValueError("Vector mode azaverf requires 'u' and 'v'")

        maxbin = int(np.nanmax(bin_idx[Rmask])) if np.any(Rmask) else 0
        # Preallocate profiles across time.
        if scalar_mode:
            prof = np.full((maxbin + 1, len(t_indices)), np.nan, dtype=float)
            counts_any = np.zeros((maxbin + 1,), dtype=int)
        else:
            prof_ur = np.full((maxbin + 1, len(t_indices)), np.nan, dtype=float)
            prof_ut = np.full((maxbin + 1, len(t_indices)), np.nan, dtype=float)
            counts_any = np.zeros((maxbin + 1,), dtype=int)

        # Flatten helpers.
        bin_flat = bin_idx.ravel()
        R_flat = R.ravel()
        dX_flat = dX.ravel()
        dY_flat = dY.ravel()
        base_mask_flat = (Rmask & not_center).ravel()

        for k, ti in enumerate(t_indices):
            if "t" in ds.dims:
                if scalar_mode:
                    A = np.asarray(ds[var].isel(t=ti).values, dtype=float)
                else:
                    U = np.asarray(ds["u"].isel(t=ti).values, dtype=float)
                    V = np.asarray(ds["v"].isel(t=ti).values, dtype=float)
            else:
                if scalar_mode:
                    A = np.asarray(ds[var].values, dtype=float)
                else:
                    U = np.asarray(ds["u"].values, dtype=float)
                    V = np.asarray(ds["v"].values, dtype=float)

            if scalar_mode:
                A_flat = A.ravel()
                finite = np.isfinite(A_flat)
                valid = base_mask_flat & finite
                if not keepzero:
                    valid = valid & (A_flat != 0)
                if not np.any(valid):
                    continue
                cnt = np.bincount(bin_flat[valid], minlength=maxbin + 1)
                s = np.bincount(bin_flat[valid], weights=A_flat[valid], minlength=maxbin + 1)
                with np.errstate(divide="ignore", invalid="ignore"):
                    p = s / cnt
                prof[:, k] = p
                counts_any = np.maximum(counts_any, cnt)
            else:
                U_flat = U.ravel()
                V_flat = V.ravel()
                finite = np.isfinite(U_flat) & np.isfinite(V_flat)
                valid = base_mask_flat & finite
                if not keepzero:
                    valid = valid & (U_flat != 0) & (V_flat != 0)
                if not np.any(valid):
                    continue

                with np.errstate(divide="ignore", invalid="ignore"):
                    ur_pt = (U_flat * dX_flat + V_flat * dY_flat) / R_flat
                    ut_pt = (-U_flat * dY_flat + V_flat * dX_flat) / R_flat

                cnt = np.bincount(bin_flat[valid], minlength=maxbin + 1)
                sur = np.bincount(bin_flat[valid], weights=ur_pt[valid], minlength=maxbin + 1)
                sut = np.bincount(bin_flat[valid], weights=ut_pt[valid], minlength=maxbin + 1)
                with np.errstate(divide="ignore", invalid="ignore"):
                    ur = sur / cnt
                    ut = sut / cnt
                prof_ur[:, k] = ur
                prof_ut[:, k] = ut
                counts_any = np.maximum(counts_any, cnt)

        nonzero_bins = np.nonzero(counts_any)[0]
        if nonzero_bins.size == 0:
            if return_profiles:
                if scalar_mode:
                    return np.asarray([]), np.asarray([[]])
                return np.asarray([]), np.asarray([[]]), np.asarray([[]])
            # Return zeros field of same shape.
            out = ds.copy(deep=True)
            if scalar_mode:
                out[var] = out[var] * 0
            else:
                out["u"] = out["u"] * 0
                out["v"] = out["v"] * 0
            return out

        first_bin = int(nonzero_bins[0])
        last_bin = int(nonzero_bins[-1])
        r_vec = (np.arange(first_bin, last_bin + 1, dtype=float) * dr)

        if return_profiles:
            if scalar_mode:
                return r_vec, prof[first_bin : last_bin + 1, :]
            return r_vec, prof_ur[first_bin : last_bin + 1, :], prof_ut[first_bin : last_bin + 1, :]

        # Build azimuthally averaged field.
        out = ds.copy(deep=True)

        # Reconstruct per-frame fields from profiles.
        bin2 = bin_idx.copy()
        in_range = (bin2 >= first_bin) & (bin2 <= last_bin) & not_center & Rmask
        # Prepare output arrays.
        if "t" in ds.dims:
            t_full = int(ds.sizes["t"])
            if frame is None:
                t_out_indices = list(range(t_full))
                prof_cols = {ti: idx for idx, ti in enumerate(t_indices)}
            else:
                t_out_indices = [int(frame)]
                prof_cols = {int(frame): 0}
        else:
            t_out_indices = [0]
            prof_cols = {0: 0}

        if scalar_mode:
            # Set values by bin, outside range -> 0.
            if "t" in ds.dims:
                for ti in t_out_indices:
                    col = prof_cols.get(ti, None)
                    if col is None:
                        out[var].isel(t=ti).values[...] = 0.0
                        continue
                    p_full = np.zeros((maxbin + 1,), dtype=float)
                    p_slice = prof[:, col]
                    p_full[:] = np.nan_to_num(p_slice, nan=0.0)
                    w_new = np.zeros_like(R)
                    w_new[in_range] = p_full[bin2[in_range]]
                    out[var].isel(t=ti).values[...] = w_new
            else:
                p_full = np.zeros((maxbin + 1,), dtype=float)
                p_full[:] = np.nan_to_num(prof[:, 0], nan=0.0)
                w_new = np.zeros_like(R)
                w_new[in_range] = p_full[bin2[in_range]]
                out[var].values[...] = w_new
            return out

        # Vector mode.
        if "t" in ds.dims:
            for ti in t_out_indices:
                col = prof_cols.get(ti, None)
                if col is None:
                    out["u"].isel(t=ti).values[...] = 0.0
                    out["v"].isel(t=ti).values[...] = 0.0
                    continue
                ur_full = np.zeros((maxbin + 1,), dtype=float)
                ut_full = np.zeros((maxbin + 1,), dtype=float)
                ur_full[:] = np.nan_to_num(prof_ur[:, col], nan=0.0)
                ut_full[:] = np.nan_to_num(prof_ut[:, col], nan=0.0)
                ur_grid = np.zeros_like(R)
                ut_grid = np.zeros_like(R)
                ur_grid[in_range] = ur_full[bin2[in_range]]
                ut_grid[in_range] = ut_full[bin2[in_range]]

                u_new = np.zeros_like(R)
                v_new = np.zeros_like(R)
                # u = ur * cos(theta) - ut * sin(theta) where cos=dx/r, sin=dy/r
                u_new[in_range] = ur_grid[in_range] * (dX[in_range] / R[in_range]) - ut_grid[in_range] * (dY[in_range] / R[in_range])
                v_new[in_range] = ur_grid[in_range] * (dY[in_range] / R[in_range]) + ut_grid[in_range] * (dX[in_range] / R[in_range])
                out["u"].isel(t=ti).values[...] = u_new
                out["v"].isel(t=ti).values[...] = v_new
        else:
            ur_full = np.zeros((maxbin + 1,), dtype=float)
            ut_full = np.zeros((maxbin + 1,), dtype=float)
            ur_full[:] = np.nan_to_num(prof_ur[:, 0], nan=0.0)
            ut_full[:] = np.nan_to_num(prof_ut[:, 0], nan=0.0)
            ur_grid = np.zeros_like(R)
            ut_grid = np.zeros_like(R)
            ur_grid[in_range] = ur_full[bin2[in_range]]
            ut_grid[in_range] = ut_full[bin2[in_range]]
            u_new = np.zeros_like(R)
            v_new = np.zeros_like(R)
            u_new[in_range] = ur_grid[in_range] * (dX[in_range] / R[in_range]) - ut_grid[in_range] * (dY[in_range] / R[in_range])
            v_new[in_range] = ur_grid[in_range] * (dY[in_range] / R[in_range]) + ut_grid[in_range] * (dX[in_range] / R[in_range])
            out["u"].values[...] = u_new
            out["v"].values[...] = v_new

        return out

    def azprofile(
        self,
        x0: float = 0.0,
        y0: float = 0.0,
        r: float = 1.0,
        na: int | None = None,
        *,
        var: str | None = None,
        frame: int | None = None,
        angle_dim: str = "angle",
    ):
        """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, y0:
            Circle center in the same units as coordinates ``x`` and ``y``.
        r:
            Circle radius.
        na:
            Number of angular samples. If None, uses PIVMAT's default heuristic
            ``round(4*r/abs(dx))`` where ``dx`` is the x-grid spacing.
        var:
            Scalar variable to sample. If None, samples vector components ``u`` and ``v``
            and 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
        ``frame`` is None, the profiles have shape ``(na, nt)``.
        """

        ds = self._obj
        if "x" not in ds.coords or "y" not in ds.coords:
            raise ValueError("azprofile requires 'x' and 'y' coordinates")

        x = np.asarray(ds.coords["x"].values, dtype=float)
        if x.size < 2:
            raise ValueError("azprofile requires at least 2 x points")
        dx = float(np.nanmedian(np.diff(x)))
        dx_abs = abs(dx) if np.isfinite(dx) and dx != 0 else 1.0
        if na is None:
            na = int(round(4.0 * float(r) / dx_abs))
        na = int(na)
        if na <= 0:
            raise ValueError("na must be positive")

        angle = np.linspace(0.0, 2.0 * np.pi, na, endpoint=False)
        x_s = x0 + float(r) * np.cos(angle)
        y_s = y0 + float(r) * np.sin(angle)

        a_da = xr.DataArray(angle, dims=(angle_dim,), coords={angle_dim: angle})
        x_da = xr.DataArray(x_s, dims=(angle_dim,), coords={angle_dim: angle})
        y_da = xr.DataArray(y_s, dims=(angle_dim,), coords={angle_dim: angle})
        cos_da = xr.DataArray(np.cos(angle), dims=(angle_dim,), coords={angle_dim: angle})
        sin_da = xr.DataArray(np.sin(angle), dims=(angle_dim,), coords={angle_dim: angle})

        # Optional frame selection.
        if frame is not None:
            if "t" not in ds.dims:
                raise ValueError("frame was provided but dataset has no 't' dimension")
            ds = ds.isel(t=int(frame))

        scalar_mode = var is not None
        if scalar_mode:
            if var not in ds:
                raise ValueError(f"Scalar variable '{var}' not found in dataset")
            p = ds[var].interp(x=x_da, y=y_da)
            # Ensure angle-first for numpy return.
            if angle_dim in p.dims:
                p = p.transpose(angle_dim, ...)
            return angle, np.asarray(p.values)

        # Vector mode
        if "u" not in ds or "v" not in ds:
            raise ValueError("Vector mode azprofile requires 'u' and 'v'")

        u_samp = ds["u"].interp(x=x_da, y=y_da)
        v_samp = ds["v"].interp(x=x_da, y=y_da)
        ur = u_samp * cos_da + v_samp * sin_da
        ut = -u_samp * sin_da + v_samp * cos_da

        ur = ur.transpose(angle_dim, ...)
        ut = ut.transpose(angle_dim, ...)
        return angle, np.asarray(ur.values), np.asarray(ut.values)

    def phaseaverf(
        self,
        period,
        *,
        opt: str = "",
        method: Literal["linear", "nearest"] = "linear",
    ):
        """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
        -------
        xarray.Dataset
            Phase-averaged dataset with dim 't' == n_phases.
        """

        ds = self._obj
        if "t" not in ds.dims:
            raise ValueError("phaseaverf requires a time dimension 't'")

        n_frames = int(ds.sizes.get("t", 0) or 0)
        if n_frames <= 0:
            raise ValueError("Empty time dimension")

        # Work in index space (0..n_frames-1) to make non-integer periods well-defined.
        tini = np.arange(n_frames, dtype=float)

        def _avg_for_points(points: np.ndarray) -> xr.Dataset:
            points = np.asarray(points, dtype=float)
            points = points[(points >= 0) & (points <= n_frames - 1)]
            if points.size == 0:
                # Return a 0-field with the same layout (single frame)
                zero = ds.isel(t=[0]).copy(deep=True)
                for v in list(zero.data_vars):
                    zero[v].values[...] = 0.0
                return zero.assign_coords(t=np.asarray([0.0], dtype=float))
            sub = ds.piv.resamplef(tini=tini, tfin=points, method=method)
            return sub.piv.averf(opt)

        phases: list[xr.Dataset] = []

        # Determine period type.
        if np.isscalar(period):
            p = float(period)
            if abs(p - float(int(round(p)))) < 1e-10:
                P = int(np.floor(p))
                if P <= 0:
                    raise ValueError("period must be positive")
                for i in range(P):
                    # Fast path: integer stride selection, no interpolation needed.
                    sub = ds.isel(t=slice(i, None, P))
                    phases.append(sub.piv.averf(opt))
            else:
                P = int(np.floor(p))
                if P <= 0:
                    raise ValueError("period must be >= 1")
                for i in range(P):
                    points = np.arange(float(i), float(n_frames), p)
                    phases.append(_avg_for_points(points))
        else:
            tvec = np.asarray(period, dtype=float).ravel()
            if tvec.size == 0:
                raise ValueError("period sequence must be non-empty")
            step = float(tvec[-1])
            if step <= 0:
                raise ValueError("period step (last element) must be positive")
            for start in tvec:
                points = np.arange(float(start), float(n_frames), step)
                phases.append(_avg_for_points(points))

        out = xr.concat(phases, dim="t")
        out = out.assign_coords(t=np.arange(out.sizes["t"], dtype=float))
        out.attrs = dict(ds.attrs)
        return out

    def probef(
        self,
        x0,
        y0,
        *,
        variables: Optional[list[str]] = None,
        method: str = "linear",
    ) -> xr.Dataset:
        """Record the time evolution of probe point(s) (PIVMAT-inspired).

        This samples variable(s) at point(s) ``(x0, y0)`` using spatial
        interpolation.

        Parameters
        ----------
        x0, 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
        -------
        xarray.Dataset
            Sampled time series. For multiple probe points, includes a ``probe`` dim
            and coordinates ``x_probe``/``y_probe``.
        """

        return cprobef(self._obj, x0, y0, variables=variables, method=method)

    def probeaverf(
        self,
        rect,
        *,
        variables: Optional[list[str]] = None,
        skipna: bool = True,
    ) -> xr.Dataset:
        """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
        -------
        xarray.Dataset
            Spatially averaged time series.
        """

        return cprobeaverf(self._obj, rect, variables=variables, skipna=skipna)

    def spatiotempf(
        self,
        X,
        Y,
        *,
        var: str = "w",
        n: Optional[int] = None,
        method: str = "linear",
    ) -> xr.Dataset:
        """Spatio-temporal diagram along line segment(s) (PIVMAT-inspired).

        Parameters
        ----------
        X, Y:
            Endpoints in physical units. Single line: ``X=[x0,x1]``, ``Y=[y0,y1]``.
            Multiple lines: ``X=[[x0,x1],[...]]``, same for ``Y``.
        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
        -------
        xarray.Dataset
            Dataset containing variable ``st``.
        """

        return cspatiotempf(self._obj, X, Y, var=var, n=n, method=method)

    def tempcorrf(
        self,
        *,
        variables: Optional[list[str]] = None,
        opt: str = "",
        normalize: bool = False,
    ) -> xr.Dataset:
        """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``.
        """

        return ctempcorrf(self._obj, variables=variables, opt=opt, normalize=normalize)

    def resamplef(
        self,
        tini,
        tfin,
        *,
        method: Literal["linear", "nearest"] = "linear",
    ):
        """(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]]

        Args:
            tini: 1D sequence of initial times (length == number of frames).
            tfin: 1D sequence of target times.
            method: Interpolation method.

        Returns:
            xarray.Dataset: resampled dataset with dim 't' == len(tfin) and coords 't' == tfin.
        """

        ds = self._obj
        if "t" not in ds.dims:
            raise ValueError("resamplef requires a time dimension 't'")

        tini_arr = np.asarray(tini, dtype=float).ravel()
        tfin_arr = np.asarray(tfin, dtype=float).ravel()

        n_frames = int(ds.sizes.get("t", 0) or 0)
        if tini_arr.size != n_frames:
            raise ValueError("Size of tini must coincide with the dataset time dimension")

        if tini_arr.size < 2:
            raise ValueError("tini must contain at least 2 points")

        if np.any(np.diff(tini_arr) <= 0):
            raise ValueError("tini must be strictly increasing")

        if tfin_arr.size == 0:
            raise ValueError("tfin must be non-empty")

        if float(np.min(tfin_arr)) < float(tini_arr[0]) or float(np.max(tfin_arr)) > float(tini_arr[-1]):
            raise ValueError("Some values of tfin fall outside the bounds of tini")

        # Interpolate in a dedicated coordinate to avoid assumptions about existing ds.t.
        ds_time = ds.assign_coords(_resample_time=("t", tini_arr)).swap_dims({"t": "_resample_time"})
        out = ds_time.interp(_resample_time=tfin_arr, method=method)
        out = out.swap_dims({"_resample_time": "t"}).assign_coords(t=tfin_arr)
        out = out.drop_vars("_resample_time")
        out.attrs = dict(ds.attrs)
        return out

    def spaverf(
        self,
        opt: str = "xy",
        *,
        var: Optional[str] = None,
    ):
        """Spatial average over X and/or Y of a vector/scalar field.

        This method is inspired by PIVMat's `spaverf`.

        Args:
            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:
            xarray.Dataset: Dataset with spatially-averaged variable(s), broadcast back
            to the original shape.
        """

        ds = self._obj
        opt_l = str(opt).lower() if opt is not None else "xy"
        include_zeros = "0" in opt_l
        axis = opt_l.replace("0", "") or "xy"

        if axis not in {"x", "y", "xy"}:
            raise ValueError("Invalid axis; expected 'x', 'y', or 'xy' (optionally with '0')")

        def _mean_broadcast(da: xr.DataArray, reduce_dims: list[str]) -> xr.DataArray:
            if include_zeros:
                mean = da.mean(dim=reduce_dims, skipna=True)
            else:
                mean = da.where(da != 0).mean(dim=reduce_dims, skipna=True)
                mean = mean.fillna(0.0)
            # Broadcast back to original y/x/t shape.
            return mean.broadcast_like(da)

        if var is None:
            if "u" not in ds or "v" not in ds:
                raise ValueError("Vector mode spaverf requires 'u' and 'v'")
            vars_to_process = ["u", "v"]
        else:
            if var not in ds:
                raise ValueError(f"Scalar variable '{var}' not found in dataset")
            vars_to_process = [var]

        reduce_dims: list[str]
        if axis == "x":
            reduce_dims = ["x"]
        elif axis == "y":
            reduce_dims = ["y"]
        else:
            reduce_dims = ["y", "x"]

        out = ds.copy(deep=True)
        for name in vars_to_process:
            da = out[name]
            # Ensure y/x exist; allow missing t (single frame).
            if "y" not in da.dims or "x" not in da.dims:
                raise ValueError(f"Variable '{name}' must have spatial dims 'y' and 'x'")
            out[name] = _mean_broadcast(da, reduce_dims)
            out[name].attrs = dict(ds[name].attrs)

        out.attrs = dict(ds.attrs)
        return out

    def subaverf(
        self,
        opt: str = "e",
        *,
        var: Optional[str] = None,
    ):
        """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.

        Args:
            opt: Option string. Default 'e'.
            var: Scalar variable name (e.g. 'w'). If None, operates on 'u' and 'v'.

        Returns:
            xarray.Dataset: Dataset with mean-subtracted variable(s).
        """

        ds = self._obj
        opt_l = str(opt).lower() if opt is not None else "e"
        ensemble = "e" in opt_l

        if var is None:
            if "u" not in ds or "v" not in ds:
                raise ValueError("Vector mode subaverf requires 'u' and 'v'")
            vars_to_process = ["u", "v"]
        else:
            if var not in ds:
                raise ValueError(f"Scalar variable '{var}' not found in dataset")
            vars_to_process = [var]

        out = ds.copy(deep=True)

        if ensemble:
            # Allow '0' to be passed through to averf if user included it.
            opt_for_averf = opt_l.replace("e", "")
            mean_ds = ds.piv.averf(opt_for_averf)

            for name in vars_to_process:
                da = ds[name]
                mean_da = mean_ds[name]

                # Broadcast mean to all time steps.
                if "t" in da.dims and "t" in mean_da.dims and mean_da.sizes.get("t", 1) == 1:
                    mean_b = mean_da.isel(t=0).broadcast_like(da)
                else:
                    mean_b = mean_da.broadcast_like(da)

                new = da - mean_b

                # Preserve invalid zeros (PIVMat multiplies by logical(original)).
                if "t" in da.dims:
                    new = new.where(da != 0, 0.0)
                else:
                    new = new.where(da != 0, 0.0)

                out[name] = new
                out[name].attrs = dict(ds[name].attrs)

            out.attrs = dict(ds.attrs)
            return out

        # Spatial subtraction mode.
        spatial_mean = ds.piv.spaverf(opt_l, var=var)
        for name in vars_to_process:
            da = ds[name]
            mean_da = spatial_mean[name]
            new = da - mean_da
            new = new.where(da != 0, 0.0)
            out[name] = new
            out[name].attrs = dict(ds[name].attrs)

        out.attrs = dict(ds.attrs)
        return out

    def fill_nans(self, method: Literal["linear", "nearest", "cubic"] = "nearest"):
        """
        This method uses scipy.interpolate.griddata to interpolate missing data.
        Parameters
        ----------
        src_data: Any
            Input data array.
        method: {'linear', 'nearest', 'cubic'}
            The method to use for interpolation in `scipy.interpolate.griddata`.
        Returns
        -------
        :class:`numpy.ndarray`:
            An interpolated :class:`numpy.ndarray`.
        """

        def _griddata_nans(src_data, x_coords, y_coords, method=method):

            src_data_flat = src_data.copy().flatten()
            data_bool = ~np.isnan(src_data_flat)

            if not data_bool.any():
                return src_data

            return griddata(
                points=(x_coords.flatten()[data_bool], y_coords.flatten()[data_bool]),
                values=src_data_flat[data_bool],
                xi=(x_coords, y_coords),
                method=method,
                # fill_value=nodata,
            )

        x_coords, y_coords = np.meshgrid(
            self._obj.coords["x"].values, self._obj.coords["y"].values
        )

        for var_name in self._obj.variables:
            if var_name not in self._obj.coords:
                for t_i in self._obj["t"]:
                    new_data = _griddata_nans(
                        self._obj.sel(t=t_i)[var_name].data,
                        x_coords,
                        y_coords,
                        method=method,
                    )
                    self._obj.sel(t=t_i)[var_name].data[:] = new_data

        return self._obj

    def fill_zeros(
        self,
        *,
        fill: bool = False,
        max_iter: int | None = None,
        variables: list[str] | None = None,
    ) -> xr.Dataset:
        """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.
        """

        ds = self._obj
        if variables is None:
            variables = [v for v in ("u", "v") if v in ds.data_vars] or list(ds.data_vars)

        out = ds.copy(deep=True)
        for name in variables:
            da = out[name]
            if da.ndim < 2:
                continue
            out[name] = interpolat_zeros_2d(da, fill=fill, max_iter=max_iter)
            out[name].attrs = dict(ds[name].attrs)

        out.attrs = dict(ds.attrs)
        return out

    def interpf(
        self,
        method: int = 0,
        *,
        variables: list[str] | None = None,
        missing: str = "0nan",
    ) -> xr.Dataset:
        """Interpolate missing data (PIVMAT-style ``interpf``).

        Missing values are defined as 0 and/or NaN (see ``missing``). The
        interpolation is applied frame-by-frame along ``t`` if present.

        Parameters
        ----------
        method:
            Interpolation method selector:
            ``0`` Laplacian inpainting (sparse solve),
            ``1`` nearest-neighbor fill,
            ``2`` linear 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
        -------
        xarray.Dataset
            Filled dataset.
        """

        return cinterpf(self._obj, method=int(method), variables=variables, missing=missing)

    def __add__(self, other):
        """add two datasets means that we sum up the velocities, assume
        that x,y,t,delta_t are all identical
        """
        self._obj["u"] += other._obj["u"]
        self._obj["v"] += other._obj["v"]
        return self._obj

    def __sub__(self, other):
        """add two datasets means that we sum up the velocities, assume
        that x,y,t,delta_t are all identical
        """
        self._obj["u"] -= other._obj["u"]
        self._obj["v"] -= other._obj["v"]
        return self._obj

    def vorticity(self, method: str = "differentiation", radius: int = 1, name: str = "w"):
        """Calculates vorticity of the data array and adds it to the dataset.

        Args:
            method (str): Vorticity calculation method. Options:
                'differentiation' (default): Standard finite difference (dv_dx - du_dy).
                'circulation': Closed contour line-integral circulation method,
                providing superior noise immunity.
            radius (int): Contour radius in grid points (used when method='circulation'). Defaults to 1.
            name (str): Name for the output scalar field. Defaults to "w".

        Input:
            xarray with the variables u,v and dimensions x,y (and optional t)

        Output:
            xarray with the estimated vorticity as a scalar field with same dimensions

        Example:
            >>> data.piv.vorticity()  # Creates data["w"] with finite-difference vorticity
            >>> data.piv.vorticity(method="circulation", radius=2)  # Noise-robust circulation vorticity
            >>> data.piv.vorticity(name="vort")  # Creates data["vort"] with vorticity
        """
        warn_if_overwriting_scalar(self._obj, name)

        if str(method).lower() in ["circulation", "circ"]:
            self._obj = cvorticity_circulation(self._obj, radius=radius, name=name)
        else:
            self._obj[name] = self._obj["v"].differentiate("x") - self._obj[
                "u"
            ].differentiate("y")
            self._obj[name].attrs["units"] = "1/delta_t"
            self._obj[name].attrs["standard_name"] = "vorticity"

        return self._obj

    def strain(self, name: str = "w"):
        """Calculates rate of strain of a two component field

        Args:
            name (str): Name for the output scalar field. Defaults to "w".
                Use different names to store multiple scalar fields in one dataset.

        Returns:
            xarray.Dataset: Dataset with added scalar field = du_dx^2 + dv_dy^2 + 0.5*(du_dy+dv_dx)^2

        Example:
            >>> data.piv.strain()  # Creates data["w"] with strain
            >>> data.piv.strain(name="strain_rate")  # Creates data["strain_rate"]
        """
        warn_if_overwriting_scalar(self._obj, name)
        du_dx = self._obj["u"].differentiate("x")
        du_dy = self._obj["u"].differentiate("y")
        dv_dx = self._obj["v"].differentiate("x")
        dv_dy = self._obj["v"].differentiate("y")

        self._obj[name] = du_dx**2 + dv_dy**2 + 0.5 * (du_dy + dv_dx) ** 2
        self._obj[name].attrs["units"] = "1/delta_t"
        self._obj[name].attrs["standard_name"] = "strain"

        return self._obj

    def divergence(self, name: str = "w"):
        """Calculates divergence field

        Args:
            name (str): Name for the output scalar field. Defaults to "w".
                Use different names to store multiple scalar fields in one dataset.

        Returns:
            xarray.Dataset: Dataset with the new property [name] = divergence

        Example:
            >>> data.piv.divergence()  # Creates data["w"] with divergence
            >>> data.piv.divergence(name="div")  # Creates data["div"] with divergence
        """
        warn_if_overwriting_scalar(self._obj, name)
        du_dx, _ = np.gradient(
            self._obj["u"], self._obj["x"], self._obj["y"], axis=(0, 1)
        )
        _, dv_dy = np.gradient(
            self._obj["v"], self._obj["x"], self._obj["y"], axis=(0, 1)
        )

        if "t" in self._obj.coords:
            self._obj[name] = (("x", "y", "t"), dv_dy + du_dx)
        else:
            self._obj[name] = (("x", "y"), dv_dy + du_dx)

        self._obj[name].attrs["units"] = "1/delta_t"
        self._obj[name].attrs["standard_name"] = "divergence"

        return self._obj

    def acceleration(self, name: str = "w", unsteady: bool = True, return_vector: bool = False):
        """Calculates material derivative or acceleration of the data array.

        Args:
            name (str): Name for the output scalar field. Defaults to "w".
            unsteady (bool): If True and time dimension 't' has multiple frames,
                includes local acceleration d(u)/dt. Defaults to True.
            return_vector (bool): If True, returns vector components 'ax' and 'ay'. Defaults to False.

        Input:
            xarray with variables u, v and dimensions y, x (and optional t)

        Output:
            xarray with the estimated acceleration as a scalar field data[name] (or ax, ay)

        Example:
            >>> data = data.piv.acceleration()  # Creates data["w"] with acceleration
            >>> data = data.piv.acceleration(name="accel")  # Creates data["accel"]
        """
        self._obj = cmaterial_acceleration(
            self._obj, name=name, unsteady=unsteady, return_vector=return_vector
        )
        return self._obj

    def kinetic_energy(self, name: str = "w"):
        """Estimates kinetic energy

        Args:
            name (str): Name for the output scalar field. Defaults to "w".
                Use different names to store multiple scalar fields in one dataset.

        Returns:
            xarray.Dataset: Dataset with kinetic energy field

        Example:
            >>> data.piv.kinetic_energy()  # Creates data["w"] with KE
            >>> data.piv.kinetic_energy(name="ke")  # Creates data["ke"]
        """
        warn_if_overwriting_scalar(self._obj, name)
        self._obj[name] = self._obj["u"] ** 2 + self._obj["v"] ** 2
        self._obj[name].attrs["units"] = "(m/s)^2"
        self._obj[name].attrs["standard_name"] = "kinetic_energy"
        return self._obj

    def tke(self, name: str = "w"):
        """Estimates turbulent kinetic energy

        Args:
            name (str): Name for the output scalar field. Defaults to "w".
                Use different names to store multiple scalar fields in one dataset.

        Returns:
            xarray.Dataset: New dataset with TKE field (based on fluctuations from mean)

        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"]
        """
        if len(self._obj.t) < 2:
            raise ValueError(
                "TKE is not defined for a single vector field, \
                              use .piv.kinetic_energy()"
            )

        warn_if_overwriting_scalar(self._obj, name)
        new_obj = self._obj.copy()
        new_obj -= new_obj.mean(dim="t")
        new_obj[name] = new_obj["u"] ** 2 + new_obj["v"] ** 2
        new_obj[name].attrs["units"] = "(m/s)^2"
        new_obj[name].attrs["standard_name"] = "TKE"

        return new_obj

    def fluct(self):
        """returns fluctuations as a new dataset"""

        if len(self._obj.t) < 2:
            raise ValueError(
                "fluctuations cannot be defined for a \
                              single vector field, use .piv.ke()"
            )

        new_obj = self._obj.copy()
        new_obj -= new_obj.mean(dim="t")

        new_obj["u"].attrs["standard_name"] = "fluctation"
        new_obj["v"].attrs["standard_name"] = "fluctation"

        return new_obj

    def reynolds_stress(self, name: str = "w"):
        """Calculates Reynolds stress from velocity fluctuations

        Args:
            name (str): Name for the output scalar field. Defaults to "w".
                Use different names to store multiple scalar fields in one dataset.

        Returns:
            xarray.Dataset: Dataset with Reynolds stress field (-<u'v'>)

        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"]
        """

        if len(self._obj.t) < 2:
            raise ValueError(
                "fluctuations cannot be defined for a \
                              single vector field, use .piv.ke()"
            )

        warn_if_overwriting_scalar(self._obj, name)
        new_obj = self._obj.copy()
        new_obj -= new_obj.mean(dim="t")

        new_obj[name] = -1 * new_obj["u"] * new_obj["v"]  # new scalar
        self._obj[name] = new_obj[name].mean(dim="t")  # reynolds stress is -\rho < u' v'>
        self._obj[name].attrs["standard_name"] = "Reynolds_stress"

        return self._obj

    def rms(self, name: str = "w"):
        """Root mean square of velocity fluctuations

        Args:
            name (str): Name for the output scalar field. Defaults to "w".
                Use different names to store multiple scalar fields in one dataset.

        Returns:
            xarray.Dataset: Dataset with RMS field (sqrt of TKE)

        Example:
            >>> data.piv.rms()  # Creates data["w"] with RMS
            >>> data.piv.rms(name="rms")  # Creates data["rms"]
        """
        self._obj = self.tke(name=name)
        self._obj[name] = np.sqrt(self._obj[name])
        self._obj[name].attrs["standard_name"] = "rms"
        self._obj[name].attrs["units"] = "m/s"
        return self._obj

    def gamma1(self, radius: int = 3, name: str = "gamma1"):
        """Calculates the Gamma1 vortex criterion (normalized angular momentum).

        Gamma1 identifies vortex centers where abs(Gamma1) >= 2/pi (~0.6366),
        reaching +/-1 at ideal vortex centers.

        Args:
            radius (int): Stencil radius in grid points. Defaults to 3.
            name (str): Variable name for the output field. Defaults to 'gamma1'.

        Returns:
            xarray.Dataset: Dataset with Gamma1 scalar field.
        """
        self._obj = cgamma1(self._obj, radius=radius, name=name)
        return self._obj

    def gamma2(self, radius: int = 3, name: str = "gamma2"):
        """Calculates the Galilean-invariant Gamma2 vortex identification criterion.

        Gamma2 identifies vortex core boundaries where abs(Gamma2) >= 2/pi (~0.6366),
        subtracting local convective velocity.

        Args:
            radius (int): Stencil radius in grid points. Defaults to 3.
            name (str): Variable name for the output field. Defaults to 'gamma2'.

        Returns:
            xarray.Dataset: Dataset with Gamma2 scalar field.
        """
        self._obj = cgamma2(self._obj, radius=radius, name=name)
        return self._obj

    def Γ1(self, n: int = 3, convCoords: bool = True):
        """Legacy method for Γ1 vortex criterion calculation."""
        self._obj = cgamma1(self._obj, radius=n, name="Γ1")
        return self._obj

    def Γ2(self, n: int = 3, convCoords: bool = True):
        """Legacy method for Γ2 vortex criterion calculation."""
        self._obj = cgamma2(self._obj, radius=n, name="Γ2")
        return self._obj

    def q_criterion(self, name: str = "Q"):
        """Calculates Hunt's Q-criterion for vortex core identification (Q > 0).

        Args:
            name (str): Variable name for the output field. Defaults to 'Q'.

        Returns:
            xarray.Dataset: Dataset with Q-criterion scalar field.
        """
        self._obj = cq_criterion(self._obj, name=name)
        return self._obj

    def okubo_weiss(self, name: str = "Q_ow"):
        """Calculates the Okubo-Weiss criterion for vortex identification (Q_ow < 0).

        Args:
            name (str): Variable name for the output field. Defaults to 'Q_ow'.

        Returns:
            xarray.Dataset: Dataset with Okubo-Weiss scalar field.
        """
        self._obj = cokubo_weiss(self._obj, name=name)
        return self._obj

    def subsbr(self, r0=None):
        """Subtracts solid body rotation from the velocity field.

        Args:
            r0 (ArrayLike, optional): Center coordinates [x0, y0]. Defaults to field center.

        Returns:
            xarray.Dataset: Dataset with subtracted solid body rotation.
        """
        self._obj = csubsbr(self._obj, r0=r0)
        return self._obj

    def normalized_median_test(
        self,
        radius: int = 1,
        threshold: float = 2.0,
        epsilon: float = 0.1,
        name_mask: str | None = None,
    ):
        """Applies Westerweel & Scarano (2005) Normalized Median Test to detect outliers.

        Args:
            radius (int): Stencil radius in grid units. Defaults to 1.
            threshold (float): Outlier detection threshold. Defaults to 2.0.
            epsilon (float): Noise floor in velocity units. Defaults to 0.1.
            name_mask (str, optional): Optional variable name to store outlier boolean mask.

        Returns:
            xarray.Dataset: Dataset with outliers flagged in 'chc' (and optional mask).
        """
        return cnormalized_median_test(
            self._obj, radius=radius, threshold=threshold, epsilon=epsilon, name_mask=name_mask
        )

    def clean(
        self,
        method: str = "normalized_median",
        threshold: float = 2.0,
        epsilon: float = 0.1,
        inpaint_method: int | str = 0,
        radius: int = 1,
    ):
        """Detects velocity outliers and inpaints missing/flagged vectors.

        Args:
            method (str): Outlier detection method ('normalized_median' or 'mask').
            threshold (float): Outlier threshold for normalized median test. Defaults to 2.0.
            epsilon (float): Noise floor parameter. Defaults to 0.1.
            inpaint_method (int or str): Inpainting scheme (0=harmonic, 1=nearest, 2=linear).
            radius (int): Neighborhood radius for median test. Defaults to 1.

        Returns:
            xarray.Dataset: Cleaned dataset.
        """
        return cclean(
            self._obj,
            method=method,
            threshold=threshold,
            epsilon=epsilon,
            inpaint_method=inpaint_method,
            radius=radius,
        )

    def filter_outliers(self, threshold: float = 2.0, replace: bool = True, **kwargs):
        """Convenience method to detect and optionally replace spurious vector outliers.

        Args:
            threshold (float): Outlier threshold for normalized median test. Defaults to 2.0.
            replace (bool): If True, replaces outliers via harmonic inpainting. If False, flags in 'chc'.
            **kwargs: Additional parameters passed to `clean` or `normalized_median_test`.

        Returns:
            xarray.Dataset: Filtered/cleaned dataset.
        """
        if replace:
            return self.clean(threshold=threshold, **kwargs)
        return self.normalized_median_test(threshold=threshold, **kwargs)

    def smooth(
        self,
        sigma: float | Sequence[float] = 1.0,
        method: str = "gaussian",
        **kwargs,
    ):
        """Applies spatial smoothing to velocity vector fields.

        Args:
            sigma (float or sequence): Smoothing scale / window size / cutoff size.
            method (str): Filtering method ('gaussian', 'median', 'boxcar', 'butterworth'). Defaults to 'gaussian'.
            **kwargs: Additional parameters passed to filtering backend (e.g. order=2 for Butterworth).

        Returns:
            xarray.Dataset: Smoothed dataset.
        """
        return csmooth(self._obj, sigma=sigma, method=method, **kwargs)

    def filter(
        self,
        sigma: float | Sequence[float] = 1.0,
        method: str = "gaussian",
        **kwargs,
    ):
        """Alias for smooth()."""
        return self.smooth(sigma=sigma, method=method, **kwargs)

    def gradient_tensor(self, return_components: bool = False):
        """Calculates velocity gradient tensor, strain rate tensor, and principal strains.

        Args:
            return_components (bool): If True, returns new dataset with tensor fields. Defaults to False.

        Returns:
            xarray.Dataset: Dataset with computed tensor variables.
        """
        return cgradient_tensor(self._obj, return_components=return_components)

    def max_shear(self, name: str = "w"):
        """Calculates maximum shear strain rate."""
        warn_if_overwriting_scalar(self._obj, name)
        res = cgradient_tensor(self._obj, return_components=True)
        self._obj[name] = res["max_shear"]
        self._obj[name].attrs["units"] = "1/delta_t"
        self._obj[name].attrs["standard_name"] = "max_shear_strain_rate"
        return self._obj

    def reynolds_decomposition(
        self,
        name_mean: str = "mean",
        name_prime: str = "prime",
    ):
        """Performs Reynolds decomposition on time series velocity dataset."""
        return creynolds_decomposition(self._obj, name_mean=name_mean, name_prime=name_prime)

    def energy_spectrum(
        self,
        window: str = "hann",
        detrend: bool = True,
        radial: bool = True,
    ):
        """Computes 2D and radial wavenumber energy spectra."""
        return cenergy_spectrum(self._obj, window=window, detrend=detrend, radial=radial)

    def spatial_correlation(
        self,
        component: str = "u",
        dim: str = "x",
        normalize: bool = True,
    ):
        """Calculates spatial two-point autocorrelation function R_ij(r)."""
        return cspatial_correlation(self._obj, component=component, dim=dim, normalize=normalize)

    def integral_length_scale(
        self,
        component: str = "u",
        dim: str = "x",
    ) -> float:
        """Calculates integral length scale by integrating autocorrelation to zero-crossing."""
        return cintegral_length_scale(self._obj, component=component, dim=dim)

    def taylor_microscale(
        self,
        component: str = "u",
        dim: str = "x",
        method: str = "curvature",
    ) -> float:
        """Estimates the Taylor microscale lambda_T from velocity fluctuations."""
        return ctaylor_microscale(self._obj, component=component, dim=dim, method=method)

    def dissipation(
        self,
        method: str = "direct",
        nu: float = 1.5e-5,
        name: str = "w",
    ):
        """Estimates turbulent kinetic energy dissipation rate epsilon."""
        return cdissipation(self._obj, method=method, nu=nu, name=name)

    def vec2scal(self, flow_property: str = "curl", name: str = "w"):
        """Creates a scalar flow property field from velocity data

        Args:
            flow_property (str): Name of the flow property to compute.
                Valid options: 'curl'/'vorticity'/'vort', 'ke'/'ken'/'kinetic_energy',
                'strain', 'divergence', 'acceleration'/'accel', 'tke', 'reynolds_stress', 'rms',
                'gamma1', 'gamma2', 'q_criterion'/'q', 'okubo_weiss'/'q_ow', 'max_shear',
                'dissipation'/'dissip'.
                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:
            xarray.Dataset: Dataset with computed scalar field

        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('gamma1', name='g1')  # Compute Gamma1 in data["g1"]
            >>> data = data.piv.vec2scal('gamma2', name='g2')  # Compute Gamma2 in data["g2"]
            >>> data = data.piv.vec2scal('q_criterion', name='Q')  # Compute Q in data["Q"]
        """
        # Replace common aliases with canonical names
        alias_map = {
            "curl": "vorticity",
            "vort": "vorticity",
            "ke": "kinetic_energy",
            "ken": "kinetic_energy",
            "q": "q_criterion",
            "q_ow": "okubo_weiss",
            "ow": "okubo_weiss",
            "accel": "acceleration",
            "principal_strain": "strain",
            "shear_strain": "strain",
            "dissip": "dissipation",
        }
        flow_property = alias_map.get(str(flow_property).lower(), flow_property)

        # Check if method exists
        if not hasattr(self, flow_property):
            valid_properties = [
                'vorticity', 'kinetic_energy', 'strain', 'divergence', 
                'acceleration', 'tke', 'reynolds_stress', 'rms',
                'gamma1', 'gamma2', 'q_criterion', 'okubo_weiss', 'max_shear',
                'dissipation'
            ]
            raise AttributeError(
                f"Unknown flow property '{flow_property}'. "
                f"Valid options are: {', '.join(valid_properties)}"
            )

        warnings.warn(
            "piv.vec2scal() currently rebinds this accessor's internal dataset "
            "reference as a side effect; a future release will make it a pure "
            "function that only returns the computed dataset. Always use the "
            "return value (`ds = ds.piv.vec2scal(...)`) rather than relying on "
            "in-place state.",
            DeprecationWarning,
            stacklevel=2,
        )
        method = getattr(self, flow_property)
        self._obj = method(name=name)

        return self._obj

    def __mul__(self, scalar):
        """Multiplies velocity field by a scalar (simple scaling)

        Args:
            scalar (float): Scaling factor

        Returns:
            xarray.Dataset: Scaled dataset

        Example:
            >>> scaled_data = data.piv * 2.0  # Double all velocities
        """
        out = self._obj.copy()
        out["u"] = out["u"] * scalar
        out["v"] = out["v"] * scalar
        if "w" in out.data_vars:
            out["w"] = out["w"] * scalar

        return out

    def __truediv__(self, scalar):
        """Divides velocity field by a scalar

        Args:
            scalar (float): Division factor

        Returns:
            xarray.Dataset: Scaled dataset

        Raises:
            ValueError: If scalar is zero

        Example:
            >>> normalized_data = data.piv / 100.0  # Normalize velocities
        """
        if scalar == 0:
            raise ValueError("Cannot divide by zero")

        out = self._obj.copy()
        out["u"] = out["u"] / scalar
        out["v"] = out["v"] / scalar

        return out

    def set_delta_t(self, delta_t: float = 0.0):
        """Sets the time interval attribute for PIV measurements

        Args:
            delta_t (float): Time interval between frame A and B. Defaults to 0.0.

        Returns:
            xarray.Dataset: Dataset with updated delta_t attribute

        Raises:
            ValueError: If delta_t is negative

        Example:
            >>> data = data.piv.set_delta_t(0.001)  # Set dt to 1 millisecond
        """
        if delta_t < 0:
            raise ValueError(f"delta_t must be non-negative, got {delta_t}")

        self._obj.attrs["delta_t"] = delta_t
        return self._obj

    def set_scale(self, scale: float = 1.0):
        """Scales all spatial coordinates and velocities by a factor

        Args:
            scale (float): Scaling factor. Defaults to 1.0.

        Returns:
            xarray.Dataset: Dataset with scaled coordinates and velocities

        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
        """
        if scale <= 0:
            raise ValueError(f"scale must be positive, got {scale}")

        for var in ["x", "y", "u", "v"]:
            self._obj[var] = self._obj[var] * scale

        return self._obj

    def rotate(self, theta: float = 0.0):
        """Rotates the coordinate system and velocity field

        Args:
            theta (float): Rotation angle in degrees (clockwise). Defaults to 0.0.

        Returns:
            xarray.Dataset: Rotated dataset

        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
        """

        theta = theta / 360.0 * 2 * np.pi

        x_i = self._obj.x * np.cos(theta) + self._obj.y * np.sin(theta)
        eta = self._obj.y * np.cos(theta) - self._obj.x * np.sin(theta)
        du_dx_i = self._obj.u * np.cos(theta) + self._obj.v * np.sin(theta)
        u_eta = self._obj.v * np.cos(theta) - self._obj.u * np.sin(theta)

        self._obj["x"] = x_i
        self._obj["y"] = eta
        self._obj["u"] = du_dx_i
        self._obj["v"] = u_eta

        if "theta" in self._obj:
            self._obj["theta"] += theta
        else:
            self._obj["theta"] = theta

        return self._obj

    @property
    def delta_t(self):
        """receives the delta_t from the set"""
        if self._delta_t is None:
            self._delta_t = self._obj.attrs["delta_t"]
        return self._delta_t

    def plot(self, **kwargs):
        """High-level, publication-quality plotting method.

        Renders a publication-quality flow field visualization with zero effort:
        - Smooth background contour (vorticity by default, or magnitude, KE, divergence, etc.)
        - Flow streamlines
        - Clean, auto-scaled velocity vector quiver arrows
        - LaTeX math labels, colorbar, equal aspect ratio, and quiver key.

        Examples
        --------
        >>> ds = synthetic.multivortex()
        >>> ds.piv.plot()
        >>> ds.piv.plot(background='mag', streamlines=False)
        >>> ds.piv.plot(background=None)
        """
        return gplot(self._obj, **kwargs)

    def animate(self, **kwargs):
        """High-performance FuncAnimation for time-series flow fields (graphics.animate)."""
        return ganimate(self._obj, **kwargs)

    def quiver(self, **kwargs):
        """graphics.quiver() as a flow_property"""
        fig, ax = gquiver(self._obj, **kwargs)
        return fig, ax

    def streamplot(self, **kwargs):
        """graphics.streamplot() as a flow_property"""
        fig, ax = gstreamplot(self._obj, **kwargs)
        return fig, ax

    def showf(self, **kwargs):
        """method for graphics.showf"""
        fig, ax = gshowf(self._obj, **kwargs)
        return fig, ax

    def showscal(self, **kwargs):
        """method for graphics.showscal"""
        gshowscal(self._obj, **kwargs)

    def to_movie(self, output, **kwargs):
        """Save the Dataset as a movie (fast artist-updating renderer).

        This is a convenience wrapper around :func:`pivpy.graphics.to_movie`.

        Parameters
        ----------
        output:
            Output path (e.g. ``'movie.mp4'`` / ``'movie.gif'``). If ``None`` and
            ``return_frames=True`` is passed, returns a list of RGBA frames.
        **kwargs:
            Passed through to :func:`pivpy.graphics.to_movie`.
        """

        return gto_movie(self._obj, output, **kwargs)

    def jpdfscal(self, var1: str, var2: str, nbin: int = 101) -> xr.Dataset:
        """Joint PDF (2D histogram) of two scalar variables (PIVMAT-style).

        Parameters
        ----------
        var1, var2:
            Names of scalar variables in the Dataset.
        nbin:
            Number of bins per axis (odd integer, default 101).
        """

        if var1 not in self._obj:
            raise KeyError(f"Variable {var1} not found in dataset")
        if var2 not in self._obj:
            raise KeyError(f"Variable {var2} not found in dataset")
        return cjpdfscal(self._obj[var1], self._obj[var2], nbin=int(nbin))

    def jpdfscal_disp(self, var1: str, var2: str, nbin: int = 101, **kwargs):
        """Compute and display the joint PDF of two scalar variables."""

        jpdf = self.jpdfscal(var1, var2, nbin=nbin)
        return gjpdfscal_disp(jpdf, **kwargs)

    def histscal_disp(self, *args, **kwargs):
        """method for graphics.histscal_disp"""
        return ghistscal_disp(self._obj, *args, **kwargs)

    def histvec_disp(self, *args, **kwargs):
        """method for graphics.histvec_disp"""
        return ghistvec_disp(self._obj, *args, **kwargs)

    def autocorrelation_plot(self, variable: str = "u", spatial_average: bool = True, **kwargs):
        """Creates autocorrelation plot of a specified variable

        Args:
            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:
            matplotlib.axes.Axes: The axes object containing the autocorrelation plot

        Example:
            >>> data.piv.autocorrelation_plot(variable='u')
            >>> data.piv.autocorrelation_plot(variable='v', spatial_average=False)
        """
        return gautocorrelation_plot(self._obj, variable=variable, 
                                     spatial_average=spatial_average, **kwargs)

    def corrm(
        self,
        variable: str = "u",
        dim: int | str = "x",
        *,
        half: bool = False,
        nan_as_zero: bool = True,
        lag_dim: str = "lag",
    ) -> xr.DataArray:
        """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.
        """

        if variable not in self._obj:
            raise KeyError(f"Variable {variable} not in dataset")

        return corrm(
            self._obj[variable],
            dim=dim,
            half=half,
            nan_as_zero=nan_as_zero,
            lag_dim=lag_dim,
        )

    def corrf(
        self,
        variable: str = "u",
        dim: int | str = "x",
        *,
        normalize: bool = False,
        nan_as_zero: bool = True,
        nowarning: bool = False,
    ) -> xr.Dataset:
        """PIVMAT-style spatial correlation and integral scales for a scalar variable.

        This wraps :func:`pivpy.compute_funcs.corrf` and returns a Dataset with
        coordinate ``r`` and variable ``f`` plus scalar outputs (``isinf``, ``r5``, ...).
        """

        if variable not in self._obj:
            raise KeyError(f"Variable {variable} not in dataset")

        return corrf(
            self._obj[variable],
            dim=dim,
            normalize=normalize,
            nan_as_zero=nan_as_zero,
            nowarning=nowarning,
        )

    def gradientf(self, variable: str = "w") -> xr.Dataset:
        """PIVMAT-style gradient of a scalar variable.

        This wraps :func:`pivpy.compute_funcs.gradientf` and returns a new
        Dataset containing gradient components as variables ``u`` and ``v``.

        Parameters
        ----------
        variable:
            Name of the scalar variable in the Dataset (default: ``'w'``).

        Returns
        -------
        xarray.Dataset
            Dataset with variables ``u`` and ``v``.
        """

        if variable not in self._obj:
            raise KeyError(f"Variable {variable} not in dataset")

        return gradientf(self._obj[variable])

    def histf(
        self,
        variable: str | None = None,
        bin=None,
        opt: str = "",
    ) -> xr.Dataset:
        """PIVMAT-style histogram of a vector/scalar field.

        - Scalar mode: pass ``variable='w'`` (or any scalar var name) to get a
          Dataset with coordinate ``bin`` and variable ``h``.
        - Vector mode: pass ``variable=None`` (default) to compute histograms
          for both components (``u``/``v`` or ``vx``/``vy``), returning variables
          ``hx`` and ``hy``.

        By default, zero values are treated as invalid and excluded. Pass
        ``opt`` containing ``'0'`` to include zeros.
        """

        ds = self._obj
        include_zeros = "0" in str(opt)

        if variable is not None:
            if variable not in ds:
                raise KeyError(f"Variable {variable} not in dataset")
            return histf(ds[variable], bin=bin, opt="0" if include_zeros else "")

        # Vector mode
        if "u" in ds and "v" in ds:
            xname, yname = "u", "v"
        elif "vx" in ds and "vy" in ds:
            xname, yname = "vx", "vy"
        else:
            raise ValueError("histf vector mode requires ('u','v') or ('vx','vy')")

        hx_ds = histf(ds[xname], bin=bin, opt="0" if include_zeros else "")
        centers = hx_ds["bin"].values
        hy_ds = histf(ds[yname], bin=centers, opt="0" if include_zeros else "")

        out = xr.Dataset(
            {
                "hx": ("bin", np.asarray(hx_ds["h"].values, dtype=int)),
                "hy": ("bin", np.asarray(hy_ds["h"].values, dtype=int)),
            },
            coords={"bin": centers},
        )
        out["hx"].attrs["long_name"] = f"histogram({xname})"
        out["hy"].attrs["long_name"] = f"histogram({yname})"
        return out

    def explore(self, port: int = 8000, host: str = "127.0.0.1", open_browser: bool = True):
        """Launches the interactive Marimo PIVPy diagnostics and visualization app."""
        from pivpy.app import launch_app
        return launch_app(dataset=self._obj, port=port, host=host, open_browser=open_browser)

    def stream_statistics(self, name_mean: str = "mean", name_prime: str = "prime"):
        """Computes online streaming temporal mean, Reynolds stresses, and TKE with O(1) memory."""
        from pivpy.io import stream_statistics
        return stream_statistics(self._obj, name_mean=name_mean, name_prime=name_prime)

average property

Return the mean flow field .

delta_t property

receives the delta_t from the set

__add__(other)

add two datasets means that we sum up the velocities, assume that x,y,t,delta_t are all identical

Source code in pivpy/pivpy.py
1906
1907
1908
1909
1910
1911
1912
def __add__(self, other):
    """add two datasets means that we sum up the velocities, assume
    that x,y,t,delta_t are all identical
    """
    self._obj["u"] += other._obj["u"]
    self._obj["v"] += other._obj["v"]
    return self._obj

__init__(xarray_obj)

Arguments: data : xarray Dataset: x,y,t are coordinates u,v,chc are the data arrays

We add few shortcuts (properties): data.piv.average is the time average (data.mean(dim='t')) data.piv.delta_t is the shortcut to get $\Delta t$ data.piv.vorticity data.piv.tke data.piv.shear

and a few methods: data.piv.vec2scal() data.piv.pan data.piv.rotate

Source code in pivpy/pivpy.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def __init__(self, xarray_obj):
    """
    Arguments:
        data : xarray Dataset:
        x,y,t are coordinates
        u,v,chc are the data arrays

    We add few shortcuts (properties):
        data.piv.average is the time average (data.mean(dim='t'))
        data.piv.delta_t is the shortcut to get $\\Delta t$
        data.piv.vorticity
        data.piv.tke
        data.piv.shear

    and a few methods:
        data.piv.vec2scal()
        data.piv.pan
        data.piv.rotate

    """
    self._obj = xarray_obj
    self._average = None
    self._delta_t = None

__mul__(scalar)

Multiplies velocity field by a scalar (simple scaling)

Args: scalar (float): Scaling factor

Returns: xarray.Dataset: Scaled dataset

Example: >>> scaled_data = data.piv * 2.0 # Double all velocities

Source code in pivpy/pivpy.py
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
def __mul__(self, scalar):
    """Multiplies velocity field by a scalar (simple scaling)

    Args:
        scalar (float): Scaling factor

    Returns:
        xarray.Dataset: Scaled dataset

    Example:
        >>> scaled_data = data.piv * 2.0  # Double all velocities
    """
    out = self._obj.copy()
    out["u"] = out["u"] * scalar
    out["v"] = out["v"] * scalar
    if "w" in out.data_vars:
        out["w"] = out["w"] * scalar

    return out

__sub__(other)

add two datasets means that we sum up the velocities, assume that x,y,t,delta_t are all identical

Source code in pivpy/pivpy.py
1914
1915
1916
1917
1918
1919
1920
def __sub__(self, other):
    """add two datasets means that we sum up the velocities, assume
    that x,y,t,delta_t are all identical
    """
    self._obj["u"] -= other._obj["u"]
    self._obj["v"] -= other._obj["v"]
    return self._obj

__truediv__(scalar)

Divides velocity field by a scalar

Args: scalar (float): Division factor

Returns: xarray.Dataset: Scaled dataset

Raises: ValueError: If scalar is zero

Example: >>> normalized_data = data.piv / 100.0 # Normalize velocities

Source code in pivpy/pivpy.py
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
def __truediv__(self, scalar):
    """Divides velocity field by a scalar

    Args:
        scalar (float): Division factor

    Returns:
        xarray.Dataset: Scaled dataset

    Raises:
        ValueError: If scalar is zero

    Example:
        >>> normalized_data = data.piv / 100.0  # Normalize velocities
    """
    if scalar == 0:
        raise ValueError("Cannot divide by zero")

    out = self._obj.copy()
    out["u"] = out["u"] / scalar
    out["v"] = out["v"] / scalar

    return out

acceleration(name='w', unsteady=True, return_vector=False)

Calculates material derivative or acceleration of the data array.

Args: name (str): Name for the output scalar field. Defaults to "w". unsteady (bool): If True and time dimension 't' has multiple frames, includes local acceleration d(u)/dt. Defaults to True. return_vector (bool): If True, returns vector components 'ax' and 'ay'. Defaults to False.

Input: xarray with variables u, v and dimensions y, x (and optional t)

Output: xarray with the estimated acceleration as a scalar field data[name] (or ax, ay)

Example: >>> data = data.piv.acceleration() # Creates data["w"] with acceleration >>> data = data.piv.acceleration(name="accel") # Creates data["accel"]

Source code in pivpy/pivpy.py
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
def acceleration(self, name: str = "w", unsteady: bool = True, return_vector: bool = False):
    """Calculates material derivative or acceleration of the data array.

    Args:
        name (str): Name for the output scalar field. Defaults to "w".
        unsteady (bool): If True and time dimension 't' has multiple frames,
            includes local acceleration d(u)/dt. Defaults to True.
        return_vector (bool): If True, returns vector components 'ax' and 'ay'. Defaults to False.

    Input:
        xarray with variables u, v and dimensions y, x (and optional t)

    Output:
        xarray with the estimated acceleration as a scalar field data[name] (or ax, ay)

    Example:
        >>> data = data.piv.acceleration()  # Creates data["w"] with acceleration
        >>> data = data.piv.acceleration(name="accel")  # Creates data["accel"]
    """
    self._obj = cmaterial_acceleration(
        self._obj, name=name, unsteady=unsteady, return_vector=return_vector
    )
    return self._obj

addnoisef(eps=0.1, opt='add', nc=0.0, seed=None)

Adds normally-distributed white noise to velocity fields.

This method is inspired by PIVMat's addnoisef.

Args: 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: xarray.Dataset: Dataset with noisy u/v.

Source code in pivpy/pivpy.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
def addnoisef(
    self,
    eps: float = 0.1,
    opt: Literal["add", "mul"] = "add",
    nc: float = 0.0,
    seed: Optional[int] = None,
):
    """Adds normally-distributed white noise to velocity fields.

    This method is inspired by PIVMat's `addnoisef`.

    Args:
        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:
        xarray.Dataset: Dataset with noisy u/v.
    """

    if eps is None or float(eps) == 0.0:
        return self._obj

    opt_l = str(opt).lower()
    if not (opt_l.startswith("add") or opt_l.startswith("mul")):
        raise ValueError("opt must be 'add' or 'mul'")

    if "u" not in self._obj or "v" not in self._obj:
        raise ValueError("Dataset must contain 'u' and 'v' variables")

    u0 = np.asarray(self._obj["u"].values)
    v0 = np.asarray(self._obj["v"].values)
    if u0.ndim != 3 or v0.ndim != 3:
        raise ValueError("Expected 'u' and 'v' to have dims ('y','x','t')")

    # Use a single reference scale for both components.
    ref_std = float(np.nanstd(np.stack([u0, v0], axis=0)))
    if not np.isfinite(ref_std) or ref_std == 0.0:
        ref_std = 1.0

    rng = np.random.default_rng(seed)

    # Convert smoothing length (in coordinate units) to gaussian sigma (in grid points).
    sigma_yx = None
    if nc is not None and float(nc) != 0.0:
        try:
            x = np.asarray(self._obj.coords["x"].values, dtype=float)
            y = np.asarray(self._obj.coords["y"].values, dtype=float)
            dx = float(np.nanmedian(np.diff(x))) if x.size >= 2 else 1.0
            dy = float(np.nanmedian(np.diff(y))) if y.size >= 2 else 1.0
            dx = abs(dx) if dx != 0 else 1.0
            dy = abs(dy) if dy != 0 else 1.0
            sigma_yx = (abs(float(nc)) / dy, abs(float(nc)) / dx)
        except Exception:
            sigma_yx = (abs(float(nc)), abs(float(nc)))

    u = u0.copy()
    v = v0.copy()

    for ti in range(u.shape[2]):
        nu = rng.standard_normal(size=u.shape[:2])
        nv = rng.standard_normal(size=v.shape[:2])

        if sigma_yx is not None:
            nu = gaussian_filter(nu, sigma=sigma_yx, mode="nearest")
            nv = gaussian_filter(nv, sigma=sigma_yx, mode="nearest")
            # Keep noise level roughly independent of smoothing.
            s_nu = float(np.nanstd(nu))
            s_nv = float(np.nanstd(nv))
            if s_nu > 0:
                nu = nu / s_nu
            if s_nv > 0:
                nv = nv / s_nv

        if opt_l.startswith("add"):
            u[:, :, ti] = u[:, :, ti] + nu * float(eps) * ref_std
            v[:, :, ti] = v[:, :, ti] + nv * float(eps) * ref_std
        else:
            u[:, :, ti] = u[:, :, ti] * (1.0 + nu * float(eps))
            v[:, :, ti] = v[:, :, ti] * (1.0 + nv * float(eps))

    self._obj["u"].values[...] = u
    self._obj["v"].values[...] = v
    return self._obj

animate(**kwargs)

High-performance FuncAnimation for time-series flow fields (graphics.animate).

Source code in pivpy/pivpy.py
2622
2623
2624
def animate(self, **kwargs):
    """High-performance FuncAnimation for time-series flow fields (graphics.animate)."""
    return ganimate(self._obj, **kwargs)

autocorrelation_plot(variable='u', spatial_average=True, **kwargs)

Creates autocorrelation plot of a specified variable

Args: 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: matplotlib.axes.Axes: The axes object containing the autocorrelation plot

Example: >>> data.piv.autocorrelation_plot(variable='u') >>> data.piv.autocorrelation_plot(variable='v', spatial_average=False)

Source code in pivpy/pivpy.py
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
def autocorrelation_plot(self, variable: str = "u", spatial_average: bool = True, **kwargs):
    """Creates autocorrelation plot of a specified variable

    Args:
        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:
        matplotlib.axes.Axes: The axes object containing the autocorrelation plot

    Example:
        >>> data.piv.autocorrelation_plot(variable='u')
        >>> data.piv.autocorrelation_plot(variable='v', spatial_average=False)
    """
    return gautocorrelation_plot(self._obj, variable=variable, 
                                 spatial_average=spatial_average, **kwargs)

averf(opt='', *, return_std_rms=False)

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'.

Args: opt: Option string. If it contains '0', zeros are included. return_std_rms: If True, also returns (std, rms) as scalar fields.

Returns: xarray.Dataset: Averaged dataset (single-frame, t=0) if return_std_rms=False. tuple: (avg, std, rms) if return_std_rms=True.

Source code in pivpy/pivpy.py
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
def averf(
    self,
    opt: str = "",
    *,
    return_std_rms: bool = False,
):
    """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'.

    Args:
        opt: Option string. If it contains '0', zeros are included.
        return_std_rms: If True, also returns (std, rms) as scalar fields.

    Returns:
        xarray.Dataset: Averaged dataset (single-frame, t=0) if ``return_std_rms=False``.
        tuple: ``(avg, std, rms)`` if ``return_std_rms=True``.
    """

    include_zeros = "0" in str(opt)

    ds = self._obj
    if "t" not in ds.dims:
        raise ValueError("averf requires a time dimension 't'")

    def _mean_excluding_zeros(arr: np.ndarray) -> np.ndarray:
        # arr is (y, x, t)
        valid = np.isfinite(arr)
        if not include_zeros:
            valid = valid & (arr != 0)
        out = np.zeros(arr.shape[:2], dtype=float)
        if include_zeros:
            out = np.nanmean(arr, axis=2)
            out = np.nan_to_num(out, nan=0.0)
            return out
        denom = valid.sum(axis=2)
        num = np.where(valid, arr, 0.0).sum(axis=2)
        with np.errstate(divide="ignore", invalid="ignore"):
            out = num / denom
        out = np.nan_to_num(out, nan=0.0, posinf=0.0, neginf=0.0)
        return out

    # Vector field mode if u/v exist, else scalar mode if w exists.
    if "u" in ds and "v" in ds:
        u0 = np.asarray(ds["u"].values, dtype=float)
        v0 = np.asarray(ds["v"].values, dtype=float)
        if u0.ndim != 3 or v0.ndim != 3:
            raise ValueError("Expected 'u' and 'v' to have dims ('y','x','t')")

        u_mean = _mean_excluding_zeros(u0)
        v_mean = _mean_excluding_zeros(v0)

        avg = ds.isel(t=[0]).copy(deep=True)
        avg = avg.drop_vars([v for v in avg.data_vars if v not in {"u", "v", "chc", "mask"}], errors="ignore")
        avg["u"] = xr.DataArray(u_mean[:, :, None], dims=("y", "x", "t"), attrs=ds["u"].attrs)
        avg["v"] = xr.DataArray(v_mean[:, :, None], dims=("y", "x", "t"), attrs=ds["v"].attrs)
        avg = avg.assign_coords(t=np.asarray([0.0], dtype=float))
        avg.attrs = dict(ds.attrs)

        if not return_std_rms:
            return avg

        # STD and RMS as scalar fields (combined magnitude) like PIVMat.
        finite = np.isfinite(u0) & np.isfinite(v0)
        if include_zeros:
            valid = finite
        else:
            valid = finite & (u0 != 0) & (v0 != 0)

        denom = valid.sum(axis=2).astype(float)
        denom_safe = np.where(denom == 0, np.nan, denom)

        du = u0 - u_mean[:, :, None]
        dv = v0 - v_mean[:, :, None]

        std_sq = np.where(valid, du * du + dv * dv, 0.0).sum(axis=2) / denom_safe
        rms_sq = np.where(valid, u0 * u0 + v0 * v0, 0.0).sum(axis=2) / denom_safe
        std_field = np.sqrt(std_sq)
        rms_field = np.sqrt(rms_sq)
        std_field = np.nan_to_num(std_field, nan=0.0)
        rms_field = np.nan_to_num(rms_field, nan=0.0)

        std_ds = ds.isel(t=[0]).copy(deep=True)
        rms_ds = ds.isel(t=[0]).copy(deep=True)
        std_ds = std_ds.drop_vars(list(std_ds.data_vars), errors="ignore")
        rms_ds = rms_ds.drop_vars(list(rms_ds.data_vars), errors="ignore")

        units = ds["u"].attrs.get("units", "")
        std_ds["w"] = xr.DataArray(std_field[:, :, None], dims=("y", "x", "t"), attrs={"standard_name": "standard_deviation", "units": units})
        rms_ds["w"] = xr.DataArray(rms_field[:, :, None], dims=("y", "x", "t"), attrs={"standard_name": "root_mean_square", "units": units})
        std_ds = std_ds.assign_coords(t=np.asarray([0.0], dtype=float))
        rms_ds = rms_ds.assign_coords(t=np.asarray([0.0], dtype=float))
        std_ds.attrs = dict(ds.attrs)
        rms_ds.attrs = dict(ds.attrs)
        return avg, std_ds, rms_ds

    if "w" in ds:
        w0 = np.asarray(ds["w"].values, dtype=float)
        if w0.ndim != 3:
            raise ValueError("Expected 'w' to have dims ('y','x','t')")
        w_mean = _mean_excluding_zeros(w0)
        avg = ds.isel(t=[0]).copy(deep=True)
        avg = avg.drop_vars([v for v in avg.data_vars if v != "w"], errors="ignore")
        avg["w"] = xr.DataArray(w_mean[:, :, None], dims=("y", "x", "t"), attrs=ds["w"].attrs)
        avg = avg.assign_coords(t=np.asarray([0.0], dtype=float))
        avg.attrs = dict(ds.attrs)
        if not return_std_rms:
            return avg

        finite = np.isfinite(w0)
        valid = finite if include_zeros else (finite & (w0 != 0))
        denom = valid.sum(axis=2).astype(float)
        denom_safe = np.where(denom == 0, np.nan, denom)
        dw = w0 - w_mean[:, :, None]
        std_sq = np.where(valid, dw * dw, 0.0).sum(axis=2) / denom_safe
        rms_sq = np.where(valid, w0 * w0, 0.0).sum(axis=2) / denom_safe
        std_field = np.nan_to_num(np.sqrt(std_sq), nan=0.0)
        rms_field = np.nan_to_num(np.sqrt(rms_sq), nan=0.0)

        units = ds["w"].attrs.get("units", "")
        std_ds = ds.isel(t=[0]).copy(deep=True)
        rms_ds = ds.isel(t=[0]).copy(deep=True)
        std_ds = std_ds.drop_vars(list(std_ds.data_vars), errors="ignore")
        rms_ds = rms_ds.drop_vars(list(rms_ds.data_vars), errors="ignore")
        std_ds["w"] = xr.DataArray(std_field[:, :, None], dims=("y", "x", "t"), attrs={"standard_name": "standard_deviation", "units": units})
        rms_ds["w"] = xr.DataArray(rms_field[:, :, None], dims=("y", "x", "t"), attrs={"standard_name": "root_mean_square", "units": units})
        std_ds = std_ds.assign_coords(t=np.asarray([0.0], dtype=float))
        rms_ds = rms_ds.assign_coords(t=np.asarray([0.0], dtype=float))
        std_ds.attrs = dict(ds.attrs)
        rms_ds.attrs = dict(ds.attrs)
        return avg, std_ds, rms_ds

    raise ValueError("Dataset must contain either ('u','v') or 'w' to use averf")

azaverf(x0=0.0, y0=0.0, *, center_units='phys', rmax=None, keepzero=False, return_profiles=False, var=None, frame=None)

Azimuthal average of a vector/scalar field.

Inspired by PIVMAT's azaverf.

Parameters:

Name Type Description Default
x0 float

Center location.

0.0
y0 float

Center location.

0.0
center_units Literal['phys', 'mesh']

'phys' (default) for coordinate units or 'mesh' for index units (0-based indices in x/y arrays).

'phys'
rmax Optional[float]

Optional maximum radius.

None
keepzero bool

If False (default), zero elements are treated as invalid and excluded.

False
return_profiles bool

If True, return radial profiles instead of an averaged field.

False
var Optional[str]

Scalar variable name to average. If None, uses vector mode (u, v).

None
frame Optional[int]

Optional integer time index to process a single frame.

None

Returns:

Type Description
Dataset

If return_profiles is False, returns an averaged dataset.

tuple

If return_profiles is True: - Vector mode: (r, ur, ut) - Scalar mode: (r, p)

Source code in pivpy/pivpy.py
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
def azaverf(
    self,
    x0: float = 0.0,
    y0: float = 0.0,
    *,
    center_units: Literal["phys", "mesh"] = "phys",
    rmax: Optional[float] = None,
    keepzero: bool = False,
    return_profiles: bool = False,
    var: Optional[str] = None,
    frame: Optional[int] = None,
):
    """Azimuthal average of a vector/scalar field.

    Inspired by PIVMAT's ``azaverf``.

    Parameters
    ----------
    x0, 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_profiles`` is False, returns an averaged dataset.

    tuple
        If ``return_profiles`` is True:
        - Vector mode: ``(r, ur, ut)``
        - Scalar mode: ``(r, p)``
    """

    ds = self._obj
    if "x" not in ds.coords or "y" not in ds.coords:
        raise ValueError("azaverf requires 'x' and 'y' coordinates")

    x = np.asarray(ds.coords["x"].values, dtype=float)
    y = np.asarray(ds.coords["y"].values, dtype=float)
    if x.size < 2 or y.size < 2:
        raise ValueError("azaverf requires at least 2 points in x and y")

    dx = float(np.nanmedian(np.diff(x)))
    dy = float(np.nanmedian(np.diff(y)))
    dx_abs = abs(dx) if dx != 0 else 1.0
    dy_abs = abs(dy) if dy != 0 else 1.0
    dr = dx_abs
    if not np.isfinite(dr) or dr == 0.0:
        dr = 1.0

    if center_units == "mesh":
        # x0/y0 are 0-based indices into x/y.
        x0_phys = float(x[0] + x0 * dx)
        y0_phys = float(y[0] + y0 * dy)
        rmax_phys = None if rmax is None else float(rmax) * dr
    elif center_units == "phys":
        x0_phys = float(x0)
        y0_phys = float(y0)
        rmax_phys = None if rmax is None else float(rmax)
    else:
        raise ValueError("center_units must be 'phys' or 'mesh'")

    X, Y = np.meshgrid(x, y)
    dX = X - x0_phys
    dY = Y - y0_phys
    R = np.sqrt(dX * dX + dY * dY)
    if rmax_phys is not None:
        Rmask = R <= rmax_phys
    else:
        Rmask = np.ones_like(R, dtype=bool)

    # Bin index: 0 corresponds to r in [0, dr)
    bin_idx = np.floor(R / dr).astype(int)
    # Exclude center where projections are undefined.
    not_center = R > 0

    if "t" in ds.dims:
        t_indices = list(range(int(ds.sizes["t"])))
    else:
        # Treat as single frame.
        t_indices = [0]

    if frame is not None:
        frame_i = int(frame)
        t_indices = [frame_i]

    # Decide scalar vs vector mode.
    scalar_mode = var is not None
    if scalar_mode:
        if var not in ds:
            raise ValueError(f"Scalar variable '{var}' not found in dataset")
    else:
        if "u" not in ds or "v" not in ds:
            raise ValueError("Vector mode azaverf requires 'u' and 'v'")

    maxbin = int(np.nanmax(bin_idx[Rmask])) if np.any(Rmask) else 0
    # Preallocate profiles across time.
    if scalar_mode:
        prof = np.full((maxbin + 1, len(t_indices)), np.nan, dtype=float)
        counts_any = np.zeros((maxbin + 1,), dtype=int)
    else:
        prof_ur = np.full((maxbin + 1, len(t_indices)), np.nan, dtype=float)
        prof_ut = np.full((maxbin + 1, len(t_indices)), np.nan, dtype=float)
        counts_any = np.zeros((maxbin + 1,), dtype=int)

    # Flatten helpers.
    bin_flat = bin_idx.ravel()
    R_flat = R.ravel()
    dX_flat = dX.ravel()
    dY_flat = dY.ravel()
    base_mask_flat = (Rmask & not_center).ravel()

    for k, ti in enumerate(t_indices):
        if "t" in ds.dims:
            if scalar_mode:
                A = np.asarray(ds[var].isel(t=ti).values, dtype=float)
            else:
                U = np.asarray(ds["u"].isel(t=ti).values, dtype=float)
                V = np.asarray(ds["v"].isel(t=ti).values, dtype=float)
        else:
            if scalar_mode:
                A = np.asarray(ds[var].values, dtype=float)
            else:
                U = np.asarray(ds["u"].values, dtype=float)
                V = np.asarray(ds["v"].values, dtype=float)

        if scalar_mode:
            A_flat = A.ravel()
            finite = np.isfinite(A_flat)
            valid = base_mask_flat & finite
            if not keepzero:
                valid = valid & (A_flat != 0)
            if not np.any(valid):
                continue
            cnt = np.bincount(bin_flat[valid], minlength=maxbin + 1)
            s = np.bincount(bin_flat[valid], weights=A_flat[valid], minlength=maxbin + 1)
            with np.errstate(divide="ignore", invalid="ignore"):
                p = s / cnt
            prof[:, k] = p
            counts_any = np.maximum(counts_any, cnt)
        else:
            U_flat = U.ravel()
            V_flat = V.ravel()
            finite = np.isfinite(U_flat) & np.isfinite(V_flat)
            valid = base_mask_flat & finite
            if not keepzero:
                valid = valid & (U_flat != 0) & (V_flat != 0)
            if not np.any(valid):
                continue

            with np.errstate(divide="ignore", invalid="ignore"):
                ur_pt = (U_flat * dX_flat + V_flat * dY_flat) / R_flat
                ut_pt = (-U_flat * dY_flat + V_flat * dX_flat) / R_flat

            cnt = np.bincount(bin_flat[valid], minlength=maxbin + 1)
            sur = np.bincount(bin_flat[valid], weights=ur_pt[valid], minlength=maxbin + 1)
            sut = np.bincount(bin_flat[valid], weights=ut_pt[valid], minlength=maxbin + 1)
            with np.errstate(divide="ignore", invalid="ignore"):
                ur = sur / cnt
                ut = sut / cnt
            prof_ur[:, k] = ur
            prof_ut[:, k] = ut
            counts_any = np.maximum(counts_any, cnt)

    nonzero_bins = np.nonzero(counts_any)[0]
    if nonzero_bins.size == 0:
        if return_profiles:
            if scalar_mode:
                return np.asarray([]), np.asarray([[]])
            return np.asarray([]), np.asarray([[]]), np.asarray([[]])
        # Return zeros field of same shape.
        out = ds.copy(deep=True)
        if scalar_mode:
            out[var] = out[var] * 0
        else:
            out["u"] = out["u"] * 0
            out["v"] = out["v"] * 0
        return out

    first_bin = int(nonzero_bins[0])
    last_bin = int(nonzero_bins[-1])
    r_vec = (np.arange(first_bin, last_bin + 1, dtype=float) * dr)

    if return_profiles:
        if scalar_mode:
            return r_vec, prof[first_bin : last_bin + 1, :]
        return r_vec, prof_ur[first_bin : last_bin + 1, :], prof_ut[first_bin : last_bin + 1, :]

    # Build azimuthally averaged field.
    out = ds.copy(deep=True)

    # Reconstruct per-frame fields from profiles.
    bin2 = bin_idx.copy()
    in_range = (bin2 >= first_bin) & (bin2 <= last_bin) & not_center & Rmask
    # Prepare output arrays.
    if "t" in ds.dims:
        t_full = int(ds.sizes["t"])
        if frame is None:
            t_out_indices = list(range(t_full))
            prof_cols = {ti: idx for idx, ti in enumerate(t_indices)}
        else:
            t_out_indices = [int(frame)]
            prof_cols = {int(frame): 0}
    else:
        t_out_indices = [0]
        prof_cols = {0: 0}

    if scalar_mode:
        # Set values by bin, outside range -> 0.
        if "t" in ds.dims:
            for ti in t_out_indices:
                col = prof_cols.get(ti, None)
                if col is None:
                    out[var].isel(t=ti).values[...] = 0.0
                    continue
                p_full = np.zeros((maxbin + 1,), dtype=float)
                p_slice = prof[:, col]
                p_full[:] = np.nan_to_num(p_slice, nan=0.0)
                w_new = np.zeros_like(R)
                w_new[in_range] = p_full[bin2[in_range]]
                out[var].isel(t=ti).values[...] = w_new
        else:
            p_full = np.zeros((maxbin + 1,), dtype=float)
            p_full[:] = np.nan_to_num(prof[:, 0], nan=0.0)
            w_new = np.zeros_like(R)
            w_new[in_range] = p_full[bin2[in_range]]
            out[var].values[...] = w_new
        return out

    # Vector mode.
    if "t" in ds.dims:
        for ti in t_out_indices:
            col = prof_cols.get(ti, None)
            if col is None:
                out["u"].isel(t=ti).values[...] = 0.0
                out["v"].isel(t=ti).values[...] = 0.0
                continue
            ur_full = np.zeros((maxbin + 1,), dtype=float)
            ut_full = np.zeros((maxbin + 1,), dtype=float)
            ur_full[:] = np.nan_to_num(prof_ur[:, col], nan=0.0)
            ut_full[:] = np.nan_to_num(prof_ut[:, col], nan=0.0)
            ur_grid = np.zeros_like(R)
            ut_grid = np.zeros_like(R)
            ur_grid[in_range] = ur_full[bin2[in_range]]
            ut_grid[in_range] = ut_full[bin2[in_range]]

            u_new = np.zeros_like(R)
            v_new = np.zeros_like(R)
            # u = ur * cos(theta) - ut * sin(theta) where cos=dx/r, sin=dy/r
            u_new[in_range] = ur_grid[in_range] * (dX[in_range] / R[in_range]) - ut_grid[in_range] * (dY[in_range] / R[in_range])
            v_new[in_range] = ur_grid[in_range] * (dY[in_range] / R[in_range]) + ut_grid[in_range] * (dX[in_range] / R[in_range])
            out["u"].isel(t=ti).values[...] = u_new
            out["v"].isel(t=ti).values[...] = v_new
    else:
        ur_full = np.zeros((maxbin + 1,), dtype=float)
        ut_full = np.zeros((maxbin + 1,), dtype=float)
        ur_full[:] = np.nan_to_num(prof_ur[:, 0], nan=0.0)
        ut_full[:] = np.nan_to_num(prof_ut[:, 0], nan=0.0)
        ur_grid = np.zeros_like(R)
        ut_grid = np.zeros_like(R)
        ur_grid[in_range] = ur_full[bin2[in_range]]
        ut_grid[in_range] = ut_full[bin2[in_range]]
        u_new = np.zeros_like(R)
        v_new = np.zeros_like(R)
        u_new[in_range] = ur_grid[in_range] * (dX[in_range] / R[in_range]) - ut_grid[in_range] * (dY[in_range] / R[in_range])
        v_new[in_range] = ur_grid[in_range] * (dY[in_range] / R[in_range]) + ut_grid[in_range] * (dX[in_range] / R[in_range])
        out["u"].values[...] = u_new
        out["v"].values[...] = v_new

    return out

azprofile(x0=0.0, y0=0.0, r=1.0, na=None, *, var=None, frame=None, angle_dim='angle')

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:

Name Type Description Default
x0 float

Circle center in the same units as coordinates x and y.

0.0
y0 float

Circle center in the same units as coordinates x and y.

0.0
r float

Circle radius.

1.0
na int | None

Number of angular samples. If None, uses PIVMAT's default heuristic round(4*r/abs(dx)) where dx is the x-grid spacing.

None
var str | None

Scalar variable to sample. If None, samples vector components u and v and returns (angle, ur, ut).

None
frame int | None

Optional time index. If provided, samples only that frame.

None
angle_dim str

Name of the angular dimension.

'angle'

Returns:

Type Description
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 frame is None, the profiles have shape (na, nt).

Source code in pivpy/pivpy.py
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
def azprofile(
    self,
    x0: float = 0.0,
    y0: float = 0.0,
    r: float = 1.0,
    na: int | None = None,
    *,
    var: str | None = None,
    frame: int | None = None,
    angle_dim: str = "angle",
):
    """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, y0:
        Circle center in the same units as coordinates ``x`` and ``y``.
    r:
        Circle radius.
    na:
        Number of angular samples. If None, uses PIVMAT's default heuristic
        ``round(4*r/abs(dx))`` where ``dx`` is the x-grid spacing.
    var:
        Scalar variable to sample. If None, samples vector components ``u`` and ``v``
        and 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
    ``frame`` is None, the profiles have shape ``(na, nt)``.
    """

    ds = self._obj
    if "x" not in ds.coords or "y" not in ds.coords:
        raise ValueError("azprofile requires 'x' and 'y' coordinates")

    x = np.asarray(ds.coords["x"].values, dtype=float)
    if x.size < 2:
        raise ValueError("azprofile requires at least 2 x points")
    dx = float(np.nanmedian(np.diff(x)))
    dx_abs = abs(dx) if np.isfinite(dx) and dx != 0 else 1.0
    if na is None:
        na = int(round(4.0 * float(r) / dx_abs))
    na = int(na)
    if na <= 0:
        raise ValueError("na must be positive")

    angle = np.linspace(0.0, 2.0 * np.pi, na, endpoint=False)
    x_s = x0 + float(r) * np.cos(angle)
    y_s = y0 + float(r) * np.sin(angle)

    a_da = xr.DataArray(angle, dims=(angle_dim,), coords={angle_dim: angle})
    x_da = xr.DataArray(x_s, dims=(angle_dim,), coords={angle_dim: angle})
    y_da = xr.DataArray(y_s, dims=(angle_dim,), coords={angle_dim: angle})
    cos_da = xr.DataArray(np.cos(angle), dims=(angle_dim,), coords={angle_dim: angle})
    sin_da = xr.DataArray(np.sin(angle), dims=(angle_dim,), coords={angle_dim: angle})

    # Optional frame selection.
    if frame is not None:
        if "t" not in ds.dims:
            raise ValueError("frame was provided but dataset has no 't' dimension")
        ds = ds.isel(t=int(frame))

    scalar_mode = var is not None
    if scalar_mode:
        if var not in ds:
            raise ValueError(f"Scalar variable '{var}' not found in dataset")
        p = ds[var].interp(x=x_da, y=y_da)
        # Ensure angle-first for numpy return.
        if angle_dim in p.dims:
            p = p.transpose(angle_dim, ...)
        return angle, np.asarray(p.values)

    # Vector mode
    if "u" not in ds or "v" not in ds:
        raise ValueError("Vector mode azprofile requires 'u' and 'v'")

    u_samp = ds["u"].interp(x=x_da, y=y_da)
    v_samp = ds["v"].interp(x=x_da, y=y_da)
    ur = u_samp * cos_da + v_samp * sin_da
    ut = -u_samp * sin_da + v_samp * cos_da

    ur = ur.transpose(angle_dim, ...)
    ut = ut.transpose(angle_dim, ...)
    return angle, np.asarray(ur.values), np.asarray(ut.values)

bwfilterf(filtsize=3.0, order=8.0, *, mode='low', trunc=False, var=None, variables=None)

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:

Name Type Description Default
filtsize float

Cutoff size in grid units. If 0, returns the dataset unchanged.

3.0
order float

Filter order (typical range 2..10). Larger means sharper cutoff.

8.0
mode Literal['low', 'high']

'low' or 'high'. High-pass is implemented by flipping the sign of order.

'low'
trunc bool

If True, truncates borders of width floor(filtsize) after filtering.

False
var Optional[str]

Scalar variable name to filter. If None, defaults to vector mode (u, v) unless variables is provided.

None
variables Optional[List[str]]

Explicit list of variables to filter.

None
Source code in pivpy/pivpy.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
def bwfilterf(
    self,
    filtsize: float = 3.0,
    order: float = 8.0,
    *,
    mode: Literal["low", "high"] = "low",
    trunc: bool = False,
    var: Optional[str] = None,
    variables: Optional[List[str]] = None,
) -> xr.Dataset:
    """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.
    """

    fs = float(filtsize)
    if fs == 0.0:
        return self._obj

    ds = self._obj
    if "x" not in ds.dims or "y" not in ds.dims:
        raise ValueError("bwfilterf requires spatial dims 'y' and 'x'")

    ord_eff = float(order)
    if str(mode).lower().startswith("high"):
        ord_eff = -abs(ord_eff)
    else:
        ord_eff = abs(ord_eff)

    # PIVMAT behavior: enforce even spatial sizes by dropping last row/col.
    out = ds
    if int(out.sizes["x"]) % 2 == 1:
        out = out.isel(x=slice(0, -1))
    if int(out.sizes["y"]) % 2 == 1:
        out = out.isel(y=slice(0, -1))

    if variables is None:
        if var is not None:
            variables = [var]
        else:
            variables = [v for v in ("u", "v") if v in out.data_vars]
            if not variables:
                raise ValueError("bwfilterf: no variables to filter (expected 'u'/'v' or var=...)")
    else:
        variables = list(variables)
        for v in variables:
            if v not in out.data_vars:
                raise ValueError(f"Variable '{v}' not found in dataset")

    def _bw_core(a2: np.ndarray) -> np.ndarray:
        return bwfilter2d(a2, fs, ord_eff)

    out2 = out.copy(deep=True)
    for name in variables:
        da = out2[name]
        if "y" not in da.dims or "x" not in da.dims:
            continue
        out2[name] = xr.apply_ufunc(
            _bw_core,
            da,
            input_core_dims=[["y", "x"]],
            output_core_dims=[["y", "x"]],
            vectorize=True,
            dask="parallelized",
            output_dtypes=[float],
        )
        out2[name].attrs = dict(out[name].attrs)

    if trunc:
        ntr = int(np.floor(fs))
        if ntr > 0:
            ny = int(out2.sizes["y"])
            nx = int(out2.sizes["x"])
            if 2 * ntr >= ny or 2 * ntr >= nx:
                raise ValueError("truncation too large for field size")
            out2 = out2.isel(y=slice(ntr, -ntr), x=slice(ntr, -ntr))

    out2.attrs = dict(out.attrs)
    self._obj = out2
    return out2

bwfilterf_pm(filtsize, order, *opts, var=None, variables=None)

PIVMAT-compatible wrapper for :meth: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')
Source code in pivpy/pivpy.py
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
def bwfilterf_pm(
    self,
    filtsize: float,
    order: float,
    *opts: str,
    var: Optional[str] = None,
    variables: Optional[List[str]] = None,
) -> xr.Dataset:
    """PIVMAT-compatible wrapper for :meth:`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')``
    """

    mode: Literal["low", "high"] = "low"
    trunc = False
    for opt in opts:
        o = str(opt).lower()
        if o.startswith("high"):
            mode = "high"
        elif o.startswith("low"):
            mode = "low"
        elif o.startswith("trunc"):
            trunc = True
        elif o == "":
            continue
        else:
            raise ValueError(f"Unknown bwfilterf option: {opt!r}")

    return self.bwfilterf(
        filtsize=float(filtsize),
        order=float(order),
        mode=mode,
        trunc=trunc,
        var=var,
        variables=variables,
    )

clean(method='normalized_median', threshold=2.0, epsilon=0.1, inpaint_method=0, radius=1)

Detects velocity outliers and inpaints missing/flagged vectors.

Args: method (str): Outlier detection method ('normalized_median' or 'mask'). threshold (float): Outlier threshold for normalized median test. Defaults to 2.0. epsilon (float): Noise floor parameter. Defaults to 0.1. inpaint_method (int or str): Inpainting scheme (0=harmonic, 1=nearest, 2=linear). radius (int): Neighborhood radius for median test. Defaults to 1.

Returns: xarray.Dataset: Cleaned dataset.

Source code in pivpy/pivpy.py
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
def clean(
    self,
    method: str = "normalized_median",
    threshold: float = 2.0,
    epsilon: float = 0.1,
    inpaint_method: int | str = 0,
    radius: int = 1,
):
    """Detects velocity outliers and inpaints missing/flagged vectors.

    Args:
        method (str): Outlier detection method ('normalized_median' or 'mask').
        threshold (float): Outlier threshold for normalized median test. Defaults to 2.0.
        epsilon (float): Noise floor parameter. Defaults to 0.1.
        inpaint_method (int or str): Inpainting scheme (0=harmonic, 1=nearest, 2=linear).
        radius (int): Neighborhood radius for median test. Defaults to 1.

    Returns:
        xarray.Dataset: Cleaned dataset.
    """
    return cclean(
        self._obj,
        method=method,
        threshold=threshold,
        epsilon=epsilon,
        inpaint_method=inpaint_method,
        radius=radius,
    )

clip(min=None, max=None, *, by=None, keep_attrs=True)

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).

Args: 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: xarray.Dataset: Dataset with clipped values. If 'by' is specified, returns dataset with locations that don't meet the criteria set to NaN.

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

Source code in pivpy/pivpy.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
def clip(
    self,
    min=None,
    max=None,
    *,
    by: str = None,
    keep_attrs: bool = True,
):
    """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).

    Args:
        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:
        xarray.Dataset: Dataset with clipped values. If 'by' is specified, returns
            dataset with locations that don't meet the criteria set to NaN.

    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
    """
    if min is None and max is None:
        raise ValueError("At least one of 'min' or 'max' must be provided")

    if by is None:
        # Clip all variables independently using xarray's built-in clip
        return self._obj.clip(min=min, max=max, keep_attrs=keep_attrs)

    # Clip based on a specific variable
    if by == "magnitude":
        # Compute magnitude if not already in dataset
        criterion = np.sqrt(self._obj["u"] ** 2 + self._obj["v"] ** 2)
    else:
        # Use existing variable
        if by not in self._obj:
            raise ValueError(
                f"Variable '{by}' not found in dataset. "
                f"Available variables: {list(self._obj.data_vars)}"
            )
        criterion = self._obj[by]

    # Create mask based on criterion
    mask = xr.ones_like(criterion, dtype=bool)
    if min is not None:
        mask = mask & (criterion >= min)
    if max is not None:
        mask = mask & (criterion <= max)

    # Apply mask to all data variables (set non-matching locations to NaN)
    result = self._obj.copy()
    for var in result.data_vars:
        result[var] = result[var].where(mask)

    if not keep_attrs:
        result.attrs = {}
        for var in result.data_vars:
            result[var].attrs = {}

    return result

corrf(variable='u', dim='x', *, normalize=False, nan_as_zero=True, nowarning=False)

PIVMAT-style spatial correlation and integral scales for a scalar variable.

This wraps :func:pivpy.compute_funcs.corrf and returns a Dataset with coordinate r and variable f plus scalar outputs (isinf, r5, ...).

Source code in pivpy/pivpy.py
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
def corrf(
    self,
    variable: str = "u",
    dim: int | str = "x",
    *,
    normalize: bool = False,
    nan_as_zero: bool = True,
    nowarning: bool = False,
) -> xr.Dataset:
    """PIVMAT-style spatial correlation and integral scales for a scalar variable.

    This wraps :func:`pivpy.compute_funcs.corrf` and returns a Dataset with
    coordinate ``r`` and variable ``f`` plus scalar outputs (``isinf``, ``r5``, ...).
    """

    if variable not in self._obj:
        raise KeyError(f"Variable {variable} not in dataset")

    return corrf(
        self._obj[variable],
        dim=dim,
        normalize=normalize,
        nan_as_zero=nan_as_zero,
        nowarning=nowarning,
    )

corrm(variable='u', dim='x', *, half=False, nan_as_zero=True, lag_dim='lag')

PIVMAT-style matrix correlation for a variable.

Parameters:

Name Type Description Default
variable str

Name of the DataArray variable in the Dataset.

'u'
dim int | str

Dimension name (recommended) or 1/2 like MATLAB for 2D arrays.

'x'
half bool

If True, return only non-negative lags (including zero-lag).

False
nan_as_zero bool

If True, treat NaNs as missing data and replace by 0 before correlating.

True
lag_dim str

Name of the lag dimension in the returned DataArray.

'lag'
Source code in pivpy/pivpy.py
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
def corrm(
    self,
    variable: str = "u",
    dim: int | str = "x",
    *,
    half: bool = False,
    nan_as_zero: bool = True,
    lag_dim: str = "lag",
) -> xr.DataArray:
    """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.
    """

    if variable not in self._obj:
        raise KeyError(f"Variable {variable} not in dataset")

    return corrm(
        self._obj[variable],
        dim=dim,
        half=half,
        nan_as_zero=nan_as_zero,
        lag_dim=lag_dim,
    )

crop(crop_vector=None)

Crops xarray Dataset to specified spatial boundaries

Args: 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: xarray.Dataset: Cropped dataset

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

Source code in pivpy/pivpy.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def crop(self, crop_vector=None):
    """Crops xarray Dataset to specified spatial boundaries

    Args:
        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:
        xarray.Dataset: Cropped dataset

    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
    """
    if crop_vector is None:
        crop_vector = 4 * [None]

    if len(crop_vector) != 4:
        raise ValueError(
            f"crop_vector must have 4 elements [xmin, xmax, ymin, ymax], "
            f"got {len(crop_vector)} elements"
        )

    xmin, xmax, ymin, ymax = crop_vector

    xmin = self._obj.x.min() if xmin is None else xmin
    xmax = self._obj.x.max() if xmax is None else xmax
    ymin = self._obj.y.min() if ymin is None else ymin
    ymax = self._obj.y.max() if ymax is None else ymax

    # Note: We don't validate xmin < xmax or ymin < ymax because coordinates
    # might be in reverse order (e.g., negative y-axis pointing down)

    warnings.warn(
        "piv.crop() currently rebinds this accessor's internal dataset "
        "reference as a side effect; a future release will make it a pure "
        "function that only returns the cropped dataset. Always use the "
        "return value (`ds = ds.piv.crop(...)`) rather than relying on "
        "in-place state.",
        DeprecationWarning,
        stacklevel=2,
    )
    self._obj = self._obj.sel(x=slice(xmin, xmax), y=slice(ymin, ymax))

    return self._obj

dissipation(method='direct', nu=1.5e-05, name='w')

Estimates turbulent kinetic energy dissipation rate epsilon.

Source code in pivpy/pivpy.py
2396
2397
2398
2399
2400
2401
2402
2403
def dissipation(
    self,
    method: str = "direct",
    nu: float = 1.5e-5,
    name: str = "w",
):
    """Estimates turbulent kinetic energy dissipation rate epsilon."""
    return cdissipation(self._obj, method=method, nu=nu, name=name)

divergence(name='w')

Calculates divergence field

Args: name (str): Name for the output scalar field. Defaults to "w". Use different names to store multiple scalar fields in one dataset.

Returns: xarray.Dataset: Dataset with the new property [name] = divergence

Example: >>> data.piv.divergence() # Creates data["w"] with divergence >>> data.piv.divergence(name="div") # Creates data["div"] with divergence

Source code in pivpy/pivpy.py
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
def divergence(self, name: str = "w"):
    """Calculates divergence field

    Args:
        name (str): Name for the output scalar field. Defaults to "w".
            Use different names to store multiple scalar fields in one dataset.

    Returns:
        xarray.Dataset: Dataset with the new property [name] = divergence

    Example:
        >>> data.piv.divergence()  # Creates data["w"] with divergence
        >>> data.piv.divergence(name="div")  # Creates data["div"] with divergence
    """
    warn_if_overwriting_scalar(self._obj, name)
    du_dx, _ = np.gradient(
        self._obj["u"], self._obj["x"], self._obj["y"], axis=(0, 1)
    )
    _, dv_dy = np.gradient(
        self._obj["v"], self._obj["x"], self._obj["y"], axis=(0, 1)
    )

    if "t" in self._obj.coords:
        self._obj[name] = (("x", "y", "t"), dv_dy + du_dx)
    else:
        self._obj[name] = (("x", "y"), dv_dy + du_dx)

    self._obj[name].attrs["units"] = "1/delta_t"
    self._obj[name].attrs["standard_name"] = "divergence"

    return self._obj

energy_spectrum(window='hann', detrend=True, radial=True)

Computes 2D and radial wavenumber energy spectra.

Source code in pivpy/pivpy.py
2361
2362
2363
2364
2365
2366
2367
2368
def energy_spectrum(
    self,
    window: str = "hann",
    detrend: bool = True,
    radial: bool = True,
):
    """Computes 2D and radial wavenumber energy spectra."""
    return cenergy_spectrum(self._obj, window=window, detrend=detrend, radial=radial)

explore(port=8000, host='127.0.0.1', open_browser=True)

Launches the interactive Marimo PIVPy diagnostics and visualization app.

Source code in pivpy/pivpy.py
2846
2847
2848
2849
def explore(self, port: int = 8000, host: str = "127.0.0.1", open_browser: bool = True):
    """Launches the interactive Marimo PIVPy diagnostics and visualization app."""
    from pivpy.app import launch_app
    return launch_app(dataset=self._obj, port=port, host=host, open_browser=open_browser)

extractf(rect, opt='phys', *, return_rect=False)

Extract a rectangular area from the dataset (PIVMAT-inspired).

Parameters:

Name Type Description Default
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.

required
opt str

'phys' (default) or 'mesh'.

'phys'
return_rect bool

If True, also returns the effective rectangle in mesh indices [ix1, iy1, ix2, iy2] (1-based, inclusive) after clamping.

False

Returns:

Type Description
Dataset

Extracted dataset.

tuple

If return_rect=True, returns (dataset, rect_mesh) where rect_mesh is [ix1, iy1, ix2, iy2] (1-based, inclusive).

Notes

Interactive rectangle selection (PIVMAT's 'draw') is not supported.

Source code in pivpy/pivpy.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def extractf(
    self,
    rect,
    opt: str = "phys",
    *,
    return_rect: bool = False,
):
    """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)`` where
        ``rect_mesh`` is ``[ix1, iy1, ix2, iy2]`` (1-based, inclusive).

    Notes
    -----
    Interactive rectangle selection (PIVMAT's 'draw') is not supported.
    """

    ds = self._obj
    if rect is None:
        raise ValueError("extractf requires rect=[x1, y1, x2, y2]")
    if isinstance(rect, str) and rect.lower().startswith("draw"):
        raise NotImplementedError("Interactive rectangle selection is not supported; pass rect explicitly.")

    if not hasattr(rect, "__len__") or len(rect) != 4:
        raise ValueError("rect must be a sequence of 4 values: [x1, y1, x2, y2]")

    x1, y1, x2, y2 = rect

    if "x" not in ds.dims or "y" not in ds.dims:
        raise ValueError("extractf requires dataset dims 'x' and 'y'")

    def _bounds_from_phys(coord_vals: np.ndarray, a: float, b: float) -> tuple[int, int]:
        vals = np.asarray(coord_vals, dtype=float)
        n = int(vals.shape[0])
        if n == 0:
            return 0, -1
        if n == 1:
            return 0, 0

        lo = float(min(a, b))
        hi = float(max(a, b))

        reversed_axis = bool(vals[1] < vals[0])
        sorted_vals = vals[::-1] if reversed_axis else vals

        i1 = int(np.searchsorted(sorted_vals, lo, side="right") - 1)
        i2 = int(np.searchsorted(sorted_vals, hi, side="left"))

        if i1 < 0:
            i1 = 0
        if i2 < 0:
            i2 = 0
        if i1 > n - 1:
            i1 = n - 1
        if i2 > n - 1:
            i2 = n - 1

        if reversed_axis:
            start = (n - 1) - i2
            stop = (n - 1) - i1
        else:
            start = i1
            stop = i2

        if start > stop:
            # Degenerate selection: choose nearest index.
            target = 0.5 * (lo + hi)
            nearest = int(np.argmin(np.abs(vals - target)))
            return nearest, nearest

        return int(start), int(stop)

    def _bounds_from_mesh(n: int, a: float, b: float) -> tuple[int, int]:
        if n <= 0:
            return 0, -1
        lo = int(np.floor(min(a, b))) - 1
        hi = int(np.ceil(max(a, b))) - 1
        lo = max(lo, 0)
        hi = min(hi, n - 1)
        if lo > hi:
            lo = hi
        return lo, hi

    opt_l = str(opt).lower()
    if opt_l.startswith("phys"):
        xs, xe = _bounds_from_phys(ds["x"].values, float(x1), float(x2))
        ys, ye = _bounds_from_phys(ds["y"].values, float(y1), float(y2))
    elif opt_l.startswith("mesh"):
        xs, xe = _bounds_from_mesh(int(ds.sizes["x"]), float(x1), float(x2))
        ys, ye = _bounds_from_mesh(int(ds.sizes["y"]), float(y1), float(y2))
    else:
        raise ValueError("opt must be 'phys' or 'mesh'")

    out = ds.isel(x=slice(xs, xe + 1), y=slice(ys, ye + 1))
    out.attrs = dict(ds.attrs)
    self._obj = out

    mesh_rect = [xs + 1, ys + 1, xe + 1, ye + 1]
    if return_rect:
        return out, mesh_rect
    return out

fill_nans(method='nearest')

This method uses scipy.interpolate.griddata to interpolate missing data.

Parameters:

Name Type Description Default
src_data

Input data array.

required
method Literal['linear', 'nearest', 'cubic']

The method to use for interpolation in scipy.interpolate.griddata.

'nearest'

Returns:

Type Description
class:`numpy.ndarray`:

An interpolated :class:numpy.ndarray.

Source code in pivpy/pivpy.py
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
def fill_nans(self, method: Literal["linear", "nearest", "cubic"] = "nearest"):
    """
    This method uses scipy.interpolate.griddata to interpolate missing data.
    Parameters
    ----------
    src_data: Any
        Input data array.
    method: {'linear', 'nearest', 'cubic'}
        The method to use for interpolation in `scipy.interpolate.griddata`.
    Returns
    -------
    :class:`numpy.ndarray`:
        An interpolated :class:`numpy.ndarray`.
    """

    def _griddata_nans(src_data, x_coords, y_coords, method=method):

        src_data_flat = src_data.copy().flatten()
        data_bool = ~np.isnan(src_data_flat)

        if not data_bool.any():
            return src_data

        return griddata(
            points=(x_coords.flatten()[data_bool], y_coords.flatten()[data_bool]),
            values=src_data_flat[data_bool],
            xi=(x_coords, y_coords),
            method=method,
            # fill_value=nodata,
        )

    x_coords, y_coords = np.meshgrid(
        self._obj.coords["x"].values, self._obj.coords["y"].values
    )

    for var_name in self._obj.variables:
        if var_name not in self._obj.coords:
            for t_i in self._obj["t"]:
                new_data = _griddata_nans(
                    self._obj.sel(t=t_i)[var_name].data,
                    x_coords,
                    y_coords,
                    method=method,
                )
                self._obj.sel(t=t_i)[var_name].data[:] = new_data

    return self._obj

fill_zeros(*, fill=False, max_iter=None, variables=None)

Fill zero-valued holes using 4-neighbor interpolation.

This is a PIVMAT interpolat-style helper, useful when invalid vectors are encoded as zeros.

Parameters:

Name Type Description Default
fill bool

If True, iterate until no zeros remain (or until max_iter).

False
max_iter int | None

Optional iteration cap.

None
variables list[str] | None

Variables to process. Default: ['u', 'v'] if present; otherwise all data_vars.

None
Source code in pivpy/pivpy.py
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
def fill_zeros(
    self,
    *,
    fill: bool = False,
    max_iter: int | None = None,
    variables: list[str] | None = None,
) -> xr.Dataset:
    """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.
    """

    ds = self._obj
    if variables is None:
        variables = [v for v in ("u", "v") if v in ds.data_vars] or list(ds.data_vars)

    out = ds.copy(deep=True)
    for name in variables:
        da = out[name]
        if da.ndim < 2:
            continue
        out[name] = interpolat_zeros_2d(da, fill=fill, max_iter=max_iter)
        out[name].attrs = dict(ds[name].attrs)

    out.attrs = dict(ds.attrs)
    return out

filter(sigma=1.0, method='gaussian', **kwargs)

Alias for smooth().

Source code in pivpy/pivpy.py
2324
2325
2326
2327
2328
2329
2330
2331
def filter(
    self,
    sigma: float | Sequence[float] = 1.0,
    method: str = "gaussian",
    **kwargs,
):
    """Alias for smooth()."""
    return self.smooth(sigma=sigma, method=method, **kwargs)

filter_outliers(threshold=2.0, replace=True, **kwargs)

Convenience method to detect and optionally replace spurious vector outliers.

Args: threshold (float): Outlier threshold for normalized median test. Defaults to 2.0. replace (bool): If True, replaces outliers via harmonic inpainting. If False, flags in 'chc'. **kwargs: Additional parameters passed to clean or normalized_median_test.

Returns: xarray.Dataset: Filtered/cleaned dataset.

Source code in pivpy/pivpy.py
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
def filter_outliers(self, threshold: float = 2.0, replace: bool = True, **kwargs):
    """Convenience method to detect and optionally replace spurious vector outliers.

    Args:
        threshold (float): Outlier threshold for normalized median test. Defaults to 2.0.
        replace (bool): If True, replaces outliers via harmonic inpainting. If False, flags in 'chc'.
        **kwargs: Additional parameters passed to `clean` or `normalized_median_test`.

    Returns:
        xarray.Dataset: Filtered/cleaned dataset.
    """
    if replace:
        return self.clean(threshold=threshold, **kwargs)
    return self.normalized_median_test(threshold=threshold, **kwargs)

filterf(sigma=[1.0, 1.0, 0.0], method='gauss', *opts, **kwargs)

Apply a spatial filter to a vector/scalar field (PIVMAT-inspired).

This method supports two calling conventions:

1) 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``.

2) PIVMAT-style normalized 2D convolution (NaN-aware)::

 ds = ds.piv.filterf(filtsize, method, 'same')
 ds = ds.piv.filterf(filtsize, method)         # default is 'valid'

where method is one of: 'gauss' (default), 'flat', 'igauss'. The option 'same' keeps the original shape; otherwise the result is smaller (Matlab conv2(...,'valid') behavior) and the x/y coordinates are truncated accordingly.

Source code in pivpy/pivpy.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
def filterf(self, sigma: List[float] | float = [1.0, 1.0, 0.0], method: str = "gauss", *opts: str, **kwargs):
    """Apply a spatial filter to a vector/scalar field (PIVMAT-inspired).

    This method supports two calling conventions:

    1) 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``.

    2) PIVMAT-style normalized 2D convolution (NaN-aware)::

         ds = ds.piv.filterf(filtsize, method, 'same')
         ds = ds.piv.filterf(filtsize, method)         # default is 'valid'

       where ``method`` is one of: ``'gauss'`` (default), ``'flat'``, ``'igauss'``.
       The option ``'same'`` keeps the original shape; otherwise the result is
       smaller (Matlab ``conv2(...,'valid')`` behavior) and the x/y coordinates are
       truncated accordingly.
    """

    # --- Legacy path: sigma is a 3-vector
    if isinstance(sigma, (list, tuple, np.ndarray)):
        sigma_list = list(sigma)
        if len(sigma_list) != 3:
            raise ValueError(
                f"sigma must have 3 elements [sigma_y, sigma_x, sigma_t], got {len(sigma_list)} elements"
            )
        if any(float(s) < 0 for s in sigma_list):
            raise ValueError(f"All sigma values must be non-negative, got {sigma_list}")

        self._obj["u"] = xr.DataArray(
            gaussian_filter(self._obj["u"].values, sigma_list, **kwargs),
            dims=("y", "x", "t"),
            attrs=self._obj["u"].attrs,
        )
        self._obj["v"] = xr.DataArray(
            gaussian_filter(self._obj["v"].values, sigma_list, **kwargs),
            dims=("y", "x", "t"),
            attrs=self._obj["v"].attrs,
        )
        return self._obj

    # --- PIVMAT-style path: sigma is actually filtsize (float)
    if kwargs:
        raise TypeError(
            "PIVMAT-style filterf(filtsize, ...) does not accept **kwargs. "
            "Pass a 3-element sigma list for gaussian_filter kwargs."
        )

    ds = self._obj
    if "x" not in ds.dims or "y" not in ds.dims:
        raise ValueError("filterf requires spatial dims 'y' and 'x'")

    fs = float(sigma)
    if fs == 0.0:
        return ds

    mode = "valid"
    for opt in opts:
        o = str(opt).lower()
        if o.startswith("same"):
            mode = "same"
        elif o.startswith("valid"):
            mode = "valid"
        elif o == "":
            continue
        else:
            raise ValueError(f"Unknown filterf option: {opt!r}")

    k = filter2d_kernel(fs, method)
    ky, kx = (int(k.shape[0]), int(k.shape[1]))
    ny = int(ds.sizes["y"])
    nx = int(ds.sizes["x"])
    if mode == "same":
        ny_out, nx_out = ny, nx
        base = ds
    else:
        ny_out = ny - ky + 1
        nx_out = nx - kx + 1
        if ny_out <= 0 or nx_out <= 0:
            raise ValueError("filter kernel larger than input")

        ly = (ky - 1) // 2
        ry = (ky - 1) - ly
        lx = (kx - 1) // 2
        rx = (kx - 1) - lx
        base = ds.isel(y=slice(ly, ny - ry), x=slice(lx, nx - rx))

    def _core(a2: np.ndarray) -> np.ndarray:
        return filter2d(a2, fs, method, mode=mode)

    out = base.copy(deep=True)
    for name in ("u", "v"):
        if name not in out.data_vars:
            continue
        da_in = ds[name]
        da_out_template = out[name]
        if "y" not in da_in.dims or "x" not in da_in.dims:
            continue
        filtered = xr.apply_ufunc(
            _core,
            da_in,
            input_core_dims=[["y", "x"]],
            output_core_dims=[["y", "x"]],
            exclude_dims={"y", "x"},
            vectorize=True,
            dask="parallelized",
            dask_gufunc_kwargs={"output_sizes": {"y": ny_out, "x": nx_out}},
            output_dtypes=[float],
        )
        # Preserve original dim order (typically ('y','x','t')).
        filtered = filtered.transpose(*da_in.dims)
        # Attach the truncated coordinates from the base dataset.
        filtered = filtered.assign_coords({"y": base["y"], "x": base["x"]})
        out[name] = filtered
        out[name].attrs = dict(ds[name].attrs)

    out.attrs = dict(ds.attrs)
    self._obj = out
    return out

flipf(dir='x')

Flip vector/scalar fields about vertical or horizontal axis (PIVMAT-inspired).

Parameters:

Name Type Description Default
dir str

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
'x'
Notes

The x/y coordinate values are left unchanged (only the data are mirrored), matching PIVMAT behavior.

Source code in pivpy/pivpy.py
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
def flipf(self, dir: str = "x") -> xr.Dataset:
    """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.
    """

    ds = self._obj
    d = str(dir)
    dl = d.lower()
    if dl in ("", "none"):
        return ds

    if dl not in ("x", "y", "xy", "yx"):
        raise ValueError("dir must be one of: 'x', 'y', 'xy', 'yx', ''")

    flip_x = "x" in dl
    flip_y = "y" in dl

    if (flip_x and "x" not in ds.dims) or (flip_y and "y" not in ds.dims):
        raise ValueError("flipf requires spatial dims 'x' and 'y'")

    out = ds.copy(deep=True)
    if flip_x:
        rev_x = np.arange(int(ds.sizes["x"]) - 1, -1, -1)
    if flip_y:
        rev_y = np.arange(int(ds.sizes["y"]) - 1, -1, -1)

    for name, da in ds.data_vars.items():
        flipped = da
        if flip_x and "x" in da.dims:
            flipped = flipped.isel(x=rev_x).assign_coords(x=ds["x"])
        if flip_y and "y" in da.dims:
            flipped = flipped.isel(y=rev_y).assign_coords(y=ds["y"])

        # Velocity sign convention: u is x-component, v is y-component.
        if flip_x and name in ("u", "vx"):
            flipped = -flipped
        if flip_y and name in ("v", "vy"):
            flipped = -flipped

        flipped.attrs = dict(da.attrs)
        out[name] = flipped

    out.attrs = dict(ds.attrs)
    self._obj = out
    return out

fluct()

returns fluctuations as a new dataset

Source code in pivpy/pivpy.py
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
def fluct(self):
    """returns fluctuations as a new dataset"""

    if len(self._obj.t) < 2:
        raise ValueError(
            "fluctuations cannot be defined for a \
                          single vector field, use .piv.ke()"
        )

    new_obj = self._obj.copy()
    new_obj -= new_obj.mean(dim="t")

    new_obj["u"].attrs["standard_name"] = "fluctation"
    new_obj["v"].attrs["standard_name"] = "fluctation"

    return new_obj

gamma1(radius=3, name='gamma1')

Calculates the Gamma1 vortex criterion (normalized angular momentum).

Gamma1 identifies vortex centers where abs(Gamma1) >= 2/pi (~0.6366), reaching +/-1 at ideal vortex centers.

Args: radius (int): Stencil radius in grid points. Defaults to 3. name (str): Variable name for the output field. Defaults to 'gamma1'.

Returns: xarray.Dataset: Dataset with Gamma1 scalar field.

Source code in pivpy/pivpy.py
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
def gamma1(self, radius: int = 3, name: str = "gamma1"):
    """Calculates the Gamma1 vortex criterion (normalized angular momentum).

    Gamma1 identifies vortex centers where abs(Gamma1) >= 2/pi (~0.6366),
    reaching +/-1 at ideal vortex centers.

    Args:
        radius (int): Stencil radius in grid points. Defaults to 3.
        name (str): Variable name for the output field. Defaults to 'gamma1'.

    Returns:
        xarray.Dataset: Dataset with Gamma1 scalar field.
    """
    self._obj = cgamma1(self._obj, radius=radius, name=name)
    return self._obj

gamma2(radius=3, name='gamma2')

Calculates the Galilean-invariant Gamma2 vortex identification criterion.

Gamma2 identifies vortex core boundaries where abs(Gamma2) >= 2/pi (~0.6366), subtracting local convective velocity.

Args: radius (int): Stencil radius in grid points. Defaults to 3. name (str): Variable name for the output field. Defaults to 'gamma2'.

Returns: xarray.Dataset: Dataset with Gamma2 scalar field.

Source code in pivpy/pivpy.py
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
def gamma2(self, radius: int = 3, name: str = "gamma2"):
    """Calculates the Galilean-invariant Gamma2 vortex identification criterion.

    Gamma2 identifies vortex core boundaries where abs(Gamma2) >= 2/pi (~0.6366),
    subtracting local convective velocity.

    Args:
        radius (int): Stencil radius in grid points. Defaults to 3.
        name (str): Variable name for the output field. Defaults to 'gamma2'.

    Returns:
        xarray.Dataset: Dataset with Gamma2 scalar field.
    """
    self._obj = cgamma2(self._obj, radius=radius, name=name)
    return self._obj

gradient_tensor(return_components=False)

Calculates velocity gradient tensor, strain rate tensor, and principal strains.

Args: return_components (bool): If True, returns new dataset with tensor fields. Defaults to False.

Returns: xarray.Dataset: Dataset with computed tensor variables.

Source code in pivpy/pivpy.py
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
def gradient_tensor(self, return_components: bool = False):
    """Calculates velocity gradient tensor, strain rate tensor, and principal strains.

    Args:
        return_components (bool): If True, returns new dataset with tensor fields. Defaults to False.

    Returns:
        xarray.Dataset: Dataset with computed tensor variables.
    """
    return cgradient_tensor(self._obj, return_components=return_components)

gradientf(variable='w')

PIVMAT-style gradient of a scalar variable.

This wraps :func:pivpy.compute_funcs.gradientf and returns a new Dataset containing gradient components as variables u and v.

Parameters:

Name Type Description Default
variable str

Name of the scalar variable in the Dataset (default: 'w').

'w'

Returns:

Type Description
Dataset

Dataset with variables u and v.

Source code in pivpy/pivpy.py
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
def gradientf(self, variable: str = "w") -> xr.Dataset:
    """PIVMAT-style gradient of a scalar variable.

    This wraps :func:`pivpy.compute_funcs.gradientf` and returns a new
    Dataset containing gradient components as variables ``u`` and ``v``.

    Parameters
    ----------
    variable:
        Name of the scalar variable in the Dataset (default: ``'w'``).

    Returns
    -------
    xarray.Dataset
        Dataset with variables ``u`` and ``v``.
    """

    if variable not in self._obj:
        raise KeyError(f"Variable {variable} not in dataset")

    return gradientf(self._obj[variable])

histf(variable=None, bin=None, opt='')

PIVMAT-style histogram of a vector/scalar field.

  • Scalar mode: pass variable='w' (or any scalar var name) to get a Dataset with coordinate bin and variable h.
  • Vector mode: pass variable=None (default) to compute histograms for both components (u/v or vx/vy), returning variables hx and hy.

By default, zero values are treated as invalid and excluded. Pass opt containing '0' to include zeros.

Source code in pivpy/pivpy.py
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
def histf(
    self,
    variable: str | None = None,
    bin=None,
    opt: str = "",
) -> xr.Dataset:
    """PIVMAT-style histogram of a vector/scalar field.

    - Scalar mode: pass ``variable='w'`` (or any scalar var name) to get a
      Dataset with coordinate ``bin`` and variable ``h``.
    - Vector mode: pass ``variable=None`` (default) to compute histograms
      for both components (``u``/``v`` or ``vx``/``vy``), returning variables
      ``hx`` and ``hy``.

    By default, zero values are treated as invalid and excluded. Pass
    ``opt`` containing ``'0'`` to include zeros.
    """

    ds = self._obj
    include_zeros = "0" in str(opt)

    if variable is not None:
        if variable not in ds:
            raise KeyError(f"Variable {variable} not in dataset")
        return histf(ds[variable], bin=bin, opt="0" if include_zeros else "")

    # Vector mode
    if "u" in ds and "v" in ds:
        xname, yname = "u", "v"
    elif "vx" in ds and "vy" in ds:
        xname, yname = "vx", "vy"
    else:
        raise ValueError("histf vector mode requires ('u','v') or ('vx','vy')")

    hx_ds = histf(ds[xname], bin=bin, opt="0" if include_zeros else "")
    centers = hx_ds["bin"].values
    hy_ds = histf(ds[yname], bin=centers, opt="0" if include_zeros else "")

    out = xr.Dataset(
        {
            "hx": ("bin", np.asarray(hx_ds["h"].values, dtype=int)),
            "hy": ("bin", np.asarray(hy_ds["h"].values, dtype=int)),
        },
        coords={"bin": centers},
    )
    out["hx"].attrs["long_name"] = f"histogram({xname})"
    out["hy"].attrs["long_name"] = f"histogram({yname})"
    return out

histscal_disp(*args, **kwargs)

method for graphics.histscal_disp

Source code in pivpy/pivpy.py
2684
2685
2686
def histscal_disp(self, *args, **kwargs):
    """method for graphics.histscal_disp"""
    return ghistscal_disp(self._obj, *args, **kwargs)

histvec_disp(*args, **kwargs)

method for graphics.histvec_disp

Source code in pivpy/pivpy.py
2688
2689
2690
def histvec_disp(self, *args, **kwargs):
    """method for graphics.histvec_disp"""
    return ghistvec_disp(self._obj, *args, **kwargs)

integral_length_scale(component='u', dim='x')

Calculates integral length scale by integrating autocorrelation to zero-crossing.

Source code in pivpy/pivpy.py
2379
2380
2381
2382
2383
2384
2385
def integral_length_scale(
    self,
    component: str = "u",
    dim: str = "x",
) -> float:
    """Calculates integral length scale by integrating autocorrelation to zero-crossing."""
    return cintegral_length_scale(self._obj, component=component, dim=dim)

interpf(method=0, *, variables=None, missing='0nan')

Interpolate missing data (PIVMAT-style interpf).

Missing values are defined as 0 and/or NaN (see missing). The interpolation is applied frame-by-frame along t if present.

Parameters:

Name Type Description Default
method int

Interpolation method selector: 0 Laplacian inpainting (sparse solve), 1 nearest-neighbor fill, 2 linear interpolation with nearest fallback.

0
variables list[str] | None

Variables to process. Default: ['u','v'] if present; otherwise ['w'] if present; otherwise all data variables.

None
missing str

Missing-value definition: '0nan' (default), 'nan', or '0'.

'0nan'

Returns:

Type Description
Dataset

Filled dataset.

Source code in pivpy/pivpy.py
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
def interpf(
    self,
    method: int = 0,
    *,
    variables: list[str] | None = None,
    missing: str = "0nan",
) -> xr.Dataset:
    """Interpolate missing data (PIVMAT-style ``interpf``).

    Missing values are defined as 0 and/or NaN (see ``missing``). The
    interpolation is applied frame-by-frame along ``t`` if present.

    Parameters
    ----------
    method:
        Interpolation method selector:
        ``0`` Laplacian inpainting (sparse solve),
        ``1`` nearest-neighbor fill,
        ``2`` linear 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
    -------
    xarray.Dataset
        Filled dataset.
    """

    return cinterpf(self._obj, method=int(method), variables=variables, missing=missing)

jpdfscal(var1, var2, nbin=101)

Joint PDF (2D histogram) of two scalar variables (PIVMAT-style).

Parameters:

Name Type Description Default
var1 str

Names of scalar variables in the Dataset.

required
var2 str

Names of scalar variables in the Dataset.

required
nbin int

Number of bins per axis (odd integer, default 101).

101
Source code in pivpy/pivpy.py
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
def jpdfscal(self, var1: str, var2: str, nbin: int = 101) -> xr.Dataset:
    """Joint PDF (2D histogram) of two scalar variables (PIVMAT-style).

    Parameters
    ----------
    var1, var2:
        Names of scalar variables in the Dataset.
    nbin:
        Number of bins per axis (odd integer, default 101).
    """

    if var1 not in self._obj:
        raise KeyError(f"Variable {var1} not found in dataset")
    if var2 not in self._obj:
        raise KeyError(f"Variable {var2} not found in dataset")
    return cjpdfscal(self._obj[var1], self._obj[var2], nbin=int(nbin))

jpdfscal_disp(var1, var2, nbin=101, **kwargs)

Compute and display the joint PDF of two scalar variables.

Source code in pivpy/pivpy.py
2678
2679
2680
2681
2682
def jpdfscal_disp(self, var1: str, var2: str, nbin: int = 101, **kwargs):
    """Compute and display the joint PDF of two scalar variables."""

    jpdf = self.jpdfscal(var1, var2, nbin=nbin)
    return gjpdfscal_disp(jpdf, **kwargs)

kinetic_energy(name='w')

Estimates kinetic energy

Args: name (str): Name for the output scalar field. Defaults to "w". Use different names to store multiple scalar fields in one dataset.

Returns: xarray.Dataset: Dataset with kinetic energy field

Example: >>> data.piv.kinetic_energy() # Creates data["w"] with KE >>> data.piv.kinetic_energy(name="ke") # Creates data["ke"]

Source code in pivpy/pivpy.py
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
def kinetic_energy(self, name: str = "w"):
    """Estimates kinetic energy

    Args:
        name (str): Name for the output scalar field. Defaults to "w".
            Use different names to store multiple scalar fields in one dataset.

    Returns:
        xarray.Dataset: Dataset with kinetic energy field

    Example:
        >>> data.piv.kinetic_energy()  # Creates data["w"] with KE
        >>> data.piv.kinetic_energy(name="ke")  # Creates data["ke"]
    """
    warn_if_overwriting_scalar(self._obj, name)
    self._obj[name] = self._obj["u"] ** 2 + self._obj["v"] ** 2
    self._obj[name].attrs["units"] = "(m/s)^2"
    self._obj[name].attrs["standard_name"] = "kinetic_energy"
    return self._obj

max_shear(name='w')

Calculates maximum shear strain rate.

Source code in pivpy/pivpy.py
2344
2345
2346
2347
2348
2349
2350
2351
def max_shear(self, name: str = "w"):
    """Calculates maximum shear strain rate."""
    warn_if_overwriting_scalar(self._obj, name)
    res = cgradient_tensor(self._obj, return_components=True)
    self._obj[name] = res["max_shear"]
    self._obj[name].attrs["units"] = "1/delta_t"
    self._obj[name].attrs["standard_name"] = "max_shear_strain_rate"
    return self._obj

normalized_median_test(radius=1, threshold=2.0, epsilon=0.1, name_mask=None)

Applies Westerweel & Scarano (2005) Normalized Median Test to detect outliers.

Args: radius (int): Stencil radius in grid units. Defaults to 1. threshold (float): Outlier detection threshold. Defaults to 2.0. epsilon (float): Noise floor in velocity units. Defaults to 0.1. name_mask (str, optional): Optional variable name to store outlier boolean mask.

Returns: xarray.Dataset: Dataset with outliers flagged in 'chc' (and optional mask).

Source code in pivpy/pivpy.py
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
def normalized_median_test(
    self,
    radius: int = 1,
    threshold: float = 2.0,
    epsilon: float = 0.1,
    name_mask: str | None = None,
):
    """Applies Westerweel & Scarano (2005) Normalized Median Test to detect outliers.

    Args:
        radius (int): Stencil radius in grid units. Defaults to 1.
        threshold (float): Outlier detection threshold. Defaults to 2.0.
        epsilon (float): Noise floor in velocity units. Defaults to 0.1.
        name_mask (str, optional): Optional variable name to store outlier boolean mask.

    Returns:
        xarray.Dataset: Dataset with outliers flagged in 'chc' (and optional mask).
    """
    return cnormalized_median_test(
        self._obj, radius=radius, threshold=threshold, epsilon=epsilon, name_mask=name_mask
    )

okubo_weiss(name='Q_ow')

Calculates the Okubo-Weiss criterion for vortex identification (Q_ow < 0).

Args: name (str): Variable name for the output field. Defaults to 'Q_ow'.

Returns: xarray.Dataset: Dataset with Okubo-Weiss scalar field.

Source code in pivpy/pivpy.py
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
def okubo_weiss(self, name: str = "Q_ow"):
    """Calculates the Okubo-Weiss criterion for vortex identification (Q_ow < 0).

    Args:
        name (str): Variable name for the output field. Defaults to 'Q_ow'.

    Returns:
        xarray.Dataset: Dataset with Okubo-Weiss scalar field.
    """
    self._obj = cokubo_weiss(self._obj, name=name)
    return self._obj

pan(shift_x=0.0, shift_y=0.0)

Shifts the coordinate system by specified amounts

Args: shift_x (float): Amount to shift in x direction. Defaults to 0.0. shift_y (float): Amount to shift in y direction. Defaults to 0.0.

Returns: xarray.Dataset: Dataset with shifted coordinates

Example: >>> data = data.piv.pan(10.0, -5.0) # Shift x by +10, y by -5

Source code in pivpy/pivpy.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def pan(self, shift_x=0.0, shift_y=0.0):
    """Shifts the coordinate system by specified amounts

    Args:
        shift_x (float): Amount to shift in x direction. Defaults to 0.0.
        shift_y (float): Amount to shift in y direction. Defaults to 0.0.

    Returns:
        xarray.Dataset: Dataset with shifted coordinates

    Example:
        >>> data = data.piv.pan(10.0, -5.0)  # Shift x by +10, y by -5
    """
    self._obj = self._obj.assign_coords(
        {"x": self._obj.x + shift_x, "y": self._obj.y + shift_y}
    )
    return self._obj

phaseaverf(period, *, opt='', method='linear')

Phase-average a vector/scalar dataset over a period.

Inspired by PIVMAT's phaseaverf.

Parameters:

Name Type Description Default
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].

required
opt str

Passed to averf. By default, zeros are excluded; pass '0' to include.

''
method Literal['linear', 'nearest']

Interpolation method used for non-integer periods.

'linear'

Returns:

Type Description
Dataset

Phase-averaged dataset with dim 't' == n_phases.

Source code in pivpy/pivpy.py
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
def phaseaverf(
    self,
    period,
    *,
    opt: str = "",
    method: Literal["linear", "nearest"] = "linear",
):
    """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
    -------
    xarray.Dataset
        Phase-averaged dataset with dim 't' == n_phases.
    """

    ds = self._obj
    if "t" not in ds.dims:
        raise ValueError("phaseaverf requires a time dimension 't'")

    n_frames = int(ds.sizes.get("t", 0) or 0)
    if n_frames <= 0:
        raise ValueError("Empty time dimension")

    # Work in index space (0..n_frames-1) to make non-integer periods well-defined.
    tini = np.arange(n_frames, dtype=float)

    def _avg_for_points(points: np.ndarray) -> xr.Dataset:
        points = np.asarray(points, dtype=float)
        points = points[(points >= 0) & (points <= n_frames - 1)]
        if points.size == 0:
            # Return a 0-field with the same layout (single frame)
            zero = ds.isel(t=[0]).copy(deep=True)
            for v in list(zero.data_vars):
                zero[v].values[...] = 0.0
            return zero.assign_coords(t=np.asarray([0.0], dtype=float))
        sub = ds.piv.resamplef(tini=tini, tfin=points, method=method)
        return sub.piv.averf(opt)

    phases: list[xr.Dataset] = []

    # Determine period type.
    if np.isscalar(period):
        p = float(period)
        if abs(p - float(int(round(p)))) < 1e-10:
            P = int(np.floor(p))
            if P <= 0:
                raise ValueError("period must be positive")
            for i in range(P):
                # Fast path: integer stride selection, no interpolation needed.
                sub = ds.isel(t=slice(i, None, P))
                phases.append(sub.piv.averf(opt))
        else:
            P = int(np.floor(p))
            if P <= 0:
                raise ValueError("period must be >= 1")
            for i in range(P):
                points = np.arange(float(i), float(n_frames), p)
                phases.append(_avg_for_points(points))
    else:
        tvec = np.asarray(period, dtype=float).ravel()
        if tvec.size == 0:
            raise ValueError("period sequence must be non-empty")
        step = float(tvec[-1])
        if step <= 0:
            raise ValueError("period step (last element) must be positive")
        for start in tvec:
            points = np.arange(float(start), float(n_frames), step)
            phases.append(_avg_for_points(points))

    out = xr.concat(phases, dim="t")
    out = out.assign_coords(t=np.arange(out.sizes["t"], dtype=float))
    out.attrs = dict(ds.attrs)
    return out

plot(**kwargs)

High-level, publication-quality plotting method.

Renders a publication-quality flow field visualization with zero effort: - Smooth background contour (vorticity by default, or magnitude, KE, divergence, etc.) - Flow streamlines - Clean, auto-scaled velocity vector quiver arrows - LaTeX math labels, colorbar, equal aspect ratio, and quiver key.

Examples:

>>> ds = synthetic.multivortex()
>>> ds.piv.plot()
>>> ds.piv.plot(background='mag', streamlines=False)
>>> ds.piv.plot(background=None)
Source code in pivpy/pivpy.py
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
def plot(self, **kwargs):
    """High-level, publication-quality plotting method.

    Renders a publication-quality flow field visualization with zero effort:
    - Smooth background contour (vorticity by default, or magnitude, KE, divergence, etc.)
    - Flow streamlines
    - Clean, auto-scaled velocity vector quiver arrows
    - LaTeX math labels, colorbar, equal aspect ratio, and quiver key.

    Examples
    --------
    >>> ds = synthetic.multivortex()
    >>> ds.piv.plot()
    >>> ds.piv.plot(background='mag', streamlines=False)
    >>> ds.piv.plot(background=None)
    """
    return gplot(self._obj, **kwargs)

probeaverf(rect, *, variables=None, skipna=True)

Time series averaged over a rectangular area (PIVMAT-inspired).

Parameters:

Name Type Description Default
rect

Rectangle [x1, y1, x2, y2] in physical units.

required
variables Optional[list[str]]

Variables to average. If None, defaults to ['u','v'] when present, otherwise ['w'].

None
skipna bool

If True (default), NaNs are ignored.

True

Returns:

Type Description
Dataset

Spatially averaged time series.

Source code in pivpy/pivpy.py
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
def probeaverf(
    self,
    rect,
    *,
    variables: Optional[list[str]] = None,
    skipna: bool = True,
) -> xr.Dataset:
    """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
    -------
    xarray.Dataset
        Spatially averaged time series.
    """

    return cprobeaverf(self._obj, rect, variables=variables, skipna=skipna)

probef(x0, y0, *, variables=None, method='linear')

Record the time evolution of probe point(s) (PIVMAT-inspired).

This samples variable(s) at point(s) (x0, y0) using spatial interpolation.

Parameters:

Name Type Description Default
x0

Probe location(s) in physical units. Scalars or 1D arrays.

required
y0

Probe location(s) in physical units. Scalars or 1D arrays.

required
variables Optional[list[str]]

Variables to sample. If None, defaults to ['u','v'] when present, otherwise ['w'].

None
method str

Interpolation method ('linear' or 'nearest' are typical).

'linear'

Returns:

Type Description
Dataset

Sampled time series. For multiple probe points, includes a probe dim and coordinates x_probe/y_probe.

Source code in pivpy/pivpy.py
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
def probef(
    self,
    x0,
    y0,
    *,
    variables: Optional[list[str]] = None,
    method: str = "linear",
) -> xr.Dataset:
    """Record the time evolution of probe point(s) (PIVMAT-inspired).

    This samples variable(s) at point(s) ``(x0, y0)`` using spatial
    interpolation.

    Parameters
    ----------
    x0, 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
    -------
    xarray.Dataset
        Sampled time series. For multiple probe points, includes a ``probe`` dim
        and coordinates ``x_probe``/``y_probe``.
    """

    return cprobef(self._obj, x0, y0, variables=variables, method=method)

q_criterion(name='Q')

Calculates Hunt's Q-criterion for vortex core identification (Q > 0).

Args: name (str): Variable name for the output field. Defaults to 'Q'.

Returns: xarray.Dataset: Dataset with Q-criterion scalar field.

Source code in pivpy/pivpy.py
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
def q_criterion(self, name: str = "Q"):
    """Calculates Hunt's Q-criterion for vortex core identification (Q > 0).

    Args:
        name (str): Variable name for the output field. Defaults to 'Q'.

    Returns:
        xarray.Dataset: Dataset with Q-criterion scalar field.
    """
    self._obj = cq_criterion(self._obj, name=name)
    return self._obj

quiver(**kwargs)

graphics.quiver() as a flow_property

Source code in pivpy/pivpy.py
2626
2627
2628
2629
def quiver(self, **kwargs):
    """graphics.quiver() as a flow_property"""
    fig, ax = gquiver(self._obj, **kwargs)
    return fig, ax

resamplef(tini, tfin, *, method='linear')

(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]]

Args: tini: 1D sequence of initial times (length == number of frames). tfin: 1D sequence of target times. method: Interpolation method.

Returns: xarray.Dataset: resampled dataset with dim 't' == len(tfin) and coords 't' == tfin.

Source code in pivpy/pivpy.py
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
def resamplef(
    self,
    tini,
    tfin,
    *,
    method: Literal["linear", "nearest"] = "linear",
):
    """(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]]

    Args:
        tini: 1D sequence of initial times (length == number of frames).
        tfin: 1D sequence of target times.
        method: Interpolation method.

    Returns:
        xarray.Dataset: resampled dataset with dim 't' == len(tfin) and coords 't' == tfin.
    """

    ds = self._obj
    if "t" not in ds.dims:
        raise ValueError("resamplef requires a time dimension 't'")

    tini_arr = np.asarray(tini, dtype=float).ravel()
    tfin_arr = np.asarray(tfin, dtype=float).ravel()

    n_frames = int(ds.sizes.get("t", 0) or 0)
    if tini_arr.size != n_frames:
        raise ValueError("Size of tini must coincide with the dataset time dimension")

    if tini_arr.size < 2:
        raise ValueError("tini must contain at least 2 points")

    if np.any(np.diff(tini_arr) <= 0):
        raise ValueError("tini must be strictly increasing")

    if tfin_arr.size == 0:
        raise ValueError("tfin must be non-empty")

    if float(np.min(tfin_arr)) < float(tini_arr[0]) or float(np.max(tfin_arr)) > float(tini_arr[-1]):
        raise ValueError("Some values of tfin fall outside the bounds of tini")

    # Interpolate in a dedicated coordinate to avoid assumptions about existing ds.t.
    ds_time = ds.assign_coords(_resample_time=("t", tini_arr)).swap_dims({"t": "_resample_time"})
    out = ds_time.interp(_resample_time=tfin_arr, method=method)
    out = out.swap_dims({"_resample_time": "t"}).assign_coords(t=tfin_arr)
    out = out.drop_vars("_resample_time")
    out.attrs = dict(ds.attrs)
    return out

reynolds_decomposition(name_mean='mean', name_prime='prime')

Performs Reynolds decomposition on time series velocity dataset.

Source code in pivpy/pivpy.py
2353
2354
2355
2356
2357
2358
2359
def reynolds_decomposition(
    self,
    name_mean: str = "mean",
    name_prime: str = "prime",
):
    """Performs Reynolds decomposition on time series velocity dataset."""
    return creynolds_decomposition(self._obj, name_mean=name_mean, name_prime=name_prime)

reynolds_stress(name='w')

Calculates Reynolds stress from velocity fluctuations

Args: name (str): Name for the output scalar field. Defaults to "w". Use different names to store multiple scalar fields in one dataset.

Returns: xarray.Dataset: Dataset with Reynolds stress field (-)

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"]

Source code in pivpy/pivpy.py
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
def reynolds_stress(self, name: str = "w"):
    """Calculates Reynolds stress from velocity fluctuations

    Args:
        name (str): Name for the output scalar field. Defaults to "w".
            Use different names to store multiple scalar fields in one dataset.

    Returns:
        xarray.Dataset: Dataset with Reynolds stress field (-<u'v'>)

    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"]
    """

    if len(self._obj.t) < 2:
        raise ValueError(
            "fluctuations cannot be defined for a \
                          single vector field, use .piv.ke()"
        )

    warn_if_overwriting_scalar(self._obj, name)
    new_obj = self._obj.copy()
    new_obj -= new_obj.mean(dim="t")

    new_obj[name] = -1 * new_obj["u"] * new_obj["v"]  # new scalar
    self._obj[name] = new_obj[name].mean(dim="t")  # reynolds stress is -\rho < u' v'>
    self._obj[name].attrs["standard_name"] = "Reynolds_stress"

    return self._obj

rms(name='w')

Root mean square of velocity fluctuations

Args: name (str): Name for the output scalar field. Defaults to "w". Use different names to store multiple scalar fields in one dataset.

Returns: xarray.Dataset: Dataset with RMS field (sqrt of TKE)

Example: >>> data.piv.rms() # Creates data["w"] with RMS >>> data.piv.rms(name="rms") # Creates data["rms"]

Source code in pivpy/pivpy.py
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
def rms(self, name: str = "w"):
    """Root mean square of velocity fluctuations

    Args:
        name (str): Name for the output scalar field. Defaults to "w".
            Use different names to store multiple scalar fields in one dataset.

    Returns:
        xarray.Dataset: Dataset with RMS field (sqrt of TKE)

    Example:
        >>> data.piv.rms()  # Creates data["w"] with RMS
        >>> data.piv.rms(name="rms")  # Creates data["rms"]
    """
    self._obj = self.tke(name=name)
    self._obj[name] = np.sqrt(self._obj[name])
    self._obj[name].attrs["standard_name"] = "rms"
    self._obj[name].attrs["units"] = "m/s"
    return self._obj

rotate(theta=0.0)

Rotates the coordinate system and velocity field

Args: theta (float): Rotation angle in degrees (clockwise). Defaults to 0.0.

Returns: xarray.Dataset: Rotated dataset

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

Source code in pivpy/pivpy.py
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
def rotate(self, theta: float = 0.0):
    """Rotates the coordinate system and velocity field

    Args:
        theta (float): Rotation angle in degrees (clockwise). Defaults to 0.0.

    Returns:
        xarray.Dataset: Rotated dataset

    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
    """

    theta = theta / 360.0 * 2 * np.pi

    x_i = self._obj.x * np.cos(theta) + self._obj.y * np.sin(theta)
    eta = self._obj.y * np.cos(theta) - self._obj.x * np.sin(theta)
    du_dx_i = self._obj.u * np.cos(theta) + self._obj.v * np.sin(theta)
    u_eta = self._obj.v * np.cos(theta) - self._obj.u * np.sin(theta)

    self._obj["x"] = x_i
    self._obj["y"] = eta
    self._obj["u"] = du_dx_i
    self._obj["v"] = u_eta

    if "theta" in self._obj:
        self._obj["theta"] += theta
    else:
        self._obj["theta"] = theta

    return self._obj

set_delta_t(delta_t=0.0)

Sets the time interval attribute for PIV measurements

Args: delta_t (float): Time interval between frame A and B. Defaults to 0.0.

Returns: xarray.Dataset: Dataset with updated delta_t attribute

Raises: ValueError: If delta_t is negative

Example: >>> data = data.piv.set_delta_t(0.001) # Set dt to 1 millisecond

Source code in pivpy/pivpy.py
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
def set_delta_t(self, delta_t: float = 0.0):
    """Sets the time interval attribute for PIV measurements

    Args:
        delta_t (float): Time interval between frame A and B. Defaults to 0.0.

    Returns:
        xarray.Dataset: Dataset with updated delta_t attribute

    Raises:
        ValueError: If delta_t is negative

    Example:
        >>> data = data.piv.set_delta_t(0.001)  # Set dt to 1 millisecond
    """
    if delta_t < 0:
        raise ValueError(f"delta_t must be non-negative, got {delta_t}")

    self._obj.attrs["delta_t"] = delta_t
    return self._obj

set_scale(scale=1.0)

Scales all spatial coordinates and velocities by a factor

Args: scale (float): Scaling factor. Defaults to 1.0.

Returns: xarray.Dataset: Dataset with scaled coordinates and velocities

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

Source code in pivpy/pivpy.py
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
def set_scale(self, scale: float = 1.0):
    """Scales all spatial coordinates and velocities by a factor

    Args:
        scale (float): Scaling factor. Defaults to 1.0.

    Returns:
        xarray.Dataset: Dataset with scaled coordinates and velocities

    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
    """
    if scale <= 0:
        raise ValueError(f"scale must be positive, got {scale}")

    for var in ["x", "y", "u", "v"]:
        self._obj[var] = self._obj[var] * scale

    return self._obj

showf(**kwargs)

method for graphics.showf

Source code in pivpy/pivpy.py
2636
2637
2638
2639
def showf(self, **kwargs):
    """method for graphics.showf"""
    fig, ax = gshowf(self._obj, **kwargs)
    return fig, ax

showscal(**kwargs)

method for graphics.showscal

Source code in pivpy/pivpy.py
2641
2642
2643
def showscal(self, **kwargs):
    """method for graphics.showscal"""
    gshowscal(self._obj, **kwargs)

smooth(sigma=1.0, method='gaussian', **kwargs)

Applies spatial smoothing to velocity vector fields.

Args: sigma (float or sequence): Smoothing scale / window size / cutoff size. method (str): Filtering method ('gaussian', 'median', 'boxcar', 'butterworth'). Defaults to 'gaussian'. **kwargs: Additional parameters passed to filtering backend (e.g. order=2 for Butterworth).

Returns: xarray.Dataset: Smoothed dataset.

Source code in pivpy/pivpy.py
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
def smooth(
    self,
    sigma: float | Sequence[float] = 1.0,
    method: str = "gaussian",
    **kwargs,
):
    """Applies spatial smoothing to velocity vector fields.

    Args:
        sigma (float or sequence): Smoothing scale / window size / cutoff size.
        method (str): Filtering method ('gaussian', 'median', 'boxcar', 'butterworth'). Defaults to 'gaussian'.
        **kwargs: Additional parameters passed to filtering backend (e.g. order=2 for Butterworth).

    Returns:
        xarray.Dataset: Smoothed dataset.
    """
    return csmooth(self._obj, sigma=sigma, method=method, **kwargs)

spatial_correlation(component='u', dim='x', normalize=True)

Calculates spatial two-point autocorrelation function R_ij(r).

Source code in pivpy/pivpy.py
2370
2371
2372
2373
2374
2375
2376
2377
def spatial_correlation(
    self,
    component: str = "u",
    dim: str = "x",
    normalize: bool = True,
):
    """Calculates spatial two-point autocorrelation function R_ij(r)."""
    return cspatial_correlation(self._obj, component=component, dim=dim, normalize=normalize)

spatiotempf(X, Y, *, var='w', n=None, method='linear')

Spatio-temporal diagram along line segment(s) (PIVMAT-inspired).

Parameters:

Name Type Description Default
X

Endpoints in physical units. Single line: X=[x0,x1], Y=[y0,y1]. Multiple lines: X=[[x0,x1],[...]], same for Y.

required
Y

Endpoints in physical units. Single line: X=[x0,x1], Y=[y0,y1]. Multiple lines: X=[[x0,x1],[...]], same for Y.

required
var str

Scalar variable name to sample.

'w'
n Optional[int]

Number of sample points along each line (None -> heuristic).

None
method str

Interpolation method ('linear' or 'nearest' are typical).

'linear'

Returns:

Type Description
Dataset

Dataset containing variable st.

Source code in pivpy/pivpy.py
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
def spatiotempf(
    self,
    X,
    Y,
    *,
    var: str = "w",
    n: Optional[int] = None,
    method: str = "linear",
) -> xr.Dataset:
    """Spatio-temporal diagram along line segment(s) (PIVMAT-inspired).

    Parameters
    ----------
    X, Y:
        Endpoints in physical units. Single line: ``X=[x0,x1]``, ``Y=[y0,y1]``.
        Multiple lines: ``X=[[x0,x1],[...]]``, same for ``Y``.
    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
    -------
    xarray.Dataset
        Dataset containing variable ``st``.
    """

    return cspatiotempf(self._obj, X, Y, var=var, n=n, method=method)

spaverf(opt='xy', *, var=None)

Spatial average over X and/or Y of a vector/scalar field.

This method is inspired by PIVMat's spaverf.

Args: 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: xarray.Dataset: Dataset with spatially-averaged variable(s), broadcast back to the original shape.

Source code in pivpy/pivpy.py
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
def spaverf(
    self,
    opt: str = "xy",
    *,
    var: Optional[str] = None,
):
    """Spatial average over X and/or Y of a vector/scalar field.

    This method is inspired by PIVMat's `spaverf`.

    Args:
        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:
        xarray.Dataset: Dataset with spatially-averaged variable(s), broadcast back
        to the original shape.
    """

    ds = self._obj
    opt_l = str(opt).lower() if opt is not None else "xy"
    include_zeros = "0" in opt_l
    axis = opt_l.replace("0", "") or "xy"

    if axis not in {"x", "y", "xy"}:
        raise ValueError("Invalid axis; expected 'x', 'y', or 'xy' (optionally with '0')")

    def _mean_broadcast(da: xr.DataArray, reduce_dims: list[str]) -> xr.DataArray:
        if include_zeros:
            mean = da.mean(dim=reduce_dims, skipna=True)
        else:
            mean = da.where(da != 0).mean(dim=reduce_dims, skipna=True)
            mean = mean.fillna(0.0)
        # Broadcast back to original y/x/t shape.
        return mean.broadcast_like(da)

    if var is None:
        if "u" not in ds or "v" not in ds:
            raise ValueError("Vector mode spaverf requires 'u' and 'v'")
        vars_to_process = ["u", "v"]
    else:
        if var not in ds:
            raise ValueError(f"Scalar variable '{var}' not found in dataset")
        vars_to_process = [var]

    reduce_dims: list[str]
    if axis == "x":
        reduce_dims = ["x"]
    elif axis == "y":
        reduce_dims = ["y"]
    else:
        reduce_dims = ["y", "x"]

    out = ds.copy(deep=True)
    for name in vars_to_process:
        da = out[name]
        # Ensure y/x exist; allow missing t (single frame).
        if "y" not in da.dims or "x" not in da.dims:
            raise ValueError(f"Variable '{name}' must have spatial dims 'y' and 'x'")
        out[name] = _mean_broadcast(da, reduce_dims)
        out[name].attrs = dict(ds[name].attrs)

    out.attrs = dict(ds.attrs)
    return out

strain(name='w')

Calculates rate of strain of a two component field

Args: name (str): Name for the output scalar field. Defaults to "w". Use different names to store multiple scalar fields in one dataset.

Returns: xarray.Dataset: Dataset with added scalar field = du_dx^2 + dv_dy^2 + 0.5*(du_dy+dv_dx)^2

Example: >>> data.piv.strain() # Creates data["w"] with strain >>> data.piv.strain(name="strain_rate") # Creates data["strain_rate"]

Source code in pivpy/pivpy.py
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
def strain(self, name: str = "w"):
    """Calculates rate of strain of a two component field

    Args:
        name (str): Name for the output scalar field. Defaults to "w".
            Use different names to store multiple scalar fields in one dataset.

    Returns:
        xarray.Dataset: Dataset with added scalar field = du_dx^2 + dv_dy^2 + 0.5*(du_dy+dv_dx)^2

    Example:
        >>> data.piv.strain()  # Creates data["w"] with strain
        >>> data.piv.strain(name="strain_rate")  # Creates data["strain_rate"]
    """
    warn_if_overwriting_scalar(self._obj, name)
    du_dx = self._obj["u"].differentiate("x")
    du_dy = self._obj["u"].differentiate("y")
    dv_dx = self._obj["v"].differentiate("x")
    dv_dy = self._obj["v"].differentiate("y")

    self._obj[name] = du_dx**2 + dv_dy**2 + 0.5 * (du_dy + dv_dx) ** 2
    self._obj[name].attrs["units"] = "1/delta_t"
    self._obj[name].attrs["standard_name"] = "strain"

    return self._obj

stream_statistics(name_mean='mean', name_prime='prime')

Computes online streaming temporal mean, Reynolds stresses, and TKE with O(1) memory.

Source code in pivpy/pivpy.py
2851
2852
2853
2854
def stream_statistics(self, name_mean: str = "mean", name_prime: str = "prime"):
    """Computes online streaming temporal mean, Reynolds stresses, and TKE with O(1) memory."""
    from pivpy.io import stream_statistics
    return stream_statistics(self._obj, name_mean=name_mean, name_prime=name_prime)

streamplot(**kwargs)

graphics.streamplot() as a flow_property

Source code in pivpy/pivpy.py
2631
2632
2633
2634
def streamplot(self, **kwargs):
    """graphics.streamplot() as a flow_property"""
    fig, ax = gstreamplot(self._obj, **kwargs)
    return fig, ax

subaverf(opt='e', *, var=None)

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.

Args: opt: Option string. Default 'e'. var: Scalar variable name (e.g. 'w'). If None, operates on 'u' and 'v'.

Returns: xarray.Dataset: Dataset with mean-subtracted variable(s).

Source code in pivpy/pivpy.py
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
def subaverf(
    self,
    opt: str = "e",
    *,
    var: Optional[str] = None,
):
    """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.

    Args:
        opt: Option string. Default 'e'.
        var: Scalar variable name (e.g. 'w'). If None, operates on 'u' and 'v'.

    Returns:
        xarray.Dataset: Dataset with mean-subtracted variable(s).
    """

    ds = self._obj
    opt_l = str(opt).lower() if opt is not None else "e"
    ensemble = "e" in opt_l

    if var is None:
        if "u" not in ds or "v" not in ds:
            raise ValueError("Vector mode subaverf requires 'u' and 'v'")
        vars_to_process = ["u", "v"]
    else:
        if var not in ds:
            raise ValueError(f"Scalar variable '{var}' not found in dataset")
        vars_to_process = [var]

    out = ds.copy(deep=True)

    if ensemble:
        # Allow '0' to be passed through to averf if user included it.
        opt_for_averf = opt_l.replace("e", "")
        mean_ds = ds.piv.averf(opt_for_averf)

        for name in vars_to_process:
            da = ds[name]
            mean_da = mean_ds[name]

            # Broadcast mean to all time steps.
            if "t" in da.dims and "t" in mean_da.dims and mean_da.sizes.get("t", 1) == 1:
                mean_b = mean_da.isel(t=0).broadcast_like(da)
            else:
                mean_b = mean_da.broadcast_like(da)

            new = da - mean_b

            # Preserve invalid zeros (PIVMat multiplies by logical(original)).
            if "t" in da.dims:
                new = new.where(da != 0, 0.0)
            else:
                new = new.where(da != 0, 0.0)

            out[name] = new
            out[name].attrs = dict(ds[name].attrs)

        out.attrs = dict(ds.attrs)
        return out

    # Spatial subtraction mode.
    spatial_mean = ds.piv.spaverf(opt_l, var=var)
    for name in vars_to_process:
        da = ds[name]
        mean_da = spatial_mean[name]
        new = da - mean_da
        new = new.where(da != 0, 0.0)
        out[name] = new
        out[name].attrs = dict(ds[name].attrs)

    out.attrs = dict(ds.attrs)
    return out

subsbr(r0=None)

Subtracts solid body rotation from the velocity field.

Args: r0 (ArrayLike, optional): Center coordinates [x0, y0]. Defaults to field center.

Returns: xarray.Dataset: Dataset with subtracted solid body rotation.

Source code in pivpy/pivpy.py
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
def subsbr(self, r0=None):
    """Subtracts solid body rotation from the velocity field.

    Args:
        r0 (ArrayLike, optional): Center coordinates [x0, y0]. Defaults to field center.

    Returns:
        xarray.Dataset: Dataset with subtracted solid body rotation.
    """
    self._obj = csubsbr(self._obj, r0=r0)
    return self._obj

taylor_microscale(component='u', dim='x', method='curvature')

Estimates the Taylor microscale lambda_T from velocity fluctuations.

Source code in pivpy/pivpy.py
2387
2388
2389
2390
2391
2392
2393
2394
def taylor_microscale(
    self,
    component: str = "u",
    dim: str = "x",
    method: str = "curvature",
) -> float:
    """Estimates the Taylor microscale lambda_T from velocity fluctuations."""
    return ctaylor_microscale(self._obj, component=component, dim=dim, method=method)

tempcorrf(*, variables=None, opt='', normalize=False)

Temporal correlation function (PIVMAT-inspired).

Parameters:

Name Type Description Default
variables Optional[list[str]]

Variables to include. Default is ['u','v'] if present, otherwise ['w'].

None
opt str

Include zeros if opt contains '0' (default excludes zeros).

''
normalize bool

If True, normalizes so that f(t=0)=1.

False
Source code in pivpy/pivpy.py
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
def tempcorrf(
    self,
    *,
    variables: Optional[list[str]] = None,
    opt: str = "",
    normalize: bool = False,
) -> xr.Dataset:
    """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``.
    """

    return ctempcorrf(self._obj, variables=variables, opt=opt, normalize=normalize)

tke(name='w')

Estimates turbulent kinetic energy

Args: name (str): Name for the output scalar field. Defaults to "w". Use different names to store multiple scalar fields in one dataset.

Returns: xarray.Dataset: New dataset with TKE field (based on fluctuations from mean)

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"]

Source code in pivpy/pivpy.py
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
def tke(self, name: str = "w"):
    """Estimates turbulent kinetic energy

    Args:
        name (str): Name for the output scalar field. Defaults to "w".
            Use different names to store multiple scalar fields in one dataset.

    Returns:
        xarray.Dataset: New dataset with TKE field (based on fluctuations from mean)

    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"]
    """
    if len(self._obj.t) < 2:
        raise ValueError(
            "TKE is not defined for a single vector field, \
                          use .piv.kinetic_energy()"
        )

    warn_if_overwriting_scalar(self._obj, name)
    new_obj = self._obj.copy()
    new_obj -= new_obj.mean(dim="t")
    new_obj[name] = new_obj["u"] ** 2 + new_obj["v"] ** 2
    new_obj[name].attrs["units"] = "(m/s)^2"
    new_obj[name].attrs["standard_name"] = "TKE"

    return new_obj

to_movie(output, **kwargs)

Save the Dataset as a movie (fast artist-updating renderer).

This is a convenience wrapper around :func:pivpy.graphics.to_movie.

Parameters:

Name Type Description Default
output

Output path (e.g. 'movie.mp4' / 'movie.gif'). If None and return_frames=True is passed, returns a list of RGBA frames.

required
**kwargs

Passed through to :func:pivpy.graphics.to_movie.

{}
Source code in pivpy/pivpy.py
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
def to_movie(self, output, **kwargs):
    """Save the Dataset as a movie (fast artist-updating renderer).

    This is a convenience wrapper around :func:`pivpy.graphics.to_movie`.

    Parameters
    ----------
    output:
        Output path (e.g. ``'movie.mp4'`` / ``'movie.gif'``). If ``None`` and
        ``return_frames=True`` is passed, returns a list of RGBA frames.
    **kwargs:
        Passed through to :func:`pivpy.graphics.to_movie`.
    """

    return gto_movie(self._obj, output, **kwargs)

vec2scal(flow_property='curl', name='w')

Creates a scalar flow property field from velocity data

Args: flow_property (str): Name of the flow property to compute. Valid options: 'curl'/'vorticity'/'vort', 'ke'/'ken'/'kinetic_energy', 'strain', 'divergence', 'acceleration'/'accel', 'tke', 'reynolds_stress', 'rms', 'gamma1', 'gamma2', 'q_criterion'/'q', 'okubo_weiss'/'q_ow', 'max_shear', 'dissipation'/'dissip'. 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: xarray.Dataset: Dataset with computed scalar field

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('gamma1', name='g1') # Compute Gamma1 in data["g1"] >>> data = data.piv.vec2scal('gamma2', name='g2') # Compute Gamma2 in data["g2"] >>> data = data.piv.vec2scal('q_criterion', name='Q') # Compute Q in data["Q"]

Source code in pivpy/pivpy.py
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
def vec2scal(self, flow_property: str = "curl", name: str = "w"):
    """Creates a scalar flow property field from velocity data

    Args:
        flow_property (str): Name of the flow property to compute.
            Valid options: 'curl'/'vorticity'/'vort', 'ke'/'ken'/'kinetic_energy',
            'strain', 'divergence', 'acceleration'/'accel', 'tke', 'reynolds_stress', 'rms',
            'gamma1', 'gamma2', 'q_criterion'/'q', 'okubo_weiss'/'q_ow', 'max_shear',
            'dissipation'/'dissip'.
            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:
        xarray.Dataset: Dataset with computed scalar field

    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('gamma1', name='g1')  # Compute Gamma1 in data["g1"]
        >>> data = data.piv.vec2scal('gamma2', name='g2')  # Compute Gamma2 in data["g2"]
        >>> data = data.piv.vec2scal('q_criterion', name='Q')  # Compute Q in data["Q"]
    """
    # Replace common aliases with canonical names
    alias_map = {
        "curl": "vorticity",
        "vort": "vorticity",
        "ke": "kinetic_energy",
        "ken": "kinetic_energy",
        "q": "q_criterion",
        "q_ow": "okubo_weiss",
        "ow": "okubo_weiss",
        "accel": "acceleration",
        "principal_strain": "strain",
        "shear_strain": "strain",
        "dissip": "dissipation",
    }
    flow_property = alias_map.get(str(flow_property).lower(), flow_property)

    # Check if method exists
    if not hasattr(self, flow_property):
        valid_properties = [
            'vorticity', 'kinetic_energy', 'strain', 'divergence', 
            'acceleration', 'tke', 'reynolds_stress', 'rms',
            'gamma1', 'gamma2', 'q_criterion', 'okubo_weiss', 'max_shear',
            'dissipation'
        ]
        raise AttributeError(
            f"Unknown flow property '{flow_property}'. "
            f"Valid options are: {', '.join(valid_properties)}"
        )

    warnings.warn(
        "piv.vec2scal() currently rebinds this accessor's internal dataset "
        "reference as a side effect; a future release will make it a pure "
        "function that only returns the computed dataset. Always use the "
        "return value (`ds = ds.piv.vec2scal(...)`) rather than relying on "
        "in-place state.",
        DeprecationWarning,
        stacklevel=2,
    )
    method = getattr(self, flow_property)
    self._obj = method(name=name)

    return self._obj

vorticity(method='differentiation', radius=1, name='w')

Calculates vorticity of the data array and adds it to the dataset.

Args: method (str): Vorticity calculation method. Options: 'differentiation' (default): Standard finite difference (dv_dx - du_dy). 'circulation': Closed contour line-integral circulation method, providing superior noise immunity. radius (int): Contour radius in grid points (used when method='circulation'). Defaults to 1. name (str): Name for the output scalar field. Defaults to "w".

Input: xarray with the variables u,v and dimensions x,y (and optional t)

Output: xarray with the estimated vorticity as a scalar field with same dimensions

Example: >>> data.piv.vorticity() # Creates data["w"] with finite-difference vorticity >>> data.piv.vorticity(method="circulation", radius=2) # Noise-robust circulation vorticity >>> data.piv.vorticity(name="vort") # Creates data["vort"] with vorticity

Source code in pivpy/pivpy.py
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
def vorticity(self, method: str = "differentiation", radius: int = 1, name: str = "w"):
    """Calculates vorticity of the data array and adds it to the dataset.

    Args:
        method (str): Vorticity calculation method. Options:
            'differentiation' (default): Standard finite difference (dv_dx - du_dy).
            'circulation': Closed contour line-integral circulation method,
            providing superior noise immunity.
        radius (int): Contour radius in grid points (used when method='circulation'). Defaults to 1.
        name (str): Name for the output scalar field. Defaults to "w".

    Input:
        xarray with the variables u,v and dimensions x,y (and optional t)

    Output:
        xarray with the estimated vorticity as a scalar field with same dimensions

    Example:
        >>> data.piv.vorticity()  # Creates data["w"] with finite-difference vorticity
        >>> data.piv.vorticity(method="circulation", radius=2)  # Noise-robust circulation vorticity
        >>> data.piv.vorticity(name="vort")  # Creates data["vort"] with vorticity
    """
    warn_if_overwriting_scalar(self._obj, name)

    if str(method).lower() in ["circulation", "circ"]:
        self._obj = cvorticity_circulation(self._obj, radius=radius, name=name)
    else:
        self._obj[name] = self._obj["v"].differentiate("x") - self._obj[
            "u"
        ].differentiate("y")
        self._obj[name].attrs["units"] = "1/delta_t"
        self._obj[name].attrs["standard_name"] = "vorticity"

    return self._obj

Γ1(n=3, convCoords=True)

Legacy method for Γ1 vortex criterion calculation.

Source code in pivpy/pivpy.py
2194
2195
2196
2197
def Γ1(self, n: int = 3, convCoords: bool = True):
    """Legacy method for Γ1 vortex criterion calculation."""
    self._obj = cgamma1(self._obj, radius=n, name="Γ1")
    return self._obj

Γ2(n=3, convCoords=True)

Legacy method for Γ2 vortex criterion calculation.

Source code in pivpy/pivpy.py
2199
2200
2201
2202
def Γ2(self, n: int = 3, convCoords: bool = True):
    """Legacy method for Γ2 vortex criterion calculation."""
    self._obj = cgamma2(self._obj, radius=n, name="Γ2")
    return self._obj

pivpy.interfacing

"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 .

pivpyTOvf(field, ncFilePath)

Convert a PIVPy xarray Dataset into a VortexFitting VelocityField.

Notes

VortexFitting's VelocityField expects to read from a NetCDF file, so this function writes a temporary NetCDF file at ncFilePath and then loads it.

Parameters:

Name Type Description Default
field

PIVPy xarray Dataset containing at least u and v variables and a single time frame.

required
ncFilePath

Path to the NetCDF file to write (it does not need to exist yet).

required

Returns:

Type Description
VelocityField

The VortexFitting velocity field loaded from the written NetCDF file.

Source code in pivpy/interfacing.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def pivpyTOvf(field, ncFilePath):
    """Convert a PIVPy xarray Dataset into a VortexFitting ``VelocityField``.

    Notes
    -----
    VortexFitting's ``VelocityField`` expects to read from a NetCDF file, so this
    function writes a temporary NetCDF file at ``ncFilePath`` and then loads it.

    Parameters
    ----------
    field:
        PIVPy xarray Dataset containing at least ``u`` and ``v`` variables and a
        single time frame.
    ncFilePath:
        Path to the NetCDF file to write (it does not need to exist yet).

    Returns
    -------
    vortexfitting.VelocityField
        The VortexFitting velocity field loaded from the written NetCDF file.
    """
    if vf is None:
        raise ImportError(
            "pivpyTOvf requires the optional 'vortexfitting' package: "
            "pip install pivpy[vortexfitting]"
        )

    # VortexFitting expects the physical system of corrdinates, but field - being obtained
    # from an OpenPIV .txt file is in the image system of coordinates. So, we have to invert
    # they y axis. The procedure that after a lot of trials and errors ended up working is
    # copied from here https://stackoverflow.com/a/70695479/10073233 and is given by:
    field = field.reindex(y = field.y[::-1]) 

    # VortexFitting expects time coordinate to go first. In practice it reads spatial
    # matrices with x as the first spatial axis for piv_netcdf, so we store as (t, x, y)
    # to match the expectations in tests/test_inter.py.
    fieldReordered = field.transpose('t','x','y') 
    fieldReordered = fieldReordered.fillna(0.0)

    # VortexFitting expects very specific names of the data arrays. And there must be
    # the third component of velocity vector.
    fieldReordered['velocity_z'] = fieldReordered['u'].copy(
        data=np.zeros(fieldReordered['u'].values.shape))
    fieldRenamed = fieldReordered.rename_vars(
        {'u':'velocity_n', 'v':'velocity_s', 'y':'grid_z', 'x':'grid_n', })

    fieldRenamed.to_netcdf(path=ncFilePath, mode='w')

    vfield = vf.VelocityField(str(ncFilePath), file_type = 'piv_netcdf', time_step=0)

    return vfield

pivpy.inter (deprecated)

Backward-compatible alias for the pivpy.interfacing module.

The original interop helpers lived in pivpy.inter. The canonical location is now pivpy.interfacing.

pivpyTOvf(field, ncFilePath)

Convert a PIVPy xarray Dataset into a VortexFitting VelocityField.

Notes

VortexFitting's VelocityField expects to read from a NetCDF file, so this function writes a temporary NetCDF file at ncFilePath and then loads it.

Parameters:

Name Type Description Default
field

PIVPy xarray Dataset containing at least u and v variables and a single time frame.

required
ncFilePath

Path to the NetCDF file to write (it does not need to exist yet).

required

Returns:

Type Description
VelocityField

The VortexFitting velocity field loaded from the written NetCDF file.

Source code in pivpy/interfacing.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def pivpyTOvf(field, ncFilePath):
    """Convert a PIVPy xarray Dataset into a VortexFitting ``VelocityField``.

    Notes
    -----
    VortexFitting's ``VelocityField`` expects to read from a NetCDF file, so this
    function writes a temporary NetCDF file at ``ncFilePath`` and then loads it.

    Parameters
    ----------
    field:
        PIVPy xarray Dataset containing at least ``u`` and ``v`` variables and a
        single time frame.
    ncFilePath:
        Path to the NetCDF file to write (it does not need to exist yet).

    Returns
    -------
    vortexfitting.VelocityField
        The VortexFitting velocity field loaded from the written NetCDF file.
    """
    if vf is None:
        raise ImportError(
            "pivpyTOvf requires the optional 'vortexfitting' package: "
            "pip install pivpy[vortexfitting]"
        )

    # VortexFitting expects the physical system of corrdinates, but field - being obtained
    # from an OpenPIV .txt file is in the image system of coordinates. So, we have to invert
    # they y axis. The procedure that after a lot of trials and errors ended up working is
    # copied from here https://stackoverflow.com/a/70695479/10073233 and is given by:
    field = field.reindex(y = field.y[::-1]) 

    # VortexFitting expects time coordinate to go first. In practice it reads spatial
    # matrices with x as the first spatial axis for piv_netcdf, so we store as (t, x, y)
    # to match the expectations in tests/test_inter.py.
    fieldReordered = field.transpose('t','x','y') 
    fieldReordered = fieldReordered.fillna(0.0)

    # VortexFitting expects very specific names of the data arrays. And there must be
    # the third component of velocity vector.
    fieldReordered['velocity_z'] = fieldReordered['u'].copy(
        data=np.zeros(fieldReordered['u'].values.shape))
    fieldRenamed = fieldReordered.rename_vars(
        {'u':'velocity_n', 'v':'velocity_s', 'y':'grid_z', 'x':'grid_n', })

    fieldRenamed.to_netcdf(path=ncFilePath, mode='w')

    vfield = vf.VelocityField(str(ncFilePath), file_type = 'piv_netcdf', time_step=0)

    return vfield