pyturbo_sf package

Submodules

pyturbo_sf.bessel_tools module

Energy Flux Decomposition Tools (2D only)

Computes spectral energy flux from advective structure functions using Bessel function decomposition:

Π(K) = -K/2 ∫₀^∞ SF̃(r) J₁(Kr) dr

where SF̃(r) is the angle-averaged advective structure function and J₁ is the Bessel function of the first kind, order 1.

Reference: Plancherel theorem relating energy flux to real-space integral involving advective SF and J₁ Bessel function.

pyturbo_sf.bessel_tools._validate_flux_function(fun)[source]

Validate that the structure function type is appropriate for energy flux.

Parameters:

fun (str) – Structure function type.

Raises:

ValueError – If fun is not in VALID_FLUX_FUNCTIONS.

pyturbo_sf.bessel_tools._initialize_wavenumbers_2d(wavenumbers, ds, dims)[source]

Initialize wavenumber configuration.

Parameters:
  • wavenumbers (array-like, dict, or None) – Wavenumber specification.

  • ds (xarray.Dataset) – Input dataset for determining domain size.

  • dims (list) – Dimension names.

Returns:

Configuration with ‘k’ (wavenumbers) and metadata.

Return type:

dict

pyturbo_sf.bessel_tools._initialize_r_bins_2d(r_bins, ds, dims, n_r_bins=100)[source]

Initialize radial bin configuration for angle-averaging.

Parameters:
  • r_bins (array-like or None) – Radial bin edges. If None, auto-generate.

  • ds (xarray.Dataset) – Input dataset for determining domain size.

  • dims (list) – Dimension names.

  • n_r_bins (int) – Number of radial bins if auto-generating. Default is 100.

Returns:

Configuration with ‘r_edges’, ‘r_centers’, ‘dr’.

Return type:

dict

pyturbo_sf.bessel_tools._initialize_flux_config_2d(k, r_config, n_bins_theta)[source]

Initialize energy flux configuration.

Parameters:
  • k (array) – Wavenumber values.

  • r_config (dict) – Radial bin configuration from _initialize_r_bins_2d.

  • n_bins_theta (int) – Number of angular bins for isotropy diagnostics.

Returns:

Configuration dictionary.

Return type:

dict

pyturbo_sf.bessel_tools._bin_sf_by_radius_2d(results, dx_vals, dy_vals, r_config, theta_bins=None)[source]

Bin structure function values by radius to get angle-averaged SF(r).

This computes SF̃(r) = (1/2π) ∫₀^{2π} SF(r,θ) dθ

Parameters:
  • results (array) – Structure function values (flattened).

  • dx_vals (array) – X-separations (flattened).

  • dy_vals (array) – Y-separations (flattened).

  • r_config (dict) – Radial bin configuration.

  • theta_bins (array, optional) – Angular bin edges for isotropy diagnostics.

Returns:

  • sf_r (array) – Angle-averaged SF at each radial bin center (n_r,).

  • sf_r_std (array) – Standard deviation in each radial bin (n_r,).

  • counts_r (array) – Number of points in each radial bin (n_r,).

  • sf_theta_r (array or None) – SF binned by (theta, r) if theta_bins provided, else None.

pyturbo_sf.bessel_tools._compute_energy_flux_2d(sf_r, r_centers, dr, k)[source]

Compute energy flux using Bessel J₁ transform.

Π(K) = -K/2 ∫₀^∞ SF̃(r) J₁(Kr) dr

≈ -K/2 Σᵢ SF̃(rᵢ) J₁(K·rᵢ) Δrᵢ

Parameters:
  • sf_r (array) – Angle-averaged structure function at radial bin centers (n_r,).

  • r_centers (array) – Radial bin centers (n_r,).

  • dr (array) – Radial bin widths (n_r,).

  • k (array) – Wavenumbers to evaluate at (n_k,).

Returns:

energy_flux – Energy flux Π(K) at each wavenumber (n_k,).

Return type:

array

pyturbo_sf.bessel_tools._process_no_bootstrap_flux_2d(ds, dims, variables_names, order, fun, k, r_config, n_theta, time_dims, conditioning_var=None, conditioning_bins=None)[source]

Handle the special case of no bootstrappable dimensions for energy flux.

Parameters:
  • ds (xarray.Dataset) – Input dataset.

  • dims (list) – Dimension names.

  • variables_names (list) – Variable names for SF calculation.

  • order (float) – SF order (should be 1 for advective).

  • fun (str) – Function type (‘advective’ or ‘scalar_scalar’).

  • k (array) – Wavenumbers.

  • r_config (dict) – Radial bin configuration.

  • n_theta (int) – Number of angular bins.

  • time_dims (list) – Time dimension names.

  • conditioning_var (str, optional) – Conditioning variable name.

  • conditioning_bins (array, optional) – Conditioning bin edges.

Returns:

  • energy_flux (array) – Energy flux at each wavenumber (n_k,).

  • flux_stds (array) – Standard deviation estimates (n_k,).

  • point_counts (array) – Point counts per wavenumber (n_k,).

  • flux_theta_k (array) – Angular distribution of flux (n_theta, n_k).

  • config (dict) – Configuration dictionary.

pyturbo_sf.bessel_tools._calculate_isotropy_error_flux_2d(flux_theta_k, energy_flux, window_size_theta)[source]

Calculate isotropy error for energy flux.

Parameters:
  • flux_theta_k (array) – Angular distribution of flux (n_theta, n_k).

  • energy_flux (array) – Angle-averaged flux (n_k,).

  • window_size_theta (int) – Window size for sliding average.

Returns:

eiso – Isotropy error at each wavenumber (n_k,).

Return type:

array

pyturbo_sf.bessel_tools._calculate_homogeneity_error_flux_2d(flux_theta_k, window_size_k)[source]

Calculate homogeneity error for energy flux.

Parameters:
  • flux_theta_k (array) – Angular distribution of flux (n_theta, n_k).

  • window_size_k (int) – Window size for sliding average.

Returns:

  • ehom (array) – Homogeneity error at subset of wavenumbers.

  • k_subset_indices (array) – Indices of wavenumbers in subset.

pyturbo_sf.bessel_tools._calculate_wavenumber_density_2d(point_counts, k)[source]

Calculate normalized wavenumber density.

pyturbo_sf.bessel_tools._create_flux_dataset_2d(results, config, order, fun, window_size_theta, window_size_k, convergence_eps, max_nbootstrap, initial_nbootstrap, bootstrappable_dims, backend, variables_names, confidence_interval, conditioning_info=None)[source]

Create output xarray Dataset for energy flux.

Parameters:
  • results (dict) – Results dictionary containing: - energy_flux: Energy flux at each wavenumber - flux_stds: Standard deviations - point_counts: Point counts per wavenumber - flux_theta_k: Angular distribution - bin_bootstraps, bin_status, etc.

  • config (dict) – Configuration dictionary.

  • order (float) – Structure function order.

  • fun (str) – Function type.

  • window_size_theta (int) – Window size for isotropy error.

  • window_size_k (int) – Window size for homogeneity error.

  • convergence_eps (float) – Convergence epsilon.

  • max_nbootstrap (int) – Maximum bootstrap iterations.

  • initial_nbootstrap (int) – Initial bootstrap iterations.

  • bootstrappable_dims (list) – Bootstrappable dimension names.

  • backend (str) – Parallel backend.

  • variables_names (list) – Variable names.

  • confidence_interval (float) – Confidence level.

  • conditioning_info (dict, optional) – Conditioning information.

Returns:

Dataset with energy flux results.

Return type:

xarray.Dataset

pyturbo_sf.binning_tools module

Binning Tools

pyturbo_sf.binning_tools._get_bin_indices_with_range_check(values, bin_edges, n_bins)[source]

Get bin indices with proper handling of edge cases.

Unlike np.clip(np.digitize(…) - 1, 0, n_bins - 1) which forces out-of-range values into edge bins, this function: 1. Properly handles values exactly at the last bin edge (includes them) 2. Returns a mask indicating which values are in range 3. Returns bin indices (only valid where in_range_mask is True)

Parameters:
  • values (array) – Values to bin

  • bin_edges (array) – Bin edge values

  • n_bins (int) – Number of bins (len(bin_edges) - 1)

Returns:

  • bin_idx (array) – Bin indices (only valid where in_range_mask is True)

  • in_range_mask (array) – Boolean mask indicating which values are within bin range

pyturbo_sf.binning_tools._initialize_1d_bins(bin_edges, dim_name)[source]

Initialize 1D bin configuration.

Parameters:
  • bin_edges (array) – Bin edges

  • dim_name (str) – Dimension name

Returns:

config – Dictionary with bin configuration including: - bin_edges: bin edges - bin_centers: bin centers - n_bins: number of bins - log_bins: whether bins are logarithmic

Return type:

dict

pyturbo_sf.binning_tools._process_no_bootstrap_1d(ds, dim_name, variables_names, order, fun, bins_config, conditioning_var=None, conditioning_bins=None)[source]

Handle the special case of no bootstrappable dimensions for 1D.

Parameters:
  • ds (xarray.Dataset) – Dataset containing scalar fields

  • dim_name (str) – Name of the dimension

  • variables_names (list) – List of variable names

  • order (float or tuple) – Order(s) of the structure function

  • fun (str) – Type of structure function

  • bins_config (dict) – Bin configuration from _initialize_1d_bins

  • conditioning_var (str, optional) – Name of conditioning variable in dataset

  • conditioning_bins (tuple, optional) – (T_lo, T_hi) bounds for conditioning

Returns:

  • sf_means (array) – Weighted means

  • sf_stds (array) – Standard deviations

  • point_counts (array) – Point counts per bin

pyturbo_sf.binning_tools._calculate_bin_density_1d(point_counts, bin_edges)[source]

Calculate normalized bin density for 1D case.

Parameters:
  • point_counts (array) – Number of points in each bin

  • bin_edges (array) – Bin edges

Returns:

bin_density – Normalized density (0 to 1)

Return type:

array

pyturbo_sf.binning_tools._create_1d_dataset(results, bins_config, dim_name, order, fun, bootstrappable_dims, convergence_eps, max_nbootstrap, initial_nbootstrap, confidence_level, backend)[source]

Create output dataset for 1D binning.

Parameters:
  • results (dict) – Results from adaptive bootstrap loop

  • bins_config (dict) – Bin configuration

  • dim_name (str) – Dimension name

  • order (str) – Order of structure function

  • fun (str) – Function type

  • bootstrappable_dims (list) – List of bootstrappable dimensions

  • convergence_eps (float) – Convergence epsilon

  • max_nbootstrap (int) – Maximum bootstraps

  • initial_nbootstrap (int) – Initial bootstraps

  • confidence_level (float) – Confidence level for intervals

  • backend (str) – Backend used

Returns:

ds_binned – Binned structure function dataset

Return type:

xarray.Dataset

pyturbo_sf.binning_tools._initialize_2d_bins(bins_x, bins_y, dims_order)[source]

Initialize 2D bin configuration.

Returns:

config – Dictionary with bin configuration including: - bins_x, bins_y: bin edges - x_centers, y_centers: bin centers - n_bins_x, n_bins_y: number of bins - log_bins_x, log_bins_y: whether bins are logarithmic

Return type:

dict

pyturbo_sf.binning_tools._process_no_bootstrap_2d(ds, dims, variables_names, order, fun, bins, time_dims, conditioning_var=None, conditioning_bins=None)[source]

Handle the special case of no bootstrappable dimensions for 2D.

Returns:

  • sf_means (array) – Weighted means

  • sf_stds (array) – Standard deviations

  • point_counts (array) – Point counts per bin

  • bins_config (dict) – Bin configuration

pyturbo_sf.binning_tools._calculate_bin_density_2d(point_counts, bins_x, bins_y)[source]

Calculate normalized bin density for 2D case.

pyturbo_sf.binning_tools._create_2d_dataset(results, bins_config, dims, order, fun, bootstrappable_dims, time_dims, convergence_eps, max_nbootstrap, initial_nbootstrap, backend, confidence_level=0.95)[source]

Create output dataset for 2D binning.

pyturbo_sf.binning_tools._initialize_3d_bins(bins_x, bins_y, bins_z, dims_order)[source]

Initialize 3D bin configuration.

Returns:

config – Dictionary with bin configuration including: - bins_x, bins_y, bins_z: bin edges - x_centers, y_centers, z_centers: bin centers - n_bins_x, n_bins_y, n_bins_z: number of bins - log_bins_x, log_bins_y, log_bins_z: whether bins are logarithmic

Return type:

dict

pyturbo_sf.binning_tools._process_no_bootstrap_3d(ds, dims, variables_names, order, fun, bins, time_dims, conditioning_var=None, conditioning_bins=None)[source]

