-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetchdata.py
533 lines (415 loc) · 22.6 KB
/
fetchdata.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
from shapely import geometry
from utils import *
from itemretr import *
from helper import *
import json
def fetchitem(sta_link: str,version: str,number_of_thing: int,old_vars : dict, asset_as: str):
"""
Fetches information about a specific item/thing from a SensorThings API.
Args:
sta_link (str): The base URL of the SensorThings API.
version (str): The version of the SensorThings API.
number_of_thing (int): The ID of the item/thing to fetch.
old_vars (dict): A dictionary containing previously fetched variables.
Returns:
fetched_vars (dict): A dictionary with updated fetched variables.
"""
thing_url =f"{sta_link}/{version}/Things({number_of_thing})"
datastreams_url = f"{thing_url}/Datastreams?$count=true&$top=1000"
locations_url = f"{thing_url}/Locations?$count=true&$top=1000"
if bool(old_vars) is False:
fetched_vars = {}
else:
fetched_vars = old_vars
fetched_vars["item_thing_url_json"] = thing_url
thing_json = open_sta_entity_links(
link=thing_url
)
datastreams_json = open_sta_entity_links(
link=datastreams_url
)
locations_json = open_sta_entity_links(
link=locations_url
)
if thing_json is not None and thing_json != {}:
print("thing json not none")
(fetched_vars["item_id"],
fetched_vars["item_title"],
fetched_vars["item_description"],
) = replace_item_info(thing_json=thing_json)
# Fetching the STAC-Item Spatial and Temporal extent
if locations_json is not None and locations_json != {}:
if locations_json["@iot.count"] == 0:
print("No location, looking for location in `observedArea` attribute of `Datastream`, and if it still couldn't find any coordinate, the spatial extent of the item will be None.")
elif locations_json["@iot.count"] == 1:
if (
locations_json.get("value", [])[0]
.get("location", {})
.get("type")
is not None
):
fetched_vars["item_geometry"] = locations_json[
"value"
][0]["location"]["type"]
else:
print("No location, looking for location in `observedArea` attribute of `Datastream`, and if it still couldn't find any coordinate, the spatial extent of the item will be None.")
if (
locations_json.get("value", [])[0]
.get("location", {})
.get("coordinates")
is not None
):
fetched_vars["item_bbox"] = [locations_json["value"][0]["location"]["coordinates"]]
else:
print("No location, looking for location in `observedArea` attribute of `Datastream`, and if it still couldn't find any coordinate, the spatial extent of the item will be None.")
elif locations_json["@iot.count"] > 1:
geometry_list = []
bbox_list = []
locations_number = get_number_of_entities(
link=thing_url,
entity="Locations")
list_of_locations_id = get_list_of_entities_id(
link=thing_url,
entity="Locations"
)
if locations_number == len(list_of_locations_id):
for location_index, location_number in enumerate(
list_of_locations_id
):
locations_url_by_number = (
f"{thing_url}/Locations({location_number})"
)
locations_json_by_number = open_sta_entity_links(
locations_url_by_number,
)
if (
locations_json_by_number.get(
"location", {}
).get("type")
is not None
):
geometry_list.append(
locations_json_by_number["location"][
"type"
]
)
else:
print("The Location of the Thing does not have any geometry type in the list of locations, will look for the location in `observedArea` attribute of Datastream, and if it couldn't find any geometry there, the geometry of the item will be None.")
if (
locations_json_by_number.get(
"location", {}
).get("coordinates")
is not None
):
bbox_list.append(
locations_json_by_number["location"][
"coordinates"
]
)
else:
print("The Location of the Thing does not have any geometry type in the list of locations. So, it will look for the location in `observedArea` attribute of Datastream, and if it couldn't find any coordinate there, the spatial extent of the item will be None.")
else:
print("The number of Locations in the Thing is not equal to the number of Locations in the list of locations. So, it will look for the location in `observedArea` attribute of Datastream, and if it couldn't find any geometry there, the geometry of the item will be None.")
if fetched_vars.get("item_geometry") is None:
fetched_vars["item_geometry"] = geometry_list
if fetched_vars.get("item_bbox") is None:
fetched_vars["item_bbox"] = bbox_list
if datastreams_json is not None and datastreams_json != {}:
print("datastream json")
# fetching the STAC-Item Spatial and Temporal extent,
# Variable names, dimensions, description and units.
# Dimension names are lat, long and time.
if datastreams_json["@iot.count"] == 0:
if fetched_vars["item_bbox"] is None:
print("The Thing does not have any Datastream. So, there is no temporal and spatial extent for the item.")
return
else:
print("The Thing does not have any Datastream. So, there is no temporal extent for the item.")
return
elif datastreams_json["@iot.count"] == 1:
datastreams_json_by_number = datastreams_json["value"][0]
try:
datastream_data = []
datastream_value = datastreams_json_by_number["@iot.id"]
datastream_data_temp = {}
asset_fields = {}
try:
datastream_data_temp["datstream_index"] = datastream_index
except Exception as exc:
print("Datastream value")
if asset_as == "GeoJSON" :
try:
asset_fields["href"] = str(f"{sta_link}/{version}/Datastreams({datastream_value})/Observations?$select=result,phenomenonTime&$resultFormat=GeoJSON")
except Exception as exc:
print("Datastream href not found",exc)
else:
try:
asset_fields["href"] = str(f"{sta_link}/{version}/Datastreams({datastream_value})/Observations?$select=result,phenomenonTime&$resultFormat=CSV")
except Exception as exc:
print("Datastream href not found",exc)
try:
sensor_url = datastreams_json_by_number["@iot.selfLink"]
except Exception as exc:
print("sensor url not found", exc)
try:
asset_fields["title"] = datastreams_json_by_number["name"]
except Exception as exc:
print("Title not found ",exc)
try:
asset_fields["description"] = datastreams_json_by_number["description"]
except Exception as exc:
print("Description not found",exc)
try:
asset_fields["extra_fields"] = {}
except Exception as exc:
print("Extra fields not found",exc)
try:
asset_fields["extra_fields"]["unitOfMeasurement"] = datastreams_json_by_number["unitOfMeasurement"]
except Exception as exc:
print("Datastream ID not found")
try:
asset_fields["extra_fields"]["properties"] = datastreams_json_by_number["properties"]
except Exception as exc:
print("Datastream ID not found")
try:
sensor_url = datastreams_json_by_number["@iot.selfLink"]
sensor_url = sensor_url +"/Sensor"
sensor_details = open_sta_entity_links(sensor_url)
sname = sensor_details["name"]
asset_fields["extra_fields"]["SensorName"] = sname
asset_fields["extra_fields"]["data_csv"] = f"{sta_link}/Datastreams({datastream_value})/Observations?$select=result,phenomenonTime&$resultFormat=csv"
asset_fields["extra_fields"]["data_geojson"] = f"{sta_link}/Datastreams({datastream_value})/Observations?$select=result,phenomenonTime&$resultFormat=geojson"
except Exception as exc:
print("Datastream ID not found ", exc)
asset_fields = {}
datastream_data_temp["asset_fields"] = asset_fields
datastream_data.append(datastream_data_temp)
except Exception as e:
print(f"Couldn't fetch datastream properties due to exception {e}")
fetched_vars["assets"] = datastream_data
if datastreams_json.get("observedArea") is not None:
if (
datastreams_json["observedArea"].get("type")
is not None
and fetched_vars["item_geometry"] is None
):
fetched_vars[
"item_geometry"
] = datastreams_json["observedArea"]["type"]
elif (
datastreams_json["observedArea"].get("type")
is None
and fetched_vars["item_geometry"] is None
):
print("The Datastream does not have any geometry type. It tries to find out the geometry type automatically.")
if (
datastreams_json["observedArea"].get("coordinates")
is not None
and fetched_vars["item_bbox"] is None
):
fetched_vars["item_bbox"] = [
datastreams_json["observedArea"]["coordinates"]
]
elif (
datastreams_json["observedArea"].get("coordinates")
is None
and fetched_vars["item_bbox"] is None
):
print("The Datastream does not have any coordinates. So, the spatial extent of the item will be None.")
return
else:
print("The Datastream does not have any observedArea. So, the spatial extent of the item will be None.")
return
if datastreams_json.get("phenomenonTime") is not None:
fetched_vars[
"item_datetime"
] = datastreams_json["phenomenonTime"]
else:
print("The Datastream does not have any phenomenonTime. So, the temporal extent of the item will be None.")
return
elif datastreams_json["@iot.count"] > 1:
geometry_list = []
bbox_list = []
datetime_list = []
variable_names_list = []
variable_descriptions_list = []
variable_units_list = []
variable_dimensions_list = []
dimension_names_list = []
datastreams_number = get_number_of_entities(
link=thing_url,
entity="Datastreams",
)
list_of_datastreams_id = get_list_of_entities_id(
link=thing_url,
entity="Datastreams",
)
datastream_data = []
if datastreams_number == len(list_of_datastreams_id):
for datastream_index, datastream_number in enumerate(
list_of_datastreams_id
):
datastreams_url_by_number = (
f"{thing_url}/Datastreams({datastream_number})"
)
datastreams_json_by_number = open_sta_entity_links(
link=datastreams_url_by_number
)
try:
datastream_value = datastreams_json_by_number["@iot.id"]
datastream_data_temp = {}
asset_fields = {}
try:
datastream_data_temp["datstream_index"] = datastream_index
except Exception as exc:
print("Datastream id not available", exc)
if asset_as == "GeoJSON" :
try:
asset_fields["href"] = str(f"{sta_link}/{version}/Datastreams({datastream_value})/Observations?$select=result,phenomenonTime&$resultFormat=GeoJSON")
except Exception as exc:
print("Datastream href not found",exc)
else:
try:
asset_fields["href"] = str(f"{sta_link}/{version}/Datastreams({datastream_value})/Observations?$select=result,phenomenonTime&$resultFormat=CSV")
except Exception as exc:
print("Datastream href not found",exc)
try:
sensor_url = datastreams_json_by_number["@iot.selfLink"]
except Exception as exc:
print("sensor url not found",exc)
try:
asset_fields["title"] = datastreams_json_by_number["name"]
except Exception as exc:
print("Datastream title not found",exc)
try:
asset_fields["description"] = datastreams_json_by_number["description"]
except Exception as exc:
print("Datastream description not found",exc)
try:
asset_fields["extra_fields"] = {}
except Exception as exc:
print("Datastream extra fields not found",exc)
try:
asset_fields["extra_fields"]["unitOfMeasurement"] = datastreams_json_by_number["unitOfMeasurement"]
except Exception as exc:
print("Datastream unit of measurment not found",exc)
try:
asset_fields["extra_fields"]["properties"] = datastreams_json_by_number["properties"]
except Exception as exc:
print("Datastream properties not found",exc)
try:
sensor_url = datastreams_json_by_number["@iot.selfLink"]
asset_fields["extra_fields"]["datastream_link"] = sensor_url
sensor_url = sensor_url +"/Sensor"
sensor_details = open_sta_entity_links(sensor_url)
sname = sensor_details["name"]
asset_fields["extra_fields"]["SensorName"] = sname
asset_fields["extra_fields"]["data_csv"] = f"{sta_link}/Datastreams({datastream_value})/Observations?$select=result,phenomenonTime&$resultFormat=csv"
asset_fields["extra_fields"]["data_geojson"] = f"{sta_link}/Datastreams({datastream_value})/Observations?$select=result,phenomenonTime&$resultFormat=geojson"
except Exception as exc:
print("Datastream ID not found", exc)
asset_fields = {}
datastream_data_temp["asset_fields"] = asset_fields
datastream_data.append(datastream_data_temp)
except Exception as e:
print(f"couldn't fetch datastream properties due to exception {e}")
fetched_vars["assets"] = datastream_data
if (
datastreams_json_by_number.get("observedArea")
is not None
):
if (
datastreams_json_by_number.get(
"observedArea", {}
).get("type")
is not None
and fetched_vars.get(
"item_geometry"
)
is None
):
geometry_list.append(
datastreams_json_by_number[
"observedArea"
]["type"]
)
elif (
datastreams_json_by_number.get(
"observedArea", {}
).get("type")
is None
and fetched_vars["item_geometry"]
is None
):
print("The Datastream does not have any geometry type. It tries to find out the geometry type automatically.")
if (
datastreams_json_by_number.get(
"observedArea", {}
).get("coordinates")
is not None
and fetched_vars.get("item_bbox")
is None
):
bbox_list.append(
datastreams_json_by_number[
"observedArea"
]["coordinates"]
)
elif (
datastreams_json_by_number.get(
"observedArea", {}
).get("coordinates")
is None
and fetched_vars.get("item_bbox")
is None
):
print("The Datastream does not have any coordinates. So, the spatial extent of the item will be None.")
else:
print("The Datastream does not have any observedArea. So, the spatial extent of the item will be None.")
if (
datastreams_json_by_number.get(
"phenomenonTime"
)
is not None
and fetched_vars.get("item_datetime")
is None
):
datetime_list.append(
datastreams_json_by_number[
"phenomenonTime"
]
)
else:
datetime_list.append(None)
print("The Datastream does not have any phenomenonTime. So, the temporal extent of the item will be None."
)
else:
print("The number of Locations in the Thing is not equal to the number of Locations in the list of locations. So, it will look for the location in `observedArea` attribute of Datastream, and if it couldn't find any geometry there, the geometry of the item will be None."
)
return
if fetched_vars.get("item_geometry") is None:
fetched_vars["item_geometry"] = geometry_list
if fetched_vars.get("item_bbox") is None:
fetched_vars["item_bbox"] = bbox_list
if fetched_vars.get("item_datetime") is None:
fetched_vars["item_datetime"] = datetime_list
fetched_vars["properties"] = thing_json.get("properties")
fetched_vars["item_footprint"] = geometryf(bbox=fetched_vars["item_bbox"],geometry_type=fetched_vars["item_geometry"])
if fetched_vars.get("collection_footprint") is None:
fetched_vars[
"collection_footprint"
] = fetched_vars["item_footprint"]
item(fetched_vars)
fetched_vars["collection_footprint"] = geometry.shape(
fetched_vars["item_footprint"]
).union(
geometry.shape(fetched_vars["collection_footprint"])
)
fetched_vars["collection_bbox"] = list(
fetched_vars["collection_footprint"].bounds)
if fetched_vars.get("collection_datetime") is None:
fetched_vars["collection_datetime"] = []
fetched_vars["collection_datetime"].extend(
fetched_vars["item_datetime"]
)
return fetched_vars