2 Landscape & Resources

To simulate the interaction between two groups, we need an environment where they can interact. This chapter covers how to generate a landscape and an environment for your simulated groups. An essential part of the simulation is to generate a realistic landscape and environment. Environmental variables are often auto-correlated. For example, the temperature recorded at a given time is similar to that recorded just before or after that particular moment. Similarly, topographic variables such as slope or elevation tend to be similar at a shorter rather than larger distances.

2.1 Autocorrelated noise generation

One way to generate such an auto-correlated variable is to use coloured noise. This uses a specific distribution to define the relation between frequencies found in your signal with the power of these frequencies. In pink noise (or \(\frac{1}{f}\)-noise) for example, the power of each frequencis will be inversely proportional to the frequencies (ie you will have, low frequencies with high power, high frequencies with low ones). We defined an environment function, which in turns uses TK95 to generate a power law noise.

To generate a single auto-correlated variable (like temperature), whose spectrum decomposition (power wrt frequency) has a slope of -3 and a standard deviation of 1.5:

tstep <- 1000
faketemp <- environment(tstep, omega=3, delta=1.5) + 1.5
plot(faketemp, type="l", ylab="temperature change", xlab="time",lwd=3)   

You can inspect the code of the environment and TK95 functions here:
Show code

Code

## Function 10. Power law noise from Kimmer & Koening
TK95 <- function(N, alpha = 1){ 
  f <- seq(from=0, to=pi, length.out=(N/2+1))[-c(1,(N/2+1))] # Fourier frequencies
  f_ <- 1 / f^alpha # Power law
  RW <- sqrt(0.5*f_) * rnorm(N/2-1) # for the real part
  IW <- sqrt(0.5*f_) * rnorm(N/2-1) # for the imaginary part
  fR <- complex(real=c(rnorm(1), RW, rnorm(1), RW[(N/2-1):1]), 
                imaginary=c(0, IW, 0, -IW[(N/2-1):1]),
                length.out=N)
  # Those complex numbers that are to be back transformed for
  # Fourier Frequencies 0, 2pi/N, 2*2pi/N, ..., pi, ..., 2pi-1/N 
  # Choose in a way that frequencies are complex-conjugated and symmetric around pi 
  # 0 and pi do not need an imaginary part
  reihe <- fft(fR, inverse=TRUE) # go back into time domain
  return(Re(reihe)) # imaginary part is 0
}

## Function 11. Environment generator
environment <- function(N, omega, delta, vt=NULL){
  ts <- TK95(N, omega)
  ts <- delta * ts/sd(ts)
  if(!is.null(vt)) {
    ts = ts + vt*1:N
  }
  return(ts)
}

This generates autocorrelated time series that can be used to define temporal change in climate (rain, temperature, etc.). But we have not used such changes for the Archaeoriddle challenge. Coloured noise remains a very straightforward way that can be easily added in the simulations.

2.2 Slope and Elevation

An important aspect of the simulation is to generate realistic elevation and slope values. To generate a 2D autocorrelated variable we used a method known as perlin noise ; using the implementation found on this stackoverflow.com post.


And you can see the code here:
Show code

Code

## Function 12. Perlin noise
perlin_noise <- function( 
    n = 5,   m = 7,    
    N = 100, M = 100
) {
  # For each point on this n*m grid, choose a unit 1 vector
  vector_field <- apply(
    array( rnorm( 2 * n * m ), dim = c(2,n,m) ),
    2:3,
    function(u) u / sqrt(sum(u^2))
  )
  f <- function(x, y) {
    # Find the grid cell in which the point (x,y) is
    i <- floor(x)
    j <- floor(y)
    stopifnot( i >= 1 || j >= 1 || i < n || j < m )
    # The 4 vectors, from the vector field, at the vertices of the square
    v1 <- vector_field[, i, j]
    v2 <- vector_field[, i+1, j]
    v3 <- vector_field[, i, j+1]
    v4 <- vector_field[, i+1, j+1]
    # Vectors from the point to the vertices
    u1 <- c(x,y) - c(i, j)
    u2 <- c(x,y) - c(i+1, j)
    u3 <- c(x,y) - c(i, j+1)
    u4 <- c(x,y) - c(i+1, j+1)
    # Scalar products
    a1 <- sum( v1 * u1 )
    a2 <- sum( v2 * u2 )
    a3 <- sum( v3 * u3 )
    a4 <- sum( v4 * u4 )
    # Weighted average of the scalar products
    s <- function(p) 3 * p^2 - 2 * p^3
    p <- s( x - i )
    q <- s( y - j )
    b1 <- (1-p)*a1 + p*a2
    b2 <- (1-p)*a3 + p*a4
    (1-q) * b1 + q * b2
  }
  xs <- seq(from = 1, to = n, length = N+1)[-(N+1)]
  ys <- seq(from = 1, to = m, length = M+1)[-(M+1)]
  return(outer( xs, ys, Vectorize(f) ))
}

