-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathBiomass_core.R
2186 lines (1943 loc) · 120 KB
/
Biomass_core.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
# Everything in this file gets sourced during simInit, and all functions and objects
# are put into the simList. To use objects and functions, use sim$xxx.
defineModule(sim, list(
name = "Biomass_core",
description = "A fast and large landscape biomass succession model modified from LANDIS-II Biomass Succession extension, v3.2.1",
keywords = c("forest succession", "LANDIS II", "Biomass"),
authors = c(
person("Yong", "Luo", email = "[email protected]", role = "aut"),
person(c("Eliot", "J", "B"), "McIntire", email = "[email protected]", role = c("aut", "cre")),
person("Ceres", "Barros", email = "[email protected]", role = "aut"),
person(c("Alex", "M."), "Chubaty", email = "[email protected]", role = "aut"),
person("Ian", "Eddy", email = "[email protected]", role = c("ctb")),
person("Jean", "Marchal", email = "[email protected]", role = "ctb")
),
childModules = character(0),
version = list(Biomass_core = numeric_version("1.4.3")),
timeframe = as.POSIXlt(c(NA, NA)),
timeunit = "year",
citation = list("citation.bib"),
documentation = list("README.txt", "Biomass_core.Rmd"),
loadOrder = list(after = c("Biomass_speciesParameters")),
reqdPkgs = list("assertthat", "compiler", "crayon", "data.table",
"dplyr", "fpCompare", "ggplot2", "grid",
"parallel", "purrr", "quickPlot (>= 1.0.2.9003)", "Rcpp",
"R.utils", "scales", "terra", "tidyr",
"reproducible (>= 2.1.0)",
"SpaDES.core (>= 2.1.4)", "SpaDES.tools (>= 1.0.0.9001)",
"ianmseddy/LandR.CS@master (>= 0.0.2.0002)",
"PredictiveEcology/pemisc@development",
"PredictiveEcology/LandR@development (>= 1.1.5.9012)"),
parameters = rbind(
defineParameter("calcSummaryBGM", "character", "end", NA, NA,
desc = paste("A character vector describing when to calculate the summary of biomass, growth and mortality",
"Currently any combination of 5 options is possible:",
"'start'- as before vegetation succession events, i.e. before dispersal,",
"'postDisp' - after dispersal, 'postRegen' - after post-disturbance regeneration (currently the same as 'start'),",
"'postGM' - after growth and mortality, 'postAging' - after aging,",
"'end' - at the end of vegetation succesion events, before plotting and saving.",
"The 'end' option is always active, being also the default option.",
"If NULL, then will skip all `summaryBGM` related events")),
defineParameter("calibrate", "logical", FALSE,
desc = "Do calibration? Defaults to `FALSE`"),
defineParameter("cohortDefinitionCols", "character", LandR::cohortDefinitionCols(), NA, NA,
desc = paste("`cohortData` columns that determine what constitutes a cohort",
"This parameter should only be modified if additional modules are adding columns to cohortData")),
defineParameter("cutpoint", "numeric", 1e10, NA, NA,
desc = "A numeric scalar indicating how large each chunk of an internal data.table is, when processing by chunks"),
defineParameter("initialB", "numeric", 10, 1, NA,
desc = paste("Initial biomass values of new age-1 cohorts.",
"If `NA` or `NULL`, initial biomass will be calculated as in LANDIS-II Biomass Suc. Extension",
"(see Scheller and Miranda, 2015 or `?LandR::.initiateNewCohorts`)")),
defineParameter("gmcsGrowthLimits", "numeric", c(1/1.5 * 100, 1.5/1 * 100), NA, NA,
paste("If using `LandR.CS` for climate-sensitive growth and mortality, a percentile",
" is used to estimate the effect of climate on growth/mortality ",
"(currentClimate/referenceClimate). Upper and lower limits are ",
"suggested to circumvent problems caused by very small denominators as well as ",
"predictions outside the data range used to generate the model")),
defineParameter("gmcsMortLimits", "numeric", c(1/1.5 * 100, 1.5/1 * 100), NA, NA,
paste("If using `LandR.CS` for climate-sensitive growth and mortality, a percentile",
" is used to estimate the effect of climate on growth/mortality ",
"(currentClimate/referenceClimate). Upper and lower limits are ",
"suggested to circumvent problems caused by very small denominators as well as ",
"predictions outside the data range used to generate the model")),
defineParameter("gmcsMinAge", "numeric", 21, 0, NA,
paste("If using `LandR.CS` for climate-sensitive growth and mortality, the minimum",
"age for which to predict climate-sensitive growth and mortality.",
"Young stands (< 30) are poorly represented by the PSP data used to parameterize the model.")),
defineParameter("growthAndMortalityDrivers", "character", "LandR", NA, NA,
desc = paste("Package name where the following functions can be found:",
"`calculateClimateEffect`, `assignClimateEffect`",
"(see `LandR.CS` for climate sensitivity equivalent functions, or leave default if this is not desired)")),
defineParameter("growthInitialTime", "numeric", start(sim), NA_real_, NA_real_,
desc = "Initial time for the growth event to occur"),
defineParameter("initialBiomassSource", "character", "cohortData", NA, NA,
paste("Currently, there are three options: 'spinUp', 'cohortData', 'biomassMap'. ",
"If 'spinUp', it will derive biomass by running spinup derived from Landis-II.",
"If 'cohortData', it will be taken from the `cohortData` object, i.e., it is already correct, by cohort.",
"If 'biomassMap', it will be taken from `sim$biomassMap`,",
"divided across species using `sim$speciesLayers` percent cover values",
"'spinUp' uses `sim$standAgeMap` as the driver, so biomass",
"is an **output**. That means it will be unlikely to match any input information",
"about biomass, unless this is set to 'biomassMap', and a `sim$biomassMap` is supplied.",
"**Only the 'cohortData' option is currently active.**")),
defineParameter("keepClimateCols", "logical", FALSE, NA, NA, "include growth and mortality predictions in `cohortData`?"),
defineParameter("minCohortBiomass", "numeric", 0, NA, NA,
desc = "Cohorts with biomass below this threshold (in $g/m^2$) are removed. Not a LANDIS-II BSE parameter."),
defineParameter("mixedType", "numeric", 2, 0, 2,
desc = paste("How to define mixed stands: 0 for none; 1 for any species admixture;",
"2 for deciduous > conifer. See `?LandR::vegTypeMapGenerator`.")),
defineParameter("plotOverstory", "logical", FALSE, NA, NA, desc = "swap max age plot with overstory biomass"),
defineParameter("seedingAlgorithm", "character", "wardDispersal", NA_character_, NA_character_,
desc = paste("Choose which seeding algorithm will be used among",
"'noSeeding' (no horizontal, nor vertical seeding - not in LANDIS-II BSE), 'noDispersal'",
"(no horizontal seeding), 'universalDispersal' (seeds disperse to any pixel), and",
"'wardDispersal' (default; seeds disperse according to distance and dispersal traits).",
"See Scheller & Miranda (2015) - Biomass Succession extension, v3.2.1 User Guide")),
defineParameter("spinupMortalityfraction", "numeric", 0.001,
desc = paste("Defines the mortality loss fraction in spin up-stage simulation.",
"Only used if `P(sim)$initialBiomassSource == 'biomassMap'`, which is currently deactivated.")),
defineParameter("sppEquivCol", "character", "Boreal", NA, NA,
"The column in `sim$sppEquiv` data.table to use as a naming convention"),
defineParameter("successionTimestep", "numeric", 10, NA, NA,
paste("Defines the simulation time step, default is 10 years.",
"Note that growth and mortality always happen on a yearly basis.",
"Cohorts younger than this age will not be included in competitive interactions")),
defineParameter("vegLeadingProportion", "numeric", 0.8, 0, 1,
desc = "A number that defines whether a species is leading for a given pixel"),
defineParameter(".maxMemory", "numeric", 5, NA, NA,
desc = "Maximum amount of memory (in GB) to use for dispersal calculations."),
defineParameter(".plotInitialTime", "numeric", start(sim), NA, NA,
desc = paste("Vector of length = 1, describing the simulation time at which the first plot event should occur.",
"To plotting off completely use `P(sim)$.plots`.")),
defineParameter(".plotInterval", "numeric", NA, NA, NA,
desc = paste("Defines the plotting time step.",
"If `NA`, the default, `.plotInterval` is set to `successionTimestep`.")),
defineParameter(".plots", "character", default = "object",
desc = paste("Passed to `types` in `Plots` (see `?Plots`). There are a few plots that are made within this module, if set.",
"Note that plots (or their data) saving will ONLY occur at `end(sim)`.",
"If `NA`, plotting is turned off completely (this includes plot saving).")),
defineParameter(".plotMaps", "logical", TRUE, NA, NA,
desc = "Controls whether maps should be plotted or not. Set to `FALSE` if `P(sim)$.plots == NA`"),
defineParameter(".saveInitialTime", "numeric", NA, NA, NA,
desc = paste("Vector of length = 1, describing the simulation time at which the first save event should occur.",
"Set to `NA` if no saving is desired. If not `NA`, then saving will occur at",
"`P(sim)$.saveInitialTime` with a frequency equal to `P(sim)$.saveInterval`")),
defineParameter(".saveInterval", "numeric", NA, NA, NA,
desc = paste("Defines the saving time step.",
"If `NA`, the default, .saveInterval is set to `P(sim)$successionTimestep`.")),
defineParameter(".sslVerify", "integer", as.integer(unname(curl::curl_options("^ssl_verifypeer$"))), NA_integer_, NA_integer_,
paste("Passed to `httr::config(ssl_verifypeer = P(sim)$.sslVerify)` when downloading KNN",
"(NFI) datasets. Set to 0L if necessary to bypass checking the SSL certificate (this",
"may be necessary when NFI's website SSL certificate is not correctly configured).")),
defineParameter(".studyAreaName", "character", NA, NA, NA,
"Human-readable name for the study area used. If `NA`, a hash of `studyArea` will be used."),
defineParameter(".useCache", "character", c(".inputObjects", "init"), NA, NA,
desc = "Internal. Can be names of events or the whole module name; these will be cached by `SpaDES`"),
defineParameter(".useParallel", "ANY", 2, NA, NA,
desc = paste("Used only in seed dispersal.",
"If numeric, it will be passed to `data.table::setDTthreads` and should be <= 2;",
"If `TRUE`, it will be passed to `parallel::makeCluster`;",
"and if a cluster object, it will be passed to `parallel::parClusterApplyB`."))
),
inputObjects = bindrows(
expectsInput("biomassMap", "SpatRaster",
desc = paste("Total biomass raster layer in study area (in $g/m^2$),",
"filtered for pixels covered by `cohortData.`",
"Only used if `P(sim)$initialBiomassSource == 'biomassMap'`, which is currently deactivated."),
sourceURL = ""),
expectsInput("cceArgs", "list",
desc = paste("A list of quoted objects used by the `growthAndMortalityDriver` `calculateClimateEffect` function")),
expectsInput("cohortData", "data.table",
desc = paste("`data.table` with cohort-level information on age and biomass, by `pixelGroup` and ecolocation",
"(i.e., `ecoregionGroup`). If supplied, it must have the following columns: `pixelGroup` (integer),",
"`ecoregionGroup` (factor), `speciesCode` (factor), `B` (integer in $g/m^2$), `age` (integer in years)")),
expectsInput("ecoregion", "data.table",
desc = "Ecoregion look up table",
sourceURL = paste0("https://raw.githubusercontent.com/LANDIS-II-Foundation/",
"Extensions-Succession/master/biomass-succession-archive/",
"trunk/tests/v6.0-2.0/ecoregions.txt")),
expectsInput("ecoregionMap", "SpatRaster",
desc = paste("Ecoregion map that has mapcodes match ecoregion table and `speciesEcoregion` table.",
"Defaults to a dummy map matching `rasterToMatch` with two regions")),
# expectsInput("initialCommunities", "data.table",
# desc = "initial community table",
# sourceURL = "https://raw.githubusercontent.com/LANDIS-II-Foundation/Extensions-Succession/master/biomass-succession-archive/trunk/tests/v6.0-2.0/initial-communities.txt"),
# expectsInput("initialCommunitiesMap", "SpatRaster",
# desc = "initial community map that has mapcodes match initial community table",
# sourceURL = "https://github.com/LANDIS-II-Foundation/Extensions-Succession/raw/master/biomass-succession-archive/trunk/tests/v6.0-2.0/initial-communities.gis"),
expectsInput("lastReg", "numeric",
desc = "An internal counter keeping track of when the last regeneration event occurred"),
expectsInput("minRelativeB", "data.frame",
desc = "table defining the relative biomass cut points to classify stand shadeness."),
expectsInput("pixelGroupMap", "SpatRaster",
desc = paste("A raster layer with `pixelGroup` IDs per pixel. Pixels are grouped" ,
"based on identical `ecoregionGroup`, `speciesCode`, `age` and `B` composition,",
"even if the user supplies other initial groupings (e.g., via the `Biomass_borealDataPrep`",
"module.")),
expectsInput("rasterToMatch", "SpatRaster",
desc = "A raster of the `studyArea` in the same resolution and projection as `biomassMap`"),
expectsInput("species", "data.table",
desc = paste("A table of invariant species traits with the following trait colums:",
"'species', 'Area', 'longevity', 'sexualmature', 'shadetolerance',",
"'firetolerance', 'seeddistance_eff', 'seeddistance_max', 'resproutprob',",
"'mortalityshape', 'growthcurve', 'resproutage_min', 'resproutage_max',",
"'postfireregen', 'wooddecayrate', 'leaflongevity' 'leafLignin',",
"'hardsoft'. The last seven traits are not used in *Biomass_core*,",
"and may be ommited. However, this may result in downstream issues with",
"other modules. Default is from Dominic Cyr and Yan Boulanger's project"),
sourceURL = "https://raw.githubusercontent.com/dcyr/LANDIS-II_IA_generalUseFiles/master/speciesTraits.csv"),
expectsInput("speciesEcoregion", "data.table",
desc = paste("Table of spatially-varying species traits (`maxB`, `maxANPP`,",
"`establishprob`), defined by species and `ecoregionGroup` (i.e. ecolocation).",
"Defaults to a dummy table based on dummy data of biomass, age, ecoregion and land cover class")),
expectsInput("speciesLayers", "SpatRaster",
desc = paste("Percent cover raster layers of tree species in Canada.",
"Defaults to the Canadian Forestry Service, National Forest Inventory,",
"kNN-derived species cover maps from 2001 using a cover threshold of 10 -",
"see https://open.canada.ca/data/en/dataset/ec9e2659-1c29-4ddb-87a2-6aced147a990 for metadata"),
sourceURL = paste0("http://ftp.maps.canada.ca/pub/nrcan_rncan/Forests_Foret/",
"canada-forests-attributes_attributs-forests-canada/2001-attributes_attributs-2001/")),
expectsInput("sppColorVect", "character",
desc = paste("A named vector of colors to use for plotting.",
"The names must be in `sim$sppEquiv[[sim$sppEquivCol]]`,",
"and should also contain a color for 'Mixed'.")),
expectsInput("sppEquiv", "data.table",
desc = "Table of species equivalencies. See `LandR::sppEquivalencies_CA`."),
expectsInput("sppNameVector", "character",
desc = paste("An optional vector of species names to be pulled from `sppEquiv`. Species names must match",
"`P(sim)$sppEquivCol` column in `sppEquiv`. If not provided, then species will be taken from",
"the entire `P(sim)$sppEquivCol` column in `sppEquiv`.",
"See `LandR::sppEquivalencies_CA`.")),
expectsInput("studyArea", "sfc",
desc = paste("Polygon to use as the study area. Must be supplied by the user. Can also be a SpatVector.")),
expectsInput("studyAreaReporting", "sfc",
desc = paste("multipolygon (typically smaller/unbuffered than studyArea) to use for plotting/reporting.",
"Defaults to `studyArea`.")),
expectsInput("sufficientLight", "data.frame",
desc = paste("Table defining how the species with different shade tolerance respond to stand shade.",
"Default is based on LANDIS-II Biomass Succession v6.2 parameters"),
sourceURL = paste0("https://raw.githubusercontent.com/LANDIS-II-Foundation/",
"Extensions-Succession/master/biomass-succession-archive/",
"trunk/tests/v6.0-2.0/biomass-succession_test.txt")),
expectsInput("treedFirePixelTableSinceLastDisp", "data.table",
desc = paste("3 columns: `pixelIndex`, `pixelGroup`, and `burnTime`.",
"Each row represents a forested pixel that was burned up to and including this year,",
"since last dispersal event, with its corresponding `pixelGroup` and time it occurred"))
# expectsInput("spinUpCache", "logical", ""),
# expectsInput("speciesEstablishmentProbMap", "RasterBrick", "Species establishment probability as a RasterBrick, one layer for each species")
),
outputObjects = bindrows(
createsOutput("activePixelIndex", "integer",
desc = "Internal use. Keeps track of which pixels are active."),
createsOutput("activePixelIndexReporting", "integer",
desc = "Internal use. Keeps track of which pixels are active in the reporting study area."),
createsOutput("ANPPMap", "SpatRaster",
desc = "ANPP map at each succession time step (in g /m^2)"),
createsOutput("biomassMap", "SpatRaster",
desc = paste("Total biomass raster layer in study area (in $g/m^2$),",
"filtered for pixels covered by `cohortData`.",
"Only used if `P(sim)$initialBiomassSource == 'biomassMap'`, which is currently deactivated.")),
createsOutput("cohortData", "data.table",
desc = paste("`data.table` with cohort-level information on age, biomass, aboveground primary",
"productivity (year's biomass gain) and mortality (year's biomass loss), by `pixelGroup`",
"and ecolocation (i.e., `ecoregionGroup`). Contains at least the following columns:",
"`pixelGroup` (integer), `ecoregionGroup` (factor), `speciesCode` (factor), `B` (integer in $g/m^2$),",
"`age` (integer in years), `mortality` (integer in $g/m^2$), `aNPPAct` (integer in $g/m^2$).",
"May have other columns depending on additional simulated processes (i.e., climate sensitivity;",
"see, e.g., `P(sim)$keepClimateCols`).")),
createsOutput("ecoregion", "data.table",
desc = "Ecoregion look up table"),
createsOutput("ecoregionMap", "SpatRaster",
desc = paste("Map with mapcodes match `ecoregion` table and `speciesEcoregion` table.",
"Defaults to a dummy map matching rasterToMatch with two regions.")),
createsOutput("inactivePixelIndex", "logical",
desc = "Internal use. Keeps track of which pixels are inactive."),
createsOutput("inactivePixelIndexReporting", "integer",
desc = "Internal use. Keeps track of which pixels are inactive in the reporting study area."),
# createsOutput("initialCommunities", "character",
# desc = "Because the initialCommunities object can be LARGE, it is saved to disk with this filename"),
createsOutput("lastFireYear", "numeric",
desc = "Year of the most recent fire."),
createsOutput("lastReg", "numeric",
desc = "An internal counter keeping track of when the last regeneration event occurred."),
createsOutput("minRelativeB", "data.frame",
desc = "Define the *relative biomass* cut points to classify stand shade."),
createsOutput("mortalityMap", "SpatRaster",
desc = "Map of biomass lost (in $g/m^2$) at each succession time step."),
createsOutput("pixelGroupMap", "SpatRaster",
desc = "Updated community map at each succession time step."),
createsOutput("regenerationOutput", "data.table",
desc = paste("If `P(sim)$calibrate == TRUE`, an summary of seed dispersal and germination",
"success (i.e., number of pixels where seeds successfully germinated) per species and year.")),
createsOutput("reproductionMap", "SpatRaster",
desc = "Regeneration map (biomass gains in $g/m^2$) at each succession time step"),
createsOutput("simulatedBiomassMap", "SpatRaster",
desc = "Biomass map at each succession time step (in $g/m^2$)"),
createsOutput("simulationOutput", "data.table",
desc = "Contains simulation results by `ecoregionGroup` (main output)"),
createsOutput("simulationTreeOutput", "data.table",
desc = "Summary of several characteristics about the stands, derived from `cohortData`"),
createsOutput("species", "data.table",
desc = paste("a table that has species traits such as longevity, shade tolerance, etc.",
"Currently obtained from LANDIS-II Biomass Succession v.6.0-2.0 inputs")),
createsOutput("speciesEcoregion", "data.table",
desc = "Define the `maxANPP`, `maxB` and `SEP` change with both ecoregion and simulation time."),
createsOutput("speciesLayers", "SpatRaster",
desc = paste("Species percent cover raster layers, based on input `speciesLayers` object.",
"Not changed by this module.")),
# createsOutput("spinUpCache", "logical", desc = ""),
createsOutput("spinupOutput", "data.table",
desc = "Spin-up output. Currently deactivated."),
createsOutput("sppColorVect", "character",
desc = paste("A named vector of colors to use for plotting.",
"The names must be in `sim$sppEquiv[[sim$sppEquivCol]]`,",
"and should also contain a color for 'Mixed'.")),
createsOutput("summaryBySpecies", "data.table",
desc = paste("The total species biomass (in $g/m^2$ as in `cohortData`), average age and aNPP (in",
"$g/m^2$ as in `cohortData`), across the landscape (used for plotting and reporting).")),
createsOutput("summaryBySpecies1", "data.table",
desc = "Number of pixels of each leading vegetation type (used for plotting and reporting)."),
createsOutput("summaryLandscape", "data.table",
desc = paste("The averages of total biomass (in *tonnes/ha*, not $g/m^2$ like in `cohortData`), age",
"and aNPP (also in tonnes/ha) across the landscape (used for plotting and reporting).")),
createsOutput("treedFirePixelTableSinceLastDisp", "data.table",
desc = paste("3 columns: `pixelIndex`, `pixelGroup`, and `burnTime`.",
"Each row represents a forested pixel that was burned up to and including this year,",
"since last dispersal event, with its corresponding `pixelGroup` and time it occurred")),
createsOutput("vegTypeMap", "SpatRaster",
desc = paste("Map of leading species in each pixel, colored according to `sim$sppColorVect`.",
"Species mixtures calculated according to `P(sim)$vegLeadingProportion` and `P(sim)$mixedType`."))
)
))
doEvent.Biomass_core <- function(sim, eventTime, eventType, debug = FALSE) {
if (is.numeric(P(sim)$.useParallel)) {
a <- data.table::setDTthreads(P(sim)$.useParallel)
if (getOption("LandR.verbose", TRUE) > 0) {
if (data.table::getDTthreads() > 1L) message("Biomass_core should be using >100% CPU")
}
on.exit(data.table::setDTthreads(a), add = TRUE)
}
## Set event priorities
dispEvtPriority <- 5
GMEvtPriority <- 6
agingEvtPriotity <- 7
summRegenPriority <- 8
## summary of BGM can occur several times, b4/after other events
summBGMPriority <- list(start = dispEvtPriority - 1,
postDisp = dispEvtPriority + 0.25,
postRegen = 4,
postGM = GMEvtPriority + 0.25,
postAging = agingEvtPriotity + 0.25,
end = summRegenPriority + 0.25)
## add "end" to parameter vector if necessary
if (!is.null(P(sim)$calcSummaryBGM))
if (!any(P(sim)$calcSummaryBGM == "end"))
params(sim)$Biomass_core$calcSummaryBGM <- c(P(sim)$calcSummaryBGM, "end")
summBGMPriority <- summBGMPriority[P(sim)$calcSummaryBGM] ## filter necessary priorities
plotPriority <- 9
savePriority <- 10
switch(eventType,
init = {
## do stuff for this event
## Define .plotInterval/.saveInterval if need be
if (is.na(P(sim)$.plotInterval))
params(sim)$Biomass_core$.plotInterval <- P(sim)$successionTimestep
if (is.na(P(sim)$.saveInterval))
params(sim)$Biomass_core$.saveInterval <- P(sim)$successionTimestep
## make sure plotting window is big enough
if (anyPlotting(P(sim)$.plots) &&
any(P(sim)$.plots == "screen")) {
## if current plot dev is too small, open a new one
if (is.null(dev.list())) {
dev(x = dev.cur() + 1, height = 7, width = 14)
clearPlot()
} else {
if (dev.size()[2] < 14) {
dev(x = dev.cur() + 1, height = 7, width = 14)
clearPlot()
}
}
## current window will be used for summary stats
## a new one for maps
mod$statsWindow <- dev.cur()
if (P(sim)$.plotMaps) {
mod$mapWindow <- mod$statsWindow + 1
dev(x = mod$mapWindow, height = 8, width = 10)
}
} else {
## if plotting is deactivated make sure maps are NOT plotted
params(sim)[[currentModule(sim)]]$.plotMaps <- FALSE
}
## if not end(sim) don't save plots and only plot to screen.
## plotMaps is the exception, as it never is saved.
if (time(sim) != end(sim)) {
if (any(is.na(P(sim)$.plots))) {
mod$plotTypes <- NA
} else if (any(P(sim)$.plots == "screen")) {
mod$plotTypes <- "screen"
} else {
mod$plotTypes <- NA
}
}
## P(sim)$.plotInitialTime == NA is no longer used to turn plotting off
## override if necessary
if (is.na(P(sim)$.plotInitialTime)) {
params(sim)[[currentModule(sim)]]$.plotInitialTime <- start(sim)
message("Using .plotInitialTime == NA no longer turns off plotting. Please use .plots == NA instead.")
}
## Run Init event
sim <- Init(sim)
## schedule events
if (!is.null(summBGMPriority$start))
sim <- scheduleEvent(sim, start(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryBGMstart", eventPriority = summBGMPriority$start)
sim <- scheduleEvent(sim, start(sim) + P(sim)$successionTimestep,
"Biomass_core", "Dispersal", eventPriority = dispEvtPriority)
sim <- scheduleEvent(sim, P(sim)$growthInitialTime,
"Biomass_core", "mortalityAndGrowth", GMEvtPriority)
if (!is.null(summBGMPriority$postDisp))
sim <- scheduleEvent(sim, start(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryBGMpostDisp", eventPriority = summBGMPriority$postDisp)
if (!is.null(summBGMPriority$postRegen))
sim <- scheduleEvent(sim, start(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryBGMpostRegen", eventPriority = summBGMPriority$postRegen)
if (!is.null(summBGMPriority$postGM))
sim <- scheduleEvent(sim, start(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryBGMpostGM", eventPriority = summBGMPriority$postGM)
if (P(sim)$successionTimestep != 1) {
sim <- scheduleEvent(sim, start(sim) + P(sim)$successionTimestep, "Biomass_core",
"cohortAgeReclassification", eventPriority = agingEvtPriotity)
if (!is.null(summBGMPriority$postAging))
sim <- scheduleEvent(sim, start(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryBGMpostAging", eventPriority = summBGMPriority$postAging)
}
## note that summaryBGM and summaryBySpecies, will occur during init too
if (!is.null(P(sim)$calcSummaryBGM)) {
sim <- scheduleEvent(sim, start(sim),
"Biomass_core", "summaryBGM", eventPriority = summBGMPriority$end)
sim <- scheduleEvent(sim, start(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryRegen", eventPriority = summRegenPriority)
sim <- scheduleEvent(sim, start(sim),
"Biomass_core", "plotSummaryBySpecies", eventPriority = plotPriority) ## only occurs before summaryRegen in init.
sim <- scheduleEvent(sim, end(sim),
"Biomass_core", "plotSummaryBySpecies", eventPriority = plotPriority) ## schedule the last plotting events (so that it doesn't depend on plot interval)
}
if (anyPlotting(P(sim)$.plots)) {
if (P(sim)$.plotMaps) {
sim <- scheduleEvent(sim, P(sim)$.plotInitialTime,
"Biomass_core", "plotMaps", eventPriority = plotPriority + 0.25)
}
sim <- scheduleEvent(sim, start(sim),
"Biomass_core", "plotAvgs", eventPriority = plotPriority + 0.5)
sim <- scheduleEvent(sim, end(sim),
"Biomass_core", "plotAvgs", eventPriority = plotPriority + 0.5)
}
if (!is.na(P(sim)$.saveInitialTime)) {
if (P(sim)$.saveInitialTime < start(sim) + P(sim)$successionTimestep) {
message(crayon::blue(
paste(".saveInitialTime should be >=", start(sim) + P(sim)$successionTimestep,
". First save changed to", start(sim) + P(sim)$successionTimestep)))
params(sim)$Biomass_core$.saveInitialTime <- start(sim) + P(sim)$successionTimestep
}
sim <- scheduleEvent(sim, P(sim)$.saveInitialTime,
"Biomass_core", "save", eventPriority = savePriority)
}
},
summaryBGMstart = {
sim <- SummaryBGM(sim)
sim <- scheduleEvent(sim, time(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryBGMstart", eventPriority = summBGMPriority$start)
},
Dispersal = {
sim <- Dispersal(sim)
sim <- scheduleEvent(sim, time(sim) + P(sim)$successionTimestep,
"Biomass_core", "Dispersal", eventPriority = dispEvtPriority)
},
mortalityAndGrowth = {
sim <- MortalityAndGrowth(sim)
sim <- scheduleEvent(sim, time(sim) + 1,
"Biomass_core", "mortalityAndGrowth", eventPriority = GMEvtPriority)
},
summaryBGMpostDisp = {
sim <- SummaryBGM(sim)
sim <- scheduleEvent(sim, time(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryBGMpostDisp", eventPriority = summBGMPriority$postDisp)
},
summaryBGMpostRegen = {
sim <- SummaryBGM(sim)
sim <- scheduleEvent(sim, time(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryBGMpostRegen", eventPriority = summBGMPriority$postRegen)
},
summaryBGMpostGM = {
sim <- SummaryBGM(sim)
sim <- scheduleEvent(sim, time(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryBGMpostGM", eventPriority = summBGMPriority$postGM)
},
cohortAgeReclassification = {
sim <- CohortAgeReclassification(sim)
if (P(sim)$successionTimestep != 1) {
sim <- scheduleEvent(sim, time(sim) + P(sim)$successionTimestep,
"Biomass_core", "cohortAgeReclassification",
eventPriority = agingEvtPriotity)
}
},
summaryBGMpostAging = {
sim <- SummaryBGM(sim)
sim <- scheduleEvent(sim, time(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryBGMpostAging", eventPriority = summBGMPriority$postAging)
},
summaryRegen = {
sim <- summaryRegen(sim)
sim <- scheduleEvent(sim, time(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryRegen", eventPriority = summRegenPriority)
},
summaryBGM = {
sim <- SummaryBGM(sim)
sim <- scheduleEvent(sim, time(sim) + P(sim)$successionTimestep,
"Biomass_core", "summaryBGM", eventPriority = summBGMPriority$end)
},
plotSummaryBySpecies = {
if (time(sim) == end(sim)) {
mod$plotTypes <- P(sim)$.plots
}
sim <- plotSummaryBySpecies(sim)
if (!is.na(P(sim)$.plotInterval)) {
if (!(time(sim) + P(sim)$.plotInterval) == end(sim))
sim <- scheduleEvent(sim, time(sim) + P(sim)$.plotInterval,
"Biomass_core", "plotSummaryBySpecies", eventPriority = plotPriority)
}
},
plotAvgs = {
if (time(sim) == end(sim)) {
mod$plotTypes <- P(sim)$.plots
}
sim <- plotAvgVegAttributes(sim)
if (!is.na(P(sim)$.plotInterval)) {
if (!(time(sim) + P(sim)$.plotInterval) == end(sim))
sim <- scheduleEvent(sim, time(sim) + P(sim)$.plotInterval,
"Biomass_core", "plotAvgs", eventPriority = plotPriority + 0.5)
}
},
plotMaps = {
sim <- plotVegAttributesMaps(sim)
if (P(sim)$.plotMaps)
sim <- scheduleEvent(sim, time(sim) + P(sim)$.plotInterval,
"Biomass_core", "plotMaps", eventPriority = plotPriority + 0.25)
},
save = {
sim <- Save(sim)
sim <- scheduleEvent(sim, time(sim) + P(sim)$.saveInterval,
"Biomass_core", "save", eventPriority = savePriority)
},
warning(paste("Undefined event type: '", current(sim)[1, "eventType", with = FALSE],
"' in module '", current(sim)[1, "moduleName", with = FALSE], "'", sep = ""))
)
return(invisible(sim))
}
### EVENT FUNCTIONS
Init <- function(sim, verbose = getOption("LandR.verbose", TRUE)) {
## stop early if raster inputs don't match
# Must have sim$rasterToMatch
#if (!identical(sort(as.character(unique(sim$cohortData$speciesCode))), sort(unique(sim$species$species))))
# stop("the species in sim$cohortData are not the same as the species in sim$species; these must match")
cacheTags <- c(currentModule(sim), "init")
# Check some parameter values
if (P(sim)$successionTimestep > 10)
warning("successionTimestep parameter is > 10. Make sure this intended, ",
"keeping in mind that growth in the model depends on estimating 'sumB'. ",
"Only trees that are older than successionTimestep are included in the ",
"calculation of sumB, i.e., trees younger than this do not contribute ",
"to competitive interactions")
paramCheckOtherMods(sim, "initialB", ifSetButDifferent = "warning")
## prepare species ------------------------------------------------
if (is.null(sim$species))
stop("'species' object must be provided")
species <- as.data.table(sim$species) # The former setDT actually changed the vector
LandR::assertSpeciesTable(species)
set(species, NULL, "speciesCode", factor(species$species, levels = unique(species$species))) # supply levels for speed
sim$species <- setkey(species, speciesCode)
## prepare dummy versions if not supplied --------------------------
## This next chunk is to supply defaults for the case where `cohortData` or `pixelGroupMap` is not supplied
## e.g., via a module like `Biomass_borealDataPrep`
if (!suppliedElsewhere("cohortData", sim, where = "sim") | !suppliedElsewhere("pixelGroupMap", sim, where = "sim")) {
if (is.null(sim$rasterToMatch))
stop("Must supply sim$rasterToMatch, since sim$cohortData or sim$pixelGroupMap are not supplied")
if ((!suppliedElsewhere("cohortData", sim, where = "sim") && suppliedElsewhere("pixelGroupMap", sim, where = "sim")) ||
(suppliedElsewhere("cohortData", sim, where = "sim") && !suppliedElsewhere("pixelGroupMap", sim, where = "sim"))) {
stop("Either 'cohortData' or 'pixelGroupMap' are being supplied without the other.",
"These two objects must be supplied together and conform to each other.",
"Either supply both of them manually, or use a module like Biomass_borealDataPrep to do so.")
}
if (suppliedElsewhere("ecoregionMap", sim, where = "sim")) {
message(blue("'ecoregionMap' was supplied, but "),
red("will be replaced by a dummy version to make "),
blue("'cohortData' or 'pixelGroupMap'.\n If this is wrong, provide matching ",
"'cohortData', 'pixelGroupMap' and 'ecoregionMap'"))
}
ecoregionMap <- makeDummyEcoregionMap(sim$rasterToMatch)
if (suppliedElsewhere("biomassMap", sim, where = "sim"))
message(blue("'biomassMap' was supplied, but "),
red("will be replaced by a dummy version to make "),
blue("'cohortData' or 'pixelGroupMap'.\n If this is wrong, provide matching ",
"'cohortData', 'pixelGroupMap' and 'biomassMap'"))
## note that to make the dummy sim$biomassMap, we need to first make a dummy rawBiomassMap
httr::with_config(config = httr::config(ssl_verifypeer = P(sim)$.sslVerify), {
rawBiomassMap <- makeDummyRawBiomassMap(sim$rasterToMatch)
})
if (suppliedElsewhere("standAgeMap", sim, where = "sim"))
message(blue("'standAgeMap' was supplied, but "),
red("will be replaced by a dummy version to make "),
blue("'cohortData' or 'pixelGroupMap'.\n If this is wrong, provide matching ",
"'cohortData', 'pixelGroupMap' and 'standAgeMap'"))
standAgeMap <- makeDummyStandAgeMap(rawBiomassMap)
if (suppliedElsewhere("rstLCC", sim, where = "sim"))
message(blue("'rstLCC' was supplied, but "),
red("will be replaced by a dummy version to make "),
blue("'cohortData' or 'pixelGroupMap'.\n If this is wrong, provide matching ",
"'cohortData', 'pixelGroupMap' and 'rstLCC'"))
rstLCC <- makeDummyRstLCC(sim$rasterToMatch)
## make sure speciesLayers match RTM (they may not if they come from another module's init.)
if (!.compareRas(sim$speciesLayers, sim$rasterToMatch, stopOnError = FALSE)) {
message(blue("'speciesLayers' and 'rasterToMatch' do not match. "),
red("'speciesLayers' will be cropped/masked/reprojected to 'rasterToMatch'. "),
blue("If this is wrong, provide matching 'speciesLayers' and 'rasterToMatch'"))
sim$speciesLayers <- postProcess(sim$speciesLayers,
to = sim$rasterToMatch,
filename1 = NULL,
writeTo = NULL,
userTags = c(currentModule(sim), "speciesLayers"))
}
ecoregionFiles <- makeDummyEcoregionFiles(ecoregionMap, rstLCC, sim$rasterToMatch)
## create pixelTable object ------------------------------------
## Round age to pixelGroupAgeClass
## check if all species have traits
tempObjs <- checkSpeciesTraits(sim$speciesLayers, sim$species, sim$sppColorVect)
sim$speciesLayers <- tempObjs$speciesLayers
sim$sppColorVect <- tempObjs$sppColorVect
rm(tempObjs)
assertSppVectors(sppEquiv = sim$species, sppEquivCol = "speciesCode",
sppColorVect = sim$sppColorVect)
pixelTable <- makePixelTable(speciesLayers = sim$speciesLayers, #species = sim$species,
standAgeMap = standAgeMap, ecoregionFiles = ecoregionFiles,
biomassMap = rawBiomassMap, rasterToMatch = sim$rasterToMatch,
rstLCC = rstLCC)
## create initial pixelCohortData table
## note that pixelGroupBiomassClass here is forced to 100, to match dummy biomass units
message(blue("Creating a", red("DUMMY"), blue("cohorData table.")))
coverColNames <- paste0("cover.", sim$species$species)
pixelCohortData <- Cache(makeAndCleanInitialCohortData, pixelTable,
sppColumns = coverColNames,
minCoverThreshold = 1,
doSubset = FALSE,
userTags = c(cacheTags, "pixelCohortData"),
omitArgs = c("userTags"))
pixelCohortData <- partitionBiomass(x = 1, pixelCohortData)
setnames(pixelCohortData, "initialEcoregionCode", "ecoregionGroup")
## When using dummy values ecoregion codes are not changed
rmZeroBiomassQuote <- quote(B > 0)
## This will fail, because LandR::makeAndCleanInitialCohortData no longer returns a B column July 2020 IE
cohortDataNoBiomass <- pixelCohortData[eval(rmZeroBiomassQuote),
.(B, logAge, speciesCode, ecoregionGroup, lcc, cover)]
## Statistical estimation of establishprob, maxB and maxANPP
## only use pixels where cover > 0
cohortDataShort <- pixelCohortData[, list(coverNum = pmax(1, .N - 1),
coverPres = sum(cover > 0)),
by = c("ecoregionGroup", "speciesCode")]
cohortDataShortNoCover <- cohortDataShort[coverPres == 0]
cohortDataShort <- cohortDataShort[coverPres > 0] # remove places where there is 0 cover
coverModel <- quote(lme4::glmer(cbind(coverPres, coverNum) ~ speciesCode +
(1 | ecoregionGroup), family = binomial))
biomassModel <- quote(lme4::lmer(B ~ logAge * speciesCode + cover * speciesCode +
(logAge + cover + speciesCode | ecoregionGroup)))
## COVER
message(blue("Estimating Species Establishment Probability from "), red("DUMMY values of ecoregionGroup "),
blue("using the formula:\n"), magenta(format(coverModel)))
modelCover <- Cache(statsModel,
modelFn = coverModel,
.specialData = cohortDataShort,
userTags = c(cacheTags, "modelCover"),
omitArgs = c("userTags")) ## DON'T IGNORE .specialData - will fail downstream due to randomness
message(blue(" The rsquared is: "))
print(modelCover$rsq)
## BIOMASS
## For Cache -- doesn't need to cache all columns in the data.table -- only the ones in the model
message(blue("Estimating maxB from "), red("DUMMY values of age and ecoregionGroup "),
blue("using the formula:\n"),
magenta(paste0(format(biomassModel), collapse = "")))
modelBiomass <- Cache(statsModel,
modelFn = biomassModel,
.specialData = cohortDataNoBiomass,
userTags = c(cacheTags, "modelBiomass"),
omitArgs = c("userTags")) ## DON'T IGNORE .specialData - will fail downstream due to randomness
message(blue(" The rsquared is: "))
print(modelBiomass$rsq)
## create speciesEcoregion ---------------------------------------------
## a single line for each combination of ecoregionGroup & speciesCode
## doesn't include combinations with B = 0 because those places can't have the species/ecoregion combo
message(blue("Create speciesEcoregion from "), red("DUMMY values"))
speciesEcoregion <- makeSpeciesEcoregion(cohortDataBiomass = cohortDataNoBiomass,
cohortDataShort = cohortDataShort,
cohortDataShortNoCover = cohortDataShortNoCover,
species = sim$species,
modelCover = modelCover,
modelBiomass = modelBiomass,
successionTimestep = P(sim)$successionTimestep,
currentYear = time(sim))
if (ncell(sim$rasterToMatch) > 3e7) .gc()
## Create initial communities, i.e., pixelGroups -----------------------
if (!suppliedElsewhere("columnsForPixelGroups", sim, where = "sim")) {
columnsForPixelGroups <- LandR::columnsForPixelGroups
} else {
columnsForPixelGroups <- sim$columnsForPixelGroups
}
## make cohortDataFiles: pixelCohortData (rm unnecessary cols, subset pixels with B>0,
## generate pixelGroups, add ecoregionGroup and totalBiomass) and cohortData
cohortDataFiles <- makeCohortDataFiles(pixelCohortData, columnsForPixelGroups, speciesEcoregion,
pixelGroupBiomassClass = 10,
pixelGroupAgeClass = 10,
minAgeForGrouping = -1)#,
#pixelFateDT = pixelFateDT)
sim$cohortData <- cohortDataFiles$cohortData
pixelCohortData <- cohortDataFiles$pixelCohortData
rm(cohortDataFiles)
## make a table of available active and inactive (no biomass) ecoregions
sim$ecoregion <- makeEcoregionDT(pixelCohortData, speciesEcoregion)
## make biomassMap, ecoregionMap, minRelativeB, pixelGroupMap
sim$biomassMap <- makeBiomassMap(pixelCohortData, sim$rasterToMatch)
sim$ecoregionMap <- makeEcoregionMap(ecoregionFiles, pixelCohortData)
sim$minRelativeB <- makeMinRelativeB(pixelCohortData)
sim$pixelGroupMap <- makePixelGroupMap(pixelCohortData, sim$rasterToMatch)
.compareRas(sim$biomassMap, sim$ecoregionMap, sim$pixelGroupMap, sim$rasterToMatch, res = TRUE)
## make ecoregionGroup a factor and export speciesEcoregion to sim
speciesEcoregion[, ecoregionGroup := factor(as.character(ecoregionGroup))]
sim$speciesEcoregion <- speciesEcoregion
## do assertions
message(blue("Create pixelGroups based on: ", paste(columnsForPixelGroups, collapse = ", "),
"\n Resulted in", magenta(length(unique(sim$cohortData$pixelGroup))),
"unique pixelGroup values"))
LandR::assertERGs(sim$ecoregionMap, cohortData = sim$cohortData,
speciesEcoregion = speciesEcoregion,
minRelativeB = sim$minRelativeB)
LandR::assertCohortData(sim$cohortData, sim$pixelGroupMap, cohortDefinitionCols = P(sim)$cohortDefinitionCols)
LandR::assertUniqueCohortData(sim$cohortData, c("pixelGroup", "ecoregionGroup", "speciesCode"))
}
## check objects
LandR::assertColumns(sim$cohortData, c(pixelGroup = "integer",
ecoregionGroup = "factor",
speciesCode = "factor",
age = "integer",
B = "integer"))
## hamornize to simulated species -- we assume species is the correct set
## (it has been filtered by B_borealDP and B_speciesParams)
## leave sim$sppEquiv untouched for future reference - sim$sppColorVect can be changed
mod$sppEquiv <- sim$sppEquiv[get(P(sim)$sppEquivCol) %in% unique(sim$species$speciesCode)]
sppColorVect <- sim$sppColorVect[c(unique(as.character(sim$species$speciesCode)), "Mixed")]
sppColorVect <- sppColorVect[complete.cases(sppColorVect)]
sppOuts <- sppHarmonize(mod$sppEquiv, unique(sim$species$speciesCode), sppEquivCol = P(sim)$sppEquivCol,
sppColorVect = sppColorVect, vegLeadingProportion = P(sim)$vegLeadingProportion)
## TODO: it'd be great to functionize this:
if (length(setdiff(sim$sppColorVect, sppOuts$sppColorVect))) {
message(blue(
"sim$sppColorVect will be filtered to simulated species only (sim$species$speciesCode)"
))
}
sim$sppColorVect <- sppOuts$sppColorVect
if (length(setdiff(sim$sppNameVector, sppOuts$sppNameVector))) {
message(blue(
"sim$sppNameVector will be filtered to simulated species only (sim$species$speciesCode)"
))
}
sim$sppNameVector <- sppOuts$sppNameVector
assertSppVectors(sppEquiv = sim$species, sppEquivCol = "speciesCode",
sppColorVect = sim$sppColorVect)
assertSppVectors(sppEquiv = mod$sppEquiv, sppEquivCol = P(sim)$sppEquivCol, sppColorVect = sim$sppColorVect)
rasterNamesToCompare <- c("ecoregionMap", "pixelGroupMap")
if (!identical(P(sim)$initialBiomassSource, "cohortData")) {
rasterNamesToCompare <- c(rasterNamesToCompare, "biomassMap")
}
haveAllRasters <- all(!unlist(lapply(rasterNamesToCompare, function(rn) is.null(sim[[rn]]))))
if (haveAllRasters) {
rastersToCompare <- mget(rasterNamesToCompare, envir(sim))
do.call(.compareRas, append(list(x = sim$rasterToMatch, res = TRUE), rastersToCompare))
} else {
stop("Expecting 3 rasters at this point: sim$biomassMap, sim$ecoregionMap, ",
"sim$pixelGroupMap and they must match sim$rasterToMatch")
}
LandR::assertERGs(sim$ecoregionMap, sim$cohortData, sim$speciesEcoregion, sim$minRelativeB)
## ecoregion -------------------------------------------------
if (is.null(sim$ecoregion))
stop("Need to supply sim$ecoregion")
setDT(sim$ecoregion)
LandR::assertColumns(sim$ecoregion, c(active = "character", ecoregionGroup = "factor"))
ecoregion <- sim$ecoregion#[, ecoregionGroup := as.factor(ecoregion)]
# ecoregion_temp <- setkey(ecoregion[, .(ecoregion, ecoregionGroup)], ecoregion)
## speciesEcoregion - checks
LandR::assertColumns(sim$speciesEcoregion,
c(ecoregionGroup = "factor", speciesCode = "factor",
establishprob = "numeric", maxB = "integer", maxANPP = "numeric"))
# speciesEcoregion[, ecoregionGroup := as.factor(ecoregion)]
speciesEcoregion <- sim$speciesEcoregion#[sim$species[, .(species, speciesCode)],
speciesEcoregion <- setkey(speciesEcoregion, ecoregionGroup, speciesCode)
## minRelativeB ----------------------------------------------
setDT(sim$minRelativeB) # make a data.table
## join to get ecoregionGroup column
sim$minRelativeB <- sim$minRelativeB[unique(speciesEcoregion[, .(ecoregionGroup)]),
on = "ecoregionGroup", nomatch = 0]
## create cohortData from communities ------------------------
active_ecoregion <- setkey(ecoregion[active == "yes", .(k = 1, ecoregionGroup)], k) # not sure what k is doing here
pixelGroupMap <- sim$pixelGroupMap
names(pixelGroupMap) <- "pixelGroup"
## Changed mechanism for active and inactive -- just use NA on ecoregionMap
ecoregionMapNAs <- is.na(as.vector(sim$ecoregionMap[]))
# very possible that sim$studyAreaReporting is not same CRS as sim$ecoregionMap
# used to be `mask(...)` which would fail ... Eliot Dec 1, 2023
ecoregionMapReporting <- maskTo(sim$ecoregionMap, sim$studyAreaReporting)
ecoregionMapReportingNAs <- is.na(as.vector(ecoregionMapReporting[]))
sim$activePixelIndex <- which(!ecoregionMapNAs) ## store for future use
sim$activePixelIndexReporting <- which(!ecoregionMapReportingNAs) ## store for future use
sim$inactivePixelIndex <- which(ecoregionMapNAs) ## store for future use
sim$inactivePixelIndexReporting <- which(ecoregionMapReportingNAs) ## store for future use
assertthat::assert_that(all(is.na(as.vector(sim$ecoregionMap[])) == is.na(as.vector(pixelGroupMap[]))))
## Keeps track of the length of the ecoregion
mod$activeEcoregionLength <- data.table(ecoregionGroup = factorValues2(sim$ecoregionMap,
as.vector(values(sim$ecoregionMap)),
att = "ecoregionGroup"),
pixelIndex = 1:ncell(sim$ecoregionMap))[
ecoregionGroup %in% active_ecoregion$ecoregionGroup,
.(NofCell = length(pixelIndex)), by = "ecoregionGroup"]
cohortData <- sim$cohortData[pixelGroup %in% unique(as.vector(values(pixelGroupMap))[sim$activePixelIndex]), ]
cohortData <- updateSpeciesEcoregionAttributes(speciesEcoregion = speciesEcoregion,
currentTime = round(time(sim)),
cohortData = cohortData)
cohortData <- updateSpeciesAttributes(species = sim$species, cohortData = cohortData)
LandR::assertCohortData(cohortData, sim$pixelGroupMap, cohortDefinitionCols = P(sim)$cohortDefinitionCols)
initialBiomassSourcePoss <- c('spinUp', 'cohortData', 'biomassMap')
if (!any(grepl(P(sim)$initialBiomassSource, initialBiomassSourcePoss))) {
stop("P(sim)$initialBiomassSource must be one of: ", paste(initialBiomassSourcePoss, collapse = ", "))
}
## spinup ------------------------------------------------------------------
if (grepl("spin", tolower(P(sim)$initialBiomassSource))) {
## negate the TRUE to allow for default to be this, even if NULL or NA
stop("'spinUp as a value for P(sim)$initialBiomassSource is not working currently; ",
"please use 'cohortData'")
if (verbose > 0)
message("Running spinup")
spinupstage <- Cache(spinUp,
cohortData = cohortData,
calibrate = P(sim)$calibrate,
successionTimestep = P(sim)$successionTimestep,
spinupMortalityfraction = P(sim)$spinupMortalityfraction,
species = sim$species,
userTags = c(cacheTags, "spinUp"),
omitArgs = c("userTags"))
cohortData <- spinupstage$cohortData
if (P(sim)$calibrate) {
sim$spinupOutput <- spinupstage$spinupOutput
}
if (P(sim)$calibrate) {
sim$simulationTreeOutput <- data.table(Year = numeric(), siteBiomass = numeric(),
Species = character(), Age = numeric(),
iniBiomass = numeric(), ANPP = numeric(),
Mortality = numeric(), deltaB = numeric(),
finBiomass = numeric())
sim$regenerationOutput <- data.table(seedingAlgorithm = character(), species = character(),
Year = numeric(), numberOfReg = numeric())
}
} else {
if (grepl("biomassMap", tolower(P(sim)$initialBiomassSource))) {
stop("'biomassMap as a value for P(sim)$initialBiomassSource is not working currently; ",
"please use 'cohortData'")
if (verbose > 0)
message("Skipping spinup and using the sim$biomassMap * SpeciesLayers pct as initial biomass values")
biomassTable <- data.table(biomass = as.vector(values(sim$biomassMap)),
pixelGroup = as.vector(values(pixelGroupMap)))
biomassTable <- na.omit(biomassTable)
maxBiomass <- maxValue(sim$biomassMap)
if (maxBiomass < 1e3) {
if (verbose > 0) {
message(crayon::green(" Because biomassMap values are all below 1000, assuming that these are on tonnes/ha.\n",
" Converting to $g/m^2$ by multiplying by 100"))
}
biomassTable[, `:=`(biomass = biomass * 100)]
}
## In case there are non-identical biomasses in each pixelGroup -- this should be irrelevant with
## improved biomass_borealDataPrep.R (Jan 6, 2019 -- Eliot)
biomassTable <- biomassTable[, list(Bsum = mean(biomass, na.rm = TRUE)), by = pixelGroup]
if (!is.integer(biomassTable[["Bsum"]]))
set(biomassTable, NULL, "Bsum", asInteger(biomassTable[["Bsum"]]))
## Delete the B from cohortData -- it will be joined from biomassTable
set(cohortData, NULL, "B", NULL)
cohortData[, totalSpeciesPresence := sum(speciesPresence), by = "pixelGroup"]
cohortData <- cohortData[biomassTable, on = "pixelGroup"]
cohortData[, B := Bsum * speciesPresence / totalSpeciesPresence, by = c("pixelGroup", "speciesCode")]
if (!is.integer(cohortData[["B"]]))
set(cohortData, NULL, "B", asInteger(cohortData[["B"]]))
}
}
pixelAll <- cohortData[, .(uniqueSumB = sum(B, na.rm = TRUE)), by = pixelGroup]
if (!is.integer(pixelAll[["uniqueSumB"]]))
set(pixelAll, NULL, "uniqueSumB", asInteger(pixelAll[["uniqueSumB"]]))
if (all(!is.na(P(sim)$.plots))) {
sim$simulatedBiomassMap <- rasterizeReduced(pixelAll, pixelGroupMap, "uniqueSumB")
}
colsToKeep <- unique(c(P(sim)$cohortDefinitionCols, "ecoregionGroup", "B"))
# colsToKeep <- unique(c(P(sim)$cohortDefinitionCols))
sim$cohortData <- cohortData[, .SD, .SDcol = colsToKeep]
sim$cohortData[, c("mortality", "aNPPAct") := 0L]
# sim$cohortData <- cohortData[, .(pixelGroup, ecoregionGroup, speciesCode, age, B, mortality = 0L, aNPPAct = 0L)]
## the above breaks with non-default cohortDefinitionCols
sim$cohortData <- setcolorder(sim$cohortData, neworder = c("pixelGroup", "ecoregionGroup", "speciesCode", "age", "B",
"mortality", "aNPPAct"))
simulationOutput <- data.table(ecoregionGroup = factorValues2(sim$ecoregionMap,
as.vector(values(sim$ecoregionMap)),
att = "ecoregionGroup"),
pixelGroup = as.vector(values(pixelGroupMap)),
pixelIndex = 1:ncell(sim$ecoregionMap))[
, .(NofPixel = length(pixelIndex)),
by = c("ecoregionGroup", "pixelGroup")]
simulationOutput <- setkey(simulationOutput, pixelGroup)[setkey(pixelAll, pixelGroup), nomatch = 0][
, .(Biomass = sum(as.numeric(uniqueSumB) * as.numeric(NofPixel))), by = ecoregionGroup] ## NOTE:
## above needs to be numeric because of integer overflow -- returned to integer in 2 lines
simulationOutput <- setkey(simulationOutput, ecoregionGroup)[
setkey(mod$activeEcoregionLength, ecoregionGroup), nomatch = 0]
sim$simulationOutput <- simulationOutput[, .(ecoregionGroup, NofCell, Year = asInteger(time(sim)),
Biomass = asInteger(Biomass / NofCell),
ANPP = 0L, Mortality = 0L, Regeneration = 0L)]
## make initial vegTypeMap - this is important when saving outputs at year = 1, with eventPriority = 1
## this vegTypeMap will be overwritten later in the same year.
if (!is.null(P(sim)$calcSummaryBGM))
sim$vegTypeMap <- vegTypeMapGenerator(sim$cohortData, sim$pixelGroupMap,
P(sim)$vegLeadingProportion, mixedType = P(sim)$mixedType,
sppEquiv = mod$sppEquiv, sppEquivCol = P(sim)$sppEquivCol,
colors = sim$sppColorVect,
doAssertion = getOption("LandR.assertions", TRUE))