Apply the spatial decorrelation transformation for spatial stream network data, allowing for random effects, anisotropy, partition factors, and big data methods.

ssn_decorrelate(
  formula,
  ssn.object,
  tailup_type = "none",
  taildown_type = "none",
  euclid_type = "none",
  nugget_type = "nugget",
  tailup_params,
  taildown_params,
  euclid_params,
  nugget_params,
  additive,
  algorithm = "ranger",
  statistic = "RMSPE",
  training,
  evaluate_test,
  anisotropy = FALSE,
  random,
  randcov_params,
  partition_factor,
  ordering,
  local,
  grid,
  dense_grid,
  ...
)

# S3 method for class 'ssn_decorrelate'
tidy(x, ...)

Arguments

formula

A two-sided linear formula describing the fixed effect structure of the model, with the response to the left of the ~ operator and the terms on the right, separated by + operators. . on the right-hand side represents every variable in ssn.object$obs except the response and geometry column.

ssn.object

A spatial stream network object with class SSN.

tailup_type, taildown_type, euclid_type, nugget_type

Covariance types specified as in ssn_lm().

tailup_params, taildown_params, euclid_params, nugget_params

Known covariance parameter objects to be used in the spatial decorrelation transformation. See tailup_params(), taildown_params(), euclid_params(), and nugget_params().

additive

Additive-function variable for the tail-up covariance, as in ssn_lm().

algorithm

The machine learning algorithm applied. Available options include "ranger", "randomForest", and "xgboost". "ranger" specifies a random forest via ranger::ranger(). "randomForest" specifies a random forest via randomForest::randomForest(). "xgboost" specifies a boosted decision tree ensemble via xgboost::xgboost().

statistic

The statistic used to evaluate fit in the test data. Available options include "bias" (mean bias), "MSPE" (mean-squared-prediction error), "RMSPE" (root-mean-squared-prediction error) and "cor2" (the predictive R-squared; i.e., the squared correlation between observations and predictions).

training

A list controlling how the training and test data are assigned when evaluating test data performance. The following arguments detail this process:

  • method: The method used to evaluate test data performance. "split" will split ssn.object$obs up into distinct training and test sets proportionally based on p. "cv" will split ssn.object$obs up via k-fold cross validation based on folds, the number of folds.

  • p: The proportion (a number between zero and one) of observations in ssn.object$obs that should be assigned to the training data. The default is 0.8, which means that 80% of the observations are assigned to the training data and 20% to the test data. Ignored if training_index or test_index are provided.

  • replicate: The number of times to replicate "split" with different random training and test assignments.

  • folds: The number of folds to use in cross-validation. Requires method = "cv". Ignored if folds_index is specified. The default is 5, matching the 80/20 default split above.

  • training_index: A numeric vector that specifies which rows (i.e., indices) of ssn.object$obs should be assigned to the training data. If omitted, defaults to the rows which are not already included in test_index.

  • test_index: A numeric vector that specifies which rows (i.e., indices) of ssn.object$obs should be assigned to the test data. If omitted, defaults to the rows which are not already included in training_index.

  • folds_index: A numeric vector that specifies which rows of ssn.object$obs are associated with each cross-validation fold. Requires method = "cv".

If omitted, training is transformed into list(method = "split", p = 0.8, replicate = 1).

evaluate_test

A logical indicating whether a grid should be constructed and evaluated when spatial decorrelation parameters are known (i.e., *_params are all specified, and, if random effects are included, randcov_params is specified). If TRUE, constructs and evaluates the grid after assigning observations to test and training data sets. If any parameters (spatial or random effects) are estimated via a grid search, evaluate_test is set to TRUE.

anisotropy

A logical indicating whether Euclidean (geometric) anisotropy should be modeled. Not required if euclid_params is provided with a nonzero rotate or a scale less than one. When anisotropy is TRUE, computational times can significantly increase. The default is FALSE.

random

