|
|
|
|
|
""" |
|
|
Compute energy spectra from vorticity field data. |
|
|
|
|
|
This script loads vorticity trajectory data from a .npy file and computes |
|
|
the azimuthally averaged energy spectrum E(k). It outputs both the spectrum |
|
|
data as a .npz file and a visualization plot as a .png file. |
|
|
|
|
|
To run direct numerical simulations and get fluid fields, please use Jax-CFD: https://github.com/google/jax-cfd |
|
|
Commit hash we used: 0c17e3855702f884265b97bd6ff0793c34f3155e |
|
|
|
|
|
Usage: |
|
|
uv run python fluid_stats.py path/to/vorticity.npy --out_dir results/ |
|
|
""" |
|
|
|
|
|
import argparse |
|
|
import logging |
|
|
import os |
|
|
from functools import partial |
|
|
|
|
|
import jax |
|
|
import jax.numpy as jnp |
|
|
import matplotlib.pyplot as plt |
|
|
import numpy as np |
|
|
from jax import jit, vmap |
|
|
from tqdm import tqdm |
|
|
|
|
|
|
|
|
logging.basicConfig( |
|
|
level=logging.INFO, |
|
|
format="%(asctime)s - %(levelname)s - %(message)s", |
|
|
datefmt="%Y-%m-%d %H:%M:%S", |
|
|
) |
|
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@jit |
|
|
def vorticity_to_velocity(vorticity): |
|
|
""" |
|
|
Convert vorticity to velocity components using the streamfunction. |
|
|
|
|
|
Solves the Poisson equation in Fourier space: psi_hat = -vorticity_hat / k^2 |
|
|
Then computes velocity from streamfunction: u_x = -d(psi)/dy, u_y = d(psi)/dx |
|
|
|
|
|
Parameters |
|
|
---------- |
|
|
vorticity : jnp.ndarray, shape (X, Y) |
|
|
2D vorticity field on a square grid. |
|
|
|
|
|
Returns |
|
|
------- |
|
|
u_x : jnp.ndarray, shape (X, Y) |
|
|
x-component of velocity. |
|
|
u_y : jnp.ndarray, shape (X, Y) |
|
|
y-component of velocity. |
|
|
""" |
|
|
N = vorticity.shape[0] |
|
|
|
|
|
|
|
|
|
|
|
vort_hat = jnp.fft.fft2(vorticity) |
|
|
|
|
|
|
|
|
kx = jnp.fft.fftfreq(N, d=1.0) * 2 * jnp.pi |
|
|
ky = jnp.fft.fftfreq(N, d=1.0) * 2 * jnp.pi |
|
|
KX, KY = jnp.meshgrid(kx, ky, indexing="ij") |
|
|
K2 = KX**2 + KY**2 |
|
|
|
|
|
|
|
|
K2 = K2.at[0, 0].set(1.0) |
|
|
psi_hat = -vort_hat / K2 |
|
|
psi_hat = psi_hat.at[0, 0].set(0.0) |
|
|
|
|
|
|
|
|
|
|
|
u_x_hat = -1j * KY * psi_hat |
|
|
u_y_hat = 1j * KX * psi_hat |
|
|
|
|
|
u_x = jnp.real(jnp.fft.ifft2(u_x_hat)) |
|
|
u_y = jnp.real(jnp.fft.ifft2(u_y_hat)) |
|
|
|
|
|
return u_x, u_y |
|
|
|
|
|
|
|
|
@partial(jit, static_argnames=["k_max"]) |
|
|
def energy_spectrum_single(u_x, u_y, k_max=None): |
|
|
""" |
|
|
Compute azimuthally averaged energy spectrum E(k) for a single velocity field. |
|
|
|
|
|
The energy spectrum is computed by binning the 2D Fourier-transformed |
|
|
velocity field by wavenumber magnitude |k|. |
|
|
|
|
|
Parameters |
|
|
---------- |
|
|
u_x : jnp.ndarray, shape (X, Y) |
|
|
x-component of velocity. |
|
|
u_y : jnp.ndarray, shape (X, Y) |
|
|
y-component of velocity. |
|
|
k_max : int, optional |
|
|
Maximum wavenumber to compute. If None, uses N//3 (2/3 dealiasing rule). |
|
|
|
|
|
Returns |
|
|
------- |
|
|
E : jnp.ndarray, shape (k_max+1,) |
|
|
Energy spectrum E(k) for k = 0, 1, ..., k_max. |
|
|
""" |
|
|
N = u_x.shape[0] |
|
|
|
|
|
|
|
|
Ux = jnp.fft.fftshift(jnp.fft.fft2(u_x)) |
|
|
Ux = Ux / (N**2) |
|
|
Uy = jnp.fft.fftshift(jnp.fft.fft2(u_y)) |
|
|
Uy = Uy / (N**2) |
|
|
|
|
|
|
|
|
kx = jnp.fft.fftshift(jnp.fft.fftfreq(N)) * N |
|
|
ky = kx |
|
|
KX, KY = jnp.meshgrid(kx, ky) |
|
|
K = jnp.hypot(KX, KY).astype(jnp.int32) |
|
|
|
|
|
if k_max is None: |
|
|
k_max = N // 3 |
|
|
|
|
|
|
|
|
def compute_E_k(k): |
|
|
mask = K == k |
|
|
return 0.5 * jnp.sum(jnp.abs(Ux) ** 2 * mask + jnp.abs(Uy) ** 2 * mask) |
|
|
|
|
|
k_vals = jnp.arange(k_max + 1) |
|
|
E = vmap(compute_E_k)(k_vals) |
|
|
|
|
|
return E |
|
|
|
|
|
|
|
|
@partial(jit, static_argnames=["k_max"]) |
|
|
def energy_spectrum_from_vorticity(vorticity, k_max=None): |
|
|
""" |
|
|
Compute energy spectrum from vorticity field using vmap. |
|
|
|
|
|
Suitable for moderate resolution fields (up to ~1024x1024). |
|
|
For larger resolutions, use energy_spectrum_from_vorticity_lax_map. |
|
|
|
|
|
Parameters |
|
|
---------- |
|
|
vorticity : jnp.ndarray, shape (T, X, Y) |
|
|
Vorticity field over T time steps on an X x Y grid. |
|
|
k_max : int, optional |
|
|
Maximum wavenumber. If None, uses N//3 (2/3 dealiasing rule). |
|
|
|
|
|
Returns |
|
|
------- |
|
|
E : jnp.ndarray, shape (T, k_max+1) |
|
|
Energy spectrum for each time step. |
|
|
""" |
|
|
N = vorticity.shape[1] |
|
|
|
|
|
if k_max is None: |
|
|
k_max = N // 3 |
|
|
|
|
|
def process_timestep(vort_t): |
|
|
u_x, u_y = vorticity_to_velocity(vort_t) |
|
|
return energy_spectrum_single(u_x, u_y, k_max) |
|
|
|
|
|
|
|
|
E = vmap(process_timestep)(vorticity) |
|
|
|
|
|
return E |
|
|
|
|
|
|
|
|
@partial(jit, static_argnames=["k_max", "batch_size"]) |
|
|
def energy_spectrum_from_vorticity_lax_map(vorticity, k_max=None, batch_size=16): |
|
|
""" |
|
|
Compute energy spectrum from vorticity field using jax.lax.map. |
|
|
|
|
|
Memory-efficient version suitable for high resolution fields (>1024x1024). |
|
|
Processes timesteps sequentially to reduce memory footprint. |
|
|
|
|
|
Parameters |
|
|
---------- |
|
|
vorticity : jnp.ndarray, shape (T, X, Y) |
|
|
Vorticity field over T time steps on an X x Y grid. |
|
|
k_max : int, optional |
|
|
Maximum wavenumber. If None, uses N//3 (2/3 dealiasing rule). |
|
|
batch_size : int, optional |
|
|
Batch size for lax.map processing. Default is 16. |
|
|
|
|
|
Returns |
|
|
------- |
|
|
E : jnp.ndarray, shape (T, k_max+1) |
|
|
Energy spectrum for each time step. |
|
|
""" |
|
|
N = vorticity.shape[1] |
|
|
|
|
|
if k_max is None: |
|
|
k_max = N // 3 |
|
|
|
|
|
def process_timestep(vort_t): |
|
|
u_x, u_y = vorticity_to_velocity(vort_t) |
|
|
return energy_spectrum_single(u_x, u_y, k_max) |
|
|
|
|
|
|
|
|
E = jax.lax.map(process_timestep, vorticity, batch_size=batch_size) |
|
|
|
|
|
return E |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def parse_args(): |
|
|
"""Parse command line arguments.""" |
|
|
parser = argparse.ArgumentParser( |
|
|
description=( |
|
|
"Compute energy spectra from 2D vorticity trajectory data. " |
|
|
"Loads vorticity fields from a .npy file, computes the azimuthally " |
|
|
"averaged energy spectrum E(k), and saves both the spectrum data " |
|
|
"and a visualization plot." |
|
|
), |
|
|
formatter_class=argparse.RawDescriptionHelpFormatter, |
|
|
epilog=""" |
|
|
Examples: |
|
|
uv run python fluid_stats.py simulation.npy |
|
|
uv run python fluid_stats.py data/vorticity.npy --out_dir results/ |
|
|
|
|
|
Input format: |
|
|
The input .npy file should contain a 4D array with shape (batch, time, X, Y) |
|
|
where batch is the number of independent trajectories, time is the number |
|
|
of snapshots, and X, Y are the spatial grid dimensions. |
|
|
""", |
|
|
) |
|
|
|
|
|
parser.add_argument( |
|
|
"input_file", |
|
|
type=str, |
|
|
help=( |
|
|
"Path to the input .npy file containing vorticity data. " |
|
|
"Expected shape: (batch, time, X, Y) where X and Y are the " |
|
|
"spatial grid dimensions (must be square, i.e., X == Y)." |
|
|
), |
|
|
) |
|
|
|
|
|
parser.add_argument( |
|
|
"--out_dir", |
|
|
type=str, |
|
|
default=".", |
|
|
help=( |
|
|
"Directory to save output files. Will be created if it does not " |
|
|
"exist. Output files are named based on the input filename. " |
|
|
"Default: current directory." |
|
|
), |
|
|
) |
|
|
|
|
|
return parser.parse_args() |
|
|
|
|
|
|
|
|
def main(): |
|
|
"""Main entry point for energy spectrum computation.""" |
|
|
args = parse_args() |
|
|
|
|
|
|
|
|
logger.info("JAX devices: %s", jax.devices()) |
|
|
|
|
|
|
|
|
if not os.path.exists(args.input_file): |
|
|
logger.error("Input file not found: %s", args.input_file) |
|
|
raise FileNotFoundError(f"Input file not found: {args.input_file}") |
|
|
|
|
|
if not args.input_file.endswith(".npy"): |
|
|
logger.warning( |
|
|
"Input file does not have .npy extension: %s", args.input_file |
|
|
) |
|
|
|
|
|
|
|
|
os.makedirs(args.out_dir, exist_ok=True) |
|
|
|
|
|
|
|
|
input_basename = os.path.splitext(os.path.basename(args.input_file))[0] |
|
|
data_filename = f"{input_basename}_spectrum_data.npz" |
|
|
plot_filename = f"{input_basename}_spectrum.png" |
|
|
data_path = os.path.join(args.out_dir, data_filename) |
|
|
plot_path = os.path.join(args.out_dir, plot_filename) |
|
|
|
|
|
|
|
|
logger.info("Loading data from: %s", args.input_file) |
|
|
field = np.load(args.input_file) |
|
|
logger.info("Loaded field with shape: %s", field.shape) |
|
|
|
|
|
|
|
|
if field.ndim != 4: |
|
|
logger.error( |
|
|
"Expected 4D array (batch, time, X, Y), got %dD array", field.ndim |
|
|
) |
|
|
raise ValueError( |
|
|
f"Expected 4D array (batch, time, X, Y), got {field.ndim}D array" |
|
|
) |
|
|
|
|
|
batch_size, time_steps, height, width = field.shape |
|
|
if height != width: |
|
|
logger.error( |
|
|
"Expected square spatial grid (X == Y), got %d x %d", height, width |
|
|
) |
|
|
raise ValueError( |
|
|
f"Expected square spatial grid (X == Y), got {height} x {width}" |
|
|
) |
|
|
|
|
|
resolution = height |
|
|
k_max = resolution // 3 |
|
|
logger.info( |
|
|
"Processing %d trajectories with %d timesteps at %dx%d resolution", |
|
|
batch_size, |
|
|
time_steps, |
|
|
resolution, |
|
|
resolution, |
|
|
) |
|
|
logger.info("Maximum wavenumber (k_max): %d", k_max) |
|
|
|
|
|
|
|
|
logger.info("Computing energy spectra...") |
|
|
spectra_list = [] |
|
|
|
|
|
for i in tqdm(range(batch_size), desc="Computing spectra"): |
|
|
if resolution > 1024: |
|
|
|
|
|
single_spectrum = energy_spectrum_from_vorticity_lax_map( |
|
|
field[i], k_max |
|
|
) |
|
|
else: |
|
|
|
|
|
single_spectrum = energy_spectrum_from_vorticity(field[i], k_max) |
|
|
spectra_list.append(single_spectrum) |
|
|
|
|
|
|
|
|
all_spectra = jnp.stack(spectra_list) |
|
|
logger.info("All spectra shape: %s", all_spectra.shape) |
|
|
|
|
|
|
|
|
mean_spectrum = all_spectra.reshape(-1, all_spectra.shape[-1]).mean(axis=0) |
|
|
logger.info("Mean spectrum shape: %s", mean_spectrum.shape) |
|
|
|
|
|
|
|
|
logger.info("Saving spectrum data to: %s", data_path) |
|
|
np.savez_compressed( |
|
|
data_path, |
|
|
mean_spectrum=np.array(mean_spectrum), |
|
|
all_spectra=np.array(all_spectra), |
|
|
k_values=np.arange(len(mean_spectrum)), |
|
|
resolution=resolution, |
|
|
batch_size=batch_size, |
|
|
time_steps=time_steps, |
|
|
) |
|
|
|
|
|
|
|
|
logger.info("Generating energy spectrum plot...") |
|
|
plt.figure(figsize=(10, 6)) |
|
|
|
|
|
|
|
|
offset = 1 |
|
|
spectrum = mean_spectrum[offset:] |
|
|
k_values = np.arange(offset, len(mean_spectrum)) |
|
|
plt.loglog(k_values, spectrum, "b-", linewidth=2, label="Mean spectrum") |
|
|
|
|
|
|
|
|
|
|
|
k_match = min(10, len(spectrum) // 3) |
|
|
if k_match > 0: |
|
|
ref_value = float(spectrum[k_match - 1]) |
|
|
|
|
|
|
|
|
scaling_k3 = ref_value * (k_match**3) |
|
|
k_theory = np.logspace(0, np.log10(len(mean_spectrum)), 100) |
|
|
power_law_k3 = scaling_k3 * k_theory ** (-3) |
|
|
plt.loglog( |
|
|
k_theory, |
|
|
power_law_k3, |
|
|
"k--", |
|
|
alpha=0.7, |
|
|
linewidth=1.5, |
|
|
label=r"$k^{-3}$ (enstrophy cascade)", |
|
|
) |
|
|
|
|
|
|
|
|
scaling_k53 = ref_value * (k_match ** (5 / 3)) |
|
|
power_law_k53 = scaling_k53 * k_theory ** (-5 / 3) |
|
|
plt.loglog( |
|
|
k_theory, |
|
|
power_law_k53, |
|
|
"r--", |
|
|
alpha=0.7, |
|
|
linewidth=1.5, |
|
|
label=r"$k^{-5/3}$ (energy cascade)", |
|
|
) |
|
|
|
|
|
plt.xlabel("Wavenumber k", fontsize=12) |
|
|
plt.ylabel("Energy Spectrum E(k)", fontsize=12) |
|
|
plt.title(f"Energy Spectrum ({resolution}x{resolution} resolution)", fontsize=14) |
|
|
plt.legend() |
|
|
plt.grid(True, alpha=0.3) |
|
|
xlim = plt.xlim() |
|
|
plt.xlim(1, xlim[1]) |
|
|
plt.tight_layout() |
|
|
|
|
|
|
|
|
plt.savefig(plot_path, dpi=300, bbox_inches="tight") |
|
|
plt.close() |
|
|
logger.info("Plot saved to: %s", plot_path) |
|
|
|
|
|
logger.info("Done!") |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |
|
|
|