Merge branch 'develop' of ariadne.geophysik.ruhr-uni-bochum.de:/data/git/pylot into develop

This commit is contained in:
2016-08-30 15:00:34 +02:00
8 changed files with 208 additions and 84 deletions

View File

@@ -1,6 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import copy
import glob
import os
from obspy import read_events, read_inventory
@@ -434,7 +435,8 @@ class Data(object):
#firstonset = find_firstonset(picks)
if self.getEvtData().picks:
raise OverwriteError('Actual picks would be overwritten!')
picks = picks_from_picksdict(picks)
else:
picks = picks_from_picksdict(picks)
self.getEvtData().picks = picks
# if 'smi:local' in self.getID() and firstonset:
# fonset_str = firstonset.strftime('%Y_%m_%d_%H_%M_%S')
@@ -443,25 +445,22 @@ class Data(object):
# self.getEvtData().resource_id = ID
def applyArrivals(arrivals):
"""
:param arrivals:
"""
pass
def applyEvent(event):
"""
takes an `obspy.core.event.Event` object and applies all new
information on the event to the actual data
:param event:
"""
if not self.isNew():
self.setEvtData(event)
else:
raise OverwriteError('Acutal event would be overwritten!')
# prevent overwriting uncertainty information
picks = copy.deepcopy(self.getEvtData().picks)
event.picks = picks
# apply event information from location
self.getEvtData().update(event)
applydata = {'pick': applyPicks,
'arrival': applyArrivals,
'event': applyEvent}
applydata[type](data)

View File

@@ -117,7 +117,7 @@ def picksdict_from_pilot(fn):
except IndexError as e:
print(e.message + '\ntake two times the largest default error value')
spe = timeerrors[onset_name][-1] * 2
phases[onset_name] = dict(mpp=pick, spe=spe)
phases[onset_name] = dict(mpp=pick, spe=spe, weight=ierror)
picks[station] = phases
return picks
@@ -395,7 +395,11 @@ def writephases(arrivals, fformat, filename):
for key in arrivals:
# P onsets
if arrivals[key]['P']:
fm = arrivals[key]['P']['fm']
try:
fm = arrivals[key]['P']['fm']
except KeyError as e:
print(e)
fm = None
if fm == None:
fm = '?'
onset = arrivals[key]['P']['mpp']
@@ -407,10 +411,12 @@ def writephases(arrivals, fformat, filename):
ss = onset.second
ms = onset.microsecond
ss_ms = ss + ms / 1000000.0
if arrivals[key]['P']['weight'] < 4:
pweight = 1 # use pick
else:
pweight = 0 # do not use pick
pweight = 1 # use pick
try:
if arrivals[key]['P']['weight'] >= 4:
pweight = 0 # do not use pick
except KeyError as e:
print(e.message + '; no weight set during processing')
fid.write('%s ? ? ? P %s %d%02d%02d %02d%02d %7.4f GAU 0 0 0 0 %d \n' % (key,
fm,
year,
@@ -421,7 +427,7 @@ def writephases(arrivals, fformat, filename):
ss_ms,
pweight))
# S onsets
if arrivals[key]['S']:
if arrivals[key].has_key('S') and arrivals[key]['S']:
fm = '?'
onset = arrivals[key]['S']['mpp']
year = onset.year
@@ -432,10 +438,12 @@ def writephases(arrivals, fformat, filename):
ss = onset.second
ms = onset.microsecond
ss_ms = ss + ms / 1000000.0
if arrivals[key]['S']['weight'] < 4:
sweight = 1 # use pick
else:
sweight = 0 # do not use pick
sweight = 1 # use pick
try:
if arrivals[key]['S']['weight'] >= 4:
sweight = 0 # do not use pick
except KeyError as e:
print(str(e) + '; no weight set during processing')
fid.write('%s ? ? ? S %s %d%02d%02d %02d%02d %7.4f GAU 0 0 0 0 %d \n' % (key,
fm,
year,

View File

@@ -1,2 +1,21 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pylot.core.io.phases import writephases
from pylot.core.util.version import get_git_version as _getVersionString
__version__ = _getVersionString()
def export(picks, fnout):
'''
Take <picks> dictionary and exports picking data to a NLLOC-obs
<phasefile> without creating an ObsPy event object.
:param picks: picking data dictionary
:type picks: dict
:param fnout: complete path to the exporting obs file
:type fnout: str
'''
# write phases to NLLoc-phase file
writephases(picks, 'HYPO71', fnout)

View File

@@ -3,14 +3,18 @@
import subprocess
import os
import glob
from obspy import read_events
from pylot.core.io.phases import writephases
from pylot.core.util.utils import getPatternLine, runProgram
from pylot.core.util.utils import getPatternLine, runProgram, which
from pylot.core.util.version import get_git_version as _getVersionString
__version__ = _getVersionString()
class NLLocError(EnvironmentError):
pass
def picksExport(picks, locrt, phasefile):
def export(picks, fnout):
'''
Take <picks> dictionary and exports picking data to a NLLOC-obs
<phasefile> without creating an ObsPy event object.
@@ -18,17 +22,14 @@ def picksExport(picks, locrt, phasefile):
:param picks: picking data dictionary
:type picks: dict
:param locrt: choose location routine
:type locrt: str
:param phasefile: complete path to the exporting obs file
:type phasefile: str
:param fnout: complete path to the exporting obs file
:type fnout: str
'''
# write phases to NLLoc-phase file
writephases(picks, locrt, phasefile)
writephases(picks, 'NLLoc', fnout)
def modifyInputFile(ctrfn, root, nllocoutn, phasefn, tttn):
def modify_inputs(ctrfn, root, nllocoutn, phasefn, tttn):
'''
:param ctrfn: name of NLLoc-control file
:type: str
@@ -66,24 +67,32 @@ def modifyInputFile(ctrfn, root, nllocoutn, phasefn, tttn):
nllfile.close()
def locate(call, fnin):
'''
Takes paths to NLLoc executable <call> and input parameter file <fnin>
and starts the location calculation.
def locate(fnin):
"""
takes an external program name
:param fnin:
:return:
"""
:param call: full path to NLLoc executable
:type call: str
exe_path = which('NLLoc')
if exe_path is None:
raise NLLocError('NonLinLoc executable not found; check your '
'environment variables')
:param fnin: full path to input parameter file
:type fnin: str
'''
# locate the event
runProgram(call, fnin)
# locate the event utilizing external NonLinLoc installation
try:
runProgram(exe_path, fnin)
except subprocess.CalledProcessError as e:
raise RuntimeError(e.output)
def readLocation(fn):
pass
def read_location(fn):
path, file = os.path.split(fn)
file = glob.glob1(path, file + '.[0-9]*.grid0.loc.hyp')
if len(file) > 1:
raise IOError('ambiguous location name {0}'.format(file))
fn = os.path.join(path, file[0])
return read_events(fn)[0]
if __name__ == '__main__':

View File

@@ -277,6 +277,15 @@ def getPatternLine(fn, pattern):
return None
def is_executable(fn):
"""
takes a filename and returns True if the file is executable on the system
and False otherwise
:param fn: path to the file to be tested
:return: True or False
"""
return os.path.isfile(fn) and os.access(fn, os.X_OK)
def isSorted(iterable):
'''
@@ -393,9 +402,44 @@ def runProgram(cmd, parameter=None):
cmd.strip()
cmd += ' %s 2>&1' % parameter
output = subprocess.check_output('{} | tee /dev/stderr'.format(cmd),
shell=True)
subprocess.check_output('{} | tee /dev/stderr'.format(cmd), shell=True)
def which(program):
"""
takes a program name and returns the full path to the executable or None
modified after: http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
:param program: name of the desired external program
:return: full path of the executable file
"""
try:
from PySide.QtCore import QSettings
settings = QSettings()
for key in settings.allKeys():
if 'binPath' in key:
os.environ['PATH'] += ':{0}'.format(settings.value(key))
except ImportError as e:
print(e.message)
def is_exe(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
def ext_candidates(fpath):
yield fpath
for ext in os.environ.get("PATHEXT", "").split(os.pathsep):
yield fpath + ext
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
for candidate in ext_candidates(exe_file):
if is_exe(candidate):
return candidate
return None
if __name__ == "__main__":
import doctest

View File

@@ -1337,8 +1337,8 @@ class LocalisationTab(PropTab):
self.locToolComboBox.setCurrentIndex(toolind)
curroot = settings.value("%s/rootPath".format(curtool), None)
curbin = settings.value("%s/binPath".format(curtool), None)
curroot = settings.value("{0}/rootPath".format(curtool), None)
curbin = settings.value("{0}/binPath".format(curtool), None)
self.rootlabel = QLabel("root directory")
self.binlabel = QLabel("bin directory")
@@ -1385,8 +1385,8 @@ class LocalisationTab(PropTab):
def getValues(self):
loctool = self.locToolComboBox.currentText()
values = {"%s/rootPath".format(loctool): self.rootedit.text(),
"%s/binPath".format(loctool): self.binedit.text(),
values = {"{0}/rootPath".format(loctool): self.rootedit.text(),
"{0}/binPath".format(loctool): self.binedit.text(),
"loc/tool": loctool}
return values