-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmpbRedTopSpread.R
1420 lines (1242 loc) · 67.8 KB
/
mpbRedTopSpread.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## package BioSIM not available on CRAN nor GitHub; needs to be installed as follows:
## install.packages("https://sourceforge.net/projects/repiceasource/files/latest", repos = NULL, type = "source")
## install.packages("https://sourceforge.net/projects/biosimclient.mrnfforesttools.p/files/latest", repos = NULL, type = "source")
defineModule(sim, list(
name = "mpbRedTopSpread",
description = "Mountain Pine Beetle Red Top Growth Model: Short-run Potential for Establishment, Eruption, and Spread",
keywords = c("mountain pine beetle, outbreak dynamics, eruptive potential, spread, climate change, twitch response"),
authors = c(
person(c("Alex", "M"), "Chubaty", email = "achubaty@for-cast.ca", role = c("aut", "cre")),
person(c("Eliot", "J B"), "McIntire", email = "eliot.mcintire@canada.ca", role = c("aut")),
person(c("Barry", "J"), "Cooke", email = "barry.cooke@canada.ca", role = c("aut"))
),
childModules = character(),
version = numeric_version("0.0.1"),
spatialExtent = raster::extent(rep(NA_real_, 4)),
timeframe = as.POSIXlt(c(NA, NA)),
timeunit = "year",
citation = list(),
reqdPkgs = list("achubaty/amc@development",
"BioSIM", ## ## not on CRAN/GitHub; see install info at top of this file
"CircStats", "data.table", "DEoptim", "EnvStats",
"gamlss", "ggplot2", "gt",
"PredictiveEcology/SpaDES.core@development (>= 1.0.8.9011)",
"PredictiveEcology/LandR@development (>= 1.0.7.9007)",
"parallelly",
"PredictiveEcology/pemisc@development (>= 0.0.3.9001)",
"PredictiveEcology/mpbutils (>= 0.1.3.9000)", "optimParallel", "purrr",
"quickPlot", "raster", "RColorBrewer",
"PredictiveEcology/reproducible@development (>= 1.2.8.9041)",
"PredictiveEcology/SpaDES.tools@development (>= 0.3.7.9021)",
"terra", "tmap"),
parameters = rbind(
defineParameter("cachePredict", "logical", TRUE, NA, NA,
"The function predictQuotedSpread can be Cached or not; default is TRUE"),
defineParameter("colNameForPrediction", "character", "ATKTREES", NA, NA,
"The column name in massAttacksDT that contains the values to predict from"),
defineParameter("coresForPrediction", "integer", 10L, NA, NA,
"The number of cores to use for `predictQuotedSpread`. These will be fork cluster cores."),
defineParameter("dataset", "character", "Boone2011", NA, NA, "Which dataset to use for stand dynamic model fitting. One of 'Boone2011' (default), 'Berryman1979_fit', or 'Berryman1979_forced'. Others to be implemented later."),
defineParameter("growthInterval", "numeric", 1, NA, NA, "This describes the interval time between growth events"),
# defineParameter("p_advectionDir", "numeric", 90, 0, 359.9999,
# "The direction of the spread bias, in degrees from north"),
# defineParameter("bgSettlingProp", "numeric", 0.1, 0, 1,
# "The proportion of beetles that settle from those that could potentially settle, even if no pine"),
defineParameter("dispersalKernel", "character", "Weibull3", NA, NA,
paste("One of 'Weibull3', 'GeneralizedGamma', 'twodt', or 'Exponential'.")),
defineParameter("thresholdPineProportion", "numeric", 0.0, 0, 1,
paste("The threshold of proportion cover of pine in the pine layer that",
"is available to be attacked during predict mode.")),
defineParameter("minAgeForMPB", "numeric", 40, NA, NA,
"The minimum age of tree that a MPB will attack a tree during epidemic phase."),
defineParameter("maxDistance", "numeric", 1.4e5, NA, NA,
"The maximum distance to allow for pair-wise from-to dispersal pairs."),
defineParameter("quotedSpread", c("language"), NULL, NA, NA,
paste("A spread function that is contained within a `quote()`.",
"If left at NULL or NA, it will use the module version.")),
defineParameter("p_advectionMag", "numeric", 5e3, NA, NA,
paste("The magnitude of the wind effect on spread.",
"This number is multiplied by the wind speed",
"(which averages 9.6 km/h in the historical dataset)")),
defineParameter("p_meanDist", "numeric", 1e4, NA, NA,
"Expected dispersal distance (m); ~63% go less than this distance."),
defineParameter("p_nu", "numeric", 1, NA, NA,
"Third parameter in the generalized gamma"),
# defineParameter("p_rescaler", "numeric", 1, NA, NA,
# "Single scalar that rescales the predicted abundances that result from growMultiYear ",
# "& dispersalFit, so that they match the observed data"),
defineParameter("p_sdDist", "numeric", 1.2, NA, NA,
paste("The dispersion term for the Weibull dispersal kernel:",
"contributes to shape and scale parameters;",
"sqrt(variance(of the Weibull distribution))")),
defineParameter("pineSpToUse", "character", c("Pinu_con" , "Pinu_ban"), NA, NA,
paste("The 1 or 2 or 3 pine species to use as possible host for MPB.",
"There are currently no differentiation by species")),
defineParameter("stemsPerHaAvg", "integer", 1125L, NA, NA,
paste("The average number of pine stems per ha in the study area.",
"Taken from Whitehead & Russo (2005), Cooke & Carroll (2017).")),
defineParameter("type", "character", "DEoptim", NA, NA,
paste("One of several modes of running this module:",
"'DEoptim', 'optim', 'runOnce', 'validate', 'predict' or 'nofit'.")),
defineParameter(".plots", "character", "screen", NA, NA,
"Zero or more of 'screen', 'png', 'pdf', 'raw'. See `?Plots`."),
defineParameter(".plotInitialTime", "numeric", start(sim), NA, NA,
"This describes the simulation time at which the first plot event should occur."),
defineParameter(".plotInterval", "numeric", 1, NA, NA,
"This describes the interval between plot events."),
defineParameter(".runName", "character", NULL, NA, NA,
"An optional name for a specific run."),
defineParameter(".saveInitialTime", "numeric", NA, NA, NA,
"This describes the simulation time at which the first save event should occur"),
defineParameter(".saveInterval", "numeric", NA, NA, NA,
"This describes the interval between save events"),
defineParameter(".useCache", "logical", FALSE, NA, NA,
"Should this entire module be run with caching activated?")
),
inputObjects = bindrows(
expectsInput("absk", "SpatialPolygonsDataFrame",
"Alberta and Saskatchewan provincial boundaries.", sourceURL = NA),
expectsInput("columnsForPixelGroups", "character",
paste("The names of the columns in cohortData that define unique pixelGroups.",
"Default is c('ecoregionGroup', 'speciesCode', 'age', 'B')."), sourceURL = NA),
expectsInput("climateSuitabilityMaps", "SpatRaster",
paste("A time series of climatic suitablity RasterLayers,",
"each with prefix 'X' and the year, e.g., 'X2010'"), sourceURL = NA),
expectsInput("massAttacksStack", "SpatRaster",
"Historical MPB attack maps (number of red attacked trees).", sourceURL = NA),
expectsInput("pineMap", "RasterLayer",
"Percent cover maps by species (lodgepole and jack pine).", sourceURL = NA),
expectsInput("rasterToMatch", "RasterLayer",
"template raster for GIS operations.", sourceURL = NA),
expectsInput("standAgeMap", "RasterLayer",
"stand age map in study area, default is Canada national stand age map",
sourceURL = paste0("http://ftp.maps.canada.ca/pub/nrcan_rncan/Forests_Foret/",
"canada-forests-attributes_attributs-forests-canada/",
"2001-attributes_attributs-2001/",
"NFI_MODIS250m_2001_kNN_Structure_Stand_Age_v1.tif")),
expectsInput("windDirStack", "SpatRaster",
"SpatRaster of wind maps for every location in the study area",
sourceURL = NA)
),
outputObjects = bindrows(
createsOutput("cohortPixelDataMPBLost", "data.table",
paste("A `cohortPixelData`-like object, but with extra columns: ",
"numStems (the estimated number of stems of Pine), ",
"BafterMPBKills (the new value for the B for the cohort after MPB attacks are removed), ",
"Bloss (the estimated B lost in that cohort after MPB attacks are removed)")),
createsOutput("massAttacksDT", "data.table", "Current MPB attack map (number of red attacked trees)."),
createsOutput("massAttacksStack", "SpatRaster",
"This will be the same data as the inputted object, but will have a different resolution."),
createsOutput("fit_mpbSpreadOptimizer", "list", "The output object from DEoptim"),
createsOutput("propPineRas", "RasterLayer",
paste("Proportion (not percent) cover map of *all* pine. This will",
" be the pixel-based sum if there are more than one layer")),
createsOutput("predictedDT", "data.table",
"Similar to massAttacksDT, but with predicted (from the models here) values of ATKTREES"),
createsOutput("thresholdAttackTreesMinDetectable", "numeric",
paste("The number of predicted attacks (post dispersal) per pixel below which ",
"it can be considered 'no attack'")),
createsOutput("ROCList", "list", "") ## TODO: DESCRIPTION NEEDED
)
))
## event types
# - type `init` is required for initilization
doEvent.mpbRedTopSpread <- function(sim, eventTime, eventType, debug = FALSE) {
switch(eventType,
"init" = {
# do stuff for this event
sim <- Init(sim)
# schedule future event(s)
if (isTRUE(any(c("fit", "DEoptim", "runOnce", "optim", "all") %in% P(sim)$type))) {
sim <- scheduleEvent(sim, time(sim), "mpbRedTopSpread", "growMultiYear", eventPriority = 2.5)
sim <- scheduleEvent(sim, time(sim), "mpbRedTopSpread", "dispersalFit", eventPriority = 3.5)
}
if (isTRUE(any(c("validate", "all") %in% P(sim)$type))) {
sim <- scheduleEvent(sim, time(sim), "mpbRedTopSpread", "growMultiYear", eventPriority = 2.5)
sim <- scheduleEvent(sim, time(sim), "mpbRedTopSpread", "validate", 4.5)
}
if (isTRUE(any(c("predict", "all") %in% P(sim)$type))) { # will automatically validate
sim <- scheduleEvent(sim, time(sim), "mpbRedTopSpread", "dispersalFit", eventPriority = 3.5) # need to run fit or get Cached object
sim <- scheduleEvent(sim, time(sim), "mpbRedTopSpread", "growPredict", eventPriority = 5.5)
sim <- scheduleEvent(sim, end(sim), "mpbRedTopSpread", "validate", 7)
} else if (isTRUE(any(c("validateAll") %in% P(sim)$type))) {
sim <- scheduleEvent(sim, end(sim), "mpbRedTopSpread", "validate", 7)
}
# sim <- scheduleEvent(sim, P(sim)$.plotInitialTime, "mpbRedTopSpread", "plot", 7.5)
# sim <- scheduleEvent(sim, P(sim)$.saveInitialTime, "mpbRedTopSpread", "save", .last())
},
"growMultiYear" = {
sim$massAttacksDT <- grow(sim$massAttacksDT, P(sim)$dataset,
sim$massAttacksStack, mod$growthData)
},
"growPredict" = {
if (is.null(sim$fit_mpbSpreadOptimizer)) {
browser() # This should no longer be necessary -- it will run the DEoptim and pull from Cache
message("A fit_mpbSpreadOptimizer object should probably be supplied")
optimOutFileList <- dir(outputPath(sim), pattern = "optimOut", full.names = TRUE)
sim$fit_mpbSpreadOptimizer <- readRDS(optimOutFileList[[3]])
DEoutFileList <- dir(outputPath(sim), pattern = "fit_mpbSpreadOptimizer", full.names = TRUE)
sim$fit_mpbSpreadOptimizer <- readRDS(DEoutFileList[[23]])
sim$fit_mpbSpreadOptimizer <- colnamesToDEout(sim$fit_mpbSpreadOptimizer, c("p_meanDist", "p_advectionMag", "p_sdDist"))
}
if (!is.null(sim$cohortData)) {
message("Using sim$cohortData to change/update the sim$propPineRas, because sim$cohortData is present")
propPineRas <- propPineFromCD(sim$cohortData, sim$sppEquiv, sim$pixelGroupMap, P(sim)$pineSpToUse) # all cohortData stuff is at full resolution
propPineRas = terra::project(terra::rast(propPineRas), terra::rast(sim$massAttacksStack), method = "bilinear" )
sim$propPineRas <- raster::raster(propPineRas)
}
sim$massAttacksDT_1Yr <- growPredict(sim)
message("Estimated ",
format(scientific = TRUE, round(sum(sim$massAttacksDT_1Yr$greenTreesYr_t, na.rm = TRUE), 0)),
" source trees ", "in year ", time(sim) + 1)
if (anyPlotting(Par$.plots)) {
title <- paste0("Predicted Attack vs. Current Attack, prior to dispersal, year ", time(sim))
Plots(fn = plot_atkYearByYearPlus1, maDT = sim$massAttacksDT_1Yr, title = title, type = "screen", usePlot = FALSE,
filename = file.path(outputPath(sim), "figures", paste0(title)))
}
## growth needs to happen after spread:
sim <- scheduleEvent(sim, time(sim), "mpbRedTopSpread", "dispersalPredict", eventPriority = 5.5)
},
"dispersalPredict" = {
paramCheckOtherMods(sim, "")
sim$predictedDT <- dispersalPredict(sim) # this object accumulates years over time
message("Estimated ",
format(scientific = TRUE, round(sum(sim$predictedDT$ATKTREES, na.rm = TRUE), 0)),
" trees attacked after dispersal ", "in year ", time(sim) + 1)
pcd <- cohortData2PixelCohortData(sim$cohortData, sim$pixelGroupMap)
pineAttackedRas <- raster(sim$massAttacksStack)
sim$predictedDT <- sim$predictedDT[sim$predictedDT$ATKTREES > 0]
pineAttackedRas[sim$predictedDT$pixel] <- sim$predictedDT$ATKTREES
pineAttackedRasLg <- raster::raster(terra::project(terra::rast(pineAttackedRas), terra::rast(sim$pixelGroupMap)))
dt <- data.table(numStemsKilled = pineAttackedRasLg[], pixelIndex = seq(ncell(pineAttackedRasLg)))
dt <- na.omit(dt)
pinesInCohortData <- equivalentName(P(sim)$pineSpToUse, sim$sppEquiv,
equivalentNameColumn(levels(sim$cohortData$speciesCode), sim$sppEquiv))
dt1 <- dt[pcd, on = "pixelIndex", nomatch = 0] # assigns to all cohorts in a pixelIndex
set(dt1, NULL, "pixelGroup", NULL) # they are no longer valid
# Until here, the numStemsKilled is theoretical -- it is the number of attacked trees, if there are trees to attack
# After this, it is converted to real
dt1[, propB := B/sum(B), by = "pixelIndex"]
dt1[, numStems := pmax(1, asInteger(propB * Par$stemsPerHaAvg))] # if B is very low, asInteger can round down to 0 stems --> causes failures below
set(dt1, NULL, "propB", NULL) # this was just to calculate how many stems of pine there are; not needed further
set(dt1, which(dt1$age < Par$minAgeForMPB), "numStemsKilled", 0)
onlyAttackablePines <- which(dt1$speciesCode %in% pinesInCohortData & dt1$age >= Par$minAgeForMPB)
dt1[onlyAttackablePines, BafterMPBKills := asInteger((1 - numStemsKilled / numStems) * B)]
dt1[onlyAttackablePines, Bloss := B - BafterMPBKills]
sim$cohortPixelDataMPBLost <- dt1[onlyAttackablePines]
message("Estimated ",
format(scientific = TRUE, round(sum(sim$cohortPixelDataMPBLost$Bloss, na.rm = TRUE), 0)),
" Biomass lost after dispersal ", "in year ", time(sim) + 1)
dt1[onlyAttackablePines, B := BafterMPBKills]
set(dt1, NULL, c("BafterMPBKills", "numStems", "Bloss"), NULL)
# Next step need to rebuild the cohortData, but with new B
# This is an update join! WTF! https://stackoverflow.com/questions/44433451/r-data-table-update-join
pcd[dt1[speciesCode %in% pinesInCohortData, c("pixelIndex", "speciesCode", "B")],
on = c("speciesCode", "pixelIndex"), c("B") := .(i.B)]
whChanged <- pcd$pixelIndex %in% dt1$pixelIndex
pcdChanged <- pcd[whChanged]
pcdUnchanged <- pcd[!whChanged]
if (!("B" %in% sim$columnsForPixelGroups)) {
co <- capture.output(dput(union(sim$columnsForPixelGroups, "B")))
stop("sim$columnsForPixelGroups must use Biomass (B column) because of partial mortality; ",
"Please set this object e.g., \n",
"sim$columnsForPixelGroups = ", co)
}
pgs <- LandR::generatePixelGroups(pcdChanged, sim$columnsForPixelGroups,
maxPixelGroup = max(pcdUnchanged$pixelGroup))
set(pcdChanged, NULL, c("uniqueComboByRow", "uniqueComboByPixelIndex"), NULL)
pcdNew <- rbindlist(list(pcdUnchanged, pcdChanged))
pgm <- makePixelGroupMap(pcdNew, rasterToMatch = sim$rasterToMatch)
sim$cohortData <- unique(pcd[, -"pixelIndex"], by = sim$columnsForPixelGroups) # need B because partial Pine mortality
sim <- scheduleEvent(sim, time(sim) + 1, "mpbRedTopSpread", "growPredict", eventPriority = 5.5)
},
"dispersalFit" = {
sim$fit_mpbSpreadOptimizer <- dispersalFit(quotedSpread = P(sim)$quotedSpread,
propPineRas = sim$propPineRas, studyArea = sim$studyArea,
massAttacksDT = sim$massAttacksDT,
massAttacksStack = sim$massAttacksStack,
maxDistance = P(sim)$maxDistance,
params = P(sim),
windDirStack = sim$windDirStack,
windSpeedStack = sim$windSpeedStack,
rasterToMatch = sim$rasterToMatch,
# bgSettlingProp = P(sim)$bgSettlingProp,
dispersalKernel = P(sim)$dispersalKernel,
type = P(sim)$type,
outputPath = outputPath(sim),
# currentTime = time(sim),
reqdPkgs = reqdPkgs(module = currentModule(sim),
modulePath = modulePath(sim))[[currentModule(sim)]]
)
# sim <- dispersal(sim)
# sim <- scheduleEvent(sim, time(sim) + 1, "mpbRedTopSpread", "dispersal", eventPriority = 5.5)
},
"validate" = {
sim <- Validate(sim)
},
"plot" = {
sim <- plotFn(sim)
sim <- scheduleEvent(sim, time(sim) + 1, "mpbRedTopSpread", "plot", eventPriority = .last() - 1)
},
warning(paste("Undefined event type: '", events(sim)[1, "eventType", with = FALSE],
"' in module '", events(sim)[1, "moduleName", with = FALSE], "'", sep = ""))
)
return(invisible(sim))
}
.inputObjects <- function(sim) {
cacheTags <- c(currentModule(sim), "function:.inputObjects")
cPath <- cachePath(sim)
dPath <- asPath(getOption("reproducible.destinationPath", dataPath(sim)), 1)
if (getOption("LandR.verbose", TRUE) > 0)
message(currentModule(sim), ": using dataPath '", dPath, "'.")
#mod$prj <- paste("+proj=aea +lat_1=47.5 +lat_2=54.5 +lat_0=0 +lon_0=-113",
# "+x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs +ellps=GRS80 +towgs84=0,0,0")
mod$prj <- paste("+proj=lcc +lat_1=49 +lat_2=77 +lat_0=0 +lon_0=-95",
"+x_0=0 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs")
## load study area
if (!suppliedElsewhere("studyArea")) {
sim$studyArea <- mpbStudyArea(ecoregions = c(112, 120, 122, 124, 126), mod$prj,
cPath, dPath)
}
## raster to match
if (!suppliedElsewhere("rasterToMatch", sim)) {
sim$rasterToMatch <- Cache(
LandR::prepInputsLCC,
year = 2005,
destinationPath = dPath,
studyArea = sf::as_Spatial(sim$studyArea)
)
}
## stand age map
if (!suppliedElsewhere("standAgeMap", sim)) {
sim$standAgeMap <- LandR::prepInputsStandAgeMap(
startTime = 2010,
ageUrl = na.omit(extractURL("standAgeMap")),
destinationPath = dPath,
studyArea = sim$studyArea,
rasterToMatch = sim$rasterToMatch,
userTags = c("stable", currentModule(sim)) ## TODO: does this need rasterToMatch? it IS rtm!
)
sim$standAgeMap[] <- asInteger(sim$standAgeMap[])
}
if (!suppliedElsewhere("windDirStack", sim)) {
aggFact <- P(sim)$aggFact
## make coarser
aggRTM <- raster::raster(sim$rasterToMatch)
aggRTM <- raster::aggregate(aggRTM, fact = aggFact)
browser()
aggRTM <- LandR::aggregateRasByDT(sim$rasterToMatch, aggRTM, fn = mean)
dem <- Cache(prepInputsCanDEM,
studyArea = sim$studyArea,
rasterToMatch = aggRTM,
destinationPath = inputPath(sim))
## TODO: using "ClimaticWind_Annual"; use mean wind for summer [flight] months only
windStk <- LandR::BioSIM_getWind(
dem = dem,
years = P(sim)$years,
climModel = P(sim)$climateModel,
rcp = P(sim)$climateScenario
)
windDirStack <- disaggregate(windStk, fact = aggFact)
sim$windDirStack <- raster::stack(crop(windDirStack, sim$rasterToMatch)) ## TODO: speed and dir??
if (!compareRaster(sim$windDirStack, sim$rasterToMatch, stopiffalse = FALSE)) {
warning("wind raster is not same resolution as sim$rasterToMatch; please debug")
browser() ## TODO: remove
}
}
kern <- tolower(P(sim)$dispersalKernel)
if (grepl("weibul", kern))
P(sim, "quotedSpread") <- quotedSpreadWeibull3
if (grepl("exponen", kern))
P(sim, "quotedSpread") <- quotedSpreadExponential
if (grepl("gamma", kern))
P(sim, "quotedSpread") <- quotedSpreadGeneralGamma
if (is.null(P(sim)$quotedSpread))
P(sim, "quotedSpread") <- quotedSpreadWeibull3
if (!suppliedElsewhere("columnsForPixelGroups", sim)) {
sim$columnsForPixelGroups <- LandR::columnsForPixelGroups
}
return(invisible(sim))
}
### initilization
Init <- function(sim) {
cr <- terra::compareGeom(sim$rasterToMatch, sim$massAttacksStack, sim$pineMap)
if (!isTRUE(cr))
stop("Rasters sim$rasterToMatch, sim$massAttacksStack, sim$pineMap must all have same metadata; they do not")
# AGGREGATE FROM HERE
if (nzchar(Filenames(sim$pineMap)))
sim$pineMap[] <- sim$pineMap[]
## use 1125 trees/ha, per Whitehead & Russo (2005), Cooke & Carroll (2017)
MAXTREES <- P(sim)$stemsPerHaAvg * prod(res(sim$pineMap)) / 100^2 ## TODO: round this?
## asymmetric spread (biased eastward)
# lodgepole pine and jack pine together
mv <- maxFn(sim$pineMap)
propPineRas <- rast(sim$pineMap)
propPineRas[] <- if (mv > 1) {
sim$pineMap[] / 100 ## much faster than calc; ## TODO: allow different params per species
} else {
sim$pineMap[]
}
nas <- is.na(propPineRas[])# & !is.na(rasterToMatch[])
propPineRas[nas] <- 0
nams <- names(sim$massAttacksStack)
rasCoarse <- coarseRaster(sim$massAttacksStack)
# massAttacksList <- raster::unstack(sim$massAttacksStack)
#opts <- options(reproducible.cacheSpeed = "fast")
#on.exit(options(opts))
#mams <- raster::stack(
# Cache(lapply, massAttacksList, function(mam)
# aggregateRasByDT(mam, rasCoarse, fn = sum))
#)
#names(mams) <- names(sim$massAttacksStack)
#sim$massAttacksStack <- mams
resRatio <- res(rasCoarse)[1]/res(sim$climateSuitabilityMaps)[1]
sim$massAttacksStack <- Cache(terra::aggregate, sim$massAttacksStack,
res(rasCoarse)[1]/res(sim$massAttacksStack)[1],
fun = "sum", na.rm = TRUE)
sim$propPineRas <- Cache(aggregate, propPineRas,
res(rasCoarse)[1]/res(propPineRas)[1], fun = "mean",
na.rm = TRUE)
sim$windDirStack <- Cache(aggregate, sim$windDirStack,
res(rasCoarse)[1]/res(sim$windDirStack)[1],
fun = "mean", na.rm = TRUE)
sim$windSpeedStack <- Cache(aggregate, sim$windSpeedStack,
res(rasCoarse)[1]/res(sim$windSpeedStack)[1],
fun = "mean", na.rm = TRUE)
sim$climateSuitabilityMaps <- Cache(aggregate, sim$climateSuitabilityMaps,
res(rasCoarse)[1]/res(sim$climateSuitabilityMaps)[1],
fun = "mean", na.rm = TRUE)
# if (resRatio < 1) {
# # climateSuitabilityMaps <- Cache(disaggregate, sim$climateSuitabilityMaps, fact = 10)
# climateSuitabilityMaps <- terra:::project(sim$climateSuitabilityMaps, terra::rast(sim$massAttacksStack))
# sim$climateSuitabilityMaps <- climateSuitabilityMaps
# }
terra::compareGeom(sim$massAttacksStack,
sim$propPineRas,
sim$windDirStack,
sim$windSpeedStack,
sim$climateSuitabilityMaps)
# options(opts)
## create a data.table consisting of the reduced map of current MPB distribution,
## proportion pine, and climatic suitability;
## use only the start year's non-zero and non-NA data
ids <- sim$massAttacksStack[]
ids <- which(ids > 0, arr.ind = TRUE)
mpb.sp <- terra::xyFromCell(sim$massAttacksStack, cell = ids[, "row"])
# crs(mpb.sp) <- crs(sim$massAttacksStack)
sim$massAttacksDT <- as.data.table(ids)
setnames(sim$massAttacksDT, old = c("row", "col"), new = c("pixel", "layerNum"))
sim$massAttacksDT <- data.table(sim$massAttacksDT, mpb.sp)
sim$massAttacksDT[, layerName := names(sim$massAttacksStack)[layerNum]]
sim$massAttacksDT[, `:=`(c("CLIMATE", "ATKTREES"), {
bb <- .BY
CLIMATE = terra::extract(sim$climateSuitabilityMaps[[bb[[1]]]], cbind(x, y))
ATKTREES = terra::extract(sim$massAttacksStack[[bb[[1]]]], cbind(x, y))#,
list(CLIMATE = unlist(CLIMATE), ATKTREES = unlist(ATKTREES))
}
),
by = "layerName"]
sim$predictedDT <- sim$massAttacksDT[0]
## growth data
mod$growthData <-
switch(P(sim)$dataset,
"Berryman1979_fit" = {
## Berryman1979_forced
data.frame(
year = c(1:15),
log10Xtm1 = c(-3.1, -2.75, -2.7, -2.4, -2.3, -1.2, -1, 0.2, 0.9, 0.65,
1.05, 0.95, 1.1, 1.5, 1.85),
log10Rt = c(0.35, 0.4, 0.1, -0.4, -0.65, 0.3, 1, 0.75, 1.2, -0.7,
-0.4, 0.2, 0.45, 0.3, -0.78),
study = c(rep("Tunnock 1970", 9), rep("Parker 1973", 6)),
stringsAsFactors = TRUE
)
},
"Berryman1979_forced" = {
## same as Berryman1979_fit
data.frame(
year = c(1:15),
log10Xtm1 = c(-3.1, -2.75, -2.7, -2.4, -2.3, -1.2, -1, 0.2, 0.9, 0.65,
1.05, 0.95, 1.1, 1.5, 1.85),
log10Rt = c(0.35, 0.4, 0.1, -0.4, -0.65, 0.3, 1, 0.75, 1.2, -0.7,
-0.4, 0.2, 0.45, 0.3, -0.78),
study = c(rep("Tunnock 1970", 9), rep("Parker 1973", 6)),
stringsAsFactors = TRUE
)
},
"Boone2011" = {
data <- read.csv(file.path(dataPath(sim), "BooneCurveData2.csv"))
data$Site <- c(rep("A", 6), rep("B", 6), rep("D", 5), rep("E", 4), rep("F", 4), rep("G", 3))
data$Year <- c(2000:2005, 2000:2005, 2001:2005, 2002:2005, 2002:2005, 2003:2005)
data
}
)
return(invisible(sim))
}
dispersalPredict <- function(sim) {
pBest <- sim$fit_mpbSpreadOptimizer$optim$bestmem
if (is.null(sim$thresholdAttackTreesMinDetectable)) {
sim$thresholdAttackTreesMinDetectable <- 1.4
}
predictedDT <- predictQuotedSpread(
showSimilar = FALSE, # a bug in the database -- remove this
massAttacksDT = sim$massAttacksDT_1Yr,
windDirStack = sim$windDirStack,
windSpeedStack = sim$windSpeedStack,
propPineRas = sim$propPineRas,
thresholdPineProportion = P(sim)$thresholdPineProportion,
dispersalKernel = P(sim)$dispersalKernel,
clNumber = Par$coresForPrediction,
#useCache = P(sim)$cachePredict,
maxDistance = P(sim)$maxDistance,
quotedSpread = P(sim)$quotedSpread, # doesn't cache correctly
#.cacheExtra = format(P(sim)$quotedSpread), # cache this instead
p = pBest,
colNameForPrediction = P(sim)$colNameForPrediction#,
#omitArgs = "quotedSpread"
)
predictedDT[, CLIMATE := sim$climateSuitabilityMaps[[unique(layerName)]][pixel]]
return(rbindlist(list(sim$predictedDT, predictedDT), use.names = TRUE, fill = TRUE))
}
#' Validate is expecting many years in the massAttacksDT, so it not appropriate for 1 year at a time
Validate <- function(sim) {
startToEnd <- paste0(start(sim), " to ", end(sim), "_", Sys.time())
if (is.null(sim$DEout)) {
DEoutFileList <- dir(outputPath(sim), pattern = "DEout", full.names = TRUE)
fit_mpbSpreadOptimizer <- readRDS(tail(DEoutFileList, 1)) # 24 was best so far
}
DEouts <- list(fit_mpbSpreadOptimizer)
sim$ROCList <- list()
for (iii in seq_along(DEouts)) {#seq(DEoutFileList)) { # 22 is good (the 6 parameter generalgamma)
if (FALSE) {
optimOut <- readRDS(optimOutFileList[3])
p <- optimOut$par
objsToExport <- setdiff(formalArgs("objFun"),
# The following are small and passed at the time of the DEoptim call
c("p", "quotedSpread", "distanceFunction"))
sim$omitPastPines <- FALSE
sim$p_sdDist <- p["p_sdDist"]
sim$dispersalKernel <- P(sim)$dispersalKernel
sim$maxDistance <- Par$maxDistance
ss <- do.call(numDeriv::hessian, append(list(func = objFun),
mget(objsToExport, envir = envir(sim))))
}
if (length(fit_mpbSpreadOptimizer$optim$bestmem) %in% 3:4 || iii > 20) {
if (all(grepl("par[[:digit:]]", names(fit_mpbSpreadOptimizer$optim$bestmem))))
if (length(fit_mpbSpreadOptimizer$optim$bestmem) == 3) {
fit_mpbSpreadOptimizer <- colnamesToDEout(fit_mpbSpreadOptimizer, c("p_meanDist", "p_advectionMag", "p_sdDist"))
} else if (length(fit_mpbSpreadOptimizer$optim$bestmem) == 4) {
fit_mpbSpreadOptimizer <- colnamesToDEout(fit_mpbSpreadOptimizer, c("p_meanDist", "p_advectionMag", "p_sdDist", "p_rescaler"))
}
p <- fit_mpbSpreadOptimizer$optim$bestmem # replace with values from disk object
DEoutPop <- as.data.table(fit_mpbSpreadOptimizer$member$pop)
setnames(DEoutPop, new = names(p))
DEoutPop <- melt(DEoutPop, measure = colnames(DEoutPop), variable.name = "Parameter")
# Caching a Plots will mean that only if the input dataset it updated will the plot be redone
Cache(Plots, DEoutPop, plot_HistsOfDEoptimPars, title = "Parameter histograms from DEoptim",
filename = paste0("Histograms of parameters from DEoptim ", Sys.time()),
omitArgs = "filename")
# Way to identify quantiles
if (FALSE) {
ll <- weibullShapeScale(p['p_meanDist'], p['p_sdDist']);
qweibull(0.99, shape = ll$shape, scale = ll$scale)
}
#########################################################
#################### PREDICT MAPS
#########################################################
opts2 <- options(reproducible.cacheSpeed = "fast")
on.exit(options(opts2))
if (NROW(sim$predictedDT) == 0) {
st1 <- system.time(sim$predictedDT <- Cache(predictQuotedSpread,
massAttacksDT = sim$massAttacksDT, # must have column named greenTreesYr_t
windDirStack = sim$windDirStack,
windSpeedStack = sim$windSpeedStack,
propPineRas = sim$propPineRas,
thresholdPineProportion = Par$thresholdPineProportion,
dispersalKernel = P(sim)$dispersalKernel,# "generalgamma",
maxDistance = P(sim)$maxDistance,
# DON'T ADD clNumber here -- it will do it automatically at the "year" level
quotedSpread = P(sim)$quotedSpread, # doesn't cache correctly
.cacheExtra = format(P(sim)$quotedSpread), # cache this instead
p = p,
omitArgs = "quotedSpread"
))
message("Time for prediction: ", format(base::as.difftime(st1[3], units = "secs"), units = "auto"))
}
sim$predictedStack <- Cache(stackFromDT, sim$predictedDT, raster(sim$massAttacksStack))
#bb <- predictedStack$X2011[][propPineRas[] < 0.3]
#cc <- massAttacksStack$X2011[][propPineRas[] < 0.1]
# lapply(seq(nlayers(sim$massAttacksStack)), function(x)
# cor.test(sim$predictedStack[][, x], sim$massAttacksStack[][, x], use = "complete.obs"))
if (length(names(sim$massAttacksStack)) > 1) {
corByYr <- cor(sim$predictedStack[], sim$massAttacksStack[], use = "complete.obs")
message("Avg correlation of time series: ", round(corByYrAvg <- mean(diag(corByYr)), 3))
corLogByYr <- cor(log(sim$predictedStack[] + 1), log(sim$massAttacksStack[] + 1), use = "complete.obs")
message("Avg correlation of log time series: ", round(corLogByYrAvg <- mean(diag(corLogByYr)), 3))
}
# plotStack <- Cache(createStackPredAndObs, sim$massAttacksStack, sim$predictedStack, threshold = 55)
fnHash <- fastdigest(format(stacksPredVObs))
availablePine <- rowSums(sim$massAttacksStack[], na.rm = TRUE)
whAttacked <- which(availablePine > 0)
availablePineMap <- raster(sim$massAttacksStack)
availablePineMap[whAttacked] <- 1
apmBuff <- Cache(raster::buffer, availablePineMap, width = 1e5)
apmBuff[sim$propPineRas[] == 0] <- NA
# cumulative maps
massAttacksStackLog <- cumulativeMap(sim$massAttacksStack, log = TRUE)
# mam <- sim$massAttacksStack
# for (lay in names(sim$massAttacksStack)) {
# mam[[lay]][is.na(mam[[lay]][])] <- 0
# }
# massAttacksStackLog <- if (nlayers(mam) > 1) sum(mam) else mam[[1]]
# massAttacksStackLog[] <- log(massAttacksStackLog[] + 1)
# cumulative maps
predictCumulativeLog <- cumulativeMap(sim$predictedStack, log = TRUE)
# pred <- sim$predictedStack
# for (lay in names(pred)) {
# pred[[lay]][is.na(pred[[lay]][])] <- 0
# }
# predictCumulativeLog <- sum(pred)
# predictCumulativeLog[] <- log(predictCumulativeLog[] + 1)
if (tolower(Par$type) == "validate") {
# Find numAttackTrees minimum threshold that defines detectable
message("Estimating (using ROC) the predicted attack density minimum threshold ",
" to be considered detectable")
system.time(optimAttackTreesMinDetectable <- Cache(optimize, f = estimateMinAttackThresh, interval = c(0.001, 200),
meanAttackStk = sim$massAttacksStack, .cacheExtra = fnHash,
predictedStk = sim$predictedStack, propPineRast = sim$propPineRas,
tol = 0.001
))
sim$thresholdAttackTreesMinDetectable <- optimAttackTreesMinDetectable$minimum
} else {
sim$thresholdAttackTreesMinDetectable <- 1.4 # this is best from DEoptim
}
# ROC curves
stackPredVObs <- Cache(stacksPredVObs, sim$massAttacksStack, sim$predictedStack,
apmBuff, threshold = sim$thresholdAttackTreesMinDetectable,
plot = TRUE)
obsPredDT <- makeAnnualMeansDT(sim$predictedStack, sim$massAttacksStack)
obsPredDT[, `:=`(rescaleLog = exp(mean(log(`Observed Mean`)/log(`Predicted Mean`))),
rescale = mean(`Observed Mean`/`Predicted Mean`))]
obsPredDT[, `Predicted Mean` := `Predicted Mean` * rescale]
set(obsPredDT, NULL, c("rescale", "rescaleLog"), NULL)
corMeans <- cor(log(obsPredDT$`Predicted Mean`), log(obsPredDT$`Observed Mean`))
message("Avg correlation of time series of mean annual values: ", round(corMeans, 3))
Cache(Plots, fn = plot_ObsVPredAbund1, dt = obsPredDT, #types = "screen",
filename = paste0("Annual Means: Obs v Pred ", startToEnd), omitArgs = "filename")
Cache(Plots, fn = plot_ObsVPredAbund2, dt = obsPredDT, #types = "screen",
filename = paste0("Annual Means: Year v Obs and Pred ", startToEnd), omitArgs = "filename")
print(paste("ROC mean value: ", round(mean(stackPredVObs$ROCs$ROC, na.rm = TRUE), 3)))
messageDF(stackPredVObs$ROCs)
sim$ROCList[[iii]] <- stackPredVObs$ROCs
}
}
# current.mode <- tmap_mode("view")
current.mode <- tmap_mode("plot")
clearPlot()
fn1 = file.path(outputPath(sim), "figures", paste0(Par$type, ": stks predicted vs. observed ", startToEnd))
# tmap doesn't work with Plots yet... do manually
#Plots(sim$absk, plot_StudyAreaFn,
#filename = file.path(outputPath(sim), paste0(Par$type, ": stks predicted vs. observed ", startToEnd)),
#ggsaveArgs = list(width = 8, height = 10, units = "in", dpi = 300),
tm_stks_predvObs <- plot_StudyAreaFn(
absk = sim$absk, cols = "darkgreen", sf::st_as_sf(sim$studyArea),
massAttacksStackLog, pred = predictCumulativeLog,
propPineMap = sim$propPineRas,
thresholdAttackTreesMinDetectable = sim$thresholdAttackTreesMinDetectable,
thresholdPineProportion = Par$thresholdPineProportion)
if ("screen" %in% Par$.plots) {
tm_stks_predvObs
}
if (any(Par$.plots %in% ggplotClassesCanHandle)) {
suppressWarnings(
Cache(tmap_save, tm_stks_predvObs, filename = paste0(fn1, ".", Par$.plots),
width = 8, height = 10, units = "in", dpi = 300, omitArgs = "filename")
)
}
# ss <- lapply(raster::unstack(stackPredVObs$stk), function(ras) {
# freqs <- table(ras[])
# sensitivity <- freqs[3]/(sum(freqs[3], freqs[1]))
# specificity <- freqs[4]/(sum(freqs[4], freqs[2]))
# return(list(sensitivity = sensitivity, specificity = specificity))
# })
# Edges
edgesPredicted <- sim$predictedStack
edgesPredicted[edgesPredicted < sim$thresholdAttackTreesMinDetectable] <- NA
edgesPredicted <- raster::stack(edgesPredicted)
edgesList <- raster::unstack(edgesPredicted)
names(edgesList) <- names(edgesPredicted)
quantileForEdge <- 0.9
edgesCoords <- lapply(edgesList, function(edge) {
xys <- xyFromCell(edge, which(!is.na(edge[])))
xEdge <- quantile(xys[, "x"], quantileForEdge)
yEdge <- quantile(xys[, "y"], quantileForEdge)
list(EastEdge = xEdge, NorthEdge = yEdge)
})
edgesPredDT <- rbindlist(edgesCoords, idcol = "layerName")
edgesPredDT[, type := "Prediction"]
edgesData <- sim$massAttacksStack
# edgesData <- raster::stack(edgesData)
edgesDataList <- raster::unstack(edgesData)
names(edgesDataList) <- names(edgesData)
edgesDataCoords <- lapply(edgesDataList, function(edge) {
xys <- xyFromCell(edge, which(!is.na(edge[])))
xEdge <- quantile(xys[, "x"], quantileForEdge)
yEdge <- quantile(xys[, "y"], quantileForEdge)
list(EastEdge = xEdge, NorthEdge = yEdge)
})
edgesDataDT <- rbindlist(edgesDataCoords, idcol = "layerName")
edgesDataDT[, type := "Data"]
setnafill(edgesPredDT, type = "locf", cols = c("EastEdge", "NorthEdge"))
edgesDT <- rbindlist(list(edgesDataDT, edgesPredDT))
edgesDTLong <- melt(edgesDT, measure = patterns("Edge"))
edgesDTLong[, value := c(NA, diff(value))/1e3, by = c("type", "variable")]
edgesDTLong[, xy := gsub("Edge", "", variable)]
Cache(Plots, edgesDTLong, plot_CentroidShift,
title = "Predicted vs. Observed edge displacment each year",
ggsaveArgs = list(width = 8, height = 10, units = "in", dpi = 300),
filename = paste0(Par$type, ": Edge Displacement Pred vs Observed ", startToEnd),
omitArgs = "filename")
# Centroids
centroidPredicted <- centroidChange(sim$predictedStack, sim$propPineRas)
centroidPredicted[, variable := paste0("X", as.numeric(gsub("X", "", variable)) - 1)]
setnames(centroidPredicted, old = c("yAtMax", "xAtMax"), new = c("yPredicted", "xPredicted"))
centroidData <- centroidChange(sim$massAttacksStack, sim$propPineRas)
setnames(centroidData, old = c("yAtMax", "xAtMax"), new = c("yData", "xData"))
centroids <- centroidData[centroidPredicted]
setnames(centroids, "variable", "layerName")
centroidsLong <- melt(centroids, measure = patterns("Data|Pred"))
centroidsLong[, type := gsub("x|y", "", variable)]
centroidsLong[, xy := gsub("^(x|y).+", "\\1", variable)]
centroidsLong[, xy := ifelse(xy == "x", "East", "North")]
centroidsLong[, UTM := value]
centroidsLong[, value := c(NA, diff(value))/1e3, by = c("variable")]
Cache(Plots, centroidsLong, plot_CentroidShift, title = "Predicted vs. Observed centroid displacment each year",
ggsaveArgs = list(width = 8, height = 10, units = "in", dpi = 300),
filename = paste0(Par$type, ": Centroid Displacement Pred vs Observed ",
startToEnd), omitArgs = "filename")
# Displacement Table
centroids[, EastObs := c(NA, diff(xData)/1e3)]
centroids[, NorthObs := c(NA, diff(yData)/1e3)]
centroids[, EastPred := c(NA, diff(xPredicted)/1e3)]
centroids[, NorthPred := c(NA, diff(yPredicted)/1e3)]
centroids <- na.omit(centroids, cols = "EastPred")
corEastDisplacement <- cor(centroids$EastObs, centroids$EastPred, method = "spearman")
corNorthDisplacement <- cor(centroids$NorthObs, centroids$NorthPred, method = "spearman")
sim$correlationsDisplacement <- c(East = corEastDisplacement, North = corNorthDisplacement)
if (end(sim) - start(sim) >= 10) {
centroids[, FiveYrPd := rep(c(paste0(layerName[1],"/",layerName[5]), paste0(layerName[6],"/",layerName[10])), each = 5)]
centroids5Y <- centroids[, lapply(.SD, function(x) sum(x)), by = FiveYrPd,
.SDcols = c("EastObs", "NorthObs", "EastPred", "NorthPred")]
centroids <- rbindlist(list(centroids, centroids5Y), fill = TRUE)
centroids[is.na(layerName), layerName := FiveYrPd]
}
centroids2 <- as.data.table(t(centroids[, list(NorthObs, NorthPred, EastObs, EastPred)]))
setnames(centroids2, centroids$layerName)
centroids2 <- cbind(layerName = c("NorthObs", "NorthPred", "EastObs", "EastPred"), centroids2)
sim$displacementTable <- centroids2 %>%
gt() %>%
tab_spanner(
label = "Annual displacement (km/y)",
columns = grep(value = TRUE, "^X.{4,4}$", colnames(centroids2))
) %>%
tab_spanner(
label = "Net displacement\n(km/5 y)",
columns = grep(value = TRUE, "^X.+/.+", colnames(centroids2))
)
gtsave(sim$displacementTable,
filename = file.path(outputPath(sim), "figures",
paste0(Par$type, ": displacementTable ", startToEnd, ".png")))
return(invisible(sim))
}
##########################
### plotting
plotFn <- function(sim) {
pBest <- sim$fit_mpbSpreadOptimizer$optim$bestmem
plotKernels(pBest)
## Histograms showing that there is no relationship between where beetle is and
# how much pine there is
par(mfrow = c(3,4));
for(i in 1:10/10) {
cc <- sim$massAttacksStack$X2011[][sim$propPineRas[] < i & sim$propPineRas[] > (i - 0.1)];
hist(log(cc), xlim = c(-1, 10), breaks = 15,
main = paste0("Prop pine: ", i - 0.1, " to ", i), xlab = "log number attacked trees")
}
return(invisible(sim))
}
### spread
dispersalFit <- function(quotedSpread, propPineRas, studyArea, massAttacksDT, massAttacksStack,
rasterToMatch, maxDistance, # massAttacksRas,
params, #currentTime, bgSettlingProp,
type, reqdPkgs,
windDirStack, windSpeedStack, outputPath, dispersalKernel) {
# Make sure propPineRas is indeed a proportion
mv <- maxFn(propPineRas)
if (mv > 1)
propPineRas[] <- propPineRas[] / 100 ## much faster than calc; ## TODO: allow different params per species
# Set NAs on propPineRas to 0
nas <- is.na(propPineRas[])
propPineRas[nas] <- 0
# Put objects in Global for objFun -- this is only when not using multi-machine cluster
omitPastPines <- FALSE # was TRUE ... but maybe bad because there are many that have multiple years
kern <- substr(tolower(dispersalKernel), start = 1, stop = 6)
ll <- list()
pars <- switch(kern,
weibul = {
ll$p <- do.call(c, params[c("p_meanDist", "p_advectionMag", "p_sdDist")])
ll$lower <- c(5000, 0.01, 0.01)
ll$upper <- c(105000, 2000, 3.5)
ll
},
genera = {
ll$p <- do.call(c, params[c("p_meanDist", "p_advectionMag", "p_sdDist", "p_nu")])#, "p_advectionDir")])
ll$lower <- c(5000, 0.01, 0.3, 0.5)
ll$upper <- c(105000, 2000, 1, 1)
ll
},
expone = {
ll$p <- do.call(c, params[c("p_meanDist", "p_advectionMag")])
ll$lower <- c(5000, 0.1)
ll$upper <- c(105000, 2000)
ll
},
twodt = {
ll$p <- do.call(c, params[c("p_meanDist", "p_advectionMag", "p_sdDist")])
ll$lower <- c(5000, 0.1, 0.01)
ll$upper <- c(105000, 2000, 0.5)
ll
},
)
p <- pars$p
lower <- pars$lower
upper <- pars$upper
p_sdDist <- p["p_sdDist"] # sqrt(variance(of the Weibull distribution)) --> contributes to shape and scale parameters
p_advectionMag <- p["p_advectionMag"]
p[] <- sapply(seq_along(p), function(x) runif(1, lower[x], upper[x]))
names(lower) <- names(p)
names(upper) <- names(p)
libPaths <- .libPaths()
# Identify the objsToExport -- needs to be ALL the formalArgs of the objFun
# however, don't pass ones that are passed manually at the DEoptim call
# Generally, only pass "very small" objects in the DEoptim call. Large ones do this way (i.e.,
# export them first.
objsToExport <- setdiff(formalArgs("objFun"),
# The following are small and passed at the time of the DEoptim call
c("p", "quotedSpread", "distanceFunction"))
# need both the objsToExport vector, and the object called "objsToExport"
objsToExport <- c(objsToExport, "reqdPkgs", "objsToExport", "libPaths")
# put objsToExport into .GlobalEnv -- the DEoptim function gets all arguments from .GlobalEnv
list2env(mget(objsToExport), envir = .GlobalEnv)
# 213 appears slower than rest
ipsNum <- c(189, 184, 217, 97, 106, 220, 213)
ips <- paste0("10.20.0.", ipsNum)
ips <- rep(ips, c(33, 16, 13, 23, 20, 5, 0))
ips <- rep("localhost", 10)
adjustments = 1#c(0.8, 1, 1, 1, 1, 1, 1)
numCoresNeeded <- 110 # This is one per true core on 4 machines, 56, 56, 28, 28 cores each
reqdPkgs <- grep(paste(collapse = "|", c("SpaDES.tools", "raster", "CircStats", "data.table",
"purrr", "mpbutils", "gamlss")),
reqdPkgs, value = TRUE)
stPre <- Sys.time()
stFileName <- gsub(":", "-", format(stPre))
customControls <- list(strategy = 2,
itermax = 60,
NP = numCoresNeeded)
# This series of functions including the first "if" block below is to try to determine if
# the DEoptim needs rerunning. If it doesn't, then don't bother setting up cluster.
cacheID <- "34814d19554e3e4b" # This is manual override the DEoptim cache. Set to NULL if need to rerun.
objsForDEoptim <- list(DEoptim, fn = objFun,
lower = lower,#c(500, 1, -90, 0.9, 1.1, 5),
upper = upper,#c(30000, 10, 240, 1.8, 1.6, 30),
# reps = 1,
quotedSpread = quotedSpread,
control = do.call(DEoptim.control, customControls))
dig <- Cache(CacheDigest, objsForDEoptim) # See if this has already been cached before
if (!(isFALSE(attr(dig, ".Cache")$newCache && is.null(cacheID))) &&
isTRUE(type %in% c("DEoptim", "fit")) ) {
cl <- LandR::clusterSetup(workers = ips, objsToExport = objsToExport,
reqdPkgs = reqdPkgs, libPaths = libPaths, doSpeedTest = 0, # fn = fn,
quotedExtra = quote(install.packages(c("rgdal", "rgeos", "sf",
"sp", "raster", "terra", "lwgeom"),
repos = "https://cran.rstudio.com")),
numCoresNeeded = numCoresNeeded, adjustments = adjustments)
on.exit(try(stopCluster(cl), silent = TRUE), add = TRUE)
customControls$cl <- cl
message("Starting DEoptim")
}
if (any(type %in% c("DEoptim", "fit", "predict"))) {
# This is customized to work on both Linux and Windows
fit_mpbSpreadOptimizer <- Cache(DEoptim, fn = objsForDEoptim$fn,
lower = objsForDEoptim$lower,#c(500, 1, -90, 0.9, 1.1, 5),
upper = objsForDEoptim$upper,#c(30000, 10, 240, 1.8, 1.6, 30),
# reps = 1,
quotedSpread = objsForDEoptim$quotedSpread,
control = objsForDEoptim$control,