Merge remote-tracking branch 'origin/develop' into develop

This commit is contained in:
Darius Arnold 2017-09-07 16:43:21 +02:00
commit 8a600e1bfa
6 changed files with 416 additions and 256 deletions

View File

@ -78,7 +78,7 @@ from pylot.core.util.utils import fnConstructor, getLogin, \
from pylot.core.util.event import Event from pylot.core.util.event import Event
from pylot.core.io.location import create_creation_info, create_event from pylot.core.io.location import create_creation_info, create_event
from pylot.core.util.widgets import FilterOptionsDialog, NewEventDlg, \ from pylot.core.util.widgets import FilterOptionsDialog, NewEventDlg, \
WaveformWidget, WaveformWidgetPG, PropertiesDlg, HelpForm, createAction, PickDlg, \ PylotCanvas, WaveformWidgetPG, PropertiesDlg, HelpForm, createAction, PickDlg, \
getDataType, ComparisonWidget, TuneAutopicker, PylotParaBox, AutoPickDlg, CanvasWidget, AutoPickWidget, \ getDataType, ComparisonWidget, TuneAutopicker, PylotParaBox, AutoPickDlg, CanvasWidget, AutoPickWidget, \
CompareEventsWidget CompareEventsWidget
from pylot.core.util.map_projection import map_projection from pylot.core.util.map_projection import map_projection
@ -620,8 +620,8 @@ class MainWindow(QMainWindow):
self.disconnectWFplotEvents() self.disconnectWFplotEvents()
if str(settings.value('pyqtgraphic')) == 'false' or not pg: if str(settings.value('pyqtgraphic')) == 'false' or not pg:
self.pg = False self.pg = False
self.dataPlot = WaveformWidget(parent=self, xlabel=xlab, ylabel=None, self.dataPlot = PylotCanvas(parent=self, connect_events=False, multicursor=True)
title=plottitle) self.dataPlot.updateWidget(xlab, None, plottitle)
else: else:
self.pg = True self.pg = True
self.dataPlot = WaveformWidgetPG(parent=self, xlabel=xlab, ylabel=None, self.dataPlot = WaveformWidgetPG(parent=self, xlabel=xlab, ylabel=None,
@ -1914,7 +1914,7 @@ class MainWindow(QMainWindow):
def init_canvas_dict(self): def init_canvas_dict(self):
self.canvas_dict = {} self.canvas_dict = {}
for key in self.fig_keys: for key in self.fig_keys:
self.canvas_dict[key] = FigureCanvas(self.fig_dict[key]) self.canvas_dict[key] = PylotCanvas(self.fig_dict[key])
def init_fig_dict_wadatijack(self, eventIDs): def init_fig_dict_wadatijack(self, eventIDs):
self.fig_dict_wadatijack = {} self.fig_dict_wadatijack = {}
@ -1933,7 +1933,7 @@ class MainWindow(QMainWindow):
for eventID in self.fig_dict_wadatijack.keys(): for eventID in self.fig_dict_wadatijack.keys():
self.canvas_dict_wadatijack[eventID] = {} self.canvas_dict_wadatijack[eventID] = {}
for key in self.fig_keys_wadatijack: for key in self.fig_keys_wadatijack:
self.canvas_dict_wadatijack[eventID][key] = FigureCanvas(self.fig_dict_wadatijack[eventID][key]) self.canvas_dict_wadatijack[eventID][key] = PylotCanvas(self.fig_dict_wadatijack[eventID][key])
def tune_autopicker(self): def tune_autopicker(self):
''' '''
@ -1964,6 +1964,8 @@ class MainWindow(QMainWindow):
''' '''
self.init_canvas_dict() self.init_canvas_dict()
self.tap.fill_tabs(picked=True) self.tap.fill_tabs(picked=True)
for canvas in self.canvas_dict.values():
canvas.setZoomBorders2content()
def autoPick(self): def autoPick(self):
autosave = self.get_current_event_path() autosave = self.get_current_event_path()

View File

@ -330,7 +330,7 @@ def autopickstation(wfstream, pickparam, verbose=False,
for ax in fig.axes: for ax in fig.axes:
ax.vlines(pstart, ax.get_ylim()[0], ax.get_ylim()[1], color='c', linestyles='dashed', label='P start') ax.vlines(pstart, ax.get_ylim()[0], ax.get_ylim()[1], color='c', linestyles='dashed', label='P start')
ax.vlines(pstop, ax.get_ylim()[0], ax.get_ylim()[1], color='c', linestyles='dashed', label='P stop') ax.vlines(pstop, ax.get_ylim()[0], ax.get_ylim()[1], color='c', linestyles='dashed', label='P stop')
ax.legend() ax.legend(loc=1)
############################################################## ##############################################################
if aicpick.getpick() is not None: if aicpick.getpick() is not None:
# check signal length to detect spuriously picked noise peaks # check signal length to detect spuriously picked noise peaks
@ -872,7 +872,7 @@ def autopickstation(wfstream, pickparam, verbose=False,
ax1.set_title('%s, %s, P Weight=%d' % (tr_filt.stats.station, ax1.set_title('%s, %s, P Weight=%d' % (tr_filt.stats.station,
tr_filt.stats.channel, tr_filt.stats.channel,
Pweight)) Pweight))
ax1.legend() ax1.legend(loc=1)
ax1.set_yticks([]) ax1.set_yticks([])
ax1.set_ylim([-1.5, 1.5]) ax1.set_ylim([-1.5, 1.5])
ax1.set_ylabel('Normalized Counts') ax1.set_ylabel('Normalized Counts')
@ -930,7 +930,7 @@ def autopickstation(wfstream, pickparam, verbose=False,
else: else:
ax2.set_title('%s, S Weight=%d, SNR=None, SNRdB=None' % ( ax2.set_title('%s, S Weight=%d, SNR=None, SNRdB=None' % (
trH1_filt.stats.channel, Sweight)) trH1_filt.stats.channel, Sweight))
ax2.legend() ax2.legend(loc=1)
ax2.set_yticks([]) ax2.set_yticks([])
ax2.set_ylim([-1.5, 1.5]) ax2.set_ylim([-1.5, 1.5])
ax2.set_ylabel('Normalized Counts') ax2.set_ylabel('Normalized Counts')
@ -973,7 +973,7 @@ def autopickstation(wfstream, pickparam, verbose=False,
[-1.3, -1.3], 'g', linewidth=2) [-1.3, -1.3], 'g', linewidth=2)
ax3.plot([lpickS, lpickS], [-1.1, 1.1], 'g--', label='lpp') ax3.plot([lpickS, lpickS], [-1.1, 1.1], 'g--', label='lpp')
ax3.plot([epickS, epickS], [-1.1, 1.1], 'g--', label='epp') ax3.plot([epickS, epickS], [-1.1, 1.1], 'g--', label='epp')
ax3.legend() ax3.legend(loc=1)
ax3.set_yticks([]) ax3.set_yticks([])
ax3.set_ylim([-1.5, 1.5]) ax3.set_ylim([-1.5, 1.5])
ax3.set_xlabel('Time [s] after %s' % tr_filt.stats.starttime) ax3.set_xlabel('Time [s] after %s' % tr_filt.stats.starttime)

View File

@ -272,7 +272,7 @@ class AICPicker(AutoPicker):
x = self.Data[0].data x = self.Data[0].data
ax.plot(self.Tcf, x / max(x), 'k', label='(HOS-/AR-) Data') ax.plot(self.Tcf, x / max(x), 'k', label='(HOS-/AR-) Data')
ax.plot(self.Tcf, aicsmooth / max(aicsmooth), 'r', label='Smoothed AIC-CF') ax.plot(self.Tcf, aicsmooth / max(aicsmooth), 'r', label='Smoothed AIC-CF')
ax.legend() ax.legend(loc=1)
ax.set_xlabel('Time [s] since %s' % self.Data[0].stats.starttime) ax.set_xlabel('Time [s] since %s' % self.Data[0].stats.starttime)
ax.set_yticks([]) ax.set_yticks([])
ax.set_title(self.Data[0].stats.station) ax.set_title(self.Data[0].stats.station)
@ -313,7 +313,7 @@ class AICPicker(AutoPicker):
ax1.plot([self.Pick, self.Pick], [-0.1, 0.5], 'b', linewidth=2, label='AIC-Pick') ax1.plot([self.Pick, self.Pick], [-0.1, 0.5], 'b', linewidth=2, label='AIC-Pick')
ax1.set_xlabel('Time [s] since %s' % self.Data[0].stats.starttime) ax1.set_xlabel('Time [s] since %s' % self.Data[0].stats.starttime)
ax1.set_yticks([]) ax1.set_yticks([])
ax1.legend() ax1.legend(loc=1)
if self.Pick is not None: if self.Pick is not None:
ax2 = fig.add_subplot(2, 1, 2, sharex=ax1) ax2 = fig.add_subplot(2, 1, 2, sharex=ax1)
@ -336,7 +336,7 @@ class AICPicker(AutoPicker):
ax2.set_xlabel('Time [s] since %s' % self.Data[0].stats.starttime) ax2.set_xlabel('Time [s] since %s' % self.Data[0].stats.starttime)
ax2.set_ylabel('Counts') ax2.set_ylabel('Counts')
ax2.set_yticks([]) ax2.set_yticks([])
ax2.legend() ax2.legend(loc=1)
if plt_flag == 1: if plt_flag == 1:
fig.show() fig.show()
try: input() try: input()
@ -480,7 +480,7 @@ class PragPicker(AutoPicker):
ax.set_xlabel('Time [s] since %s' % self.Data[0].stats.starttime) ax.set_xlabel('Time [s] since %s' % self.Data[0].stats.starttime)
ax.set_yticks([]) ax.set_yticks([])
ax.set_title(self.Data[0].stats.station) ax.set_title(self.Data[0].stats.station)
ax.legend() ax.legend(loc=1)
if plt_flag == 1: if plt_flag == 1:
fig.show() fig.show()
try: input() try: input()

View File

@ -150,7 +150,7 @@ def earllatepicker(X, nfac, TSNR, Pick1, iplot=0, verbosity=1, fig=None):
ax.set_title( ax.set_title(
'Earliest-/Latest Possible/Most Likely Pick & Symmetric Pick Error, %s' % 'Earliest-/Latest Possible/Most Likely Pick & Symmetric Pick Error, %s' %
X[0].stats.station) X[0].stats.station)
ax.legend() ax.legend(loc=1)
if plt_flag == 1: if plt_flag == 1:
fig.show() fig.show()
try: input() try: input()
@ -330,7 +330,7 @@ def fmpicker(Xraw, Xfilt, pickwin, Pick, iplot=0, fig=None):
ax1.plot(t[islope1], xraw[islope1], label='Slope Window') ax1.plot(t[islope1], xraw[islope1], label='Slope Window')
ax1.plot(zc1, np.zeros(len(zc1)), '*g', markersize=14, label='Zero Crossings') ax1.plot(zc1, np.zeros(len(zc1)), '*g', markersize=14, label='Zero Crossings')
ax1.plot(t[islope1], datafit1, '--g', linewidth=2) ax1.plot(t[islope1], datafit1, '--g', linewidth=2)
ax1.legend() ax1.legend(loc=1)
ax1.text(Pick + 0.02, max(xraw) / 2, '%s' % FM, fontsize=14) ax1.text(Pick + 0.02, max(xraw) / 2, '%s' % FM, fontsize=14)
ax1.set_yticks([]) ax1.set_yticks([])
ax1.set_title('First-Motion Determination, %s, Unfiltered Data' % Xraw[ ax1.set_title('First-Motion Determination, %s, Unfiltered Data' % Xraw[
@ -680,7 +680,7 @@ def wadaticheck(pickdic, dttolerance, iplot=0, fig_dict=None):
ax.plot(checkedPpicks, wdfit2, 'g', label='Wadati 2') ax.plot(checkedPpicks, wdfit2, 'g', label='Wadati 2')
ax.set_title('Wadati-Diagram, %d S-P Times, Vp/Vs(raw)=%5.2f,' \ ax.set_title('Wadati-Diagram, %d S-P Times, Vp/Vs(raw)=%5.2f,' \
'Vp/Vs(checked)=%5.2f' % (len(SPtimes), vpvsr, cvpvsr)) 'Vp/Vs(checked)=%5.2f' % (len(SPtimes), vpvsr, cvpvsr))
ax.legend() ax.legend(loc=1)
else: else:
ax.set_title('Wadati-Diagram, %d S-P Times' % len(SPtimes)) ax.set_title('Wadati-Diagram, %d S-P Times' % len(SPtimes))
@ -791,7 +791,7 @@ def checksignallength(X, pick, TSNR, minsiglength, nfac, minpercent, iplot=0, fi
ax.plot([t[isignal[0]], t[isignal[len(isignal) - 1]]], ax.plot([t[isignal[0]], t[isignal[len(isignal) - 1]]],
[minsiglevel, minsiglevel], 'g', linewidth=2, label='Minimum Signal Level') [minsiglevel, minsiglevel], 'g', linewidth=2, label='Minimum Signal Level')
ax.plot([pick, pick], [min(rms), max(rms)], 'b', linewidth=2, label='Onset') ax.plot([pick, pick], [min(rms), max(rms)], 'b', linewidth=2, label='Onset')
ax.legend() ax.legend(loc=1)
ax.set_xlabel('Time [s] since %s' % X[0].stats.starttime) ax.set_xlabel('Time [s] since %s' % X[0].stats.starttime)
ax.set_ylabel('Counts') ax.set_ylabel('Counts')
ax.set_title('Check for Signal Length, Station %s' % X[0].stats.station) ax.set_title('Check for Signal Length, Station %s' % X[0].stats.station)
@ -903,7 +903,7 @@ def checkPonsets(pickdic, dttolerance, jackfactor=5, iplot=0, fig_dict=None):
ax.set_xlabel('Number of P Picks') ax.set_xlabel('Number of P Picks')
ax.set_ylabel('Onset Time [s] from 1.1.1970') ax.set_ylabel('Onset Time [s] from 1.1.1970')
ax.legend() ax.legend(loc=1)
ax.set_title('Jackknifing and Median Tests on P Onsets') ax.set_title('Jackknifing and Median Tests on P Onsets')
if plt_flag: if plt_flag:
fig.show() fig.show()
@ -1110,7 +1110,7 @@ def checkZ4S(X, pick, zfac, checkwin, iplot, fig=None):
ax.set_ylabel('Normalized Counts') ax.set_ylabel('Normalized Counts')
ax.axvspan(pick, pick + checkwin, color='c', alpha=0.2, ax.axvspan(pick, pick + checkwin, color='c', alpha=0.2,
lw=0) lw=0)
ax.legend() ax.legend(loc=1)
ax.set_xlabel('Time [s] since %s' % zdat[0].stats.starttime) ax.set_xlabel('Time [s] since %s' % zdat[0].stats.starttime)
if plt_flag == 1: if plt_flag == 1:
fig.show() fig.show()

View File

@ -1,3 +1,6 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
import obspy import obspy
@ -13,6 +16,7 @@ plt.interactive(False)
class map_projection(QtGui.QWidget): class map_projection(QtGui.QWidget):
def __init__(self, parent, figure=None): def __init__(self, parent, figure=None):
''' '''
:param: picked, can be False, auto, manual :param: picked, can be False, auto, manual
:value: str :value: str
''' '''
@ -272,7 +276,7 @@ class map_projection(QtGui.QWidget):
for index, name in enumerate(self.station_names): for index, name in enumerate(self.station_names):
self.annotations.append(self.main_ax.annotate(' %s' % name, xy=(self.x[index], self.y[index]), self.annotations.append(self.main_ax.annotate(' %s' % name, xy=(self.x[index], self.y[index]),
fontsize='x-small', color='white', zorder=12)) fontsize='x-small', color='white', zorder=12))
self.legend = self.main_ax.legend() self.legend = self.main_ax.legend(loc=1)
def add_cbar(self, label): def add_cbar(self, label):
cbar = self.main_ax.figure.colorbar(self.sc_picked, fraction=0.025) cbar = self.main_ax.figure.colorbar(self.sc_picked, fraction=0.025)

View File

@ -31,6 +31,8 @@ except ImportError:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT
from matplotlib.widgets import MultiCursor from matplotlib.widgets import MultiCursor
from matplotlib.tight_layout import get_renderer, get_subplotspec_list, get_tight_layout_figure
from PySide import QtCore, QtGui from PySide import QtCore, QtGui
from PySide.QtGui import QAction, QApplication, QCheckBox, QComboBox, \ from PySide.QtGui import QAction, QApplication, QCheckBox, QComboBox, \
QDateTimeEdit, QDialog, QDialogButtonBox, QDoubleSpinBox, QGroupBox, \ QDateTimeEdit, QDialog, QDialogButtonBox, QDoubleSpinBox, QGroupBox, \
@ -522,12 +524,13 @@ class WaveformWidgetPG(QtGui.QWidget):
try: try:
self.plotWidget.getPlotItem().vb.setLimits(xMin=float(0), self.plotWidget.getPlotItem().vb.setLimits(xMin=float(0),
xMax=float(self.wfend - self.wfstart), xMax=float(self.wfend - self.wfstart),
yMin=-0.5, yMin=.5,
yMax=len(nsc) + 0.5) yMax=len(nsc) + .5)
except: except:
print('Warning: Could not set zoom limits') print('Warning: Could not set zoom limits')
for n, (network, station, channel) in enumerate(nsc): for n, (network, station, channel) in enumerate(nsc):
n+=1
st = st_select.select(network=network, station=station, channel=channel) st = st_select.select(network=network, station=station, channel=channel)
trace = st[0] trace = st[0]
if mapping: if mapping:
@ -552,7 +555,7 @@ class WaveformWidgetPG(QtGui.QWidget):
self.xlabel = 'seconds since {0}'.format(self.wfstart) self.xlabel = 'seconds since {0}'.format(self.wfstart)
self.ylabel = '' self.ylabel = ''
self.setXLims([0, self.wfend - self.wfstart]) self.setXLims([0, self.wfend - self.wfstart])
self.setYLims([-0.5, nmax + 0.5]) self.setYLims([0.5, nmax + 0.5])
return plots return plots
# def getAxes(self): # def getAxes(self):
@ -604,29 +607,274 @@ class WaveformWidgetPG(QtGui.QWidget):
pass pass
class WaveformWidget(FigureCanvas): class PylotCanvas(FigureCanvas):
def __init__(self, parent=None, xlabel='x', ylabel='y', title='Title'): def __init__(self, figure=None, parent=None, connect_events=True, multicursor=False,
panZoomX=True, panZoomY=True):
self._parent = parent self._parent = parent
self.figure = Figure() if not figure:
self.figure.set_facecolor((.92, .92, .92)) figure = Figure()
# create axes
self.ax = figure.add_subplot(111)
self.axes = figure.axes
self.figure = figure
self.figure.set_facecolor((1., 1., 1.))
# attribute plotdict is a dictionary connecting position and a name # attribute plotdict is a dictionary connecting position and a name
self.plotdict = dict() self.plotdict = dict()
# create axes
self.axes = self.figure.add_subplot(111)
# initialize super class # initialize super class
super(WaveformWidget, self).__init__(self.figure) super(PylotCanvas, self).__init__(self.figure)
# add an cursor for station selection
self.multiCursor = MultiCursor(self.figure.canvas, (self.axes,), if multicursor:
horizOn=True, useblit=True, # add a cursor for station selection
color='m', lw=1) self.multiCursor = MultiCursor(self.figure.canvas, self.axes,
# update labels of the entire widget horizOn=True, useblit=True,
self.updateWidget(xlabel, ylabel, title) color='m', lw=1)
# initialize panning attributes
self.press = None
self.xpress = None
self.ypress = None
self.cur_xlim = None
self.cur_ylim = None
# panZoom activated selection
self.panZoomX = panZoomX
self.panZoomY = panZoomY
self.limits = {}
for ax in self.axes:
self.limits[ax] = {'x': (-np.inf, np.inf),
'y': (-np.inf, np.inf)}
if connect_events:
self.connectEvents()
try: try:
self.figure.tight_layout() self.figure.tight_layout()
except: except:
pass pass
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.setFocus()
def panPress(self, gui_event):
ax_check = False
for ax in self.axes:
if gui_event.inaxes == ax:
ax_check = True
break
if not ax_check: return
self.cur_xlim = ax.get_xlim()
self.cur_ylim = ax.get_ylim()
self.press = gui_event.xdata, gui_event.ydata
self.press_rel = gui_event.x, gui_event.y
self.xpress, self.ypress = self.press
def pan(self, gui_event):
if self.press is None:
return
if gui_event.button == 1:
self.panMotion(gui_event)
elif gui_event.button == 3:
if self.panZoomX or self.panZoomY:
self.panZoom(gui_event)
def panMotion(self, gui_event):
ax_check = False
for ax in self.axes:
if gui_event.inaxes == ax:
ax_check = True
break
if not ax_check: return
dx = gui_event.xdata - self.xpress
dy = gui_event.ydata - self.ypress
self.cur_xlim -= dx
self.cur_ylim -= dy
ax.set_xlim(self.cur_xlim)
ax.set_ylim(self.cur_ylim)
self.refreshPickDlgText()
ax.figure.canvas.draw()
def panRelease(self, gui_event):
self.press = None
self.press_rel = None
self.figure.canvas.draw()
def panZoom(self, gui_event, threshold=2., factor=1.1):
if not gui_event.x and not gui_event.y:
return
if not gui_event.button == 3:
return
ax_check = False
for ax in self.axes:
if gui_event.inaxes == ax:
ax_check = True
break
if not ax_check: return
#self.updateCurrentLimits() #maybe put this down to else:
# calculate delta (relative values in axis)
old_x, old_y = self.press_rel
xdiff = gui_event.x - old_x
ydiff = gui_event.y - old_y
# threshold check
if abs(xdiff) < threshold and abs(ydiff) < threshold:
return
# refresh press positions to new position
self.press = gui_event.xdata, gui_event.ydata
self.press_rel = gui_event.x, gui_event.y
self.xpress, self.ypress = self.press
if abs(xdiff) >= threshold and self.panZoomX:
x_left, x_right = self.getXLims(ax)
new_xlim = self.calcPanZoom(self.xpress, x_left, x_right, factor, (xdiff > 0))
self.setXLims(ax, new_xlim)
if abs(ydiff) >= threshold and self.panZoomY:
y_bot, y_top = self.getYLims(ax)
new_ylim = self.calcPanZoom(self.ypress, y_bot, y_top, factor, (ydiff > 0))
self.setYLims(ax, new_ylim)
self.draw()
def saveFigure(self):
if self.figure:
fd = QtGui.QFileDialog()
fname, filter = fd.getSaveFileName(self._parent, filter='Images (*.png)')
if not fname:
return
if not fname.endswith('.png'):
fname += '.png'
self.figure.savefig(fname)
def calcPanZoom(self, origin, lower_b, upper_b, factor, positive):
d_lower = abs(origin - lower_b)
d_upper = abs(origin - upper_b)
if positive:
d_lower *= 1 - 1/factor
d_upper *= 1 - 1/factor
lower_b += d_lower
upper_b -= d_upper
else:
d_lower /= 1 + 1/factor
d_upper /= 1 + 1/factor
lower_b -= d_lower
upper_b += d_upper
new_lim = [lower_b, upper_b]
new_lim.sort()
return new_lim
def scrollZoom(self, gui_event, factor=2.):
if not gui_event.xdata or not gui_event.ydata:
return
ax_check = False
for ax in self.axes:
if gui_event.inaxes == ax:
ax_check = True
break
if not ax_check: return
self.updateCurrentLimits()
if gui_event.button == 'up':
scale_factor = 1 / factor
elif gui_event.button == 'down':
# deal with zoom out
scale_factor = factor
else:
# deal with something that should never happen
scale_factor = 1
print(gui_event.button)
new_xlim = gui_event.xdata - \
scale_factor * (gui_event.xdata - self.getXLims(ax))
new_ylim = gui_event.ydata - \
scale_factor * (gui_event.ydata - self.getYLims(ax))
new_xlim.sort()
global_x = self.getGlobalLimits(ax, 'x')
global_y = self.getGlobalLimits(ax, 'y')
new_xlim[0] = max(new_xlim[0], global_x[0])
new_xlim[1] = min(new_xlim[1], global_x[1])
new_ylim.sort()
new_ylim[0] = max(new_ylim[0], global_y[0])
new_ylim[1] = min(new_ylim[1], global_y[1])
self.setXLims(ax, new_xlim)
self.setYLims(ax, new_ylim)
self.refreshPickDlgText()
self.draw()
def refreshPickDlgText(self):
# TODO: Maybe decreasing performance if activated too often on move event
# refresh text for pickdlg if given
parent = self.parent()
if hasattr(parent, 'refreshArrivalsText'):
parent.refreshArrivalsText()
if hasattr(parent, 'refreshPhaseText'):
parent.refreshPhaseText()
def keyPressHandler(self, gui_event):
if gui_event.key == 'ctrl+s':
self.saveFigure()
def connectEvents(self):
self.cidscroll = self.connectScrollEvent(self.scrollZoom)
self.cidpress = self.connectPressEvent(self.panPress)
self.cidmotion = self.connectMotionEvent(self.pan)
self.cidrelease = self.connectReleaseEvent(self.panRelease)
self.cidkpress = self.connectKeyPressEvent(self.keyPressHandler)
def disconnectEvents(self):
self.disconnectScrollEvent(self.cidscroll)
self.disconnectMotionEvent(self.cidmotion)
self.disconnectPressEvent(self.cidpress)
self.disconnectReleaseEvent(self.cidrelease)
self.disconnectKeyPressEvent(self.cidkpress)
self.cidscroll = None
self.cidrelease = None
self.cidpress = None
self.cidmotion = None
self.cidkpress = None
def disconnectPressEvent(self, cid):
self.mpl_disconnect(cid)
def connectPressEvent(self, slot):
return self.mpl_connect('button_press_event', slot)
def disconnectMotionEvent(self, cid):
self.mpl_disconnect(cid)
def connectMotionEvent(self, slot):
return self.mpl_connect('motion_notify_event', slot)
def disconnectReleaseEvent(self, cid):
self.mpl_disconnect(cid)
def connectReleaseEvent(self, slot):
return self.mpl_connect('button_release_event', slot)
def disconnectScrollEvent(self, cid):
self.mpl_disconnect(cid)
def connectScrollEvent(self, slot):
return self.mpl_connect('scroll_event', slot)
def disconnectKeyPressEvent(self, cid):
self.mpl_disconnect(cid)
def connectKeyPressEvent(self, slot):
return self.mpl_connect('key_press_event', slot)
def getPlotDict(self): def getPlotDict(self):
return self.plotdict return self.plotdict
@ -645,7 +893,9 @@ class WaveformWidget(FigureCanvas):
def plotWFData(self, wfdata, title=None, zoomx=None, zoomy=None, def plotWFData(self, wfdata, title=None, zoomx=None, zoomy=None,
noiselevel=None, scaleddata=False, mapping=True, noiselevel=None, scaleddata=False, mapping=True,
component='*', nth_sample=1, iniPick=None, verbosity=0): component='*', nth_sample=1, iniPick=None, verbosity=0):
self.getAxes().cla() ax = self.axes[0]
ax.cla()
self.clearPlotDict() self.clearPlotDict()
wfstart, wfend = full_range(wfdata) wfstart, wfend = full_range(wfdata)
nmax = 0 nmax = 0
@ -692,58 +942,54 @@ class WaveformWidget(FigureCanvas):
trace.normalize(np.max(np.abs(trace.data)) * 2) trace.normalize(np.max(np.abs(trace.data)) * 2)
times = [time for index, time in enumerate(time_ax) if not index % nth_sample] times = [time for index, time in enumerate(time_ax) if not index % nth_sample]
data = [datum + n for index, datum in enumerate(trace.data) if not index % nth_sample] data = [datum + n for index, datum in enumerate(trace.data) if not index % nth_sample]
self.getAxes().plot(times, data, 'k', linewidth=0.7) ax.plot(times, data, 'k', linewidth=0.7)
if noiselevel is not None: if noiselevel is not None:
for level in noiselevel: for level in noiselevel:
self.getAxes().plot([time_ax[0], time_ax[-1]], ax.plot([time_ax[0], time_ax[-1]],
[level, level], '--k') [level, level], '--k')
if iniPick:
ax = self.getAxes()
ax.vlines(iniPick, ax.get_ylim()[0], ax.get_ylim()[1],
colors='m', linestyles='dashed',
linewidth=2)
self.setPlotDict(n, (station, channel, network)) self.setPlotDict(n, (station, channel, network))
if iniPick:
ax.vlines(iniPick, ax.get_ylim()[0], ax.get_ylim()[1],
colors='m', linestyles='dashed',
linewidth=2)
xlabel = 'seconds since {0}'.format(wfstart) xlabel = 'seconds since {0}'.format(wfstart)
ylabel = '' ylabel = ''
self.updateWidget(xlabel, ylabel, title) self.updateWidget(xlabel, ylabel, title)
self.setXLims([0, wfend - wfstart]) self.setXLims(ax, [0, wfend - wfstart])
self.setYLims([-0.5, nmax + 0.5]) self.setYLims(ax, [-0.5, nmax + 0.5])
if zoomx is not None: if zoomx is not None:
self.setXLims(zoomx) self.setXLims(ax, zoomx)
if zoomy is not None: if zoomy is not None:
self.setYLims(zoomy) self.setYLims(ax, zoomy)
self.draw() self.draw()
def getAxes(self): def getXLims(self, ax):
return self.axes return ax.get_xlim()
def getXLims(self): def getYLims(self, ax):
return self.getAxes().get_xlim() return ax.get_ylim()
def getYLims(self): def setXLims(self, ax, lims):
return self.getAxes().get_ylim() ax.set_xlim(lims)
def setXLims(self, lims): def setYLims(self, ax, lims):
self.getAxes().set_xlim(lims) ax.set_ylim(lims)
def setYLims(self, lims):
self.getAxes().set_ylim(lims)
def setYTickLabels(self, pos, labels): def setYTickLabels(self, pos, labels):
self.getAxes().set_yticks(list(pos)) self.axes[0].set_yticks(list(pos))
self.getAxes().set_yticklabels(labels) self.axes[0].set_yticklabels(labels)
self.draw() self.draw()
def updateXLabel(self, text): def updateXLabel(self, text):
self.getAxes().set_xlabel(text) self.axes[0].set_xlabel(text)
self.draw() self.draw()
def updateYLabel(self, text): def updateYLabel(self, text):
self.getAxes().set_ylabel(text) self.axes[0].set_ylabel(text)
self.draw() self.draw()
def updateTitle(self, text): def updateTitle(self, text):
self.getAxes().set_title(text, verticalalignment='bottom') self.axes[0].set_title(text, verticalalignment='bottom')
self.draw() self.draw()
def updateWidget(self, xlabel, ylabel, title): def updateWidget(self, xlabel, ylabel, title):
@ -752,11 +998,41 @@ class WaveformWidget(FigureCanvas):
self.updateTitle(title) self.updateTitle(title)
def insertLabel(self, pos, text): def insertLabel(self, pos, text):
pos = pos / max(self.getAxes().ylim) pos = pos / max(self.axes[0].ylim)
axann = self.getAxes().annotate(text, xy=(.03, pos), axann = self.axes[0].annotate(text, xy=(.03, pos),
xycoords='axes fraction') xycoords='axes fraction')
axann.set_bbox(dict(facecolor='lightgrey', alpha=.6)) axann.set_bbox(dict(facecolor='lightgrey', alpha=.6))
def setZoomBorders2content(self):
if not self.axes:
return
for ax in self.limits.keys():
xlims = self.getXLims(ax)
ylims = self.getYLims(ax)
self.limits[ax] = {'x': xlims,
'y': ylims}
for axis, limit in self.limits[ax].items():
self.setGlobalLimits(ax, axis, limit)
def updateCurrentLimits(self):
for ax in self.limits.keys():
self.setXLims(ax, self.getXLims(ax))
self.setYLims(ax, self.getYLims(ax))
def getGlobalLimits(self, ax, axis):
return self.limits[ax][axis]
def setGlobalLimits(self, ax, axis, limits):
self.limits[ax][axis] = limits
def resetZoom(self):
for ax in self.figure.axes:
self.setXLims(ax, self.getGlobalLimits(ax, 'x'))
self.setYLims(ax, self.getGlobalLimits(ax, 'y'))
self.draw()
class PhaseDefaults(QtGui.QDialog): class PhaseDefaults(QtGui.QDialog):
def __init__(self, parent=None, nrow=10, def __init__(self, parent=None, nrow=10,
@ -894,24 +1170,22 @@ class PickDlg(QDialog):
self.stime, self.etime = full_range(self.getWFData()) self.stime, self.etime = full_range(self.getWFData())
# initialize plotting widget # initialize plotting widget
self.multicompfig = WaveformWidget(self) self.multicompfig = PylotCanvas(parent=self, multicursor=True)
self.phaseplot = PhasePlotWidget(self) self.phaseplot = PhasePlotWidget(self)
self.phaseplot.hide() self.phaseplot.hide()
# setup ui
self.setupUi()
# plot data # plot data
self.getPlotWidget().plotWFData(wfdata=self.getWFData(), self.multicompfig.plotWFData(wfdata=self.getWFData(),
title=self.getStation()) title=self.getStation())
xlims = self.getPlotWidget().getXLims() self.multicompfig.setZoomBorders2content()
ylims = self.getPlotWidget().getYLims()
self.limits = {'x': xlims, self.multicompfig.updateCurrentLimits()
'y': ylims} self.multicompfig.draw()
self.multicompfig.setFocus()
self.updateCurrentLimits() # setup ui
self.setupUi()
# set plot labels # set plot labels
self.setPlotLabels() self.setPlotLabels()
@ -919,12 +1193,6 @@ class PickDlg(QDialog):
# draw picks if present # draw picks if present
self.drawAllPicks() self.drawAllPicks()
# connect button press event to an action
self.cidpress = self.connectPressEvent(self.panPress)
self.cidmotion = self.connectMotionEvent(self.panMotion)
self.cidrelease = self.connectReleaseEvent(self.panRelease)
self.cidscroll = self.connectScrollEvent(self.scrollZoom)
# init expected picks using obspy Taup # init expected picks using obspy Taup
try: try:
if self.metadata: if self.metadata:
@ -952,7 +1220,7 @@ class PickDlg(QDialog):
self.addPickPhases(menuBar) self.addPickPhases(menuBar)
# create matplotlib toolbar to inherit functionality # create matplotlib toolbar to inherit functionality
self.figToolBar = NavigationToolbar2QT(self.getPlotWidget(), self) self.figToolBar = NavigationToolbar2QT(self.multicompfig, self)
self.figToolBar.hide() self.figToolBar.hide()
# create icons # create icons
@ -976,7 +1244,7 @@ class PickDlg(QDialog):
tip='Zoom into waveform', tip='Zoom into waveform',
checkable=True) checkable=True)
self.resetZoomAction = createAction(parent=self, text='Home', self.resetZoomAction = createAction(parent=self, text='Home',
slot=self.resetZoom, icon=home_icon, slot=self.multicompfig.resetZoom, icon=home_icon,
tip='Reset zoom to original limits') tip='Reset zoom to original limits')
self.resetPicksAction = createAction(parent=self, text='Delete Picks', self.resetPicksAction = createAction(parent=self, text='Delete Picks',
slot=self.delPicks, icon=del_icon, slot=self.delPicks, icon=del_icon,
@ -1083,7 +1351,7 @@ class PickDlg(QDialog):
self.get_arrivals(True) self.get_arrivals(True)
ax = self.phaseplot.ax ax = self.phaseplot.ax
self.arrivals.plot(ax=ax, show=False) self.arrivals.plot(ax=ax, show=False)
ax.legend() ax.legend(loc=1)
self.phaseplot.new = False self.phaseplot.new = False
self.phaseplot.draw() self.phaseplot.draw()
self.phaseplot.show() self.phaseplot.show()
@ -1126,11 +1394,11 @@ class PickDlg(QDialog):
def drawArrivals(self, textOnly=False): def drawArrivals(self, textOnly=False):
if not self.arrivals: if not self.arrivals:
return return
ax = self.getPlotWidget().axes ax = self.multicompfig.axes[0]
if not textOnly: if not textOnly:
ylims = self.getGlobalLimits('y') ylims = self.getGlobalLimits('y')
else: else:
ylims = self.getPlotWidget().getYLims() ylims = self.multicompfig.getYLims(ax)
stime = self.getStartTime() stime = self.getStartTime()
source_origin = self.pylot_event.origins[0] source_origin = self.pylot_event.origins[0]
source_time = source_origin.time source_time = source_origin.time
@ -1144,7 +1412,7 @@ class PickDlg(QDialog):
def drawArrivalsText(self): def drawArrivalsText(self):
return self.drawArrivals(True) return self.drawArrivals(True)
def refreshArrivalsText(self): def refreshArrivalsText(self, event=None):
self.removeArrivalsText() self.removeArrivalsText()
self.drawArrivalsText() self.drawArrivalsText()
@ -1210,42 +1478,6 @@ class PickDlg(QDialog):
if phaseIndex == 0: if phaseIndex == 0:
picksMenu.addSeparator() picksMenu.addSeparator()
def disconnectPressEvent(self):
widget = self.getPlotWidget()
widget.mpl_disconnect(self.cidpress)
self.cidpress = None
def connectPressEvent(self, slot):
widget = self.getPlotWidget()
return widget.mpl_connect('button_press_event', slot)
def disconnectScrollEvent(self):
widget = self.getPlotWidget()
widget.mpl_disconnect(self.cidscroll)
self.cidscroll = None
def connectScrollEvent(self, slot):
widget = self.getPlotWidget()
return widget.mpl_connect('scroll_event', slot)
def disconnectMotionEvent(self):
widget = self.getPlotWidget()
widget.mpl_disconnect(self.cidmotion)
self.cidmotion = None
def connectMotionEvent(self, slot):
widget = self.getPlotWidget()
return widget.mpl_connect('motion_notify_event', slot)
def disconnectReleaseEvent(self):
widget = self.getPlotWidget()
widget.mpl_disconnect(self.cidrelease)
self.cidrelease = None
def connectReleaseEvent(self, slot):
widget = self.getPlotWidget()
return widget.mpl_connect('button_release_event', slot)
def disable_ar_buttons(self): def disable_ar_buttons(self):
self.enable_ar_buttons(False) self.enable_ar_buttons(False)
@ -1293,13 +1525,11 @@ class PickDlg(QDialog):
def init_p_pick(self): def init_p_pick(self):
self.set_button_color(self.p_button, 'yellow') self.set_button_color(self.p_button, 'yellow')
self.updateCurrentLimits()
self.activatePicking() self.activatePicking()
self.currentPhase = str(self.p_button.text()) self.currentPhase = str(self.p_button.text())
def init_s_pick(self): def init_s_pick(self):
self.set_button_color(self.s_button, 'yellow') self.set_button_color(self.s_button, 'yellow')
self.updateCurrentLimits()
self.activatePicking() self.activatePicking()
self.currentPhase = str(self.s_button.text()) self.currentPhase = str(self.s_button.text())
@ -1332,7 +1562,7 @@ class PickDlg(QDialog):
self.currentPhase = None self.currentPhase = None
self.reset_p_button() self.reset_p_button()
self.reset_s_button() self.reset_s_button()
self.getPlotWidget().plotWFData(wfdata=self.getWFData(), self.multicompfig.plotWFData(wfdata=self.getWFData(),
title=self.getStation()) title=self.getStation())
self.drawAllPicks() self.drawAllPicks()
self.drawArrivals() self.drawArrivals()
@ -1341,23 +1571,18 @@ class PickDlg(QDialog):
self.deactivatePicking() self.deactivatePicking()
def activatePicking(self): def activatePicking(self):
self.resetZoom()
if self.zoomAction.isChecked(): if self.zoomAction.isChecked():
self.zoomAction.trigger() self.zoomAction.trigger()
self.disconnectReleaseEvent() self.multicompfig.disconnectEvents()
self.disconnectScrollEvent() self.cidpress = self.multicompfig.connectPressEvent(self.setIniPick)
self.disconnectMotionEvent()
self.disconnectPressEvent()
self.cidpress = self.connectPressEvent(self.setIniPick)
self.filterWFData() self.filterWFData()
self.pick_block = self.togglePickBlocker() #self.pick_block = self.togglePickBlocker()
self.disconnect_pick_delete() self.disconnect_pick_delete()
def deactivatePicking(self): def deactivatePicking(self):
self.disconnectPressEvent() self.disconnectPressEvent()
self.cidpress = self.connectPressEvent(self.panPress) self.multicompfig.connectEvents()
self.cidmotion = self.connectMotionEvent(self.panMotion)
self.cidrelease = self.connectReleaseEvent(self.panRelease)
self.cidscroll = self.connectScrollEvent(self.scrollZoom)
self.connect_pick_delete() self.connect_pick_delete()
def getParameter(self): def getParameter(self):
@ -1377,14 +1602,11 @@ class PickDlg(QDialog):
return self.network + '.' + self.station return self.network + '.' + self.station
return self.station return self.station
def getPlotWidget(self):
return self.multicompfig
def getChannelID(self, key): def getChannelID(self, key):
return self.getPlotWidget().getPlotDict()[int(key)][1] return self.multicompfig.getPlotDict()[int(key)][1]
def getTraceID(self, channels): def getTraceID(self, channels):
plotDict = self.getPlotWidget().getPlotDict() plotDict = self.multicompfig.getPlotDict()
traceIDs = [] traceIDs = []
for channel in channels: for channel in channels:
channel = channel.upper() channel = channel.upper()
@ -1416,11 +1638,7 @@ class PickDlg(QDialog):
self.cur_ylim = limits self.cur_ylim = limits
def getGlobalLimits(self, axis): def getGlobalLimits(self, axis):
return self.limits[axis] return self.multicompfig.getGlobalLimits(axis)
def updateCurrentLimits(self):
self.setXLims(self.getPlotWidget().getXLims())
self.setYLims(self.getPlotWidget().getYLims())
def getWFData(self): def getWFData(self):
return self.data return self.data
@ -1469,11 +1687,9 @@ class PickDlg(QDialog):
channel = self.getChannelID(trace_number) channel = self.getChannelID(trace_number)
wfdata = self.selectWFData(channel) wfdata = self.selectWFData(channel)
self.disconnectScrollEvent() self.multicompfig.disconnectEvents()
self.disconnectPressEvent() self.disconnectPressEvent()
self.disconnectReleaseEvent() self.cidpress = self.multicompfig.connectPressEvent(self.setPick)
self.disconnectMotionEvent()
self.cidpress = self.connectPressEvent(self.setPick)
if self.getPhaseID(self.currentPhase) == 'P': if self.getPhaseID(self.currentPhase) == 'P':
self.set_button_color(self.p_button, 'green') self.set_button_color(self.p_button, 'green')
@ -1541,7 +1757,7 @@ class PickDlg(QDialog):
self.setXLims([ini_pick - x_res, ini_pick + x_res]) self.setXLims([ini_pick - x_res, ini_pick + x_res])
self.setYLims(np.array([-noiselevel * 3.5, noiselevel * 3.5]) + self.setYLims(np.array([-noiselevel * 3.5, noiselevel * 3.5]) +
trace_number) trace_number)
self.getPlotWidget().plotWFData(wfdata=data, self.multicompfig.plotWFData(wfdata=data,
title=self.getStation() + title=self.getStation() +
' picking mode', ' picking mode',
zoomx=self.getXLims(), zoomx=self.getXLims(),
@ -1609,7 +1825,7 @@ class PickDlg(QDialog):
noiselevels = [trace + 1 / (2.5 * 2) for trace in traces] + \ noiselevels = [trace + 1 / (2.5 * 2) for trace in traces] + \
[trace - 1 / (2.5 * 2) for trace in traces] [trace - 1 / (2.5 * 2) for trace in traces]
self.getPlotWidget().plotWFData(wfdata=data, self.multicompfig.plotWFData(wfdata=data,
title=self.getStation() + title=self.getStation() +
' picking mode', ' picking mode',
zoomx=self.getXLims(), zoomx=self.getXLims(),
@ -1623,7 +1839,7 @@ class PickDlg(QDialog):
parameter = self.parameter parameter = self.parameter
# get axes limits # get axes limits
self.updateCurrentLimits() self.multicompfig.updateCurrentLimits()
# setting pick # setting pick
pick = gui_event.xdata # get pick time relative to the traces timeaxis not to the global pick = gui_event.xdata # get pick time relative to the traces timeaxis not to the global
@ -1701,10 +1917,14 @@ class PickDlg(QDialog):
self.disconnectPressEvent() self.disconnectPressEvent()
self.enable_ar_buttons() self.enable_ar_buttons()
self.zoomAction.setEnabled(True) self.zoomAction.setEnabled(True)
self.pick_block = self.togglePickBlocker() #self.pick_block = self.togglePickBlocker()
self.leave_picking_mode() self.leave_picking_mode()
self.setDirty(True) self.setDirty(True)
def disconnectPressEvent(self):
self.multicompfig.mpl_disconnect(self.cidpress)
self.cidpress = None
def drawAllPicks(self): def drawAllPicks(self):
self.removePhaseText() self.removePhaseText()
self.drawPicks(picktype='manual') self.drawPicks(picktype='manual')
@ -1712,11 +1932,11 @@ class PickDlg(QDialog):
def drawPicks(self, phase=None, picktype='manual', textOnly=False): def drawPicks(self, phase=None, picktype='manual', textOnly=False):
# plotting picks # plotting picks
ax = self.getPlotWidget().axes ax = self.multicompfig.axes[0]
if not textOnly: if not textOnly:
ylims = self.getGlobalLimits('y') ylims = self.multicompfig.getGlobalLimits(ax, 'y')
else: else:
ylims = self.getPlotWidget().getYLims() ylims = ax.get_ylim()
if self.getPicks(picktype): if self.getPicks(picktype):
if phase is not None and not phase == 'SPt': if phase is not None and not phase == 'SPt':
if (type(self.getPicks(picktype)[phase]) is dict if (type(self.getPicks(picktype)[phase]) is dict
@ -1783,11 +2003,11 @@ class PickDlg(QDialog):
ax.legend(loc=1) ax.legend(loc=1)
def connect_pick_delete(self): def connect_pick_delete(self):
self.cidpick = self.getPlotWidget().mpl_connect('pick_event', self.onpick_delete) self.cidpick = self.multicompfig.mpl_connect('pick_event', self.onpick_delete)
def disconnect_pick_delete(self): def disconnect_pick_delete(self):
if hasattr(self, 'cidpick'): if hasattr(self, 'cidpick'):
self.getPlotWidget().mpl_disconnect(self.cidpick) self.multicompfig.mpl_disconnect(self.cidpick)
def onpick_delete(self, event): def onpick_delete(self, event):
if not event.mouseevent.button == 3: if not event.mouseevent.button == 3:
@ -1808,6 +2028,8 @@ class PickDlg(QDialog):
for picktype in allpicks.keys(): for picktype in allpicks.keys():
picks = allpicks[picktype] picks = allpicks[picktype]
for phase in picks: for phase in picks:
if not type(picks[phase]) in [dict, AttribDict]:
continue
pick_rel = picks[phase]['mpp'] - starttime pick_rel = picks[phase]['mpp'] - starttime
# add relative pick time, phaseID and picktype index # add relative pick time, phaseID and picktype index
X.append((pick_rel, phase, picktype)) X.append((pick_rel, phase, picktype))
@ -1818,8 +2040,8 @@ class PickDlg(QDialog):
# delete the value from corresponding dictionary # delete the value from corresponding dictionary
allpicks[picktype].pop(phase) allpicks[picktype].pop(phase)
# information output # information output
msg = 'Deleted {} pick for phase {}, {}[s] from starttime {}' msg = 'Deleted {} pick for phase {}, at timestamp {} (relative time: {} s)'
print(msg.format(picktype, phase, pick_rel, starttime)) print(msg.format(picktype, phase, starttime+pick_rel, pick_rel))
self.setDirty(True) self.setDirty(True)
def drawPhaseText(self): def drawPhaseText(self):
@ -1834,47 +2056,19 @@ class PickDlg(QDialog):
pass pass
self.phaseText = [] self.phaseText = []
def refreshPhaseText(self): def refreshPhaseText(self, event=None):
self.removePhaseText() self.removePhaseText()
self.drawPhaseText() self.drawPhaseText()
def panPress(self, gui_event):
ax = self.getPlotWidget().axes
if gui_event.inaxes != ax: return
self.cur_xlim = ax.get_xlim()
self.cur_ylim = ax.get_ylim()
self.press = gui_event.xdata, gui_event.ydata
self.xpress, self.ypress = self.press
def panRelease(self, gui_event):
ax = self.getPlotWidget().axes
self.press = None
self.refreshPhaseText()
self.refreshArrivalsText()
ax.figure.canvas.draw()
def panMotion(self, gui_event):
if self.press is None: return
ax = self.getPlotWidget().axes
if gui_event.inaxes != ax: return
dx = gui_event.xdata - self.xpress
dy = gui_event.ydata - self.ypress
self.cur_xlim -= dx
self.cur_ylim -= dy
ax.set_xlim(self.cur_xlim)
ax.set_ylim(self.cur_ylim)
ax.figure.canvas.draw()
def togglePickBlocker(self): def togglePickBlocker(self):
return not self.pick_block return not self.pick_block
def filterWFData(self): def filterWFData(self):
if self.pick_block: if self.pick_block:
return return
self.updateCurrentLimits() self.multicompfig.updateCurrentLimits()
data = self.getWFData().copy() data = self.getWFData().copy()
old_title = self.getPlotWidget().getAxes().get_title() old_title = self.multicompfig.axes[0].get_title()
title = None title = None
phase = self.currentPhase phase = self.currentPhase
filtoptions = None filtoptions = None
@ -1897,7 +2091,7 @@ class PickDlg(QDialog):
title = old_title.replace(', filtered)', ')') title = old_title.replace(', filtered)', ')')
if title is None: if title is None:
title = old_title title = old_title
self.getPlotWidget().plotWFData(wfdata=data, title=title, self.multicompfig.plotWFData(wfdata=data, title=title,
zoomx=self.getXLims(), zoomx=self.getXLims(),
zoomy=self.getYLims()) zoomy=self.getYLims())
self.setPlotLabels() self.setPlotLabels()
@ -1905,87 +2099,45 @@ class PickDlg(QDialog):
self.draw() self.draw()
def resetPlot(self): def resetPlot(self):
self.updateCurrentLimits() self.resetZoom()
data = self.getWFData().copy() data = self.getWFData().copy()
title = self.getPlotWidget().getAxes().get_title() title = self.multicompfig.axes[0].get_title()
self.getPlotWidget().plotWFData(wfdata=data, title=title, self.multicompfig.plotWFData(wfdata=data, title=title,
zoomx=self.getXLims(), zoomx=self.getXLims(),
zoomy=self.getYLims()) zoomy=self.getYLims())
self.setPlotLabels() self.setPlotLabels()
self.drawAllPicks() self.drawAllPicks()
self.draw() self.draw()
def resetZoom(self):
ax = self.multicompfig.axes[0]
self.setXLims(self.multicompfig.getGlobalLimits(ax, 'x'))
self.setYLims(self.multicompfig.getGlobalLimits(ax, 'y'))
def setPlotLabels(self): def setPlotLabels(self):
# get channel labels # get channel labels
pos = self.getPlotWidget().getPlotDict().keys() pos = self.multicompfig.getPlotDict().keys()
labels = [self.getPlotWidget().getPlotDict()[key][1] for key in pos] labels = [self.multicompfig.getPlotDict()[key][1] for key in pos]
ax = self.multicompfig.figure.axes[0]
# set channel labels # set channel labels
self.getPlotWidget().setYTickLabels(pos, labels) self.multicompfig.setYTickLabels(pos, labels)
self.getPlotWidget().setXLims(self.getXLims()) self.multicompfig.setXLims(ax, self.getXLims())
self.getPlotWidget().setYLims(self.getYLims()) self.multicompfig.setYLims(ax, self.getYLims())
def zoom(self): def zoom(self):
if self.zoomAction.isChecked() and self.pick_block: if self.zoomAction.isChecked() and self.pick_block:
self.zoomAction.setChecked(False) self.zoomAction.setChecked(False)
elif self.zoomAction.isChecked(): elif self.zoomAction.isChecked():
self.disconnectPressEvent() self.multicompfig.disconnectEvents()
self.disconnectMotionEvent()
self.disconnectReleaseEvent()
self.disconnectScrollEvent()
self.figToolBar.zoom() self.figToolBar.zoom()
else: else:
self.figToolBar.zoom() self.figToolBar.zoom()
self.cidpress = self.connectPressEvent(self.panPress)
self.cidmotion = self.connectMotionEvent(self.panMotion)
self.cidrelease = self.connectReleaseEvent(self.panRelease)
self.cidscroll = self.connectScrollEvent(self.scrollZoom)
def scrollZoom(self, gui_event, factor=2.):
if not gui_event.xdata or not gui_event.ydata:
return
self.updateCurrentLimits()
if gui_event.button == 'up':
scale_factor = 1 / factor
elif gui_event.button == 'down':
# deal with zoom out
scale_factor = factor
else:
# deal with something that should never happen
scale_factor = 1
print(gui_event.button)
new_xlim = gui_event.xdata - \
scale_factor * (gui_event.xdata - self.getXLims())
new_ylim = gui_event.ydata - \
scale_factor * (gui_event.ydata - self.getYLims())
new_xlim.sort()
global_x = self.getGlobalLimits('x')
global_y = self.getGlobalLimits('y')
new_xlim[0] = max(new_xlim[0], global_x[0])
new_xlim[1] = min(new_xlim[1], global_x[1])
new_ylim.sort()
new_ylim[0] = max(new_ylim[0], global_y[0])
new_ylim[1] = min(new_ylim[1], global_y[1])
self.getPlotWidget().setXLims(new_xlim)
self.getPlotWidget().setYLims(new_ylim)
self.refreshArrivalsText()
self.refreshPhaseText()
self.draw()
def resetZoom(self):
self.getPlotWidget().setXLims(self.getGlobalLimits('x'))
self.getPlotWidget().setYLims(self.getGlobalLimits('y'))
self.draw()
def draw(self): def draw(self):
self.getPlotWidget().draw() self.multicompfig.draw()
def apply(self): def apply(self):
picks = self.getPicks() picks = self.getPicks()
@ -2035,9 +2187,11 @@ class CanvasWidget(QWidget):
def __init__(self, parent, canvas): def __init__(self, parent, canvas):
QtGui.QWidget.__init__(self, parent)#, 1) QtGui.QWidget.__init__(self, parent)#, 1)
canvas = canvas
self.main_layout = QtGui.QVBoxLayout() self.main_layout = QtGui.QVBoxLayout()
self.setLayout(self.main_layout) self.setLayout(self.main_layout)
self.main_layout.addWidget(canvas) self.main_layout.addWidget(canvas)
canvas.setZoomBorders2content()
class MultiEventWidget(QWidget): class MultiEventWidget(QWidget):
@ -2507,7 +2661,7 @@ class TuneAutopicker(QWidget):
[y_bot, y_bot], linewidth=2, color='teal') [y_bot, y_bot], linewidth=2, color='teal')
ax.plot([pick - 0.5, pick + 0.5], ax.plot([pick - 0.5, pick + 0.5],
[y_top, y_top], linewidth=2, color='teal') [y_top, y_top], linewidth=2, color='teal')
ax.legend() ax.legend(loc=1)
def plot_manual_Spick_to_ax(self, ax, pick): def plot_manual_Spick_to_ax(self, ax, pick):
y_top = 0.9 * ax.get_ylim()[1] y_top = 0.9 * ax.get_ylim()[1]
@ -2518,7 +2672,7 @@ class TuneAutopicker(QWidget):
[y_bot, y_bot], linewidth=2, color='magenta') [y_bot, y_bot], linewidth=2, color='magenta')
ax.plot([pick - 0.5, pick + 0.5], ax.plot([pick - 0.5, pick + 0.5],
[y_top, y_top], linewidth=2, color='magenta') [y_top, y_top], linewidth=2, color='magenta')
ax.legend() ax.legend(loc=1)
def fill_tabs(self, event=None, picked=False): def fill_tabs(self, event=None, picked=False):
self.clear_all() self.clear_all()