A one-sided linear formula describing the random effect structure of the model. Terms are specified to the right of the ~ operator. Each term has the structure x1 + ... + xn | g1/.../gm, where x1 + ... + xn specifies the model for the random effects and g1/.../gm is the grouping structure. Separate terms are separated by + and must generally be wrapped in parentheses. Random intercepts are added to each model implicitly when at least one other variable is defined. If a random intercept is not desired, this must be explicitly defined (e.g., x1 + ... + xn - 1 | g1/.../gm). If only a random intercept is desired for a grouping structure, the random intercept must be specified as 1 | g1/.../gm. Note that g1/.../gm is shorthand for (1 | g1/.../gm). If only random intercepts are desired and the shorthand notation is used, parentheses can be omitted.

randcov_params

An object from spmodel::randcov_params() that contains the random effect variances used by the spatial decorrelation transformation.

partition_factor

A one-sided linear formula with a single term specifying the partition factor. The partition factor assumes observations from different levels of the partition factor are uncorrelated.

ordering

The data ordering applied. Available options include "pid", "grts", "maxmin", "middleout", "outsidein", "coordinate", "random", and "none". "pid" applies ordering by point ID from the network geometry, with network ID used to break ties. "grts" applies ordering using a spatially balanced GRTS sample via spsurvey::grts(). "maxmin" applies maximum minimum distance ordering via GPvecchia::order_maxmin_exact(). "middleout" applies middle out ordering via GPvecchia::order_middleout(). "outsidein" applies outside in ordering via GPvecchia::order_outsidein(). "coordinate" applies coordinate ordering via GPvecchia::order_coordinate(..., coordinate = c(1, 2)), which orders from bottom-left to top-right of the spatial domain. "random" applies a completely random ordering. "none" applies no random ordering. The default is "pid". "maxmin", "middleout", "outsidein", and "coordinate" require GPvecchia; "grts" requires spsurvey.

local

An optional logical or list controlling the big data approximation. If omitted, local is set to TRUE or FALSE based on the sample size (the number of non-missing observations in ssn.object$obs) – if the sample size exceeds 5,000, local is set to TRUE. Otherwise it is set to FALSE. If local is FALSE, no big data approximation is implemented. If a list is provided, the following arguments detail the big data approximation:

  • method: The big data approximation method. If method = "all", all earlier observations in the ordering are used and size is ignored. If method = "covariance", the size data observations with the highest absolute covariance among earlier observations are used. The default is "covariance".

  • size: The number of data observations to use when method is "covariance". The default is 30.

  • parallel: If TRUE, parallel processing via the parallel package is used. The default is FALSE.

  • ncores: If parallel = TRUE, the number of cores to parallelize over. The default is the number of available cores on your machine.

When local is a list, at least one list element must be provided to initialize default arguments for the other list elements. If local is TRUE, defaults for local are chosen such that local is transformed into list(size = 30, method = "covariance", parallel = FALSE).

grid

An explicit grid of parameter values by which to evaluate fit. The names of grid must contain all the names returned by ssn_decorrelate_grid(formula, ssn.object, ...).

dense_grid

If grid is not provided, dense_grid is a logical which controls the density of the constructed grid to be evaluated. If dense_grid is TRUE, a denser grid is used. If dense_grid is FALSE, a sparser grid is used. By default, dense_grid is FALSE.

...

Other arguments to the functions called by algorithm.

x

A fitted model from ssn_decorrelate().

Value

A list with many elements that store information about the fitted model object:

  • algorithm: The machine learning algorithm used.

  • decorrelate_data: The output of ssn_decorrelate_data() applied to ssn.object.

  • fit: The fitted machine learning model object applied to the decorrelated data.

  • grid: If used, the grid of spatial decorrelation parameters evaluated and their corresponding metrics when applied to the test data.

  • newdata: The name ".missing" when observations with NA response values are stored as prediction data, or NULL otherwise.

  • training: If used, the observations assigned to each training and test data set.

  • test: If used, a list with mean bias (bias), mean-squared-prediction error (MSPE), root-mean-squared-prediction error (RMSPE), and predictive R-squared (cor2) for the candidate selected by statistic.

Details

The spatial decorrelation transformation is a preprocessing transformation that reduces the impacts of spatial dependence (i.e., covariance, correlation) on machine learning models. Predictions are made on the decorrelated scale and then recorrelated to account for spatial dependence. See Heaton et al., 2025 for details.

