-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemep_qaqc_funcs.R
3453 lines (2915 loc) · 127 KB
/
emep_qaqc_funcs.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
### FUNCTIONS USED FOR EMEP QAQC
# COLLATE and CALCULATE FUNCS -------------------------------------------------------
get_auto_meta = function(network = 'aurn', pollutant = 'no2', year = 2018) {
#sites in multiple networks but with different site codes I'm
#aware of. there may be more so add to the vector as needed
DUPLICATED_SITES = c('CD9', 'BL0', 'CD1', 'CHEP', 'TD5', 'NM2', 'NM3', 'TH4')
#pollutants in meta databases are in capitals
pollutant = str_to_upper(pollutant)
network_levs = rev(network)
names(network) = network
if ('kcl' %in% network_levs) {
network = network[str_detect(network, 'kcl', negate = T)] #remove kcl from network and treat separately
#get a list of monitoring stations in London from the londonair website - used to handle
#the kcl network monitors
#be aware that in the kcl network and in londonair datasets PM2.5 is named PM25!
laqn = getMetaLAQN() %>%
as_tibble() %>%
filter(species_code %in% str_remove(pollutant, '\\.')) %>%
dplyr::select(code, poll = species_code)
sites_kcl = importMeta(source = 'kcl', all = T) %>%
left_join(laqn, ., by = 'code') %>%
mutate(network = factor('kcl', levels = network_levs, ordered = T),
.before = code) %>%
dplyr::select(network, code, site, site_type, poll, start_date = OpeningDate,
end_date = ClosingDate, longitude, latitude)
}
#networks = c(aurn = 'aurn', saqn = 'saqn', waqn = 'waqn', ni = 'ni', aqe = 'aqe')
sites = map_dfr(network, ~importMeta(.x, all = T), .id = 'network') %>%
mutate(network = factor(network, levels = network_levs, ordered = T),
end_date = na_if(end_date, 'ongoing'),
end_date = as_datetime(end_date)) %>%
filter(variable %in% pollutant) %>%
rename(poll = variable) %>%
dplyr::select(-Parameter_name, -ratified_to, -zone, -agglomeration, -local_authority)
if ('kcl' %in% network_levs) {
#combine the kcl network with other networks to one tibble
sites = bind_rows(sites, sites_kcl)
}
sites2 = sites %>%
#filter on year, operational sites have end date set to NA
filter((year(start_date) <= year) &
(is.na(end_date) | year(end_date) >= year)) %>%
mutate(poll = str_to_lower(poll)) %>%
#nest on pollutants and monitoring period
group_by(across(-poll:-end_date)) %>%
nest() %>%
rename(poll_info = data) %>%
#and remove duplicate sites that occur in multiple networks
#some sites have a different site code in different networks,
#so need to be removed manually
arrange(code, desc(network)) %>%
distinct(code, .keep_all = T) %>%
filter(!code %in% DUPLICATED_SITES) %>%
#recode site type into 5 main groups (note airport sites are now classified as industrial!)
mutate(site_type_grp = recode_site_type(site_type),
.after = site_type) %>%
ungroup()
sites2
}
get_auto_data = function(site, network, pollutant, start_year, end_year, to_narrow = F) {
#download automatic data from ricardo servers
#make sure that the requested period is defined
if (is.na(start_year) | is.na(end_year)) {
stop('Either start or end of monitoring period is missing')
} else {
year_range = start_year:end_year
if (network == 'waqn') {
vs = importWAQN(site = site, year = year_range)
} else if (network == 'saqn') {
vs = importSAQN(site = site, year = year_range)
} else if (network == 'ni') {
vs = importNI(site = site, year = year_range)
} else if (network == 'aurn') {
vs = importAURN(site = site, year = year_range)
} else if (network == 'aqe') {
vs = openair::importAQE(site = site, year = year_range)
} else if (network == 'kcl') {
vs = importKCL(site = site, year = year_range)
} else {
vs = NULL
}
}
#only process non-empty data frames
if (is.null(vs)) {
print(paste0('Site ', site, ' has no ', pollutant, ' data in ', start_year, ' \nor the data are currently NOT available.'))
return(NULL)
} else {
if ('pm2.5' %in% pollutant) pollutant = c(pollutant, 'pm25')
vs = vs %>%
select(date, code, any_of(str_to_lower(pollutant)))
if ('pm25' %in% names(vs)) vs = rename(vs, pm2.5 = pm25)
if (to_narrow == T) {
vs = vs %>%
pivot_longer(cols = any_of(pollutant), names_to = 'pollutant', values_to = 'conc')
}
}
vs = vs %>%
mutate(code = as.character(code)) # don't want code as factor
vs
}
get_isd_sites = function(year, CC_file = NULL) {
assert_choice(year, choices = 1901:2023)
isd_sites = read_html(str_c('https://www.ncei.noaa.gov/data/global-hourly/access/', year)) %>%
html_elements('a') %>%
html_text() %>%
str_subset('\\.csv') %>%
path_ext_remove()
if (!is.null(CC_file)) {
assert_file_exists(CC_file)
country_codes = read_rds(CC_file)
} else {
f0 = 'https://www1.ncdc.noaa.gov/pub/data/noaa/country-list.txt'
country_codes = read_csv(f0) %>%
set_names('dummy') %>%
separate_wider_delim(cols = dummy, delim = rep(' '),
names = c('country_code', 'country_name')) %>%
distinct()
}
sites_meta = getMeta(plot = F, end.year = 'all') %>%
mutate(code2 = str_remove(code, '-'))
sites_avail = sites_meta %>%
filter(code2 %in% isd_sites) %>%
select(-code2) %>%
left_join(country_codes, by = c('ctry' = 'country_code')) %>%
rename(country_code = ctry) %>%
relocate(country_name, .before = country_code)
sites_avail
}
sample_sites = function(meta_df, type = NULL, selector = NULL, n = NULL) {
#samples sites from a tibble with site meta data
#type - sf, random, stratified, manual, subset, exclude
#selector arg is dependent on type arg
#if type is 'sf' selector must be either an sf polygon(s) or a path to a geospatial file containing such polygons
#if type is 'random' selector is redundant but n (number of sites) must be given
#if type is 'stratified' selector is a name of a grouping column in meta_df and n the number of sites
#if type is 'subset' selector is either 'airport' (extracts airports) or a subsetting expression -e.g. expression(latitude > 50)
#if type is 'manual' selector is either a vector of site codes or a path to an rds file with a dataframe which has a column 'code'
#if type is 'exclude' selector is either a vector of site codes or a path to an rds file with a dataframe which has a column 'code'
assert_choice(type, c('sf', 'random', 'stratified', 'subset', 'manual', 'exclude'), null.ok = T)
if (is.null(type)) {
return(meta_df)
}
if ('sf' %in% type) {
assert(check_class(selector, 'sf'),
check_file_exists(selector))
assert_choice('code', names(meta_df))
meta_df2 = meta_df %>%
st_as_sf(coords = c('longitude', 'latitude'), crs = 4326)
if(file_exists(selector)) {
selector = st_read(selector)
}
if (st_crs(selector) != st_crs(meta_df2)) {
selector = selector %>%
st_transform(crs = st_crs(meta_df2))
}
meta_df2 = meta_df2 %>%
st_filter(selector) %>%
st_drop_geometry()
meta_df = meta_df %>%
semi_join(select(meta_df2, code))
} else if ('random' %in% type) {
assert_count(n, positive = T)
meta_df = meta_df %>%
slice_sample(n = n)
} else if ('stratified' %in% type) {
assert_choice(selector, names(meta_df))
n_groups = n_distinct(meta_df[[selector]])
meta_df = meta_df %>%
slice_sample(n = ceiling(n/n_groups), by = one_of(selector)) %>%
slice_sample(n = n)
} else if ('manual' %in% type) {
assert(check_choice('code', names(meta_df)),
check_file_exists(selector),
check_character(selector))
if (file_exists(selector)) {
selector = read_rds(selector) %>%
pull(code)
}
meta_df = meta_df %>%
filter('code' %in% selector)
} else if ('exclude' %in% type) {
assert(check_choice('code', names(meta_df)),
check_file_exists(selector),
check_character(selector))
if (file_exists(selector)) {
selector = read_rds(selector) %>%
pull(code)
}
meta_df = meta_df %>%
filter(!'code' %in% selector)
} else if ('subset' %in% type) {
if (is.expression(selector)) {
meta_df = meta_df %>%
filter(eval(selector))
} else if('airport' %in% selector) {
meta_df = meta_df %>%
filter(!is.na(call))
} else {
}
}
meta_df
}
extract_wrf_var_point = function(wrf_file_pth, wrf_var, code, xr_index) {
wrf_file = ncpy$Dataset(wrf_file_pth)
#get dttm from file
date = wrf_file %>%
wrf$extract_times(timeidx = wrf$ALL_TIMES)
if (wrf_var == 'ws') {
value = wrf_file %>%
wrf$getvar('uvmet10_wspd_wdir', timeidx = wrf$ALL_TIMES)
value = value$sel(south_north = xr_index[1], west_east = xr_index[0], wspd_wdir = 'wspd')
} else if (wrf_var == 'wd') {
value = wrf_file %>%
wrf$getvar('uvmet10_wspd_wdir', timeidx = wrf$ALL_TIMES)
value = value$sel(south_north = xr_index[1], west_east = xr_index[0], wspd_wdir = 'wdir')
} else {
value = wrf_file %>%
wrf$getvar(wrf_var, timeidx = wrf$ALL_TIMES)
value = value$sel(south_north = xr_index[1], west_east = xr_index[0])
}
value = value %>%
wrf$to_np()
#convert air temp to degC
if(wrf_var == 'T2') {
value = value - 273.15
}
#in case just one datetime redimension the vector to matrix
if(length(date) == 1) {
value = t(value)
}
#in case data for just one site
if (length(code) == 1){
value = t(t(value))
}
#combine date, wrf_var and extracted data into a long tibble
value = value %>%
as_tibble(.name_repair = 'minimal') %>%
set_names(code)
wrf_var = rep(wrf_var, length(date))
dframe = tibble(date, wrf_var, value) %>%
pivot_longer(cols = -c(date, wrf_var), names_to = 'code', values_to = 'value')
}
calculate_wrf_precip = function(wrf_frame) {
#calculates hourly precip in mm from RAINC and RAINCC
wrf_frame = wrf_frame %>%
pivot_wider(id_cols = c(date, code), names_from = wrf_var, values_from = value) %>%
mutate(precip = RAINNC + RAINC,
precip = precip -lag(precip)) %>%
select(-RAINNC, -RAINC) %>%
pivot_longer(cols = c(-date, -code), names_to = 'var', values_to = 'value')
}
compare_file_size = function(test_dir, ref_dir) {
###tests if domains of test and ref match - temporarily disabled because of Tomas's uEMEP directory
# domain = map_chr(c(test_pth, ref_pth), extract_domain_from_fpath)
# if(length(unique(domain)) != 1) {
# stop('Comparing EMEP outputs in two different domains')
# }
if (any(is.na(c(test_dir, ref_dir)))) return(NULL)
d_content = map_dfr(c(test = test_dir, ref = ref_dir), dir_info, .id = 'run') %>%
select(run, path, size)
d_content2 = d_content %>%
filter(str_detect(path, '\\.nc$')) %>%
mutate(path = path_ext_remove(path)) %>%
mutate(fname = str_extract(path, '(\\d{4}_[^\\d{4}]+$)|sites|sondes'),
fname = str_replace(fname, '\\d{4}_?', ''),
size = as.double(size)) %>%
filter(!is.na(fname)) %>%
pivot_wider(id_cols = c(fname), names_from = 'run', values_from = 'size') %>%
mutate(abs_diff = fs_bytes(abs(test - ref)),
rel_diff = round((test - ref)/ref * 100, 1),
test = fs_bytes(test),
ref = fs_bytes(ref))
d_content2
}
read_emep = function(emep_fname, emep_crs, var = 'all', dims = c('i', 'j', 'time'), proxy = T, time_index = NULL) {
#reads emep data from a provided file name - value is a star_proxy object!!!
#crs needs to be given as stars automatically expects Earth to be an ellipsoid
#if var == 'all' it loads those vars which have dimensions set in dims
#can subset on time dimension but only for vars with 2 spatial and 1 time dimension
if (is.null(emep_fname)) return(NULL)
emep_tidync = emep_fname %>%
tidync()
emep_vars = emep_tidync$variable$name
if (all(var != 'all')) {
selected_var = base::intersect(emep_vars, var)
if (length(selected_var) == 0) {
return(NULL)
}
} else {
selected_dims = emep_tidync$dimension %>%
filter(name %in% dims) %>%
pull(id) %>%
sort() %>%
str_c('D', .) %>%
str_c(collapse = ',')
selected_var = emep_tidync$grid %>%
unnest(col = variables) %>%
filter(grid == selected_dims) %>%
pull(variable)
}
emep_data = read_stars(emep_fname, sub = selected_var, proxy = T, RasterIO = list(nXOff = 1, nYOff = 1)) %>%
st_set_crs(emep_crs)
if (!is.null(time_index)) {
if (all(names(dim(emep_data)) == c('x', 'y' ,'time'))) {
emep_data = emep_data[selected_var, , , time_index]
}
}
if (proxy == F) {
emep_data = emep_data %>%
st_as_stars(curvilinear = NULL) #we don't want the output in curvilinear grid
}
emep_data
}
calc_budget = function(stars_object, evp_list) {
#calculates the budget for all vars in stars_object based on parameters in evp_list
budget_list = vector('list', length(names(stars_object)))
for (i in seq_along(names(stars_object))) {
emep_var = names(stars_object)[i]
stars_sub = stars_object %>%
select(all_of(c(emep_var, 'Area_Grid_km2')))
if (emep_var == 'Area_Grid_km2') {
budget_list[[i]] = stars_sub %>%
select(Area_Grid_km2) %>%
as_tibble() %>%
summarise(Mean = as.double(mean(Area_Grid_km2, na.rm = T)))
} else if (evp_list[[emep_var]][['budg_stat']] == 'sum') {
budget_list[[i]] = stars_sub %>%
as_tibble() %>%
mutate(q = .data[[emep_var]] * Area_Grid_km2 * evp_list[[emep_var]][['budg_factor']]) %>%
summarise(Total = as.double(sum(q, na.rm = T)))
} else if (evp_list[[emep_var]][['budg_stat']] == 'mean') {
budget_list[[i]] = stars_sub %>%
as_tibble() %>%
summarise(Mean = as.double(mean(.data[[emep_var]], na.rm = T) * evp_list[[emep_var]][['budg_factor']]))
} else {
stop('budget_stat can be either "mean" or "sum"')
}
budget_list[[i]] = budget_list[[i]] %>%
mutate(Variable = emep_var,
Unit = evp_list[[emep_var]][['budg_units']]) %>%
select(Variable, everything())
}
budget_df = bind_rows(budget_list) %>%
relocate(Unit, .after = last_col())
budget_df
}
collate_obs_mod_nc = function(nc_pth, var_name_lookup, site_code = 'MY1', i_index = NA_integer_,
j_index = NA_integer_, network = 'aurn', var = 'no2') {
#var_name_lookup needs to be format: obs_name = EMEP_var_name (e.g. no2 = 'SURF_ug_NO2')
#network is either one of supported networks from Ricardo servers or a full path to the observation file
nc = nc_open(nc_pth)
nc_date = nc.get.time.series(nc) %>%
as_datetime(tz = 'UTC') %>%
floor_date(unit = 'hour') %>%
tibble() %>%
set_names('date')
nc_year = unique(year(nc_date$date))
var_mod = unname(var_name_lookup[str_to_lower(var)])
mod_data = ncvar_get(nc,
varid = var_mod,
start = c(i_index, j_index, 1), count = c(1, 1,-1)) %>%
as_tibble() %>%
mutate(code = site_code, .before = value) %>%
rename(mod = value) %>%
bind_cols(nc_date, .)
if (str_detect(var_mod, 'ppb_O3')) {#convert ozone to ug/m3
mod_data = mod_data %>%
mutate(mod = mod * 2)
}
if (file_exists(network)) {
#return NULL if pollutant not in the file
obs_data = tryCatch(
error = function(cnd) NULL,
read_csv(network) %>%
select(date, !!var) %>%
rename(obs = !!var)
)
} else {
#return NULL if pollutant not measured at auto site on Ricardo servers
obs_data = tryCatch(
error = function(cnd) NULL,
get_auto_data(site = site_code, network = network, pollutant = str_to_lower(var),
start_year = min(nc_year), end_year = max(nc_year), to_narrow = T) %>%
select(-code) %>%
rename(obs = conc, var = pollutant)
)
}
if (!is.null(obs_data)) {
both = left_join(mod_data, obs_data, by = 'date') %>%
#if missing data in observations there will be na values in code and pollutant columns after joining
#the mutate function makes sure the na values are replaced
mutate(code = !!site_code,
var = !!var) %>%
relocate(mod, .after = obs)
} else {
log_warn('No data for {var} at {site_code}')
both = mod_data %>%
mutate(code = !!site_code,
var = !!var,
obs = NA_real_,
.before = mod)
}
nc_close(nc)
both
}
calc_diff_stars = function(stars1, stars2) {
if (is.null(names(stars1)) || is.null(names(stars2))) {
warn('both stars objects must be named. returning NULL')
return(NULL)
}
stars_diff = tryCatch(
error = function(cnd) {
list(stars1, stars2)
},
c(stars1, stars2) %>%
mutate(abs_diff := !!sym(names(stars1)) - !!sym(names(stars2)),
rel_diff := (!!sym(names(stars1)) - !!sym(names(stars2)))/!!sym(names(stars2)) * 100)
)
if ('abs_diff' %in% names(stars_diff)) {
if (all(near(as.numeric(stars_diff$abs_diff), 0))) {
stars_diff = stars_diff %>%
mutate(abs_diff = NA_real_,
rel_diff = NA_real_)
}
stars_diff = names(stars_diff) %>%
map(select, .data = stars_diff)
}
stars_diff
}
calculate_emep_diff = function(emep_var,
outer_test_fname = NULL, outer_ref_fname = NULL,
inner_test_fname = NULL, inner_ref_fname = NULL,
test_crs = NULL, ref_crs = NULL, time_index = NULL,
run_labels = c('test', 'ref')) {
if (any(is.null(c(test_crs, ref_crs)))) stop('Both test_crs and ref_crs MUST be provided!')
#determine what needs plotting and check if paths are valid
emep_fnames = list(outer_test_fname, outer_ref_fname, inner_test_fname, inner_ref_fname)
emep_stars = pmap(list(emep_fname = emep_fnames, emep_crs = c(test_crs, ref_crs, test_crs, ref_crs)),
read_emep, var = emep_var, proxy = F, time_index = time_index)
if (length(compact(emep_stars)) == 0) return(NULL)
out = vector('list', length = 2)
for (i in 1:2) {
stars1 = emep_stars[[i*2 - 1]]
stars2 = emep_stars[[i*2]]
if (is.null(stars1) || is.null(stars2)) {
out[[i]] = NULL
} else {
names(stars1) = run_labels[1]
names(stars2) = run_labels[2]
stars_diff = tryCatch(
error = function(cnd) {
list(stars1, stars2)
},
c(stars1, stars2) %>%
mutate(abs_diff := !!sym(names(stars1)) - !!sym(names(stars2)),
rel_diff := (!!sym(names(stars1)) - !!sym(names(stars2)))/!!sym(names(stars2)) * 100)
)
if ('abs_diff' %in% names(stars_diff)) {
if (all(near(as.numeric(stars_diff$abs_diff), 0))) {
stars_diff = stars_diff %>%
mutate(abs_diff = NA_real_,
rel_diff = NA_real_)
}
stars_diff = names(stars_diff) %>%
map(select, .data = stars_diff)
}
out[[i]] = stars_diff
names(out)[[i]] = str_c(emep_var, c('outer', 'inner')[i], sep = '_')
}
}
if (all(map_lgl(out, is.null))) {
return(NULL)
} else {
out = compact(out)
out
}
}
calculate_emep_diff2 = function(outer_test_stars = NULL, outer_ref_stars = NULL,
inner_test_stars = NULL, inner_ref_stars = NULL,
run_labels = c('test', 'ref')) {
#extract var name
emep_var = map_chr(compact(list(outer_test_stars, outer_ref_stars, inner_test_stars, inner_ref_stars)), names) %>%
na.omit() %>%
unique()
emep_stars = list(outer_test_stars, outer_ref_stars, inner_test_stars, inner_ref_stars)
out = vector('list', length = 2)
for (i in 1:2) {
stars1 = emep_stars[[i*2 - 1]]
stars2 = emep_stars[[i*2]]
if (is.null(stars1) || is.null(stars2)) {
out[[i]] = NULL
} else {
names(stars1) = run_labels[1]
names(stars2) = run_labels[2]
stars_diff = tryCatch(
error = function(cnd) {
list(stars1, stars2)
},
c(stars1, stars2) %>%
mutate(abs_diff := !!sym(names(stars1)) - !!sym(names(stars2)),
rel_diff := (!!sym(names(stars1)) - !!sym(names(stars2)))/!!sym(names(stars2)) * 100)
)
if ('abs_diff' %in% names(stars_diff)) {
if (all(near(as.numeric(stars_diff$abs_diff), 0))) {
stars_diff = stars_diff %>%
mutate(abs_diff = NA_real_,
rel_diff = NA_real_)
}
stars_diff = names(stars_diff) %>%
map(select, .data = stars_diff)
}
out[[i]] = stars_diff
names(out)[[i]] = str_c(emep_var, c('outer', 'inner')[i], sep = '_')
}
}
out = compact(out)
}
read_RunLog_emissions = function(RunLog_pth) {
#pulls emission tables out of RunLog.out file
t_start = str_which(read_lines(RunLog_pth), 'emissions by countries')
t_end = str_which(read_lines(RunLog_pth), 'road dust emission')
t_lengths = diff(c(t_start, t_end), 1) - 2
read_RunLog_tables = function(s, n) {
t_names = names(read_table(RunLog_pth, skip = s, n_max = 0))
#the following if chunk is needed due to EMEP 4.17 having different RunLog.out formatting
##t_data only needed to know the number of columns
t_data = read_table(RunLog_pth, skip = s + 1, n_max = 0)
if (length(t_data) == length(t_names) + 1) {
CC_index = str_which(t_names, 'CC')
t_names = t_names %>%
append('Land', after = CC_index)
}
t = read_table(RunLog_pth, skip = s + 1, n_max = n,
col_names = t_names, col_types = cols(CC = 'c', Land = 'c', .default = 'd'))
if ('TOTAL' %in% t$CC) {
t[t$CC == 'TOTAL', 'Land'] = 'TOT'
t[t$CC == 'TOTAL', 'CC'] = '999'
}
if ('EU' %in% t$Land) {
t[t$Land == 'EU', 'CC'] = '998'
}
if ('EMTAB' %in% names(t)) t = select(t, -EMTAB)
t = t %>%
mutate(CC = parse_integer(CC))
}
RL_tables = map2_dfr(t_start, t_lengths, read_RunLog_tables) %>%
group_by(CC, Land) %>%
summarise(across(.cols = everything(), .fns = ~sum(.x, na.rm = T))) %>%
ungroup()
RL_tables
}
compare_run_emissions = function(test_dir, ref_dir, save_file = T, mbs_table_fname = NA) {
MBS_files = c(test_dir,ref_dir) %>%
path('MassBudgetSummary.txt') %>%
set_names(c('test', 'ref'))
MBS_data = MBS_files %>%
map_dfr(read_table, skip = 1, col_names = T, .id = 'run') %>%
select(run, species = Spec, emission = emis) %>%
pivot_wider(id_cols = species, names_from = run, values_from = emission) %>%
mutate(abs_diff = test - ref,
rel_diff = abs_diff/ref*100)
if (save_file == T) {
# - determine output filename based on whether it is an outer or inner domain file
stopifnot('output file name must be provided' = !is.na(mbs_table_fname))
out_fname = paste0(map_chr(path_split(test_dir), last), '_', mbs_table_fname)
write_lines(paste0('# Test file: ', MBS_files[1]), file = path(tables_pth_out, out_fname))
write_lines(paste0('# Ref file: ', MBS_files[2]), path(tables_pth_out, out_fname), append = T)
write_lines(paste0('#', str_c(rep('-', 50), collapse = '-')), path(tables_pth_out, out_fname), append = T)
write_csv(MBS_data, path(tables_pth_out, out_fname), na = '', col_names = T, append = T)
}
MBS_data
}
compare_inv_mod_emissions = function(model_run_dir, emiss_inv_pth, save_file = T) {
if (!file_exists(emiss_inv_pth)) {
stop('Emission Inventory filepath is not valid.')
}
runlog_file = read_lines(path(model_run_dir, 'RunLog.out'))
mod_year = runlog_file[str_detect(runlog_file, 'emissions by countries')] %>%
str_extract('\\d{4}') %>%
as.integer() %>%
unique()
stopifnot('Could not determine the model emission year - check RunLog.out' = length(mod_year) == 1)
# - determine output filename based on whether it is an outer or inner domain file
out_fname = paste0(map_chr(path_split(model_run_dir), last), '_', INV_MOD_EMISS_TABLE_FNAME)
runlog_emiss = model_run_dir %>%
path('RunLog.out') %>%
read_RunLog_emissions() %>%
mutate(type = 'model')
inventory = read_delim(emiss_inv_pth, comment = '#', delim = ';',
col_names = c('Land', 'year', 'sector', 'pollutant', 'unit', 'value'),
col_types = 'cicccd') %>%
filter(year == mod_year) %>%
select(Land, pollutant, value) %>%
pivot_wider(id_cols = Land, names_from = pollutant, values_from = value) %>%
rename(co = CO, nh3 = NH3, voc = NMVOC, nox = NOx, pm25 = PM2.5, pmco = PMcoarse, sox = SOx) %>%
mutate(type = 'inventory')
merged = bind_rows(inventory, runlog_emiss) %>%
group_by(Land) %>%
filter(n() > 1) %>%
ungroup() %>%
pivot_longer(cols = co:sox, names_to = 'pollutant', values_to = 'emiss') %>%
pivot_wider(id_cols = c(Land, pollutant), names_from = type, values_from = emiss) %>%
mutate(abs_diff = model - inventory,
rel_diff = abs_diff/inventory*100) %>%
arrange(Land)
if (save_file == T) {
write_lines(paste0('# EMEP file: ', path(model_run_dir, 'RunLog.out')), file = path(tables_pth_out, out_fname))
write_lines(paste0('#', str_c(rep('-', 50), collapse = '-')), path(tables_pth_out, out_fname), append = T)
write_csv(merged, path(tables_pth_out, out_fname), na = '', col_names = T, append = T)
}
merged
}
summarise_mobs = function(mobs_lframe, var = 'all', avg_time = 'day',
summary_stat = 'mean', data_thresh = 75, drop_na = T) {
#mobs_lframe is mobs dataframe in the long format
if (drop_na == T) {
mobs = mobs_lframe %>%
mutate(mod = if_else(is.na(obs), NA_real_, mod))
} else {
mobs = mobs_lframe
}
mobs = mobs %>%
timeAverage(avg.time = avg_time, data.thresh = data_thresh, type = c('code', 'var'), statistic = summary_stat) %>%
ungroup() %>%
mutate(across(where(is.factor), ~as.character(.x)))
if (var != 'all') {
mobs = mobs %>%
filter(var %in% !!var)
}
mobs
}
calculate_modstats = function(dframe, modstats = MODSTATS_STATS, type = 'default', pretty_format = T) {
#workaround for modStats crashing when calculating r if n < 3
#if pretty_format == T the output is rounded to two or one decimal place depending on stat
if(is.null(type)) type = 'default' #modstats doesn't accept NULL in type
type = compact(type)
if ('r' %in% modstats) {
modstats2 = setdiff(modstats, 'r')
modstats2 = c('n', modstats2) %>% #make sure n is in modstats2
unique()
mobs_stats = modStats(dframe, statistic = modstats2, type = type)
ms_var = mobs_stats %>%
group_by(across(all_of(type))) %>%
filter(n > 2) %>%
ungroup() %>%
select(all_of(type))
if (nrow(ms_var) > 0) {
mobs_stats = dframe %>%
semi_join(ms_var) %>%
modStats(statistic = 'r', type = type) %>%
left_join(mobs_stats, .) %>%
mutate(across(where(is.factor), ~as.character(.x)))
}
}
if (pretty_format == T) {
mobs_stats = mobs_stats %>%
mutate(across(any_of(c('FAC2', 'NMB', 'r')), ~round(.x, 2)),
across(any_of(c('MB', 'RMSE')), ~round(.x, 1)),
across(any_of(c('p', 'P')), ~round(.x, 4)))
}
mobs_stats
}
add_ox = function(site_dframe, df_format = c('long', 'wide'), units = 'ug/m3') {
#adds ox concentrations to the dataframe if both no2 and o3 (must be in ug/m3) are present
if (all(df_format == 'wide')) {
site_dframe = mobs_to_long(site_dframe)
}
if (all(c('no2', 'o3') %in% unique(site_dframe$var))) {
site_dframe_ox = site_dframe %>%
filter(var %in% c('no2', 'o3')) %>%
pivot_wider(id_cols = c(date, code), names_from = var, values_from = c(obs, mod))
if (units == 'ug/m3') {
site_dframe_ox = site_dframe_ox %>%
mutate(var = 'ox',
obs = obs_o3 + obs_no2,
mod = mod_o3 + mod_no2) %>%
dplyr::select(date, code, var, obs, mod)
} else if (units == 'ppb') {
site_dframe_ox = site_dframe_ox %>%
mutate(var = 'ox(ppb)',
obs = obs_o3/2 + obs_no2/1.9125,
mod = mod_o3/2 + mod_no2/1.9125) %>%
dplyr::select(date, code, var, obs, mod)
} else {
stop('Units for Ox calculation can either be "ppb" or "ug/m3"')
}
site_dframe = site_dframe %>%
bind_rows(site_dframe_ox) %>%
distinct() %>%
arrange(date)
} else {
}
site_dframe
}
my_importNOAA = function(code, year, pth = NULL) {
# function to supress timeAverage printing
# (can't see option to turn it off)
quiet <- function(x) {
sink(tempfile())
on.exit(sink())
invisible(force(x))
}
## location of data
file.name <- paste0(
"https://www.ncei.noaa.gov/data/global-hourly/access/",
year, "/", gsub(pattern = "-", "", code), ".csv"
)
# suppress warnings because some fields might be missing in the list
# Note that not all available data is returned - just what I think is most useful
met_data <- try(suppressWarnings(read_csv(
file.name,
col_types = cols_only(
STATION = col_character(),
DATE = col_datetime(format = ""),
SOURCE = col_double(),
LATITUDE = col_double(),
LONGITUDE = col_double(),
ELEVATION = col_double(),
NAME = col_character(),
REPORT_TYPE = col_character(),
CALL_SIGN = col_double(),
QUALITY_CONTROL = col_character(),
WND = col_character(),
CIG = col_character(),
VIS = col_character(),
TMP = col_character(),
DEW = col_character(),
SLP = col_character(),
AA1 = col_character(),
AW1 = col_character(),
GA1 = col_character(),
GA2 = col_character(),
GA3 = col_character()
),
progress = FALSE
)), silent = TRUE
)
if (class(met_data)[1] == "try-error") {
message(paste0("Missing data for site ", code, " and year ", year))
met_data <- NULL
return()
}
met_data <- rename(met_data,
code = STATION,
station = NAME,
date = DATE,
latitude = LATITUDE,
longitude = LONGITUDE,
elev = ELEVATION
)
met_data$code <- code
# separate WND column
if ("WND" %in% names(met_data)) {
met_data <- separate(met_data, WND, into = c("wd", "wd_qc", "wo_tc", "ws", "ws_qc"))
met_data <- mutate(met_data,
across(c(wd, wd_qc, ws, ws_qc), ~as.numeric(.x)),
wd = if_else(wd == 999, NA, wd),
ws = if_else(ws == 9999, NA, ws),
ws = ws / 10
)
}
# separate TMP column
if ("TMP" %in% names(met_data)) {
met_data <- separate(met_data, TMP, into = c("air_temp", "air_temp_qc"), sep = ",")
met_data <- mutate(met_data,
air_temp = as.numeric(air_temp),
air_temp = if_else(air_temp == 9999, NA, air_temp),
air_temp = air_temp / 10
)
}
# separate DEW column
if ("DEW" %in% names(met_data)) {
met_data <- separate(met_data, DEW, into = c("dew_point", "dew_qc"), sep = ",")
met_data <- mutate(met_data,
dew_point = as.numeric(dew_point),
dew_point = if_else(dew_point == 9999, NA, dew_point),
dew_point = dew_point / 10
)
}
# separate SLP column
if ("SLP" %in% names(met_data)) {
met_data <- separate(met_data, SLP,
into = c("atmos_pres", "pres_qc"), sep = ",",
fill = "right"
)
met_data <- mutate(met_data,
atmos_pres = as.numeric(atmos_pres),
atmos_pres = if_else(atmos_pres %in% c(99999, 999999), NA, atmos_pres),
atmos_pres = atmos_pres / 10
)
}
## relative humidity - general formula based on T and dew point
met_data$RH <- 100 * ((112 - 0.1 * met_data$air_temp + met_data$dew_point) /
(112 + 0.9 * met_data$air_temp))^8
# PRECIP AA1
if ("AA1" %in% names(met_data)) {
met_data <- separate(met_data, AA1,
into = c("precip_code", "precip_raw", "precip_cc", "precip_qc"),
sep = ","
)
met_data <- mutate(met_data,
precip_raw = as.numeric(precip_raw),
precip_raw = if_else(precip_raw == 9999, NA, precip_raw),
precip_raw = precip_raw / 10,
precip_code = if_else(precip_code =='99', NA, precip_code)
)
}
## select the variables we want
met_data <- select(met_data, any_of(c(
"date", "code", "report_type" = "REPORT_TYPE",
"ws", "wd", "wo_tc", "wd_qc",
"air_temp", "air_temp_qc",
"atmos_pres", "pres_qc",
"dew_point", "dew_qc", "RH",
"precip_code", "precip_raw",
"precip_cc", "precip_qc"
)))
if (!is.null(pth)) {
write_rds(met_data, pth)
}
met_data
}
clean_noaa = function(noaa_dframe) {
#filters out problematic data based on quality flags
#please see isd_format_document.pdf for flag explanation
noaa_dframe = noaa_dframe %>%
mutate(wd = if_else(wd_qc %in% c(1, 5), wd, NA),
wd = if_else(wo_tc %in% c('C', 'N', 'V', '9'), wd, NA),
ws = if_else(wd_qc %in% c(1, 5), ws, NA),
air_temp = if_else(air_temp_qc %in% c('1', '5'), air_temp, NA),
dew_point = if_else(dew_qc %in% c('1', '5'), dew_point, NA),
atmos_pres = if_else(pres_qc %in% c('1', '5'), atmos_pres, NA),
RH = if_else(!(is.na(air_temp) | is.na(dew_point)), RH, NA))
if ('precip_code' %in% names(noaa_dframe)) {
noaa_dframe = noaa_dframe %>%
mutate(precip_raw = if_else(precip_qc %in% c('1', '5') & precip_cc %in% c('2', '3', '9') & !precip_code %in% c('00', '99'), precip_raw, NA),
precip_code = if_else(precip_qc %in% c('1', '5') & precip_cc %in% c('2', '3', '9') & !precip_code %in% c('00', '99'), precip_code, NA))
}
noaa_dframe = noaa_dframe %>%
mutate(obs_minute = minute(date), .after = report_type) %>%
select(-any_of(c('wo_tc', 'wd_qc', 'air_temp_qc', 'pres_qc', 'dew_qc', 'precip_cc', 'precip_qc')))
noaa_dframe
}
assess_noaa = function(noaa_dframe) {