-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utilities.py
1475 lines (1338 loc) · 71.3 KB
/
Utilities.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
'''
======================================
Utilities for processing PlanetScope imagery
Author: Yan Cheng
Email: chengyan2017@gmail.com
Contributors: Dr. Anton Vrieling
======================================
'''
'''
Major updates
===============================================================
10/01/2022
- fix bugs
- udm2_setnull() -> a_nodata
- gdal_merge() -> compression and -a_nodata
- new function -> stack_to_nc() and prep_pipline() for data preparation for deep learning models
13/02/2020
- remove retrieve_exist_files()
- change the code for checking existing files in clip()
- check existing file for band_algebra()
- add a global variable remove_exist, set this variable as True if you killed a process manually and need to rerun it.
In this case the latest generated file will be removed because most likely the latest one is not complete...
12/02/2020
0. New preparation instruction
1. new variables
- default_gdal_osgeo_dir --> the directory of osgeo folder
- default_process_level
2. os.environ['PROJ_LIB'] = self.gdal_proj_path
3. udm2_setnull()
- Check existing files
4. merge()
- check existing merged files in the output direstory
5. clip()
- check existing clipped files in the output directory
6. asset_attrs(asset_type)
- change the function name from asset_suffix to asset_attrs
- Add data type infromation for different asset type
'''
'''
Preparations
=======================================
1. Download Pycharm - community version
2. Download Preparation_for_PlanetScope_tools.zip file
3. Installation of python 3.7.X
- double click python-3.7.6-amd64.exe in Preparation_for_PlanetScope_tools.zip
- select customize installation
- check [Install launcher for all users]
- check [Add Python to PATH
- make a note of the installed location (e.g., C:\Program Files (x86)\Python37_6)
4. Installation of required packages
- search and open command prompt
- type command line and press enter
- cd [PATH OF INSTALLED PYTHON 3.7.X, WITHOUT SQUARE BRACKETS]
- python -m pip install --user -r [PATH OF DOWNLOADED requirements.txt IN Preparation_for_PlanetScope_tools.zip,
WITHOUT SQUARE BRACKETS]
- python -m pip install --user [PATH OF DOWNLOADED .WHL FILE IN Preparation_for_PlanetScope_tools.zip, WITHOUT
SQUARE BRACKETS]
- find your installed packages here C:\\Users\[USER NAME]\AppData\Roaming\Python\Python37\site-packages
- make a note of the path of osgeo package in this path... it is associate to the default_gdal_osgeo_dir variable
To do list
==========================================================
- Check existing clip_clear_perc()
- Compress data
- Stack NDVI and clear prob
- Plot time series
- Optimize for loops
- Satellite id info from Execution Track file
- gdal warp
'''
from planet import api
from planet.api import filters
from datetime import datetime
import time
import geopandas as gpd
import json
from tqdm import tqdm
from glob import glob
import os
from osgeo import ogr, gdal
import rasterio
import matplotlib.pyplot as plt
import numpy as np
import requests
from requests.auth import HTTPBasicAuth
import sys
import warnings
import netCDF4
import shutil
warnings.simplefilter('ignore')
from pathlib import Path
import string
class Utilities:
'''
Commonly used tools for the processing and raster analytics of PlanetScope imagery
:param:
'''
# Set environment
default_gdal_osgeo_dir = str(Path(os.getcwd()) / 'venv/lib/python3.8/site-packages/osgeo')
# Set directories
default_work_dir = '/mnt/raid5/Planet/pre_processed/Sierra_Nevada_AOI1'
default_output_dirs = {'raw': 'raw', 'clipped raw': 'clipped_raw', 'merge': 'merge', 'clip': 'clip',
'clear prob': 'clear_prob', 'NDVI': 'NDVI', 'clip clear perc': 'bomas'}
# API Key
default_api_file = str(Path(os.getcwd()) / 'api_key.txt')
default_api_key = open(default_api_file, 'r').readlines()[0]
# Specs
default_satellite = 'PS'
default_proj_code = 32737
# Filter settings
default_filter_items = ['date', 'cloud_cover', 'aoi']
default_item_types = ["PSScene4Band"]
default_process_level = '3B'
default_asset_types = ['analytic_sr', 'udm2']
default_start_date = '2019-01-01'
default_end_date = '2020-01-01'
default_cloud_cover = 1
default_aoi_shp = '/mnt/raid5/California_timeseries/aois/sn_aoi1.shp'
default_all_scenes = '/mnt/raid5/California_timeseries/Sierra_Nevada/aoi1/sn_aoi1_20190101_20200101_1000_0000.gpkg'
# Color composition for visualization
default_rgb_composition = {'red': 4, 'green': 3, 'blue': 2} # False color composition for PlanetScope images
default_dpi = 90
default_percentile = [2, 98]
default_remove_latest = True
def __init__(self, gdal_osgeo_dir=default_gdal_osgeo_dir, work_dir=default_work_dir,
output_dirs=default_output_dirs, satellite=default_satellite, proj_code=default_proj_code,
api_key=default_api_key, filter_items=default_filter_items, item_types=default_item_types,
process_level=default_process_level, asset_types=default_asset_types, start_date=default_start_date,
end_date=default_end_date, cloud_cover=default_cloud_cover, aoi_shp=default_aoi_shp,
rgb_composition=default_rgb_composition, dpi=default_dpi, percentile=default_percentile,
remove_latest=default_remove_latest, all_scenes=default_all_scenes):
'''
:param gdal_osgeo_dir: string
:param work_dir: string
:param output_dirs: dictionary, the name of folder for storing different outputs
:param satellite: string, abbreviation of satellite name, PS - PLanetScope, S2 - Sentinel-2
:param proj_code: int, the EPSG code of projection systtem
:param api_key: string
:param filter_items: list, a list of filter item names
:param item_types: list, a list of item type, more info: https://developers.planet.com/docs/data/items-assets/
:param process_level: string, processing level
:param asset_types: list, a list of asset type, more info: https://developers.planet.com/docs/data/psscene4band/
:param start_date: string, start date with a format of 'YYYY-MM-DD'
:param end_date: string, end date with a format of 'YYYY-MM-DD'
:param cloud_cover: float, maximum cloud cover
:param aoi_shp: string, file path of AOI.shp, better to be projected one
:param rgb_composition: list, band sequence for rgb color composition, [4, 1, 3] is false color composition for
PlanetScope images
:param dpi: int, dpi of saved plot
:param percentile: list, minimum and maximum percentile
:param remove_latest: boolean, true means remove the latest file in the folder because the process was killed
manually and the latest file is not complete. If false, the latest file will not be removed.
'''
# self.gdal_osgeo_dir = gdal_osgeo_dir
# self.gdal_scripts_path = str(Path(gdal_osgeo_dir) / 'scripts')
# self.gdal_data_path = str(Path(gdal_osgeo_dir) / 'data/gdal')
# self.gdal_proj_path = str(Path(gdal_osgeo_dir) / 'data/proj')
# sys.path.append(self.gdal_scripts_path)
# os.environ["GDAL_DATA"] = self.gdal_data_path
# os.environ['PROJ_LIB'] = self.gdal_proj_path
self.gdal_calc_path = str(Path('/home/yan/anaconda3/envs/PlanetScopePy_new/bin/gdal_calc.py'))
# self.gdal_calc_path = str(Path(gdal_osgeo_dir) / 'scripts/gdal_calc.py')
self.gdal_merge_path = str(Path('/home/yan/anaconda3/envs/PlanetScopePy_new/bin/gdal_merge.py'))
# self.gdal_merge_path = str(Path(gdal_osgeo_dir) / 'scripts/gdal_merge.py')
self.gdal_vrtmerge_path = str(Path(
'/home/yan/anaconda3/envs/PlanetScopePy_gdal333/lib/python3.7/site-packages/osgeo_utils/samples/gdal_vrtmerge.py'))
self.work_dir = work_dir
self.output_dirs = output_dirs
self.satellite = satellite
self.proj_code = proj_code
self.api_key = api_key
self.client = api.ClientV1(api_key=api_key)
self.filter_items = filter_items
self.item_types = item_types
self.process_level = process_level
self.asset_types = asset_types
self.start_date = datetime(year=int(start_date.split('-')[0]), month=int(start_date.split('-')[1]),
day=int(start_date.split('-')[2]))
self.end_date = datetime(year=int(end_date.split('-')[0]), month=int(end_date.split('-')[1]),
day=int(end_date.split('-')[2]))
self.cloud_cover = cloud_cover
self.aoi_shp = aoi_shp
self.rgb_composition = rgb_composition
self.dpi = dpi
self.percentile = percentile
self.remove_latest = remove_latest
self.records_path = None # File path of execution track document
self.id_list_download = None # a list of item id which will be downloaded
self.all_scenes = all_scenes
def shp_to_json(self):
'''
Convert AOI shapefile to json format that is required for retrieve imagery for specific location
using Planet API
:return: aoi_geom, dictionary
'''
shp = gpd.read_file(self.aoi_shp)
if shp.crs != {'init': 'epsg:{}'.format(str(self.proj_code))}:
shp = shp.to_crs({'init': 'epsg:{}'.format(str(self.proj_code))})
else:
shp = shp.to_crs({'init': 'epsg:4326'})
coors = np.array(dict(json.loads(shp['geometry'].to_json()))
['features'][0]['geometry']['coordinates'])[:, :, 0:2].tolist()
aoi_geom = {"type": "Polygon", "coordinates": coors}
# print(self.aoi_geom)
return aoi_geom
@staticmethod
def asset_attrs(asset_type):
'''
Attributes, such as suffix and data type, for each asset type
:param asset_type: string, one item in the list of asset type, more info:
https://developers.planet.com/docs/data/psscene4band/
:return: string, associated attributes of each asset type
'''
switch = {
'analytic_sr': {
'suffix': 'AnalyticMS_SR',
'data type': 'UInt16'
},
'udm2': {
'suffix': 'udm2',
'data type': 'Byte'
}
}
return switch.get(asset_type, 'None')
@staticmethod
def pixel_res(satellite_abbr):
'''
:param satellite_abbr: string, abbreviation of satellite name, PS - PLanetScope, S2 - Sentinel-2
:return: int, associated pixel resolution of each satellite imagery
'''
switch = {
'PS': 3,
'S2': 30
}
return switch.get(satellite_abbr, 'None')
@staticmethod
def create_dir(f):
'''
Create new folder if it does not exist
:param f: string, the path of a folder to be created
:return:
'''
if not os.path.exists(f):
os.mkdir(f)
def setup_dirs(self):
'''
Create all required folders for saving different outputs
:return:
'''
print('The outputs will be saved in this directory: ' + self.work_dir)
for i in self.output_dirs.keys():
self.create_dir(Path(self.work_dir) / '{}'.format(self.output_dirs[i]))
def create_track_file(self):
'''
Create a txt file to track all the execution of code and outputs, including:
1. Date
2. Item id that does not have required types of asset
3. Item id of downloaded items
4. Metadata of each downloaded item
:return:
'''
records_path = Path(self.work_dir) / 'Execution_Track.txt'
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
if not os.path.exists(records_path):
records_file = open(records_path, "w")
records_file.write('Execution Track for Utilities.py\n\n'.format(time_str))
records_file.write('Execution date and time: {}\n\n'.format(time_str))
else:
records_file = open(records_path, "a+")
records_file.write('Execution date and time: {}\n\n'.format(time_str))
records_file.close()
self.records_path = records_path
def start_up(self):
# self.create_track_file()
self.setup_dirs()
def create_filter(self):
'''
Creater filters
:return: filter
'''
if 'date' in list(self.filter_items):
date_filter = filters.date_range('acquired', gte=self.start_date, lte=self.end_date)
and_filter = date_filter
if 'cloud_cover' in list(self.filter_items):
cloud_filter = filters.range_filter('cloud_cover', lte=self.cloud_cover)
and_filter = filters.and_filter(and_filter, cloud_filter)
if 'aoi' in list(self.filter_items):
aoi_geom = self.shp_to_json()
aoi_filter = filters.geom_filter(aoi_geom)
and_filter = filters.and_filter(and_filter, aoi_filter)
return and_filter
def download_one(self, item_id, asset_type, item_type):
'''
Download individual asset without using Planet client
:param item_id: string, item id
:param asset_type: string, one item in the list of asset type, more info:
https://developers.planet.com/docs/data/psscene4band/
:param item_type: string, one item in the list of item type, more info:
https://developers.planet.com/docs/data/items-assets/
:return: asset_exist, boolean, existence of required asset
'''
output_dir = Path(self.work_dir) / self.output_dirs['raw']
# records_file = open(self.records_path, "a+")
# Request asset with item id
item_url = 'https://api.planet.com/data/v1/item-types/{}/items/{}/assets'.format(item_type, item_id)
result = requests.get(item_url, auth=HTTPBasicAuth(self.api_key, ''))
# List the asset types available for this particular satellite image
asset_type_list = result.json().keys()
# print(asset_type_list)
if asset_type in asset_type_list:
links = result.json()[u'{}'.format(asset_type)]['_links']
self_link = links['_self']
activation_link = links['activate']
# Activate asset
activation = requests.get(activation_link, auth=HTTPBasicAuth(self.api_key, ''))
# print(activation.response.status_code)
asset_activated = False
# i = 0
while not asset_activated:
activation_status_result = requests.get(self_link, auth=HTTPBasicAuth(self.api_key, ''))
asset_status = activation_status_result.json()["status"]
if asset_status == 'active':
asset_activated = True
# print("Asset is active and ready to download")
else:
# Still activating. Wait and check again.
# print("...Still waiting for asset activation...")
# i += 1
# print('You have been waiting for {} minutes'.format(i - 1))
time.sleep(60)
# Download asset with download url
download_url = activation_status_result.json()["location"]
# print(download_link)
response = requests.get(download_url, stream=True)
total_length = response.headers.get('content-length')
with open(Path(output_dir) / '{}_{}_{}.tif'.format(item_id, self.process_level,
self.asset_attrs(asset_type)['suffix']), "wb") as handle:
if total_length is None:
for data in response.iter_content():
handle.write(data)
else:
dl = 0
total_length = int(total_length)
for data in response.iter_content(chunk_size=1024):
handle.write(data)
dl += len(data)
done = int(50 * dl / total_length)
sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50 - done)))
sys.stdout.flush()
asset_exist = True
else:
# records_file.write("NO FILE: {} {} {}\n\n".format(item_id, asset_type, item_type))
asset_exist = False
# records_file.close()
return asset_exist
def download_client(self, item_id, asset_type, item_type):
'''
Activate and download individual asset with specific item id and asset type
Using Planet client, slower than using download_one()
:param item_id: string, item id
:param asset_type: string, one item in the list of asset type, more info:
https://developers.planet.com/docs/data/psscene4band/
:param item_type: string, one item in the list of item type, more info:
https://developers.planet.com/docs/data/items-assets/
:return: asset_exist, boolean, existence of required asset
'''
output_dir = Path(self.work_dir) / self.output_dirs['raw']
# records_file = open(self.records_path, "a+")
assets = self.client.get_assets_by_id(item_type, item_id).get()
# print(assets.keys())
if asset_type in assets.keys():
# Activate asset
activation = self.client.activate(assets[asset_type])
# print(activation.response.status_code)
asset_activated = False
# i = 0
while not asset_activated:
assets = self.client.get_assets_by_id(item_type, item_id).get()
asset = assets.get(asset_type)
asset_status = asset["status"]
# If asset is already active, we are done
if asset_status == 'active':
asset_activated = True
# print("Asset is active and ready to download")
# Still activating. Wait and check again.
else:
# print("...Still waiting for asset activation...")
# i += 1
# print('You have been waiting for {} minutes'.format(i - 1))
time.sleep(60)
# Download asset
callback = api.write_to_file(directory=output_dir)
body = self.client.download(assets[asset_type], callback=callback)
body.wait()
asset_exist = True
else:
# records_file.write("{} {} {}\n\n".format(item_id, asset_type, item_type))
asset_exist = False
# records_file.close()
return asset_exist
def download_clipped(self, item_id, item_type, asset_type='analytic_sr'):
'''
Activate and download clipped assets, does not support udm2
:param item_id: string, item id
:param asset_type: string, one item in the list of asset type, more info:
https://developers.planet.com/docs/data/psscene4band/
:param item_type: string, one item in the list of item type, more info:
https://developers.planet.com/docs/data/items-assets/
:return: asset_exist, boolean, existence of required asset
'''
# Create new folder
output_dir = Path(self.work_dir) / self.output_dirs['clipped_raw']
self.create_dir(output_dir)
# records_file = open(self.records_path, "a+")
print('The clipped raw images will be saved in this directory: ' + output_dir)
# Construct clip API payload
clip_payload = {
'aoi': self.shp_to_json(),
'targets': [{
'item_id': item_id,
'item_type': item_type,
'asset_type': asset_type
}]}
# Request clip of scene (This will take some time to complete)
request = requests.post('https://api.planet.com/compute/ops/clips/v1', auth=(self.api_key, ''),
json=clip_payload)
asset_type_list = request.json().keys()
# print(asset_type_list)
if asset_type in asset_type_list:
clip_url = request.json()['_links']['_self']
# print(request.json())
# Poll API to monitor clip status. Once finished, download and upzip the scene
clip_succeeded = False
while not clip_succeeded:
# Poll API
check_state_request = requests.get(clip_url, auth=(self.api_key, ''))
# If clipping process succeeded , we are done
if check_state_request.json()['state'] == 'succeeded':
clip_download_url = check_state_request.json()['_links']['results'][0]
clip_succeeded = True
# print("Clip of scene succeeded and is ready to download")
else:
# print("...Still waiting for asset activation...")
# i += 1
# print('You have been waiting for {} minutes'.format(i - 1))
time.sleep(60)
# Download clipped asset
response = requests.get(clip_download_url, stream=True)
total_length = response.headers.get('content-length')
with open(Path(output_dir) / '{}_{}_{}.tif'.format(item_id, self.process_level,
self.asset_attrs(asset_type)['suffix']),
"wb") as handle:
if total_length is None:
for data in response.iter_content():
handle.write(data)
else:
dl = 0
total_length = int(total_length)
for data in response.iter_content(chunk_size=1024):
handle.write(data)
dl += len(data)
done = int(50 * dl / total_length)
sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50 - done)))
sys.stdout.flush()
asset_exist = True
else:
# records_file.write("NO FILE: {} {} {}\n\n".format(item_id, asset_type, item_type))
asset_exist = False
# records_file.close()
return asset_exist
def download_assets(self, clipped=None, output_dir=None):
'''
Download all required assets
:param clipped: boolean, True means downloading clipped assests, otherwise downloading raw imagery
:param output_dir: string, the directory for saving downloaded assets. In case you have downloaded some assets
before using this script, this argument can avoid downloading the same assets again.
:return:
'''
print('Start to download assets :)')
# records_file = open(self.records_path, "a+")
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
# records_file.write('Execute download_assets():\nArguments: clipped={} output_dir={}\nStart time: {}\n\n'
# .format(clipped, output_dir, time_str))
if output_dir is None:
output_dir = Path(self.work_dir) / self.output_dirs['raw']
# Download clipped assets or not
if clipped is None:
clipped = False
# Create filter
and_filter = self.create_filter()
# records_file.write('Filter settings: {}\n\n'.format(and_filter))
# Search items
req = filters.build_search_request(and_filter, self.item_types)
res = self.client.quick_search(req)
# List id of all items in the search result
id_list_search = [i['id'] for i in res.items_iter(250)]
for asset_type in self.asset_types:
# Retrieve id of existing assets in the folder used to save all downloaded assets
file_list = glob('{}\\*{}.tif'.format(output_dir, self.asset_attrs(asset_type)['suffix']))
id_list_exist = [i.split('\\')[-1].split('_{}_'.format(self.process_level))[0] for i in file_list]
# List id of all items to be downloaded
self.id_list_download = [i for i in id_list_search if i not in id_list_exist]
# print(self.id_list_download)
# Download (clipped) assets based on their item id
for item_id in tqdm(self.id_list_download, total=len(self.id_list_download), unit="item",
desc='Downloading assets'):
if not clipped:
for item_type in self.item_types:
asset_exist = self.download_one(item_id, asset_type, item_type)
if asset_exist is True:
metadata = [i for i in res.items_iter(250) if i['id'] == item_id]
# records_file = open(self.records_path, "a+")
# records_file.write('File Exists: {}_{}_{} {}\n\n'
# .format(item_id, self.process_level,
# self.asset_attrs(asset_type)['suffix'], item_type))
# records_file.write('Metadata for {}_{}_{} {}\n{}\n\n'
# .format(item_id, self.process_level,
# self.asset_attrs(asset_type)['suffix'],
# item_type, metadata))
else:
for item_type in self.item_types:
self.download_clipped(item_id, item_type)
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
print('Finish downloading assets :)')
print('The raw images have been saved in this directory: ' + output_dir)
# print('The information of missing assets has be saved in this file: ' + self.records_path)
# records_file.write('The outputs have been saved in this directory: {}\n\n'.format(output_dir))
# records_file.write('End time: {}\n\n'.format(time_str))
# records_file.close()
def gdal_udm2_setnull(self, input_path, output_path, compression='LZW'):
'''
Set the value of background pixels as no data
:param input_path:
:param output_path:
:return:
'''
temp_output_path = Path(self.work_dir) / 'TempFile.tif'
gdal_calc_str = 'python {0} --calc "A+B+C+D+E+F+G" --co "COMPRESS=LZW" --format GTiff ' \
'--type Byte -A {1} --A_band 1 -B {2} --B_band 2 -C {3} --C_band 3 -D {4} --D_band 4 ' \
'-E {5} --E_band 5 -F {6} --F_band 6 -G {7} --G_band 7 --NoDataValue 0.0 ' \
'--outfile {8} --overwrite'
gdal_calc_process = gdal_calc_str.format(self.gdal_calc_path, input_path, input_path, input_path, input_path,
input_path, input_path, input_path, temp_output_path)
os.system(gdal_calc_process)
gdal_calc_str = 'python {0} --calc "A*(B>0)" --format GTiff ' \
'--type Byte -A {1} -B {2} --outfile {3} --allBands A --overwrite'
gdal_calc_str = gdal_calc_str + f' --co "COMPRESS={compression}"' if compression is not None else gdal_calc_str
gdal_calc_process = gdal_calc_str.format(self.gdal_calc_path, input_path, temp_output_path, output_path)
os.system(gdal_calc_process)
os.remove(temp_output_path)
def udm2_setnull(self, file_list=None, compression='LZW'):
'''
Set the value of background pixels as no data
:param file_list:
:return:
'''
print('Start to process udm2 data :)')
# records_file = open(self.records_path, "a+")
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
# records_file.write('Execute udm2_setnull():\nArguments: file_list={}\nStart time: {}\n\n'
# .format(file_list, time_str))
input_dir = str(Path(self.work_dir) / self.output_dirs['raw'])
output_dir = input_dir
if file_list is None:
file_list = []
for i in self.id_list_download:
a = glob(str(Path('{}/{}*udm2.tif'.format(input_dir, i))))
for j in a:
file_list.append(j)
else:
file_list = [file for file in file_list if 'udm2' in file]
# print(file_list)
# Check existing setnull data and remove the latest one in case it was not complete
item_id_list = list(set([Path(file).stem.split('_{}_'.format(self.process_level))[0]
for file in file_list]))
exist_setnull = list(
set([Path(file).stem.split('_{}_'.format(self.process_level))[0]
for file in glob(str(Path('{}/*setnull*.tif'.format(output_dir))))]))
new_setnull = [i for i in item_id_list if i not in exist_setnull]
if new_setnull:
if exist_setnull:
file_list_exist_setnull = glob(str(Path('{}/*setnull.tif'.format(output_dir))))
if self.remove_latest is True:
latest_file = max(file_list_exist_setnull, key=os.path.getctime)
# Remove the latest file, in case it is not complete
os.remove(latest_file)
file_list_exist_setnull.remove(latest_file)
# Add the removed one to the file list
new_setnull.append(Path(latest_file).stem.split('_{}_'.format(self.process_level))[0])
file_list = [file for file in file_list for i in new_setnull if i in file]
for input_path in tqdm(file_list, total=len(file_list), unit="item", desc='Processing udm2 data'):
output_path = str(Path(output_dir) / str(Path(input_path).stem.split('.')[0] + '_setnull.tif'))
try:
self.gdal_udm2_setnull(input_path=input_path, output_path=output_path, compression=compression)
except:
pass
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
print('Finish processing udm2 data :)')
print('The outputs have been saved in this directory: ' + output_dir)
# records_file.write('The outputs have been saved in this directory: {}\n\n'.format(output_dir))
# records_file.write('End time: {}\n\n'.format(time_str))
# records_file.close()
def gdal_merge(self, input_path, output_path, data_type, separate=False, compression=None):
'''
GDAL merge function. More info: https://gdal.org/programs/gdal_merge.html
:param output_path:
:param input_path:
:param data_type:
:param separate:
:param compression:
:return:
'''
# Errors when apply LZW compression!!!
# ERROR 1: TIFFReadEncodedStrip() failed.
# ERROR 1: /mnt/raid5/Planet/pre_processed/Sierra_Nevada_AOI1/raw/20190509_172738_0f46_3B_udm2_clip_setnull.tif,
# band 8: IReadBlock failed at X offset 0, Y offset 1339: TIFFReadEncodedStrip() failed.
gdal_merge_str = 'python {0} -o {1} {2} -ot {3}' if separate is False \
else 'python {0} -o {1} {2} -ot {3} -separate'
gdal_merge_str = ' '.join([gdal_merge_str, f'-co COMPRESS={compression}']) if compression is not None else gdal_merge_str
gdal_merge_process = gdal_merge_str.format(self.gdal_merge_path, output_path, input_path, data_type)
os.system(gdal_merge_process)
def merge(self, input_dir=None, file_list=None, asset_type_list=default_asset_types):
'''
Merge images acquired in the same day with the same satellite id
:param input_dir: string, input folder
:param file_list: list, a list of file path
:param asset_type_list: list, a list of asset types
:return:
'''
if 'udm2' in asset_type_list:
# Preprocessing udm2 data
self.udm2_setnull(file_list)
else:
pass
print('Start to merge images collected in the same day on the same orbit :)')
# records_file = open(self.records_path, "a+")
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
# records_file.write('Execute merge():\nArguments: file_list={}\nStart time: {}\n\n'.format(file_list, time_str))
input_dir = str(Path(self.work_dir) / self.output_dirs['raw']) if input_dir is None else input_dir
output_dir = str(Path(self.work_dir) / self.output_dirs['merge'])
if file_list is None:
file_list = []
for i in self.id_list_download:
a = glob(str(Path('{}/{}*.tif'.format(input_dir, i))))
for j in a:
file_list.append(j)
# print(file_list)
for asset_type in asset_type_list:
date_list = list(set([Path(file).stem.split('_')[0]
for file in file_list if self.asset_attrs(asset_type)['suffix'] in file]))
# Check existing merged data and remove the latest file in case it was not complete
file_list_exist = glob(str(Path('{}/*{}.tif'.format(output_dir, self.asset_attrs(asset_type)['suffix']))))
if file_list_exist:
date_list_exist = list(set([Path(file).stem.split('_')[0] for file in file_list_exist]))
if self.remove_latest is True:
latest_file = max(file_list_exist, key=os.path.getctime)
latest_file_date = Path(latest_file).stem.split('_')[0]
os.remove(latest_file)
date_list_exist.remove(latest_file_date)
date_list = [date for date in date_list if date not in date_list_exist]
for date in tqdm(date_list, total=len(date_list), unit="item", desc='Merging images'):
if asset_type == 'udm2':
file_list_new = glob(str(Path('{}/{}*{}*_setnull.tif'
.format(input_dir, date, self.asset_attrs(asset_type)['suffix']))))
else:
file_list_new = [i for i in file_list if
date in Path(i).stem and self.asset_attrs(asset_type)['suffix'] in Path(i).stem]
satellite_id_list = list(set([Path(x).stem.split('_{}_'.format(self.process_level))[0]
.split('_')[-1] for x in file_list_new]))
for satellite_id in satellite_id_list:
output_path = str(Path(output_dir) / str(date + '_' + satellite_id + '_{}.tif'
.format(self.asset_attrs(asset_type)['suffix'])))
input_path = ' '.join(str(i) for i in file_list_new if satellite_id in i)
self.gdal_merge(input_path, output_path, self.asset_attrs(asset_type)['data type'],
separate=False, compression=None)
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
print('Finish merging images :)')
print('The merged images have been saved in this directory: ' + output_dir)
# records_file.write('The outputs have been saved in this directory: {}\n\n'.format(output_dir))
# records_file.write('End time: {}\n\n'.format(time_str))
# records_file.close()
def gdal_clip(self, input_path, pixel_res, shapefile_path, output_path, data_type, compression=None):
'''
GDAL clip function
:param input_path:
:param pixel_res:
:param shapefile_path:
:param data_type:
:param output_path:
:return:
'''
# Open datasets
raster = gdal.Open(input_path, gdal.GA_ReadOnly)
# Projection = Raster.GetProjectionRef()
# print(Projection)
vector_driver = ogr.GetDriverByName('ESRI Shapefile')
vector_dataset = vector_driver.Open(shapefile_path, 0) # 0=Read-only, 1=Read-Write
layer = vector_dataset.GetLayer()
feature = layer.GetFeature(0)
geom = feature.GetGeometryRef()
minX, maxX, minY, maxY = geom.GetEnvelope() # Get bounding box of the shapefile feature
if data_type == 'UInt16':
gdal_data_type = gdal.GDT_UInt16
if data_type == 'Byte':
gdal_data_type = gdal.GDT_Byte
# Create raster
OutTile = gdal.Warp('temp.vrt', raster, format='VRT',
outputType=gdal_data_type,
outputBounds=[minX, minY, maxX, maxY],
xRes=pixel_res, yRes=pixel_res,
targetAlignedPixels=True,
# dstSRS='epsg:{}'.format(str(self.proj_code)),
resampleAlg=gdal.GRA_NearestNeighbour,
cutlineDSName=shapefile_path,
cutlineLayer=Path(shapefile_path).stem.split('.')[0],
cropToCutline=True,
# dstNodata=-9999,
options=['COMPRESS=LZW'])
# Compression
if compression is not None:
translateoptions = gdal.TranslateOptions(gdal.ParseCommandLine(f"-of Gtiff -co COMPRESS={compression}"))
else:
translateoptions = gdal.TranslateOptions(gdal.ParseCommandLine("-of Gtiff"))
gdal.Translate(output_path, 'temp.vrt', options=translateoptions)
# gdal_translate_str = 'python {0} -co COMPRESS=LZW temp.vrt {1}'
# gdal_translate_process = gdal_translate_str.format(self.gdal_translate_path, output_path)
# os.system(gdal_translate_process)
# Close dataset
OutTile = None
raster = None
vector_dataset.Destroy()
@staticmethod
def get_aoi_scenes(all_scenes, aoi):
"""
Retrieve scenes intersect with an aoi.
:param all_scenes:
:param aoi:
:return: GeoDataFrame,
"""
all_scenes_gdf = gpd.GeoDataFrame.from_file(all_scenes)
aoi_gdf = gpd.GeoDataFrame.from_file(aoi)
out = gpd.overlay(all_scenes_gdf, aoi_gdf, how='intersection')
return out
def clip(self, file_list=None, aoi_shp=None, suffix='', discard_empty_scene=None, all_scenes=None):
'''
Clip imagery to the extent of AOI
:param discard_empty_scene:
:param suffix:
:param aoi_shp:
:param file_list:
:return:
'''
print('Start GDAL clip :)')
# records_file = open(self.records_path, "a+")
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
# records_file.write('Execute clip():\nArguments: file_list={}\nStart time: {}\n\n'.format(file_list, time_str))
input_dir = str(Path(self.work_dir) / self.output_dirs['merge'])
output_dir = str(Path(self.work_dir) / self.output_dirs['clip'])
aoi_shp = self.aoi_shp if aoi_shp is None else aoi_shp
if file_list is None:
file_list = []
for i in self.id_list_download:
a = glob(str(Path('{}/{}*.tif'.format(input_dir, i))))
for j in a:
file_list.append(j)
# print(file_list)
# Check existing clipped images and remove the latest file, in case it is not complete
file_list_exist = glob(str(Path('{}/*.tif'.format(output_dir))))
if file_list_exist:
if self.remove_latest is True:
latest_file = max(file_list_exist, key=os.path.getctime)
os.remove(latest_file)
file_list_exist.remove(latest_file)
file_list = [file for file in file_list if file not in file_list_exist]
if discard_empty_scene is True:
all_scenes = self.all_scenes if all_scenes is None else all_scenes
overlayed_gdf = self.get_aoi_scenes(all_scenes=all_scenes, aoi=aoi_shp)
date_orbit_list = overlayed_gdf['id'].apply(lambda x: x.split('_')).apply(lambda x: '_'.join([x[0], x[-1]])).tolist()
file_list = [fp for date_orbit in date_orbit_list for fp in file_list if date_orbit in fp]
for input_path in tqdm(file_list, total=len(file_list), unit="item", desc='Clipping images'):
output_name = str(Path(input_path).stem) + f'{suffix}' + str(Path(input_path).suffix)
output_path = str(Path(output_dir) / output_name)
if self.asset_attrs('udm2')['suffix'] in input_path:
data_type = self.asset_attrs('udm2')['data type']
if self.asset_attrs('analytic_sr')['suffix'] in input_path:
data_type = self.asset_attrs('analytic_sr')['data type']
self.gdal_clip(input_path, self.pixel_res(self.satellite), aoi_shp, output_path, data_type)
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
print('Finish clipping images :)')
print('The clipped images have been saved in this directory: ' + output_dir)
# records_file.write('The outputs have been saved in this directory: {}\n\n'.format(output_dir))
# records_file.write('End time: {}\n\n'.format(time_str))
# records_file.close()
def gdal_calc_ndvi(self, input_path, output_path):
'''
Band algebra for NDVI
:param input_path:
:param output_path:
:return:
'''
gdal_calc_str = 'python {0} --calc "(A-B)/(A+B)*10000" --co "COMPRESS=LZW" --format GTiff ' \
'--type UInt16 -A {1} --A_band 4 -B {2} --B_band 3 --outfile {3} --overwrite'
gdal_calc_process = gdal_calc_str.format(self.gdal_calc_path, input_path, input_path, output_path)
os.system(gdal_calc_process)
def gdal_calc_clear_prob(self, input_path, output_path):
'''
Band algebra for clear probability
:param input_path:
:param output_path:
:return:
'''
gdal_calc_str = 'python {0} --calc "A*B" --co "COMPRESS=LZW" --format GTiff --type UInt16 -A {1} ' \
'--A_band 1 -B {2} --B_band 7 --outfile {3} --overwrite'
gdal_calc_process = gdal_calc_str.format(self.gdal_calc_path, input_path, input_path, output_path)
os.system(gdal_calc_process)
def band_algebra(self, output_type, file_list=None):
'''
Band algebra for clear probablity or NDVI
:param output_type:
:param file_list:
:return:
'''
print('Start GDAL band calculation :)')
# records_file = open(self.records_path, "a+")
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
# records_file.write('Execute band_algebra():\nArguments: output_type={} file_list={}\nStart time: {}\n\n'
# .format(output_type, file_list, time_str))
input_dir = self.work_dir + '\\' + self.output_dirs['clip']
if output_type == 'clear prob':
asset_type = 'udm2'
clear_prob_dir = self.work_dir + '\\' + self.output_dirs['clear prob']
if file_list is None:
file_list = []
for i in self.id_list_download:
a = glob("{}\\{}*{}.tif".format(input_dir, i, self.asset_attrs('udm2')['suffix']))
for j in a:
file_list.append(j)
else:
file_list = [file for file in file_list if self.asset_attrs('udm2')['suffix'] in file]
# Check existing clipped images and remove the latest file, in case it is not complete
file_list_exist = glob('{}\\*.tif'.format(clear_prob_dir))
if file_list_exist:
item_id_list_exist = [
file.split('\\')[-1].split('_{}'.format(self.asset_attrs(asset_type)['suffix']))[0]
for file in file_list_exist]
if self.remove_latest is True:
latest_file = max(file_list_exist, key=os.path.getctime)
os.remove(latest_file)
file_list_exist.remove(latest_file)
file_list = [file for file in file_list if file.split('\\')[-1].split(
'_{}'.format(self.asset_attrs(asset_type)['suffix']))[0] not in item_id_list_exist]
for udm2_path in file_list:
clear_prob_path = clear_prob_dir + '\\' + \
udm2_path.split('\\')[-1].split('_{}'.format(self.asset_attrs('udm2')['suffix']))[
0] + '_clearprob.tif'
self.gdal_calc_clear_prob(input_path=udm2_path, output_path=clear_prob_path)
print('Finish GDAL Calculation :)')
print('The outputs have been saved in this directory: ' + clear_prob_dir)
if output_type == 'NDVI':
ndvi_dir = Path(self.work_dir) / self.output_dirs['NDVI']
if file_list is None:
file_list = []
for i in self.id_list_download:
a = glob("{}\\{}*SR.tif".format(input_dir, i))
for j in a:
file_list.append(j)
else:
file_list = [file for file in file_list if 'SR' in file]
for sr_path in file_list:
ndvi_path = Path(ndvi_dir) / sr_path.split('\\')[-1].split(
'_{}'.format(self.asset_attrs('analytic_sr')['suffix']))[0] + '_ndvi.tif'
self.gdal_calc_ndvi(input_path=sr_path, output_path=ndvi_path)
time_str = datetime.now().strftime("%Y%m%d-%H%M%S")
print('Finish GDAL Calculation :)')
print('The outputs have been saved in this directory: ' + ndvi_dir)
# records_file.write('The outputs have been saved in this directory: {}\n\n'.format(ndvi_dir))
# records_file.write('End time: {}\n\n'.format(time_str))
# records_file.close()
def stack_as_nc(self, input_dir, output_dir, output_name, ref_image, base_date='19000101', date_list=None,
input_suffix=None, udm2=None, udm2_suffix=None, ref_udm2=None, proj=True):
"""
:param base_date: string, in the form of 'yyyy-mm-dd'
:return:
"""
print('Start!')
if udm2_suffix is None:
udm2_suffix = ''
if input_suffix is None:
input_suffix = ''
if date_list is None:
fp_list_all = glob(os.path.join(input_dir, '*.tif'))
else:
fp_list_all = [fp for fp in glob(os.path.join(input_dir, '*.tif'))
if Path(fp).stem.split('_')[0] in date_list]
date_orbit_list = sorted(list(
set(['_'.join([str(Path(fp).stem.split('_')[0]), str(Path(fp).stem.split('_')[1])]) for fp in fp_list_all])))
ds = gdal.Open(ref_image) # reference -> could be any image from the candidate images to be stacked into a netCDF file
# get the number of bands
n_band = int(ds.RasterCount)
# convert image to array
a = ds.ReadAsArray()
# get the number of rows and columns
if int(n_band) == 1:
ny, nx = np.shape(a)
else:
ny, nx = np.shape(a[0])
# get the information of coordinate transformation
b = ds.GetGeoTransform() # bbox, interval
prj = ds.GetProjection()
# calculate coordinates