-
Notifications
You must be signed in to change notification settings - Fork 5
/
sat_coverage_finder.py
323 lines (282 loc) · 9.33 KB
/
sat_coverage_finder.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
# -*- coding: utf-8 -*-
"""Sentinel Sat Coverage Finder.ipynb
This code is for quickly finding recent coverage around a given target coordinate.
Created by Tim Ehrhart (tehrhart@gmail.com)
"""
"""Key: (approximate resolutions and costs per km2)
Sentinel-2 10.0m (free)
Planet 3.0m EUR 2.50/km2 (Available via SkyWatch)
SPOT 1.5m EUR 0.70/km2 (cheapest via SentinelHub)
TripleSat 0.8m EUR 10.00/km2 (Available via SkyWatch)
Satellogic 0.7m (free)/km2 (Free via the Ukraine Observer platform)
PHR 0.5m EUR 8.00/km2 (PHR is Airbus Pleiades, cheapest via SentinelHub)
SkySat 0.5m EUR 10.00/km2 (Available via SkyWatch)
MAXAR 0.5m EUR 16.50/km2 (Resampled from 0.3 to 0.5, minimum 5km2 purchase)
"""
# -*- coding: utf-8 -*-
"""Sat Coverage Finder.ipynb
Automatically generated by Colaboratory.
This code is for quickly finding recent coverage around a given target coordinate.
"""
#!pip3 install geopandas
#Login
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
import geopandas as gpd
from shapely.geometry import Polygon, Point
import json, requests
from datetime import datetime, timedelta
import time
# Google Maps API Key
googleMapsKey = "XXXXXXXXXXXX"
# Skywatch client credentials (API key)
sw_url = "https://api.skywatch.co/earthcache"
sw_key = "XXXXXXXXXXXX"
# SentinelHub client credentials
client_id = 'XXXXXXXXXXXX'
client_secret = 'XXXXXXXXXXXX'
# Create a session
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
# Get token for the session
token = oauth.fetch_token(token_url='https://services.sentinel-hub.com/oauth/token',
client_secret=client_secret)
def getNameFromLatLon(lat,lon):
#Fastest way to get a resonable name from a lat and lon
geoURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng={},{}&sensor=true&key={}".format(lat,lon,googleMapsKey)
response = requests.get(geoURL)
j = response.json()
return j['plus_code']['compound_code']
def getBboxFromPoint(x,y,size=5010):
#For Maxar and Planet searches
#size = 5000 meters by default
crs = ('EPSG:4326')
s = gpd.GeoSeries([Point(x,y)], crs=crs)
b = s.to_crs(epsg=900913).buffer((size/2)+1).to_crs(epsg=4326)
j = json.loads(b.to_json())
return(str(j['features'][0]['bbox']))
def getCoordCircleFromPoint(x,y,size=5010):
#For Airbus searches
#size = 5000 meters by default
crs = ('EPSG:4326')
s = gpd.GeoSeries([Point(x,y)], crs=crs)
b = s.to_crs(epsg=900913).buffer((size/2)+1).to_crs(epsg=4326)
j = json.loads(b.to_json())
return(json.dumps(j['features'][0]['geometry']['coordinates']))
def planetSearch(lat, lon, spacecraft, startDate, endDate):
bbox = getBboxFromPoint(lon, lat)
searchURL = "https://services.sentinel-hub.com/api/v1/dataimport/search"
headers = {'Content-type': 'application/json'}
payload = """
{
"provider": "PLANET",
"bounds": {
"bbox": %s
},
"data": [
{
"itemType": "PSScene",
"productBundle": "analytic_sr_udm2",
"dataFilter": {
"timeRange": {
"from": "%s",
"to": "%s"
},
"maxCloudCoverage": 80
}
}
]
}""" % (bbox, startDate, endDate)
resp = oauth.post(searchURL, data=payload, headers=headers)
j = json.loads(resp.text)
results = []
if (len(j['features']) > 0):
for f in j['features']:
results.append(f['properties']['acquired'])
else:
results = []
return results
def maxarSearch(lat, lon, spacecraft, startDate, endDate):
bbox = getBboxFromPoint(lon, lat)
searchURL = "https://services.sentinel-hub.com/api/v1/dataimport/search"
headers = {'Content-type': 'application/json'}
payload = """{
"provider": "MAXAR",
"bounds": {
"bbox": %s
},
"data": [
{
"dataFilter": {
"timeRange": {
"from": "%s",
"to": "%s"
}
},
"productBands": "4BB",
"productKernel": "CC"
}
]
}""" % (bbox, startDate, endDate)
resp = oauth.post(searchURL, data=payload, headers=headers)
j = json.loads(resp.text)
results = []
if (len(j['features']) > 0):
for f in j['features']:
results.append(f['acquisitionDateStart'])
else:
results = []
#print("MAXAR: {}".format(results))
return results
def airbusSearch(lat, lon, spacecraft, startDate, endDate):
coords = getCoordCircleFromPoint(lon, lat)
searchURL = "https://services.sentinel-hub.com/api/v1/dataimport/search"
headers = {'Content-type': 'application/json'}
payload = """{
"provider": "AIRBUS",
"bounds": {
"geometry": {
"type": "MultiPolygon",
"coordinates": [%s]
}
},
"data": [
{
"constellation": "%s",
"dataFilter": {
"maxCloudCoverage": 80,
"timeRange": {
"from": "%s",
"to": "%s"
}
}
}
]
}""" % (coords,spacecraft,startDate,endDate)
resp = oauth.post(searchURL, data=payload, headers=headers)
j = json.loads(resp.text)
results = []
if (j['totalResults'] > 0):
for f in j['features']:
results.append(f['properties']['acquisitionDate'])
else:
results = []
return results
def imageSearch(lat, lon, spacecraft, startDate, endDate):
if spacecraft in ("SPOT","PHR"):
return airbusSearch(lat, lon, spacecraft, startDate, endDate)
elif spacecraft in ("MAXAR"):
return maxarSearch(lat, lon, spacecraft, startDate, endDate)
elif spacecraft in ("PLANET"):
return planetSearch(lat, lon, spacecraft, startDate, endDate)
else:
return []
def skywatchSearch(lat, lon, startDate, endDate):
#lat, lon = 47.82658, 37.70989
startDate = startDate[:10]
endDate = endDate[:10]
headers = {'x-api-key': sw_key}
sw_request = sw_url + "/archive/search"
coords = getCoordCircleFromPoint(lon, lat)
data = """{
"location": {
"type": "Polygon",
"coordinates": %s
},
"start_date": "%s",
"end_date": "%s",
"resolution": [
"high","medium"
],
"coverage": 50,
"interval_length": 0,
"order_by": [
"resolution"
]
}""" % (coords, startDate, endDate)
#Start the search
response = requests.post(sw_request, headers=headers, data=data)
#Get the search ID for follow-up
j = response.json()
search_id=j['data']['id']
status = 202
while status == 202:
time.sleep(3.0)
headers = {'x-api-key': sw_key}
sw_request = sw_url + "/archive/search/%s/search_results" % (search_id)
response = requests.get(sw_request, headers=headers)
status = response.status_code
if status != 200:
return([])
else:
j = response.json()
results = {}
try:
if(int(j['pagination']['count']) > 0):
for item in j['data']:
#print("Found {} imagery at {}".format(item['source'],item['start_time']))
if item['source'] not in results:
results[item['source']] = []
results[item['source']].append(item['start_time'])
results[item['source']].sort(reverse=False)
except:
return results
return results
def searchAll(lat, lon, startDate,endDate):
#Search via SentinelHub API
spacecraft = ["SPOT","PHR","MAXAR","PLANET"]
results = {}
for sc in spacecraft:
searchResults = imageSearch(lat, lon, sc, startDate, endDate)
searchResults.sort(reverse=False)
if searchResults:
results[sc] = searchResults
#Search via Skywach API
skyResults = skywatchSearch(lat, lon, startDate, endDate)
results.update(skyResults)
return results
def PrintLastImages(results):
#Pass a "results" dict and print out the last image per platform
for i in results:
print("{:<25} {:^25}".format(i,cleanDate(results[i].pop())).ljust(40), end='')
print()
def PrintAllImages(results):
#Pass a "results" dict and print all images per platform
for sc in results:
print("{}:".format(sc))
for image in results[sc]:
print("{:^5}".format(image.ljust(40), end=''))
print()
def cleanDate(d):
return d[:19].replace(' ','T') + "Z"
def PrintImagesByDate(results):
#Pass a "results" dict and print all images in date order
masterList = {}
for sc in results:
for d in results[sc]:
masterList[cleanDate(d)] = sc
for i in sorted(masterList.keys()) :
print("{:<25} {:<25}".format(i, masterList[i]))
#Set up
#Search past X days
numDays = 7
minusDays = datetime.today() - timedelta(days = numDays )
today = datetime.today()
start_s = (minusDays.isoformat(timespec='seconds')+"Z")
end_s = (today.isoformat(timespec='seconds')+"Z")
spacecraft = ["SPOT","PHR","MAXAR","PLANET"]
#lat, lon = 47.55892311832438, 7.607494473687124
#latLonList = [[47.1015, 37.5968],[46.6872, 32.5119],[46.0763, 30.4698],[46.8556, 29.6006],[47.8731, 35.3017],[49.9909, 36.2314],[44.6047, 33.5334],[47.244, 38.847],[49.1531, 37.2497],[50.599, 36.597],[46.8775, 35.3086]]
latLonList = [[ 49.225575, 37.298781 ]]
for ll in latLonList:
lat, lon = ll[0], ll[1]
try:
locationName = getNameFromLatLon(lat, lon)
except:
locationName = "(Unknown)"
print(("\nSearching for imagery within 2.5km of {} {} ({}) from {} until {}...").format(lat, lon, locationName, start_s, end_s))
results = searchAll(lat, lon, start_s,end_s)
print("\nMost recent images per platform:")
PrintLastImages(results)
print("\nAvailable images in chronological order:")
PrintImagesByDate(results)