tailup_type Details: Let \(D\) be a matrix of hydrologic distances, \(W\) be a diagonal matrix of weights from additive, \(r = D / range\), and \(I\) be an identity matrix. Then parametric forms for flow-connected elements of \(R(zu)\) are given below:

  • linear: \((1 - r) * (r <= 1) * W\)

  • spherical: \((1 - 1.5r + 0.5r^3) * (r <= 1) * W\)

  • exponential: \(exp(-r) * W\)

  • mariah: \(log(90r + 1) / 90r * (D > 0) + 1 * (D = 0) * W\)

  • epa: \((D - range)^2 * F * (r <= 1) * W / 16range^5\)

  • gaussian: \(2 exp(-r^2) * (1 - pnorm(r * 2^{1/2})) * W\)

  • wave: \(\rho_c(D) * W\), see tailup_initial().

  • none: \(I\) * W

Details describing the F matrix in the epa covariance are given in Garreta et al. (2010). Flow-unconnected elements of \(R(zu)\) are assumed uncorrelated. Observations on different networks are also assumed uncorrelated.

taildown_type Details: Let \(D\) be a matrix of hydrologic distances, \(r = D / range\), and \(I\) be an identity matrix. Then parametric forms for flow-connected elements of \(R(zd)\) are given below:

  • linear: \((1 - r) * (r <= 1)\)

  • spherical: \((1 - 1.5r + 0.5r^3) * (r <= 1)\)

  • exponential: \(exp(-r)\)

  • mariah: \(log(90r + 1) / 90r * (D > 0) + 1 * (D = 0)\)

  • epa: \((D - range)^2 * F1 * (r <= 1) / 16range^5\)

  • gaussian: \(0\)

  • wave: \(\rho_c(D)\), see taildown_initial().

  • none: \(I\)

Now let \(A\) be a matrix that contains the shorter of the two distances between two sites and the common downstream junction, \(r1 = A / range\), \(B\) be a matrix that contains the longer of the two distances between two sites and the common downstream junction, \(r2 = B / range\), and \(I\) be an identity matrix. Then parametric forms for flow-unconnected elements of \(R(zd)\) are given below:

  • linear: \((1 - r2) * (r2 <= 1)\)

  • spherical: \((1 - 1.5r1 + 0.5r2) * (1 - r2)^2 * (r2 <= 1)\)

  • exponential: \(0\)

  • mariah: \((log(90r1 + 1) - log(90r2 + 1)) / (90r1 - 90r2) * (A =/ B) + (1 / (90r1 + 1)) * (A = B)\)

  • epa: \((B - range)^2 * F2 * (r2 <= 1) / 16range^5\)

  • gaussian: \(2 exp(-(B - A) / range) * (1 - pnorm(r * 2^{1/2})) * W\)

  • wave: \(\rho_u(A, B)\), see taildown_initial().

  • none: \(I\)

Details describing the F1 and F2 matrices in the epa covariance are given in Garreta et al. (2010). Observations on different networks are assumed uncorrelated.

euclid_type Details: Let \(D\) be a matrix of Euclidean distances, \(r = D / range\), and \(I\) be an identity matrix. Then parametric forms for elements of \(R(ze)\) are given below:

  • exponential: \(exp(- r )\)

  • spherical: \((1 - 1.5r + 0.5r^3) * (r <= 1)\)

  • gaussian: \(exp(- r^2 )\)

  • cubic: \((1 - 7r^2 + 8.75r^3 - 3.5r^5 + 0.75r^7) * (r <= 1)\)

  • pentaspherical: \((1 - 1.875r + 1.25r^3 - 0.375r^5) * (r <= 1)\)

  • circular: \(1 - (2 / \pi) * (r * sqrt(1 - r^2) + \arcsin(r))\) for \(0 \le r \le 1\), and zero for \(r > 1\)

  • wave: \(sin(r) * (h > 0) / r + (h = 0)\)

  • jbessel: \(Bj(h * range)\), Bj is Bessel-J function

  • gravity: \((1 + r^2)^{-0.5}\)

  • rquad: \((1 + r^2)^{-1}\)

  • magnetic: \((1 + r^2)^{-1.5}\)

  • matern: \(2^{1-extra} eta^{extra} K_{extra}(eta) / Gamma(extra)\), where \(eta = \sqrt{2 extra} D / range\)

  • cauchy: \((1 + r^2)^{-extra}\)

  • pexponential: \(exp(-D^{extra} / range)\)

  • none: \(I\)

