tests/testthat/test-physics.R

test_that("norouzi_lambdas returns correct defaults", {
  lam <- norouzi_lambdas("norouzi")
  expect_equal(lam$lambda_wet, 1.0)
  expect_equal(lam$lambda_dry, 10.0)
  expect_equal(lam$lambda3,    1.0)
  expect_equal(lam$lambda4,    1000.0)
  expect_equal(lam$lambda5,    1000.0)
  expect_equal(lam$lambda6,    1.0)
})

test_that("norouzi_lambdas smooth config increases lambda3", {
  lam_n <- norouzi_lambdas("norouzi")
  lam_s <- norouzi_lambdas("smooth")
  expect_gt(lam_s$lambda3, lam_n$lambda3)
})

test_that("build_residual_sets returns expected structure", {
  df <- data.frame(
    clay      = runif(50, 5, 60),
    silt      = runif(50, 5, 50),
    sand_total = runif(50, 10, 80),
    Depth_num = runif(50, 2.5, 50)
  )
  sets <- build_residual_sets(df, c("clay", "silt", "sand_total", "Depth_num"),
                              S1 = 10L, S2 = 5L, S3 = 5L, S4 = 10L)

  expect_named(sets, c("set1", "set2", "set3", "set4"))
  expect_equal(nrow(sets$set1), 10L)
  expect_equal(nrow(sets$set2), 5L)
  expect_true("pF" %in% names(sets$set1))

  # S2 all at pF0 = 6.2
  expect_true(all(sets$set2$pF == 6.2))

  # S1 pF values within [5, 7.6]
  expect_true(all(sets$set1$pF >= 5.0 & sets$set1$pF <= 7.6))
})

test_that("build_residual_sets is reproducible with same seed", {
  df <- data.frame(clay = runif(30, 5, 60), silt = runif(30, 5, 50),
                   sand_total = runif(30, 10, 80))
  s1 <- build_residual_sets(df, c("clay","silt","sand_total"), seed = 42L,
                             S1=10L, S2=5L, S3=5L, S4=10L)
  s2 <- build_residual_sets(df, c("clay","silt","sand_total"), seed = 42L,
                             S1=10L, S2=5L, S3=5L, S4=10L)
  expect_equal(s1$set1$pF, s2$set1$pF)
  expect_equal(s1$set1$clay, s2$set1$clay)
})

test_that("S = 0 switches a residual term off instead of breaking", {
  df <- data.frame(clay = runif(30, 5, 60), silt = runif(30, 5, 50),
                   sand = runif(30, 5, 90), bd   = runif(30, 1.1, 1.6))
  xi <- names(df)

  ## Every term off: all four sets must be well-formed and empty. Before the
  ## S = 0 fix, the scalar-pF sets (set2, set3) errored here.
  s <- build_residual_sets(df, xi, S1 = 0L, S2 = 0L, S3 = 0L, S4 = 0L)
  for (nm in c("set1", "set2", "set3", "set4")) {
    expect_equal(nrow(s[[nm]]), 0L)
    expect_true(all(c(xi, "pF") %in% names(s[[nm]])))
  }

  ## Partially off: the enabled terms keep their requested sizes.
  s2 <- build_residual_sets(df, xi, S1 = 7L, S2 = 0L, S3 = 4L, S4 = 0L)
  expect_equal(vapply(s2, nrow, integer(1)),
               c(set1 = 7L, set2 = 0L, set3 = 4L, set4 = 0L))
  expect_true(all(s2$set1$pF >= 5.0 & s2$set1$pF <= 7.6))
  expect_true(all(s2$set3$pF == 7.6))
})

test_that("physics loss over empty collocation sets is 0, not NaN", {
  skip_if_not(requireNamespace("tensorflow", quietly = TRUE) &&
                reticulate::py_module_available("tensorflow"),
              "TensorFlow not available")

  df <- data.frame(clay = runif(30, 5, 60), silt = runif(30, 5, 50),
                   sand = runif(30, 5, 90), bd   = runif(30, 1.1, 1.6))
  xi     <- names(df)
  scaler <- fit_minmax(df, xi)
  mods   <- build_swrc_model(n_covariates = length(xi), K = 16L)

  to_t <- function(d) residual_to_tensors(d, scaler, K = 16L,
                                          knot_grid = seq(0, 1, length.out = 16L))

  ## All four off: the physics loss must be exactly 0. tf$reduce_mean over an
  ## empty tensor returns NaN, which used to propagate into the total loss and
  ## silently destroy training whenever the residuals were switched off.
  sets <- build_residual_sets(df, xi, S1 = 0L, S2 = 0L, S3 = 0L, S4 = 0L)
  L <- compute_physics_loss(mods$theta_model,
                            lapply(sets, to_t), training = FALSE)
  for (nm in names(L)) {
    v <- as.numeric(L[[nm]])
    expect_false(is.nan(v), info = nm)
    expect_equal(v, 0, info = nm)
  }

  ## One term on: that term is finite, the switched-off ones are exactly 0.
  sets2 <- build_residual_sets(df, xi, S1 = 0L, S2 = 5L, S3 = 0L, S4 = 0L)
  L2 <- compute_physics_loss(mods$theta_model,
                             lapply(sets2, to_t), training = FALSE)
  expect_true(is.finite(as.numeric(L2$L_phys)))
  expect_equal(as.numeric(L2$L_lin), 0)
  expect_equal(as.numeric(L2$L_sat), 0)
})

