QuakeML to json

Warning: Much of this functionality will eventually be moved to obspy, see this PR.

The following demonstrates obsplus’ ability to serialize obspy catalog objects into json. All such conversions should be lossless.

Get a catalog

[1]:
import obspy
import obsplus

crandall = obsplus.load_dataset('crandall_test')

cat = crandall.event_client.get_events()

print(cat)
8 Event(s) in Catalog:
2007-08-06T08:48:40.010000Z | +39.464, -111.228 | 4.2  mb
2007-08-07T02:14:24.080000Z | +39.463, -111.223 | 1.17 ml
2007-08-07T03:44:18.470000Z | +39.462, -111.215 | 1.68 ml
2007-08-07T07:13:05.760000Z | +39.461, -111.224 | 2.55 ml
2007-08-07T02:05:04.490000Z | +39.465, -111.225 | 2.44 ml
2007-08-06T10:47:25.600000Z | +39.462, -111.232 | 1.92 ml
2007-08-07T21:42:51.130000Z | +39.463, -111.220 | 1.88 ml
2007-08-06T01:44:48.810000Z | +39.462, -111.238 | 2.32 ml

json conversions

[2]:
import obsplus

# convert to json str
json_str = obsplus.cat_to_json(cat)

# print sample
print(json_str[0:400])

# convert back
cat2 = obsplus.json_to_cat(json_str)
{"resource_id":{"id":"smi:local/1023cbfe-e4dd-4b09-b5a5-9ce40f12725f"},"events":[{"resource_id":{"id":"smi:local/248839"},"event_type":null,"event_type_certainty":null,"creation_info":{"agency_id":"NIOSH","agency_uri":null,"author":"DC","author_uri":null,"creation_time":"2018-10-10T20:33:13.618111","version":null},"preferred_origin_id":{"id":"smi:local/404329"},"preferred_magnitude_id":null,"prefe
/usr/share/miniconda3/envs/test/lib/python3.10/site-packages/obspy/core/util/attribdict.py:120: UserWarning: Setting attribute "seed_string" which is not a default attribute ("network_code", "station_code", "channel_code", "location_code", "resource_uri").
  warnings.warn(msg)
[3]:
# json serialization should be lossless after handling Quantity Errors
# this won't be needed once obspy 1.2.0 is released.
import obspy.core.event as ev

from obsplus.utils import yield_obj_parent_attr


def _remove_empty_quantity_errors(catalog):
    """
    Copy the catalog and set all empty QunatityErrors to None.
    This is needed to check equality of catalogs that may have
    None or empty QuantityErrors.

    Fixed in https://github.com/obspy/obspy/pull/2185
    """
    cat = catalog.copy()
    for obj, parent, attr in yield_obj_parent_attr(cat, cls=ev.QuantityError):
        if not obj:
            setattr(parent, attr, None)
    return cat

cat1 = _remove_empty_quantity_errors(cat)

cat2 = _remove_empty_quantity_errors(cat2)

assert cat1 == cat2