|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +# Copyright (C) 2021 Triantafyllis Nikolaos |
| 5 | + |
| 6 | +# This file is part of Gisola. |
| 7 | + |
| 8 | +# Gisola is free software: you can redistribute it and/or modify |
| 9 | +# it under the terms of the GNU General Public License as published by |
| 10 | +# the Free Software Foundation, either version 3 of the License, |
| 11 | +# or any later version. |
| 12 | + |
| 13 | +# Gisola is distributed in the hope that it will be useful, |
| 14 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 | +# GNU General Public License for more details. |
| 17 | + |
| 18 | +# You should have received a copy of the GNU General Public License |
| 19 | +# along with Gisola. If not, see <https://www.gnu.org/licenses/>. |
| 20 | + |
| 21 | +import yaml, logging, sys, os, time as tm |
| 22 | +from obspy import UTCDateTime, Stream, Trace, Inventory |
| 23 | +#from obspy.geodetics.base import inside_geobounds |
| 24 | +from turfpy.measurement import boolean_point_in_polygon |
| 25 | +from geojson import Point, Polygon, Feature |
| 26 | + |
| 27 | +# local lib |
| 28 | +import event |
| 29 | + |
| 30 | +def setup_logger(name, log_file, level=logging.INFO): |
| 31 | + """To setup as many loggers as you want""" |
| 32 | + |
| 33 | + handler = logging.FileHandler(log_file) |
| 34 | + console = logging.StreamHandler() |
| 35 | + |
| 36 | + form=logging.Formatter('%(asctime)s %(levelname)s %(message)s') |
| 37 | + form.converter = tm.gmtime |
| 38 | + |
| 39 | + handler.setFormatter(form) |
| 40 | + console.setFormatter(form) |
| 41 | + |
| 42 | + logger = logging.getLogger(name) |
| 43 | + logger.setLevel(level) |
| 44 | + console.setLevel(level) |
| 45 | + |
| 46 | + logger.addHandler(handler) |
| 47 | + logger.addHandler(console) |
| 48 | + |
| 49 | + logger.propagate = False |
| 50 | + |
| 51 | + return logger |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | +def read(filepath): |
| 56 | + with open(filepath, 'r') as _f: |
| 57 | + return yaml.load(_f, Loader=yaml.FullLoader) |
| 58 | + |
| 59 | +def rules(magnitude, domain): |
| 60 | + return [elem[2] for elem in list(filter(lambda x: True \ |
| 61 | + if round(x[0],1)<=round(magnitude,1) and round(magnitude,1)<=round(x[1],1) \ |
| 62 | + else False, domain))] |
| 63 | + |
| 64 | +def init(evnt, _cfg): |
| 65 | + """ |
| 66 | + Initialize process based on event's info and configuration |
| 67 | + """ |
| 68 | + # check crustal model geobox |
| 69 | + def check(rule): |
| 70 | + if rule['Geobox'] and boolean_point_in_polygon(Feature(\ |
| 71 | + geometry=Point((org.longitude, org.latitude))), \ |
| 72 | + Polygon([[eval('('+x.replace(')','').replace('(','')+')') for x in rule['Geobox'].replace(', ', ',').split('),(')]])): |
| 73 | + return True |
| 74 | + |
| 75 | + # global variables for the entire program |
| 76 | + global cfg, evt, org, inv, distRules, shiftRules, windowRules, freqRules, st, \ |
| 77 | + gridRules, crustalRules, workdir, sourcedir, crustaldir, grdatdir, greendir,\ |
| 78 | + vel_types, acc_types, inpinvdir, inversiondir, allstatdir, rawdir, blackList, \ |
| 79 | + whiteList, magPriority, azmGap, outputdir, bestinvdir, besttl, solutions, \ |
| 80 | + correlations, logger, locations, revise |
| 81 | + |
| 82 | + # make configuration global variable |
| 83 | + cfg=_cfg |
| 84 | + |
| 85 | + # make event global variable |
| 86 | + evt=evnt |
| 87 | + org=event.getOrigin(cfg,evnt,cfg['Watcher']['Historical']) |
| 88 | + mag=event.getMagnitude(evnt, org) |
| 89 | + |
| 90 | + # broadband |
| 91 | + vel_types=['M/S', 'M/SEC', 'NM/S', 'NM/SEC', 'CM/S', 'CM/SEC', 'MM/S', 'MM/SEC'] |
| 92 | + |
| 93 | + # strong motion |
| 94 | + acc_types=['M/S**2', 'M/(S**2)', 'M/SEC**2', 'M/(SEC**2)', 'M/S/S', \ |
| 95 | + 'NM/S**2', 'NM/(S**2)', 'NM/SEC**2', 'NM/(SEC**2)', 'CM/S**2', \ |
| 96 | + 'CM/(S**2)', 'CM/SEC**2', 'CM/(SEC**2)', 'MM/S**2', 'MM/(S**2)', \ |
| 97 | + 'MM/SEC**2', 'MM/(SEC**2)'] |
| 98 | + |
| 99 | + st=Stream() # init |
| 100 | + |
| 101 | + # read configuration file |
| 102 | + #cfg=read(filepath) |
| 103 | + |
| 104 | + # define workdir |
| 105 | + #workdir=os.path.join(cfg['WorkDir'],str(org.time)[:4],str(org.time).split('.')[0]+'_'+\ |
| 106 | + # os.path.basename(str(evt.resource_id)),str(UTCDateTime.now())) |
| 107 | + workdir=os.path.join(cfg['WorkDir'],str(org.time)[:4],os.path.basename(str(evt.resource_id)),str(UTCDateTime.now())) |
| 108 | + |
| 109 | + sourcedir=os.path.join(workdir, 'sources') |
| 110 | + crustaldir=os.path.join(workdir, 'crustals') |
| 111 | + grdatdir=os.path.join(workdir,'grdat') |
| 112 | + greendir=os.path.join(workdir,'greens') |
| 113 | + inpinvdir=os.path.join(workdir,'inpinv') |
| 114 | + allstatdir=os.path.join(workdir,'allstat') |
| 115 | + rawdir=os.path.join(workdir,'raw') |
| 116 | + inversiondir=os.path.join(workdir,'inversions') |
| 117 | + outputdir=os.path.join(workdir,'output') |
| 118 | + |
| 119 | + os.makedirs(workdir) |
| 120 | + os.makedirs(outputdir) |
| 121 | + |
| 122 | + revise=False |
| 123 | + |
| 124 | + logger = setup_logger(str(UTCDateTime.now()), os.path.join(outputdir, 'log')) |
| 125 | + |
| 126 | + #logging.basicConfig(level=getattr(logging, 'INFO'), \ |
| 127 | + #format='%(asctime)s - %(message)s\n', handlers=[ |
| 128 | + # logging.FileHandler(filename=os.path.join(workdir, 'log')), |
| 129 | + # logging.StreamHandler() |
| 130 | + #]) |
| 131 | + |
| 132 | + distRules=rules(mag.mag, cfg['Inventory']['Distance']) |
| 133 | + shiftRules=rules(mag.mag, cfg['Inversion']['TimeShift']) |
| 134 | + windowRules=rules(mag.mag, cfg['Inversion']['Window']) |
| 135 | + freqRules=rules(mag.mag, cfg['Inversion']['Frequency']) |
| 136 | + |
| 137 | + # filter grid rules based on magnitude |
| 138 | + gridRules=list(filter(lambda x: True if round(x['Rule'][0],1)<=round(mag.mag,1) and \ |
| 139 | + round(mag.mag,1)<=round(x['Rule'][1],1) else False, cfg['Green']['Grid'])) |
| 140 | + |
| 141 | + crustalRules=list(filter(check, cfg['Green']['Crustal'])) |
| 142 | + |
| 143 | + if not crustalRules: |
| 144 | + crustalRules=[rule for rule in cfg['Green']['Crustal'] if not rule['Geobox']] |
| 145 | + |
| 146 | + # read station file for whitelist and blacklist |
| 147 | + if cfg['Inventory']['WhiteList']['Filepath']: |
| 148 | + with open(cfg['Inventory']['WhiteList']['Filepath'], 'r') as _: |
| 149 | + lines= _.readlines() |
| 150 | + |
| 151 | + magPriority=max(rules(mag.mag, cfg['Inventory']['WhiteList']['Rules'])) |
| 152 | + |
| 153 | + whiteList=[] |
| 154 | + blackList=[] |
| 155 | + |
| 156 | + for line in lines: |
| 157 | + if not(line.startswith('#') or line.startswith('\n')): |
| 158 | + net, sta, *_=line.split() |
| 159 | + priority=int(_[0]) if _ else int(cfg['Inventory']['WhiteList']['Priority']) |
| 160 | + |
| 161 | + if priority==0: |
| 162 | + blackList.append([net,sta]) |
| 163 | + |
| 164 | + elif priority >= magPriority: |
| 165 | + whiteList.append([net,sta,priority]) |
| 166 | + |
| 167 | +def dump(dictionary): |
| 168 | + return yaml.dump(dictionary, indent=2, sort_keys=True) |
| 169 | + |
| 170 | +# decorator function for logging |
| 171 | +def log(func): |
| 172 | + def inner(*args, **kwargs): |
| 173 | + func(*args, **kwargs) |
| 174 | + logger.info(st.__str__(extended=True)) |
| 175 | + return inner |
| 176 | + |
| 177 | +# decorator function for timing |
| 178 | +def time(func): |
| 179 | + def inner(*args, **kwargs): |
| 180 | + start = tm.time() |
| 181 | + func(*args, **kwargs) |
| 182 | + logger.info('Function \'{}\' executed {} seconds'.format(func.__name__,round(tm.time()-start,2))) |
| 183 | + return inner |
| 184 | + |
| 185 | +# add more properties to Trace |
| 186 | +Trace.enabled=False # enabled for processing |
| 187 | +Trace.distance=None |
| 188 | +Trace.azimuth=None |
| 189 | + |
0 commit comments