forked from ices-tools-prod/HEAT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HEAT.R
639 lines (503 loc) · 28.6 KB
/
HEAT.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
# Install and load R packages ---------------------------------------------
ipak <- function(pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}
packages <- c("sf", "data.table", "tidyverse", "ggplot2", "ggmap", "mapview")
ipak(packages)
# Define paths
inputPath <- "Input"
outputPath <- "Output"
# Define assessment period - Uncomment the period you want to run the assessment for!
assessmentPeriod <- "2011-2016"
#assessmentPeriod <- "2016-2021"
# Create paths
dir.create(inputPath, showWarnings = FALSE, recursive = TRUE)
dir.create(outputPath, showWarnings = FALSE, recursive = TRUE)
# Download and unpack files needed for the assessment --------------------------
download.file.unzip.maybe <- function(url, refetch = FALSE, path = ".") {
dest <- file.path(path, sub("\\?.+", "", basename(url)))
if (refetch || !file.exists(dest)) {
download.file(url, dest, mode = "wb")
if (tools::file_ext(dest) == "zip") {
unzip(dest, exdir = path)
}
}
}
if (assessmentPeriod == "2011-2016"){
# Assessment Period 2011-2016
urls <- c("https://www.dropbox.com/s/poruz8srxfqiflm/AssessmentUnits.zip?dl=1",
"https://www.dropbox.com/s/05mjl0haig72wrj/Indicators.csv?dl=1",
"https://www.dropbox.com/s/uikixp822dq3u92/IndicatorUnits.csv?dl=1",
"https://www.dropbox.com/s/lbo4d24lauyz6gn/UnitGridSize.csv?dl=1",
"https://www.dropbox.com/s/xqlqhypxbz7mm0c/StationSamplesICE.txt.gz?dl=1",
"https://www.dropbox.com/s/66rkujevbkvic2q/StationSamplesCTD.txt.gz?dl=1")
} else {
# Assessment Period 2016-2021
urls <- c("https://www.dropbox.com/s/4jbqffm2nstma9v/AssessmentUnits.zip?dl=1",
"https://www.dropbox.com/s/s5pzd8cvksfffgn/Indicators.csv?dl=1",
"https://www.dropbox.com/s/28wr662sz6jxjox/IndicatorUnits.csv?dl=1",
"https://www.dropbox.com/s/cs4boo7247p6e13/UnitGridSize.csv?dl=1",
"https://www.dropbox.com/s/vp04vrl2gk5vxx1/StationSamplesICE.txt.gz?dl=1",
"https://www.dropbox.com/s/89i1w79lmlab425/StationSamplesCTD.txt.gz?dl=1")
}
files <- sapply(urls, download.file.unzip.maybe, path = inputPath)
unitsFile <- file.path(inputPath, paste0("AssessmentUnits.shp"))
indicatorsFile <- file.path(inputPath, "Indicators.csv")
indicatorUnitsFile <- file.path(inputPath, "IndicatorUnits.csv")
unitGridSizeFile <- file.path(inputPath, "UnitGridSize.csv")
stationSamplesICEFile <- file.path(inputPath, "StationSamplesICE.txt.gz")
# Assessment Units + Grid Units-------------------------------------------------
# Read assessment unit from shape file
units <- st_read(unitsFile)
# Filter for open sea assessment units
units <- units[units$Code %like% 'SEA',]
# Correct Description column name - temporary solution!
colnames(units)[2] <- "Description"
# Correct Åland Sea ascii character - temporary solution!
units[14,2] <- 'Åland Sea'
# Include stations from position 55.86667+-0.01667 12.75+-0.01667 which will include the Danish station KBH/DMU 431 and the Swedish station Wlandskrona into assessment unit 3/SEA-003
units[3,] <- st_union(units[3,],st_as_sfc("POLYGON((12.73333 55.85,12.73333 55.88334,12.76667 55.88334,12.76667 55.85,12.73333 55.85))", crs = 4326))
# Assign IDs
units$UnitID = 1:nrow(units)
# Identify invalid geometries
st_is_valid(units)
# Transform projection into ETRS_1989_LAEA
units <- st_transform(units, crs = 3035)
# Calculate area
units$UnitArea <- st_area(units)
# Identify invalid geometries
st_is_valid(units)
# Make geometries valid by doing the buffer of nothing trick
#units <- sf::st_buffer(units, 0.0)
# Identify overlapping assessment units
#st_overlaps(units)
# Make grid units
make.gridunits <- function(units, gridSize) {
units <- st_transform(units, crs = 3035)
bbox <- st_bbox(units)
xmin <- floor(bbox$xmin / gridSize) * gridSize
ymin <- floor(bbox$ymin / gridSize) * gridSize
xmax <- ceiling(bbox$xmax / gridSize) * gridSize
ymax <- ceiling(bbox$ymax / gridSize) * gridSize
xn <- (xmax - xmin) / gridSize
yn <- (ymax - ymin) / gridSize
grid <- st_make_grid(units, cellsize = gridSize, c(xmin, ymin), n = c(xn, yn), crs = 3035) %>%
st_sf()
grid$GridID = 1:nrow(grid)
gridunits <- st_intersection(grid, units)
gridunits$Area <- st_area(gridunits)
return(gridunits)
}
gridunits10 <- make.gridunits(units, 10000)
gridunits30 <- make.gridunits(units, 30000)
gridunits60 <- make.gridunits(units, 60000)
unitGridSize <- fread(input = unitGridSizeFile) %>% setkey(UnitID)
a <- merge(unitGridSize[GridSize == 10000], gridunits10 %>% select(UnitID, GridID, GridArea = Area))
b <- merge(unitGridSize[GridSize == 30000], gridunits30 %>% select(UnitID, GridID, GridArea = Area))
c <- merge(unitGridSize[GridSize == 60000], gridunits60 %>% select(UnitID, GridID, GridArea = Area))
gridunits <- st_as_sf(rbindlist(list(a,b,c)))
rm(a,b,c)
# Read stationSamples ----------------------------------------------------------
stationSamples <- fread(input = stationSamplesICEFile, sep = "\t", na.strings = "NULL", stringsAsFactors = FALSE, header = TRUE, check.names = TRUE)
# Make stations spatial keeping original latitude/longitude
stationSamples <- st_as_sf(stationSamples, coords = c("Longitude..degrees_east.", "Latitude..degrees_north."), remove = FALSE, crs = 4326)
# Transform projection into ETRS_1989_LAEA
stationSamples <- st_transform(stationSamples, crs = 3035)
# Classify stations into 10 and 30k gridunits
stationSamples <- st_join(stationSamples, st_cast(gridunits), join = st_intersects)
# Remove spatial column
stationSamples <- st_set_geometry(stationSamples, NULL)
stationSamples <- as.data.table(stationSamples)
# Read indicator configs -------------------------------------------------------
indicators <- fread(input = indicatorsFile) %>% setkey(IndicatorID)
indicatorUnits <- fread(input = indicatorUnitsFile) %>% setkey(IndicatorID, UnitID)
wk1list = list()
wk2list = list()
# Loop indicators --------------------------------------------------------------
for(i in 1:nrow(indicators)){
indicatorID <- indicators[i, IndicatorID]
criteriaID <- indicators[i, CriteriaID]
name <- indicators[i, Name]
year.min <- indicators[i, YearMin]
year.max <- indicators[i, YearMax]
month.min <- indicators[i, MonthMin]
month.max <- indicators[i, MonthMax]
depth.min <- indicators[i, DepthMin]
depth.max <- indicators[i, DepthMax]
metric <- indicators[i, Metric]
response <- indicators[i, Response]
# Copy data
wk <- as.data.table(stationSamples)
# Create Period
wk[, Period := ifelse(month.min > month.max & Month >= month.min, Year + 1, Year)]
# Create Indicator
if (name == 'Dissolved Inorganic Nitrogen') {
wk$ES <- apply(wk[, list(Nitrate..umol.l., Nitrite..umol.l., Ammonium..umol.l.)], 1, function(x){
if (all(is.na(x)) | is.na(x[1])) {
NA
}
else {
sum(x, na.rm = TRUE)
}
})
}
else if (name == 'Dissolved Inorganic Phosphorus') {
wk[,ES := Phosphate..umol.l.]
}
else if (name == 'Chlorophyll a') {
wk[, ES := Chlorophyll.a..ug.l.]
}
else if (name == 'Secchi Depth') {
wk[, ES := Secchi..m..METAVAR.DOUBLE]
}
else if (name == "Total Nitrogen") {
wk[, ES := Total.Nitrogen..umol.l.]
}
else if (name == "Total Phosphorus") {
wk[, ES := Total.Phosphorus..umol.l.]
}
else {
next
}
# Add unit grid size
wk <- wk[unitGridSize, on="UnitID", nomatch=0]
# Filter stations rows and columns --> UnitID, GridID, GridArea, Period, Month, StationID, Depth, Temperature, Salinity, ES
if (month.min > month.max) {
wk0 <- wk[
(Period >= year.min & Period <= year.max) &
(Month >= month.min | Month <= month.max) &
(Depth..m.db..PRIMARYVAR.DOUBLE >= depth.min & Depth..m.db..PRIMARYVAR.DOUBLE <= depth.max) &
!is.na(ES) &
!is.na(UnitID),
.(IndicatorID = indicatorID, UnitID, GridSize, GridID, GridArea, Period, Month, StationID, Depth = Depth..m.db..PRIMARYVAR.DOUBLE, Temperature = Temperature..degC., Salinity = Salinity..., ES)]
} else {
wk0 <- wk[
(Period >= year.min & Period <= year.max) &
(Month >= month.min & Month <= month.max) &
(Depth..m.db..PRIMARYVAR.DOUBLE >= depth.min & Depth..m.db..PRIMARYVAR.DOUBLE <= depth.max) &
!is.na(ES) &
!is.na(UnitID),
.(IndicatorID = indicatorID, UnitID, GridSize, GridID, GridArea, Period, Month, StationID, Depth = Depth..m.db..PRIMARYVAR.DOUBLE, Temperature = Temperature..degC., Salinity = Salinity..., ES)]
}
# Calculate station mean --> UnitID, GridID, GridArea, Period, Month, ES, SD, N
wk1 <- wk0[, .(ES = mean(ES), SD = sd(ES), N = .N), keyby = .(IndicatorID, UnitID, GridID, GridArea, Period, Month, StationID)]
# Calculate annual mean --> UnitID, Period, ES, SD, N, NM
wk2 <- wk1[, .(ES = mean(ES), SD = sd(ES), N = .N, NM = uniqueN(Month)), keyby = .(IndicatorID, UnitID, Period)]
wk1list[[i]] <- wk1
wk2list[[i]] <- wk2
}
# Combine station and annual indicator results
wk1 <- rbindlist(wk1list)
wk2 <- rbindlist(wk2list)
# Combine with indicator and indicator unit configuration tables
wk3 <- indicators[indicatorUnits[wk2]]
# Standard Error
wk3[, SE := SD / sqrt(N)]
# 95 % Confidence Interval
wk3[, CI := qnorm(0.975) * SE]
# Calculate Eutrophication Ratio (ER)
wk3[, ER := ifelse(Response == 1, ES / ET, ET / ES)]
# Calculate (BEST)
wk3[, BEST := ifelse(Response == 1, ET / (1 + ACDEV / 100), ET / (1 - ACDEV / 100))]
# Calculate Ecological Quality Ratio (ERQ)
wk3[, EQR := ifelse(Response == 1, ifelse(BEST > ES, 1, BEST / ES), ifelse(ES > BEST, 1, ES / BEST))]
# Calculate Ecological Quality Ratio Boundaries (ERQ_HG/GM/MP/PB)
wk3[, EQR_GM := ifelse(Response == 1, 1 / (1 + ACDEV / 100), 1 - ACDEV / 100)]
wk3[, EQR_HG := 0.5 * 0.95 + 0.5 * EQR_GM]
wk3[, EQR_PB := 2 * EQR_GM - 0.95]
wk3[, EQR_MP := 0.5 * EQR_GM + 0.5 * EQR_PB]
# Calculate Ecological Quality Ratio Scaled (EQRS)
wk3[, EQRS := ifelse(EQR <= EQR_PB, (EQR - 0) * (0.2 - 0) / (EQR_PB - 0) + 0,
ifelse(EQR <= EQR_MP, (EQR - EQR_PB) * (0.4 - 0.2) / (EQR_MP - EQR_PB) + 0.2,
ifelse(EQR <= EQR_GM, (EQR - EQR_MP) * (0.6 - 0.4) / (EQR_GM - EQR_MP) + 0.4,
ifelse(EQR <= EQR_HG, (EQR - EQR_GM) * (0.8 - 0.6) / (EQR_HG - EQR_GM) + 0.6,
(EQR - EQR_HG) * (1 - 0.8) / (1 - EQR_HG) + 0.8))))]
wk3[, EQRS_Class := ifelse(EQRS >= 0.8, "High",
ifelse(EQRS >= 0.6, "Good",
ifelse(EQRS >= 0.4, "Moderate",
ifelse(EQRS >= 0.2, "Poor","Bad"))))]
# Calculate General Temporal Confidence (GTC) - Confidence in number of annual observations
wk3[, GTC := ifelse(N > GTC_HM, 100, ifelse(N < GTC_ML, 0, 50))]
# Calculate Number of Months Potential
wk3[, NMP := ifelse(MonthMin > MonthMax, 12 - MonthMin + 1 + MonthMax, MonthMax - MonthMin + 1)]
# Calculate Specific Temporal Confidence (STC) - Confidence in number of annual missing months
wk3[, STC := ifelse(NMP - NM <= STC_HM, 100, ifelse(NMP - NM >= STC_ML, 0, 50))]
# Calculate General Spatial Confidence (GSC) - Confidence in number of annual observations per number of grids
# Calculate Specific Spatial Confidence (SSC) - Confidence in area of sampled grid units as a percentage to the total unit area
a <- wk1[, .N, keyby = .(IndicatorID, UnitID, Period, GridID, GridArea)] # UnitGrids
b <- a[, .(GridArea = sum(as.numeric(GridArea))), keyby = .(IndicatorID, UnitID, Period)] #GridAreas
c <- as.data.table(units)[, .(UnitArea = as.numeric(UnitArea)), keyby = .(UnitID)] # UnitAreas
d <- c[b, on = .(UnitID = UnitID)] # UnitAreas ~ GridAreas
wk3 <- wk3[d[,.(IndicatorID, UnitID, Period, UnitArea, GridArea)], on = .(IndicatorID = IndicatorID, UnitID = UnitID, Period = Period)]
wk3[, SSC := ifelse(GridArea / UnitArea * 100 > SSC_HM, 100, ifelse(GridArea / UnitArea * 100 < SSC_ML, 0, 50))]
rm(a,b,c,d)
# Calculate assessment ES --> UnitID, Period, ES, SD, N, N_OBS, GTC, STC, SSC
wk4 <- wk3[, .(Period = min(Period) * 10000 + max(Period), ES = mean(ES), SD = sd(ES), N = .N, N_OBS = sum(N), GTC = mean(GTC), STC = mean(STC), SSC = mean(SSC)), .(IndicatorID, UnitID)]
# Add Year Count where STC = 100 --> NSTC100
wk4 <- wk3[STC == 100, .(NSTC100 = .N), .(IndicatorID, UnitID)][wk4, on = .(IndicatorID, UnitID)]
# Adjust Specific Spatial Confidence if number of years where STC = 100 is at least half of the number of years with meassurements
wk4[, STC := ifelse(!is.na(NSTC100) & NSTC100 >= N/2, 100, STC)]
# Combine with indicator and indicator unit configuration tables
wk5 <- indicators[indicatorUnits[wk4]]
#-------------------------------------------------------------------------------
# Confidence Assessment
# ------------------------------------------------------------------------------
# Calculate Temporal Confidence averaging General and Specific Temporal Confidence
wk5 <- wk5[, TC := (GTC + STC) / 2]
wk5[, TC_Class := ifelse(TC >= 75, "High", ifelse(TC >= 50, "Moderate", "Low"))]
# Calculate Spatial Confidence as the Specific Spatial Confidence
wk5 <- wk5[, SC := SSC]
wk5[, SC_Class := ifelse(SC >= 75, "High", ifelse(SC >= 50, "Moderate", "Low"))]
# Standard Error - using number of years in the assessment period and the associated standard deviation
#wk5[, SE := SD / sqrt(N)]
# Accuracy Confidence for Non-Problem Area
#wk5[, AC_NPA := ifelse(Response == 1, pnorm(ET, ES, SD), pnorm(ES, ET, SD))]
# Standard Error - using number of observations behind the annual mean - to be used in Accuracy Confidence Calculation!!!
wk5[, AC_SE := SD / sqrt(N_OBS)]
# Accuracy Confidence for Non-Problem Area
wk5[, AC_NPA := ifelse(Response == 1, pnorm(ET, ES, AC_SE), pnorm(ES, ET, AC_SE))]
# Accuracy Confidence for Problem Area
wk5[, AC_PA := 1 - AC_NPA]
# Accuracy Confidence Area Class - Not sure what this should be used for?
#wk5[, ACAC := ifelse(AC_NPA > 0.5, "NPA", ifelse(AC_NPA < 0.5, "PA", "PPA"))]
# Accuracy Confidence
wk5[, AC := ifelse(AC_NPA > AC_PA, AC_NPA, AC_PA)]
# Accuracy Confidence Class
wk5[, ACC := ifelse(AC > 0.9, 100, ifelse(AC < 0.7, 0, 50))]
wk5[, ACC_Class := ifelse(ACC >= 75, "High", ifelse(ACC >= 50, "Moderate", "Low"))]
# Calculate Overall Confidence
wk5 <- wk5[, C := (TC + SC + ACC) / 3]
wk5[, C_Class := ifelse(C >= 75, "High", ifelse(C >= 50, "Moderate", "Low"))]
# ------------------------------------------------------------------------------
# Calculate Eutrophication Ratio (ER)
wk5[, ER := ifelse(Response == 1, ES / ET, ET / ES)]
# Calculate (BEST)
wk5[, BEST := ifelse(Response == 1, ET / (1 + ACDEV / 100), ET / (1 - ACDEV / 100))]
# Calculate Ecological Quality Ratio (ERQ)
wk5[, EQR := ifelse(Response == 1, ifelse(BEST > ES, 1, BEST / ES), ifelse(ES > BEST, 1, ES / BEST))]
# Calculate Ecological Quality Ratio Boundaries (ERQ_HG/GM/MP/PB)
wk5[, EQR_GM := ifelse(Response == 1, 1 / (1 + ACDEV / 100), 1 - ACDEV / 100)]
wk5[, EQR_HG := 0.5 * 0.95 + 0.5 * EQR_GM]
wk5[, EQR_PB := 2 * EQR_GM - 0.95]
wk5[, EQR_MP := 0.5 * EQR_GM + 0.5 * EQR_PB]
# Calculate Ecological Quality Ratio Scaled (EQRS)
wk5[, EQRS := ifelse(EQR <= EQR_PB, (EQR - 0) * (0.2 - 0) / (EQR_PB - 0) + 0,
ifelse(EQR <= EQR_MP, (EQR - EQR_PB) * (0.4 - 0.2) / (EQR_MP - EQR_PB) + 0.2,
ifelse(EQR <= EQR_GM, (EQR - EQR_MP) * (0.6 - 0.4) / (EQR_GM - EQR_MP) + 0.4,
ifelse(EQR <= EQR_HG, (EQR - EQR_GM) * (0.8 - 0.6) / (EQR_HG - EQR_GM) + 0.6,
(EQR - EQR_HG) * (1 - 0.8) / (1 - EQR_HG) + 0.8))))]
# Assign Status and Confidence Classes
wk5[, EQRS_Class := ifelse(EQRS >= 0.8, "High",
ifelse(EQRS >= 0.6, "Good",
ifelse(EQRS >= 0.4, "Moderate",
ifelse(EQRS >= 0.2, "Poor","Bad"))))]
# Criteria ---------------------------------------------------------------------
# Criteria result as a simple average of the indicators in each category per unit - CategoryID, UnitID, N, ER, EQR, EQRS, C
wk6 <- wk5[!is.na(ER), .(.N, ER = mean(ER), EQR = mean(EQR), EQRS = mean(EQRS), C = mean(C)), .(CriteriaID, UnitID)]
# Criteria result as a weighted average of the indicators in each category per unit - CategoryID, UnitID, N, ER, EQR, EQRS, C
#wk6 <- wk5[!is.na(ER), .(.N, ER = weighted.mean(ER, IW, na.rm = TRUE), EQR = weighted.mean(EQR, IW, na.rm = TRUE), EQRS = weighted.mean(EQRS, IW, na.rm = TRUE), C = weighted.mean(C, IW, na.rm = TRUE)), .(CriteriaID, UnitID)]
wk7 <- dcast(wk6, UnitID ~ CriteriaID, value.var = c("N","ER","EQR","EQRS","C"))
# Assessment -------------------------------------------------------------------
# Assessment result - UnitID, N, ER, EQR, EQRS, C
wk8 <- wk6[, .(.N, ER = max(ER), EQR = min(EQR), EQRS = min(EQRS), C = mean(C)), (UnitID)] %>% setkey(UnitID)
wk9 <- wk7[wk8, on = .(UnitID = UnitID), nomatch=0]
# Assign Status and Confidence Classes
wk9[, EQRS_Class := ifelse(EQRS >= 0.8, "High",
ifelse(EQRS >= 0.6, "Good",
ifelse(EQRS >= 0.4, "Moderate",
ifelse(EQRS >= 0.2, "Poor","Bad"))))]
wk9[, EQRS_1_Class := ifelse(EQRS_1 >= 0.8, "High",
ifelse(EQRS_1 >= 0.6, "Good",
ifelse(EQRS_1 >= 0.4, "Moderate",
ifelse(EQRS_1 >= 0.2, "Poor","Bad"))))]
wk9[, EQRS_2_Class := ifelse(EQRS_2 >= 0.8, "High",
ifelse(EQRS_2 >= 0.6, "Good",
ifelse(EQRS_2 >= 0.4, "Moderate",
ifelse(EQRS_2 >= 0.2, "Poor","Bad"))))]
wk9[, EQRS_3_Class := ifelse(EQRS_3 >= 0.8, "High",
ifelse(EQRS_3 >= 0.6, "Good",
ifelse(EQRS_3 >= 0.4, "Moderate",
ifelse(EQRS_3 >= 0.2, "Poor","Bad"))))]
wk9[, C_Class := ifelse(C >= 75, "High",
ifelse(C >= 50, "Moderate", "Low"))]
wk9[, C_1_Class := ifelse(C_1 >= 75, "High",
ifelse(C_1 >= 50, "Moderate", "Low"))]
wk9[, C_2_Class := ifelse(C_2 >= 75, "High",
ifelse(C_2 >= 50, "Moderate", "Low"))]
wk9[, C_3_Class := ifelse(C_3 >= 75, "High",
ifelse(C_3 >= 50, "Moderate", "Low"))]
# Write results
fwrite(wk3, file = file.path(outputPath, "Annual_Indicator.csv"))
fwrite(wk5, file = file.path(outputPath, "Assessment_Indicator.csv"))
fwrite(wk9, file = file.path(outputPath, "Assessment.csv"))
# Create plots
#EQRS_Class_colors <- c("#3BB300", "#99FF66", "#FFCABF", "#FF8066", "#FF0000")
EQRS_Class_colors <- c(rgb(119,184,143,max=255), rgb(186,215,194,max=255), rgb(235,205,197,max=255), rgb(216,161,151,max=255), rgb(199,122,112,max=255))
EQRS_Class_limits <- c("High", "Good", "Moderate", "Poor", "Bad")
EQRS_Class_labels <- c(">= 0.8 - 1.0 (High)", ">= 0.6 - 0.8 (Good)", ">= 0.4 - 0.6 (Moderate)", ">= 0.2 - 0.4 (Poor)", ">= 0.0 - 0.2 (Bad)")
#C_Class_colors <- c("#3BB300", "#FFCABF", "#FF0000")
C_Class_colors <- c(rgb(252,231,218,max=255), rgb(245,183,142,max=255), rgb(204,100,23,max=255))
C_Class_limits <- c("High", "Moderate", "Low")
C_Class_labels <- c(">= 75 % (High)", "50 - 74 % (Moderate)", "< 50 % (Low)")
# Assessment map Status + Confidence
wk <- merge(units, wk9, all.x = TRUE)
# Status maps
ggplot(wk) +
ggtitle(label = paste0("Eutrophication Status ", assessmentPeriod)) +
geom_sf(aes(fill = EQRS_Class)) +
scale_fill_manual(name = "EQRS", values = EQRS_Class_colors, limits = EQRS_Class_limits, labels = EQRS_Class_labels)
ggsave(file.path(outputPath, "Assessment_Map_EQRS.png"), width = 12, height = 9, dpi = 300)
ggplot(wk) +
ggtitle(label = paste0("Eutrophication Status ", assessmentPeriod)) +
geom_sf(aes(fill = EQRS_1_Class)) +
scale_fill_manual(name = "EQRS_1", values = EQRS_Class_colors, limits = EQRS_Class_limits, labels = EQRS_Class_labels)
ggsave(file.path(outputPath, "Assessment_Map_EQRS_1.png"), width = 12, height = 9, dpi = 300)
ggplot(wk) +
ggtitle(label = paste0("Eutrophication Status ", assessmentPeriod)) +
geom_sf(aes(fill = EQRS_2_Class)) +
scale_fill_manual(name = "EQRS_2", values = EQRS_Class_colors, limits = EQRS_Class_limits, labels = EQRS_Class_labels)
ggsave(file.path(outputPath, "Assessment_Map_EQRS_2.png"), width = 12, height = 9, dpi = 300)
ggplot(wk) +
ggtitle(label = paste0("Eutrophication Status ", assessmentPeriod)) +
geom_sf(aes(fill = EQRS_3_Class)) +
scale_fill_manual(name = "EQRS_3", values = EQRS_Class_colors, limits = EQRS_Class_limits, labels = EQRS_Class_labels)
ggsave(file.path(outputPath, "Assessment_Map_EQRS_3.png"), width = 12, height = 9, dpi = 300)
# Confidence maps
ggplot(wk) +
ggtitle(label = paste0("Eutrophication Confidence ", assessmentPeriod)) +
geom_sf(aes(fill = C_Class)) +
scale_fill_manual(name = "C", values = C_Class_colors, limits = C_Class_limits, labels = C_Class_labels)
ggsave(file.path(outputPath, "Assessment_Map_C.png"), width = 12, height = 9, dpi = 300)
ggplot(wk) +
ggtitle(label = paste0("Eutrophication Confidence ", assessmentPeriod)) +
geom_sf(aes(fill = C_1_Class)) +
scale_fill_manual(name = "C_1", values = C_Class_colors, limits = C_Class_limits, labels = C_Class_labels)
ggsave(file.path(outputPath, "Assessment_Map_C_1.png"), width = 12, height = 9, dpi = 300)
ggplot(wk) +
ggtitle(label = paste0("Eutrophication Confidence ", assessmentPeriod)) +
geom_sf(aes(fill = C_2_Class)) +
scale_fill_manual(name = "C_2", values = C_Class_colors, limits = C_Class_limits, labels = C_Class_labels)
ggsave(file.path(outputPath, "Assessment_Map_C_2.png"), width = 12, height = 9, dpi = 300)
ggplot(wk) +
ggtitle(label = paste0("Eutrophication Confidence ", assessmentPeriod)) +
geom_sf(aes(fill = C_3_Class)) +
scale_fill_manual(name = "C_3", values = C_Class_colors, limits = C_Class_limits, labels = C_Class_labels)
ggsave(file.path(outputPath, "Assessment_Map_C_3.png"), width = 12, height = 9, dpi = 300)
# Create Assessment Indicator maps
for (i in 1:nrow(indicators)) {
indicatorID <- indicators[i, IndicatorID]
indicatorCode <- indicators[i, Code]
indicatorName <- indicators[i, Name]
indicatorYearMin <- indicators[i, YearMin]
indicatorYearMax <- indicators[i, YearMax]
indicatorMonthMin <- indicators[i, MonthMin]
indicatorMonthMax <- indicators[i, MonthMax]
indicatorDepthMin <- indicators[i, DepthMin]
indicatorDepthMax <- indicators[i, DepthMax]
indicatorYearMin <- indicators[i, YearMin]
indicatorMetric <- indicators[i, Metric]
wk <- wk5[IndicatorID == indicatorID] %>% setkey(UnitID)
wk <- merge(units, wk, by = "UnitID", all.x = TRUE)
# Status map (EQRS)
title <- paste0("Eutrophication Status ", indicatorYearMin, "-", indicatorYearMax)
subtitle <- paste0(indicatorName, " (", indicatorCode, ")", "\n")
subtitle <- paste0(subtitle, "Months: ", indicatorMonthMin, "-", indicatorMonthMax, ", ")
subtitle <- paste0(subtitle, "Depths: ", indicatorDepthMin, "-", indicatorDepthMax, ", ")
subtitle <- paste0(subtitle, "Metric: ", indicatorMetric)
fileName <- gsub(":", "", paste0("Assessment_Indicator_Map_", indicatorCode, "_EQRS", ".png"))
ggplot(wk) +
labs(title = title , subtitle = subtitle) +
geom_sf(aes(fill = EQRS_Class)) +
scale_fill_manual(name = "EQRS", values = EQRS_Class_colors, limits = EQRS_Class_limits, labels = EQRS_Class_labels)
ggsave(file.path(outputPath, fileName), width = 12, height = 9, dpi = 300)
# Temporal Confidence map (TC)
title <- paste0("Eutrophication Temporal Confidence ", indicatorYearMin, "-", indicatorYearMax)
subtitle <- paste0(indicatorName, " (", indicatorCode, ")", "\n")
subtitle <- paste0(subtitle, "Months: ", indicatorMonthMin, "-", indicatorMonthMax, ", ")
subtitle <- paste0(subtitle, "Depths: ", indicatorDepthMin, "-", indicatorDepthMax, ", ")
subtitle <- paste0(subtitle, "Metric: ", indicatorMetric)
fileName <- gsub(":", "", paste0("Assessment_Indicator_Map_", indicatorCode, "_TC", ".png"))
ggplot(wk) +
labs(title = title , subtitle = subtitle) +
geom_sf(aes(fill = TC_Class)) +
scale_fill_manual(name = "TC", values = C_Class_colors, limits = C_Class_limits, labels = C_Class_labels)
ggsave(file.path(outputPath, fileName), width = 12, height = 9, dpi = 300)
# Spatial Confidence map (SC)
title <- paste0("Eutrophication Spatial Confidence ", indicatorYearMin, "-", indicatorYearMax)
subtitle <- paste0(indicatorName, " (", indicatorCode, ")", "\n")
subtitle <- paste0(subtitle, "Months: ", indicatorMonthMin, "-", indicatorMonthMax, ", ")
subtitle <- paste0(subtitle, "Depths: ", indicatorDepthMin, "-", indicatorDepthMax, ", ")
subtitle <- paste0(subtitle, "Metric: ", indicatorMetric)
fileName <- gsub(":", "", paste0("Assessment_Indicator_Map_", indicatorCode, "_SC", ".png"))
ggplot(wk) +
labs(title = title , subtitle = subtitle) +
geom_sf(aes(fill = SC_Class)) +
scale_fill_manual(name = "SC", values = C_Class_colors, limits = C_Class_limits, labels = C_Class_labels)
ggsave(file.path(outputPath, fileName), width = 12, height = 9, dpi = 300)
# Accuracy Confidence Class map (ACC)
title <- paste0("Eutrophication Accuracy Class Confidence ", indicatorYearMin, "-", indicatorYearMax)
subtitle <- paste0(indicatorName, " (", indicatorCode, ")", "\n")
subtitle <- paste0(subtitle, "Months: ", indicatorMonthMin, "-", indicatorMonthMax, ", ")
subtitle <- paste0(subtitle, "Depths: ", indicatorDepthMin, "-", indicatorDepthMax, ", ")
subtitle <- paste0(subtitle, "Metric: ", indicatorMetric)
fileName <- gsub(":", "", paste0("Assessment_Indicator_Map_", indicatorCode, "_ACC", ".png"))
ggplot(wk) +
labs(title = title , subtitle = subtitle) +
geom_sf(aes(fill = ACC_Class)) +
scale_fill_manual(name = "ACC", values = C_Class_colors, limits = C_Class_limits, labels = C_Class_labels)
ggsave(file.path(outputPath, fileName), width = 12, height = 9, dpi = 300)
# Confidence map (C)
title <- paste0("Eutrophication Confidence ", indicatorYearMin, "-", indicatorYearMax)
subtitle <- paste0(indicatorName, " (", indicatorCode, ")", "\n")
subtitle <- paste0(subtitle, "Months: ", indicatorMonthMin, "-", indicatorMonthMax, ", ")
subtitle <- paste0(subtitle, "Depths: ", indicatorDepthMin, "-", indicatorDepthMax, ", ")
subtitle <- paste0(subtitle, "Metric: ", indicatorMetric)
fileName <- gsub(":", "", paste0("Assessment_Indicator_Map_", indicatorCode, "_C", ".png"))
ggplot(wk) +
labs(title = title , subtitle = subtitle) +
geom_sf(aes(fill = C_Class)) +
scale_fill_manual(name = "C", values = C_Class_colors, limits = C_Class_limits, labels = C_Class_labels)
ggsave(file.path(outputPath, fileName), width = 12, height = 9, dpi = 300)
}
# Create Annual Indicator bar charts
for (i in 1:nrow(indicators)) {
indicatorID <- indicators[i, IndicatorID]
indicatorCode <- indicators[i, Code]
indicatorName <- indicators[i, Name]
indicatorUnit <- indicators[i, Units]
indicatorYearMin <- indicators[i, YearMin]
indicatorYearMax <- indicators[i, YearMax]
indicatorMonthMin <- indicators[i, MonthMin]
indicatorMonthMax <- indicators[i, MonthMax]
indicatorDepthMin <- indicators[i, DepthMin]
indicatorDepthMax <- indicators[i, DepthMax]
indicatorYearMin <- indicators[i, YearMin]
indicatorMetric <- indicators[i, Metric]
for (j in 1:nrow(units)) {
unitID <- as.data.table(units)[j, UnitID]
unitCode <- as.data.table(units)[j, Code]
unitName <- as.data.table(units)[j, Description]
title <- paste0("Eutrophication State [ES, CI, N] and Threshold [ET] ", indicatorYearMin, "-", indicatorYearMax)
subtitle <- paste0(indicatorName, " (", indicatorCode, ")", " in ", unitName, " (", unitCode, ")", "\n")
subtitle <- paste0(subtitle, "Months: ", indicatorMonthMin, "-", indicatorMonthMax, ", ")
subtitle <- paste0(subtitle, "Depths: ", indicatorDepthMin, "-", indicatorDepthMax, ", ")
subtitle <- paste0(subtitle, "Metric: ", indicatorMetric, ", ")
subtitle <- paste0(subtitle, "Unit: ", indicatorUnit)
fileName <- gsub(":", "", paste0("Annual_Indicator_Bar_", indicatorCode, "_", unitCode, ".png"))
wk <- wk3[IndicatorID == indicatorID & UnitID == unitID]
if (nrow(wk) > 0) {
ggplot(wk, aes(x = factor(Period, levels = indicatorYearMin:indicatorYearMax), y = ES)) +
labs(title = title , subtitle = subtitle) +
geom_col() +
geom_text(aes(label = N), vjust = -0.25, hjust = -0.25) +
geom_errorbar(aes(ymin = ES - CI, ymax = ES + CI), width = .2) +
geom_hline(aes(yintercept = ET)) +
scale_x_discrete(NULL, factor(indicatorYearMin:indicatorYearMax), drop=FALSE) +
scale_y_continuous(NULL)
ggsave(file.path(outputPath, fileName), width = 12, height = 9, dpi = 300)
}
}
}