test_that("monotone = FALSE yields a free head and refuses theta_s", {
  skip_if_not(requireNamespace("tensorflow", quietly = TRUE) &&
                reticulate::py_module_available("tensorflow"),
              "TensorFlow not available")

  mono <- build_swrc_model(n_covariates = 4L, K = 16L, monotone = TRUE)
  free <- build_swrc_model(n_covariates = 4L, K = 16L, monotone = FALSE)

  ## Both expose the same interface, so downstream code is architecture-blind.
  expect_equal(dim(mono$theta_model$output)[[2]],
               dim(free$theta_model$output)[[2]])
  ## The free head is a different graph, not the same one relabelled.
  expect_false(identical(mono$theta_model$count_params(),
                         free$theta_model$count_params()))
  expect_true("theta_free" %in% vapply(free$theta_model$layers,
                                       function(l) l$name, character(1)))
  expect_true("theta_hat"  %in% vapply(mono$theta_model$layers,
                                       function(l) l$name, character(1)))
})

test_that("s3_form = \"equality\" penalises |theta(pF1)|, inequality only theta > 0", {
  skip_if_not(requireNamespace("tensorflow", quietly = TRUE) &&
                reticulate::py_module_available("tensorflow"),
              "TensorFlow not available")

  df <- data.frame(clay = runif(30, 5, 60), silt = runif(30, 5, 50),
                   sand = runif(30, 5, 90), bd   = runif(30, 1.1, 1.6))
  xi     <- names(df)
  scaler <- fit_minmax(df, xi)
  mods   <- build_swrc_model(n_covariates = length(xi), K = 16L)
  to_t   <- function(d) residual_to_tensors(d, scaler, K = 16L,
                                            knot_grid = seq(0, 1, length.out = 16L))
  sets <- lapply(build_residual_sets(df, xi, S1 = 0L, S2 = 0L, S3 = 20L,
                                     S4 = 0L), to_t)

  ineq <- compute_physics_loss(mods$theta_model, sets, training = FALSE,
                               s3_form = "inequality")
  eq   <- compute_physics_loss(mods$theta_model, sets, training = FALSE,
                               s3_form = "equality")

  ## |theta| >= relu(theta) pointwise, so the equality form can never be the
  ## smaller of the two.
  expect_gte(as.numeric(eq$L_neg), as.numeric(ineq$L_neg))
  ## A curve sitting below zero costs nothing under the published inequality
  ## but is penalised under the equality, which is the whole point. At
  ## initialisation theta(7.6) is non-zero, so the equality term is strictly
  ## positive. Note that neither form penalises theta == 0: the null curve
  ## satisfies both exactly, and only the data term rules it out.
  expect_gt(as.numeric(eq$L_neg), 0)

  ## The option must not touch the other three terms.
  for (nm in c("L_lin", "L_pos", "L_sat"))
    expect_equal(as.numeric(eq[[nm]]), as.numeric(ineq[[nm]]), info = nm)

  ## Default is the published form.
  dflt <- compute_physics_loss(mods$theta_model, sets, training = FALSE)
  expect_equal(as.numeric(dflt$L_neg), as.numeric(ineq$L_neg))

  ## An unknown value is rejected rather than silently ignored.
  expect_error(compute_physics_loss(mods$theta_model, sets, training = FALSE,
                                    s3_form = "nonsense"))
})

test_that("s3_form survives a fit and a save/load round trip", {
  skip_if_not(requireNamespace("tensorflow", quietly = TRUE) &&
                reticulate::py_module_available("tensorflow"),
              "TensorFlow not available")

  df <- prepare_swrc_data(swrc_example, depth_col = "depth")
  fit <- fit_swrc(df, x_inputs = c("clay", "silt", "bd_gcm3"),
                  s3_form = "equality", S1 = 0L, S2 = 0L, S3 = 10L, S4 = 0L,
                  epochs = 1L, verbose = FALSE)
  expect_identical(fit$s3_form, "equality")

  d <- file.path(tempdir(), paste0("s3form-", as.integer(runif(1, 1, 1e6))))
  dir.create(d, recursive = TRUE)
  on.exit(unlink(d, recursive = TRUE), add = TRUE)
  save_swrc_model(fit, dir = d, name = "eq")
  back <- load_swrc_model(dir = d, name = "eq")
  expect_identical(back$s3_form, "equality")

  ## A fit object from before the option existed must still load, as the
  ## published inequality form.
  meta_path <- file.path(d, "eq_meta.rds")
  meta <- readRDS(meta_path)
  meta$s3_form <- NULL
  saveRDS(meta, meta_path)
  old <- load_swrc_model(dir = d, name = "eq")
  expect_identical(old$s3_form, "inequality")
})

Try the soilFlux package in your browser

Any scripts or data that you put into this service are public.

soilFlux documentation built on Dec. 4, 2026, 5:10 p.m.