-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmisc_behr_v3_validation.m
3996 lines (3425 loc) · 200 KB
/
misc_behr_v3_validation.m
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
classdef misc_behr_v3_validation
%UNTITLED3 Summary of this class goes here
% Detailed explanation goes here
properties(Constant = true)
behr_v2_dir = '/Volumes/share-sat/SAT/BEHR/BEHR_Files_v2-1C';
wrf_v2_dir = '/Volumes/share-sat/SAT/BEHR/Monthly_NO2_Profiles';
gcas_dir = '/Volumes/share2/USERS/LaughnerJ/CampaignRaw/DISCOVER-AQ_TX/B200/GCAS-SAO';
plot_colors = struct('aircraft', struct('raw', [0.5 0.5 0.5], 'avg', 'k'),... % black and grey for the aircraft data
'v2', struct('raw', 'g', 'avg', [0 0.5 0]),... % greens for version 2
'monthly', struct('raw', [1 0.75 0], 'avg', 'r'),... % red and orange for the monthly profiles
'daily', struct('raw', 'c', 'avg', 'b')); % blue and cyan for the daily profiles
plot_markers = struct('aircraft', struct('raw', '.', 'avg', 'o', 'filled', false),...
'v2', struct('raw', '.', 'avg', '+', 'filled', false),...
'monthly', struct('raw', '.', 'avg', 's', 'filled', true),...
'daily', struct('raw', '.', 'avg', 'd', 'filled', false));
plot_wrf_prof_legend_names = struct('aircraft', 'Aircraft', 'v2', 'V2', 'monthly', 'Monthly', 'daily', 'Daily');
profile_extend_methods = {'wrf','geos','extrap'};
discover_campaigns = {'discover_md','discover_ca','discover_tx','discover_co'};
end
methods(Static = true)
%%%%%%%%%%%%%%%%%%%%%%%%%
% Property-like Methods %
%%%%%%%%%%%%%%%%%%%%%%%%%
function value = my_dir()
value = fileparts(mfilename('fullpath'));
end
function value = validation_root_dir()
value = fullfile(misc_behr_v3_validation.my_dir, 'Workspaces', 'Validation');
end
function value = gc_data_path()
value = fullfile(misc_behr_v3_validation.validation_root_dir, 'GEOS-Chem-Monthly-Data');
end
function value = profile_comp_file(extend_method, directory)
E = JLLErrors;
narginchk(1,2);
if nargin < 2 || isempty(directory)
directory = fullfile(misc_behr_v3_validation.validation_root_dir, 'VCD-Comparison');
end
extend_method = opt_ask_multichoice('Which profile extension method to use?', misc_behr_v3_validation.profile_extend_methods, extend_method, 'extend_method', 'list', true);
value = fullfile(directory, sprintf('profile-structs-%s.mat', extend_method));
end
function value = pandora_comp_file(directory)
if nargin < 1 || isempty(directory)
directory = fullfile(misc_behr_v3_validation.validation_root_dir, 'VCD-Comparison');
end
value = fullfile(directory, 'pandora-structs.mat');
end
function value = gcas_comp_file()
value = fullfile(misc_behr_v3_validation.validation_root_dir, 'VCD-Comparison', 'gcas-structs.mat');
end
function value = gcas_vec_comp_file()
value = fullfile(misc_behr_v3_validation.validation_root_dir, 'VCD-Comparison', 'gcas-vec-structs.mat');
end
function value = scd_comp_dir()
value = fullfile(misc_behr_v3_validation.validation_root_dir, 'SCD-Wind-Comparisons');
if ~exist(value, 'dir')
mkdir(value)
end
end
function value = scd_comp_file(is_partial)
if ~exist('is_partial', 'var') || ~is_partial
partial_str = '';
else
partial_str = '_partial';
end
value = fullfile(misc_behr_v3_validation.scd_comp_dir, sprintf('scd_daily_%s%s.mat', datestr(now, 'yyyy-mm-dd_HH-MM-SS'), partial_str));
end
function value = wrf_comp_file()
value = fullfile(misc_behr_v3_validation.validation_root_dir, 'Profile-Comparison', 'wrf-match-structs.mat');
end
function value = pres_comp_file()
value = fullfile(misc_behr_v3_validation.validation_root_dir, 'Error-Analysis', 'pres-comp.mat');
end
function value = acarreta_cldpres_error_raw_file()
value = fullfile(misc_behr_v3_validation.validation_root_dir, 'Error-Analysis', 'AcarrataCldPresUncert.txt');
end
function value = wrf_data_dir()
value = fullfile(misc_behr_v3_validation.validation_root_dir, 'WRF');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Interactive methods for getting parameters %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function extend_method = get_profile_extend_method(extend_method)
allowed_methods = misc_behr_v3_validation.profile_extend_methods;
if nargin < 1 || isempty(extend_method)
extend_method = ask_multichoice('Which profile extension method to use?', allowed_methods, 'list', true);
elseif ~ismember(extend_method, allowed_methods)
E.badinput('EXTEND_METHOD must be one of: %s', strjoin(allowed_methods, ', '));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Generative validation methods %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function insitu_comparison = generate_vcd_comparison_structs(varargin)
E = JLLErrors;
p = inputParser;
p.addParameter('data_source', '');
p.addParameter('extend_method', '');
p.addParameter('v3_dir', '');
p.addParameter('v2_dir', '');
p.addParameter('do_save', nan);
p.addParameter('overwrite', nan);
p.parse(varargin{:});
pout = p.Results;
data_source = pout.data_source;
profile_extend_method = pout.extend_method;
behr_v3_dir = pout.v3_dir;
behr_v2_dir = pout.v2_dir;
do_save = pout.do_save;
do_overwrite = pout.overwrite;
allowed_data_sources = {'aircraft', 'pandora'};
if isempty(data_source)
data_source = ask_multichoice('Which data source to use?', allowed_data_sources, 'list', true);
elseif ~ismember(data_source, allowed_data_sources)
E.badinput('DATA_SOURCE must be one of: %s', strjoin(allowed_data_sources, ', '));
end
if strcmpi(data_source, 'aircraft')
profile_extend_method = misc_behr_v3_validation.get_profile_extend_method(profile_extend_method);
end
if isnan(do_save)
do_save = ask_yn('Save the comparison files generated?');
elseif ~isscalar(do_save) || ~islogical(do_save)
E.badinput('DO_SAVE must be a scalar logical');
end
if do_save
if strcmpi(data_source, 'aircraft')
comparison_save_name = misc_behr_v3_validation.profile_comp_file(profile_extend_method);
elseif strcmpi(data_source, 'pandora')
comparison_save_name = misc_behr_v3_validation.pandora_comp_file;
end
if exist(comparison_save_name, 'file')
if isnan(do_overwrite)
do_overwrite = ask_yn(sprintf('%s exists. Overwrite?', comparison_save_name));
end
if ~do_overwrite
insitu_comparison = [];
fprintf('%s exists and ''overwrite'' is false. Aborting.\n', comparison_save_name);
return
end
end
end
versions = {'v2','v3'};
regions = {'us'};
prof_modes = {'monthly', 'daily'};
insitu_comparison = struct();
for v=1:numel(versions)
if strcmpi(versions{v}, 'v3')
n_regions = numel(regions);
n_profs = numel(prof_modes);
% The proper version strings won't work as field names,
% so we map the "versions" version name to the proper
% one here.
behr_vers = 'v3-0B';
else
n_regions = 1;
n_profs = 1;
behr_vers = 'v2-1C';
end
version_comp = struct();
for r=1:n_regions
for p=1:n_profs
if strcmpi(versions{v}, 'v3')
if isempty(behr_v3_dir)
behr_dir = behr_paths.BEHRMatSubdir(regions{r}, prof_modes{p});
else
behr_dir = fullfile(behr_v3_dir, lower(prof_modes{p}));
end
behr_prefix = regexp(behr_filename(today, prof_modes{p}, regions{r}), 'OMI_BEHR.*(?=_v\d-\d[A-Z]_\d\d\d\d\d\d\d\d)', 'match', 'once');
wrf_prof_mode = ''; % an empty string tell verify_sat_vs_aircraft to determine the profile mode from the BEHR Data structure
else
if isempty(behr_v2_dir)
behr_dir = misc_behr_v3_validation.behr_v2_dir;
else
behr_dir = behr_v2_dir;
end
behr_prefix = 'OMI_BEHR';
wrf_prof_mode = 'monthly'; % verify_sat_vs_aircraft can read the BEHRProfileMode field in Data to determine which profiles to use, but the v2 files don't have that.
end
if strcmpi(data_source, 'aircraft')
% Set up the necessary inputs for comparing
% against aircraft data
% First we do the four DISCOVER campaigns, which are nice
% because they are geared towards satellite validation with
% spirals clearly marked in the data.
spiral_campaigns = {'discover_md', 'discover_ca', 'discover_tx', 'discover_co'};
other_campaigns = {'seac4rs', 'dc3', 'arctas_carb', 'intex_b', 'soas'};
% For each campaign that doesn't identify the
% profiles in the data, we need to specify which
% of the precreated range files that identify
% profiles by the UTC ranges to use.
range_files = {'SEAC4RS_Profile_Ranges_Std.mat',...
'DC3_Profile_Ranges_Std.mat',...
'ARCTAS-CA Altitude Ranges Exclusive 3.mat',...
'INTEXB_Profile_UTC_Ranges.mat',...
'SOAS_Profile_UTC_Ranges.mat'};
time_windows = [1.5, 3]; % how far away from satellite overpass (in hours) the profile is allowed to be
behr_comp = struct();
all_campaigns = [spiral_campaigns, other_campaigns];
campaign_range_files = [repmat({''}, size(spiral_campaigns)), range_files];
% Specify whether to use the LIF or
% NCAR/chemiluminesnce/non-LIF NO2 measurement.
no2_fields = {'no2_lif','no2_lif','no2_lif','no2_lif','no2_lif','no2_lif','no2_lif','no2_lif','no2_ncar'};
elseif strcmpi(data_source, 'pandora')
% Right now I only have Pandora data for the
% four DISCOVER campaigns.
all_campaigns = {'discover_md','discover_ca','discover_tx','discover_co'};
time_windows = [0.25 0.5 1];
else
E.notimplemented('No input settings for data source = %s', data_source);
end
for a=1:numel(all_campaigns)
campaign = struct();
for b=1:numel(time_windows)
[~, time_fieldname] = misc_behr_v3_validation.format_profile_time_range(time_windows(b));
if strcmpi(data_source, 'aircraft')
all_profs_final = misc_behr_v3_validation.make_profile_vcd_comparison_for_one_campaign(all_campaigns{a}, prof_modes{p}, behr_dir, behr_prefix, behr_vers, campaign_range_files{a}, no2_fields{a}, time_windows(b), profile_extend_method, wrf_prof_mode);
elseif strcmpi(data_source, 'pandora')
all_profs_final = misc_behr_v3_validation.make_pandora_vcd_comparison_for_one_campaign(all_campaigns{a}, prof_modes{p}, behr_dir, behr_prefix, behr_vers, time_windows(b));
else
E.notimplemented('No validation method defined for data source = %s', data_source);
end
campaign.(time_fieldname) = all_profs_final;
end
behr_comp.(all_campaigns{a}) = campaign;
end
fn = sprintf('%s_%s', regions{r}, prof_modes{p});
version_comp.(fn) = behr_comp;
end
end
insitu_comparison.(versions{v}) = version_comp;
end
if do_save
save(comparison_save_name, '-struct', 'insitu_comparison');
end
end
function all_profs_final = make_pandora_vcd_comparison_for_one_campaign(campaign, prof_mode, behr_dir, behr_prefix, behr_vers, time_window)
comparison_params = {'behr_dir', behr_dir,...
'behr_prefix', behr_prefix,...
'behr_version', behr_vers,...
'behr_prof_mode', prof_mode,...
'time_range', time_window};
all_profs_final = run_pandora_verification(campaign, comparison_params{:});
end
function all_profs_final = make_profile_vcd_comparison_for_one_campaign(campaign, prof_mode, behr_dir, behr_prefix, behr_vers, campaign_range_file, no2_field, time_window, extension_mode, wrf_prof_mode)
comparison_params = {'behr_dir', behr_dir,...
'behr_prefix', behr_prefix,...
'behr_version', behr_vers,...
'utc_range_file', campaign_range_file,...
'no2_field', no2_field,...
'DEBUG_LEVEL',1,...
'time_range', time_window,...
'wrf_prof_mode', wrf_prof_mode,...
'gc_data_dir', misc_behr_v3_validation.gc_data_path(),...
'gc_data_year', 2012,...
'gc_file_pattern', 'ts_12_14_satellite.%savg.nc',...
'gc_file_date_fmt', 'yyyymm',...
'prof_extension', extension_mode,...
'match_bl_only', 3,...
'min_height', 1,... % added b/c some SEAC4RS profiles are very short, causing issues with the extrapolation
};
try
[all_profs_final, all_profs_detail] = run_insitu_verification(campaign, prof_mode, comparison_params{:});
all_profs_final.details = all_profs_detail;
catch err
if strcmp(err.identifier, 'call_verify:file_not_found')
% The daily product will not have
% data for some days which causes
% an error in
% Run_Spiral_Verification.
all_profs_final = [];
fprintf(err.message);
else
rethrow(err);
end
end
end
function [times, time_fieldname] = format_profile_time_range(win)
base_time = datenum('2000-01-01 13:30:00');
start_time = base_time - win/24;
end_time = base_time + win/24;
times = {datestr(start_time, 'HH:MM'), datestr(end_time, 'HH:MM')};
time_fieldname = sprintf('t%s_%s', datestr(start_time, 'HHMM'), datestr(end_time, 'HHMM'));
end
function [gcas_comparison, gcas_comparison_vec] = generate_gcas_comparison_struct(do_save)
E = JLLErrors;
if ~exist('do_save', 'var')
do_save = ask_yn('Save the comparison files generated?');
elseif ~isscalar(do_save) || ~islogical(do_save)
E.badinput('DO_SAVE must be a scalar logical');
end
versions = {'v2','v3'};
regions = {'us'};
prof_modes = {'monthly', 'daily'};
sat_fields = {'BEHRColumnAmountNO2Trop', 'ColumnAmountNO2Trop'}; % can add VisOnly later if desired
all_campaigns = {'discover_tx'};
time_windows = [1.5, 3];
gcas_comparison = struct();
gcas_comparison_vec = struct();
for v=1:numel(versions)
if strcmpi(versions{v}, 'v3')
n_regions = numel(regions);
n_profs = numel(prof_modes);
else
n_regions = 1;
n_profs = 1;
end
version_comp = struct();
version_comp_vec = struct();
for r=1:n_regions
for p=1:n_profs
if strcmpi(versions{v}, 'v3')
behr_dir = behr_paths.BEHRMatSubdir(regions{r}, prof_modes{p});
else
behr_dir = misc_behr_v3_validation.behr_v2_dir;
end
behr_comp = struct();
behr_comp_vec = struct();
for a=1:numel(all_campaigns)
campaign = struct();
campaign_vec = struct();
for b=1:numel(time_windows)
[~, time_fn] = misc_behr_v3_validation.format_profile_time_range(time_windows(b));
% Construct the options list
opts_list = {'campaign', all_campaigns{a},...
'behr_dir', behr_dir,...
'vectorize', false,...
'cloud_prod', 'omi',...
'cloud_frac_max', 0.2,...
'row_anomaly', 'XTrackFlags',...
'sat_fields', sat_fields,...
'time_window', time_windows(b)};
try
campaign.(time_fn) = run_gcas_verification(opts_list{:});
campaign_vec.(time_fn) = vectorize_gcas_matches(campaign.(time_fn));
catch err
if strcmp(err.identifier, 'load_behr_file_for_gcas:file_not_found')
campaign.(time_fn) = [];
campaign_vec.(time_fn) = [];
else
rethrow(err)
end
end
end
behr_comp.(all_campaigns{a}) = campaign;
behr_comp_vec.(all_campaigns{a}) = campaign_vec;
end
fn = sprintf('%s_%s', regions{r}, prof_modes{p});
version_comp.(fn) = behr_comp;
version_comp_vec.(fn) = behr_comp_vec;
end
end
gcas_comparison.(versions{v}) = version_comp;
gcas_comparison_vec.(versions{v}) = version_comp_vec;
end
if do_save
save(misc_behr_v3_validation.gcas_comp_file, '-struct', 'gcas_comparison');
save(misc_behr_v3_validation.gcas_vec_comp_file, '-struct', 'gcas_comparison_vec');
end
end
function generate_profile_comparison_struct(varargin)
% This will generate a structure containing WRF data matched to
% individual DISCOVER profiles, as well as information about
% the OMI overpass time vs. the profile time
%
% The hierarchy of the structure will be:
% profile type (daily, monthly, or version 2)
% campaign
% pXXXXXX (XXXXXX is the profile number)
% profdate (average profile UTC datetime)
% nearest OMI overpass (in space) time
% match
p = inputParser;
p.addParameter('do_save', nan);
% By default, we want to restrict the campaign average profiles
% to just the 1.5 hours before or after the standard OMI
% overpass of 1:30 pm.
p.addParameter('avg_prof_lst_range', [12, 15]);
p.parse(varargin{:});
pout = p.Results;
do_save = pout.do_save;
avg_prof_lst_range = pout.avg_prof_lst_range;
if isnan(do_save)
do_save = ask_yn('Save the resulting match structures?');
end
profile_types = {'daily', 'monthly', 'v2'};
campaigns = {'seac4rs', 'soas', 'dc3', 'discover_md', 'discover_ca', 'discover_tx', 'discover_co'};
%campaigns = {'discover_ca'};
% Loop through each campaign, load each merge file, find each
% profile, extract the necessary fields to match up the
% aircraft and WRF data, and pass it to match_wrf2aircraft to
% do the actual matching
profile_comp_struct = make_empty_struct_from_cell(profile_types);
for a=1:numel(campaigns)
% List the merge files
[merge_names, ~, merge_dir] = merge_field_names(campaigns{a});
merges = dirff(fullfile(merge_dir, '*.mat'));
all_merge_wrf_dirs = make_empty_struct_from_cell(profile_types, {{}});
for b=1:numel(merges)
M = load(merges(b).name);
% Make raw structures for each profile that is listed
% in the file. This is only used when matching
% individual profiles, so if we're working on a
% campaign that does not include individual profiles
% (e.g. DC3) then can (and must) skip this part, since
% the Raws structure relies on the profile numbers
% field. We can also skip calculating the nearest OMI
% time, since that might be time consuming and it's
% only needed for matching/filtering individual
% profiles.
if ~isempty(merge_names.profile_numbers)
Raws = misc_behr_v3_validation.make_raw_struct(M.Merge, merge_names, campaigns{a});
profile_fns = fieldnames(Raws);
% Calculate the OMI overpass time from the v3 BEHR
% files, getting the closest overpass in space. We can
% use this to decide if a profile is important for the
% retrieval
OmiTimes = misc_behr_v3_validation.calc_nearest_omi_times(M.Merge.metadata.date, Raws);
end
for p=1:numel(profile_types)
% Get the right WRF directory for the given profile
% type
if strcmpi(profile_types{p}, 'v2')
wrf_dir = misc_behr_v3_validation.wrf_v2_dir;
else
try
wrf_dir = find_wrf_path('us', profile_types{p}, M.Merge.metadata.date);
catch err
if strcmp(err.identifier, 'find_wrf_path:dir_does_not_exist')
continue
else
rethrow(err);
end
end
end
if ~ismember(wrf_dir, all_merge_wrf_dirs.(profile_types{p}))
all_merge_wrf_dirs.(profile_types{p}){end+1} = wrf_dir;
end
% Only DISCOVER campaigns have profile numbers.
% Other campaigns (e.g. DC3) didn't do specific
% satellite verification spirals, so we can't
% compare individual profiles (at least not as
% easily). So now that we've gathered the WRF
% directories that we need, skip the individual
% profile matching.
if isempty(merge_names.profile_numbers)
continue
end
for f=1:numel(profile_fns)
Match = match_wrf2aircraft(Raws.(profile_fns{f}), wrf_dir, profile_types{p});
xlon = Match.wrf.xlon;
xlat = Match.wrf.xlat;
% These will be the same in every Match
% structure, including them greatly increases
% the size of the final file unnecessarily
Match.wrf = rmfield(Match.wrf, 'xlon');
Match.wrf = rmfield(Match.wrf, 'xlat');
profile_comp_struct.(profile_types{p}).(campaigns{a}).(profile_fns{f}).match = Match;
profile_comp_struct.(profile_types{p}).(campaigns{a}).(profile_fns{f}).prof_date = mean(Raws.(profile_fns{f}).dvec);
profile_comp_struct.(profile_types{p}).(campaigns{a}).(profile_fns{f}).omi_time = OmiTimes.(profile_fns{f});
profile_comp_struct.wrf_xlon = xlon;
profile_comp_struct.wrf_xlat = xlat;
end
end
end
% Match the WRF output to the entire P3 flight
for p=1:numel(profile_types)
if ~isempty(all_merge_wrf_dirs.(profile_types{p}))
Match = match_wrf2campaigns.(campaigns{a})(profile_types{p}, all_merge_wrf_dirs.(profile_types{p}), 'lst_range', avg_prof_lst_range);
profile_comp_struct.(profile_types{p}).(campaigns{a}).All.match = Match;
end
end
end
if do_save
save(misc_behr_v3_validation.wrf_comp_file, '-struct', 'profile_comp_struct')
end
end
function generate_behr_wrf_surfpres_comparison
% This function will make monthly averages of the surface
% pressure derived from GLOBE data and compare it to the
% surface pressure in the monthly WRF files.
test_year = 2012;
for m = 1:12
start_date = datenum(test_year, m, 1);
end_date = datenum(test_year, m, eomday(test_year, m));
% We don't need to reject any pixels because the terrain
% pressure should be valid for all pixels
[behr_pres, longrid, latgrid] = behr_time_average(start_date, end_date, 'avgfield', 'GLOBETerpres', 'rejectmode', 'none');
wrf_info = ncinfo(find_wrf_path('us','monthly',start_date,'fullpath'));
wrf_lon = double(ncread(wrf_info.Filename, 'XLONG'));
wrf_lat = double(ncread(wrf_info.Filename, 'XLAT'));
wrf_pres = double(ncread(wrf_info.Filename, 'pres'));
wrf_pres = wrf_pres(:,:,1);
behr_pres_interp = interp2(longrid, latgrid, behr_pres, wrf_lon, wrf_lat);
if m == 1
all_wrf_pres = nan([size(wrf_pres), 12]);
all_behr_pres = nan([size(wrf_pres), 12]);
lon = wrf_lon;
lat = wrf_lat;
end
all_wrf_pres(:,:,m) = wrf_pres;
all_behr_pres(:,:,m) = behr_pres_interp;
end
save(misc_behr_v3_validation.pres_comp_file, 'all_wrf_pres', 'all_behr_pres', 'lon', 'lat');
end
%%%%%%%%%%%%%%%%%%%%%
% Utility functions %
%%%%%%%%%%%%%%%%%%%%%
function OmiTimes = calc_nearest_omi_times(this_date, Raws)
Data = load_behr_file(this_date, 'monthly', 'us');
% For each orbit, get the center longitude/latitude line. Also
% get the average time
center_lon = cell(size(Data));
center_lat = cell(size(Data));
avg_time = cell(size(Data));
for a=1:numel(Data)
n = round(size(Data(a).Longitude,2)/2);
center_lon{a} = Data(a).Longitude(:,n);
center_lat{a} = Data(a).Latitude(:,n);
avg_time{a} = omi_time_conv(mean(Data(a).Time));
end
OmiTimes = make_empty_struct_from_cell(fieldnames(Raws));
% For each profile, calculate the average lon/lat and figure
% out which overpass comes the closest
raw_fns = fieldnames(Raws);
for f=1:numel(raw_fns)
shortest_dist = Inf;
omi_time = NaN;
prof_avg_lon = nanmean(Raws.(raw_fns{a}).lon);
prof_avg_lat = nanmean(Raws.(raw_fns{a}).lat);
for a=1:numel(center_lon)
min_dist = min(sqrt( (prof_avg_lon - center_lon{a}).^2 + (prof_avg_lat - center_lat{a}).^2 ));
if min_dist < shortest_dist
shortest_dist = min_dist;
omi_time = avg_time{a};
end
end
OmiTimes.(raw_fns{f}) = omi_time;
end
end
function Raws = make_raw_struct(Merge, merge_names, campaign)
% The Raw structure for input into match_wrf2aircraft requires
% the fields lon, lat, pres, dvec, and campaign. pres must be
% pressure in hPa. dvec must be a vector that gives the date
% and UTC time as a Matlab datenumber.
% First get all the profile numbers
profnums = remove_merge_fills(Merge, merge_names.profile_numbers);
u_profnums = unique(profnums(profnums > 0));
prof_fns = sprintfmulti('p%d', u_profnums);
substruct = struct('lon', [], 'lat', [], 'pres', [], 'dvec', [], 'campaign', campaign);
Raws = make_empty_struct_from_cell(prof_fns, substruct);
% Read the other necessary variables. Read in UTC with NO2 to
% ensure it has the same fill values.
[AllRaw.no2, utc, ~, AllRaw.lon, AllRaw.lat] = remove_merge_fills(Merge, merge_names.no2_lif, 'unit', 'ppm',...
'lon', merge_names.longitude, 'lat', merge_names.latitude);
AllRaw.pres = remove_merge_fills(Merge, merge_names.pressure, 'unit', 'hPa');
% UTC is given in seconds after midnight.
if any(utc < 0)
warning('Fill values in UTC time vector')
end
AllRaw.dvec = datenum(Merge.metadata.date) + utc ./ (24*60*60);
data_fns = fieldnames(AllRaw);
% Now assign the proper subsets to the individual profile
% fields
for a=1:numel(u_profnums)
pp = profnums == u_profnums(a);
for b=1:numel(data_fns)
Raws.(prof_fns{a}).(data_fns{b}) = AllRaw.(data_fns{b})(pp);
end
end
end
function [no2, xlon, xlat] = load_wrf_no2(prof_type, wrf_date, west_east_inds, north_south_inds, bottom_top_ind)
if strcmpi(prof_type, 'v2')
wrf_file_name = sprintf('m%02d_NO2_profile.mat', wrf_date);
W = load(fullfile(misc_behr_v3_validation.wrf_v2_dir, wrf_file_name));
no2 = permute(W.PROFILE.NO2_profile, [3 2 1]); % no2 in these files is arrange bottom_top, south_north, west_east; it needs to be the other way here
xlon = W.PROFILE.Longitude'; % likewise lat and lon need transposed to have west_east in the first dimension
xlat = W.PROFILE.Latitude';
elseif strcmpi(prof_type, 'monthly')
wrf_file_name = sprintf('WRF_BEHR_monthly_%02d.nc', wrf_date);
[no2, xlon, xlat] = read_wrf_vars(find_wrf_path('us',prof_type,wrf_date), wrf_file_name, {'no2', 'XLONG', 'XLAT'});
elseif strcmpi(prof_type, 'daily')
wrf_file_name = sprintf('wrfout_d01_%s', datestr(wrf_date, 'yyyy-mm-dd_HH-MM-SS'));
[no2, xlon, xlat] = read_wrf_vars(find_wrf_path('us',prof_type,wrf_date), wrf_file_name, {'no2', 'XLONG', 'XLAT'});
else
E.notimplemented('Loading WRF files for mode %s', prof_type);
end
no2 = no2(west_east_inds, north_south_inds, bottom_top_ind);
xlon = xlon(west_east_inds, north_south_inds);
xlat = xlat(west_east_inds, north_south_inds);
end
function locs = read_locs_file()
locs_file = fullfile(misc_behr_v3_validation.my_dir, 'Workspaces', 'trend_locations.nc');
ni = ncinfo(locs_file);
ncvarnames = {ni.Variables.Name};
struct_tmp_cell = cell(1, 2*numel(ncvarnames));
for a=1:numel(ncvarnames)
struct_tmp_cell{(a-1)*2 + 1} = ncvarnames{a};
val = ncread(locs_file, ncvarnames{a});
if ischar(val)
val = cellstr(val);
else
val = num2cell(val);
end
struct_tmp_cell{a*2} = val;
end
% This makes it into a structure where each index is a location
locs = struct(struct_tmp_cell{:});
end
function [xx, yy] = find_loc_indices(loc, lon, lat, radius)
% LOC must be a scalar element of the locations structure, LON
% and LAT must be 2D arrays of longitude and latitude
% coordinates for an NO2 average or similar 2D field. RADIUS
% must be a scalar number of grid cells in each direction to
% get. If omitted, defaults to 0.
E = JLLErrors;
if ~exist('radius', 'var')
radius = 0;
end
sz = size(lon);
r = sqrt((lon - loc.Longitude).^2 + (lat - loc.Latitude).^2);
[~, i_min] = min(r(:));
[xx, yy] = ind2sub(size(lon), i_min);
xx = (xx - radius):(xx + radius);
xx = xx(xx > 0 & xx <= sz(1));
yy = (yy - radius):(yy + radius);
yy = yy(yy > 0 & yy <= sz(2));
end
function [behr_daily, wrf_monthly, wrf_daily] = load_wrf_and_behr_data(plot_loc, date_in, varargin)
p = inputParser;
p.addParameter('load_gridded', false);
p.addParameter('max_frac_nans', 1);
p.parse(varargin{:});
pout = p.Results;
load_gridded = pout.load_gridded;
max_frac_nans = pout.max_frac_nans;
if load_gridded
[Native, Data] = load_behr_file(date_in, 'daily', 'us');
else
Data = load_behr_file(date_in, 'daily', 'us');
Native = Data; % solely for the "is location in swath" check
end
wrf_int_mode = 'box';
plot_radius = 10; %TODO: make this resolution agnostic. Will probably need to modify find_loc_indices
wrf_daily.lon = {};
wrf_daily.lat = {};
wrf_daily.no2_vcds = {};
behr_daily.lon = {};
behr_daily.lat = {};
behr_daily.no2_vcds = {};
behr_daily.no2_scds = {};
if load_gridded
behr_daily.areaweights = {};
end
for a=1:numel(Data)
% Loop over every swath. If the location is in the box
% defined by the four corner pixel centers of the swath
% plot it
corner_x = [Native(a).Longitude(1,1), Native(a).Longitude(1,end), Native(a).Longitude(end,end), Native(a).Longitude(end,1)];
corner_y = [Native(a).Latitude(1,1), Native(a).Latitude(1,end), Native(a).Latitude(end,end), Native(a).Latitude(end,1)];
if ~inpolygon(plot_loc.Longitude, plot_loc.Latitude, corner_x, corner_y);
continue
end
badpix = mod(Data(a).BEHRQualityFlags, 2) ~= 0;
Data(a).BEHRColumnAmountNO2Trop(badpix) = NaN;
[xx_sat, yy_sat] = misc_behr_v3_validation.find_loc_indices(plot_loc, Data(a).Longitude, Data(a).Latitude, plot_radius);
these_scds = Data(a).BEHRColumnAmountNO2Trop(xx_sat,yy_sat) .* Data(a).BEHRAMFTrop(xx_sat, yy_sat);
if fracnan(these_scds) > max_frac_nans
continue
end
behr_daily.no2_vcds{end+1} = Data(a).BEHRColumnAmountNO2Trop(xx_sat,yy_sat);
behr_daily.no2_scds{end+1} = these_scds;
if load_gridded
behr_daily.lon{end+1} = Data(a).Longitude(xx_sat,yy_sat);
behr_daily.lat{end+1} = Data(a).Latitude(xx_sat,yy_sat);
else
% If not loaded gridded data, using the pixel corners
% if usually better with pcolor() because of how it
% matches colors and coordinates.
behr_daily.lon{end+1} = squeeze(Data(a).FoV75CornerLongitude(1,xx_sat,yy_sat));
behr_daily.lat{end+1} = squeeze(Data(a).FoV75CornerLatitude(1,xx_sat,yy_sat));
end
if load_gridded
behr_daily.areaweights{end+1} = Data(a).Areaweight;
end
% Get the WRF file name, but just retrieve the date b/c
% files produced on the cluster will have different paths
% and use the subset files, which aren't stored locally.
[~, daily_wrf_file_tmp] = fileparts(Data(a).BEHRWRFFile);
wrf_date = date_from_wrf_filenames(daily_wrf_file_tmp);
daily_file = fullfile(find_wrf_path('us','daily',wrf_date), sprintf('wrfout_d01_%s', datestr(wrf_date, 'yyyy-mm-dd_HH-MM-SS')));
daily_wrf_no2_vcds = compute_wrf_trop_columns(daily_file, wrf_int_mode, 200);
daily_wrf_lon = ncread(daily_file, 'XLONG');
daily_wrf_lat = ncread(daily_file, 'XLAT');
[xx_daily, yy_daily] = misc_behr_v3_validation.find_loc_indices(plot_loc, daily_wrf_lon, daily_wrf_lat, plot_radius);
wrf_daily.lon{end+1} = daily_wrf_lon(xx_daily, yy_daily);
wrf_daily.lat{end+1} = daily_wrf_lat(xx_daily, yy_daily);
wrf_daily.no2_vcds{end+1} = daily_wrf_no2_vcds(xx_daily, yy_daily);
end
% Load a new monthly file, if needed
if numel(behr_daily.lon) > 0
wrf_monthly_file = fullfile(find_wrf_path('us','monthly',date_in), sprintf('WRF_BEHR_monthly_%02d.nc', month(date_in)));
monthly_wrf_no2_vcds_tmp = compute_wrf_trop_columns(wrf_monthly_file, wrf_int_mode, 200);
monthly_wrf_lon_tmp = ncread(wrf_monthly_file, 'XLONG');
monthly_wrf_lat_tmp = ncread(wrf_monthly_file, 'XLAT');
[xx_monthly, yy_monthly] = misc_behr_v3_validation.find_loc_indices(plot_loc, monthly_wrf_lon_tmp, monthly_wrf_lat_tmp, plot_radius);
wrf_monthly.lon = monthly_wrf_lon_tmp(xx_monthly, yy_monthly);
wrf_monthly.lat = monthly_wrf_lat_tmp(xx_monthly, yy_monthly);
wrf_monthly.no2_vcds = monthly_wrf_no2_vcds_tmp(xx_monthly, yy_monthly);
else
wrf_monthly.lon = [];
wrf_monthly.lat = [];
wrf_monthly.no2_vcds = [];
end
end
function [box_vals, box_pres, box_quartiles] = make_boxplot_bins(pres, no2)
[box_vals, box_pres, box_quartiles] = bin_omisp_pressure(pres, no2, 'median');
return
% % old way, would need for true box plots
% [binned_no2, binned_pres] = bin_omisp_pressure(pres, no2, 'binonly');
% % Because BOXPLOT is pretty simpleminded, we need to make the
% % values and pressures vectors equal lengths
% box_vals = veccat(binned_no2{:});
% box_pres = nan(size(box_vals));
% i = 1;
% for a=1:numel(binned_no2)
% j = i + numel(binned_no2{a}) - 1;
% box_pres(i:j) = binned_pres(a);
% i = j + 1;
% end
%
% box_nans = isnan(box_vals);
% box_vals(box_nans) = [];
% box_pres(box_nans) = [];
end
function [aircraft_comp, pandora_comp] = match_aircraft_and_pandora_sites(aircraft_comp, pandora_comp, varargin)
p = inputParser;
p.addParameter('match_time', false);
p.parse(varargin{:});
pout = p.Results;
match_time = pout.match_time;
aircraft_comp.details = match_verify_struct_details(aircraft_comp, aircraft_comp.details);
aircraft_coords = [aircraft_comp.profile_lon(:), aircraft_comp.profile_lat(:)];
pandora_coords = [pandora_comp.profile_lon(:), pandora_comp.profile_lat(:)];
xx_air = false(size(aircraft_coords,1),1);
xx_pandora = false(size(pandora_coords,1),1);
distance_crit = 0.05;
for i_pan = 1:size(pandora_coords, 1)
distances = sqrt((pandora_coords(i_pan, 1) - aircraft_coords(:,1)).^2 + (pandora_coords(i_pan, 2) - aircraft_coords(:,2)).^2);
xx_air = xx_air | distances < distance_crit;
xx_pandora(i_pan) = any(distances < distance_crit);
end
if match_time
air_dates = cellfun(@(x) datenum(x, 'yyyy-mm-dd'), aircraft_comp.profile_dates);
pandora_dates = floor(pandora_comp.omi_time);
xx_air = xx_air & ismember(air_dates, pandora_dates);
xx_pandora = xx_pandora & ismember(pandora_dates, air_dates);
end
fns_air = fieldnames(aircraft_comp);
for i_air = 1:numel(fns_air)
if ~ischar(aircraft_comp.(fns_air{i_air}))
aircraft_comp.(fns_air{i_air}) = aircraft_comp.(fns_air{i_air})(xx_air);
end
end
fns_pandora = fieldnames(pandora_comp);
for i_pan = 1:numel(fns_pandora)
if ~ischar(pandora_comp.(fns_pandora{i_pan}))
pandora_comp.(fns_pandora{i_pan}) = pandora_comp.(fns_pandora{i_pan})(xx_pandora);
end
end
end
function save_scd_results(filename, results, eval_opts)
h5_filename = strrep(filename, 'mat', 'h5');
loc_names = {results.loc_name};
valid_results = ~cellfun(@isempty, loc_names);
results = results(valid_results);
save(filename, 'results');
for i_res = 1:numel(results)
if isempty(results(i_res).loc_name)
continue
end
sanitized_locname = regexprep(results(i_res).loc_name, '\W', '');
this_date = results(i_res).date;
misc_behr_v3_validation.scd_subgroup(h5_filename, sprintf('/%s/%s', sanitized_locname, this_date), results(i_res));
end
description = ['This file contains the locations randomly selected to compare OMI SCDs to WRF VCDs\n',...
'to determine how well WRF is capturing the wind fields. The hierarchy is SiteName/Date/<datasets>.\n',...
'Each day will have a user value and user confidence field. Confidence ranges from 1 (low) to 3 (high).\n',...
'User value will have one of the following numeric values, with its corresponsing meaning:\n\n%s\n\n',...
'The BEHR SCDs and WRF monthly and daily VCDs will be included as subgroups with lat/lon coordinates.'];
opts_description = sprintfmulti(' %d: %s', num2cell(1:numel(eval_opts)), eval_opts);
h5writeatt(h5_filename, '/', 'Description', sprintf(description, strjoin(opts_description, '\n')));
end
function [data_structs, opts] = load_comparison_data(varargin)
E = JLLErrors;
p = inputParser;
p.addParameter('comp_file','');
p.addParameter('alt_dir', '');
p.addParameter('data_source', '');
p.addParameter('extend_method', '');
p.addParameter('x_var', '');
p.addParameter('y_var', '');
p.addParameter('prof_mode', '');
p.addParameter('campaigns', {});
p.addParameter('time_range', '');
p.addParameter('version', '');
% This allows us to just pass all parameters from any calling
% function
p.KeepUnmatched = true;
p.parse(varargin{:});
pout = p.Results;
comp_file = pout.comp_file;
alternate_dir = pout.alt_dir;
data_source = pout.data_source;
prof_extend_method = pout.extend_method;
x_var = pout.x_var;
y_var = pout.y_var;
prof_mode = pout.prof_mode;
campaigns = pout.campaigns;
time_range = pout.time_range;
product_version = pout.version;
if ~isempty(comp_file)
comp_struct = load(comp_file);
else
data_source = opt_ask_multichoice('Which data source to use?', {'aircraft', 'pandora'}, data_source, '"data_source"', 'list', true);
if strcmpi(data_source, 'pandora')
comp_struct = load(misc_behr_v3_validation.pandora_comp_file(alternate_dir));
else
opts.extend_method = misc_behr_v3_validation.get_profile_extend_method(prof_extend_method);
comp_struct = load(misc_behr_v3_validation.profile_comp_file(opts.extend_method, alternate_dir));
end
end
[opts.data_source, allowed_vars, opts.labels] = misc_behr_v3_validation.comp_struct_type(comp_struct);
opts.alt_dir = alternate_dir;
opts.x_var = opt_ask_multichoice('Which variable to plot on the x-axis?', allowed_vars, x_var, '"x_var"', 'list', true);
opts.y_var = opt_ask_multichoice('Which variable to plot on the y-axis?', allowed_vars, y_var, '"y_var"', 'list', true);
opts.labels.x = opts.labels.(opts.x_var);
opts.labels.y = opts.labels.(opts.y_var);
allowed_prof_modes = {'monthly', 'daily', 'both', 'md-swap'};
if regcmpi(opts.x_var, 'behr') || regcmpi(opts.y_var, 'behr')
opts.prof_mode = opt_ask_multichoice('Which profile mode to use for v3 data?', allowed_prof_modes, prof_mode, '"prof_mode"', 'list', true);
else
% There's no difference in the SP data between our monthly
% and daily profile product
opts.prof_mode = 'monthly';
end
allowed_campaigns = fieldnames(comp_struct.v2.us_monthly);
if isempty(campaigns)
opts.campaigns = ask_multiselect('Which campaign(s) to plot?', allowed_campaigns);
else
if ischar(campaigns)
campaigns = {campaigns};
elseif ~iscellstr(campaigns)