-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
708 lines (562 loc) · 31.9 KB
/
main.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
from PyQt4 import QtCore, QtGui, QtWebKit, QtNetwork
import qdarkstyle
import pyqtgraph as pg
from obspy.clients.fdsn.client import Client
from obspy.core import UTCDateTime
from obspy.geodetics import degrees2kilometers
import sys
import pandas as pd
import numpy as np
from DateAxisItem import DateAxisItem
import math
from glob import iglob
import imp
import inspect
import os
import time
def compile_and_import_ui_files():
"""
Automatically compiles all .ui files found in the same directory as the
application py file.
They will have the same name as the .ui files just with a .py extension.
Needs to be defined in the same file as function loading the gui as it
modifies the globals to be able to automatically import the created py-ui
files. Its just very convenient.
"""
directory = os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe())))
for filename in iglob(os.path.join(directory, '*.ui')):
ui_file = filename
py_ui_file = os.path.splitext(ui_file)[0] + os.path.extsep + 'py'
if not os.path.exists(py_ui_file) or \
(os.path.getmtime(ui_file) >= os.path.getmtime(py_ui_file)):
from PyQt4 import uic
print("Compiling ui file: %s" % ui_file)
with open(py_ui_file, 'w') as open_file:
uic.compileUi(ui_file, open_file)
# Import the (compiled) file.
try:
import_name = os.path.splitext(os.path.basename(py_ui_file))[0]
globals()[import_name] = imp.load_source(import_name, py_ui_file)
except ImportError as e:
print("Error importing %s" % py_ui_file)
print(e.message)
class PandasModel(QtCore.QAbstractTableModel):
"""
Class to populate a table view with a pandas dataframe
"""
def __init__(self, data, isc_nm=None, oth_nm=None, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self._data = np.array(data.values)
self._cols = data.columns
self.r, self.c = np.shape(self._data)
# Column headers for tables
self.isc_col_header = ['isc_ind', 'Event ID', 'qtime', 'Lat (dd)', 'Lon (dd)', 'Depth (km)', 'Mag']
self.oth_col_header = ['isc_ind', 'Event ID', 'qtime', 'Lat (dd)', 'Lon (dd)', 'Depth (km)', 'Mag']
self.matched_col_header = ['oth_ind', 'Event ID', 'qtime', 'Lat (dd)', 'Lon (dd)', 'Depth (km)', 'Mag',
'isc_ind', 'Event ID Match', 'qtime_match', 'Lat Match (dd)', 'Lon Match (dd)',
'Depth Match (km)', 'Mag Match', 'Time Diff (s)', 'Distance Diff (km)',
'Depth Diff (km)', 'Mag Diff']
self.isc_nm = isc_nm
self.oth_nm = oth_nm
self.matched_color = QtGui.QColor(0, 0, 0)
self.matched_color.setNamedColor('#008000')
self.matched_color.setAlpha(100)
self.isc_nm_color = QtGui.QColor(0, 0, 0)
self.isc_nm_color.setNamedColor('#4169E1')
self.isc_nm_color.setAlpha(100)
self.oth_nm_color = QtGui.QColor(0, 0, 0)
self.oth_nm_color.setNamedColor('#FFA500')
self.oth_nm_color.setAlpha(100)
def rowCount(self, parent=None):
return self.r
def columnCount(self, parent=None):
return self.c
def data(self, index, role=QtCore.Qt.DisplayRole):
if index.isValid():
if role == QtCore.Qt.DisplayRole:
return self._data[index.row(), index.column()]
if role == QtCore.Qt.BackgroundRole:
if not self.isc_nm == None:
bool_in = index.row() in self.isc_nm
if bool_in:
return QtCore.QVariant(QtGui.QBrush(self.isc_nm_color))
elif not bool_in:
return QtCore.QVariant(QtGui.QBrush(self.matched_color))
if not self.oth_nm == None:
bool_in = index.row() in self.oth_nm
if bool_in:
return QtCore.QVariant(QtGui.QBrush(self.oth_nm_color))
elif not bool_in:
return QtCore.QVariant(QtGui.QBrush(self.matched_color))
if self.isc_nm == None and self.oth_nm == None:
return QtCore.QVariant(QtGui.QBrush(self.matched_color))
return None
def headerData(self, p_int, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation == QtCore.Qt.Horizontal:
if not self.isc_nm == None:
return self.isc_col_header[p_int]
elif not self.oth_nm == None:
return self.oth_col_header[p_int]
elif self.isc_nm == None and self.oth_nm == None:
return self.matched_col_header[p_int]
elif orientation == QtCore.Qt.Vertical:
return p_int
return None
class TableDialog(QtGui.QDialog):
"""
Class to create a separate child window to display the isc, local and matched Pandas arrays as 3 tables
"""
def __init__(self, parent=None, isc_df=None, oth_df=None, matched_df=None, isc_nm=None, oth_nm=None):
super(TableDialog, self).__init__(parent)
self.isc_df = isc_df
self.oth_df = oth_df
self.matched_df = matched_df
self.isc_nm = isc_nm
self.oth_nm = oth_nm
self.initUI()
def initUI(self):
self.layout = QtGui.QVBoxLayout(self)
self.isc_event_table_view = QtGui.QTableView()
self.oth_event_table_view = QtGui.QTableView()
self.matched_event_table_view = QtGui.QTableView()
self.isc_event_table_view.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self.oth_event_table_view.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self.matched_event_table_view.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
self.layout.addWidget(self.isc_event_table_view)
self.layout.addWidget(self.oth_event_table_view)
self.layout.addWidget(self.matched_event_table_view)
self.setLayout(self.layout)
self.isc_model = PandasModel(self.isc_df, isc_nm=self.isc_nm)
self.oth_model = PandasModel(self.oth_df, oth_nm=self.oth_nm)
self.matched_model = PandasModel(self.matched_df)
self.isc_event_table_view.setModel(self.isc_model)
self.oth_event_table_view.setModel(self.oth_model)
self.matched_event_table_view.setModel(self.matched_model)
self.setWindowTitle('Tables')
self.show()
class TaskThread(QtCore.QThread):
taskFinished = QtCore.pyqtSignal()
def run(self):
time.sleep(3)
self.taskFinished.emit()
class SelectionDialog(QtGui.QDialog):
"""
Pop-up window to select the desired earthquake catalogues and start time/end time for comparison
"""
def __init__(self, parent=None):
super(SelectionDialog, self).__init__(parent)
# Injected by the compile_and_import_ui_files() function.
self.selui = select_cat_time.Ui_SelectionDialog()
self.selui.setupUi(self)
self.selui.int_cat_input.clearFocus()
self.selui.starttime.setFocus()
def getValues(self):
int_cat_return = str(self.selui.int_cat_input.text())
oth_cat_return = str(self.selui.oth_cat_input.text())
# Return the placeholder text as default if nothing is set
if int_cat_return == '':
int_cat_return = str(self.selui.int_cat_input.placeholderText())
if oth_cat_return == '':
oth_cat_return = str(self.selui.oth_cat_input.placeholderText())
return (int_cat_return, oth_cat_return,
UTCDateTime(self.selui.starttime.dateTime().toPyDateTime()),
UTCDateTime(self.selui.endtime.dateTime().toPyDateTime()))
class MainWindow(QtGui.QWidget):
"""
Main Window for compare_catalogues GUI
"""
def __init__(self):
super(MainWindow, self).__init__()
self.setupUi()
self.show()
self.raise_()
# Open the selection dialog to select earthquake catalogue server and start time/end time
sel_dlg = SelectionDialog(parent=self)
if sel_dlg.exec_():
self.sel_dlg_ret = sel_dlg.getValues()
self.get_catalogues()
QtGui.QApplication.instance().focusChanged.connect(self.changed_widget_focus)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
def setupUi(self):
vbox = QtGui.QVBoxLayout()
self.setLayout(vbox)
hbox = QtGui.QHBoxLayout()
self.compare_catalogues_button = QtGui.QPushButton('Compare Catalogues!')
self.compare_catalogues_button.released.connect(self.compare_catalogues)
hbox.addWidget(self.compare_catalogues_button)
self.icon_size_by_depth_button = QtGui.QPushButton('Icon Size by Depth')
self.icon_size_by_depth_button.released.connect(self.icon_size_by_depth)
self.icon_size_by_depth_button.setEnabled(False)
hbox.addWidget(self.icon_size_by_depth_button)
self.icon_size_by_mag_button = QtGui.QPushButton('Icon Size by Mag')
self.icon_size_by_mag_button.released.connect(self.icon_size_by_mag)
self.icon_size_by_mag_button.setEnabled(False)
hbox.addWidget(self.icon_size_by_mag_button)
self.icon_size_reset_button = QtGui.QPushButton('Icon Size Reset')
self.icon_size_reset_button.released.connect(self.icon_size_reset)
self.icon_size_reset_button.setEnabled(False)
hbox.addWidget(self.icon_size_reset_button)
vbox.addLayout(hbox)
web_view = self.web_view = QtWebKit.QWebView()
web_view.page().mainFrame().addToJavaScriptWindowObject("MainWindow", self)
web_view.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
web_view.load(QtCore.QUrl('map.html'))
web_view.loadFinished.connect(self.onLoadFinished)
web_view.linkClicked.connect(QtGui.QDesktopServices.openUrl)
vbox.addWidget(web_view)
self.graph_view = pg.GraphicsLayoutWidget()
vbox.addWidget(self.graph_view)
def onLoadFinished(self):
with open('map.js', 'r') as f:
frame = self.web_view.page().mainFrame()
frame.evaluateJavaScript(f.read())
def changed_widget_focus(self):
# deselect the highlighted point in the scatter graphs
# if this is not done then the event will be continuously highlighted in the map view
# even if another event is clicked on via the map view
try:
if not QtGui.QApplication.focusWidget() == self.graph_view:
self.scatter_point_deselect()
except AttributeError:
pass
def get_catalogues(self):
isc_catalogue = Client(self.sel_dlg_ret[0])
oth_catalogue = Client(self.sel_dlg_ret[1])
t_start = self.sel_dlg_ret[2]
t_end = self.sel_dlg_ret[3]
print('\nRequesting Earthquake Catalogues from Remote Servers.....')
self.isc_cat = isc_catalogue.get_events(starttime=t_start, endtime=t_end)
self.oth_cat = oth_catalogue.get_events(starttime=t_start, endtime=t_end)
# create empty data frame
self.isc_df = pd.DataFrame(data=None, columns=['isc_ind', 'event_id', 'qtime', 'lat', 'lon', 'depth', 'mag'])
self.oth_df = pd.DataFrame(data=None, columns=['oth_ind', 'event_id', 'qtime', 'lat', 'lon', 'depth', 'mag'])
# iterate through the events in oth cat
for _i, event in enumerate(self.oth_cat):
print "\r Parsing event from Local Cat", _i + 1, ' of ', len(self.oth_cat), ' ....',
sys.stdout.flush()
# Get quake origin info
origin_info = event.preferred_origin() or event.origins[0]
try:
mag_info = event.preferred_magnitude() or event.magnitudes[0]
magnitude = mag_info.mag
except IndexError:
# No magnitude for event
magnitude = None
self.oth_df.loc[_i] = [int(_i), str(event.resource_id.id), int(origin_info.time.timestamp),
origin_info.latitude, origin_info.longitude,
origin_info.depth, magnitude]
# Convert the depth field to Km from m
self.oth_df.loc[:, 'depth'] *= (1.0 / 1000)
print('\n')
# iterate through the events in isc cat
for _i, event in enumerate(self.isc_cat):
print "\r Parsing event from ISC Cat", _i + 1, ' of ', len(self.isc_cat), ' ....',
sys.stdout.flush()
# Get quake origin info
origin_info = event.preferred_origin() or event.origins[0]
try:
mag_info = event.preferred_magnitude() or event.magnitudes[0]
magnitude = mag_info.mag
except IndexError:
# No magnitude for event
magnitude = None
self.isc_df.loc[_i] = [int(_i), str(event.resource_id.id), int(origin_info.time.timestamp),
origin_info.latitude, origin_info.longitude,
origin_info.depth, magnitude]
# Convert the depth field to Km from m
self.isc_df.loc[:, 'depth'] *= (1.0 / 1000)
# =====================Finding matching events =======================
print('\nFinding Matching Events.....')
progressDialog = QtGui.QProgressDialog("Finding Matching Events",
"Cancel", 0, len(self.oth_df))
global match_index
global length_oth_df
match_index = 0
length_oth_df = len(self.oth_df)
def get_isc_match(row):
global match_index
global length_oth_df
progressDialog.setValue(match_index)
print "\r Matching event from Local Cat", match_index, ' of ', length_oth_df, ' ....',
sys.stdout.flush()
temp = self.isc_df_drop.apply(lambda x: abs(x - row), axis=1) # Pandas DF
# NaNs are treated as small
smallest_temp = temp.nsmallest(2, columns=['lat', 'lon', 'qtime']).iloc[0] # Pandas Series
distance_diff = degrees2kilometers(math.sqrt(abs(smallest_temp['lat']) ** 2 +
abs(smallest_temp['lon']) ** 2))
isc_index = smallest_temp.name
if smallest_temp['qtime'] <= 15 and \
(abs(smallest_temp['lon']) <= 1 or np.isnan(smallest_temp['lon'])) and \
(abs(smallest_temp['lat']) <= 1 or np.isnan(smallest_temp['lat'])):
ret_s = pd.Series([isc_index, self.isc_df.loc[isc_index, 'event_id'],
self.isc_df.loc[isc_index, 'qtime'], self.isc_df.loc[isc_index, 'lat'],
self.isc_df.loc[isc_index, 'lon'],
self.isc_df.loc[isc_index, 'depth'], self.isc_df.loc[isc_index, 'mag'],
smallest_temp['qtime'], distance_diff, smallest_temp['depth'], smallest_temp['mag']],
index=['isc_ind', 'event_id_match', 'qtime_match', 'lat_match', 'lon_match',
'depth_match', 'mag_match', 'qtime_diff', 'dist_diff', 'depth_diff',
'mag_diff'])
else:
ret_s = pd.Series([None, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
index=['isc_ind', 'event_id_match', 'qtime_match', 'lat_match', 'lon_match',
'depth_match', 'mag_match', 'qtime_diff', 'dist_diff', 'depth_diff',
'mag_diff'])
match_index += 1
return ret_s
# Drop the event_id column (strings) from the data frame to apply vectorised function
self.oth_df_drop = self.oth_df.drop('event_id', axis=1)
self.isc_df_drop = self.isc_df.drop('event_id', axis=1)
self.matched_df = pd.concat((self.oth_df, self.oth_df_drop.apply(get_isc_match, axis=1)), axis=1)
# drop a row from the matched df if isc_ind in matched df is NaN
# (I.e. there was no matching earthquake in isc cat)
self.matched_df.dropna(subset=['isc_ind'], inplace=True)
self.matched_df.reset_index(drop=True, inplace=True)
# find isc events not matched and oth events not matched
self.isc_not_matched_df = self.isc_df[~self.isc_df['isc_ind'].isin(self.matched_df['isc_ind'])]
self.oth_not_matched_df = self.oth_df[~self.oth_df['oth_ind'].isin(self.matched_df['oth_ind'])]
def compare_catalogues(self):
self.compare_catalogues_button.setEnabled(False)
self.icon_size_by_depth_button.setEnabled(True)
self.icon_size_by_mag_button.setEnabled(True)
self.icon_size_reset_button.setEnabled(True)
# Plot the matched events
for row_index, row in self.matched_df.iterrows():
js_call = "addEvent('{event_id}', '{df_id}', {row_index}, " \
"{latitude}, {longitude}, '{a_color}', '{p_color}');" \
.format(event_id=row['event_id'], df_id="matched", row_index=int(row_index), latitude=row['lat'],
longitude=row['lon'], a_color="Red",
p_color="#008000")
self.web_view.page().mainFrame().evaluateJavaScript(js_call)
# Plot ISC events (not matched)
for row_index, row in self.isc_not_matched_df.iterrows():
js_call = "addEvent('{event_id}', '{df_id}', {row_index}, " \
"{latitude}, {longitude}, '{a_color}', '{p_color}');" \
.format(event_id=row['event_id'], df_id="isc", row_index=int(row_index), latitude=row['lat'],
longitude=row['lon'], a_color="Red",
p_color="#4169E1")
self.web_view.page().mainFrame().evaluateJavaScript(js_call)
# Plot oth events (not matched)
for row_index, row in self.oth_not_matched_df.iterrows():
js_call = "addEvent('{event_id}', '{df_id}', {row_index}, " \
"{latitude}, {longitude}, '{a_color}', '{p_color}');" \
.format(event_id=row['event_id'], df_id="oth", row_index=int(row_index), latitude=row['lat'],
longitude=row['lon'], a_color="Red",
p_color="#FFA500")
self.web_view.page().mainFrame().evaluateJavaScript(js_call)
js_call = "createOverlay();"
self.web_view.page().mainFrame().evaluateJavaScript(js_call)
self.table_accessor = None
isc_nm, oth_nm = self.table_view_create_color()
self.tbld = TableDialog(parent=self, isc_df=self.isc_df, oth_df=self.oth_df,
matched_df=self.matched_df, isc_nm=isc_nm, oth_nm=oth_nm)
# Lookup Dictionary for table views
self.tbl_view_dict = {"isc": self.tbld.isc_event_table_view,
"oth": self.tbld.oth_event_table_view,
"matched": self.tbld.matched_event_table_view}
# Create a new table_accessor dictionary for this class
self.table_accessor = {self.tbld.isc_event_table_view: [self.isc_df, range(0, len(self.isc_df))],
self.tbld.oth_event_table_view: [self.oth_df, range(0, len(self.oth_df))],
self.tbld.matched_event_table_view: [self.matched_df, range(0, len(self.matched_df))]}
self.tbld.isc_event_table_view.clicked.connect(self.table_view_clicked)
self.tbld.oth_event_table_view.clicked.connect(self.table_view_clicked)
self.tbld.matched_event_table_view.clicked.connect(self.table_view_clicked)
self.tbld.isc_event_table_view.horizontalHeader().sectionClicked.connect(self.table_view_headerclicked)
self.tbld.oth_event_table_view.horizontalHeader().sectionClicked.connect(self.table_view_headerclicked)
self.tbld.matched_event_table_view.horizontalHeader().sectionClicked.connect(self.table_view_headerclicked)
# Double click and zoom is making markers disappear when clicking on them
# self.tbld.isc_event_table_view.doubleClicked.connect(self.table_view_dblclicked)
# self.tbld.oth_event_table_view.doubleClicked.connect(self.table_view_dblclicked)
# self.tbld.matched_event_table_view.doubleClicked.connect(self.table_view_dblclicked)
self.scatter_build_graph()
def icon_size_by_depth(self):
# Change the sizes of the icons in map view to represent depth difference between matched events
depth_norm_series = self.matched_df.loc[:, 'depth_diff'] \
.apply(lambda x: (x / self.matched_df.loc[:, 'depth_diff'].max()))
depth_size_list = (depth_norm_series + 0.3).multiply(18, fill_value=0.1).tolist()
js_call = "arrange_marker_by_depth({sizes});" \
.format(sizes=depth_size_list)
self.web_view.page().mainFrame().evaluateJavaScript(js_call)
def icon_size_by_mag(self):
# Change the sizes of the icons in map view to represent magnitude difference between matched events
mag_norm_series = self.matched_df.loc[:, 'mag_diff'] \
.apply(lambda x: (x / self.matched_df.loc[:, 'mag_diff'].max()))
mag_size_list = (mag_norm_series + 0.3).multiply(18, fill_value=0.1).tolist()
js_call = "arrange_marker_by_depth({sizes});" \
.format(sizes=mag_size_list)
self.web_view.page().mainFrame().evaluateJavaScript(js_call)
def icon_size_reset(self):
js_call = "resetMarkerSize();"
self.web_view.page().mainFrame().evaluateJavaScript(js_call)
js_call = "setAllInactive();"
self.web_view.page().mainFrame().evaluateJavaScript(js_call)
def table_view_highlight(self, focus_widget, row_index):
if focus_widget == self.tbld.matched_event_table_view:
selected_row = self.matched_df.loc[row_index]
# get the index of the the ISC and oth matched quake
isc_index = selected_row['isc_ind']
oth_index = selected_row['oth_ind']
# Find the row_numbers of these two indexes
matched_row_number = self.table_accessor[self.tbld.matched_event_table_view][1].index(row_index)
isc_row_number = self.table_accessor[self.tbld.isc_event_table_view][1].index(isc_index)
oth_row_number = self.table_accessor[self.tbld.oth_event_table_view][1].index(oth_index)
# Highlight/Select the rows in the table
self.tbld.matched_event_table_view.selectRow(matched_row_number)
self.tbld.isc_event_table_view.selectRow(isc_row_number)
self.tbld.oth_event_table_view.selectRow(oth_row_number)
# Highlight the marker on the map
js_call = "highlightEvent('{event_id}');".format(event_id=selected_row['event_id'])
self.web_view.page().mainFrame().evaluateJavaScript(js_call)
elif focus_widget == self.tbld.isc_event_table_view:
self.tbld.oth_event_table_view.clearSelection()
self.tbld.matched_event_table_view.clearSelection()
selected_row = self.isc_df.loc[row_index]
# Find the row_number of this index
isc_row_number = self.table_accessor[focus_widget][1].index(row_index)
focus_widget.selectRow(isc_row_number)
# Highlight the marker on the map
js_call = "highlightEvent('{event_id}');".format(event_id=selected_row['event_id'])
self.web_view.page().mainFrame().evaluateJavaScript(js_call)
elif focus_widget == self.tbld.oth_event_table_view:
self.tbld.isc_event_table_view.clearSelection()
self.tbld.matched_event_table_view.clearSelection()
selected_row = self.oth_df.loc[row_index]
# Find the row_number of this index
oth_row_number = self.table_accessor[focus_widget][1].index(row_index)
focus_widget.selectRow(oth_row_number)
# Highlight the marker on the map
js_call = "highlightEvent('{event_id}');".format(event_id=selected_row['event_id'])
self.web_view.page().mainFrame().evaluateJavaScript(js_call)
def table_view_create_color(self):
# Find the row number in the table_view corresponding to events that are matched,
# not_matched (local cat), not matched (international cat)
find = lambda searchList, elem: [[i for i, x in enumerate(searchList) if x == e][0] for e in elem]
# The first time initializing the table
if self.table_accessor == None:
if not self.oth_not_matched_df.empty:
# first unmatched events in local catalogue
oth_not_matched_rn_list = self.oth_not_matched_df.loc[:, 'oth_ind'].tolist()
else:
oth_not_matched_rn_list = None
if not self.isc_not_matched_df.empty:
# now unmatched events in local catalogue
isc_not_matched_rn_list = self.isc_not_matched_df.loc[:, 'isc_ind'].tolist()
else:
isc_not_matched_rn_list = None
else:
if not self.oth_not_matched_df.empty:
# first unmatched events in local catalogue
oth_not_matched_rn_list = find(self.table_accessor[self.tbld.oth_event_table_view][1],
self.oth_not_matched_df.loc[:, 'oth_ind'].tolist())
else:
oth_not_matched_rn_list = None
if not self.isc_not_matched_df.empty:
# now unmatched events in local catalogue
isc_not_matched_rn_list = find(self.table_accessor[self.tbld.isc_event_table_view][1],
self.isc_not_matched_df.loc[:, 'isc_ind'].tolist())
else:
isc_not_matched_rn_list = None
return (isc_not_matched_rn_list, oth_not_matched_rn_list)
def table_view_headerclicked(self, logicalIndex):
focus_widget = QtGui.QApplication.focusWidget()
table_df = self.table_accessor[focus_widget][0]
header = focus_widget.horizontalHeader()
self.order = header.sortIndicatorOrder()
table_df.sort_values(by=table_df.columns[logicalIndex],
ascending=self.order, inplace=True)
self.table_accessor[focus_widget][1] = table_df.index.tolist()
isc_nm, oth_nm = self.table_view_create_color()
if focus_widget == self.tbld.isc_event_table_view:
self.model = PandasModel(table_df, isc_nm=isc_nm)
elif focus_widget == self.tbld.oth_event_table_view:
self.model = PandasModel(table_df, oth_nm=oth_nm)
else:
self.model = PandasModel(table_df)
focus_widget.setModel(self.model)
focus_widget.update()
def table_view_dblclicked(self):
self.table_view_clicked()
self.panMap(self.selected_row['lon'], self.selected_row['lat'])
def table_view_clicked(self):
focus_widget = QtGui.QApplication.focusWidget()
row_number = focus_widget.selectionModel().selectedRows()[0].row()
row_index = self.table_accessor[focus_widget][1][row_number]
# Highlight/Select the current row in the table
self.table_view_highlight(focus_widget, row_index)
def scatter_build_graph(self):
# Plot the Magnitude Difference of matched events, Depth Difference of matched events and the
# Unmatched events as scatter plots
self.graph_view.clear()
# Set the colors of the scatter points
matched_col = pg.mkColor('#008000')
unmatched_col = pg.mkColor('#FFA500')
# Drop the rows with NaN values in the specified columns (i.e. the international catalogue did not have
# magtnitudes and/or depths)
matched_df_drop_mdna = self.matched_df.dropna(subset=['mag_match', 'depth_match'], inplace=False)
plot1 = self.graph_view.addPlot(0, 0, title="Magnitude Difference",
axisItems={'bottom': DateAxisItem(orientation='bottom',
utcOffset=0)})
plot2 = self.graph_view.addPlot(0, 1, title="Depth Difference",
axisItems={'bottom': DateAxisItem(orientation='bottom',
utcOffset=0)})
plot3 = self.graph_view.addPlot(0, 2, title="Magnitude of Unmatched Events",
axisItems={'bottom': DateAxisItem(orientation='bottom',
utcOffset=0)})
self.lastClicked = []
self.mag_diff_scatter_plot = pg.ScatterPlotItem(pxMode=True)
self.mag_diff_scatter_plot.sigClicked.connect(self.scatter_point_clicked)
self.mag_diff_scatter_plot.addPoints(matched_df_drop_mdna['qtime'], matched_df_drop_mdna['mag_diff'], size=9,
brush=matched_col)
plot1.addItem(self.mag_diff_scatter_plot)
self.depth_diff_scatter_plot = pg.ScatterPlotItem(pxMode=True)
self.depth_diff_scatter_plot.sigClicked.connect(self.scatter_point_clicked)
self.depth_diff_scatter_plot.addPoints(matched_df_drop_mdna['qtime'], matched_df_drop_mdna['depth_diff'],
size=9, brush=matched_col)
plot2.addItem(self.depth_diff_scatter_plot)
self.unmatched_mag_scatter_plot = pg.ScatterPlotItem(pxMode=True)
self.unmatched_mag_scatter_plot.sigClicked.connect(self.scatter_point_clicked)
self.unmatched_mag_scatter_plot.addPoints(self.oth_not_matched_df['qtime'], self.oth_not_matched_df['mag'],
size=9, brush=unmatched_col)
plot3.addItem(self.unmatched_mag_scatter_plot)
def scatter_point_deselect(self):
try:
for p in self.lastClicked:
p.resetPen()
except AttributeError:
pass
def scatter_point_clicked(self, plot, points):
for p in self.lastClicked:
p.resetPen()
for p in points:
p.setPen('r', width=2)
self.lastClicked = points
# Highlight the event on the map view and table view when scatter point is clicked
if plot == self.mag_diff_scatter_plot:
select_row = self.matched_df.loc[self.matched_df['qtime'] == points[0].pos()[0]]
self.table_view_highlight(self.tbld.matched_event_table_view, select_row.index.tolist()[0])
elif plot == self.depth_diff_scatter_plot:
select_row = self.matched_df.loc[self.matched_df['qtime'] == points[0].pos()[0]]
self.table_view_highlight(self.tbld.matched_event_table_view, select_row.index.tolist()[0])
elif plot == self.unmatched_mag_scatter_plot:
select_row = self.oth_not_matched_df.loc[self.oth_not_matched_df['qtime'] == points[0].pos()[0]]
self.table_view_highlight(self.tbld.oth_event_table_view, select_row.index.tolist()[0])
def panMap(self, lng, lat):
# Pan to the double cliked event (from the table child window)
self.web_view.page().mainFrame().evaluateJavaScript('map.panTo(L.latLng({}, {}));'.format(lat, lng))
self.web_view.page().mainFrame().evaluateJavaScript('map.setZoom({});'.format(10))
@QtCore.pyqtSlot(float, float, str, str, int)
def onMap_marker_selected(self, lat, lng, event_id, df_id, row_index):
self.table_view_highlight(self.tbl_view_dict[str(df_id)], row_index)
if __name__ == '__main__':
# proxy = raw_input("Proxy:")
# port = raw_input("Proxy Port:")
# networkProxy = QtNetwork.QNetworkProxy(QtNetwork.QNetworkProxy.HttpProxy, proxy, int(port))
# QtNetwork.QNetworkProxy.setApplicationProxy(networkProxy)
# Automatically compile all ui files if they have been changed.
compile_and_import_ui_files()
app = QtGui.QApplication([])
app.setStyleSheet(qdarkstyle.load_stylesheet(pyside=False))
w = MainWindow()
w.raise_()
app.exec_()