# Test spatial network construction # These tests verify the correctness of buildSpatialNetwork and related functions test_that("buildSpatialNetwork returns correct dimensions", { skip_if_not_installed("RANN") set.seed(42) n <- 50 coords <- cbind(x = runif(n), y = runif(n)) rownames(coords) <- paste0("spot_", seq_len(n)) W <- buildSpatialNetwork(coords, method = "knn", k = 5) expect_equal(nrow(W), n) expect_equal(ncol(W), n) expect_equal(rownames(W), rownames(coords)) expect_equal(colnames(W), rownames(coords)) }) test_that("KNN network has correct number of neighbors", { skip_if_not_installed("RANN") set.seed(42) n <- 30 k <- 5 coords <- cbind(x = runif(n), y = runif(n)) rownames(coords) <- paste0("spot_", seq_len(n)) W <- buildSpatialNetwork(coords, method = "knn", k = k, binary = TRUE) # Each row should have at least k neighbors (may have more due to symmetry) row_sums <- rowSums(W) expect_true(all(row_sums >= k)) }) test_that("Delaunay network is symmetric", { skip_if_not_installed("geometry") set.seed(42) n <- 30 coords <- cbind(x = runif(n), y = runif(n)) rownames(coords) <- paste0("spot_", seq_len(n)) W <- buildSpatialNetwork(coords, method = "delaunay", binary = TRUE) # Network should be symmetric expect_equal(W, t(W)) }) test_that("KNN network is symmetric after union", { skip_if_not_installed("RANN") set.seed(42) n <- 30 coords <- cbind(x = runif(n), y = runif(n)) rownames(coords) <- paste0("spot_", seq_len(n)) W <- buildSpatialNetwork(coords, method = "knn", k = 5, binary = TRUE) # Network should be symmetric expect_equal(W, t(W)) }) test_that("binary network contains only 0 and 1", { skip_if_not_installed("RANN") set.seed(42) n <- 30 coords <- cbind(x = runif(n), y = runif(n)) rownames(coords) <- paste0("spot_", seq_len(n)) W <- buildSpatialNetwork(coords, method = "knn", k = 5, binary = TRUE) expect_true(all(W %in% c(0, 1))) }) test_that("diagonal is zero (no self-connections)", { skip_if_not_installed("RANN") set.seed(42) n <- 30 coords <- cbind(x = runif(n), y = runif(n)) rownames(coords) <- paste0("spot_", seq_len(n)) W <- buildSpatialNetwork(coords, method = "knn", k = 5) # Diagonal should be all zeros (ignore names) expect_true(all(diag(W) == 0)) }) test_that("buildSpatialNetwork handles small datasets", { skip_if_not_installed("RANN") # Very small dataset coords_small <- cbind(x = c(0, 1, 2), y = c(0, 0, 0)) rownames(coords_small) <- paste0("spot_", 1:3) # Should work with k = 2 (maximum possible) W <- buildSpatialNetwork(coords_small, method = "knn", k = 2) expect_equal(nrow(W), 3) })