Skip to contents

Rules are checked and executed once per tick. Rules for agents are run before rules for environments. For each rule, the ... conditions are checked and, if they prove valid, the rule's .consequence is run.

Think of rules as the code to be run within your ABM. Rules could establish connections or abort them, they could remove or add agents, they could stop the whole simulation or make agents move.

For helping utilities (i.e., readily implemented helpers to be used in your rules or as readymade consequences) and examples, see the full documentation, particularly per environment type.

Usage

add_rule(.tidyabm, .label, ..., .consequence)

# S3 method for tidyabm
add_rule(.tidyabm, .label, ..., .consequence)

Arguments

.tidyabm

a tidyabm object

.label

string describing the rule

...

<data-masking> expressions that return a logical value and are defined in terms of all characteristics and variables of me (which is the tidyabm object to which the rule was applied to). If multiple expressions are included, they are combined with the & operator.

.consequence

function to be executed if all conditions apply. Use a function with two arguments, me (which is the tidyabm object at that specific point in time) and abm (which is the whole tidyabm object). Note that for tidyabm_env objects these two arguments are the same but for tidyabm_agent objects they are different in that the first (me) is the current agent and the second (abm) is the whole environment model. Importantly, for any changes to apply the function has to return the updated me (i.e., a tidyabm_agent object for agent rules and a tidyabm_env object for environment rules). If the function misses to do so, any changes will be ignored and a warning will be issued during runtime. If you write your own functions or need to provide additional arguments to functions, use the style of anonymized functions directly in-line (through function(me, abm) ... return(me) or \(me, abm) ... return(me)).

Value

a tidyabm object

Examples

create_agent() %>%
  set_characteristic(age = 15) %>%
  add_rule('minors move',
           age >= 18,
           .consequence = \(me, abm) {
             spot <- grid_get_free_neighboring_spots(me, abm) %>%
               dplyr::slice_sample(n = 1)
             grid_move(me, abm,
                       new_x = spot$.x,
                       new_y = spot$.y) %>%
               return()
           })
#> # A tibble: 1 × 1
#>     age
#> * <dbl>
#> 1    15
#> # ABM agent
#> * 1 agent characteristic(s), 
#> * 0 agent variable(s), 
#> * 1 agent rule(s), 

create_grid_environment(seed = 1269, size = 5) %>%
  add_variable(n_agents = \(me, abm) nrow(convert_agents_to_tibble(me))) %>%
  add_rule('no more agents',
           n_agents == 0,
           .consequence = stop_abm)
#> # A tibble: 0 × 0
#> # ABM grid environment
#> * 5x5, 0 agents
#> * 0 environment characteristic(s), 
#> * 1 environment variable(s), 
#> * 1 environment rule(s), 
#> * not initiated