Cellular Automata (CA) are spatially explicit models where the environment is divided into a grid of cells, each representing a small spatial unit (e.g., 1 m² of land).
Each cell has a state that changes over discrete time steps according to a set of rules based on the states of its neighboring cells.
✅Core Components of CA Models
| Component | Description | Example_Flood_Simulation |
|---|---|---|
| Cell/Grid | Spatial unit of the system | Each cell represents a location in the terrain |
| State | Condition of the cell at time t | 0 = dry, 1 = flooded |
| Neighborhood | The cells influencing a given cell (often 4 or 8 neighbors) | Moore neighborhood (8 adjacent cells) |
| Transition Rule | Defines how cell states update each step | A cell floods if a neighbor is flooded and its elevation = threshold |
| Time Step | Discrete simulation update | 1 iteration = 1 flood propagation step |
✅ Mathematical Representation
Let \(S_{i,j}^{(t)}\) be the state of cell \((i,j)\) at time \(t\). Then, the new state is determined by: \[S_{i,j}^{(t+1)}=f(S_{i,j}^{(t)},N_{i,j}^{(t)},E_i,j) \] where:
✅ Environmental Applications of CA
| Feature | Cellular_Automata | Agent_Based_Model |
|---|---|---|
| Entities | Cells on a grid | Independent agents |
| Rules | Local and uniform | Individual and heterogeneous |
| Interaction | With neighboring cells | With environment and other agents |
| Examples | Flood propagation, urban growth | Evacuation, disease spread, land-use change |
The simulation below demonstrates how Cellular Automata (CA) can be applied to model spatially dynamic environmental processes, using flood propagation as an example. The CA framework is particularly suited for such modeling because it represents space as a grid of discrete cells, each of which can change state (e.g., dry or flooded) according to simple, local rules.
Setting Up the Environment
The model uses R’s built-in volcano dataset — a matrix representing the topographic surface of Maunga Whau (Mount Eden) in Auckland, New Zealand. This dataset provides a realistic elevation surface that serves as the spatial landscape for the simulation. The matrix is converted into a raster object using the terra package, allowing spatial operations such as adjacency and neighborhood analysis.
Initialization of States
Each cell in the grid is initially assigned a state variable:
To start the simulation, 20 random cells are designated as initial water sources, mimicking rainfall accumulation or localized flooding in low-lying areas.
Transition Rule (Flood Propagation)
The simulation evolves according to a transition rule that governs how flooding spreads:
A cell becomes flooded if one of its neighboring cells is already flooded and its elevation is within a threshold (threshold = 2) of that neighbor.
This rule represents the physical process of water flowing from higher to lower areas, constrained by local topography. The Moore neighborhood (8 adjacent cells) is used, meaning each cell interacts with all surrounding cells diagonally and horizontally/vertically.
Temporal Evolution
The system updates through discrete time steps (T = 20). In each iteration, the propagate_once() function:
Checks all currently flooded cells.
Identifies their neighbors using the adjacent() function.
Floods neighboring cells if their elevation is sufficiently low.
As iterations progress, the flood gradually expands outward, filling adjacent low-elevation areas while higher regions remain dry. This dynamic reflects how water naturally seeks equilibrium under gravitational forces.
Visualization and Interpretation
After running 20 time steps, the results are visualized using ggplot2.
The background raster represents elevation (using a viridis color scale).
Blue points indicate flooded cells.
The resulting plot — titled “Flood Spread Simulation on Volcano Dataset” — vividly shows how floodwaters spread through the landscape, highlighting valleys and basins as the most affected zones.
Insights
This simple Cellular Automata model demonstrates how complex spatial phenomena can emerge from simple local rules. Despite its simplicity, it captures essential aspects of flood dynamics:
Local interactions lead to large-scale patterns.
Topography constrains the direction and extent of flooding.
Small initial perturbations (the 20 random water cells) can evolve into widespread effects.
In real-world applications, such models can be expanded to include rainfall intensity, soil permeability, drainage networks, and temporal precipitation data, making CA a powerful and computationally efficient tool for environmental risk analysis, hydrological forecasting, and disaster preparedness planning.
# Load required packages
library(terra)## terra 1.7.23
##
## Attaching package: 'terra'
## The following object is masked from 'package:knitr':
##
## spin
library(ggplot2)
# Use built-in volcano dataset (Maunga Whau, Auckland)
data(volcano)
# Convert volcano matrix to raster
elev <- rast(volcano)
# Initialize water source: 20 random cells
water <- rast(elev)
values(water) <- 0
values(water)[sample(1:ncell(water), 20)] <- 1
# Cellular Automata propagation function
threshold <- 2
propagate_once <- function(water_r, elev_r, thr) {
w <- values(water_r)
e <- values(elev_r)
res <- w
nm <- adjacent(elev_r, cells = 1:ncell(elev_r), directions = 8, pairs = TRUE)
for (c in which(w > 0)) {
neigh <- nm[nm[, 1] == c, 2]
for (nc in neigh) {
if (e[nc] <= e[c] + thr) res[nc] <- 1
}
}
setValues(water_r, res)
}
# Run simulation for T steps
T <- 20
wcur <- water
for (t in 1:T) {
wcur <- propagate_once(wcur, elev, threshold)
}
# Prepare data for plotting
df_plot <- as.data.frame(cbind(xyFromCell(elev, 1:ncell(elev)),
elev = as.numeric(values(elev)),
water = as.numeric(values(wcur))))
# Plot final state
ggplot(df_plot, aes(x = x, y = y)) +
geom_raster(aes(fill = elev)) +
scale_fill_viridis_c(option = "C") +
geom_point(data = df_plot[df_plot$water > 0, ], aes(x = x, y = y),
color = "dodgerblue", size = 0.8) +
coord_equal() +
labs(title = "Flood Spread Simulation on Volcano Dataset", fill = "Elevation")✅ Relationship between ABM and Cellular Automata (CA)
| Feature | Cellular_Automata | Agent_Based_Model |
|---|---|---|
| Entities | Cells on a grid | Independent agents |
| Rules | Local and uniform | Individual and heterogeneous |
| Interaction | With neighboring cells | With environment and other agents |
| Examples | Flood propagation, urban growth | Evacuation, disease spread, land-use change |
✅ Relevant Publications on the use of Cellular Automata
Yeh, Li & Xia (2021) provided a comprehensive overview of urban CA modeling, emphasizing its role in simulating urban growth, land use changes, and policy impact analysis.Link
Zhang et al. (2023) enhanced CA models by incorporating spatiotemporal heterogeneity and urban growth intensity, achieving high accuracy in simulating urban expansion in Huizhou, China.Link
Tariq & Mumtaz (2023) applied a CA-Markov model to simulate land use and land cover (LULC) changes from 1990 to 2054, showing significant urban expansion and deforestation trends.Link
Agent-Based Modeling (ABM) is a computational modeling approach that simulates the actions and interactions of autonomous agents (e.g., people, animals, vehicles, households, or even floodwater units) within a defined environment to explore how collective behaviors emerge from individual decisions.
In simple terms: ABM models the “bottom-up” dynamics of a system — how local actions produce global patterns.
ABM emerged from research in complex adaptive systems during the 1970s and 1980s. Early work was influenced by:
✅First Applications
✅ Growth in Computing Power
✅ Core Components of ABM
| Component | Description | Example_Disaster_Risk_Context |
|---|---|---|
| Agents | The entities that act and make decisions. Each agent has attributes and rules of behavior. | Households deciding whether to evacuate during a flood. |
| Environment | The spatial or social context where agents interact — can be a grid, map, or network. | A city map with hazard zones and safe areas. |
| Rules | Define how agents behave and respond to stimuli or other agents. | “If flood depth > 1m, move to higher ground.” |
| Interactions | Agents interact with one another or with their environment. | People sharing warnings through social media. |
| Emergence | System-level outcomes that arise from many simple interactions. | Patterns of evacuation, congestion, or risk exposure. |
✅ Characteristics of Agents
Each agent in an ABM typically has:
Autonomy: makes independent decisions.
Heterogeneity: agents differ in attributes (age, wealth, preparedness).
Adaptiveness: they can learn or adjust based on feedback.
Bounded rationality: decisions are made with limited information or imperfect reasoning.
Mobility: agents can move through space (spatial ABM).
Example: In a wildfire simulation, each household agent decides whether to evacuate based on wind direction, fire distance, and neighbor behavior.
✅ The Environment
The environment is the spatial or conceptual space where agents exist and act.
Can be discrete (e.g., raster grids, as in a cellular automaton)
Or continuous (e.g., actual geographic space with coordinates)
The environment can also change over time, reacting to agent actions (e.g., pollution spreading, floodwater rising).
Example: Using a map of Davao City, the environment includes flood zones, roads, hospitals, and evacuation centers.
✅ Rules of Interaction and Decision-Making
Rules can be deterministic or probabilistic.
Deterministic rule: “If rainfall > 50 mm, flood cell becomes wet.”
Probabilistic rule: “An agent has a 60% chance of evacuating if water level exceeds 1 m.”
Agents may also follow social rules (e.g., peer influence, communication).
✅ Emergent Behavior
One of the most powerful aspects of ABM is emergence — complex, system-wide behaviors that arise from many simple interactions.
✅ Examples:
Traffic jams emerging from individual driving rules
Flood propagation from local water movements
Disease outbreaks from individual contacts
Evacuation bottlenecks from household mobility
“The whole is greater than the sum of its parts.”
✅ ABM in Environmental Risk and Disaster Analysis
| Application | Example |
|---|---|
| Flood evacuation | Simulate how households move toward evacuation centers and identify bottlenecks. |
| Wildfire spread | Model how fire spreads through vegetation cells, considering wind and fuel. |
| Disease transmission | Agents represent people; simulate contact-based spread of dengue or COVID-19. |
| Urban resilience | Examine how social networks and resources affect recovery speed. |
| Land-use change | Simulate how farmers decide to deforest, plant, or reforest areas based on incentives. |
Suppose we want to answer the question: How do individual households evacuate to the nearest shelter in a spatial environment when an alarm is triggered, and what is the overall evacuation efficiency in terms of time and steps taken?
To answer this question we use ABM. This simulation models an evacuation scenario where households (agents) move toward the nearest shelter when an alarm is triggered. The environment is represented as a 40 × 40 grid, and the agents follow simple rules to reach safety.
Step 1: Define the Environment
The simulation begins by creating a 40 × 40 grid that represents the spatial environment. This grid acts as the area where agents (households) and shelters are located.
Shelters are placed at three fixed positions: (5,5), (35,35), and (20,20). These serve as safe zones for evacuation.
Step 2: Initialize Agents
Next, 200 agents are randomly distributed across the grid. Each agent has:
Step 3: Define Movement Logic
A distance function calculates the Euclidean distance between an agent and all shelters.
Each agent identifies its nearest shelter based on this distance.
Movement rule:
If the agent is not evacuated, it moves one cell per time step toward the shelter:
If x < shelter_x, move right; if x > shelter_x, move left.
Similarly for y.
When an agent reaches the shelter coordinates, it is marked as evacuated.
Step 4: Run the Simulation
The simulation runs for up to 60 steps or until all agents are evacuated. At each time step:
Step 5: Summarize Results
After the simulation ends:
Step 6: Visualize Final State
A plot shows:
# Simple ABM: agents evacuate to nearest shelter when an alarm triggers
library(dplyr)##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:terra':
##
## intersect, union
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(ggplot2)
set.seed(2025)
# Create a small grid of 40 x 40
grid_size <- 40
cells <- expand.grid(x = 1:grid_size, y = 1:grid_size)
# Define shelters (some fixed cells)
shelters <- tibble(x = c(5, 35, 20), y = c(5, 35, 20))
# Create agents (households) randomly distributed
n_agents <- 200
agents <- tibble(
id = 1:n_agents,
x = sample(1:grid_size, n_agents, replace = TRUE),
y = sample(1:grid_size, n_agents, replace = TRUE),
evacuated = FALSE,
steps = 0
)
# Distance function
dist2 <- function(x1, y1, x2, y2) sqrt((x1 - x2)^2 + (y1 - y2)^2)
# Simulation parameters
max_steps <- 60
history <- list()
for(t in 1:max_steps) {
# compute nearest shelter for each agent
agents <- agents %>%
rowwise() %>%
mutate(
sh_dist = min(dist2(x, y, shelters$x, shelters$y)),
sh_x = shelters$x[which.min(dist2(x, y, shelters$x, shelters$y))],
sh_y = shelters$y[which.min(dist2(x, y, shelters$x, shelters$y))]
) %>%
ungroup()
# move each non-evacuated agent one step towards shelter
agents <- agents %>%
mutate(
x = ifelse(!evacuated & x < sh_x, x + 1,
ifelse(!evacuated & x > sh_x, x - 1, x)),
y = ifelse(!evacuated & y < sh_y, y + 1,
ifelse(!evacuated & y > sh_y, y - 1, y)),
steps = ifelse(!evacuated, steps + 1, steps),
evacuated = evacuated | (x == sh_x & y == sh_y)
)
# record
history[[t]] <- agents
if(all(agents$evacuated)) break
}
# ---- Plot the initial state (t = 1) ----
agents_t1 <- history[[1]]
ggplot() +
geom_point(data = agents_t1, aes(x = x, y = y), color = "red", size = 1.8, alpha = 0.7) +
geom_point(data = shelters, aes(x = x, y = y), shape = 15, size = 5, color = "black") +
labs(title = "ABM Evacuation - Initial State (t = 1)",
subtitle = "Red dots: agents; black squares: shelters",
x = "X coordinate", y = "Y coordinate") +
coord_equal() + theme_minimal()# ---- Plot the final state ----
agents_final <- history[[length(history)]]
ggplot() +
geom_point(data = agents_final, aes(x = x, y = y, color = evacuated), size = 2) +
geom_point(data = shelters, aes(x = x, y = y), shape = 15, size = 4, color = "black") +
labs(title = paste0("ABM Evacuation - Final State (t = ", length(history), ")"),
subtitle = "Agents move towards nearest shelter until all are evacuated") +
coord_equal() + theme_minimal()Interpret
The spatial distribution of the evacuated agents suggests they have reached or are positioned near designated safe zones or exits, which could be located at the plotted coordinates.
The absence of non-evacuated agents implies a 100% evacuation success rate, indicating that the model’s parameters (e.g., movement speed, exit accessibility, and environment layout) allowed all agents to reach safety within the simulation time.
The time step t = 20 may represent the total duration needed for full evacuation, useful for evaluating the efficiency of the evacuation strategy.
This result can be compared to earlier time steps (e.g., t = 10 or t = 15) to assess evacuation dynamics — how quickly agents move and what bottlenecks might appear under different conditions.
# ---- Count how many agents evacuated to each shelter ----
# Get final state of agents
agents_final <- history[[length(history)]]
# Keep only those who successfully evacuated
evacuated_agents <- agents_final %>%
filter(evacuated == TRUE) %>%
group_by(sh_x, sh_y) %>%
summarise(
n_evacuated = n(),
avg_steps = mean(steps)
) %>%
ungroup()## `summarise()` has grouped output by 'sh_x'. You can override using the
## `.groups` argument.
# Print evacuation summary
print(evacuated_agents)## # A tibble: 3 x 4
## sh_x sh_y n_evacuated avg_steps
## <dbl> <dbl> <int> <dbl>
## 1 5 5 29 7
## 2 20 20 137 11.6
## 3 35 35 34 9
✅ Interpretation
This table summarizes the results of an agent-based model (ABM) simulation where agents evacuate to nearby shelters. Here’s an interpretation of the data:
Shelter coordinates (sh_x, sh_y):
Number of agents evacuated (n_evacuated):
Shelter 1 received 29 agents, shelter 2 received 137 agents, and shelter 3 received 34 agents.
This indicates that shelter 2 was the most preferred or accessible for agents in the model, likely due to its central location relative to agent distribution.
Average steps to evacuate (avg_steps):
Agents took an average of 7 steps to reach shelter 1, 11.6 steps to reach shelter 2, and 9 steps to reach shelter 3.
Although shelter 2 received the most agents, it required the highest average steps, suggesting it is farther away for many agents compared to the other shelters.
Overall interpretation :
The simulation shows patterns of evacuation behavior where most agents chose shelter 2 despite it requiring more steps on average. This might reflect either a higher capacity, perceived safety, or centrality of shelter 2 in the agent distribution. Shelters 1 and 3 had fewer evacuees but were reached more quickly. These results can help in planning evacuation strategies by identifying which shelters are likely to attract more evacuees and how accessible they are.
✅ Possible Extensions
Introduce obstacles or varying agent behaviors (e.g., differing speeds or decision rules) to test the robustness of evacuation outcomes.
Analyze time-to-evacuate distributions across agents to quantify evacuation efficiency.
Compare different evacuation policies or spatial layouts to identify optimal configurations for safety and efficiency.
✅ Relevant publications that uses ABM
Focus: Simulates human behavior during debris flow events and evaluates early warning systems (EWS) effectiveness.
Key finding: EWS reduced casualties by 30%; credibility of warnings is critical.
Read full article frontiersin.org