Search code examples
rspatstat

Obtain values from simulated mppm in spatstat


I have obtained an mppm object by fitting a model on several independent datasets using the mppm function from the R package spatstat. How can I generate simulated realisations of this model and obtain the x, y, and marks attributes of the simulations ?

I fitted my model as such:

data <- listof(NMJ1,NMJ2,NMJ3)
data <- hyperframe(X=1:3, Points=data)
model  <- mppm(Points ~marks*sqrt(x^2+y^2), data)

where NMJ1, NMJ2, and NMJ3 are marked ppp and are independent realisations of the same experiment.

sim <- simulate(model) allows me to generate simulated realisations of this model, and plot(sim,axes = TRUE) to plot them. sim itself is an hyperframe object:

> sim
Hyperframe:
   Sim1
1 (ppp)
2 (ppp)
3 (ppp)

How can I access the values (x, y, and marks) in this hyperframe ? My goal is to generate a large number of independent realisations from my model, and to use the simulated values for another task. Is there a practical way to obtain, retrieve and save these values ?


Solution

  • Since you say you want to simulate this many times I have here shown the code with two simulations (rather than one as you have in the question):

    library(spatstat)
    data <- list(amacrine, amacrine, amacrine)
    data <- hyperframe(X=1:3, Points=data)
    model  <- mppm(Points ~marks*sqrt(x^2+y^2), data)
    sim <- simulate(model, nsim = 2)
    #> Generating simulated realisations of 3 models..
    #> 1, 2,  3.
    

    Now sim is a hyperframe with 2 columns (one for each simulation). Each column is a list of 3 point patterns. To get the three sets of coordinates and marks for the first simulation use as.data.frame on each point pattern:

    co1 <- lapply(sim$Sim1, as.data.frame)
    

    Then co1 is a list of length 3, and we can print out the first few coordinates with the head() command, e.g. the coordinates of the third point pattern:

    head(co1[[3]])
    #>           x         y marks
    #> 1 0.4942587 0.7889985   off
    #> 2 0.6987270 0.7637359    on
    #> 3 0.3926415 0.6819965    on
    #> 4 0.7982686 0.9060733   off
    #> 5 1.3507722 0.9731363    on
    #> 6 0.6450985 0.6924126    on
    

    We can extract the coordinates and marks for each simulation by another lapply that runs over every simulation (in this case 2):

    co <- lapply(sim, function(x) lapply(x, as.data.frame))
    

    Now co is a list with 2 elements, and each element is a list of 3 sets of coordinates:

    length(co)
    #> [1] 2
    length(co[[2]])
    #> [1] 3
    head(co[[2]][[3]])
    #>           x          y marks
    #> 1 0.1660580 0.04180501    on
    #> 2 0.7840025 0.71727782    on
    #> 3 1.2011733 0.17109112    on
    #> 4 1.0429867 0.49284639    on
    #> 5 1.1411869 0.86711072   off
    #> 6 1.0375942 0.06427601    on