# Test Moran's I calculation # These tests verify the correctness of Moran's I implementation test_that("moranI returns correct structure", { skip_if_not_installed("RANN") set.seed(42) n <- 50 x <- rnorm(n) coords <- cbind(runif(n), runif(n)) rownames(coords) <- paste0("spot_", seq_len(n)) # Build simple KNN network W <- buildSpatialNetwork(coords, method = "knn", k = 5) result <- moranI(x, W) expect_type(result, "list") expect_named(result, c("observed", "expected", "sd")) expect_true(is.numeric(result$observed)) expect_true(is.numeric(result$expected)) expect_true(is.numeric(result$sd)) }) test_that("moranI expected value is approximately -1/(n-1)", { skip_if_not_installed("RANN") set.seed(42) n <- 100 x <- rnorm(n) coords <- cbind(runif(n), runif(n)) rownames(coords) <- paste0("spot_", seq_len(n)) W <- buildSpatialNetwork(coords, method = "knn", k = 6) result <- moranI(x, W) expected_theoretical <- -1 / (n - 1) expect_equal(result$expected, expected_theoretical, tolerance = 1e-10) }) test_that("moranI_test returns valid p-values", { skip_if_not_installed("RANN") set.seed(42) n <- 50 x <- rnorm(n) coords <- cbind(runif(n), runif(n)) rownames(coords) <- paste0("spot_", seq_len(n)) W <- buildSpatialNetwork(coords, method = "knn", k = 5) result <- moranI_test(x, W) expect_true(result["p.value"] >= 0 && result["p.value"] <= 1) }) test_that("moranI detects spatially clustered data", { skip_if_not_installed("RANN") set.seed(42) n <- 200 # Create spatially structured data coords <- cbind(x = runif(n, 0, 100), y = runif(n, 0, 100)) rownames(coords) <- paste0("spot_", seq_len(n)) # Expression follows spatial gradient (strong signal) x_spatial <- coords[, "x"] * 2 + rnorm(n, sd = 5) # Random expression x_random <- rnorm(n, mean = 50, sd = 10) W <- buildSpatialNetwork(coords, method = "knn", k = 10) result_spatial <- moranI(x_spatial, W) result_random <- moranI(x_random, W) # Spatial data should have higher Moran's I expect_gt(result_spatial$observed, result_random$observed) }) test_that("moranI handles zero variance input gracefully", { skip_if_not_installed("RANN") n <- 50 x_constant <- rep(5, n) coords <- cbind(runif(n), runif(n)) rownames(coords) <- paste0("spot_", seq_len(n)) W <- buildSpatialNetwork(coords, method = "knn", k = 5) # Should handle gracefully without error result <- moranI(x_constant, W) # Result should exist (may contain NA due to zero variance) expect_type(result, "list") })