alarm-redist / redist

Simulation methods for legislative redistricting.
https://alarm-redist.github.io/redist/
GNU General Public License v2.0
67 stars 23 forks source link

Custom constraint fails when map objects are filtered by row index #162

Closed tylersimko closed 1 year ago

tylersimko commented 1 year ago

When creating a custom constraint, row-indexing by the redist_map object throws an error.

For example, this custom constraint indexing an individual column by current district works fine:

library(redist)
iowa_map <- redist_map(iowa, existing_plan = cd_2010, pop_tol = 0.05)

dist_constr <- redist_constr(iowa_map) %>% 

  # Example: custom constraint for even population in districts
  add_constr_custom(strength = 5000, function(plan, distr){

    pop <- iowa_map$pop[plan==distr]

    if (sum(pop) %% 2 == 0) {
      1
    } else {
      0
    }

  })

But if you try to change pop to row index the entire redist_map directly, you get an error:

# Example: custom constraint to ensure even population in districts
dist_constr <- redist_constr(iowa_map) %>% 

  # Example: custom constraint to ensure even population in districts
  add_constr_custom(strength = 5000, function(plan, distr){

    iowa_sub <- iowa_map[plan==distr,]

    if (sum(iowa_sub$pop) %% 2 == 0) {
      1
    } else {
      0
    }

  })
#> [1] "iowa_map"
#> Error in rlang::env_has(env, name): attempt to use zero-length variable name
CoryMcCartan commented 1 year ago

Looks like this was fixed by 187f049

christopherkenny commented 1 year ago

Oh this was also the silly is a valid function name issue?