-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathgeo_visualise_results.py
1527 lines (1348 loc) · 93 KB
/
geo_visualise_results.py
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
# Visualise: Performance of each modelling approach, with reference to test datasets & zones
# Import required packages
import sys
import subprocess
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm, colors, gridspec
from mpl_toolkits.basemap import Basemap
import pandas as pd
from osgeo import gdal, gdalconst
import pickle
gdal.UseExceptions() # Useful for trouble-shooting
# Import helper functions relevant to this script
sys.path.append('E:/mdm123/D/scripts/geo/')
from geo_helpers import extract_projection_info, array_to_geotiff
# List paths to GDAL scripts
ogr2ogr = 'C:/Anaconda3/envs/geo/Library/bin/ogr2ogr.exe'
gdal_warp = 'C:/Anaconda3/envs/geo/Library/bin/gdalwarp.exe'
gdal_rasterise = 'C:/Anaconda3/envs/geo/Library/bin/gdal_rasterize.exe'
# Define paths to relevant folders
folder_srtm = 'E:/mdm123/D/data/DSM/SRTM/proc'
folder_dtm = 'E:/mdm123/D/data/DTM/proc'
folder_logs = 'E:/mdm123/D/ML/logs'
folder_results_rf = 'E:/mdm123/D/ML/results/rf'
folder_results_densenet = 'E:/mdm123/D/ML/results/densenet'
folder_results_convnet = 'E:/mdm123/D/ML/results/convnet'
folder_fig = 'E:/mdm123/D/figures/All'
folder_maps = 'E:/mdm123/D/maps/PNG'
folder_input_1D = 'E:/mdm123/D/ML/inputs/1D'
folder_lcdb = 'E:/mdm123/D/data/LRIS/lris-lcdb-v50/proc'
folder_flha = 'E:/mdm123/D/data/NIWA/NZ_FLHA/proc'
folder_hand = 'E:/mdm123/D/maps/HAND/TIF'
# Define list of colours to be used for each ML model: in order of RF, DCN, FCN
models = ['rf','dcn','fcn']
model_colours = {'rf':'#fc8d62', 'dcn':'#66c2a5', 'fcn':'#8da0cb'}
label_colours = {'rf':'#d95f02', 'dcn':'#1b9e77', 'fcn':'#7570b3'}
dataset_colours = ['blue', 'green', 'firebrick']
# Define a list of the zones within which test areas were defined
test_zones = ['MRL18_WPE','MRL18_WVL','TSM16_ATG']
# Define various properties for the three test zones
test_zones_props = {'MRL18_WPE':{'label':'Wairau Plains East (Marlborough)',
'elv_cbar_range':(0,12),
'res_cbar_range':(-5,10)},
'MRL18_WVL':{'label':'Wairau Valley (Marlborough)',
'elv_cbar_range':(230,300),
'res_cbar_range':(-5,10)},
'TSM16_ATG':{'label':'Takaka (Tasman)',
'elv_cbar_range':(0,75),
'res_cbar_range':(-10,15)}}
# Define no_data value to be used
no_data = -9999
###############################################################################
# 1. Define additional helper functions specific to result visualisation #
###############################################################################
# Define a function that retrieves the DTM, SRTM & DIFF arrays for a given zone, as well as a dictionary defining CRS properties for GeoTIFF generation
def get_base_raster_data(zone, no_data=-9999):
# Import the SRTM raster for that zone - get array & geographic properties
srtm_tif = '{}/{}/SRTM_{}_Z.tif'.format(folder_srtm, zone, zone)
srtm_ds = gdal.Open(srtm_tif, gdalconst.GA_ReadOnly)
srtm_proj, srtm_res_x, srtm_res_y, srtm_x_min, srtm_x_max, srtm_y_min, srtm_y_max, srtm_width, srtm_height = extract_projection_info(srtm_tif)
srtm_props = {'proj':srtm_proj, 'res_x':srtm_res_x, 'res_y':srtm_res_y, 'x_min':srtm_x_min, 'y_max':srtm_y_max, 'x_max':srtm_x_max, 'y_min':srtm_y_min, 'width':srtm_width, 'height':srtm_height}
srtm_array = np.array(srtm_ds.GetRasterBand(1).ReadAsArray()).astype('float32')
srtm_ds = None
# Import the Resampled DTM raster for that zone - get array & geographic properties
dtm_tif = '{}/{}/DTM_{}_30m_Median.tif'.format(folder_dtm, zone, zone)
dtm_ds = gdal.Open(dtm_tif, gdalconst.GA_ReadOnly)
dtm_array = np.array(dtm_ds.GetRasterBand(1).ReadAsArray()).astype('float32')
dtm_array[dtm_array==no_data] = np.nan
dtm_ds = None
# Import the SRTM-DTM DIFF raster for that zone - get array & geographic properties
diff_tif = '{}/{}/SRTM_{}_Median_Diff.tif'.format(folder_srtm, zone, zone)
diff_ds = gdal.Open(diff_tif, gdalconst.GA_ReadOnly)
diff_array = np.array(diff_ds.GetRasterBand(1).ReadAsArray()).astype('float32')
diff_ds = None
# Import raster describing which pixels in that zone were assigned to the test dataset
test_tif = '{}/patches/TIF/{}_test_patches.tif'.format(folder_logs, zone)
test_ds = gdal.Open(test_tif, gdalconst.GA_ReadOnly)
test_array = np.array(test_ds.GetRasterBand(1).ReadAsArray()).astype('float32')
test_ds = None
# Import the MERIT DEM raster for that zone - get array & geographic properties
merit_tif = '{}/{}/MERIT_{}.tif'.format(folder_srtm.replace('SRTM','MERIT'), zone, zone)
merit_ds = gdal.Open(merit_tif, gdalconst.GA_ReadOnly)
merit_array = np.array(merit_ds.GetRasterBand(1).ReadAsArray()).astype('float32')
merit_ds = None
# Import the FLHA (NIWA Flood Hazard) raster for that zone - get array & geographic properties
flha_tif = '{}/FLHA_{}.tif'.format(folder_flha, zone)
flha_ds = gdal.Open(flha_tif, gdalconst.GA_ReadOnly)
flha_array = np.array(flha_ds.GetRasterBand(1).ReadAsArray()).astype('float32')
flha_ds = None
# Replace no_data values (-9999) with 0 (to distinguish no_flood from no_data)
flha_array = np.where(flha_array==no_data, 0, flha_array)
# Import the HAND (Height Above Nearest Drainage) raster for that zone - get array & geographic properties
hand_tif = '{}/DTM-SRTM_HAND_{}.tif'.format(folder_hand, zone)
hand_ds = gdal.Open(hand_tif, gdalconst.GA_ReadOnly)
hand_array = np.array(hand_ds.GetRasterBand(1).ReadAsArray()).astype('float32')
hand_ds = None
# Return arrays for the DTM, SRTM & their DIFF, as well as the SRTM projection property dict
return dtm_array, srtm_array, diff_array, test_array, merit_array, flha_array, hand_array, srtm_props
# Define a function that takes a prediction vector (pixel-based models) & returns three 2D arrays: corrections, corrected SRTM, and residuals
def process_1D_predictions(zone, prediction_vector, output_format, no_data=-9999):
# Get 2D arrays for that zone's DTM, SRTM, DIFF & MERIT data, as well as the SRTM GeoTIFF's geographical projection properties
dtm_array, srtm_array, diff_array, test_array, merit_array, flha_array, hand_array, srtm_props = get_base_raster_data(zone)
# Check that length of predictions vector matches expectations
if diff_array.size != len(prediction_vector): print('Prediction vector does not match expectation')
if diff_array.shape != srtm_array.shape: print('SRTM & DIFF arrays are of different shapes')
# Initialise new numpy arrays of the same dimensions as the SRTM array, for the full zone & also limited to the test patches
pred_corrections = np.zeros(srtm_array.shape)
pred_corrections_test = np.zeros(srtm_array.shape)
pred_elevations = np.zeros(srtm_array.shape)
pred_elevations_test = np.zeros(srtm_array.shape)
# Make copies of other rasters, in which pixels out of test extent will be set to np.nan
dtm_array_test = dtm_array.copy()
srtm_array_test = srtm_array.copy()
diff_array_test = diff_array.copy()
merit_array_test = merit_array.copy()
flha_array_test = flha_array.copy()
hand_array_test = hand_array.copy()
# Iterate through all cells, filling the new arrays as appropriate
i = 0
array_height = srtm_array.shape[0]
array_width = srtm_array.shape[1]
# Starting at the top & moving down:
for j in range(array_height):
# Starting at the left & moving right:
for k in range(array_width):
# If corresponding DIFF pixel is no_data, assign no_data pixels to all new arrays
if diff_array[j,k] == no_data:
pred_corrections[j,k] = np.nan
pred_corrections_test[j,k] = np.nan
pred_elevations[j,k] = np.nan
pred_elevations_test[j,k] = np.nan
dtm_array_test[j,k] = np.nan
srtm_array_test[j,k] = np.nan
diff_array_test[j,k] = np.nan
merit_array_test[j,k] = np.nan
flha_array_test[j,k] = np.nan
hand_array_test[j,k] = np.nan
# If corresponding DIFF pixel is valid, use the predictions available in the input vector
else:
# Full arrays processed the same regardless of whether or not this pixel belongs to a test patch
correction = prediction_vector[i]
elevation = srtm_array[j,k]
pred_corrections[j,k] = correction
pred_elevations[j,k] = elevation - correction
# For test arrays, assign predicted values if patch is a test patch, otherwise no_data value
if test_array[j,k]:
pred_corrections_test[j,k] = correction
pred_elevations_test[j,k] = elevation - correction
else:
pred_corrections_test[j,k] = np.nan
pred_elevations_test[j,k] = np.nan
dtm_array_test[j,k] = np.nan
srtm_array_test[j,k] = np.nan
diff_array_test[j,k] = np.nan
merit_array_test[j,k] = np.nan
flha_array_test[j,k] = np.nan
hand_array_test[j,k] = np.nan
# Increment the vector counter
i += 1
# Calculate residuals (diff - predictions)
pred_residuals = diff_array - pred_corrections
pred_residuals_test = pred_residuals.copy()
pred_residuals_test[test_array==0] = np.nan
# Get array extents of test data, for export of clipped arrays
x_min = np.where(test_array==1)[1].min()
x_max = np.where(test_array==1)[1].max()
y_min = np.where(test_array==1)[0].min()
y_max = np.where(test_array==1)[0].max()
# Arrays returned will depend on the output_format argument provided
if output_format == 'full_zone':
return pred_corrections, pred_elevations, pred_residuals, dtm_array, srtm_array, diff_array, merit_array, flha_array, hand_array
elif output_format == 'test_pad':
return pred_corrections_test, pred_elevations_test, pred_residuals_test, dtm_array_test, srtm_array_test, diff_array_test, merit_array_test, flha_array_test, hand_array_test
elif output_format == 'test_clip':
return pred_corrections_test[y_min:y_max+1, x_min:x_max+1], pred_elevations_test[y_min:y_max+1, x_min:x_max+1], pred_residuals_test[y_min:y_max+1, x_min:x_max+1], dtm_array_test[y_min:y_max+1, x_min:x_max+1], srtm_array_test[y_min:y_max+1, x_min:x_max+1], diff_array_test[y_min:y_max+1, x_min:x_max+1], merit_array_test[y_min:y_max+1, x_min:x_max+1], flha_array_test[y_min:y_max+1, x_min:x_max+1], hand_array_test[y_min:y_max+1, x_min:x_max+1]
else:
print('Unknown input value for output_format!')
return None
# Define a function that takes a prediction array (patch-based models) & returns three 2D arrays: corrections, corrected SRTM, and residuals
def process_2D_predictions(zone, prediction_array, output_format, no_data=-9999):
# Get 2D arrays for that zone's DTM, SRTM, DIFF & MERIT data, as well as the SRTM GeoTIFF's geographical projection properties
dtm_array, srtm_array, diff_array, test_array, merit_array, flha_array, hand_array, srtm_props = get_base_raster_data(zone)
# Limit predictions array extent to same dimensions as other arrays (as they have same origin in upper-left)
pred_corrections = prediction_array[0, :srtm_array.shape[0], :srtm_array.shape[1]]
# Calculate elevations & residuals arrays
pred_elevations = srtm_array - pred_corrections
pred_residuals = diff_array - pred_corrections
# Calculate another set of arrays, with nan values outside of the test patches extent
dtm_array_test = dtm_array.copy()
srtm_array_test = srtm_array.copy()
diff_array_test = diff_array.copy()
merit_array_test = merit_array.copy()
flha_array_test = flha_array.copy()
hand_array_test = hand_array.copy()
pred_corrections_test = pred_corrections.copy()
pred_elevations_test = pred_elevations.copy()
pred_residuals_test = pred_residuals.copy()
dtm_array_test[test_array==0] = np.nan
srtm_array_test[test_array==0] = np.nan
diff_array_test[test_array==0] = np.nan
merit_array_test[test_array==0] = np.nan
flha_array_test[test_array==0] = np.nan
hand_array_test[test_array==0] = np.nan
pred_corrections_test[test_array==0] = np.nan
pred_elevations_test[test_array==0] = np.nan
pred_residuals_test[test_array==0] = np.nan
# Get array extents of test data, for export of clipped arrays
x_min = np.where(test_array==1)[1].min()
x_max = np.where(test_array==1)[1].max()
y_min = np.where(test_array==1)[0].min()
y_max = np.where(test_array==1)[0].max()
# Arrays returned will depend on the output_format argument provided
if output_format == 'full_zone':
return pred_corrections, pred_elevations, pred_residuals, dtm_array, srtm_array, diff_array, merit_array, flha_array, hand_array
elif output_format == 'test_pad':
return pred_corrections_test, pred_elevations_test, pred_residuals_test, dtm_array_test, srtm_array_test, diff_array_test, merit_array_test, flha_array_test, hand_array_test
elif output_format == 'test_clip':
return pred_corrections_test[y_min:y_max+1, x_min:x_max+1], pred_elevations_test[y_min:y_max+1, x_min:x_max+1], pred_residuals_test[y_min:y_max+1, x_min:x_max+1], dtm_array_test[y_min:y_max+1, x_min:x_max+1], srtm_array_test[y_min:y_max+1, x_min:x_max+1], diff_array_test[y_min:y_max+1, x_min:x_max+1], merit_array_test[y_min:y_max+1, x_min:x_max+1], flha_array_test[y_min:y_max+1, x_min:x_max+1], hand_array_test[y_min:y_max+1, x_min:x_max+1]
else:
print('Unknown input value for output_format!')
return None
###############################################################################
# 2. Generate rasters indicating test patch coverage within each zone #
###############################################################################
# Define path to SHP of all patches, split up according to usage (train, dev, test)
patches_all = '{}/patches/SHP/patches_target_split.shp'.format(folder_logs)
# Loop through each of the test zones, generating a new SHP & GeoTIFF showing coverage of test patches for each
for zone in test_zones:
print('Processing {} zone...'.format(zone))
# Save a filtered version of the patch SHP, containing only those in the appropriate zone
patches_zone_shp = '{}/patches/SHP/patches_target_split_{}.shp'.format(folder_logs, zone)
filter_query = "zone = '{}' and usage = 'test'".format(zone)
filter_command = [ogr2ogr, patches_zone_shp, patches_all, '-sql', 'SELECT * FROM patches_target_split WHERE {}'.format(filter_query), '-overwrite']
filter_result = subprocess.run(filter_command, stdout=subprocess.PIPE)
if filter_result.returncode != 0: print(filter_result.stdout)
# Read that zone's SRTM GeoTIFF's geographical projection properties, to use as a template
diff_tif = '{}/{}/SRTM_{}_Median_Diff.tif'.format(folder_srtm, zone, zone)
diff_proj, diff_res_x, diff_res_y, diff_x_min, diff_x_max, diff_y_min, diff_y_max, diff_width, diff_height = extract_projection_info(diff_tif)
# Convert new SHP to a GeoTIFF, using that zone's DIFF raster as a template
patches_zone_tif = '{}/patches/TIF/{}_test_patches.tif'.format(folder_logs, zone)
rasterise_command = [gdal_rasterise, '-te', str(diff_x_min), str(diff_y_min), str(diff_x_max), str(diff_y_max), '-tr', str(diff_res_x), str(-diff_res_y), '-burn', '1', '-ot', 'Int16', '-a_nodata', '-9999', '-init', '0', patches_zone_shp, patches_zone_tif]
rasterise_result = subprocess.run(rasterise_command, stdout=subprocess.PIPE)
if rasterise_result.returncode != 0: print(rasterise_result.stdout)
###############################################################################
# 3. Generate prediction GeoTIFFs for each test zone, for each ML model #
###############################################################################
# Random Forest predictions
for zone in test_zones:
# Import zone predictions as vector
rf_predictions = np.load('{}/RF_Predictions_ByZone_{}.npy'.format(folder_results_rf, zone))
# Get general 2D arrays for this zone
dtm_array, srtm_array, diff_array, test_array, merit_array, flha_array, hand_array, srtm_props = get_base_raster_data(zone)
# Get 2D result arrays covering FULL zone & save to GeoTIFFs
rf_corrections_array, rf_elevations_array, rf_residuals_array, _,_,_,_,_,_ = process_1D_predictions(zone, rf_predictions, 'full_zone', no_data=-9999)
rf_corrections_tif = '{}/TIF/rf_corrections_{}.tif'.format(folder_results_rf, zone)
rf_elevations_tif = '{}/TIF/rf_elevations_{}.tif'.format(folder_results_rf, zone)
rf_residuals_tif = '{}/TIF/rf_residuals_{}.tif'.format(folder_results_rf, zone)
array_to_geotiff(rf_corrections_array, rf_corrections_tif, -9999, srtm_props)
array_to_geotiff(rf_elevations_array, rf_elevations_tif, -9999, srtm_props)
array_to_geotiff(rf_residuals_array, rf_residuals_tif, -9999, srtm_props)
# Get 2D result arrays covering FULL zone (with non-test pixels set to np.nan) & save to GeoTIFFs
rf_corrections_test_array, rf_elevations_test_array, rf_residuals_test_array, _,_,_,_,_,_ = process_1D_predictions(zone, rf_predictions, 'test_pad', no_data=-9999)
rf_corrections_test_tif = '{}/TIF/rf_corrections_{}_test.tif'.format(folder_results_rf, zone)
rf_elevations_test_tif = '{}/TIF/rf_elevations_{}_test.tif'.format(folder_results_rf, zone)
rf_residuals_test_tif = '{}/TIF/rf_residuals_{}_test.tif'.format(folder_results_rf, zone)
array_to_geotiff(rf_corrections_test_array, rf_corrections_test_tif, -9999, srtm_props)
array_to_geotiff(rf_elevations_test_array, rf_elevations_test_tif, -9999, srtm_props)
array_to_geotiff(rf_residuals_test_array, rf_residuals_test_tif, -9999, srtm_props)
# Densely-connected neural network predictions
for zone in test_zones:
# Import zone predictions as vector
densenet_predictions = np.load('{}/predictions/densenet_ensemble_{}_prediction.npy'.format(folder_results_densenet, zone))
# Get general 2D arrays for this zone
dtm_array, srtm_array, diff_array, test_array, merit_array, flha_array, hand_array, srtm_props = get_base_raster_data(zone)
# Get 2D result arrays covering FULL zone & save to GeoTIFFs
densenet_corrections_array, densenet_elevations_array, densenet_residuals_array,_,_,_,_,_,_ = process_1D_predictions(zone, densenet_predictions, 'full_zone', no_data=-9999)
densenet_corrections_tif = '{}/TIF/densenet_corrections_{}.tif'.format(folder_results_densenet, zone)
densenet_elevations_tif = '{}/TIF/densenet_elevations_{}.tif'.format(folder_results_densenet, zone)
densenet_residuals_tif = '{}/TIF/densenet_residuals_{}.tif'.format(folder_results_densenet, zone)
array_to_geotiff(densenet_corrections_array, densenet_corrections_tif, -9999, srtm_props)
array_to_geotiff(densenet_elevations_array, densenet_elevations_tif, -9999, srtm_props)
array_to_geotiff(densenet_residuals_array, densenet_residuals_tif, -9999, srtm_props)
# Get 2D result arrays covering FULL zone (with non-test pixels set to np.nan) & save to GeoTIFFs
densenet_corrections_test_array, densenet_elevations_test_array, densenet_residuals_test_array,_,_,_,_,_,_ = process_1D_predictions(zone, densenet_predictions, 'test_pad', no_data=-9999)
densenet_corrections_test_tif = '{}/TIF/densenet_corrections_{}_test.tif'.format(folder_results_densenet, zone)
densenet_elevations_test_tif = '{}/TIF/densenet_elevations_{}_test.tif'.format(folder_results_densenet, zone)
densenet_residuals_test_tif = '{}/TIF/densenet_residuals_{}_test.tif'.format(folder_results_densenet, zone)
array_to_geotiff(densenet_corrections_test_array, densenet_corrections_test_tif, -9999, srtm_props)
array_to_geotiff(densenet_elevations_test_array, densenet_elevations_test_tif, -9999, srtm_props)
array_to_geotiff(densenet_residuals_test_array, densenet_residuals_test_tif, -9999, srtm_props)
# Fully-convolutional neural network predictions
for zone in test_zones:
# Import zone predictions as array
convnet_predictions = np.load('{}/predictions/convnet_ensemble_{}_prediction_intact.npy'.format(folder_results_convnet, zone))
# Get general 2D arrays for this zone
dtm_array, srtm_array, diff_array, test_array, merit_array, flha_array, hand_array, srtm_props = get_base_raster_data(zone)
# Get 2D result arrays covering FULL zone & save to GeoTIFFs
convnet_corrections_array, convnet_elevations_array, convnet_residuals_array,_,_,_,_,_,_ = process_2D_predictions(zone, convnet_predictions, 'full_zone', no_data=-9999)
convnet_corrections_tif = '{}/TIF/convnet_corrections_{}.tif'.format(folder_results_convnet, zone)
convnet_elevations_tif = '{}/TIF/convnet_elevations_{}.tif'.format(folder_results_convnet, zone)
convnet_residuals_tif = '{}/TIF/convnet_residuals_{}.tif'.format(folder_results_convnet, zone)
array_to_geotiff(convnet_corrections_array, convnet_corrections_tif, -9999, srtm_props)
array_to_geotiff(convnet_elevations_array, convnet_elevations_tif, -9999, srtm_props)
array_to_geotiff(convnet_residuals_array, convnet_residuals_tif, -9999, srtm_props)
# Get 2D result arrays covering FULL zone (with non-test pixels set to np.nan) & save to GeoTIFFs
convnet_corrections_test_array, convnet_elevations_test_array, convnet_residuals_test_array,_,_,_,_,_,_ = process_2D_predictions(zone, convnet_predictions, 'test_pad', no_data=-9999)
convnet_corrections_test_tif = '{}/TIF/convnet_corrections_{}_test.tif'.format(folder_results_convnet, zone)
convnet_elevations_test_tif = '{}/TIF/convnet_elevations_{}_test.tif'.format(folder_results_convnet, zone)
convnet_residuals_test_tif = '{}/TIF/convnet_residuals_{}_test.tif'.format(folder_results_convnet, zone)
array_to_geotiff(convnet_corrections_test_array, convnet_corrections_test_tif, -9999, srtm_props)
array_to_geotiff(convnet_elevations_test_array, convnet_elevations_test_tif, -9999, srtm_props)
array_to_geotiff(convnet_residuals_test_array, convnet_residuals_test_tif, -9999, srtm_props)
###############################################################################
# 4. Map elevations & residuals in each zone, showing results of all models #
###############################################################################
# Loop through each test zone
for zone in test_zones:
# Import Random Forest arrays - ONLY test dataset pixels
rf_predictions = np.load('{}/RF_Predictions_ByZone_{}.npy'.format(folder_results_rf, zone))
rf_cor, rf_elv, rf_res, _,_,_,_,_,_ = process_1D_predictions(zone, rf_predictions, 'test_clip', no_data=-9999)
# Import Densenet arrays - ONLY test dataset pixels
dn_predictions = np.load('{}/predictions/densenet_ensemble_{}_prediction.npy'.format(folder_results_densenet, zone))
dn_cor, dn_elv, dn_res, _,_,_,_,_,_ = process_1D_predictions(zone, dn_predictions, 'test_clip', no_data=-9999)
# Import Convnet arrays - ONLY test dataset pixels
cn_predictions = np.load('{}/predictions/convnet_ensemble_{}_prediction_intact.npy'.format(folder_results_convnet, zone))
cn_cor, cn_elv, cn_res, dtm, srtm, diff, merit, flha, hand = process_2D_predictions(zone, cn_predictions, 'test_clip', no_data=-9999)
# Read satellite imagery for that test zone into memory
sat_img = plt.imread('{}/SatImg_{}.png'.format(folder_maps, zone))
# Evaluate RMSE of all DSMs, with reference to the LiDAR DTM available
srtm_RMSE = np.sqrt(np.nanmean(np.square(dtm - srtm)))
merit_RMSE = np.sqrt(np.nanmean(np.square(dtm - merit)))
rf_RMSE = np.sqrt(np.nanmean(np.square(dtm - rf_elv)))
dn_RMSE = np.sqrt(np.nanmean(np.square(dtm - dn_elv)))
cn_RMSE = np.sqrt(np.nanmean(np.square(dtm - cn_elv)))
# Get corresponding improvement, with respect to SRTM's RMSE
merit_RMSE_reduction = (srtm_RMSE - merit_RMSE)/srtm_RMSE * 100
rf_RMSE_reduction = (srtm_RMSE - rf_RMSE)/srtm_RMSE * 100
dn_RMSE_reduction = (srtm_RMSE - dn_RMSE)/srtm_RMSE * 100
cn_RMSE_reduction = (srtm_RMSE - cn_RMSE)/srtm_RMSE * 100
# Get elevation range & build appropriate colourmap
elv_min, elv_max = test_zones_props[zone]['elv_cbar_range']
elv_cmap = cm.terrain
elv_cmap.set_bad(color='whitesmoke')
elv_norm = colors.Normalize(vmin=elv_min, vmax=elv_max)
# Get residual range & build appropriate colourmap
res_min, res_max = test_zones_props[zone]['res_cbar_range']
res_cmap = cm.coolwarm
res_cmap.set_bad(color='whitesmoke')
res_norm = colors.Normalize(vmin=res_min, vmax=res_max)
res_norm = colors.TwoSlopeNorm(vmin=res_min, vcenter=0.0, vmax=res_max)
# For the 'TSM16_ATG' zone, rotate arrays for easier plotting
if zone == 'TSM16_ATG':
dtm, srtm, merit, diff, sat_img, rf_elv, rf_res, dn_elv, dn_res, cn_elv, cn_res = [np.rot90(raster, axes=(1,0)) for raster in [dtm, srtm, merit, diff, sat_img, rf_elv, rf_res, dn_elv, dn_res, cn_elv, cn_res]]
# Determine figure size based on desired width & array dimensions
width = 8
scale = width/(2*srtm.shape[1])
height = 1.05 * 5 * srtm.shape[0] * scale
# Generate plot showing both elevations & residuals
fig, axes = plt.subplots(nrows=5, ncols=2, figsize=(width,height))
# Row 1A: LiDAR DTM
axes[0,0].imshow(dtm, aspect='equal', cmap=elv_cmap, norm=elv_norm)
axes[0,0].set_title('a) LiDAR (resampled to SRTM resolution)', x=0, ha='left', size=9, pad=4)
axes[0,0].axis('off')
# Row 1B: Satellite imagery
axes[0,1].imshow(sat_img, aspect='equal')
axes[0,1].set_title("b) 'NZ Imagery' basemap (LINZ Data Service)", x=0, ha='left', size=9, pad=4)
axes[0,1].axis('off')
# Row 2A: SRTM DSM
axes[1,0].imshow(srtm, aspect='equal', cmap=elv_cmap, norm=elv_norm)
axes[1,0].set_title('c) SRTM: RMSE={:.2f}m (compared to LiDAR)'.format(srtm_RMSE), x=0, ha='left', size=9, pad=4)
axes[1,0].axis('off')
# Row 2B: SRTM Residuals
axes[1,1].imshow(diff, aspect='equal', cmap=res_cmap, norm=res_norm)
axes[1,1].set_title('d) SRTM residuals: \u03BC={:.2f}m, \u03C3={:.2f}m'.format(np.nanmean(diff), np.nanstd(diff)), x=0, ha='left', size=9, pad=4)
axes[1,1].axis('off')
# Row 3A: Random Forest - elevations
axes[2,0].imshow(rf_elv, aspect='equal', cmap=elv_cmap, norm=elv_norm)
axes[2,0].set_title('e) RF-corrected SRTM: RMSE={:.2f}m (-{:.1f}%)'.format(rf_RMSE, rf_RMSE_reduction), x=0, ha='left', size=9, pad=4)
axes[2,0].axis('off')
# Row 3B: Random Forest - residuals
axes[2,1].imshow(rf_res, aspect='equal', cmap=res_cmap, norm=res_norm)
axes[2,1].set_title('f) RF-corrected SRTM residuals: \u03BC={:.2f}m, \u03C3={:.2f}m'.format(np.nanmean(rf_res), np.nanstd(rf_res)), x=0, ha='left', size=9, pad=4)
axes[2,1].axis('off')
# Row 4A: Densenet - elevations
axes[3,0].imshow(dn_elv, aspect='equal', cmap=elv_cmap, norm=elv_norm)
axes[3,0].set_title('g) DCN-corrected SRTM: RMSE={:.2f}m (-{:.1f}%)'.format(dn_RMSE, dn_RMSE_reduction), x=0, ha='left', size=9, pad=4)
axes[3,0].axis('off')
# Row 4B: Densenet - residuals
axes[3,1].imshow(dn_res, aspect='equal', cmap=res_cmap, norm=res_norm)
axes[3,1].set_title('h) DCN-corrected SRTM: \u03BC={:.2f}m, \u03C3={:.2f}m'.format(np.nanmean(dn_res), np.nanstd(dn_res)), x=0, ha='left', size=9, pad=4)
axes[3,1].axis('off')
# Row 5A: Convnet - elevations
axes[4,0].imshow(cn_elv, aspect='equal', cmap=elv_cmap, norm=elv_norm)
axes[4,0].set_title('i) FCN-corrected SRTM: RMSE={:.2f}m (-{:.1f}%)'.format(cn_RMSE, cn_RMSE_reduction), x=0, ha='left', size=9, pad=4)
axes[4,0].axis('off')
# Row 5B: Convnet - residuals
axes[4,1].imshow(cn_res, aspect='equal', cmap=res_cmap, norm=res_norm)
axes[4,1].set_title('j) FCN-corrected SRTM residuals: \u03BC={:.2f}m, \u03C3={:.2f}m'.format(np.nanmean(cn_res), np.nanstd(cn_res)), x=0, ha='left', size=9, pad=4)
axes[4,1].axis('off')
# Add a small north arrow indicator to each map
arrowprops = dict(facecolor='black', width=1.5, headwidth=4, headlength=4)
if zone == 'TSM16_ATG':
x, y, arrow_length = 0.1, 0.95, 0.06
xytext = (x-arrow_length, y)
else:
x, y, arrow_length = 0.97, 0.96, 0.11
xytext = (x, y-arrow_length)
for ax in axes.ravel():
ax.annotate('N', xy=(x,y), xycoords='axes fraction', xytext=xytext, textcoords='axes fraction', arrowprops=arrowprops, ha='center', va='center', fontsize=8)
# Add a simple scale bar to the DTM map, assuming that each grid cell is approx. 23m (SRTM at this latitude)
ncells_1km = 1000/23
offset = 8
adjust_y = 10 if zone == 'TSM16_ATG' else 0
axes[0,0].plot([offset, offset + ncells_1km], [offset + adjust_y, offset + adjust_y], color='black', linewidth=0.8)
axes[0,0].plot([offset, offset], [offset-1+adjust_y, offset+1+adjust_y], color='black', linewidth=0.8)
axes[0,0].plot([offset + ncells_1km, offset + ncells_1km], [offset-1+adjust_y, offset+1+adjust_y], color='black', linewidth=0.8)
axes[0,0].annotate('1km', xy=(offset + 0.5*ncells_1km, 1.3*offset + adjust_y), ha='center', va='top', size=8)
# Tighten layout
fig.tight_layout(pad=1)
# Adjust layout to fit two colourbars at the bottom
fig.subplots_adjust(top=0.98, bottom=0.06, wspace=0.05, hspace=0.12)
# Add colourbar for elevations
elv_cbar = fig.add_axes([0.03, 0.04, 0.4, 0.01]) # [left, bottom, width, height]
fig.colorbar(cm.ScalarMappable(cmap=elv_cmap, norm=elv_norm), cax=elv_cbar, orientation='horizontal').set_label(label='Elevation [m]', size=9)
elv_cbar.tick_params(labelsize=8)
# Add colourbar for residuals
res_cbar = fig.add_axes([0.5, 0.04, 0.4, 0.01]) # [left, bottom, width, height]
fig.colorbar(cm.ScalarMappable(cmap=res_cmap, norm=res_norm), cax=res_cbar, orientation='horizontal').set_label(label='Residuals [m]', size=9)
res_cbar.tick_params(labelsize=8)
# Save figure
fig.savefig('{}/maps_elv_res_{}.png'.format(folder_fig, zone), dpi=300, bbox_inches='tight')
plt.close()
# Generate plot showing only elevations, and only the convnet results
width = 8
scale = width/(srtm.shape[1])
height = 1.05 * 3 * srtm.shape[0] * scale
fig, axes = plt.subplots(nrows=3, figsize=(width,height))
# Row 1: LiDAR DTM
axes[0].imshow(dtm, aspect='equal', cmap=elv_cmap, norm=elv_norm)
axes[0].set_title('a) LiDAR (resampled to SRTM resolution)', x=0, ha='left', size=9, pad=4)
axes[0].axis('off')
# Row 2: SRTM DSM
axes[1].imshow(srtm, aspect='equal', cmap=elv_cmap, norm=elv_norm)
axes[1].set_title('b) SRTM: RMSE={:.2f}m (compared to LiDAR)'.format(srtm_RMSE), x=0, ha='left', size=9, pad=4)
axes[1].axis('off')
# Row 3: Convnet - elevations
axes[2].imshow(cn_elv, aspect='equal', cmap=elv_cmap, norm=elv_norm)
axes[2].set_title('c) FCN-corrected SRTM: RMSE={:.2f}m (an improvement of {:.1f}% over raw SRTM)'.format(cn_RMSE, cn_RMSE_reduction), x=0, ha='left', size=9, pad=4)
axes[2].axis('off')
# Add a small north arrow indicator to each map
arrowprops = dict(facecolor='black', width=1.5, headwidth=4, headlength=4)
if zone == 'TSM16_ATG':
x, y, arrow_length = 0.07, 0.95, 0.04
xytext = (x-arrow_length, y)
else:
x, y, arrow_length = 0.97, 0.96, 0.07
xytext = (x, y-arrow_length)
for ax in axes.ravel():
ax.annotate('N', xy=(x,y), xycoords='axes fraction', xytext=xytext, textcoords='axes fraction', arrowprops=arrowprops, ha='center', va='center', fontsize=10)
# Add a simple scale bar to the DTM map, assuming that each grid cell is approx. 23m (SRTM at this latitude)
ncells_1km = 1000/23
offset = 8
adjust_y = 10 if zone == 'TSM16_ATG' else 0
axes[0].plot([offset, offset + ncells_1km], [offset + adjust_y, offset + adjust_y], color='black', linewidth=0.8)
axes[0].plot([offset, offset], [offset-1+adjust_y, offset+1+adjust_y], color='black', linewidth=0.8)
axes[0].plot([offset + ncells_1km, offset + ncells_1km], [offset-1+adjust_y, offset+1+adjust_y], color='black', linewidth=0.8)
axes[0].annotate('1km', xy=(offset + 0.5*ncells_1km, 1.3*offset + adjust_y), ha='center', va='top', size=8)
# Tighten layout
fig.tight_layout(pad=1)
# Adjust layout to fit two colourbars at the bottom
fig.subplots_adjust(bottom=0.07, wspace=0.05, hspace=0.07)
# Add colourbar for elevations
elv_cbar = fig.add_axes([0.06, 0.04, 0.88, 0.015]) # [left, bottom, width, height]
fig.colorbar(cm.ScalarMappable(cmap=elv_cmap, norm=elv_norm), cax=elv_cbar, orientation='horizontal').set_label(label='Elevation [m]', size=9)
elv_cbar.tick_params(labelsize=8)
# Save figure
fig.savefig('{}/maps_elv_{}_convnet.png'.format(folder_fig, zone), dpi=300, bbox_inches='tight')
plt.close()
###############################################################################
# 5. Compare overall residuals using boxplots #
###############################################################################
# Read in error residuals calculated earlier for the test dataset
residuals_dict_rf = pickle.load(open('{}/rf_residuals.p'.format(folder_results_rf), 'rb'))
residuals_dict_densenet = pickle.load(open('{}/densenet_residuals_models.p'.format(folder_results_densenet), 'rb'))
residuals_dict_convnet = pickle.load(open('{}/convnet_residuals_models.p'.format(folder_results_convnet), 'rb'))
# Check that initial residuals are the same (in each dictionary)
fig, axes = plt.subplots(figsize=(9,5))
axes.boxplot([d['test']['initial'] for d in [residuals_dict_rf, residuals_dict_densenet, residuals_dict_convnet]], showfliers=False)
# Get residuals to plot
res_initial = residuals_dict_convnet['test']['initial']
res_baseline = residuals_dict_convnet['test']['naive']
res_rf = residuals_dict_rf['test']['rf']
res_densenet = residuals_dict_densenet['test']['densenet_ensemble']
res_convnet = residuals_dict_convnet['test']['convnet_ensemble']
# Boxplots of error residuals
bp_data = [res_initial, res_baseline, res_rf, res_densenet, res_convnet]
bp_colours = ['dimgrey', 'darkgrey'] + [model_colours[m] for m in models]
bp_label_colours = ['dimgrey', 'darkgrey'] + [label_colours[m] for m in models]
# Add boxplots to the figure
fig, axes = plt.subplots(figsize=(9,5))
bps = axes.boxplot(bp_data, showfliers=False, medianprops={'color':'black'}, patch_artist=True)
for patch, colour in zip(bps['boxes'], bp_colours):
patch.set_facecolor(colour)
# Add axis ticks & labels
axes.set_xticks(range(1,6))
axes.set_xticklabels(['Initial','Baseline\ncorrection','RF\ncorrection','DCN\ncorrection','FCN\ncorrection'])
axes.set_ylabel('Residual error before/after correction [m]')
# Turn spines off
[axes.spines[edge].set_visible(False) for edge in ['top','right']]
# Add a horizontal line for zero error
axes.axhline(y=0, linestyle='dashed', color='black', linewidth=0.8, alpha=0.3)
# Add labels for medians & IQR
iqr_label_y = 0
for i, data in enumerate(bp_data):
median = np.median(data)
q75, q25 = np.percentile(data, [75 ,25])
iqr = q75 - q25
iqr_label_y = max(1.02*(q75 + 1.5*iqr), iqr_label_y)
axes.annotate('{:.3f}m'.format(median), xy=(i+1.28, median), ha='left', va='center')
axes.annotate('IQR = {:.3f}m'.format(iqr), xy=(i+1, iqr_label_y), color=bp_label_colours[i], fontweight='bold', ha='center', va='bottom')
fig.tight_layout()
fig.savefig('{}/residuals_bymodel_boxplots.png'.format(folder_fig), dpi=300)
plt.close()
###############################################################################
# 6. Assess correction efficacy by zone, land cover, FLHA class & HAND range #
###############################################################################
# Set up a dictionary to contain SRTM-LiDAR difference values corresponding to each Manaaki Whenua landclass type present in that LiDAR zone coverage
diff_by_landcover = {1:{'label':'Artificial\nsurfaces', 'data':[], 'colour':(78/255, 78/255, 78/255)},
2:{'label':'Bare/lightly-\nvegetated\nsurfaces', 'data':[], 'colour':(255/255, 235/255, 190/255)},
3:{'label':'Water\nbodies', 'data':[], 'colour':(0/255, 197/255, 255/255)},
4:{'label':'Cropland', 'data':[], 'colour':(255/255, 170/255, 0/255)},
5:{'label':'Grassland,\nSedgeland\n& Marshland', 'data':[], 'colour':(255/255, 255/255, 115/255)},
6:{'label':'Scrub &\nShrubland', 'data':[], 'colour':(137/255, 205/255, 102/255)},
7:{'label':'Forest', 'data':[], 'colour':(38/255, 115/255, 0/255)},
8:{'label':'Other', 'data':[], 'colour':'#FF0000'}}
# Initalise dictionary to hold test residuals, classed in different ways
res = {'initial':{'by_zone':{zone:[] for zone in ['All'] + test_zones}, 'by_lcdb':{i:[] for i in range(1,8)}, 'by_flha':{'flood':[], 'noflood':[]}, 'by_hand':{'hand_{}'.format(h):[] for h in range(1,6)}},
'rf':{'by_zone':{zone:[] for zone in ['All'] + test_zones}, 'by_lcdb':{i:[] for i in range(1,8)}, 'by_flha':{'flood':[], 'noflood':[]}, 'by_hand':{'hand_{}'.format(h):[] for h in range(1,6)}},
'dn':{'by_zone':{zone:[] for zone in ['All'] + test_zones}, 'by_lcdb':{i:[] for i in range(1,8)}, 'by_flha':{'flood':[], 'noflood':[]}, 'by_hand':{'hand_{}'.format(h):[] for h in range(1,6)}},
'cn':{'by_zone':{zone:[] for zone in ['All'] + test_zones}, 'by_lcdb':{i:[] for i in range(1,8)}, 'by_flha':{'flood':[], 'noflood':[]}, 'by_hand':{'hand_{}'.format(h):[] for h in range(1,6)}}}
# Loop through the three test zones
for i, zone in enumerate(test_zones):
print('Processing {} zone...'.format(zone))
# Get the test array & SRTM props dictionary
_, _, _, test, _, _, _, srtm_props = get_base_raster_data(zone)
# Land cover classes
lcdb_tif = '{}/LCDB_GroupID_{}.tif'.format(folder_lcdb, zone)
lcdb_ds = gdal.Open(lcdb_tif, gdalconst.GA_ReadOnly)
lcdb = np.array(lcdb_ds.ReadAsArray())
lcdb_ds = None
# Import Random Forest arrays - ONLY test dataset pixels
rf_predictions = np.load('{}/RF_Predictions_ByZone_{}.npy'.format(folder_results_rf, zone))
rf_cor, rf_elv, rf_res, _,_,_,_,_,_ = process_1D_predictions(zone, rf_predictions, 'test_clip', no_data=-9999)
# Import Densenet arrays - ONLY test dataset pixels
dn_predictions = np.load('{}/predictions/densenet_ensemble_{}_prediction.npy'.format(folder_results_densenet, zone))
dn_cor, dn_elv, dn_res, _,_,_,_,_,_ = process_1D_predictions(zone, dn_predictions, 'test_clip', no_data=-9999)
# Import Convnet arrays - ONLY test dataset pixels
cn_predictions = np.load('{}/predictions/convnet_ensemble_{}_prediction_intact.npy'.format(folder_results_convnet, zone))
cn_cor, cn_elv, cn_res, dtm, srtm, diff, merit, flha, hand = process_2D_predictions(zone, cn_predictions, 'test_clip', no_data=-9999)
# Check extent of the test patch coverage, with reference to the zone coverage as a whole
x_min = np.where(test==1)[1].min()
x_max = np.where(test==1)[1].max()
y_min = np.where(test==1)[0].min()
y_max = np.where(test==1)[0].max()
# For the LCDB array, set to np.nan any pixels which aren't in the test patches & clip it to test data extent
lcdb[test==0] = np.nan
lcdb = lcdb[y_min:y_max+1, x_min:x_max+1]
# Mask all arrays wherever no_data values are present
dtm = np.ma.masked_equal(dtm, no_data)
srtm = np.ma.masked_equal(srtm, no_data)
diff = np.ma.masked_equal(diff, no_data)
test = np.ma.masked_equal(test[y_min:y_max+1, x_min:x_max+1], no_data)
lcdb = np.ma.masked_equal(lcdb, no_data)
flha = np.ma.masked_equal(flha, no_data)
hand = np.ma.masked_equal(hand, no_data)
rf_cor = np.ma.masked_equal(rf_cor, no_data)
rf_elv = np.ma.masked_equal(rf_elv, no_data)
rf_res = np.ma.masked_equal(rf_res, no_data)
dn_cor = np.ma.masked_equal(dn_cor, no_data)
dn_elv = np.ma.masked_equal(dn_elv, no_data)
dn_res = np.ma.masked_equal(dn_res, no_data)
cn_cor = np.ma.masked_equal(cn_cor, no_data)
cn_elv = np.ma.masked_equal(cn_elv, no_data)
cn_res = np.ma.masked_equal(cn_res, no_data)
# Check that all arrays have the same shape
if not (dtm.shape == srtm.shape == diff.shape == test.shape == lcdb.shape == flha.shape == hand.shape == rf_cor.shape == dn_cor.shape == cn_cor.shape):
print('Different test array dimensions!')
break
# Class residuals by test zone
# Get list of residuals for that zone (for each model)
res_initial_byzone = diff.flatten().tolist()
res_rf_byzone = rf_res.flatten().tolist()
res_dn_byzone = dn_res.flatten().tolist()
res_cn_byzone = cn_res.flatten().tolist()
# Filter out any None values (masked)
res_initial_byzone = [r for r in res_initial_byzone if (not np.isnan(r) and r != None)]
res_rf_byzone = [r for r in res_rf_byzone if (not np.isnan(r) and r != None)]
res_dn_byzone = [r for r in res_dn_byzone if (not np.isnan(r) and r != None)]
res_cn_byzone = [r for r in res_cn_byzone if (not np.isnan(r) and r != None)]
# Update dictionary of all test residuals
res['initial']['by_zone'][zone] = res_initial_byzone
res['initial']['by_zone']['All'] = np.append(res['initial']['by_zone']['All'], res_initial_byzone)
res['rf']['by_zone'][zone] = res_rf_byzone
res['rf']['by_zone']['All'] = np.append(res['rf']['by_zone']['All'], res_rf_byzone)
res['dn']['by_zone'][zone] = res_dn_byzone
res['dn']['by_zone']['All'] = np.append(res['dn']['by_zone']['All'], res_dn_byzone)
res['cn']['by_zone'][zone] = res_cn_byzone
res['cn']['by_zone']['All'] = np.append(res['cn']['by_zone']['All'], res_cn_byzone)
# Class residuals by land cover class
# Loop through each potential land cover class (as defined in proc_LCDB.py) and calculate elevation residuals for that particular class
for i in range(1,8):
# Get lists of residuals for that land cover class - for each of the input residual arrays
res_initial_byclass = diff[lcdb==i].flatten().tolist()
res_rf_byclass = rf_res[lcdb==i].flatten().tolist()
res_dn_byclass = dn_res[lcdb==i].flatten().tolist()
res_cn_byclass = cn_res[lcdb==i].flatten().tolist()
# Filter out any None values (masked)
res_initial_byclass = [r for r in res_initial_byclass if (not np.isnan(r) and r != None)]
res_rf_byclass = [r for r in res_rf_byclass if (not np.isnan(r) and r != None)]
res_dn_byclass = [r for r in res_dn_byclass if (not np.isnan(r) and r != None)]
res_cn_byclass = [r for r in res_cn_byclass if (not np.isnan(r) and r != None)]
# Update dictionary of all test residuals
res['initial']['by_lcdb'][i] = np.append(res['initial']['by_lcdb'][i], res_initial_byclass)
res['rf']['by_lcdb'][i] = np.append(res['rf']['by_lcdb'][i], res_rf_byclass)
res['dn']['by_lcdb'][i] = np.append(res['dn']['by_lcdb'][i], res_dn_byclass)
res['cn']['by_lcdb'][i] = np.append(res['cn']['by_lcdb'][i], res_cn_byclass)
# Class residuals by NIWA's Flood Hazard susceptibility map
# Loop through each potential land cover class (as defined in proc_LCDB.py) and calculate elevation residuals for that particular class
for flha_code, flha_label in zip([1,0], ['flood','noflood']):
# Get lists of residuals for that flood susceptibility - for each of the input residual arrays
res_initial_byflha = diff[flha==flha_code].flatten().tolist()
res_rf_byflha = rf_res[flha==flha_code].flatten().tolist()
res_dn_byflha = dn_res[flha==flha_code].flatten().tolist()
res_cn_byflha = cn_res[flha==flha_code].flatten().tolist()
# Filter out any None values (masked)
res_initial_byflha = [r for r in res_initial_byflha if (not np.isnan(r) and r != None)]
res_rf_byflha = [r for r in res_rf_byflha if (not np.isnan(r) and r != None)]
res_dn_byflha = [r for r in res_dn_byflha if (not np.isnan(r) and r != None)]
res_cn_byflha = [r for r in res_cn_byflha if (not np.isnan(r) and r != None)]
# Update dictionary of all test residuals
res['initial']['by_flha'][flha_label] = np.append(res['initial']['by_flha'][flha_label], res_initial_byflha)
res['rf']['by_flha'][flha_label] = np.append(res['rf']['by_flha'][flha_label], res_rf_byflha)
res['dn']['by_flha'][flha_label] = np.append(res['dn']['by_flha'][flha_label], res_dn_byflha)
res['cn']['by_flha'][flha_label] = np.append(res['cn']['by_flha'][flha_label], res_cn_byflha)
# Class residuals by HAND (height above nearest drainage) range
# Define breaks for each of the five HAND ranges
hand_breaks = [(0,2), (2,5), (5,10), (10,20), (20, max(50, np.nanmax(hand))+1)]
# Loop through each HAND range
for j, breaks in enumerate(hand_breaks):
hand_class = 'hand_{}'.format(j+1)
# Get lists of residuals corresponding to that range of HAND values - for each of the input residual arrays
res_initial_byhand = diff[(hand >= breaks[0]) & (hand < breaks[1])].flatten().tolist()
res_rf_byhand = rf_res[(hand >= breaks[0]) & (hand < breaks[1])].flatten().tolist()
res_dn_byhand = dn_res[(hand >= breaks[0]) & (hand < breaks[1])].flatten().tolist()
res_cn_byhand = cn_res[(hand >= breaks[0]) & (hand < breaks[1])].flatten().tolist()
# Filter out any None values (masked)
res_initial_byhand = [r for r in res_initial_byhand if (not np.isnan(r) and r != None)]
res_rf_byhand = [r for r in res_rf_byhand if (not np.isnan(r) and r != None)]
res_dn_byhand = [r for r in res_dn_byhand if (not np.isnan(r) and r != None)]
res_cn_byhand = [r for r in res_cn_byhand if (not np.isnan(r) and r != None)]
# Update dictionary of all test residuals
res['initial']['by_hand'][hand_class] = np.append(res['initial']['by_hand'][hand_class], res_initial_byhand)
res['rf']['by_hand'][hand_class] = np.append(res['rf']['by_hand'][hand_class], res_rf_byhand)
res['dn']['by_hand'][hand_class] = np.append(res['dn']['by_hand'][hand_class], res_dn_byhand)
res['cn']['by_hand'][hand_class] = np.append(res['cn']['by_hand'][hand_class], res_cn_byhand)
# Define some common properties for the boxplots of residuals
bp_width = 0.1
bp_offset = 0.2
bp_colours = ['dimgrey'] + [model_colours[m] for m in models]
# Define labels for the four test zones/subsets
test_zones_classes = ['All'] + test_zones
test_zones_labels = ['Overall (all test\nzones combined)', 'Wairau Plains East\n(Marlborough)', 'Wairau Valley\n(Marlborough)', 'Takaka\n(Tasman)']
# Define colours for the six HAND ranges
hand_cmap = cm.Blues_r
hand_colours = [hand_cmap(i/5) for i in range(5)]
# 6a. Set up a figure summarising all residuals by test zone & LCDB class
fig, axes = plt.subplots(nrows=2, figsize=(9,9))
# Plot 1: Residuals by test zone
for i, test_zone in enumerate(test_zones_classes):
i += 1
# Add boxplots to the figure
bps = axes[0].boxplot([res['initial']['by_zone'][test_zone], res['rf']['by_zone'][test_zone], res['dn']['by_zone'][test_zone], res['cn']['by_zone'][test_zone]], positions=[i-1.5*bp_offset, i-0.5*bp_offset, i+0.5*bp_offset, i+1.5*bp_offset], showfliers=False, medianprops={'color':'black'}, widths=bp_width, patch_artist=True)
for patch, colour in zip(bps['boxes'], bp_colours):
patch.set_facecolor(colour)
# Get RMSE associated with each set of residuals
RMSE_initial = np.sqrt(np.nanmean(np.square(res['initial']['by_zone'][test_zone])))
RMSE_rf = np.sqrt(np.nanmean(np.square(res['rf']['by_zone'][test_zone])))
RMSE_dn = np.sqrt(np.nanmean(np.square(res['dn']['by_zone'][test_zone])))
RMSE_cn = np.sqrt(np.nanmean(np.square(res['cn']['by_zone'][test_zone])))
# Calculate percentage improvement made by method
RMSE_rf_improve = (RMSE_initial - RMSE_rf)/RMSE_initial * 100.
RMSE_dn_improve = (RMSE_initial - RMSE_dn)/RMSE_initial * 100.
RMSE_cn_improve = (RMSE_initial - RMSE_cn)/RMSE_initial * 100.
# Determine which method achieved the highest improvement & label that point
RMSEs_ordered = [RMSE_rf, RMSE_dn, RMSE_cn]
best_index = np.argmin(RMSEs_ordered)
best_RMSE = RMSEs_ordered[best_index]
best_improve = [RMSE_rf_improve, RMSE_dn_improve, RMSE_cn_improve][best_index]
best_model = models[best_index]
best_colour = label_colours[best_model]
axes[0].annotate(u'RMSE \u2193\nby {:.0f}%'.format(best_improve), xy=(i/4 - 1/8, 0.98), xycoords='axes fraction', ha='center', va='top', size=10, color=best_colour)
# Add axis ticks & labels, and turn some spines off
axes[0].set_xticks(range(1,5))
axes[0].set_xticklabels(test_zones_labels)
axes[0].set_xticklabels(['{}\n[{:,} pixels]'.format(label, len(res['initial']['by_zone'][z])) for label, z in zip(test_zones_labels, test_zones_classes)])
axes[0].set_ylabel('Residuals before/after correction [m]')
[axes[0].spines[edge].set_visible(False) for edge in ['top','right']]
# Colour background based on land cover class & add a horizontal line for zero error
[axes[0].axvspan(j-0.45, j+0.45, alpha=0.25, facecolor='lightgrey', edgecolor='none') for j in range(1,5)]
axes[0].axhline(y=0, linestyle='dashed', color='black', linewidth=0.8, alpha=0.3)
axes[0].set_xlim(0.5,4.5)
# Add title
axes[0].set_title('a) By test zone/subset', x=0, ha='left', color='dimgrey', weight='bold', alpha=0.8)
# Plot 2: Residuals by land cover class (LCDB), as defined in geo_process_LCDB.py
for j in range(1,8):
# Add boxplots to the figure
bps = axes[1].boxplot([res['initial']['by_lcdb'][j], res['rf']['by_lcdb'][j], res['dn']['by_lcdb'][j], res['cn']['by_lcdb'][j]], positions=[j-1.5*bp_offset, j-0.5*bp_offset, j+0.5*bp_offset, j+1.5*bp_offset], showfliers=False, medianprops={'color':'black'}, widths=bp_width, patch_artist=True)
for patch, colour in zip(bps['boxes'], bp_colours):
patch.set_facecolor(colour)
# Get RMSE associated with each set of residuals
RMSE_initial = np.sqrt(np.nanmean(np.square(res['initial']['by_lcdb'][j])))
RMSE_rf = np.sqrt(np.nanmean(np.square(res['rf']['by_lcdb'][j])))
RMSE_dn = np.sqrt(np.nanmean(np.square(res['dn']['by_lcdb'][j])))
RMSE_cn = np.sqrt(np.nanmean(np.square(res['cn']['by_lcdb'][j])))
# Calculate percentage improvement made by method
RMSE_rf_improve = (RMSE_initial - RMSE_rf)/RMSE_initial * 100.
RMSE_dn_improve = (RMSE_initial - RMSE_dn)/RMSE_initial * 100.
RMSE_cn_improve = (RMSE_initial - RMSE_cn)/RMSE_initial * 100.
# Determine which method achieved the highest improvement & label that point
RMSEs_ordered = [RMSE_rf, RMSE_dn, RMSE_cn]
best_index = np.argmin(RMSEs_ordered)
best_RMSE = RMSEs_ordered[best_index]
best_improve = [RMSE_rf_improve, RMSE_dn_improve, RMSE_cn_improve][best_index]
best_model = models[best_index]
best_colour = label_colours[best_model]
axes[1].annotate(u'RMSE \u2193\nby {:.0f}%'.format(best_improve), xy=(j/7 - 1/14, 0.98), xycoords='axes fraction', ha='center', va='top', size=10, color=best_colour)
# Add axis ticks & labels, and turn some spines off
axes[1].set_xticks(range(1,8))
axes[1].set_xticklabels(['{}\n[{:,} pixels]'.format(diff_by_landcover[j]['label'], len(res['initial']['by_lcdb'][j])) for j in range(1,8)])
axes[1].set_ylabel('Residuals before/after correction [m]')
[axes[1].spines[edge].set_visible(False) for edge in ['top','right']]
# Colour background based on land cover class & add a horizontal line for zero error
[axes[1].axvspan(j-0.45, j+0.45, alpha=0.1, facecolor=diff_by_landcover[j]['colour'], edgecolor='none') for j in range(1,8)]
axes[1].axhline(y=0, linestyle='dashed', color='black', linewidth=0.8, alpha=0.3)
axes[1].set_xlim(0.5,7.5)
# Add title
axes[1].set_title('b) By land cover class', x=0, ha='left', color='dimgrey', weight='bold', alpha=0.8)
# Tighten up layout, add a common legend at the top & save figure
fig.tight_layout(pad=0, h_pad=1.8)
fig.subplots_adjust(top=0.93)
fig.legend(handles=bps['boxes'], labels=['Initial','RF','DCN','FCN'], frameon=False, ncol=4, loc='upper center', prop={'size':11})
fig.savefig('{}/residuals_boxplots_by_zone-lcdb.png'.format(folder_fig), dpi=300, bbox='tight')
plt.close()
# 6b. Set up a figure summarising all residuals by FLHA & HAND zones
fig, axes = plt.subplots(nrows=2, figsize=(9,9))
# Plot 1: Residuals by FLHA zone
for i, flha_label in enumerate(['flood','noflood']):
i += 1
# Add boxplots to the figure
bps = axes[0].boxplot([res['initial']['by_flha'][flha_label], res['rf']['by_flha'][flha_label], res['dn']['by_flha'][flha_label], res['cn']['by_flha'][flha_label]], positions=[i-1.5*bp_offset, i-0.5*bp_offset, i+0.5*bp_offset, i+1.5*bp_offset], showfliers=False, medianprops={'color':'black'}, widths=bp_width, patch_artist=True)
for patch, colour in zip(bps['boxes'], bp_colours):
patch.set_facecolor(colour)
# Get RMSE associated with each set of residuals
RMSE_initial = np.sqrt(np.nanmean(np.square(res['initial']['by_flha'][flha_label])))
RMSE_rf = np.sqrt(np.nanmean(np.square(res['rf']['by_flha'][flha_label])))
RMSE_dn = np.sqrt(np.nanmean(np.square(res['dn']['by_flha'][flha_label])))
RMSE_cn = np.sqrt(np.nanmean(np.square(res['cn']['by_flha'][flha_label])))
# Calculate percentage improvement made by method
RMSE_rf_improve = (RMSE_initial - RMSE_rf)/RMSE_initial * 100.
RMSE_dn_improve = (RMSE_initial - RMSE_dn)/RMSE_initial * 100.
RMSE_cn_improve = (RMSE_initial - RMSE_cn)/RMSE_initial * 100.
# Determine which method achieved the highest improvement & label that point
RMSEs_ordered = [RMSE_rf, RMSE_dn, RMSE_cn]
best_index = np.argmin(RMSEs_ordered)
best_RMSE = RMSEs_ordered[best_index]
best_improve = [RMSE_rf_improve, RMSE_dn_improve, RMSE_cn_improve][best_index]
best_model = models[best_index]
best_colour = label_colours[best_model]
axes[0].annotate(u'RMSE \u2193\nby {:.0f}%'.format(best_improve), xy=(i/2 - 1/4, 0.98), xycoords='axes fraction', ha='center', va='top', size=10, color=best_colour)
# Add axis ticks & labels, and turn some spines off
axes[0].set_xticks(range(1,3))
axes[0].set_xticklabels(['Flood-prone\n[{:,} pixels]'.format(len(res['initial']['by_flha']['flood'])), 'Not flood-prone\n({:,} pixels)'.format(len(res['initial']['by_flha']['noflood']))])
axes[0].set_ylabel('Residuals before/after correction [m]')
[axes[0].spines[edge].set_visible(False) for edge in ['top','right']]
# Colour background based on flood proneness & add a horizontal line for zero error
[axes[0].axvspan(j-0.48+1, j+0.48+1, alpha=0.08, facecolor=flha_colour, edgecolor='none') for j, flha_colour in enumerate(['red','green'])]
axes[0].axhline(y=0, linestyle='dashed', color='black', linewidth=0.8, alpha=0.3)
axes[0].set_xlim(0.5,2.5)
# Add legend & title
axes[0].set_title('a) By flood susceptibility, based on resampled NIWA raster [39]', x=0, ha='left', color='dimgrey', weight='bold', alpha=0.8)
# Plot 2: Residuals by HAND range
for k in range(1,6):
# Add boxplots to the figure
h = 'hand_{}'.format(k)
bps = axes[1].boxplot([res['initial']['by_hand'][h], res['rf']['by_hand'][h], res['dn']['by_hand'][h], res['cn']['by_hand'][h]], positions=[k-1.5*bp_offset, k-0.5*bp_offset, k+0.5*bp_offset, k+1.5*bp_offset], showfliers=False, medianprops={'color':'black'}, widths=bp_width, patch_artist=True)
for patch, colour in zip(bps['boxes'], bp_colours):
patch.set_facecolor(colour)
# Get RMSE associated with each set of residuals
RMSE_initial = np.sqrt(np.nanmean(np.square(res['initial']['by_hand'][h])))
RMSE_rf = np.sqrt(np.nanmean(np.square(res['rf']['by_hand'][h])))
RMSE_dn = np.sqrt(np.nanmean(np.square(res['dn']['by_hand'][h])))
RMSE_cn = np.sqrt(np.nanmean(np.square(res['cn']['by_hand'][h])))
# Calculate percentage improvement made by method
RMSE_rf_improve = (RMSE_initial - RMSE_rf)/RMSE_initial * 100.
RMSE_dn_improve = (RMSE_initial - RMSE_dn)/RMSE_initial * 100.
RMSE_cn_improve = (RMSE_initial - RMSE_cn)/RMSE_initial * 100.
# Determine which method achieved the highest improvement & label that point
RMSEs_ordered = [RMSE_rf, RMSE_dn, RMSE_cn]
best_index = np.argmin(RMSEs_ordered)
best_RMSE = RMSEs_ordered[best_index]
best_improve = [RMSE_rf_improve, RMSE_dn_improve, RMSE_cn_improve][best_index]
best_model = models[best_index]
best_colour = label_colours[best_model]
axes[1].annotate(u'RMSE \u2193\nby {:.0f}%'.format(best_improve), xy=(k/5 - 1/10, 0.98), xycoords='axes fraction', ha='center', va='top', size=10, color=best_colour)
# Add axis ticks & labels, and turn some spines off
axes[1].set_xticks(range(1,6))
axes[1].set_xticklabels(['{}\n[{:,} pixels]'.format(label, len(res['initial']['by_hand'][h])) for label, h in zip(['0 - 2 m','2 - 5 m','5 - 10 m','10 - 20 m','> 20 m'], ['hand_1','hand_2','hand_3','hand_4','hand_5'])])
axes[1].set_ylabel('Residuals before/after correction [m]')
[axes[1].spines[edge].set_visible(False) for edge in ['top','right']]
# Colour background based on graded blues & add a horizontal line for zero error
[axes[1].axvspan(k-0.45, k+0.45, alpha=0.1, facecolor=hand_colours[k-1], edgecolor='none') for k in range(1,6)]
axes[1].axhline(y=0, linestyle='dashed', color='black', linewidth=0.8, alpha=0.3)
axes[1].set_xlim(0.5,5.5)
# Add legend & title
axes[1].set_title('b) By height above nearest drainage (HAND) [68]', x=0, ha='left', color='dimgrey', weight='bold', alpha=0.8)
# Tighten up layout, add a common legend at the top & save figure
fig.tight_layout(pad=0, h_pad=1.8)
fig.subplots_adjust(top=0.93)
fig.legend(handles=bps['boxes'], labels=['Initial','RF','DCN','FCN'], frameon=False, ncol=4, loc='upper center', prop={'size':11})
fig.savefig('{}/residuals_boxplots_by_flha-hand.png'.format(folder_fig), dpi=300, bbox='tight')
plt.close()
###############################################################################
# 7. Check distribution of land cover, elevations & slopes in each dataset #
###############################################################################
# Read in 1D inputs for each dataset (training, validation, testing)
vectors_train = pd.read_csv('{}/Input1D_Train.csv'.format(folder_input_1D))
vectors_dev = pd.read_csv('{}/Input1D_Dev.csv'.format(folder_input_1D))
vectors_test = pd.read_csv('{}/Input1D_Test.csv'.format(folder_input_1D))
# 7a. Generate plot showing distribution of elevations & slope (by SRTM) for each dataset
fig, axes = plt.subplots(nrows=2, figsize=(8, 7))
# Extract elevation values from each dataset
z_train = vectors_train['srtm_z'].values
z_dev = vectors_dev['srtm_z'].values
z_test = vectors_test['srtm_z'].values
# Extract slope values from each dataset
slope_train = vectors_train['srtm_slope'].values
slope_dev = vectors_dev['srtm_slope'].values
slope_test = vectors_test['srtm_slope'].values
# Add elevation data as histograms
axes[0].hist([z_train, z_dev, z_test], color=dataset_colours, label=['Train','Validation','Test'], linewidth=2, alpha=0.5, bins=50, density=True, histtype='step', log=True)
axes[0].set_xlabel('SRTM Elevations [m]')
axes[0].set_ylabel('Relative frequency (log-scale)')
axes[0].set_title('a) Distribution of elevation values, by input dataset', x=0, size=10, ha='left', color='dimgrey', weight='bold', alpha=0.8)
[axes[0].spines[edge].set_visible(False) for edge in ['top','right']]
h0, l0 = axes[0].get_legend_handles_labels()
axes[0].legend(h0[::-1], l0[::-1], frameon=False, loc='upper right')
# Add slope data as histograms
axes[1].hist([slope_train, slope_dev, slope_test], color=dataset_colours, label=['Train','Validation','Test'], linewidth=2, alpha=0.5, bins=50, density=True, histtype='step', log=True)
axes[1].set_xlabel('Slopes - derived from SRTM elevations [%]')
axes[1].set_ylabel('Relative frequency (log-scale)')
axes[1].set_title('b) Distribution of slope values, by input dataset', x=0, size=10, ha='left', color='dimgrey', weight='bold', alpha=0.8)
[axes[1].spines[edge].set_visible(False) for edge in ['top','right']]
h1, l1 = axes[1].get_legend_handles_labels()
axes[1].legend(h1[::-1], l1[::-1], frameon=False, loc='upper right')
# Save figure
fig.tight_layout(h_pad=1.8)
fig.savefig('{}/inputdata_distribution_srtm_z-slope.png'.format(folder_fig), dpi=300)
plt.close()
# 7b. Generate plot showing distribution of land cover groups for each dataset
fig, axes = plt.subplots(nrows=3, sharex=True, figsize=(8,5))
lc_colours = [diff_by_landcover[i]['colour'] for i in range(1,8)]
lc_labels = [diff_by_landcover[i]['label'] for i in range(1,8)]
# Plot 1: Training data
lc_train_counts = [len(vectors_train[vectors_train['lcdb']==i].index) for i in range(1,8)]
lc_train_freq = [count/sum(lc_train_counts) for count in lc_train_counts]
axes[0].bar(x=range(1,8), height=lc_train_freq, color=lc_colours, alpha=0.7)
[axes[0].annotate('{:.1f}%'.format(freq*100), xy=(i, freq), ha='center', va='bottom') for i, freq in zip(range(1,8), lc_train_freq)]
axes[0].annotate('a) Training dataset', xy=(0.02, 0.98), xycoords='axes fraction', ha='left', va='top', fontweight='bold', color='dimgrey', alpha=0.8)
# Plot 2: Validation data
lc_dev_counts = [len(vectors_dev[vectors_dev['lcdb']==i].index) for i in range(1,8)]
lc_dev_freq = [count/sum(lc_dev_counts) for count in lc_dev_counts]
axes[1].bar(x=range(1,8), height=lc_dev_freq, color=lc_colours, alpha=0.7)
[axes[1].annotate('{:.1f}%'.format(freq*100), xy=(i, freq), ha='center', va='bottom') for i, freq in zip(range(1,8), lc_dev_freq)]
axes[1].annotate('b) Validation dataset', xy=(0.02, 0.98), xycoords='axes fraction', ha='left', va='top', fontweight='bold', color='dimgrey', alpha=0.8)
# Plot 3: Testing data
lc_test_counts = [len(vectors_test[vectors_test['lcdb']==i].index) for i in range(1,8)]
lc_test_freq = [count/sum(lc_test_counts) for count in lc_test_counts]
axes[2].bar(x=range(1,8), height=lc_test_freq, color=lc_colours, alpha=0.7)
[axes[2].annotate('{:.1f}%'.format(freq*100), xy=(i, freq), ha='center', va='bottom') for i, freq in zip(range(1,8), lc_test_freq)]
axes[2].annotate('c) Testing dataset', xy=(0.02, 0.98), xycoords='axes fraction', ha='left', va='top', fontweight='bold', color='dimgrey', alpha=0.8)
# Add figure labels, etc
[[[axes[i].spines[edge].set_visible(False)] for edge in ['top','right']] for i in [0,1,2]]