/
asf_notebook.py
655 lines (508 loc) · 21.1 KB
/
asf_notebook.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
# asf_notebook.py
# Alex Lewandowski, Rui Kawahara
# Nov-03-2021
# Module of Alaska Satellite Facility OpenSARLab Jupyter Notebook helper functions
import os # for chdir, getcwd, path.exists
import re
from typing import List
import requests # for post, get
from getpass import getpass # used to input URS creds and add to .netrc
import zipfile # for extractall, ZipFile, BadZipFile
from datetime import datetime, date
import glob
import sys
import subprocess
from osgeo import gdal # for Open
import numpy as np
import pandas as pd
import warnings
from matplotlib.widgets import RectangleSelector
import matplotlib.pyplot as plt
import matplotlib.patches as patches
plt.rcParams.update({'font.size': 12})
from IPython.display import Markdown
from IPython.display import display
import ipywidgets as widgets
from ipywidgets import Layout
from hyp3_sdk import Batch
import asf_search as asf
def deprecation_warn(stacklevel=4):
warnings.warn("asf_notebook is deprecated and has been replaced with opensarlab-lib",
DeprecationWarning, stacklevel=stacklevel)
deprecation_warn(3)
#######################
# Utility Functions #
#######################
def path_exists(path: str) -> bool:
"""
Takes a string path, returns true if exists or
prints error message and returns false if it doesn't.
"""
deprecation_warn()
assert type(path) == str, 'Error: path must be a string'
if os.path.exists(path):
return True
else:
print(f"Invalid Path: {path}")
return False
def new_directory(path: str):
"""
Takes a path for a new or existing directory. Creates directory
and sub-directories if not already present.
"""
deprecation_warn()
assert type(path) == str
if os.path.exists(path):
print(f"{path} already exists.")
else:
os.makedirs(path)
print(f"Created: {path}")
if not os.path.exists(path):
print(f"Failed to create path!")
def asf_unzip(output_dir: str, file_path: str):
"""
Takes an output directory path and a file path to a zipped archive.
If file is a valid zip, it extracts all to the output directory.
"""
deprecation_warn()
warnings.warn("asf_notebook is deprecated and has been replaced with opensarlab-lib",
DeprecationWarning, stacklevel=1)
ext = os.path.splitext(file_path)[1]
assert type(output_dir) == str, 'Error: output_dir must be a string'
assert type(file_path) == str, 'Error: file_path must be a string'
assert ext == '.zip', 'Error: file_path must be the path of a zip'
if path_exists(output_dir):
if path_exists(file_path):
print(f"Extracting: {file_path}")
try:
zipfile.ZipFile(file_path).extractall(output_dir)
except zipfile.BadZipFile:
print(f"Zipfile Error.")
return
def get_power_set(my_set, set_size=None):
"""
my_set: list or set of strings
set_size: deprecated, kept as optional for backwards compatibility
returns: the power set of input strings
"""
deprecation_warn()
p_set = set()
if len(my_set) > 1:
pow_set_size = 1 << len(my_set) # 2^n
for counter in range(0, pow_set_size):
temp = ""
for j in range(0, len(my_set)):
if(counter & (1 << j) > 0):
if temp != "":
temp = f"{temp} and {my_set[j]}"
else:
temp = my_set[j]
if temp != "":
p_set.add(temp)
else:
p_set = set(my_set)
return p_set
def remove_nan_filled_tifs(tif_dir: str, file_names: list):
"""
Takes a path to a directory containing tifs and
and a list of the tif filenames.
Deletes any tifs containing only NaN values.
"""
deprecation_warn()
assert type(tif_dir) == str, 'Error: tif_dir must be a string'
assert len(file_names) > 0, 'Error: file_names must contain at least 1 file name'
removed = 0
for tiff in file_names:
raster = gdal.Open(f"{tif_dir}{tiff}")
if raster:
band = raster.ReadAsArray()
if np.count_nonzero(band) < 1:
os.remove(f"{tif_dir}{tiff}")
removed += 1
print(f"GeoTiffs Examined: {len(file_names)}")
print(f"GeoTiffs Removed: {removed}")
def input_path(prompt):
deprecation_warn()
print(f"Current working directory: {os.getcwd()}")
print(prompt)
return input()
def handle_old_data(data_dir, contents):
deprecation_warn()
print(f"\n********************** WARNING! **********************")
print(f"The directory {data_dir} already exists and contains:")
for item in contents:
print(f"• {item.split('/')[-1]}")
print(f"\n\n[1] Delete old data and continue.")
print(f"[2] Save old data and add the data from this analysis to it.")
print(f"[3] Save old data and pick a different subdirectory name.")
while True:
try:
selection = int(input("Select option 1, 2, or 3.\n"))
except ValueError:
continue
if selection < 1 or selection > 3:
continue
return selection
#########################
# OpenSARlab Functions #
#########################
def jupytertheme_matplotlib_format() -> bool:
"""
If recognised jupytertheme dark mode is being used,
reformat matplotlib settings for improved dark mode visibility.
Return True if matplotlib settings adjusted or False if not
"""
deprecation_warn()
try:
from jupyterthemes import jtplot
print(f"jupytertheme style: {jtplot.infer_theme()}")
if jtplot.infer_theme() in ('osl_dark', 'onedork'):
plt.rcParams.update({'hatch.color': 'white'})
plt.rcParams.update({'axes.facecolor': 'lightgrey'})
plt.rcParams.update({'axes.labelcolor': 'white'})
plt.rcParams.update({'xtick.color': 'lightgrey'})
plt.rcParams.update({'ytick.color': 'lightgrey'})
return True
except ModuleNotFoundError:
print("jupytertheme not installed")
pass
return False
###################
# GDAL Functions #
###################
def vrt_to_gtiff(vrt: str, output: str):
deprecation_warn()
if '.vrt' not in vrt:
print('Error: The path to your vrt does not contain a ".vrt" extension.')
return
if '.' not in output:
output = f"{output}.tif"
elif len(output) > 4 and (output[:-3] == 'tif' or output[:-4] == 'tiff'):
print('Error: the output argument must either not contain a ' /
'file extension, or have a "tif" or "tiff" file extension.')
return
cmd = f"gdal_translate -co \"COMPRESS=DEFLATE\" -a_nodata 0 {vrt} {output}"
sub = subprocess.run(cmd, stderr=subprocess.PIPE, shell=True)
print(str(sub.stderr)[2: -3])
#########################
# Hyp3v2 API Functions #
#########################
def get_RTC_projects(hyp3):
deprecation_warn()
return hyp3.my_info()['job_names']
def get_job_dates(jobs: List[str]) -> List[str]:
deprecation_warn()
dates = set()
for job in jobs:
for granule in job.job_parameters['granules']:
dates.add(date_from_product_name(granule).split('T')[0])
return list(dates)
def filter_jobs_by_date(jobs, date_range):
deprecation_warn()
remaining_jobs = Batch()
for job in jobs:
for granule in job.job_parameters['granules']:
dt = date_from_product_name(granule).split('T')[0]
aquistion_date = date(int(dt[:4]), int(dt[4:6]), int(dt[-2:]))
if date_range[0] <= aquistion_date <= date_range[1]:
remaining_jobs += job
break
return remaining_jobs
def get_paths_orbits(jobs):
deprecation_warn()
vertex_API_URL = "https://api.daac.asf.alaska.edu/services/search/param"
for job in jobs:
granule_metadata = asf.granule_search(job.job_parameters['granules'])[0]
job.path = granule_metadata.properties['pathNumber']
job.orbit_direction = granule_metadata.properties['flightDirection']
return jobs
def filter_jobs_by_path(jobs, paths):
deprecation_warn()
if 'All Paths' in paths:
return jobs
remaining_jobs = Batch()
for job in jobs:
if job.path in paths:
remaining_jobs += job
return remaining_jobs
def filter_jobs_by_orbit(jobs, orbit_direction):
deprecation_warn()
remaining_jobs = Batch()
for job in jobs:
if job.orbit_direction == orbit_direction:
remaining_jobs += job
return remaining_jobs
#######################################
# Product Related Utility Functions #
#######################################
def get_product_info(granules: dict, products_info: list, date_range: list) -> dict:
deprecation_warn()
paths = []
directions = []
urls = []
vertex_API_URL = "https://api.daac.asf.alaska.edu/services/search/param"
for granule_name in granules:
dt = date_from_product_name(granule_name)
if dt:
dt = dt.split('T')[0]
else:
continue
if date(int(dt[:4]), int(dt[4:6]), int(dt[-2:])) >= date_range[0]:
if date(int(dt[:4]), int(dt[4:6]), int(dt[-2:])) <= date_range[1]:
parameters = [('granule_list', granule_name), ('output', 'json')]
try:
response = requests.post(
vertex_API_URL,
params=parameters,
stream=True
)
except requests.exceptions.RequestException as e:
print(e)
sys.exit(1)
json_response = None
if response.json()[0]:
json_response = response.json()[0][0]
local_queue_id = granules[granule_name]
for p_info in products_info:
if p_info['local_queue_id'] == local_queue_id:
try:
paths.append(json_response['track'])
directions.append(json_response['flightDirection'])
urls.append(p_info['url'])
except TypeError:
print(f"TypeError: json_response for {granule_name}: {json_response}")
pass
break
return {'paths': paths, 'directions': directions, 'urls': urls}
def date_from_product_name(product_name: str) -> str:
deprecation_warn()
regex = "\w[0-9]{7}T[0-9]{6}"
results = re.search(regex, product_name)
if results:
return results.group(0)
else:
return None
def get_products_dates(products_info: list) -> list:
deprecation_warn()
dates = []
for info in products_info:
date_regex = "\w[0-9]{7}T[0-9]{6}"
date_strs = re.findall(date_regex, info['granule'])
if date_strs:
for d in date_strs:
dates.append(d[0:8])
dates.sort()
dates = list(set(dates))
return dates
# get_products_dates_insar will be deprecated in the
# near future as it is now duplicted in get_products_dates
def get_products_dates_insar(products_info: list) -> list:
deprecation_warn()
dates = []
for info in products_info:
date_regex = "\w[0-9]{7}T[0-9]{6}"
date_strs = re.findall(date_regex, info['granule'])
if date_strs:
for d in date_strs:
dates.append(d[0:8])
dates.sort()
dates = list(set(dates))
return dates
######################################
# Jupyter Notebook Widget Functions #
######################################
def gui_date_picker(dates: list) -> widgets.SelectionRangeSlider:
deprecation_warn()
start_date = datetime.strptime(min(dates), '%Y%m%d')
end_date = datetime.strptime(max(dates), '%Y%m%d')
date_range = pd.date_range(start_date, end_date, freq='D')
options = [(date.strftime(' %m/%d/%Y '), date) for date in date_range]
index = (0, len(options)-1)
selection_range_slider = widgets.SelectionRangeSlider(
options = options,
index = index,
description = 'Dates',
orientation = 'horizontal',
layout = {'width': '500px'})
return(selection_range_slider)
def get_slider_vals(selection_range_slider: widgets.SelectionRangeSlider) -> list:
'''Returns the minimum and maximum dates retrieved from the
interactive time slider.
Parameters:
- selection_range_slider: Handle of the interactive time slider
'''
deprecation_warn()
[a,b] = list(selection_range_slider.value)
slider_min = a.to_pydatetime()
slider_max = b.to_pydatetime()
return[slider_min, slider_max]
def get_polarity_from_path(path: str) -> str:
"""
Takes a path to a HyP3 product containing its polarity in its filename
Returns the polarity string or none if not found
"""
deprecation_warn()
path = os.path.basename(path)
regex = "(v|V|h|H){2}"
return re.search(regex, path).group(0)
def get_RTC_polarizations(base_path: str) -> list:
"""
Takes a string path to a directory containing RTC product directories
Returns a list of present polarizations
"""
deprecation_warn()
assert type(base_path) == str, 'Error: base_path must be a string.'
assert os.path.exists(base_path), f"Error: select_RTC_polarization was passed an invalid base_path, {base_path}"
paths = []
pths = glob.glob(f"{base_path}/*/*.tif")
if len(pths) > 0:
for p in pths:
filename = os.path.basename(p)
polar_fname = re.search("^\w[\--~]{5,300}(_|-)(vv|VV|vh|VH|hh|HH|hv|HV).(tif|tiff)$", filename)
if polar_fname:
paths.append(polar_fname.string.split('.')[0][-2:])
if len(paths) > 0:
return list(set(paths))
else:
print(f"Error: found no available polarizations.")
def select_parameter(things, description=""):
deprecation_warn()
return widgets.RadioButtons(
options=things,
description=description,
disabled=False,
layout=Layout(min_width='800px')
)
def select_mult_parameters(things, description="", width='175px'):
deprecation_warn()
height = len(things) * 19
return widgets.SelectMultiple(
options=things,
description=description,
disabled=False,
layout=widgets.Layout(height=f"{height}px", width=width)
)
########################
# Subset AOI Selector #
########################
class AOI_Selector:
def __init__(self,
image,
fig_xsize=None, fig_ysize=None,
cmap=plt.cm.gist_gray,
vmin=None, vmax=None,
drawtype='box'
):
deprecation_warn()
display(Markdown(f"<text style=color:blue><b>Area of Interest Selector Tips:\n</b></text>"))
display(Markdown(f'<text style=color:blue>- This plot uses "matplotlib notebook", whereas the other plots in this notebook use "matplotlib inline".</text>'))
display(Markdown(f'<text style=color:blue>- If you run this cell out of sequence and the plot is not interactive, rerun the "%matplotlib notebook" code cell.</text>'))
display(Markdown(f'<text style=color:blue>- Use the pan tool to pan with the left mouse button.</text>'))
display(Markdown(f'<text style=color:blue>- Use the pan tool to zoom with the right mouse button.</text>'))
display(Markdown(f'<text style=color:blue>- You can also zoom with a selection box using the zoom to rectangle tool.</text>'))
display(Markdown(f'<text style=color:blue>- To turn off the pan or zoom to rectangle tool so you can select an AOI, click the selected tool button again.</text>'))
display(Markdown(f'<text style=color:darkred><b>IMPORTANT!</b></text>'))
display(Markdown(f'<text style=color:darkred>- Upon loading the AOI selector, the selection tool is already active.</text>'))
display(Markdown(f'<text style=color:darkred>- Click, drag, and release the left mouse button to select an area.</text>'))
display(Markdown(f'<text style=color:darkred>- The square tool icon in the menu is <b>NOT</b> the selection tool. It is the zoom tool.</text>'))
display(Markdown(f'<text style=color:darkred>- If you select any tool, you must toggle it off before you can select an AOI</text>'))
self.image = image
self.x1 = None
self.y1 = None
self.x2 = None
self.y2 = None
if not vmin:
self.vmin = np.nanpercentile(self.image, 1)
else:
self.vmin = vmin
if not vmax:
self.vmax=np.nanpercentile(self.image, 99)
else:
self.vmax = vmax
if fig_xsize and fig_ysize:
self.fig, self.current_ax = plt.subplots(figsize=(fig_xsize, fig_ysize))
else:
self.fig, self.current_ax = plt.subplots()
self.fig.suptitle('Area-Of-Interest Selector', fontsize=16)
self.current_ax.imshow(self.image, cmap=plt.cm.gist_gray, vmin=self.vmin, vmax=self.vmax)
def toggle_selector(self, event):
print(' Key pressed.')
if event.key in ['Q', 'q'] and toggle_selector.RS.active:
print(' RectangleSelector deactivated.')
toggle_selector.RS.set_active(False)
if event.key in ['A', 'a'] and not toggle_selector.RS.active:
print(' RectangleSelector activated.')
toggle_selector.RS.set_active(True)
toggle_selector.RS = RectangleSelector(self.current_ax, self.line_select_callback,
drawtype=drawtype, useblit=True,
button=[1, 3], # don't use middle button
minspanx=0, minspany=0,
spancoords='pixels',
rectprops = dict(facecolor='red', edgecolor = 'yellow',
alpha=0.3, fill=True),
interactive=True)
plt.connect('key_press_event', toggle_selector)
def line_select_callback(self, eclick, erelease):
'eclick and erelease are the press and release events'
self.x1, self.y1 = eclick.xdata, eclick.ydata
self.x2, self.y2 = erelease.xdata, erelease.ydata
print("(%3.2f, %3.2f) --> (%3.2f, %3.2f)" % (self.x1, self.y1, self.x2, self.y2))
print(" The button you used were: %s %s" % (eclick.button, erelease.button))
##################
# Line Selector #
##################
class LineSelector:
def __init__(self, image, width, height):
deprecation_warn()
self.x1 = None
self.x2 = None
self.y1 = None
self.y2 = None
self.pnt1 = None
self.pnt2 = None
self.fig = plt.figure(figsize=(width, height))
self.ax = self.fig.add_subplot(111, visible=False)
self.rect = patches.Rectangle(
(0.0, 0.0), width, height,
fill=False, clip_on=False, visible=False)
self.rect_patch = self.ax.add_patch(self.rect)
self.cid = self.rect_patch.figure.canvas.mpl_connect('button_press_event',
self)
self.image = image
self.plot = self.gray_plot(self.image, fig=self.fig, return_ax=True)
self.plot.set_title('Select 2 Points of Interest')
def gray_plot(self, image, vmin=None, vmax=None, fig=None, return_ax=False):
'''
Plots an image in grayscale.
Parameters:
- image: 2D array of raster values
- vmin: Minimum value for colormap
- vmax: Maximum value for colormap
- return_ax: Option to return plot axis
'''
if vmin is None:
vmin = np.nanpercentile(self.image, 1)
if vmax is None:
vmax = np.nanpercentile(self.image, 99)
ax = fig.add_axes([0.1,0.1,0.8,0.8])
ax.imshow(image, cmap=plt.cm.gist_gray, vmin=vmin, vmax=vmax)
if return_ax:
return(ax)
def __call__(self, event):
self.x1 = event.xdata
self.y1 = event.ydata
if len(self.plot.get_lines()) == 3:
self.plot.get_lines()[2].remove()
plt.plot(self.x1, self.y1, 'ro')
for i, pnt in enumerate(self.plot.get_lines()):
if len(self.plot.get_lines()) == 3 and i == 0:
pnt.remove()
self.line_x = [pnt.get_xdata() for pnt in self.plot.get_lines()]
self.line_y = [pnt.get_ydata() for pnt in self.plot.get_lines()]
if len(self.plot.get_lines()) > 1:
plt.plot(self.line_x, self.line_y)
for i, pnt in enumerate(self.plot.get_lines()):
if i == 0:
self.pnt1 = pnt.get_xydata()
elif i == 1:
self.pnt2 = pnt.get_xydata()