API Reference¶
Overview¶
PyBurgers: 1D Stochastic Burgers Equation Solver.
A tool for studying Burgers turbulence using DNS and LES.
Core Solvers¶
Burgers
¶
Bases: ABC
Abstract base class for Burgers equation solvers.
Provides common functionality for solving the 1D stochastic Burgers equation using Fourier collocation for spatial derivatives and pluggable time integration with CFL-based adaptive time stepping.
Subclasses must implement
- _get_nx(): Return the grid resolution for this mode
- _create_spectral_workspace(): Create the spectral workspace for this mode
- _setup_mode_specific(): Initialize mode-specific components
- _setup_output_fields(): Configure output fields dictionary
- _compute_noise(): Generate/process noise for this time step
- _compute_rhs(): Compute the right-hand side of the equation
- _save_diagnostics(): Compute and save mode-specific diagnostics
Attributes:
| Name | Type | Description |
|---|---|---|
input |
Input configuration object. |
|
output |
Output handler for NetCDF writing. |
|
nx |
Number of grid points. |
|
dx |
Grid spacing. |
|
visc |
Kinematic viscosity. |
|
noise_amp |
Noise amplitude. |
|
cfl_target |
Target CFL number. |
|
max_step |
Maximum allowed time step. |
|
t_duration |
Total simulation time. |
|
t_save |
Output save interval in physical time. |
|
t_print |
Progress print interval in physical time. |
Initialize the Burgers solver.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_obj
|
Input
|
Input configuration containing simulation parameters. |
required |
output_obj
|
Output
|
Output handler for writing results to NetCDF. |
required |
Source code in pyburgers/core.py
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 | |
run
¶
Execute the time integration loop.
Advances the simulation using the configured time integrator with CFL-based adaptive time stepping. Output is written at exact multiples of t_save by clamping dt to hit output times.
Source code in pyburgers/core.py
DNS
¶
Bases: Burgers
Direct numerical simulation solver for the Burgers equation.
Solves the 1D stochastic Burgers equation at full resolution using Fourier collocation for spatial derivatives and pluggable time integration.
This class inherits common functionality from Burgers and implements DNS-specific behavior for noise generation and diagnostics. Uses a SpectralWorkspace with Derivatives and Dealias utilities (no Filter needed for DNS).
Source code in pyburgers/core.py
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 | |
LES
¶
Bases: Burgers
Large-eddy simulation solver for the Burgers equation.
Solves the filtered 1D stochastic Burgers equation using Fourier collocation for spatial derivatives, pluggable time integration, and subgrid-scale models for unresolved turbulence.
This class inherits common functionality from Burgers and implements LES-specific behavior including SGS modeling and filtered noise.
Attributes:
| Name | Type | Description |
|---|---|---|
nx_dns |
Number of DNS grid points (for noise generation). |
|
sgs_model_id |
SGS model type identifier (0-4). |
|
spectral |
SpectralWorkspace with derivatives, dealias, and filter. |
|
subgrid |
SGS model instance. |
|
tke_sgs |
Subgrid TKE (for Deardorff model). |
Initialize the LES solver.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_obj
|
Input
|
Input configuration containing simulation parameters. |
required |
output_obj
|
Output
|
Output handler for writing results to NetCDF. |
required |
Source code in pyburgers/les.py
Numerical Methods¶
Temporal Integrators¶
TemporalIntegrator
¶
Bases: ABC
Base class for time integration schemes.
Provides the interface and factory method for time integrators used
by the Burgers equation solver. Subclasses implement the step method
to advance the solution by one timestep.
Attributes:
| Name | Type | Description |
|---|---|---|
nx |
Number of grid points. |
|
dissipative_stability_limit |
float
|
Maximum stable |λ dt| for real negative eigenvalues (dissipative operators). Used by the core to set the hyperviscous time step limit. Subclasses override this based on their stability region for purely dissipative terms. |
Initialize the time integrator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nx
|
int
|
Number of grid points. |
required |
Source code in pyburgers/numerics/temporal/temporal.py
get_integrator
staticmethod
¶
Factory method to create the appropriate time integrator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scheme
|
int
|
Time integration scheme identifier. 1 = Adams-Bashforth 2nd order 2 = Adams-Moulton 2nd order predictor-corrector 3 = Williamson low-storage RK3 |
required |
nx
|
int
|
Number of grid points for pre-allocating storage arrays. |
required |
Returns:
| Type | Description |
|---|---|
TemporalIntegrator
|
Instance of the requested TemporalIntegrator subclass. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If scheme is not a valid option (1-3). |
Source code in pyburgers/numerics/temporal/temporal.py
step
abstractmethod
¶
step(u: ndarray, dt: float, compute_rhs: Callable[[], ndarray], zero_nyquist: Callable[[bool], None]) -> None
Advance the solution by one timestep.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array (modified in-place). |
required |
dt
|
float
|
Time step size. |
required |
compute_rhs
|
Callable[[], ndarray]
|
Callable that computes and returns the RHS vector. |
required |
zero_nyquist
|
Callable[[bool], None]
|
Callable that zeros the Nyquist mode.
Accepts a |
required |
Source code in pyburgers/numerics/temporal/temporal.py
AB2
¶
Bases: TemporalIntegrator
Adams-Bashforth 2nd-order multistep method.
Uses the variable-step AB2 formula to maintain 2nd-order accuracy under CFL-based adaptive time stepping:
ω = dt_n / dt_{n-1}
u^{n+1} = u^n + dt_n · [(1 + ω/2) · F^n − (ω/2) · F^{n-1}]
Reduces to the standard (3/2, -1/2) coefficients when dt is constant. The first timestep is bootstrapped with forward Euler since no previous RHS is available.
Note: variable-step AB2 is weakly unstable when the step-size ratio ω = dt_n / dt_{n-1} varies rapidly between steps. In practice the CFL controller changes dt smoothly (ω ≈ 1), so the instability does not manifest, but users should be aware of this known limitation if adapting the scheme to more aggressive step-size controllers.
AB2 has a stability boundary at |λ dt| = 1 for real negative eigenvalues, but its imaginary stability boundary is very small (~0 for purely imaginary). For advection-diffusion problems, the combined eigenvalue λdt = α + iβ must lie inside a kidney-shaped stability region that is much smaller than the real-axis limit of 1. A limit of 0.2 keeps the viscous dt constraint binding (rather than the CFL) for u_max up to ~0.26, preventing the advective eigenvalue from reaching the unstable π × CFL ≈ 1.26 regime.
Attributes:
| Name | Type | Description |
|---|---|---|
dissipative_stability_limit |
float
|
0.2 — keeps the viscous dt limit binding so the combined advection-diffusion eigenvalue stays within AB2's stability region for typical DNS velocities. |
_rhs_prev |
ndarray | None
|
RHS from the previous timestep, or None before the first step (triggers Euler bootstrap). |
_dt_prev |
float | None
|
Time step used on the previous timestep, or None before the first step. |
Initialize AB2 integrator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nx
|
int
|
Number of grid points. |
required |
Source code in pyburgers/numerics/temporal/temporal_ab2.py
step
¶
step(u: ndarray, dt: float, compute_rhs: Callable[[], ndarray], zero_nyquist: Callable[[bool], None]) -> None
Advance the solution by one timestep using AB2.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array (modified in-place). |
required |
dt
|
float
|
Time step size. |
required |
compute_rhs
|
Callable[[], ndarray]
|
Callable that computes and returns the RHS vector. |
required |
zero_nyquist
|
Callable[[bool], None]
|
Callable that zeros the Nyquist mode. |
required |
Source code in pyburgers/numerics/temporal/temporal_ab2.py
AM2
¶
Bases: TemporalIntegrator
Adams-Bashforth 2nd-order predictor / Adams-Moulton 2nd-order corrector.
Implements a PECE predictor-corrector scheme pairing the variable-step AB2 predictor with the AM2 (trapezoidal rule) corrector:
Predict: u^* = u^n + dt·[(1 + ω/2)·F^n − (ω/2)·F^{n-1}] (AB2, variable-step)
Evaluate: F^* = F(u^*)
Correct: u^{n+1} = u^n + dt/2·(F^* + F^n) (AM2)
Evaluate: F^{n+1} = F(u^{n+1}) [implicit in next step]
The variable-step AB2 predictor maintains 2nd-order accuracy under CFL-based adaptive time stepping. The AM2 corrector (trapezoidal rule) uses constant coefficients since it spans only the current interval and is A-stable as a standalone implicit method.
The scheme reduces to the variable-step Euler bootstrap on the first timestep, matching the AB2 bootstrap strategy.
Stability: The AM2 corrector is A-stable. In PECE mode the effective stability region for real negative eigenvalues is slightly wider than AB2 alone, but the AB2 predictor still constrains the overall stability. The AM2 corrector's A-stability allows a larger dissipative_stability_limit (0.4) than standalone AB2 (0.1), since the corrector damps the parasitic root from the predictor.
Attributes:
| Name | Type | Description |
|---|---|---|
dissipative_stability_limit |
float
|
0.4 — the A-stable corrector permits a larger limit than standalone AB2. |
_rhs_prev |
ndarray | None
|
RHS from the previous timestep (F^{n-1}), or None before the first step (triggers Euler bootstrap). |
_rhs_n |
Pre-allocated buffer holding F^n, copied from compute_rhs() before the corrector evaluation overwrites the shared RHS buffer. |
|
_u_save |
Pre-allocated buffer for u^n, restored before applying the corrector so the predictor modification does not persist. |
|
_dt_prev |
float | None
|
Time step used on the previous timestep, or None before the first step. |
Initialize AM2 predictor-corrector integrator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nx
|
int
|
Number of grid points. |
required |
Source code in pyburgers/numerics/temporal/temporal_am2.py
step
¶
step(u: ndarray, dt: float, compute_rhs: Callable[[], ndarray], zero_nyquist: Callable[[bool], None]) -> None
Advance the solution by one timestep using AB2-AM2 predictor-corrector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array (modified in-place). |
required |
dt
|
float
|
Time step size. |
required |
compute_rhs
|
Callable[[], ndarray]
|
Callable that computes and returns the RHS vector. Returns a reference to a shared buffer; callers must copy before invoking compute_rhs a second time. |
required |
zero_nyquist
|
Callable[[bool], None]
|
Callable that zeros the Nyquist mode.
Accepts a |
required |
Source code in pyburgers/numerics/temporal/temporal_am2.py
RK3
¶
Bases: TemporalIntegrator
Williamson (1980) low-storage 3rd-order Runge-Kutta.
Uses two coefficient vectors for a three-stage integration with a single auxiliary storage array Q.
RK3's stability region for real negative eigenvalues extends to |λ dt| ~ 2.5+, so the dissipative_stability_limit of 2.5 is set well above typical max_step · π⁴ values and will not constrain the time step in practice. The limit is retained for interface consistency.
Attributes:
| Name | Type | Description |
|---|---|---|
dissipative_stability_limit |
float
|
2.5 — exceeds typical hyperviscous eigenvalue at max_step, so max_step governs instead. |
Q |
Low-storage register array. |
Initialize RK3 integrator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nx
|
int
|
Number of grid points. |
required |
Source code in pyburgers/numerics/temporal/temporal_rk3.py
step
¶
step(u: ndarray, dt: float, compute_rhs: Callable[[], ndarray], zero_nyquist: Callable[[bool], None]) -> None
Advance the solution by one timestep using 3-stage RK3.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array (modified in-place). |
required |
dt
|
float
|
Time step size. |
required |
compute_rhs
|
Callable[[], ndarray]
|
Callable that computes and returns the RHS vector. |
required |
zero_nyquist
|
Callable[[bool], None]
|
Callable that zeros the Nyquist mode. |
required |
Source code in pyburgers/numerics/temporal/temporal_rk3.py
Spatial Operators¶
SpatialOperator
¶
Bases: ABC
Base class for spatial discretization (gradient computation) schemes.
Provides the interface and factory method for gradient operators used
by the Burgers equation solver. Subclasses implement the compute method
to evaluate spatial derivatives and the zero_nyquist method to enforce
spectral constraints (a no-op for finite-difference schemes).
Class attributes encode the scheme's maximum modified-wavenumber magnitudes at the Nyquist frequency, normalised by dx:
viscous_eigenvalue max |k̃²| · dx² (for d²/dx²)
hyperviscous_eigenvalue max |k̃⁴| · dx⁴ (for d⁴/dx⁴)
These are used by the core solver to set scheme-appropriate stability limits for the viscous and hyperviscous time step constraints, analogous to how TemporalIntegrator.dissipative_stability_limit works for the time scheme.
Attributes:
| Name | Type | Description |
|---|---|---|
nx |
Number of grid points. |
|
dx |
Grid spacing. |
Initialize the gradient operator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nx
|
int
|
Number of grid points. |
required |
dx
|
float
|
Grid spacing. |
required |
Source code in pyburgers/numerics/spatial/spatial.py
get_operator
staticmethod
¶
Factory method to create the appropriate gradient operator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scheme
|
int
|
Spatial discretization scheme identifier. 1 = 2nd-order central finite differences 2 = 4th-order central finite differences 3 = Spectral (Fourier collocation) |
required |
nx
|
int
|
Number of grid points. |
required |
dx
|
float
|
Grid spacing. |
required |
spectral
|
SpectralWorkspace
|
SpectralWorkspace used for spectral derivatives (scheme=3) and Nyquist zeroing (all schemes). |
required |
Returns:
| Type | Description |
|---|---|
SpatialOperator
|
Instance of the requested SpatialOperator subclass. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If scheme is not a valid option (1-3). |
Source code in pyburgers/numerics/spatial/spatial.py
compute
abstractmethod
¶
Compute spatial derivatives of u.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array. |
required |
orders
|
list[int | str]
|
List of derivative orders to compute. Supported values: 1, 2, 3, 4 (integer derivative orders) and 'sq' (dealiased d(u²)/dx for the nonlinear advection term). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dictionary mapping order keys ('1', '2', '3', '4', 'sq') to |
dict[str, ndarray]
|
derivative arrays. |
Source code in pyburgers/numerics/spatial/spatial.py
zero_nyquist
abstractmethod
¶
Zero the Nyquist mode after each integration stage.
For spectral schemes this enforces the spectral constraint on the highest resolved wavenumber. For finite-difference schemes this is a no-op.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
restore_physical
|
bool
|
Whether to transform back to physical space after zeroing (spectral schemes only). |
True
|
Source code in pyburgers/numerics/spatial/spatial.py
FD2
¶
Bases: SpatialOperator
2nd-order central finite-difference gradient operator.
All derivatives are approximated with 2nd-order accurate central difference stencils. Periodic boundary conditions are enforced implicitly via numpy.roll. The Nyquist constraint does not apply to finite-difference schemes, so zero_nyquist is a no-op.
Modified-wavenumber maxima at Nyquist (ξ = π): viscous_eigenvalue = 4 (max |k̃²|·dx², stencil gives -4/dx²) hyperviscous_eigenvalue = 16 (max |k̃⁴|·dx⁴, stencil gives +16/dx⁴)
Stencils (h = dx): du/dx = (u[i+1] - u[i-1]) / (2h) d²u/dx² = (u[i+1] - 2u[i] + u[i-1]) / h² d³u/dx³ = (u[i+2] - 2u[i+1] + 2u[i-1] - u[i-2]) / (2h³) d⁴u/dx⁴ = (u[i+2] - 4u[i+1] + 6u[i] - 4u[i-1] + u[i-2]) / h⁴ sq = d(u²)/dx via 2nd-order FD applied to v = u²
Source code in pyburgers/numerics/spatial/spatial_fd2.py
compute
¶
Compute finite-difference derivatives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array. |
required |
orders
|
list[int | str]
|
Derivative orders to compute (1, 2, 3, 4, 'sq'). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dictionary of derivative arrays keyed by string order. |
Source code in pyburgers/numerics/spatial/spatial_fd2.py
zero_nyquist
¶
Zero the Nyquist mode via spectral transform.
FD stencils have zero advective modified wavenumber at Nyquist, so multistep integrators (AB2) can amplify that mode through the parasitic root. Zeroing it each step prevents this.
Only acts when restore_physical=True (final integrator stage), since FD derivatives need physical-space u and intermediate stages don't accumulate parasitic growth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
restore_physical
|
bool
|
Whether to transform back to physical space. |
True
|
Source code in pyburgers/numerics/spatial/spatial_fd2.py
FD4
¶
Bases: SpatialOperator
4th-order central finite-difference gradient operator.
All derivatives are approximated with 4th-order accurate central difference stencils. Periodic boundary conditions are enforced implicitly via numpy.roll. The Nyquist constraint does not apply to finite-difference schemes, so zero_nyquist is a no-op.
Modified-wavenumber maxima at Nyquist (ξ = π): viscous_eigenvalue = 16/3 ≈ 5.33 (max |k̃²|·dx², stencil gives -64/(12dx²)) hyperviscous_eigenvalue = 80/3 ≈ 26.67 (max |k̃⁴|·dx⁴, stencil gives 160/(6dx⁴))
Stencils (h = dx): du/dx = (-u[i+2] + 8u[i+1] - 8u[i-1] + u[i-2]) / (12h) d²u/dx² = (-u[i+2] + 16u[i+1] - 30u[i] + 16u[i-1] - u[i-2]) / (12h²) d³u/dx³ = (u[i+3] - 8u[i+2] + 13u[i+1] - 13u[i-1] + 8u[i-2] - u[i-3]) / (8h³) d⁴u/dx⁴ = (-u[i+3] + 12u[i+2] - 39u[i+1] + 56u[i] - 39u[i-1] + 12u[i-2] - u[i-3]) / (6h⁴) sq = d(u²)/dx via 4th-order FD applied to v = u²
Source code in pyburgers/numerics/spatial/spatial_fd4.py
compute
¶
Compute finite-difference derivatives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array. |
required |
orders
|
list[int | str]
|
Derivative orders to compute (1, 2, 3, 4, 'sq'). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dictionary of derivative arrays keyed by string order. |
Source code in pyburgers/numerics/spatial/spatial_fd4.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 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 | |
zero_nyquist
¶
Zero the Nyquist mode via spectral transform.
FD stencils have zero advective modified wavenumber at Nyquist, so multistep integrators (AB2) can amplify that mode through the parasitic root. Zeroing it each step prevents this.
Only acts when restore_physical=True (final integrator stage), since FD derivatives need physical-space u and intermediate stages don't accumulate parasitic growth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
restore_physical
|
bool
|
Whether to transform back to physical space. |
True
|
Source code in pyburgers/numerics/spatial/spatial_fd4.py
Spectral
¶
Bases: SpatialOperator
Spectral (Fourier collocation) gradient operator.
Delegates all derivative computation and Nyquist enforcement to the existing Derivatives object in the SpectralWorkspace. No code is duplicated; this class is a thin adapter.
Initialize the spectral gradient operator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nx
|
int
|
Number of grid points. |
required |
dx
|
float
|
Grid spacing. |
required |
spectral
|
SpectralWorkspace
|
SpectralWorkspace whose Derivatives object is reused. |
required |
Source code in pyburgers/numerics/spatial/spatial_spectral.py
compute
¶
Compute spectral derivatives via FFT.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array. |
required |
orders
|
list[int | str]
|
Derivative orders to compute (1, 2, 3, 4, 'sq'). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dictionary of derivative arrays keyed by order. |
Source code in pyburgers/numerics/spatial/spatial_spectral.py
zero_nyquist
¶
Zero the Nyquist mode in spectral space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
restore_physical
|
bool
|
Whether to transform back to physical space. |
True
|
Source code in pyburgers/numerics/spatial/spatial_spectral.py
Data Models¶
data_models
¶
Core Data Models for PyBurgers.
This module defines the core data structures used throughout PyBurgers. These
structures are implemented as Python dataclasses to provide a clear and
robust way to manage the model's state and configuration.
DNSConfig
dataclass
¶
Direct numerical simulation configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
points |
int
|
Number of grid points. |
FFTWConfig
dataclass
¶
FFTW parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
planning |
str
|
FFTW planning approach. |
threads |
int
|
Number of threads to use. |
LESConfig
dataclass
¶
Large-eddy simulation configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
points |
int
|
Number of grid points. |
GridConfig
dataclass
¶
LoggingConfig
dataclass
¶
Logging settings.
Attributes:
| Name | Type | Description |
|---|---|---|
level |
str
|
Logging level for the simulation (e.g., 'info', 'debug'). |
file |
str | None
|
Optional log file path for file logging. |
NoiseConfig
dataclass
¶
Noise method parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
exponent |
float
|
FBM exponent controlling the spectral slope. |
amplitude |
float
|
Noise amplitude. |
seed |
int | None
|
RNG seed for reproducibility. None means a random seed. |
OutputConfig
dataclass
¶
Output file configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
interval_save |
float
|
Save interval in physical time [s]. |
interval_print |
float
|
Print progress interval in physical time [s]. |
PhysicsConfig
dataclass
¶
Physics configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
noise |
NoiseConfig
|
NoiseConfig configuration. |
viscosity |
float
|
The fluid's kinematic viscosity [m^2/s]. |
subgrid_model |
int
|
Subgrid-scale model ID (1-4) for LES. |
NumericsConfig
dataclass
¶
Numerical method selections and time stepping parameters.
Attributes:
| Name | Type | Description |
|---|---|---|
temporal |
int
|
Time integration scheme ID (1=AB2, 2=AM2, 3=RK3). |
spatial |
int
|
Spatial discretization scheme ID (1=FD2, 2=FD4, 3=Spectral). |
cfl |
float
|
Target CFL number for adaptive time stepping. |
max_step |
float
|
Maximum allowed time step [s]. |
TimeConfig
dataclass
¶
Time-related parameters for the simulation.
Attributes:
| Name | Type | Description |
|---|---|---|
duration |
float
|
Total simulation time [s]. |
Exceptions¶
exceptions
¶
Custom exception types for PyBurgers.
PyBurgersError
¶
Bases: Exception
Base class for all custom exceptions in PyBurgers.
NamelistError
¶
Bases: PyBurgersError
Raised for errors found in the namelist configuration.
InvalidMode
¶
Bases: PyBurgersError
Raised when an invalid simulation mode is specified.
Utilities¶
Derivatives
¶
Computes spectral derivatives using real FFT (rfft/irfft).
Uses Fourier collocation to compute spatial derivatives of a field. Supports first, second, and third order derivatives, as well as the dealiased derivative of the squared field (d(u^2)/dx).
Since velocity fields are real-valued, rfft is used for efficiency (~2x speedup, ~50% memory reduction for frequency arrays).
Attributes:
| Name | Type | Description |
|---|---|---|
nx |
Number of grid points. |
|
dx |
Grid spacing. |
|
nk |
Number of rfft output coefficients (nx//2 + 1). |
|
m |
Nyquist mode index (nx/2). |
|
fac |
Derivative scaling factor (2pi/(nxdx)). |
|
k |
Wavenumber array (non-negative frequencies only). |
Initialize the Derivatives calculator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nx
|
int
|
Number of grid points (must be even). |
required |
dx
|
float
|
Grid spacing. |
required |
fftw_planning
|
str
|
FFTW planning strategy. |
'FFTW_MEASURE'
|
fftw_threads
|
int
|
Number of threads for FFTW. |
1
|
Source code in pyburgers/utils/spectral.py
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 | |
compute
¶
Compute spectral derivatives of the input field.
When u is not the internal velocity buffer (self.u),
a separate FFT buffer pair is used so the primary velocity
state is never touched.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Input field array (real-valued). |
required |
orders
|
list[int | str]
|
List of derivative orders to compute. Can include integers (1, 2, 3, 4) for standard derivatives or 'sq' for the dealiased derivative of u^2. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dictionary mapping order keys ('1', '2', '3', '4', 'sq') to |
dict[str, ndarray]
|
the corresponding derivative arrays. Arrays are reused |
dict[str, ndarray]
|
internally, so callers should consume values before the |
dict[str, ndarray]
|
next compute() call. |
Source code in pyburgers/utils/spectral.py
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 | |
zero_nyquist
¶
FFT self.u, zero the Nyquist mode, and restore physical space.
Called after each integration stage to enforce the Nyquist constraint. Performs FFT, zeros the Nyquist mode, and IFFTs back to physical space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
restore_physical
|
bool
|
Ignored; always restores physical space after zeroing. Retained for interface compatibility with SpatialOperator. |
True
|
Source code in pyburgers/utils/spectral.py
Dealias
¶
Dealias(nx: int, fftw_planning: str = 'FFTW_MEASURE', fftw_threads: int = 1, *, shared_der: Derivatives | None = None)
Dealiases nonlinear products using the 3/2 rule.
Computes |x| * x with proper dealiasing to avoid aliasing errors in the nonlinear term of the Burgers equation.
Uses real FFT (rfft/irfft) for efficiency since input fields are real-valued.
Attributes:
| Name | Type | Description |
|---|---|---|
nx |
Number of grid points. |
|
nk |
Number of rfft output coefficients (nx//2 + 1). |
|
m |
Nyquist mode index (nx/2). |
Initialize the Dealias calculator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nx
|
int
|
Number of grid points. |
required |
fftw_planning
|
str
|
FFTW planning strategy. |
'FFTW_MEASURE'
|
fftw_threads
|
int
|
Number of threads for FFTW. |
1
|
shared_der
|
Derivatives | None
|
Optional Derivatives instance whose padded FFT plans and buffers are reused instead of allocating new ones. When provided, the padded-forward and padded-inverse plans are shared. Callers must ensure Dealias.compute() and Derivatives.compute('sq') are not called concurrently. |
None
|
Source code in pyburgers/utils/spectral.py
compute
¶
Compute the dealiased product |x| * x.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Input array (real-valued). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Dealiased result of |x| * x. The returned array is an |
ndarray
|
internal buffer; copy it if you need to preserve the values |
ndarray
|
across calls. |
Source code in pyburgers/utils/spectral.py
Filter
¶
Spectral filtering operations.
Provides spectral cutoff filtering and downscaling from DNS to LES resolution using Fourier methods.
Uses real FFT (rfft/irfft) for efficiency since input fields are real-valued.
Attributes:
| Name | Type | Description |
|---|---|---|
nx |
Number of grid points for the filtered field. |
|
nk |
Number of rfft output coefficients (nx//2 + 1). |
|
nx2 |
Number of grid points for the source field (DNS resolution). |
Initialize the Filter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nx
|
int
|
Number of grid points for the target (filtered) field. |
required |
nx2
|
int | None
|
Optional number of grid points for source field (used for downscaling from DNS to LES). |
None
|
fftw_planning
|
str
|
FFTW planning strategy. |
'FFTW_MEASURE'
|
fftw_threads
|
int
|
Number of threads for FFTW. |
1
|
Source code in pyburgers/utils/spectral.py
cutoff
¶
Apply a spectral cutoff filter.
Removes high-frequency modes above nx/ratio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Input array to filter (real-valued). |
required |
ratio
|
int
|
Cutoff ratio (keeps modes up to nx/ratio). |
required |
out
|
ndarray | None
|
Optional pre-allocated output array. If provided, the result is written here instead of allocating a new array. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Filtered array with high frequencies removed. |
Source code in pyburgers/utils/spectral.py
downscale
¶
Downscale a field from DNS to LES resolution.
Uses Fourier filtering to project a high-resolution field onto a coarser grid while preserving low-frequency content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Input array at DNS resolution (real-valued). |
required |
ratio
|
int
|
Downscaling ratio (nx2 / nx). |
required |
out
|
ndarray | None
|
Optional pre-allocated output array. If provided, the result is written here instead of allocating a new array. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Downscaled array at LES resolution. |
Source code in pyburgers/utils/spectral.py
SpectralWorkspace
¶
SpectralWorkspace(nx: int, dx: float, nx2: int | None = None, noise_beta: float | None = None, noise_nx: int | None = None, fftw_planning: str = 'FFTW_MEASURE', fftw_threads: int = 1, rng: Generator | None = None)
Centralized workspace for all spectral operations.
Manages FFT plans and aligned buffers for a simulation by bundling Derivatives, Dealias, Filter, and FBM noise utilities into a single workspace. All utilities share consistent FFTW settings (planning strategy, threads).
This design eliminates redundant FFT plan creation and ensures that resources are shared efficiently across the simulation.
Attributes:
| Name | Type | Description |
|---|---|---|
derivatives |
Derivatives calculator for spatial derivatives. |
|
dealias |
Dealias calculator for nonlinear products. |
|
filter |
Filter for spectral cutoff and downscaling. |
|
noise |
FBM noise generator (only if noise_beta provided). |
|
u |
ndarray
|
Primary velocity buffer (float64, size nx). |
fu |
ndarray
|
Primary Fourier space buffer (complex128, size nx//2+1 for rfft). |
Example
DNS workspace with noise¶
workspace = SpectralWorkspace(nx=512, dx=0.01, noise_beta=-0.75) derivs = workspace.derivatives.compute(u, order=[1, 2]) noise = workspace.noise.compute_noise()
LES workspace with filtering and noise at DNS resolution¶
workspace_les = SpectralWorkspace( ... nx=512, dx=0.01, nx2=8192, noise_beta=-0.75, noise_nx=8192 ... ) filtered = workspace_les.filter.cutoff(x, ratio=2)
Initialize the spectral workspace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nx
|
int
|
Number of grid points for the simulation. |
required |
dx
|
float
|
Grid spacing. |
required |
nx2
|
int | None
|
Optional number of grid points for DNS resolution (used in LES mode for downscaling noise from DNS to LES grid). If provided, creates Filter with downscaling capability. |
None
|
noise_beta
|
float | None
|
Optional FBM exponent for noise generation. If provided, creates FBM noise generator. Typical value is 0.75. |
None
|
noise_nx
|
int | None
|
Optional number of grid points for noise generation. If not provided and noise_beta is given, uses nx. For LES, set this to nx_dns to generate noise at DNS resolution. |
None
|
fftw_planning
|
str
|
FFTW planning strategy. Options: - 'FFTW_ESTIMATE': Fast planning, slower execution - 'FFTW_MEASURE': Balanced (default) - 'FFTW_PATIENT': Slow planning, faster execution |
'FFTW_MEASURE'
|
fftw_threads
|
int
|
Number of threads for FFTW operations. |
1
|
Source code in pyburgers/utils/spectral_workspace.py
__repr__
¶
Return a string representation of the workspace.
Source code in pyburgers/utils/spectral_workspace.py
fftw
¶
FFTW wisdom management for PyBurgers.
This module handles loading and saving FFTW wisdom to disk, which allows FFT plans to be reused across runs for faster initialization.
The wisdom file is stored at ~/.pyburgers_fftw_wisdom.
File locking is used to prevent race conditions when multiple PyBurgers instances access the wisdom file concurrently.
load_wisdom
¶
Load accumulated FFTW wisdom from cache file.
FFTW wisdom is cumulative: a single file can hold optimal plans for many different transform sizes. This function imports whatever plans are present; pyfftw will use matching plans and re-plan any missing sizes on-demand.
No parameter validation is performed — grid sizes and physical parameters do not affect whether a stored plan is valid.
Uses file locking to prevent concurrent access conflicts.
Returns:
| Type | Description |
|---|---|
tuple[bool, str]
|
Tuple of (success: bool, message: str). |
Source code in pyburgers/utils/fftw.py
save_wisdom
¶
Save accumulated FFTW wisdom to cache file.
Exports all plans that have been created in this session and writes them to the cache file, merging with any plans already present. Plans accumulate across runs so that each new configuration adds to the file rather than replacing it.
Uses file locking to prevent concurrent write conflicts.
Returns:
| Type | Description |
|---|---|
bool
|
True if wisdom was saved successfully, False otherwise. |
Source code in pyburgers/utils/fftw.py
warmup_fftw_plans
¶
warmup_fftw_plans(nx_dns: int, nx_les: int, noise_beta: float, fftw_planning: str, fftw_threads: int, domain_length: float = 2 * 3.141592653589793) -> tuple[bool, str]
Generate FFTW plans for common PyBurgers sizes.
This creates representative FFTW plans for DNS/LES grids, filters, dealiasing, and FBM noise so wisdom can be saved once and reused.
If warmup fails (e.g., out of memory, invalid parameters), the function returns False and a descriptive error message. The simulation can still continue - plans will be created on-demand during initialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nx_dns
|
int
|
DNS grid resolution. |
required |
nx_les
|
int
|
LES grid resolution. |
required |
noise_beta
|
float
|
FBM noise exponent. |
required |
fftw_planning
|
str
|
FFTW planning strategy. |
required |
fftw_threads
|
int
|
Number of FFTW threads. |
required |
domain_length
|
float
|
Length of the periodic domain (default: 2π). |
2 * 3.141592653589793
|
Returns:
| Type | Description |
|---|---|
bool
|
Tuple of (success: bool, message: str) indicating whether warmup |
str
|
completed successfully and any relevant diagnostic information. |
Source code in pyburgers/utils/fftw.py
FBM
¶
FBM(beta: float, n_pts: int, fftw_planning: str = 'FFTW_MEASURE', fftw_threads: int = 1, rng: Generator | None = None)
Generates fractional Brownian motion (FBM) noise.
FBM noise is used as the stochastic forcing term in the Burgers equation. The noise has a power spectrum that scales as k^(-beta).
Attributes:
| Name | Type | Description |
|---|---|---|
beta |
FBM exponent, controls spectral slope. |
|
n_pts |
Number of grid points. |
|
fftw_planning |
FFTW planning strategy. |
|
fftw_threads |
Number of FFTW threads. |
|
nyquist |
Nyquist mode index (n/2). |
|
wavenumber |
Wavenumber array for spectral coloring. |
Initialize the FBM noise generator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
beta
|
float
|
FBM exponent controlling the spectral slope. Typical value is -0.75 for Burgers turbulence. |
required |
n_pts
|
int
|
Number of grid points. |
required |
fftw_planning
|
str
|
FFTW planning strategy (default: 'FFTW_MEASURE'). |
'FFTW_MEASURE'
|
fftw_threads
|
int
|
Number of FFTW threads (default: 1). |
1
|
rng
|
Generator | None
|
NumPy Generator for reproducible noise. If None, a fresh default_rng() is created (non-reproducible). |
None
|
Source code in pyburgers/utils/fbm.py
compute_noise
¶
Generate a realization of FBM noise.
Creates white noise, transforms to spectral space, applies the FBM spectral coloring (k^(beta/2)), and transforms back.
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
Real-valued noise array with FBM spectral characteristics. |
Note
The returned array is an internal buffer that will be overwritten
on the next call to compute_noise(). If you need to preserve the
values, make a copy: noise.copy().
Source code in pyburgers/utils/fbm.py
constants
¶
Defines constants for PyBurgers.
This module provides a centralized location for all constants used throughout PyBurgers. Constants are grouped into logical namespaces using frozen dataclasses.
Module-level instances
spectral: Spectral algorithm constants. sgs: Subgrid-scale model constants.
SpectralConstants
dataclass
¶
Spectral algorithm constants.
Attributes:
| Name | Type | Description |
|---|---|---|
DEALIAS_SCALE |
float
|
Scale factor for dealiasing using 3/2 padding rule |
SGSConstants
dataclass
¶
SGSConstants(TEST_FILTER_RATIO: int = 2, SMAG_CONSTANT_CS: float = 0.16, DEARDORFF_CE: float = 0.7, DEARDORFF_C1: float = 0.1, WONGLILLY_EXPONENT: float = 4.0 / 3.0)
Subgrid-scale model constants.
Attributes:
| Name | Type | Description |
|---|---|---|
TEST_FILTER_RATIO |
int
|
Ratio for test filter width in dynamic models |
SMAG_CONSTANT_CS |
float
|
Smagorinsky constant (Cs) for constant-coefficient model |
DEARDORFF_CE |
float
|
Deardorff model constant for TKE dissipation |
DEARDORFF_C1 |
float
|
Deardorff model constant for eddy viscosity |
WONGLILLY_EXPONENT |
float
|
Exponent for Wong-Lilly dynamic procedure (4/3) |
logging_helper
¶
Logging configuration for PyBurgers.
This module provides centralized logging setup and helper functions for consistent logging across all PyBurgers modules.
setup_logging
¶
setup_logging(level: str | int = 'INFO', format_string: str | None = None, log_file: str | None = None, file_mode: str = 'w') -> None
Configure the root logger for PyBurgers.
This should be called once at application startup, typically in the main entry point (burgers.py).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
str | int
|
Log level as string ("DEBUG", "INFO", etc.) or int. |
'INFO'
|
format_string
|
str | None
|
Optional custom format string. If None, uses DEBUG_FORMAT for DEBUG level, DEFAULT_FORMAT otherwise. |
None
|
log_file
|
str | None
|
Optional log file path for file logging. |
None
|
file_mode
|
str
|
File mode for log file handler (default: "w"). |
'w'
|
Source code in pyburgers/utils/logging_helper.py
get_logger
¶
Get a logger for the specified module/class.
Creates a child logger under the PyBurgers namespace for consistent hierarchical logging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name for the logger, typically the class or module name. Examples: "DNS", "LES", "SGS", "Input", "Output" |
required |
Returns:
| Type | Description |
|---|---|
Logger
|
Configured logger instance. |
Example
logger = get_logger("DNS") logger.info("Starting simulation") [PyBurgers: DNS] Starting simulation
Source code in pyburgers/utils/logging_helper.py
get_log_level
¶
Convert a log level name to its integer value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level_name
|
str
|
Case-insensitive level name ("debug", "INFO", etc.) |
required |
Returns:
| Type | Description |
|---|---|
int
|
Integer log level value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If level_name is not a valid log level. |
Source code in pyburgers/utils/logging_helper.py
Input/Output¶
Input
¶
Orchestrates the loading and validation of all model inputs.
This class reads configuration from a JSON namelist file. All data is validated and organized into the appropriate dataclasses.
Attributes:
| Name | Type | Description |
|---|---|---|
time |
TimeConfig
|
Dataclass with time-related parameters (duration). |
physics |
PhysicsConfig
|
Dataclass with physics parameters (noise, viscosity). |
grid |
GridConfig
|
Dataclass with grid configuration (length, DNS, LES). |
numerics |
NumericsConfig
|
Dataclass with numerical method selections (integration, cfl, max_step). |
output |
OutputConfig
|
Dataclass with output file configuration. |
logging |
LoggingConfig
|
Dataclass with logging settings. |
fftw |
FFTWConfig
|
Dataclass with FFTW configuration. |
Initialize the Input class and load all configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namelist_path
|
str
|
The file path to the JSON namelist. |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the namelist file does not exist. |
JSONDecodeError
|
If the namelist JSON file is malformed. |
NamelistError
|
If required configuration is missing or invalid. |
Source code in pyburgers/utils/io/input.py
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 | |
get_dns_config
¶
Get DNS-specific configuration as a dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with DNS configuration values. |
Source code in pyburgers/utils/io/input.py
get_les_config
¶
Get LES-specific configuration as a dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with LES configuration values. |
Source code in pyburgers/utils/io/input.py
Output
¶
Manages the creation and writing of NetCDF output files.
This class handles all aspects of the output file, from its initial creation to writing data at each time step and final closing.
Attributes:
| Name | Type | Description |
|---|---|---|
outfile |
Dataset
|
A |
fields_time |
dict[str, Any]
|
A dictionary mapping time-varying field names to their NetCDF variable objects. |
fields_static |
dict[str, Any]
|
A dictionary mapping static field names to their NetCDF variable objects. |
attributes |
dict[str, dict[str, Any]]
|
A dictionary defining the metadata (dimensions, units, etc.) for each possible output variable. |
Initialize the Output class and create the NetCDF file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outfile
|
str
|
The path and name for the output NetCDF file. |
required |
sync_interval
|
int
|
Number of saves between disk syncs. Higher values improve performance but risk data loss on crash. Defaults to 100. |
100
|
Source code in pyburgers/utils/io/output.py
set_dims
¶
Set the dimensions in the NetCDF output file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dims
|
dict[str, int]
|
A dictionary mapping dimension names to their sizes. A size of 0 indicates an unlimited dimension. |
required |
Source code in pyburgers/utils/io/output.py
set_fields
¶
Create the variables (fields) in the NetCDF output file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fields
|
dict[str, Any]
|
A dictionary of fields to be created in the output file. |
required |
Source code in pyburgers/utils/io/output.py
save
¶
Save a snapshot of the simulation state to the output file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fields
|
dict[str, Any]
|
A dictionary of data fields to save. |
required |
tidx
|
int
|
The time index for the current snapshot. |
required |
time
|
float
|
The simulation time in seconds. |
required |
initial
|
bool
|
A boolean flag indicating if this is the initial save, in which case only static fields are written. Defaults to False. |
False
|
Source code in pyburgers/utils/io/output.py
close
¶
Close the NetCDF output file.
Performs a final sync to ensure all buffered data is written before closing the file.
Source code in pyburgers/utils/io/output.py
Physics¶
SGS
¶
Base class for subgrid-scale models.
Provides the interface and factory method for SGS models used in Large-Eddy Simulation. The base class returns zero SGS stress, equivalent to no subgrid model.
Attributes:
| Name | Type | Description |
|---|---|---|
input |
Input configuration object. |
|
spectral |
SpectralWorkspace with shared spectral utilities. |
|
nx |
Number of LES grid points. |
|
dx |
Grid spacing. |
|
result |
dict[str, Any]
|
Dictionary containing SGS stress (tau) and coefficient. |
Initialize the SGS model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_obj
|
Input
|
Input configuration object containing simulation parameters. |
required |
spectral
|
SpectralWorkspace
|
SpectralWorkspace containing shared spectral utilities. The base SGS class does not use this, but accepts it for consistency with subclasses. |
required |
Source code in pyburgers/physics/sgs/sgs.py
get_model
staticmethod
¶
Factory method to create the appropriate SGS model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
int
|
SGS model type identifier. 1 = Constant-coefficient Smagorinsky 2 = Dynamic Smagorinsky 3 = Dynamic Wong-Lilly 4 = Deardorff 1.5-order TKE |
required |
input_obj
|
Input
|
Input configuration object. |
required |
spectral
|
SpectralWorkspace
|
SpectralWorkspace containing shared spectral utilities (Derivatives, Dealias, Filter). REQUIRED for all SGS models. |
required |
Returns:
| Type | Description |
|---|---|
SGS
|
Instance of the requested SGS model subclass. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If model is not a valid option (1-4). |
Source code in pyburgers/physics/sgs/sgs.py
compute
¶
Compute the SGS stress tensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array. |
required |
dudx
|
ndarray
|
Velocity gradient (du/dx) array. |
required |
tke_sgs
|
ndarray | float
|
Subgrid TKE (used by Deardorff model). |
required |
dt
|
float
|
Current time step size. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing: - 'tau': SGS stress array - 'coeff': Model coefficient - 'tke_sgs': Updated subgrid TKE (Deardorff only) |
Source code in pyburgers/physics/sgs/sgs.py
SmagConstant
¶
Bases: SGS
Constant-coefficient Smagorinsky subgrid-scale model.
The classic Smagorinsky model computes SGS stress as
tau = -2 * Cs^2 * dx^2 * |S| * S
where Cs is a constant (typically 0.16) and S is the strain rate.
Uses the shared spectral workspace for dealiasing operations.
Initialize the constant Smagorinsky model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_obj
|
Input
|
Input configuration object. |
required |
spectral
|
SpectralWorkspace
|
SpectralWorkspace with shared Dealias utility. |
required |
Source code in pyburgers/physics/sgs/sgs_smagcon.py
compute
¶
Compute the Smagorinsky SGS stress.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array (unused). |
required |
dudx
|
ndarray
|
Velocity gradient array. |
required |
tke_sgs
|
ndarray | float
|
Subgrid TKE (unused in this model). |
required |
dt
|
float
|
Current time step size (unused in this model). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with 'tau' (SGS stress) and 'coeff' (Cs). |
Source code in pyburgers/physics/sgs/sgs_smagcon.py
SmagDynamic
¶
Bases: SGS
Dynamic Smagorinsky subgrid-scale model.
Uses the Germano identity to dynamically compute the Smagorinsky coefficient from the resolved velocity field. This removes the need for tuning Cs and allows it to adapt to local flow conditions.
Uses the shared spectral workspace for filtering and dealiasing operations.
Initialize the dynamic Smagorinsky model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_obj
|
Input
|
Input configuration object. |
required |
spectral
|
SpectralWorkspace
|
SpectralWorkspace with shared Dealias and Filter utilities. |
required |
Source code in pyburgers/physics/sgs/sgs_smagdyn.py
compute
¶
Compute the dynamic Smagorinsky SGS stress.
Uses test filtering to compute the Leonard stress L and model tensor M, then determines Cs^2 from their contraction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array. |
required |
dudx
|
ndarray
|
Velocity gradient array. |
required |
tke_sgs
|
ndarray | float
|
Subgrid TKE (unused in this model). |
required |
dt
|
float
|
Current time step size (unused in this model). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with 'tau' (SGS stress) and 'coeff' (Cs). |
Source code in pyburgers/physics/sgs/sgs_smagdyn.py
WongLilly
¶
Bases: SGS
Dynamic Wong-Lilly subgrid-scale model.
A scale-similarity based SGS model that uses a different scaling for the SGS stress compared to the Smagorinsky model. The stress scales as dx^(4/3) rather than dx^2.
Uses the shared spectral workspace for filtering operations.
Initialize the Wong-Lilly model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_obj
|
Input
|
Input configuration object. |
required |
spectral
|
SpectralWorkspace
|
SpectralWorkspace with shared Filter utility. |
required |
Source code in pyburgers/physics/sgs/sgs_wonglilly.py
compute
¶
Compute the Wong-Lilly SGS stress.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array. |
required |
dudx
|
ndarray
|
Velocity gradient array. |
required |
tke_sgs
|
ndarray | float
|
Subgrid TKE (unused in this model). |
required |
dt
|
float
|
Current time step size (unused in this model). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with 'tau' (SGS stress) and 'coeff' (C_WL). |
Source code in pyburgers/physics/sgs/sgs_wonglilly.py
Deardorff
¶
Bases: SGS
Deardorff 1.5-order TKE subgrid-scale model.
A prognostic SGS model that solves a transport equation for subgrid turbulent kinetic energy (TKE). The eddy viscosity is computed from the subgrid TKE as: nu_t = c1 * dx * sqrt(tke_sgs).
Uses the shared spectral workspace for dealiasing and derivative operations.
Initialize the Deardorff TKE model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_obj
|
Input
|
Input configuration object. |
required |
spectral
|
SpectralWorkspace
|
SpectralWorkspace with shared Dealias and Derivatives utilities. |
required |
Source code in pyburgers/physics/sgs/sgs_deardorff.py
compute
¶
Compute the Deardorff SGS stress and update subgrid TKE.
Solves the prognostic TKE equation and computes the SGS stress from the updated subgrid TKE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
u
|
ndarray
|
Velocity field array. |
required |
dudx
|
ndarray
|
Velocity gradient array. |
required |
tke_sgs
|
ndarray | float
|
Current subgrid TKE array. |
required |
dt
|
float
|
Current time step size for TKE tendency integration. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with 'tau' (SGS stress), 'coeff' (c1), |
dict[str, Any]
|
and 'tke_sgs' (updated subgrid TKE). |