[reformat] code reformatting with PyCharm
This commit is contained in:
1 parent
4107f0249d
commit
20b31a1c5c
49 files changed
+3255
-3194
No files matched your search
@@ -1,12 +1,11 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
from obspy import UTCDateTime, read_inventory, read
|
||||
from obspy.io.xseed import Parser
|
||||
from pylot.core.util.utils import key_for_set_value, find_in_list, \
|
||||
@@ -116,7 +115,7 @@ def make_time_line(line, datetime):
|
||||
return newline
|
||||
|
||||
|
||||
def evt_head_check(root_dir, out_dir = None):
|
||||
def evt_head_check(root_dir, out_dir=None):
|
||||
"""
|
||||
A function to make sure that an arbitrary number of .gse files have correct values in their header.
|
||||
:param root_dir: a directory leading to the .gse files.
|
||||
@@ -183,7 +182,7 @@ def read_metadata(path_to_inventory):
|
||||
print("Neither dataless-SEED file, inventory-xml file nor "
|
||||
"RESP-file found!")
|
||||
print("!!WRONG CALCULATION OF SOURCE PARAMETERS!!")
|
||||
robj = None,
|
||||
robj = None,
|
||||
elif invtype == 'dless': # prevent multiple read of large dlsv
|
||||
print("Reading metadata information from dataless-SEED file ...")
|
||||
if len(inv[invtype]) == 1:
|
||||
@@ -201,7 +200,7 @@ def restitute_trace(input_tuple):
|
||||
tr, invtype, inobj, unit, force = input_tuple
|
||||
|
||||
remove_trace = False
|
||||
|
||||
|
||||
seed_id = tr.get_id()
|
||||
# check, whether this trace has already been corrected
|
||||
if 'processing' in tr.stats.keys() \
|
||||
@@ -244,14 +243,14 @@ def restitute_trace(input_tuple):
|
||||
remove_trace = True
|
||||
# apply restitution to data
|
||||
print("Correcting instrument at station %s, channel %s" \
|
||||
% (tr.stats.station, tr.stats.channel))
|
||||
% (tr.stats.station, tr.stats.channel))
|
||||
try:
|
||||
if invtype in ['resp', 'dless']:
|
||||
try:
|
||||
tr.simulate(**kwargs)
|
||||
tr.simulate(**kwargs)
|
||||
except ValueError as e:
|
||||
vmsg = '{0}'.format(e)
|
||||
print(vmsg)
|
||||
vmsg = '{0}'.format(e)
|
||||
print(vmsg)
|
||||
|
||||
else:
|
||||
tr.attach_response(inventory)
|
||||
@@ -293,15 +292,15 @@ def restitute_data(data, invtype, inobj, unit='VEL', force=False):
|
||||
for tr in data:
|
||||
input_tuples.append((tr, invtype, inobj, unit, force))
|
||||
data.remove(tr)
|
||||
|
||||
|
||||
pool = gen_Pool()
|
||||
result = pool.map(restitute_trace, input_tuples)
|
||||
pool.close()
|
||||
|
||||
|
||||
for tr, remove_trace in result:
|
||||
if not remove_trace:
|
||||
data.traces.append(tr)
|
||||
|
||||
|
||||
# check if ALL traces could be restituted, take care of large datasets
|
||||
# better try restitution for smaller subsets of data (e.g. station by
|
||||
# station)
|
||||
@@ -343,8 +342,8 @@ def get_prefilt(trace, tlow=(0.5, 0.9), thi=(5., 2.), verbosity=0):
|
||||
trace.stats.station, trace.stats.channel))
|
||||
# get corner frequencies for pre-filtering
|
||||
fny = trace.stats.sampling_rate / 2
|
||||
fc21 = fny - (fny * thi[0]/100.)
|
||||
fc22 = fny - (fny * thi[1]/100.)
|
||||
fc21 = fny - (fny * thi[0] / 100.)
|
||||
fc22 = fny - (fny * thi[1] / 100.)
|
||||
return (tlow[0], tlow[1], fc21, fc22)
|
||||
|
||||
|
||||
|
||||
+13
-11
@@ -9,17 +9,19 @@ Created on Wed Feb 26 12:31:25 2014
|
||||
import os
|
||||
import platform
|
||||
|
||||
from pylot.core.loc import nll
|
||||
from pylot.core.loc import hyposat
|
||||
from pylot.core.io.inputs import PylotParameter
|
||||
from pylot.core.loc import hypo71
|
||||
from pylot.core.loc import hypodd
|
||||
from pylot.core.loc import hyposat
|
||||
from pylot.core.loc import nll
|
||||
from pylot.core.loc import velest
|
||||
from pylot.core.io.inputs import PylotParameter
|
||||
|
||||
|
||||
def readDefaultFilterInformation(fname):
|
||||
pparam = PylotParameter(fname)
|
||||
return readFilterInformation(pparam)
|
||||
|
||||
|
||||
|
||||
def readFilterInformation(pylot_parameter):
|
||||
p_filter = {'filtertype': pylot_parameter['filter_type'][0],
|
||||
'freq': [pylot_parameter['minfreq'][0], pylot_parameter['maxfreq'][0]],
|
||||
@@ -31,6 +33,7 @@ def readFilterInformation(pylot_parameter):
|
||||
'S': s_filter}
|
||||
return filter_information
|
||||
|
||||
|
||||
# determine system dependent path separator
|
||||
system_name = platform.system()
|
||||
if system_name in ["Linux", "Darwin"]:
|
||||
@@ -59,14 +62,14 @@ LOCTOOLS = dict(nll=nll, hyposat=hyposat, velest=velest, hypo71=hypo71, hypodd=h
|
||||
class SetChannelComponents(object):
|
||||
def __init__(self):
|
||||
self.setDefaultCompPosition()
|
||||
|
||||
|
||||
def setDefaultCompPosition(self):
|
||||
# default component order
|
||||
self.compPosition_Map = dict(Z=2, N=1, E=0)
|
||||
self.compName_Map = {'3': 'Z',
|
||||
'1': 'N',
|
||||
'2': 'E'}
|
||||
|
||||
|
||||
def _getCurrentPosition(self, component):
|
||||
for key, value in self.compName_Map.items():
|
||||
if value == component:
|
||||
@@ -85,10 +88,10 @@ class SetChannelComponents(object):
|
||||
def setCompPosition(self, component_alter, component, switch=True):
|
||||
component_alter = str(component_alter)
|
||||
if not component_alter in self.compName_Map.keys():
|
||||
errMsg='setCompPosition: Unrecognized alternative component {}. Expecting one of {}.'
|
||||
errMsg = 'setCompPosition: Unrecognized alternative component {}. Expecting one of {}.'
|
||||
raise ValueError(errMsg.format(component_alter, self.compName_Map.keys()))
|
||||
if not component in self.compPosition_Map.keys():
|
||||
errMsg='setCompPosition: Unrecognized target component {}. Expecting one of {}.'
|
||||
errMsg = 'setCompPosition: Unrecognized target component {}. Expecting one of {}.'
|
||||
raise ValueError(errMsg.format(component, self.compPosition_Map.keys()))
|
||||
print('setCompPosition: set component {} to {}'.format(component_alter, component))
|
||||
if switch:
|
||||
@@ -97,7 +100,7 @@ class SetChannelComponents(object):
|
||||
|
||||
def getCompPosition(self, component):
|
||||
return self._getCurrentPosition(component)[0]
|
||||
|
||||
|
||||
def getPlotPosition(self, component):
|
||||
component = str(component)
|
||||
if component in self.compPosition_Map.keys():
|
||||
@@ -105,6 +108,5 @@ class SetChannelComponents(object):
|
||||
elif component in self.compName_Map.keys():
|
||||
return self.compPosition_Map[self.compName_Map[component]]
|
||||
else:
|
||||
errMsg='getCompPosition: Unrecognized component {}. Expecting one of {} or {}.'
|
||||
errMsg = 'getCompPosition: Unrecognized component {}. Expecting one of {} or {}.'
|
||||
raise ValueError(errMsg.format(component, self.compPosition_Map.keys(), self.compName_Map.keys()))
|
||||
|
||||
@@ -25,5 +25,6 @@ class OverwriteError(IOError):
|
||||
class ParameterError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ProcessingError(RuntimeError):
|
||||
pass
|
||||
+10
-10
@@ -6,7 +6,6 @@ import os
|
||||
from obspy import UTCDateTime
|
||||
from obspy.core.event import Event as ObsPyEvent
|
||||
from obspy.core.event import Origin, ResourceIdentifier
|
||||
|
||||
from pylot.core.io.phases import picks_from_picksdict
|
||||
|
||||
|
||||
@@ -14,10 +13,11 @@ class Event(ObsPyEvent):
|
||||
'''
|
||||
Pickable class derived from ~obspy.core.event.Event containing information on a single event.
|
||||
'''
|
||||
|
||||
def __init__(self, path):
|
||||
self.pylot_id = path.split('/')[-1]
|
||||
# initialize super class
|
||||
super(Event, self).__init__(resource_id=ResourceIdentifier('smi:local/'+self.pylot_id))
|
||||
super(Event, self).__init__(resource_id=ResourceIdentifier('smi:local/' + self.pylot_id))
|
||||
self.path = path
|
||||
self.database = path.split('/')[-2]
|
||||
self.datapath = path.split('/')[-3]
|
||||
@@ -32,13 +32,13 @@ class Event(ObsPyEvent):
|
||||
def get_notes_path(self):
|
||||
notesfile = os.path.join(self.path, 'notes.txt')
|
||||
return notesfile
|
||||
|
||||
|
||||
def get_notes(self):
|
||||
notesfile = self.get_notes_path()
|
||||
if os.path.isfile(notesfile):
|
||||
with open(notesfile) as infile:
|
||||
path = str(infile.readlines()[0].split('\n')[0])
|
||||
text = '[eventInfo: '+path+']'
|
||||
text = '[eventInfo: ' + path + ']'
|
||||
self.addNotes(text)
|
||||
try:
|
||||
datetime = UTCDateTime(path.split('/')[-1])
|
||||
@@ -73,13 +73,13 @@ class Event(ObsPyEvent):
|
||||
'''
|
||||
for station in picks:
|
||||
self.pylot_picks[station] = picks[station]
|
||||
#add ObsPy picks
|
||||
# add ObsPy picks
|
||||
self.picks = picks_from_picksdict(self.pylot_picks)
|
||||
|
||||
|
||||
def addAutopicks(self, autopicks):
|
||||
for station in autopicks:
|
||||
self.pylot_autopicks[station] = autopicks[station]
|
||||
|
||||
|
||||
def setPick(self, station, pick):
|
||||
if pick:
|
||||
self.pylot_picks[station] = pick
|
||||
@@ -89,14 +89,14 @@ class Event(ObsPyEvent):
|
||||
except Exception as e:
|
||||
print('Could not remove pick {} from station {}: {}'.format(pick, station, e))
|
||||
self.picks = picks_from_picksdict(self.pylot_picks)
|
||||
|
||||
|
||||
def setPicks(self, picks):
|
||||
'''
|
||||
set pylot picks and delete and overwrite all existing
|
||||
'''
|
||||
self.pylot_picks = picks
|
||||
self.picks = picks_from_picksdict(self.pylot_picks)
|
||||
|
||||
|
||||
def getPick(self, station):
|
||||
if station in self.pylot_picks.keys():
|
||||
return self.pylot_picks[station]
|
||||
@@ -110,7 +110,7 @@ class Event(ObsPyEvent):
|
||||
|
||||
def setAutopicks(self, autopicks):
|
||||
self.pylot_autopicks = autopicks
|
||||
|
||||
|
||||
def getAutopick(self, station):
|
||||
if station in self.pylot_autopicks.keys():
|
||||
return self.pylot_autopicks[station]
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
from mpl_toolkits.basemap import Basemap
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import obspy
|
||||
from matplotlib import cm
|
||||
from scipy.interpolate import griddata
|
||||
from PySide import QtGui
|
||||
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
|
||||
from PySide import QtCore, QtGui
|
||||
|
||||
from mpl_toolkits.basemap import Basemap
|
||||
from pylot.core.util.widgets import PickDlg
|
||||
from scipy.interpolate import griddata
|
||||
|
||||
plt.interactive(False)
|
||||
|
||||
|
||||
class map_projection(QtGui.QWidget):
|
||||
def __init__(self, parent, figure=None):
|
||||
'''
|
||||
@@ -29,7 +28,7 @@ class map_projection(QtGui.QWidget):
|
||||
self.init_stations()
|
||||
self.init_basemap(resolution='l')
|
||||
self.init_map()
|
||||
#self.show()
|
||||
# self.show()
|
||||
|
||||
def init_map(self):
|
||||
self.init_lat_lon_dimensions()
|
||||
@@ -37,7 +36,7 @@ class map_projection(QtGui.QWidget):
|
||||
self.init_x_y_dimensions()
|
||||
self.connectSignals()
|
||||
self.draw_everything()
|
||||
|
||||
|
||||
def onpick(self, event):
|
||||
ind = event.ind
|
||||
button = event.mouseevent.button
|
||||
@@ -45,7 +44,7 @@ class map_projection(QtGui.QWidget):
|
||||
return
|
||||
data = self._parent.get_data().getWFData()
|
||||
for index in ind:
|
||||
station=str(self.station_names[index].split('.')[-1])
|
||||
station = str(self.station_names[index].split('.')[-1])
|
||||
try:
|
||||
pickDlg = PickDlg(self, parameter=self._parent._inputs,
|
||||
data=data.select(station=station),
|
||||
@@ -90,7 +89,7 @@ class map_projection(QtGui.QWidget):
|
||||
else:
|
||||
self.figure = self._parent.am_figure
|
||||
self.toolbar = self._parent.am_toolbar
|
||||
|
||||
|
||||
self.main_ax = self.figure.add_subplot(111)
|
||||
self.canvas = self.figure.canvas
|
||||
|
||||
@@ -106,29 +105,29 @@ class map_projection(QtGui.QWidget):
|
||||
|
||||
self.comboBox_am = QtGui.QComboBox()
|
||||
self.comboBox_am.insertItem(0, 'auto')
|
||||
self.comboBox_am.insertItem(1, 'manual')
|
||||
|
||||
self.comboBox_am.insertItem(1, 'manual')
|
||||
|
||||
self.top_row.addWidget(QtGui.QLabel('Select a phase: '))
|
||||
self.top_row.addWidget(self.comboBox_phase)
|
||||
self.top_row.setStretch(1,1) #set stretch of item 1 to 1
|
||||
self.top_row.setStretch(1, 1) # set stretch of item 1 to 1
|
||||
|
||||
self.main_box.addWidget(self.canvas)
|
||||
self.main_box.addWidget(self.toolbar)
|
||||
|
||||
|
||||
def init_stations(self):
|
||||
def get_station_names_lat_lon(parser):
|
||||
station_names=[]
|
||||
lat=[]
|
||||
lon=[]
|
||||
station_names = []
|
||||
lat = []
|
||||
lon = []
|
||||
for station in parser.stations:
|
||||
station_name=station[0].station_call_letters
|
||||
network=station[0].network_code
|
||||
station_name = station[0].station_call_letters
|
||||
network = station[0].network_code
|
||||
if not station_name in station_names:
|
||||
station_names.append(network+'.'+station_name)
|
||||
station_names.append(network + '.' + station_name)
|
||||
lat.append(station[0].latitude)
|
||||
lon.append(station[0].longitude)
|
||||
return station_names, lat, lon
|
||||
|
||||
|
||||
station_names, lat, lon = get_station_names_lat_lon(self.parser)
|
||||
self.station_names = station_names
|
||||
self.lat = lat
|
||||
@@ -136,52 +135,53 @@ class map_projection(QtGui.QWidget):
|
||||
|
||||
def init_picks(self):
|
||||
phase = self.comboBox_phase.currentText()
|
||||
|
||||
def get_picks(station_names):
|
||||
picks=[]
|
||||
picks = []
|
||||
for station in station_names:
|
||||
try:
|
||||
station=station.split('.')[-1]
|
||||
station = station.split('.')[-1]
|
||||
picks.append(self.picks_dict[station][phase]['mpp'])
|
||||
except:
|
||||
picks.append(np.nan)
|
||||
return picks
|
||||
|
||||
def get_picks_rel(picks):
|
||||
picks_rel=[]
|
||||
picks_rel = []
|
||||
picks_utc = []
|
||||
for pick in picks:
|
||||
if type(pick) is obspy.core.utcdatetime.UTCDateTime:
|
||||
picks_utc.append(pick)
|
||||
minp = min(picks_utc)
|
||||
for pick in picks:
|
||||
if type(pick) is obspy.core.utcdatetime.UTCDateTime:
|
||||
if type(pick) is obspy.core.utcdatetime.UTCDateTime:
|
||||
pick -= minp
|
||||
picks_rel.append(pick)
|
||||
return picks_rel
|
||||
|
||||
|
||||
self.picks = get_picks(self.station_names)
|
||||
self.picks_rel = get_picks_rel(self.picks)
|
||||
|
||||
def init_picks_active(self):
|
||||
def remove_nan_picks(picks):
|
||||
picks_no_nan=[]
|
||||
picks_no_nan = []
|
||||
for pick in picks:
|
||||
if not np.isnan(pick):
|
||||
picks_no_nan.append(pick)
|
||||
return picks_no_nan
|
||||
|
||||
|
||||
self.picks_no_nan = remove_nan_picks(self.picks_rel)
|
||||
|
||||
def init_stations_active(self):
|
||||
def remove_nan_lat_lon(picks, lat, lon):
|
||||
lat_no_nan=[]
|
||||
lon_no_nan=[]
|
||||
lat_no_nan = []
|
||||
lon_no_nan = []
|
||||
for index, pick in enumerate(picks):
|
||||
if not np.isnan(pick):
|
||||
lat_no_nan.append(lat[index])
|
||||
lon_no_nan.append(lon[index])
|
||||
return lat_no_nan, lon_no_nan
|
||||
|
||||
|
||||
self.lat_no_nan, self.lon_no_nan = remove_nan_lat_lon(self.picks_rel, self.lat, self.lon)
|
||||
|
||||
def init_lat_lon_dimensions(self):
|
||||
@@ -189,7 +189,7 @@ class map_projection(QtGui.QWidget):
|
||||
londim = max(lon) - min(lon)
|
||||
latdim = max(lat) - min(lat)
|
||||
return londim, latdim
|
||||
|
||||
|
||||
self.londim, self.latdim = get_lon_lat_dim(self.lon, self.lat)
|
||||
|
||||
def init_x_y_dimensions(self):
|
||||
@@ -197,30 +197,30 @@ class map_projection(QtGui.QWidget):
|
||||
xdim = max(x) - min(x)
|
||||
ydim = max(y) - min(y)
|
||||
return xdim, ydim
|
||||
|
||||
|
||||
self.x, self.y = self.basemap(self.lon, self.lat)
|
||||
self.xdim, self.ydim = get_x_y_dim(self.x, self.y)
|
||||
|
||||
def init_basemap(self, resolution='l'):
|
||||
#basemap = Basemap(projection=projection, resolution = resolution, ax=self.main_ax)
|
||||
basemap = Basemap(projection='lcc', resolution = resolution, ax=self.main_ax,
|
||||
# basemap = Basemap(projection=projection, resolution = resolution, ax=self.main_ax)
|
||||
basemap = Basemap(projection='lcc', resolution=resolution, ax=self.main_ax,
|
||||
width=5e6, height=2e6,
|
||||
lat_0=(min(self.lat)+max(self.lat))/2.,
|
||||
lon_0=(min(self.lon)+max(self.lon))/2.)
|
||||
|
||||
#basemap.fillcontinents(color=None, lake_color='aqua',zorder=1)
|
||||
basemap.drawmapboundary(zorder=2)#fill_color='darkblue')
|
||||
lat_0=(min(self.lat) + max(self.lat)) / 2.,
|
||||
lon_0=(min(self.lon) + max(self.lon)) / 2.)
|
||||
|
||||
# basemap.fillcontinents(color=None, lake_color='aqua',zorder=1)
|
||||
basemap.drawmapboundary(zorder=2) # fill_color='darkblue')
|
||||
basemap.shadedrelief(zorder=3)
|
||||
basemap.drawcountries(zorder=4)
|
||||
basemap.drawstates(zorder=5)
|
||||
basemap.drawcoastlines(zorder=6)
|
||||
self.basemap = basemap
|
||||
self.figure.tight_layout()
|
||||
|
||||
|
||||
def init_lat_lon_grid(self):
|
||||
def get_lat_lon_axis(lat, lon):
|
||||
steplat = (max(lat)-min(lat))/250
|
||||
steplon = (max(lon)-min(lon))/250
|
||||
steplat = (max(lat) - min(lat)) / 250
|
||||
steplon = (max(lon) - min(lon)) / 250
|
||||
|
||||
lataxis = np.arange(min(lat), max(lat), steplat)
|
||||
lonaxis = np.arange(min(lon), max(lon), steplon)
|
||||
@@ -235,7 +235,8 @@ class map_projection(QtGui.QWidget):
|
||||
|
||||
def init_picksgrid(self):
|
||||
self.picksgrid_no_nan = griddata((self.lat_no_nan, self.lon_no_nan),
|
||||
self.picks_no_nan, (self.latgrid, self.longrid), method='linear') ##################
|
||||
self.picks_no_nan, (self.latgrid, self.longrid),
|
||||
method='linear') ##################
|
||||
|
||||
def draw_contour_filled(self, nlevel='50'):
|
||||
levels = np.linspace(min(self.picks_no_nan), max(self.picks_no_nan), nlevel)
|
||||
@@ -244,7 +245,7 @@ class map_projection(QtGui.QWidget):
|
||||
|
||||
def scatter_all_stations(self):
|
||||
self.sc = self.basemap.scatter(self.lon, self.lat, s=50, facecolor='none', latlon=True,
|
||||
zorder=10, picker=True, edgecolor='m', label='Not Picked')
|
||||
zorder=10, picker=True, edgecolor='m', label='Not Picked')
|
||||
self.cid = self.canvas.mpl_connect('pick_event', self.onpick)
|
||||
if self.eventLoc:
|
||||
lat, lon = self.eventLoc
|
||||
@@ -255,11 +256,11 @@ class map_projection(QtGui.QWidget):
|
||||
lon = self.lon_no_nan
|
||||
lat = self.lat_no_nan
|
||||
|
||||
#workaround because of an issue with latlon transformation of arrays with len <3
|
||||
# workaround because of an issue with latlon transformation of arrays with len <3
|
||||
if len(lon) <= 2 and len(lat) <= 2:
|
||||
self.sc_picked = self.basemap.scatter(lon[0], lat[0], s=50, facecolor='white',
|
||||
c=self.picks_no_nan[0], latlon=True, zorder=11, label='Picked')
|
||||
if len(lon) == 2 and len(lat) == 2:
|
||||
if len(lon) == 2 and len(lat) == 2:
|
||||
self.sc_picked = self.basemap.scatter(lon[1], lat[1], s=50, facecolor='white',
|
||||
c=self.picks_no_nan[1], latlon=True, zorder=11)
|
||||
else:
|
||||
@@ -267,11 +268,11 @@ class map_projection(QtGui.QWidget):
|
||||
c=self.picks_no_nan, latlon=True, zorder=11, label='Picked')
|
||||
|
||||
def annotate_ax(self):
|
||||
self.annotations=[]
|
||||
self.annotations = []
|
||||
for index, name in enumerate(self.station_names):
|
||||
self.annotations.append(self.main_ax.annotate(' %s' % name, xy=(self.x[index], self.y[index]),
|
||||
fontsize='x-small', color='white', zorder=12))
|
||||
self.legend=self.main_ax.legend()
|
||||
self.legend = self.main_ax.legend()
|
||||
|
||||
def add_cbar(self, label):
|
||||
cbar = self.main_ax.figure.colorbar(self.sc_picked, fraction=0.025)
|
||||
@@ -307,19 +308,19 @@ class map_projection(QtGui.QWidget):
|
||||
def remove_drawings(self):
|
||||
if hasattr(self, 'sc_picked'):
|
||||
self.sc_picked.remove()
|
||||
del(self.sc_picked)
|
||||
del (self.sc_picked)
|
||||
if hasattr(self, 'sc_event'):
|
||||
self.sc_event.remove()
|
||||
del(self.sc_event)
|
||||
del (self.sc_event)
|
||||
if hasattr(self, 'cbar'):
|
||||
self.cbar.remove()
|
||||
del(self.cbar)
|
||||
del (self.cbar)
|
||||
if hasattr(self, 'contourf'):
|
||||
self.remove_contourf()
|
||||
del(self.contourf)
|
||||
del (self.contourf)
|
||||
if hasattr(self, 'cid'):
|
||||
self.canvas.mpl_disconnect(self.cid)
|
||||
del(self.cid)
|
||||
del (self.cid)
|
||||
try:
|
||||
self.sc.remove()
|
||||
except Exception as e:
|
||||
@@ -343,18 +344,18 @@ class map_projection(QtGui.QWidget):
|
||||
xlim = map.ax.get_xlim()
|
||||
ylim = map.ax.get_ylim()
|
||||
x, y = event.xdata, event.ydata
|
||||
zoom = {'up': 1./2.,
|
||||
zoom = {'up': 1. / 2.,
|
||||
'down': 2.}
|
||||
|
||||
|
||||
if not event.xdata or not event.ydata:
|
||||
return
|
||||
|
||||
|
||||
if event.button in zoom:
|
||||
factor = zoom[event.button]
|
||||
xdiff = (xlim[1]-xlim[0])*factor
|
||||
xdiff = (xlim[1] - xlim[0]) * factor
|
||||
xl = x - 0.5 * xdiff
|
||||
xr = x + 0.5 * xdiff
|
||||
ydiff = (ylim[1]-ylim[0])*factor
|
||||
ydiff = (ylim[1] - ylim[0]) * factor
|
||||
yb = y - 0.5 * ydiff
|
||||
yt = y + 0.5 * ydiff
|
||||
|
||||
@@ -364,10 +365,8 @@ class map_projection(QtGui.QWidget):
|
||||
map.ax.set_xlim(xl, xr)
|
||||
map.ax.set_ylim(yb, yt)
|
||||
map.ax.figure.canvas.draw()
|
||||
|
||||
|
||||
def _warn(self, message):
|
||||
self.qmb = QtGui.QMessageBox(QtGui.QMessageBox.Icon.Warning,
|
||||
'Warning', message)
|
||||
self.qmb.show()
|
||||
|
||||
|
||||
self.qmb.show()
|
||||
+12
-12
@@ -2,20 +2,23 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
from obspy import UTCDateTime
|
||||
from pylot.core.util.utils import fit_curve, find_nearest, clims
|
||||
from pylot.core.util.utils import fit_curve, clims
|
||||
from pylot.core.util.version import get_git_version as _getVersionString
|
||||
|
||||
__version__ = _getVersionString()
|
||||
__author__ = 'sebastianw'
|
||||
|
||||
|
||||
def create_axis(x0, incr, npts):
|
||||
ax = np.zeros(npts)
|
||||
for i in range(npts):
|
||||
ax[i] = x0 + incr * i
|
||||
return ax
|
||||
|
||||
|
||||
def gauss_parameter(te, tm, tl, eta):
|
||||
'''
|
||||
takes three onset times and returns the parameters sig1, sig2, a1 and a2
|
||||
@@ -79,9 +82,9 @@ def gauss_branches(k, param_tuple):
|
||||
:returns fun_vals: list with function values along axes x
|
||||
'''
|
||||
|
||||
#python 3 workaround
|
||||
# python 3 workaround
|
||||
mu, sig1, sig2, a1, a2 = param_tuple
|
||||
|
||||
|
||||
def _func(k, mu, sig1, sig2, a1, a2):
|
||||
if k < mu:
|
||||
rval = a1 * 1 / (np.sqrt(2 * np.pi) * sig1) * np.exp(-((k - mu) / sig1) ** 2 / 2)
|
||||
@@ -110,9 +113,9 @@ def exp_branches(k, param_tuple):
|
||||
:returns fun_vals: list with function values along axes x:
|
||||
'''
|
||||
|
||||
#python 3 workaround
|
||||
# python 3 workaround
|
||||
mu, sig1, sig2, a = param_tuple
|
||||
|
||||
|
||||
def _func(k, mu, sig1, sig2, a):
|
||||
mu = float(mu)
|
||||
if k < mu:
|
||||
@@ -313,14 +316,14 @@ class ProbabilityDensityFunction(object):
|
||||
:return float: rval
|
||||
'''
|
||||
|
||||
#rval = 0
|
||||
#for x in self.axis:
|
||||
# rval = 0
|
||||
# for x in self.axis:
|
||||
# rval += x * self.data(x)
|
||||
rval = self.mu
|
||||
# Not sure about this! That might not be the barycentre.
|
||||
# However, for std calculation (next function)
|
||||
# self.mu is also used!! (LK, 02/2017)
|
||||
return rval
|
||||
return rval
|
||||
|
||||
def standard_deviation(self):
|
||||
mu = self.mu
|
||||
@@ -394,7 +397,6 @@ class ProbabilityDensityFunction(object):
|
||||
qu = self.quantile(1 - prob_value)
|
||||
return qu - ql
|
||||
|
||||
|
||||
def quantile_dist_frac(self, x):
|
||||
"""
|
||||
takes a probability value and returns the fraction of two
|
||||
@@ -411,8 +413,7 @@ class ProbabilityDensityFunction(object):
|
||||
"""
|
||||
if x <= 0 or x >= 0.25:
|
||||
raise ValueError('Value out of range.')
|
||||
return self.quantile_distance(0.5-x)/self.quantile_distance(x)
|
||||
|
||||
return self.quantile_distance(0.5 - x) / self.quantile_distance(x)
|
||||
|
||||
def plot(self, label=None):
|
||||
import matplotlib.pyplot as plt
|
||||
@@ -486,4 +487,3 @@ class ProbabilityDensityFunction(object):
|
||||
x0, npts = self.commonlimits(incr, other)
|
||||
|
||||
return x0, incr, npts
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def create_bin_list(l_boundary, u_boundary, nbins=100):
|
||||
"""
|
||||
takes two boundaries and a number of bins and creates a list of bins for
|
||||
@@ -54,4 +55,4 @@ def histplot(array, binlist, xlab='Values',
|
||||
if fnout:
|
||||
plt.savefig(fnout)
|
||||
else:
|
||||
plt.show()
|
||||
plt.show()
|
||||
+18
-14
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import sys, os, traceback
|
||||
import multiprocessing
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
from PySide.QtCore import QThread, Signal, Qt, Slot, QRunnable, QObject
|
||||
from PySide.QtGui import QDialog, QProgressBar, QLabel, QHBoxLayout, QPushButton
|
||||
|
||||
@@ -42,7 +45,7 @@ class AutoPickThread(QThread):
|
||||
|
||||
class Thread(QThread):
|
||||
message = Signal(str)
|
||||
|
||||
|
||||
def __init__(self, parent, func, arg=None, progressText=None, pb_widget=None, redirect_stdout=False):
|
||||
QThread.__init__(self, parent)
|
||||
self.func = func
|
||||
@@ -55,7 +58,7 @@ class Thread(QThread):
|
||||
|
||||
def run(self):
|
||||
if self.redirect_stdout:
|
||||
sys.stdout = self
|
||||
sys.stdout = self
|
||||
try:
|
||||
if self.arg:
|
||||
self.data = self.func(self.arg)
|
||||
@@ -68,7 +71,7 @@ class Thread(QThread):
|
||||
exc_type, exc_obj, exc_tb = sys.exc_info()
|
||||
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
|
||||
print('Exception: {}, file: {}, line: {}'.format(exc_type, fname, exc_tb.tb_lineno))
|
||||
sys.stdout = sys.__stdout__
|
||||
sys.stdout = sys.__stdout__
|
||||
|
||||
def __del__(self):
|
||||
self.wait()
|
||||
@@ -79,7 +82,7 @@ class Thread(QThread):
|
||||
# generate widget if not given in init
|
||||
if not self.pb_widget:
|
||||
self.pb_widget = QDialog(self.parent())
|
||||
self.pb_widget.setWindowFlags(Qt.SplashScreen)
|
||||
self.pb_widget.setWindowFlags(Qt.SplashScreen)
|
||||
self.pb_widget.setModal(True)
|
||||
|
||||
# add button
|
||||
@@ -109,6 +112,7 @@ class Worker(QRunnable):
|
||||
'''
|
||||
|
||||
'''
|
||||
|
||||
def __init__(self, fun, args,
|
||||
progressText=None,
|
||||
pb_widget=None,
|
||||
@@ -116,7 +120,7 @@ class Worker(QRunnable):
|
||||
super(Worker, self).__init__()
|
||||
self.fun = fun
|
||||
self.args = args
|
||||
#self.kwargs = kwargs
|
||||
# self.kwargs = kwargs
|
||||
self.signals = WorkerSignals()
|
||||
self.progressText = progressText
|
||||
self.pb_widget = pb_widget
|
||||
@@ -131,9 +135,9 @@ class Worker(QRunnable):
|
||||
result = self.fun(self.args)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
exctype, value = sys.exc_info ()[:2]
|
||||
exctype, value = sys.exc_info()[:2]
|
||||
print(exctype, value, traceback.format_exc())
|
||||
#self.signals.error.emit ((exctype, value, traceback.format_exc ()))
|
||||
# self.signals.error.emit ((exctype, value, traceback.format_exc ()))
|
||||
else:
|
||||
self.signals.result.emit(result)
|
||||
finally:
|
||||
@@ -157,7 +161,7 @@ class WorkerSignals(QObject):
|
||||
|
||||
class MultiThread(QThread):
|
||||
finished = Signal(str)
|
||||
message = Signal(str)
|
||||
message = Signal(str)
|
||||
|
||||
def __init__(self, parent, func, args, ncores=1,
|
||||
progressText=None, pb_widget=None, redirect_stdout=False):
|
||||
@@ -170,16 +174,16 @@ class MultiThread(QThread):
|
||||
self.redirect_stdout = redirect_stdout
|
||||
self.finished.connect(self.hideProgressbar)
|
||||
self.showProgressbar()
|
||||
|
||||
|
||||
def run(self):
|
||||
if self.redirect_stdout:
|
||||
sys.stdout = self
|
||||
sys.stdout = self
|
||||
try:
|
||||
if not self.ncores:
|
||||
self.ncores = multiprocessing.cpu_count()
|
||||
pool = multiprocessing.Pool(self.ncores)
|
||||
self.data = pool.map_async(self.func, self.args, callback=self.emitDone)
|
||||
#self.data = pool.apply_async(self.func, self.shotlist, callback=self.emitDone) #emit each time returned
|
||||
# self.data = pool.apply_async(self.func, self.shotlist, callback=self.emitDone) #emit each time returned
|
||||
pool.close()
|
||||
self._executed = True
|
||||
except Exception as e:
|
||||
@@ -188,7 +192,7 @@ class MultiThread(QThread):
|
||||
exc_type, exc_obj, exc_tb = sys.exc_info()
|
||||
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
|
||||
print('Exception: {}, file: {}, line: {}'.format(exc_type, fname, exc_tb.tb_lineno))
|
||||
sys.stdout = sys.__stdout__
|
||||
sys.stdout = sys.__stdout__
|
||||
|
||||
def __del__(self):
|
||||
self.wait()
|
||||
@@ -197,7 +201,7 @@ class MultiThread(QThread):
|
||||
if self.progressText:
|
||||
if not self.pb_widget:
|
||||
self.pb_widget = QDialog(self.parent())
|
||||
self.pb_widget.setWindowFlags(Qt.SplashScreen)
|
||||
self.pb_widget.setWindowFlags(Qt.SplashScreen)
|
||||
self.pb_widget.setModal(True)
|
||||
hl = QHBoxLayout()
|
||||
pb = QProgressBar()
|
||||
|
||||
@@ -2,26 +2,28 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import hashlib
|
||||
import numpy as np
|
||||
from scipy.interpolate import splrep, splev
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import warnings
|
||||
import subprocess
|
||||
|
||||
import numpy as np
|
||||
from obspy import UTCDateTime, read
|
||||
from pylot.core.io.inputs import PylotParameter
|
||||
from scipy.interpolate import splrep, splev
|
||||
|
||||
|
||||
|
||||
def _pickle_method(m):
|
||||
if m.im_self is None:
|
||||
return getattr, (m.im_class, m.im_func.func_name)
|
||||
else:
|
||||
return getattr, (m.im_self, m.im_func.func_name)
|
||||
|
||||
|
||||
def fit_curve(x, y):
|
||||
return splev, splrep(x, y)
|
||||
|
||||
|
||||
def getindexbounds(f, eta):
|
||||
mi = f.argmax()
|
||||
m = max(f)
|
||||
@@ -34,9 +36,9 @@ def getindexbounds(f, eta):
|
||||
def gen_Pool(ncores='max'):
|
||||
import multiprocessing
|
||||
|
||||
if ncores=='max':
|
||||
ncores=multiprocessing.cpu_count()
|
||||
|
||||
if ncores == 'max':
|
||||
ncores = multiprocessing.cpu_count()
|
||||
|
||||
pool = multiprocessing.Pool(ncores)
|
||||
return pool
|
||||
|
||||
@@ -106,6 +108,7 @@ def findComboBoxIndex(combo_box, val):
|
||||
"""
|
||||
return combo_box.findText(val) if combo_box.findText(val) is not -1 else 0
|
||||
|
||||
|
||||
def find_in_list(list, str):
|
||||
"""
|
||||
takes a list of strings and a string and returns the first list item
|
||||
@@ -135,6 +138,7 @@ def find_in_list(list, str):
|
||||
return rlist[0]
|
||||
return None
|
||||
|
||||
|
||||
def find_nearest(array, value):
|
||||
'''
|
||||
function find_nearest takes an array and a value and returns the
|
||||
@@ -181,12 +185,14 @@ def fnConstructor(s):
|
||||
fn = '_' + fn
|
||||
return fn
|
||||
|
||||
|
||||
def real_None(value):
|
||||
if value == 'None':
|
||||
return None
|
||||
else:
|
||||
return value
|
||||
|
||||
|
||||
def four_digits(year):
|
||||
"""
|
||||
takes a two digit year integer and returns the correct four digit equivalent
|
||||
@@ -307,6 +313,7 @@ def getPatternLine(fn, pattern):
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def is_executable(fn):
|
||||
"""
|
||||
takes a filename and returns True if the file is executable on the system
|
||||
@@ -492,6 +499,7 @@ def runProgram(cmd, parameter=None):
|
||||
|
||||
subprocess.check_output('{} | tee /dev/stderr'.format(cmd), shell=True)
|
||||
|
||||
|
||||
def which(program, infile=None):
|
||||
"""
|
||||
takes a program name and returns the full path to the executable or None
|
||||
@@ -510,7 +518,7 @@ def which(program, infile=None):
|
||||
bpath = os.path.join(os.path.expanduser('~'), '.pylot', 'pylot.in')
|
||||
else:
|
||||
bpath = os.path.join(os.path.expanduser('~'), '.pylot', infile)
|
||||
|
||||
|
||||
if os.path.exists(bpath):
|
||||
nllocpath = ":" + PylotParameter(bpath).get('nllocbin')
|
||||
os.environ['PATH'] += nllocpath
|
||||
@@ -538,6 +546,7 @@ def which(program, infile=None):
|
||||
|
||||
return None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
|
||||
+1781
-1780
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user