Handle the special case of no bootstrappable dimensions for 3D.

Returns:

  • sf_means (array) – Weighted means

  • sf_stds (array) – Standard deviations

  • point_counts (array) – Point counts per bin

  • bins_config (dict) – Bin configuration

pyturbo_sf.binning_tools._calculate_bin_density_3d(point_counts, bins_x, bins_y, bins_z)[source]

Calculate normalized bin density for 3D case.

pyturbo_sf.binning_tools._create_3d_dataset(results, bins_config, dims, order, fun, bootstrappable_dims, time_dims, convergence_eps, max_nbootstrap, initial_nbootstrap, backend, variables_names, confidence_level=0.95)[source]

Create output dataset for 3D binning.

pyturbo_sf.bootstrapping_tools module

Bootstrapping Tools

pyturbo_sf.bootstrapping_tools._compute_weighted_bootstrap_stats(bootstrap_samples, confidence_level=0.95)[source]

Compute bootstrap statistics with proper effective sample size correction.

Parameters:
  • bootstrap_samples (list of dict) – Each dict contains ‘mean’ and ‘weight’ (number of points in that bootstrap)

  • confidence_level (float) – Confidence level for intervals (default: 0.95)

Returns:

  • theta_hat (float) – Point estimate (weighted mean of bootstrap means)

  • std_error (float) – Bootstrap standard error with effective sample size correction

  • ci_lower (float) – Lower confidence interval bound (theta_hat - z * SE)

  • ci_upper (float) – Upper confidence interval bound (theta_hat + z * SE)

Notes

The standard error is computed using effective sample size:

  1. n_eff = (sum(w))^2 / sum(w^2)

  2. var_corrected = var_weighted * n_eff / (n_eff - 1) [Bessel correction]

  3. SE = sqrt(var_corrected / n_eff)

This properly accounts for: - Unequal weights in bootstrap samples - Bias correction (Bessel’s correction) - Variance of the mean (not variance of data)

pyturbo_sf.bootstrapping_tools.run_bootstrap_sf_1d(args)[source]

Standalone bootstrap function for parallel processing.

pyturbo_sf.bootstrapping_tools.monte_carlo_simulation_1d(ds, dim, variables_names, order, nbootstrap, bootsize, num_bootstrappable, all_spacings, boot_indexes, fun='scalar', spacing=None, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, seed=None)[source]

Run Monte Carlo simulation for structure function calculation with multiple bootstrap samples.

Parameters:

seed (int, optional) – Random seed for reproducibility. If None, uses random state.

pyturbo_sf.bootstrapping_tools._process_spacing_data_batch_1d(sf_results, separations, bin_edges, n_bins, bin_accumulators, point_counts, bin_spacing_counts, sp_value, bin_list, add_to_counts=True, pair_counts_results=None)[source]

Process structure function data for a specific spacing value with batch processing.

FIXED: Now records each bootstrap mean independently rather than incrementally. Each bootstrap iteration produces one mean estimate per bin. Uses pair_counts for proper weighting when combining separations into bins.

pyturbo_sf.bootstrapping_tools._calculate_bootstrap_statistics_1d(bin_accumulators, n_bins, confidence_level=0.95)[source]

Calculate weighted means, bootstrap standard errors, and CIs for 1D bins.

Parameters:
  • bin_accumulators (dict) – Accumulator dictionary with bin indices as keys

  • n_bins (int) – Number of bins

  • confidence_level (float) – Confidence level for intervals

Returns:

  • sf_means (array) – Weighted means

  • sf_stds (array) – Bootstrap standard errors

  • ci_lower (array) – Lower confidence interval bounds

  • ci_upper (array) – Upper confidence interval bounds

pyturbo_sf.bootstrapping_tools._evaluate_convergence_1d(sf_stds, point_counts, bin_bootstraps, convergence_eps, max_bootstraps)[source]

Evaluate which bins have converged.

Parameters:
  • sf_stds (array) – Standard deviations

  • point_counts (array) – Point counts

  • bin_bootstraps (array) – Number of bootstraps per bin

  • convergence_eps (float) – Convergence threshold

  • max_bootstraps (int) – Maximum number of bootstraps

Returns:

  • converged (array) – Boolean array indicating converged bins

  • convergence_reasons (dict) – Dictionary mapping reason to count

pyturbo_sf.bootstrapping_tools._group_bins_for_iteration_1d(unconverged_indices, bin_density, bootstrap_steps)[source]

Group unconverged bins by similar characteristics.

Parameters:
  • unconverged_indices (array) – Indices of unconverged bins

  • bin_density (array) – Normalized bin density

  • bootstrap_steps (array) – Step sizes for each bin

Returns:

groups – Dictionary mapping (step, density_quartile) to list of bin indices

Return type:

dict

pyturbo_sf.bootstrapping_tools._get_spacing_distribution_1d(bin_list, spacing_effectiveness, total_bootstraps, spacing_values)[source]

Determine optimal distribution of bootstraps across spacings.

Parameters:
  • bin_list (list) – List of bins to process

  • spacing_effectiveness (dict) – Effectiveness scores for each spacing

  • total_bootstraps (int) – Total bootstraps to distribute

  • spacing_values (list) – Available spacing values

Returns:

distribution – List of (spacing, bootstraps) tuples

Return type:

list

pyturbo_sf.bootstrapping_tools._update_spacing_effectiveness_1d(bin_spacing_effectiveness, bin_spacing_counts, bin_spacing_bootstraps, sp_value, bin_list, bootstraps)[source]

Update spacing effectiveness metrics.

Parameters:
  • bin_spacing_effectiveness (dict) – Effectiveness scores

  • bin_spacing_counts (dict) – Point counts

  • bin_spacing_bootstraps (dict) – Bootstrap counts

  • sp_value (int) – Current spacing value

  • bin_list (list) – Bins that were processed

  • bootstraps (int) – Number of bootstraps run

pyturbo_sf.bootstrapping_tools._run_adaptive_bootstrap_loop_1d(ds, dim_name, variables_names, order, fun, bins_config, initial_nbootstrap, max_nbootstrap, step_nbootstrap, convergence_eps, spacing_values, bootsize_dict, num_bootstrappable, all_spacings, boot_indexes, n_jobs, backend, conditioning_var=None, conditioning_bins=None, confidence_level=0.95, seed=None)[source]

Run adaptive bootstrap loop for 1D structure function binning.

This is the main workhorse function that handles the iterative bootstrap refinement process.

Parameters:
  • confidence_level (float, optional) – Confidence level for intervals. Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility.

pyturbo_sf.bootstrapping_tools.run_bootstrap_sf_2d(args)[source]

Standalone bootstrap function for parallel processing in 2D.

pyturbo_sf.bootstrapping_tools.monte_carlo_simulation_2d(ds, dims, variables_names, order, nbootstrap, bootsize, num_bootstrappable, all_spacings, boot_indexes, bootstrappable_dims, fun='longitudinal', spacing=None, n_jobs=-1, backend='threading', time_dims=None, conditioning_var=None, conditioning_bins=None, seed=None)[source]

Run Monte Carlo simulation for structure function calculation with multiple bootstrap samples.

Parameters:
  • ds (xarray.Dataset) – Dataset containing velocity components and/or scalar fields

  • dims (list) – List of dimension names

  • variables_names (list) – List of variable names to use, depends on function type

  • order (int or tuple) – Order(s) of the structure function

  • nbootstrap (int) – Number of bootstrap samples

  • bootsize (dict) – Dictionary with dimensions as keys and bootsize as values

  • num_bootstrappable (int) – Number of bootstrappable dimensions

  • all_spacings (list) – List of all spacing values

  • boot_indexes (dict) – Dictionary with spacing values as keys and boot indexes as values

  • bootstrappable_dims (list) – List of bootstrappable dimensions

  • fun (str, optional) – Type of structure function

  • spacing (int or dict, optional) – Spacing value to use

  • n_jobs (int, optional) – Number of jobs for parallel processing

  • backend (str, optional) – Backend for parallel processing

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

  • seed (int, optional) – Random seed for reproducibility

Returns:

Lists of structure function values, DX values, DY values

Return type:

list, list, list

pyturbo_sf.bootstrapping_tools._process_bootstrap_batch_2d(sf_results, dx_vals, dy_vals, bins_x, bins_y, bin_accumulators, target_bins, point_counts=None, spacing_counts=None, sp_value=None, add_to_counts=True, pair_counts_results=None)[source]

Process a batch of bootstrap results for 2D Cartesian binning.

FIXED: Now records each bootstrap mean independently rather than incrementally. Each bootstrap iteration produces one mean estimate per bin.

Parameters:
  • sf_results (list) – Structure function results from monte carlo simulation

  • dx_vals (list) – Separation distances for each bootstrap

  • dy_vals (list) – Separation distances for each bootstrap

  • bins_x (array) – Bin edges for x and y dimensions

  • bins_y (array) – Bin edges for x and y dimensions

  • bin_accumulators (dict) – Accumulator dictionary with keys (j, i)

  • target_bins (set) – Set of (j, i) tuples for bins to process

  • point_counts (array, optional) – Array to update with point counts

  • spacing_counts (dict, optional) – Dictionary of spacing counts to update

  • sp_value (int, optional) – Current spacing value

  • add_to_counts (bool) – Whether to update counts

  • pair_counts_results (list, optional) – List of pair counts arrays from structure function calculations.

Returns:

updated_bins – Set of bins that were updated

Return type:

set

pyturbo_sf.bootstrapping_tools._process_bootstrap_batch_polar_2d(sf_results, dx_vals, dy_vals, r_bins, theta_bins, bin_accumulators, angular_accumulators, target_r_bins, point_counts=None, spacing_counts=None, sp_value=None, add_to_counts=True, pair_counts_results=None)[source]

Process a batch of bootstrap results for polar binning.

FIXED: Now records each bootstrap mean independently rather than incrementally. Each bootstrap iteration produces one mean estimate per radial bin.

Parameters:
  • sf_results (list) – Structure function results

  • dx_vals (list) – Separation distances

  • dy_vals (list) – Separation distances

  • r_bins (array) – Radial bin edges

  • theta_bins (array) – Angular bin edges

  • bin_accumulators (dict) – Radial accumulator with keys as r_idx

  • angular_accumulators (dict) – Angular accumulator with keys as (theta_idx, r_idx)

  • target_r_bins (set) – Set of radial bin indices to process

  • point_counts (array, optional) – Array to update with counts

  • spacing_counts (dict, optional) – Dictionary of spacing counts

  • sp_value (int, optional) – Current spacing value

  • add_to_counts (bool) – Whether to update counts

  • pair_counts_results (list, optional) – List of pair counts arrays from structure function calculations. Each element corresponds to a bootstrap iteration.

Returns:

updated_r_bins – Set of r bins that were updated

Return type:

set

pyturbo_sf.bootstrapping_tools._process_bootstrap_batch_flux_2d(sf_results, dx_vals, dy_vals, config, k_accumulators, angular_accumulators, r_accumulators, target_k_set, point_counts, spacing_counts, sp_value, update_counts)[source]

Process a batch of bootstrap results for energy flux computation.

This function: 1. Bins SF values by radius to get angle-averaged SF̃(r) 2. Computes energy flux Π(K) = -K/2 ∫ SF̃(r) J₁(Kr) dr

Parameters:
  • sf_results (list of arrays) – Structure function values from each bootstrap.

  • dx_vals (list of arrays) – Separation distances from each bootstrap.

  • dy_vals (list of arrays) – Separation distances from each bootstrap.

  • config (dict) – Configuration with ‘k’, ‘r_centers’, ‘dr’, ‘theta_bins’, etc.

  • k_accumulators (dict) – Accumulators for wavenumber statistics (energy flux).

  • angular_accumulators (dict) – Accumulators for angular-wavenumber statistics.

  • r_accumulators (dict) – Accumulators for radial SF statistics.

  • target_k_set (set) – Set of wavenumber indices to process.

  • point_counts (array or None) – Point counts to update (if update_counts is True).

  • spacing_counts (dict) – Counts per spacing.

  • sp_value (int) – Current spacing value.

  • update_counts (bool) – Whether to update point counts.

pyturbo_sf.bootstrapping_tools._calculate_bootstrap_statistics_2d(bin_accumulators, bin_shape)[source]

Calculate weighted means and bootstrap standard errors for 2D bins.

Parameters:
  • bin_accumulators (dict) – Accumulator dictionary with keys (j, i)

  • bin_shape (tuple) – Shape of output arrays (ny, nx)

Returns:

  • sf_means (array) – Weighted means

  • sf_stds (array) – Bootstrap standard errors

