-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils2query.py
314 lines (267 loc) · 11.9 KB
/
utils2query.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
import os
import io
import pandas as pd
from obspy import UTCDateTime
from datetime import timedelta
ROOT_DIR = os.path.dirname(__file__)
pick_codex = os.path.join(ROOT_DIR,"query_picks.txt")
single_pick_codex = os.path.join(ROOT_DIR,"query_single_picks.txt")
event_codex = os.path.join(ROOT_DIR,"query_events.txt")
def get_text2php(from_text,rm_line=None, add_line=None):
"""
Parameters:
from_text: list
List of lines from readlines() method
rm_line: int or None
remove specific line in a text in txt file
add_line: list of tuple (int,str)
In the first place is the index number where you want to add a line.
In the second place is the line of code that you need to add
"""
text = from_text[0] #line 1
text_sketch = from_text[1:]
for index,line in enumerate(text_sketch,2): # 2 because refers to line 2
if rm_line != None:
if rm_line == 1:
raise Exception("Line 1 of text can't be removed.")
if index == rm_line:
pass
else:
text= f'{text}\
{line}'
if add_line != None:
##count lines that will be added.
count = 0
for i in range(len(add_line)):
if index == add_line[i][0]:
count += 1
# if want to add in the last line, first write
# the last line of the original text
if index == len(text_sketch)+count:
text= f'{text}\
{line}'
# Add text that you want to add.
text = f'{text}\
{add_line[i][1]}'
# if it is not the last line add theline of the
# original text
if index != len(text_sketch)+count:
text= f'{text}\
{line}'
else:
text= f'{text}\
{line}'
return text
def get_fulltime(sql,single=False):
df = pd.DataFrame(sql)
df.index+=1
df.index.name= 'No'
if single:
df['time_pick'] = df.apply(lambda x: get_timepick(x,None), axis=1).astype(str)
df = df.drop(columns=['time_ms_pick'])
df[f'time_pick'] = pd.to_datetime(df[f'time_pick'], format='%Y-%m-%dT%H:%M:%S.%f')
else:
df['time_pick_p'] = df.apply(lambda x: get_timepick(x,'p'), axis=1).astype(str)
df['time_pick_s'] = df.apply(lambda x: get_timepick(x,'s'), axis=1).astype(str)
df = df.drop(columns=['time_ms_pick_p','time_ms_pick_s'])
df[f'time_pick_p'] = pd.to_datetime(df[f'time_pick_p'], format='%Y-%m-%dT%H:%M:%S.%f')
df[f'time_pick_s'] = pd.to_datetime(df[f'time_pick_s'], format='%Y-%m-%dT%H:%M:%S.%f')
return df
def get_timepick(df,pick):
if pick == None:
pick = df[f'time_pick'] + \
timedelta(milliseconds=float(df[f'time_ms_pick']/1000))
else:
pick = df[f'time_pick_{pick}'] + \
timedelta(milliseconds=float(df[f'time_ms_pick_{pick}']/1000))
return UTCDateTime(pick)
def str2datetime(mydatetime):
date,hour = mydatetime.split()
year,month,day,hour,minute,sec = date[0:4],date[4:6],date[6:8],hour[0:2],hour[2:4],hour[4:6]
return f"{year}/{month}/{day} {hour}:{minute}:{sec}"
class QueryHelper(object):
def __init__(self,query,initial_date,final_date,
min_mag,max_mag,min_prof,max_prof,
event_type=None,station_list=None,
pick="P"):
"""
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
"""
self.query = query
self.initial_date = str2datetime(initial_date)
self.final_date = str2datetime(final_date)
self.min_mag = min_mag
self.max_mag = max_mag
self.min_prof = min_prof
self.max_prof = max_prof
self.event_type = event_type
self.station_list = station_list
self.__singleP_eventtype_lines = [38] #42 in where
self.__singleP_radialquery_lines = [15,41] #7 in select, 45 in where
self.__singleP_stationlist_lines = [38] #42 in where
self.__singleP_idquery_lines = [38] #40 in where
self.__P_eventtype_lines = [46] #42 in where
self.__P_radialquery_lines = [15,49] #7 in select, 45 in where
self.__P_stationlist_lines = [46] #42 in where
self.__P_idquery_lines = [46] #40 in where
self.__E_eventtype_lines = [23] #42 in where
self.__E_radialquery_lines = [7,27] #7 in select, 26 in where
self.__E_stationlist_lines = [22] #42 in where
self.__E_idquery_lines = [22] #40 in where
if self.query in ("pick","PICK","Pick","picks","Picks"):
query_text = open(pick_codex,"r", encoding="latin-1").readlines()
elif self.query in ("single_pick","single_PICK","single_Pick","single_picks","single_Picks"):
query_text = open(single_pick_codex,"r", encoding="latin-1").readlines()
elif self.query in ("event","Event","EVENT","events","EVENTS"):
self.station_list = None
query_text = open(event_codex,"r", encoding="latin-1").readlines()
pick = None
else:
raise Exception("query= 'pick' or 'Event'")
query_text = get_text2php(query_text)
self.query_text = str(query_text)%(f'{self.min_mag}',f'{self.max_mag}',
f'{self.min_prof}',f'{self.max_prof}',
f'"{self.initial_date}"',
f'"{self.final_date}"')
if pick != None:
self.query_text = self.query_text.replace("left join Arrival A_p on A_p._parent_oid=Origin._oid and A_p.phase_code = 'P'",
f"left join Arrival A_p on A_p._parent_oid=Origin._oid and A_p.phase_code = '{pick}'")
# print(self.query_text)
def __add_event_type(self,event_type):
if len(event_type) == 1:
event_type = f"('{event_type[0]}')"
else:
event_type = str(tuple(event_type))
condition = ("Event.type in %s AND")%(event_type)
if self.query in ("pick","PICK","Pick","picks","Picks"):
lines = self.__P_eventtype_lines
if self.query in ("single_pick","single_PICK","single_Pick","single_picks","single_Picks"):
lines = self.__singleP_eventtype_lines
elif self.query in ("event","Event","EVENT","events","EVENTS"):
lines = self.__E_eventtype_lines
return [(lines[0],condition)]
def __add_radial_query(self,latitude,longitude,radio):
select = "round(( 6371 * acos(cos(radians( %s)) * cos(radians(Origin.latitude_value)) * cos(radians(Origin.longitude_value) - radians(%s)) + sin(radians( %s)) * sin(radians(Origin.latitude_value)))),2) as radio,"
select = select%(f'{latitude}',f'{longitude}',f'{latitude}')
condition = "HAVING radio < %s;"
condition = condition%(radio)
if self.query in ("pick","PICK","Pick","picks","Picks"):
lines = self.__P_radialquery_lines
if self.query in ("single_pick","single_PICK","single_Pick","single_picks","single_Picks"):
lines = self.__singleP_radialquery_lines
elif self.query in ("event","Event","EVENT","events","EVENTS"):
lines = self.__E_radialquery_lines
return [(lines[0],select),(lines[1],condition)]
def __add_station_list(self,station_list):
if len(station_list) == 1:
station_list = f"('{station_list[0]}')"
else:
station_list = str(tuple(station_list))
condition = ("pick_p.waveformID_stationCode in %s AND")%(station_list)
if self.query in ("pick","PICK","Pick","picks","Picks"):
lines = self.__P_stationlist_lines
elif self.query in ("single_pick","single_PICK","single_Pick","single_picks","single_Picks"):
condition = ("pick.waveformID_stationCode in %s AND")%(station_list)
lines = self.__singleP_stationlist_lines
elif self.query in ("event","Event","EVENT","events","EVENTS"):
lines = self.__E_stationlist_lines
return [(lines[0],condition)]
def __add_id_query(self,loc_id):
if len(loc_id) == 1:
loc_id = f"('{loc_id[0]}')"
else:
loc_id = str(tuple(loc_id))
condition = "POEv.PublicID in %s AND"%(loc_id)
if self.query in ("pick","PICK","Pick","picks","Picks"):
lines = self.__P_stationlist_lines
if self.query in ("single_pick","single_PICK","single_Pick","single_picks","single_Picks"):
lines = self.__singleP_stationlist_lines
elif self.query in ("event","Event","EVENT","events","EVENTS"):
lines = self.__E_stationlist_lines
return [(lines[0],condition)]
def simple_query(self):
text = self.query_text
if self.event_type != None:
text = io.StringIO(text).readlines()
event_info = self.__add_event_type(self.event_type)
text = get_text2php(from_text=text,
add_line=event_info)
if self.station_list != None:
text = io.StringIO(text).readlines()
stalist_info = self.__add_station_list(self.station_list)
text = get_text2php(from_text=text,
add_line=stalist_info)
return text
def id_query(self,loc_id):
"""
Parameters:
-----------
ID: str
identification code
results:
--------
text: str
formatted text with ID
"""
text = io.StringIO(self.query_text).readlines()
id_text = self.__add_id_query(loc_id)
text = get_text2php(from_text=text,
add_line=id_text)
if self.event_type != None:
text = io.StringIO(text).readlines()
event_info = self.__add_event_type(self.event_type)
text = get_text2php(from_text=text,
add_line=event_info)
if self.station_list != None:
text = io.StringIO(text).readlines()
stalist_info = self.__add_station_list(self.station_list)
text = get_text2php(from_text=text,
add_line=stalist_info)
return text
def radial_query(self,lat, lon, radio):
"""
Parameters:
-----------
lat: int
latitude
lon: int
longitude
radio: int
radio in km
Results:
--------
text: str
formatted text with ID
"""
text = io.StringIO(self.query_text).readlines()
radial_text = self.__add_radial_query(lat, lon, radio)
text = get_text2php(from_text=text,
add_line=radial_text)
if self.event_type != None:
text = io.StringIO(text).readlines()
event_info = self.__add_event_type(self.event_type)
text = get_text2php(from_text=text,
add_line=event_info)
if self.station_list != None:
text = io.StringIO(text).readlines()
stalist_info = self.__add_station_list(self.station_list)
text = get_text2php(from_text=text,
add_line=stalist_info)
return text