rm(list=ls()) #clear workspace library(raster) library(raster) library(sp) library(rgdal) library(rgeos) library(dplyr) library(igraph) rm(list=ls()) setwd("C:/Users/aradhik/Google Drive/Kutzu/from Gehendra") ###Kudzu Infestation in Oklahoma set.seed(95) # set random number seed #### kudzu grid #### #read in raster of OK grid OK.rast16<-raster("OK_raster_timberland_500m.tif") sim.yr0<-OK.rast16 #vectorized code #on average takes less than 10 seconds for each simulation fun.one.ann.sim<-function(raster_in){ rasterl<-raster_in #create a raster layer with value 1 for kudzu cells otherwise 2 rasterl[!is.na(raster_in) & raster_in==1]<-1 rasterl[!is.na(raster_in) & raster_in==0]<-2 #minimum distance from kudzu cells to other cells d <- gridDistance(rasterl,origin=1) #set outside values to NA d[is.na(raster_in)]<-NA prob <- exp(0.0369599-0.00474401*d) #create raster with uniformly distributed random numbers rannum<-rasterl rannum[]<-runif(ncell(rannum)) rannum[is.na(raster_in)]<-NA #set outside values to NA #table(getValues(prob>rannum)) # use it to see the numbers of 1 return(prob>rannum) # raster with binary values } # matrices to store the cumulative results of the simulations blanklayer<-OK.rast16 blanklayer[]<-0 sim.yr1.tally <- blanklayer # tally spread after the 1st year sim.yr2.tally <- blanklayer # tally spread after the 2nd year sim.yr3.tally <- blanklayer # tally spread after the 3rd year sim.yr4.tally <- blanklayer # tally spread after the 4th year sim.yr5.tally <- blanklayer # tally spread after the 5th year # apply the above function to do 10 5-year simulations for (i in 1:6000){ start_time <- Sys.time() sim.yr1 <- fun.one.ann.sim(sim.yr0) # spread after the 1st year sim.yr2 <- fun.one.ann.sim(sim.yr1) # spread after the 2nd year sim.yr3 <- fun.one.ann.sim(sim.yr2) # spread after the 3rd year sim.yr4 <- fun.one.ann.sim(sim.yr3) # spread after the 4th year sim.yr5 <- fun.one.ann.sim(sim.yr4) # spread after the 5th year sim.yr1.tally <- sim.yr1.tally + sim.yr1 sim.yr2.tally <- sim.yr2.tally + sim.yr2 sim.yr3.tally <- sim.yr3.tally + sim.yr3 sim.yr4.tally <- sim.yr4.tally + sim.yr4 sim.yr5.tally <- sim.yr5.tally + sim.yr5 cat(i, print(Sys.time() - start_time)) } # save Raster writeRaster(sim.yr1,file="sim.yr1.tif", overwrite=TRUE) writeRaster(sim.yr2,file="sim.yr2.tif", overwrite=TRUE) writeRaster(sim.yr3,file="sim.yr3.tif", overwrite=TRUE) writeRaster(sim.yr4,file="sim.yr4.tif", overwrite=TRUE) writeRaster(sim.yr5,file="sim.yr5.tif", overwrite=TRUE) writeRaster(sim.yr1.tally,file="sim.yr1.tally.tif", overwrite=TRUE) writeRaster(sim.yr2.tally,file="sim.yr2.tally.tif", overwrite=TRUE) writeRaster(sim.yr3.tally,file="sim.yr3.tally.tif", overwrite=TRUE) writeRaster(sim.yr4.tally,file="sim.yr4.tally.tif", overwrite=TRUE) writeRaster(sim.yr5.tally,file="sim.yr5.tally.tif", overwrite=TRUE)