Created
May 13, 2025 06:54
-
-
Save Martin-Jung/3a7cf30048800aac9c78577998006ddf to your computer and use it in GitHub Desktop.
Fragmentation test with penalties and constraints
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # load packages | |
| library(prioritizr) | |
| library(prioritizrdata) | |
| library(terra) | |
| library(microbenchmark) | |
| # import planning unit data | |
| wa_pu <- get_wa_pu() | |
| # preview data | |
| print(wa_pu) | |
| wa_pu[!is.na(wa_pu)] <- 1 | |
| # import feature data | |
| wa_features <- get_wa_features() | |
| wa_pa <- get_wa_locked_in() | |
| # calculate budget | |
| budget <- terra::global(wa_pu, "sum", na.rm = TRUE)[[1]] * 0.3 | |
| # create problem | |
| p1 <- | |
| problem(wa_pu, features = wa_features) |> | |
| add_loglinear_targets(10, 0.9, 100, 0.2) |> | |
| add_proportion_decisions() |> | |
| add_locked_in_constraints(wa_pa) |> | |
| add_default_solver(gap = 0.1, verbose = FALSE) | |
| # Minimum shortfall without blm | |
| s1 <- solve(p1 |> add_min_shortfall_objective(budget) ) | |
| names(s1) <- "minshort_loglinear" | |
| # Minimum shortfall with blm | |
| bmat <- boundary_matrix(wa_pu) | |
| # rescale matrix values to have a maximum value of 1 | |
| bmat <- rescale_matrix(bmat, max = 1) | |
| s2 <- solve(p1 |> add_boundary_penalties(penalty = 1, data = bmat) |> | |
| add_min_shortfall_objective(budget)) | |
| names(s2) <- "minshort_loglinear_prop_blm" | |
| # And with binary decisions and blm | |
| s3 <- solve(p1 |> add_binary_decisions() |> | |
| add_boundary_penalties(penalty = 1, data = bmat) |> | |
| add_min_shortfall_objective(budget)) | |
| names(s3) <- "minshort_loglinear_bin_blm" | |
| s4 <- solve(p1 |>add_neighbor_constraints(k = 2) |> | |
| add_min_shortfall_objective(budget)) | |
| names(s4) <- "minshort_loglinear_ngb" | |
| # Plot all next to each other | |
| plot(c(s1,s2, s3, s4)) # Bit non.sensical but ok for test | |
| # Benchmark them all | |
| bm <- microbenchmark( | |
| naive = solve(p1 |> add_min_shortfall_objective(budget)), | |
| minshort = solve(p1 |> add_boundary_penalties(penalty = 1, data = bmat) |> | |
| add_min_shortfall_objective(budget)), | |
| minshort_binary = solve(p1 |> add_binary_decisions() |> | |
| add_boundary_penalties(penalty = 1, data = bmat) |> | |
| add_min_shortfall_objective(budget)), | |
| minshort_neigh = solve(p1 |> add_min_shortfall_objective(budget) |> | |
| add_neighbor_constraints(k = 2) | |
| ), | |
| minshort_neigh_binary = solve(p1 |> add_min_shortfall_objective(budget) |> | |
| add_binary_decisions() |> | |
| add_neighbor_constraints(k = 2) | |
| ), | |
| times = 1 | |
| ) | |
| bm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment