WALL-E: Einmal aufräumen und zurück!

This commit is contained in:
Sebastian Wehling-Benatelli 2016-03-30 08:14:58 +02:00
parent a2640e3126
commit d7cfd0d176
29 changed files with 1285 additions and 1105 deletions

View File

@ -1,6 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import print_function
import os import os
import argparse import argparse
import glob import glob
@ -94,7 +95,6 @@ def autoPyLoT(inputfile):
print("!!No source parameter estimation possible!!") print("!!No source parameter estimation possible!!")
print(" !!! ") print(" !!! ")
# multiple event processing # multiple event processing
# read each event in database # read each event in database
datapath = datastructure.expandDataPath() datapath = datastructure.expandDataPath()
@ -218,8 +218,8 @@ def autoPyLoT(inputfile):
# single event processing # single event processing
else: else:
data.setWFData(glob.glob(os.path.join(datapath, parameter.getParam('eventID'), '*'))) data.setWFData(glob.glob(os.path.join(datapath, parameter.getParam('eventID'), '*')))
print("Working on event "), parameter.getParam('eventID') print("Working on event {0}".format(parameter.getParam('eventID')))
print data print(data)
wfdat = data.getWFData() # all available streams wfdat = data.getWFData() # all available streams
########################################################## ##########################################################
@ -338,6 +338,7 @@ def autoPyLoT(inputfile):
************************************'''.format(version=_getVersionString()) ************************************'''.format(version=_getVersionString())
print(endsp) print(endsp)
if __name__ == "__main__": if __name__ == "__main__":
# parse arguments # parse arguments
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(

View File

@ -1,5 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8 # encoding: utf-8
from __future__ import print_function
""" """
makePyLoT -- build and install PyLoT makePyLoT -- build and install PyLoT
@ -123,7 +125,7 @@ USAGE
except KeyboardInterrupt: except KeyboardInterrupt:
cleanUp(verbose) cleanUp(verbose)
return 0 return 0
except Exception, e: except Exception as e:
if DEBUG or TESTRUN: if DEBUG or TESTRUN:
raise e raise e
indent = len(program_name) * " " indent = len(program_name) * " "
@ -139,7 +141,7 @@ def buildPyLoT(verbosity=None):
"\n" "\n"
" Current working directory: {1}\n" " Current working directory: {1}\n"
).format(system, os.getcwd()) ).format(system, os.getcwd())
print msg print(msg)
if system.startswith(('win', 'microsoft')): if system.startswith(('win', 'microsoft')):
raise CLIError( raise CLIError(
"building on Windows system not tested yet; implementation pending") "building on Windows system not tested yet; implementation pending")

View File

@ -4,6 +4,7 @@ import numpy as np
from pylot.core.active import seismicshot from pylot.core.active import seismicshot
from pylot.core.active.surveyUtils import cleanUp from pylot.core.active.surveyUtils import cleanUp
class Survey(object): class Survey(object):
def __init__(self, path, sourcefile, receiverfile, useDefaultParas=False): def __init__(self, path, sourcefile, receiverfile, useDefaultParas=False):
''' '''
@ -70,7 +71,8 @@ class Survey(object):
Removes traces that do not exist in the dataset for any reason. Removes traces that do not exist in the dataset for any reason.
''' '''
filename = 'updateShots.out' filename = 'updateShots.out'
count = 0; countTraces = 0 count = 0;
countTraces = 0
for shot in self.data.values(): for shot in self.data.values():
del_traceIDs = shot.updateTraceList() del_traceIDs = shot.updateTraceList()
if len(del_traceIDs) > 0: if len(del_traceIDs) > 0:
@ -135,7 +137,10 @@ class Survey(object):
def plotDiffs(self): def plotDiffs(self):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
diffs = []; dists = []; mpicks = []; picks = [] diffs = [];
dists = [];
mpicks = [];
picks = []
diffsDic = self.getDiffsFromManual() diffsDic = self.getDiffsFromManual()
for shot in self.data.values(): for shot in self.data.values():
for traceID in shot.getTraceIDlist(): for traceID in shot.getTraceIDlist():
@ -181,10 +186,12 @@ class Survey(object):
''' '''
from datetime import datetime from datetime import datetime
starttime = datetime.now() starttime = datetime.now()
count = 0; tpicksum = starttime - starttime count = 0;
tpicksum = starttime - starttime
for shot in self.data.values(): for shot in self.data.values():
tstartpick = datetime.now(); count += 1 tstartpick = datetime.now();
count += 1
for traceID in shot.getTraceIDlist(): for traceID in shot.getTraceIDlist():
distance = shot.getDistance(traceID) # receive distance distance = shot.getDistance(traceID) # receive distance
@ -211,7 +218,8 @@ class Survey(object):
if shot.getSNR(traceID)[0] > 1: if shot.getSNR(traceID)[0] > 1:
shot.setEarllatepick(traceID) shot.setEarllatepick(traceID)
tpicksum += (datetime.now() - tstartpick); tpick = tpicksum/count tpicksum += (datetime.now() - tstartpick);
tpick = tpicksum / count
tremain = (tpick * (len(self.getShotDict()) - count)) tremain = (tpick * (len(self.getShotDict()) - count))
tend = datetime.now() + tremain tend = datetime.now() + tremain
progress = float(count) / float(len(self.getShotDict())) * 100 progress = float(count) / float(len(self.getShotDict())) * 100
@ -339,7 +347,9 @@ class Survey(object):
count = 0 count = 0
fmtomo_factor = 1000 # transforming [m/s] -> [km/s] fmtomo_factor = 1000 # transforming [m/s] -> [km/s]
LatAll = []; LonAll = []; DepthAll = [] LatAll = [];
LonAll = [];
DepthAll = []
srcfile = open(directory + '/' + sourcefile, 'w') srcfile = open(directory + '/' + sourcefile, 'w')
srcfile.writelines('%10s\n' % len(self.data)) # number of sources srcfile.writelines('%10s\n' % len(self.data)) # number of sources
for shotnumber in self.getShotlist(): for shotnumber in self.getShotlist():
@ -347,7 +357,9 @@ class Survey(object):
ttfilename = str(shotnumber) + ttFileExtension ttfilename = str(shotnumber) + ttFileExtension
(x, y, z) = shot.getSrcLoc() # getSrcLoc returns (x, y, z) (x, y, z) = shot.getSrcLoc() # getSrcLoc returns (x, y, z)
srcfile.writelines('%10s %10s %10s\n' % (getAngle(y), getAngle(x), (-1) * z)) # lat, lon, depth srcfile.writelines('%10s %10s %10s\n' % (getAngle(y), getAngle(x), (-1) * z)) # lat, lon, depth
LatAll.append(getAngle(y)); LonAll.append(getAngle(x)); DepthAll.append((-1)*z) LatAll.append(getAngle(y));
LonAll.append(getAngle(x));
DepthAll.append((-1) * z)
srcfile.writelines('%10s\n' % 1) # srcfile.writelines('%10s\n' % 1) #
srcfile.writelines('%10s %10s %10s\n' % (1, 1, ttfilename)) srcfile.writelines('%10s %10s %10s\n' % (1, 1, ttfilename))
ttfile = open(directory + '/' + ttfilename, 'w') ttfile = open(directory + '/' + ttfilename, 'w')
@ -360,7 +372,9 @@ class Survey(object):
delta = shot.getSymmetricPickError(traceID) * fmtomo_factor delta = shot.getSymmetricPickError(traceID) * fmtomo_factor
(x, y, z) = shot.getRecLoc(traceID) (x, y, z) = shot.getRecLoc(traceID)
ttfile.writelines('%20s %20s %20s %10s %10s\n' % (getAngle(y), getAngle(x), (-1) * z, pick, delta)) ttfile.writelines('%20s %20s %20s %10s %10s\n' % (getAngle(y), getAngle(x), (-1) * z, pick, delta))
LatAll.append(getAngle(y)); LonAll.append(getAngle(x)); DepthAll.append((-1)*z) LatAll.append(getAngle(y));
LonAll.append(getAngle(x));
DepthAll.append((-1) * z)
count += 1 count += 1
ttfile.close() ttfile.close()
srcfile.close() srcfile.close()

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import numpy as np import numpy as np
def vgrids2VTK(inputfile='vgrids.in', outputfile='vgrids.vtk', absOrRel='abs', inputfileref='vgridsref.in'): def vgrids2VTK(inputfile='vgrids.in', outputfile='vgrids.vtk', absOrRel='abs', inputfileref='vgridsref.in'):
''' '''
Generate a vtk-file readable by e.g. paraview from FMTOMO output vgrids.in Generate a vtk-file readable by e.g. paraview from FMTOMO output vgrids.in
@ -8,6 +9,7 @@ def vgrids2VTK(inputfile = 'vgrids.in', outputfile = 'vgrids.vtk', absOrRel = 'a
:param: absOrRel, can be "abs" or "rel" for absolute or relative velocities. if "rel" inputfileref must be given :param: absOrRel, can be "abs" or "rel" for absolute or relative velocities. if "rel" inputfileref must be given
:type: str :type: str
''' '''
def getDistance(angle): def getDistance(angle):
PI = np.pi PI = np.pi
R = 6371. R = 6371.
@ -53,7 +55,8 @@ def vgrids2VTK(inputfile = 'vgrids.in', outputfile = 'vgrids.vtk', absOrRel = 'a
''' '''
Reads in velocity from vgrids file and returns a list containing all values in the same order Reads in velocity from vgrids file and returns a list containing all values in the same order
''' '''
vel = []; count = 0 vel = [];
count = 0
fin = open(filename, 'r') fin = open(filename, 'r')
vglines = fin.readlines() vglines = fin.readlines()
@ -74,7 +77,9 @@ def vgrids2VTK(inputfile = 'vgrids.in', outputfile = 'vgrids.vtk', absOrRel = 'a
sR, sTheta, sPhi = readStartpoints(inputfile) sR, sTheta, sPhi = readStartpoints(inputfile)
vel = readVelocity(inputfile) vel = readVelocity(inputfile)
nX = nPhi; nY = nTheta; nZ = nR nX = nPhi;
nY = nTheta;
nZ = nR
sZ = sR - R sZ = sR - R
sX = getDistance(np.rad2deg(sPhi)) sX = getDistance(np.rad2deg(sPhi))
@ -137,6 +142,7 @@ def vgrids2VTK(inputfile = 'vgrids.in', outputfile = 'vgrids.vtk', absOrRel = 'a
print("Wrote velocity grid for %d points to file: %s" % (nPoints, outputfile)) print("Wrote velocity grid for %d points to file: %s" % (nPoints, outputfile))
return return
def rays2VTK(fnin, fdirout='./vtk_files/', nthPoint=50): def rays2VTK(fnin, fdirout='./vtk_files/', nthPoint=50):
''' '''
Writes VTK file(s) for FMTOMO rays from rays.dat. There is one file created for each ray. Writes VTK file(s) for FMTOMO rays from rays.dat. There is one file created for each ray.
@ -147,6 +153,7 @@ def rays2VTK(fnin, fdirout = './vtk_files/', nthPoint = 50):
:param: nthPoint, plot every nth point of the ray :param: nthPoint, plot every nth point of the ray
:type: integer :type: integer
''' '''
def getDistance(angle): def getDistance(angle):
PI = np.pi PI = np.pi
R = 6371. R = 6371.
@ -178,7 +185,8 @@ def rays2VTK(fnin, fdirout = './vtk_files/', nthPoint = 50):
for index in range(nRayPoints): for index in range(nRayPoints):
if index % nthPoint is 0 or index == (nRayPoints - 1): if index % nthPoint is 0 or index == (nRayPoints - 1):
rad, lat, lon = infile.readline().split() rad, lat, lon = infile.readline().split()
rays[shotnumber][raynumber].append([getDistance(np.rad2deg(float(lon))), getDistance(np.rad2deg(float(lat))), float(rad) - R]) rays[shotnumber][raynumber].append(
[getDistance(np.rad2deg(float(lon))), getDistance(np.rad2deg(float(lat))), float(rad) - R])
else: else:
dummy = infile.readline() dummy = infile.readline()
@ -233,4 +241,3 @@ def rays2VTK(fnin, fdirout = './vtk_files/', nthPoint = 50):
# outfile.close() # outfile.close()
# print("Wrote velocity grid for %d points to file: %s" %(nPoints, outputfile)) # print("Wrote velocity grid for %d points to file: %s" %(nPoints, outputfile))

View File

@ -2,6 +2,7 @@
import sys import sys
import numpy as np import numpy as np
def vgrids2VTK(inputfile='vgrids.in', outputfile='vgrids.vtk', absOrRel='abs', inputfileref='vgridsref.in'): def vgrids2VTK(inputfile='vgrids.in', outputfile='vgrids.vtk', absOrRel='abs', inputfileref='vgridsref.in'):
''' '''
Generate a vtk-file readable by e.g. paraview from FMTOMO output vgrids.in Generate a vtk-file readable by e.g. paraview from FMTOMO output vgrids.in
@ -19,7 +20,9 @@ def vgrids2VTK(inputfile = 'vgrids.in', outputfile = 'vgrids.vtk', absOrRel = 'a
nPoints = nR * nTheta * nPhi nPoints = nR * nTheta * nPhi
nX = nPhi; nY = nTheta; nZ = nR nX = nPhi;
nY = nTheta;
nZ = nR
sZ = sR - R sZ = sR - R
sX = _getDistance(sPhi) sX = _getDistance(sPhi)
@ -79,6 +82,7 @@ def vgrids2VTK(inputfile = 'vgrids.in', outputfile = 'vgrids.vtk', absOrRel = 'a
print("Wrote velocity grid for %d points to file: %s" % (nPoints, outputfile)) print("Wrote velocity grid for %d points to file: %s" % (nPoints, outputfile))
return return
def rays2VTK(fnin, fdirout='./vtk_files/', nthPoint=50): def rays2VTK(fnin, fdirout='./vtk_files/', nthPoint=50):
''' '''
Writes VTK file(s) for FMTOMO rays from rays.dat Writes VTK file(s) for FMTOMO rays from rays.dat
@ -110,7 +114,8 @@ def rays2VTK(fnin, fdirout = './vtk_files/', nthPoint = 50):
for index in range(nRayPoints): for index in range(nRayPoints):
if index % nthPoint is 0 or index == (nRayPoints - 1): if index % nthPoint is 0 or index == (nRayPoints - 1):
rad, lat, lon = infile.readline().split() rad, lat, lon = infile.readline().split()
rays[shotnumber][raynumber].append([_getDistance(np.rad2deg(float(lon))), _getDistance(np.rad2deg(float(lat))), float(rad) - R]) rays[shotnumber][raynumber].append(
[_getDistance(np.rad2deg(float(lon))), _getDistance(np.rad2deg(float(lat))), float(rad) - R])
else: else:
dummy = infile.readline() dummy = infile.readline()
@ -152,6 +157,7 @@ def rays2VTK(fnin, fdirout = './vtk_files/', nthPoint = 50):
count += 1 count += 1
outfile.writelines('\n') outfile.writelines('\n')
def _readVgrid(filename): def _readVgrid(filename):
def readNumberOfPoints(filename): def readNumberOfPoints(filename):
fin = open(filename, 'r') fin = open(filename, 'r')
@ -192,7 +198,8 @@ def _readVgrid(filename):
''' '''
Reads in velocity from vgrids file and returns a list containing all values in the same order Reads in velocity from vgrids file and returns a list containing all values in the same order
''' '''
vel = []; count = 0 vel = [];
count = 0
fin = open(filename, 'r') fin = open(filename, 'r')
vglines = fin.readlines() vglines = fin.readlines()
@ -218,6 +225,7 @@ def _readVgrid(filename):
start = (sR, sTheta, sPhi) start = (sR, sTheta, sPhi)
return number, delta, start, vel return number, delta, start, vel
def _generateGrids(number, delta, start): def _generateGrids(number, delta, start):
nR, nTheta, nPhi = number nR, nTheta, nPhi = number
dR, dTheta, dPhi = delta dR, dTheta, dPhi = delta
@ -233,6 +241,7 @@ def _generateGrids(number, delta, start):
return (thetaGrid, phiGrid, rGrid) return (thetaGrid, phiGrid, rGrid)
def addCheckerboard(spacing=10., pertubation=0.1, inputfile='vgrids.in', def addCheckerboard(spacing=10., pertubation=0.1, inputfile='vgrids.in',
outputfile='vgrids_cb.in', ampmethod='linear', rect=(None, None)): outputfile='vgrids_cb.in', ampmethod='linear', rect=(None, None)):
''' '''
@ -244,6 +253,7 @@ def addCheckerboard(spacing = 10., pertubation = 0.1, inputfile = 'vgrids.in',
:param: pertubation, pertubation (default: 0.1 = 10%) :param: pertubation, pertubation (default: 0.1 = 10%)
type: float type: float
''' '''
def correctSpacing(spacing, delta, disttype=None): def correctSpacing(spacing, delta, disttype=None):
if spacing > delta: if spacing > delta:
spacing_corr = round(spacing / delta) * delta spacing_corr = round(spacing / delta) * delta
@ -298,7 +308,8 @@ def addCheckerboard(spacing = 10., pertubation = 0.1, inputfile = 'vgrids.in',
count = 0 count = 0
evenOdd = 1 evenOdd = 1
even = 0; odd = 0 even = 0;
odd = 0
# In the following loop it is checked whether the positive distance from the border of the model # In the following loop it is checked whether the positive distance from the border of the model
# for a point on the grid divided by the spacing is even or odd and then pertubated. # for a point on the grid divided by the spacing is even or odd and then pertubated.
@ -344,6 +355,7 @@ def addCheckerboard(spacing = 10., pertubation = 0.1, inputfile = 'vgrids.in',
'Outputfile: %s.' % (inputfile, spacing, pertubation * 100, outputfile)) 'Outputfile: %s.' % (inputfile, spacing, pertubation * 100, outputfile))
outfile.close() outfile.close()
def addBox(x=(None, None), y=(None, None), z=(None, None), def addBox(x=(None, None), y=(None, None), z=(None, None),
boxvelocity=1.0, inputfile='vgrids.in', boxvelocity=1.0, inputfile='vgrids.in',
outputfile='vgrids_box.in'): outputfile='vgrids_box.in'):
@ -423,10 +435,12 @@ def addBox(x = (None, None), y = (None, None), z = (None, None),
'Outputfile: %s.' % (inputfile, outputfile)) 'Outputfile: %s.' % (inputfile, outputfile))
outfile.close() outfile.close()
def _update_progress(progress): def _update_progress(progress):
sys.stdout.write("%d%% done \r" % (progress)) sys.stdout.write("%d%% done \r" % (progress))
sys.stdout.flush() sys.stdout.flush()
def _getAngle(distance): def _getAngle(distance):
''' '''
Function returns the angle on a Sphere of the radius R = 6371 [km] for a distance [km]. Function returns the angle on a Sphere of the radius R = 6371 [km] for a distance [km].
@ -436,9 +450,9 @@ def _getAngle(distance):
angle = distance * 180. / (PI * R) angle = distance * 180. / (PI * R)
return angle return angle
def _getDistance(angle): def _getDistance(angle):
PI = np.pi PI = np.pi
R = 6371. R = 6371.
distance = angle / 180 * (PI * R) distance = angle / 180 * (PI * R)
return distance return distance

View File

@ -3,6 +3,7 @@ import sys
import numpy as np import numpy as np
from scipy.interpolate import griddata from scipy.interpolate import griddata
class SeisArray(object): class SeisArray(object):
''' '''
Can be used to interpolate missing values of a receiver grid, if only support points were measured. Can be used to interpolate missing values of a receiver grid, if only support points were measured.
@ -15,6 +16,7 @@ class SeisArray(object):
Supports vtk output for sources and receivers. Supports vtk output for sources and receivers.
Note: Source and Receiver files for FMTOMO will be generated by the Survey object (because traveltimes will be added directly). Note: Source and Receiver files for FMTOMO will be generated by the Survey object (because traveltimes will be added directly).
''' '''
def __init__(self, recfile): def __init__(self, recfile):
self.recfile = recfile self.recfile = recfile
self._receiverlines = {} self._receiverlines = {}
@ -151,7 +153,8 @@ class SeisArray(object):
Returns the mean distance between two traceID's depending on the number of geophones in between Returns the mean distance between two traceID's depending on the number of geophones in between
''' '''
num_spaces = abs(self._getGeophoneNumber(traceID1) - self._getGeophoneNumber(traceID2)) num_spaces = abs(self._getGeophoneNumber(traceID1) - self._getGeophoneNumber(traceID2))
mean_distance = abs(self._getReceiverValue(traceID1, coordinate) - self._getReceiverValue(traceID2, coordinate))/num_spaces mean_distance = abs(
self._getReceiverValue(traceID1, coordinate) - self._getReceiverValue(traceID2, coordinate)) / num_spaces
return mean_distance return mean_distance
def interpolateValues(self, coordinate): def interpolateValues(self, coordinate):
@ -214,7 +217,8 @@ class SeisArray(object):
for traceID in self.getReceiverCoordinates().keys(): for traceID in self.getReceiverCoordinates().keys():
if type(self.getReceiverCoordinates()[traceID]) is not tuple: if type(self.getReceiverCoordinates()[traceID]) is not tuple:
z = griddata((measured_x, measured_y), measured_z, (self._getXreceiver(traceID), self._getYreceiver(traceID)), method = method) z = griddata((measured_x, measured_y), measured_z,
(self._getXreceiver(traceID), self._getYreceiver(traceID)), method=method)
self._setZvalue(traceID, float(z)) self._setZvalue(traceID, float(z))
def _getAngle(self, distance): def _getAngle(self, distance):
@ -239,7 +243,9 @@ class SeisArray(object):
''' '''
Returns a list of all measured receivers known to SeisArray. Returns a list of all measured receivers known to SeisArray.
''' '''
x = []; y = []; z = [] x = [];
y = [];
z = []
for traceID in self.getMeasuredReceivers().keys(): for traceID in self.getMeasuredReceivers().keys():
x.append(self.getMeasuredReceivers()[traceID][0]) x.append(self.getMeasuredReceivers()[traceID][0])
y.append(self.getMeasuredReceivers()[traceID][1]) y.append(self.getMeasuredReceivers()[traceID][1])
@ -250,7 +256,9 @@ class SeisArray(object):
''' '''
Returns a list of all measured topography points known to the SeisArray. Returns a list of all measured topography points known to the SeisArray.
''' '''
x = []; y = []; z = [] x = [];
y = [];
z = []
for pointID in self.getMeasuredTopo().keys(): for pointID in self.getMeasuredTopo().keys():
x.append(self.getMeasuredTopo()[pointID][0]) x.append(self.getMeasuredTopo()[pointID][0])
y.append(self.getMeasuredTopo()[pointID][1]) y.append(self.getMeasuredTopo()[pointID][1])
@ -261,7 +269,9 @@ class SeisArray(object):
''' '''
Returns a list of all measured source locations known to SeisArray. Returns a list of all measured source locations known to SeisArray.
''' '''
x = []; y = []; z = [] x = [];
y = [];
z = []
for pointID in self.getSourceLocations().keys(): for pointID in self.getSourceLocations().keys():
x.append(self.getSourceLocations()[pointID][0]) x.append(self.getSourceLocations()[pointID][0])
y.append(self.getSourceLocations()[pointID][1]) y.append(self.getSourceLocations()[pointID][1])
@ -285,7 +295,9 @@ class SeisArray(object):
''' '''
Returns a list of all receivers (measured and interpolated). Returns a list of all receivers (measured and interpolated).
''' '''
x = []; y =[]; z = [] x = [];
y = [];
z = []
for traceID in self.getReceiverCoordinates().keys(): for traceID in self.getReceiverCoordinates().keys():
x.append(self.getReceiverCoordinates()[traceID][0]) x.append(self.getReceiverCoordinates()[traceID][0])
y.append(self.getReceiverCoordinates()[traceID][1]) y.append(self.getReceiverCoordinates()[traceID][1])
@ -364,7 +376,8 @@ class SeisArray(object):
thetaGrid = np.linspace(thetaS - deltaTheta, thetaN + deltaTheta, num=nTheta + 2) # +2 cushion nodes thetaGrid = np.linspace(thetaS - deltaTheta, thetaN + deltaTheta, num=nTheta + 2) # +2 cushion nodes
phiGrid = np.linspace(phiW - deltaPhi, phiE + deltaPhi, num=nPhi + 2) # +2 cushion nodes phiGrid = np.linspace(phiW - deltaPhi, phiE + deltaPhi, num=nPhi + 2) # +2 cushion nodes
nTotal = len(thetaGrid) * len(phiGrid); count = 0 nTotal = len(thetaGrid) * len(phiGrid);
count = 0
for theta in thetaGrid: for theta in thetaGrid:
for phi in phiGrid: for phi in phiGrid:
xval = self._getDistance(phi) xval = self._getDistance(phi)
@ -457,7 +470,6 @@ class SeisArray(object):
outfile.close() outfile.close()
def generateInterfaces(self, nTheta, nPhi, depthmax, cushionfactor=0.1, def generateInterfaces(self, nTheta, nPhi, depthmax, cushionfactor=0.1,
outfilename='interfaces.in', method='linear', outfilename='interfaces.in', method='linear',
returnInterfaces=False): returnInterfaces=False):
@ -641,7 +653,10 @@ class SeisArray(object):
return nlayers return nlayers
def readMygrid(filename): def readMygrid(filename):
ztop = []; zbot = []; vtop = []; vbot = [] ztop = [];
zbot = [];
vtop = [];
vbot = []
infile = open(filename, 'r') infile = open(filename, 'r')
nlayers = readMygridNlayers(filename) nlayers = readMygridNlayers(filename)
@ -696,7 +711,8 @@ class SeisArray(object):
outfile.writelines('%10s %10s \n' % (1, 1)) outfile.writelines('%10s %10s \n' % (1, 1))
outfile.writelines('%10s %10s %10s\n' % (nR + 2, nTheta + 2, nPhi + 2)) outfile.writelines('%10s %10s %10s\n' % (nR + 2, nTheta + 2, nPhi + 2))
outfile.writelines('%10s %10s %10s\n' % (deltaR, np.deg2rad(deltaTheta), np.deg2rad(deltaPhi))) outfile.writelines('%10s %10s %10s\n' % (deltaR, np.deg2rad(deltaTheta), np.deg2rad(deltaPhi)))
outfile.writelines('%10s %10s %10s\n' %(rbot - deltaR, np.deg2rad(thetaS - deltaTheta), np.deg2rad(phiW - deltaPhi))) outfile.writelines(
'%10s %10s %10s\n' % (rbot - deltaR, np.deg2rad(thetaS - deltaTheta), np.deg2rad(phiW - deltaPhi)))
surface = self.interpolateTopography(nTheta, nPhi, thetaSN, phiWE, method=method) surface = self.interpolateTopography(nTheta, nPhi, thetaSN, phiWE, method=method)
@ -726,14 +742,18 @@ class SeisArray(object):
else: else:
for index in range(nlayers): for index in range(nlayers):
if (ztop[index]) >= depth > (zbot[index]): if (ztop[index]) >= depth > (zbot[index]):
vel = (depth - ztop[index]) / (zbot[index] - ztop[index]) * (vbot[index] - vtop[index]) + vtop[index] vel = (depth - ztop[index]) / (zbot[index] - ztop[index]) * (
vbot[index] - vtop[index]) + vtop[index]
break break
if not (ztop[index]) >= depth > (zbot[index]): if not (ztop[index]) >= depth > (zbot[index]):
print('ERROR in grid inputfile, could not find velocity for a z-value of %s in the inputfile'%(depth-topo)) print(
'ERROR in grid inputfile, could not find velocity for a z-value of %s in the inputfile' % (
depth - topo))
return return
count += 1 count += 1
if vel < 0: if vel < 0:
print('ERROR, vel <0; z, topo, zbot, vbot, vtop:', depth, topo, zbot[index], vbot[index], vtop[index]) print(
'ERROR, vel <0; z, topo, zbot, vbot, vtop:', depth, topo, zbot[index], vbot[index], vtop[index])
outfile.writelines('%10s %10s\n' % (vel, decm)) outfile.writelines('%10s %10s\n' % (vel, decm))
progress = float(count) / float(nTotal) * 100 progress = float(count) / float(nTotal) * 100
@ -786,11 +806,11 @@ class SeisArray(object):
plt.legend() plt.legend()
if annotations == True: if annotations == True:
for traceID in self.getReceiverCoordinates().keys(): for traceID in self.getReceiverCoordinates().keys():
ax.annotate((' ' + str(traceID)), xy = (self._getXreceiver(traceID), self._getYreceiver(traceID)), fontsize = 'x-small', color = 'k') ax.annotate((' ' + str(traceID)), xy=(self._getXreceiver(traceID), self._getYreceiver(traceID)),
fontsize='x-small', color='k')
for shotnumber in self.getSourceLocations().keys(): for shotnumber in self.getSourceLocations().keys():
ax.annotate((' ' + str(shotnumber)), xy = (self._getXshot(shotnumber), self._getYshot(shotnumber)), fontsize = 'x-small', color = 'b') ax.annotate((' ' + str(shotnumber)), xy=(self._getXshot(shotnumber), self._getYshot(shotnumber)),
fontsize='x-small', color='b')
def plotArray3D(self, ax=None): def plotArray3D(self, ax=None):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
@ -815,12 +835,13 @@ class SeisArray(object):
ax.plot(xmr, ymr, zmr, 'ro', label='measured receivers') ax.plot(xmr, ymr, zmr, 'ro', label='measured receivers')
if len(xsc) > 0: if len(xsc) > 0:
ax.plot(xsc, ysc, zsc, 'b*', label='shot locations') ax.plot(xsc, ysc, zsc, 'b*', label='shot locations')
ax.set_xlabel('X [m]'); ax.set_ylabel('Y [m]'); ax.set_zlabel('Z [m]') ax.set_xlabel('X [m]');
ax.set_ylabel('Y [m]');
ax.set_zlabel('Z [m]')
ax.legend() ax.legend()
return ax return ax
def plotSurface3D(self, ax=None, step=0.5, method='linear', exag=False): def plotSurface3D(self, ax=None, step=0.5, method='linear', exag=False):
from matplotlib import cm from matplotlib import cm
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
@ -853,7 +874,9 @@ class SeisArray(object):
ax.set_zlim(-(max(x) - min(x) / 2), (max(x) - min(x) / 2)) ax.set_zlim(-(max(x) - min(x) / 2), (max(x) - min(x) / 2))
ax.set_aspect('equal') ax.set_aspect('equal')
ax.set_xlabel('X [m]'); ax.set_ylabel('Y [m]'); ax.set_zlabel('Z [m]') ax.set_xlabel('X [m]');
ax.set_ylabel('Y [m]');
ax.set_zlabel('Z [m]')
ax.legend() ax.legend()
return ax return ax
@ -1005,7 +1028,6 @@ class SeisArray(object):
print("Wrote %d sources to file: %s" % (nPoints, filename)) print("Wrote %d sources to file: %s" % (nPoints, filename))
return return
def saveSeisArray(self, filename='seisArray.pickle'): def saveSeisArray(self, filename='seisArray.pickle'):
import cPickle import cPickle
outfile = open(filename, 'wb') outfile = open(filename, 'wb')

View File

@ -11,12 +11,15 @@ from pylot.core.pick.charfuns import AICcf
from pylot.core.pick.utils import getSNR from pylot.core.pick.utils import getSNR
from pylot.core.pick.utils import earllatepicker from pylot.core.pick.utils import earllatepicker
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
plt.interactive('True') plt.interactive('True')
class SeismicShot(object): class SeismicShot(object):
''' '''
SuperClass for a seismic shot object. SuperClass for a seismic shot object.
''' '''
def __init__(self, obsfile): def __init__(self, obsfile):
''' '''
Initialize seismic shot object giving an inputfile. Initialize seismic shot object giving an inputfile.
@ -368,7 +371,8 @@ class SeismicShot(object):
# threshold = folm * max(hoscflist[leftb : rightb]) # combination of local maximum and threshold # threshold = folm * max(hoscflist[leftb : rightb]) # combination of local maximum and threshold
### TEST TEST ### TEST TEST
threshold = folm * (max(hoscflist[leftb : rightb]) - min(hoscflist[leftb : rightb])) + min(hoscflist[leftb : rightb]) # combination of local maximum and threshold threshold = folm * (max(hoscflist[leftb: rightb]) - min(hoscflist[leftb: rightb])) + min(
hoscflist[leftb: rightb]) # combination of local maximum and threshold
### TEST TEST ### TEST TEST
m = leftb m = leftb
@ -446,7 +450,8 @@ class SeismicShot(object):
return float(x), float(y), float(z) return float(x), float(y), float(z)
# return float(self.getSingleStream(traceID)[0].stats.seg2['SOURCE_LOCATION']) # return float(self.getSingleStream(traceID)[0].stats.seg2['SOURCE_LOCATION'])
def getTraceIDs4Dist(self, distance = 0, distancebin = (0, 0)): ########## nur fuer 2D benutzt, 'distance bins' ########## def getTraceIDs4Dist(self, distance=0,
distancebin=(0, 0)): ########## nur fuer 2D benutzt, 'distance bins' ##########
''' '''
Returns the traceID(s) for a certain distance between source and receiver. Returns the traceID(s) for a certain distance between source and receiver.
Used for 2D Tomography. TO BE IMPROVED. Used for 2D Tomography. TO BE IMPROVED.
@ -517,7 +522,6 @@ class SeismicShot(object):
else: else:
self.setManualPickFlag(traceID, 1) self.setManualPickFlag(traceID, 1)
def setPick(self, traceID, pick): ########## siehe Kommentar ########## def setPick(self, traceID, pick): ########## siehe Kommentar ##########
if not traceID in self.picks.keys(): if not traceID in self.picks.keys():
self.picks[traceID] = {} self.picks[traceID] = {}
@ -587,7 +591,6 @@ class SeismicShot(object):
return distancearray return distancearray
def plot2dttc(self, ax=None): ########## 2D ########## def plot2dttc(self, ax=None): ########## 2D ##########
''' '''
Function to plot the traveltime curve for automated picks of a shot. 2d only! ATM: X DIRECTION!! Function to plot the traveltime curve for automated picks of a shot. 2d only! ATM: X DIRECTION!!
@ -605,7 +608,8 @@ class SeismicShot(object):
# shotnumbers = [shotnumbers for (shotnumbers, shotnames) in sorted(zip(shotnumbers, shotnames))] # shotnumbers = [shotnumbers for (shotnumbers, shotnames) in sorted(zip(shotnumbers, shotnames))]
plotarray = sorted(zip(self.getDistArray4ttcPlot(), picks)) plotarray = sorted(zip(self.getDistArray4ttcPlot(), picks))
x = []; y = [] x = [];
y = []
for point in plotarray: for point in plotarray:
x.append(point[0]) x.append(point[0])
y.append(point[1]) y.append(point[1])
@ -632,7 +636,8 @@ class SeismicShot(object):
ax = fig.add_subplot(111) ax = fig.add_subplot(111)
plotarray = sorted(zip(self.getDistArray4ttcPlot(), manualpicktimesarray)) plotarray = sorted(zip(self.getDistArray4ttcPlot(), manualpicktimesarray))
x = []; y = [] x = [];
y = []
for point in plotarray: for point in plotarray:
x.append(point[0]) x.append(point[0])
y.append(point[1]) y.append(point[1])
@ -669,7 +674,8 @@ class SeismicShot(object):
ax.plot([0, tnoise], [noiselevel, noiselevel], 'm', linewidth=lw, label='noise level') ax.plot([0, tnoise], [noiselevel, noiselevel], 'm', linewidth=lw, label='noise level')
ax.plot([tnoise, pick], [noiselevel, noiselevel], 'g:', linewidth=lw, label='gap') ax.plot([tnoise, pick], [noiselevel, noiselevel], 'g:', linewidth=lw, label='gap')
ax.plot([tnoise + tgap, pick + tsignal], [noiselevel * snr, noiselevel * snr], 'b', linewidth = lw, label = 'signal level') ax.plot([tnoise + tgap, pick + tsignal], [noiselevel * snr, noiselevel * snr], 'b', linewidth=lw,
label='signal level')
ax.legend() ax.legend()
ax.text(0.05, 0.9, 'SNR: %s' % snr, transform=ax.transAxes) ax.text(0.05, 0.9, 'SNR: %s' % snr, transform=ax.transAxes)
@ -868,9 +874,12 @@ class SeismicShot(object):
from matplotlib import cm from matplotlib import cm
cmap = cm.jet cmap = cm.jet
x = []; xcut = [] x = [];
y = []; ycut = [] xcut = []
z = []; zcut = [] y = [];
ycut = []
z = [];
zcut = []
for traceID in self.picks.keys(): for traceID in self.picks.keys():
if self.getPickFlag(traceID) != 0: if self.getPickFlag(traceID) != 0:
@ -895,7 +904,8 @@ class SeismicShot(object):
ax = plt.axes() ax = plt.axes()
count = 0 count = 0
ax.imshow(zgrid, extent = [min(x), max(x), min(y), max(y)], vmin = tmin, vmax = tmax, cmap = cmap, origin = 'lower', alpha = 0.85) ax.imshow(zgrid, extent=[min(x), max(x), min(y), max(y)], vmin=tmin, vmax=tmax, cmap=cmap, origin='lower',
alpha=0.85)
ax.text(0.5, 0.95, 'shot: %s' % self.getShotnumber(), transform=ax.transAxes ax.text(0.5, 0.95, 'shot: %s' % self.getShotnumber(), transform=ax.transAxes
, horizontalalignment='center') , horizontalalignment='center')
sc = ax.scatter(x, y, c=z, s=30, label='picked shots', vmin=tmin, vmax=tmax, cmap=cmap, linewidths=1.5) sc = ax.scatter(x, y, c=z, s=30, label='picked shots', vmin=tmin, vmax=tmax, cmap=cmap, linewidths=1.5)
@ -928,5 +938,3 @@ class SeismicShot(object):
fontsize='x-small', color='r') fontsize='x-small', color='r')
plt.show() plt.show()

View File

@ -2,8 +2,10 @@
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import math import math
import numpy as np import numpy as np
plt.interactive(True) plt.interactive(True)
class regions(object): class regions(object):
''' '''
A class used for manual inspection and processing of all picks for the user. A class used for manual inspection and processing of all picks for the user.
@ -179,7 +181,8 @@ class regions(object):
self.drawLastPolyLine() self.drawLastPolyLine()
x = self._polyx x = self._polyx
y = self._polyy y = self._polyy
self._polyx = []; self._polyy = [] self._polyx = [];
self._polyy = []
key = self.getKey() key = self.getKey()
self.markPolygon(x, y, key=key) self.markPolygon(x, y, key=key)
@ -279,8 +282,10 @@ class regions(object):
angle = 0 angle = 0
epsilon = 1e-07 epsilon = 1e-07
for index in range(len(x)): for index in range(len(x)):
xval1 = x[index - 1]; yval1 = y[index - 1] xval1 = x[index - 1];
xval2 = x[index]; yval2 = y[index] yval1 = y[index - 1]
xval2 = x[index];
yval2 = y[index]
angle += getangle([xval1 - pickX, yval1 - pickY], [xval2 - pickX, yval2 - pickY]) angle += getangle([xval1 - pickX, yval1 - pickY], [xval2 - pickX, yval2 - pickY])
if 360 - epsilon <= angle <= 360 + epsilon: ### IMPROVE THAT?? if 360 - epsilon <= angle <= 360 + epsilon: ### IMPROVE THAT??
return True return True
@ -289,9 +294,12 @@ class regions(object):
self.printOutput('No polygon defined.') self.printOutput('No polygon defined.')
return return
shots_found = {}; numtraces = 0 shots_found = {};
x0 = min(x); x1 = max(x) numtraces = 0
y0 = min(y); y1 = max(y) x0 = min(x);
x1 = max(x)
y0 = min(y);
y1 = max(y)
shots, numtracesrect = self.findTracesInShotDict((x0, x1), (y0, y1), highlight=False) shots, numtracesrect = self.findTracesInShotDict((x0, x1), (y0, y1), highlight=False)
for shotnumber in shots.keys(): for shotnumber in shots.keys():
@ -315,9 +323,12 @@ class regions(object):
''' '''
Returns traces corresponding to a certain area in the plot with all picks over the distances. Returns traces corresponding to a certain area in the plot with all picks over the distances.
''' '''
shots_found = {}; numtraces = 0 shots_found = {};
if picks == 'normal': pickflag = 0 numtraces = 0
elif picks == 'includeCutOut': pickflag = None if picks == 'normal':
pickflag = 0
elif picks == 'includeCutOut':
pickflag = None
for line in self._allpicks: for line in self._allpicks:
dist, pick, shotnumber, traceID, flag = line dist, pick, shotnumber, traceID, flag = line
@ -344,9 +355,11 @@ class regions(object):
if shot.getPickFlag(traceID) is 0: if shot.getPickFlag(traceID) is 0:
return return
self.ax.scatter(shot.getDistance(traceID), shot.getPick(traceID), s = 50, marker = 'o', facecolors = 'none', edgecolors = 'm', alpha = 1) self.ax.scatter(shot.getDistance(traceID), shot.getPick(traceID), s=50, marker='o', facecolors='none',
edgecolors='m', alpha=1)
if annotations == True: if annotations == True:
self.ax.annotate(s='s%s|t%s' % (shot.getShotnumber(), traceID), xy=(shot.getDistance(traceID), shot.getPick(traceID)), fontsize='xx-small') self.ax.annotate(s='s%s|t%s' % (shot.getShotnumber(), traceID),
xy=(shot.getDistance(traceID), shot.getPick(traceID)), fontsize='xx-small')
def highlightAllActiveRegions(self): def highlightAllActiveRegions(self):
''' '''
@ -382,7 +395,8 @@ class regions(object):
for traceID in self.shots_found[key]['shots'][shotnumber]: for traceID in self.shots_found[key]['shots'][shotnumber]:
count += 1 count += 1
if count > maxfigures: if count > maxfigures:
print 'Maximum number of figures (%s) reached. %sth figure was not opened.' %(maxfigures, count) print 'Maximum number of figures (%s) reached. %sth figure was not opened.' % (
maxfigures, count)
break break
shot.plot_traces(traceID) shot.plot_traces(traceID)
else: else:
@ -420,7 +434,6 @@ class regions(object):
self.markPolygon(self.shots_found[key]['xvalues'], self.markPolygon(self.shots_found[key]['xvalues'],
self.shots_found[key]['yvalues'], key=key) self.shots_found[key]['yvalues'], key=key)
def markRectangle(self, (x0, x1), (y0, y1), key=None, color='grey', alpha=0.1, linewidth=1): def markRectangle(self, (x0, x1), (y0, y1), key=None, color='grey', alpha=0.1, linewidth=1):
''' '''
Mark a rectangular region on the axes. Mark a rectangular region on the axes.

View File

@ -1,6 +1,13 @@
import numpy as np from __future__ import print_function
def readParameters(parfile, parameter): def readParameters(parfile, parameter):
"""
:param parfile:
:param parameter:
:return:
"""
from ConfigParser import ConfigParser from ConfigParser import ConfigParser
parameterConfig = ConfigParser() parameterConfig = ConfigParser()
parameterConfig.read('parfile') parameterConfig.read('parfile')
@ -9,14 +16,29 @@ def readParameters(parfile, parameter):
return value return value
def setArtificialPick(shot_dict, traceID, pick): def setArtificialPick(shot_dict, traceID, pick):
"""
:param shot_dict:
:param traceID:
:param pick:
:return:
"""
for shot in shot_dict.values(): for shot in shot_dict.values():
shot.setPick(traceID, pick) shot.setPick(traceID, pick)
shot.setPickwindow(traceID, shot.getCut()) shot.setPickwindow(traceID, shot.getCut())
def fitSNR4dist(shot_dict, shiftdist=30, shiftSNR=100): def fitSNR4dist(shot_dict, shiftdist=30, shiftSNR=100):
"""
:param shot_dict:
:param shiftdist:
:param shiftSNR:
:return:
"""
import numpy as np import numpy as np
import matplotlib.pyplot as plt
dists = [] dists = []
picks = [] picks = []
snrs = [] snrs = []
@ -41,6 +63,14 @@ def fitSNR4dist(shot_dict, shiftdist = 30, shiftSNR = 100):
def plotFittedSNR(dists, snrthresholds, snrs, snrBestFit): def plotFittedSNR(dists, snrthresholds, snrs, snrBestFit):
"""
:param dists:
:param snrthresholds:
:param snrs:
:param snrBestFit:
:return:
"""
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
plt.interactive(True) plt.interactive(True)
fig = plt.figure() fig = plt.figure()
@ -54,7 +84,22 @@ def plotFittedSNR(dists, snrthresholds, snrs, snrBestFit):
plt.ylabel('SNR') plt.ylabel('SNR')
plt.legend() plt.legend()
def setDynamicFittedSNR(shot_dict, shiftdist=30, shiftSNR=100, p1=0.004, p2=-0.0007): def setDynamicFittedSNR(shot_dict, shiftdist=30, shiftSNR=100, p1=0.004, p2=-0.0007):
"""
:param shot_dict:
:type shot_dict: dict
:param shiftdist:
:type shiftdist: int
:param shiftSNR:
:type shiftSNR: int
:param p1:
:type p1: float
:param p2:
:type p2: float
:return:
"""
import numpy as np import numpy as np
minSNR = 2.5 minSNR = 2.5
# fit_fn = fitSNR4dist(shot_dict) # fit_fn = fitSNR4dist(shot_dict)
@ -69,14 +114,21 @@ def setDynamicFittedSNR(shot_dict, shiftdist = 30, shiftSNR = 100, p1 = 0.004, p
shot.setSNRthreshold(traceID, minSNR) shot.setSNRthreshold(traceID, minSNR)
else: else:
shot.setSNRthreshold(traceID, snrthreshold) shot.setSNRthreshold(traceID, snrthreshold)
print "setDynamicFittedSNR: Finished setting of fitted SNR-threshold" print("setDynamicFittedSNR: Finished setting of fitted SNR-threshold")
def setConstantSNR(shot_dict, snrthreshold=2.5): def setConstantSNR(shot_dict, snrthreshold=2.5):
import numpy as np """
:param shot_dict:
:param snrthreshold:
:return:
"""
for shot in shot_dict.values(): for shot in shot_dict.values():
for traceID in shot.getTraceIDlist(): for traceID in shot.getTraceIDlist():
shot.setSNRthreshold(traceID, snrthreshold) shot.setSNRthreshold(traceID, snrthreshold)
print "setConstantSNR: Finished setting of SNR threshold to a constant value of %s"%snrthreshold print("setConstantSNR: Finished setting of SNR threshold to a constant value of %s" % snrthreshold)
def findTracesInRanges(shot_dict, distancebin, pickbin): def findTracesInRanges(shot_dict, distancebin, pickbin):
''' '''
@ -103,11 +155,17 @@ def findTracesInRanges(shot_dict, distancebin, pickbin):
return shots_found return shots_found
def cleanUp(survey):
def cleanUp(survey):
"""
:param survey:
:return:
"""
for shot in survey.data.values(): for shot in survey.data.values():
shot.traces4plot = {} shot.traces4plot = {}
# def plotScatterStats(survey, key, ax = None): # def plotScatterStats(survey, key, ax = None):
# import matplotlib.pyplot as plt # import matplotlib.pyplot as plt
# x = []; y = []; value = [] # x = []; y = []; value = []
@ -131,14 +189,19 @@ def cleanUp(survey):
# cbar.set_label(key) # cbar.set_label(key)
def plotScatterStats4Shots(survey, key): def plotScatterStats4Shots(survey, key):
''' """
Statistics, scatter plot. Statistics, scatter plot.
key can be 'mean SNR', 'median SNR', 'mean SPE', 'median SPE', or 'picked traces' key can be 'mean SNR', 'median SNR', 'mean SPE', 'median SPE', or 'picked traces'
''' :param survey:
:param key:
:return:
"""
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
statsShot = {} statsShot = {}
x = []; y = []; value = [] x = []
y = []
value = []
for shot in survey.data.values(): for shot in survey.data.values():
for traceID in shot.getTraceIDlist(): for traceID in shot.getTraceIDlist():
if not shot in statsShot.keys(): if not shot in statsShot.keys():
@ -182,15 +245,21 @@ def plotScatterStats4Shots(survey, key):
ax.annotate(' %s' % shot.getShotnumber(), xy=(shot.getSrcLoc()[0], shot.getSrcLoc()[1]), ax.annotate(' %s' % shot.getShotnumber(), xy=(shot.getSrcLoc()[0], shot.getSrcLoc()[1]),
fontsize='x-small', color='k') fontsize='x-small', color='k')
def plotScatterStats4Receivers(survey, key): def plotScatterStats4Receivers(survey, key):
''' """
Statistics, scatter plot. Statistics, scatter plot.
key can be 'mean SNR', 'median SNR', 'mean SPE', 'median SPE', or 'picked traces' key can be 'mean SNR', 'median SNR', 'mean SPE', 'median SPE', or 'picked traces'
''' :param survey:
:param key:
:return:
"""
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
statsRec = {} statsRec = {}
x = []; y = []; value = [] x = []
y = []
value = []
for shot in survey.data.values(): for shot in survey.data.values():
for traceID in shot.getTraceIDlist(): for traceID in shot.getTraceIDlist():
if not traceID in statsRec.keys(): if not traceID in statsRec.keys():
@ -205,7 +274,6 @@ def plotScatterStats4Receivers(survey, key):
statsRec[traceID]['picked traces'] += 1 statsRec[traceID]['picked traces'] += 1
statsRec[traceID]['SPE'].append(shot.getSymmetricPickError(traceID)) statsRec[traceID]['SPE'].append(shot.getSymmetricPickError(traceID))
for traceID in statsRec.keys(): for traceID in statsRec.keys():
statsRec[traceID]['mean SNR'] = np.mean(statsRec[traceID]['SNR']) statsRec[traceID]['mean SNR'] = np.mean(statsRec[traceID]['SNR'])
statsRec[traceID]['median SNR'] = np.median(statsRec[traceID]['SNR']) statsRec[traceID]['median SNR'] = np.median(statsRec[traceID]['SNR'])

View File

@ -5,9 +5,7 @@ from obspy.core import read
from obspy.signal.trigger import coincidenceTrigger from obspy.signal.trigger import coincidenceTrigger
class CoincidenceTimes(object): class CoincidenceTimes(object):
def __init__(self, st, comp='Z', coinum=4, sta=1., lta=10., on=5., off=1.): def __init__(self, st, comp='Z', coinum=4, sta=1., lta=10., on=5., off=1.):
_type = 'recstalta' _type = 'recstalta'
self.coinclist = self.createCoincTriggerlist(data=st, trigcomp=comp, self.coinclist = self.createCoincTriggerlist(data=st, trigcomp=comp,

View File

@ -15,6 +15,7 @@ from scipy.optimize import curve_fit
from scipy import integrate, signal from scipy import integrate, signal
from pylot.core.read.data import Data from pylot.core.read.data import Data
class Magnitude(object): class Magnitude(object):
''' '''
Superclass for calculating Wood-Anderson peak-to-peak Superclass for calculating Wood-Anderson peak-to-peak
@ -72,7 +73,6 @@ class Magnitude(object):
self.calcsourcespec() self.calcsourcespec()
self.run_calcMoMw() self.run_calcMoMw()
def getwfstream(self): def getwfstream(self):
return self.wfstream return self.wfstream
@ -154,6 +154,7 @@ class Magnitude(object):
def run_calcMoMw(self): def run_calcMoMw(self):
self.pickdic = None self.pickdic = None
class WApp(Magnitude): class WApp(Magnitude):
''' '''
Method to derive peak-to-peak amplitude as seen on a Wood-Anderson- Method to derive peak-to-peak amplitude as seen on a Wood-Anderson-
@ -261,6 +262,7 @@ class M0Mw(Magnitude):
picks[key]['P']['Mw'] = Mw picks[key]['P']['Mw'] = Mw
self.picdic = picks self.picdic = picks
def calcMoMw(wfstream, w0, rho, vp, delta, inv): def calcMoMw(wfstream, w0, rho, vp, delta, inv):
''' '''
Subfunction of run_calcMoMw to calculate individual Subfunction of run_calcMoMw to calculate individual
@ -302,7 +304,6 @@ def calcMoMw(wfstream, w0, rho, vp, delta, inv):
return Mo, Mw return Mo, Mw
def calcsourcespec(wfstream, onset, inventory, vp, delta, azimuth, incidence, Qp, iplot): def calcsourcespec(wfstream, onset, inventory, vp, delta, azimuth, incidence, Qp, iplot):
''' '''
Subfunction to calculate the source spectrum and to derive from that the plateau Subfunction to calculate the source spectrum and to derive from that the plateau
@ -639,10 +640,3 @@ def fitSourceModel(f, S, fc0, iplot):
plt.close() plt.close()
return w0, fc return w0, fc

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from obspy.signal.trigger import recSTALTA, triggerOnset from obspy.signal.trigger import recursive_sta_lta, trigger_onset
def createSingleTriggerlist(st, station='ZV01', trigcomp='Z', stalta=(1, 10), def createSingleTriggerlist(st, station='ZV01', trigcomp='Z', stalta=(1, 10),
@ -24,8 +24,8 @@ def createSingleTriggerlist(st, station='ZV01', trigcomp='Z', stalta=(1, 10),
tr = st.copy().select(component=trigcomp, station=station)[0] tr = st.copy().select(component=trigcomp, station=station)[0]
df = tr.stats.sampling_rate df = tr.stats.sampling_rate
cft = recSTALTA(tr.data, int(stalta[0] * df), int(stalta[1] * df)) cft = recursive_sta_lta(tr.data, int(stalta[0] * df), int(stalta[1] * df))
triggers = triggerOnset(cft, trigonoff[0], trigonoff[1]) triggers = trigger_onset(cft, trigonoff[0], trigonoff[1])
trigg = [] trigg = []
for time in triggers: for time in triggers:
trigg.append(tr.stats.starttime + time[0] / df) trigg.append(tr.stats.starttime + time[0] / df)

View File

@ -9,6 +9,7 @@ from pylot.core.util.version import get_git_version as _getVersionString
__version__ = _getVersionString() __version__ = _getVersionString()
def picksExport(picks, locrt, phasefile): def picksExport(picks, locrt, phasefile):
''' '''
Take <picks> dictionary and exports picking data to a NLLOC-obs Take <picks> dictionary and exports picking data to a NLLOC-obs
@ -26,6 +27,7 @@ def picksExport(picks, locrt, phasefile):
# write phases to NLLoc-phase file # write phases to NLLoc-phase file
writephases(picks, locrt, phasefile) writephases(picks, locrt, phasefile)
def modifyInputFile(ctrfn, root, nllocoutn, phasefn, tttn): def modifyInputFile(ctrfn, root, nllocoutn, phasefn, tttn):
''' '''
:param ctrfn: name of NLLoc-control file :param ctrfn: name of NLLoc-control file
@ -63,6 +65,7 @@ def modifyInputFile(ctrfn, root, nllocoutn, phasefn, tttn):
nllfile.write(filedata) nllfile.write(filedata)
nllfile.close() nllfile.close()
def locate(call, fnin): def locate(call, fnin):
''' '''
Takes paths to NLLoc executable <call> and input parameter file <fnin> Takes paths to NLLoc executable <call> and input parameter file <fnin>
@ -78,8 +81,10 @@ def locate(call, fnin):
# locate the event # locate the event
subprocess.call([call, fnin]) subprocess.call([call, fnin])
def readLocation(fn): def readLocation(fn):
pass pass
if __name__ == '__main__': if __name__ == '__main__':
pass pass

View File

@ -21,10 +21,12 @@ import matplotlib.pyplot as plt
import numpy as np import numpy as np
from obspy.core import Stream from obspy.core import Stream
class CharacteristicFunction(object): class CharacteristicFunction(object):
''' '''
SuperClass for different types of characteristic functions. SuperClass for different types of characteristic functions.
''' '''
def __init__(self, data, cut, t2=None, order=None, t1=None, fnoise=None, stealthMode=False): def __init__(self, data, cut, t2=None, order=None, t1=None, fnoise=None, stealthMode=False):
''' '''
Initialize data type object with information from the original Initialize data type object with information from the original
@ -247,6 +249,7 @@ class AICcf(CharacteristicFunction):
self.cf = cf - np.mean(cf) self.cf = cf - np.mean(cf)
self.xcf = x self.xcf = x
class HOScf(CharacteristicFunction): class HOScf(CharacteristicFunction):
''' '''
Function to calculate skewness (statistics of order 3) or kurtosis Function to calculate skewness (statistics of order 3) or kurtosis
@ -302,7 +305,6 @@ class HOScf(CharacteristicFunction):
class ARZcf(CharacteristicFunction): class ARZcf(CharacteristicFunction):
def calcCF(self, data): def calcCF(self, data):
print 'Calculating AR-prediction error from single trace ...' print 'Calculating AR-prediction error from single trace ...'
@ -426,7 +428,6 @@ class ARZcf(CharacteristicFunction):
class ARHcf(CharacteristicFunction): class ARHcf(CharacteristicFunction):
def calcCF(self, data): def calcCF(self, data):
print 'Calculating AR-prediction error from both horizontal traces ...' print 'Calculating AR-prediction error from both horizontal traces ...'
@ -464,7 +465,8 @@ class ARHcf(CharacteristicFunction):
self.arPredH(xnp, self.arpara, i + 1, lpred) self.arPredH(xnp, self.arpara, i + 1, lpred)
# prediction error = CF # prediction error = CF
cf[i + lpred] = np.sqrt(np.sum(np.power(self.xpred[0][i:i + lpred] - xnp[0][i:i + lpred], 2) \ cf[i + lpred] = np.sqrt(np.sum(np.power(self.xpred[0][i:i + lpred] - xnp[0][i:i + lpred], 2) \
+ np.power(self.xpred[1][i:i + lpred] - xnp[1][i:i + lpred], 2)) / (2 * lpred)) + np.power(self.xpred[1][i:i + lpred] - xnp[1][i:i + lpred], 2)) / (
2 * lpred))
nn = np.isnan(cf) nn = np.isnan(cf)
if len(nn) > 1: if len(nn) > 1:
cf[nn] = 0 cf[nn] = 0
@ -561,8 +563,8 @@ class ARHcf(CharacteristicFunction):
z = np.array([z1.tolist(), z2.tolist()]) z = np.array([z1.tolist(), z2.tolist()])
self.xpred = z self.xpred = z
class AR3Ccf(CharacteristicFunction):
class AR3Ccf(CharacteristicFunction):
def calcCF(self, data): def calcCF(self, data):
print 'Calculating AR-prediction error from all 3 components ...' print 'Calculating AR-prediction error from all 3 components ...'
@ -605,7 +607,8 @@ class AR3Ccf(CharacteristicFunction):
# prediction error = CF # prediction error = CF
cf[i + lpred] = np.sqrt(np.sum(np.power(self.xpred[0][i:i + lpred] - xnp[0][i:i + lpred], 2) \ cf[i + lpred] = np.sqrt(np.sum(np.power(self.xpred[0][i:i + lpred] - xnp[0][i:i + lpred], 2) \
+ np.power(self.xpred[1][i:i + lpred] - xnp[1][i:i + lpred], 2) \ + np.power(self.xpred[1][i:i + lpred] - xnp[1][i:i + lpred], 2) \
+ np.power(self.xpred[2][i:i + lpred] - xnp[2][i:i + lpred], 2)) / (3 * lpred)) + np.power(self.xpred[2][i:i + lpred] - xnp[2][i:i + lpred], 2)) / (
3 * lpred))
nn = np.isnan(cf) nn = np.isnan(cf)
if len(nn) > 1: if len(nn) > 1:
cf[nn] = 0 cf[nn] = 0

View File

@ -25,6 +25,7 @@ from pylot.core.pick.utils import getnoisewin, getsignalwin
from pylot.core.pick.charfuns import CharacteristicFunction from pylot.core.pick.charfuns import CharacteristicFunction
import warnings import warnings
class AutoPicker(object): class AutoPicker(object):
''' '''
Superclass of different, automated picking algorithms applied on a CF determined Superclass of different, automated picking algorithms applied on a CF determined
@ -87,7 +88,6 @@ class AutoPicker(object):
Tsmooth=self.getTsmooth(), Tsmooth=self.getTsmooth(),
Pick1=self.getpick1()) Pick1=self.getpick1())
def getTSNR(self): def getTSNR(self):
return self.TSNR return self.TSNR
@ -273,7 +273,8 @@ class AICPicker(AutoPicker):
p13, = plt.plot(self.Tcf[isignal], self.Data[0].data[isignal], 'r') p13, = plt.plot(self.Tcf[isignal], self.Data[0].data[isignal], 'r')
p14, = plt.plot(self.Tcf[islope], dataslope, 'g--') p14, = plt.plot(self.Tcf[islope], dataslope, 'g--')
p15, = plt.plot(self.Tcf[islope], datafit, 'g', linewidth=2) p15, = plt.plot(self.Tcf[islope], datafit, 'g', linewidth=2)
plt.legend([p11, p12, p13, p14, p15], ['Data', 'Noise Window', 'Signal Window', 'Slope Window', 'Slope'], plt.legend([p11, p12, p13, p14, p15],
['Data', 'Noise Window', 'Signal Window', 'Slope Window', 'Slope'],
loc='best') loc='best')
plt.title('Station %s, SNR=%7.2f, Slope= %12.2f counts/s' % (self.Data[0].stats.station, plt.title('Station %s, SNR=%7.2f, Slope= %12.2f counts/s' % (self.Data[0].stats.station,
self.SNR, self.slope)) self.SNR, self.slope))

View File

@ -70,7 +70,8 @@ def earllatepicker(X, nfac, TSNR, Pick1, iplot=None, stealthMode = False):
# get earliest possible pick # get earliest possible pick
EPick = np.nan; count = 0 EPick = np.nan;
count = 0
pis = isignal pis = isignal
# if EPick stays NaN the signal window size will be doubled # if EPick stays NaN the signal window size will be doubled
@ -94,7 +95,6 @@ def earllatepicker(X, nfac, TSNR, Pick1, iplot=None, stealthMode = False):
T0 = np.mean(np.diff(zc)) * X[0].stats.delta # this is half wave length! T0 = np.mean(np.diff(zc)) * X[0].stats.delta # this is half wave length!
EPick = Pick1 - T0 # half wavelength as suggested by Diehl et al. EPick = Pick1 - T0 # half wavelength as suggested by Diehl et al.
# get symmetric pick error as mean from earliest and latest possible pick # get symmetric pick error as mean from earliest and latest possible pick
# by weighting latest possible pick two times earliest possible pick # by weighting latest possible pick two times earliest possible pick
diffti_tl = LPick - Pick1 diffti_tl = LPick - Pick1
@ -499,7 +499,6 @@ def wadaticheck(pickdic, dttolerance, iplot):
Spicks.append(UTCSpick.timestamp) Spicks.append(UTCSpick.timestamp)
SPtimes.append(spt) SPtimes.append(spt)
if len(SPtimes) >= 3: if len(SPtimes) >= 3:
# calculate slope # calculate slope
p1 = np.polyfit(Ppicks, SPtimes, 1) p1 = np.polyfit(Ppicks, SPtimes, 1)
@ -881,7 +880,6 @@ def checkZ4S(X, pick, zfac, checkwin, iplot):
if len(ndat) == 0: # check for other components if len(ndat) == 0: # check for other components
ndat = X.select(component="1") ndat = X.select(component="1")
z = zdat[0].data z = zdat[0].data
tz = np.arange(0, zdat[0].stats.npts / zdat[0].stats.sampling_rate, tz = np.arange(0, zdat[0].stats.npts / zdat[0].stats.sampling_rate,
zdat[0].stats.delta) zdat[0].stats.delta)
@ -960,7 +958,6 @@ def writephases(arrivals, fformat, filename):
:type: string :type: string
''' '''
if fformat == 'NLLoc': if fformat == 'NLLoc':
print ("Writing phases to %s for NLLoc" % filename) print ("Writing phases to %s for NLLoc" % filename)
fid = open("%s" % filename, 'w') fid = open("%s" % filename, 'w')
@ -1098,4 +1095,5 @@ def writephases(arrivals, fformat, filename):
if __name__ == '__main__': if __name__ == '__main__':
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -81,7 +81,6 @@ class Data(object):
picks_str += str(pick) + '\n' picks_str += str(pick) + '\n'
return picks_str return picks_str
def getParent(self): def getParent(self):
""" """

View File

@ -3,6 +3,7 @@
from pylot.core.util.errors import ParameterError from pylot.core.util.errors import ParameterError
class AutoPickParameter(object): class AutoPickParameter(object):
''' '''
AutoPickParameters is a parameter type object capable to read and/or write AutoPickParameters is a parameter type object capable to read and/or write
@ -193,6 +194,7 @@ class FilterOptions(object):
``'highpass'`` ``'highpass'``
Butterworth-Highpass Butterworth-Highpass
''' '''
def __init__(self, filtertype='bandpass', freq=[2., 5.], order=3, def __init__(self, filtertype='bandpass', freq=[2., 5.], order=3,
**kwargs): **kwargs):
self._order = order self._order = order

View File

@ -10,6 +10,7 @@ from obspy.core import UTCDateTime
from pylot.core.util.utils import getOwner, createPick, createArrival, \ from pylot.core.util.utils import getOwner, createPick, createArrival, \
createEvent, createOrigin, createMagnitude createEvent, createOrigin, createMagnitude
def readPILOTEvent(phasfn=None, locfn=None, authority_id=None, **kwargs): def readPILOTEvent(phasfn=None, locfn=None, authority_id=None, **kwargs):
""" """
readPILOTEvent - function readPILOTEvent - function
@ -133,5 +134,3 @@ def readPILOTEvent(phasfn=None, locfn=None, authority_id=None, **kwargs):
except AttributeError as e: except AttributeError as e:
raise AttributeError('{0} - Matlab LOC files {1} and {2} contains \ raise AttributeError('{0} - Matlab LOC files {1} and {2} contains \
insufficient data!'.format(e, phasfn, locfn)) insufficient data!'.format(e, phasfn, locfn))

View File

@ -14,11 +14,12 @@ import argparse
import obspy import obspy
from pylot.core.pick.utils import earllatepicker from pylot.core.pick.utils import earllatepicker
if __name__ == "__main__": if __name__ == "__main__":
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('--X', type=~obspy.core.stream.Stream, help='time series (seismogram) read with obspy module read') parser.add_argument('--X', type=~obspy.core.stream.Stream,
parser.add_argument('--nfac', type=int, help='(noise factor), nfac times noise level to calculate latest possible pick') help='time series (seismogram) read with obspy module read')
parser.add_argument('--nfac', type=int,
help='(noise factor), nfac times noise level to calculate latest possible pick')
parser.add_argument('--TSNR', type=tuple, help='length of time windows around pick used to determine SNR \ parser.add_argument('--TSNR', type=tuple, help='length of time windows around pick used to determine SNR \
[s] (Tnoise, Tgap, Tsignal)') [s] (Tnoise, Tgap, Tsignal)')
parser.add_argument('--Pick1', type=float, help='Onset time of most likely pick') parser.add_argument('--Pick1', type=float, help='Onset time of most likely pick')

View File

@ -13,11 +13,12 @@ from pylot.core.pick.utils import fmpicker
if __name__ == "__main__": if __name__ == "__main__":
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('--Xraw', type=obspy.core.stream.Stream, help='unfiltered time series (seismogram) read with obspy module read') parser.add_argument('--Xraw', type=obspy.core.stream.Stream,
parser.add_argument('--Xfilt', type=obspy.core.stream.Stream, help='filtered time series (seismogram) read with obspy module read') help='unfiltered time series (seismogram) read with obspy module read')
parser.add_argument('--Xfilt', type=obspy.core.stream.Stream,
help='filtered time series (seismogram) read with obspy module read')
parser.add_argument('--pickwin', type=float, help='length of pick window [s] for first motion determination') parser.add_argument('--pickwin', type=float, help='length of pick window [s] for first motion determination')
parser.add_argument('--Pick', type=float, help='Onset time of most likely pick') parser.add_argument('--Pick', type=float, help='Onset time of most likely pick')
parser.add_argument('--iplot', type=int, help='if set, figure no. iplot occurs') parser.add_argument('--iplot', type=int, help='if set, figure no. iplot occurs')
args = parser.parse_args() args = parser.parse_args()
fmpicker(args.Xraw, args.Xfilt, args.pickwin, args.Pick, args.iplot) fmpicker(args.Xraw, args.Xfilt, args.pickwin, args.Pick, args.iplot)

View File

@ -11,6 +11,7 @@ from pylot.core.loc import nll
from pylot.core.loc import hsat from pylot.core.loc import hsat
from pylot.core.loc import velest from pylot.core.loc import velest
def readFilterInformation(fname): def readFilterInformation(fname):
def convert2FreqRange(*args): def convert2FreqRange(*args):
if len(args) > 1: if len(args) > 1:
@ -18,6 +19,7 @@ def readFilterInformation(fname):
elif len(args) == 1: elif len(args) == 1:
return float(args[0]) return float(args[0])
return None return None
filter_file = open(fname, 'r') filter_file = open(fname, 'r')
filter_information = dict() filter_information = dict()
for filter_line in filter_file.readlines(): for filter_line in filter_file.readlines():

View File

@ -21,5 +21,6 @@ class DatastructureError(Exception):
class OverwriteError(IOError): class OverwriteError(IOError):
pass pass
class ParameterError(Exception): class ParameterError(Exception):
pass pass

View File

@ -2,6 +2,7 @@
import sys import sys
from PySide.QtCore import QThread, Signal from PySide.QtCore import QThread, Signal
class AutoPickThread(QThread): class AutoPickThread(QThread):
message = Signal(str) message = Signal(str)
finished = Signal() finished = Signal()
@ -28,6 +29,5 @@ class AutoPickThread(QThread):
sys.stdout = sys.__stdout__ sys.stdout = sys.__stdout__
self.finished.emit() self.finished.emit()
def write(self, text): def write(self, text):
self.message.emit(text) self.message.emit(text)

View File

@ -10,6 +10,7 @@ import numpy as np
from obspy.core import UTCDateTime from obspy.core import UTCDateTime
import obspy.core.event as ope import obspy.core.event as ope
def createAmplitude(pickID, amp, unit, category, cinfo): def createAmplitude(pickID, amp, unit, category, cinfo):
''' '''
@ -28,6 +29,7 @@ def createAmplitude(pickID, amp, unit, category, cinfo):
amplitude.pick_id = pickID amplitude.pick_id = pickID
return amplitude return amplitude
def createArrival(pickresID, cinfo, phase, azimuth=None, dist=None): def createArrival(pickresID, cinfo, phase, azimuth=None, dist=None):
''' '''
createArrival - function to create an Obspy Arrival createArrival - function to create an Obspy Arrival
@ -56,6 +58,7 @@ def createArrival(pickresID, cinfo, phase, azimuth=None, dist=None):
arrival.distance = dist arrival.distance = dist
return arrival return arrival
def createCreationInfo(agency_id=None, creation_time=None, author=None): def createCreationInfo(agency_id=None, creation_time=None, author=None):
''' '''
@ -71,6 +74,7 @@ def createCreationInfo(agency_id=None, creation_time=None, author=None):
return ope.CreationInfo(agency_id=agency_id, author=author, return ope.CreationInfo(agency_id=agency_id, author=author,
creation_time=creation_time) creation_time=creation_time)
def createEvent(origintime, cinfo, originloc=None, etype=None, resID=None, def createEvent(origintime, cinfo, originloc=None, etype=None, resID=None,
authority_id=None): authority_id=None):
''' '''
@ -115,6 +119,7 @@ def createEvent(origintime, cinfo, originloc=None, etype=None, resID=None,
event.origins = [o] event.origins = [o]
return event return event
def createMagnitude(originID, cinfo): def createMagnitude(originID, cinfo):
''' '''
createMagnitude - function to create an ObsPy Magnitude object createMagnitude - function to create an ObsPy Magnitude object
@ -129,6 +134,7 @@ def createMagnitude(originID, cinfo):
magnitude.origin_id = originID magnitude.origin_id = originID
return magnitude return magnitude
def createOrigin(origintime, cinfo, latitude, longitude, depth): def createOrigin(origintime, cinfo, latitude, longitude, depth):
''' '''
createOrigin - function to create an ObsPy Origin createOrigin - function to create an ObsPy Origin
@ -158,6 +164,7 @@ def createOrigin(origintime, cinfo, latitude, longitude, depth):
origin.depth = depth origin.depth = depth
return origin return origin
def createPick(origintime, picknum, picktime, eventnum, cinfo, phase, station, def createPick(origintime, picknum, picktime, eventnum, cinfo, phase, station,
wfseedstr, authority_id): wfseedstr, authority_id):
''' '''
@ -196,6 +203,7 @@ def createPick(origintime, picknum, picktime, eventnum, cinfo, phase, station,
pick.waveform_id = ope.ResourceIdentifier(id=wfseedstr, prefix='file:/') pick.waveform_id = ope.ResourceIdentifier(id=wfseedstr, prefix='file:/')
return pick return pick
def createResourceID(timetohash, restype, authority_id=None, hrstr=None): def createResourceID(timetohash, restype, authority_id=None, hrstr=None):
''' '''
@ -220,6 +228,7 @@ def createResourceID(timetohash, restype, authority_id=None, hrstr=None):
resID.convertIDToQuakeMLURI(authority_id=authority_id) resID.convertIDToQuakeMLURI(authority_id=authority_id)
return resID return resID
def demeanTrace(trace, window): def demeanTrace(trace, window):
""" """
returns the DATA where each trace is demean by the average value within returns the DATA where each trace is demean by the average value within
@ -234,6 +243,7 @@ def demeanTrace(trace, window):
trace.data -= trace.data[window].mean() trace.data -= trace.data[window].mean()
return trace return trace
def findComboBoxIndex(combo_box, val): def findComboBoxIndex(combo_box, val):
""" """
Function findComboBoxIndex takes a QComboBox object and a string and Function findComboBoxIndex takes a QComboBox object and a string and
@ -246,6 +256,7 @@ def findComboBoxIndex(combo_box, val):
""" """
return combo_box.findText(val) if combo_box.findText(val) is not -1 else 0 return combo_box.findText(val) if combo_box.findText(val) is not -1 else 0
def find_nearest(array, value): def find_nearest(array, value):
''' '''
Function find_nearest takes an array and a value and returns the Function find_nearest takes an array and a value and returns the
@ -256,6 +267,7 @@ def find_nearest(array, value):
''' '''
return (np.abs(array - value)).argmin() return (np.abs(array - value)).argmin()
def fnConstructor(s): def fnConstructor(s):
''' '''
@ -277,6 +289,7 @@ def fnConstructor(s):
fn = '_' + fn fn = '_' + fn
return fn return fn
def getGlobalTimes(stream): def getGlobalTimes(stream):
''' '''
@ -293,6 +306,7 @@ def getGlobalTimes(stream):
max_end = trace.stats.endtime max_end = trace.stats.endtime
return min_start, max_end return min_start, max_end
def getHash(time): def getHash(time):
''' '''
:param time: time object for which a hash should be calculated :param time: time object for which a hash should be calculated
@ -303,6 +317,7 @@ def getHash(time):
hg.update(time.strftime('%Y-%m-%d %H:%M:%S.%f')) hg.update(time.strftime('%Y-%m-%d %H:%M:%S.%f'))
return hg.hexdigest() return hg.hexdigest()
def getLogin(): def getLogin():
''' '''
@ -310,6 +325,7 @@ def getLogin():
''' '''
return pwd.getpwuid(os.getuid())[0] return pwd.getpwuid(os.getuid())[0]
def getOwner(fn): def getOwner(fn):
''' '''
@ -319,6 +335,7 @@ def getOwner(fn):
''' '''
return pwd.getpwuid(os.stat(fn).st_uid).pw_name return pwd.getpwuid(os.stat(fn).st_uid).pw_name
def getPatternLine(fn, pattern): def getPatternLine(fn, pattern):
""" """
Takes a file name and a pattern string to search for in the file and Takes a file name and a pattern string to search for in the file and
@ -343,6 +360,7 @@ def getPatternLine(fn, pattern):
return None return None
def isSorted(iterable): def isSorted(iterable):
''' '''
@ -352,6 +370,7 @@ def isSorted(iterable):
''' '''
return sorted(iterable) == iterable return sorted(iterable) == iterable
def prepTimeAxis(stime, trace): def prepTimeAxis(stime, trace):
''' '''
@ -378,6 +397,7 @@ def prepTimeAxis(stime, trace):
'delta: {2}'.format(nsamp, len(time_ax), tincr)) 'delta: {2}'.format(nsamp, len(time_ax), tincr))
return time_ax return time_ax
def scaleWFData(data, factor=None, components='all'): def scaleWFData(data, factor=None, components='all'):
""" """
produce scaled waveforms from given waveform data and a scaling factor, produce scaled waveforms from given waveform data and a scaling factor,
@ -409,6 +429,7 @@ def scaleWFData(data, factor=None, components='all'):
return data return data
def runProgram(cmd, parameter=None): def runProgram(cmd, parameter=None):
""" """
run an external program specified by cmd with parameters input returning the run an external program specified by cmd with parameters input returning the
@ -429,6 +450,8 @@ def runProgram(cmd, parameter=None):
output = subprocess.check_output('{} | tee /dev/stderr'.format(cmd), output = subprocess.check_output('{} | tee /dev/stderr'.format(cmd),
shell=True) shell=True)
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -31,12 +31,15 @@
# #
# include RELEASE-VERSION # include RELEASE-VERSION
from __future__ import print_function
__all__ = "get_git_version" __all__ = "get_git_version"
# NO IMPORTS FROM PYLOT IN THIS FILE! (file gets used at installation time) # NO IMPORTS FROM PYLOT IN THIS FILE! (file gets used at installation time)
import os import os
import inspect import inspect
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
# NO IMPORTS FROM PYLOT IN THIS FILE! (file gets used at installation time) # NO IMPORTS FROM PYLOT IN THIS FILE! (file gets used at installation time)
script_dir = os.path.abspath(os.path.dirname(inspect.getfile( script_dir = os.path.abspath(os.path.dirname(inspect.getfile(
@ -108,4 +111,4 @@ def get_git_version(abbrev=4):
if __name__ == "__main__": if __name__ == "__main__":
print get_git_version() print(get_git_version())

View File

@ -9,6 +9,7 @@ import datetime
import numpy as np import numpy as np
from matplotlib.figure import Figure from matplotlib.figure import Figure
try: try:
from matplotlib.backends.backend_qt4agg import FigureCanvas from matplotlib.backends.backend_qt4agg import FigureCanvas
except ImportError: except ImportError:
@ -167,6 +168,7 @@ class MPLWidget(FigureCanvas):
xycoords='axes fraction') xycoords='axes fraction')
axann.set_bbox(dict(facecolor='lightgrey', alpha=.6)) axann.set_bbox(dict(facecolor='lightgrey', alpha=.6))
class PickDlg(QDialog): class PickDlg(QDialog):
def __init__(self, parent=None, data=None, station=None, picks=None, def __init__(self, parent=None, data=None, station=None, picks=None,
rotate=False): rotate=False):
@ -516,7 +518,6 @@ class PickDlg(QDialog):
inoise = getnoisewin(t, ini_pick, noise_win, gap_win) inoise = getnoisewin(t, ini_pick, noise_win, gap_win)
trace = demeanTrace(trace=trace, window=inoise) trace = demeanTrace(trace=trace, window=inoise)
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 * 2.5, noiselevel * 2.5]) + self.setYLims(np.array([-noiselevel * 2.5, noiselevel * 2.5]) +
trace_number) trace_number)
@ -757,7 +758,6 @@ class PickDlg(QDialog):
self.drawPicks() self.drawPicks()
self.draw() self.draw()
def setPlotLabels(self): def setPlotLabels(self):
# get channel labels # get channel labels
@ -1052,7 +1052,6 @@ class LocalisationTab(PropTab):
return values return values
class NewEventDlg(QDialog): class NewEventDlg(QDialog):
def __init__(self, parent=None, titleString="Create a new event"): def __init__(self, parent=None, titleString="Create a new event"):
""" """
@ -1293,6 +1292,8 @@ class HelpForm(QDialog):
def updatePageTitle(self): def updatePageTitle(self):
self.pageLabel.setText(self.webBrowser.documentTitle()) self.pageLabel.setText(self.webBrowser.documentTitle())
if __name__ == '__main__': if __name__ == '__main__':
import doctest import doctest
doctest.testmod() doctest.testmod()