-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.py
354 lines (306 loc) · 13 KB
/
query.py
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
346
347
348
349
350
351
352
353
354
# /**
# * @author Emmanuel Castillo
# * @email [email protected] / [email protected]
# * @create date 2021-07-08 06:55:32
# * @modify date 2021-07-08 06:55:32
# * @desc [description]
# */
import pymysql as MySQLdb
import os
import pandas as pd
import utils2query as utq
SGC_PUBLIC_STATIONS = ['APAC','AGCC','ARGC','ARMEC','BAR2','BBAC','BET','BOG',
'BRJC','CAP2','CCALA','CBETA','CBOC','CHI','CLBC','CLEJA','CPOP2',
'CPRAD','CRJC','CRU','CUM','DBB','EZNC','FLO2','GARC',
'GR1C','GRPC','GUA','GUY2C','HEL','JAMC','LCBC','MACC',
'MAL','MAN1C','MAP','MEDEC','NIZA','NOR','OCA','ORTC','PAL','PAM','PAS2','PDSC','PGA1B','PIZC',
'POP2','PRA','PRV','PTA','PTB','PTGC','PTLC','QUBC',
'RECRC','RNCC','RUS','SAIC','SERC','SJC','SMAR','SOL','SPBC',
'TAM','TUM','TUM3C','URE','URI','URMC','VIL','YOT',
'YPLC','ZAR','VMM05','VMM06','VMM07','VMM08',
'VMM09','VMM10','VMM11','VMM12']
VMM_stations = ['AGCC','EZNC','SNPBC','MORC','OCNC','SML1C','VMM05','VMM06',
'VMM07','VMM08','VMM09','VMM10','VMM11','VMM12','VMM13','BRR',
'LL1C','LL5C','LL6C','LL7C','LL8C','OCA','PAM','BAR2','PTB','ZAR',
'RUS','SPBC','NOR','HEL']
class Query(object):
def __init__(self,MySQLdb_dict,query):
"""
Parameters:
-----------
MySQLdb_dict: dict
MySQLdb_dict= {'host':host, 'user':user, 'passwd':passwd, 'db': db}
query: str
picks or events
"""
self.MySQLdb_dict= MySQLdb_dict
self.query = query
@property
def MySQLdb(self):
db= MySQLdb.connect(host=self.MySQLdb_dict['host'], user=self.MySQLdb_dict['user'],
passwd=self.MySQLdb_dict['passwd'], db=self.MySQLdb_dict['db'])
return db
def simple_SQLquery(self,initial_date, final_date,
min_mag, max_mag, min_prof, max_prof,
event_type=None,station_list=None,
sort = None,merge_picks="inner",to_csv=None):
"""
Parameters:
-----------
initial_date: str
initial date in the next format : YYYYMMDD HHMMSS
final_date: str
final date in the next format : YYYYMMDD HHMMSS
min_mag: int
minimum magnitude
max_mag: int
maximum magnitude
min_prof: int
minimum depth
max_prof
maximum depth
event_type: list
"earthquake" or "not locatable" etc
station_list: list
Only select stations located in station_list
to_csv: str
path
"""
self.info = f'initial_date={initial_date},final_date={final_date},'+\
f'min_mag={min_mag},max_mag={max_mag},'+\
f'min_prof={min_prof},max_prof={max_prof},'+\
f'event_type={event_type},station_list={station_list}'
if station_list == "sgc_public":
station_list = SGC_PUBLIC_STATIONS
if self.query in ("event","Event","EVENT","events","EVENTS"):
query = utq.QueryHelper(self.query,initial_date, final_date,
min_mag, max_mag, min_prof, max_prof,
event_type,station_list)
codex = query.simple_query()
df = pd.read_sql_query(codex,self.MySQLdb)
else:
if merge_picks == "inner":
query = utq.QueryHelper(self.query,initial_date, final_date,
min_mag, max_mag, min_prof, max_prof,
event_type,station_list)
codex = query.simple_query()
simple_query = pd.read_sql_query(codex,self.MySQLdb)
df = utq.get_fulltime(simple_query)
else:
dfs = {}
for phase in ['P','S']:
query = utq.QueryHelper("single_picks",initial_date, final_date,
min_mag, max_mag, min_prof, max_prof,
event_type,station_list,phase)
codex = query.simple_query()
simple_query = pd.read_sql_query(codex,self.MySQLdb)
df = utq.get_fulltime(simple_query,True)
# df.rename(columns={ 'time_pick':f'time_pick_{phase.lower()}',
# 'time_ms_pick':f'time_ms_pick_{phase.lower()}',
# 'pick':f'pick_{phase.lower()}'}, inplace=True)
# df.to_csv(f"/home/ecastillo/tesis/catalog/manual/events/{phase}.csv")
dfs[phase] = df
# dfs.append(df)
df = pd.merge(dfs["P"],dfs["S"],on=['agency','id','time_event','latitude','latitude_uncertainty',
'longitude','longitude_uncertainty','depth','depth_uncertainty','rms','region','earth_model',
'method','event_type','magnitude','magnitude_type','picker','network','station','location'],how='left',suffixes=("_p", "_s"))
# df.to_csv("")
if sort != None:
df = df.sort_values(by=sort,ascending=True,ignore_index=True)
if to_csv != None:
if os.path.isdir(os.path.dirname(os.path.realpath(to_csv))):
pass
else:
os.makedirs(os.path.dirname(os.path.realpath(to_csv)))
with open(to_csv,'w') as csv:
csv.write(f'#{self.info}\n')
df.to_csv(to_csv, mode='a')
print(f"\nCSV output: {to_csv}")
return df
def id_SQLquery(self,loc_id, initial_date, final_date,
min_mag, max_mag, min_prof, max_prof,
event_type=None,station_list=None,
sort = None,to_csv=None):
"""
Parameters:
-----------
loc_id: list
list of ids
initial_date: str
initial date in the next format : YYYYMMDD HHMMSS
final_date: str
final date in the next format : YYYYMMDD HHMMSS
min_mag: int
minimum magnitude
max_mag: int
maximum magnitude
min_prof: int
minimum depth
max_prof
maximum depth
event_type: list
"earthquake" or "not locatable" etc
station_list: list
Only select stations located in station_list
to_csv: str
path
"""
self.info = f'ID={loc_id}'+\
f'initial_date={initial_date},final_date={final_date},'+\
f'min_mag={min_mag},max_mag={max_mag},'+\
f'min_prof={min_prof},max_prof={max_prof},'+\
f'event_type={event_type},station_list={station_list}'
if station_list == "sgc_public":
station_list = SGC_PUBLIC_STATIONS
query = utq.QueryHelper(self.query,initial_date, final_date,
min_mag, max_mag, min_prof, max_prof,
event_type,station_list)
codex = query.id_query(loc_id)
id_query = pd.read_sql_query(codex,self.MySQLdb)
if self.query in ("pick","PICK","Pick","picks","Picks"):
df = utq.get_fulltime(id_query)
elif self.query in ("event","Event","EVENT","events","EVENTS"):
df = id_query
if sort != None:
df = df.sort_values(by=sort,ascending=True)
if to_csv != None:
if os.path.isdir(os.path.dirname(os.path.realpath(to_csv))):
pass
else:
os.makedirs(os.path.dirname(os.path.realpath(to_csv)))
with open(to_csv,'w') as csv:
csv.write(f'#{self.info}\n')
df.to_csv(to_csv, mode='a')
print(f"\nCSV output: {to_csv}")
return df
def radial_SQLquery(self,lat, lon, ratio, initial_date, final_date,
min_mag, max_mag, min_prof, max_prof,
event_type=None,station_list=None,
sort = None,to_csv=None):
"""
Parameters:
-----------
lat: float
latitude
lon: float
longitude
ratio: float
ratio
initial_date: str
initial date in the next format : YYYYMMDD HHMMSS
final_date: str
final date in the next format : YYYYMMDD HHMMSS
min_mag: int
minimum magnitude
max_mag: int
maximum magnitude
min_prof: int
minimum depth
max_prof
maximum depth
event_type: list
"earthquake" or "not locatable" etc
station_list: list
Only select stations located in station_list
to_csv: str
path
"""
self.info = f'lat={lat},lon={lon},ratio={ratio},'+\
f'initial_date={initial_date},final_date={final_date},'+\
f'min_mag={min_mag},max_mag={max_mag},'+\
f'min_prof={min_prof},max_prof={max_prof},'+\
f'event_type={event_type},station_list={station_list}'
if station_list == "sgc_public":
station_list = SGC_PUBLIC_STATIONS
query = utq.QueryHelper(self.query,initial_date, final_date,
min_mag, max_mag, min_prof, max_prof,
event_type,station_list)
codex = query.radial_query(lat, lon, ratio)
radial_query = pd.read_sql_query(codex,self.MySQLdb)
if self.query in ("pick","PICK","Pick","picks","Picks"):
df = utq.get_fulltime(radial_query)
elif self.query in ("event","Event","EVENT","events","EVENTS"):
df = radial_query
if sort != None:
df = df.sort_values(by=sort,ascending=True)
if to_csv != None:
if os.path.isdir(os.path.dirname(os.path.realpath(to_csv))):
pass
else:
os.makedirs(os.path.dirname(os.path.realpath(to_csv)))
with open(to_csv,'w') as csv:
csv.write(f'#{self.info}\n')
df.to_csv(to_csv, mode='a')
print(f"\nCSV output: {to_csv}")
return df
if __name__ == "__main__":
# nido de los santos
# 6.6 a 7.3
# -72.7 a -73.4
# 6.81 y -73.1 radio 0.5°-> 60km
# 5.2 y -73.7 radio 0.5°-> 60km
## GLOBAL VARIBALES
picks =True
events = False
start = "20191201 000000"
# end = "20200901 000000"
end = "20191202 000000"
output_path = "/home/ecastillo/tesis/catalog/manual/events/"
agency = "RSNCmanual"
lat = 6.81
lon = -73.17
ratio = 120
min_mag = -0.2
max_mag = 10
min_prof = -5
max_prof = 260
# ## GLOBAL VARIBALES
# picks = True
# events = False
# start = "20180101 000000"
# end = "20190101 000000"
# output_path = "/home/ecastillo/tesis/manual_picks"
# agency = "SGC"
#### only for events
# lat = 3.46
# lon = -74.18
# ratio = 30
# min_mag = 2
# max_mag = 3
# min_prof = 0
# max_prof = 10
## phpmyadmin credentials
host = "10.100.100.232"
port_fdsn = "8091"
user="consulta"
passwd="consulta"
db="seiscomp3"
MySQLdb_dict= {'host':host, 'user':user, 'passwd':passwd, 'db': db}
client_dict= {'ip_fdsn':f"http://{host}", 'port_fdsn':port_fdsn}
_startname, _endname = start.replace(" ",""),end.replace(" ","")
if events == True:
name = f"{agency}_events_{_startname}_{_endname}.csv"
csv_path = os.path.join(output_path,name)
events = Query(MySQLdb_dict,"events").radial_SQLquery(lat,lon,ratio,
start, end,
min_mag, max_mag,
min_prof, max_prof,
"earthquake", "sgc_public",
['time_event'],
csv_path)
print(events)
# (self,lat, lon, ratio, initial_date, final_date,
# min_mag, max_mag, min_prof, max_prof,
# event_type=None,station_list=None,
# sort = None,to_csv=None):
if picks == True:
name = f"{agency}_picks_{_startname}_{_endname}.csv"
csv_path = os.path.join(output_path,name)
picks = Query(MySQLdb_dict,"picks").simple_SQLquery(
start, end,
min_mag, max_mag,
min_prof, max_prof,
None, SGC_PUBLIC_STATIONS,
['time_event'],"left",
csv_path)
print(picks)