|
1 | 1 | import argparse
|
| 2 | +import csv |
2 | 3 | import logging
|
3 | 4 | import os.path
|
4 | 5 | import time
|
5 | 6 | import xml.etree.ElementTree as eTree
|
6 | 7 |
|
| 8 | +import csep |
7 | 9 | import h5py
|
8 | 10 | import numpy
|
9 | 11 | import pandas
|
| 12 | +import pandas as pd |
| 13 | +from csep.core.catalogs import CSEPCatalog |
10 | 14 | from csep.core.regions import QuadtreeGrid2D, CartesianGrid2D
|
11 | 15 | from csep.models import Polygon
|
| 16 | +from csep.utils.time_utils import strptime_to_utc_epoch |
12 | 17 |
|
13 | 18 | log = logging.getLogger(__name__)
|
14 | 19 |
|
| 20 | +class CatalogForecastParsers: |
15 | 21 |
|
16 |
| -class ForecastParsers: |
| 22 | + @staticmethod |
| 23 | + def csv(filename, **kwargs): |
| 24 | + csep_headers = ['lon', 'lat', 'magnitude', 'time_string', 'depth', 'catalog_id', |
| 25 | + 'event_id'] |
| 26 | + hermes_headers = ['realization_id', 'magnitude', 'depth', 'latitude', 'longitude', |
| 27 | + 'time'] |
| 28 | + headers_df = pd.read_csv(filename, nrows=0).columns.str.strip().to_list() |
| 29 | + |
| 30 | + # CSEP headers |
| 31 | + if headers_df[:2] == csep_headers[:2]: |
| 32 | + |
| 33 | + return csep.load_catalog_forecast(filename, **kwargs) |
| 34 | + |
| 35 | + elif headers_df == hermes_headers: |
| 36 | + return csep.load_catalog_forecast(filename, |
| 37 | + catalog_loader=CatalogForecastParsers.load_hermes_catalog, |
| 38 | + **kwargs |
| 39 | + ) |
| 40 | + else: |
| 41 | + raise Exception('Catalog Forecast could not be loaded') |
| 42 | + |
| 43 | + @staticmethod |
| 44 | + def load_hermes_catalog(filename, **kwargs): |
| 45 | + """ Loads hermes synthetic catalogs in csep-ascii format. |
| 46 | +
|
| 47 | + This function can load multiple catalogs stored in a single file. This typically called to |
| 48 | + load a catalog-based forecast, but could also load a collection of catalogs stored in the same file |
| 49 | +
|
| 50 | + Args: |
| 51 | + filename (str): filepath or directory of catalog files |
| 52 | + **kwargs (dict): passed to class constructor |
| 53 | +
|
| 54 | + Return: |
| 55 | + yields CSEPCatalog class |
| 56 | + """ |
| 57 | + |
| 58 | + def read_float(val): |
| 59 | + """Returns val as float or None if unable""" |
| 60 | + try: |
| 61 | + val = float(val) |
| 62 | + except: |
| 63 | + val = None |
| 64 | + return val |
| 65 | + |
| 66 | + def is_header_line(line): |
| 67 | + if line[0].lower() == 'realization_id': |
| 68 | + return True |
| 69 | + else: |
| 70 | + return False |
| 71 | + |
| 72 | + def read_catalog_line(line): |
| 73 | + # convert to correct types |
| 74 | + |
| 75 | + catalog_id = int(line[0]) |
| 76 | + magnitude = read_float(line[1]) |
| 77 | + depth = read_float(line[2]) |
| 78 | + lat = read_float(line[3]) |
| 79 | + lon = read_float(line[4]) |
| 80 | + # maybe fractional seconds are not included |
| 81 | + origin_time = line[5] |
| 82 | + if origin_time: |
| 83 | + try: |
| 84 | + origin_time = strptime_to_utc_epoch(origin_time, |
| 85 | + format='%Y-%m-%d %H:%M:%S.%f') |
| 86 | + except ValueError: |
| 87 | + origin_time = strptime_to_utc_epoch(origin_time, |
| 88 | + format='%Y-%m-%d %H:%M:%S') |
| 89 | + |
| 90 | + event_id = 0 |
| 91 | + # temporary event |
| 92 | + temp_event = (event_id, origin_time, lat, lon, depth, magnitude) |
| 93 | + return temp_event, catalog_id |
| 94 | + |
| 95 | + # handle all catalogs in single file |
| 96 | + if os.path.isfile(filename): |
| 97 | + with open(filename, 'r', newline='') as input_file: |
| 98 | + catalog_reader = csv.reader(input_file, delimiter=',') |
| 99 | + # csv treats everything as a string convert to correct types |
| 100 | + events = [] |
| 101 | + # all catalogs should start at zero |
| 102 | + prev_id = None |
| 103 | + for line in catalog_reader: |
| 104 | + # skip header line on first read if included in file |
| 105 | + if prev_id is None: |
| 106 | + if is_header_line(line): |
| 107 | + continue |
| 108 | + # read line and return catalog id |
| 109 | + temp_event, catalog_id = read_catalog_line(line) |
| 110 | + empty = False |
| 111 | + # OK if event_id is empty |
| 112 | + if all([val in (None, '') for val in temp_event[1:]]): |
| 113 | + empty = True |
| 114 | + # first event is when prev_id is none, catalog_id should always start at zero |
| 115 | + if prev_id is None: |
| 116 | + prev_id = 0 |
| 117 | + # if the first catalog doesn't start at zero |
| 118 | + if catalog_id != prev_id: |
| 119 | + if not empty: |
| 120 | + events = [temp_event] |
| 121 | + else: |
| 122 | + events = [] |
| 123 | + for id in range(catalog_id): |
| 124 | + yield CSEPCatalog(data=[], catalog_id=id, **kwargs) |
| 125 | + prev_id = catalog_id |
| 126 | + continue |
| 127 | + # accumulate event if catalog_id is the same as previous event |
| 128 | + if catalog_id == prev_id: |
| 129 | + if not all([val in (None, '') for val in temp_event]): |
| 130 | + events.append(temp_event) |
| 131 | + prev_id = catalog_id |
| 132 | + # create and yield class if the events are from different catalogs |
| 133 | + elif catalog_id == prev_id + 1: |
| 134 | + yield CSEPCatalog(data=events, catalog_id=prev_id, **kwargs) |
| 135 | + # add event to new event list |
| 136 | + if not empty: |
| 137 | + events = [temp_event] |
| 138 | + else: |
| 139 | + events = [] |
| 140 | + prev_id = catalog_id |
| 141 | + # this implies there are empty catalogs, because they are not listed in the ascii file |
| 142 | + elif catalog_id > prev_id + 1: |
| 143 | + yield CSEPCatalog(data=events, catalog_id=prev_id, **kwargs) |
| 144 | + # if prev_id = 0 and catalog_id = 2, then we skipped one catalog. thus, we skip catalog_id - prev_id - 1 catalogs |
| 145 | + num_empty_catalogs = catalog_id - prev_id - 1 |
| 146 | + # first yield empty catalog classes |
| 147 | + for id in range(num_empty_catalogs): |
| 148 | + yield CSEPCatalog(data=[], |
| 149 | + catalog_id=catalog_id - num_empty_catalogs + id, |
| 150 | + **kwargs) |
| 151 | + prev_id = catalog_id |
| 152 | + # add event to new event list |
| 153 | + if not empty: |
| 154 | + events = [temp_event] |
| 155 | + else: |
| 156 | + events = [] |
| 157 | + else: |
| 158 | + raise ValueError( |
| 159 | + "catalog_id should be monotonically increasing and events should be ordered by catalog_id") |
| 160 | + # yield final catalog, note: since this is just loading catalogs, it has no idea how many should be there |
| 161 | + cat = CSEPCatalog(data=events, catalog_id=prev_id, **kwargs) |
| 162 | + yield cat |
| 163 | + |
| 164 | + elif os.path.isdir(filename): |
| 165 | + raise NotImplementedError( |
| 166 | + "reading from directory or batched files not implemented yet!") |
| 167 | + |
| 168 | + |
| 169 | + |
| 170 | +class GriddedForecastParsers: |
17 | 171 |
|
18 | 172 | @staticmethod
|
19 | 173 | def dat(filename):
|
@@ -151,7 +305,7 @@ def is_mag(num):
|
151 | 305 | sep = " "
|
152 | 306 |
|
153 | 307 | if "tile" in line:
|
154 |
| - rates, region, magnitudes = ForecastParsers.quadtree(filename) |
| 308 | + rates, region, magnitudes = GriddedForecastParsers.quadtree(filename) |
155 | 309 | return rates, region, magnitudes
|
156 | 310 |
|
157 | 311 | data = pandas.read_csv(
|
@@ -308,13 +462,13 @@ def serialize():
|
308 | 462 | args = parser.parse_args()
|
309 | 463 |
|
310 | 464 | if args.format == "quadtree":
|
311 |
| - ForecastParsers.quadtree(args.filename) |
| 465 | + GriddedForecastParsers.quadtree(args.filename) |
312 | 466 | if args.format == "dat":
|
313 |
| - ForecastParsers.dat(args.filename) |
| 467 | + GriddedForecastParsers.dat(args.filename) |
314 | 468 | if args.format == "csep" or args.format == "csv":
|
315 |
| - ForecastParsers.csv(args.filename) |
| 469 | + GriddedForecastParsers.csv(args.filename) |
316 | 470 | if args.format == "xml":
|
317 |
| - ForecastParsers.xml(args.filename) |
| 471 | + GriddedForecastParsers.xml(args.filename) |
318 | 472 |
|
319 | 473 |
|
320 | 474 | if __name__ == "__main__":
|
|
0 commit comments