pyturbo_sf.bootstrapping_tools._calculate_bootstrap_statistics_polar_2d(bin_accumulators, angular_accumulators, n_bins_r, n_bins_theta, confidence_level=0.95)[source]

Calculate statistics for polar binning with CI support.

Returns:

  • sf_means (array) – Radial means

  • sf_stds (array) – Radial standard errors

  • ci_lower (array) – Lower confidence interval bounds

  • ci_upper (array) – Upper confidence interval bounds

  • sfr (array) – Angular-radial structure function

  • sfr_counts (array) – Counts for angular-radial bins

pyturbo_sf.bootstrapping_tools._calculate_bootstrap_statistics_flux_2d(k_accumulators, angular_accumulators, r_accumulators, n_k, n_theta, n_r, confidence_level=0.95)[source]

Calculate statistics from energy flux accumulators with CI support.

Parameters:
  • k_accumulators (dict) – Accumulators for wavenumber (flux) statistics.

  • angular_accumulators (dict) – Accumulators for angular-wavenumber statistics.

  • r_accumulators (dict) – Accumulators for radial SF statistics.

  • n_k (int) – Number of wavenumbers.

  • n_theta (int) – Number of angular bins.

  • n_r (int) – Number of radial bins.

  • confidence_level (float) – Confidence level for intervals.

Returns:

  • energy_flux (array) – Energy flux at each wavenumber.

  • flux_stds (array) – Standard errors.

  • ci_lower, ci_upper (array) – Confidence interval bounds.

  • flux_theta_k (array) – Angular distribution of flux.

  • flux_theta_k_counts (array) – Counts for angular-wavenumber bins.

  • sf_r (array) – Angle-averaged structure function.

pyturbo_sf.bootstrapping_tools._update_spacing_effectiveness_flux_2d(bin_spacing_effectiveness, bin_spacing_counts, bin_spacing_bootstraps, sp_value, k_indices, bootstraps)[source]

Update spacing effectiveness for energy flux calculation.

pyturbo_sf.bootstrapping_tools._update_spacing_effectiveness_2d(bin_spacing_effectiveness, bin_spacing_counts, bin_spacing_bootstraps, sp_value, bin_indices, bootstraps)[source]

Update spacing effectiveness metrics.

Parameters:
  • bin_spacing_effectiveness (dict) – Effectiveness scores for each spacing

  • bin_spacing_counts (dict) – Point counts for each spacing

  • bin_spacing_bootstraps (dict) – Bootstrap counts for each spacing

  • sp_value (int) – Current spacing value

  • bin_indices (list) – Bins that were processed

  • bootstraps (int) – Number of bootstraps run

pyturbo_sf.bootstrapping_tools._evaluate_convergence_2d(sf_stds, point_counts, bin_bootstraps, convergence_eps, max_bootstraps)[source]

Evaluate which bins have converged.

Returns:

  • converged (array) – Boolean array indicating converged bins

  • convergence_reasons (dict) – Dictionary mapping reason to count

pyturbo_sf.bootstrapping_tools._evaluate_convergence_flux_2d(sf_stds, point_counts, bin_bootstraps, convergence_eps, max_bootstraps)[source]

Evaluate convergence for energy flux (wavenumber) case.

pyturbo_sf.bootstrapping_tools._group_bins_for_iteration_2d(unconverged_indices, bin_density, bootstrap_steps)[source]

Group unconverged bins by similar characteristics.

Returns:

groups – Dictionary mapping (step, density_quartile) to list of bin indices

Return type:

dict

pyturbo_sf.bootstrapping_tools._group_wavenumbers_for_iteration_2d(unconverged_indices, bin_density, bootstrap_steps)[source]

Group unconverged wavenumbers by characteristics.

pyturbo_sf.bootstrapping_tools._get_spacing_distribution_2d(bin_list, spacing_effectiveness, total_bootstraps, spacing_values)[source]

Determine optimal distribution of bootstraps across spacings.

Parameters:
  • bin_list (list) – List of bins to process

  • spacing_effectiveness (dict) – Effectiveness scores for each spacing

  • total_bootstraps (int) – Total bootstraps to distribute

  • spacing_values (list) – Available spacing values

Returns:

distribution – List of (spacing, bootstraps) tuples

Return type:

list

pyturbo_sf.bootstrapping_tools._get_spacing_distribution_flux_2d(k_list, spacing_effectiveness, total_bootstraps, spacing_values)[source]

Determine spacing distribution for energy flux case.

pyturbo_sf.bootstrapping_tools._run_adaptive_bootstrap_loop_2d(valid_ds, dims, variables_names, order, fun, bins_config, initial_nbootstrap, max_nbootstrap, step_nbootstrap, convergence_eps, spacing_values, bootsize_dict, num_bootstrappable, all_spacings, boot_indexes, bootstrappable_dims, n_jobs, backend, time_dims, conditioning_var, conditioning_bins, is_2d=True, confidence_level=0.95, seed=None)[source]

Generic adaptive bootstrap loop used by both 2D and isotropic functions.

This function now handles both 2D and polar cases internally.

Parameters:
  • confidence_level (float, optional) – Confidence level for intervals. Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility.

pyturbo_sf.bootstrapping_tools._run_adaptive_bootstrap_loop_flux_2d(valid_ds, dims, variables_names, order, fun, config, initial_nbootstrap, max_nbootstrap, step_nbootstrap, convergence_eps, spacing_values, bootsize_dict, num_bootstrappable, all_spacings, boot_indexes, bootstrappable_dims, n_jobs, backend, time_dims, conditioning_var, conditioning_bins, confidence_level=0.95, seed=None)[source]

Adaptive bootstrap loop for energy flux computation.

Computes Π(K) = -K/2 ∫ SF̃(r) J₁(Kr) dr using: 1. Radial binning to get angle-averaged SF̃(r) 2. J₁ Bessel transform to get energy flux Π(K)

Parameters:
  • confidence_level (float, optional) – Confidence level for intervals. Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility.

pyturbo_sf.bootstrapping_tools.run_bootstrap_sf_3d(args)[source]

Standalone bootstrap function for parallel processing in 3D.

pyturbo_sf.bootstrapping_tools.monte_carlo_simulation_3d(ds, dims, variables_names, order, nbootstrap, bootsize, num_bootstrappable, all_spacings, boot_indexes, bootstrappable_dims, fun='longitudinal', spacing=None, n_jobs=-1, backend='threading', time_dims=None, conditioning_var=None, conditioning_bins=None, seed=None)[source]

Run Monte Carlo simulation for structure function calculation with multiple bootstrap samples.

Parameters:
  • ds (xarray.Dataset) – Dataset containing velocity components and/or scalar fields

  • dims (list) – List of dimension names

  • variables_names (list) – List of variable names to use, depends on function type

  • order (int or tuple) – Order(s) of the structure function

  • nbootstrap (int) – Number of bootstrap samples

  • bootsize (dict) – Dictionary with dimensions as keys and bootsize as values

  • num_bootstrappable (int) – Number of bootstrappable dimensions

  • all_spacings (list) – List of all spacing values

  • boot_indexes (dict) – Dictionary with spacing values as keys and boot indexes as values

  • bootstrappable_dims (list) – List of bootstrappable dimensions

  • fun (str, optional) – Type of structure function

  • spacing (int or dict, optional) – Spacing value to use

  • n_jobs (int, optional) – Number of jobs for parallel processing

  • backend (str, optional) – Backend for parallel processing

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

  • seed (int, optional) – Random seed for reproducibility

Returns:

Lists of structure function values, DX values, DY values, DZ values, pair_counts

Return type:

list, list, list, list, list

pyturbo_sf.bootstrapping_tools._process_bootstrap_batch_3d(sf_results, dx_vals, dy_vals, dz_vals, bins_x, bins_y, bins_z, bin_accumulators, target_bins, point_counts=None, spacing_counts=None, sp_value=None, add_to_counts=True, pair_counts_results=None)[source]

Process a batch of bootstrap results for 3D Cartesian binning.

FIXED: Now records each bootstrap mean independently rather than incrementally. Each bootstrap iteration produces one mean estimate per bin. Uses pair_counts for proper weighting when combining separations into bins.

Parameters:
  • sf_results (list) – Structure function results from monte carlo simulation

  • dx_vals (list) – Separation distances for each bootstrap

  • dy_vals (list) – Separation distances for each bootstrap

  • dz_vals (list) – Separation distances for each bootstrap

  • bins_x (array) – Bin edges for x, y, and z dimensions

  • bins_y (array) – Bin edges for x, y, and z dimensions

  • bins_z (array) – Bin edges for x, y, and z dimensions

  • bin_accumulators (dict) – Accumulator dictionary with keys (k, j, i)

  • target_bins (set) – Set of (k, j, i) tuples for bins to process

  • point_counts (array, optional) – Array to update with point counts

  • spacing_counts (dict, optional) – Dictionary of spacing counts to update

  • sp_value (int, optional) – Current spacing value

  • add_to_counts (bool) – Whether to update counts

  • pair_counts_results (list, optional) – List of pair counts arrays from structure function calculations.

Returns:

updated_bins – Set of bins that were updated

Return type:

set

pyturbo_sf.bootstrapping_tools._process_bootstrap_batch_spherical_3d(sf_results, dx_vals, dy_vals, dz_vals, r_bins, theta_bins, phi_bins, bin_accumulators, angular_accumulators, target_r_bins, point_counts=None, spacing_counts=None, sp_value=None, add_to_counts=True, pair_counts_results=None)[source]

Process a batch of bootstrap results for spherical binning.

FIXED: Now records each bootstrap mean independently rather than incrementally. Each bootstrap iteration produces one mean estimate per radial bin. Uses pair_counts for proper weighting when combining separations into bins.

Parameters:
  • sf_results (list) – Structure function results

  • dx_vals (list) – Separation distances

  • dy_vals (list) – Separation distances

  • dz_vals (list) – Separation distances

  • r_bins (array) – Radial bin edges

  • theta_bins (array) – Azimuthal angular bin edges

  • phi_bins (array) – Polar angular bin edges

  • bin_accumulators (dict) – Radial accumulator with keys as r_idx

  • angular_accumulators (dict) – Angular accumulator with keys as (phi_idx, theta_idx, r_idx)

  • target_r_bins (set) – Set of radial bin indices to process

  • point_counts (array, optional) – Array to update with counts

  • spacing_counts (dict, optional) – Dictionary of spacing counts

  • sp_value (int, optional) – Current spacing value

  • add_to_counts (bool) – Whether to update counts

  • pair_counts_results (list, optional) – List of pair counts arrays from structure function calculations.

Returns:

updated_r_bins – Set of r bins that were updated

Return type:

set

pyturbo_sf.bootstrapping_tools._calculate_bootstrap_statistics_3d(bin_accumulators, bin_shape)[source]

Calculate weighted means and bootstrap standard errors for 3D bins.

Parameters:
  • bin_accumulators (dict) – Accumulator dictionary with keys (k, j, i)

  • bin_shape (tuple) – Shape of output arrays (nz, ny, nx)

Returns:

  • sf_means (array) – Weighted means

  • sf_stds (array) – Bootstrap standard errors

pyturbo_sf.bootstrapping_tools._calculate_bootstrap_statistics_spherical_3d(bin_accumulators, angular_accumulators, n_bins_r, n_bins_theta, n_bins_phi, confidence_level=0.95)[source]

Calculate statistics for spherical binning with CI support.

Returns:

  • sf_means (array) – Radial means

  • sf_stds (array) – Radial standard errors

  • ci_lower (array) – Lower confidence interval bounds

  • ci_upper (array) – Upper confidence interval bounds

  • sfr (array) – Angular-radial structure function

  • sfr_counts (array) – Counts for angular-radial bins

pyturbo_sf.bootstrapping_tools._update_spacing_effectiveness_3d(bin_spacing_effectiveness, bin_spacing_counts, bin_spacing_bootstraps, sp_value, bin_indices, bootstraps)[source]

Update spacing effectiveness metrics for 3D.

Parameters:
  • bin_spacing_effectiveness (dict) – Effectiveness scores for each spacing

  • bin_spacing_counts (dict) – Point counts for each spacing

  • bin_spacing_bootstraps (dict) – Bootstrap counts for each spacing

  • sp_value (int) – Current spacing value

  • bin_indices (list) – Bins that were processed

  • bootstraps (int) – Number of bootstraps run

pyturbo_sf.bootstrapping_tools._evaluate_convergence_3d(sf_stds, point_counts, bin_bootstraps, convergence_eps, max_bootstraps)[source]

Evaluate which bins have converged for 3D.

Returns:

  • converged (array) – Boolean array indicating converged bins

  • convergence_reasons (dict) – Dictionary mapping reason to count