Different parameters for the Perlin noise will result in either a higher or lower level of definition for our future DEM raster. Our aim is to find a balance between having the environment sufficiently detailed across a relatively wide area, while also ensuring it remains manageable in terms of memory usage.

require(terra)
require(sf)

a <- 0.6
k <- 8
m <- perlin_noise(2, 2, 2^k, 2^k)
for ( i in 2:k )
  m <- m + a^i * perlin_noise(2^i, 2^i, 2^k, 2^k)

If we change k (that dictates the total resolution of the DEM), the size of the raster grows explonentially and would quickly become hard to manage.


allsizes <- sapply(1:7,function(k)
{
    print(k)
    mt <- perlin_noise(2, 2, 2^k, 2^k)
    for ( i in 2:k ) mt <- mt + 0.6^i * perlin_noise(2^i, 2^i, 2^k, 2^k)
    object.size(mt)  
})
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
plot(2^(1:7),allsizes/1000,type="b",pch=20,col="red",cex=2,ylab="size of raster (kb)", xlab="resolution")

To enhance realism, slight adjustments were made to the extremes to create water bodies and mountains more closely resembling those found in an real landscape.

height <- (m[,])*20
#height[height<50]=0
height <- height^3
height <- height+abs(mean(height))
height[height<min(height)*.25] <- min(height)*.25

We can then visualise the result as a 2D raster. We set up the total extent of the raster to define precisely where it is on our GIS using geographic coordinates.

We also define the mean height as the water level: All the cells below are considered water bodies.

height.ras <- rast(height, extent=c(-3.5, 0.5, -0.5, 3.5), crs="+proj=latlon")
maxh <- max(height.ras[], na.rm=T)
plot(height.ras, col=col_ramp(20), legend=F, reset=F)
height.wat <- height.ras
height.wat[height.wat>mean(height.wat[])] <- NA
plot(height.wat, col="lightblue", add=T, legend=F)

This has been put in the function plotMap

plotMap(height.ras,height.wat)

The actual raster used for the original archaeoriddle is available in data_original/east_narnia4x.tif and looks like

original.ras <- rast("data_original/east_narnia4x.tif")
original.wat <- original.ras
original.wat[original.wat>mean(original.wat[])] <- NA
plotMap(original.ras,original.wat)

If you really want to feel like being in a video game, you can play with rayshader, but getting the right parameters to have a nice rendering is tricky, slow, and it’s not unlikely you’ll waste a lot of time ¯\_(ツ)_/¯

require(rayshader)
height_map <- raster_to_matrix(raster::raster(height)) 

hm_shade <- sphere_shade(height_map, texture = "imhof1", zscale=5) 
hm_ray <- add_shadow(hm_shade, ray_shade(height_map, zscale = 19), 0.8) 
hm_ambiant <- add_shadow(hm_ray, ambient_shade(height_map), 0,5) 
hm_lamb <- add_shadow(hm_ambiant, lamb_shade(height_map), 0) 
plot_3d(
  hm_lamb,height_map, zscale = 10, fov = 0, theta = 20, zoom = .5, phi = 45,
  windowsize = c(1000, 800),water = TRUE, waterdepth = 0,
  wateralpha = 1, watercolor = "lightblue", waterlinecolor = "lightblue",
  waterlinealpha = .7, baseshape="hex")

#HQ render, very slow
#render_highquality( samples=256, clear = TRUE,light=TRUE)

2.3 Environmental resources

