if (FALSE) {
# load data
sim_pu_raster <- get_sim_pu_raster()
sim_features <- get_sim_features()
sim_zones_pu_raster <- get_sim_zones_pu_raster()
sim_zones_features <- get_sim_zones_features()
# create minimal problem
p1 <-
problem(sim_pu_raster, sim_features) %>%
add_min_set_objective() %>%
add_relative_targets(0.1) %>%
add_default_solver(verbose = FALSE)
# create problem with constraints that require 1 neighbor
# and neighbors are defined using a rook-style neighborhood
p2 <- p1 %>% add_neighbor_constraints(1)
# create problem with constraints that require 2 neighbor
# and neighbors are defined using a rook-style neighborhood
p3 <- p1 %>% add_neighbor_constraints(2)
# create problem with constraints that require 3 neighbor
# and neighbors are defined using a queen-style neighborhood
p4 <-
p1 %>%
add_neighbor_constraints(
3, data = adjacency_matrix(sim_pu_raster, directions = 8)
)
# solve problems
s1 <- terra::rast(list(solve(p1), solve(p2), solve(p3), solve(p4)))
names(s1) <- c("basic solution", "1 neighbor", "2 neighbors", "3 neighbors")
# plot solutions
plot(s1, axes = FALSE)
# create minimal problem with multiple zones
p5 <-
problem(sim_zones_pu_raster, sim_zones_features) %>%
add_min_set_objective() %>%
add_relative_targets(matrix(0.1, ncol = 3, nrow = 5)) %>%
add_default_solver(verbose = FALSE)
# create problem where selected planning units require at least 2 neighbors
# for each zone and planning units are only considered neighbors if they
# are allocated to the same zone
z6 <- diag(3)
print(z6)
p6 <- p5 %>% add_neighbor_constraints(rep(2, 3), zones = z6)
# create problem where the planning units in zone 1 don't explicitly require
# any neighbors, planning units in zone 2 require at least 1 neighbors, and
# planning units in zone 3 require at least 2 neighbors. As before, planning
# units are still only considered neighbors if they are allocated to the
# same zone
p7 <- p5 %>% add_neighbor_constraints(c(0, 1, 2), zones = z6)
# create problem given the same constraints as outlined above, except
# that when determining which selected planning units are neighbors,
# planning units that are allocated to zone 1 and zone 2 can also treated
# as being neighbors with each other
z8 <- diag(3)
z8[1, 2] <- 1
z8[2, 1] <- 1
print(z8)
p8 <- p5 %>% add_neighbor_constraints(c(0, 1, 2), zones = z8)
# solve problems
s2 <- list(p5, p6, p7, p8)
s2 <- lapply(s2, solve)
s2 <- lapply(s2, category_layer)
s2 <- terra::rast(s2)
names(s2) <- c("basic problem", "p6", "p7", "p8")
# plot solutions
plot(s2, main = names(s2), axes = FALSE)
}
Run the code above in your browser using DataLab