-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspase.py
More file actions
345 lines (270 loc) · 12.1 KB
/
spase.py
File metadata and controls
345 lines (270 loc) · 12.1 KB
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
import os
import utilrsw
from hapimeta import cli, logger
log = logger('spase')
all_file = 'data/catalogs-all.pkl'
log.info(f"Reading {all_file}")
servers = utilrsw.read(all_file)
servers_keep = cli()
# Set to True to read info from data/info directory instead of from the catalog.
# Use this for testing to avoid having to re-run the catalog step after making
# changes to the info files.
reread_info = False
def spase_stub(config):
SchemaURL = config.get("SchemaURL", None)
Version = config.get("Version")
Spase = {
"xmlns": SchemaURL,
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:schemaLocation": f"{SchemaURL} {SchemaURL}/spase-{Version}.xsd",
"Version": Version,
"NumericalData": {
"AccessInformation": [],
"Parameter": []
}
}
return Spase
def add_NumericalData(Spase, dataset, map):
NumericalData = utilrsw.map_dict(dataset, map)
Spase['NumericalData'] = NumericalData
def add_Parameter(Spase, dataset, map):
parameters = utilrsw.get_path(dataset, 'info.parameters')
if parameters is not None:
Parameters = []
for parameter in parameters:
Parameter = utilrsw.map_dict(parameter, map)
Parameters.append(Parameter)
Spase['NumericalData']['Parameter'] = Parameters
def add_AccessInformation(Spase, dataset, about, capabilities, formatMap, template):
import copy
def script_info():
# Defaults to use if update fails.
languages = ['IDL', 'Javascript', 'MATLAB', 'Python', 'Autoplot', 'curl', 'wget']
try:
url = "https://hapi-server.org/servers/?return=script-options"
response = utilrsw.net.get_json(url)
languages = {}
for element in response['data']:
language = element.get('label', '')
language = language.split('/')[0]
languages[language] = True
languages = list(languages.keys())
except Exception as e:
log.warning(f"Unable to get script languages from {url}: {e}")
languages = ', '.join(languages)
language_formats = []
for language in languages.split(', '):
language_formats.append(f"x_Script.{language.strip()}")
return languages, language_formats
def formats(capabilities):
outputFormats = utilrsw.get_path(capabilities, 'outputFormats', default=['csv'])
Formats = []
for fmt in outputFormats:
if fmt not in formatMap:
#log.warning(f"Unknown output format: {fmt}. Skipping.")
continue
Formats.append(config['formatMap'][fmt])
return Formats
def description(about):
def extra(type):
desc = ""
type_capitalized = type.capitalize()
note = utilrsw.get_path(about, type)
if note is not None:
if isinstance(note, str):
desc = f"{type_capitalized}: {note}"
if isinstance(note, list):
notes = ""
for i, n in enumerate(note):
notes += f"{i+1}. {n}; "
notes = notes.rstrip('; ')
desc = f"{type_capitalized}s: {notes}"
return desc
desc = ""
description = utilrsw.get_path(about, 'description')
contact = utilrsw.get_path(about, 'contact')
contactID = utilrsw.get_path(about, 'contactID')
if description is None and contact is None and contactID is None:
return None
if description is not None:
desc += description
if contact and contactID:
if contact == contactID:
desc = f"{desc} (Contact: {contact})"
else:
desc = f"{desc} (Contact: {contact} <{contactID}>)"
if not contact and contactID:
desc = f"{desc} (Contact: <{contactID}>)"
if contact and not contactID:
desc = f"{desc} (Contact: {contact})"
serverCitation = utilrsw.get_path(about, 'serverCitation')
if serverCitation is not None:
desc = f"{desc}. Server Citation: {serverCitation} (see dataset description for citing the dataset)"
note = extra('note')
if note:
desc = f"{desc}. {note}"
warning = extra('warning')
if warning:
desc = f"{desc}. {warning}"
return desc + "."
data_formats = formats(capabilities)
languages, language_formats = script_info()
template = copy.deepcopy(template)
for i in range(len(template)):
url = template[i]['AccessURL']['URL'].format(server=dataset['server'], dataset=dataset['id'])
template[i]['AccessURL']['URL'] = url
template[i]['AccessURL']['ProductKey'] = dataset['id']
desc = description(about)
if desc is not None:
template[0]['AccessURL']['Description'] = desc
template[0]['AccessURL']['Format'] = data_formats
desc = template[1]['AccessURL']['Description'].format(languages=languages)
template[1]['AccessURL']['Description'] = desc
template[1]['AccessURL']['Format'] = language_formats
Spase['NumericalData']['AccessInformation'] = template
def add_SpatialMapping(Spase, dataset):
geoLocation = utilrsw.get_path(dataset, 'info.geoLocation')
if False and (geoLocation is not None):
# We discussed putting a warning in the description. This is not a good option
# because the description will become detached from the value. I think we
# should just do the conversion calculation and note that the
# calculation has been made in the description.
Spase['NumericalData']['SpatialMapping'] = {
"centerLongitude": geoLocation[0],
"centerLatitude": geoLocation[1]
}
if len(geoLocation) > 2:
Spase['NumericalData']['SpatialMapping']['centerElevation'] = geoLocation[2]
desc = "The SpatialMapping values are from the geoLocation object in HAPI metadata. "
desc += "Warning: In SPASE, centerLongitude and centerLatitude are in defined to be in GEO and "
desc += "centerElevation in WGS84. In HAPI, their equivalents are defined to be in WGS84. "
desc += "The values given for centerLongitude and centerLatitude are direct copies "
desc += "of content in the HAPI geoLocation and have not "
desc += "been converted from WGS84 to GEO."
Spase['NumericalData']['SpatialMapping']['Description'] = desc
point = utilrsw.get_path(dataset, 'info.location.point')
if point is not None:
coordinateSystemName = utilrsw.get_path(dataset, 'info.location.coordinateSystemName')
# TODO: 1. Check coordinateSystemSchema and verify that 'GEO' is a valid
# name and it means the same thing as GEO in SPASE.
# 2. If vectorComponents, verify that they contain latitude, longitude,
# and altitude and adjust what elements of point correspond to
# centerLongitude, centerLongitude, and centerElevation.
if coordinateSystemName == 'GEO':
Spase['NumericalData']['SpatialMapping'] = {
"centerLongitude": point[0],
"centerLatitude": point[1]
}
if len(point) > 2:
Spase['NumericalData']['SpatialMapping']['centerElevation'] = point[2]
def add_ResourceHeader(Spase, dataset):
import datetime
def extract_doi(doi_string):
DOI = None
if doi_string.startswith('https://doi.org/'):
DOI = doi_string[len('https://doi.org/'):]
if doi_string.startswith('doi:'):
DOI = doi_string[len('doi:'):]
return DOI
def informationURLs(dataset):
url_template = "https://hapi-server.org/servers/#server={server}&dataset={dataset}"
url = url_template.format(server=dataset['server'], dataset=dataset['id'])
InformationURLs = [{
"Name": "hapi-server.org",
"URL": url,
"Description": "hapi-server.org dataset information page"
}]
resourceURL = utilrsw.get_path(dataset, 'info.resourceURL')
if resourceURL is not None:
InformationURLs.append({
"Name": "Resource URL from HAPI metadata",
"URL": resourceURL,
"Description": "The URL is the the resourceURL field in the HAPI /info response for this dataset."
})
additionalMetadata = utilrsw.get_path(dataset, 'info.additionalMetadata')
if additionalMetadata is not None:
if isinstance(additionalMetadata, dict):
additionalMetadata = [additionalMetadata]
for additional in additionalMetadata:
InformationURL = {"Name": "", "URL": ""}
desc = ""
if 'contentURL' not in additional and 'content' not in additional:
log.error(f"{dataset['id']}: additionalMetadata entry missing one of 'contentURL' or 'content'")
continue
if 'contentURL' in additional:
InformationURL["URL"] = additional['contentURL']
if 'content' in additional:
url = f"{dataset['server_url']}/info?dataset={dataset['id']}"
desc = f"Additional metadata content is available in the additionalMetadata node in: {url}"
if 'name' in additional:
InformationURL["Name"] = additional['name']
else:
InformationURL['Name'] = "Additional metadata"
if 'aboutURL' in additional:
desc += f"Metadata description: {additional['aboutURL']}"
if 'schemaURL' in additional:
desc += f". Metadata schema: {additional['schemaURL']}."
note = "The information in this InformationURL node is derived from an additionalMetadata node in HAPI /info response"
if desc != "":
InformationURL['Description'] = f"{desc}. {note}"
else:
InformationURL['Description'] = note
InformationURLs.append(InformationURL)
return InformationURLs
if 'ResourceHeader' not in Spase['NumericalData']:
Spase['NumericalData']['ResourceHeader'] = {}
Spase['NumericalData']['ResourceHeader']["InformationURL"] = informationURLs(dataset)
now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%MZ")
Spase['NumericalData']['ResourceHeader']['ReleaseDate'] = now
for field in ['datasetCitation', 'resourceID', 'citation']:
value = utilrsw.get_path(dataset, f'info.{field}')
if value is not None:
DOI = extract_doi(value)
if DOI is not None:
Spase['NumericalData']['ResourceHeader']['DOI'] = DOI
else:
desc = Spase['NumericalData']['ResourceHeader'].get('Description', '')
desc = desc.rstrip('.')
extra = f"HAPI resourceID: {value}."
Spase['NumericalData']['ResourceHeader']['Description'] = f"{desc}. {extra}"
desc = Spase['NumericalData']['ResourceHeader'].get('Description', '')
desc = desc.rstrip('.')
desc = f"{desc}. The ReleaseDate is the date that this SPASE record was generated by an automated process. Changes are not tracked so the ReleaseDate may change when no changes have occured."
script_path = os.path.dirname(os.path.realpath(__file__))
out_path = os.path.join(script_path, 'data', 'spase')
config_file = os.path.join(script_path, 'spase.json')
config = utilrsw.read(config_file)
Spase = spase_stub(config["Spase"])
for server in servers:
if servers_keep is not None and server not in servers_keep:
continue
log.info(f"Processing server: {server}")
catalog = utilrsw.get_path(servers[server], 'catalog.catalog')
if catalog is None:
log.error(f"No catalog found for server: {server}")
continue
log.info(f" {len(catalog)} datasets")
about = utilrsw.get_path(servers[server], 'about')
capabilities = utilrsw.get_path(servers[server], 'capabilities')
for idx, dataset in enumerate(catalog):
dataset['server'] = server
dataset['server_url'] = about['x_url']
dataset['dataset'] = dataset['id']
log.info(f" {idx+1}. {dataset['id']}")
if reread_info:
info_file = os.path.join(script_path, 'data', 'infos', server, f"{dataset['id']}.json")
try:
info_dict = utilrsw.read(info_file)
except Exception as e:
log.error(f" reread_info = True but unable to read info file {info_file} for server {server}, dataset {dataset['id']}. Using info from catalog.")
continue
dataset['info'] = info_dict
log.info(f" reread_info = True => overriding info from {all_file} with that in {info_file}.")
add_NumericalData(Spase, dataset, config['hapi2spase']['dataset'])
add_ResourceHeader(Spase, dataset)
add_SpatialMapping(Spase, dataset)
add_AccessInformation(Spase, dataset, about, capabilities, config['formatMap'], config['AccessInformation'])
add_Parameter(Spase, dataset, config['hapi2spase']['parameter'])
out_file = os.path.join(out_path, server, f"{dataset['id']}.json")
log.debug(f"Writing {out_file}")
utilrsw.write(out_file, Spase)