We will generate zones of higher resources/fitness that will attract settlements and support higher carrying capacity ie population size. The resources will be located at given hotspots with an area around which they decay following a sigmoid function. We provide a very basic function logisticdecay which allows you to define multiple sources with different decay arrays around them.

Here’s the code for the generation of resources under logistic decay
Show code

Code

## Fucntion 13. Logistic decay for resource generation
logisticdecay <- function(pt, rast, L=1, k=0.0001, x0=60000){
  ds <- terra::distance(rast, pt)
  logdec = L-L/(1+exp(-k*(ds-x0)))
  return(logdec)
}


For the original archaeoriddle, these hotspots and their radius were manually selected given the topography of Rabbit Hole. These manual setups are given below:

##resource geolocalisation set manually
goodresources <- vect(
  cbind(
    x=c(-0.2300711, -3.1455282, -0.5086485, -1.9639755,
        -0.4077843, 0.019688, -3.116710),
    y=c(3.6423000, -0.2551019, -0.7440748, 1.1303214,
        1.0248567, 0.2194895, 2.0267718)
  )
)
#spread of resources
areas <- 4 * c(100, 2000, 200, 300, 100, 200, 400)
#speed of ressource decay:
ks <- c(0.0002, 0.0001000, 0.0001600, 0.0001800, 0.00040, .0002, 0.0002)/4


crs(goodresources) <- crs(original.ras)

The function logisticdecay generates individual rasters for all the identified hotspots, which are then merged to create an aggregate raster referred to as ‘resources’.

When considering the selection of hotspots, you may choose to retain the one utilized for the archaeoriddle but to adjust these resources center to your own topography ; one can use locator() to find the coordinates of the hotspot by clicking on the map. An example of that is given in this section of the chapter

These resources span along all the map, but we want to restrict them to places where people can settle. Given this new landscape, we can now generate sites in specific locations. We first need to define where the sites can appear (not in water nor too high in the mountains), so we first create a raster called ‘viable’, a binary map defining where groups can or cannot live.

height.groups <- height.ras # taking back the raster created before
height.groups[height.groups<mean(height.groups[])] <- NA #replace values that are below mean level (under water)
height.groups[height.groups<(maxh*.7)] <- 1 # values below 70% of the maximum height are set as 1
height.groups[height.groups>(maxh*.7)] <- 200 # value above at 200 (high mountains)
height.groups[is.na(height.groups)] <- -1 #  NA values (below waters) are set to -1
height.poly <- as.polygons(height.groups) # convert height.groups as polygons that will be of three type: -1 => under water, 1, viable, and 200, high mountaines
viable <- makeValid(height.poly[2,]) # select polygon with '1' and make it a valid polygon as it may have some loop and problems

We now also have a polygon called viable representing the space where sites can be created. This space is represented by the green area on the map below.

plot(viable,col=adjustcolor("chartreuse",.8))

We then loop over every center manually defined previously and apply the logistic decay within the viable raster.


allres <- lapply(
  seq_along(goodresources),
  function(i){
    logisticdecay(goodresources[i], mask(height.ras, viable),
                  x=areas[i], k=ks[i]
    )
  }
)

allna <- sapply(allres, function(i)any(is.na(values(i))))
allres <- allres[!allna]

And then we add all the resource rasters, which gives us a final ress raster as below:

ress <- allres[[1]]
for(i in 2:length(allres))
    ress <- ress + allres[[i]]
ress <- mask(ress,viable)
plot(ress)

2.4 Manually Select Resources

Below is some useful code to manually select the resource origins on the map (by clicking on the screen) and explore different decays around them

plotMap(height.ras, height.wat, paste0("year ", 0))
new_site <- vect(as.data.frame(locator()), geom=c("x", "y"))  # select point on the screen
crs(new_site) <- crs(height.ras)
d2 <- logisticdecay(new_site, height.ras, x=20000) # generate a logistic decay around the point

plot(d2)
w <- (0.7*d2 + 0.3*ress) / (0.7*minmax(d2)[2] + 0.3*minmax(ress)[2])
plot(w)
plot(mask(w*logisticdecay(new_site, height.ras, k=0.00002, x=1), territory))

multisamp <- sapply(
  1:1000,
  function(i){
    spatSample(x=w, size=1, method="weights", xy=T)[1:2]
  }
)