Newer
Older
import json
import math
from collections import OrderedDict
import numpy as np
from obspy import Stream, Trace, UTCDateTime
from geomagio.TimeseriesFactory import TimeseriesFactory
from geomagio.api.ws.Element import ELEMENT_INDEX
class CovJSONFactory(TimeseriesFactory):
"""Factory for reading/writing CovJSON format Geomagnetic Data."""
def __init__(
self,
time_format="iso8601", # could be "iso8601" or "numeric"
time_axis_mode="expanded", # could be "expanded" or "start-stop-num"
**kwargs,
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
):
"""
Parameters
----------
time_format : {"iso8601", "numeric"}
- "iso8601": each time value is an ISO8601 string
- "numeric": each time value is numeric (epoch milliseconds)
time_axis_mode : {"expanded", "start-stop-num"}
- "expanded": store domain axes as a list of all time values
- "start-stop-num": store domain axes as start, stop, and num
"""
super().__init__(**kwargs)
self.time_format = time_format
self.time_axis_mode = time_axis_mode
def parse_string(self, data: str, **kwargs):
"""
Parse a CovJSON string into an ObsPy Stream.
Supports both "expanded" (t->values) and "start-stop-num" domain axes:
- If domain->axes->t->values is found, each entry is a time sample.
- Otherwise, if domain->axes->t has start, stop, and num,
generate times using linear increments (assuming uniform sampling).
For the time format:
- If times are numeric, they are interpreted as epoch milliseconds.
- If times are strings, they are interpreted as ISO8601 (parsed by UTCDateTime).
Returns an empty Stream if no valid time axis can be found.
"""
covjson = json.loads(data)
domain = covjson.get("domain", {})
ranges = covjson.get("ranges", {})
info = covjson.get("geomag:info", {})
# domain->axes->(x, y, z, t)
axes = domain.get("axes", {})
x_axis = axes.get("x", {}).get("values", [])
y_axis = axes.get("y", {}).get("values", [])
z_axis = axes.get("z", {}).get("values", [])
t_axis = axes.get("t", {})
# Determine the times from t_axis:
times = []
if "values" in t_axis:
# "expanded" approach
raw_values = t_axis["values"]
for val in raw_values:
# If numeric, interpret as epoch ms; if string, parse ISO8601
if isinstance(val, (int, float)):
# interpret as epoch ms
times.append(UTCDateTime(val / 1000.0))
else:
# interpret as ISO8601
times.append(UTCDateTime(val))
elif {"start", "stop", "num"}.issubset(t_axis):
# "start-stop-num" approach
start_raw = t_axis["start"]
stop_raw = t_axis["stop"]
num = t_axis["num"]
# parse start, stop
if isinstance(start_raw, (int, float)):
start_dt = UTCDateTime(start_raw / 1000.0)
else:
start_dt = UTCDateTime(start_raw)
if isinstance(stop_raw, (int, float)):
stop_dt = UTCDateTime(stop_raw / 1000.0)
else:
stop_dt = UTCDateTime(stop_raw)
if num <= 1:
# trivial case: single sample
times = [start_dt]
else:
# create uniform times from start to stop
step = (stop_dt.timestamp - start_dt.timestamp) / (num - 1)
for i in range(num):
times.append(UTCDateTime(start_dt.timestamp + i * step))
else:
# no recognized time axis => return empty stream
return Stream()
# If still no times, return empty
if not times:
return Stream()
lon = float(x_axis[0] if x_axis else info.get("longitude", 0.0))
lat = float(y_axis[0] if y_axis else info.get("latitude", 0.0))
alt = float(z_axis[0] if z_axis else info.get("altitude", 0.0))
station = info.get("iaga_code", "")
data_type = info.get("data_type", "")
data_interval_type = info.get("data_interval_type", "")
station_name = info.get("station_name", station)
stream = Stream()
# Build traces from ranges
for channel_name, channel_range in ranges.items():
values = channel_range.get("values", [])
if not values:
continue
data_array = np.array(values, dtype=float)
stats = {
"network": "",
"station": station,
"channel": channel_name,
"starttime": times[0],
"npts": len(data_array),
}
# Compute sampling_rate if multiple times
if len(times) > 1:
dt = times[1].timestamp - times[0].timestamp
stats["sampling_rate"] = 1.0 / dt if dt != 0 else 1.0
else:
stats["sampling_rate"] = 1.0
# Additional metadata
stats["geodetic_longitude"] = lon
stats["geodetic_latitude"] = lat
stats["elevation"] = alt
stats["station_name"] = station_name
stats["data_type"] = data_type
stats["data_interval_type"] = data_interval_type
trace = Trace(data=data_array, header=stats)
stream += trace
return stream
def write_file(self, fh, timeseries: Stream, channels):
"""
Write a CovJSON coverage. Currently uses "expanded" time axis and iso8601 times.
"""
if not timeseries or len(timeseries) == 0:
fh.write(json.dumps({}, indent=2).encode("utf-8"))
return
timeseries.merge()
# Filter channels
if channels:
new_stream = Stream()
for ch in channels:
new_stream += timeseries.select(channel=ch)
timeseries = new_stream
timeseries.sort(keys=["starttime"])
tr = timeseries[0]
stats = tr.stats
station = stats.station or ""
lat = float(getattr(stats, "geodetic_latitude", 0.0))
lon = float(getattr(stats, "geodetic_longitude", 0.0))
alt = float(getattr(stats, "elevation", 0.0))
data_type = getattr(stats, "data_type", str(self.type))
data_interval_type = getattr(stats, "data_interval_type", str(self.interval))
station_name = getattr(stats, "station_name", station)
reported_orientation = "".join(channels)
sensor_orientation = getattr(stats, "sensor_orientation", "")
digital_sampling_rate = getattr(stats, "digital_sampling_rate", 0.0)
sampling_period = getattr(stats, "sampling_period", 0.0)
npts = tr.stats.npts
delta = tr.stats.delta
starttime = tr.stats.starttime
if self.time_axis_mode == "expanded":
time_values = []
for i in range(npts):
current_time = starttime + i * delta
if self.time_format == "numeric":
# e.g. convert to epoch milliseconds
time_values.append(int(current_time.timestamp * 1000))
else:
# default iso8601
time_values.append(current_time.isoformat())
time_axis_dict = {"values": time_values}
else:
# for "start-stop-num" approach
# numeric epoch example
if self.time_format == "numeric":
start_val = int(starttime.timestamp * 1000)
end_val = int((starttime + (npts - 1) * delta).timestamp * 1000)
else:
# if iso8601, you might store e.g. start/end as iso strings
start_val = starttime.isoformat()
end_val = (starttime + (npts - 1) * delta).isoformat()
time_axis_dict = {
"start": start_val,
"stop": end_val,
"num": npts,
}
domain = OrderedDict()
domain["type"] = "Domain"
domain["domainType"] = "PointSeries"
domain["axes"] = {
"x": {"values": [lon]},
"y": {"values": [lat]},
"z": {"values": [alt]},
"t": time_axis_dict, # either start-stop-num or expanded
}
domain["referencing"] = [
{
"coordinates": ["x", "y", "z"],
"system": {
"type": "GeographicCRS",
"id": "http://www.opengis.net/def/crs/OGC/1.3/CRS84",
},
},
{
"coordinates": ["t"],
"system": {
"type": "TemporalRS",
"id": "Gregorian",
"calendar": "Gregorian",
},
},
]
parameters = OrderedDict()
ranges_obj = OrderedDict()
for trace in timeseries:
ch_name = trace.stats.channel
if channels and ch_name not in channels:
continue
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
element_info = ELEMENT_INDEX.get(ch_name)
if element_info:
param_description = element_info.name
param_unit = element_info.units
param_label = element_info.abbreviation or ch_name
else:
param_description = f"Data for channel {ch_name}"
param_unit = "nT"
param_label = ch_name
param_meta = {
"type": "Parameter",
"description": {"en": param_description},
"unit": {
"label": {"en": param_unit},
"symbol": {
"type": "https://intermagnet.org/faq/10.geomagnetic-comp.html",
"value": param_unit,
},
},
"observedProperty": {
"id": "https://intermagnet.org/faq/10.geomagnetic-comp.html",
"label": {"en": param_label},
},
}
parameters[ch_name] = param_meta
arr = trace.data
cov_range = OrderedDict()
cov_range["type"] = "NdArray"
cov_range["dataType"] = "float"
cov_range["axisNames"] = ["t"]
cov_range["shape"] = [len(arr)]
cov_range["values"] = [float(v) for v in arr]
ranges_obj[ch_name] = cov_range
coverage = OrderedDict()
coverage["type"] = "Coverage"
coverage["domain"] = domain
coverage["parameters"] = parameters
coverage["ranges"] = ranges_obj
coverage["geomag:info"] = {
"institute": getattr(stats, "agency_name", ""),
"latitude": lat,
"longitude": lon,
"altitude": alt,
"station_name": station_name,
"iaga_code": station,
"reported_orientation": reported_orientation,
"sensor_orientation": sensor_orientation,
"digital_sampling_rate": digital_sampling_rate,
"data_interval_type": data_interval_type,
"data_type": data_type,
"sampling_period": sampling_period,
}
# Optional: Possibly unsupported
optional_fields = {
"location": getattr(stats, "location", None),
"comments": getattr(stats, "filter_comments", None),
"declination_base": getattr(stats, "declincation_base", None),
"terms_of_use": getattr(stats, "conditions_of_use", None),
}
for key, value in optional_fields.items():
if value is not None:
coverage["geomag:info"][key] = value
covjson_str = json.dumps(coverage, indent=2)
fh.write(covjson_str.encode("utf-8"))