pyturbo_sf.bootstrapping_tools._group_bins_for_iteration_3d(unconverged_indices, bin_density, bootstrap_steps)[source]

Group unconverged bins by similar characteristics for 3D.

Returns:

groups – Dictionary mapping (step, density_quartile) to list of bin indices

Return type:

dict

pyturbo_sf.bootstrapping_tools._group_wavenumbers_for_iteration_3d(unconverged_indices, bin_density, bootstrap_steps)[source]

Group unconverged wavenumbers by characteristics for 3D.

pyturbo_sf.bootstrapping_tools._get_spacing_distribution_3d(bin_list, spacing_effectiveness, total_bootstraps, spacing_values)[source]

Determine optimal distribution of bootstraps across spacings for 3D.

Parameters:
  • bin_list (list) – List of bins to process

  • spacing_effectiveness (dict) – Effectiveness scores for each spacing

  • total_bootstraps (int) – Total bootstraps to distribute

  • spacing_values (list) – Available spacing values

Returns:

distribution – List of (spacing, bootstraps) tuples

Return type:

list

pyturbo_sf.bootstrapping_tools._run_adaptive_bootstrap_loop_3d(valid_ds, dims, variables_names, order, fun, bins_config, initial_nbootstrap, max_nbootstrap, step_nbootstrap, convergence_eps, spacing_values, bootsize_dict, num_bootstrappable, all_spacings, boot_indexes, bootstrappable_dims, n_jobs, backend, time_dims, is_3d=True, conditioning_var=None, conditioning_bins=None, confidence_level=0.95, seed=None)[source]

Generic adaptive bootstrap loop used by both 3D and spherical functions.

This function handles both 3D Cartesian and spherical cases internally.

Parameters:
  • confidence_level (float, optional) – Confidence level for intervals. Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility.

pyturbo_sf.core module

Core functions for structure function calculations.

pyturbo_sf.core.is_time_dimension(dim, ds)[source]

Determine if a dimension is a time dimension.

Parameters:
  • dim (str) – Name of the dimension

  • ds (xarray.Dataset) – Dataset containing the dimension

Returns:

True if the dimension is a time dimension, False otherwise

Return type:

bool

pyturbo_sf.core._check_bootsize_power_of_2(dims, data_shape, bootsize_dict)[source]

Check if bootsize is data_size / power_of_2 and warn if not. Returns a dictionary of valid bootsizes for each dimension.

pyturbo_sf.core.validate_dataset_1d(ds)[source]

Validate that the dataset has a single dimension for 1D structure function analysis.

Parameters:

ds (xarray.Dataset) – Dataset containing scalar fields with a single dimension

Returns:

  • str – The name of the single dimension

  • dict – Dictionary of dimension names and sizes

Raises:

ValueError – If the dataset doesn’t have exactly one dimension

pyturbo_sf.core.validate_dataset_2d(ds)[source]

Validate the dataset has exactly 2 dimensions and detect if any are time dimensions.

Parameters:

ds (xarray.Dataset) – Dataset containing velocity components and/or scalar fields

Returns:

  • list – List of dimension names in correct order

  • dict – Dictionary with dimension names and sizes

  • xarray.Dataset – Potentially transposed dataset to ensure correct dimension order

  • dict – Dictionary indicating which dimensions are time dimensions

Raises:

ValueError – If dataset doesn’t have exactly 2 dimensions or dimensions are incompatible

pyturbo_sf.core.validate_dataset_3d(ds)[source]

Validate the dataset has exactly 3 dimensions and detect if any are time dimensions.

Parameters:

ds (xarray.Dataset) – Dataset containing velocity components and/or scalar fields

Returns:

  • list – List of dimension names in correct order

  • dict – Dictionary with dimension names and sizes

  • xarray.Dataset – Dataset with dimensions in the correct order

  • dict – Dictionary indicating which dimensions are time dimensions

Raises:

ValueError – If dataset doesn’t have exactly 3 dimensions or dimensions are incompatible

pyturbo_sf.core.setup_bootsize_1d(dim, data_shape, bootsize=None)[source]

Set up bootsize parameters for bootstrapping.

Parameters:
  • dim (str) – Name of the dataset dimension

  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict or int, optional) – Bootsize for the dimension. Can be a dictionary with dimension name as key, or a single integer to be used for the dimension.

Returns:

  • dict – Dictionary with dimension name as key and bootsize as value

  • list – List of bootstrappable dimensions

  • int – Number of bootstrappable dimensions

pyturbo_sf.core.setup_bootsize_2d(dims, data_shape, bootsize=None)[source]

Set up bootsize parameters for bootstrapping.

Parameters:
  • dims (list) – List of dimension names

  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict, optional) – Dictionary with dimensions as keys and bootsize as values

Returns:

  • dict – Dictionary with dimensions as keys and bootsize as values

  • list – List of bootstrappable dimensions

  • int – Number of bootstrappable dimensions

pyturbo_sf.core.setup_bootsize_3d(dims, data_shape, bootsize=None)[source]

Set up bootsize parameters for bootstrapping.

Parameters:
  • dims (list) – List of dimension names

  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict, optional) – Dictionary with dimensions as keys and bootsize as values

Returns:

  • dict – Dictionary with dimensions as keys and bootsize as values

  • list – List of bootstrappable dimensions

  • int – Number of bootstrappable dimensions

pyturbo_sf.core.calculate_adaptive_spacings_1d(dim, data_shape, bootsize, num_bootstrappable)[source]

Calculate adaptive spacings based on dimension size.

Parameters:
  • dim (str) – Name of the dataset dimension

  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict) – Dictionary with dimension name as key and bootsize as value

  • num_bootstrappable (int) – Number of bootstrappable dimensions

Returns:

  • dict – Dictionary with spacing information

  • list – List of all spacing values

pyturbo_sf.core.calculate_adaptive_spacings_2d(dims, data_shape, bootsize, bootstrappable_dims, num_bootstrappable)[source]

Calculate adaptive spacings based on dimension sizes.

Parameters:
  • dims (list) – List of dimension names

  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict) – Dictionary with dimensions as keys and bootsize as values

  • bootstrappable_dims (list) – List of bootstrappable dimensions

  • num_bootstrappable (int) – Number of bootstrappable dimensions

Returns:

  • dict – Dictionary with spacing information

  • list – List of all spacing values

pyturbo_sf.core._get_simplified_adaptive_spacings_2d(data_shape, bootsize)[source]

Calculate adaptive spacings based on dimension sizes. Uses shared spacings across all dimensions based on the most limiting dimension.

Parameters:
  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict) – Dictionary with dimensions as keys and bootsize as values

Returns:

Dictionary with ‘shared_spacings’ for all dimensions

Return type:

dict

pyturbo_sf.core.calculate_adaptive_spacings_3d(dims, data_shape, bootsize, bootstrappable_dims, num_bootstrappable)[source]

Calculate adaptive spacings based on dimension sizes.

Parameters:
  • dims (list) – List of dimension names

  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict) – Dictionary with dimensions as keys and bootsize as values

  • bootstrappable_dims (list) – List of bootstrappable dimensions

  • num_bootstrappable (int) – Number of bootstrappable dimensions

Returns:

  • dict – Dictionary with spacing information

  • list – List of all spacing values

pyturbo_sf.core._get_simplified_adaptive_spacings_3d(data_shape, bootsize, bootstrappable_dims)[source]

Calculate adaptive spacings based on dimension sizes. Uses shared spacings across all dimensions based on the most limiting dimension.

Parameters:
  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict) – Dictionary with dimensions as keys and bootsize as values

  • bootstrappable_dims (list) – List of bootstrappable dimensions

Returns:

Dictionary with ‘shared_spacings’ for all dimensions

Return type:

dict

pyturbo_sf.core.compute_boot_indexes_1d(dim, data_shape, bootsize, all_spacings, num_bootstrappable)[source]

Pre-compute boot indexes for all possible spacings to improve performance.

Parameters:
  • dim (str) – Name of the dataset dimension

  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict) – Dictionary with dimension name as key and bootsize as value

  • all_spacings (list) – List of all spacing values

  • num_bootstrappable (int) – Number of bootstrappable dimensions

Returns:

Dictionary with spacing values as keys and boot indexes as values

Return type:

dict

pyturbo_sf.core.get_boot_indexes_1d(dim, data_shape, bootsize, all_spacings, boot_indexes, num_bootstrappable, spacing=None)[source]

Get boot indexes for bootstrappable dimensions.

Parameters:
  • dim (str) – Name of the dataset dimension

  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict) – Dictionary with dimension name as key and bootsize as value

  • all_spacings (list) – List of all spacing values

  • boot_indexes (dict) – Dictionary with spacing values as keys and boot indexes as values

  • num_bootstrappable (int) – Number of bootstrappable dimensions

  • spacing (int or dict, optional) – Spacing value to use

Returns:

Dictionary with dimension name as key and boot indexes as values

Return type:

dict

pyturbo_sf.core.compute_boot_indexes_2d(dims, data_shape, bootsize, all_spacings, bootstrappable_dims)[source]

Pre-compute boot indexes for all possible spacings to improve performance.

Parameters:
  • dims (list) – List of dimension names

  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict) – Dictionary with dimensions as keys and bootsize as values

  • all_spacings (list) – List of all spacing values

  • bootstrappable_dims (list) – List of bootstrappable dimensions

Returns:

Dictionary with spacing values as keys and boot indexes as values

Return type:

dict

pyturbo_sf.core.get_boot_indexes_2d(dims, data_shape, bootsize, all_spacings, boot_indexes, bootstrappable_dims, num_bootstrappable, spacing=None)[source]

Get boot indexes for bootstrappable dimensions.

Parameters:
  • dims (list) – List of dimension names

  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict) – Dictionary with dimensions as keys and bootsize as values

  • all_spacings (list) – List of all spacing values

  • boot_indexes (dict) – Dictionary with spacing values as keys and boot indexes as values

  • bootstrappable_dims (list) – List of bootstrappable dimensions

  • num_bootstrappable (int) – Number of bootstrappable dimensions

  • spacing (int or dict, optional) – Spacing value to use

Returns:

Dictionary with dimension names as keys and boot indexes as values

Return type:

dict

pyturbo_sf.core.compute_boot_indexes_3d(dims, data_shape, bootsize, all_spacings, bootstrappable_dims)[source]

Pre-compute boot indexes for all possible spacings to improve performance.

Parameters:
  • dims (list) – List of dimension names

  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict) – Dictionary with dimensions as keys and bootsize as values

  • all_spacings (list) – List of all spacing values

  • bootstrappable_dims (list) – List of bootstrappable dimensions

Returns:

Dictionary with spacing values as keys and boot indexes as values

Return type:

dict

pyturbo_sf.core.get_boot_indexes_3d(dims, data_shape, bootsize, all_spacings, boot_indexes, bootstrappable_dims, num_bootstrappable, spacing=None)[source]

Get boot indexes for bootstrappable dimensions.

Parameters:
  • dims (list) – List of dimension names

  • data_shape (dict) – Dictionary with dimension sizes

  • bootsize (dict) – Dictionary with dimensions as keys and bootsize as values

  • all_spacings (list) – List of all spacing values

  • boot_indexes (dict) – Dictionary with spacing values as keys and boot indexes as values

  • bootstrappable_dims (list) – List of bootstrappable dimensions

  • num_bootstrappable (int) – Number of bootstrappable dimensions

  • spacing (int or dict, optional) – Spacing value to use

Returns:

Dictionary with dimension names as keys and boot indexes as values

Return type:

dict

pyturbo_sf.isotropy_tools module

Isotropization Tools

pyturbo_sf.isotropy_tools._initialize_polar_bins_2d(r_bins, n_theta)[source]

Initialize polar bin configuration.

Returns:

config – Dictionary with polar bin configuration

Return type:

dict

pyturbo_sf.isotropy_tools._process_no_bootstrap_polar_2d(ds, dims, variables_names, order, fun, r_bins, n_theta, time_dims, conditioning_var, conditioning_bins)[source]

Handle the special case of no bootstrappable dimensions for polar.

pyturbo_sf.isotropy_tools._calculate_bin_density_polar_2d(point_counts, r_bins)[source]

Calculate normalized bin density for polar case.

pyturbo_sf.isotropy_tools._create_isotropic_dataset(results, bins_config, order, fun, window_size_theta, window_size_r, convergence_eps, max_nbootstrap, initial_nbootstrap, bootstrappable_dims, backend, variables_names, confidence_interval, conditioning_info=None)[source]

Create output dataset for isotropic binning.

Parameters:
  • results (dict) – Results dictionary from bootstrap loop

  • bins_config (dict) – Bin configuration

  • conditioning_info (dict, optional) – If provided, contains ‘var_name’, ‘bins’, and ‘bin_idx’ for the conditioning variable. When present, adds a conditioning dimension to the dataset.

