OceananigansLagrangianFilter.jl Library
Documenting the public user interface.
OceananigansLagrangianFilter.OnlineLagrangianFilter
OceananigansLagrangianFilter.OnlineLagrangianFilter.OnlineFilterConfig — Type
OnlineFilterConfig(;
)A configuration object for online filtering.
OceananigansLagrangianFilter.OnlineLagrangianFilter.OnlineFilterConfig — Method
OnlineFilterConfig(; grid::AbstractGrid,
output_filename::String = "online_filtered_output",
var_names_to_filter::Tuple{Vararg{String}},
velocity_names::Tuple{Vararg{String}},
N::Union{Int, Nothing} = nothing,
freq_c::Union{Int, Nothing} = nothing,
filter_params::Union{NamedTuple, Nothing} = nothing,
map_to_mean::Bool = true,
compute_mean_velocities::Bool = true,
npad::Int = 5,
filter_mode::String = "online",
label::String = ""
)Constructs a configuration object for offline Lagrangian filtering of Oceananigans data. This function validates the input data file, time specifications, and filter parameters before creating the OfflineFilterConfig object.
Keyword arguments
grid: (required) The grid for the simulation. Ifnothing, the grid is inferred from theoriginal_data_filename(preferred option)output_filename: The filename for the output of the online filtered data. Default:"online_filtered_output".var_names_to_filter: (required) ATupleofStrings specifying the names of the tracer variables to be filtered.velocity_names: (required) ATupleofStrings specifying the names of the velocity fields in the data file to be used for advection.N,freq_c: Parameters for a Butterworth filter.Nis the order of the filter, andfreq_cis the cutoff frequency. These are used to automatically generatefilter_paramsif not provided. Must be specified together iffilter_paramsis not given.filter_params: ANamedTuplecontaining the coefficients for a custom filter. Only filterparams ORNand `freqc` should be given.map_to_mean: ABoolindicating whether to map filtered data to the mean position (i.e. calculate generalised Lagrangian mean). Default:true.compute_mean_velocities: ABoolindicating whether to compute the mean velocities from the maps. Default:true.npad: The number of cells to pad the interpolation to mean position, used when there are periodic boundary conditions. Default:5.compute_Eulerian_filter: ABoolindicating whether to also compute an Eulerian-mean-based filter for comparison. Default:false.filter_mode: AStringindicating whether to run the filter in "offline" or "online" mode. Default: "online". TODO use multiple dispatch for this instead.label: AStringlabel for the variables that will be created to pass to the model. For use when multiple filter configurations are to be run at the same time. Default: "".
Example:
using OceananigansLagrangianFilter
using Oceananigans.Units
Nx = 50
Nz = 20
L = 10kilometers
H = 100meters
grid = RectilinearGrid(CPU(),size = (Nx, Nz),
x = (-L/2, L/2),
z = (-H, 0),
topology = (Periodic, Flat, Bounded))
filter_config = OnlineFilterConfig( grid = grid,
output_filename = "test_filter.jld2",
var_names_to_filter = ("b","T"),
velocity_names = ("u","w"),
N = 2,
freq_c = 1e-4/2)
# output
┌ Info: Advection for Lagrangian filtering will be performed using full model velocities u, v, and w.
└ Maps for regridding to mean position will be computed corresponding to velocities: ("u", "w").
[ Info: Mean velocities corresponding to ("u", "w") will be computed.
[ Info: Variables to be filtered: ("b", "T"). Ensure these are valid tracer or auxiliary field names in the simulation.
[ Info: Setting filter parameters to use Butterworth order 2, cutoff frequency 5.0e-5
OnlineFilterConfig(50×1×20 RectilinearGrid{Float64, Periodic, Flat, Bounded} on CPU with 3×0×3 halo
├── Periodic x ∈ [-5000.0, 5000.0) regularly spaced with Δx=200.0
├── Flat y
└── Bounded z ∈ [-100.0, 0.0] regularly spaced with Δz=5.0, "test_filter.jld2", ("b", "T"), ("u", "w"), (a1 = 1.421067568548072e-20, b1 = -7.071067811865475e-5, c1 = 3.535533905932738e-5, d1 = -3.535533905932738e-5, N_coeffs = 1), true, true, 5, "online", "")OceananigansLagrangianFilter.OfflineLagrangianFilter
OceananigansLagrangianFilter.OfflineLagrangianFilter.OfflineFilterConfig — Type
OfflineFilterConfig(;
)A configuration object for apply_offline_filter.
OceananigansLagrangianFilter.OfflineLagrangianFilter.OfflineFilterConfig — Method
OfflineFilterConfig(; original_data_filename::String,
var_names_to_filter::Tuple{Vararg{String}},
velocity_names::Tuple{Vararg{String}},
T_start::Union{Real,Nothing} = nothing,
T_end::Union{Real,Nothing} = nothing,
T::Union{Real,Nothing} = nothing,
architecture::AbstractArchitecture = CPU(),
T_out::Union{Real,Nothing} = nothing,
N::Union{Int, Nothing} = nothing,
freq_c::Union{Int, Nothing} = nothing,
filter_params::Union{NamedTuple, Nothing} = nothing,
Δt::Union{Real,Nothing} = nothing,
backend::AbstractInMemoryBackend = InMemory(4),
map_to_mean::Bool = true,
forward_output_filename::String = "forward_output.jld2",
backward_output_filename::String = "backward_output.jld2",
output_filename::String = "filtered_output.jld2",
npad::Int = 5,
compute_mean_velocities::Bool = true,
delete_intermediate_files::Bool = true,
compute_Eulerian_filter::Bool = false,
output_netcdf::Bool = false,
output_original_data::Bool = true,
advection::Union{AbstractAdvectionScheme, Nothing} = WENO(),
grid::Union{AbstractGrid, Nothing} = nothing,
filter_mode::String = "offline",
label::String = "")Constructs a configuration object for offline Lagrangian filtering of Oceananigans data. This function validates the input data file, time specifications, and filter parameters before creating the OfflineFilterConfig object.
Keyword arguments
original_data_filename: (required) The path to the JLD2 file containing the original Oceananigans output data.var_names_to_filter: (required) ATupleofStrings specifying the names of the tracer variables to be filtered.velocity_names: (required) ATupleofStrings specifying the names of the velocity fields in the data file to be used for advection.T_start: Start time for the filter. Must be within the time range of the data. If not given, defaults to either T_end - T (if they are given), or the start time of the original data.T_end: End time for the filter. Must be within the time range of the data. If not given, defaults to either Tstart + T (after Tstart given or computed, if T is given), or the end time of the original data.T: Duration of the filtering. If not given, defaults to Tend - Tstart (after Tstart and Tend are given or computed).architecture: The architecture (CPU or GPU) to be used for the filtering computation. Default:CPU().T_out: The output time step for the filtered data. Ifnothing, it defaults to the time step of the original data.N,freq_c: Parameters for a Butterworth squared filter.Nis the order of the filter, andfreq_cis the cutoff frequency. These are used to automatically generatefilter_paramsif not provided. Must be specified together iffilter_paramsis not given.filter_params: ANamedTuplecontaining the coefficients for a custom filter. Only filterparams ORNand `freqc` should be given.Δt: The time step for the internal Lagrangian filter simulation. Ifnothing, it defaults toT_out / 10, but this may not be appropriate.backend: The backend for loadingFieldTimeSeriesdata. SeeOceananigans.Fields.FieldTimeSeries. Default:InMemory(4).map_to_mean: ABoolindicating whether to map filtered data to the mean position (i.e. calculate generalised Lagrangian mean). Default:true.forward_output_filename: The filename for the output of the forward filter pass. Default:"forward_output.jld2".backward_output_filename: The filename for the output of the backward filter pass. Default:"backward_output.jld2".output_filename: The filename for the final combined and mapped output. Default:"filtered_output.jld2".npad: The number of cells to pad the interpolation to mean position, used when there are periodic boundary conditions. Default:5.compute_mean_velocities: ABoolindicating whether to compute the mean velocities from the maps. Default:true.delete_intermediate_files: ABoolindicating whether to deleteforward_output.jld2andbackward_output.jld2after the final combined file is created. Default:true.compute_Eulerian_filter: ABoolindicating whether to also compute an Eulerian-mean-based filter for comparison. Default:false.output_netcdf: ABoolindicating whether to also convert the final JLD2 output file to a NetCDF file. Default:false.output_original_data: ABoolindicating whether to include the original data in the final output file for comparison. Default:true.
advection: The advection scheme to use for the Lagrangian filter simulation. Default:WENO(). Using lower-order schemes may be a source of error.grid: The grid for the simulation. Ifnothing, the grid is inferred from theoriginal_data_filename(preferred option)filter_mode: AStringindicating whether to run the filter in "offline" or "online" mode. Default: "offline". TODO use multiple dispatch for this instead.label: AStringlabel for the variables that will be created to pass to the model. For use when multiple filter configurations are to be run at the same time. Default: "".
Example:
using OceananigansLagrangianFilter
using Oceananigans.Units
path_to_sim = "../test/data/reference_sim.jld2"
filter_config = OfflineFilterConfig(original_data_filename=path_to_sim,
output_filename = "output_file.jld2",
var_names_to_filter = ("b",),
velocity_names = ("u","w"),
architecture = CPU(),
Δt = 20minutes,
T_out = 1hour,
N = 2,
freq_c = 1e-4/2,
compute_mean_velocities = true,
output_netcdf = true,
delete_intermediate_files = true,
compute_Eulerian_filter = true)
# output
┌ Info: Advection for Lagrangian filtering will be performed using only velocities ("u", "w") -
│ any other velocity components will be zero by default. Maps for regridding to mean position will
└ be computed corresponding to velocities: ("u", "w").
[ Info: Mean velocities corresponding to ("u", "w") will be computed.
[ Info: Filter interval will be from T_start=0.0 to T_end=86400.0, duration T=86400.0
[ Info: Setting filter parameters to use Butterworth squared, order 2, cutoff frequency 5.0e-5
OfflineFilterConfig("../test/data/reference_sim.jld2", ("b",), ("u", "w"), 0.0, 86400.0, 86400.0, CPU(), 3600.0, (a1 = 1.767766952966369e-5, b1 = 1.767766952966369e-5, c1 = 3.535533905932738e-5, d1 = 3.535533905932738e-5, N_coeffs = 1), 1200.0, InMemory{Int64}(1, 4), true, "forward_output.jld2", "backward_output.jld2", "output_file.jld2", 5, true, true, true, true, true, WENO{3, Float64, Float32}(order=5)
├── buffer_scheme: WENO{2, Float64, Float32}(order=3)
│ └── buffer_scheme: Centered(order=2)
└── advecting_velocity_scheme: Centered(order=4), 10×1×10 RectilinearGrid{Float64, Periodic, Flat, Bounded} on CPU with 3×0×3 halo
├── Periodic x ∈ [-5000.0, 5000.0) regularly spaced with Δx=1000.0
├── Flat y
└── Bounded z ∈ [-100.0, 0.0] regularly spaced with Δz=10.0, "offline", "")
OceananigansLagrangianFilter.OfflineLagrangianFilter.run_offline_Lagrangian_filter — Method
run_offline_Lagrangian_filter(config::OfflineFilterConfig)Runs an offline Lagrangian filter on an Oceananigans FieldTimeSeries dataset as configured by config.
This function performs a series of steps to filter the data:
- Prepare data on disk: The input data is copied and manipulated on disk to be suitable for the forward and backward Lagrangian simulations.
- Run forward simulation: A
LagrangianFiltermodel is created and run forward in time to compute the first half of the filter contributions. - Run backward simulation: The input data is re-prepared for a backward pass, and the simulation is run a second time to compute the remaining contributions.
- Combine results: The forward and backward simulation outputs are summed to produce the final filtered data.
- Post-processing: Optional post-processing steps are performed, including regridding the data to the mean position, computing a comparative Eulerian filter, and converting the output file to NetCDF.
- Cleanup: Intermediate files are removed to save disk space.
Arguments
config: An instance ofOfflineFilterConfigthat specifies all parameters and file paths for the filtering process.
OceananigansLagrangianFilter.Utils
OceananigansLagrangianFilter.Utils.compute_Eulerian_filter! — Method
compute_Eulerian_filter!(config::AbstractConfig)Computes the Eulerian filter for specified variables and writes the results to a combined output file. This function performs a direct, convolution-style filtering of a time series by applying a weighting function to the data at each time step.
The function iterates through each variable to be filtered:
- Reads data: The entire time series of the variable is read from the JLD2 file.
- Applies weighting: At each output time, a weighting function
Gis computed and applied to the entire time series. The weighted data is summed to produce the filtered field. - Writes output: The resulting filtered field is saved back to the same JLD2 file in a new group with the
_Eulerian_filteredsuffix.
This method serves as a benchmark for comparison with the main Lagrangian filter.
The method uses data saved to the filter output file - incase we decide to save this at lower frequency than the original data, it should be rewritten to use the original data file instead.
Arguments
config: An instance ofAbstractConfigcontaining the file path, variable names, and filter parameters.
OceananigansLagrangianFilter.Utils.compute_time_shift! — Method
compute_time_shift!(config::AbstractConfig)Computes the time shift for an online filter based on its coefficients and writes the shifted time series to the output file.
This function is only applicable for online filtering. The time shift is computed as the time delay introduced by the filter's transfer function. This new time series is stored in a new group called timeseries/t_shifted within the output JLD2 file.
Arguments
config: A configuration object of typeOfflineFilterConfigwhich contains thefilter_mode,output_filename, andfilter_params(filter coefficients).
Throws
error: Ifconfig.filter_modeis not"online". The time shift for offline (forward-backward) filtering is zero by definition due to an even weight function.
OceananigansLagrangianFilter.Utils.create_filtered_vars — Method
create_filtered_vars(config::AbstractConfig)Creates a Tuple of Symbols representing the names of the filtered tracer variables.
- For a single-exponential filter (
N_coeffs = 0.5), the function generates names with a_C1suffix. - For a multi-coefficient filter (
N_coeffs > 0.5), it generates pairs of names for each coefficient, suffixed with_C#and_S#, where#is the coefficient index.
If map_to_mean or compute_mean_velocities is enabled in the configuration, additional symbols are created for the spatial mapping variables corresponding to each velocity component, prefixed with xi_ and suffixed with the corresponding coefficient names.
Arguments
config: An instance ofAbstractConfigcontaining the names of the variables to filter, the filter parameters, and themap_to_meanandcompute_mean_velocitiesbooleans.
Returns
A Tuple of Symbols representing the names of the filtered variables to be used as tracers in the simulation.
OceananigansLagrangianFilter.Utils.create_forcing — Method
create_forcing(filtered_vars::Tuple{Vararg{Symbol}}, config::AbstractConfig)Creates a NamedTuple of forcing functions for each filtered variable and, if enabled, for the spatial mapping variables. These forcing terms are used to numerically integrate the filter equations.
The function handles two cases: a single-exponential filter (N_coeffs = 0.5) and a multi-coefficient Butterworth squared filter (N_coeffs > 0.5).
- For standard filtered variables, the forcing is a combination of terms derived from the filter's coefficients and a term from the original data.
- For spatial mapping variables (if
map_to_meanorcompute_mean_velocitiesis true), the forcing includes terms derived from the filter's coefficients and a term from the original velocity data.
Arguments
filtered_vars: ATupleofSymbols representing the names of the filtered variables.config: An instance ofAbstractConfigcontaining the names of the variables to be filtered, velocity names, and the filter parameters.
Returns
A NamedTuple where each key is a variable name from filtered_vars and each value is a Tuple of the corresponding forcing functions.
OceananigansLagrangianFilter.Utils.create_input_data_on_disk — Method
create_input_data_on_disk(config::AbstractConfig; direction::String="forward")Prepares a new JLD2 file on disk with the time-filtered data for a forward or backward Lagrangian simulation.
This function performs the following steps:
- Validates
direction: Ensures the direction is either"forward"or"backward". - Creates a new file: A new JLD2 file is created with the suffix
_filter_input.jld2and any existing file with the same name is deleted. - Copies metadata: Key metadata from the original file (e.g.,
gridinformation) is copied to the new file to maintain consistency. - Time truncation: The data is truncated to the time range specified by
config.T_startandconfig.T_end. - Time shifting:
- For
"forward"filtering, a new time variable is created, shifted so thatt=0corresponds toconfig.T_start. - For
"backward"filtering, the data is re-ordered and a new time variable is created, shifted so thatt=0corresponds toconfig.T_end.
- For
- Velocity reversal: For
"backward"filtering, the velocity fields (u,v,w) are negated to correctly simulate backward advection.
Arguments
config: An instance ofAbstractConfigcontaining the file paths, variable names, and time specifications.
Keyword Arguments
direction: AStringindicating the simulation direction. It must be either"forward"(the default) or"backward".
OceananigansLagrangianFilter.Utils.create_original_vars — Method
create_original_vars(config::AbstractConfig)Creates a NamedTuple to serve as auxiliary fields for the original variables in a simulation. The fields are initialised from the input data to ensure that they are in the correct location. - the value of the data is unimportant.
Arguments
config: An instance ofAbstractConfigcontaining the names of the variables and the simulation grid.
Returns
A NamedTuple where each key is a Symbol of a variable name to be filtered, and each value is an empty CenterField for that variable.
OceananigansLagrangianFilter.Utils.create_output_fields — Method
create_output_fields(model::AbstractModel, config::AbstractConfig)Reconstructs the final output fields from the model's tracers and auxiliary fields. This function performs the following steps:
- Reconstructs filtered variables: For each variable to be filtered, it sums the contributions from the individual filter coefficients (
_Cand_Stracers) using the coefficients fromfilter_params. - Reconstructs spatial mapping fields: If spatial mapping is enabled, the function also reconstructs the
xi_fields that represent the filtered position. - Builds mean velocities: If
compute_mean_velocitiesis true, the function reconstructs the mean velocity fields using thexi_fields. - Includes original data: The original data is added to the output dictionary for comparison and analysis if
config.output_original_datais true.
Arguments
model: An instance of anAbstractModelcontaining the tracer and auxiliary fields.config: An instance ofAbstractConfigwith the names of the variables, velocity components, and filter parameters.
Returns
A Dict where keys are the names of the output fields (e.g., var_name_Lagrangian_filtered, xi_vel_name, var_name) and values are the corresponding reconstructed Fields.
OceananigansLagrangianFilter.Utils.get_frequency_response — Method
get_frequency_response(;freq::AbstractArray, filter_params::NamedTuple)Calculates the frequency response of the offline filter. This function takes a set of frequencies and the filter's coefficients to compute how the filter amplifies or attenuates different frequency components of a signal.
The response is computed by summing the contributions of each coefficient pair based on the filter's transfer function in the frequency domain. The result is a measure of the filter's gain at each given frequency.
Arguments
freq: A vector of frequencies (in radians per unit time).filter_params: ANamedTuplecontaining the filter coefficients (a,b,c,d) and the number of coefficient pairs (N_coeffs).
Returns
- A vector
Ghatrepresenting the filter's frequency response at each corresponding frequency infreq.
OceananigansLagrangianFilter.Utils.get_weight_function — Method
get_weight_function(;t::AbstractArray, tref::Real, filter_params::NamedTuple, direction::String = "both")Computes the weighting function for the offline filter. This function calculates the filter's impulse response, which determines how much each point in the timeseries t contributes to the filtered value at a reference time tref. The weighting function is based on the provided filter_params, which contains the coefficients for the filter's impulse response.
Keyword arguments
t: A collection of time points in the timeseries.tref: The reference time at which the filter is being evaluated.filter_params: ANamedTuplecontaining the coefficients (a,b,c,d) and the number of coefficient pairs (N_coeffs).direction: AStringindicating the direction of the filter. It can be "both" (default), "forward", or "backward". This determines whether the filter is applied symmetrically aroundtref, only to past times, or only to future times.
Returns
- A vector of weights
G, with the same dimensions ast, representing the value of the filter's impulse response at each time point relative totref.
OceananigansLagrangianFilter.Utils.initialise_filtered_vars_from_data — Method
initialise_filtered_vars_from_data(model::AbstractModel, saved_original_vars::Tuple,
config::AbstractConfig)Initializes the model's tracer fields, which represent the components of the filtered variables. This function sets the initial values of the filtered variables to the (scaled) first timestep of the original data. This improves the "spin-up" of the filter simulation by providing a good starting point.
The initialization formula depends on the number of filter coefficients (N_coeffs):
- For a single-exponential filter (
N_coeffs = 0.5), only the_C1tracer exists and is initialized. - For a multi-coefficient filter (
N_coeffs > 0.5), both the_Cand_Stracers for each coefficient are initialized.
Arguments
model: TheAbstractModelwhose tracers are to be initialized.saved_original_vars: ATupleofFieldTimeSeriesobjects containing the original data for each variable.config: An instance ofAbstractConfigwith the filter parameters.
OceananigansLagrangianFilter.Utils.initialise_filtered_vars_from_model — Method
initialise_filtered_vars_from_model(model::AbstractModel,config::AbstractConfig)Initializes the model's filtered tracer fields using the actual tracer fields that are assumed to have been already set. This improves the "spin-up" of the filter simulation by providing a good starting point.
The initialization formula depends on the number of filter coefficients (N_coeffs):
- For a single-exponential filter (
N_coeffs = 0.5), only the_C1tracer exists and is initialized. - For a multi-coefficient filter (
N_coeffs > 0.5), both the_Cand_Stracers for each coefficient are initialized.
Arguments
model: TheAbstractModelwhose tracers are to be initialized.config: An instance ofAbstractConfigwith the filter parameters.
OceananigansLagrangianFilter.Utils.jld2_to_netcdf — Method
jld2_to_netcdf(jld2_filename::String, nc_filename::String)Converts a JLD2 output file generated by an Oceananigans simulation into a standard NetCDF file. This function is useful for post-processing and for sharing data with other tools that expect the NetCDF format.
The conversion process involves the following steps:
- Read JLD2 data: Opens the input JLD2 file and reads the grid, time, and all timeseries variables.
- Create NetCDF file: Creates a new NetCDF file with a
.ncextension. - Define dimensions: Defines NetCDF dimensions based on the grid sizes and staggered locations (e.g.,
x_caafor cell centers,x_faafor cell faces). - Define grid variables: Writes the grid coordinates and metadata (e.g.,
Lx,Ny,Hx) as variables to the NetCDF file. - Write timeseries data: Iterates through each variable in the JLD2 file's timeseries, determines its location on the grid, and writes the data to a new variable in the NetCDF file.
- Add metadata: Adds attributes to each variable, including boundary conditions and units, for better documentation.
Arguments
jld2_filename: AStringspecifying the path to the input JLD2 file.nc_filename: AStringspecifying the path for the output NetCDF file.
OceananigansLagrangianFilter.Utils.load_data — Method
load_data(config::AbstractConfig)Loads the velocity and tracer data from the intermediate input file created by create_input_data_on_disk. The data for each variable is loaded as a FieldTimeSeries and returned as a single NamedTuple.
Arguments
config: An instance ofAbstractConfigcontaining the file path, variable names,
architecture, and backend.
Returns
A NamedTuple with fields velocity_data and var_data, where each field contains a Tuple of FieldTimeSeries objects.
OceananigansLagrangianFilter.Utils.regrid_to_mean_position! — Method
regrid_to_mean_position!(config::AbstractConfig)Regrids the filtered data to the mean position. This function reads the combined output file, interpolates the filtered variables to the mean position, and saves the result in new variables within the same file.
The regridding process involves the following steps:
- Extracts positions: The mean positions (
xi_u,xi_v,xi_w) and filtered variable data are extracted for each time step. - Handles periodicity: For periodic dimensions (x, y, or z), the data is padded by repeating values near the boundaries to ensure accurate interpolation across the periodic boundaries.
- Interpolates data: A linear interpolator is used to map the filtered data from the irregular advected positions to the original, regular grid points.
- Saves new fields: The regridded data is saved as new variables in the combined output file, with a
_Lagrangian_filtered_at_meansuffix.
Arguments
config: An instance ofAbstractConfigcontaining the file paths, variable names, and grid information.extra_vars_to_regrid::Tuple{Vararg{String}}=(): Optional tuple of additional filtered variable names that have been calculated by the filter and also need to be regridded. Include velocities here if needed.
OceananigansLagrangianFilter.Utils.set_offline_BW2_filter_params — Method
set_offline_BW2_filter_params(; N::Int=1, freq_c::Real=1)Calculates the coefficients for a filter that has a frequency response given by a Butterworth filter with order N and cutoff frequency freq_c, squared.
Uses N exponentials and N/2 sets of coefficients (a,b,c,d). N should therefore be even, since exponentials come in pairs to ensure a real-valued filter.
However, the special case N=1 is allowed, which gives a single (real) exponential filter.
Frequency response: Ghat(omega) = 1 / (1 + (omega / freq_c)^(2*N)) Real filter shape: G(t) = sum_{i=1}^{N/2} exp(-c_i*abs(t))*(a_i*cos(d_i * abs(t)) + b_i*sin(d_i * abs(t)))
This function supports two types of filters:
- A single exponential filter when
N=1. This is a special case that generates two coefficients instead of 4. The unidirectional filter is a single exponential, andN_coeffs = 0.5. Onlya1andc1are returned. - A Butterworth squared filter for
N>1. This generatesN/2sets of coefficients (a,b,c,d), representing a filter of orderN. The coefficients are computed based on the filter's order and cutoff frequency.
Arguments
N: The order parameter for the filter.N=1for a single exponential. ForN>1, the filter's order isN. Must be a non-negative even integer.freq_c: The cutoff frequency of the filter. Must be a real number.
Returns
- A
NamedTuplecontaining the filter coefficients andN_coeffs, the number of coefficient pairs.
OceananigansLagrangianFilter.Utils.set_online_BW_filter_params — Method
set_online_BW_filter_params(; N::Int=1, freq_c::Real=1)Calculates the coefficients for a filter that has a frequency response given by a Butterworth filter with order N and cutoff frequency freq_c. Note that the frequency response is not squared, like in the offline forward-backward filter, and the frequency response is not real-valued, implying a nonlinear phase shift.
Uses N exponentials and N/2 sets of coefficients (a,b,c,d). N should therefore be even, since exponentials come in pairs to ensure a real-valued filter.
However, the special case N=1 is allowed, which gives a single (real) exponential filter.
Frequency response: abs(Ghat(omega)) = 1 / sqrt(1 + (omega / freq_c)^(2*N)) Real filter shape: G(t) = sum_{i=1}^{N/2} exp(-c_i*t)* (a_i*cos(d_i * t) + b_i*sin(d_i * t)) for t>=0, and 0 for t<0.
This function supports two types of filters:
- A single exponential filter when
N=1. This is a special case that generates two coefficients instead of 4. The unidirectional filter is a single exponential, andN_coeffs = 0.5. Onlya1andc1are returned. - A Butterworth filter for
N>1. This generatesN/2sets of coefficients (a,b,c,d), representing a filter of orderN. The coefficients are computed based on the filter's order and cutoff frequency.
Arguments
N: The order parameter for the filter.N=1for a single exponential. ForN>1, the filter's order isN. Must be a non-negative even integer.freq_c: The cutoff frequency of the filter. Must be a real number.
Returns
- A
NamedTuplecontaining the filter coefficients andN_coeffs, the number of coefficient pairs.
OceananigansLagrangianFilter.Utils.sum_forward_backward_contributions! — Method
sum_forward_backward_contributions!(config::AbstractConfig)Combines the output from the forward and backward filter simulations into a single output file. This function performs the final step of the offline filter algorithm by summing the contributions from each pass.
The function performs the following steps:
- Initializes the combined file: A new JLD2 file is created to store the final output.
- Copies metadata and unfiltered data: The file structure, metadata, and the original, unfiltered data are copied from the forward output file.
- Sums filtered contributions: For each filtered variable, the data from the backward output file is loaded as a
FieldTimeSeries. The data is then interpolated to match the time steps of the forward simulation, and the two datasets are summed and written to the combined output file.
Arguments
config: An instance ofAbstractConfigcontaining the file paths and variable names.extra_filtered_var_names::Tuple{Vararg{String}}=(): Optional tuple of additional filtered variable names that have been calculated by the filter and also need to be combined.extra_filtered_velocity_names::Tuple{Vararg{String}}=(): Optional tuple of additional filtered velocity names that have been calculated by the filter and also need to be combined.extra_original_data_names::Tuple{Vararg{String}}=(): Optional tuple of additional original names that have been output and should be copied to the combined output file.
OceananigansLagrangianFilter.Utils.update_input_data! — Method
update_input_data!(model::AbstractModel, input_data::NamedTuple)Updates the velocity and auxiliary fields of a simulation at the current simulation time t. This function is designed to be used as a callback in an Oceananigans Simulation at callsite UpdateStateCallsite().
The function performs two main tasks:
- Updates velocities: It sets the
u,v, andwvelocity fields of themodelto the corresponding data from thevelocity_dataFieldTimeSeriesat the current simulation time. - Updates auxiliary fields: It updates the auxiliary fields of the
modelwith the original data from thevar_dataFieldTimeSeries, which are used for forcing terms.
Arguments
model: The model.input_data: ANamedTuplecontainingvelocity_dataandvar_data, where each field is aTupleofFieldTimeSeriesobjects.
OceananigansLagrangianFilter.Utils.zero_closure_for_filtered_vars — Method
zero_closure_for_filtered_vars(config::AbstractConfig)Initializes the model's filtered tracer fields using the actual tracer fields that are assumed to have been already set. This improves the "spin-up" of the filter simulation by providing a good starting point.
The initialization formula depends on the number of filter coefficients (N_coeffs):
- For a single-exponential filter (
N_coeffs = 0.5), only the_C1tracer exists and is initialized. - For a multi-coefficient filter (
N_coeffs > 0.5), both the_Cand_Stracers for each coefficient are initialized.
Arguments
model: TheAbstractModelwhose tracers are to be initialized.config: An instance ofAbstractConfigwith the filter parameters.