## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 6,
  fig.height = 4
)

## ----setup--------------------------------------------------------------------
library(neuromapr)

## ----simulate-data------------------------------------------------------------
set.seed(42)
n <- 100
coords <- matrix(rnorm(n * 3), ncol = 3)
distmat <- as.matrix(dist(coords))

map_a <- rnorm(n)
map_b <- 0.4 * map_a + rnorm(n, sd = 0.8)

## ----simple-compare-----------------------------------------------------------
result <- compare_maps(map_a, map_b, verbose = FALSE)
result

## ----null-comparison----------------------------------------------------------
result_null <- compare_maps(
  map_a, map_b,
  null_method = "burt2020",
  distmat = distmat,
  n_perm = 500L,
  seed = 1,
  verbose = FALSE
)
result_null

## ----null-distribution-plot, fig.cap = "Null correlations from 500 variogram-matching surrogates. The dashed red line marks the observed correlation."----
null_df <- data.frame(r = result_null$null_r)
obs_r <- result_null$r

ggplot2::ggplot(null_df, ggplot2::aes(x = r)) +
  ggplot2::geom_histogram(
    bins = 30, fill = "steelblue", alpha = 0.7
  ) +
  ggplot2::geom_vline(
    xintercept = obs_r,
    linetype = "dashed", color = "red", linewidth = 1
  ) +
  ggplot2::labs(
    x = "Null correlation (r)",
    y = "Count"
  ) +
  ggplot2::theme_minimal()

## ----precompute---------------------------------------------------------------
nulls <- generate_nulls(
  map_a,
  method = "moran",
  distmat = distmat,
  n_perm = 200L,
  seed = 42
)
nulls

## ----plot-nulls, fig.cap = "Built-in plot method for a null_distribution object."----
plot(nulls, parcel = 1L)

## ----reuse-nulls--------------------------------------------------------------
compare_maps(map_a, map_b, nulls = nulls, verbose = FALSE)

## ----permtest-----------------------------------------------------------------
mae <- function(a, b) mean(abs(a - b))

result_mae <- permtest_metric(
  map_a, rnorm(n),
  metric_func = mae,
  n_perm = 200L,
  seed = 1
)
result_mae$observed
result_mae$p_value

## ----permtest-spatial---------------------------------------------------------
result_spatial <- permtest_metric(
  map_a, rnorm(n),
  metric_func = mae,
  n_perm = 200L,
  seed = 1,
  null_method = "burt2020",
  distmat = distmat
)
result_spatial$p_value