pyturbo_sf.isotropy_tools._calculate_isotropy_error_2d(sfr, sf_means, window_size_theta)[source]

Calculate error of isotropy using sliding windows.

pyturbo_sf.isotropy_tools._calculate_homogeneity_error_2d(sfr, window_size_r)[source]

Calculate error of homogeneity.

pyturbo_sf.isotropy_tools._initialize_spherical_bins_3d(r_bins, n_theta, n_phi)[source]

Initialize spherical bin configuration.

Returns:

config – Dictionary with spherical bin configuration

Return type:

dict

pyturbo_sf.isotropy_tools._process_no_bootstrap_spherical_3d(ds, dims, variables_names, order, fun, r_bins, n_theta, n_phi, time_dims, conditioning_var=None, conditioning_bins=None)[source]

Handle the special case of no bootstrappable dimensions for spherical.

pyturbo_sf.isotropy_tools._calculate_bin_density_spherical_3d(point_counts, r_bins)[source]

Calculate normalized bin density for spherical case.

pyturbo_sf.isotropy_tools._create_spherical_dataset(results, bins_config, order, fun, window_size_theta, window_size_phi, window_size_r, convergence_eps, max_nbootstrap, initial_nbootstrap, bootstrappable_dims, backend, variables_names, confidence_interval=0.95, conditioning_info=None)[source]

Create output dataset for spherical binning.

Parameters:

conditioning_info (dict, optional) – If provided, contains ‘var_name’, ‘bins’, and ‘bin_idx’ for the conditioning variable.

pyturbo_sf.isotropy_tools._calculate_isotropy_error_3d(sfr, sf_means, window_size_theta, window_size_phi)[source]

Calculate error of isotropy using sliding windows for 3D.

pyturbo_sf.isotropy_tools._calculate_homogeneity_error_3d(sfr, window_size_r)[source]

Calculate error of homogeneity for 3D.

pyturbo_sf.one_dimensional module

One-dimensional structure function calculations.

pyturbo_sf.one_dimensional.bin_sf_1d(ds, variables_names, order, bins, bootsize=None, fun='scalar', initial_nbootstrap=100, max_nbootstrap=1000, step_nbootstrap=100, convergence_eps=0.1, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, confidence_interval=0.95, seed=None)[source]

Bin structure function results with improved weighted statistics and memory efficiency.

Parameters:
  • ds (xarray.Dataset) – Dataset containing scalar fields

  • variables_names (list) – List of variable names to use, depends on function type

  • order (float or tuple) – Order(s) of the structure function

  • bins (dict) – Dictionary with dimension as key and bin edges as values

  • bootsize (dict or int, optional) – Bootsize for the dimension

  • fun (str, optional) – Type of structure function: [‘scalar’, ‘scalar_scalar’]

  • initial_nbootstrap (int, optional) – Initial number of bootstrap samples

  • max_nbootstrap (int, optional) – Maximum number of bootstrap samples

  • step_nbootstrap (int, optional) – Step size for increasing bootstrap samples

  • convergence_eps (float, optional) – Convergence threshold for bin standard deviation

  • n_jobs (int, optional) – Number of jobs for parallel processing

  • backend (str, optional) – Backend for joblib: ‘threading’, ‘multiprocessing’, or ‘loky’. Default is ‘threading’.

  • mask (str, optional) – Name of mask variable in dataset

  • conditioning_bins (tuple, optional) – Conditions for masking. If dict with ‘array’ and ‘shifted’ keys, creates separate indicators I_α and I_β. If list, applies same condition to both.

  • confidence_interval (float, optional) – Confidence level for intervals. Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility. Use same seed for conditioned and unconditioned runs to ensure point_counts partition correctly.

Returns:

Dataset with binned structure function results

Return type:

xarray.Dataset

pyturbo_sf.structure_functions module

List of All the structure functions.

pyturbo_sf.structure_functions.calc_scalar_1d(subset, dim, variable_name, order, n_points, conditioning_var=None, conditioning_bins=None)[source]

Calculate scalar structure function: (dscalar^n)

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • dim (str) – Name of the dimension

  • variable_name (str) – Name of the scalar variable

  • order (int) – Order of the structure function

  • n_points (int) – Number of points

  • conditioning_var (str, optional) – Name of variable to condition on (e.g., ‘vorticity’, ‘temperature’)

  • conditioning_bins (list, optional) – Bin edges [T_lo, T_hi] for conditioning variable.

Returns:

  • results (array) – Structure function values

  • separations (array) – Separation values

  • pair_counts (array) – Number of valid (origin, separation) pairs for each separation

pyturbo_sf.structure_functions.calc_scalar_scalar_1d(subset, dim, variables_names, order, n_points, conditioning_var=None, conditioning_bins=None)[source]

Calculate scalar-scalar structure function: (dscalar1^n * dscalar2^k)

With conditional masking: D_ss^(αβ)(x,r) = ⟨[δs1]^n [δs2]^k I_α(x)I_β(x+r)⟩ / P_αβ

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • dim (str) – Name of the dimension

  • variables_names (list) – List of variable names (should contain two scalar variables)

  • order (tuple) – Tuple of orders (n, k) for the structure function

  • n_points (int) – Number of points

  • conditioning_var (str, optional) – Name of variable to condition on (e.g., ‘vorticity’, ‘temperature’)

  • conditioning_bins (list, optional) – Bin edges [T_lo, T_hi] for conditioning variable.

Returns:

  • results (array) – Structure function values

  • separations (array) – Separation values

  • pair_counts (array) – Number of valid (origin, separation) pairs for each separation

pyturbo_sf.structure_functions.calculate_structure_function_1d(ds, dim, variables_names, order, fun='scalar', nb=0, spacing=None, num_bootstrappable=0, boot_indexes=None, bootsize=None, conditioning_var=None, conditioning_bins=None)[source]

Main function to calculate structure functions based on specified type.

Parameters:
  • ds (xarray.Dataset) – Dataset containing scalar fields

  • dim (str) – Name of the dimension

  • variables_names (list) – List of variable names to use, depends on function type

  • order (int or tuple) – Order(s) of the structure function

  • fun (str, optional) – Type of structure function: [‘scalar’, ‘scalar_scalar’]

  • nb (int, optional) – Bootstrap index

  • spacing (dict or int, optional) – Spacing value to use

  • num_bootstrappable (int, optional) – Number of bootstrappable dimensions

  • boot_indexes (dict, optional) – Dictionary with spacing values as keys and boot indexes as values

  • bootsize (dict, optional) – Dictionary with dimension name as key and bootsize as value

  • conditioning_var (str, optional) – Name of variable to condition on (e.g., ‘vorticity’, ‘temperature’)

  • conditioning_bins (list, optional) – Conditions for masking

Returns:

  • results (array) – Structure function values

  • separations (array) – Separation values

  • pair_counts (array) – Number of valid (origin, separation) pairs for each separation

