-
Notifications
You must be signed in to change notification settings - Fork 3
/
manual_tool.py
1299 lines (953 loc) · 45.7 KB
/
manual_tool.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
# must pass input --websocket-max-message-size=500000000
# or whatever number is closest to the size of the h5 files youre reading in from local
# otherwise typical h5 file will not be able to be passed and the server will close
# example command
# bokeh serve --show manual_tool.py --websocket-max-message-size=500000000
""
import pandas as pd
import numpy as np
import geopandas as gpd
import h5py
import os
import re
import sys
import datetime
import warnings
import pyproj
from tqdm import tqdm
from io import BytesIO
from pybase64 import b64decode
from pathlib import Path
from scipy.signal import peak_widths, find_peaks
from astropy.time import Time, TimeDatetime
from bokeh.plotting import figure, curdoc
from bokeh.models import CheckboxGroup, Button, Circle, TextInput, FileInput, RadioButtonGroup, Select, MultiChoice
from bokeh.models import DateRangeSlider, DatePicker, Dropdown
from bokeh.models import Paragraph, Div, Panel, Tabs
from bokeh.models import Range1d, ColumnDataSource, MultiLine, HoverTool
from bokeh.layouts import column, row
from bokeh.tile_providers import get_provider
from bokeh.server.server import Server
from sliderule import icesat2
from bokeh.models import BoxEditTool
import logging
# ########################## ICESAT2 FUNCTIONS ##############################
def photon_refraction(W, Z, ref_az, ref_el,
n1=1.00029, n2=1.34116):
'''
ICESat-2 refraction correction implented as outlined in Parrish, et al.
2019 for correcting photon depth data.
Highly recommended to reference elevations to geoid datum to remove sea
surface variations.
https://www.mdpi.com/2072-4292/11/14/1634
Code Author:
Jonathan Markel
Graduate Research Assistant
3D Geospatial Laboratory
The University of Texas at Austin
jonathanmarkel@gmail.com
Parameters
----------
W : float, or nx1 array of float
Elevation of the water surface.
Z : nx1 array of float
Elevation of seabed photon data. Highly recommend use of geoid heights.
ref_az : nx1 array of float
Photon-rate reference photon azimuth data. Should be pulled from ATL03
data parameter 'ref_azimuth'. Must be same size as seabed Z array.
ref_el : nx1 array of float
Photon-rate reference photon azimuth data. Should be pulled from ATL03
data parameter 'ref_elev'. Must be same size as seabed Z array.
n1 : float, optional
Refractive index of air. The default is 1.00029.
n2 : float, optional
Refractive index of water. Recommended to use 1.34116 for saltwater
and 1.33469 for freshwater. The default is 1.34116.
Returns
-------
dE : nx1 array of float
Easting offset of seabed photons.
dN : nx1 array of float
Northing offset of seabed photons.
dZ : nx1 array of float
Vertical offset of seabed photons.
'''
# compute uncorrected depths
D = W - Z
H = 496 # mean orbital altitude of IS2, km
Re = 6371 # mean radius of Earth, km
# angle of incidence (wout Earth curvature)
theta_1_ = (np.pi / 2) - ref_el
# incidence correction for earths curvature
theta_EC = np.arctan(H * np.tan(theta_1_) / Re)
# angle of incidence
theta_1 = theta_1_ + theta_EC
# angle of refraction
theta_2 = np.arcsin(n1 * np.sin(theta_1) / n2) # eq 1
phi = theta_1 - theta_2
# uncorrected slant range to the uncorrected seabed photon location
S = D / np.cos(theta_1) # eq 3
# corrected slant range
R = S * n1 / n2 # eq 2
P = np.sqrt(R**2 + S**2 - 2*R*S*np.cos(theta_1 - theta_2)) # eq 6
gamma = (np.pi / 2) - theta_1 # eq 4
alpha = np.arcsin(R * np.sin(phi) / P) # eq 5
beta = gamma - alpha # eq 7
# cross-track offset
dY = P * np.cos(beta) # eq 8
# vertical offset
dZ = P * np.sin(beta) # eq 9
kappa = ref_az
# UTM offsets
dE = dY * np.sin(kappa) # eq 10
dN = dY * np.cos(kappa) # eq 11
return dE, dN, dZ
def convert_seg_to_ph_res(segment_res_data,
ph_index_beg,
segment_ph_cnt,
total_ph_cnt):
'''Upsamples segment-rate data to the photon-rate.'''
# initialize photon resolution array
ph_res_data = pd.Series(np.nan, index=list(range(total_ph_cnt)))
# trim away segments without photon data
segs_with_data = segment_ph_cnt != 0
segment_ph_cnt = segment_ph_cnt[segs_with_data]
ph_index_beg = ph_index_beg[segs_with_data]
segment_res_data = segment_res_data[segs_with_data]
# set value for first photon in segment
ph_res_data.iloc[ph_index_beg - 1] = segment_res_data
ph_res_data.fillna(method='ffill', inplace=True)
return ph_res_data.values
def read_h5_as_df(h5_file_bytes_io, gtxx, conf_type=1, verbose=False):
if ((conf_type <= 0) or (conf_type >= 4)):
raise Exception('''Requested confidence type must be between
0 and 4 (land, ocean, sea ice, land ice and inland water).''')
# checks on beam input
if isinstance(gtxx, str):
# user input a single string like 'gt1r'
# check its the right format
gtxx = gtxx.lower()
if re.search('gt[1-3][lr]', gtxx) is None:
raise Exception(
'Unrecognized beam format. Use GT#(L/R) - for example, \'GT1R\'.')
# set up in iterable
gtxx = [gtxx]
elif isinstance(gtxx, list):
# user input a list of strings
# make all inputs lowercase and remove duplicates
gtxx = [g.lower() for g in gtxx]
gtxx = list(np.unique(gtxx))
# check all elements are the right format
if any(re.search('gt[1-3][lr]', g) is None for g in gtxx):
raise Exception(
'Unrecognized beam format. Use GT#(L/R) - for example, \'GT1R\'.')
pass
else:
raise Exception('''Requested beams must be either a string (e.g.\'gt1r\')
or list (e.g. [\'gt1r\', \'gt2l\']).''')
df_all = []
# if verbose:
# print(h5_file_path)
# print('File size: {:.2f} GB'.format(os.path.getsize(h5_file_path) / 1e9))
with h5py.File(h5_file_bytes_io, 'r') as f:
for beam in tqdm(gtxx):
pho = dict()
seg = dict()
anc = {}
if verbose:
print(beam.upper())
if verbose:
print('Reading photon-resolution data...')
##### PHOTON RESOLUTION DATA #####
lat_ph = np.array(f[beam + '/heights/lat_ph'])
lon_ph = np.array(f[beam + '/heights/lon_ph'])
pho['geometry'] = gpd.points_from_xy(lon_ph, lat_ph)
pho['delta_time'] = np.array(f[beam + '/heights/delta_time'])
pho['height'] = np.array(f[beam + '/heights/h_ph'])
# sliderule documentation not clear on this - skipping
#df['distance'] = np.array(f[gtxx + '/heights/dist_ph_along'])
pho['quality_ph'] = np.array(f[beam + '/heights/quality_ph'])
signal_conf = np.array(f[beam + '/heights/signal_conf_ph'])
# user input signal type
pho['atl03_cnf'] = signal_conf[:, conf_type]
if verbose:
print('Reading ancillary data...')
##### ANCILLARY / ORBIT DATA #####
# variable resolution
anc['atlas_sdp_gps_epoch'] = np.array(
f['/ancillary_data/atlas_sdp_gps_epoch'])
anc['sc_orient'] = np.array(
f['/orbit_info/sc_orient'])
anc['sc_orient_time'] = np.array(
f['/orbit_info/sc_orient'])
anc['rgt'] = np.array(
f['/orbit_info/rgt'])
pho['rgt'] = np.int64(anc['rgt'][0] * np.ones(len(lat_ph)))
anc['orbit_number'] = np.array(
f['/orbit_info/orbit_number'])
anc['cycle_number'] = np.array(
f['/orbit_info/cycle_number'])
pho['cycle'] = np.int64(
anc['cycle_number'][0] * np.ones(len(lat_ph)))
if len(anc['sc_orient']) == 1:
# no spacecraft transitions during this granule
pho['sc_orient'] = np.int64(
anc['sc_orient'][0] * np.ones(len(lat_ph)))
else:
warnings.warn(
'Spacecraft in transition detected! sc_orient parameter set to -1.')
pho['sc_orient'] = np.int64(-1 * np.ones(len(lat_ph)))
# track / pair data from user input
pho['track'] = np.int64(beam[2]) * \
np.ones(len(lat_ph), dtype=np.int64)
if beam[3].lower() == 'r':
pair_val = 1
elif beam[3].lower() == 'l':
pair_val = 0
pho['pair'] = pair_val * np.ones(len(lat_ph), dtype=np.int64)
if verbose:
print('Reading segment resolution data and upsampling...')
##### SEGMENT RESOLUTION DATA #####
seg['ref_azimuth'] = np.array(
f[beam + '/geolocation/ref_azimuth'])
seg['ref_elev'] = np.array(
f[beam + '/geolocation/ref_elev'])
seg['segment_id'] = np.array(
f[beam + '/geolocation/segment_id'])
seg['segment_dist_x'] = np.array(
f[beam + '/geolocation/segment_dist_x'])
seg['solar_azimuth'] = np.array(
f[beam + '/geolocation/solar_azimuth'])
seg['solar_elev'] = np.array(
f[beam + '/geolocation/solar_elevation'])
seg['ph_index_beg'] = np.array(
f[beam + '/geolocation/ph_index_beg'])
seg['segment_ph_cnt'] = np.array(
f[beam + '/geolocation/segment_ph_cnt'])
seg['geoid'] = np.array(
f[beam + '/geophys_corr/geoid'])
##### UPSAMPLE SEGMENT RATE DATA #####
pho['segment_id'] = np.int64(convert_seg_to_ph_res(segment_res_data=seg['segment_id'],
ph_index_beg=seg['ph_index_beg'],
segment_ph_cnt=seg['segment_ph_cnt'],
total_ph_cnt=len(lat_ph)))
pho['segment_dist'] = convert_seg_to_ph_res(segment_res_data=seg['segment_dist_x'],
ph_index_beg=seg['ph_index_beg'],
segment_ph_cnt=seg['segment_ph_cnt'],
total_ph_cnt=len(lat_ph))
pho['ref_azimuth'] = convert_seg_to_ph_res(segment_res_data=seg['ref_azimuth'],
ph_index_beg=seg['ph_index_beg'],
segment_ph_cnt=seg['segment_ph_cnt'],
total_ph_cnt=len(lat_ph))
pho['ref_elev'] = convert_seg_to_ph_res(segment_res_data=seg['ref_elev'],
ph_index_beg=seg['ph_index_beg'],
segment_ph_cnt=seg['segment_ph_cnt'],
total_ph_cnt=len(lat_ph))
pho['geoid_z'] = convert_seg_to_ph_res(segment_res_data=seg['geoid'],
ph_index_beg=seg['ph_index_beg'],
segment_ph_cnt=seg['segment_ph_cnt'],
total_ph_cnt=len(lat_ph))
if verbose:
print('Converting times...')
##### TIME CONVERSION / INDEXING #####
t_gps = Time(anc['atlas_sdp_gps_epoch'] +
pho['delta_time'], format='gps')
t_utc = Time(t_gps, format='iso', scale='utc')
pho['time'] = t_utc.datetime
# sorting into the same order as sliderule df's purely for asthetics
if verbose:
print('Concatenating data...')
df = gpd.GeoDataFrame(pho)
df.set_index('time', inplace=True)
df = df.loc[:, ['rgt', 'cycle', 'track', 'segment_id', 'segment_dist',
'sc_orient', 'atl03_cnf', 'height', 'quality_ph', 'delta_time', 'pair', 'geometry',
'ref_azimuth', 'ref_elev']]
df_all.append(df)
return pd.concat(df_all)
def reduce_gdf(gdf, RGT=None, track=None, pair=None, cycle=None):
''''''
D = gdf.copy()
if RGT is not None:
D = D[D.loc[:, 'rgt'] == RGT]
if track is not None:
D = D[D.loc[:, 'track'] == track]
if pair is not None:
D = D[D.loc[:, 'pair'] == pair]
if cycle is not None:
D = D[D.loc[:, 'cycle'] == cycle]
return D
# def bkapp(doc):
# ########################## DATA SETUP ##############################
# local, sliderule
data_origin = None
surface_class = 41
no_bottom_class = 45
bathy_class = 40
gt_labels = ['gt1r', 'gt1l', 'gt2r', 'gt2l', 'gt3r', 'gt3l']
df_cols = ['lon', 'lat', 'rgt', 'cycle', 'track', 'segment_id', 'segment_dist', 'sc_orient',
'atl03_cnf', 'height', 'quality_ph', 'delta_time', 'pair',
'ref_azimuth', 'ref_elev', 'x_wm', 'y_wm',
'height_ortho', 'classification', 'surface_height', 'surface_sigma', 'dZ', 'height_ortho_c']
gdf_empty = pd.DataFrame([], columns=df_cols)
# source to hold all h5 data
src = ColumnDataSource(data=gdf_empty)
# source to hold data for individual beams
src_gt = ColumnDataSource(data=gdf_empty)
# source to manage plotting of all photon data
plt_src = ColumnDataSource(data=gdf_empty)
# source to hold data for individual beams - subsampled for plotting
src_gt_sub = ColumnDataSource(data=gdf_empty)
# sources for individual track classified data
sfc_src = ColumnDataSource(data=gdf_empty)
subsfc_src = ColumnDataSource(data=gdf_empty)
bathy_src = ColumnDataSource(data=gdf_empty)
# bounding box
bbox = pd.DataFrame([], index=['x', 'y', 'w', 'h']).T
bbox_src = ColumnDataSource(bbox)
rake_src = ColumnDataSource(data=pd.DataFrame([]))
# ########################## WIDGET / CALLBACK SETUP ##############################
# Select input h5 file
w_file_input = FileInput(accept=".h5", sizing_mode="stretch_width")
def import_h5(attr, old, new):
w_status_box.text = 'Loading h5...'
decoded = b64decode(w_file_input.value)
f = BytesIO(decoded)
# h = h5py.File(f,'r')
gdf1 = read_h5_as_df(f,
gt_labels,
conf_type=1, verbose=False)
# coords/conversions
gdf1.insert(0, 'lat', gdf1.geometry.y, False)
gdf1.insert(0, 'lon', gdf1.geometry.x, False)
wgs84 = pyproj.crs.CRS.from_epsg(4979)
wgs84_egm08 = pyproj.crs.CRS.from_epsg(3855)
tform = pyproj.transformer.Transformer.from_crs(
crs_from=wgs84, crs_to=wgs84_egm08)
_, _, z_g = tform.transform(gdf1.geometry.y, gdf1.geometry.x, gdf1.height)
gdf1.insert(0, 'height_ortho', z_g, False)
# allocation of to be used arrays
gdf1.insert(0, 'classification', np.int64(np.zeros_like(z_g)), False)
gdf1.insert(0, 'surface_height', np.nan*np.zeros_like(z_g), False)
gdf1.insert(0, 'surface_sigma', np.nan*np.zeros_like(z_g), False)
gdf1.insert(0, 'height_ortho_c', np.nan*np.zeros_like(z_g), False)
gdf1.insert(0, 'dZ', np.zeros_like(z_g), False)
# color_arr = np.chararray(np.shape(z_g), itemsize=7)
# color_arr[:] = unclass_color
# gdf1.insert(0, 'color', color_arr, False)
src.data = gdf1.drop('geometry', axis=1)
# enable the gtxx selector boxes
w_gt_select.disabled = False
w_status_box.text = 'Successfully imported H5 file. Use tabs on left to select a beam.'
global data_origin
data_origin = 'local'
w_file_input.on_change('value', import_h5)
# Buttons to select which beam youre classifying
w_gt_select = RadioButtonGroup(labels=gt_labels,
disabled=True, sizing_mode="stretch_width")
def select_profile(attr, old, new):
# make the imagery window visible
imagery_renderer = fig_imagery.select_one({'name': 'tile_renderer'})
imagery_renderer.visible = True
# start fresh with classes in case the user is coming from another tab
src_gt.data = gdf_empty
plt_src.data = gdf_empty
src_gt_sub.data = gdf_empty
sfc_src.data = gdf_empty
subsfc_src.data = gdf_empty
bathy_src.data = gdf_empty
src_gt.selected.indices = []
plt_src.selected.indices = []
src_gt_sub.selected.indices = []
sfc_src.selected.indices = []
subsfc_src.selected.indices = []
bathy_src.selected.indices = []
w_save_button.disabled = False
surface_line = fig_primary.select_one({'name': 'surface_model'})
surface_line.visible = True
########
global data_origin
if data_origin == 'local':
# data loaded from local h5
pair_char = gt_labels[new][3]
track_ = np.int64(gt_labels[new][2])
if pair_char == 'l':
pair_ = 0
elif pair_char == 'r':
pair_ = 1
gdf_ = reduce_gdf(pd.DataFrame(src.data), track=track_, pair=pair_)
# update name of output file
w_out_name.value = re.sub('ATL03', 'BATHY',
w_file_input.filename[:-3] + '_' + gt_labels[w_gt_select.active].upper())
elif data_origin == 'sliderule':
print(attr)
print(new.split())
track_data = new.split(' ')
rgt_ = np.int64(track_data[0])
cycle_ = np.int64(track_data[1])
track_ = np.int64(track_data[2])
pair_ = np.int64(track_data[3])
gdf_ = reduce_gdf(pd.DataFrame(src.data),
RGT=rgt_,
track=track_,
pair=pair_,
cycle=cycle_)
# update name of output file
w_out_name.value = 'BATHY_API_' + \
re.sub('-', '', w_sr_dates.value) + '_' + \
re.sub(' ', '_', w_sr_tracks.value)
# print(pair_, track_)
src_gt.data = gdf_ # profile data
# profile data, subsampled for plotting
src_gt_sub.data = gdf_.sample(min(int(1e5), gdf_.shape[0]))
# convert sampled gdf lat lon to web mercator for plotting
wgs84 = pyproj.crs.CRS.from_epsg(4979)
web_merc = pyproj.crs.CRS.from_epsg(3857)
tform = pyproj.transformer.Transformer.from_crs(
crs_from=wgs84, crs_to=web_merc)
# src_gt_sub.data['y_wm'], src_gt_sub.data['x_wm'] = tform.transform(src_gt_sub.data['lat'],
# src_gt_sub.data['lon'])
src_gt.data['x_wm'], src_gt.data['y_wm'] = tform.transform(
src_gt.data['lat'], src_gt.data['lon'])
# update imagery window
fig_imagery.x_range.start = min(src_gt.data['x_wm'])
fig_imagery.x_range.end = max(src_gt.data['x_wm'])
fig_imagery.y_range.start = min(src_gt.data['y_wm'])
fig_imagery.y_range.end = max(src_gt.data['y_wm'])
# update primary window details
fig_primary.xaxis.axis_label = 'Latitude (deg)'
fig_primary.yaxis.axis_label = 'Orthometric Height (m)'
# enable water surface calculation button
w_surface_button.disabled = False
w_select_button.disabled = True
w_refract_button.disabled = True
w_save_button.disabled = True
w_save_button.button_type = 'default'
w_save_button.label = 'Save Data to Output'
# update primary plot/remove legend
plt_src.data = dict(src_gt.data)
fig_primary.legend.visible = False
w_gt_select.on_change('active', select_profile)
# Button to start water surface modeling
w_surface_button = Button(label='Model Water Surface',
disabled=True, sizing_mode="stretch_width")
def model_surface():
if src_gt.data['segment_id'] != []:
# calculate water surface model
# tweakable parameters
z_bin_size = 0.1
# vertical bins from 100m depth to 50m above 0 datum
z_bin_edges = np.arange(-25, 75 + z_bin_size, z_bin_size)
z_centered_bins = z_bin_edges[:-1] + z_bin_size
# at each 20m segment evaluate the 400m on either side
process_chunk_half_width = 20
for seg_i in tqdm(np.arange(src_gt.data['segment_id'].min(), src_gt.data['segment_id'].max(), 5)):
# index for segment processing window
chunk_i = (src_gt.data['segment_id'] >= (seg_i-process_chunk_half_width)) \
& (src_gt.data['segment_id'] <= (seg_i+process_chunk_half_width))
#gdf_seg = gdf1.loc[ chunk_i , : ]
depth = -src_gt.data['height_ortho'][chunk_i]
hist, _ = np.histogram(depth, bins=z_bin_edges)
# print(hist)
# find peaks
pk_i, pk_dict = find_peaks(hist)
pk_dict['fwhm'], pk_dict['width_heights_hm'], pk_dict['left_ips_hm'], pk_dict['right_ips_hm'] \
= peak_widths(hist, pk_i, rel_height=0.4)
pk_dict['i'] = pk_i
pk_dict['heights'] = hist[pk_dict['i']]
# estimate standard deviation
# std. dev. est.
pk_dict['sigma_est'] = z_bin_size * (pk_dict['fwhm'] / 2.35)
# get z value of peak
pk_dict['z'] = z_centered_bins[pk_dict['i']]
pk_df = pd.DataFrame.from_dict(pk_dict, orient='columns')
pk_df.sort_values(by='heights', inplace=True, ascending=False)
if pk_df.shape[0] == 0:
# no peaks in segment
src_gt.data['surface_height'][chunk_i] = -99
continue
else:
surf_pk = pk_df.iloc[0]
src_gt.data['surface_height'][chunk_i] = -surf_pk.z
src_gt.data['surface_sigma'][chunk_i] = surf_pk.sigma_est
lower_bound = (src_gt.data['surface_height'] -
3*src_gt.data['surface_sigma'])
upper_bound = (src_gt.data['surface_height'] +
3*src_gt.data['surface_sigma'])
surf_idx = (src_gt.data['height_ortho'] >= lower_bound) \
& (src_gt.data['height_ortho'] <= upper_bound)
subsurf_idx = (src_gt.data['height_ortho'] < lower_bound)
# update surface and subsurface classifications
src_gt.data['classification'][surf_idx] = surface_class
src_gt.data['classification'][subsurf_idx] = no_bottom_class
# update plotting data with new surface data for passing later
plt_src.data = dict(src_gt.data)
w_select_button.disabled = False
w_surface_button.disabled = True
w_surface_button.on_click(model_surface)
# Button to begin point selection
w_select_button = Button(label='Begin Point Selection',
disabled=True,
sizing_mode="stretch_width")
def select_bathy():
# make the lasso tool active
# remove the water surface model from the plot
# or get the glyph from the Figure:
surface_line = fig_primary.select_one({'name': 'surface_model'})
surface_line.visible = False
# remove the legend from the plot
fig_primary.legend.visible = False
# change the subsurface points to black just for this selection step
subsurface_renderer = fig_primary.select_one({'name': 'subsurface'})
subsurface_renderer.glyph.fill_color = 'black'
subsurface_renderer.glyph.line_color = 'black'
subsurface_renderer.selection_glyph.size = 0.5
subsurface_renderer.selection_glyph.fill_color = 'red'
subsurface_renderer.selection_glyph.line_color = 'red'
subsurface_renderer.nonselection_glyph.size = 0.5
subsurface_renderer.nonselection_glyph.fill_color = 'black'
subsurface_renderer.nonselection_glyph.line_color = 'black'
# get index of surface classifications
surf_idx = plt_src.data['classification'] == surface_class
# add all subsurface data to subsurface plot source and remove the intermediate plotting data
rm_idx = ((plt_src.data['height_ortho'] >=
plt_src.data['surface_height']) | surf_idx)
subsfc_src.data = {key: value[~rm_idx]
for (key, value) in plt_src.data.items()}
plt_src.data = gdf_empty
# enable selection tool
w_refract_button.disabled = False
w_select_button.disabled = True
w_select_button.on_click(select_bathy)
# Button to start refraction correction and update plots/data
w_refract_button = Button(label='Calculate Refraction',
disabled=True,
sizing_mode="stretch_width")
def correct_refraction():
# switch subsurface photons back to gray for background
subsurface_renderer = fig_primary.select_one({'name': 'subsurface'})
subsurface_renderer.glyph.fill_color = 'grey'
subsurface_renderer.glyph.line_color = 'grey'
subsurface_renderer.selection_glyph.size = 0.5
subsurface_renderer.selection_glyph.fill_color = 'grey'
subsurface_renderer.selection_glyph.line_color = 'grey'
subsurface_renderer.nonselection_glyph.size = 0.5
subsurface_renderer.nonselection_glyph.fill_color = 'grey'
subsurface_renderer.nonselection_glyph.line_color = 'grey'
# disable lasso?
# disable point selection button
w_select_button.disabled = True
# for all selected points
bathy_idx = subsfc_src.selected.indices
subsfc_src.selected.indices = []
bathy_bool = np.zeros((len(subsfc_src.data['height']),), dtype=bool)
bathy_bool[bathy_idx] = True
# update classifications before passing data along to bathy_src holder
subsfc_src.data['classification'][bathy_bool] = bathy_class
bathy_src.data = {key: value[bathy_bool]
for (key, value) in subsfc_src.data.items()}
# remove bathy from subsurface noise data handler
subsfc_src.data = {key: value[~bathy_bool]
for (key, value) in subsfc_src.data.items()}
# check that all points to be refracted have all required fields
ref_el_bad = np.any(np.isnan(bathy_src.data['ref_elev']))
ref_az_bad = np.any(np.isnan(bathy_src.data['ref_azimuth']))
if ref_el_bad or ref_az_bad:
w_status_box.text = "WARNING: UNABLE TO CALCULATE EXACT REFRACTION CORRECTION. APPROXIMATING WITHOUT PLANIMETRIC COMPONENT."
D = bathy_src.data['surface_height'] - bathy_src.data['height_ortho']
bathy_src.data['dZ'] = 0.25416 * D
else:
# calculate refraction, assuming good data
_, _, bathy_src.data['dZ'] = photon_refraction(W=bathy_src.data['surface_height'],
Z=bathy_src.data['height_ortho'],
ref_az=bathy_src.data['ref_azimuth'],
ref_el=bathy_src.data['ref_elev'],
n1=1.00029, n2=1.34116)
bathy_src.data['height_ortho_c'] = bathy_src.data['height_ortho'] + \
bathy_src.data['dZ']
# reactivate surface photons on plot
surf_idx = (src_gt.data['classification'] == surface_class)
sfc_src.data = {key: value[surf_idx]
for (key, value) in src_gt.data.items()}
fig_primary.legend.visible = True
# disable calculate refraction button
w_refract_button.disabled = True
w_save_button.disabled = False
w_refract_button.on_click(correct_refraction)
# Text box for specifying directory to output data
w_out_path = TextInput(title="Output directory:",
value=os.getcwd(),
disabled=False,
sizing_mode="stretch_width")
# trying to change the text background red if the output directory doesnt exist - buggy
def check_out_dir_exists(attr, old, new):
if not Path(w_out_path.value_input).exists():
w_out_path.background = 'red'
else:
w_out_path.background = 'white'
w_out_path.on_change('value_input', check_out_dir_exists)
# Text box for specifying what the output file name should be
w_out_name = TextInput(title="Output file name base:",
disabled=False,
sizing_mode="stretch_width")
# Check boxes to select output file types
w_checkbox_text = Paragraph(
text="""Select output file types (more coming soon...)""")
w_checkbox_out_type = CheckboxGroup(
labels=['csv'], active=[0], disabled=True, sizing_mode="stretch_width")
# Button to write refraction corrected data to output files
w_save_button = Button(label='Save Data to Output',
disabled=True,
sizing_mode="stretch_width")
def save_output():
csv_output_path = os.path.join(w_out_path.value,
w_out_name.value + '.csv')
# combine surface data, bathy data, subsurface data
df_comb = pd.concat([pd.DataFrame(bathy_src.data),
pd.DataFrame(sfc_src.data),
pd.DataFrame(subsfc_src.data)])
if 0 in w_checkbox_out_type.active:
# csv checked
df_out = df_comb.loc[:,
['lon', 'lat',
'height_ortho', 'classification',
'surface_height', 'surface_sigma', 'dZ']]
df_out.to_csv(csv_output_path, index=False)
w_save_button.button_type = 'success'
w_save_button.label = 'Output Saved!'
w_save_button.disabled = True
print()
w_save_button.on_click(save_output)
# Button to end the underlying bokeh server
# need to add a lifecycle hook to close it on tab closure too
w_quit_button = Button(label='END SESSION',
disabled=False,
button_type='danger',
sizing_mode="stretch_width")
def close_app():
sys.exit
w_quit_button.on_click(close_app)
w_status_box = Div(text="""status updates to go here...""",
height=30)
# Widgets/callbacks for Sliderule query tab
# w_date_slider = DateRangeSlider(value=(datetime.date(2020, 6, 1), datetime.date(2020, 7, 1)),
# start=datetime.date(2018, 9, 15), end=datetime.date.today())
w_date_picker_start = DatePicker(title='Start Date',
value="2021-06-01",
min_date="2018-09-15",
max_date=datetime.date.today(),
width=150)
w_date_picker_end = DatePicker(title='End Date',
value="2021-06-15",
min_date="2018-09-15",
max_date=datetime.date.today(),
width=150)
# when start date is selected, update min date possible in end widget
def update_end_date_widget(attr, old, new):
w_date_picker_end.min_date = w_date_picker_start.value
w_date_picker_start.on_change('value', update_end_date_widget)
# when end date is selected, update max date possible in start widget
def update_start_date_widget(attr, old, new):
w_date_picker_start.max_date = w_date_picker_end.value
w_date_picker_end.on_change('value', update_start_date_widget)
# window to select bounding box
# see figure call (fig_bbox) in format/plot section
# this here doesnt actually work
# def bbox_updated(attr, old, new):
# w_status_box.text = 'New bounding box selected...'
# bathy_src.on_change('data', bbox_updated)
# which data release to download
w_release_select = Select(title="Release Version:",
value="005", options=["005"])
w_surftype_select = Select(
title='ATL03 Photon Surface Type', value='1', options=['0', '1', '2', '3', '4'])
conf_list = ["atl03_tep", "atl03_not_considered", "atl03_background",
"atl03_within_10m", "atl03_low", "atl03_medium", "atl03_high"]
conf_list_sub = ["atl03_background", "atl03_low",
"atl03_medium", "atl03_high", "atl03_within_10m"]
w_conf_select = MultiChoice(
title="ATL03 Photon Confidence", value=conf_list_sub, options=conf_list)
# button to finalize bounding box and begin query
w_query_button = Button(label='Submit Query',
disabled=False,
button_type='success',
sizing_mode=None)
def query_sliderule():
global data_origin
data_origin = 'sliderule'
# first, convert bokeh height/width format to bbox corners
# upper left, bottom left, bottom right, upper right, upper left
x_wm_bbox = [bbox_src.data['x'][0] - bbox_src.data['w'][0]/2,
bbox_src.data['x'][0] - bbox_src.data['w'][0]/2,
bbox_src.data['x'][0] + bbox_src.data['w'][0]/2,
bbox_src.data['x'][0] + bbox_src.data['w'][0]/2,
bbox_src.data['x'][0] - bbox_src.data['w'][0]/2]
y_wm_bbox = [bbox_src.data['y'][0] + bbox_src.data['h'][0]/2,
bbox_src.data['y'][0] - bbox_src.data['h'][0]/2,
bbox_src.data['y'][0] - bbox_src.data['h'][0]/2,
bbox_src.data['y'][0] + bbox_src.data['h'][0]/2,
bbox_src.data['y'][0] + bbox_src.data['h'][0]/2]
# convert bbox from web mercator to lat/lon
wgs84 = pyproj.crs.CRS.from_epsg(4979)
web_merc = pyproj.crs.CRS.from_epsg(3857)
tform = pyproj.transformer.Transformer.from_crs(
crs_from=web_merc, crs_to=wgs84)
lat, lon = tform.transform(x_wm_bbox, y_wm_bbox)
# actual querying code
url = "icesat2sliderule.org"
icesat2.init(url, verbose=True, loglevel=logging.DEBUG)
asset = "nsidc-s3"
# convert bbox corners to Sliderule compatible region data
sr_reg = icesat2.toregion(gpd.GeoDataFrame(
geometry=gpd.points_from_xy(lon, lat)))
# Select release
time_start = datetime.datetime.strptime(
w_date_picker_start.value, "%Y-%m-%d").date().strftime('%Y-%m-%dT%H:%M:%SZ')
time_end = datetime.datetime.strptime(
w_date_picker_end.value, "%Y-%m-%d").date().strftime('%Y-%m-%dT%H:%M:%SZ')
print('***** CMR')
granules_list = icesat2.cmr(polygon=sr_reg[0], version=w_release_select.value, short_name='ATL03',
time_start=time_start,
time_end=time_end)
print(granules_list)
# print(w_surftype_select.value, w_conf_select.value, w_release_select.value)
params = {}
params['poly'] = sr_reg[0]
params['srt'] = int(w_surftype_select.value)
params['cnf'] = w_conf_select.value
print('querying...')
gdf = icesat2.atl03sp(params,
asset=asset,
version=w_release_select.value,
resources=granules_list)
print('DONE')