## Window tables reveal how association direction changes over the sample space.
local({
  set.seed(12345)
  n <- 520
  x <- runif(n)
  y <- (x - 0.5)^2 + rnorm(n, sd = 0.022)
  structure <- fes(
    x,
    y,
    K1 = 4,
    K2 = 4,
    M = 4,
    return.details = TRUE
  )
  windows <- structure$significant.windows
  windows$x_center <- (windows$x_min + windows$x_max) / 2
  windows$evidence <- -log10(
    pmax(windows$adjusted_p_value, .Machine$double.xmin)
  )
  print(windows[
    seq_len(min(10L, nrow(windows))),
    c("resolution", "x_min", "x_max", "y_min", "y_max",
      "direction", "log_odds_ratio", "adjusted_p_value")
  ])

  old_parameters <- graphics::par(no.readonly = TRUE)
  old_parameters$new <- FALSE
  on.exit(graphics::par(old_parameters))
  graphics::layout(matrix(c(1, 2), nrow = 1L), widths = c(1.2, 1))
  graphics::par(mar = c(4, 4, 3.3, 1), mgp = c(2.2, 0.7, 0))
  plot(structure, max.windows = 12, main = "U-shaped dependency map")

  graphics::par(mar = c(4, 4, 3.3, 1), mgp = c(2.2, 0.7, 0))
  colors <- ifelse(windows$direction == "positive", "#D95F02", "#2166AC")
  sizes <- 0.9 + 1.8 * windows$evidence / max(windows$evidence)
  graphics::plot(
    windows$x_center,
    windows$log_odds_ratio,
    pch = 21,
    cex = sizes,
    col = colors,
    bg = grDevices::adjustcolor(colors, alpha.f = 0.35),
    xlab = "Window center on transformed X",
    ylab = "Local log-odds ratio",
    main = "Direction changes across X",
    bty = "n",
    las = 1,
    panel.first = graphics::grid(col = "#ECECEC", lty = 1)
  )
  graphics::abline(h = 0, v = 0.5, col = "#666666", lty = 2)
  graphics::legend(
    "topleft",
    legend = c("Positive", "Negative"),
    pt.bg = grDevices::adjustcolor(c("#D95F02", "#2166AC"), alpha.f = 0.35),
    col = c("#D95F02", "#2166AC"),
    pch = 21,
    bty = "n",
    cex = 0.8
  )
})