pyturbo_sf.structure_functions.calc_longitudinal_2d(subset, variables_names, order, dims, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate longitudinal structure function: (du*dx + dv*dy)^n / |r|^n or (du*dx + dw*dz)^n / |r|^n or (dv*dy + dw*dz)^n / |r|^n depending on the plane.

With conditional masking: D_L^(αβ)(x,r) = ⟨[δu_L]^n I_α(x)I_β(x+r)⟩ / P_αβ

Returns:

  • results (array) – Mean SF value for each separation

  • dx_vals, dy_vals (array) – Mean separation distances

  • pair_counts (array) – Number of valid (origin, separation) pairs for each separation

pyturbo_sf.structure_functions.calc_transverse_2d(subset, variables_names, order, dims, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate transverse structure function: (du*dy - dv*dx)^n / |r|^n or (du*dz - dw*dx)^n / |r|^n or (dv*dz - dw*dy)^n / |r|^n depending on the plane.

With conditional masking: D_T^(αβ)(x,r) = ⟨[δu_T]^n I_α(x)I_β(x+r)⟩ / P_αβ

Return type:

results, dx_vals, dy_vals, pair_counts

pyturbo_sf.structure_functions.calc_default_vel_2d(subset, variables_names, order, dims, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate default velocity structure function with conditional masking.

D_ij^(αβ)(x,r) = ⟨[u_i(x+r) - u_i(x)][u_j(x+r) - u_j(x)]I_α(x)I_β(x+r)⟩ / P_αβ

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain 2 or 3 velocity components)

  • order (int) – Order of the structure function

  • dims (list) – List of dimension names

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

  • conditioning_var (str, optional) – Name of variable to condition on (e.g., ‘vorticity’, ‘temperature’)

  • conditioning_bins (list, optional) – Conditions for masking

Returns:

Structure function values, DX values, DY values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_scalar_2d(subset, variables_names, order, dims, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate scalar structure function: (dscalar^n)

With conditional masking: D_s^(αβ)(x,r) = ⟨[s(x+r) - s(x)]^n I_α(x)I_β(x+r)⟩ / P_αβ

pyturbo_sf.structure_functions.calc_scalar_scalar_2d(subset, variables_names, order, dims, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate scalar-scalar structure function: (dscalar1^n * dscalar2^k)

With conditional masking: D_s1s2^(αβ)(x,r) = ⟨[s1(x+r) - s1(x)]^n [s2(x+r) - s2(x)]^k I_α(x)I_β(x+r)⟩ / P_αβ

pyturbo_sf.structure_functions.calc_longitudinal_transverse_2d(subset, variables_names, order, dims, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate cross longitudinal-transverse structure function: (du_longitudinal^n * du_transverse^k)

With conditional masking: D_LT^(αβ)(x,r) = ⟨[δu_L]^n [δu_T]^k I_α(x)I_β(x+r)⟩ / P_αβ

pyturbo_sf.structure_functions.calc_longitudinal_scalar_2d(subset, variables_names, order, dims, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate cross longitudinal-scalar structure function: (du_longitudinal^n * dscalar^k)

With conditional masking: D_Ls^(αβ)(x,r) = ⟨[δu_L]^n [δs]^k I_α(x)I_β(x+r)⟩ / P_αβ

pyturbo_sf.structure_functions.calc_transverse_scalar_2d(subset, variables_names, order, dims, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate cross transverse-scalar structure function: (du_transverse^n * dscalar^k)

With conditional masking: D_Ts^(αβ)(x,r) = ⟨[δu_T]^n [δs]^k I_α(x)I_β(x+r)⟩ / P_αβ

pyturbo_sf.structure_functions.calc_advective_2d(subset, variables_names, order, dims, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate advective structure function: - 2D: (du*deltaadv_u + dv*deltaadv_v)^n - 3D: (du*deltaadv_u + dv*deltaadv_v + dw*deltaadv_w)^n

With conditional masking: D_adv^(αβ)(x,r) = ⟨[advective_term]^n I_α(x)I_β(x+r)⟩ / P_αβ

pyturbo_sf.structure_functions.calculate_structure_function_2d(ds, dims, variables_names, order, fun='longitudinal', nbx=0, nby=0, spacing=None, num_bootstrappable=0, bootstrappable_dims=None, boot_indexes=None, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Main function to calculate structure functions based on specified type.

Parameters:
  • ds (xarray.Dataset) – Dataset containing velocity components and/or scalar fields

  • dims (list) – List of dimension names

  • variables_names (list) – List of variable names to use, depends on function type

  • order (int or tuple) – Order(s) of the structure function

  • fun (str, optional) – Type of structure function

  • nbx (int, optional) – Bootstrap indices for x and y dimensions

  • nby (int, optional) – Bootstrap indices for x and y dimensions

  • spacing (dict or int, optional) – Spacing value to use

  • num_bootstrappable (int, optional) – Number of bootstrappable dimensions

  • bootstrappable_dims (list, optional) – List of bootstrappable dimensions

  • boot_indexes (dict, optional) – Dictionary with spacing values as keys and boot indexes as values

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_default_vel_3d(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate default velocity structure function in 3D: (du^n + dv^n + dw^n)

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain velocity components matching number of spatial dimensions)

  • order (int) – Order of the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_longitudinal_3d(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D longitudinal structure function: (du*dx + dv*dy + dw*dz)^n / |r|^n

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain velocity components matching number of spatial dimensions)

  • order (int) – Order of the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_transverse_ij(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D transverse structure function in ij (xy) plane: The component of velocity difference perpendicular to separation in xy-plane

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain two velocity components)

  • order (int) – Order of the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_transverse_ik(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D transverse structure function in ik (xz) plane: The component of velocity difference perpendicular to separation in xz-plane

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain two velocity components)

  • order (int) – Order of the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_transverse_jk(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D transverse structure function in jk (yz) plane: The component of velocity difference perpendicular to separation in yz-plane

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain two velocity components)

  • order (int) – Order of the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_scalar_3d(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D scalar structure function: (dscalar^n)

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain one scalar variable)

  • order (int) – Order of the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_longitudinal_scalar_3d(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D longitudinal-scalar structure function: (du_longitudinal^n * dscalar^k)

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (velocity components matching spatial dimensions, plus one scalar)

  • order (tuple) – Tuple of orders (n, k) for the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_transverse_ij_scalar(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D transverse-scalar structure function in ij (xy) plane: (du_transverse_ij^n * dscalar^k)

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain two velocity components and a scalar)

  • order (tuple) – Tuple of orders (n, k) for the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_transverse_ik_scalar(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D transverse-scalar structure function in ik (xz) plane: (du_transverse_ik^n * dscalar^k)

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain two velocity components and a scalar)

  • order (tuple) – Tuple of orders (n, k) for the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_transverse_jk_scalar(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D transverse-scalar structure function in jk (yz) plane: (du_transverse_jk^n * dscalar^k)

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain two velocity components and a scalar)

  • order (tuple) – Tuple of orders (n, k) for the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_longitudinal_transverse_ij(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D longitudinal-transverse structure function in ij (xy) plane: (du_longitudinal_ij^n * du_transverse_ij^k)

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain two velocity components)

  • order (tuple) – Tuple of orders (n, k) for the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_longitudinal_transverse_ik(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D longitudinal-transverse structure function in ik (xz) plane: (du_longitudinal_ik^n * du_transverse_ik^k)

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain two velocity components)

  • order (tuple) – Tuple of orders (n, k) for the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_longitudinal_transverse_jk(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D longitudinal-transverse structure function in jk (yz) plane: (du_longitudinal_jk^n * du_transverse_jk^k)

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain two velocity components)

  • order (tuple) – Tuple of orders (n, k) for the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_scalar_scalar_3d(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D scalar-scalar structure function: (dscalar1^n * dscalar2^k)

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain two scalar variables)

  • order (tuple) – Tuple of orders (n, k) for the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_advective_3d(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate 3D advective structure function: (du*deltaadv_u + dv*deltaadv_v + dw*deltaadv_w)^n

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing required variables

  • variables_names (list) – List of variable names (should contain velocity and advective components for spatial dimensions)

  • order (int) – Order of the structure function

  • dims (list) – List of dimension names

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calc_pressure_work_3d(subset, variables_names, order, dims, nz, ny, nx, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Calculate pressure work structure function: (∇_j(δΦ δu_j))^n

Parameters:
  • subset (xarray.Dataset) – Subset of the dataset containing pressure and velocity components

  • variables_names (list) – List of variable names (first is pressure, followed by velocity components for spatial dimensions)

  • order (int) – Order of the structure function

  • dims (list) – List of dimension names (should be [‘z’, ‘y’, ‘x’])

  • nz (int) – Array dimensions

  • ny (int) – Array dimensions

  • nx (int) – Array dimensions

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.structure_functions.calculate_structure_function_3d(ds, dims, variables_names, order, fun='longitudinal', nbz=0, nby=0, nbx=0, spacing=None, num_bootstrappable=0, bootstrappable_dims=None, boot_indexes=None, time_dims=None, conditioning_var=None, conditioning_bins=None)[source]

Main function to calculate structure functions based on specified type.

Parameters:
  • ds (xarray.Dataset) – Dataset containing velocity components and/or scalar fields

  • dims (list) – List of dimension names

  • variables_names (list) – List of variable names to use, depends on function type

  • order (int or tuple) – Order(s) of the structure function

  • fun (str, optional) – Type of structure function

  • nbz (int, optional) – Bootstrap indices for z, y, and x dimensions

  • nby (int, optional) – Bootstrap indices for z, y, and x dimensions

  • nbx (int, optional) – Bootstrap indices for z, y, and x dimensions

  • spacing (dict or int, optional) – Spacing value to use

  • num_bootstrappable (int, optional) – Number of bootstrappable dimensions

  • bootstrappable_dims (list, optional) – List of bootstrappable dimensions

  • boot_indexes (dict, optional) – Dictionary with spacing values as keys and boot indexes as values

  • time_dims (dict, optional) – Dictionary indicating which dimensions are time dimensions

Returns:

Structure function values, DX values, DY values, DZ values

Return type:

numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray

pyturbo_sf.three_dimensional module

Three-dimensional structure function calculations.

Note: 3D energy flux (Bessel) decomposition is not yet implemented. Only 2D energy flux is available via two_dimensional.get_energy_flux_2d().

pyturbo_sf.three_dimensional.bin_sf_3d(ds, variables_names, order, bins, bootsize=None, fun='longitudinal', initial_nbootstrap=100, max_nbootstrap=1000, step_nbootstrap=100, convergence_eps=0.1, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, confidence_interval=0.95, seed=None)[source]

Bin 3D structure function with proper volume element weighting.

Uses the same modular structure as 2D binning with helper functions.

Parameters:
  • ds (xarray.Dataset) – Input dataset with velocity/scalar fields.

  • variables_names (list) – Names of variables to use.

  • order (float or tuple) – Order of the structure function.

  • bins (dict) – Dictionary with dimensions as keys and bin edges as values.

  • bootsize (dict, optional) – Bootstrap block sizes for each dimension.

  • fun (str) – Structure function type. Default is ‘longitudinal’.

  • initial_nbootstrap (int) – Initial number of bootstrap iterations. Default is 100.

  • max_nbootstrap (int) – Maximum number of bootstrap iterations. Default is 1000.

  • step_nbootstrap (int) – Bootstrap step size for adaptive convergence. Default is 100.

  • convergence_eps (float) – Convergence epsilon for bootstrap. Default is 0.1.

  • n_jobs (int) – Number of parallel jobs. Default is -1 (all cores).

  • backend (str) – Parallel backend. Default is ‘threading’.

  • conditioning_var (str, optional) – Name of variable to condition on.

  • conditioning_bins (array-like, optional) – Bin edges for conditioning variable.

  • confidence_interval (float) – Confidence level for intervals (0-1). Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility. Use same seed for conditioned and unconditioned runs to ensure point_counts partition correctly.

Returns:

  • xarray.Dataset – Dataset with binned structure function results.

  • Note (This function produces 3D output where confidence intervals are computed)

  • using the standard normal approximation. For percentile-based CIs, use

  • get_isotropic_sf_3d which produces 1D radial output.

pyturbo_sf.three_dimensional.get_isotropic_sf_3d(ds, variables_names, order=2.0, bins=None, bootsize=None, initial_nbootstrap=100, max_nbootstrap=1000, step_nbootstrap=100, fun='longitudinal', n_bins_theta=36, n_bins_phi=18, window_size_theta=None, window_size_phi=None, window_size_r=None, convergence_eps=0.1, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, confidence_interval=0.95, seed=None)[source]

Get isotropic (spherically binned) structure function with volume element weighting.

Uses the same modular structure as 2D isotropic binning with helper functions.

Parameters:
  • ds (xarray.Dataset) – Input dataset with velocity fields.

  • variables_names (list) – Names of velocity components to use.

  • order (float) – Order of the structure function. Default is 2.0.

  • bins (dict) – Dictionary with ‘r’ key for radial bin edges.

  • bootsize (dict, optional) – Bootstrap block sizes for each dimension.

  • initial_nbootstrap (int) – Initial number of bootstrap iterations. Default is 100.

  • max_nbootstrap (int) – Maximum number of bootstrap iterations. Default is 1000.

  • step_nbootstrap (int) – Bootstrap step size for adaptive convergence. Default is 100.

  • fun (str) – Structure function type. Default is ‘longitudinal’.

  • n_bins_theta (int) – Number of azimuthal angle bins. Default is 36.

  • n_bins_phi (int) – Number of polar angle bins. Default is 18.

  • window_size_theta (int, optional) – Window size for azimuthal isotropy error calculation.

  • window_size_phi (int, optional) – Window size for polar isotropy error calculation.

  • window_size_r (int, optional) – Window size for radial homogeneity error calculation.

  • convergence_eps (float) – Convergence epsilon for bootstrap. Default is 0.1.

  • n_jobs (int) – Number of parallel jobs. Default is -1 (all cores).

  • backend (str) – Parallel backend. Default is ‘threading’.

  • conditioning_var (str, optional) – Name of variable to condition on (e.g., ‘vorticity’, ‘temperature’).

  • conditioning_bins (array-like, optional) – Bin edges for conditioning variable. Can be: - [T_lo, T_hi]: Single bin - np.linspace(…) or np.logspace(…): Multiple bins (N+1 edges for N bins)

  • confidence_interval (float) – Confidence level for intervals. Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility. Use same seed for conditioned and unconditioned runs to ensure point_counts partition correctly.

Returns:

Dataset with isotropic structure function results. If conditioning_bins has >2 elements, output has ‘cond_bin’ dimension.

Return type:

xarray.Dataset

pyturbo_sf.three_dimensional._get_isotropic_sf_3d_single_bin(ds, variables_names, order, bins, bootsize, initial_nbootstrap, max_nbootstrap, step_nbootstrap, fun, n_bins_theta, n_bins_phi, window_size_theta, window_size_phi, window_size_r, convergence_eps, n_jobs, backend, conditioning_var, conditioning_bins, confidence_interval, conditioning_info=None, seed=None)[source]

Internal function to compute 3D isotropic SF for a single conditioning bin.

Parameters:

seed (int, optional) – Random seed for reproducibility.

pyturbo_sf.two_dimensional module

Two-dimensional structure function calculations.

pyturbo_sf.two_dimensional.bin_sf_2d(ds, variables_names, order, bins, bootsize=None, fun='longitudinal', initial_nbootstrap=100, max_nbootstrap=1000, step_nbootstrap=100, convergence_eps=0.1, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, confidence_interval=0.95, seed=None)[source]

Bin structure function with proper volume element weighting.

Parameters:
  • ds (xarray.Dataset) – Input dataset with velocity/scalar fields.

  • variables_names (list) – Names of variables to use.

  • order (float or tuple) – Order of the structure function.

  • bins (dict) – Dictionary with dimensions as keys and bin edges as values.

  • bootsize (dict, optional) – Bootstrap block sizes for each dimension.

  • fun (str) – Structure function type. Default is ‘longitudinal’.

  • initial_nbootstrap (int) – Initial number of bootstrap iterations. Default is 100.

  • max_nbootstrap (int) – Maximum number of bootstrap iterations. Default is 1000.

  • step_nbootstrap (int) – Bootstrap step size for adaptive convergence. Default is 100.

  • convergence_eps (float) – Convergence epsilon for bootstrap. Default is 0.1.

  • n_jobs (int) – Number of parallel jobs. Default is -1 (all cores).

  • backend (str) – Parallel backend. Default is ‘threading’.

  • conditioning_var (str, optional) – Name of variable to condition on.

  • conditioning_bins (array-like, optional) – Bin edges for conditioning variable.

  • confidence_interval (float) – Confidence level for intervals. Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility. Use same seed for conditioned and unconditioned runs to ensure point_counts partition correctly.

Returns:

  • xarray.Dataset – Dataset with binned structure function results.

  • Note (This function produces 2D output where confidence intervals are computed)

  • using weighted percentile bootstrap method.

pyturbo_sf.two_dimensional.get_isotropic_sf_2d(ds, variables_names, order=2.0, bins=None, bootsize=None, initial_nbootstrap=100, max_nbootstrap=1000, step_nbootstrap=100, fun='longitudinal', n_bins_theta=36, window_size_theta=None, window_size_r=None, convergence_eps=0.1, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, confidence_interval=0.95, seed=None)[source]

Get isotropic (radially binned) structure function with volume element weighting.

Parameters:
  • ds (xarray.Dataset) – Input dataset with velocity fields.

  • variables_names (list) – Names of velocity components to use.

  • order (float) – Order of the structure function. Default is 2.0.

  • bins (dict) – Dictionary with ‘r’ key for radial bin edges.

  • bootsize (dict, optional) – Bootstrap block sizes for each dimension.

  • initial_nbootstrap (int) – Initial number of bootstrap iterations. Default is 100.

  • max_nbootstrap (int) – Maximum number of bootstrap iterations. Default is 1000.

  • step_nbootstrap (int) – Bootstrap step size for adaptive convergence. Default is 100.

  • fun (str) – Structure function type. Default is ‘longitudinal’.

  • n_bins_theta (int) – Number of angular bins. Default is 36.

  • window_size_theta (int, optional) – Window size for isotropy error calculation.

  • window_size_r (int, optional) – Window size for homogeneity error calculation.

  • convergence_eps (float) – Convergence epsilon for bootstrap. Default is 0.1.

  • n_jobs (int) – Number of parallel jobs. Default is -1 (all cores).

  • backend (str) – Parallel backend. Default is ‘threading’.

  • conditioning_var (str, optional) – Name of variable to condition on (e.g., ‘vorticity’, ‘temperature’).

  • conditioning_bins (array-like, optional) – Bin edges for conditioning variable. Can be: - [T_lo, T_hi]: Single bin - np.linspace(…) or np.logspace(…): Multiple bins (N+1 edges for N bins)

  • confidence_interval (float) – Confidence level for intervals. Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility. Use same seed for conditioned and unconditioned runs to ensure point_counts partition correctly.

Returns:

Dataset with isotropic structure function results. If conditioning_bins has >2 elements, output has ‘cond_bin’ dimension.

Return type:

xarray.Dataset

pyturbo_sf.two_dimensional._get_isotropic_sf_2d_single_bin(ds, variables_names, order, bins, bootsize, initial_nbootstrap, max_nbootstrap, step_nbootstrap, fun, n_bins_theta, window_size_theta, window_size_r, convergence_eps, n_jobs, backend, conditioning_var, conditioning_bins, confidence_interval, conditioning_info=None, seed=None)[source]

Internal function to compute isotropic SF for a single conditioning bin.

Parameters:

seed (int, optional) – Random seed for reproducibility.

pyturbo_sf.two_dimensional.get_energy_flux_2d(ds, variables_names, order=1.0, wavenumbers=None, r_bins=None, bootsize=None, initial_nbootstrap=100, max_nbootstrap=1000, step_nbootstrap=100, fun='advective', n_bins_theta=36, n_r_bins=100, window_size_theta=None, window_size_k=None, convergence_eps=0.1, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, confidence_interval=0.95, seed=None)[source]

Compute spectral energy flux from advective structure function.

Uses the Bessel J₁ transform to compute energy flux:

Π(K) = -K/2 ∫₀^∞ SF̃(r) J₁(Kr) dr

where SF̃(r) is the angle-averaged advective structure function.

Parameters:
  • ds (xarray.Dataset) – Input dataset with velocity fields.

  • variables_names (list) – Names of velocity components to use. For advective SF, typically [u, v, u] or similar for δu·δu·δr/|δr|.

  • order (float) – Order of the structure function. Default is 1.0 (third-order for advective). Note: The advective SF is inherently odd-order.

  • wavenumbers (array-like or dict, optional) – If array-like: wavenumber values to evaluate at. If dict with ‘k’: uses those wavenumbers. If None: automatically generates logarithmically-spaced wavenumbers.

  • r_bins (array-like, optional) – Radial bin edges for angle-averaging. If None, auto-generated.

  • bootsize (dict, optional) – Bootstrap block sizes for each dimension.

  • initial_nbootstrap (int) – Initial number of bootstrap iterations. Default is 100.

  • max_nbootstrap (int) – Maximum number of bootstrap iterations. Default is 1000.

  • step_nbootstrap (int) – Bootstrap step size for adaptive convergence. Default is 100.

  • fun (str) – Structure function type. Must be ‘advective’ or ‘scalar_scalar’. Default is ‘advective’.

  • n_bins_theta (int) – Number of angular bins for isotropy diagnostics. Default is 36.

  • n_r_bins (int) – Number of radial bins if auto-generating r_bins. Default is 100.

  • window_size_theta (int, optional) – Window size for isotropy error calculation.

  • window_size_k (int, optional) – Window size for homogeneity error calculation.

  • convergence_eps (float) – Convergence epsilon for bootstrap. Default is 0.1.

  • n_jobs (int) – Number of parallel jobs. Default is -1 (all cores).

  • backend (str) – Parallel backend. Default is ‘threading’.

  • conditioning_var (str, optional) – Name of variable to condition on (e.g., ‘vorticity’, ‘temperature’).

  • conditioning_bins (array-like, optional) – Bin edges for conditioning variable.

  • confidence_interval (float) – Confidence level for intervals. Default is 0.95.

Returns:

Dataset containing: - energy_flux: Spectral energy flux Π(K) at each wavenumber - flux_polar: Angular distribution of flux (theta, k) - sf_r: Angle-averaged structure function SF̃(r) - error_isotropy: Isotropy error at each wavenumber - error_homogeneity: Homogeneity error at subset of wavenumbers - std_error: Standard error from bootstrap - ci_upper, ci_lower: Confidence interval bounds - mask_quality: Quality mask (True for reliable estimates) - n_bootstrap: Number of bootstrap iterations per wavenumber - point_counts: Number of points per radial bin - converged: Convergence status

Return type:

xarray.Dataset

Notes

The energy flux Π(K) represents the rate of energy transfer across wavenumber K. Positive values indicate forward cascade (energy flowing to smaller scales), negative values indicate inverse cascade.

This function only accepts ‘advective’ or ‘scalar_scalar’ structure function types, as the J₁ Bessel transform is only physically meaningful for these quantities.

References

Derived from Plancherel theorem relating spectral energy flux to real-space advective structure function.

pyturbo_sf.two_dimensional._get_energy_flux_2d_single_bin(ds, variables_names, order, wavenumbers, r_bins, bootsize, initial_nbootstrap, max_nbootstrap, step_nbootstrap, fun, n_bins_theta, n_r_bins, window_size_theta, window_size_k, convergence_eps, n_jobs, backend, conditioning_var, conditioning_bins, confidence_interval, conditioning_info=None, seed=None)[source]

Internal function to compute energy flux for a single conditioning bin.

Parameters:

seed (int, optional) – Random seed for reproducibility.

pyturbo_sf.utils module

Utility functions for structure function calculations.

pyturbo_sf.utils._is_log_spaced(arr)[source]

Check if array is logarithmically spaced.

pyturbo_sf.utils._calculate_confidence_intervals(means, stds, counts, confidence_level=0.95)[source]

Calculate confidence intervals using normal approximation (mean ± z * std).

This function is used as a FALLBACK when bootstrap samples are not available. When bootstrap samples are available, use weighted percentile method instead.

Parameters:
  • means (array) – Point estimates

  • stds (array) – Standard deviations or standard errors

  • counts (array) – Number of samples per bin

  • confidence_level (float) – Confidence level (default: 0.95)

Returns:

  • ci_upper (array) – Upper confidence interval bounds

  • ci_lower (array) – Lower confidence interval bounds

pyturbo_sf.utils._calculate_quality_mask(sf_bessel, sf_stds, point_counts, eiso, converged, min_points=10, max_isotropy_error=None, max_std_ratio=None)[source]

Calculate quality mask for reliable estimates in 2D/3D.

Parameters:
  • sf_bessel (array) – Bessel-weighted structure function values.

  • sf_stds (array) – Standard errors.

  • point_counts (array) – Number of contributing points.

  • eiso (array) – Isotropy errors.

  • converged (array) – Convergence status.

  • min_points (int) – Minimum points required. Default is 10.

  • max_isotropy_error (float, optional) – Maximum allowed isotropy error.

  • max_std_ratio (float, optional) – Maximum allowed std/mean ratio.

Returns:

mask – Boolean mask (True = reliable).

Return type:

array

pyturbo_sf.utils.fast_shift_1d(input_array, shift=0)[source]

Shift 1D array by the specified integer amount and return the shifted array. Works with datetime arrays as well as numeric arrays.

Parameters:
  • input_array (array_like) – 1-dimensional array to be shifted.

  • shift (int, optional) – Shift amount.

Returns:

1D array shifted by the specified integer amount

Return type:

shifted_array

pyturbo_sf.utils.fast_shift_2d(input_array, y_shift=0, x_shift=0)[source]

Shift 2D array in x and y by the specified integer amounts and returns the shifted arrays. Also works with 1D arrays by treating them as 1-row 2D arrays.

Parameters:
  • input_array (array_like) – 1-dimensional or 2-dimensional array to be shifted.

  • shift_x (int, optional) – Shift amount for x shift.

  • shift_y (int, optional) – Shift amount for y shift.

Returns:

Array shifted in the x-y directions by the specified integer amount

Return type:

shifted_xy_array

pyturbo_sf.utils.fast_shift_3d(input_array, z_shift=0, y_shift=0, x_shift=0)[source]

Shift 3D array in x, y, and z by the specified integer amounts and returns the shifted arrays.

Parameters:
  • input_array (array_like) – 3-dimensional array to be shifted.

  • z_shift (int, optional) – Shift amount for z shift.

  • y_shift (int, optional) – Shift amount for y shift.

  • x_shift (int, optional) – Shift amount for x shift.

Returns:

3D array shifted in the x-y-z directions by the specified integer amount

Return type:

shifted_xyz_array

pyturbo_sf.utils.calculate_time_diff_1d(time_array, shift)[source]

Calculate time difference in seconds when the coordinate is a datetime.

Parameters:
  • time_array (array_like) – Array of datetime values

  • shift (int) – Shift amount

Returns:

Array of time differences in seconds

Return type:

array_like

pyturbo_sf.utils.map_variables_by_pattern_2d(provided, expected, plane_tuple)[source]

Map provided variables to expected ones using common naming patterns.

Parameters:
  • provided (list) – List of provided variable names

  • expected (list) – List of expected variable names

  • plane_tuple (tuple) – Tuple of dimension names

Returns:

Tuple of mapped variable names or None if mapping fails

Return type:

tuple or None

pyturbo_sf.utils.check_and_reorder_variables_2d(variables_names, dims, fun='longitudinal')[source]

Check if the provided variable names match the expected components for the given plane and function type, and reorder them if necessary.

Parameters:
  • variables_names (list) – List of variable names provided by the user

  • dims (list) – List of dimension names (e.g., [‘y’, ‘x’])

  • fun (str) – Type of structure function

Returns:

Tuple of variable names in the correct order for the given plane and function type

Return type:

tuple

pyturbo_sf.utils.check_and_reorder_variables_3d(variables_names, dims, fun='longitudinal')[source]

Check if the provided variable names match the expected components for the given function type, and reorder them if necessary.

Parameters:
  • variables_names (list) – List of variable names provided by the user

  • dims (list) – List of dimension names (e.g., [‘z’, ‘y’, ‘x’])

  • fun (str) – Type of structure function

Returns:

Tuple of variable names in the correct order for the given function type

Return type:

tuple

pyturbo_sf.utils.map_variables_by_pattern_3d(provided, expected)[source]

Map provided variables to expected ones using common naming patterns.

Parameters:
  • provided (list) – List of provided variable names

  • expected (list) – List of expected variable names

Returns:

Tuple of mapped variable names or None if mapping fails

Return type:

tuple or None

Module contents

PyTurbo_SF

A Python package for efficient structure function calculations in 1D, 2D, and 3D data.

Main Functions

bin_sf_1d : 1D structure function binning bin_sf_2d : 2D structure function binning bin_sf_3d : 3D structure function binning get_isotropic_sf_2d : 2D isotropic (radial) structure function get_isotropic_sf_3d : 3D isotropic (spherical) structure function get_energy_flux_2d : 2D spectral energy flux via Bessel transform

Submodules

one_dimensional : 1D structure function calculations two_dimensional : 2D structure function calculations three_dimensional : 3D structure function calculations core : Core utilities and validation utils : Helper functions and variable mapping structure_functions : Low-level SF computation functions binning_tools : Binning utilities bootstrapping_tools : Bootstrap resampling for uncertainty quantification isotropy_tools : Isotropic averaging for 2D/3D data bessel_tools : Bessel transform for energy flux decomposition

pyturbo_sf.bin_sf_1d(ds, variables_names, order, bins, bootsize=None, fun='scalar', initial_nbootstrap=100, max_nbootstrap=1000, step_nbootstrap=100, convergence_eps=0.1, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, confidence_interval=0.95, seed=None)[source]

Bin structure function results with improved weighted statistics and memory efficiency.

Parameters:
  • ds (xarray.Dataset) – Dataset containing scalar fields

  • variables_names (list) – List of variable names to use, depends on function type

  • order (float or tuple) – Order(s) of the structure function

  • bins (dict) – Dictionary with dimension as key and bin edges as values

  • bootsize (dict or int, optional) – Bootsize for the dimension

  • fun (str, optional) – Type of structure function: [‘scalar’, ‘scalar_scalar’]

  • initial_nbootstrap (int, optional) – Initial number of bootstrap samples

  • max_nbootstrap (int, optional) – Maximum number of bootstrap samples

  • step_nbootstrap (int, optional) – Step size for increasing bootstrap samples

  • convergence_eps (float, optional) – Convergence threshold for bin standard deviation

  • n_jobs (int, optional) – Number of jobs for parallel processing

  • backend (str, optional) – Backend for joblib: ‘threading’, ‘multiprocessing’, or ‘loky’. Default is ‘threading’.

  • mask (str, optional) – Name of mask variable in dataset

  • conditioning_bins (tuple, optional) – Conditions for masking. If dict with ‘array’ and ‘shifted’ keys, creates separate indicators I_α and I_β. If list, applies same condition to both.

  • confidence_interval (float, optional) – Confidence level for intervals. Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility. Use same seed for conditioned and unconditioned runs to ensure point_counts partition correctly.

Returns:

Dataset with binned structure function results

Return type:

xarray.Dataset

pyturbo_sf.bin_sf_2d(ds, variables_names, order, bins, bootsize=None, fun='longitudinal', initial_nbootstrap=100, max_nbootstrap=1000, step_nbootstrap=100, convergence_eps=0.1, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, confidence_interval=0.95, seed=None)[source]

Bin structure function with proper volume element weighting.

Parameters:
  • ds (xarray.Dataset) – Input dataset with velocity/scalar fields.

  • variables_names (list) – Names of variables to use.

  • order (float or tuple) – Order of the structure function.

  • bins (dict) – Dictionary with dimensions as keys and bin edges as values.

  • bootsize (dict, optional) – Bootstrap block sizes for each dimension.

  • fun (str) – Structure function type. Default is ‘longitudinal’.

  • initial_nbootstrap (int) – Initial number of bootstrap iterations. Default is 100.

  • max_nbootstrap (int) – Maximum number of bootstrap iterations. Default is 1000.

  • step_nbootstrap (int) – Bootstrap step size for adaptive convergence. Default is 100.

  • convergence_eps (float) – Convergence epsilon for bootstrap. Default is 0.1.

  • n_jobs (int) – Number of parallel jobs. Default is -1 (all cores).

  • backend (str) – Parallel backend. Default is ‘threading’.

  • conditioning_var (str, optional) – Name of variable to condition on.

  • conditioning_bins (array-like, optional) – Bin edges for conditioning variable.

  • confidence_interval (float) – Confidence level for intervals. Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility. Use same seed for conditioned and unconditioned runs to ensure point_counts partition correctly.

Returns:

  • xarray.Dataset – Dataset with binned structure function results.

  • Note (This function produces 2D output where confidence intervals are computed)

  • using weighted percentile bootstrap method.

pyturbo_sf.bin_sf_3d(ds, variables_names, order, bins, bootsize=None, fun='longitudinal', initial_nbootstrap=100, max_nbootstrap=1000, step_nbootstrap=100, convergence_eps=0.1, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, confidence_interval=0.95, seed=None)[source]

Bin 3D structure function with proper volume element weighting.

Uses the same modular structure as 2D binning with helper functions.

Parameters:
  • ds (xarray.Dataset) – Input dataset with velocity/scalar fields.

  • variables_names (list) – Names of variables to use.

  • order (float or tuple) – Order of the structure function.

  • bins (dict) – Dictionary with dimensions as keys and bin edges as values.

  • bootsize (dict, optional) – Bootstrap block sizes for each dimension.

  • fun (str) – Structure function type. Default is ‘longitudinal’.

  • initial_nbootstrap (int) – Initial number of bootstrap iterations. Default is 100.

  • max_nbootstrap (int) – Maximum number of bootstrap iterations. Default is 1000.

  • step_nbootstrap (int) – Bootstrap step size for adaptive convergence. Default is 100.

  • convergence_eps (float) – Convergence epsilon for bootstrap. Default is 0.1.

  • n_jobs (int) – Number of parallel jobs. Default is -1 (all cores).

  • backend (str) – Parallel backend. Default is ‘threading’.

  • conditioning_var (str, optional) – Name of variable to condition on.

  • conditioning_bins (array-like, optional) – Bin edges for conditioning variable.

  • confidence_interval (float) – Confidence level for intervals (0-1). Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility. Use same seed for conditioned and unconditioned runs to ensure point_counts partition correctly.

Returns:

  • xarray.Dataset – Dataset with binned structure function results.

  • Note (This function produces 3D output where confidence intervals are computed)

  • using the standard normal approximation. For percentile-based CIs, use

  • get_isotropic_sf_3d which produces 1D radial output.

pyturbo_sf.get_isotropic_sf_2d(ds, variables_names, order=2.0, bins=None, bootsize=None, initial_nbootstrap=100, max_nbootstrap=1000, step_nbootstrap=100, fun='longitudinal', n_bins_theta=36, window_size_theta=None, window_size_r=None, convergence_eps=0.1, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, confidence_interval=0.95, seed=None)[source]

Get isotropic (radially binned) structure function with volume element weighting.

Parameters:
  • ds (xarray.Dataset) – Input dataset with velocity fields.

  • variables_names (list) – Names of velocity components to use.

  • order (float) – Order of the structure function. Default is 2.0.

  • bins (dict) – Dictionary with ‘r’ key for radial bin edges.

  • bootsize (dict, optional) – Bootstrap block sizes for each dimension.

  • initial_nbootstrap (int) – Initial number of bootstrap iterations. Default is 100.

  • max_nbootstrap (int) – Maximum number of bootstrap iterations. Default is 1000.

  • step_nbootstrap (int) – Bootstrap step size for adaptive convergence. Default is 100.

  • fun (str) – Structure function type. Default is ‘longitudinal’.

  • n_bins_theta (int) – Number of angular bins. Default is 36.

  • window_size_theta (int, optional) – Window size for isotropy error calculation.

  • window_size_r (int, optional) – Window size for homogeneity error calculation.

  • convergence_eps (float) – Convergence epsilon for bootstrap. Default is 0.1.

  • n_jobs (int) – Number of parallel jobs. Default is -1 (all cores).

  • backend (str) – Parallel backend. Default is ‘threading’.

  • conditioning_var (str, optional) – Name of variable to condition on (e.g., ‘vorticity’, ‘temperature’).

  • conditioning_bins (array-like, optional) – Bin edges for conditioning variable. Can be: - [T_lo, T_hi]: Single bin - np.linspace(…) or np.logspace(…): Multiple bins (N+1 edges for N bins)

  • confidence_interval (float) – Confidence level for intervals. Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility. Use same seed for conditioned and unconditioned runs to ensure point_counts partition correctly.

Returns:

Dataset with isotropic structure function results. If conditioning_bins has >2 elements, output has ‘cond_bin’ dimension.

Return type:

xarray.Dataset

pyturbo_sf.get_isotropic_sf_3d(ds, variables_names, order=2.0, bins=None, bootsize=None, initial_nbootstrap=100, max_nbootstrap=1000, step_nbootstrap=100, fun='longitudinal', n_bins_theta=36, n_bins_phi=18, window_size_theta=None, window_size_phi=None, window_size_r=None, convergence_eps=0.1, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, confidence_interval=0.95, seed=None)[source]

Get isotropic (spherically binned) structure function with volume element weighting.

Uses the same modular structure as 2D isotropic binning with helper functions.

Parameters:
  • ds (xarray.Dataset) – Input dataset with velocity fields.

  • variables_names (list) – Names of velocity components to use.

  • order (float) – Order of the structure function. Default is 2.0.

  • bins (dict) – Dictionary with ‘r’ key for radial bin edges.

  • bootsize (dict, optional) – Bootstrap block sizes for each dimension.

  • initial_nbootstrap (int) – Initial number of bootstrap iterations. Default is 100.

  • max_nbootstrap (int) – Maximum number of bootstrap iterations. Default is 1000.

  • step_nbootstrap (int) – Bootstrap step size for adaptive convergence. Default is 100.

  • fun (str) – Structure function type. Default is ‘longitudinal’.

  • n_bins_theta (int) – Number of azimuthal angle bins. Default is 36.

  • n_bins_phi (int) – Number of polar angle bins. Default is 18.

  • window_size_theta (int, optional) – Window size for azimuthal isotropy error calculation.

  • window_size_phi (int, optional) – Window size for polar isotropy error calculation.

  • window_size_r (int, optional) – Window size for radial homogeneity error calculation.

  • convergence_eps (float) – Convergence epsilon for bootstrap. Default is 0.1.

  • n_jobs (int) – Number of parallel jobs. Default is -1 (all cores).

  • backend (str) – Parallel backend. Default is ‘threading’.

  • conditioning_var (str, optional) – Name of variable to condition on (e.g., ‘vorticity’, ‘temperature’).

  • conditioning_bins (array-like, optional) – Bin edges for conditioning variable. Can be: - [T_lo, T_hi]: Single bin - np.linspace(…) or np.logspace(…): Multiple bins (N+1 edges for N bins)

  • confidence_interval (float) – Confidence level for intervals. Default is 0.95.

  • seed (int, optional) – Random seed for reproducibility. Use same seed for conditioned and unconditioned runs to ensure point_counts partition correctly.

Returns:

Dataset with isotropic structure function results. If conditioning_bins has >2 elements, output has ‘cond_bin’ dimension.

Return type:

xarray.Dataset

pyturbo_sf.get_energy_flux_2d(ds, variables_names, order=1.0, wavenumbers=None, r_bins=None, bootsize=None, initial_nbootstrap=100, max_nbootstrap=1000, step_nbootstrap=100, fun='advective', n_bins_theta=36, n_r_bins=100, window_size_theta=None, window_size_k=None, convergence_eps=0.1, n_jobs=-1, backend='threading', conditioning_var=None, conditioning_bins=None, confidence_interval=0.95, seed=None)[source]

Compute spectral energy flux from advective structure function.

Uses the Bessel J₁ transform to compute energy flux:

Π(K) = -K/2 ∫₀^∞ SF̃(r) J₁(Kr) dr

where SF̃(r) is the angle-averaged advective structure function.

Parameters:
  • ds (xarray.Dataset) – Input dataset with velocity fields.

  • variables_names (list) – Names of velocity components to use. For advective SF, typically [u, v, u] or similar for δu·δu·δr/|δr|.

  • order (float) – Order of the structure function. Default is 1.0 (third-order for advective). Note: The advective SF is inherently odd-order.

  • wavenumbers (array-like or dict, optional) – If array-like: wavenumber values to evaluate at. If dict with ‘k’: uses those wavenumbers. If None: automatically generates logarithmically-spaced wavenumbers.

  • r_bins (array-like, optional) – Radial bin edges for angle-averaging. If None, auto-generated.

  • bootsize (dict, optional) – Bootstrap block sizes for each dimension.

  • initial_nbootstrap (int) – Initial number of bootstrap iterations. Default is 100.

  • max_nbootstrap (int) – Maximum number of bootstrap iterations. Default is 1000.

  • step_nbootstrap (int) – Bootstrap step size for adaptive convergence. Default is 100.

  • fun (str) – Structure function type. Must be ‘advective’ or ‘scalar_scalar’. Default is ‘advective’.

  • n_bins_theta (int) – Number of angular bins for isotropy diagnostics. Default is 36.

  • n_r_bins (int) – Number of radial bins if auto-generating r_bins. Default is 100.

  • window_size_theta (int, optional) – Window size for isotropy error calculation.

  • window_size_k (int, optional) – Window size for homogeneity error calculation.

  • convergence_eps (float) – Convergence epsilon for bootstrap. Default is 0.1.

  • n_jobs (int) – Number of parallel jobs. Default is -1 (all cores).

  • backend (str) – Parallel backend. Default is ‘threading’.

  • conditioning_var (str, optional) – Name of variable to condition on (e.g., ‘vorticity’, ‘temperature’).

  • conditioning_bins (array-like, optional) – Bin edges for conditioning variable.

  • confidence_interval (float) – Confidence level for intervals. Default is 0.95.

Returns:

Dataset containing: - energy_flux: Spectral energy flux Π(K) at each wavenumber - flux_polar: Angular distribution of flux (theta, k) - sf_r: Angle-averaged structure function SF̃(r) - error_isotropy: Isotropy error at each wavenumber - error_homogeneity: Homogeneity error at subset of wavenumbers - std_error: Standard error from bootstrap - ci_upper, ci_lower: Confidence interval bounds - mask_quality: Quality mask (True for reliable estimates) - n_bootstrap: Number of bootstrap iterations per wavenumber - point_counts: Number of points per radial bin - converged: Convergence status

Return type:

xarray.Dataset

Notes

The energy flux Π(K) represents the rate of energy transfer across wavenumber K. Positive values indicate forward cascade (energy flowing to smaller scales), negative values indicate inverse cascade.

This function only accepts ‘advective’ or ‘scalar_scalar’ structure function types, as the J₁ Bessel transform is only physically meaningful for these quantities.

References

Derived from Plancherel theorem relating spectral energy flux to real-space advective structure function.