Building observations
It is recommended that you read the "Sample Builder" section before reading this section.
When handling weather and climate data, it can be tedious and error-prone when setting up the observation for calibration with EnsembleKalmanProcesses (or EKP for short). As such, ClimaCalibrate provides recipes for estimating the noise covariance matrix and packaging it, together with the observation and its metadata, into an EKP.Observation.
We start with a SampleCollection, which the SampleBuilder module produces by flattening one or more ClimaAnalysis.OutputVars into a matrix of samples. ObservationRecipe then takes that SampleCollection, estimates the noise covariance matrix from the samples, selects the sample at the specified index as the observation, and builds the EKP.Observation used in the calibration.
How do I use this to set up observation for calibration with EKP?
All functions assume that any data preprocessing is done with ClimaAnalysis.
Covariance Estimators
There are currently three covariance estimators, DiagonalCovariance, SVDplusDCovariance, and SVDplusModelErrorCovariance, which are subtypes of AbstractCovarianceEstimator. Each estimates the noise covariance matrix from the matrix of samples in a SampleCollection. DiagonalCovariance approximates the observation noise covariance as a diagonal matrix, whose diagonal is described by a diagonal term or given directly as a Diagonal matrix or a UniformScaling. For example, DiagonalCovariance(ScalarDiagonal(2.0)) is twice the identity matrix. SVDplusDCovariance approximates the variances and the correlations between points from, often limited, time series observations. SVDplusModelErrorCovariance is a SVDplusDCovariance whose diagonal term is the variance that the low-rank part does not explain plus a model error term. Because SVDplusDCovariance and SVDplusModelErrorCovariance estimate them across samples, they require at least two samples (columns), whereas DiagonalCovariance works with a single sample if its diagonal does not depend on the samples, as with a ScalarDiagonal.
Necessary data preprocessing
In most cases, the OutputVars represent time series data of summary statistics. For example, to compute seasonal averages of a OutputVar, one can use ClimaAnalysis.average_season_across_time, which will produce a OutputVar that can be used with SVDplusDCovariance.
import ClimaAnalysis
obs_var = ClimaAnalysis.OutputVar(
"precip.mon.mean.nc",
"precip",
new_start_date = start_date,
shift_by = Dates.firstdayofmonth,
)
# -- preprocessing for units, times, grid, etc. --
seasonal_averages = ClimaAnalysis.average_season_across_time(obs_var)Observation
After preprocessing the OutputVars so that they represent time series data of summary statistics, you build the samples with functions provided by the SampleBuilder module and pass a covariance estimator, the resulting SampleCollection, and the index of the sample to use as the observation to ObservationRecipe.observation, as shown below. See the building samples page for the details of build_samples_by_times.
import ClimaAnalysis
import EnsembleKalmanProcesses as EKP
import ClimaCalibrate
import ClimaCalibrate.ObservationRecipe
import ClimaCalibrate.SampleBuilder
# Vars are OutputVars preprocessed to ensure consistent units, times,
# and grid as the diagnostics produced from the model.
# In this example, we want to calibrate with seasonal averages, so we use
# ClimaAnalysis.average_season_across_time
vars = ClimaAnalysis.average_season_across_time.(vars)
# We need the start and end dates of each sample. To find these, we can use the
# function below. In this example, the dates in `vars` are all the same. For
# debugging, it is helpful to use `ClimaAnalysis.dates(var)`.
sample_date_ranges =
ObservationRecipe.seasonally_aligned_yearly_sample_date_ranges(first(vars))
# Build the samples (one per date range)
sample_collection =
SampleBuilder.build_samples_by_times(
vars,
sample_date_ranges;
FT = Float32
)
# We choose SVDplusDCovariance
covar_estimator = ObservationRecipe.SVDplusDCovariance(
ObservationRecipe.ModelErrorScaleDiagonal(Float32(0.05)) .+
ObservationRecipe.ScalarDiagonal(Float32(1e-6)),
)
# Finally, we form the observation, using the first sample as the observation
# in the calibration
obs = ObservationRecipe.observation(covar_estimator, sample_collection, 1)Transforming the samples
To weight the samples used for the covariance matrix, pipe the sample collection into a transform before passing it to observation (see transformations):
# One weight for each variable in vars, which has three variables here
transformed_collection =
sample_collection |> SampleBuilder.PerVariableWeighting([2.0, 1.0, 1.0])
obs = ObservationRecipe.observation(covar_estimator, transformed_collection, 1)The observation and its metadata come from the untransformed samples. What happens to the transforms depends on the estimator.
DiagonalCovariancethrows an error for any transform.SVDplusDCovarianceapplies the transforms before computing the SVD and the diagonal term.SVDplusModelErrorCovarianceapplies the transforms in the same way asSVDplusDCovariance.
Putting it together, here is an example of using transforms to weight the covariance matrix.
# vars contains the variables pr, tas, and rsut
transformed_collection =
sample_collection |>
SampleBuilder.LatitudeWeighting() |>
SampleBuilder.PerVariableWeighting(
Dict("pr" => 2.0, "tas" => 1.0, "rsut" => 1.0),
)
covar_estimator = ObservationRecipe.SVDplusDCovariance(
ObservationRecipe.ModelErrorScaleDiagonal(Float32(0.05)) .+
ObservationRecipe.ScalarDiagonal(Float32(1e-6)),
)
obs = ObservationRecipe.observation(covar_estimator, transformed_collection, 1)The covariance matrix of obs is estimated from the weighted samples, while the observation itself is unweighted, so it can be compared directly with the untransformed output of the model in the G ensemble matrix.
Metadata
When creating an observation with observation, metadata is extracted from the OutputVars and attached to the observation. The metadata for each observation can be accessed with EKP.get_metadata(obs::EKP.Observation) and the metadata for each iteration can be accessed with ClimaCalibrate.get_metadata_for_nth_iteration. The metadata can be used with ClimaAnalysis.unflatten to reconstruct the original OutputVar before flattening. See the ClimaAnalysis documentation about ClimaAnalysis.FlatVar for more information.
Debugging observational and simulation data
When setting up a calibration, it may be helpful to visualize the EKP.Observations or inspect the observational data and metadata together. To help with this, ObservationRecipe provides several functions that reconstruct the underlying data back into OutputVars:
reconstruct_varsreconstructs the samples of anEKP.Observationas a vector ofOutputVars.reconstruct_diag_covreconstructs the diagonal of the covariance matrix of anEKP.Observationas a vector ofOutputVars (only supported for diagonal covariance matrices).reconstruct_greconstructs the G ensemble matrix of theitth iteration as a matrix ofOutputVars.reconstruct_g_meanreconstructs the mean forward model evaluation of theitth iteration as a vector ofOutputVars.reconstruct_g_mean_finalreconstructs the mean forward model evaluation of the last iteration as a vector ofOutputVars.reconstruct_residualreconstructs the normalized residual(mean(G) - obs) / σof theitth iteration as a vector ofOutputVars, whereσis the square root of the diagonal of the observation noise covariance.
# obs is an EKP.Observation
# ekp is the EKP.EnsembleKalmanProcess
# it is the iteration index
ObservationRecipe.reconstruct_vars(obs)
# Reconstructing the diagonal of a covariance matrix as an OutputVar is only
# supported for diagonal covariance matrices
ObservationRecipe.reconstruct_diag_cov(obs)
ObservationRecipe.reconstruct_g(ekp, it)
ObservationRecipe.reconstruct_g_mean(ekp, it)
ObservationRecipe.reconstruct_g_mean_final(ekp)
ObservationRecipe.reconstruct_residual(ekp, it)Creating custom covariance estimators
In the cases where the provided covariance estimators are not sufficient, it is possible to create your own covariance estimator using the functionality provided by ClimaCalibrate and ClimaAnalysis.
The steps are:
- Define a struct that subtypes
ObservationRecipe.AbstractCovarianceEstimator. Any fields of this struct will be available when implementing thecovariancemethod. - Implement a method of
covariancethat dispatches on your struct, with the signatureObservationRecipe.covariance(estimator::YourType, sample_collection). It must return a noise covariance matrix.
What you can use
The sample_collection argument is a SampleCollection, which stores a matrix of samples and a matrix of metadata, or a TransformedSampleCollection if the samples were piped into transforms. Here's a collection of helpful functions from the SampleBuilder module when creating the covariance matrix.
get_samples: return the full sample matrix.get_metadata: return the full metadata matrix. Each column holds oneClimaAnalysis.Var.Metadataper variable.num_samples: return the number of samples.
You can get a SampleCollection from a TransformedSampleCollection with either apply_transform(sample_collection) or base(sample_collection).
The covariance you return must be a square matrix whose side length equals the number of rows of the sample matrix and must not contain NaN or Inf.
build_samples checks that the short names, the units, the flattened lengths, and the dimensions agree across the samples, so for those it is fine to work with a single column (e.g. view(get_metadata(sample_collection), :, 1)).
There are two things to keep in mind.
First, the values of the time dimension are not the same across the columns. Each sample can span a different time range, which is exactly what build_samples_by_times produces. If your estimator depends on the times or the dates of the samples, read them from all columns rather than from one.
Second, the dimensions passed to the ignore_dims of build_samples are not checked either, so their values can differ across the columns as well. If your estimator reads the values of a dimension from a single column, check that dimension across the columns first. The provided estimators do this for the latitudes when latitude weighting is enabled, since the weights of the first sample are applied to all samples.
Example: per-variable constant variance
The following estimator gives each variable its own constant variance, filling that variable's block of a diagonal covariance matrix.
import ClimaAnalysis
import ClimaCalibrate.ObservationRecipe
import ClimaCalibrate.SampleBuilder
import LinearAlgebra: Diagonal
# One variance per variable, in the same order as the OutputVars used to build
# the samples.
struct PerVariableScalar <: ObservationRecipe.AbstractCovarianceEstimator
variances::Vector{Float64}
end
function ObservationRecipe.covariance(
estimator::PerVariableScalar,
sample_collection,
)
# Only the metadata is used, so the transforms do not matter
sample_collection = SampleBuilder.base(sample_collection)
FT = eltype(SampleBuilder.get_samples(sample_collection))
# Only the flattened lengths are needed here, and those are the same across
# the samples, so the first column is enough
metadata = view(SampleBuilder.get_metadata(sample_collection), :, 1)
# Repeat each variance over its variable's flattened block, then stack.
diag_cov = reduce(
vcat,
fill(FT(v), ClimaAnalysis.flattened_length(m)) for
(v, m) in zip(estimator.variances, metadata)
)
return Diagonal(diag_cov)
endUsing it is the same as for the built-in estimators:
julia> sample_collectionSampleCollection (9×1 matrix of Float32) 1 sample(s), each 9 value(s) from 2 variable(s) Short name Units Indices Dimensions ---------------------------------------------- pr mm/day 1:6 lat (2), time (3) rsut W m-2 7:9 lat (3), time (1)julia> estimator = PerVariableScalar([0.1, 0.5])Main.PerVariableScalar([0.1, 0.5])julia> obs = ObservationRecipe.observation(estimator, sample_collection, 1);julia> EKP.get_covs(obs)1-element Vector{LinearAlgebra.Diagonal{Float32, Vector{Float32}}}: Diagonal(Float32[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.5, 0.5, 0.5])
Diagonal terms
The covariance matrix produced by SVDplusDCovariance observation recipe is the sum of a low rank approximation of the covariance matrix computed from the samples and a diagonal matrix. The covariance matrix produced by the DiagonalCovariance observation recipe is only the diagonal matrix. In both cases, the diagonal matrix is described by a diagonal term, a subtype of ObservationRecipe.AbstractDiagonalTerm. A diagonal term describes how the matrix should be built from a SampleCollection. It is not a matrix itself.
You can pass your own diagonal term as the first positional argument to SVDplusDCovariance(::AbstractDiagonalTerm) or DiagonalCovariance.
The built-in diagonal terms are
ScalarDiagonal: the entries are constant for each variable, with a scalar chosen per variable.ModelErrorScaleDiagonal: the entries are(scale * mean)^2, where the mean of each entry is taken across the samples, ignoringNaNs, and the scale is the model error scale of the variable that the entry belongs to.VarianceDiagonal: the entries are the variance of each row of the sample matrix, taken across the samples and ignoringNaNs.ResidualVarianceDiagonal: the entries are the variance of each row of the sample matrix minus the diagonal of the truncated SVD of the sample covariance matrix.QuantileDiagonal: the entries are constant for each variable, where the constant is a quantile of the entries that another diagonal term produces for that variable.LatitudeWeightDiagonal: the entries are the latitude weights1 / max(cosd(lat), min_cosd_lat)for the weighted variables and one for the other variables.
Diagonal terms can be combined with broadcasting, which produces a BroadcastedDiagonal. Once every term is computed, the expression is broadcast over the resulting Diagonal matrices. For example, ModelErrorScaleDiagonal(0.05) .+ ScalarDiagonal(1e-6) sums two terms and 2.0 .* VarianceDiagonal() scales one, but VarianceDiagonal() .+ 1e-6 is an error since adding a scalar to a Diagonal matrix does not produce a diagonal matrix. A Diagonal matrix can be mixed in as well.
julia> sample_collectionSampleCollection (8×3 matrix of Float64) 3 sample(s), each 8 value(s) from 2 variable(s) Short name Units Indices Dimensions ---------------------------------------------- pr mm/day 1:5 lat (5), time (1) rsut W m-2 6:8 lat (3), time (1)julia> diagonal_term = ObservationRecipe.ScalarDiagonal([1e-6, 1e-4]) .+ ObservationRecipe.ModelErrorScaleDiagonal(0.05);julia> covar_estimator = ObservationRecipe.SVDplusDCovariance(diagonal_term);julia> covariance_matrix = ObservationRecipe.covariance(covar_estimator, sample_collection);julia> covariance_matrix.diag_cov8×8 LinearAlgebra.Diagonal{Float64, Vector{Float64}}: 0.010001 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.040001 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.090001 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.160001 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.250001 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.0101 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.0401 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 0.0901
Creating custom diagonal terms
If the built-in terms are not sufficient, then define a struct that subtypes ObservationRecipe.AbstractDiagonalTerm and implement a method of compute_diagonal with the signature ObservationRecipe.compute_diagonal(term::YourType, sample_collection). The method must return an n × n diagonal matrix, where n is the number of rows of get_samples(sample_collection). It is your responsibility to ensure the entries of the diagonal matrix make sense. It is recommended to match the element type of the samples, which the built-in terms do.
Besides get_samples and get_metadata, the function var_indices is useful when the diagonal should depend on the variable. It returns the rows of the samples that belong to each variable, so view(get_samples(sample_collection), var_indices(sample_collection)[i], :) is the block of the samples for the i-th variable.
For example, the following term fills each variable's block with the largest squared value in that block:
import LinearAlgebra: Diagonal
import ClimaCalibrate: ObservationRecipe, SampleBuilder
struct MaxSquaredDiagonal <: ObservationRecipe.AbstractDiagonalTerm end
function ObservationRecipe.compute_diagonal(
::MaxSquaredDiagonal,
sample_collection,
)
samples = SampleBuilder.get_samples(sample_collection)
diag = similar(samples, size(samples, 1))
for rows in SampleBuilder.var_indices(sample_collection)
diag[rows] .= maximum(abs2, view(samples, rows, :))
end
return Diagonal(diag)
endA custom term composes with the built-in ones and can be wrapped in QuantileDiagonal:
julia> term = ObservationRecipe.QuantileDiagonal(0.5, MaxSquaredDiagonal()) .+ ObservationRecipe.ScalarDiagonal(1e-6);julia> ObservationRecipe.compute_diagonal(term, sample_collection)8×8 LinearAlgebra.Diagonal{Float64, Vector{Float64}}: 225.0 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 225.0 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 225.0 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 225.0 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 225.0 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 81.0 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 81.0 ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ ⋅ 81.0
Frequently asked questions
Q: I need to compute g_ensemble and I do not know how the data of the OutputVars is flattened.
A: When forming the sample, the data in a OutputVar is flattened using ClimaAnalysis.flatten. See ClimaAnalysis.flatten in the ClimaAnalysis documentation for more information. The order of the variables in the observation is the same as the order of the OutputVars when creating the EKP.Observation using ObservationRecipe.observation. If you are using ObservationRecipe, it is recommended that you also use GEnsembleBuilder which simplifies building the G ensemble matrix.
Q: How is the name of the observation determined?
A: By default, the name of the observation is determined by the short name in the attributes of the OutputVar. If there are multiple OutputVars, then the name is all the short names separated by semicolons. If a OutputVar has no short name, the empty string will be used instead and a warning is emitted. You can override this by passing the name keyword argument to ObservationRecipe.observation.
Q: What are the model error scale and regularization terms when making a covariance matrix?
A: The model error scale and regularization terms are used to inflate the diagonal of the observation covariance matrix to reflect estimates of measurement error. You can add a fixed percentage inflation of the noise due to the model error to the covariance matrix with a ModelErrorScaleDiagonal term. Additionally, to prevent very small variance along the diagonal of the covariance matrix, you can add a regularization with a ScalarDiagonal term. The regularization can also be a QuantileDiagonal, which sets the regularization from a quantile of the model error scale instead of a fixed value, as in QuantileDiagonal(0.05, ModelErrorScaleDiagonal(0.05)).
SVDplusDCovariance and DiagonalCovariance accept them, since both take a diagonal term.
SVDplusDCovariance builds a covariance of the form SVD + D, where D is the diagonal matrix built from the diagonal term, such as (model_error_scale * mean(samples))^2 + regularization for ModelErrorScaleDiagonal(model_error_scale) .+ ScalarDiagonal(regularization). The SVD term alone has rank at most one less than the number of samples, so with fewer samples than observation entries, which is the usual case, the covariance is singular and EKP cannot invert it unless D is positive. Use a diagonal term with positive entries.
Q: How do I apply latitude weighting to the covariance matrix?
A: The weight is 1 / max(cosd(lat), min_cosd_lat) which is applied to the diagonal for diagonal covariance matrices and sqrt(1 / max(cosd(lat), min_cosd_lat)) which is applied to the samples for SVDplusDCovariance matrices. This inflates the variance of the smaller grid cells toward the poles and so gives them less weight in the misfit. The min_cosd_lat keyword argument of LatitudeWeighting and LatitudeWeightDiagonal (default 0.1) caps the weight at 1 / min_cosd_lat. Without a cap the weight grows without bound toward the poles, where cosd(lat) reaches zero, and the variances spans so many orders of magnitude that the covariance is badly conditioned.
For SVDplusDCovariance, to apply latitude weighting, you can pipe the samples into a LatitudeWeighting:
covar_estimator = ObservationRecipe.SVDplusDCovariance(
ObservationRecipe.ModelErrorScaleDiagonal(0.05) .+
ObservationRecipe.ScalarDiagonal(1e-6),
)
weighted_collection = sample_collection |> SampleBuilder.LatitudeWeighting()
obs = ObservationRecipe.observation(covar_estimator, weighted_collection, 1)DiagonalCovariance does not accept transforms. Multiply its diagonal term by a LatitudeWeightDiagonal instead.
covar_estimator = ObservationRecipe.DiagonalCovariance(
ObservationRecipe.VarianceDiagonal() .*
ObservationRecipe.LatitudeWeightDiagonal(),
)
obs = ObservationRecipe.observation(covar_estimator, sample_collection, 1)The variables without a latitude dimension are not weighted, and ObservationRecipe.LatitudeWeightDiagonal(["pr"]) weights only pr.
Q: How do I make a variable count more or less in the calibration?
A: Pipe the samples into a PerVariableWeighting. The weights must be positive, and a weight smaller than 1 makes a variable count more. For example, PerVariableWeighting(Dict("pr" => 0.5, "rsut" => 1.0)) makes pr count four times as much. See transformations for more about the transforms.