Home > Software design >  Generate random rasters with grid values summing up to a number
Generate random rasters with grid values summing up to a number

Time:11-08

Is it possible to generate 5 random raster layers with defined minimum and maximum values for each one of them? And with pixel values summing up to n?

CodePudding user response:

Imagining the rasters would have different min/max,

set.seed(42)
rand_1 <- terra::rast(array(sample(2:9, 100, replace = TRUE), dim=c(10,10,1), dimnames= NULL))
rand_2 <- terra::rast(array(sample(6:11, 100, replace = TRUE), dim=c(10,10,1), dimnames= NULL))
rand_3 <- terra::rast(array(sample(1:7, 100, replace = TRUE), dim=c(10,10,1), dimnames= NULL))
rand_4 <- terra::rast(array(sample(5:10, 100, replace = TRUE), dim=c(10,10,1), dimnames= NULL))
rand_5 <- terra::rast(array(sample(1:20, 100, replace = TRUE), dim=c(10,10,1), dimnames= NULL))
rand_5_diff_min_max <- c(rand_1, rand_2, rand_3, rand_4, rand_5)
rand_5_diff_min_max
class       : SpatRaster 
dimensions  : 10, 10, 5  (nrow, ncol, nlyr)
resolution  : 1, 1  (x, y)
extent      : 0, 10, 0, 10  (xmin, xmax, ymin, ymax)
coord. ref. :  
source(s)   : memory
names       : lyr.1, lyr.1, lyr.1, lyr.1, lyr.1 
min values  :     2,     6,     1,     5,     1 
max values  :     9,    11,     7,    10,    20

where same min/max could be achieved with

rand_5 <- terra::rast(array(sample(2:9, 500, replace = TRUE), dim=c(10,10,5), dimnames= NULL))

If you have dimnames in mind, put them in a dimnames = list('. Still don't know your thinking on pixels adding to n.

CodePudding user response:

You could do

library(terra)
x <- rast(ncol=10, nrow=10)
xmin <- 1:5  / 10
xmax <- 6:10 / 10
x <- rast(sapply(1:5, \(i) init(x, runif(ncell(x), min=xmin[i], max=xmax[i]))))

x <- x / sum(x)

Of course, after this the ranges of the values have changed. But this shows how to do things with raster data. Your real question is probably "how do I take five random numbers that are within certain bounds (different for each number), and that add up to 1". Once you have figured that out, the raster stuff is easy (replace init with your function). That is a bit tricky, and it would be helpful if provide an example of the bounds that you have in mind.

  • Related