The powered-exponential range has units of distance raised to extra.

nugget_type Details: Let \(I\) be an identity matrix and \(0\) be the zero matrix. Then parametric forms for elements the nugget variance are given below:

  • nugget: \(I\)

  • none: \(0\)

In short, the nugget effect is modeled when nugget_type is "nugget" and omitted when nugget_type is "none".

estmethod Details: The various estimation methods are

  • reml: Maximize the restricted log-likelihood.

  • ml: Maximize the log-likelihood.

anisotropy Details: By default, all Euclidean covariance parameters except rotate and scale as well as all random effect variance parameters are assumed unknown, requiring estimation. If either rotate or scale are given values other than 0 and 1 (respectively) in euclid_params(), anisotropy is implicitly set to TRUE. (Geometric) Anisotropy is modeled by transforming a Euclidean covariance function that decays differently in different directions to one that decays equally in all directions via rotation and scaling of the original Euclidean coordinates. The rotation is controlled by the rotate parameter in \([0, \pi]\) radians. The scaling is controlled by the scale parameter in \([0, 1]\). The anisotropy correction involves first a rotation of the coordinates clockwise by rotate and then a scaling of the coordinates' minor axis by the reciprocal of scale. The Euclidean covariance is then computed using these transformed coordinates.

random Details: If random effects are used, the model can be written as \(y = X \beta + Z1u1 + ... Zjuj + zu + zd + ze + n\), where each Z is a random effects design matrix and each u is a random effect.

partition_factor Details: The partition factor can be represented in matrix form as \(P\), where elements of \(P\) equal one for observations in the same level of the partition factor and zero otherwise. The covariance matrix involving only the spatial and random effects components is then multiplied element-wise (Hadamard product) by \(P\), yielding the final covariance matrix.

training Details: When replicate or the number of cross validation folds is at least two, there are separate grids evaluated for each replication (or fold). Statistics in each grid are averaged across replications (or folds) to determine a final grid ranked by statistic.

local Details: The big data approximation works by leveraging the conditional nature of the spatial decorrelation transformation via the Vecchia approximation. The Vecchia approximation enables efficient computation of the conditional distribution by considering only the size most relevant observations in the ordering (rather than using all the observations).

Observations with NA response values are removed for model fitting, but their values can be predicted afterwards by running predict(object).

References

Matthew J. Heaton, Andrew Millane, and Jake S. Rhodes. 2025. A Scalable Spatial Decorrelation Preprocessing Approach for Machine and Deep Learning. Journal of Data Science. 1-15, DOI 10.6339/25-JDS1210

Examples

# \donttest{
# Copy the mf04p .ssn data to a local directory and read it into R
# When modeling with your .ssn object, you will load it using the relevant
# path to the .ssn data on your machine
copy_lsn_to_temp()
temp_path <- paste0(tempdir(), "/MiddleFork04.ssn")
mf04p <- ssn_import(temp_path,
  predpts = "pred1km", overwrite = TRUE
)
ssn_create_distmat(mf04p, predpts = "pred1km", overwrite = TRUE)
fit <- ssn_decorrelate(
  Summer_mn ~ ELEV_DEM, mf04p, tailup_type = "exponential",
  taildown_type = "exponential", euclid_type = "exponential",
  additive = "afvArea", dense_grid = FALSE
)
#> Error in ssn_decorrelate(Summer_mn ~ ELEV_DEM, mf04p, tailup_type = "exponential",     taildown_type = "exponential", euclid_type = "exponential",     additive = "afvArea", dense_grid = FALSE): could not find function "ssn_decorrelate"
tidy(fit$grid)
#> Error in eval(expr, envir, enclos): object 'fit' not found
head(predict(fit, "pred1km"))
#> Error in eval(expr, envir, enclos): object 'fit' not found
# }