12 Commits
Author SHA1 Message Date
sebastianw b5ba62e86f [change] replaced all occurrences of PySide and QtGui references with the PySide2 substitue 2021-01-29 11:21:44 +01:00
sebastianw 21f4567236 Merge branch 'feature/port-to-python-3.9.0' of ssh://ariadne.geophysik.ruhr-uni-bochum.de:/data/git/pylot into feature/port-to-python-3.9.0 2021-01-29 11:06:42 +01:00
sebastianw 553b935d69 [change] adopted map_projections for the use of cartopy instead of basemap (WIP) 2021-01-29 11:04:22 +01:00
sebastianw 0bdfd96659 correct for deprecated condition usage 2021-01-29 11:04:16 +01:00
sebastianw 79fac36cf5 [init] started porting to the next python version
Aiming also to avoid deprecations and outdated versions of dependencies.
2021-01-29 11:04:16 +01:00
marcel adc3304840 release version 0.2
release notes:
==============
Features:
- centralize all functionalities of PyLoT and control them from within the main GUI
- handling multiple events inside GUI with project files (save and load work progress)
- GUI based adjustments of pick parameters and I/O
- interactive tuning of parameters from within the GUI
- call automatic picking algorithm from within the GUI
- comparison of automatic with manual picks for multiple events using clear differentiation of manual picks into 'tune' and 'test-set' (beta)
- manual picking of different (user defined) phase types
- phase onset estimation with ObsPy TauPy

- interactive zoom/scale functionalities in all plots (mousewheel, pan, pan-zoom)
- array map to visualize stations and control onsets (beta feature, switch to manual picks not implemented)

Platform support:
- python 3 support
- Windows support

Performance:
- multiprocessing for automatic picking and restitution of multiple stations
- use pyqtgraph library for better performance on main waveform plot

Visualization:
- pick uncertainty (quality classes) visualization with gradients
- pick color unification for all plots
- new icons and stylesheets

Known Issues:
2021-01-29 11:04:05 +01:00
Marc S. Boxberg 417316a8bb release version: 0.1a
release notes:
==============
Features
- consistent manual phase picking through predefined SNR dependant zoom level
- uniform uncertainty estimation from waveform's properties for automatic and manual picks
- pdf representation and comparison of picks taking the uncertainty intrinsically into account
- Richter and moment magnitude estimation
- location determination with external installation of [NonLinLoc](http://alomax.free.fr/nlloc/index.html)
Known issues
- Magnitude estimation from manual PyLoT takes some time (instrument correction)
2021-01-29 11:03:25 +01:00
marcel 889e632198 [update] README.md 2021-01-29 10:54:48 +01:00
sebastianw 543f12f1a2 [change] adopted map_projections for the use of cartopy instead of basemap (WIP) 2020-12-06 17:39:34 +01:00
sebastianw 2c2eca37e3 [change] made parameter 'extent' optional since it was never meant to be mandatory before 2020-10-27 07:03:59 +01:00
sebastianw 55810b9926 correct for deprecated condition usage 2020-10-21 15:24:35 +02:00
sebastianw 8b4eed3974 [init] started porting to the next python version
Aiming also to avoid deprecations and outdated versions of dependencies.
2020-10-19 18:10:26 +02:00
110 changed files with 116212 additions and 196449 deletions

No files matched your search

-2
View File
@@ -1,5 +1,3 @@
*.pyc *.pyc
*~ *~
.idea
pylot/RELEASE-VERSION pylot/RELEASE-VERSION
/tests/test_autopicker/dmt_database_test/
-39
View File
@@ -1,39 +0,0 @@
Darius Arnold <Darius.Arnold@ruhr-uni-bochum.de> <Darius_A@web.de>
Darius Arnold <Darius.Arnold@ruhr-uni-bochum.de> <darius.arnold@rub.de>
Darius Arnold <Darius.Arnold@ruhr-uni-bochum.de> <darius.arnold@ruhr-uni-bochum.de>
Darius Arnold <Darius.Arnold@ruhr-uni-bochum.de> <mail@dariusarnold.de>
Dennis Wlecklik <dennisw@minos02.geophysik.ruhr-uni-bochum.de>
Jeldrik Gaal <jeldrikgaal@gmail.com>
Kaan Coekerim <kaan.coekerim@ruhr-uni-bochum.de>
Kaan Coekerim <kaan.coekerim@ruhr-uni-bochum.de> <kaan.coekerim@rub.de>
Ludger Kueperkoch <kueperkoch@igem-energie.de> <kueperkoch@bestec-for-nature.com>
Ludger Kueperkoch <kueperkoch@igem-energie.de> <ludger@quake2.(none)>
Ludger Kueperkoch <kueperkoch@igem-energie.de> <ludger@sauron.bestec-for-nature>
Marc S. Boxberg <marc.boxberg@rub.de>
Marcel Paffrath <marcel.paffrath@ruhr-uni-bochum.de> <marcel.paffrath@rub.de>
Marcel Paffrath <marcel.paffrath@ruhr-uni-bochum.de> <marcel@minos01.geophysik.ruhr-uni-bochum.de>
Marcel Paffrath <marcel.paffrath@ruhr-uni-bochum.de> <marcel@minos02.geophysik.ruhr-uni-bochum.de>
Marcel Paffrath <marcel.paffrath@ruhr-uni-bochum.de> <marcel@minos25.geophysik.ruhr-uni-bochum.de>
Marcel Paffrath <marcel.paffrath@ruhr-uni-bochum.de> <marcel@email.com>
Sally Zimmermann <sally.zimmermann@ruhr-uni-bochum.de>
Sebastian Wehling-Benatelli <sebastian.wehling-benatelli@cgi.com> <sebastianw@minos01.geophysik.ruhr-uni-bochum.de>
Sebastian Wehling-Benatelli <sebastian.wehling-benatelli@cgi.com> <sebastianw@minos02.geophysik.ruhr-uni-bochum.de>
Sebastian Wehling-Benatelli <sebastian.wehling-benatelli@cgi.com> <sebastianw@minos22.geophysik.ruhr-uni-bochum.de>
Sebastian Wehling-Benatelli <sebastian.wehling-benatelli@cgi.com> <sebastian.wehling-benatelli@scisys.de>
Sebastian Wehling-Benatelli <sebastian.wehling-benatelli@cgi.com> <sebastian.wehling@rub.de>
Sebastian Wehling-Benatelli <sebastian.wehling-benatelli@cgi.com> <sebastian.wehling@rub.de>
Sebastian Wehling-Benatelli <sebastian.wehling-benatelli@cgi.com> <DarkBeQst@users.noreply.github.com>
Thomas Moeller <thomas.moeller@rub.de>
Ann-Christin Koch <ann-christin.koch@ruhr-uni-bochum.de> <Ann-Christin.Koch@ruhr-uni-bochum.de>
Sebastian Priebe <sebastian.priebe@rub.de>
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

+739 -1613
View File
File diff suppressed because it is too large. Load diff
+66 -54
View File
@@ -1,98 +1,110 @@
# PyLoT # PyLoT
version: 0.3 version: 0.2
The Python picking and Localisation Tool The Python picking and Localisation Tool
This python library contains a graphical user interfaces for picking seismic phases. This software needs [ObsPy][ObsPy] This python library contains a graphical user interfaces for picking
and the PySide2 Qt5 bindings for python to be installed first. seismic phases. This software needs [ObsPy][ObsPy]
and the PySide Qt4 bindings for python to be installed first.
PILOT has originally been developed in Mathworks' MatLab. In order to distribute PILOT without facing portability PILOT has originally been developed in Mathworks' MatLab. In order to
problems, it has been decided to redevelop the software package in Python. The great work of the ObsPy group allows easy distribute PILOT without facing portability problems, it has been decided
handling of a bunch of seismic data and PyLoT will benefit a lot compared to the former MatLab version. to redevelop the software package in Python. The great work of the ObsPy
group allows easy handling of a bunch of seismic data and PyLoT will
benefit a lot compared to the former MatLab version.
The development of PyLoT is part of the joint research project MAGS2, AlpArray and AdriaArray. The development of PyLoT is part of the joint research project MAGS2 and AlpArray.
## Installation ## Installation
At the moment there is no automatic installation procedure available for PyLoT. Best way to install is to clone the At the moment there is no automatic installation procedure available for PyLoT.
repository and add the path to your Python path. Best way to install is to clone the repository and add the path to your Python path.
It is highly recommended to use Anaconda for a simple creation of a Python installation using either the *pylot.yml* or the *requirements.txt* file found in the PyLoT root directory. First make sure that the *conda-forge* channel is available in your Anaconda installation:
conda config --add channels conda-forge
Afterwards run (from the PyLoT main directory where the files *requirements.txt* and *pylot.yml* are located)
conda env create -f pylot.yml
or
conda create -c conda-forge --name pylot_311 python=3.11 --file requirements.txt
to create a new Anaconda environment called *pylot_311*.
Afterwards activate the environment by typing
conda activate pylot_311
#### Prerequisites: #### Prerequisites:
In order to run PyLoT you need to install: In order to run PyLoT you need to install:
- Python 3 - python 2 or 3
- cartopy
- joblib
- obspy
- pyaml
- pyqtgraph
- pyside2
(the following are already dependencies of the above packages):
- scipy - scipy
- numpy - numpy
- matplotlib - matplotlib
- obspy
- pyside
#### Some handwork: #### Some handwork:
Some extra information on error estimates (just needed for reading old PILOT data) and the Richter magnitude scaling PyLoT needs a properties folder on your system to work. It should be situated in your home directory
relation (on Windows usually C:/Users/*username*):
mkdir ~/.pylot
In the next step you have to copy some files to this directory:
*for local distance seismicity*
cp path-to-pylot/inputs/pylot_local.in ~/.pylot/pylot.in
*for regional distance seismicity*
cp path-to-pylot/inputs/pylot_regional.in ~/.pylot/pylot.in
*for global distance seismicity*
cp path-to-pylot/inputs/pylot_global.in ~/.pylot/pylot.in
and some extra information on error estimates (just needed for reading old PILOT data) and the Richter magnitude scaling relation
cp path-to-pylot/inputs/PILOT_TimeErrors.in path-to-pylot/inputs/richter_scaling.data ~/.pylot/ cp path-to-pylot/inputs/PILOT_TimeErrors.in path-to-pylot/inputs/richter_scaling.data ~/.pylot/
You may need to do some modifications to these files. Especially folder names should be reviewed. You may need to do some modifications to these files. Especially folder names should be reviewed.
PyLoT has been tested on Mac OSX (10.11), Debian Linux 8 and on Windows 10/11. PyLoT has been tested on Mac OSX (10.11), Debian Linux 8 and on Windows 10.
## Example Dataset
An example dataset with waveform data, metadata and automatic picks in the obspy-dmt dataset format for testing the teleseismic picking can be found at https://zenodo.org/doi/10.5281/zenodo.13759803
## Release notes ## Release notes
#### Features: #### Features:
- event organisation in project files and waveform visualisation - centralize all functionalities of PyLoT and control them from within the main GUI
- consistent manual phase picking through predefined SNR dependant zoom level - handling multiple events inside GUI with project files (save and load work progress)
- consistent automatic phase picking routines using Higher Order Statistics, AIC and Autoregression - GUI based adjustments of pick parameters and I/O
- pick correlation correction for teleseismic waveforms - interactive tuning of parameters from within the GUI
- interactive tuning of auto-pick parameters - call automatic picking algorithm from within the GUI
- uniform uncertainty estimation from waveform's properties for automatic and manual picks - comparison of automatic with manual picks for multiple events using clear differentiation of manual picks into 'tune' and 'test-set' (beta)
- pdf representation and comparison of picks taking the uncertainty intrinsically into account - manual picking of different (user defined) phase types
- Richter and moment magnitude estimation - phase onset estimation with ObsPy TauPy
- location determination with external installation of [NonLinLoc](http://alomax.free.fr/nlloc/index.html) - interactive zoom/scale functionalities in all plots (mousewheel, pan, pan-zoom)
- array map to visualize stations and control onsets (beta feature, switch to manual picks not implemented)
#### Known issues: ##### Platform support:
- Python 3 support
- Windows support
Current release is still in development progress and has several issues. We are currently lacking manpower, but hope to assess many of the issues in the near future. ##### Performance:
- multiprocessing for automatic picking and restitution of multiple stations
- use pyqtgraph library for better performance on main waveform plot
##### Visualization:
- pick uncertainty (quality classes) visualization with gradients
- pick color unification for all plots
- new icons and stylesheets
#### Known Issues:
- some Qt related errors might occur at runtime
- filter toggle not working in pickDlg
- PyLoT data structure requires at least three parent directories for waveform data directory
## Staff ## Staff
Developer(s): M. Paffrath, S. Wehling-Benatelli, L. Kueperkoch, D. Arnold, K. Cökerim, K. Olbert, M. Bischoff, C. Wollin, M. Rische, S. Zimmermann Original author(s): L. Kueperkoch, S. Wehling-Benatelli, M. Bischoff (PILOT)
Original author(s): M. Rische, S. Wehling-Benatelli, L. Kueperkoch, M. Bischoff (PILOT) Developer(s): S. Wehling-Benatelli, L. Kueperkoch, M. Paffrath, K. Olbert,
M. Bischoff, C. Wollin, M. Rische
Others: A. Bruestle, T. Meier, W. Friederich Others: A. Bruestle, T. Meier, W. Friederich
[ObsPy]: http://github.com/obspy/obspy/wiki [ObsPy]: http://github.com/obspy/obspy/wiki
March 2025 September 2017
+28 -24
View File
@@ -8,7 +8,6 @@ import datetime
import glob import glob
import os import os
import traceback import traceback
from obspy import read_events from obspy import read_events
from obspy.core.event import ResourceIdentifier from obspy.core.event import ResourceIdentifier
@@ -19,7 +18,7 @@ import pylot.core.loc.hypodd as hypodd
import pylot.core.loc.hyposat as hyposat import pylot.core.loc.hyposat as hyposat
import pylot.core.loc.nll as nll import pylot.core.loc.nll as nll
import pylot.core.loc.velest as velest import pylot.core.loc.velest as velest
# from PySide.QtGui import QWidget, QInputDialog # from PySide2.QtWidgets import QWidget, QInputDialog
from pylot.core.analysis.magnitude import MomentMagnitude, LocalMagnitude from pylot.core.analysis.magnitude import MomentMagnitude, LocalMagnitude
from pylot.core.io.data import Data from pylot.core.io.data import Data
from pylot.core.io.inputs import PylotParameter from pylot.core.io.inputs import PylotParameter
@@ -28,7 +27,7 @@ from pylot.core.util.dataprocessing import restitute_data, Metadata
from pylot.core.util.defaults import SEPARATOR from pylot.core.util.defaults import SEPARATOR
from pylot.core.util.event import Event from pylot.core.util.event import Event
from pylot.core.util.structure import DATASTRUCTURE from pylot.core.util.structure import DATASTRUCTURE
from pylot.core.util.utils import get_none, trim_station_components, check4gapsAndRemove, check4doubled, \ from pylot.core.util.utils import get_None, trim_station_components, check4gapsAndRemove, check4doubled, \
check4rotated check4rotated
from pylot.core.util.version import get_git_version as _getVersionString from pylot.core.util.version import get_git_version as _getVersionString
@@ -91,9 +90,9 @@ def autoPyLoT(input_dict=None, parameter=None, inputfile=None, fnames=None, even
sp=sp_info) sp=sp_info)
print(splash) print(splash)
parameter = get_none(parameter) parameter = get_None(parameter)
inputfile = get_none(inputfile) inputfile = get_None(inputfile)
eventid = get_none(eventid) eventid = get_None(eventid)
fig_dict = None fig_dict = None
fig_dict_wadatijack = None fig_dict_wadatijack = None
@@ -119,9 +118,13 @@ def autoPyLoT(input_dict=None, parameter=None, inputfile=None, fnames=None, even
obspyDMT_wfpath = input_dict['obspyDMT_wfpath'] obspyDMT_wfpath = input_dict['obspyDMT_wfpath']
if not parameter: if not parameter:
if not inputfile: if inputfile:
print('Using default input parameter') parameter = PylotParameter(inputfile)
parameter = PylotParameter(inputfile) # iplot = parameter['iplot']
else:
infile = os.path.join(os.path.expanduser('~'), '.pylot', 'pylot.in')
print('Using default input file {}'.format(infile))
parameter = PylotParameter(infile)
else: else:
if not type(parameter) == PylotParameter: if not type(parameter) == PylotParameter:
print('Wrong input type for parameter: {}'.format(type(parameter))) print('Wrong input type for parameter: {}'.format(type(parameter)))
@@ -136,11 +139,13 @@ def autoPyLoT(input_dict=None, parameter=None, inputfile=None, fnames=None, even
if parameter.hasParam('datastructure'): if parameter.hasParam('datastructure'):
# getting information on data structure # getting information on data structure
datastructure = DATASTRUCTURE[parameter.get('datastructure')]() datastructure = DATASTRUCTURE[parameter.get('datastructure')]()
dsfields = {'dpath': parameter.get('datapath'),} dsfields = {'root': parameter.get('rootpath'),
'dpath': parameter.get('datapath'),
'dbase': parameter.get('database')}
exf = ['dpath'] exf = ['root', 'dpath', 'dbase']
if parameter['eventID'] != '*' and fnames == 'None': if parameter['eventID'] is not '*' and fnames == 'None':
dsfields['eventID'] = parameter['eventID'] dsfields['eventID'] = parameter['eventID']
exf.append('eventID') exf.append('eventID')
@@ -148,7 +153,7 @@ def autoPyLoT(input_dict=None, parameter=None, inputfile=None, fnames=None, even
datastructure.setExpandFields(exf) datastructure.setExpandFields(exf)
# check if default location routine NLLoc is available and all stations are used # check if default location routine NLLoc is available and all stations are used
if get_none(parameter['nllocbin']) and station == 'all': if get_None(parameter['nllocbin']) and station == 'all':
locflag = 1 locflag = 1
# get NLLoc-root path # get NLLoc-root path
nllocroot = parameter.get('nllocroot') nllocroot = parameter.get('nllocroot')
@@ -184,15 +189,15 @@ def autoPyLoT(input_dict=None, parameter=None, inputfile=None, fnames=None, even
if not input_dict: if not input_dict:
# started in production mode # started in production mode
datapath = datastructure.expandDataPath() datapath = datastructure.expandDataPath()
if fnames in [None, 'None'] and parameter['eventID'] == '*': if fnames == 'None' and parameter['eventID'] is '*':
# multiple event processing # multiple event processing
# read each event in database # read each event in database
events = [event for event in glob.glob(os.path.join(datapath, '*')) if events = [event for event in glob.glob(os.path.join(datapath, '*')) if
(os.path.isdir(event) and not event.endswith('EVENTS-INFO'))] (os.path.isdir(event) and not event.endswith('EVENTS-INFO'))]
elif fnames in [None, 'None'] and parameter['eventID'] != '*' and not type(parameter['eventID']) == list: elif fnames == 'None' and parameter['eventID'] is not '*' and not type(parameter['eventID']) == list:
# single event processing # single event processing
events = glob.glob(os.path.join(datapath, parameter['eventID'])) events = glob.glob(os.path.join(datapath, parameter['eventID']))
elif fnames in [None, 'None'] and type(parameter['eventID']) == list: elif fnames == 'None' and type(parameter['eventID']) == list:
# multiple event processing # multiple event processing
events = [] events = []
for eventID in parameter['eventID']: for eventID in parameter['eventID']:
@@ -204,10 +209,12 @@ def autoPyLoT(input_dict=None, parameter=None, inputfile=None, fnames=None, even
locflag = 2 locflag = 2
else: else:
# started in tune or interactive mode # started in tune or interactive mode
datapath = parameter['datapath'] datapath = os.path.join(parameter['rootpath'],
parameter['datapath'])
events = [] events = []
for eventID in eventid: for eventID in eventid:
events.append(os.path.join(datapath, events.append(os.path.join(datapath,
parameter['database'],
eventID)) eventID))
if not events: if not events:
@@ -234,15 +241,12 @@ def autoPyLoT(input_dict=None, parameter=None, inputfile=None, fnames=None, even
data.get_evt_data().path = eventpath data.get_evt_data().path = eventpath
print('Reading event data from filename {}...'.format(filename)) print('Reading event data from filename {}...'.format(filename))
except Exception as e: except Exception as e:
if type(e) == FileNotFoundError: print('Could not read event from file {}: {}'.format(filename, e))
print('Creating new event file.')
else:
print('Could not read event from file {}: {}'.format(filename, e))
data = Data() data = Data()
pylot_event = Event(eventpath) # event should be path to event directory pylot_event = Event(eventpath) # event should be path to event directory
data.setEvtData(pylot_event) data.setEvtData(pylot_event)
if fnames in [None, 'None']: if fnames == 'None':
data.setWFData(glob.glob(os.path.join(event_datapath, '*'))) data.setWFData(glob.glob(os.path.join(datapath, event_datapath, '*')))
# the following is necessary because within # the following is necessary because within
# multiple event processing no event ID is provided # multiple event processing no event ID is provided
# in autopylot.in # in autopylot.in
@@ -273,7 +277,7 @@ def autoPyLoT(input_dict=None, parameter=None, inputfile=None, fnames=None, even
if not wfdat: if not wfdat:
print('Could not find station {}. STOP!'.format(station)) print('Could not find station {}. STOP!'.format(station))
return return
# wfdat = remove_underscores(wfdat) #wfdat = remove_underscores(wfdat)
# trim components for each station to avoid problems with different trace starttimes for one station # trim components for each station to avoid problems with different trace starttimes for one station
wfdat = check4gapsAndRemove(wfdat) wfdat = check4gapsAndRemove(wfdat)
wfdat = check4doubled(wfdat) wfdat = check4doubled(wfdat)
+4 -10
View File
@@ -3,14 +3,8 @@
#$ -l low #$ -l low
#$ -cwd #$ -cwd
#$ -pe smp 40 #$ -pe smp 40
##$ -l mem=3G #$ -l mem=2G
#$ -l h_vmem=6G #$ -l h_vmem=2G
##$ -l os=*stretch #$ -l os=*stretch
#$ -q low.q@minos11,low.q@minos12,low.q@minos13,low.q@minos14,low.q@minos15
conda activate pylot_311 python ./autoPyLoT.py -i /home/marcel/.pylot/pylot_alparray_mantle_corr_stack_0.03-0.5.in -dmt processed -c $NSLOTS
#python ./autoPyLoT.py -i /home/marcel/.pylot/pylot_adriaarray_m5.0-5.4.in -c 20 -dmt processed
#python ./autoPyLoT.py -i /home/marcel/.pylot/pylot_adriaarray_m5.4-5.7.in -c 20 -dmt processed
#python ./autoPyLoT.py -i /home/marcel/.pylot/pylot_adriaarray_m5.7-6.0.in -c 20 -dmt processed
python ./autoPyLoT.py -i /home/marcel/.pylot/pylot_adriaarray_m6.0-10.0.in -c 20 -dmt processed
-77
View File
@@ -1,77 +0,0 @@
# Pick-Correlation Correction
## Introduction
Currently, the pick-correlation correction algorithm is not accessible from they PyLoT GUI. The main file *pick_correlation_correction.py* is located in the directory *pylot\correlation*.
The program only works for an obspy dmt database structure.
The basic workflow of the algorithm is shown in the following diagram. The first step **(1)** is the normal (automatic) picking procedure in PyLoT. Everything from step **(2)** to **(5)** is part of the correlation correction algorithm.
*Note: The first step is not required in case theoretical onsets are used instead of external picks when the parameter use_taupy_onsets is set to True. However, an existing event quakeML (.xml) file generated by PyLoT might be required for each event in case not external picks are used.*
![images/workflow_stacking.png](images/workflow_stacking.png)
A detailed description of the algorithm can be found in the corresponding publication:
*Paffrath, M., Friederich, W., and the AlpArray and AlpArray-SWATH D Working Groups: Teleseismic P waves at the AlpArray seismic network: wave fronts, absolute travel times and travel-time residuals, Solid Earth, 12, 1635–1660, https://doi.org/10.5194/se-12-1635-2021, 2021.*
## How to use
To use the program you have to call the main program providing two mandatory arguments: a path to the obspy dmt database folder *dmt_database_path* and the path to the PyLoT infile *pylot.in* for picking of the beam trace:
```python pick_correlation_correction.py dmt_database_path pylot.in```
By default, the parameter file *parameters.yaml* is used. You can use the command line option *--params* to specify a different parameter file and other optional arguments such as *-pd* for plotting detailed information or *-n 4* to use 4 cores for parallel processing:
```python pick_correlation_correction.py dmt_database_path pylot.in --params parameters_adriaarray.yaml -pd -n 4```
## Cross-Correlation Parameters
The program uses the parameters in the file *parameters.yaml* by default. You can use the command line option *--params* to specify a different parameter file. An example of the parameter file is provided in the *correlation\parameters.yaml* file.
In the top level of the parameter file the logging level *logging* can be set, as well as a list of pick phases *pick_phases* (e.g. ['P', 'S']).
For each pick phase the different parameters can be set in the first sub-level of the parameter file, e.g.:
```yaml
logging: info
pick_phases: ['P', 'S']
P:
min_corr_stacking: 0.8
min_corr_export: 0.6
[...]
S:
min_corr_stacking: 0.7
[...]
```
The following parameters are available:
| Parameter Name | Description | Parameter Type |
|--------------------------------|----------------------------------------------------------------------------------------------------|----------------|
| min_corr_stacking | Minimum correlation coefficient for building beam trace | float |
| min_corr_export | Minimum correlation coefficient for pick export | float |
| min_stack | Minimum number of stations for building beam trace | int |
| t_before | Correlation window before reference pick | float |
| t_after | Correlation window after reference pick | float |
| cc_maxlag | Maximum shift for initial correlation | float |
| cc_maxlag2 | Maximum shift for second (final) correlation (also for calculating pick uncertainty) | float |
| initial_pick_outlier_threshold | Threshold for excluding large outliers of initial (AIC) picks | float |
| export_threshold | Automatically exclude all onsets which deviate more than this threshold from corrected taup onsets | float |
| min_picks_export | Minimum number of correlated picks for export | int |
| min_picks_autopylot | Minimum number of reference auto picks to continue with event | int |
| check_RMS | Do RMS check to search for restitution errors (very experimental) | bool |
| use_taupy_onsets | Use taupy onsets as reference picks instead of external picks | bool |
| station_list | Use the following stations as reference for stacking | list[str] |
| use_stacked_trace | Use existing stacked trace if found (spare re-computation) | bool |
| data_dir | obspyDMT data subdirectory (e.g. 'raw', 'processed') | str |
| pickfile_extension | Use quakeML files (PyLoT output) with the following extension | str |
| dt_stacking | Time difference for stacking window (in seconds) | list[float] |
| filter_options | Filter for first correlation (rough) | dict |
| filter_options_final | Filter for second correlation (fine) | dict |
| filter_type | Filter type (e.g. bandpass) | str |
| sampfreq | Sampling frequency (in Hz) | float |
## Example Dataset
An example dataset with waveform data, metadata and automatic picks in the obspy-dmt dataset format for testing can be found at https://zenodo.org/doi/10.5281/zenodo.13759803
+179 -276
View File
@@ -2,36 +2,36 @@
- [PyLoT Documentation](#pylot-documentation) - [PyLoT Documentation](#pylot-documentation)
- [PyLoT GUI](#pylot-gui) - [PyLoT GUI](#pylot-gui)
- [First start](#first-start) - [First start](#first-start)
- [Main Screen](#main-screen) - [Main Screen](#main-screen)
- [Waveform Plot](#waveform-plot) - [Waveform Plot](#waveform-plot)
- [Mouse view controls](#mouse-view-controls) - [Mouse view controls](#mouse-view-controls)
- [Buttons](#buttons) - [Buttons](#buttons)
- [Array Map](#array-map) - [Array Map](#array-map)
- [Eventlist](#eventlist) - [Eventlist](#eventlist)
- [Usage](#usage) - [Usage](#usage)
- [Projects and Events](#projects-and-events) - [Projects and Events](#projects-and-events)
- [Event folder structure](#event-folder-structure) - [Event folder structure](#event-folder-structure)
- [Loading event information from CSV file](#loading-event-information-from-csv-file) - [Loading event information from CSV file](#loading-event-information-from-csv-file)
- [Adding events to project](#adding-events-to-project) - [Adding events to project](#adding-events-to-project)
- [Saving projects](#saving-projects) - [Saving projects](#saving-projects)
- [Adding metadata](#adding-metadata) - [Adding metadata](#adding-metadata)
- [Picking](#picking) - [Picking](#picking)
- [Manual Picking](#manual-picking) - [Manual Picking](#manual-picking)
- [Picking window](#picking-window) - [Picking window](#picking-window)
- [Picking Window Settings](#picking-window-settings) - [Picking Window Settings](#picking-window-settings)
- [Filtering](#filtering) - [Filtering](#filtering)
- [Export and Import of manual picks](#export-and-import-of-manual-picks) - [Export and Import of manual picks](#export-and-import-of-manual-picks)
- [Export](#export) - [Export](#export)
- [Import](#import) - [Import](#import)
- [Automatic Picking](#automatic-picking) - [Automatic Picking](#automatic-picking)
- [Tuning](#tuning) - [Tuning](#tuning)
- [Production run of the autopicker](#production-run-of-the-autopicker) - [Production run of the autopicker](#production-run-of-the-autopicker)
- [Evaluation of automatic picks](#evaluation-of-automatic-picks) - [Evaluation of automatic picks](#evaluation-of-automatic-picks)
- [1. Jackknife check](#1-jackknife-check) - [1. Jackknife check](#1-jackknife-check)
- [2. Wadati check](#2-wadati-check) - [2. Wadati check](#2-wadati-check)
- [Comparison between automatic and manual picks](#comparison-between-automatic-and-manual-picks) - [Comparison between automatic and manual picks](#comparison-between-automatic-and-manual-picks)
- [Export and Import of automatic picks](#export-and-import-of-automatic-picks) - [Export and Import of automatic picks](#export-and-import-of-automatic-picks)
- [Location determination](#location-determination) - [Location determination](#location-determination)
- [FAQ](#faq) - [FAQ](#faq)
@@ -44,17 +44,15 @@ This section describes how to use PyLoT graphically to view waveforms and create
After opening PyLoT for the first time, the setup routine asks for the following information: After opening PyLoT for the first time, the setup routine asks for the following information:
Questions: Questions:
1. Full Name 1. Full Name
2. Authority: Enter authority/institution name 2. Authority: Enter authority/institution name
3. Format: Enter output format (*.xml, *.cnv, *.obs) 3. Format: Enter output format (*.xml, *.cnv, *.obs)
[//]: <> (TODO: explain what these things mean, where they are used) [//]: <> (TODO: explain what these things mean, where they are used)
## Main Screen ## Main Screen
After entering the [information](#first-start), PyLoTs main window is shown. It defaults to a view of After entering the [information](#first-start), PyLoTs main window is shown. It defaults to a view of the [Waveform Plot](#waveform-plot), which starts empty.
the [Waveform Plot](#waveform-plot), which starts empty.
<img src=images/gui/pylot-main-screen.png alt="Tune autopicks button" title="Tune autopicks button"> <img src=images/gui/pylot-main-screen.png alt="Tune autopicks button" title="Tune autopicks button">
@@ -63,21 +61,24 @@ Add trace data by [loading a project](#projects-and-events) or by [adding event
### Waveform Plot ### Waveform Plot
The waveform plot shows a trace list of all stations of an event. The waveform plot shows a trace list of all stations of an event.
Click on any trace to open the stations [picking window](#picking-window), where you can review automatic and manual Click on any trace to open the stations [picking window](#picking-window), where you can review automatic and manual picks.
picks.
<img src=images/gui/pylot-waveform-plot.png alt="A Waveform Plot showing traces of one event"> <img src=images/gui/pylot-waveform-plot.png alt="A Waveform Plot showing traces of one event">
Above the traces the currently displayed event can be selected. In the bottom bar information about the trace under the Above the traces the currently displayed event can be selected.
mouse cursor is shown. This information includes the station name (station), the absolute UTC time (T) of the point In the bottom bar information about the trace under the mouse cursor is shown. This information includes the station name (station), the absolute UTC time (T) of the point under the mouse cursor and the relative time since the first trace start in seconds (t) as well as a trace count.
under the mouse cursor and the relative time since the first trace start in seconds (t) as well as a trace count.
#### Mouse view controls #### Mouse view controls
Hold left mouse button and drag to pan view. Hold left mouse button and drag to pan view.
Hold right mouse button and Direction | Result --- | --- Move the mouse up | Increase amplitude scale Move the mouse Hold right mouse button and
down | Decrease amplitude scale Move the mouse right | Increase time scale Move the mouse left | Decrease time scale Direction | Result
--- | ---
Move the mouse up | Increase amplitude scale
Move the mouse down | Decrease amplitude scale
Move the mouse right | Increase time scale
Move the mouse left | Decrease time scale
Press right mouse button and click "View All" from the context menu to reset the view. Press right mouse button and click "View All" from the context menu to reset the view.
@@ -85,100 +86,81 @@ Press right mouse button and click "View All" from the context menu to reset the
[//]: <> (Hack: We need these invisible spaces to add space to the first column, otherwise ) [//]: <> (Hack: We need these invisible spaces to add space to the first column, otherwise )
| Icon &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | Description | Icon &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | Description
|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| --- | ---
| <img src="../icons/newfile.png" alt="Create new project" width="64" height="64"> | Create a new project, for more information about projects see [Projects and Events](#projects-and-events). | <img src="../icons/newfile.png" alt="Create new project" width="64" height="64"> | Create a new project, for more information about projects see [Projects and Events](#projects-and-events).
| <img src="../icons/openproject.png" alt="Open project" width="64" height="64"> | Load a project file from disk. | <img src="../icons/openproject.png" alt="Open project" width="64" height="64"> | Load a project file from disk.
| <img src="../icons/saveproject.png" alt="Save Project" width="64" height="64"> | Save all current events into an associated project file on disk. If there is no project file currently associated, you will be asked to create a new one. | <img src="../icons/saveproject.png" alt="Save Project" width="64" height="64"> | Save all current events into an associated project file on disk. If there is no project file currently associated, you will be asked to create a new one.
| <img src="../icons/saveprojectas.png" alt="Save Project as" width="64" height="64"> | Save all current events into a new project file on disk. See [Saving projects](#saving-projects). | <img src="../icons/saveprojectas.png" alt="Save Project as" width="64" height="64"> | Save all current events into a new project file on disk. See [Saving projects](#saving-projects).
| <img src="../icons/add.png" alt="Add event data" width="64" height="64"> | Add event data by selecting directories containing waveforms. For more information see [Event folder structure](#event-folder-structure). | <img src="../icons/add.png" alt="Add event data" width="64" height="64"> | Add event data by selecting directories containing waveforms. For more information see [Event folder structure](#event-folder-structure).
| <img src="../icons/openpick.png" alt="Load event information" width="64" height="64"> | Load picks/origins from disk into the currently displayed event. If a pick already exists for a station, the one from file will overwrite the existing one. | <img src="../icons/openpick.png" alt="Load event information" width="64" height="64"> | Load picks/origins from disk into the currently displayed event. If a pick already exists for a station, the one from file will overwrite the existing one.
| <img src="../icons/openpicks.png" alt="Load information for all events" width="64" height="64"> | Load picks/origins for all events of the current project. PyLoT searches for files within the directory of the event and tries to load them for that event. For this function to work, the files containing picks/origins have to be named as described in [Event folder structure](#event-folder-structure). If a pick already exists for a station, the one from file will overwrite the existing one. | <img src="../icons/openpicks.png" alt="Load information for all events" width="64" height="64"> | Load picks/origins for all events of the current project. PyLoT searches for files within the directory of the event and tries to load them for that event. For this function to work, the files containing picks/origins have to be named as described in [Event folder structure](#event-folder-structure). If a pick already exists for a station, the one from file will overwrite the existing one.
| <img src="../icons/savepicks.png" alt="Save picks" width="64" height="64"> | Save event information such as picks and origin to file. You will be asked to select a directory in which this information should be saved. | <img src="../icons/savepicks.png" alt="Save picks" width="64" height="64"> | Save event information such as picks and origin to file. You will be asked to select a directory in which this information should be saved.
| <img src="../icons/openloc.png" alt="Load location information" width="64" height="64"> | Load location information from disk, | <img src="../icons/openloc.png" alt="Load location information" width="64" height="64"> | Load location information from disk,
| <img src="../icons/Matlab_PILOT_icon.png" alt="Load legacy information" width="64" height="64"> | Load event information from a previous, MatLab based PILOT version. | <img src="../icons/Matlab_PILOT_icon.png" alt="Load legacy information" width="64" height="64"> | Load event information from a previous, MatLab based PILOT version.
| <img src="../icons/key_Z.png" alt="Display Z" width="64" height="64"> | Display Z component of streams in waveform plot. | <img src="../icons/key_Z.png" alt="Display Z" width="64" height="64"> | Display Z component of streams in waveform plot.
| <img src="../icons/key_N.png" alt="Display N" width="64" height="64"> | Display N component of streams in waveform plot. | <img src="../icons/key_N.png" alt="Display N" width="64" height="64"> | Display N component of streams in waveform plot.
| <img src="../icons/key_E.png" alt="Display E" width="64" height="64"> | Display E component of streams in waveform plot. | <img src="../icons/key_E.png" alt="Display E" width="64" height="64"> | Display E component of streams in waveform plot.
| <img src="../icons/tune.png" alt="Tune Autopicker" width="64" height="64"> | Open the [Tune Autopicker window](#tuning). | <img src="../icons/tune.png" alt="Tune Autopicker" width="64" height="64"> | Open the [Tune Autopicker window](#tuning).
| <img src="../icons/autopylot_button.png" alt="" width="64" height="64"> | Opens a window that allows starting the autopicker for all events ([Production run of the AutoPicker](#production-run-of-the-autopicker)). | <img src="../icons/autopylot_button.png" alt="" width="64" height="64"> | Opens a window that allows starting the autopicker for all events ([Production run of the AutoPicker](#production-run-of-the-autopicker)).
| <img src="../icons/compare_button.png" alt="Comparison" width="64" height="64"> | Compare automatic and manual picks, only available if automatic and manual picks for an event exist. See [Comparison between automatic and manual picks](#comparison-between-automatic-and-manual-picks). | <img src="../icons/compare_button.png" alt="Comparison" width="64" height="64"> | Compare automatic and manual picks, only available if automatic and manual picks for an event exist. See [Comparison between automatic and manual picks](#comparison-between-automatic-and-manual-picks).
| <img src="../icons/locate_button.png" alt="Locate event" width="64" height="64"> | Run a location routine (NonLinLoc) as configured in the settings on the picks. See [Location determination](#location-determination). | <img src="../icons/locate_button.png" alt="Locate event" width="64" height="64"> | Run a location routine (NonLinLoc) as configured in the settings on the picks. See [Location determination](#location-determination).
### Array Map ### Array Map
The array map will display a color diagram to allow a visual check of the consistency of picks across multiple stations. The array map will display a color diagram to allow a visual check of the consistency of picks across multiple stations. This works by calculating the time difference of every onset to the earliest onset. Then isolines are drawn between stations with the same time difference and the areas between isolines are colored.
This works by calculating the time difference of every onset to the earliest onset. Then isolines are drawn between The result should resemble a color gradient as the wavefront rolls over the network area. Stations where picks are earlier/later than their neighbours can be reviewed by clicking on them, which opens the [picking window](#picking-window).
stations with the same time difference and the areas between isolines are colored.
The result should resemble a color gradient as the wavefront rolls over the network area. Stations where picks are
earlier/later than their neighbours can be reviewed by clicking on them, which opens
the [picking window](#picking-window).
Above the Array Map the picks that are used to create the map can be customized. The phase of picks that should be used Above the Array Map the picks that are used to create the map can be customized.
can be selected, which allows checking the consistency of the P- and S-phase separately. Additionally the pick type can The phase of picks that should be used can be selected, which allows checking the consistency of the P- and S-phase separately.
be set to manual, automatic or hybrid, meaning display only manual picks, automatic picks or only display automatic Additionally the pick type can be set to manual, automatic or hybrid, meaning display only manual picks, automatic picks or only display automatic picks for stations where there are no manual ones.
picks for stations where there are no manual ones.
![Array Map](images/gui/arraymap-example.png "Array Map") ![Array Map](images/gui/arraymap-example.png "Array Map")
*Array Map for an event at the Northern Mid Atlantic Ridge, between North Africa and Mexico (Lat. 22.58, Lon. -45.11). *Array Map for an event at the Northern Mid Atlantic Ridge, between North Africa and Mexico (Lat. 22.58, Lon. -45.11). The wavefront moved from west to east over the network area (Alps and Balcan region), with the earliest onsets in blue in the west.*
The wavefront moved from west to east over the network area (Alps and Balcan region), with the earliest onsets in blue
in the west.*
To be able to display an array map PyLoT needs to load an inventory file, where the metadata of seismic stations is To be able to display an array map PyLoT needs to load an inventory file, where the metadata of seismic stations is kept. For more information see [Metadata](#adding-metadata). Additionally automatic or manual picks need to exist for the current event.
kept. For more information see [Metadata](#adding-metadata). Additionally automatic or manual picks need to exist for
the current event.
### Eventlist ### Eventlist
The eventlist displays event parameters. The displayed parameters are saved in the .xml file in the event folder. Events The eventlist displays event parameters. The displayed parameters are saved in the .xml file in the event folder. Events can be deleted from the project by pressing the red X in the leftmost column of the corresponding event.
can be deleted from the project by pressing the red X in the leftmost column of the corresponding event.
<img src="images/gui/eventlist.png" alt="Eventlist"> <img src="images/gui/eventlist.png" alt="Eventlist">
| Column | Description | Column | Description
|------------|--------------------------------------------------------------------------------------------------------------------| --- | ---
| Event | Full path to the events folder. | Event | Full path to the events folder.
| Time | Time of event. | Time | Time of event.
| Lat | Latitude in degrees of event location. | Lat | Latitude in degrees of event location.
| Lon | Longitude in degrees of event location. | Lon | Longitude in degrees of event location.
| Depth | Depth in km of event. | Depth | Depth in km of event.
| Mag | Magnitude of event. | Mag | Magnitude of event.
| [N] MP | Number of manual picks. | [N] MP | Number of manual picks.
| [N] AP | Number of automatic picks. | [N] AP | Number of automatic picks.
| Tuning Set | Select whether this event is a Tuning event. See [Automatic Picking](#automatic-picking). | Tuning Set | Select whether this event is a Tuning event. See [Automatic Picking](#automatic-picking).
| Test Set | Select whether this event is a Test event. See [Automatic Picking](#automatic-picking). | Test Set | Select whether this event is a Test event. See [Automatic Picking](#automatic-picking).
| Notes | Free form text field for notes regarding this event. Text will be saved in the notes.txt file in the event folder. | Notes | Free form text field for notes regarding this event. Text will be saved in the notes.txt file in the event folder.
## Usage ## Usage
### Projects and Events ### Projects and Events
PyLoT uses projects to categorize different seismic data. A project consists of one or multiple events. Events contain PyLoT uses projects to categorize different seismic data. A project consists of one or multiple events. Events contain seismic traces from one or multiple stations. An event also contains further information, e.g. origin time, source parameters and automatic as well as manual picks.
seismic traces from one or multiple stations. An event also contains further information, e.g. origin time, source Projects are used to group events which should be analysed together. A project could contain all events from a specific region within a timeframe of interest or all recorded events of a seismological experiment.
parameters and automatic as well as manual picks. Projects are used to group events which should be analysed together. A
project could contain all events from a specific region within a timeframe of interest or all recorded events of a
seismological experiment.
### Event folder structure ### Event folder structure
PyLoT expects the following folder structure for seismic data: PyLoT expects the following folder structure for seismic data:
* Every event should be in it's own folder with the following naming scheme for the folders: * Every event should be in it's own folder with the following naming scheme for the folders:
``e[id].[doy].[yy]``, where ``[id]`` is a four-digit numerical id increasing from 0001, ``[doy]`` the three digit day ``e[id].[doy].[yy]``, where ``[id]`` is a four-digit numerical id increasing from 0001, ``[doy]`` the three digit day of year and ``[yy]`` the last two digits of the year of the event. This structure has to be created by the user of PyLoT manually.
of year and ``[yy]`` the last two digits of the year of the event. This structure has to be created by the user of
PyLoT manually.
* These folders should contain the seismic data for their event as ``.mseed`` or other supported filetype * These folders should contain the seismic data for their event as ``.mseed`` or other supported filetype
* All automatic and manual picks should be in an ``.xml`` file in their event folder. PyLoT saves picks in this file. * All automatic and manual picks should be in an ``.xml`` file in their event folder. PyLoT saves picks in this file. This file does not have to be added manually unless there are picks to be imported. The format used to save picks is QUAKEML.
This file does not have to be added manually unless there are picks to be imported. The format used to save picks is Picks are saved in a file with the same filename as the event folder with ``PyLoT_`` prepended.
QUAKEML. * The file ``notes.txt`` is used for saving analysts comments. Everything saved here will be displayed in the 'Notes' column of the eventlist.
Picks are saved in a file with the same filename as the event folder with ``PyLoT_`` prepended.
* The file ``notes.txt`` is used for saving analysts comments. Everything saved here will be displayed in the 'Notes'
column of the eventlist.
### Loading event information from CSV file ### Loading event information from CSV file
Event information can be saved in a ``.csv`` file located in the rootpath. The file is made from one header line, which Event information can be saved in a ``.csv`` file located in the rootpath. The file is made from one header line, which is followed by one or multiple data lines. Values are separated by comma, while a dot is used as a decimal separator.
is followed by one or multiple data lines. Values are separated by comma, while a dot is used as a decimal separator.
This information is then shown in the table in the [Eventlist tab](#Eventlist). This information is then shown in the table in the [Eventlist tab](#Eventlist).
One example header and data line is shown below. One example header and data line is shown below.
@@ -187,61 +169,50 @@ One example header and data line is shown below.
The meaning of the header entries is: The meaning of the header entries is:
| Header | description | Header | description
|----------------------|------------------------------------------------------------------------------------------------| --- | ---
| event | Event id, has to be the same as the folder name in which waveform data for this event is kept. | event | Event id, has to be the same as the folder name in which waveform data for this event is kept.
| Data | Origin date of the event, format DD/MM/YY or DD/MM/YYYY. | Data | Origin date of the event, format DD/MM/YY or DD/MM/YYYY.
| Time | Origin time of the event. Format HH:MM:SS. | Time | Origin time of the event. Format HH:MM:SS.
| Lat, Long | Origin latitude and longitude in decimal degrees. | Lat, Long | Origin latitude and longitude in decimal degrees.
| Region | Flinn-Engdahl region name. | Region | Flinn-Engdahl region name.
| Basis Lat, Basis Lon | Latitude and longitude of the basis of the station network in decimal degrees. | Basis Lat, Basis Lon | Latitude and longitude of the basis of the station network in decimal degrees.
| Distance [km] | Distance from origin coordinates to basis coordinates in km. | Distance [km] | Distance from origin coordinates to basis coordinates in km.
| Distance [rad] | Distance from origin coordinates to basis coordinates in rad. | Distance [rad] | Distance from origin coordinates to basis coordinates in rad.
### Adding events to project ### Adding events to project
PyLoT GUI starts with an empty project. To add events, use the add event data button. Select one or multiple folders PyLoT GUI starts with an empty project. To add events, use the add event data button. Select one or multiple folders containing events.
containing events.
[//]: <> (TODO: explain _Directories: Root path, Data path, Database path_)
### Saving projects ### Saving projects
Save the current project from the menu with File->Save project or File->Save project as. PyLoT uses ``.plp`` files to Save the current project from the menu with File->Save project or File->Save project as.
save project information. This file format is not interchangeable between different versions of Python interpreters. PyLoT uses ``.plp`` files to save project information. This file format is not interchangeable between different versions of Python interpreters.
Saved projects contain the automatic and manual picks. Seismic trace data is not included into the ``.plp`` file, but Saved projects contain the automatic and manual picks. Seismic trace data is not included into the ``.plp`` file, but read from its location used when saving the file.
read from its location used when saving the file.
### Adding metadata ### Adding metadata
[//]: <> (TODO: Add picture of metadata "manager" when it is done) [//]: <> (TODO: Add picture of metadata "manager" when it is done)
PyLoT can handle ``.dless``, ``.xml``, ``.resp`` and ``.dseed`` file formats for Metadata. Metadata files stored on disk PyLoT can handle ``.dless``, ``.xml``, ``.resp`` and ``.dseed`` file formats for Metadata. Metadata files stored on disk can be added to a project by clicking *Edit*->*Manage Inventories*. This opens up a window where the folders which contain metadata files can be selected. PyLoT will then search these files for the station names when it needs the information.
can be added to a project by clicking *Edit*->*Manage Inventories*. This opens up a window where the folders which
contain metadata files can be selected. PyLoT will then search these files for the station names when it needs the
information.
# Picking # Picking
PyLoTs automatic and manual pick determination works as following: PyLoTs automatic and manual pick determination works as following:
* Using certain parameters, a first initial/coarse pick is determined. The first manual pick is determined by visual review of the whole waveform and selection of the most likely onset by the analyst. The first automatic pick is determined by calculation of a characteristic function (CF) for the seismic trace. When a wave arrives, the CFs properties change, which is determined as the signals onset.
* Using certain parameters, a first initial/coarse pick is determined. The first manual pick is determined by visual * Afterwards, a refined set of parameters is applied to a small part of the waveform around the initial onset. For manual picks this means a closer view of the trace, for automatic picks this is done by a recalculated CF with different parameters.
review of the whole waveform and selection of the most likely onset by the analyst. The first automatic pick is
determined by calculation of a characteristic function (CF) for the seismic trace. When a wave arrives, the CFs
properties change, which is determined as the signals onset.
* Afterwards, a refined set of parameters is applied to a small part of the waveform around the initial onset. For
manual picks this means a closer view of the trace, for automatic picks this is done by a recalculated CF with
different parameters.
* This second picking phase results in the precise pick, which is treated as the onset time. * This second picking phase results in the precise pick, which is treated as the onset time.
## Manual Picking ## Manual Picking
To create manual picks, you will need to open or create a project that contains seismic trace data ( To create manual picks, you will need to open or create a project that contains seismic trace data (see [Adding events to projects](#adding-events-to-project)). Click on a trace to open the [Picking window](#picking-window).
see [Adding events to projects](#adding-events-to-project)). Click on a trace to open
the [Picking window](#picking-window).
### Picking window ### Picking window
Open the picking window of a station by leftclicking on any trace in the waveform plot. Here you can create manual picks Open the picking window of a station by leftclicking on any trace in the waveform plot. Here you can create manual picks for the selected station.
for the selected station.
<img src="images/gui/picking/pickwindow.png" alt="Picking window"> <img src="images/gui/picking/pickwindow.png" alt="Picking window">
@@ -249,24 +220,24 @@ for the selected station.
#### Picking Window Settings #### Picking Window Settings
| Icon | Shortcut | Menu Alternative | Description | Icon | Shortcut | Menu Alternative | Description
|----------------------------------------------------------------------------------|----------------|-----------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ---|---|---|---
| <img src="../icons/filter_p.png" alt="Filter P" width="64" height="64"> | p | Filter->Apply P Filter | Filter all channels according to the options specified in Filter parameter, P Filter section. | <img src="../icons/filter_p.png" alt="Filter P" width="64" height="64"> | p | Filter->Apply P Filter | Filter all channels according to the options specified in Filter parameter, P Filter section.
| <img src="../icons/filter_s.png" alt="Filter S" width="64" height="64"> | s | Filter->Apply S Filter | Filter all channels according to the options specified in Filter parameter, S Filter section. | <img src="../icons/filter_s.png" alt="Filter S" width="64" height="64"> | s | Filter->Apply S Filter | Filter all channels according to the options specified in Filter parameter, S Filter section.
| <img src="../icons/key_A.png" alt="Filter Automatically" width="64" height="64"> | Ctrl + a | Filter->Automatic Filtering | If enabled, automatically select the correct filter option (P, S) depending on the selected phase to be picked. | <img src="../icons/key_A.png" alt="Filter Automatically" width="64" height="64"> | Ctrl + a | Filter->Automatic Filtering | If enabled, automatically select the correct filter option (P, S) depending on the selected phase to be picked.
| ![desc](images/gui/picking/phase_selection.png "Phase selection") | 1 (P) or 5 (S) | Picks->P or S | Select phase to pick. If Automatic Filtering is enabled, this will apply the appropriate filter depending on the phase. | ![desc](images/gui/picking/phase_selection.png "Phase selection") | 1 (P) or 5 (S) | Picks->P or S | Select phase to pick. If Automatic Filtering is enabled, this will apply the appropriate filter depending on the phase.
| ![Zoom into](../icons/zoom_in.png "Zoom into waveform") | - | - | Zoom into waveform. | ![Zoom into](../icons/zoom_in.png "Zoom into waveform") | - | - | Zoom into waveform.
| ![Reset zoom](../icons/zoom_0.png "Reset zoom") | - | - | Reset zoom to default view. | ![Reset zoom](../icons/zoom_0.png "Reset zoom") | - | - | Reset zoom to default view.
| ![Delete picks](../icons/delete.png "Delete picks") | - | - | Delete all manual picks on this station. | ![Delete picks](../icons/delete.png "Delete picks") | - | - | Delete all manual picks on this station.
| ![Rename a phase](../icons/sync.png "Rename a phase") | - | - | Click this button and then the picked phase to rename it. | ![Rename a phase](../icons/sync.png "Rename a phase") | - | - | Click this button and then the picked phase to rename it.
| ![Continue](images/gui/picking/continue.png "Continue with next station") | - | - | If checked, after accepting the manual picks for this station with 'OK', the picking window for the next station will be opened. This option is useful for fast manual picking of a complete event. | ![Continue](images/gui/picking/continue.png "Continue with next station") | - | - | If checked, after accepting the manual picks for this station with 'OK', the picking window for the next station will be opened. This option is useful for fast manual picking of a complete event.
| Estimated onsets | - | - | Show the theoretical onsets for this station. Needs metadata and origin information. | Estimated onsets | - | - | Show the theoretical onsets for this station. Needs metadata and origin information.
| Compare to channel | - | - | Select a data channel to compare against. The selected channel will be displayed in the picking window behind every channel allowing the analyst to visually compare signal correlation between different channels. | Compare to channel | - | - | Select a data channel to compare against. The selected channel will be displayed in the picking window behind every channel allowing the analyst to visually compare signal correlation between different channels.
| Scaling | - | - | Individual means every channel is scaled to its own maximum. If a channel is selected here, all channels will be scaled relatively to this channel. | Scaling | - | - | Individual means every channel is scaled to its own maximum. If a channel is selected here, all channels will be scaled relatively to this channel.
| Menu Command | Shortcut | Description | Menu Command | Shortcut | Description
|---------------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| ---|---|---
| P Channels and S Channels | - | Select which channels should be treated as P or S channels during picking. When picking a phase, only the corresponding channels will be shown during the precise pick. Normally, the Z channel should be selected for the P phase and the N and E channel for the S phase. | P Channels and S Channels | - | Select which channels should be treated as P or S channels during picking. When picking a phase, only the corresponding channels will be shown during the precise pick. Normally, the Z channel should be selected for the P phase and the N and E channel for the S phase.
### Filtering ### Filtering
@@ -274,167 +245,105 @@ Access the Filter options by pressing Ctrl+f on the Waveform plot or by the menu
<img src=images/gui/pylot-filter-options.png> <img src=images/gui/pylot-filter-options.png>
Here you are able to select filter type, order and frequencies for the P and S pick separately. These settings are used Here you are able to select filter type, order and frequencies for the P and S pick separately. These settings are used in the GUI for displaying the filtered waveform data and during manual picking. The values used by PyLoT for automatic picking are displayed next to the manual values. They can be changed in the [Tune Autopicker dialog](#tuning).
in the GUI for displaying the filtered waveform data and during manual picking. The values used by PyLoT for automatic A green value automatic value means the automatic and manual filter parameter is configured the same, red means they are configured differently.
picking are displayed next to the manual values. They can be changed in the [Tune Autopicker dialog](#tuning). By toggling the "Overwrite filteroptions" checkmark you can set whether the manual precise/second pick uses the filter settings for the automatic picker (unchecked) or whether it uses the filter options in this dialog (checked).
A green value automatic value means the automatic and manual filter parameter is configured the same, red means they are To guarantee consistent picking results between automatic and manual picking it is recommended to use the same filter settings for the determination of automatic and manual picks.
configured differently. By toggling the "Overwrite filteroptions" checkmark you can set whether the manual
precise/second pick uses the filter settings for the automatic picker (unchecked) or whether it uses the filter options
in this dialog (checked). To guarantee consistent picking results between automatic and manual picking it is recommended
to use the same filter settings for the determination of automatic and manual picks.
### Export and Import of manual picks ### Export and Import of manual picks
#### Export #### Export
After the creation of manual picks they can either be saved in the project file ( After the creation of manual picks they can either be saved in the project file (see [Saving projects](#saving-projects)). Alternatively the picks can be exported by pressing the <img src="../icons/savepicks.png" alt="Save event information button" title="Save picks button" height=24 width=24> button above the waveform plot or in the menu File->Save event information (shortcut Ctrl+p). Select the event directory in which to save the file. The filename will be ``PyLoT_[event_folder_name].[filetype selected during first startup]``.
see [Saving projects](#saving-projects)). Alternatively the picks can be exported by pressing You can rename and copy this file, but PyLoT will then no longer be able to automatically recognize the correct picks for an event and the file will have to be manually selected when loading.
the <img src="../icons/savepicks.png" alt="Save event information button" title="Save picks button" height=24 width=24>
button above the waveform plot or in the menu File->Save event information (shortcut Ctrl+p). Select the event directory
in which to save the file. The filename will be ``PyLoT_[event_folder_name].[filetype selected during first startup]``
.
You can rename and copy this file, but PyLoT will then no longer be able to automatically recognize the correct picks
for an event and the file will have to be manually selected when loading.
#### Import #### Import
To import previously saved picks press To import previously saved picks press the <img src="../icons/openpick.png" alt="Load event information button" width="24" height="24"> button and select the file to load. You will be asked to save the current state of your project if you have not done so before. You can continue without saving by pressing "Discard". This does not delete any information from your project, it just means that no project file is saved before the changes of importing picks are applied.
the <img src="../icons/openpick.png" alt="Load event information button" width="24" height="24"> button and select the PyLoT will automatically load files named after the scheme it uses when saving picks, described in the paragraph above. If it can't find any matching files, a file dialogue will open and you can select the file you wish to load.
file to load. You will be asked to save the current state of your project if you have not done so before. You can
continue without saving by pressing "Discard". This does not delete any information from your project, it just means
that no project file is saved before the changes of importing picks are applied. PyLoT will automatically load files
named after the scheme it uses when saving picks, described in the paragraph above. If it can't find any matching files,
a file dialogue will open and you can select the file you wish to load.
If you see a warning "Mismatch in event identifiers" and are asked whether to continue loading the picks, this means If you see a warning "Mismatch in event identifiers" and are asked whether to continue loading the picks, this means that PyLoT doesn't recognize the picks in the file as belonging to this specific event. They could have either been saved under a different installation of PyLoT but with the same waveform data, which means they are still compatible and you can continue loading them. Or they could be picks from a different event, in which case loading them is not recommended.
that PyLoT doesn't recognize the picks in the file as belonging to this specific event. They could have either been
saved under a different installation of PyLoT but with the same waveform data, which means they are still compatible and
you can continue loading them. Or they could be picks from a different event, in which case loading them is not
recommended.
## Automatic Picking ## Automatic Picking
The general workflow for automatic picking is as following:
- After setting up the project by loading waveforms and optionally metadata, the right parameters for the autopicker The general workflow for automatic picking is as following:
have to be determined - After setting up the project by loading waveforms and optionally metadata, the right parameters for the autopicker have to be determined
- This [tuning](#tuning) is done for single stations with immediate graphical feedback of all picking results - This [tuning](#tuning) is done for single stations with immediate graphical feedback of all picking results
- Afterwards the autopicker can be run for all or a subset of events from the project - Afterwards the autopicker can be run for all or a subset of events from the project
For automatic picking PyLoT discerns between tune and test events, which the user has to set as such. Tune events are For automatic picking PyLoT discerns between tune and test events, which the user has to set as such. Tune events are used to calibrate the autopicking algorithm, test events are then used to test the calibration. The purpose of that is controlling whether the parameters found during tuning are able to reliably pick the "unknown" test events.
used to calibrate the autopicking algorithm, test events are then used to test the calibration. The purpose of that is If this behaviour is not desired and all events should be handled the same, dont mark any events. Since this is just a way to group events to compare the picking results, nothing else will change.
controlling whether the parameters found during tuning are able to reliably pick the "unknown" test events.
If this behaviour is not desired and all events should be handled the same, dont mark any events. Since this is just a
way to group events to compare the picking results, nothing else will change.
### Tuning ### Tuning
Tuning describes the process of adjusting the autopicker settings to the characteristics of your data set. To do this in Tuning describes the process of adjusting the autopicker settings to the characteristics of your data set. To do this in PyLoT, use the <img src=../icons/tune.png height=24 alt="Tune autopicks button" title="Tune autopicks button"> button to open the Tune Autopicker.
PyLoT, use the <img src=../icons/tune.png height=24 alt="Tune autopicks button" title="Tune autopicks button"> button to
open the Tune Autopicker.
<img src=images/gui/tuning/tune_autopicker.png> <img src=images/gui/tuning/tune_autopicker.png>
View of a station in the Tune Autopicker window. View of a station in the Tune Autopicker window.
1. Select the event to be displayed and processed. 1. Select the event to be displayed and processed.
2. Select the station from the event. 2. Select the station from the event.
3. To pick the currently displayed trace, click 3. To pick the currently displayed trace, click the <img src=images/gui/tuning/autopick_trace_button.png alt="Pick trace button" title="Autopick trace button" height=16> button.
the <img src=images/gui/tuning/autopick_trace_button.png alt="Pick trace button" title="Autopick trace button" height=16> 4. These tabs are used to select the current view. __Traces Plot__ contains a plot of the stations traces, where manual picks can be created/edited. __Overview__ contains graphical results of the automatic picking process. The __P and S tabs__ contain the automatic picking results of the P and S phase, while __log__ contains a useful text output of automatic picking.
button. 5. These buttons are used to load/save/reset settings for automatic picking. The parameters can be saved in PyLoT input files, which have the file ending *.in*. They are human readable text files, which can also be edited by hand. Saving the parameters allows you to load them again later, even on different machines.
4. These tabs are used to select the current view. __Traces Plot__ contains a plot of the stations traces, where manual 6. These menus control the behaviour of the creation of manual picks from the Tune Autopicker window. Picks allows to select the phase for which a manual pick should be created, Filter allows to filter waveforms and edit the filter parameters. P-Channels and S-Channels allow to select the channels that should be displayed when creating a manual P or S pick.
picks can be created/edited. __Overview__ contains graphical results of the automatic picking process. The __P and S 7. This menu is the same as in the [Picking Window](#picking-window-settings), with the exception of the __Manual Onsets__ options. The __Manual Onsets__ buttons accepts or reject the manual picks created in the Tune Autopicker window, pressing accept adds them to the manual picks for the event, while reject removes them.
tabs__ contain the automatic picking results of the P and S phase, while __log__ contains a useful text output of
automatic picking.
5. These buttons are used to load/save/reset settings for automatic picking. The parameters can be saved in PyLoT input
files, which have the file ending *.in*. They are human readable text files, which can also be edited by hand. Saving
the parameters allows you to load them again later, even on different machines.
6. These menus control the behaviour of the creation of manual picks from the Tune Autopicker window. Picks allows to
select the phase for which a manual pick should be created, Filter allows to filter waveforms and edit the filter
parameters. P-Channels and S-Channels allow to select the channels that should be displayed when creating a manual P
or S pick.
7. This menu is the same as in the [Picking Window](#picking-window-settings), with the exception of the __Manual
Onsets__ options. The __Manual Onsets__ buttons accepts or reject the manual picks created in the Tune Autopicker
window, pressing accept adds them to the manual picks for the event, while reject removes them.
8. The traces plot in the centre allows creating manual picks and viewing the waveforms. 8. The traces plot in the centre allows creating manual picks and viewing the waveforms.
9. The parameters which influence the autopicking result are in the Main settings and Advanced settings tabs on the left 9. The parameters which influence the autopicking result are in the Main settings and Advanced settings tabs on the left side. For a description of all the parameters see the [tuning documentation](tuning.md).
side. For a description of all the parameters see the [tuning documentation](tuning.md).
### Production run of the autopicker ### Production run of the autopicker
After the settings used during tuning give the desired results, the autopicker can be used on the complete dataset. To After the settings used during tuning give the desired results, the autopicker can be used on the complete dataset. To invoke the autopicker on the whole set of events, click the <img src=../icons/autopylot_button.png alt="Autopick" title="Autopick" height=32> button.
invoke the autopicker on the whole set of events, click
the <img src=../icons/autopylot_button.png alt="Autopick" title="Autopick" height=32> button.
### Evaluation of automatic picks ### Evaluation of automatic picks
PyLoT has two internal consistency checks for automatic picks that were determined for an event: PyLoT has two internal consistency checks for automatic picks that were determined for an event:
1. Jackknife check 1. Jackknife check
2. Wadati check 2. Wadati check
#### 1. Jackknife check #### 1. Jackknife check
The jackknife test in PyLoT checks the consistency of automatically determined P-picks by checking the statistical The jackknife test in PyLoT checks the consistency of automatically determined P-picks by checking the statistical variance of the picks. The variance of all P-picks is calculated and compared to the variance of subsets, in which one pick is removed.
variance of the picks. The variance of all P-picks is calculated and compared to the variance of subsets, in which one The idea is, that picks that are close together in time should not influence the estimation of the variance much, while picks whose positions deviates from the norm influence the variance to a greater extent. If the estimated variance of a subset with a pick removed differs to much from the estimated variance of all picks, the pick that was removed from the subset will be marked as invalid.
pick is removed. The factor by which picks are allowed to skew from the estimation of variance can be configured, it is called *jackfactor*, see [here](tuning.md#Pick-quality-control).
The idea is, that picks that are close together in time should not influence the estimation of the variance much, while
picks whose positions deviates from the norm influence the variance to a greater extent. If the estimated variance of a
subset with a pick removed differs to much from the estimated variance of all picks, the pick that was removed from the
subset will be marked as invalid.
The factor by which picks are allowed to skew from the estimation of variance can be configured, it is called *
jackfactor*, see [here](tuning.md#Pick-quality-control).
Additionally, the deviation of picks from the median is checked. For that, the median of all P-picks that passed the Additionally, the deviation of picks from the median is checked. For that, the median of all P-picks that passed the Jackknife test is calculated. Picks whose onset times deviate from the mean onset time by more than the *mdttolerance* are marked as invalid.
Jackknife test is calculated. Picks whose onset times deviate from the mean onset time by more than the *mdttolerance*
are marked as invalid.
<img src=images/gui/jackknife_plot.png title="Jackknife/Median test diagram"> <img src=images/gui/jackknife_plot.png title="Jackknife/Median test diagram">
*The result of both tests (Jackknife and Median) is shown in a diagram afterwards. The onset time is plotted against a *The result of both tests (Jackknife and Median) is shown in a diagram afterwards. The onset time is plotted against a running number of stations. Picks that failed either the Jackknife or the median test are colored red. The median is plotted as a green line.*
running number of stations. Picks that failed either the Jackknife or the median test are colored red. The median is
plotted as a green line.*
The Jackknife and median check are suitable to check for picks that are outside of the expected time window, for The Jackknife and median check are suitable to check for picks that are outside of the expected time window, for example, when a wrong phase was picked. It won't recognize picks that are in close proximity to the right onset which are just slightly to late/early.
example, when a wrong phase was picked. It won't recognize picks that are in close proximity to the right onset which
are just slightly to late/early.
#### 2. Wadati check #### 2. Wadati check
The Wadati check checks the consistency of S picks. For this the SP-time, the time difference between S and P onset is The Wadati check checks the consistency of S picks. For this the SP-time, the time difference between S and P onset is plotted against the P onset time. A line is fitted to the points, which minimizes the error. Then the deviation of single picks to this line is checked. If the deviation in seconds is above the *wdttolerance* parameter ([see here](tuning.md#Pick-quality-control)), the pick is marked as invalid.
plotted against the P onset time. A line is fitted to the points, which minimizes the error. Then the deviation of
single picks to this line is checked. If the deviation in seconds is above the *wdttolerance*
parameter ([see here](tuning.md#Pick-quality-control)), the pick is marked as invalid.
<img src=images/gui/wadati_plot.png title="Output diagram of Wadati check"> <img src=images/gui/wadati_plot.png title="Output diagram of Wadati check">
*The Wadati plot in PyLoT shows the SP onset time difference over the P onset time. A first line is fitted (black). All *The Wadati plot in PyLoT shows the SP onset time difference over the P onset time. A first line is fitted (black). All picks which deviate to much from this line are marked invalid (red). Then a second line is fitted which excludes the invalid picks. From this lines slope, the ratio of P and S wave velocity is determined.*
picks which deviate to much from this line are marked invalid (red). Then a second line is fitted which excludes the
invalid picks. From this lines slope, the ratio of P and S wave velocity is determined.*
### Comparison between automatic and manual picks ### Comparison between automatic and manual picks
Every pick in PyLoT consists of an earliest possible, latest possible and most likely onset time. The earliest and Every pick in PyLoT consists of an earliest possible, latest possible and most likely onset time.
latest possible onset time characterize the uncertainty of a pick. This approach is described in Diel, Kissling and The earliest and latest possible onset time characterize the uncertainty of a pick.
Bormann (2012) - Tutorial for consistent phase picking at local to regional distances. These times are represented as a This approach is described in Diel, Kissling and Bormann (2012) - Tutorial for consistent phase picking at local to regional distances.
Probability Density Function (PDF) for every pick. The PDF is implemented as two exponential distributions around the These times are represented as a Probability Density Function (PDF) for every pick.
most likely onset as the expected value. The PDF is implemented as two exponential distributions around the most likely onset as the expected value.
To compare two single picks, their PDFs are cross correlated to create a new PDF. This corresponds to the subtraction of To compare two single picks, their PDFs are cross correlated to create a new PDF.
the automatic pick from the manual pick. This corresponds to the subtraction of the automatic pick from the manual pick.
<img src=images/gui/comparison/comparison_pdf.png title="Comparison between automatic and manual pick"> <img src=images/gui/comparison/comparison_pdf.png title="Comparison between automatic and manual pick">
*Comparison between an automatic and a manual pick for a station in PyLoT by comparing their PDFs.* *Comparison between an automatic and a manual pick for a station in PyLoT by comparing their PDFs.*
*The upper plot shows the difference between the two single picks that are shown in the lower plot.* *The upper plot shows the difference between the two single picks that are shown in the lower plot.*
*The difference is implemented as a cross correlation between the two PDFs. and results in a new PDF, the comparison *The difference is implemented as a cross correlation between the two PDFs. and results in a new PDF, the comparison PDF.*
PDF.* *The expected value of the comparison PDF corresponds to the time distance between the automatic and manual picks most likely onset.*
*The expected value of the comparison PDF corresponds to the time distance between the automatic and manual picks most *The standard deviation corresponds to the combined uncertainty.*
likely onset.*
*The standard deviation corresponds to the combined uncertainty.*
To compare the automatic and manual picks between multiple stations of an event, the properties of all the comparison To compare the automatic and manual picks between multiple stations of an event, the properties of all the comparison PDFs are shown in a histogram.
PDFs are shown in a histogram.
<img src=images/gui/comparison/compare_widget.png title="Comparison between picks of an event"> <img src=images/gui/comparison/compare_widget.png title="Comparison between picks of an event">
@@ -443,13 +352,11 @@ PDFs are shown in a histogram.
*The bottom left plot shows the expected values of the comparison PDFs for P picks.* *The bottom left plot shows the expected values of the comparison PDFs for P picks.*
*The top right plot shows the standard deviation of the comparison PDFs for S picks.* *The top right plot shows the standard deviation of the comparison PDFs for S picks.*
*The bottom right plot shows the expected values of the comparison PDFs for S picks.* *The bottom right plot shows the expected values of the comparison PDFs for S picks.*
*The standard deviation plots show that most P picks have an uncertainty between 1 and 2 seconds, while S pick *The standard deviation plots show that most P picks have an uncertainty between 1 and 2 seconds, while S pick uncertainties have a much larger spread between 1 to 15 seconds.*
uncertainties have a much larger spread between 1 to 15 seconds.*
*This means P picks have higher quality classes on average than S picks.* *This means P picks have higher quality classes on average than S picks.*
*The expected values are largely negative, meaning that the algorithm tends to pick earlier than the analyst with the *The expected values are largely negative, meaning that the algorithm tends to pick earlier than the analyst with the applied settings (Manual - Automatic).*
applied settings (Manual - Automatic).* *The number of samples mentioned in the plots legends is the amount of stations that have an automatic and a manual P pick.*
*The number of samples mentioned in the plots legends is the amount of stations that have an automatic and a manual P
pick.*
### Export and Import of automatic picks ### Export and Import of automatic picks
@@ -462,11 +369,7 @@ To be added.
# FAQ # FAQ
Q: During manual picking the error "No channel to plot for phase ..." is displayed, and I am unable to create a pick. Q: During manual picking the error "No channel to plot for phase ..." is displayed, and I am unable to create a pick.
A: Select a channel that should be used for the corresponding phase in the Pickwindow. For further information A: Select a channel that should be used for the corresponding phase in the Pickwindow. For further information read [Picking Window settings](#picking-window-settings).
read [Picking Window settings](#picking-window-settings).
Q: I see a warning "Mismatch in event identifiers" when loading picks from a file. Q: I see a warning "Mismatch in event identifiers" when loading picks from a file.
A: This means that PyLoT doesn't recognize the picks in the file as belonging to this specific event. They could have A: This means that PyLoT doesn't recognize the picks in the file as belonging to this specific event. They could have been saved under a different installation of PyLoT but with the same waveform data, which means they are still compatible and you can continue loading them or they could be the picks of a different event, in which case loading them is not recommended.
been saved under a different installation of PyLoT but with the same waveform data, which means they are still
compatible and you can continue loading them or they could be the picks of a different event, in which case loading them
is not recommended.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

+61 -112
View File
@@ -6,146 +6,95 @@ A description of the parameters used for determining automatic picks.
Parameters applied to the traces before picking algorithm starts. Parameters applied to the traces before picking algorithm starts.
| Name | Description | Name | Description
|---------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| --- | ---
| *P Start*, *P | | *P Start*, *P Stop* | Define time interval relative to trace start time for CF calculation on vertical trace. Value is relative to theoretical onset time if 'Use TauPy' option is enabled in main settings of 'Tune Autopicker' dialogue.
| Stop* | Define time interval relative to trace start time for CF calculation on vertical trace. Value is relative to theoretical onset time if 'Use TauPy' option is enabled in main settings of 'Tune Autopicker' dialogue. | *S Start*, *S Stop* | Define time interval relative to trace start time for CF calculation on horizontal traces. Value is relative to theoretical onset time if 'Use TauPy' option is enabled in main settings of 'Tune Autopicker' dialogue.
| *S Start*, *S | | *Bandpass Z1* | Filter settings for Butterworth bandpass applied to vertical trace for calculation of initial P pick.
| Stop* | Define time interval relative to trace start time for CF calculation on horizontal traces. Value is relative to theoretical onset time if 'Use TauPy' option is enabled in main settings of 'Tune Autopicker' dialogue. | *Bandpass Z2* | Filter settings for Butterworth bandpass applied to vertical trace for calculation of precise P pick.
| *Bandpass | | *Bandpass H1* | Filter settings for Butterworth bandpass applied to horizontal traces for calculation of initial S pick.
| Z1* | Filter settings for Butterworth bandpass applied to vertical trace for calculation of initial P pick. | *Bandpass H2* | Filter settings for Butterworth bandpass applied to horizontal traces for calculation of precise S pick.
| *Bandpass | |
| Z2* | Filter settings for Butterworth bandpass applied to vertical trace for calculation of precise P pick. |
| *Bandpass | |
| H1* | Filter settings for Butterworth bandpass applied to horizontal traces for calculation of initial S pick. |
| *Bandpass | |
| H2* | Filter settings for Butterworth bandpass applied to horizontal traces for calculation of precise S pick. |
## Inital P pick ## Inital P pick
Parameters used for determination of initial P pick. Parameters used for determination of initial P pick.
| Name | Description | Name | Description
|-------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------| --- | ---
| * | | *tLTA* | Size of gliding LTA window in seconds used for calculation of HOS-CF.
| tLTA* | Size of gliding LTA window in seconds used for calculation of HOS-CF. | *pickwin P* | Size of time window in seconds in which the minimum of the AIC-CF in front of the maximum of the HOS-CF is determined.
| *pickwin | | *AICtsmooth* | Average of samples in this time window will be used for smoothing of the AIC-CF.
| P* | Size of time window in seconds in which the minimum of the AIC-CF in front of the maximum of the HOS-CF is determined. | *checkwinP* | Time in front of the global maximum of the HOS-CF in which to search for a second local extrema.
| * | | *minfactorP* | Used with *checkwinP*. If a second local maximum is found, it has to be at least as big as the first maximum * *minfactorP*.
| AICtsmooth* | Average of samples in this time window will be used for smoothing of the AIC-CF. | *tsignal* | Time window in seconds after the initial P pick used for determining signal amplitude.
| * | | *tnoise* | Time window in seconds in front of initial P pick used for determining noise amplitude.
| checkwinP* | Time in front of the global maximum of the HOS-CF in which to search for a second local extrema. | *tsafetey* | Time in seconds between *tsignal* and *tnoise*.
| *minfactorP* | Used with * | *tslope* | Time window in seconds after initial P pick in which the slope of the onset is calculated.
| checkwinP*. If a second local maximum is found, it has to be at least as big as the first maximum * *minfactorP*. | |
| * | |
| tsignal* | Time window in seconds after the initial P pick used for determining signal amplitude. |
| * | |
| tnoise* | Time window in seconds in front of initial P pick used for determining noise amplitude. |
| *tsafetey* | Time in seconds between *tsignal* and * |
| tnoise*. | |
| * | |
| tslope* | Time window in seconds after initial P pick in which the slope of the onset is calculated. |
## Inital S pick ## Inital S pick
Parameters used for determination of initial S pick Parameters used for determination of initial S pick
| Name | Description | Name | Description
|-------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------| --- | ---
| * | | *tdet1h* | Length of time window in seconds in which AR params of the waveform are determined.
| tdet1h* | Length of time window in seconds in which AR params of the waveform are determined. | *tpred1h* | Length of time window in seconds in which the waveform is predicted using the AR model.
| * | | *AICtsmoothS* | Average of samples in this time window is used for smoothing the AIC-CF.
| tpred1h* | Length of time window in seconds in which the waveform is predicted using the AR model. | *pickwinS* | Time window in which the minimum in the AIC-CF in front of the maximum in the ARH-CF is determined.
| * | | *checkwinS* | Time in front of the global maximum of the ARH-CF in which to search for a second local extrema.
| AICtsmoothS* | Average of samples in this time window is used for smoothing the AIC-CF. | *minfactorP* | Used with *checkwinS*. If a second local maximum is found, it has to be at least as big as the first maximum * *minfactorS*.
| * | | *tsignal* | Time window in seconds after the initial P pick used for determining signal amplitude.
| pickwinS* | Time window in which the minimum in the AIC-CF in front of the maximum in the ARH-CF is determined. | *tnoise* | Time window in seconds in front of initial P pick used for determining noise amplitude.
| * | | *tsafetey* | Time in seconds between *tsignal* and *tnoise*.
| checkwinS* | Time in front of the global maximum of the ARH-CF in which to search for a second local extrema. | *tslope* | Time window in seconds after initial P pick in which the slope of the onset is calculated.
| *minfactorP* | Used with * |
| checkwinS*. If a second local maximum is found, it has to be at least as big as the first maximum * *minfactorS*. | |
| * | |
| tsignal* | Time window in seconds after the initial P pick used for determining signal amplitude. |
| * | |
| tnoise* | Time window in seconds in front of initial P pick used for determining noise amplitude. |
| *tsafetey* | Time in seconds between *tsignal* and * |
| tnoise*. | |
| * | |
| tslope* | Time window in seconds after initial P pick in which the slope of the onset is calculated. |
## Precise P pick ## Precise P pick
Parameters used for determination of precise P pick. Parameters used for determination of precise P pick.
| Name | Description | Name | Description
|-------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| --- | ---
| *Precalcwin* | Time window in seconds for recalculation of the HOS-CF. The new CF will be two times the size of * | *Precalcwin* | Time window in seconds for recalculation of the HOS-CF. The new CF will be two times the size of *Precalcwin*, since it will be calculated from the initial pick to +/- *Precalcwin*.
| Precalcwin*, since it will be calculated from the initial pick to +/- *Precalcwin*. | | *tsmoothP* | Average of samples in this time window will be used for smoothing the second HOS-CF.
| * | | *ausP* | Controls artificial uplift of samples during precise picking. A common local minimum of the smoothed and unsmoothed HOS-CF is found when the previous sample is larger or equal to the current sample times (1+*ausP*).
| tsmoothP* | Average of samples in this time window will be used for smoothing the second HOS-CF. |
| * | |
| ausP* | Controls artificial uplift of samples during precise picking. A common local minimum of the smoothed and unsmoothed HOS-CF is found when the previous sample is larger or equal to the current sample times (1+* |
| ausP*). | |
## Precise S pick ## Precise S pick
Parameters used for determination of precise S pick. Parameters used for determination of precise S pick.
| Name | Description | Name | Description
|--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| --- | ---
| * | | *tdet2h* | Time window for determination of AR coefficients.
| tdet2h* | Time window for determination of AR coefficients. | *tpred2h* | Time window in which the waveform is predicted using the determined AR parameters.
| * | | *Srecalcwin* | Time window for recalculation of ARH-CF. New CF will be calculated from initial pick +/- *Srecalcwin*.
| tpred2h* | Time window in which the waveform is predicted using the determined AR parameters. | *tsmoothS* | Average of samples in this time window will be used for smoothing the second ARH-CF.
| *Srecalcwin* | Time window for recalculation of ARH-CF. New CF will be calculated from initial pick +/- * | *ausS* | Controls artificial uplift of samples during precise picking. A common local minimum of the smoothed and unsmoothed ARH-CF is found when the previous sample is larger or equal to the current sample times (1+*ausS*).
| Srecalcwin*. | | *pickwinS* | Time window around initial pick in which to look for a precise pick.
| * | |
| tsmoothS* | Average of samples in this time window will be used for smoothing the second ARH-CF. |
| * | |
| ausS* | Controls artificial uplift of samples during precise picking. A common local minimum of the smoothed and unsmoothed ARH-CF is found when the previous sample is larger or equal to the current sample times (1+* |
| ausS*). | |
| * | |
| pickwinS* | Time window around initial pick in which to look for a precise pick. |
## Pick quality control ## Pick quality control
Parameters used for checking quality and integrity of automatic picks. Parameters used for checking quality and integrity of automatic picks.
| Name | Description | Name | Description
|--------------------------------------------|-----------------------------------------------------------------------| --- | ---
| * | | *minAICPslope* | Initial P picks with a slope lower than this value will be discared.
| minAICPslope* | Initial P picks with a slope lower than this value will be discared. | *minAICPSNR* | Initial P picks with a SNR below this value will be discarded.
| * | | *minAICSslope* | Initial S picks with a slope lower than this value will be discarded.
| minAICPSNR* | Initial P picks with a SNR below this value will be discarded. | *minAICSSNR* | Initial S picks with a SNR below this value will be discarded.
| * | | *minsiglength*, *noisefacor*. *minpercent* | Parameters for checking signal length. In the time window of size *minsiglength* after the initial P pick *minpercent* of samples have to be larger than the RMS value.
| minAICSslope* | Initial S picks with a slope lower than this value will be discarded. | *zfac* | To recognize misattributed S picks, the RMS amplitude of vertical and horizontal traces are compared. The RMS amplitude of the vertical traces has to be at least *zfac* higher than the RMS amplitude on the horizontal traces for the pick to be accepted as a valid P pick.
| * | | *jackfactor* | A P pick is removed if the jackknife pseudo value of the variance of his subgroup is larger than the variance of all picks multiplied with the *jackfactor*.
| minAICSSNR* | Initial S picks with a SNR below this value will be discarded. | *mdttolerance* | Maximum allowed deviation of P onset times from the median. Value in seconds.
| *minsiglength*, *noisefacor*. *minpercent* | Parameters for checking signal length. In the time window of size * | *wdttolerance* | Maximum allowed deviation of S onset times from the line during the Wadati test. Value in seconds.
minsiglength* after the initial P pick *
minpercent* of samples have to be larger than the RMS value. |
| *
zfac* | To recognize misattributed S picks, the RMS amplitude of vertical and horizontal traces are compared. The RMS amplitude of the vertical traces has to be at least *
zfac* higher than the RMS amplitude on the horizontal traces for the pick to be accepted as a valid P pick. |
| *
jackfactor* | A P pick is removed if the jackknife pseudo value of the variance of his subgroup is larger than the variance of all picks multiplied with the *
jackfactor*. |
| *
mdttolerance* | Maximum allowed deviation of P onset times from the median. Value in seconds. |
| *
wdttolerance* | Maximum allowed deviation of S onset times from the line during the Wadati test. Value in seconds. |
## Pick quality determination ## Pick quality determination
Parameters for discrete quality classes. Parameters for discrete quality classes.
| Name | Description | Name | Description
|--------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------| --- | ---
| * | | *timeerrorsP* | Width of the time windows in seconds between earliest and latest possible pick which represent the quality classes 0, 1, 2, 3 for P onsets.
| timeerrorsP* | Width of the time windows in seconds between earliest and latest possible pick which represent the quality classes 0, 1, 2, 3 for P onsets. | *timeerrorsS* | Width of the time windows in seconds between earliest and latest possible pick which represent the quality classes 0, 1, 2, 3 for S onsets.
| * | | *nfacP*, *nfacS* | For determination of latest possible onset time. The time when the signal reaches an amplitude of *nfac* * mean value of the RMS amplitude in the time window *tnoise* corresponds to the latest possible onset time.
| timeerrorsS* | Width of the time windows in seconds between earliest and latest possible pick which represent the quality classes 0, 1, 2, 3 for S onsets. |
| *nfacP*, *nfacS* | For determination of latest possible onset time. The time when the signal reaches an amplitude of * |
| nfac* * mean value of the RMS amplitude in the time window *tnoise* corresponds to the latest possible onset time. | |
-1
View File
@@ -30,7 +30,6 @@
<file>icons/openloc.png</file> <file>icons/openloc.png</file>
<file>icons/compare_button.png</file> <file>icons/compare_button.png</file>
<file>icons/pick_qualities_button.png</file> <file>icons/pick_qualities_button.png</file>
<file>icons/eventlist_xml_button.png</file>
<file>icons/locate_button.png</file> <file>icons/locate_button.png</file>
<file>icons/Matlab_PILOT_icon.png</file> <file>icons/Matlab_PILOT_icon.png</file>
<file>icons/printer.png</file> <file>icons/printer.png</file>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

+7583 -1458
View File
File diff suppressed because it is too large. Load diff
+104841 -109998
View File
File diff suppressed because it is too large. Load diff
+4 -3
View File
@@ -4,8 +4,10 @@
%Parameters are optimized for %extent data sets! %Parameters are optimized for %extent data sets!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#main settings# #main settings#
#datapath# %data path #rootpath# %project path
#eventID# %event ID for single event processing (* for all events found in datapath) #datapath# %data path
#database# %name of data base
#eventID# %event ID for single event processing (* for all events found in database)
#invdir# %full path to inventory or dataless-seed file #invdir# %full path to inventory or dataless-seed file
PILOT #datastructure# %choose data structure PILOT #datastructure# %choose data structure
True #apverbose# %choose 'True' or 'False' for terminal output True #apverbose# %choose 'True' or 'False' for terminal output
@@ -41,7 +43,6 @@ global #extent# %extent of a
1150.0 #sstop# %end time [s] after P-onset for calculating CF for S-picking 1150.0 #sstop# %end time [s] after P-onset for calculating CF for S-picking
True #use_taup# %use estimated traveltimes from TauPy for calculating windows for CF True #use_taup# %use estimated traveltimes from TauPy for calculating windows for CF
iasp91 #taup_model# %define TauPy model for traveltime estimation. Possible values: 1066a, 1066b, ak135, ak135f, herrin, iasp91, jb, prem, pwdk, sp6 iasp91 #taup_model# %define TauPy model for traveltime estimation. Possible values: 1066a, 1066b, ak135, ak135f, herrin, iasp91, jb, prem, pwdk, sp6
P,Pdiff #taup_phases# %Specify possible phases for TauPy (comma separated). See Obspy TauPy documentation for possible values.
0.05 0.5 #bpz1# %lower/upper corner freq. of first band pass filter Z-comp. [Hz] 0.05 0.5 #bpz1# %lower/upper corner freq. of first band pass filter Z-comp. [Hz]
0.001 0.5 #bpz2# %lower/upper corner freq. of second band pass filter Z-comp. [Hz] 0.001 0.5 #bpz2# %lower/upper corner freq. of second band pass filter Z-comp. [Hz]
0.05 0.5 #bph1# %lower/upper corner freq. of first band pass filter H-comp. [Hz] 0.05 0.5 #bph1# %lower/upper corner freq. of first band pass filter H-comp. [Hz]
+5 -4
View File
@@ -4,8 +4,10 @@
%Parameters are optimized for %extent data sets! %Parameters are optimized for %extent data sets!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#main settings# #main settings#
/DATA/Insheim/EVENT_DATA/LOCAL/2018.02_Insheim #datapath# %data path /DATA/Insheim #rootpath# %project path
e0006.038.18 #eventID# %event ID for single event processing (* for all events found in datapath) EVENT_DATA/LOCAL #datapath# %data path
2018.02_Insheim #database# %name of data base
e0006.038.18 #eventID# %event ID for single event processing (* for all events found in database)
/DATA/Insheim/STAT_INFO #invdir# %full path to inventory or dataless-seed file /DATA/Insheim/STAT_INFO #invdir# %full path to inventory or dataless-seed file
PILOT #datastructure# %choose data structure PILOT #datastructure# %choose data structure
True #apverbose# %choose 'True' or 'False' for terminal output True #apverbose# %choose 'True' or 'False' for terminal output
@@ -40,8 +42,7 @@ local #extent# %extent of a
-0.5 #sstart# %start time [s] relative to P-onset for calculating CF for S-picking -0.5 #sstart# %start time [s] relative to P-onset for calculating CF for S-picking
10.0 #sstop# %end time [s] after P-onset for calculating CF for S-picking 10.0 #sstop# %end time [s] after P-onset for calculating CF for S-picking
False #use_taup# %use estimated traveltimes from TauPy for calculating windows for CF False #use_taup# %use estimated traveltimes from TauPy for calculating windows for CF
iasp91 #taup_model# %define TauPy model for traveltime estimation iasp91 #taup_model# %define TauPy model for traveltime estimation
P #taup_phases# %Specify possible phases for TauPy (comma separated). See Obspy TauPy documentation for possible values.
2.0 20.0 #bpz1# %lower/upper corner freq. of first band pass filter Z-comp. [Hz] 2.0 20.0 #bpz1# %lower/upper corner freq. of first band pass filter Z-comp. [Hz]
2.0 30.0 #bpz2# %lower/upper corner freq. of second band pass filter Z-comp. [Hz] 2.0 30.0 #bpz2# %lower/upper corner freq. of second band pass filter Z-comp. [Hz]
2.0 10.0 #bph1# %lower/upper corner freq. of first band pass filter H-comp. [Hz] 2.0 10.0 #bph1# %lower/upper corner freq. of first band pass filter H-comp. [Hz]
+5 -4
View File
@@ -4,8 +4,10 @@
%Parameters are optimized for %extent data sets! %Parameters are optimized for %extent data sets!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#main settings# #main settings#
#datapath# %data path #rootpath# %project path
#eventID# %event ID for single event processing (* for all events found in datapath) #datapath# %data path
#database# %name of data base
#eventID# %event ID for single event processing (* for all events found in database)
#invdir# %full path to inventory or dataless-seed file #invdir# %full path to inventory or dataless-seed file
PILOT #datastructure# %choose data structure PILOT #datastructure# %choose data structure
True #apverbose# %choose 'True' or 'False' for terminal output True #apverbose# %choose 'True' or 'False' for terminal output
@@ -40,8 +42,7 @@ local #extent# %extent of a
-1.0 #sstart# %start time [s] relative to P-onset for calculating CF for S-picking -1.0 #sstart# %start time [s] relative to P-onset for calculating CF for S-picking
10.0 #sstop# %end time [s] after P-onset for calculating CF for S-picking 10.0 #sstop# %end time [s] after P-onset for calculating CF for S-picking
True #use_taup# %use estimated traveltimes from TauPy for calculating windows for CF True #use_taup# %use estimated traveltimes from TauPy for calculating windows for CF
iasp91 #taup_model# %define TauPy model for traveltime estimation iasp91 #taup_model# %define TauPy model for traveltime estimation
P #taup_phases# %Specify possible phases for TauPy (comma separated). See Obspy TauPy documentation for possible values.
2.0 10.0 #bpz1# %lower/upper corner freq. of first band pass filter Z-comp. [Hz] 2.0 10.0 #bpz1# %lower/upper corner freq. of first band pass filter Z-comp. [Hz]
2.0 12.0 #bpz2# %lower/upper corner freq. of second band pass filter Z-comp. [Hz] 2.0 12.0 #bpz2# %lower/upper corner freq. of second band pass filter Z-comp. [Hz]
2.0 8.0 #bph1# %lower/upper corner freq. of first band pass filter H-comp. [Hz] 2.0 8.0 #bph1# %lower/upper corner freq. of first band pass filter H-comp. [Hz]
+1 -3
View File
@@ -166,7 +166,7 @@ def installPyLoT(verbosity=None):
if verbosity > 1: if verbosity > 1:
print('copying input files into destination folder ...') print('copying input files into destination folder ...')
ans = input('please specify scope of interest ' ans = input('please specify scope of interest '
'([0]=local, 1=regional, 2=global, 3=active) :') or 0 '([0]=local, 1=regional, 2=global) :') or 0
if not isinstance(ans, int): if not isinstance(ans, int):
ans = int(ans) ans = int(ans)
if ans == 0: if ans == 0:
@@ -175,8 +175,6 @@ def installPyLoT(verbosity=None):
ans = 'regional' ans = 'regional'
elif ans == 2: elif ans == 2:
ans = 'global' ans = 'global'
elif ans == 3:
ans = 'active'
link_dest = [] link_dest = []
for file, destination in files_to_copy.items(): for file, destination in files_to_copy.items():
link_file = ans in file link_file = ans in file
-12
View File
@@ -1,12 +0,0 @@
name: pylot_311
channels:
- conda-forge
- defaults
dependencies:
- cartopy=0.23.0=py311hcf9f919_1
- joblib=1.4.2=pyhd8ed1ab_0
- obspy=1.4.1=py311he736701_3
- pyaml=24.7.0=pyhd8ed1ab_0
- pyqtgraph=0.13.7=pyhd8ed1ab_0
- pyside2=5.15.8=py311h3d699ce_4
- pytest=8.3.2=pyhd8ed1ab_0
+1 -1
View File
@@ -9,7 +9,7 @@ PyLoT - the Python picking and Localization Tool
This python library contains a graphical user interfaces for picking This python library contains a graphical user interfaces for picking
seismic phases. This software needs ObsPy (http://github.com/obspy/obspy/wiki) seismic phases. This software needs ObsPy (http://github.com/obspy/obspy/wiki)
and the Qt libraries to be installed first. and the Qt4 libraries to be installed first.
PILOT has been developed in Mathworks' MatLab. In order to distribute PILOT has been developed in Mathworks' MatLab. In order to distribute
PILOT without facing portability problems, it has been decided to re- PILOT without facing portability problems, it has been decided to re-
+25 -78
View File
@@ -144,10 +144,6 @@ class Magnitude(object):
azimuthal_gap=self.origin_id.get_referred_object().quality.azimuthal_gap) azimuthal_gap=self.origin_id.get_referred_object().quality.azimuthal_gap)
else: else:
# no scaling necessary # no scaling necessary
# Temporary fix needs rework
if (len(self.magnitudes.keys()) == 0):
print("Error in local magnitude calculation ")
return None
mag = ope.Magnitude( mag = ope.Magnitude(
mag=np.median([M.mag for M in self.magnitudes.values()]), mag=np.median([M.mag for M in self.magnitudes.values()]),
magnitude_type=self.type, magnitude_type=self.type,
@@ -225,16 +221,11 @@ class LocalMagnitude(Magnitude):
power = [np.power(tr.data, 2) for tr in st if tr.stats.channel[-1] not power = [np.power(tr.data, 2) for tr in st if tr.stats.channel[-1] not
in 'Z3'] in 'Z3']
# checking horizontal count and calculating power_sum accordingly if len(power) != 2:
if len(power) == 1: raise ValueError('Wood-Anderson amplitude defintion only valid for '
print('WARNING: Only one horizontal found for station {0}.'.format(st[0].stats.station)) 'two horizontals: {0} given'.format(len(power)))
power_sum = power[0] power_sum = power[0] + power[1]
elif len(power) == 2: #
power_sum = power[0] + power[1]
else:
raise ValueError('Wood-Anderson aomplitude defintion only valid for'
' up to two horizontals: {0} given'.format(len(power)))
sqH = np.sqrt(power_sum) sqH = np.sqrt(power_sum)
# get time array # get time array
@@ -286,13 +277,12 @@ class LocalMagnitude(Magnitude):
for a in self.arrivals: for a in self.arrivals:
if a.phase not in 'sS': if a.phase not in 'sS':
continue continue
pick = a.pick_id.get_referred_object()
station = pick.waveform_id.station_code
# make sure calculating Ml only from reliable onsets # make sure calculating Ml only from reliable onsets
# NLLoc: time_weight = 0 => do not use onset! # NLLoc: time_weight = 0 => do not use onset!
if a.time_weight == 0: if a.time_weight == 0:
print("Uncertain pick at Station {}, do not use it!".format(station))
continue continue
pick = a.pick_id.get_referred_object()
station = pick.waveform_id.station_code
wf = select_for_phase(self.stream.select( wf = select_for_phase(self.stream.select(
station=station), a.phase) station=station), a.phase)
if not wf: if not wf:
@@ -329,7 +319,7 @@ class LocalMagnitude(Magnitude):
if self.verbose: if self.verbose:
print( print(
"Local Magnitude for station {0}: ML = {1:3.1f}".format( "Local Magnitude for station {0}: ML = {1:3.1f}".format(
station, magnitude.mag)) station, magnitude.mag))
magnitude.origin_id = self.origin_id magnitude.origin_id = self.origin_id
magnitude.waveform_id = pick.waveform_id magnitude.waveform_id = pick.waveform_id
magnitude.amplitude_id = amplitude.resource_id magnitude.amplitude_id = amplitude.resource_id
@@ -404,32 +394,24 @@ class MomentMagnitude(Magnitude):
print("WARNING: No instrument corrected data available," print("WARNING: No instrument corrected data available,"
" no magnitude calculation possible! Go on.") " no magnitude calculation possible! Go on.")
continue continue
wf = self.stream.select(station=station) scopy = self.stream.copy()
wf = scopy.select(station=station)
if not wf: if not wf:
continue continue
try:
scopy = wf.copy()
except AssertionError:
print("WARNING: Something's wrong with the data,"
"station {},"
"no calculation of moment magnitude possible! Go on.".format(station))
continue
onset = pick.time onset = pick.time
distance = degrees2kilometers(a.distance) distance = degrees2kilometers(a.distance)
azimuth = a.azimuth azimuth = a.azimuth
incidence = a.takeoff_angle incidence = a.takeoff_angle
if not 0. <= incidence <= 360.: w0, fc = calcsourcespec(wf, onset, self.p_velocity, distance,
if self.verbose:
print(f'WARNING: Incidence angle outside bounds - {incidence}')
return
w0, fc = calcsourcespec(scopy, onset, self.p_velocity, distance,
azimuth, incidence, self.p_attenuation, azimuth, incidence, self.p_attenuation,
self.plot_flag, self.verbose) self.plot_flag, self.verbose)
if w0 is None or fc is None: if w0 is None or fc is None:
if self.verbose: if self.verbose:
print("WARNING: insufficient frequency information") print("WARNING: insufficient frequency information")
continue continue
WF = select_for_phase(scopy, "P") WF = select_for_phase(self.stream.select(
station=station), a.phase)
WF = select_for_phase(WF, "P")
m0, mw = calcMoMw(WF, w0, self.rock_density, self.p_velocity, m0, mw = calcMoMw(WF, w0, self.rock_density, self.p_velocity,
distance, self.verbose) distance, self.verbose)
self.moment_props = (station, dict(w0=w0, fc=fc, Mo=m0)) self.moment_props = (station, dict(w0=w0, fc=fc, Mo=m0))
@@ -440,40 +422,6 @@ class MomentMagnitude(Magnitude):
self.event.station_magnitudes.append(magnitude) self.event.station_magnitudes.append(magnitude)
self.magnitudes = (station, magnitude) self.magnitudes = (station, magnitude)
# WIP JG
def getSourceSpec(self):
for a in self.arrivals:
if a.phase not in 'pP':
continue
# make sure calculating Mo only from reliable onsets
# NLLoc: time_weight = 0 => do not use onset!
if a.time_weight == 0:
continue
pick = a.pick_id.get_referred_object()
station = pick.waveform_id.station_code
if len(self.stream) <= 2:
print("Station:" '{0}'.format(station))
print("WARNING: No instrument corrected data available,"
" no magnitude calculation possible! Go on.")
continue
wf = self.stream.select(station=station)
if not wf:
continue
try:
scopy = wf.copy()
except AssertionError:
print("WARNING: Something's wrong with the data,"
"station {},"
"no calculation of moment magnitude possible! Go on.".format(station))
continue
onset = pick.time
distance = degrees2kilometers(a.distance)
azimuth = a.azimuth
incidence = a.takeoff_angle
w0, fc, plt = calcsourcespec(scopy, onset, self.p_velocity, distance,
azimuth, incidence, self.p_attenuation,
3, self.verbose)
return w0, fc, plt
def calcMoMw(wfstream, w0, rho, vp, delta, verbosity=False): def calcMoMw(wfstream, w0, rho, vp, delta, verbosity=False):
''' '''
@@ -506,7 +454,7 @@ def calcMoMw(wfstream, w0, rho, vp, delta, verbosity=False):
# additional common parameters for calculating Mo # additional common parameters for calculating Mo
# average radiation pattern of P waves (Aki & Richards, 1980) # average radiation pattern of P waves (Aki & Richards, 1980)
rP = 2 / np.sqrt(15) rP = 2 / np.sqrt(15)
freesurf = 2.0 # free surface correction, assuming vertical incidence freesurf = 2.0 # free surface correction, assuming vertical incidence
Mo = w0 * 4 * np.pi * rho * np.power(vp, 3) * delta / (rP * freesurf) Mo = w0 * 4 * np.pi * rho * np.power(vp, 3) * delta / (rP * freesurf)
@@ -566,7 +514,7 @@ def calcsourcespec(wfstream, onset, vp, delta, azimuth, incidence,
iplot = 2 iplot = 2
else: else:
iplot = 0 iplot = 0
# get Q value # get Q value
Q, A = qp Q, A = qp
@@ -574,6 +522,7 @@ def calcsourcespec(wfstream, onset, vp, delta, azimuth, incidence,
Fc = None Fc = None
w0 = None w0 = None
zdat = select_for_phase(wfstream, "P") zdat = select_for_phase(wfstream, "P")
if len(zdat) == 0: if len(zdat) == 0:
@@ -588,6 +537,7 @@ def calcsourcespec(wfstream, onset, vp, delta, azimuth, incidence,
# trim traces to common range (for rotation) # trim traces to common range (for rotation)
trstart, trend = common_range(wfstream) trstart, trend = common_range(wfstream)
wfstream.trim(trstart, trend) wfstream.trim(trstart, trend)
# rotate into LQT (ray-coordindate-) system using Obspy's rotate # rotate into LQT (ray-coordindate-) system using Obspy's rotate
# L: P-wave direction # L: P-wave direction
# Q: SV-wave direction # Q: SV-wave direction
@@ -636,15 +586,14 @@ def calcsourcespec(wfstream, onset, vp, delta, azimuth, incidence,
# fft # fft
fny = freq / 2 fny = freq / 2
# l = len(xdat) / freq #l = len(xdat) / freq
# number of fft bins after Bath # number of fft bins after Bath
# n = freq * l #n = freq * l
# find next power of 2 of data length # find next power of 2 of data length
m = pow(2, np.ceil(np.log(len(xdat)) / np.log(2))) m = pow(2, np.ceil(np.log(len(xdat)) / np.log(2)))
N = min(int(np.power(m, 2)), 16384) N = int(np.power(m, 2))
# N = int(np.power(m, 2))
y = dt * np.fft.fft(xdat, N) y = dt * np.fft.fft(xdat, N)
Y = abs(y[: int(N / 2)]) Y = abs(y[: N / 2])
L = (N - 1) / freq L = (N - 1) / freq
f = np.arange(0, fny, 1 / L) f = np.arange(0, fny, 1 / L)
@@ -685,8 +634,8 @@ def calcsourcespec(wfstream, onset, vp, delta, azimuth, incidence,
w0 = np.median([w01, w02]) w0 = np.median([w01, w02])
Fc = np.median([fc1, fc2]) Fc = np.median([fc1, fc2])
if verbosity: if verbosity:
print("calcsourcespec: Using w0-value = %e m/Hz and fc = %f Hz" % ( print("calcsourcespec: Using w0-value = %e m/Hz and fc = %f Hz" % (
w0, Fc)) w0, Fc))
if iplot >= 1: if iplot >= 1:
f1 = plt.figure() f1 = plt.figure()
tLdat = np.arange(0, len(Ldat) * dt, dt) tLdat = np.arange(0, len(Ldat) * dt, dt)
@@ -721,8 +670,6 @@ def calcsourcespec(wfstream, onset, vp, delta, azimuth, incidence,
plt.xlabel('Frequency [Hz]') plt.xlabel('Frequency [Hz]')
plt.ylabel('Amplitude [m/Hz]') plt.ylabel('Amplitude [m/Hz]')
plt.grid() plt.grid()
if iplot == 3:
return w0, Fc, plt
plt.show() plt.show()
try: try:
input() input()
@@ -777,7 +724,7 @@ def fitSourceModel(f, S, fc0, iplot, verbosity=False):
iplot = 2 iplot = 2
else: else:
iplot = 0 iplot = 0
w0 = [] w0 = []
stdw0 = [] stdw0 = []
fc = [] fc = []
+56 -113
View File
@@ -2,25 +2,24 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import copy import copy
import logging
import os import os
from PySide2.QtWidgets import QMessageBox
from obspy import read_events from obspy import read_events
from obspy.core import read, Stream, UTCDateTime from obspy.core import read, Stream, UTCDateTime
from obspy.core.event import Event as ObsPyEvent from obspy.core.event import Event as ObsPyEvent
from obspy.io.sac import SacIOError from obspy.io.sac import SacIOError
from PySide2.QtWidgets import QMessageBox
import pylot.core.loc.velest as velest
import pylot.core.loc.focmec as focmec import pylot.core.loc.focmec as focmec
import pylot.core.loc.hypodd as hypodd import pylot.core.loc.hypodd as hypodd
import pylot.core.loc.velest as velest
from pylot.core.io.phases import readPILOTEvent, picks_from_picksdict, \ from pylot.core.io.phases import readPILOTEvent, picks_from_picksdict, \
picksdict_from_pilot, merge_picks, PylotParameter picksdict_from_pilot, merge_picks, PylotParameter
from pylot.core.util.errors import FormatError, OverwriteError from pylot.core.util.errors import FormatError, OverwriteError
from pylot.core.util.event import Event from pylot.core.util.event import Event
from pylot.core.util.obspyDMT_interface import qml_from_obspyDMT from pylot.core.util.obspyDMT_interface import qml_from_obspyDMT
from pylot.core.util.utils import fnConstructor, full_range, check4rotated, \ from pylot.core.util.utils import fnConstructor, full_range, check4rotated, \
check_for_gaps_and_merge, trim_station_components, check_for_nan check4gapsAndMerge, trim_station_components
class Data(object): class Data(object):
@@ -36,17 +35,8 @@ class Data(object):
loaded event. Container object holding, e.g. phase arrivals, etc. loaded event. Container object holding, e.g. phase arrivals, etc.
""" """
def __init__(self, parent=None, evtdata=None, picking_parameter=None): def __init__(self, parent=None, evtdata=None):
self._parent = parent self._parent = parent
if not picking_parameter:
if hasattr(parent, '_inputs'):
picking_parameter = parent._inputs
else:
logging.warning('No picking parameters found! Using default input parameters!!!')
picking_parameter = PylotParameter()
self.picking_parameter = picking_parameter
if self.getParent(): if self.getParent():
self.comp = parent.getComponent() self.comp = parent.getComponent()
else: else:
@@ -58,10 +48,10 @@ class Data(object):
elif isinstance(evtdata, dict): elif isinstance(evtdata, dict):
evt = readPILOTEvent(**evtdata) evt = readPILOTEvent(**evtdata)
evtdata = evt evtdata = evt
elif isinstance(evtdata, str): elif type(evtdata) in [str, unicode]:
try: try:
cat = read_events(evtdata) cat = read_events(evtdata)
if len(cat) != 1: if len(cat) is not 1:
raise ValueError('ambiguous event information for file: ' raise ValueError('ambiguous event information for file: '
'{file}'.format(file=evtdata)) '{file}'.format(file=evtdata))
evtdata = cat[0] evtdata = cat[0]
@@ -74,7 +64,7 @@ class Data(object):
elif 'LOC' in evtdata: elif 'LOC' in evtdata:
raise NotImplementedError('PILOT location information ' raise NotImplementedError('PILOT location information '
'read support not yet ' 'read support not yet '
'implemented.') 'implemeted.')
elif 'event.pkl' in evtdata: elif 'event.pkl' in evtdata:
evtdata = qml_from_obspyDMT(evtdata) evtdata = qml_from_obspyDMT(evtdata)
else: else:
@@ -110,7 +100,7 @@ class Data(object):
old_pick.phase_hint == new_pick.phase_hint, old_pick.phase_hint == new_pick.phase_hint,
old_pick.method_id == new_pick.method_id] old_pick.method_id == new_pick.method_id]
if all(comparison): if all(comparison):
del (old_pick) del(old_pick)
old_picks.append(new_pick) old_picks.append(new_pick)
elif not other.isNew() and self.isNew(): elif not other.isNew() and self.isNew():
new = other + self new = other + self
@@ -122,7 +112,7 @@ class Data(object):
return self + other return self + other
else: else:
raise ValueError("both Data objects have differing " raise ValueError("both Data objects have differing "
"unique Event identifiers") "unique Event identifiers")
return self return self
def getPicksStr(self): def getPicksStr(self):
@@ -138,7 +128,7 @@ class Data(object):
def getParent(self): def getParent(self):
""" """
Get PySide.QtGui.QWidget parent object Get PySide2.QtWidgets.QWidget parent object
""" """
return self._parent return self._parent
@@ -173,8 +163,9 @@ class Data(object):
def checkEvent(self, event, fcheck, forceOverwrite=False): def checkEvent(self, event, fcheck, forceOverwrite=False):
""" """
Check information in supplied event and own event and replace with own Check information in supplied event and own event and replace own
information if no other information are given or forced by forceOverwrite information with supplied information if own information not exiisting
or forced by forceOverwrite
:param event: Event that supplies information for comparison :param event: Event that supplies information for comparison
:type event: pylot.core.util.event.Event :type event: pylot.core.util.event.Event
:param fcheck: check and delete existing information :param fcheck: check and delete existing information
@@ -230,7 +221,7 @@ class Data(object):
def replacePicks(self, event, picktype): def replacePicks(self, event, picktype):
""" """
Replace picks in event with own picks Replace own picks with the one in event
:param event: Event that supplies information for comparison :param event: Event that supplies information for comparison
:type event: pylot.core.util.event.Event :type event: pylot.core.util.event.Event
:param picktype: 'auto' or 'manual' picks :param picktype: 'auto' or 'manual' picks
@@ -238,29 +229,26 @@ class Data(object):
:return: :return:
:rtype: None :rtype: None
""" """
checkflag = 1 checkflag = 0
picks = event.picks picks = event.picks
# remove existing picks # remove existing picks
for j, pick in reversed(list(enumerate(picks))): for j, pick in reversed(list(enumerate(picks))):
try: try:
if picktype in str(pick.method_id.id): if picktype in str(pick.method_id.id):
picks.pop(j) picks.pop(j)
checkflag = 2 checkflag = 1
except AttributeError as e: except AttributeError as e:
msg = '{}'.format(e) msg = '{}'.format(e)
print(e) print(e)
checkflag = 0 checkflag = 0
if checkflag > 0: if checkflag:
if checkflag == 1: print("Found %s pick(s), remove them and append new picks to catalog." % picktype)
print("Write new %s picks to catalog." % picktype)
if checkflag == 2:
print("Found %s pick(s), remove them and append new picks to catalog." % picktype)
# append new picks # append new picks
for pick in self.get_evt_data().picks: for pick in self.get_evt_data().picks:
if picktype in str(pick.method_id.id): if picktype in str(pick.method_id.id):
picks.append(pick) picks.append(pick)
def exportEvent(self, fnout, fnext='.xml', fcheck='auto', upperErrors=None): def exportEvent(self, fnout, fnext='.xml', fcheck='auto', upperErrors=None):
""" """
Export event to file Export event to file
@@ -270,6 +258,7 @@ class Data(object):
can be a str or a list of strings of ['manual', 'auto', 'origin', 'magnitude'] can be a str or a list of strings of ['manual', 'auto', 'origin', 'magnitude']
""" """
from pylot.core.util.defaults import OUTPUTFORMATS from pylot.core.util.defaults import OUTPUTFORMATS
if not type(fcheck) == list: if not type(fcheck) == list:
fcheck = [fcheck] fcheck = [fcheck]
@@ -281,11 +270,8 @@ class Data(object):
raise FormatError(errmsg) raise FormatError(errmsg)
if hasattr(self.get_evt_data(), 'notes'): if hasattr(self.get_evt_data(), 'notes'):
try: with open(os.path.join(os.path.dirname(fnout), 'notes.txt'), 'w') as notes_file:
with open(os.path.join(os.path.dirname(fnout), 'notes.txt'), 'w') as notes_file: notes_file.write(self.get_evt_data().notes)
notes_file.write(self.get_evt_data().notes)
except Exception as e:
print('Warning: Could not save notes.txt: ', str(e))
# check for already existing xml-file # check for already existing xml-file
if fnext == '.xml': if fnext == '.xml':
@@ -302,9 +288,7 @@ class Data(object):
return return
self.checkEvent(event, fcheck) self.checkEvent(event, fcheck)
self.setEvtData(event) self.setEvtData(event)
self.get_evt_data().write(fnout + fnext, format=evtformat) self.get_evt_data().write(fnout + fnext, format=evtformat)
# try exporting event # try exporting event
else: else:
evtdata_org = self.get_evt_data() evtdata_org = self.get_evt_data()
@@ -327,64 +311,38 @@ class Data(object):
del picks_copy[k] del picks_copy[k]
break break
lendiff = len(picks) - len(picks_copy) lendiff = len(picks) - len(picks_copy)
if lendiff != 0: if lendiff is not 0:
print("Manual as well as automatic picks available. Prefered the {} manual ones!".format(lendiff)) print("Manual as well as automatic picks available. Prefered the {} manual ones!".format(lendiff))
no_uncertainties_p = []
no_uncertainties_s = []
if upperErrors: if upperErrors:
# check for pick uncertainties exceeding adjusted upper errors # check for pick uncertainties exceeding adjusted upper errors
# Picks with larger uncertainties will not be saved in output file! # Picks with larger uncertainties will not be saved in output file!
for j in range(len(picks)): for j in range(len(picks)):
for i in range(len(picks_copy)): for i in range(len(picks_copy)):
if picks_copy[i].phase_hint[0] == 'P': if picks_copy[i].phase_hint[0] == 'P':
# Skipping pick if no upper_uncertainty is found and warning user if (picks_copy[i].time_errors['upper_uncertainty'] >= upperErrors[0]) or \
if picks_copy[i].time_errors['upper_uncertainty'] is None: (picks_copy[i].time_errors['uncertainty'] is None):
#print("{1} P-Pick of station {0} does not have upper_uncertainty and cant be checked".format(
# picks_copy[i].waveform_id.station_code,
# picks_copy[i].method_id))
if not picks_copy[i].waveform_id.station_code in no_uncertainties_p:
no_uncertainties_p.append(picks_copy[i].waveform_id.station_code)
continue
#print ("checking for upper_uncertainty")
if (picks_copy[i].time_errors['uncertainty'] is None) or \
(picks_copy[i].time_errors['upper_uncertainty'] >= upperErrors[0]):
print("Uncertainty exceeds or equal adjusted upper time error!") print("Uncertainty exceeds or equal adjusted upper time error!")
print("Adjusted uncertainty: {}".format(upperErrors[0])) print("Adjusted uncertainty: {}".format(upperErrors[0]))
print("Pick uncertainty: {}".format(picks_copy[i].time_errors['uncertainty'])) print("Pick uncertainty: {}".format(picks_copy[i].time_errors['uncertainty']))
print("{1} P-Pick of station {0} will not be saved in outputfile".format( print("{1} P-Pick of station {0} will not be saved in outputfile".format(
picks_copy[i].waveform_id.station_code, picks_copy[i].waveform_id.station_code,
picks_copy[i].method_id)) picks_copy[i].method_id))
print("#")
del picks_copy[i] del picks_copy[i]
break break
if picks_copy[i].phase_hint[0] == 'S': if picks_copy[i].phase_hint[0] == 'S':
if (picks_copy[i].time_errors['upper_uncertainty'] >= upperErrors[1]) or \
# Skipping pick if no upper_uncertainty is found and warning user (picks_copy[i].time_errors['uncertainty'] is None):
if picks_copy[i].time_errors['upper_uncertainty'] is None:
#print("{1} S-Pick of station {0} does not have upper_uncertainty and cant be checked".format(
#picks_copy[i].waveform_id.station_code,
#picks_copy[i].method_id))
if not picks_copy[i].waveform_id.station_code in no_uncertainties_s:
no_uncertainties_s.append(picks_copy[i].waveform_id.station_code)
continue
if (picks_copy[i].time_errors['uncertainty'] is None) or \
(picks_copy[i].time_errors['upper_uncertainty'] >= upperErrors[1]):
print("Uncertainty exceeds or equal adjusted upper time error!") print("Uncertainty exceeds or equal adjusted upper time error!")
print("Adjusted uncertainty: {}".format(upperErrors[1])) print("Adjusted uncertainty: {}".format(upperErrors[1]))
print("Pick uncertainty: {}".format(picks_copy[i].time_errors['uncertainty'])) print("Pick uncertainty: {}".format(picks_copy[i].time_errors['uncertainty']))
print("{1} S-Pick of station {0} will not be saved in outputfile".format( print("{1} S-Pick of station {0} will not be saved in outputfile".format(
picks_copy[i].waveform_id.station_code, picks_copy[i].waveform_id.station_code,
picks_copy[i].method_id)) picks_copy[i].method_id))
print("#")
del picks_copy[i] del picks_copy[i]
break break
for s in no_uncertainties_p:
print("P-Pick of station {0} does not have upper_uncertainty and cant be checked".format(s))
for s in no_uncertainties_s:
print("S-Pick of station {0} does not have upper_uncertainty and cant be checked".format(s))
if fnext == '.obs': if fnext == '.obs':
try: try:
@@ -394,14 +352,6 @@ class Data(object):
header = '# EQEVENT: Label: EQ%s Loc: X 0.00 Y 0.00 Z 10.00 OT 0.00 \n' % evid header = '# EQEVENT: Label: EQ%s Loc: X 0.00 Y 0.00 Z 10.00 OT 0.00 \n' % evid
nllocfile = open(fnout + fnext) nllocfile = open(fnout + fnext)
l = nllocfile.readlines() l = nllocfile.readlines()
# Adding A0/Generic Amplitude to .obs file
# l2 = []
# for li in l:
# for amp in evtdata_org.amplitudes:
# if amp.waveform_id.station_code == li[0:5].strip():
# li = li[0:64] + '{:0.2e}'.format(amp.generic_amplitude) + li[73:-1] + '\n'
# l2.append(li)
# l = l2
nllocfile.close() nllocfile.close()
l.insert(0, header) l.insert(0, header)
nllocfile = open(fnout + fnext, 'w') nllocfile = open(fnout + fnext, 'w')
@@ -412,19 +362,25 @@ class Data(object):
not implemented: {1}'''.format(evtformat, e)) not implemented: {1}'''.format(evtformat, e))
if fnext == '.cnv': if fnext == '.cnv':
try: try:
velest.export(picks_copy, fnout + fnext, self.picking_parameter, eventinfo=self.get_evt_data()) velest.export(picks_copy, fnout + fnext, eventinfo=self.get_evt_data())
except KeyError as e: except KeyError as e:
raise KeyError('''{0} export format raise KeyError('''{0} export format
not implemented: {1}'''.format(evtformat, e)) not implemented: {1}'''.format(evtformat, e))
if fnext == '_focmec.in': if fnext == '.focmec':
try: try:
focmec.export(picks_copy, fnout + fnext, self.picking_parameter, eventinfo=self.get_evt_data()) infile = os.path.join(os.path.expanduser('~'), '.pylot', 'pylot.in')
print('Using default input file {}'.format(infile))
parameter = PylotParameter(infile)
focmec.export(picks_copy, fnout + fnext, parameter, eventinfo=self.get_evt_data())
except KeyError as e: except KeyError as e:
raise KeyError('''{0} export format raise KeyError('''{0} export format
not implemented: {1}'''.format(evtformat, e)) not implemented: {1}'''.format(evtformat, e))
if fnext == '.pha': if fnext == '.pha':
try: try:
hypodd.export(picks_copy, fnout + fnext, self.picking_parameter, eventinfo=self.get_evt_data()) infile = os.path.join(os.path.expanduser('~'), '.pylot', 'pylot.in')
print('Using default input file {}'.format(infile))
parameter = PylotParameter(infile)
hypodd.export(picks_copy, fnout + fnext, parameter, eventinfo=self.get_evt_data())
except KeyError as e: except KeyError as e:
raise KeyError('''{0} export format raise KeyError('''{0} export format
not implemented: {1}'''.format(evtformat, e)) not implemented: {1}'''.format(evtformat, e))
@@ -455,30 +411,20 @@ class Data(object):
data.filter(**kwargs) data.filter(**kwargs)
self.dirty = True self.dirty = True
def setWFData(self, fnames, fnames_alt=None, checkRotated=False, metadata=None, tstart=0, tstop=0): def setWFData(self, fnames, fnames_syn=None, checkRotated=False, metadata=None, tstart=0, tstop=0):
""" """
Clear current waveform data and set given waveform data Clear current waveform data and set given waveform data
:param fnames: waveform data names to append :param fnames: waveform data names to append
:param fnames_alt: alternative data to show (e.g. synthetic/processed)
:type fnames: list :type fnames: list
""" """
def check_fname_exists(filenames: list) -> list:
if filenames:
filenames = [fn for fn in filenames if os.path.isfile(fn)]
return filenames
self.wfdata = Stream() self.wfdata = Stream()
self.wforiginal = None self.wforiginal = None
self.wf_alt = Stream() self.wfsyn = Stream()
if tstart == tstop: if tstart == tstop:
tstart = tstop = None tstart = tstop = None
self.tstart = tstart self.tstart = tstart
self.tstop = tstop self.tstop = tstop
# remove directories
fnames = check_fname_exists(fnames)
fnames_alt = check_fname_exists(fnames_alt)
# if obspy_dmt: # if obspy_dmt:
# wfdir = 'raw' # wfdir = 'raw'
# self.processed = False # self.processed = False
@@ -496,8 +442,8 @@ class Data(object):
# wffnames = fnames # wffnames = fnames
if fnames is not None: if fnames is not None:
self.appendWFData(fnames) self.appendWFData(fnames)
if fnames_alt is not None: if fnames_syn is not None:
self.appendWFData(fnames_alt, alternative=True) self.appendWFData(fnames_syn, synthetic=True)
else: else:
return False return False
@@ -505,9 +451,7 @@ class Data(object):
# remove possible underscores in station names # remove possible underscores in station names
# self.wfdata = remove_underscores(self.wfdata) # self.wfdata = remove_underscores(self.wfdata)
# check for gaps and merge # check for gaps and merge
self.wfdata, _ = check_for_gaps_and_merge(self.wfdata) self.wfdata = check4gapsAndMerge(self.wfdata)
# check for nans
check_for_nan(self.wfdata)
# check for stations with rotated components # check for stations with rotated components
if checkRotated and metadata is not None: if checkRotated and metadata is not None:
self.wfdata = check4rotated(self.wfdata, metadata, verbosity=0) self.wfdata = check4rotated(self.wfdata, metadata, verbosity=0)
@@ -519,7 +463,7 @@ class Data(object):
self.dirty = False self.dirty = False
return True return True
def appendWFData(self, fnames, alternative=False): def appendWFData(self, fnames, synthetic=False):
""" """
Read waveform data from fnames and append it to current wf data Read waveform data from fnames and append it to current wf data
:param fnames: waveform data to append :param fnames: waveform data to append
@@ -532,20 +476,19 @@ class Data(object):
if self.dirty: if self.dirty:
self.resetWFData() self.resetWFData()
orig_or_alternative_data = {True: self.wf_alt, real_or_syn_data = {True: self.wfsyn,
False: self.wfdata} False: self.wfdata}
warnmsg = '' warnmsg = ''
for fname in set(fnames): for fname in set(fnames):
try: try:
orig_or_alternative_data[alternative] += read(fname, starttime=self.tstart, endtime=self.tstop) real_or_syn_data[synthetic] += read(fname, starttime=self.tstart, endtime=self.tstop)
except TypeError: except TypeError:
try: try:
orig_or_alternative_data[alternative] += read(fname, format='GSE2', starttime=self.tstart, endtime=self.tstop) real_or_syn_data[synthetic] += read(fname, format='GSE2', starttime=self.tstart, endtime=self.tstop)
except Exception as e: except Exception as e:
try: try:
orig_or_alternative_data[alternative] += read(fname, format='SEGY', starttime=self.tstart, real_or_syn_data[synthetic] += read(fname, format='SEGY', starttime=self.tstart, endtime=self.tstop)
endtime=self.tstop)
except Exception as e: except Exception as e:
warnmsg += '{0}\n{1}\n'.format(fname, e) warnmsg += '{0}\n{1}\n'.format(fname, e)
except SacIOError as se: except SacIOError as se:
@@ -560,8 +503,8 @@ class Data(object):
def getOriginalWFData(self): def getOriginalWFData(self):
return self.wforiginal return self.wforiginal
def getAltWFdata(self): def getSynWFData(self):
return self.wf_alt return self.wfsyn
def resetWFData(self): def resetWFData(self):
""" """
@@ -585,7 +528,7 @@ class Data(object):
def setEvtData(self, event): def setEvtData(self, event):
self.evtdata = event self.evtdata = event
def applyEVTData(self, data, typ='pick'): def applyEVTData(self, data, typ='pick', authority_id='rub'):
""" """
Either takes an `obspy.core.event.Event` object and applies all new Either takes an `obspy.core.event.Event` object and applies all new
information on the event to the actual data if typ is 'event or information on the event to the actual data if typ is 'event or
@@ -836,8 +779,8 @@ class PilotDataStructure(GenericDataStructure):
def __init__(self, **fields): def __init__(self, **fields):
if not fields: if not fields:
fields = {'database': '', fields = {'database': '2006.01',
'root': ''} 'root': '/data/Egelados/EVENT_DATA/LOCAL'}
GenericDataStructure.__init__(self, **fields) GenericDataStructure.__init__(self, **fields)
+20 -8
View File
@@ -6,18 +6,28 @@ import numpy as np
Default parameters used for picking Default parameters used for picking
""" """
defaults = {'datapath': {'type': str, defaults = {'rootpath': {'type': str,
'tooltip': 'path to eventfolders', 'tooltip': 'project path',
'value': '',
'namestring': 'Root path'},
'datapath': {'type': str,
'tooltip': 'data path',
'value': '', 'value': '',
'namestring': 'Data path'}, 'namestring': 'Data path'},
'database': {'type': str,
'tooltip': 'name of data base',
'value': '',
'namestring': 'Database path'},
'eventID': {'type': str, 'eventID': {'type': str,
'tooltip': 'event ID for single event processing (* for all events found in datapath)', 'tooltip': 'event ID for single event processing (* for all events found in database)',
'value': '*', 'value': '',
'namestring': 'Event ID'}, 'namestring': 'Event ID'},
'extent': {'type': str, 'extent': {'type': str,
'tooltip': 'extent of array ("active", "local", "regional" or "global")', 'tooltip': 'extent of array ("local", "regional" or "global")',
'value': 'local', 'value': 'local',
'namestring': 'Array extent'}, 'namestring': 'Array extent'},
@@ -505,14 +515,16 @@ defaults = {'datapath': {'type': str,
'namestring': 'TauPy model'}, 'namestring': 'TauPy model'},
'taup_phases': {'type': str, 'taup_phases': {'type': str,
'tooltip': 'Specify possible phases for TauPy (comma separated). See Obspy TauPy documentation for possible values.', 'tooltip': 'Specify possible phases for TauPy (comma separated). See Obspy TauPy documentation for possible values.',
'value': 'ttall', 'value': 'ttall',
'namestring': 'TauPy phases'}, 'namestring': 'TauPy phases'},
} }
settings_main = { settings_main = {
'dirs': [ 'dirs': [
'rootpath',
'datapath', 'datapath',
'database',
'eventID', 'eventID',
'invdir', 'invdir',
'datastructure', 'datastructure',
-84
View File
@@ -1,84 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Script to get event parameters from PyLoT-xml file to write
them into eventlist.
LK, igem, 03/2021
Edited for use in PyLoT
JG, igem, 01/2022
"""
import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
import glob
from obspy.core.event import read_events
from pyproj import Proj
"""
Creates an eventlist file summarizing all events found in a certain folder. Only called by pressing UI Button eventlis_xml_action
:rtype:
:param path: Path to root folder where single Event folder are to found
"""
def geteventlistfromxml(path, outpath):
p = Proj(proj='utm', zone=32, ellps='WGS84')
# open eventlist file and write header
evlist = outpath + '/eventlist'
evlistobj = open(evlist, 'w')
evlistobj.write(
'EventID Date To Lat Lon EAST NORTH Dep Ml NoP NoS RMS errH errZ Gap \n')
# data path
dp = path + "/e*/*.xml"
# list of all available xml-files
xmlnames = glob.glob(dp)
# read all onset weights
for names in xmlnames:
print("Getting location parameters from {}".format(names))
cat = read_events(names)
try:
st = cat.events[0].origins[0].time
Lat = cat.events[0].origins[0].latitude
Lon = cat.events[0].origins[0].longitude
EAST, NORTH = p(Lon, Lat)
Dep = cat.events[0].origins[0].depth / 1000
Ml = cat.events[0].magnitudes[1].mag
NoP = []
NoS = []
except IndexError:
print('Insufficient data found for event (not localised): ' + names.split('/')[-1].split('_')[-1][
:-4] + ' Skipping event for eventlist.')
continue
for i in range(len(cat.events[0].origins[0].arrivals)):
if cat.events[0].origins[0].arrivals[i].phase == 'P':
NoP.append(cat.events[0].origins[0].arrivals[i].phase)
elif cat.events[0].origins[0].arrivals[i].phase == 'S':
NoS.append(cat.events[0].origins[0].arrivals[i].phase)
# NoP = cat.events[0].origins[0].quality.used_station_count
errH = cat.events[0].origins[0].origin_uncertainty.max_horizontal_uncertainty
errZ = cat.events[0].origins[0].depth_errors.uncertainty
Gap = cat.events[0].origins[0].quality.azimuthal_gap
# evID = names.split('/')[6]
evID = names.split('/')[-1].split('_')[-1][:-4]
Date = str(st.year) + str('%02d' % st.month) + str('%02d' % st.day)
To = str('%02d' % st.hour) + str('%02d' % st.minute) + str('%02d' % st.second) + \
'.' + str('%06d' % st.microsecond)
# write into eventlist
evlistobj.write('%s %s %s %9.6f %9.6f %13.6f %13.6f %8.6f %3.1f %d %d NaN %d %d %d\n' % (evID, \
Date, To, Lat, Lon,
EAST, NORTH, Dep, Ml,
len(NoP), len(NoS),
errH, errZ, Gap))
print('Adding Event ' + names.split('/')[-1].split('_')[-1][:-4] + ' to eventlist')
print('Eventlist created and saved in: ' + outpath)
evlistobj.close()
+3 -33
View File
@@ -1,7 +1,5 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import logging
import os
from pylot.core.io import default_parameters from pylot.core.io import default_parameters
from pylot.core.util.errors import ParameterError from pylot.core.util.errors import ParameterError
@@ -53,16 +51,10 @@ class PylotParameter(object):
self.__parameter = {} self.__parameter = {}
self._verbosity = verbosity self._verbosity = verbosity
self._parFileCont = {} self._parFileCont = {}
# io from parsed arguments alternatively # io from parsed arguments alternatively
for key, val in kwargs.items(): for key, val in kwargs.items():
self._parFileCont[key] = val self._parFileCont[key] = val
self.from_file() self.from_file()
# if no filename or kwargs given, use default values
if not fnin and not kwargs:
self.reset_defaults()
if fnout: if fnout:
self.export2File(fnout) self.export2File(fnout)
@@ -96,10 +88,10 @@ class PylotParameter(object):
return bool(self.__parameter) return bool(self.__parameter)
def __getitem__(self, key): def __getitem__(self, key):
if key in self.__parameter: try:
return self.__parameter[key] return self.__parameter[key]
else: except:
logging.warning(f'{key} not found in PylotParameter') return None
def __setitem__(self, key, value): def __setitem__(self, key, value):
try: try:
@@ -426,28 +418,6 @@ class PylotParameter(object):
line = value + name + ttip line = value + name + ttip
fid.write(line) fid.write(line)
@staticmethod
def check_deprecated_parameters(parameters):
if parameters.hasParam('database') and parameters.hasParam('rootpath'):
parameters['datapath'] = os.path.join(parameters['rootpath'], parameters['datapath'],
parameters['database'])
logging.warning(
f'Parameters database and rootpath are deprecated. '
f'Tried to merge them to now path: {parameters["datapath"]}.'
)
remove_keys = []
for key in parameters:
if not key in default_parameters.defaults.keys():
remove_keys.append(key)
logging.warning(f'Removing deprecated parameter: {key}')
for key in remove_keys:
del parameters[key]
parameters._settings_main = default_parameters.settings_main
parameters._settings_special_pick = default_parameters.settings_special_pick
class FilterOptions(object): class FilterOptions(object):
''' '''
+3 -3
View File
@@ -1,7 +1,7 @@
from obspy import UTCDateTime from obspy import UTCDateTime
from obspy.core import event as ope from obspy.core import event as ope
from pylot.core.util.utils import get_login, get_hash from pylot.core.util.utils import getLogin, getHash
def create_amplitude(pickID, amp, unit, category, cinfo): def create_amplitude(pickID, amp, unit, category, cinfo):
@@ -61,7 +61,7 @@ def create_creation_info(agency_id=None, creation_time=None, author=None):
:return: :return:
''' '''
if author is None: if author is None:
author = get_login() author = getLogin()
if creation_time is None: if creation_time is None:
creation_time = UTCDateTime() creation_time = UTCDateTime()
return ope.CreationInfo(agency_id=agency_id, author=author, return ope.CreationInfo(agency_id=agency_id, author=author,
@@ -210,7 +210,7 @@ def create_resourceID(timetohash, restype, authority_id=None, hrstr=None):
''' '''
assert isinstance(timetohash, UTCDateTime), "'timetohash' is not an ObsPy" \ assert isinstance(timetohash, UTCDateTime), "'timetohash' is not an ObsPy" \
"UTCDateTime object" "UTCDateTime object"
hid = get_hash(timetohash) hid = getHash(timetohash)
if hrstr is None: if hrstr is None:
resID = ope.ResourceIdentifier(restype + '/' + hid[0:6]) resID = ope.ResourceIdentifier(restype + '/' + hid[0:6])
else: else:
+213 -231
View File
@@ -1,14 +1,13 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import glob
import logging
import os
import warnings
import glob
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
import obspy.core.event as ope import obspy.core.event as ope
import os
import scipy.io as sio import scipy.io as sio
import warnings
from obspy.core import UTCDateTime from obspy.core import UTCDateTime
from obspy.core.event import read_events from obspy.core.event import read_events
from obspy.core.util import AttribDict from obspy.core.util import AttribDict
@@ -17,8 +16,8 @@ from pylot.core.io.inputs import PylotParameter
from pylot.core.io.location import create_event, \ from pylot.core.io.location import create_event, \
create_magnitude create_magnitude
from pylot.core.pick.utils import select_for_phase, get_quality_class from pylot.core.pick.utils import select_for_phase, get_quality_class
from pylot.core.util.utils import get_owner, full_range, four_digits, transformFilterString4Export, \ from pylot.core.util.utils import getOwner, full_range, four_digits, transformFilterString4Export, \
backtransformFilterString, loopIdentifyPhase, identifyPhase backtransformFilterString
def add_amplitudes(event, amplitudes): def add_amplitudes(event, amplitudes):
@@ -59,7 +58,7 @@ def readPILOTEvent(phasfn=None, locfn=None, authority_id='RUB', **kwargs):
if phasfn is not None and os.path.isfile(phasfn): if phasfn is not None and os.path.isfile(phasfn):
phases = sio.loadmat(phasfn) phases = sio.loadmat(phasfn)
phasctime = UTCDateTime(os.path.getmtime(phasfn)) phasctime = UTCDateTime(os.path.getmtime(phasfn))
phasauthor = get_owner(phasfn) phasauthor = getOwner(phasfn)
else: else:
phases = None phases = None
phasctime = None phasctime = None
@@ -67,7 +66,7 @@ def readPILOTEvent(phasfn=None, locfn=None, authority_id='RUB', **kwargs):
if locfn is not None and os.path.isfile(locfn): if locfn is not None and os.path.isfile(locfn):
loc = sio.loadmat(locfn) loc = sio.loadmat(locfn)
locctime = UTCDateTime(os.path.getmtime(locfn)) locctime = UTCDateTime(os.path.getmtime(locfn))
locauthor = get_owner(locfn) locauthor = getOwner(locfn)
else: else:
loc = None loc = None
locctime = None locctime = None
@@ -218,7 +217,7 @@ def picksdict_from_obs(fn):
return picks return picks
def picksdict_from_picks(evt, parameter=None): def picksdict_from_picks(evt):
""" """
Takes an Event object and return the pick dictionary commonly used within Takes an Event object and return the pick dictionary commonly used within
PyLoT PyLoT
@@ -231,10 +230,9 @@ def picksdict_from_picks(evt, parameter=None):
'auto': {} 'auto': {}
} }
for pick in evt.picks: for pick in evt.picks:
errors = None
phase = {} phase = {}
station = pick.waveform_id.station_code station = pick.waveform_id.station_code
if pick.waveform_id.channel_code is None: if pick.waveform_id.channel_code == None:
channel = '' channel = ''
else: else:
channel = pick.waveform_id.channel_code channel = pick.waveform_id.channel_code
@@ -246,15 +244,16 @@ def picksdict_from_picks(evt, parameter=None):
else: else:
filter_id = None filter_id = None
try: try:
pick_method = str(pick.method_id) picker = str(pick.method_id)
if pick_method.startswith('smi:local/'): if picker.startswith('smi:local/'):
pick_method = pick_method.split('smi:local/')[1] picker = picker.split('smi:local/')[1]
except IndexError: except IndexError:
pick_method = 'manual' # MP MP TODO maybe improve statement picker = 'manual' # MP MP TODO maybe improve statement
if pick_method == 'None': if picker == 'None':
pick_method = 'manual' picker = 'manual'
try: try:
onsets = picksdict[pick_method][station] #onsets = picksdict[picker][station]
onsets = picksdict[station]
except KeyError as e: except KeyError as e:
# print(e) # print(e)
onsets = {} onsets = {}
@@ -275,32 +274,27 @@ def picksdict_from_picks(evt, parameter=None):
phase['epp'] = epp phase['epp'] = epp
phase['lpp'] = lpp phase['lpp'] = lpp
phase['spe'] = spe phase['spe'] = spe
weight = phase.get('weight') try:
if not weight: phase['weight'] = weight
if not parameter: except:
logging.warning('Using default input parameter') # get onset weight from uncertainty
parameter = PylotParameter() infile = os.path.join(os.path.expanduser('~'), '.pylot', 'pylot.in')
pick.phase_hint = identifyPhase(pick.phase_hint) print('Using default input file {}'.format(infile))
parameter = PylotParameter(infile)
if pick.phase_hint == 'P': if pick.phase_hint == 'P':
errors = parameter['timeerrorsP'] errors = parameter['timeerrorsP']
elif pick.phase_hint == 'S': elif pick.phase_hint == 'S':
errors = parameter['timeerrorsS'] errors = parameter['timeerrorsS']
if errors: weight = get_quality_class(spe, errors)
weight = get_quality_class(spe, errors) phase['weight'] = weight
phase['weight'] = weight
phase['channel'] = channel phase['channel'] = channel
phase['network'] = network phase['network'] = network
phase['picker'] = pick_method phase['picker'] = picker
if pick.polarity == 'positive': phase['fm'] = 'N'
phase['fm'] = 'U'
elif pick.polarity == 'negative':
phase['fm'] = 'D'
else:
phase['fm'] = 'N'
phase['filter_id'] = filter_id if filter_id is not None else '' phase['filter_id'] = filter_id if filter_id is not None else ''
onsets[pick.phase_hint] = phase.copy() onsets[pick.phase_hint] = phase.copy()
picksdict[pick_method][station] = onsets.copy() picksdict[station] = onsets.copy()
return picksdict return picksdict
@@ -356,24 +350,26 @@ def picks_from_picksdict(picks, creation_info=None):
warnings.warn(str(e), RuntimeWarning) warnings.warn(str(e), RuntimeWarning)
filter_id = '' filter_id = ''
pick.filter_id = filter_id pick.filter_id = filter_id
try: try:
polarity = picks[station][label]['fm'] polarity = phase['fm']
if polarity == 'U' or polarity == '+': if polarity == 'U' or '+':
pick.polarity = 'positive' pick.polarity = 'positive'
elif polarity == 'D' or polarity == '-': elif polarity == 'D' or '-':
pick.polarity = 'negative' pick.polarity = 'negative'
else: else:
pick.polarity = 'undecidable' pick.polarity = 'undecidable'
except: except KeyError as e:
pick.polarity = 'undecidable' if 'fm' in str(e): # no polarity information found for this phase
print("No polarity information available!") pass
else:
raise e
picks_list.append(pick) picks_list.append(pick)
return picks_list return picks_list
def reassess_pilot_db(root_dir, db_dir, out_dir=None, fn_param=None, verbosity=0): def reassess_pilot_db(root_dir, db_dir, out_dir=None, fn_param=None, verbosity=0):
# TODO: change root to datapath import glob
db_root = os.path.join(root_dir, db_dir) db_root = os.path.join(root_dir, db_dir)
evt_list = glob.glob1(db_root, 'e????.???.??') evt_list = glob.glob1(db_root, 'e????.???.??')
@@ -388,7 +384,9 @@ def reassess_pilot_event(root_dir, db_dir, event_id, out_dir=None, fn_param=None
from pylot.core.io.inputs import PylotParameter from pylot.core.io.inputs import PylotParameter
from pylot.core.pick.utils import earllatepicker from pylot.core.pick.utils import earllatepicker
# TODO: change root to datapath
if fn_param is None:
fn_param = defaults.AUTOMATIC_DEFAULTS
default = PylotParameter(fn_param, verbosity) default = PylotParameter(fn_param, verbosity)
@@ -478,6 +476,7 @@ def reassess_pilot_event(root_dir, db_dir, event_id, out_dir=None, fn_param=None
os.makedirs(out_dir) os.makedirs(out_dir)
fnout_prefix = os.path.join(out_dir, 'PyLoT_{0}.'.format(event_id)) fnout_prefix = os.path.join(out_dir, 'PyLoT_{0}.'.format(event_id))
evt.write(fnout_prefix + 'xml', format='QUAKEML') evt.write(fnout_prefix + 'xml', format='QUAKEML')
# evt.write(fnout_prefix + 'cnv', format='VELEST')
def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None): def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
@@ -506,16 +505,16 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
and FOCMEC- and HASH-input files and FOCMEC- and HASH-input files
:type eventinfo: `obspy.core.event.Event` object :type eventinfo: `obspy.core.event.Event` object
""" """
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')
# write header # write header
fid.write('# EQEVENT: %s Label: EQ%s Loc: X 0.00 Y 0.00 Z 10.00 OT 0.00 \n' % fid.write('# EQEVENT: %s Label: EQ%s Loc: X 0.00 Y 0.00 Z 10.00 OT 0.00 \n' %
(parameter.get('datapath'), parameter.get('eventID'))) (parameter.get('database'), parameter.get('eventID')))
arrivals = chooseArrivals(arrivals)
for key in arrivals: for key in arrivals:
# P onsets # P onsets
if 'P' in arrivals[key]: if arrivals[key].has_key('P'):
try: try:
fm = arrivals[key]['P']['fm'] fm = arrivals[key]['P']['fm']
except KeyError as e: except KeyError as e:
@@ -536,7 +535,6 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
try: try:
if arrivals[key]['P']['weight'] >= 4: if arrivals[key]['P']['weight'] >= 4:
pweight = 0 # do not use pick pweight = 0 # do not use pick
print("Station {}: Uncertain pick, do not use it!".format(key))
except KeyError as e: except KeyError as e:
print(e.message + '; no weight set during processing') 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, fid.write('%s ? ? ? P %s %d%02d%02d %02d%02d %7.4f GAU 0 0 0 0 %d \n' % (key,
@@ -549,7 +547,7 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
ss_ms, ss_ms,
pweight)) pweight))
# S onsets # S onsets
if 'S' in arrivals[key] and arrivals[key]['S']['mpp'] is not None: if arrivals[key].has_key('S') and arrivals[key]['S']['mpp'] is not None:
fm = '?' fm = '?'
onset = arrivals[key]['S']['mpp'] onset = arrivals[key]['S']['mpp']
year = onset.year year = onset.year
@@ -566,20 +564,15 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
sweight = 0 # do not use pick sweight = 0 # do not use pick
except KeyError as e: except KeyError as e:
print(str(e) + '; no weight set during processing') print(str(e) + '; no weight set during processing')
Ao = arrivals[key]['S']['Ao'] # peak-to-peak amplitude fid.write('%s ? ? ? S %s %d%02d%02d %02d%02d %7.4f GAU 0 0 0 0 %d \n' % (key,
if Ao == None: fm,
Ao = 0.0 year,
# fid.write('%s ? ? ? S %s %d%02d%02d %02d%02d %7.4f GAU 0 0 0 0 %d \n' % (key, month,
fid.write('%s ? ? ? S %s %d%02d%02d %02d%02d %7.4f GAU 0 %9.2f 0 0 %d \n' % (key, day,
fm, hh,
year, mm,
month, ss_ms,
day, sweight))
hh,
mm,
ss_ms,
Ao,
sweight))
fid.close() fid.close()
elif fformat == 'HYPO71': elif fformat == 'HYPO71':
@@ -588,7 +581,6 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
# write header # write header
fid.write(' %s\n' % fid.write(' %s\n' %
parameter.get('eventID')) parameter.get('eventID'))
arrivals = chooseArrivals(arrivals) # MP MP what is chooseArrivals? It is not defined anywhere
for key in arrivals: for key in arrivals:
if arrivals[key]['P']['weight'] < 4: if arrivals[key]['P']['weight'] < 4:
stat = key stat = key
@@ -664,11 +656,10 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
print("Writing phases to %s for HYPOSAT" % filename) print("Writing phases to %s for HYPOSAT" % filename)
fid = open("%s" % filename, 'w') fid = open("%s" % filename, 'w')
# write header # write header
fid.write('%s, event %s \n' % (parameter.get('datapath'), parameter.get('eventID'))) fid.write('%s, event %s \n' % (parameter.get('database'), parameter.get('eventID')))
arrivals = chooseArrivals(arrivals)
for key in arrivals: for key in arrivals:
# P onsets # P onsets
if 'P' in arrivals[key] and arrivals[key]['P']['mpp'] is not None: if arrivals[key].has_key('P') and arrivals[key]['P']['mpp'] is not None:
if arrivals[key]['P']['weight'] < 4: if arrivals[key]['P']['weight'] < 4:
Ponset = arrivals[key]['P']['mpp'] Ponset = arrivals[key]['P']['mpp']
pyear = Ponset.year pyear = Ponset.year
@@ -697,7 +688,7 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
fid.write('%-5s P1 %4.0f %02d %02d %02d %02d %05.02f %5.3f -999. 0.00 -999. 0.00\n' fid.write('%-5s P1 %4.0f %02d %02d %02d %02d %05.02f %5.3f -999. 0.00 -999. 0.00\n'
% (key, pyear, pmonth, pday, phh, pmm, Pss, pstd)) % (key, pyear, pmonth, pday, phh, pmm, Pss, pstd))
# S onsets # S onsets
if 'S' in arrivals[key] and arrivals[key]['S']['mpp'] is not None: if arrivals[key].has_key('S') and arrivals[key]['S']['mpp'] is not None:
if arrivals[key]['S']['weight'] < 4: if arrivals[key]['S']['weight'] < 4:
Sonset = arrivals[key]['S']['mpp'] Sonset = arrivals[key]['S']['mpp']
syear = Sonset.year syear = Sonset.year
@@ -756,40 +747,37 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
cns, eventsource['longitude'], cew, eventsource['depth'], eventinfo.magnitudes[0]['mag'], ifx)) cns, eventsource['longitude'], cew, eventsource['depth'], eventinfo.magnitudes[0]['mag'], ifx))
n = 0 n = 0
# check whether arrivals are dictionaries (autoPyLoT) or pick object (PyLoT) # check whether arrivals are dictionaries (autoPyLoT) or pick object (PyLoT)
if isinstance(arrivals, dict) is False: if isinstance(arrivals, dict) == False:
# convert pick object (PyLoT) into dictionary # convert pick object (PyLoT) into dictionary
evt = ope.Event(resource_id=eventinfo['resource_id']) evt = ope.Event(resource_id=eventinfo['resource_id'])
evt.picks = arrivals evt.picks = arrivals
arrivals = picksdict_from_picks(evt, parameter=parameter) arrivals = picksdict_from_picks(evt)
# check for automatic and manual picks for key in arrivals:
# prefer manual picks
usedarrivals = chooseArrivals(arrivals)
for key in usedarrivals:
# P onsets # P onsets
if 'P' in usedarrivals[key]: if arrivals[key].has_key('P'):
if usedarrivals[key]['P']['weight'] < 4: if arrivals[key]['P']['weight'] < 4:
n += 1 n += 1
stat = key stat = key
if len(stat) > 4: # VELEST handles only 4-string station IDs if len(stat) > 4: # VELEST handles only 4-string station IDs
stat = stat[1:5] stat = stat[1:5]
Ponset = usedarrivals[key]['P']['mpp'] Ponset = arrivals[key]['P']['mpp']
Pweight = usedarrivals[key]['P']['weight'] Pweight = arrivals[key]['P']['weight']
Prt = Ponset - stime # onset time relative to source time Prt = Ponset - stime # onset time relative to source time
if n % 6 != 0: if n % 6 is not 0:
fid.write('%-4sP%d%6.2f' % (stat, Pweight, Prt)) fid.write('%-4sP%d%6.2f' % (stat, Pweight, Prt))
else: else:
fid.write('%-4sP%d%6.2f\n' % (stat, Pweight, Prt)) fid.write('%-4sP%d%6.2f\n' % (stat, Pweight, Prt))
# S onsets # S onsets
if 'S' in usedarrivals[key]: if arrivals[key].has_key('S'):
if usedarrivals[key]['S']['weight'] < 4: if arrivals[key]['S']['weight'] < 4:
n += 1 n += 1
stat = key stat = key
if len(stat) > 4: # VELEST handles only 4-string station IDs if len(stat) > 4: # VELEST handles only 4-string station IDs
stat = stat[1:5] stat = stat[1:5]
Sonset = usedarrivals[key]['S']['mpp'] Sonset = arrivals[key]['S']['mpp']
Sweight = usedarrivals[key]['S']['weight'] Sweight = arrivals[key]['S']['weight']
Srt = Ponset - stime # onset time relative to source time Srt = Ponset - stime # onset time relative to source time
if n % 6 != 0: if n % 6 is not 0:
fid.write('%-4sS%d%6.2f' % (stat, Sweight, Srt)) fid.write('%-4sS%d%6.2f' % (stat, Sweight, Srt))
else: else:
fid.write('%-4sS%d%6.2f\n' % (stat, Sweight, Srt)) fid.write('%-4sS%d%6.2f\n' % (stat, Sweight, Srt))
@@ -805,13 +793,9 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
print("No source origin calculated yet, thus no hypoDD-infile creation possible!") print("No source origin calculated yet, thus no hypoDD-infile creation possible!")
return return
stime = eventsource['time'] stime = eventsource['time']
try: event = parameter.get('eventID')
event = eventinfo['pylot_id'] hddID = event.split('.')[0][1:5]
hddID = event.split('.')[0][1:5] # write header
except:
print("Error 1111111!")
hddID = "00000"
# write header
fid.write('# %d %d %d %d %d %5.2f %7.4f +%6.4f %7.4f %4.2f 0.1 0.5 %4.2f %s\n' % ( fid.write('# %d %d %d %d %d %5.2f %7.4f +%6.4f %7.4f %4.2f 0.1 0.5 %4.2f %s\n' % (
stime.year, stime.month, stime.day, stime.hour, stime.minute, stime.second, stime.year, stime.month, stime.day, stime.hour, stime.minute, stime.second,
eventsource['latitude'], eventsource['longitude'], eventsource['depth'] / 1000, eventsource['latitude'], eventsource['longitude'], eventsource['depth'] / 1000,
@@ -821,21 +805,18 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
# convert pick object (PyLoT) into dictionary # convert pick object (PyLoT) into dictionary
evt = ope.Event(resource_id=eventinfo['resource_id']) evt = ope.Event(resource_id=eventinfo['resource_id'])
evt.picks = arrivals evt.picks = arrivals
arrivals = picksdict_from_picks(evt, parameter=parameter) arrivals = picksdict_from_picks(evt)
# check for automatic and manual picks for key in arrivals:
# prefer manual picks if arrivals[key].has_key('P'):
usedarrivals = chooseArrivals(arrivals)
for key in usedarrivals:
if 'P' in usedarrivals[key]:
# P onsets # P onsets
if usedarrivals[key]['P']['weight'] < 4: if arrivals[key]['P']['weight'] < 4:
Ponset = usedarrivals[key]['P']['mpp'] Ponset = arrivals[key]['P']['mpp']
Prt = Ponset - stime # onset time relative to source time Prt = Ponset - stime # onset time relative to source time
fid.write('%s %6.3f 1 P\n' % (key, Prt)) fid.write('%s %6.3f 1 P\n' % (key, Prt))
if 'S' in usedarrivals[key]: if arrivals[key].has_key('S'):
# S onsets # S onsets
if usedarrivals[key]['S']['weight'] < 4: if arrivals[key]['S']['weight'] < 4:
Sonset = usedarrivals[key]['S']['mpp'] Sonset = arrivals[key]['S']['mpp']
Srt = Sonset - stime # onset time relative to source time Srt = Sonset - stime # onset time relative to source time
fid.write('%-5s %6.3f 1 S\n' % (key, Srt)) fid.write('%-5s %6.3f 1 S\n' % (key, Srt))
@@ -851,15 +832,8 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
print("No source origin calculated yet, thus no FOCMEC-infile creation possible!") print("No source origin calculated yet, thus no FOCMEC-infile creation possible!")
return return
stime = eventsource['time'] stime = eventsource['time']
# avoid printing '*' in focmec-input file
if parameter.get('eventid') == '*' or parameter.get('eventid') is None:
evID = 'e0000'
else:
evID = parameter.get('eventid')
# write header line including event information # write header line including event information
fid.write('%s %d%02d%02d%02d%02d%02.0f %7.4f %6.4f %3.1f %3.1f\n' % (evID, fid.write('%s %d%02d%02d%02d%02d%02.0f %7.4f %6.4f %3.1f %3.1f\n' % (parameter.get('eventID'),
stime.year, stime.month, stime.day, stime.year, stime.month, stime.day,
stime.hour, stime.minute, stime.second, stime.hour, stime.minute, stime.second,
eventsource['latitude'], eventsource['latitude'],
@@ -872,13 +846,10 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
# convert pick object (PyLoT) into dictionary # convert pick object (PyLoT) into dictionary
evt = ope.Event(resource_id=eventinfo['resource_id']) evt = ope.Event(resource_id=eventinfo['resource_id'])
evt.picks = arrivals evt.picks = arrivals
arrivals = picksdict_from_picks(evt, parameter=parameter) arrivals = picksdict_from_picks(evt)
# check for automatic and manual picks for key in arrivals:
# prefer manual picks if arrivals[key].has_key('P'):
usedarrivals = chooseArrivals(arrivals) if arrivals[key]['P']['weight'] < 4 and arrivals[key]['P']['fm'] is not None:
for key in usedarrivals:
if 'P' in usedarrivals[key]:
if usedarrivals[key]['P']['weight'] < 4 and usedarrivals[key]['P']['fm'] is not None:
stat = key stat = key
for i in range(len(picks)): for i in range(len(picks)):
station = picks[i].waveform_id.station_code station = picks[i].waveform_id.station_code
@@ -897,7 +868,7 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
fid.write('%-4s %6.2f %6.2f%s \n' % (stat, fid.write('%-4s %6.2f %6.2f%s \n' % (stat,
az, az,
inz, inz,
usedarrivals[key]['P']['fm'])) arrivals[key]['P']['fm']))
break break
fid.close() fid.close()
@@ -955,11 +926,10 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
eventsource['quality']['used_phase_count'], eventsource['quality']['used_phase_count'],
erh, erz, eventinfo.magnitudes[0]['mag'], erh, erz, eventinfo.magnitudes[0]['mag'],
hashID)) hashID))
# Prefer Manual Picks over automatic ones if possible
arrivals = chooseArrivals(arrivals) # MP MP what is chooseArrivals? It is not defined anywhere
# write phase lines # write phase lines
for key in arrivals: for key in arrivals:
if 'P' in arrivals[key]: if arrivals[key].has_key('P'):
if arrivals[key]['P']['weight'] < 4 and arrivals[key]['P']['fm'] is not None: if arrivals[key]['P']['weight'] < 4 and arrivals[key]['P']['fm'] is not None:
stat = key stat = key
ccode = arrivals[key]['P']['channel'] ccode = arrivals[key]['P']['channel']
@@ -1004,25 +974,6 @@ def writephases(arrivals, fformat, filename, parameter=None, eventinfo=None):
fid2.close() fid2.close()
def chooseArrivals(arrivals):
"""
takes arrivals and returns the manual picks if manual and automatic ones are there
returns automatic picks if only automatic picks are there
:param arrivals: 'dictionary' with automatic and or manual arrivals
:return: arrivals but with the manual picks prefered if possible
"""
# If len of arrivals is greater than 2 it comes from autopicking so only autopicks are available
if len(arrivals) > 2:
return arrivals
if arrivals['auto'] and arrivals['manual']:
usedarrivals = arrivals['manual']
elif arrivals['auto']:
usedarrivals = arrivals['auto']
elif arrivals['manual']:
usedarrivals = arrivals['manual']
return usedarrivals
def merge_picks(event, picks): def merge_picks(event, picks):
""" """
takes an event object and a list of picks and searches for matching takes an event object and a list of picks and searches for matching
@@ -1052,63 +1003,37 @@ def merge_picks(event, picks):
return event return event
def getQualitiesfromxml(path, errorsP, errorsS, plotflag=1, figure=None, verbosity=0): def getQualitiesfromxml(xmlnames, ErrorsP, ErrorsS, plotflag=1):
""" """
Script to get onset uncertainties from Quakeml.xml files created by PyLoT. Script to get onset uncertainties from Quakeml.xml files created by PyLoT.
Uncertainties are tranformed into quality classes and visualized via histogram if desired. Uncertainties are tranformed into quality classes and visualized via histogram if desired.
Ludger Küperkoch, BESTEC GmbH, 07/2017 Ludger Küperkoch, BESTEC GmbH, 07/2017
:param path: path containing xml files :param xmlnames: list of xml obspy event files containing picks
:type path: str :type xmlnames: list
:param errorsP: time errors of P waves for the four discrete quality classes :param ErrorsP: time errors of P waves for the four discrete quality classes
:type errorsP: :type ErrorsP:
:param errorsS: time errors of S waves for the four discrete quality classes :param ErrorsS: time errors of S waves for the four discrete quality classes
:type errorsS: :type ErrorsS:
:param plotflag: :param plotflag:
:type plotflag: :type plotflag:
:return: :return:
:rtype: :rtype:
""" """
def calc_perc(uncertainties, ntotal): from pylot.core.pick.utils import get_quality_class
''' simple function that calculates percentage of number of uncertainties (list length)''' from pylot.core.util.utils import loopIdentifyPhase, identifyPhase
if len(uncertainties) == 0:
return 0
else:
return 100. / ntotal * len(uncertainties)
def calc_weight_perc(psweights, weight_ids):
''' calculate percentages of different weights (pick classes!?) of total number of uncertainties of a phase'''
# count total number of list items for this phase
numWeights = np.sum([len(weight) for weight in psweights.values()])
# iterate over all available weights to return a list with percentages for plotting
plot_list = []
for weight_id in weight_ids:
plot_list.append(calc_perc(psweights[weight_id], numWeights))
return plot_list, numWeights
# get all xmlfiles in path (maybe this should be changed to one xml file for this function, selectable via GUI?)
xmlnames = glob.glob(os.path.join(path, '*.xml'))
if len(xmlnames) == 0:
print(f'No files found in path {path}.')
return False
# first define possible phases here
phases = ['P', 'S']
# define possible weights (0-4)
weight_ids = list(range(5))
# put both error lists in a dictionary with P/S key so that amount of code can be halfed by simply using P/S as key
errors = dict(P=errorsP, S=errorsS)
# create dictionaries for each phase (P/S) with a dictionary of empty list for each weight defined in weights
# tuple above
weights = {}
for phase in phases:
weights[phase] = {weight_id: [] for weight_id in weight_ids}
# read all onset weights
Pw0 = []
Pw1 = []
Pw2 = []
Pw3 = []
Pw4 = []
Sw0 = []
Sw1 = []
Sw2 = []
Sw3 = []
Sw4 = []
for names in xmlnames: for names in xmlnames:
print("Getting onset weights from {}".format(names)) print("Getting onset weights from {}".format(names))
cat = read_events(names) cat = read_events(names)
@@ -1116,60 +1041,117 @@ def getQualitiesfromxml(path, errorsP, errorsS, plotflag=1, figure=None, verbosi
arrivals = cat.events[0].picks arrivals = cat.events[0].picks
arrivals_copy = cat_copy.events[0].picks arrivals_copy = cat_copy.events[0].picks
# Prefere manual picks if qualities are sufficient! # Prefere manual picks if qualities are sufficient!
for pick in arrivals: for Pick in arrivals:
if pick.method_id.id.split('/')[1] == 'manual': if Pick.method_id.id.split('/')[1] == 'manual':
mstation = pick.waveform_id.station_code mstation = Pick.waveform_id.station_code
mstation_ext = mstation + '_' mstation_ext = mstation + '_'
for mpick in arrivals_copy: for mpick in arrivals_copy:
phase = identifyPhase(loopIdentifyPhase(pick.phase_hint)) # MP MP catch if this fails? phase = identifyPhase(loopIdentifyPhase(Pick.phase_hint))
if ((mpick.waveform_id.station_code == mstation) or if phase == 'P':
(mpick.waveform_id.station_code == mstation_ext)) and \ if ((mpick.waveform_id.station_code == mstation) or
(mpick.method_id.id.split('/')[1] == 'auto') and \ (mpick.waveform_id.station_code == mstation_ext)) and \
(mpick.time_errors['uncertainty'] <= errors[phase][3]): (mpick.method_id.split('/')[1] == 'auto') and \
del mpick (mpick.time_errors['uncertainty'] <= ErrorsP[3]):
break del mpick
break
elif phase == 'S':
if ((mpick.waveform_id.station_code == mstation) or
(mpick.waveform_id.station_code == mstation_ext)) and \
(mpick.method_id.split('/')[1] == 'auto') and \
(mpick.time_errors['uncertainty'] <= ErrorsS[3]):
del mpick
break
lendiff = len(arrivals) - len(arrivals_copy) lendiff = len(arrivals) - len(arrivals_copy)
if lendiff != 0: if lendiff is not 0:
print("Found manual as well as automatic picks, prefered the {} manual ones!".format(lendiff)) print("Found manual as well as automatic picks, prefered the {} manual ones!".format(lendiff))
for pick in arrivals_copy: for Pick in arrivals_copy:
phase = identifyPhase(loopIdentifyPhase(pick.phase_hint)) phase = identifyPhase(loopIdentifyPhase(Pick.phase_hint))
uncertainty = pick.time_errors.uncertainty if phase == 'P':
if not uncertainty: Pqual = get_quality_class(Pick.time_errors.uncertainty, ErrorsP)
if verbosity > 0: if Pqual == 0:
print('No uncertainty, pick {} invalid!'.format(pick.method_id.id)) Pw0.append(Pick.time_errors.uncertainty)
continue elif Pqual == 1:
# check P/S phase Pw1.append(Pick.time_errors.uncertainty)
if phase not in phases: elif Pqual == 2:
Pw2.append(Pick.time_errors.uncertainty)
elif Pqual == 3:
Pw3.append(Pick.time_errors.uncertainty)
elif Pqual == 4:
Pw4.append(Pick.time_errors.uncertainty)
elif phase == 'S':
Squal = get_quality_class(Pick.time_errors.uncertainty, ErrorsS)
if Squal == 0:
Sw0.append(Pick.time_errors.uncertainty)
elif Squal == 1:
Sw1.append(Pick.time_errors.uncertainty)
elif Squal == 2:
Sw2.append(Pick.time_errors.uncertainty)
elif Squal == 3:
Sw3.append(Pick.time_errors.uncertainty)
elif Squal == 4:
Sw4.append(Pick.time_errors.uncertainty)
else:
print("Phase hint not defined for picking!") print("Phase hint not defined for picking!")
continue pass
qual = get_quality_class(uncertainty, errors[phase])
weights[phase][qual].append(uncertainty)
if plotflag == 0: if plotflag == 0:
p_unc = [weights['P'][weight_id] for weight_id in weight_ids] Punc = [Pw0, Pw1, Pw2, Pw3, Pw4]
s_unc = [weights['S'][weight_id] for weight_id in weight_ids] Sunc = [Sw0, Sw1, Sw2, Sw3, Sw4]
return p_unc, s_unc return Punc, Sunc
else: else:
if not figure:
fig = plt.figure()
ax = fig.add_subplot(111)
# get percentage of weights # get percentage of weights
listP, numPweights = calc_weight_perc(weights['P'], weight_ids) numPweights = np.sum([len(Pw0), len(Pw1), len(Pw2), len(Pw3), len(Pw4)])
listS, numSweights = calc_weight_perc(weights['S'], weight_ids) numSweights = np.sum([len(Sw0), len(Sw1), len(Sw2), len(Sw3), len(Sw4)])
if len(Pw0) > 0:
P0perc = 100 / numPweights * len(Pw0)
else:
P0perc = 0
if len(Pw1) > 0:
P1perc = 100 / numPweights * len(Pw1)
else:
P1perc = 0
if len(Pw2) > 0:
P2perc = 100 / numPweights * len(Pw2)
else:
P2perc = 0
if len(Pw3) > 0:
P3perc = 100 / numPweights * len(Pw3)
else:
P3perc = 0
if len(Pw4) > 0:
P4perc = 100 / numPweights * len(Pw4)
else:
P4perc = 0
if len(Sw0) > 0:
S0perc = 100 / numSweights * len(Sw0)
else:
S0perc = 0
if len(Sw1) > 0:
S1perc = 100 / numSweights * len(Sw1)
else:
S1perc = 0
if len(Sw2) > 0:
S2perc = 100 / numSweights * len(Sw2)
else:
S2perc = 0
if len(Sw3) > 0:
S3perc = 100 / numSweights * len(Sw3)
else:
S3perc = 0
if len(Sw4) > 0:
S4perc = 100 / numSweights * len(Sw4)
else:
S4perc = 0
y_pos = np.arange(len(weight_ids)) weights = ('0', '1', '2', '3', '4')
y_pos = np.arange(len(weights))
width = 0.34 width = 0.34
ax.bar(y_pos - width, listP, width, color='black') plt.bar(y_pos - width, [P0perc, P1perc, P2perc, P3perc, P4perc], width, color='black')
ax.bar(y_pos, listS, width, color='red') plt.bar(y_pos, [S0perc, S1perc, S2perc, S3perc, S4perc], width, color='red')
ax.set_ylabel('%') plt.ylabel('%')
ax.set_xticks(y_pos, weight_ids) plt.xticks(y_pos, weights)
ax.set_xlim([-0.5, 4.5]) plt.xlim([-0.5, 4.5])
ax.set_xlabel('Qualities') plt.xlabel('Qualities')
ax.set_title('{0} P-Qualities, {1} S-Qualities'.format(numPweights, numSweights)) plt.title('{0} P-Qualities, {1} S-Qualities'.format(numPweights, numSweights))
plt.show()
if not figure:
fig.show()
return listP, listS
+4 -4
View File
@@ -4,12 +4,11 @@
import glob import glob
import os import os
import subprocess import subprocess
from obspy import read_events from obspy import read_events
from pylot.core.io.phases import writephases from pylot.core.io.phases import writephases
from pylot.core.util.gui import which
from pylot.core.util.utils import getPatternLine, runProgram from pylot.core.util.utils import getPatternLine, runProgram
from pylot.core.util.gui import which
from pylot.core.util.version import get_git_version as _getVersionString from pylot.core.util.version import get_git_version as _getVersionString
__version__ = _getVersionString() __version__ = _getVersionString()
@@ -82,8 +81,9 @@ def locate(fnin, parameter=None):
:param fnin: external program name :param fnin: external program name
:return: None :return: None
""" """
exe_path = os.path.join(parameter['nllocbin'], 'NLLoc')
if not os.path.isfile(exe_path): exe_path = which('NLLoc', parameter)
if exe_path is None:
raise NLLocError('NonLinLoc executable not found; check your ' raise NLLocError('NonLinLoc executable not found; check your '
'environment variables') 'environment variables')
+118 -183
View File
@@ -9,21 +9,21 @@ function conglomerate utils.
:author: MAGS2 EP3 working group / Ludger Kueperkoch :author: MAGS2 EP3 working group / Ludger Kueperkoch
""" """
import copy import copy
import traceback
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
from obspy import Trace import traceback
from obspy.taup import TauPyModel from obspy.taup import TauPyModel
from pylot.core.pick.charfuns import CharacteristicFunction from pylot.core.pick.charfuns import CharacteristicFunction
from pylot.core.pick.charfuns import HOScf, AICcf, ARZcf, ARHcf, AR3Ccf from pylot.core.pick.charfuns import HOScf, AICcf, ARZcf, ARHcf, AR3Ccf
from pylot.core.pick.picker import AICPicker, PragPicker from pylot.core.pick.picker import AICPicker, PragPicker
from pylot.core.pick.utils import checksignallength, checkZ4S, earllatepicker, \ from pylot.core.pick.utils import checksignallength, checkZ4S, earllatepicker, \
getSNR, fmpicker, checkPonsets, wadaticheck, get_quality_class, PickingFailedException, MissingTraceException getSNR, fmpicker, checkPonsets, wadaticheck, get_pickparams, get_quality_class
from pylot.core.util.utils import getPatternLine, gen_Pool, \ from pylot.core.util.utils import getPatternLine, gen_Pool,\
get_bool, identifyPhaseID, get_none, correct_iplot get_Bool, identifyPhaseID, get_None, correct_iplot
from obspy.taup import TauPyModel
from obspy import Trace
def autopickevent(data, param, iplot=0, fig_dict=None, fig_dict_wadatijack=None, ncores=0, metadata=None, origin=None): def autopickevent(data, param, iplot=0, fig_dict=None, fig_dict_wadatijack=None, ncores=0, metadata=None, origin=None):
""" """
@@ -182,25 +182,25 @@ class PickingResults(dict):
# TODO What are those? # TODO What are those?
self.w0 = None self.w0 = None
self.fc = None self.fc = None
self.Ao = None # Wood-Anderson peak-to-peak amplitude self.Ao = None # Wood-Anderson peak-to-peak amplitude
# Station information # Station information
self.network = None self.network = None
self.channel = None self.channel = None
# pick information # pick information
self.picker = 'auto' # type of pick self.picker = 'auto' # type of pick
self.marked = [] self.marked = []
# pick results # pick results
self.epp = None # earliest possible pick self.epp = None # earliest possible pick
self.mpp = None # most likely onset self.mpp = None # most likely onset
self.lpp = None # latest possible pick self.lpp = None # latest possible pick
self.fm = 'N' # first motion polarity, can be set to 'U' (Up) or 'D' (Down) self.fm = 'N' # first motion polarity, can be set to 'U' (Up) or 'D' (Down)
self.snr = None # signal-to-noise ratio of onset self.snr = None # signal-to-noise ratio of onset
self.snrdb = None # signal-to-noise ratio of onset [dB] self.snrdb = None # signal-to-noise ratio of onset [dB]
self.spe = None # symmetrized picking error self.spe = None # symmetrized picking error
self.weight = 4 # weight of onset self.weight = 4 # weight of onset
# to correctly provide dot access to dictionary attributes, all attribute access of the class is forwarded to the # to correctly provide dot access to dictionary attributes, all attribute access of the class is forwarded to the
# dictionary # dictionary
@@ -232,6 +232,20 @@ class PickingContainer:
self.Sflag = 0 self.Sflag = 0
class MissingTraceException(ValueError):
"""
Used to indicate missing traces in a obspy.core.stream.Stream object
"""
pass
class PickingFailedException(Exception):
"""
Raised when picking fails due to missing values etc.
"""
pass
class AutopickStation(object): class AutopickStation(object):
def __init__(self, wfstream, pickparam, verbose, iplot=0, fig_dict=None, metadata=None, origin=None): def __init__(self, wfstream, pickparam, verbose, iplot=0, fig_dict=None, metadata=None, origin=None):
@@ -258,14 +272,10 @@ class AutopickStation(object):
self.pickparams = copy.deepcopy(pickparam) self.pickparams = copy.deepcopy(pickparam)
self.verbose = verbose self.verbose = verbose
self.iplot = correct_iplot(iplot) self.iplot = correct_iplot(iplot)
self.fig_dict = get_none(fig_dict) self.fig_dict = get_None(fig_dict)
self.metadata = metadata self.metadata = metadata
self.origin = origin self.origin = origin
# initialize TauPy pick estimates
self.estFirstP = None
self.estFirstS = None
# initialize picking results # initialize picking results
self.p_results = PickingResults() self.p_results = PickingResults()
self.s_results = PickingResults() self.s_results = PickingResults()
@@ -325,10 +335,9 @@ class AutopickStation(object):
""" """
waveform_data = {} waveform_data = {}
for key in self.channelorder: for key in self.channelorder:
waveform_data[key] = self.wfstream.select(component=key) # try ZNE first waveform_data[key] = self.wfstream.select(component=key) # try ZNE first
if len(waveform_data[key]) == 0: if len(waveform_data[key]) == 0:
waveform_data[key] = self.wfstream.select( waveform_data[key] = self.wfstream.select(component=str(self.channelorder[key])) # use 123 as second option
component=str(self.channelorder[key])) # use 123 as second option
return waveform_data['Z'], waveform_data['N'], waveform_data['E'] return waveform_data['Z'], waveform_data['N'], waveform_data['E']
def get_traces_from_streams(self): def get_traces_from_streams(self):
@@ -419,7 +428,7 @@ class AutopickStation(object):
if station_coords is None: if station_coords is None:
exit_taupy() exit_taupy()
raise AttributeError('Warning: Could not find station in metadata') raise AttributeError('Warning: Could not find station in metadata')
# TODO: raise when metadata.get_coordinates returns None # TODO raise when metadata.get_coordinates returns None
source_origin = origin[0] source_origin = origin[0]
model = TauPyModel(taup_model) model = TauPyModel(taup_model)
taup_phases = self.pickparams['taup_phases'] taup_phases = self.pickparams['taup_phases']
@@ -447,29 +456,31 @@ class AutopickStation(object):
for arr in arrivals: for arr in arrivals:
phases[identifyPhaseID(arr.phase.name)].append(arr) phases[identifyPhaseID(arr.phase.name)].append(arr)
# get first P and S onsets from arrivals list # get first P and S onsets from arrivals list
arrival_time_p = 0 estFirstP = 0
arrival_time_s = 0 estFirstS = 0
if len(phases['P']) > 0: if len(phases['P']) > 0:
arrP, arrival_time_p = min([(arr, arr.time) for arr in phases['P']], key=lambda t: t[1]) arrP, estFirstP = min([(arr, arr.time) for arr in phases['P']], key=lambda t: t[1])
if len(phases['S']) > 0: if len(phases['S']) > 0:
arrS, arrival_time_s = min([(arr, arr.time) for arr in phases['S']], key=lambda t: t[1]) arrS, estFirstS = min([(arr, arr.time) for arr in phases['S']], key=lambda t: t[1])
print('autopick: estimated first arrivals for P: {} s, S:{} s after event' print('autopick: estimated first arrivals for P: {} s, S:{} s after event'
' origin time using TauPy'.format(arrival_time_p, arrival_time_s)) ' origin time using TauPy'.format(estFirstP, estFirstS))
return arrival_time_p, arrival_time_s return estFirstP, estFirstS
def exit_taupy(): def exit_taupy():
"""If taupy failed to calculate theoretical starttimes, picking continues. """If taupy failed to calculate theoretical starttimes, picking continues.
For this a clean exit is required, since the P starttime is no longer relative to the theoretic onset but For this a clean exit is required, since the P starttime is no longer relative to the theoretic onset but
to the vertical trace starttime, eg. it can't be < 0.""" to the vertical trace starttime, eg. it can't be < 0."""
# TODO here the pickparams is modified, instead of a copy
if self.pickparams["pstart"] < 0: if self.pickparams["pstart"] < 0:
# TODO here the pickparams is modified, instead of a copy
self.pickparams["pstart"] = 0 self.pickparams["pstart"] = 0
if self.pickparams["sstart"] < 0:
self.pickparams["sstart"] = 0
if get_bool(self.pickparams["use_taup"]) is False: if self.pickparams["use_taup"] is False or not self.origin or not self.metadata:
# correct user mistake where a relative cuttime is selected (pstart < 0) but use of taupy is disabled/ has # correct user mistake where a relative cuttime is selected (pstart < 0) but use of taupy is disabled/ has
# not the required parameters # not the required parameters
if not self.origin:
print('Requested use_taup but no origin given. Exit taupy.')
if not self.metadata:
print('Requested use_taup but no metadata given. Exit taupy.')
exit_taupy() exit_taupy()
return return
@@ -481,34 +492,16 @@ class AutopickStation(object):
raise AttributeError('No source origins given!') raise AttributeError('No source origins given!')
arrivals = create_arrivals(self.metadata, self.origin, self.pickparams["taup_model"]) arrivals = create_arrivals(self.metadata, self.origin, self.pickparams["taup_model"])
arrival_P, arrival_S = first_PS_onsets(arrivals) estFirstP, estFirstS = first_PS_onsets(arrivals)
self.estFirstP = (self.origin[0].time + arrival_P) - self.ztrace.stats.starttime
# modifiy pstart and pstop relative to estimated first P arrival (relative to station time axis) # modifiy pstart and pstop relative to estimated first P arrival (relative to station time axis)
self.pickparams["pstart"] += self.estFirstP self.pickparams["pstart"] += (self.origin[0].time + estFirstP) - self.ztrace.stats.starttime
self.pickparams["pstop"] += self.estFirstP self.pickparams["pstop"] += (self.origin[0].time + estFirstP) - self.ztrace.stats.starttime
print('autopick: CF calculation times respectively:' print('autopick: CF calculation times respectively:'
' pstart: {} s, pstop: {} s'.format(self.pickparams["pstart"], self.pickparams["pstop"])) ' pstart: {} s, pstop: {} s'.format(self.pickparams["pstart"], self.pickparams["pstop"]))
# make sure pstart and pstop are inside the starttime/endtime of vertical trace # make sure pstart and pstop are inside the starttime/endtime of vertical trace
self.pickparams["pstart"] = max(self.pickparams["pstart"], 0) self.pickparams["pstart"] = max(self.pickparams["pstart"], 0)
self.pickparams["pstop"] = min(self.pickparams["pstop"], len(self.ztrace) * self.ztrace.stats.delta) self.pickparams["pstop"] = min(self.pickparams["pstop"], len(self.ztrace) * self.ztrace.stats.delta)
if self.horizontal_traces_exist():
# for the two horizontal components take earliest and latest time to make sure that the s onset is not clipped
# if start and endtime of horizontal traces differ, the s windowsize will automatically increase
trace_s_start = min([self.etrace.stats.starttime, self.ntrace.stats.starttime])
self.estFirstS = (self.origin[0].time + arrival_S) - trace_s_start
# modifiy sstart and sstop relative to estimated first S arrival (relative to station time axis)
self.pickparams["sstart"] += self.estFirstS
self.pickparams["sstop"] += self.estFirstS
print('autopick: CF calculation times respectively:'
' sstart: {} s, sstop: {} s'.format(self.pickparams["sstart"], self.pickparams["sstop"]))
# make sure pstart and pstop are inside the starttime/endtime of horizontal traces
self.pickparams["sstart"] = max(self.pickparams["sstart"], 0)
self.pickparams["sstop"] = min(self.pickparams["sstop"], len(self.ntrace) * self.ntrace.stats.delta,
len(self.etrace) * self.etrace.stats.delta)
def autopickstation(self): def autopickstation(self):
""" """
Main function of autopickstation, which calculates P and S picks and returns them in a dictionary. Main function of autopickstation, which calculates P and S picks and returns them in a dictionary.
@@ -518,17 +511,6 @@ class AutopickStation(object):
station's value is the station name on which the picks were calculated. station's value is the station name on which the picks were calculated.
:rtype: dict :rtype: dict
""" """
if get_bool(self.pickparams['use_taup']) is True and self.origin is not None:
try:
# modify pstart, pstop, sstart, sstop to be around theoretical onset if taupy should be used,
# else do nothing
self.modify_starttimes_taupy()
except AttributeError as ae:
print(ae)
except MissingTraceException as mte:
print(mte)
try: try:
self.pick_p_phase() self.pick_p_phase()
except MissingTraceException as mte: except MissingTraceException as mte:
@@ -536,19 +518,17 @@ class AutopickStation(object):
except PickingFailedException as pfe: except PickingFailedException as pfe:
print(pfe) print(pfe)
if self.horizontal_traces_exist(): if self.horizontal_traces_exist() and self.p_results.weight is not None and self.p_results.weight < 4:
if (self.p_results.weight is not None and self.p_results.weight < 4) or \ try:
get_bool(self.pickparams.get('use_taup')): self.pick_s_phase()
try: except MissingTraceException as mte:
self.pick_s_phase() print(mte)
except MissingTraceException as mte: except PickingFailedException as pfe:
print(mte) print(pfe)
except PickingFailedException as pfe:
print(pfe)
self.plot_pick_results() self.plot_pick_results()
self.finish_picking() self.finish_picking()
return [{'P': self.p_results, 'S': self.s_results}, self.ztrace.stats.station] return [{'P': self.p_results, 'S':self.s_results}, self.ztrace.stats.station]
def finish_picking(self): def finish_picking(self):
@@ -597,7 +577,7 @@ class AutopickStation(object):
self.s_results.channel = self.etrace.stats.channel self.s_results.channel = self.etrace.stats.channel
self.s_results.network = self.etrace.stats.network self.s_results.network = self.etrace.stats.network
self.s_results.fm = None # override default value 'N' self.s_results.fm = None # override default value 'N'
def plot_pick_results(self): def plot_pick_results(self):
if self.iplot > 0: if self.iplot > 0:
@@ -612,20 +592,12 @@ class AutopickStation(object):
plt_flag = 0 plt_flag = 0
fig._tight = True fig._tight = True
ax1 = fig.add_subplot(311) ax1 = fig.add_subplot(311)
tdata = np.linspace(start=0, stop=self.ztrace.stats.endtime - self.ztrace.stats.starttime, tdata = np.linspace(start=0, stop=self.ztrace.stats.endtime-self.ztrace.stats.starttime, num=self.ztrace.stats.npts)
num=self.ztrace.stats.npts)
# plot tapered trace filtered with bpz2 filter settings # plot tapered trace filtered with bpz2 filter settings
ax1.plot(tdata, self.tr_filt_z_bpz2.data / max(self.tr_filt_z_bpz2.data), color=linecolor, linewidth=0.7, ax1.plot(tdata, self.tr_filt_z_bpz2.data/max(self.tr_filt_z_bpz2.data), color=linecolor, linewidth=0.7, label='Data')
label='Data')
# plot pickwindows for P
pstart, pstop = self.pickparams['pstart'], self.pickparams['pstop']
if pstart is not None and pstop is not None:
ax1.axvspan(pstart, pstop, color='r', alpha=0.1, zorder=0, label='P window')
if self.estFirstP is not None:
ax1.axvline(self.estFirstP, ls='dashed', color='r', alpha=0.4, label='TauPy estimate')
if self.p_results.weight < 4: if self.p_results.weight < 4:
# plot CF of initial onset (HOScf or ARZcf) # plot CF of initial onset (HOScf or ARZcf)
ax1.plot(self.cf1.getTimeArray(), self.cf1.getCF() / max(self.cf1.getCF()), 'b', label='CF1') ax1.plot(self.cf1.getTimeArray(), self.cf1.getCF()/max(self.cf1.getCF()), 'b', label='CF1')
if self.p_data.p_aic_plot_flag == 1: if self.p_data.p_aic_plot_flag == 1:
aicpick = self.p_data.aicpick aicpick = self.p_data.aicpick
refPpick = self.p_data.refPpick refPpick = self.p_data.refPpick
@@ -660,44 +632,38 @@ class AutopickStation(object):
ax1.set_ylim([-1.5, 1.5]) ax1.set_ylim([-1.5, 1.5])
ax1.set_ylabel('Normalized Counts') ax1.set_ylabel('Normalized Counts')
if self.horizontal_traces_exist():# and self.s_data.Sflag == 1: if self.horizontal_traces_exist() and self.s_data.Sflag == 1:
# plot E trace # plot E trace
ax2 = fig.add_subplot(3, 1, 2, sharex=ax1) ax2 = fig.add_subplot(3, 1, 2, sharex=ax1)
th1data = np.linspace(0, self.etrace.stats.endtime - self.etrace.stats.starttime, th1data = np.linspace(0, self.etrace.stats.endtime-self.etrace.stats.starttime, self.etrace.stats.npts)
self.etrace.stats.npts)
# plot filtered and tapered waveform # plot filtered and tapered waveform
ax2.plot(th1data, self.etrace.data / max(self.etrace.data), color=linecolor, linewidth=0.7, ax2.plot(th1data, self.etrace.data / max(self.etrace.data), color=linecolor, linewidth=0.7, label='Data')
label='Data')
if self.p_results.weight < 4: if self.p_results.weight < 4:
# plot initial CF (ARHcf or AR3Ccf) # plot initial CF (ARHcf or AR3Ccf)
ax2.plot(self.arhcf1.getTimeArray(), self.arhcf1.getCF() / max(self.arhcf1.getCF()), 'b', ax2.plot(self.arhcf1.getTimeArray(), self.arhcf1.getCF() / max(self.arhcf1.getCF()), 'b', label='CF1')
label='CF1')
if self.s_data.aicSflag == 1 and self.s_results.weight <= 4: if self.s_data.aicSflag == 1 and self.s_results.weight <= 4:
aicarhpick = self.aicarhpick aicarhpick = self.aicarhpick
refSpick = self.refSpick refSpick = self.refSpick
# plot second cf, used for determing precise onset (ARHcf or AR3Ccf) # plot second cf, used for determing precise onset (ARHcf or AR3Ccf)
ax2.plot(self.arhcf2.getTimeArray(), self.arhcf2.getCF() / max(self.arhcf2.getCF()), 'm', ax2.plot(self.arhcf2.getTimeArray(), self.arhcf2.getCF() / max(self.arhcf2.getCF()), 'm', label='CF2')
label='CF2')
# plot preliminary onset time, calculated from CF1 # plot preliminary onset time, calculated from CF1
ax2.plot([aicarhpick.getpick(), aicarhpick.getpick()], [-1, 1], 'g', label='Initial S Onset') ax2.plot([aicarhpick.getpick(), aicarhpick.getpick()], [-1, 1], 'g', label='Initial S Onset')
ax2.plot([aicarhpick.getpick() - 0.5, aicarhpick.getpick() + 0.5], [1, 1], 'g') ax2.plot([aicarhpick.getpick() - 0.5, aicarhpick.getpick() + 0.5], [1, 1], 'g')
ax2.plot([aicarhpick.getpick() - 0.5, aicarhpick.getpick() + 0.5], [-1, -1], 'g') ax2.plot([aicarhpick.getpick() - 0.5, aicarhpick.getpick() + 0.5], [-1, -1], 'g')
# plot precise onset time, calculated from CF2 # plot precise onset time, calculated from CF2
ax2.plot([refSpick.getpick(), refSpick.getpick()], [-1.3, 1.3], 'g', linewidth=2, ax2.plot([refSpick.getpick(), refSpick.getpick()], [-1.3, 1.3], 'g', linewidth=2, label='Final S Pick')
label='Final S Pick')
ax2.plot([refSpick.getpick() - 0.5, refSpick.getpick() + 0.5], [1.3, 1.3], 'g', linewidth=2) ax2.plot([refSpick.getpick() - 0.5, refSpick.getpick() + 0.5], [1.3, 1.3], 'g', linewidth=2)
ax2.plot([refSpick.getpick() - 0.5, refSpick.getpick() + 0.5], [-1.3, -1.3], 'g', linewidth=2) ax2.plot([refSpick.getpick() - 0.5, refSpick.getpick() + 0.5], [-1.3, -1.3], 'g', linewidth=2)
ax2.plot([self.s_results.lpp, self.s_results.lpp], [-1.1, 1.1], 'g--', label='lpp') ax2.plot([self.s_results.lpp, self.s_results.lpp], [-1.1, 1.1], 'g--', label='lpp')
ax2.plot([self.s_results.epp, self.s_results.epp], [-1.1, 1.1], 'g--', label='epp') ax2.plot([self.s_results.epp, self.s_results.epp], [-1.1, 1.1], 'g--', label='epp')
title = '{channel}, S weight={sweight}, SNR={snr:7.2}, SNR[dB]={snrdb:7.2}' title = '{channel}, S weight={sweight}, SNR={snr:7.2}, SNR[dB]={snrdb:7.2}'
ax2.set_title(title.format(channel=str(self.etrace.stats.channel), ax2.set_title(title.format(channel=self.etrace.stats.channel,
sweight=str(self.s_results.weight), sweight=self.s_results.weight,
snr=str(self.s_results.snr), snr=self.s_results.snr,
snrdb=str(self.s_results.snrdb))) snrdb=self.s_results.snrdb))
else: else:
title = '{channel}, S weight={sweight}, SNR=None, SNR[dB]=None' title = '{channel}, S weight={sweight}, SNR=None, SNR[dB]=None'
ax2.set_title(title.format(channel=str(self.etrace.stats.channel), ax2.set_title(title.format(channel=self.etrace.stats.channel, sweight=self.s_results.weight))
sweight=str(self.s_results.weight)))
ax2.legend(loc=1) ax2.legend(loc=1)
ax2.set_yticks([]) ax2.set_yticks([])
ax2.set_ylim([-1.5, 1.5]) ax2.set_ylim([-1.5, 1.5])
@@ -705,19 +671,15 @@ class AutopickStation(object):
# plot N trace # plot N trace
ax3 = fig.add_subplot(3, 1, 3, sharex=ax1) ax3 = fig.add_subplot(3, 1, 3, sharex=ax1)
th2data = np.linspace(0, self.ntrace.stats.endtime - self.ntrace.stats.starttime, th2data= np.linspace(0, self.ntrace.stats.endtime-self.ntrace.stats.starttime, self.ntrace.stats.npts)
self.ntrace.stats.npts)
# plot trace # plot trace
ax3.plot(th2data, self.ntrace.data / max(self.ntrace.data), color=linecolor, linewidth=0.7, ax3.plot(th2data, self.ntrace.data / max(self.ntrace.data), color=linecolor, linewidth=0.7, label='Data')
label='Data')
if self.p_results.weight < 4: if self.p_results.weight < 4:
p22, = ax3.plot(self.arhcf1.getTimeArray(), self.arhcf1.getCF() / max(self.arhcf1.getCF()), 'b', p22, = ax3.plot(self.arhcf1.getTimeArray(), self.arhcf1.getCF() / max(self.arhcf1.getCF()), 'b', label='CF1')
label='CF1')
if self.s_data.aicSflag == 1: if self.s_data.aicSflag == 1:
aicarhpick = self.aicarhpick aicarhpick = self.aicarhpick
refSpick = self.refSpick refSpick = self.refSpick
ax3.plot(self.arhcf2.getTimeArray(), self.arhcf2.getCF() / max(self.arhcf2.getCF()), 'm', ax3.plot(self.arhcf2.getTimeArray(), self.arhcf2.getCF() / max(self.arhcf2.getCF()), 'm', label='CF2')
label='CF2')
ax3.plot([aicarhpick.getpick(), aicarhpick.getpick()], [-1, 1], 'g', label='Initial S Onset') ax3.plot([aicarhpick.getpick(), aicarhpick.getpick()], [-1, 1], 'g', label='Initial S Onset')
ax3.plot([aicarhpick.getpick() - 0.5, aicarhpick.getpick() + 0.5], [1, 1], 'g') ax3.plot([aicarhpick.getpick() - 0.5, aicarhpick.getpick() + 0.5], [1, 1], 'g')
ax3.plot([aicarhpick.getpick() - 0.5, aicarhpick.getpick() + 0.5], [-1, -1], 'g') ax3.plot([aicarhpick.getpick() - 0.5, aicarhpick.getpick() + 0.5], [-1, -1], 'g')
@@ -727,15 +689,6 @@ class AutopickStation(object):
ax3.plot([refSpick.getpick() - 0.5, refSpick.getpick() + 0.5], [-1.3, -1.3], 'g', linewidth=2) ax3.plot([refSpick.getpick() - 0.5, refSpick.getpick() + 0.5], [-1.3, -1.3], 'g', linewidth=2)
ax3.plot([self.s_results.lpp, self.s_results.lpp], [-1.1, 1.1], 'g--', label='lpp') ax3.plot([self.s_results.lpp, self.s_results.lpp], [-1.1, 1.1], 'g--', label='lpp')
ax3.plot([self.s_results.epp, self.s_results.epp], [-1.1, 1.1], 'g--', label='epp') ax3.plot([self.s_results.epp, self.s_results.epp], [-1.1, 1.1], 'g--', label='epp')
# plot pickwindows for S
sstart, sstop = self.pickparams['sstart'], self.pickparams['sstop']
if sstart is not None and sstop is not None:
for axis in [ax2, ax3]:
axis.axvspan(sstart, sstop, color='b', alpha=0.1, zorder=0, label='S window')
if self.estFirstS is not None:
axis.axvline(self.estFirstS, ls='dashed', color='b', alpha=0.4, label='TauPy estimate')
ax3.legend(loc=1) ax3.legend(loc=1)
ax3.set_yticks([]) ax3.set_yticks([])
ax3.set_ylim([-1.5, 1.5]) ax3.set_ylim([-1.5, 1.5])
@@ -767,8 +720,7 @@ class AutopickStation(object):
if aicpick.getpick() is None: if aicpick.getpick() is None:
msg = "Bad initial (AIC) P-pick, skipping this onset!\nAIC-SNR={0}, AIC-Slope={1}counts/s\n " \ msg = "Bad initial (AIC) P-pick, skipping this onset!\nAIC-SNR={0}, AIC-Slope={1}counts/s\n " \
"(min. AIC-SNR={2}, min. AIC-Slope={3}counts/s)" "(min. AIC-SNR={2}, min. AIC-Slope={3}counts/s)"
msg = msg.format(aicpick.getSNR(), aicpick.getSlope(), self.pickparams["minAICPSNR"], msg = msg.format(aicpick.getSNR(), aicpick.getSlope(), self.pickparams["minAICPSNR"], self.pickparams["minAICPslope"])
self.pickparams["minAICPslope"])
self.vprint(msg) self.vprint(msg)
return 0 return 0
# Quality check initial pick with minimum signal length # Quality check initial pick with minimum signal length
@@ -778,16 +730,14 @@ class AutopickStation(object):
if len(self.nstream) == 0 or len(self.estream) == 0: if len(self.nstream) == 0 or len(self.estream) == 0:
msg = 'One or more horizontal component(s) missing!\n' \ msg = 'One or more horizontal component(s) missing!\n' \
'Signal length only checked on vertical component!\n' \ 'Signal length only checked on vertical component!\n' \
'Decreasing minsiglengh from {0} to {1}' \ 'Decreasing minsiglengh from {0} to {1}'\
.format(minsiglength, minsiglength / 2) .format(minsiglength, minsiglength / 2)
self.vprint(msg) self.vprint(msg)
minsiglength = minsiglength / 2 minsiglength = minsiglength / 2
else: else:
# filter, taper other traces as well since signal length is compared on all traces # filter, taper other traces as well since signal length is compared on all traces
trH1_filt, _ = self.prepare_wfstream(self.estream, freqmin=self.pickparams["bph1"][0], trH1_filt, _ = self.prepare_wfstream(self.estream, freqmin=self.pickparams["bph1"][0], freqmax=self.pickparams["bph1"][1])
freqmax=self.pickparams["bph1"][1]) trH2_filt, _ = self.prepare_wfstream(self.nstream, freqmin=self.pickparams["bph1"][0], freqmax=self.pickparams["bph1"][1])
trH2_filt, _ = self.prepare_wfstream(self.nstream, freqmin=self.pickparams["bph1"][0],
freqmax=self.pickparams["bph1"][1])
zne += trH1_filt zne += trH1_filt
zne += trH2_filt zne += trH2_filt
minsiglength = minsiglength minsiglength = minsiglength
@@ -834,6 +784,15 @@ class AutopickStation(object):
# save filtered trace in instance for later plotting # save filtered trace in instance for later plotting
self.tr_filt_z_bpz2 = tr_filt self.tr_filt_z_bpz2 = tr_filt
if get_Bool(self.pickparams['use_taup']) is True and self.origin is not None:
try:
# modify pstart, pstop to be around theoretical onset if taupy should be used, else does nothing
self.modify_starttimes_taupy()
except AttributeError as ae:
print(ae)
except MissingTraceException as mte:
print(mte)
Lc = self.pickparams['pstop'] - self.pickparams['pstart'] Lc = self.pickparams['pstop'] - self.pickparams['pstart']
Lwf = self.ztrace.stats.endtime - self.ztrace.stats.starttime Lwf = self.ztrace.stats.endtime - self.ztrace.stats.starttime
@@ -858,34 +817,24 @@ class AutopickStation(object):
self.cf1 = None self.cf1 = None
assert isinstance(self.cf1, CharacteristicFunction), 'cf1 is not set correctly: maybe the algorithm name ({})' \ assert isinstance(self.cf1, CharacteristicFunction), 'cf1 is not set correctly: maybe the algorithm name ({})' \
' is corrupted'.format(self.pickparams["algoP"]) ' is corrupted'.format(self.pickparams["algoP"])
# get the original waveform stream from first CF class cut to identical length as CF for plotting
cut_ogstream = self.cf1.getDataArray(self.cf1.getCut())
# MP: Rename to cf_stream for further use of z_copy and to prevent chaos when z_copy suddenly becomes a cf
# stream and later again a waveform stream
cf_stream = z_copy.copy()
cf_stream[0].data = self.cf1.getCF()
# calculate AIC cf from first cf (either HOS or ARZ) # calculate AIC cf from first cf (either HOS or ARZ)
aiccf = AICcf(cf_stream, cuttimes) z_copy[0].data = self.cf1.getCF()
aiccf = AICcf(z_copy, cuttimes)
# get preliminary onset time from AIC-CF # get preliminary onset time from AIC-CF
self.set_current_figure('aicFig') self.set_current_figure('aicFig')
aicpick = AICPicker(aiccf, self.pickparams["tsnrz"], self.pickparams["pickwinP"], self.iplot, aicpick = AICPicker(aiccf, self.pickparams["tsnrz"], self.pickparams["pickwinP"], self.iplot,
Tsmooth=self.pickparams["aictsmooth"], fig=self.current_figure, Tsmooth=self.pickparams["aictsmooth"], fig=self.current_figure, linecolor=self.current_linecolor)
linecolor=self.current_linecolor, ogstream=cut_ogstream)
# save aicpick for plotting later # save aicpick for plotting later
self.p_data.aicpick = aicpick self.p_data.aicpick = aicpick
# add pstart and pstop to aic plot # add pstart and pstop to aic plot
if self.current_figure: if self.current_figure:
# TODO remove plotting from picking, make own plot function # TODO remove plotting from picking, make own plot function
for ax in self.current_figure.axes: for ax in self.current_figure.axes:
ax.vlines(self.pickparams["pstart"], ax.get_ylim()[0], ax.get_ylim()[1], color='c', linestyles='dashed', ax.vlines(self.pickparams["pstart"], ax.get_ylim()[0], ax.get_ylim()[1], color='c', linestyles='dashed', label='P start')
label='P start') ax.vlines(self.pickparams["pstop"], ax.get_ylim()[0], ax.get_ylim()[1], color='c', linestyles='dashed', label='P stop')
ax.vlines(self.pickparams["pstop"], ax.get_ylim()[0], ax.get_ylim()[1], color='c', linestyles='dashed',
label='P stop')
ax.legend(loc=1) ax.legend(loc=1)
Pflag = self._pick_p_quality_control(aicpick, cf_stream, tr_filt) Pflag = self._pick_p_quality_control(aicpick, z_copy, tr_filt)
# go on with processing if AIC onset passes quality control # go on with processing if AIC onset passes quality control
slope = aicpick.getSlope() slope = aicpick.getSlope()
if not slope: slope = 0 if not slope: slope = 0
@@ -896,8 +845,7 @@ class AutopickStation(object):
error_msg = 'AIC P onset slope to small: got {}, min {}'.format(slope, self.pickparams["minAICPslope"]) error_msg = 'AIC P onset slope to small: got {}, min {}'.format(slope, self.pickparams["minAICPslope"])
raise PickingFailedException(error_msg) raise PickingFailedException(error_msg)
if aicpick.getSNR() < self.pickparams["minAICPSNR"]: if aicpick.getSNR() < self.pickparams["minAICPSNR"]:
error_msg = 'AIC P onset SNR to small: got {}, min {}'.format(aicpick.getSNR(), error_msg = 'AIC P onset SNR to small: got {}, min {}'.format(aicpick.getSNR(), self.pickparams["minAICPSNR"])
self.pickparams["minAICPSNR"])
raise PickingFailedException(error_msg) raise PickingFailedException(error_msg)
self.p_data.p_aic_plot_flag = 1 self.p_data.p_aic_plot_flag = 1
@@ -905,8 +853,7 @@ class AutopickStation(object):
'autopickstation: re-filtering vertical trace...'.format(aicpick.getSlope(), aicpick.getSNR()) 'autopickstation: re-filtering vertical trace...'.format(aicpick.getSlope(), aicpick.getSNR())
self.vprint(msg) self.vprint(msg)
# refilter waveform with larger bandpass # refilter waveform with larger bandpass
tr_filt, z_copy = self.prepare_wfstream(self.zstream, freqmin=self.pickparams["bpz2"][0], tr_filt, z_copy = self.prepare_wfstream(self.zstream, freqmin=self.pickparams["bpz2"][0], freqmax=self.pickparams["bpz2"][1])
freqmax=self.pickparams["bpz2"][1])
# save filtered trace in instance for later plotting # save filtered trace in instance for later plotting
self.tr_filt_z_bpz2 = tr_filt self.tr_filt_z_bpz2 = tr_filt
# determine new times around initial onset # determine new times around initial onset
@@ -918,29 +865,25 @@ class AutopickStation(object):
else: else:
self.cf2 = None self.cf2 = None
assert isinstance(self.cf2, CharacteristicFunction), 'cf2 is not set correctly: maybe the algorithm name () is ' \ assert isinstance(self.cf2, CharacteristicFunction), 'cf2 is not set correctly: maybe the algorithm name () is ' \
'corrupted'.format(self.pickparams["algoP"]) 'corrupted'.format(self.pickparams["algoP"])
self.set_current_figure('refPpick') self.set_current_figure('refPpick')
# get refined onset time from CF2 # get refined onset time from CF2
refPpick = PragPicker(self.cf2, self.pickparams["tsnrz"], self.pickparams["pickwinP"], self.iplot, refPpick = PragPicker(self.cf2, self.pickparams["tsnrz"], self.pickparams["pickwinP"], self.iplot, self.pickparams["ausP"],
self.pickparams["ausP"], self.pickparams["tsmoothP"], aicpick.getpick(), self.current_figure, self.current_linecolor)
self.pickparams["tsmoothP"], aicpick.getpick(), self.current_figure,
self.current_linecolor, ogstream=cut_ogstream)
# save PragPicker result for plotting # save PragPicker result for plotting
self.p_data.refPpick = refPpick self.p_data.refPpick = refPpick
self.p_results.mpp = refPpick.getpick() self.p_results.mpp = refPpick.getpick()
if self.p_results.mpp is None: if self.p_results.mpp is None:
msg = 'Bad initial (AIC) P-pick, skipping this onset!\n AIC-SNR={}, AIC-Slope={}counts/s\n' \ msg = 'Bad initial (AIC) P-pick, skipping this onset!\n AIC-SNR={}, AIC-Slope={}counts/s\n' \
'(min. AIC-SNR={}, min. AIC-Slope={}counts/s)' '(min. AIC-SNR={}, min. AIC-Slope={}counts/s)'
msg.format(aicpick.getSNR(), aicpick.getSlope(), self.pickparams["minAICPSNR"], msg.format(aicpick.getSNR(), aicpick.getSlope(), self.pickparams["minAICPSNR"], self.pickparams["minAICPslope"])
self.pickparams["minAICPslope"])
self.vprint(msg) self.vprint(msg)
self.s_data.Sflag = 0 self.s_data.Sflag = 0
raise PickingFailedException(msg) raise PickingFailedException(msg)
# quality assessment, get earliest/latest pick and symmetrized uncertainty # quality assessment, get earliest/latest pick and symmetrized uncertainty
# todo quality assessment in own function #todo quality assessment in own function
self.set_current_figure('el_Ppick') self.set_current_figure('el_Ppick')
elpicker_results = earllatepicker(z_copy, self.pickparams["nfacP"], self.pickparams["tsnrz"], elpicker_results = earllatepicker(z_copy, self.pickparams["nfacP"], self.pickparams["tsnrz"], self.p_results.mpp,
self.p_results.mpp,
self.iplot, fig=self.current_figure, linecolor=self.current_linecolor) self.iplot, fig=self.current_figure, linecolor=self.current_linecolor)
self.p_results.epp, self.p_results.lpp, self.p_results.spe = elpicker_results self.p_results.epp, self.p_results.lpp, self.p_results.spe = elpicker_results
snr_results = getSNR(z_copy, self.pickparams["tsnrz"], self.p_results.mpp) snr_results = getSNR(z_copy, self.pickparams["tsnrz"], self.p_results.mpp)
@@ -948,11 +891,10 @@ class AutopickStation(object):
# weight P-onset using symmetric error # weight P-onset using symmetric error
self.p_results.weight = get_quality_class(self.p_results.spe, self.pickparams["timeerrorsP"]) self.p_results.weight = get_quality_class(self.p_results.spe, self.pickparams["timeerrorsP"])
if self.p_results.weight <= self.pickparams["minfmweight"] and self.p_results.snr >= self.pickparams[ if self.p_results.weight <= self.pickparams["minfmweight"] and self.p_results.snr >= self.pickparams["minFMSNR"]:
"minFMSNR"]: # if SNR is low enough, try to determine first motion of onset
# if SNR is high enough, try to determine first motion of onset
self.set_current_figure('fm_picker') self.set_current_figure('fm_picker')
self.p_results.fm = fmpicker(self.zstream.copy(), z_copy, self.pickparams["fmpickwin"], self.p_results.mpp, self.p_results.fm = fmpicker(self.zstream, z_copy, self.pickparams["fmpickwin"], self.p_results.mpp,
self.iplot, self.current_figure, self.current_linecolor) self.iplot, self.current_figure, self.current_linecolor)
msg = "autopickstation: P-weight: {}, SNR: {}, SNR[dB]: {}, Polarity: {}" msg = "autopickstation: P-weight: {}, SNR: {}, SNR[dB]: {}, Polarity: {}"
msg = msg.format(self.p_results.weight, self.p_results.snr, self.p_results.snrdb, self.p_results.fm) msg = msg.format(self.p_results.weight, self.p_results.snr, self.p_results.snrdb, self.p_results.fm)
@@ -1022,7 +964,7 @@ class AutopickStation(object):
trH1_filt, _ = self.prepare_wfstream(self.zstream, filter_freq_min, filter_freq_max) trH1_filt, _ = self.prepare_wfstream(self.zstream, filter_freq_min, filter_freq_max)
trH2_filt, _ = self.prepare_wfstream(self.estream, filter_freq_min, filter_freq_max) trH2_filt, _ = self.prepare_wfstream(self.estream, filter_freq_min, filter_freq_max)
trH3_filt, _ = self.prepare_wfstream(self.nstream, filter_freq_min, filter_freq_max) trH3_filt, _ = self.prepare_wfstream(self.nstream, filter_freq_min, filter_freq_max)
h_copy = self.hdat.copy() h_copy =self. hdat.copy()
h_copy[0].data = trH1_filt.data h_copy[0].data = trH1_filt.data
h_copy[1].data = trH2_filt.data h_copy[1].data = trH2_filt.data
h_copy[2].data = trH3_filt.data h_copy[2].data = trH3_filt.data
@@ -1164,11 +1106,9 @@ class AutopickStation(object):
''.format(self.s_results.weight, self.s_results.snr, self.s_results.snrdb)) ''.format(self.s_results.weight, self.s_results.snr, self.s_results.snrdb))
def pick_s_phase(self): def pick_s_phase(self):
if get_bool(self.pickparams.get('use_taup')) is True:
cuttimesh = (self.pickparams.get('sstart'), self.pickparams.get('sstop')) # determine time window for calculating CF after P onset
else: cuttimesh = self._calculate_cuttimes(type='S', iteration=1)
# determine time window for calculating CF after P onset
cuttimesh = self._calculate_cuttimes(type='S', iteration=1)
# calculate autoregressive CF # calculate autoregressive CF
self.arhcf1 = self._calculate_autoregressive_cf_s_pick(cuttimesh) self.arhcf1 = self._calculate_autoregressive_cf_s_pick(cuttimesh)
@@ -1176,14 +1116,10 @@ class AutopickStation(object):
# calculate AIC cf # calculate AIC cf
haiccf = self._calculate_aic_cf_s_pick(cuttimesh) haiccf = self._calculate_aic_cf_s_pick(cuttimesh)
# get the original waveform stream cut to identical length as CF for plotting
ogstream = haiccf.getDataArray(haiccf.getCut())
# get preliminary onset time from AIC cf # get preliminary onset time from AIC cf
self.set_current_figure('aicARHfig') self.set_current_figure('aicARHfig')
aicarhpick = AICPicker(haiccf, self.pickparams["tsnrh"], self.pickparams["pickwinS"], self.iplot, aicarhpick = AICPicker(haiccf, self.pickparams["tsnrh"], self.pickparams["pickwinS"], self.iplot,
Tsmooth=self.pickparams["aictsmoothS"], fig=self.current_figure, Tsmooth=self.pickparams["aictsmoothS"], fig=self.current_figure, linecolor=self.current_linecolor)
linecolor=self.current_linecolor, ogstream=ogstream)
# save pick for later plotting # save pick for later plotting
self.aicarhpick = aicarhpick self.aicarhpick = aicarhpick
@@ -1194,10 +1130,8 @@ class AutopickStation(object):
# get refined onset time from CF2 # get refined onset time from CF2
self.set_current_figure('refSpick') self.set_current_figure('refSpick')
refSpick = PragPicker(arhcf2, self.pickparams["tsnrh"], self.pickparams["pickwinS"], self.iplot, refSpick = PragPicker(arhcf2, self.pickparams["tsnrh"], self.pickparams["pickwinS"], self.iplot, self.pickparams["ausS"],
self.pickparams["ausS"], self.pickparams["tsmoothS"], aicarhpick.getpick(), self.current_figure, self.current_linecolor)
self.pickparams["tsmoothS"], aicarhpick.getpick(), self.current_figure,
self.current_linecolor)
# save refSpick for later plotitng # save refSpick for later plotitng
self.refSpick = refSpick self.refSpick = refSpick
self.s_results.mpp = refSpick.getpick() self.s_results.mpp = refSpick.getpick()
@@ -1221,6 +1155,7 @@ class AutopickStation(object):
self.current_linecolor = plot_style['linecolor']['rgba_mpl'] self.current_linecolor = plot_style['linecolor']['rgba_mpl']
def autopickstation(wfstream, pickparam, verbose=False, iplot=0, fig_dict=None, metadata=None, origin=None): def autopickstation(wfstream, pickparam, verbose=False, iplot=0, fig_dict=None, metadata=None, origin=None):
""" """
Main function to calculate picks for the station. Main function to calculate picks for the station.
@@ -1308,11 +1243,11 @@ def iteratepicker(wf, NLLocfile, picks, badpicks, pickparameter, fig_dict=None):
print( print(
"iteratepicker: The following picking parameters have been modified for iterative picking:") "iteratepicker: The following picking parameters have been modified for iterative picking:")
print( print(
"pstart: %fs => %fs" % (pstart_old, pickparameter.get('pstart'))) "pstart: %fs => %fs" % (pstart_old, pickparameter.get('pstart')))
print( print(
"pstop: %fs => %fs" % (pstop_old, pickparameter.get('pstop'))) "pstop: %fs => %fs" % (pstop_old, pickparameter.get('pstop')))
print( print(
"sstop: %fs => %fs" % (sstop_old, pickparameter.get('sstop'))) "sstop: %fs => %fs" % (sstop_old, pickparameter.get('sstop')))
print("pickwinP: %fs => %fs" % ( print("pickwinP: %fs => %fs" % (
pickwinP_old, pickparameter.get('pickwinP'))) pickwinP_old, pickparameter.get('pickwinP')))
print("Precalcwin: %fs => %fs" % ( print("Precalcwin: %fs => %fs" % (
+31 -32
View File
@@ -16,16 +16,11 @@ autoregressive prediction: application ot local and regional distances, Geophys.
:author: MAGS2 EP3 working group :author: MAGS2 EP3 working group
""" """
import numpy as np import numpy as np
try: from scipy import signal
from scipy.signal import tukey
except ImportError:
from scipy.signal.windows import tukey
from obspy.core import Stream from obspy.core import Stream
from pylot.core.pick.utils import PickingFailedException
class CharacteristicFunction(object): class CharacteristicFunction(object):
""" """
@@ -60,7 +55,7 @@ class CharacteristicFunction(object):
self.setOrder(order) self.setOrder(order)
self.setFnoise(fnoise) self.setFnoise(fnoise)
self.setARdetStep(t2) self.setARdetStep(t2)
self.calcCF() self.calcCF(self.getDataArray())
self.arpara = np.array([]) self.arpara = np.array([])
self.xpred = np.array([]) self.xpred = np.array([])
@@ -155,7 +150,7 @@ class CharacteristicFunction(object):
if self.cut[0] == 0 and self.cut[1] == 0: if self.cut[0] == 0 and self.cut[1] == 0:
start = 0 start = 0
stop = len(self.orig_data[0]) stop = len(self.orig_data[0])
elif self.cut[0] == 0 and self.cut[1] != 0: elif self.cut[0] == 0 and self.cut[1] is not 0:
start = 0 start = 0
stop = self.cut[1] / self.dt stop = self.cut[1] / self.dt
else: else:
@@ -164,7 +159,7 @@ class CharacteristicFunction(object):
zz = self.orig_data.copy() zz = self.orig_data.copy()
z1 = zz[0].copy() z1 = zz[0].copy()
zz[0].data = z1.data[int(start):int(stop)] zz[0].data = z1.data[int(start):int(stop)]
if zz[0].stats.npts == 0: # cut times do not fit data length! if zz[0].stats.npts == 0: # cut times do not fit data length!
zz[0].data = z1.data # take entire data zz[0].data = z1.data # take entire data
data = zz data = zz
return data return data
@@ -172,7 +167,7 @@ class CharacteristicFunction(object):
if self.cut[0] == 0 and self.cut[1] == 0: if self.cut[0] == 0 and self.cut[1] == 0:
start = 0 start = 0
stop = min([len(self.orig_data[0]), len(self.orig_data[1])]) stop = min([len(self.orig_data[0]), len(self.orig_data[1])])
elif self.cut[0] == 0 and self.cut[1] != 0: elif self.cut[0] == 0 and self.cut[1] is not 0:
start = 0 start = 0
stop = min([self.cut[1] / self.dt, len(self.orig_data[0]), stop = min([self.cut[1] / self.dt, len(self.orig_data[0]),
len(self.orig_data[1])]) len(self.orig_data[1])])
@@ -192,7 +187,7 @@ class CharacteristicFunction(object):
start = 0 start = 0
stop = min([self.cut[1] / self.dt, len(self.orig_data[0]), stop = min([self.cut[1] / self.dt, len(self.orig_data[0]),
len(self.orig_data[1]), len(self.orig_data[2])]) len(self.orig_data[1]), len(self.orig_data[2])])
elif self.cut[0] == 0 and self.cut[1] != 0: elif self.cut[0] == 0 and self.cut[1] is not 0:
start = 0 start = 0
stop = self.cut[1] / self.dt stop = self.cut[1] / self.dt
else: else:
@@ -212,15 +207,17 @@ class CharacteristicFunction(object):
data = self.orig_data.copy() data = self.orig_data.copy()
return data return data
def calcCF(self): def calcCF(self, data=None):
pass self.cf = data
class AICcf(CharacteristicFunction): class AICcf(CharacteristicFunction):
def calcCF(self): def calcCF(self, data):
""" """
Function to calculate the Akaike Information Criterion (AIC) after Maeda (1985). Function to calculate the Akaike Information Criterion (AIC) after Maeda (1985).
:param data: data, time series (whether seismogram or CF)
:type data: tuple
:return: AIC function :return: AIC function
:rtype: :rtype:
""" """
@@ -229,7 +226,7 @@ class AICcf(CharacteristicFunction):
ind = np.where(~np.isnan(xnp))[0] ind = np.where(~np.isnan(xnp))[0]
if ind.size: if ind.size:
xnp[:ind[0]] = xnp[ind[0]] xnp[:ind[0]] = xnp[ind[0]]
xnp = tukey(len(xnp), alpha=0.05) * xnp xnp = signal.tukey(len(xnp), alpha=0.05) * xnp
xnp = xnp - np.mean(xnp) xnp = xnp - np.mean(xnp)
datlen = len(xnp) datlen = len(xnp)
k = np.arange(1, datlen) k = np.arange(1, datlen)
@@ -244,7 +241,7 @@ class AICcf(CharacteristicFunction):
ff = np.where(inf is True) ff = np.where(inf is True)
if len(ff) >= 1: if len(ff) >= 1:
cf[ff] = 0 cf[ff] = 0
self.cf = cf - np.mean(cf) self.cf = cf - np.mean(cf)
self.xcf = x self.xcf = x
@@ -258,11 +255,13 @@ class HOScf(CharacteristicFunction):
""" """
super(HOScf, self).__init__(data, cut, pickparams["tlta"], pickparams["hosorder"]) super(HOScf, self).__init__(data, cut, pickparams["tlta"], pickparams["hosorder"])
def calcCF(self): def calcCF(self, data):
""" """
Function to calculate skewness (statistics of order 3) or kurtosis Function to calculate skewness (statistics of order 3) or kurtosis
(statistics of order 4), using one long moving window, as published (statistics of order 4), using one long moving window, as published
in Kueperkoch et al. (2010), or order 2, i.e. STA/LTA. in Kueperkoch et al. (2010).
:param data: data, time series (whether seismogram or CF)
:type data: tuple
:return: HOS cf :return: HOS cf
:rtype: :rtype:
""" """
@@ -306,7 +305,7 @@ class HOScf(CharacteristicFunction):
if ind.size: if ind.size:
first = ind[0] first = ind[0]
LTA[:first] = LTA[first] LTA[:first] = LTA[first]
self.cf = LTA self.cf = LTA
self.xcf = x self.xcf = x
@@ -314,13 +313,14 @@ class HOScf(CharacteristicFunction):
class ARZcf(CharacteristicFunction): class ARZcf(CharacteristicFunction):
def __init__(self, data, cut, t1, t2, pickparams): def __init__(self, data, cut, t1, t2, pickparams):
super(ARZcf, self).__init__(data, cut, t1=t1, t2=t2, order=pickparams["Parorder"], super(ARZcf, self).__init__(data, cut, t1=t1, t2=t2, order=pickparams["Parorder"], fnoise=pickparams["addnoise"])
fnoise=pickparams["addnoise"])
def calcCF(self): def calcCF(self, data):
""" """
function used to calculate the AR prediction error from a single vertical trace. Can be used to pick function used to calculate the AR prediction error from a single vertical trace. Can be used to pick
P onsets. P onsets.
:param data:
:type data: ~obspy.core.stream.Stream
:return: ARZ cf :return: ARZ cf
:rtype: :rtype:
""" """
@@ -448,15 +448,16 @@ class ARZcf(CharacteristicFunction):
class ARHcf(CharacteristicFunction): class ARHcf(CharacteristicFunction):
def __init__(self, data, cut, t1, t2, pickparams): def __init__(self, data, cut, t1, t2, pickparams):
super(ARHcf, self).__init__(data, cut, t1=t1, t2=t2, order=pickparams["Sarorder"], super(ARHcf, self).__init__(data, cut, t1=t1, t2=t2, order=pickparams["Sarorder"], fnoise=pickparams["addnoise"])
fnoise=pickparams["addnoise"])
def calcCF(self): def calcCF(self, data):
""" """
Function to calculate a characteristic function using autoregressive modelling of the waveform of Function to calculate a characteristic function using autoregressive modelling of the waveform of
both horizontal traces. both horizontal traces.
The waveform is predicted in a moving time window using the calculated AR parameters. The difference The waveform is predicted in a moving time window using the calculated AR parameters. The difference
between the predicted and the actual waveform servers as a characteristic function. between the predicted and the actual waveform servers as a characteristic function.
:param data: wavefor stream
:type data: ~obspy.core.stream.Stream
:return: ARH cf :return: ARH cf
:rtype: :rtype:
""" """
@@ -464,9 +465,6 @@ class ARHcf(CharacteristicFunction):
print('Calculating AR-prediction error from both horizontal traces ...') print('Calculating AR-prediction error from both horizontal traces ...')
xnp = self.getDataArray(self.getCut()) xnp = self.getDataArray(self.getCut())
if len(xnp[0]) == 0:
raise PickingFailedException('calcCF: Found empty data trace for cut times. Return')
n0 = np.isnan(xnp[0].data) n0 = np.isnan(xnp[0].data)
if len(n0) > 1: if len(n0) > 1:
xnp[0].data[n0] = 0 xnp[0].data[n0] = 0
@@ -602,15 +600,16 @@ class ARHcf(CharacteristicFunction):
class AR3Ccf(CharacteristicFunction): class AR3Ccf(CharacteristicFunction):
def __init__(self, data, cut, t1, t2, pickparams): def __init__(self, data, cut, t1, t2, pickparams):
super(AR3Ccf, self).__init__(data, cut, t1=t1, t2=t2, order=pickparams["Sarorder"], super(AR3Ccf, self).__init__(data, cut, t1=t1, t2=t2, order=pickparams["Sarorder"], fnoise=pickparams["addnoise"])
fnoise=pickparams["addnoise"])
def calcCF(self): def calcCF(self, data):
""" """
Function to calculate a characteristic function using autoregressive modelling of the waveform of Function to calculate a characteristic function using autoregressive modelling of the waveform of
all three traces. all three traces.
The waveform is predicted in a moving time window using the calculated AR parameters. The difference The waveform is predicted in a moving time window using the calculated AR parameters. The difference
between the predicted and the actual waveform servers as a characteristic function between the predicted and the actual waveform servers as a characteristic function
:param data: stream holding all three traces
:type data: ~obspy.core.stream.Stream
:return: AR3C cf :return: AR3C cf
:rtype: :rtype:
""" """
+3 -6
View File
@@ -2,11 +2,10 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import copy import copy
import operator
import os
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
import operator
import os
from obspy.core import AttribDict from obspy.core import AttribDict
from pylot.core.util.pdf import ProbabilityDensityFunction from pylot.core.util.pdf import ProbabilityDensityFunction
@@ -118,7 +117,7 @@ class Comparison(object):
pdf_a = self.get('auto').generate_pdf_data(type) pdf_a = self.get('auto').generate_pdf_data(type)
pdf_b = self.get('manu').generate_pdf_data(type) pdf_b = self.get('manu').generate_pdf_data(type)
for station, phases in pdf_a.items(): for station, phases in pdf_a.items():
if station in pdf_b.keys(): if station in pdf_b.keys():
compare_pdf = dict() compare_pdf = dict()
@@ -402,8 +401,6 @@ class PDFstatistics(object):
Takes a path as argument. Takes a path as argument.
""" """
# TODO: change root to datapath
def __init__(self, directory): def __init__(self, directory):
"""Initiates some values needed when dealing with pdfs later""" """Initiates some values needed when dealing with pdfs later"""
self._rootdir = directory self._rootdir = directory
+24 -27
View File
@@ -19,10 +19,9 @@ calculated after Diehl & Kissling (2009).
:author: MAGS2 EP3 working group / Ludger Kueperkoch :author: MAGS2 EP3 working group / Ludger Kueperkoch
""" """
import warnings
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
import warnings
from scipy.signal import argrelmax, argrelmin from scipy.signal import argrelmax, argrelmin
from pylot.core.pick.charfuns import CharacteristicFunction from pylot.core.pick.charfuns import CharacteristicFunction
@@ -37,8 +36,7 @@ class AutoPicker(object):
warnings.simplefilter('ignore') warnings.simplefilter('ignore')
def __init__(self, cf, TSNR, PickWindow, iplot=0, aus=None, Tsmooth=None, Pick1=None, def __init__(self, cf, TSNR, PickWindow, iplot=0, aus=None, Tsmooth=None, Pick1=None, fig=None, linecolor='k'):
fig=None, linecolor='k', ogstream=None):
""" """
Create AutoPicker object Create AutoPicker object
:param cf: characteristic function, on which the picking algorithm is applied :param cf: characteristic function, on which the picking algorithm is applied
@@ -60,15 +58,12 @@ class AutoPicker(object):
:type fig: `~matplotlib.figure.Figure` :type fig: `~matplotlib.figure.Figure`
:param linecolor: matplotlib line color string :param linecolor: matplotlib line color string
:type linecolor: str :type linecolor: str
:param ogstream: original stream (waveform), e.g. for plotting purposes
:type ogstream: `~obspy.core.stream.Stream`
""" """
assert isinstance(cf, CharacteristicFunction), "%s is not a CharacteristicFunction object" % str(cf) assert isinstance(cf, CharacteristicFunction), "%s is not a CharacteristicFunction object" % str(cf)
self._linecolor = linecolor self._linecolor = linecolor
self._pickcolor_p = 'b' self._pickcolor_p = 'b'
self.cf = cf.getCF() self.cf = cf.getCF()
self.ogstream = ogstream
self.Tcf = cf.getTimeArray() self.Tcf = cf.getTimeArray()
self.Data = cf.getXCF() self.Data = cf.getXCF()
self.dt = cf.getIncrement() self.dt = cf.getIncrement()
@@ -177,14 +172,12 @@ class AICPicker(AutoPicker):
nn = np.isnan(self.cf) nn = np.isnan(self.cf)
if len(nn) > 1: if len(nn) > 1:
self.cf[nn] = 0 self.cf[nn] = 0
# taper AIC-CF to get rid of side maxima # taper AIC-CF to get rid off side maxima
tap = np.hanning(len(self.cf)) tap = np.hanning(len(self.cf))
aic = tap * self.cf + max(abs(self.cf)) aic = tap * self.cf + max(abs(self.cf))
# smooth AIC-CF # smooth AIC-CF
ismooth = int(round(self.Tsmooth / self.dt)) ismooth = int(round(self.Tsmooth / self.dt))
# MP MP better start with original data than zeros if array shall be smoothed, created artificial value before aicsmooth = np.zeros(len(aic))
# when starting with i in range(1...) loop below and subtracting offset afterwards
aicsmooth = np.copy(aic)
if len(aic) < ismooth: if len(aic) < ismooth:
print('AICPicker: Tsmooth larger than CF!') print('AICPicker: Tsmooth larger than CF!')
return return
@@ -194,7 +187,7 @@ class AICPicker(AutoPicker):
ii1 = i - ismooth ii1 = i - ismooth
aicsmooth[i] = aicsmooth[i - 1] + (aic[i] - aic[ii1]) / ismooth aicsmooth[i] = aicsmooth[i - 1] + (aic[i] - aic[ii1]) / ismooth
else: else:
aicsmooth[i] = np.mean(aic[0: i]) # MP MP created np.nan for i=1 aicsmooth[i] = np.mean(aic[1: i])
# remove offset in AIC function # remove offset in AIC function
offset = abs(min(aic) - min(aicsmooth)) offset = abs(min(aic) - min(aicsmooth))
aicsmooth = aicsmooth - offset aicsmooth = aicsmooth - offset
@@ -203,7 +196,7 @@ class AICPicker(AutoPicker):
# minimum in AIC function # minimum in AIC function
icfmax = np.argmax(cf) icfmax = np.argmax(cf)
# TODO: If this shall be kept, maybe add thresh_factor to pylot parameters # MP MP testing threshold
thresh_hit = False thresh_hit = False
thresh_factor = 0.7 thresh_factor = 0.7
thresh = thresh_factor * cf[icfmax] thresh = thresh_factor * cf[icfmax]
@@ -215,6 +208,7 @@ class AICPicker(AutoPicker):
if sample <= cf[index - 1]: if sample <= cf[index - 1]:
icfmax = index - 1 icfmax = index - 1
break break
# MP MP ---
# find minimum in AIC-CF front of maximum of HOS/AR-CF # find minimum in AIC-CF front of maximum of HOS/AR-CF
lpickwindow = int(round(self.PickWindow / self.dt)) lpickwindow = int(round(self.PickWindow / self.dt))
@@ -320,7 +314,16 @@ class AICPicker(AutoPicker):
plt.close(fig) plt.close(fig)
return return
iislope = islope[0][0:imax + 1] iislope = islope[0][0:imax + 1]
dataslope = self.Data[0].data[iislope] # MP MP change slope calculation
# get all maxima of aicsmooth
iaicmaxima = argrelmax(aicsmooth)[0]
# get first index of maximum after pickindex (indices saved in iaicmaxima)
aicmax = iaicmaxima[np.where(iaicmaxima > pickindex)[0]]
if len(aicmax) > 0:
iaicmax = aicmax[0]
else:
iaicmax = -1
dataslope = aicsmooth[pickindex: iaicmax]
# calculate slope as polynomal fit of order 1 # calculate slope as polynomal fit of order 1
xslope = np.arange(0, len(dataslope), 1) xslope = np.arange(0, len(dataslope), 1)
try: try:
@@ -331,8 +334,8 @@ class AICPicker(AutoPicker):
else: else:
self.slope = 1 / (len(dataslope) * self.Data[0].stats.delta) * (datafit[-1] - datafit[0]) self.slope = 1 / (len(dataslope) * self.Data[0].stats.delta) * (datafit[-1] - datafit[0])
# normalize slope to maximum of cf to make it unit independent # normalize slope to maximum of cf to make it unit independent
self.slope /= self.Data[0].data[icfmax] self.slope /= aicsmooth[iaicmax]
except Exception as e: except ValueError as e:
print("AICPicker: Problems with data fitting! {}".format(e)) print("AICPicker: Problems with data fitting! {}".format(e))
else: else:
@@ -351,12 +354,6 @@ class AICPicker(AutoPicker):
self.Tcf = self.Tcf[0:len(self.Tcf) - 1] self.Tcf = self.Tcf[0:len(self.Tcf) - 1]
ax1.plot(self.Tcf, cf / max(cf), color=self._linecolor, linewidth=0.7, label='(HOS-/AR-) Data') ax1.plot(self.Tcf, cf / max(cf), color=self._linecolor, linewidth=0.7, label='(HOS-/AR-) Data')
ax1.plot(self.Tcf, aicsmooth / max(aicsmooth), 'r', label='Smoothed AIC-CF') ax1.plot(self.Tcf, aicsmooth / max(aicsmooth), 'r', label='Smoothed AIC-CF')
# plot the original waveform also for evaluation of the CF and pick
if self.ogstream:
data = self.ogstream[0].data
if len(data) == len(self.Tcf):
ax1.plot(self.Tcf, 0.5 * data / max(data), 'k', label='Seismogram', alpha=0.3, zorder=0,
lw=0.5)
if self.Pick is not None: if self.Pick is not None:
ax1.plot([self.Pick, self.Pick], [-0.1, 0.5], 'b', linewidth=2, label='AIC-Pick') ax1.plot([self.Pick, self.Pick], [-0.1, 0.5], 'b', linewidth=2, label='AIC-Pick')
ax1.set_xlabel('Time [s] since %s' % self.Data[0].stats.starttime) ax1.set_xlabel('Time [s] since %s' % self.Data[0].stats.starttime)
@@ -377,7 +374,7 @@ class AICPicker(AutoPicker):
label='Signal Window') label='Signal Window')
ax2.axvspan(self.Tcf[iislope[0]], self.Tcf[iislope[-1]], color='g', alpha=0.2, lw=0, ax2.axvspan(self.Tcf[iislope[0]], self.Tcf[iislope[-1]], color='g', alpha=0.2, lw=0,
label='Slope Window') label='Slope Window')
ax2.plot(self.Tcf[iislope], datafit, 'g', linewidth=2, ax2.plot(self.Tcf[pickindex: iaicmax], datafit, 'g', linewidth=2,
label='Slope') # MP MP changed temporarily! label='Slope') # MP MP changed temporarily!
if self.slope is not None: if self.slope is not None:
@@ -479,7 +476,7 @@ class PragPicker(AutoPicker):
cfpick_r = 0 cfpick_r = 0
cfpick_l = 0 cfpick_l = 0
lpickwindow = int(round(self.PickWindow / self.dt)) lpickwindow = int(round(self.PickWindow / self.dt))
# for i in range(max(np.insert(ipick, 0, 2)), min([ipick1 + lpickwindow + 1, len(self.cf) - 1])): #for i in range(max(np.insert(ipick, 0, 2)), min([ipick1 + lpickwindow + 1, len(self.cf) - 1])):
# # local minimum # # local minimum
# if self.cf[i + 1] > self.cf[i] <= self.cf[i - 1]: # if self.cf[i + 1] > self.cf[i] <= self.cf[i - 1]:
# if cfsmooth[i - 1] * (1 + aus1) >= cfsmooth[i]: # if cfsmooth[i - 1] * (1 + aus1) >= cfsmooth[i]:
@@ -511,9 +508,9 @@ class PragPicker(AutoPicker):
if flagpick_l > 0 and flagpick_r > 0 and cfpick_l <= 3 * cfpick_r: if flagpick_l > 0 and flagpick_r > 0 and cfpick_l <= 3 * cfpick_r:
self.Pick = pick_l self.Pick = pick_l
pickflag = 1 pickflag = 1
# elif flagpick_l > 0 and flagpick_r > 0 and cfpick_l >= cfpick_r: elif flagpick_l > 0 and flagpick_r > 0 and cfpick_l >= cfpick_r:
# self.Pick = pick_r self.Pick = pick_r
# pickflag = 1 pickflag = 1
elif flagpick_l == 0 and flagpick_r > 0 and cfpick_l >= cfpick_r: elif flagpick_l == 0 and flagpick_r > 0 and cfpick_l >= cfpick_r:
self.Pick = pick_l self.Pick = pick_l
pickflag = 1 pickflag = 1
+286 -647
View File
File diff suppressed because it is too large. Load diff
+365 -469
View File
@@ -1,55 +1,38 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import traceback import os
import cartopy.crs as ccrs
import cartopy.feature as cf
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import matplotlib
import matplotlib.patheffects as PathEffects
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
import obspy import obspy
from PySide2 import QtWidgets, QtGui import traceback
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from PySide2 import QtWidgets
from matplotlib.figure import Figure
from mpl_toolkits.axes_grid1.inset_locator import inset_axes from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from obspy import UTCDateTime from mpl_toolkits.basemap import Basemap
from pylot.core.util.utils import identifyPhaseID
from scipy.interpolate import griddata from scipy.interpolate import griddata
from pylot.core.util.widgets import PickDlg, PylotCanvas
from pylot.core.pick.utils import get_quality_class from pylot.core.pick.utils import get_quality_class
from pylot.core.util.widgets import PickDlg
matplotlib.use('Qt5Agg') plt.interactive(False)
class MplCanvas(FigureCanvas):
def __init__(self, extern_axes=None, projection=None, width=15, height=5, dpi=100):
if extern_axes is None:
self.fig = plt.figure(figsize=(width, height), dpi=dpi)
self.axes = self.fig.add_subplot(111, projection=projection)
else:
self.fig = extern_axes.figure
self.axes = extern_axes
super(MplCanvas, self).__init__(self.fig)
class Array_map(QtWidgets.QWidget): class Array_map(QtWidgets.QWidget):
def __init__(self, parent, metadata, parameter=None, axes=None, annotate=True, pointsize=25., def __init__(self, parent, metadata, parameter=None, figure=None, annotate=True, pointsize=25.,
linewidth=1.5, width=5e6, height=2e6): linewidth=1.5, width=5e6, height=2e6):
QtWidgets.QWidget.__init__(self, parent=parent) '''
Create a map of the array.
assert (parameter is not None or parent is not None), 'either parent or parameter has to be set' :param parent: object of PyLoT Mainwindow class
# set properties :param parameter: object of PyLoT parameter class
:param figure:
'''
QtWidgets.QWidget.__init__(self)
assert (parameter != None or parent != None), 'either parent or parameter has to be set'
self._parent = parent self._parent = parent
self.metadata = metadata self.metadata = metadata
self.pointsize = pointsize self.pointsize = pointsize
self.linewidth = linewidth self.linewidth = linewidth
self.extern_plot_axes = axes
self.width = width self.width = width
self.height = height self.height = height
self.annotate = annotate self.annotate = annotate
@@ -60,249 +43,39 @@ class Array_map(QtWidgets.QWidget):
self.hybrids_dict = None self.hybrids_dict = None
self.eventLoc = None self.eventLoc = None
self.parameter = parameter if parameter else parent._inputs self.parameter = parameter if parameter else parent._inputs
self.figure = figure
self.picks_rel = {} self.picks_rel = {}
self.picks_rel_mean_corrected = {}
self.marked_stations = [] self.marked_stations = []
self.highlighted_stations = [] self.highlighted_stations = []
# call functions to draw everything
self.projection = ccrs.PlateCarree()
self.init_graphics() self.init_graphics()
self.ax = self.canvas.axes
self.ax.set_adjustable('datalim')
self.init_stations() self.init_stations()
self.init_crtpyMap() self.init_basemap(resolution='l')
self.init_map() self.init_map()
# set original map limits to fall back on when home button is pressed
self.org_xlim = self.ax.get_xlim()
self.org_ylim = self.ax.get_ylim()
# initial map without event
self.ax.set_xlim(self.org_xlim[0], self.org_xlim[1])
self.ax.set_ylim(self.org_ylim[0], self.org_ylim[1])
self._style = None if not hasattr(parent, '_style') else parent._style self._style = None if not hasattr(parent, '_style') else parent._style
# self.show()
def update_hybrids_dict(self):
self.hybrids_dict = self.picks_dict.copy()
for station, pick in self.autopicks_dict.items():
if not station in self.hybrids_dict.keys():
self.hybrids_dict[station] = pick
return self.hybrids_dict
def init_map(self): def init_map(self):
self.init_colormap() self.init_colormap()
self.connectSignals() self.connectSignals()
self.draw_everything() self.draw_everything()
self.canvas.setZoomBorders2content()
def init_graphics(self):
"""
Initializes all GUI components and figure elements to be populated by other functions
"""
# initialize figure elements
if self.extern_plot_axes is None:
self.canvas = MplCanvas(projection=self.projection)
else:
self.canvas = MplCanvas(extern_axes=self.extern_plot_axes)
self.plotWidget = self.canvas
# initialize GUI elements
self.status_label = QtWidgets.QLabel()
self.map_reset_button = QtWidgets.QPushButton('Reset Map View')
self.save_map_button = QtWidgets.QPushButton('Save Map')
self.go2eq_button = QtWidgets.QPushButton('Go to Event Location')
self.subtract_mean_cb = QtWidgets.QCheckBox('Subtract mean')
self.main_box = QtWidgets.QVBoxLayout()
self.setLayout(self.main_box)
self.top_row = QtWidgets.QHBoxLayout()
self.main_box.addLayout(self.top_row, 0)
self.comboBox_phase = QtWidgets.QComboBox()
self.comboBox_phase.insertItem(0, 'P')
self.comboBox_phase.insertItem(1, 'S')
self.comboBox_am = QtWidgets.QComboBox()
self.comboBox_am.insertItem(0, 'hybrid (prefer manual)')
self.comboBox_am.insertItem(1, 'manual')
self.comboBox_am.insertItem(2, 'auto')
self.annotations_box = QtWidgets.QCheckBox('Annotate')
self.annotations_box.setChecked(True)
self.auto_refresh_box = QtWidgets.QCheckBox('Automatic refresh')
self.auto_refresh_box.setChecked(True)
self.refresh_button = QtWidgets.QPushButton('Refresh')
self.cmaps_box = QtWidgets.QComboBox()
self.cmaps_box.setMaxVisibleItems(20)
[self.cmaps_box.addItem(map_name) for map_name in sorted(plt.colormaps())]
# try to set to plasma as default
self.cmaps_box.setCurrentIndex(self.cmaps_box.findText('plasma'))
self.top_row.addWidget(QtWidgets.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.addWidget(QtWidgets.QLabel('Pick type: '))
self.top_row.addWidget(self.comboBox_am)
self.top_row.setStretch(3, 1) # set stretch of item 1 to 1
self.top_row.addWidget(self.cmaps_box)
self.top_row.addWidget(self.annotations_box)
self.top_row.addWidget(self.auto_refresh_box)
self.top_row.addWidget(self.refresh_button)
self.main_box.addWidget(self.plotWidget, 10)
self.bot_row = QtWidgets.QHBoxLayout()
self.main_box.addLayout(self.bot_row, 0)
self.bot_row.addWidget(QtWidgets.QLabel(''), 5)
self.bot_row.addWidget(self.map_reset_button, 2)
self.bot_row.addWidget(self.go2eq_button, 2)
self.bot_row.addWidget(self.save_map_button, 2)
self.bot_row.addWidget(self.subtract_mean_cb, 0)
self.bot_row.addWidget(self.status_label, 5)
def init_colormap(self): def init_colormap(self):
self.init_lat_lon_dimensions() self.init_lat_lon_dimensions()
self.init_lat_lon_grid() self.init_lat_lon_grid()
self.init_x_y_dimensions()
def init_crtpyMap(self):
self.ax.add_feature(cf.LAND)
self.ax.add_feature(cf.OCEAN)
self.ax.add_feature(cf.COASTLINE, linewidth=1, edgecolor='gray')
self.ax.add_feature(cf.BORDERS, alpha=0.7)
self.ax.add_feature(cf.LAKES, alpha=0.7)
self.ax.add_feature(cf.RIVERS, linewidth=1)
# parallels and meridians
self.add_merid_paral()
self.canvas.fig.tight_layout()
def add_merid_paral(self):
self.gridlines = self.ax.gridlines(draw_labels=False, alpha=0.6, color='gray',
linewidth=self.linewidth / 2, zorder=7, crs=ccrs.PlateCarree())
def remove_merid_paral(self):
if len(self.gridlines.xline_artists):
self.gridlines.xline_artists[0].remove()
self.gridlines.yline_artists[0].remove()
def org_map_view(self):
self.ax.set_xlim(self.org_xlim[0], self.org_xlim[1])
self.ax.set_ylim(self.org_ylim[0], self.org_ylim[1])
# parallels and meridians
#self.remove_merid_paral()
#self.add_merid_paral()
self.canvas.draw_idle()
def go2eq(self):
if self.eventLoc:
lats, lons = self.eventLoc
self.ax.set_xlim(lons - 10, lons + 10)
self.ax.set_ylim(lats - 5, lats + 5)
# parallels and meridians
#self.remove_merid_paral()
#self.add_merid_paral()
self.canvas.draw_idle()
else:
self.status_label.setText('No event information available')
def connectSignals(self):
self.comboBox_phase.currentIndexChanged.connect(self._refresh_drawings)
self.comboBox_am.currentIndexChanged.connect(self._refresh_drawings)
self.cmaps_box.currentIndexChanged.connect(self._refresh_drawings)
self.annotations_box.stateChanged.connect(self.switch_annotations)
self.refresh_button.clicked.connect(self._refresh_drawings)
self.map_reset_button.clicked.connect(self.org_map_view)
self.go2eq_button.clicked.connect(self.go2eq)
self.save_map_button.clicked.connect(self.saveFigure)
self.subtract_mean_cb.stateChanged.connect(self.toggle_subtract_mean)
self.plotWidget.mpl_connect('motion_notify_event', self.mouse_moved)
self.plotWidget.mpl_connect('scroll_event', self.mouse_scroll)
self.plotWidget.mpl_connect('button_press_event', self.mouseLeftPress)
self.plotWidget.mpl_connect('button_release_event', self.mouseLeftRelease)
# set mouse events -----------------------------------------------------
def mouse_moved(self, event):
if not event.inaxes == self.ax:
return
else:
cont, inds = self.sc.contains(event)
lat = event.ydata
lon = event.xdata
text = f'Longitude: {lon:3.3f}, Latitude: {lat:3.3f}'
if cont:
indices = inds['ind']
text += ' | Station: ' if len(indices) == 1 else ' | Stations: '
text += ' - '.join([self._station_onpick_ids[index] for index in indices[:5]])
if len(indices) > 5:
text += '...'
self.status_label.setText(text)
def mouse_scroll(self, event):
if not event.inaxes == self.ax:
return
zoom = {'up': 1. / 2., 'down': 2.}
if event.button in zoom:
xlim = self.ax.get_xlim()
ylim = self.ax.get_ylim()
x, y = event.xdata, event.ydata
factor = zoom[event.button]
xdiff = (xlim[1] - xlim[0]) * factor
xl = x - 0.5 * xdiff
xr = x + 0.5 * xdiff
ydiff = (ylim[1] - ylim[0]) * factor
yb = y - 0.5 * ydiff
yt = y + 0.5 * ydiff
self.ax.set_xlim(xl, xr)
self.ax.set_ylim(yb, yt)
# parallels and meridians
#self.remove_merid_paral()
#self.add_merid_paral()
self.ax.figure.canvas.draw_idle()
def mouseLeftPress(self, event):
if not event.inaxes == self.ax:
return
self.map_x = event.xdata
self.map_y = event.ydata
self.map_xlim = self.ax.get_xlim()
self.map_ylim = self.ax.get_ylim()
def mouseLeftRelease(self, event):
if not event.inaxes == self.ax:
return
new_x = event.xdata
new_y = event.ydata
dx = new_x - self.map_x
dy = new_y - self.map_y
self.ax.set_xlim((self.map_xlim[0] - dx, self.map_xlim[1] - dx))
self.ax.set_ylim(self.map_ylim[0] - dy, self.map_ylim[1] - dy)
# parallels and meridians
#self.remove_merid_paral()
#self.add_merid_paral()
self.ax.figure.canvas.draw_idle()
def onpick(self, event): def onpick(self, event):
btn_msg = {1: ' in selection. Aborted', 2: ' to delete a pick on. Aborted', 3: ' to display info.'}
ind = event.ind ind = event.ind
button = event.mouseevent.button button = event.mouseevent.button
msg_reason = None if ind == []:
if len(ind) > 1:
self._parent.update_status(f'Found more than one station {btn_msg.get(button)}')
return return
if button == 1: if button == 1:
self.openPickDlg(ind) self.openPickDlg(ind)
@@ -311,14 +84,6 @@ class Array_map(QtWidgets.QWidget):
elif button == 3: elif button == 3:
self.pickInfo(ind) self.pickInfo(ind)
# data handling -----------------------------------------------------
def update_hybrids_dict(self):
self.hybrids_dict = self.picks_dict.copy()
for station, pick in self.autopicks_dict.items():
if not station in self.hybrids_dict.keys():
self.hybrids_dict[station] = pick
return self.hybrids_dict
def deletePick(self, ind): def deletePick(self, ind):
self.update_hybrids_dict() self.update_hybrids_dict()
for index in ind: for index in ind:
@@ -352,6 +117,15 @@ class Array_map(QtWidgets.QWidget):
except Exception as e: except Exception as e:
print('Could not delete pick for station {}.{}: {}'.format(network, station, e)) print('Could not delete pick for station {}.{}: {}'.format(network, station, e))
def highlight_station(self, network, station, color):
stat_dict = self.stations_dict['{}.{}'.format(network, station)]
lat = stat_dict['latitude']
lon = stat_dict['longitude']
self.highlighted_stations.append(self.basemap.scatter(lon, lat, s=self.pointsize, edgecolors=color,
facecolors='none', latlon=True,
zorder=12, label='deleted'))
self.canvas.draw()
def pickInfo(self, ind): def pickInfo(self, ind):
self.update_hybrids_dict() self.update_hybrids_dict()
for index in ind: for index in ind:
@@ -365,159 +139,18 @@ class Array_map(QtWidgets.QWidget):
for key, info in picks.items(): for key, info in picks.items():
print('{}: {}'.format(key, info)) print('{}: {}'.format(key, info))
def _from_dict(self, function, key):
return function(self.stations_dict.values(), key=lambda x: x[key])[key]
def get_min_from_stations(self, key):
return self._from_dict(min, key)
def get_max_from_stations(self, key):
return self._from_dict(max, key)
def current_picks_dict(self):
picktype = self.comboBox_am.currentText().split(' ')[0]
auto_manu = {'auto': self.autopicks_dict,
'manual': self.picks_dict,
'hybrid': self.hybrids_dict}
return auto_manu[picktype]
def init_stations(self):
self.stations_dict = self.metadata.get_all_coordinates()
self.latmin = self.get_min_from_stations('latitude')
self.lonmin = self.get_min_from_stations('longitude')
self.latmax = self.get_max_from_stations('latitude')
self.lonmax = self.get_max_from_stations('longitude')
def init_picks(self):
def get_picks(station_dict):
self.update_hybrids_dict()
picks = {}
uncertainties = {}
# selected phase
phase = self.comboBox_phase.currentText()
for st_id in station_dict.keys():
try:
station_name = st_id.split('.')[-1]
# current_picks_dict: auto or manual
station_picks = self.current_picks_dict().get(station_name)
if not station_picks:
continue
for phase_hint, pick in station_picks.items():
if identifyPhaseID(phase_hint) == phase:
break
else:
continue
if pick['picker'] == 'auto':
if not pick['spe']:
continue
picks[st_id] = pick['mpp']
uncertainties[st_id] = pick['spe']
except KeyError:
continue
except Exception as e:
print('Cannot display pick for station {}. Reason: {}'.format(station_name, e))
return picks, uncertainties
def get_picks_rel(picks, func=min):
picks_rel = {}
picks_utc = []
for pick in picks.values():
if type(pick) is UTCDateTime:
picks_utc.append(pick.timestamp)
if picks_utc:
self._reference_picktime = UTCDateTime(func(picks_utc))
for st_id, pick in picks.items():
if type(pick) is UTCDateTime:
pick -= self._reference_picktime
picks_rel[st_id] = pick
return picks_rel
def get_picks_rel_mean_corr(picks):
return get_picks_rel(picks, func=np.nanmean)
self.picks, self.uncertainties = get_picks(self.stations_dict)
self.picks_rel = get_picks_rel(self.picks)
self.picks_rel_mean_corrected = get_picks_rel_mean_corr(self.picks)
def toggle_subtract_mean(self):
if self.subtract_mean_cb.isChecked():
cmap = 'seismic'
else:
cmap = 'viridis'
self.cmaps_box.setCurrentIndex(self.cmaps_box.findText(cmap))
self._refresh_drawings()
def init_lat_lon_dimensions(self):
# init minimum and maximum lon and lat dimensions
self.londim = self.lonmax - self.lonmin
self.latdim = self.latmax - self.latmin
def init_lat_lon_grid(self, nstep=250):
# create a regular grid to display colormap
lataxis = np.linspace(self.latmin, self.latmax, nstep)
lonaxis = np.linspace(self.lonmin, self.lonmax, nstep)
self.longrid, self.latgrid = np.meshgrid(lonaxis, lataxis)
def init_picksgrid(self):
picks, uncertainties, lats, lons = self.get_picks_lat_lon()
try:
self.picksgrid_active = griddata((lats, lons), picks, (self.latgrid, self.longrid), method='linear')
except Exception as e:
self._warn('Could not init picksgrid: {}'.format(e))
def get_st_lat_lon_for_plot(self):
stations = []
latitudes = []
longitudes = []
for st_id, coords in self.stations_dict.items():
stations.append(st_id)
latitudes.append(coords['latitude'])
longitudes.append(coords['longitude'])
return stations, latitudes, longitudes
def get_picks_lat_lon(self):
picks_rel = self.picks_rel_mean_corrected if self.subtract_mean_cb.isChecked() else self.picks_rel
picks = []
uncertainties = []
latitudes = []
longitudes = []
for st_id, pick in picks_rel.items():
picks.append(pick)
uncertainties.append(self.uncertainties.get(st_id))
latitudes.append(self.stations_dict[st_id]['latitude'])
longitudes.append(self.stations_dict[st_id]['longitude'])
return picks, uncertainties, latitudes, longitudes
# plotting -----------------------------------------------------
def highlight_station(self, network, station, color):
stat_dict = self.stations_dict['{}.{}'.format(network, station)]
lat = stat_dict['latitude']
lon = stat_dict['longitude']
self.highlighted_stations.append(self.ax.scatter(lon, lat, s=self.pointsize, edgecolors=color,
facecolors='none', zorder=12,
transform=ccrs.PlateCarree(), label='deleted'))
def openPickDlg(self, ind): def openPickDlg(self, ind):
try: data = self._parent.get_data().getWFData()
wfdata = self._parent.get_data().getWFData()
except AttributeError:
QtWidgets.QMessageBox.warning(
self, "PyLoT Warning",
"No waveform data found. Check if they were already loaded in Waveform plot tab."
)
return
wfdata_comp = self._parent.get_data().getAltWFdata()
for index in ind: for index in ind:
network, station = self._station_onpick_ids[index].split('.')[:2] network, station = self._station_onpick_ids[index].split('.')[:2]
pyl_mw = self._parent pyl_mw = self._parent
try: try:
wfdata = wfdata.select(station=station) data = data.select(station=station)
wfdata_comp = wfdata_comp.select(station=station) if not data:
if not wfdata:
self._warn('No data for station {}'.format(station)) self._warn('No data for station {}'.format(station))
return return
pickDlg = PickDlg(self._parent, parameter=self.parameter, pickDlg = PickDlg(self._parent, parameter=self.parameter,
data=wfdata.copy(), data_compare=wfdata_comp.copy(), network=network, station=station, data=data, network=network, station=station,
picks=self._parent.get_current_event().getPick(station), picks=self._parent.get_current_event().getPick(station),
autopicks=self._parent.get_current_event().getAutopick(station), autopicks=self._parent.get_current_event().getAutopick(station),
filteroptions=self._parent.filteroptions, metadata=self.metadata, filteroptions=self._parent.filteroptions, metadata=self.metadata,
@@ -548,38 +181,288 @@ class Array_map(QtWidgets.QWidget):
print(message, e) print(message, e)
print(traceback.format_exc()) print(traceback.format_exc())
def draw_contour_filled(self, nlevel=51): def connectSignals(self):
if self.subtract_mean_cb.isChecked(): self.comboBox_phase.currentIndexChanged.connect(self._refresh_drawings)
abs_max = self.get_residuals_absmax() self.comboBox_am.currentIndexChanged.connect(self._refresh_drawings)
levels = np.linspace(-abs_max, abs_max, nlevel) self.cmaps_box.currentIndexChanged.connect(self._refresh_drawings)
else: self.annotations_box.stateChanged.connect(self.switch_annotations)
levels = np.linspace(min(self.picks_rel.values()), max(self.picks_rel.values()), nlevel) self.refresh_button.clicked.connect(self._refresh_drawings)
self.canvas.mpl_connect('motion_notify_event', self.mouse_moved)
# self.zoom_id = self.basemap.ax.figure.canvas.mpl_connect('scroll_event', self.zoom)
self.contourf = self.ax.contourf(self.longrid, self.latgrid, self.picksgrid_active, levels, def _from_dict(self, function, key):
linewidths=self.linewidth * 5, transform=ccrs.PlateCarree(), return function(self.stations_dict.values(), key=lambda x: x[key])[key]
alpha=0.4, zorder=8, cmap=self.get_colormap())
def get_residuals_absmax(self): def get_min_from_stations(self, key):
return np.max(np.absolute(list(self.picks_rel_mean_corrected.values()))) return self._from_dict(min, key)
def get_max_from_stations(self, key):
return self._from_dict(max, key)
def get_min_from_picks(self):
return min(self.picks_rel.values())
def get_max_from_picks(self):
return max(self.picks_rel.values())
def mouse_moved(self, event):
if not event.inaxes == self.main_ax:
return
x = event.xdata
y = event.ydata
lat, lon = self.basemap(x, y, inverse=True)
self.status_label.setText('Latitude: {}, Longitude: {}'.format(lat, lon))
def current_picks_dict(self):
picktype = self.comboBox_am.currentText().split(' ')[0]
auto_manu = {'auto': self.autopicks_dict,
'manual': self.picks_dict,
'hybrid': self.hybrids_dict}
return auto_manu[picktype]
def init_graphics(self):
if not self.figure:
self.figure = Figure()
self.status_label = QtWidgets.QLabel()
self.main_ax = self.figure.add_subplot(111)
#self.main_ax.set_facecolor('0.7')
self.canvas = PylotCanvas(self.figure, parent=self._parent, multicursor=True,
panZoomX=False, panZoomY=False)
self.main_box = QtWidgets.QVBoxLayout()
self.setLayout(self.main_box)
self.top_row = QtWidgets.QHBoxLayout()
self.main_box.addLayout(self.top_row, 1)
self.comboBox_phase = QtWidgets.QComboBox()
self.comboBox_phase.insertItem(0, 'P')
self.comboBox_phase.insertItem(1, 'S')
self.comboBox_am = QtWidgets.QComboBox()
self.comboBox_am.insertItem(0, 'hybrid (prefer manual)')
self.comboBox_am.insertItem(1, 'manual')
self.comboBox_am.insertItem(2, 'auto')
self.annotations_box = QtWidgets.QCheckBox('Annotate')
self.annotations_box.setChecked(True)
self.auto_refresh_box = QtWidgets.QCheckBox('Automatic refresh')
self.auto_refresh_box.setChecked(True)
self.refresh_button = QtWidgets.QPushButton('Refresh')
self.cmaps_box = QtWidgets.QComboBox()
self.cmaps_box.setMaxVisibleItems(20)
[self.cmaps_box.addItem(map_name) for map_name in sorted(plt.colormaps())]
# try to set to hsv as default
self.cmaps_box.setCurrentIndex(self.cmaps_box.findText('hsv'))
self.top_row.addWidget(QtWidgets.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.addWidget(QtWidgets.QLabel('Pick type: '))
self.top_row.addWidget(self.comboBox_am)
self.top_row.setStretch(3, 1) # set stretch of item 1 to 1
self.top_row.addWidget(self.cmaps_box)
self.top_row.addWidget(self.annotations_box)
self.top_row.addWidget(self.auto_refresh_box)
self.top_row.addWidget(self.refresh_button)
self.main_box.addWidget(self.canvas, 1)
self.main_box.addWidget(self.status_label, 0)
def init_stations(self):
self.stations_dict = self.metadata.get_all_coordinates()
self.latmin = self.get_min_from_stations('latitude')
self.lonmin = self.get_min_from_stations('longitude')
self.latmax = self.get_max_from_stations('latitude')
self.lonmax = self.get_max_from_stations('longitude')
def init_picks(self):
def get_picks(station_dict):
self.update_hybrids_dict()
picks = {}
uncertainties = {}
# selected phase
phase = self.comboBox_phase.currentText()
for st_id in station_dict.keys():
try:
station_name = st_id.split('.')[-1]
# current_picks_dict: auto or manual
pick = self.current_picks_dict()[station_name][phase]
if pick['picker'] == 'auto':
if not pick['spe']:
continue
picks[st_id] = pick['mpp']
uncertainties[st_id] = pick['spe']
except KeyError:
continue
except Exception as e:
print('Cannot display pick for station {}. Reason: {}'.format(station_name, e))
return picks, uncertainties
def get_picks_rel(picks):
picks_rel = {}
picks_utc = []
for pick in picks.values():
if type(pick) is obspy.core.utcdatetime.UTCDateTime:
picks_utc.append(pick)
if picks_utc:
self._earliest_picktime = min(picks_utc)
for st_id, pick in picks.items():
if type(pick) is obspy.core.utcdatetime.UTCDateTime:
pick -= self._earliest_picktime
picks_rel[st_id] = pick
return picks_rel
self.picks, self.uncertainties = get_picks(self.stations_dict)
self.picks_rel = get_picks_rel(self.picks)
def init_lat_lon_dimensions(self):
# init minimum and maximum lon and lat dimensions
self.londim = self.lonmax - self.lonmin
self.latdim = self.latmax - self.latmin
def init_x_y_dimensions(self):
# transformation of lat/lon to ax coordinate system
for st_id, coords in self.stations_dict.items():
lat, lon = coords['latitude'], coords['longitude']
coords['x'], coords['y'] = self.basemap(lon, lat)
self.xdim = self.get_max_from_stations('x') - self.get_min_from_stations('x')
self.ydim = self.get_max_from_stations('y') - self.get_min_from_stations('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,
width=self.width, height=self.height,
lat_0=(self.latmin + self.latmax) / 2.,
lon_0=(self.lonmin + self.lonmax) / 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)
# labels = [left,right,top,bottom]
parallels = np.arange(-90, 90, 5.)
parallels_small = np.arange(-90, 90, 2.5)
basemap.drawparallels(parallels_small, linewidth=0.5, zorder=7)
basemap.drawparallels(parallels, zorder=7)#, labels=[1, 1, 0, 0])
meridians = np.arange(-180, 180, 5.)
meridians_small = np.arange(-180, 180, 2.5)
basemap.drawmeridians(meridians_small, linewidth=0.5, zorder=7)
basemap.drawmeridians(meridians, zorder=7)#, labels=[0, 0, 1, 1])
self.basemap = basemap
self.figure._tight = True
self.figure.tight_layout()
def init_lat_lon_grid(self, nstep=250):
# create a regular grid to display colormap
lataxis = np.linspace(self.latmin, self.latmax, nstep)
lonaxis = np.linspace(self.lonmin, self.lonmax, nstep)
self.longrid, self.latgrid = np.meshgrid(lonaxis, lataxis)
def init_picksgrid(self):
picks, uncertainties, lats, lons = self.get_picks_lat_lon()
try:
self.picksgrid_active = griddata((lats, lons), picks, (self.latgrid, self.longrid),
method='linear')
except Exception as e:
self._warn('Could not init picksgrid: {}'.format(e))
def get_st_lat_lon_for_plot(self):
stations = []
latitudes = []
longitudes = []
for st_id, coords in self.stations_dict.items():
stations.append(st_id)
latitudes.append(coords['latitude'])
longitudes.append(coords['longitude'])
return stations, latitudes, longitudes
def get_st_x_y_for_plot(self):
stations = []
xs = []
ys = []
for st_id, coords in self.stations_dict.items():
stations.append(st_id)
xs.append(coords['x'])
ys.append(coords['y'])
return stations, xs, ys
def get_picks_lat_lon(self):
picks = []
uncertainties = []
latitudes = []
longitudes = []
for st_id, pick in self.picks_rel.items():
picks.append(pick)
uncertainties.append(self.uncertainties.get(st_id))
latitudes.append(self.stations_dict[st_id]['latitude'])
longitudes.append(self.stations_dict[st_id]['longitude'])
return picks, uncertainties, latitudes, longitudes
def draw_contour_filled(self, nlevel='100'):
# self.test_gradient()
levels = np.linspace(self.get_min_from_picks(), self.get_max_from_picks(), nlevel)
self.contourf = self.basemap.contour(self.longrid, self.latgrid, self.picksgrid_active, levels,
linewidths=self.linewidth, latlon=True, zorder=8, alpha=0.7,
cmap=self.get_colormap())
def get_colormap(self): def get_colormap(self):
return plt.get_cmap(self.cmaps_box.currentText()) return plt.get_cmap(self.cmaps_box.currentText())
def test_gradient(self):
st_ids = self.picks_rel.keys()
x, y = np.gradient(self.picksgrid_active)
gradient_modulus = np.sqrt(x ** 2 + y ** 2)
global_mean_gradient = np.nanmean(gradient_modulus)
delta_gradient = []
for st_id in st_ids:
pick_item = self.picks_rel.pop(st_id)
self.init_picksgrid()
x, y = np.gradient(self.picksgrid_active)
gradient_modulus = np.sqrt(x ** 2 + y ** 2)
mean_gradient = np.nanmean(gradient_modulus)
dgradient = global_mean_gradient - mean_gradient
# print('station: {}, mean gradient: {}'.format(st_id, dgradient))
delta_gradient.append(dgradient)
self.picks_rel[st_id] = pick_item
global_std_gradient = np.nanstd(delta_gradient)
marked_stations = []
for st_id, dg in zip(st_ids, delta_gradient):
if abs(dg) > global_std_gradient:
marked_stations.append(st_id)
self.marked_stations = marked_stations
self.init_picksgrid()
# fig = plt.figure()
# x = list(range(len(st_ids)))
# gradients = zip(x, delta_gradient)
# gradients.sort(key=lambda a: a[1])
# plt.plot(gradients[0], gradients[1])
# global_var_gradient = np.nanvar(delta_gradient)
# plt.plot(x, delta_gradient)
# plt.axhline(global_std_gradient, color='green')
# plt.axhline(2 * global_std_gradient, color='blue')
# plt.axhline(global_var_gradient, color='red')
# plt.xticks(x, st_ids)
# plt.show()
def scatter_all_stations(self): def scatter_all_stations(self):
stations, lats, lons = self.get_st_lat_lon_for_plot() stations, lats, lons = self.get_st_lat_lon_for_plot()
self.sc = self.basemap.scatter(lons, lats, s=self.pointsize, facecolor='none', latlon=True, marker='.',
self.sc = self.ax.scatter(lons, lats, s=self.pointsize * 3, facecolor='none', marker='.', zorder=10, picker=True, edgecolor='0.5', label='Not Picked')
zorder=10, picker=True, edgecolor='0.5', label='Not Picked', self.cid = self.canvas.mpl_connect('pick_event', self.onpick)
transform=ccrs.PlateCarree())
self.cid = self.plotWidget.mpl_connect('pick_event', self.onpick)
self._station_onpick_ids = stations self._station_onpick_ids = stations
if self.eventLoc: if self.eventLoc:
lats, lons = self.eventLoc lats, lons = self.eventLoc
self.sc_event = self.ax.scatter(lons, lats, s=5 * self.pointsize, facecolor='red', zorder=11, self.sc_event = self.basemap.scatter(lons, lats, s=2*self.pointsize, facecolor='red',
label='Event (might be outside map region)', marker='*', latlon=True, zorder=11, label='Event (might be outside map region)')
edgecolors='black',
transform=ccrs.PlateCarree())
def scatter_picked_stations(self): def scatter_picked_stations(self):
picks, uncertainties, lats, lons = self.get_picks_lat_lon() picks, uncertainties, lats, lons = self.get_picks_lat_lon()
@@ -588,21 +471,24 @@ class Array_map(QtWidgets.QWidget):
phase = self.comboBox_phase.currentText() phase = self.comboBox_phase.currentText()
timeerrors = self.parameter['timeerrors{}'.format(phase)] timeerrors = self.parameter['timeerrors{}'.format(phase)]
sizes = np.array([self.pointsize * (5. - get_quality_class(uncertainty, timeerrors)) sizes = np.array([self.pointsize * ((5. - get_quality_class(uncertainty, timeerrors)))
for uncertainty in uncertainties]) for uncertainty in uncertainties])
cmap = self.get_colormap() cmap = self.get_colormap()
# workaround because of an issue with latlon transformation of arrays with len <3
vmin = vmax = None if len(lons) <= 2 and len(lats) <= 2:
if self.subtract_mean_cb.isChecked(): self.sc_picked = self.basemap.scatter(lons[0], lats[0], s=sizes, edgecolors='white', cmap=cmap,
vmin, vmax = -self.get_residuals_absmax(), self.get_residuals_absmax() c=picks[0], latlon=True, zorder=11)
if len(lons) == 2 and len(lats) == 2:
self.sc_picked = self.ax.scatter(lons, lats, s=sizes, edgecolors='white', cmap=cmap, vmin=vmin, vmax=vmax, self.sc_picked = self.basemap.scatter(lons[1], lats[1], s=sizes, edgecolors='white', cmap=cmap,
c=picks, zorder=11, label='Picked', transform=ccrs.PlateCarree()) c=picks[1], latlon=True, zorder=11)
if len(lons) > 2 and len(lats) > 2:
self.sc_picked = self.basemap.scatter(lons, lats, s=sizes, edgecolors='white', cmap=cmap,
c=picks, latlon=True, zorder=11, label='Picked')
def annotate_ax(self): def annotate_ax(self):
self.annotations = [] self.annotations = []
stations, ys, xs = self.get_st_lat_lon_for_plot() stations, xs, ys = self.get_st_x_y_for_plot()
# MP MP testing station highlighting if they have high impact on mean gradient of color map # MP MP testing station highlighting if they have high impact on mean gradient of color map
# if self.picks_rel: # if self.picks_rel:
# self.test_gradient() # self.test_gradient()
@@ -615,21 +501,16 @@ class Array_map(QtWidgets.QWidget):
color = 'lightgrey' color = 'lightgrey'
if st in self.marked_stations: if st in self.marked_stations:
color = 'red' color = 'red'
self.annotations.append( self.annotations.append(self.main_ax.annotate(' %s' % st, xy=(x, y),
self.ax.annotate(f'{st}', xy=(x + 0.003, y + 0.003), fontsize=self.pointsize / 4., fontsize=self.pointsize/4., fontweight='semibold',
fontweight='semibold', color=color, alpha=0.8, color=color, zorder=14))
transform=ccrs.PlateCarree(), zorder=14, self.legend = self.main_ax.legend(loc=1)
path_effects=[PathEffects.withStroke( self.legend.get_frame().set_facecolor((1, 1, 1, 0.75))
linewidth=self.pointsize / 15., foreground='k')]))
self.legend = self.ax.legend(loc=1, framealpha=1)
self.legend.set_zorder(100)
self.legend.get_frame().set_facecolor((1, 1, 1, 0.95))
def add_cbar(self, label): def add_cbar(self, label):
self.cbax_bg = inset_axes(self.ax, width="6%", height="75%", loc=5) self.cbax_bg = inset_axes(self.main_ax, width="6%", height="75%", loc=5)
cbax = inset_axes(self.ax, width='2%', height='70%', loc=5) cbax = inset_axes(self.main_ax, width='2%', height='70%', loc=5)
cbar = self.ax.figure.colorbar(self.sc_picked, cax=cbax) cbar = self.main_ax.figure.colorbar(self.sc_picked, cax=cbax)
cbar.set_label(label) cbar.set_label(label)
cbax.yaxis.tick_left() cbax.yaxis.tick_left()
cbax.yaxis.set_label_position('left') cbax.yaxis.set_label_position('left')
@@ -640,7 +521,6 @@ class Array_map(QtWidgets.QWidget):
self.cbax_bg.patch.set_facecolor((1, 1, 1, 0.75)) self.cbax_bg.patch.set_facecolor((1, 1, 1, 0.75))
return cbar return cbar
# handle drawings -----------------------------------------------------
def refresh_drawings(self, picks=None, autopicks=None): def refresh_drawings(self, picks=None, autopicks=None):
self.picks_dict = picks self.picks_dict = picks
self.autopicks_dict = autopicks self.autopicks_dict = autopicks
@@ -674,15 +554,13 @@ class Array_map(QtWidgets.QWidget):
if picks_available: if picks_available:
self.scatter_picked_stations() self.scatter_picked_stations()
if hasattr(self, 'sc_picked'): if hasattr(self, 'sc_picked'):
self.cbar = self.add_cbar( self.cbar = self.add_cbar(label='Time relative to first onset ({}) [s]'.format(self._earliest_picktime))
label='Time relative to reference onset ({}) [s]'.format(self._reference_picktime)
)
self.comboBox_phase.setEnabled(True) self.comboBox_phase.setEnabled(True)
else: else:
self.comboBox_phase.setEnabled(False) self.comboBox_phase.setEnabled(False)
if self.annotate: if self.annotate:
self.annotate_ax() self.annotate_ax()
self.plotWidget.draw_idle() self.canvas.draw()
def remove_drawings(self): def remove_drawings(self):
self.remove_annotations() self.remove_annotations()
@@ -706,7 +584,7 @@ class Array_map(QtWidgets.QWidget):
self.remove_contourf() self.remove_contourf()
del self.contourf del self.contourf
if hasattr(self, 'cid'): if hasattr(self, 'cid'):
self.plotWidget.mpl_disconnect(self.cid) self.canvas.mpl_disconnect(self.cid)
del self.cid del self.cid
try: try:
self.sc.remove() self.sc.remove()
@@ -716,7 +594,7 @@ class Array_map(QtWidgets.QWidget):
self.legend.remove() self.legend.remove()
except Exception as e: except Exception as e:
print('Warning: could not remove legend. Reason: {}'.format(e)) print('Warning: could not remove legend. Reason: {}'.format(e))
self.plotWidget.draw_idle() self.canvas.draw()
def remove_contourf(self): def remove_contourf(self):
for item in self.contourf.collections: for item in self.contourf.collections:
@@ -727,16 +605,34 @@ class Array_map(QtWidgets.QWidget):
annotation.remove() annotation.remove()
self.annotations = [] self.annotations = []
def saveFigure(self): def zoom(self, event):
if self.canvas.fig: map = self.basemap
fd = QtWidgets.QFileDialog() xlim = map.ax.get_xlim()
fname, filter = fd.getSaveFileName(self.parent(), filter='Images (*.png *.svg *.jpg)') ylim = map.ax.get_ylim()
if not fname: x, y = event.xdata, event.ydata
return zoom = {'up': 1. / 2.,
if not any([fname.endswith(item) for item in ['.png', '.svg', '.jpg']]): 'down': 2.}
fname += '.png'
self.canvas.fig.savefig(fname) if not event.xdata or not event.ydata:
return
if event.button in zoom:
factor = zoom[event.button]
xdiff = (xlim[1] - xlim[0]) * factor
xl = x - 0.5 * xdiff
xr = x + 0.5 * xdiff
ydiff = (ylim[1] - ylim[0]) * factor
yb = y - 0.5 * ydiff
yt = y + 0.5 * ydiff
if xl < map.xmin or yb < map.ymin or xr > map.xmax or yt > map.ymax:
xl, xr = map.xmin, map.xmax
yb, yt = map.ymin, map.ymax
map.ax.set_xlim(xl, xr)
map.ax.set_ylim(yb, yt)
map.ax.figure.canvas.draw()
def _warn(self, message): def _warn(self, message):
self.qmb = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Icon.Warning, 'Warning', message) self.qmb = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Icon.Warning,
'Warning', message)
self.qmb.show() self.qmb.show()
+1 -2
View File
@@ -2,13 +2,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
try: try:
# noinspection PyUnresolvedReferences
from urllib2 import urlopen from urllib2 import urlopen
except: except:
from urllib.request import urlopen from urllib.request import urlopen
def checkurl(url='https://git.geophysik.ruhr-uni-bochum.de/marcel/pylot/'): def checkurl(url='https://ariadne.geophysik.ruhr-uni-bochum.de/trac/PyLoT/'):
""" """
check if URL is available check if URL is available
:param url: url :param url: url
+25 -44
View File
@@ -2,11 +2,9 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import glob import glob
import logging import numpy as np
import os import os
import sys import sys
import numpy as np
from obspy import UTCDateTime, read_inventory, read from obspy import UTCDateTime, read_inventory, read
from obspy.io.xseed import Parser from obspy.io.xseed import Parser
@@ -27,10 +25,6 @@ class Metadata(object):
# saves which metadata files are from obspy dmt # saves which metadata files are from obspy dmt
self.obspy_dmt_invs = [] self.obspy_dmt_invs = []
if inventory: if inventory:
# make sure that no accidental backslashes mess up the path
if isinstance(inventory, str):
inventory = inventory.replace('\\', '/')
inventory = os.path.abspath(inventory)
if os.path.isdir(inventory): if os.path.isdir(inventory):
self.add_inventory(inventory) self.add_inventory(inventory)
if os.path.isfile(inventory): if os.path.isfile(inventory):
@@ -52,15 +46,13 @@ class Metadata(object):
def __repr__(self): def __repr__(self):
return self.__str__() return self.__str__()
def add_inventory(self, path_to_inventory, obspy_dmt_inv=False): def add_inventory(self, path_to_inventory, obspy_dmt_inv = False):
""" """
Add path to list of inventories. Add path to list of inventories.
:param path_to_inventory: Path to a folder :param path_to_inventory: Path to a folder
:type path_to_inventory: str :type path_to_inventory: str
:return: None :return: None
""" """
path_to_inventory = path_to_inventory.replace('\\', '/')
path_to_inventory = os.path.abspath(path_to_inventory)
assert (os.path.isdir(path_to_inventory)), '{} is no directory'.format(path_to_inventory) assert (os.path.isdir(path_to_inventory)), '{} is no directory'.format(path_to_inventory)
if path_to_inventory not in self.inventories: if path_to_inventory not in self.inventories:
self.inventories.append(path_to_inventory) self.inventories.append(path_to_inventory)
@@ -91,10 +83,10 @@ class Metadata(object):
print('Path {} not in inventories list.'.format(path_to_inventory)) print('Path {} not in inventories list.'.format(path_to_inventory))
return return
self.inventories.remove(path_to_inventory) self.inventories.remove(path_to_inventory)
for filename in list(self.inventory_files.keys()): for filename in self.inventory_files.keys():
if filename.startswith(path_to_inventory): if filename.startswith(path_to_inventory):
del (self.inventory_files[filename]) del (self.inventory_files[filename])
for seed_id in list(self.seed_ids.keys()): for seed_id in self.seed_ids.keys():
if self.seed_ids[seed_id].startswith(path_to_inventory): if self.seed_ids[seed_id].startswith(path_to_inventory):
del (self.seed_ids[seed_id]) del (self.seed_ids[seed_id])
# have to clean self.stations_dict as well # have to clean self.stations_dict as well
@@ -196,11 +188,7 @@ class Metadata(object):
metadata = self.get_metadata(seed_id, time) metadata = self.get_metadata(seed_id, time)
if not metadata: if not metadata:
return return
try: return metadata['data'].get_coordinates(seed_id, time)
return metadata['data'].get_coordinates(seed_id, time)
# no specific exception defined in obspy inventory
except Exception as e:
logging.warning(f'Could not get metadata for {seed_id}')
def get_all_coordinates(self): def get_all_coordinates(self):
def stat_info_from_parser(parser): def stat_info_from_parser(parser):
@@ -220,10 +208,9 @@ class Metadata(object):
network_name = network.code network_name = network.code
if not station_name in self.stations_dict.keys(): if not station_name in self.stations_dict.keys():
st_id = '{}.{}'.format(network_name, station_name) st_id = '{}.{}'.format(network_name, station_name)
self.stations_dict[st_id] = {'latitude': station.latitude, self.stations_dict[st_id] = {'latitude': station[0].latitude,
'longitude': station.longitude, 'longitude': station[0].longitude,
'elevation': station.elevation} 'elevation': station[0].elevation}
read_stat = {'xml': stat_info_from_inventory, read_stat = {'xml': stat_info_from_inventory,
'dless': stat_info_from_parser} 'dless': stat_info_from_parser}
@@ -268,6 +255,9 @@ class Metadata(object):
if not fnames: if not fnames:
# search for station name in filename # search for station name in filename
fnames = glob.glob(os.path.join(path_to_inventory, '*' + station + '*')) fnames = glob.glob(os.path.join(path_to_inventory, '*' + station + '*'))
if not fnames:
# search for network name in filename
fnames = glob.glob(os.path.join(path_to_inventory, '*' + network + '*'))
if not fnames: if not fnames:
if self.verbosity: if self.verbosity:
print('Could not find filenames matching station name, network name or seed id') print('Could not find filenames matching station name, network name or seed id')
@@ -287,7 +277,6 @@ class Metadata(object):
self.seed_ids[station_seed_id] = fname self.seed_ids[station_seed_id] = fname
return True return True
except Exception as e: except Exception as e:
logging.warning(e)
continue continue
print('Could not find metadata for station_seed_id {} in path {}'.format(station_seed_id, path_to_inventory)) print('Could not find metadata for station_seed_id {} in path {}'.format(station_seed_id, path_to_inventory))
@@ -362,25 +351,25 @@ def check_time(datetime):
:type datetime: list :type datetime: list
:return: returns True if Values are in supposed range, returns False otherwise :return: returns True if Values are in supposed range, returns False otherwise
>>> check_time([1999, 1, 1, 23, 59, 59, 999000]) >>> check_time([1999, 01, 01, 23, 59, 59, 999000])
True True
>>> check_time([1999, 1, 1, 23, 59, 60, 999000]) >>> check_time([1999, 01, 01, 23, 59, 60, 999000])
False False
>>> check_time([1999, 1, 1, 23, 59, 59, 1000000]) >>> check_time([1999, 01, 01, 23, 59, 59, 1000000])
False False
>>> check_time([1999, 1, 1, 23, 60, 59, 999000]) >>> check_time([1999, 01, 01, 23, 60, 59, 999000])
False False
>>> check_time([1999, 1, 1, 23, 60, 59, 999000]) >>> check_time([1999, 01, 01, 23, 60, 59, 999000])
False False
>>> check_time([1999, 1, 1, 24, 59, 59, 999000]) >>> check_time([1999, 01, 01, 24, 59, 59, 999000])
False False
>>> check_time([1999, 1, 31, 23, 59, 59, 999000]) >>> check_time([1999, 01, 31, 23, 59, 59, 999000])
True True
>>> check_time([1999, 2, 30, 23, 59, 59, 999000]) >>> check_time([1999, 02, 30, 23, 59, 59, 999000])
False False
>>> check_time([1999, 2, 29, 23, 59, 59, 999000]) >>> check_time([1999, 02, 29, 23, 59, 59, 999000])
False False
>>> check_time([2000, 2, 29, 23, 59, 59, 999000]) >>> check_time([2000, 02, 29, 23, 59, 59, 999000])
True True
>>> check_time([2000, 13, 29, 23, 59, 59, 999000]) >>> check_time([2000, 13, 29, 23, 59, 59, 999000])
False False
@@ -392,7 +381,6 @@ def check_time(datetime):
return False return False
# TODO: change root to datapath
def get_file_list(root_dir): def get_file_list(root_dir):
""" """
Function uses a directorie to get all the *.gse files from it. Function uses a directorie to get all the *.gse files from it.
@@ -456,7 +444,7 @@ def evt_head_check(root_dir, out_dir=None):
""" """
if not out_dir: if not out_dir:
print('WARNING files are going to be overwritten!') print('WARNING files are going to be overwritten!')
inp = str(input('Continue? [y/N]')) inp = str(raw_input('Continue? [y/N]'))
if not inp == 'y': if not inp == 'y':
sys.exit() sys.exit()
filelist = get_file_list(root_dir) filelist = get_file_list(root_dir)
@@ -652,8 +640,6 @@ def restitute_data(data, metadata, unit='VEL', force=False, ncores=0):
""" """
# data = remove_underscores(data) # data = remove_underscores(data)
if not data:
return
# loop over traces # loop over traces
input_tuples = [] input_tuples = []
@@ -661,14 +647,9 @@ def restitute_data(data, metadata, unit='VEL', force=False, ncores=0):
input_tuples.append((tr, metadata, unit, force)) input_tuples.append((tr, metadata, unit, force))
data.remove(tr) data.remove(tr)
if ncores == 0: pool = gen_Pool(ncores)
result = [] result = pool.imap_unordered(restitute_trace, input_tuples)
for input_tuple in input_tuples: pool.close()
result.append(restitute_trace(input_tuple))
else:
pool = gen_Pool(ncores)
result = pool.imap_unordered(restitute_trace, input_tuples)
pool.close()
for tr, remove_trace in result: for tr, remove_trace in result:
if not remove_trace: if not remove_trace:
+4 -2
View File
@@ -26,7 +26,9 @@ elif system_name == "Windows":
# suffix for phase name if not phase identified by last letter (P, p, etc.) # suffix for phase name if not phase identified by last letter (P, p, etc.)
ALTSUFFIX = ['diff', 'n', 'g', '1', '2', '3'] ALTSUFFIX = ['diff', 'n', 'g', '1', '2', '3']
FILTERDEFAULTS = readDefaultFilterInformation() FILTERDEFAULTS = readDefaultFilterInformation(os.path.join(os.path.expanduser('~'),
'.pylot',
'pylot.in'))
TIMEERROR_DEFAULTS = os.path.join(os.path.expanduser('~'), TIMEERROR_DEFAULTS = os.path.join(os.path.expanduser('~'),
'.pylot', '.pylot',
@@ -35,7 +37,7 @@ TIMEERROR_DEFAULTS = os.path.join(os.path.expanduser('~'),
OUTPUTFORMATS = {'.xml': 'QUAKEML', OUTPUTFORMATS = {'.xml': 'QUAKEML',
'.cnv': 'CNV', '.cnv': 'CNV',
'.obs': 'NLLOC_OBS', '.obs': 'NLLOC_OBS',
'_focmec.in': 'FOCMEC', '.focmec': 'FOCMEC',
'.pha': 'HYPODD'} '.pha': 'HYPODD'}
LOCTOOLS = dict(nll=nll, hyposat=hyposat, velest=velest, hypo71=hypo71, hypodd=hypodd) LOCTOOLS = dict(nll=nll, hyposat=hyposat, velest=velest, hypo71=hypo71, hypodd=hypodd)
+10 -9
View File
@@ -2,7 +2,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os import os
from obspy import UTCDateTime from obspy import UTCDateTime
from obspy.core.event import Event as ObsPyEvent from obspy.core.event import Event as ObsPyEvent
from obspy.core.event import Origin, ResourceIdentifier from obspy.core.event import Origin, ResourceIdentifier
@@ -26,7 +25,9 @@ class Event(ObsPyEvent):
# initialize super class # 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.path = path
self.datapath = os.path.split(path)[0] # path.split('/')[-3] self.database = path.split('/')[-2]
self.datapath = path.split('/')[-3]
self.rootpath = '/' + os.path.join(*path.split('/')[:-3])
self.pylot_autopicks = {} self.pylot_autopicks = {}
self.pylot_picks = {} self.pylot_picks = {}
self.notes = '' self.notes = ''
@@ -72,7 +73,7 @@ class Event(ObsPyEvent):
text = lines[0] text = lines[0]
self.addNotes(text) self.addNotes(text)
try: try:
datetime = UTCDateTime(self.path.split('/')[-1]) datetime = UTCDateTime(path.split('/')[-1])
origin = Origin(resource_id=self.resource_id, time=datetime, latitude=0, longitude=0, depth=0) origin = Origin(resource_id=self.resource_id, time=datetime, latitude=0, longitude=0, depth=0)
self.origins.append(origin) self.origins.append(origin)
except: except:
@@ -295,13 +296,13 @@ class Event(ObsPyEvent):
:rtype: None :rtype: None
""" """
try: try:
import pickle import cPickle
except ImportError: except ImportError:
import _pickle as pickle import _pickle as cPickle
try: try:
outfile = open(filename, 'wb') outfile = open(filename, 'wb')
pickle.dump(self, outfile, -1) cPickle.dump(self, outfile, -1)
self.dirty = False self.dirty = False
except Exception as e: except Exception as e:
print('Could not pickle PyLoT event. Reason: {}'.format(e)) print('Could not pickle PyLoT event. Reason: {}'.format(e))
@@ -316,11 +317,11 @@ class Event(ObsPyEvent):
:rtype: Event :rtype: Event
""" """
try: try:
import pickle import cPickle
except ImportError: except ImportError:
import _pickle as pickle import _pickle as cPickle
infile = open(filename, 'rb') infile = open(filename, 'rb')
event = pickle.load(infile) event = cPickle.load(infile)
event.dirty = False event.dirty = False
print('Loaded %s' % filename) print('Loaded %s' % filename)
return event return event
+16 -38
View File
@@ -3,37 +3,24 @@
# small script that creates array maps for each event within a previously generated PyLoT project # small script that creates array maps for each event within a previously generated PyLoT project
import os import os
num_thread = "16"
os.environ["OMP_NUM_THREADS"] = num_thread
os.environ["OPENBLAS_NUM_THREADS"] = num_thread
os.environ["MKL_NUM_THREADS"] = num_thread
os.environ["VECLIB_MAXIMUM_THREADS"] = num_thread
os.environ["NUMEXPR_NUM_THREADS"] = num_thread
os.environ["NUMEXPR_MAX_THREADS"] = num_thread
import multiprocessing import multiprocessing
import sys
import glob
import matplotlib
matplotlib.use('Qt5Agg')
sys.path.append(os.path.join('/'.join(sys.argv[0].split('/')[:-1]), '../../..'))
from PyLoT import Project from PyLoT import Project
from pylot.core.util.dataprocessing import Metadata from pylot.core.util.dataprocessing import Metadata
from pylot.core.util.array_map import Array_map from pylot.core.util.array_map import Array_map
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import argparse
def main(project_file_path, manual=False, auto=True, file_format='png', f_ext='', ncores=None): def main(project_file_path, manual=False, auto=True, file_format='png', f_ext='', ncores=None):
project = Project.load(project_file_path) project = Project.load(project_file_path)
nEvents = len(project.eventlist) nEvents = len(project.eventlist)
input_list = [] input_list = []
print('\n')
for index, event in enumerate(project.eventlist): for index, event in enumerate(project.eventlist):
# MP MP TESTING +++
#if not eventdir.endswith('20170908_044946.a'):
# continue
# MP MP ----
kwargs = dict(project=project, event=event, nEvents=nEvents, index=index, manual=manual, auto=auto, kwargs = dict(project=project, event=event, nEvents=nEvents, index=index, manual=manual, auto=auto,
file_format=file_format, f_ext=f_ext) file_format=file_format, f_ext=f_ext)
input_list.append(kwargs) input_list.append(kwargs)
@@ -42,21 +29,15 @@ def main(project_file_path, manual=False, auto=True, file_format='png', f_ext=''
for item in input_list: for item in input_list:
array_map_worker(item) array_map_worker(item)
else: else:
pool = multiprocessing.Pool(ncores, maxtasksperchild=1000) pool = multiprocessing.Pool(ncores)
pool.map(array_map_worker, input_list) result = pool.map(array_map_worker, input_list)
pool.close() pool.close()
pool.join() pool.join()
def array_map_worker(input_dict): def array_map_worker(input_dict):
event = input_dict['event'] event = input_dict['event']
eventdir = event.path eventdir = event.path
print('Working on event: {} ({}/{})'.format(eventdir, input_dict['index'] + 1, input_dict['nEvents'])) print('Working on event: {} ({}/{})'.format(eventdir, input_dict['index'] + 1, input_dict['nEvents']))
xml_picks = glob.glob(os.path.join(eventdir, f'*{input_dict["f_ext"]}.xml'))
if not len(xml_picks):
print('Event {} does not have any picks associated with event file extension {}'.format(eventdir,
input_dict['f_ext']))
return
# check for picks # check for picks
manualpicks = event.getPicks() manualpicks = event.getPicks()
autopicks = event.getAutopicks() autopicks = event.getAutopicks()
@@ -70,12 +51,11 @@ def array_map_worker(input_dict):
continue continue
if not metadata: if not metadata:
metadata = Metadata(inventory=metadata_path, verbosity=0) metadata = Metadata(inventory=metadata_path, verbosity=0)
# create figure to plot on # create figure to plot on
fig, ax = plt.subplots(figsize=(15, 9)) fig = plt.figure(figsize=(16,9))
# create array map object # create array map object
map = Array_map(None, metadata, parameter=input_dict['project'].parameter, axes=ax, map = Array_map(None, metadata, parameter=input_dict['project'].parameter, figure=fig,
width=2.13e6, height=1.2e6, pointsize=25., linewidth=1.0) width=2.13e6, height=1.2e6, pointsize=15., linewidth=1.0)
# set combobox to auto/manual to plot correct pick type # set combobox to auto/manual to plot correct pick type
map.comboBox_am.setCurrentIndex(map.comboBox_am.findText(pick_type)) map.comboBox_am.setCurrentIndex(map.comboBox_am.findText(pick_type))
# add picks to map and save file # add picks to map and save file
@@ -85,13 +65,11 @@ def array_map_worker(input_dict):
fig.savefig(fpath_out, dpi=300.) fig.savefig(fpath_out, dpi=300.)
print('Wrote file: {}'.format(fpath_out)) print('Wrote file: {}'.format(fpath_out))
if __name__ == '__main__': if __name__ == '__main__':
cl = argparse.ArgumentParser() dataroot = '/home/marcel'
cl.add_argument('--dataroot', help='Directory containing the PyLoT .plp file', type=str) infiles=['alparray_all_events_0.03-0.1_mantle_correlated_v3.plp']
cl.add_argument('--infiles', help='.plp files to use', nargs='+')
cl.add_argument('--ncores', hepl='Specify number of parallel processes', type=int, default=1)
args = cl.parse_args()
for infile in args.infiles: for infile in infiles:
main(os.path.join(args.dataroot, infile), f_ext='_correlated_0.03-0.1', ncores=args.ncores) main(os.path.join(dataroot, infile), f_ext='_correlated_0.1Hz', ncores=10)
#main('E:\Shared\AlpArray\\test_aa.plp', f_ext='_correlated_0.5Hz', ncores=1)
#main('/home/marcel/alparray_m6.5-6.9_mantle_correlated_v3.plp', f_ext='_correlated_0.5Hz')
+13 -14
View File
@@ -1,17 +1,17 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os import os
from functools import lru_cache
try: try:
import pyqtgraph as pg import pyqtgraph as pg
except Exception as e: except Exception as e:
print('Warning: Could not import module pyqtgraph.') print('Warning: Could not import module pyqtgraph.')
try: try:
from PySide2 import QtCore from PySide import QtCore
except Exception as e: except Exception as e:
print('Warning: Could not import module QtCore.') print('Warning: Could not import module QtCore.')
from pylot.core.util.utils import pick_color from pylot.core.util.utils import pick_color
@@ -26,14 +26,14 @@ def pick_linestyle_pg(picktype, key):
:return: Qt line style parameters :return: Qt line style parameters
:rtype: :rtype:
""" """
linestyles_manu = {'mpp': (QtCore.Qt.SolidLine, 2), linestyles_manu = {'mpp': (QtCore.Qt.SolidLine, 2.),
'epp': (QtCore.Qt.DashLine, 1), 'epp': (QtCore.Qt.DashLine, 1.),
'lpp': (QtCore.Qt.DashLine, 1), 'lpp': (QtCore.Qt.DashLine, 1.),
'spe': (QtCore.Qt.DashLine, 1)} 'spe': (QtCore.Qt.DashLine, 1.)}
linestyles_auto = {'mpp': (QtCore.Qt.DotLine, 2), linestyles_auto = {'mpp': (QtCore.Qt.DotLine, 2.),
'epp': (QtCore.Qt.DashDotLine, 1), 'epp': (QtCore.Qt.DashDotLine, 1.),
'lpp': (QtCore.Qt.DashDotLine, 1), 'lpp': (QtCore.Qt.DashDotLine, 1.),
'spe': (QtCore.Qt.DashDotLine, 1)} 'spe': (QtCore.Qt.DashDotLine, 1.)}
linestyles = {'manual': linestyles_manu, linestyles = {'manual': linestyles_manu,
'auto': linestyles_auto} 'auto': linestyles_auto}
return linestyles[picktype][key] return linestyles[picktype][key]
@@ -49,7 +49,7 @@ def which(program, parameter):
:rtype: str :rtype: str
""" """
try: try:
from PySide2.QtCore import QSettings from PySide.QtCore import QSettings
settings = QSettings() settings = QSettings()
for key in settings.allKeys(): for key in settings.allKeys():
if 'binPath' in key: if 'binPath' in key:
@@ -57,7 +57,7 @@ def which(program, parameter):
nllocpath = ":" + parameter.get('nllocbin') nllocpath = ":" + parameter.get('nllocbin')
os.environ['PATH'] += nllocpath os.environ['PATH'] += nllocpath
except Exception as e: except Exception as e:
print(e) print(e.message)
def is_exe(fpath): def is_exe(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK) return os.path.exists(fpath) and os.access(fpath, os.X_OK)
@@ -81,7 +81,6 @@ def which(program, parameter):
return None return None
@lru_cache(maxsize=128)
def make_pen(picktype, phase, key, quality): def make_pen(picktype, phase, key, quality):
""" """
Make PyQtGraph.QPen Make PyQtGraph.QPen
@@ -101,4 +100,4 @@ def make_pen(picktype, phase, key, quality):
rgba = pick_color(picktype, phase, quality) rgba = pick_color(picktype, phase, quality)
linestyle, width = pick_linestyle_pg(picktype, key) linestyle, width = pick_linestyle_pg(picktype, key)
pen = pg.mkPen(rgba, width=width, style=linestyle) pen = pg.mkPen(rgba, width=width, style=linestyle)
return pen return pen
+364
View File
@@ -0,0 +1,364 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import obspy
from PySide2 import QtWidgets
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import cartopy
import cartopy.feature as cpf
from pylot.core.util.widgets import PickDlg
from scipy.interpolate import griddata
plt.interactive(False)
class map_projection(QtWidgets.QWidget):
def __init__(self, parent, figure=None):
'''
:param: picked, can be False, auto, manual
:value: str
'''
QtWidgets.QWidget.__init__(self)
self._parent = parent
self.metadata = parent.metadata
self.parser = parent.metadata[1]
self.picks = None
self.picks_dict = None
self.eventLoc = None
self.figure = figure
self.init_graphics()
self.init_stations()
self.init_basemap()
self.init_map()
# self.show()
def init_map(self):
self.init_lat_lon_dimensions()
self.init_lat_lon_grid()
self.connectSignals()
self.draw_everything()
def onpick(self, event):
ind = event.ind
button = event.mouseevent.button
if ind == [] or not button == 1:
return
data = self._parent.get_data().getWFData()
for index in ind:
station = str(self.station_names[index].split('.')[-1])
try:
pickDlg = PickDlg(self, parameter=self._parent._inputs,
data=data.select(station=station),
station=station,
picks=self._parent.get_current_event().getPick(station),
autopicks=self._parent.get_current_event().getAutopick(station))
except Exception as e:
message = 'Could not generate Plot for station {st}.\n {er}'.format(st=station, er=e)
self._warn(message)
print(message, e)
return
pyl_mw = self._parent
try:
if pickDlg.exec_():
pyl_mw.setDirty(True)
pyl_mw.update_status('picks accepted ({0})'.format(station))
replot = pyl_mw.get_current_event().setPick(station, pickDlg.getPicks())
self._refresh_drawings()
if replot:
pyl_mw.plotWaveformData()
pyl_mw.drawPicks()
pyl_mw.draw()
else:
pyl_mw.drawPicks(station)
pyl_mw.draw()
else:
pyl_mw.update_status('picks discarded ({0})'.format(station))
except Exception as e:
message = 'Could not save picks for station {st}.\n{er}'.format(st=station, er=e)
self._warn(message)
print(message, e)
def connectSignals(self):
self.comboBox_phase.currentIndexChanged.connect(self._refresh_drawings)
self.zoom_id = self.main_ax.figure.canvas.mpl_connect('scroll_event', self.zoom)
def init_graphics(self):
if not self.figure:
if not hasattr(self._parent, 'am_figure'):
self.figure = plt.figure()
self.toolbar = NavigationToolbar(self.figure.canvas, self)
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
self.main_box = QtWidgets.QVBoxLayout()
self.setLayout(self.main_box)
self.top_row = QtWidgets.QHBoxLayout()
self.main_box.addLayout(self.top_row)
self.comboBox_phase = QtWidgets.QComboBox()
self.comboBox_phase.insertItem(0, 'P')
self.comboBox_phase.insertItem(1, 'S')
self.comboBox_am = QtWidgets.QComboBox()
self.comboBox_am.insertItem(0, 'auto')
self.comboBox_am.insertItem(1, 'manual')
self.top_row.addWidget(QtWidgets.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.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 = []
for station in parser.stations:
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)
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
self.lon = lon
def init_picks(self):
phase = self.comboBox_phase.currentText()
def get_picks(station_names):
picks = []
for station in station_names:
try:
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_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:
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 = []
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 = []
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):
def get_lon_lat_dim(lon, lat):
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_basemap(self, resolution='l'):
ax = self.main_ax(projection=cartopy.crs.PlateCarree())
ax.add_feature(cpf.LAND)
ax.add_feature(cpf.OCEAN)
ax.add_feature(cpf.COASTLINE)
ax.add_feature(cpf.BORDERS, linestyle=':')
ax.add_feature(cpf.LAKES, alpha=0.5)
ax.add_feature(cpf.RIVERS)
ax.set_extent([min(self.lon), max(self.lon), min(self.lat), max(self.lat)])
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
lataxis = np.arange(min(lat), max(lat), steplat)
lonaxis = np.arange(min(lon), max(lon), steplon)
return lataxis, lonaxis
def get_lat_lon_grid(lataxis, lonaxis):
longrid, latgrid = np.meshgrid(lonaxis, lataxis)
return latgrid, longrid
self.lataxis, self.lonaxis = get_lat_lon_axis(self.lat, self.lon)
self.latgrid, self.longrid = get_lat_lon_grid(self.lataxis, self.lonaxis)
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') ##################
def draw_contour_filled(self, nlevel='50'):
levels = np.linspace(min(self.picks_no_nan), max(self.picks_no_nan), nlevel)
self.contourf = self.main_ax.contourf(self.longrid, self.latgrid, self.picksgrid_no_nan,
levels, latlon=True, zorder=9, alpha=0.5)
def scatter_all_stations(self):
self.sc = self.main_ax.scatter(self.lon, self.lat, s=50, facecolor='none', latlon=True,
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
self.sc_event = self.main_ax.scatter(lon, lat, s=100, facecolor='red',
latlon=True, zorder=11, label='Event (might be outside map region)')
def scatter_picked_stations(self):
lon = self.lon_no_nan
lat = self.lat_no_nan
# 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.main_ax.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:
self.sc_picked = self.main_ax.scatter(lon[1], lat[1], s=50, facecolor='white',
c=self.picks_no_nan[1], latlon=True, zorder=11)
else:
self.sc_picked = self.main_ax.scatter(lon, lat, s=50, facecolor='white',
c=self.picks_no_nan, latlon=True, zorder=11, label='Picked')
def annotate_ax(self):
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(loc=1)
def add_cbar(self, label):
cbar = self.main_ax.figure.colorbar(self.sc_picked, fraction=0.025)
cbar.set_label(label)
return cbar
def refresh_drawings(self, picks=None):
self.picks_dict = picks
self._refresh_drawings()
def _refresh_drawings(self):
self.remove_drawings()
self.draw_everything()
def draw_everything(self):
if self.picks_dict:
self.init_picks()
self.init_picks_active()
self.init_stations_active()
if len(self.picks_no_nan) >= 3:
self.init_picksgrid()
self.draw_contour_filled()
self.scatter_all_stations()
if self.picks_dict:
self.scatter_picked_stations()
self.cbar = self.add_cbar(label='Time relative to first onset [s]')
self.comboBox_phase.setEnabled(True)
else:
self.comboBox_phase.setEnabled(False)
self.annotate_ax()
self.canvas.draw()
def remove_drawings(self):
if hasattr(self, 'sc_picked'):
self.sc_picked.remove()
del (self.sc_picked)
if hasattr(self, 'sc_event'):
self.sc_event.remove()
del (self.sc_event)
if hasattr(self, 'cbar'):
self.cbar.remove()
del (self.cbar)
if hasattr(self, 'contourf'):
self.remove_contourf()
del (self.contourf)
if hasattr(self, 'cid'):
self.canvas.mpl_disconnect(self.cid)
del (self.cid)
try:
self.sc.remove()
except Exception as e:
print('Warning: could not remove station scatter plot.\nReason: {}'.format(e))
try:
self.legend.remove()
except Exception as e:
print('Warning: could not remove legend. Reason: {}'.format(e))
self.canvas.draw()
def remove_contourf(self):
for item in self.contourf.collections:
item.remove()
def remove_annotations(self):
for annotation in self.annotations:
annotation.remove()
def zoom(self, event):
map = self.main_ax
xlim = map.ax.get_xlim()
ylim = map.ax.get_ylim()
x, y = event.xdata, event.ydata
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
xl = x - 0.5 * xdiff
xr = x + 0.5 * xdiff
ydiff = (ylim[1] - ylim[0]) * factor
yb = y - 0.5 * ydiff
yt = y + 0.5 * ydiff
if xl < map.xmin or yb < map.ymin or xr > map.xmax or yt > map.ymax:
xl, xr = map.xmin, map.xmax
yb, yt = map.ymin, map.ymax
map.ax.set_xlim(xl, xr)
map.ax.set_ylim(yb, yt)
map.ax.figure.canvas.draw()
def _warn(self, message):
self.qmb = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Icon.Warning,
'Warning', message)
self.qmb.show()
+6 -15
View File
@@ -2,7 +2,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os import os
from obspy import UTCDateTime from obspy import UTCDateTime
@@ -35,25 +34,17 @@ def qml_from_obspyDMT(path):
if not os.path.exists(path): if not os.path.exists(path):
return IOError('Could not find Event at {}'.format(path)) return IOError('Could not find Event at {}'.format(path))
infile = open(path, 'rb')
with open(path, 'rb') as infile: event_dmt = pickle.load(infile)#, fix_imports=True)
event_dmt = pickle.load(infile) # , fix_imports=True)
event_dmt['origin_id'].id = str(event_dmt['origin_id'].id) event_dmt['origin_id'].id = str(event_dmt['origin_id'].id)
ev = Event(resource_id=event_dmt['event_id']) ev = Event(resource_id=event_dmt['event_id'])
# small bugfix "unhashable type: 'newstr' " #small bugfix "unhashable type: 'newstr' "
event_dmt['origin_id'].id = str(event_dmt['origin_id'].id) event_dmt['origin_id'].id = str(event_dmt['origin_id'].id)
origin = Origin(resource_id=event_dmt['origin_id'], time=event_dmt['datetime'], longitude=event_dmt['longitude'],
origin = Origin(resource_id=event_dmt['origin_id'], latitude=event_dmt['latitude'], depth=event_dmt['depth'])
time=event_dmt['datetime'], mag = Magnitude(mag=event_dmt['magnitude'], magnitude_type=event_dmt['magnitude_type'],
longitude=event_dmt['longitude'],
latitude=event_dmt['latitude'],
depth=event_dmt['depth'])
mag = Magnitude(mag=event_dmt['magnitude'],
magnitude_type=event_dmt['magnitude_type'],
origin_id=event_dmt['origin_id']) origin_id=event_dmt['origin_id'])
ev.magnitudes.append(mag) ev.magnitudes.append(mag)
ev.origins.append(origin) ev.origins.append(origin)
return ev return ev
+1 -2
View File
@@ -1,9 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import warnings
import numpy as np import numpy as np
import warnings
from obspy import UTCDateTime from obspy import UTCDateTime
from pylot.core.util.utils import fit_curve, clims from pylot.core.util.utils import fit_curve, clims
+13 -29
View File
@@ -1,9 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import sys, os, traceback
import multiprocessing import multiprocessing
import os
import sys
import traceback
from PySide2.QtCore import QThread, Signal, Qt, Slot, QRunnable, QObject from PySide2.QtCore import QThread, Signal, Qt, Slot, QRunnable, QObject
from PySide2.QtWidgets import QDialog, QProgressBar, QLabel, QHBoxLayout, QPushButton from PySide2.QtWidgets import QDialog, QProgressBar, QLabel, QHBoxLayout, QPushButton
@@ -22,14 +19,12 @@ class Thread(QThread):
self.abortButton = abortButton self.abortButton = abortButton
self.finished.connect(self.hideProgressbar) self.finished.connect(self.hideProgressbar)
self.showProgressbar() self.showProgressbar()
self.old_stdout = None
def run(self): def run(self):
if self.redirect_stdout: if self.redirect_stdout:
self.old_stdout = sys.stdout
sys.stdout = self sys.stdout = self
try: try:
if self.arg is not None: if self.arg:
self.data = self.func(self.arg) self.data = self.func(self.arg)
else: else:
self.data = self.func() self.data = self.func()
@@ -38,19 +33,13 @@ class Thread(QThread):
self._executed = False self._executed = False
self._executedError = e self._executedError = e
traceback.print_exc() traceback.print_exc()
exctype, value = sys.exc_info()[:2] exctype, value = sys.exc_info ()[:2]
self._executedErrorInfo = '{} {} {}'. \ self._executedErrorInfo = '{} {} {}'.\
format(exctype, value, traceback.format_exc()) format(exctype, value, traceback.format_exc())
if self.redirect_stdout: sys.stdout = sys.__stdout__
sys.stdout = self.old_stdout
def showProgressbar(self): def showProgressbar(self):
if self.progressText: if self.progressText:
# # generate widget if not given in init
# if not self.pb_widget:
# self.pb_widget = ProgressBarWidget(self.parent())
# self.pb_widget.setWindowFlags(Qt.SplashScreen)
# self.pb_widget.setModal(True)
# generate widget if not given in init # generate widget if not given in init
if not self.pb_widget: if not self.pb_widget:
@@ -86,7 +75,6 @@ class Worker(QRunnable):
''' '''
Worker class to be run by MultiThread(QThread). Worker class to be run by MultiThread(QThread).
''' '''
def __init__(self, fun, args, def __init__(self, fun, args,
progressText=None, progressText=None,
pb_widget=None, pb_widget=None,
@@ -94,30 +82,28 @@ class Worker(QRunnable):
super(Worker, self).__init__() super(Worker, self).__init__()
self.fun = fun self.fun = fun
self.args = args self.args = args
# self.kwargs = kwargs #self.kwargs = kwargs
self.signals = WorkerSignals() self.signals = WorkerSignals()
self.progressText = progressText self.progressText = progressText
self.pb_widget = pb_widget self.pb_widget = pb_widget
self.redirect_stdout = redirect_stdout self.redirect_stdout = redirect_stdout
self.old_stdout = None
@Slot() @Slot()
def run(self): def run(self):
if self.redirect_stdout: if self.redirect_stdout:
self.old_stdout = sys.stdout
sys.stdout = self sys.stdout = self
try: try:
result = self.fun(self.args) result = self.fun(self.args)
except: except:
exctype, value = sys.exc_info()[:2] exctype, value = sys.exc_info ()[:2]
print(exctype, value, traceback.format_exc()) 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: else:
self.signals.result.emit(result) self.signals.result.emit(result)
finally: finally:
self.signals.finished.emit('Done') self.signals.finished.emit('Done')
sys.stdout = self.old_stdout sys.stdout = sys.__stdout__
def write(self, text): def write(self, text):
self.signals.message.emit(text) self.signals.message.emit(text)
@@ -149,20 +135,18 @@ class MultiThread(QThread):
self.progressText = progressText self.progressText = progressText
self.pb_widget = pb_widget self.pb_widget = pb_widget
self.redirect_stdout = redirect_stdout self.redirect_stdout = redirect_stdout
self.old_stdout = None
self.finished.connect(self.hideProgressbar) self.finished.connect(self.hideProgressbar)
self.showProgressbar() self.showProgressbar()
def run(self): def run(self):
if self.redirect_stdout: if self.redirect_stdout:
self.old_stdout = sys.stdout sys.stdout = self
sys.stdout = self
try: try:
if not self.ncores: if not self.ncores:
self.ncores = multiprocessing.cpu_count() self.ncores = multiprocessing.cpu_count()
pool = multiprocessing.Pool(self.ncores, maxtasksperchild=1000) pool = multiprocessing.Pool(self.ncores)
self.data = pool.map_async(self.func, self.args, callback=self.emitDone) 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() pool.close()
self._executed = True self._executed = True
except Exception as e: except Exception as e:
@@ -171,7 +155,7 @@ class MultiThread(QThread):
exc_type, exc_obj, exc_tb = sys.exc_info() exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] 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)) print('Exception: {}, file: {}, line: {}'.format(exc_type, fname, exc_tb.tb_lineno))
sys.stdout = self.old_stdout sys.stdout = sys.__stdout__
def showProgressbar(self): def showProgressbar(self):
if self.progressText: if self.progressText:
+324 -751
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -35,9 +35,9 @@ from __future__ import print_function
__all__ = "get_git_version" __all__ = "get_git_version"
import inspect
# 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
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)
+631 -2338
View File
File diff suppressed because it is too large. Load diff
-2
View File
@@ -1,2 +0,0 @@
# -*- coding: utf-8 -*-
#
@@ -1,101 +0,0 @@
############################# correlation parameters #####################################
# min_corr_stacking: minimum correlation coefficient for building beam trace
# min_corr_export: minimum correlation coefficient for pick export
# min_stack: minimum number of stations for building beam trace
# t_before: correlation window before pick
# t_after: correlation window after pick#
# cc_maxlag: maximum shift for initial correlation
# cc_maxlag2: maximum shift for second (final) correlation (also for calculating pick uncertainty)
# initial_pick_outlier_threshold: (hopefully) threshold for excluding large outliers of initial (AIC) picks
# export_threshold: automatically exclude all onsets which deviate more than this threshold from corrected taup onsets
# min_picks_export: minimum number of correlated picks for export
# min_picks_autopylot: minimum number of reference auto picks to continue with event
# check_RMS: do RMS check to search for restitution errors (very experimental)
# use_taupy_onsets: use taupy onsets as reference picks instead of external picks
# station_list: use the following stations as reference for stacking
# use_stacked_trace: use existing stacked trace if found (spare re-computation)
# data_dir: obspyDMT data subdirectory (e.g. 'raw', 'processed')
# pickfile_extension: use quakeML files (PyLoT output) with the following extension, e.g. '_autopylot' for pickfiles
# such as 'PyLoT_20170501_141822_autopylot.xml'
# dt_stacking: time shift for stacking (e.g. [0, 250] for 0 and 250 seconds shift)
# filter_options: filter for first correlation (rough)
# filter_options_final: filter for second correlation (fine)
# filter_type: e.g. 'bandpass'
# sampfreq: sampling frequency of the data
logging: info
pick_phases: ['P', 'S']
# P-phase
P:
min_corr_stacking: 0.8
min_corr_export: 0.6
min_stack: 20
t_before: 30.
t_after: 50.
cc_maxlag: 50.
cc_maxlag2: 5.
initial_pick_outlier_threshold: 30.
export_threshold: 2.5
min_picks_export: 100
min_picks_autopylot: 50
check_RMS: True
use_taupy_onsets: False
station_list: ['HU.MORH', 'HU.TIH', 'OX.FUSE', 'OX.BAD']
use_stacked_trace: False
data_dir: 'processed'
pickfile_extension: '_autopylot'
dt_stacking: [250, 250]
# filter for first correlation (rough)
filter_options:
freqmax: 0.5
freqmin: 0.03
# filter for second correlation (fine)
filter_options_final:
freqmax: 0.5
freqmin: 0.03
filter_type: bandpass
sampfreq: 20.0
# ignore if autopylot fails to pick master-trace (not recommended if absolute onset times matter)
ignore_autopylot_fail_on_master: True
# S-phase
S:
min_corr_stacking: 0.7
min_corr_export: 0.6
min_stack: 20
t_before: 60.
t_after: 60.
cc_maxlag: 100.
cc_maxlag2: 25.
initial_pick_outlier_threshold: 30.
export_threshold: 5.0
min_picks_export: 200
min_picks_autopylot: 50
check_RMS: True
use_taupy_onsets: False
station_list: ['HU.MORH','HU.TIH', 'OX.FUSE', 'OX.BAD']
use_stacked_trace: False
data_dir: 'processed'
pickfile_extension: '_autopylot'
dt_stacking: [250, 250]
# filter for first correlation (rough)
filter_options:
freqmax: 0.1
freqmin: 0.01
# filter for second correlation (fine)
filter_options_final:
freqmax: 0.2
freqmin: 0.01
filter_type: bandpass
sampfreq: 20.0
# ignore if autopylot fails to pick master-trace (not recommended if absolute onset times matter)
ignore_autopylot_fail_on_master: True
File diff suppressed because it is too large. Load diff
@@ -1,41 +0,0 @@
#!/bin/bash
#ulimit -s 8192
#ulimit -v $(ulimit -v | awk '{printf("%d",$1*0.95)}')
#ulimit -v
#655360
source /opt/anaconda3/etc/profile.d/conda.sh
conda activate pylot_311
NSLOTS=20
#qsub -l low -cwd -l "os=*stretch" -pe smp 40 submit_pick_corr_correction.sh
#$ -l low
#$ -l h_vmem=6G
#$ -cwd
#$ -pe smp 20
#$ -N corr_pick
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/pylot_tools/"
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/"
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/pylot/"
#export MKL_NUM_THREADS=${NSLOTS:=1}
#export NUMEXPR_NUM_THREADS=${NSLOTS:=1}
#export OMP_NUM_THREADS=${NSLOTS:=1}
#python pick_correlation_correction.py '/data/AlpArray_Data/dmt_database_mantle_M5.8-6.0' '/home/marcel/.pylot/pylot_alparray_mantle_corr_stack_0.03-0.5.in' -pd -n ${NSLOTS:=1} -istart 0 -istop 100
#python pick_correlation_correction.py '/data/AlpArray_Data/dmt_database_mantle_M5.8-6.0' '/home/marcel/.pylot/pylot_alparray_mantle_corr_stack_0.03-0.5.in' -pd -n ${NSLOTS:=1} -istart 100 -istop 200
#python pick_correlation_correction.py '/data/AlpArray_Data/dmt_database_mantle_M6.0-6.5' '/home/marcel/.pylot/pylot_alparray_mantle_corr_stack_0.03-0.5.in' -pd -n ${NSLOTS:=1} -istart 0 -istop 100
#python pick_correlation_correction.py '/data/AlpArray_Data/dmt_database_mantle_M5.8-6.0' '/home/marcel/.pylot/pylot_alparray_mantle_corr_stack_0.03-0.5.in' -pd -n ${NSLOTS:=1} -istart 100 -istop 200
#python pick_correlation_correction.py 'H:\sciebo\dmt_database' 'H:\Sciebo\dmt_database\pylot_alparray_mantle_corr_S_0.01-0.2.in' -pd -n 4 -t
#pylot_infile='/home/marcel/.pylot/pylot_alparray_syn_fwi_mk6_it3.in'
pylot_infile='/home/marcel/.pylot/pylot_adriaarray_corr_P_and_S.in'
# THIS SCRIPT SHOLD BE CALLED BY "submit_to_grid_engine.py" using the following line:
# use -pd for detailed plots in eventdir/correlation_XX_XX/figures
python pick_correlation_correction.py $1 $pylot_infile -n ${NSLOTS:=1} -istart $2 --params 'parameters_adriaarray.yaml' # -pd
#--event_blacklist eventlist.txt
@@ -1,28 +0,0 @@
#!/usr/bin/env python
import subprocess
fnames = [
('/data/AdriaArray_Data/dmt_database_mantle_M5.0-5.4', 0),
('/data/AdriaArray_Data/dmt_database_mantle_M5.4-5.7', 0),
('/data/AdriaArray_Data/dmt_database_mantle_M5.7-6.0', 0),
('/data/AdriaArray_Data/dmt_database_mantle_M6.0-6.3', 0),
('/data/AdriaArray_Data/dmt_database_mantle_M6.3-10.0', 0),
# ('/data/AdriaArray_Data/dmt_database_ISC_mantle_M5.0-5.4', 0),
# ('/data/AdriaArray_Data/dmt_database_ISC_mantle_M5.4-5.7', 0),
# ('/data/AdriaArray_Data/dmt_database_ISC_mantle_M5.7-6.0', 0),
# ('/data/AdriaArray_Data/dmt_database_ISC_mantle_M6.0-10.0', 0),
]
#fnames = [('/data/AlpArray_Data/dmt_database_mantle_0.01-0.2_SKS-phase', 0),
# ('/data/AlpArray_Data/dmt_database_mantle_0.01-0.2_S-phase', 0),]
####
script_location = '/home/marcel/VersionCtrl/git/pylot/pylot/correlation/submit_pick_corr_correction.sh'
####
for fnin, istart in fnames:
input_cmds = f'qsub -q low.q@minos15,low.q@minos14,low.q@minos13,low.q@minos12,low.q@minos11 {script_location} {fnin} {istart}'
print(input_cmds)
print(subprocess.check_output(input_cmds.split()))
-61
View File
@@ -1,61 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import glob
import json
from obspy import read_events
from pylot.core.util.dataprocessing import Metadata
from pylot.core.util.obspyDMT_interface import qml_from_obspyDMT
def get_event_obspy_dmt(eventdir):
event_pkl_file = os.path.join(eventdir, 'info', 'event.pkl')
if not os.path.exists(event_pkl_file):
raise IOError('Could not find event path for event: {}'.format(eventdir))
event = qml_from_obspyDMT(event_pkl_file)
return event
def get_event_pylot(eventdir, extension=''):
event_id = get_event_id(eventdir)
filename = os.path.join(eventdir, 'PyLoT_{}{}.xml'.format(event_id, extension))
if not os.path.isfile(filename):
return
cat = read_events(filename)
return cat[0]
def get_event_id(eventdir):
event_id = os.path.split(eventdir)[-1]
return event_id
def get_picks(eventdir, extension=''):
event_id = get_event_id(eventdir)
filename = 'PyLoT_{}{}.xml'
filename = filename.format(event_id, extension)
fpath = os.path.join(eventdir, filename)
fpaths = glob.glob(fpath)
if len(fpaths) == 1:
cat = read_events(fpaths[0])
picks = cat[0].picks
return picks
elif len(fpaths) == 0:
print('get_picks: File not found: {}'.format(fpath))
return
print(f'WARNING: Ambiguous pick file specification. Found the following pick files {fpaths}\nFilemask: {fpath}')
return
def write_json(object, fname):
with open(fname, 'w') as outfile:
json.dump(object, outfile, sort_keys=True, indent=4)
def get_metadata(eventdir):
metadata_path = os.path.join(eventdir, 'resp')
metadata = Metadata(inventory=metadata_path, verbosity=0)
return metadata
View File
Whitespace-only changes.
-23
View File
@@ -1,23 +0,0 @@
from pylot.tomography.fmtomo_utils import Tomo3d
import os
citer = 0
niter = 12
n_proc = 4 # only four processes for minimal example with four sources
# for some reason this did not work as expected and was commented out
#if os.path.isfile('inviter.in'):
# with open('inviter.in', 'r') as infile:
# citer = int(infile.read())
# print ('Continue on iteration step ', citer)
tomo = Tomo3d(os.getcwd(), os.getcwd(), overwrite=True, buildObs=False, saveRays=[6, 12], citer=citer)
try:
tomo.runTOMO3D(n_proc, niter)
except KeyboardInterrupt:
print('runTTOMO3D interrupted by user or machine. Cleaning up.')
except Exception as e:
print(f'Catching unknown Exception in runTOMO3D: {e}. Trying to clean up...')
finally:
tomo.removeDirectories()
@@ -1,2 +0,0 @@
# -*- coding: utf-8 -*-
#
@@ -1,177 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Small script to compare arrival times of hybrid tau-p/fmm with simple tau-p for standard earth model
import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
from obspy.taup import TauPyModel
from pylot.tomography.fmtomo_tools.fmtomo_teleseismic_utils import organize_receivers, organize_sources, organize_event_names
def read_file(fnin):
infile = open(fnin, 'r')
return infile.readlines()
def compare_arrivals(arrivals_file, receivers_file, sources_file, input_source_file, model='ak135_diehl_v2', exclude_phases=[]):
'''
Reads FMTOMO arrivals.dat file together with corresponding receiver, source and input_source files to match
each arrival to a source and receiver combination, calculate tau-p arrivals for a given earth model and
calculate differences
'''
arrivals_taup = {}
arrivals_tomo = {}
receiver_ids = {}
event_names = {}
events = organize_event_names(input_source_file)
model = TauPyModel(model)
# organize sources and receivers in dictionaries containing their ID used by FMTOMO as dictionary key
receivers_dict = organize_receivers(receivers_file)
sources_dict = organize_sources(sources_file)
# read arrivals file
with open(arrivals_file, 'r') as infile_arrivals:
arrivals = infile_arrivals.readlines()
count = 0
for src_number, source in sources_dict.items():
if source['phase'] in exclude_phases:
continue
src_name = events[src_number - 1]
if not src_name in event_names.keys():
arrivals_taup[src_name] = []
arrivals_tomo[src_name] = []
receiver_ids[src_name] = []
event_names[src_name] = count
count += 1
for line in arrivals:
# read line by line from fmtomo_tools output file arrivals.dat
rec_id, src_id, ray_id, refl, arrival_time, diff, head = line.split()
arrival_time = float(arrival_time)
rec_id = int(rec_id)
src_id = int(src_id)
ray_id = int(ray_id)
# identify receiver and source using dictionary
receiver = receivers_dict[rec_id]
source = sources_dict[src_id]
src_name = events[src_id - 1]
phase = source['phase']
if phase in exclude_phases: continue
taup_arrival = model.get_travel_times_geo(source_depth_in_km=source['depth'],
source_latitude_in_deg=source['lat'],
source_longitude_in_deg=source['lon'],
receiver_latitude_in_deg=receiver['lat'],
receiver_longitude_in_deg=receiver['lon'],
phase_list=[phase])
receiver_depth_in_km = 6371. - receiver['rad']
if len(taup_arrival) == 1:
taup_arrival_time = taup_arrival[0].time
else:
taup_arrival_time = np.nan
arrivals_taup[src_name].append(taup_arrival_time)
arrivals_tomo[src_name].append(arrival_time)
receiver_ids[src_name].append(rec_id)
#plt.plot([min(arrivals_taup),max(arrivals_taup)],[min(arrivals_taup), max(arrivals_taup)], 'k-')
sorted_by_first_arrival = sorted([(src_name, min(arrivals)) for src_name, arrivals in arrivals_taup.items()],
key=lambda x: x[1])
# print some output for analysis
for item in sorted_by_first_arrival:
print(item)
#[print(source) for source in sources_dict.items()]
#[print(item) for item in enumerate(events)]
current_fmtomo_folder_name = os.path.split(os.path.abspath(arrivals_file))[-2]
fname_savefig = '{}'.format(current_fmtomo_folder_name)
if exclude_phases:
fname_savefig += '_e'
for phase in exclude_phases:
fname_savefig += '_{}'.format(phase)
plot_differences(arrivals_taup, arrivals_tomo, sorted_by_first_arrival, fname_savefig)
#for event_name in ['20160124_103037.a_P.ttf', '20160729_211833.a_Pdiff.ttf', '20160729_211833.a_P.ttf']:
# plot_event(arrivals_tomo, arrivals_taup, receiver_ids, receivers_dict, src_name=event_name)
def plot_differences(arrivals_taup, arrivals_tomo, sorted_by_first_arrival, fname_savefig):
fig = plt.figure(figsize=(16,9))
ax = fig.add_subplot(111)
# init plot for tt differences
cmap = plt.get_cmap('jet')
colors = cmap(np.linspace(0, 1, len(sorted_by_first_arrival)))
for index, item in enumerate(sorted_by_first_arrival):
src_name = item[0]
ax.scatter(arrivals_taup[src_name], np.array(arrivals_tomo[src_name]) - np.array(arrivals_taup[src_name]),
c=colors[index], s=25, marker='.', label=src_name, edgecolors='none')
# shrink box for legend
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.legend(bbox_to_anchor=[1, 1], loc='upper left')
plt.title(fname_savefig)
ax.set_xlabel('Absolute time $t_{tau-p}$')
ax.set_ylabel('Time difference $t_{hybrid} - t_{tau-p}$')
print('Saving plot to {}.png'.format(fname_savefig))
fig.savefig(fname_savefig + '.png', dpi=300)
#plt.show()
def plot_event(arrivals_tomo, arrivals_taup, receiver_ids_dict, receivers_dict, src_name):
arrivals_diff = np.array(arrivals_tomo[src_name]) - np.array(arrivals_taup[src_name])
receiver_ids = receiver_ids_dict[src_name]
x = np.array([receivers_dict[rec_id]['lon'] for rec_id in receiver_ids])
y = np.array([receivers_dict[rec_id]['lat'] for rec_id in receiver_ids])
sc = plt.scatter(x, y, c=arrivals_diff, edgecolor='none')
plt.xlabel('Longitude [deg]')
plt.ylabel('Latitude [deg]')
cbar = plt.colorbar(sc)
cbar.ax.set_ylabel('traveltime difference ($t_{hybrid} - t_{tau-p}$)')
plt.title('{}'.format(src_name))
plt.show()
# folders=[
# 'alparray_0_receiver_elev_zero',
# 'alparray_0_receiver_elev_zero_finer_pgrid_vgrid_r',
# 'alparray_0_receiver_elev_zero_finer_vgrid_llr',
# 'alparray_0_receiver_elev_zero_smaller_box',
# 'alparray_0_receiver_elev_zero_shallow_box',
# 'alparray_0_receiver_elev_zero_finer_pgrid_llr',
# 'alparray_0_receiver_elev_zero_finer_interface',
# #'alparray_0_receiver_elev_zero_bigger_box',
# ]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Compare arrivals with TauP-times')
parser.add_argument('fmtomodir', help='path containing fm3d output')
parser.add_argument('-e', dest='exclude', default=[], help='exclude phases, comma separated, no spaces')
args = parser.parse_args()
fdir = args.fmtomodir
arrivals_file = os.path.join(fdir, 'arrivals.dat')
receivers_file = os.path.join(fdir, 'receivers.in')
sources_file = os.path.join(fdir, 'sources.in')
input_source_file = os.path.join(fdir, 'input_source_file_P.in')
exclude_phases = args.exclude
if exclude_phases:
exclude_phases = exclude_phases.split(',')
compare_arrivals(arrivals_file, receivers_file, sources_file, input_source_file=input_source_file, exclude_phases=exclude_phases)
@@ -1,39 +0,0 @@
import os
cwdir = '/data/AlpArray_Data/fmtomo/v5/tradeoff_curves'
parent_dir_name = 'crust_included_grad_smooth_FIXED_dts'#_grad_1.5'
dampings = [3., 10., 30.]#, 30.]
smoothings = [5.6]
def main(submit_run=True):
fdir_parent = os.path.join(cwdir, parent_dir_name)
for damp in dampings:
for smooth in smoothings:
fdir_out = fdir_parent + '_sm{}_damp{}'.format(smooth, damp)
if not os.path.isdir(fdir_out):
os.mkdir(fdir_out)
os.system('cp -P {}/* {}'.format(fdir_parent, fdir_out))
invertfile = os.path.join(fdir_out, 'invert3d.in')
modify_invert_in(invertfile, damp, smooth)
if submit_run:
os.chdir(fdir_out)
os.system('qsub submit_fmtomo.sh')
def modify_invert_in(fnin, damp, smooth):
with open(fnin, 'r') as infile:
lines = infile.readlines()
with open(fnin, 'w') as outfile:
for line in lines:
if not line.startswith('c'):
value, comment = line.split('c:')
if 'Global damping' in comment:
line = line.replace(value.strip(), str(damp) + ' ')
elif 'Global smoothing' in comment:
line = line.replace(value.strip(), str(smooth) + ' ')
outfile.write(line)
if __name__ == '__main__':
main()
@@ -1,29 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from obspy.geodetics.base import gps2dist_azimuth
def main(infile):
per = 4e4 # earth perimeter
fid = open(infile, 'r')
nrec = fid.readline()
latsrc, lonsrc, depsrc = [float(value) for value in fid.readline().split()]
phase = fid.readline()
latrec, lonrec, deprec = [float(value) for value in fid.readline().split()[:3]]
print ('Lat/Lon Source: {} / {}'.format(latsrc, lonsrc))
print ('Lat/Lon Receiver: {} / {}'.format(latrec, lonrec))
dist_deg = gps2dist_azimuth(latsrc, lonsrc, latrec, lonrec)[0] / 1e3 / per * 360
print ('Distance: {} [deg]'.format(dist_deg))
if __name__ == "__main__":
parser = argparse.ArgumentParser('Estimate distance from source to first'
' receiver in WGS84 ellipsoid in FMTOMO pick file.')
parser.add_argument('infile', help='FMTOMO pickfile (*.ttf)')
args = parser.parse_args()
main(args.infile)
@@ -1,185 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import glob, os, shutil
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
from obspy.geodetics import gps2dist_azimuth
#pwd = '/rscratch/minos13/marcel/fmtomo_alparray/v3.5/alparray_events_thinned/picks'
pwd = '/data/AlpArray_Data/fmtomo/v6/crust_incl_hf_sm_FIX_DTS_grad_sm30_dm10_EASI_test_Plomerova_NS_events/picks'
os.chdir(pwd)
infiles = glob.glob('*.ttf')
clat=46.
clon=11.
ddist = 5
dazim = 5
def make_grid(ddist, dazim):
distgrid = np.arange(35, 135, ddist)
bazimgrid = np.arange(0, 360, dazim)
grid = []
for bazim in np.deg2rad(bazimgrid):
for dist in distgrid:
grid.append(np.array([bazim, dist]))
return np.array(grid)
def make_axes():
fig = plt.figure(figsize=(16,9))
ax1 = fig.add_subplot(121, projection='polar')
ax2 = fig.add_subplot(122)
ax1.set_theta_direction(-1)
ax1.set_theta_zero_location('N')
return ax1, ax2
def load_events():
events = {}
for infile in infiles:
with open(infile, 'r') as fid:
eventid = infile.split('.ttf')[0]
npicks = int(fid.readline())
lat, lon, depth = [float(item) for item in fid.readline().split()]
dist, bazim, azim = gps2dist_azimuth(clat, clon, lat, lon, a=6.371e6, f=0)
bazim = np.deg2rad(bazim)
dist = dist / (np.pi * 6371) * 180 / 1e3
events[eventid] = dict(dist=dist, bazim=bazim, npicks=npicks)
return events
def get_events_in_grid():
events_in_grid = []
for index, gcorner in enumerate(grid):
bazim_l, dist_l = gcorner
bazim_u = bazim_l + np.deg2rad(dazim)
dist_u = dist_l + ddist
events_in_grid.append(dict(bazims=(bazim_l, bazim_u), dists=(dist_l, dist_u), events=[]))
for eventid, event in events.items():
if (dist_l <= event['dist'] < dist_u) and (bazim_l <= event['bazim'] <= bazim_u):
events_in_grid[index]['events'].append(eventid)
return events_in_grid
def filter_events():
filtered_events = {}
for eventdict in events_in_grid:
cur_events = eventdict['events']
if not cur_events: continue
eventid = get_best_event(cur_events)
filtered_events[eventid] = events[eventid]
return filtered_events
def get_best_event(cur_events):
''' return eventid with highest number of picks'''
select_events = {key: events[key] for key in cur_events}
npicks = {key: value['npicks'] for key, value in select_events.items()}
eventid = max(npicks, key=npicks.get)
return eventid
def plot_distribution(events_dict):
cmap_bnd = plt.get_cmap('Greys_r')
cmap_center = plt.get_cmap('viridis')
nevents = [len(grid_dict['events']) for grid_dict in events_dict]
npicks = []
for ev_dict in events_dict:
npick = 0
for eventid in ev_dict['events']:
npick += events[eventid]['npicks']
npicks.append(npick)
npicks = np.array(npicks)
ev_max = max(nevents)
np_max = max(npicks)
print('N picks total:', np.sum(npicks))
print('N picks max: ', np_max)
print('N events max: ', ev_max)
ax_polar, ax_hist = make_axes()
patches = []
for npick, ev_dict in zip(npicks, events_dict):
bazim_l, bazim_u = ev_dict.get('bazims')
dist_l, dist_u = ev_dict.get('dists')
n_ev = len(ev_dict.get('events'))
color_edge = cmap_bnd(n_ev / ev_max)
color_center = cmap_center(npick / np_max)
# color = cmap(np.random.rand())
rect = Rectangle((bazim_l, dist_l), np.deg2rad(dazim), ddist, edgecolor=color_edge)#, facecolor=color_center)
patches.append(rect)
collection = PatchCollection(patches, cmap=cmap_center)
collection.set_array(npicks)
ax_polar.add_collection(collection)
ax_polar.set_ylim((10, 135))
cbar = plt.colorbar(collection)
cbar.set_label('N picks')
# ax.scatter(grid[:, 0] + 0.5 * dazim, grid[:, 1] + 0.5 * ddist, c=nevents, s=50)
bazims = []
dists = []
for event in events.values():
bazims.append(event.get('bazim'))
dists.append(event.get('dist'))
ax_polar.scatter(bazims, dists, c='k', zorder=3, s=5, alpha=0.5)
ax_hist.hist(np.rad2deg(bazims), bins=np.arange(0, 360, dazim))
ax_hist.set_xlabel('Backazimuth (deg)')
ax_hist.set_ylabel('Number of events')
plt.title('Polar event distribution and histogram of backazimuths')
def export_filtered_events(fdir_save='picks_save'):
if not os.path.isdir(fdir_save):
os.mkdir(fdir_save)
for infile in infiles:
eventid = infile.split('.ttf')[0]
if not eventid in events:
for fname in glob.glob('{}.*'.format(eventid)):
shutil.move(fname, fdir_save)
print('Moved file {} to path {}'.format(fname, fdir_save))
def write_input_source_file(fname='input_source_file_P_new.in'):
with open(fname, 'w') as outfile:
outfile.write('{}\n'.format(len(events)))
for eventid in sorted(list(events.keys())):
outfile.write('1 1 {}.ttf\n'.format(eventid))
def filter_bazim(events, bazims_list):
events_filtered = {}
for eventid, event_dict in events.items():
for baz_min, baz_max in bazims_list:
if baz_min <= event_dict['bazim'] * 180. <= baz_max:
events_filtered[eventid] = event_dict
return events_filtered
filter_bazims = [(330, 360), (0, 30), (150, 210)]
events = load_events()
#plot_distribution(events)
events = filter_bazim(events, bazims_list=filter_bazims)
print()
#grid = make_grid(ddist, dazim)
#events_in_grid = get_events_in_grid()
#plot_distribution()
#events = filter_events()
#events_in_grid = get_events_in_grid()
#plot_distribution(events)
#plt.show()
export_filtered_events()
write_input_source_file()
@@ -1,28 +0,0 @@
import os
import numpy as np
from obspy.geodetics import gps2dist_azimuth
from fmtomo_tools.fmtomo_teleseismic_utils import organize_sources
fmtomodir = '/data/AdriaArray_Data/fmtomo_adriaarray/alpadege/no_crust_correction'
clon = 17.5
clat = 42.25
os.chdir(fmtomodir)
sources = organize_sources('sources.in')
dists = []
lats = []
lons = []
for source_id, source_dict in sources.items():
slat = source_dict['lat']
slon = source_dict['lon']
lats.append(slat)
lons.append(slon)
dist_m = gps2dist_azimuth(slat, slon, clat, clon, a=6.371e6, f=0)[0]
dist = dist_m / (np.pi * 6371) * 180 / 1e3
dists.append(dist)
File diff suppressed because it is too large. Load diff
@@ -1,52 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import argparse
from fmtomo_teleseismic_utils import setup_fmtomo_sim
#setup_fmtomo_sim('/data/AlpArray_Data/dmt_database/', '//data/AlpArray_Data/fmtomo/v6_S/crust_incl_hf_sm_FIX_DTS_grad_sm30_dm10')
#setup_fmtomo_sim('/rscratch/minos13/marcel/dmt_database_test_event', '/home/marcel/marcel_scratch/alparray/fmtomo_traveltime_tomo/alparray_0/')
#setup_fmtomo_sim('/rscratch/minos13/marcel/dmt_database_m7', '/home/marcel/marcel_scratch/alparray/fmtomo_traveltime_tomo/alparray_0/')
#setup_fmtomo_sim('/rscratch/minos22/marcel/dmt_database_m7', '/rscratch/minos22/marcel/alparray/fmtomo_traveltime_tomo/alparray_0_receiver_elev_zero_smaller_box')
#setup_fmtomo_sim('/rscratch/minos22/marcel/dmt_database_m7', '/rscratch/minos22/marcel/alparray/fmtomo_traveltime_tomo/alparray_0_receiver_elev_zero_bigger_box')
#setup_fmtomo_sim('/rscratch/minos22/marcel/dmt_database_m7', '/rscratch/minos22/marcel/alparray/fmtomo_traveltime_tomo/alparray_0_receiver_elev_zero_shallow_box')
#setup_fmtomo_sim('/rscratch/minos22/marcel/dmt_database_m7', '/rscratch/minos22/marcel/alparray/fmtomo_traveltime_tomo/alparray_0_receiver_elev_zero_finer_interface')
#setup_fmtomo_sim('/rscratch/minos22/marcel/dmt_database_m7', '/rscratch/minos22/marcel/alparray/fmtomo_traveltime_tomo/alparray_0_receiver_elev_zero_bigger_box_equal_dist_2')
#pgrid = Propgrid('/rscratch/minos22/marcel/alparray/fmtomo_traveltime_tomo/alparray_0/propgrid.in')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Prepare grid for fm3d teleseismic hybrid calculation.')
parser.add_argument('dmt_path', help='path containing dmt_database with PyLoT picks')
parser.add_argument('fmtomodir', help='path containing fm3d output')
parser.add_argument('fname_extension', help='filename extension of pick files')
parser.add_argument('--blacklist', default=None,
help='station blacklist file (csv). After first line: NW_id,ST_id in each line')
parser.add_argument('--no_write_init_nodes', default=False, action='store_true',
help='do not calculate and write init nodes')
parser.add_argument('--no_recalculate_init_nodes', default=False, action='store_true',
help='do not recalculate init nodes if nodes file exists')
parser.add_argument('-n', dest='ncores', default=None, help='number of cores for multiprocessing')
parser.add_argument('--model', default='ak135')
parser.add_argument('--s_phase', default=False, action='store_true')
args = parser.parse_args()
database_path = os.path.abspath(args.dmt_path)
fmtomodir = os.path.abspath(args.fmtomodir)
if args.ncores is not None:
ncores = int(args.ncores)
else:
ncores = None
fname_extension = args.fname_extension
sub_phases = {'P': ['P', 'PKP'], 'S': ['S', 'SKS']}
phase_types = ['P']
if args.s_phase:
phase_types.append('S')
setup_fmtomo_sim(database_path, fmtomodir, fname_extension, sub_phases, ncores=ncores, check_notesfile=False,
model=args.model, fname_station_blacklist=args.blacklist,
no_write_init_nodes=args.no_write_init_nodes,
no_recalculate_init_nodes=args.no_recalculate_init_nodes, phase_types=phase_types)
@@ -1,930 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import subprocess
import warnings
import os
import glob
from datetime import datetime
import multiprocessing
import numpy as np
import json
from obspy import read_events, UTCDateTime
from obspy.taup import TauPyModel
from obspy.geodetics import locations2degrees, gps2dist_azimuth
from pylot.core.util.utils import identifyPhaseID
from pylot.core.util.obspyDMT_interface import qml_from_obspyDMT
from pylot.tomography.utils import pol2cart, pol2cart_vector
from pylot.tomography.utils import get_metadata
class Propgrid(object):
'''
small class that is built from an fm3d propgrid.in file; generates a regular grid in the same way as fm3d
'''
def __init__(self, filename):
self.r_earth = 6371. # earth radius in km
self.init_propgrid(filename)
def init_propgrid(self, filename_propgrid):
self.read_propgrid(filename_propgrid)
self.init_rGrid()
self.init_latGrid()
self.init_longGrid()
def init_rGrid(self):
self.rs = np.zeros(self.nR)
self.rbot = self.r_earth + self.zTop - (self.nR - 1) * self.deltaR
for index in range(self.nR):
self.rs[index] = self.rbot + index * self.deltaR
def init_latGrid(self):
self.lats = np.zeros(self.nLat)
self.latS = np.deg2rad(self.latSdeg)
self.deltaLat = np.deg2rad(self.deltaLatDeg)
for index in range(self.nLat):
self.lats[index] = self.latS + index * self.deltaLat
def init_longGrid(self):
self.longs = np.zeros(self.nLong)
self.longW = np.deg2rad(self.longWdeg)
self.deltaLong = np.deg2rad(self.deltaLongDeg)
for index in range(self.nLong):
self.longs[index] = self.longW + index * self.deltaLong
def read_propgrid(self, filename_propgrid):
infile = open(filename_propgrid, 'r')
self.nR, self.nLat, self.nLong = [int(value) for value in infile.readline().split()]
self.deltaR, self.deltaLatDeg, self.deltaLongDeg = [np.float64(value) for value in infile.readline().split()]
self.zTop, self.latSdeg, self.longWdeg = [np.float64(value) for value in infile.readline().split()]
infile.close()
def check_event_notes(eventdir):
eventfile = os.path.join(eventdir, 'notes.txt')
if os.path.isfile(eventfile):
with open(eventfile, 'r') as infile:
notes = infile.readline()
print(notes)
if 'exclude' in notes:
print('Will exclude this event!')
return False
else:
print('No notes file found.')
return True
def prepare_fmtomo_dir_first_run(fmtomo_dir):
"""
This helper function calls the file 'fm3d_prepare_tele' in the fmtomo binary after creating a "fake" receivers.in
and sources.in file so that fm3d can prepare the teleseismic run and writes the file "init_nodes.out" that contains
information on the boundary nodes of the current propagation grid. Make sure that "grid3dg" has already been called
for this function to work.
:param fmtomo_dir:
:return:
"""
def write1(fid):
fid.write('1\n')
def write_rec_file():
""" Writes a fake receiver (has to be inside the grid) """
with open(recfile, 'w') as fid:
write1(fid)
fid.write(f'0 {clat} {clon}\n')
for _ in range(3):
write1(fid)
def write_src_file():
""" Writes a fake source """
fakesrc_str = '''
1
1
P
0.0000 0.0000 0.0000 0.00000 0.00000 0.00000
1
1
2 1
1
1
'''
with open(srcfile, 'w') as fid:
fid.write(fakesrc_str)
def get_clat_clon():
if not os.path.isfile(propgrid_file):
raise IOError(f'Missing file {propgrid_file} for fmtomo first run preparation.')
with open(propgrid_file, 'r') as fid:
_, nlat, nlon = (int(item) for item in fid.readline().split())
_, dlat, dlon = (float(item) for item in fid.readline().split())
_, lat0, lon0 = (float(item) for item in fid.readline().split())
clat = lat0 + nlat / 2 * dlat
clon = lon0 + nlon / 2 * dlon
return clat, clon
# check if binary file exists
fmtomo_prep_tele = os.path.join(fmtomo_dir, 'fm3d_prepare_tele')
assert os.path.isfile(fmtomo_prep_tele), f'Missing binary file {fmtomo_prep_tele}'
# set filenames for propgrid, sources and receivers
propgrid_file = os.path.join(fmtomo_dir, 'propgrid.in')
recfile = os.path.join(fmtomo_dir, 'receivers.in')
srcfile = os.path.join(fmtomo_dir, 'sources.in')
# get coords from propgrid
clat, clon = get_clat_clon()
# write fake source and receiver files
write_src_file()
write_rec_file()
# execute fm3d_prepare tele from local directory
curdir = os.getcwd()
os.chdir(fmtomo_dir)
rval = subprocess.check_output([fmtomo_prep_tele]).decode('utf-8')
if not rval.split('\n')[-2] == ' Finished teleseismic preparation. Stop.':
raise ValueError('Unexpected output initialisation run.')
if not os.path.isfile(os.path.join(fmtomo_dir, 'init_nodes.out')):
raise Exception('Could not create output file init_nodes.')
os.chdir(curdir)
# clean up
os.remove(srcfile)
os.remove(recfile)
print('Prepare fmtomo dir first run: Success')
def setup_fmtomo_sim(database_path_dmt, fmtomo_dir, fname_extension, sub_phases, ncores=None, model='ak135',
min_picks_per_phase=10, write_vtk=True, check_notesfile=True, fname_station_blacklist=None,
no_write_init_nodes=False, no_recalculate_init_nodes=False, phase_types=('P, S')):
'''
main function of this program, writes picks and input source file for FMTOMO obsdata program
'''
assert os.path.isdir(database_path_dmt), 'Unrecognized directory {}'.format(database_path_dmt)
assert os.path.isdir(fmtomo_dir), 'Unrecognized directory {}'.format(fmtomo_dir)
tstart = datetime.now()
print('Starting script at {}'.format(tstart))
print('Check notesfile set to {}'.format(check_notesfile))
# save means of event traveltimes to dictionary for statistical analysis
#tt_means = {}
fname_fmtomo_nodes = os.path.join(fmtomo_dir, 'init_nodes.out')
# do first initialisation of FMTOMO to generate init_nodes file if required
if not no_recalculate_init_nodes:
prepare_fmtomo_dir_first_run(fmtomo_dir)
eventdirs = glob.glob(os.path.join(database_path_dmt, '*.?'))
nEvents = len(eventdirs)
# create directory that will contain the picks
picksdir = os.path.join(fmtomo_dir, 'picks')
if not os.path.isdir(picksdir):
os.mkdir(picksdir)
# track and count ALL source locations & phases (P and S) for fmtomo_tools
associations_str = ''
nsrc_total = 0
# iterate over P and S to create one model each
for phase_type in phase_types:
sourcefile_str = ''
nsrc = 0
# iterate over all events in "database_path_dmt"
for eventindex, eventdir in enumerate(eventdirs):
print('Working on {}-picks for event {} ({}/{})'.format(phase_type, eventdir,
eventindex + 1, len(eventdirs)))
if check_notesfile and not check_event_notes(eventdir):
continue
# create ObsPy event from .pkl file in dmt eventdir
event = get_event_obspy_dmt(eventdir)
if len(event.origins) > 1:
raise Exception('Ambiguous origin information for event {}'.format(event))
origin = event.origins[0]
# get all picks from PyLoT *.xml file
picks = get_picks(eventdir, extension=fname_extension)
if not picks:
print('No picks for event {} found.'.format(eventdir))
continue
# remove picks for blacklisted stations
if fname_station_blacklist:
picks, n_deleted_blacklist = remove_blacklisted_station_picks(picks, fname_station_blacklist)
# get metadata for current event from dmt_database
metadata = get_metadata(eventdir)
# get a dictionary containing coordinates for all stations
stations_dict = metadata.get_all_coordinates()
# catch event id
event_id = get_event_id(eventdir)
# map specific phases to another phase (Pdiff -> P)
merge_phases = {'Pdiff': 'P'}
for key, value in merge_phases.items():
print('Will map phase {} to phase {} if present.'.format(key, value))
# assign all picks of this event to a phase and add to sorted_picks dictionary
sorted_picks = sort_picks_by_phase(picks, stations_dict, origin,
sub_phases[phase_type], model, merge_phases=merge_phases)
sorted_picks = remove_uncommon_picks(sorted_picks, min_picks_per_phase)
# the following should not be necessary when calculating traveltimes on borders using TauPy
#sorted_picks = translate_phase_names_TAUP(sorted_picks)
#
# iterate over sorted picks and write a traveltime file for each phase type
for phase, picks_list in sorted_picks.items():
pickfile_base = '{}_{}'.format(event_id, phase)
pickfile_name = pickfile_base + '.ttf'
init_nodes_name = pickfile_base + '.nodes'
vtk_file_name = pickfile_base + '.vtk'
pickfile = os.path.join(picksdir, pickfile_name)
init_nodes_file = os.path.join(picksdir, init_nodes_name)
vtk_file = os.path.join(picksdir, vtk_file_name)
# remove source time
picks_list = subtract_source_time(picks_list, origin.time)
# save mean for statistical analysis
#tt_means[pickfile_base] = mean
# create a list with all "true" phases used for taupy to calculate boundary ttimes/ray parameters
phases = list(set([item['true_phase'] for item in picks_list]))
if no_write_init_nodes == False:
if no_recalculate_init_nodes and os.path.isfile(init_nodes_file):
print('Found previously calculated init nodes. Will not recalculate.')
else:
# calculate travel times and ray parameters for boundary nodes and write to file
points_list = initNodesFm3d(fname_fmtomo_nodes, origin, model, phases, ncores=ncores)
# in case initNodes fails and returns None continue with next phase
if not points_list:
print('No points list, initNodesFm3d failed for event.')
continue
if not write_init_points(points_list, init_nodes_file):
print('Write init points failed for event.')
continue
if write_vtk==True:
write_vtk_file(points_list, vtk_file)
# write picks to pickfile for fm3d
write_picks_to_pickfile(pickfile, phase, picks_list, stations_dict, origin)
# add pickfile to sourcefile string and count number of pickfiles
sourcefile_str += '1 1 {}\n'.format(pickfile_name)
# add source location, phaseID and .nodes filename to association string
source_string = '{phase} {lat} {lon} {depth} {fname}\n'
associations_str += source_string.format(phase=phase, lat=origin.latitude,
lon=origin.longitude, depth=origin.depth,
fname=init_nodes_name)
nsrc += 1
nsrc_total += 1
average_time = (datetime.now() - tstart) / (eventindex + 1)
print('Average time for event (phase {}): {}'.format(phase_type, average_time))
print('ETA for {}-events: {}'.format(phase_type, tstart + nEvents * average_time))
write_src_file(fmtomo_dir, phase_type, nsrc, sourcefile_str)
write_assc_file(fmtomo_dir, nsrc_total, associations_str)
#write_json(tt_means, os.path.join(fmtomo_dir, 'ttmeans.json'))
print('Script finished! Good Bye!')
def write_src_file(fmtomo_dir, phase_type, nsrc, sourcefile_str):
# write input_source_file for obsdata
input_source_file = open(os.path.join(fmtomo_dir, 'input_source_file_{}.in'.format(phase_type)), 'w')
input_source_file.write('{}\n'.format(nsrc))
input_source_file.write(sourcefile_str)
input_source_file.close()
def write_assc_file(fmtomo_dir, nsrc_total, associations_str):
# write input_associations file for fm3d
input_assc_file = open(os.path.join(fmtomo_dir, 'input_associations_file.in'), 'w')
input_assc_file.write('{}\n'.format(nsrc_total))
input_assc_file.write(associations_str)
input_assc_file.close()
def write_json(object, fname):
with open(fname, 'w') as outfile:
json.dump(object, outfile, sort_keys=True, indent=4)
def write_vtk_file(points_list, fname):
outfile = open(fname, 'w')
nPoints = len(points_list)
outfile.write('# vtk DataFile Version 2.0\n')
outfile.write('FMM Init points\n')
outfile.write('ASCII\n')
outfile.write('DATASET POLYDATA\n')
outfile.write('POINTS {} float\n'.format(nPoints))
for point in points_list:
lat = point['pt_lat']
lon = point['pt_lon']
rad = point['pt_R']
x, y, z = pol2cart(lat, lon, rad)
outfile.write('{x} {y} {z}\n'.format(x=x, y=y, z=z))
# write number of vertices and their indices
outfile.write('\nVERTICES {} {}\n'.format(nPoints, 2*nPoints))
for index, point in enumerate(points_list):
outfile.write('{} {}\n'.format(1, index))
# write header with number of data points
outfile.write('\nPOINT_DATA {}\n'.format(nPoints))
# write header for traveltimes
outfile.write('SCALARS traveltime float 1\n')
outfile.write('LOOKUP_TABLE default\n')
for point in points_list:
time = point.get('time')
outfile.write('{}\n'.format(time if time else 0))
# write header for point indices
outfile.write('SCALARS point_index integer 1\n')
outfile.write('LOOKUP_TABLE default\n')
for point in points_list:
pt_index = point.get('pt_index')
outfile.write('{}\n'.format(pt_index if pt_index else 0))
outfile.write('VECTORS tt_grad float\n')
for point in points_list:
lat = point['pt_lat']
lon = point['pt_lon']
r_comp = point.get('ray_param_km_z_comp')
n_comp = point.get('ray_param_km_n_comp')
e_comp = point.get('ray_param_km_e_comp')
sx, sy, sz = pol2cart_vector(lat, lon, n_comp, e_comp, r_comp)
outfile.write('{sx} {sy} {sz}\n'.format(sx=sx if sx else 0.,
sy=sy if sy else 0.,
sz=sz if sz else 0.,))
outfile.close()
def write_init_points(points_list, outfile):
fid = open(outfile, 'w')
print('Writing {} init points to file {}.'.format(len(points_list), outfile))
output_str = ''
# count number of points for file header
npoints = 0
for point_dict in points_list:
nArrivals = point_dict.get('nArrivals')
if not nArrivals:
#print('No arrivals for point:')
#print(point_dict)
continue
if nArrivals > 1:
fid.close()
os.remove(outfile)
warning_template = 'Ambiguous information for point: {}, having {} different arrivals. Skipping event.'
print(warning_template.format(point_dict, nArrivals))
return False
output_template = '{index} {time} {ray_param_z} {ray_param_n} {ray_param_e}\n'
output_str += (output_template.format(index=point_dict['pt_index'],
time=point_dict.get('time'),
ray_param_z=point_dict.get('ray_param_km_z_comp'),
ray_param_n=point_dict.get('ray_param_km_n_comp'),
ray_param_e=point_dict.get('ray_param_km_e_comp')))
npoints += 1
fid.write('{}\n'.format(npoints))
fid.write(output_str)
fid.close()
return True
def initNodesFm3d(filename_init_nodes, source_origin, model, phases, min_dist=25., ncores=None, R=6371000.):
# This function uses obspy TauPy to calculate travel times and ray parameters on boundary points of the fm3d grid
def exposed_sides(grid_boundaries, src_lat, src_lon):
# check which sides of grid are exposed to source (taken from fm3d teleseismic.f90 code)
# here: baz is calculated, not az
north = grid_boundaries['north']
east = grid_boundaries['east']
south = grid_boundaries['south']
west = grid_boundaries['west']
# north
baz1 = gps2dist_azimuth(north, west, src_lat, src_lon, a=R, f=0)[1]
baz2 = gps2dist_azimuth(north, east, src_lat, src_lon, a=R, f=0)[1]
exposed_north = all(np.cos(np.deg2rad(baz)) > 0.01 for baz in [baz1, baz2])
# east
baz1 = gps2dist_azimuth(north, east, src_lat, src_lon, a=R, f=0)[1]
baz2 = gps2dist_azimuth(south, east, src_lat, src_lon, a=R, f=0)[1]
exposed_east = all(np.sin(np.deg2rad(baz)) > 0.01 for baz in [baz1, baz2])
# south
baz1 = gps2dist_azimuth(south, west, src_lat, src_lon, a=R, f=0)[1]
baz2 = gps2dist_azimuth(south, east, src_lat, src_lon, a=R, f=0)[1]
exposed_south = all(np.cos(np.deg2rad(baz)) < -0.01 for baz in [baz1, baz2])
# west
baz1 = gps2dist_azimuth(north, west, src_lat, src_lon, a=R, f=0)[1]
baz2 = gps2dist_azimuth(south, west, src_lat, src_lon, a=R, f=0)[1]
exposed_west = all(np.sin(np.deg2rad(baz)) < -0.01 for baz in [baz1, baz2])
exposed_dict = dict(north=exposed_north, east=exposed_east, south=exposed_south, west=exposed_west,
rbot=True)
return exposed_dict
def point_valid(pt_lat, pt_lon, pt_R, exposed_dict, grid_boundaries, R_earth):
# check whether point has to be active or not depending on its position to the source
def check_point(actual, desired, threshold=0.001):
# checks receiver (boundary) point orientation by comparison to corner boundary points
return abs(actual - desired) < threshold
# check for negative depth (above surface)
if pt_R > R_earth:
return False
# check if point belongs to bottom interface
#if check_point(pt_R, grid_boundaries['rbot']):
# return True
pt_faces_dir = {}
pt_exposed_dir = {}
directions = {'north': pt_lat,
'east': pt_lon,
'south': pt_lat,
'west': pt_lon,
'rbot': pt_R,}
for direction, pt_lat_or_lon in directions.items():
# check if point belongs to boundary of this direction and save to pt_faces_dir
pt_direction_check = check_point(pt_lat_or_lon, grid_boundaries[direction])
pt_faces_dir[direction] = pt_direction_check
# check if point is exposed to source in this direction and save to pt_exposed_dir
pt_exposed_dir[direction] = pt_direction_check and exposed_dict[direction]
# compare number of points facing source direction to the actual direction they are facing
return sum(pt_faces_dir.values()) == sum(pt_exposed_dir.values())
import datetime
now = datetime.datetime.now()
infile = open(filename_init_nodes, 'r')
R_earth = 6371.
# read input files containing fm3d boundary points in each line in the order: lat lon radius
init_nodes = infile.readlines()
nPoints = len(init_nodes)
# split lines and convert to floats except for first value which is converted to int
init_nodes = [[float(val) if index != 0 else int(val) for index, val in enumerate(line.split())]
for line in init_nodes]
grid_boundaries = dict(north=max(init_nodes, key=lambda x: x[1])[1],
east=max(init_nodes, key=lambda x: x[2])[2],
south=min(init_nodes, key=lambda x: x[1])[1],
west=min(init_nodes, key=lambda x: x[2])[2],
rbot=min(init_nodes, key=lambda x: x[3])[3],
rtop=max(init_nodes, key=lambda x: x[3])[3])
# get source coordinates
src_lat, src_lon, src_depth = source_origin.latitude, source_origin.longitude, source_origin.depth
#src_lat = 0; src_lon = 180; src_depth=50
# calculate which sides are exposed to source
exposed_dict = exposed_sides(grid_boundaries, src_lat, src_lon)
# iterate over all points and calculate distance. Append a dictionary to an input list for
# multiprocessing worker for each point
points_list = []
for point in init_nodes:
pt_index, pt_lat, pt_lon, pt_R = point
pt_depth = R_earth - pt_R
dist = locations2degrees(pt_lat, pt_lon, src_lat, src_lon)
# check minimum distance for this point
if dist < min_dist:
warnings.warn('Distance for point {} less than minimum'
' distance ({} km). Skipping event!'.format(point, min_dist))
return
# check if point is exposed to source and has to be initiated
if not point_valid(pt_lat, pt_lon, pt_R, exposed_dict, grid_boundaries, R_earth):
continue
input_dict = {'pt_index': pt_index,
'pt_depth': pt_depth,
'pt_R': pt_R,
'pt_lat': pt_lat,
'pt_lon': pt_lon,
'src_lat': src_lat,
'src_lon': src_lon,
'src_depth': src_depth,
'dist': dist,
'model': model,
'phases': phases,
}
points_list.append(input_dict)
print('n Points init:', len(points_list))
#plot_points(points_list)
rvals = []
pool = multiprocessing.Pool(ncores, maxtasksperchild=1000)
for rval in pool.imap(taup_worker, points_list, chunksize=10):
rvals.append(rval)
pool.close()
pool.join()
print('Done after {}'.format(datetime.datetime.now() - now))
#plot_points(points_list)
return rvals
def taup_worker(input_dict):
# initiate model for TauP method
model = TauPyModel(model=input_dict['model'])
huge_time = 1e7
try:
arrivals = model.get_ray_paths(input_dict['src_depth'], input_dict['dist'],
phase_list=input_dict['phases'],
receiver_depth_in_km=input_dict['pt_depth'], )
if len(arrivals) < 1:
#print('No arrivals for phase {}'.format(input_dict['phase']))
#print(input_dict)
return input_dict
arr = arrivals[0]
input_dict['nArrivals'] = len(arrivals)
baz = gps2dist_azimuth(input_dict['pt_lat'], input_dict['pt_lon'],
input_dict['src_lat'], input_dict['src_lon'],
a=6371.*1e3, f=0)[1]
# calculate traveltime gradient, division by R to transform from rad to km
# multiply with -1 to get values for azimuth instead of back-azimuth
ray_param_km_z_comp = arr.ray_param / np.tan(np.deg2rad(arr.incident_angle)) / input_dict['pt_R']
ray_param_km_n_comp = arr.ray_param * (-1) * np.cos(np.deg2rad(baz)) / input_dict['pt_R']
ray_param_km_e_comp = arr.ray_param * (-1) * np.sin(np.deg2rad(baz)) / input_dict['pt_R']
input_dict['ray_param_km_z_comp'] = ray_param_km_z_comp
input_dict['ray_param_km_n_comp'] = ray_param_km_n_comp
input_dict['ray_param_km_e_comp'] = ray_param_km_e_comp
input_dict['time'] = arr.time
except Exception as e:
print(e, input_dict)
return input_dict
def plot_points(points_list):
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = []
y = []
z = []
color = np.full(len(points_list), np.nan)
for index, points_dict in enumerate(points_list):
x.append(points_dict['pt_lat'])
y.append(points_dict['pt_lon'])
z.append(points_dict['pt_depth'])
arrivals = points_dict.get('arrivals')
if arrivals:
color[index] = arrivals[0].time
ax.scatter(x, y, z, c=color)
plt.show()
def subtract_source_time(picks_list, origin_time):
# WAS FUNCTION DEMEAN, but demean after calculating residuals using rtimes_tele in FMTOMO!!
for phase_dict in picks_list:
taup_time = phase_dict['taup_time']
pick = phase_dict['pick']
pick_time = pick.time
ttres = pick_time - taup_time
# I think doing this is wrong because taup times do NOT include station elevation!!! 5.3.20
phase_dict['ttres'] = ttres
mean = np.mean([phase_dict['pick'].time.timestamp for phase_dict in picks_list])
for phase_dict in picks_list:
phase_dict['ttres_demeaned'] = phase_dict['ttres'] - mean # see above comment
phase_dict['abstimes'] = phase_dict['pick'].time - origin_time
return picks_list
def translate_phase_names_TAUP(sorted_picks):
# PKP and PKIKP are all just 'P' phases in fm3d (not very sure about this!)
translations = {'PKIKP': 'PKP',
'SKIKS': 'SKS',}
for phase_name in sorted_picks.keys():
if phase_name in translations.keys():
sorted_picks[translations[phase_name]] = sorted_picks.pop(phase_name)
return sorted_picks
def write_picks_to_pickfile(pickfile, phase, picks_list, stations_dict, origin, picks_mode='abs'):
fid = open(pickfile, 'w')
header = '{npicks}\n' \
'{lat_src:<15} {lon_src:<15} {depth_src:<15}\n' \
'{phase_name}\n'
# pickfile header including npicks, src coords, phasetype
formatted_str = header.format(npicks=len(picks_list),
lat_src=origin.latitude,
lon_src=origin.longitude,
depth_src=origin.depth,
phase_name=phase)
fid.write(formatted_str)
# write picks for each station to pickfile
for phase_dict in picks_list:
pick = phase_dict['pick']
seed_id = pick.waveform_id.get_seed_string()
# travel time residual (demeaned or abs)
if picks_mode == 'abs':
picktime = phase_dict['abstimes']
elif picks_mode == 'res':
warnings.warn('Using residuals here might not be exact. See above code where ttres_demeaned is calculated.')
picktime = phase_dict['ttres_demeaned']
else:
raise IOError(f'Unknown picks_mode {picks_mode}')
uncertainty = pick.time_errors.uncertainty
network, station = seed_id.split('.')[:2]
# get stations coords from metadata dict
station_coords = stations_dict.get('{}.{}'.format(network, station))
# prepare line to be written to pickfile and format, use traveltime residual
line = '{lat_rec:<15} {lon_rec:<15} {depth_rec:<15} {picktime:<15} {uncert:15}\n'
formatted_line = line.format(lat_rec=station_coords['latitude'],
lon_rec=station_coords['longitude'],
depth_rec=station_coords['elevation'] * (-1e-3),
picktime=picktime,
uncert=uncertainty)
fid.write(formatted_line)
print('Wrote {} picks for phase {} to file {}'.format(len(picks_list), phase, pickfile))
fid.close()
def remove_blacklisted_station_picks(picks, fname_blacklist, verbosity=1):
blacklisted_stations = get_station_blacklist(fname_blacklist)
deleted_picks = []
deleted_stations = []
for index, pick in list(reversed(list(enumerate(picks)))):
seed_id = pick.waveform_id.get_seed_string()
network, station = seed_id.split('.')[:2]
nwst_id = '{}.{}'.format(network, station)
if nwst_id in blacklisted_stations.keys():
timewindow = blacklisted_stations[nwst_id]
if not timewindow == 'always':
tstart, tstop = [UTCDateTime(time) for time in timewindow.split('to')]
if not tstart <= picks[index].time <= tstop:
continue
deleted_picks.append(picks.pop(index))
deleted_stations.append(nwst_id)
if verbosity > 0:
print('Deleted picks for blacklisted stations:\n{}'.format(deleted_stations))
return picks, deleted_stations
def get_station_blacklist(fname_csv):
with open(fname_csv, 'r') as infile:
# skip first line
blacklist = infile.readlines()[1:]
blacklisted_stations = {}
for line in blacklist:
network, station, time = line.split(',')[:3]
nwst_id = '{}.{}'.format(network, station)
blacklisted_stations[nwst_id] = time
return blacklisted_stations
def remove_uncommon_picks(sorted_picks, min_picks_per_phase):
for phase_name, picks_list in reversed(list(sorted_picks.items())):
if len(picks_list) < min_picks_per_phase:
msg = 'Removed picks for phase {}, as there are only {} picks given (threshold is {})'
print(msg.format(phase_name, len(picks_list), min_picks_per_phase))
del(sorted_picks[phase_name])
return sorted_picks
def sort_picks_by_phase(picks, stations_dict, source_origin, phase_types, model,
max_phase_diff=50., merge_phases=None, verbosity=0):
'''
# First: Iterate through all picks to estimate possible phases for source/location combination, then assign
# each pick to one phase and return sorted picks dictionary, as there has to be one pickfile for each phasetype
:param picks:
:param stations_dict:
:param source_origin:
:param phase_types:
:param model:
:param max_phase_diff:
:param merge_phases: assign a phase (key) to another phase (value) e.g. {Pdiff: P}
:param verbosity:
:return:
'''
print('Starting to sort picks by phase calculating theoretical travel times for each pick...')
phases_dict = {}
for pick in picks:
# PROBLEM: seed_id from PyLoT does not contain Location ID!!! Makes it hard to find station coords
# workaround: use stations_dict (ignore channel and location ID) instead of metadata.get_coordinates()
seed_id = pick.waveform_id.get_seed_string()
network, station = seed_id.split('.')[:2]
phaseID = pick.phase_hint
uncertainty = pick.time_errors.uncertainty
# skip different phase
if not phaseID in phase_types:
continue
# pick invalid if no uncertainty is given
if not uncertainty:
continue
station_coords = stations_dict.get('{}.{}'.format(network, station))
if not station_coords:
print('Could not find coordinates for station: {}'.format(seed_id))
continue
# estimate phase type by taking the closest phase from Tau-P method (time is relative to source origin)
phase_name, phase_time_rel, phase_diff = get_closest_taup_phase(source_origin, station_coords,
phaseID, pick.time, model)
if phase_diff > max_phase_diff:
if verbosity > 0:
print ('Warning, max_diff too large (> {} s) for phase {} at {}. Skipping'.format(max_phase_diff,
phase_name, seed_id))
continue
phase_time = source_origin.time + phase_time_rel
# merge phase if selected, keep track of original phase for TauPy node initiation
true_phase = phase_name
if merge_phases and phase_name in merge_phases.keys():
phase_name = merge_phases[phase_name]
if not phase_name in phases_dict.keys():
print('Adding phase to sorted picks dictionary: {}'.format(phase_name))
phases_dict[phase_name] = []
phases_dict[phase_name].append({'pick': pick,
'taup_time': phase_time,
'true_phase': true_phase,})
return phases_dict
def get_closest_taup_phase(source_origin, station_coords, phase, pick_time, model='ak135'):
'''
Estimate phase that was picked by searching for earliest P/S phase arriving at
station_coords for given source_coords using TauPy. As PyLoT only searches for first arrivals
using the same method, this should(!) yield the correct phase.
:return:
'''
phases = {'P': [],
'S': []}
phase_lists = {'P': ['ttp'],
'S': ['tts']}
# possible phases for fm3d (*K* and *KIK* -> *)
#phase_list = {'P': ['P', 'PKP', 'PKiKP', 'PKIKP', 'PcP', 'ScP', 'SKP', 'PKKP', 'SKKP', 'PP',],
# 'S': ['S', 'SKS', 'SKIKS', 'ScS']}
# in case pick phase hint is just P or S
if phase in phases.keys():
phase_list = phase_lists[phase]
common_phase = phase
# in case an explicit phase name is given use only this phase
else:
phase_list = [phase]
common_phase = identifyPhaseID(phase)
model = TauPyModel(model=model)
arrivals = model.get_travel_times_geo(source_origin.depth,
source_origin.latitude,
source_origin.longitude,
station_coords['latitude'],
station_coords['longitude'],
phase_list)
# identifies phases from arrivals as P or S phase, not necessary when using 'ttp' or 'tts' for get_travel_times_geo
for arr in arrivals:
phases[identifyPhaseID(arr.phase.name)].append(arr)
source_time = source_origin.time
if not arrivals:
raise Exception('No arrivals found for source.')
# get first P or S onsets from arrivals list
arr, min_diff = min([(arr, abs(source_time + arr.time - pick_time)) for arr in phases[common_phase]],
key=lambda t: t[1])
return arr.name, arr.time, min_diff
def get_event_obspy_dmt(eventdir):
event_pkl_file = os.path.join(eventdir, 'info', 'event.pkl')
if not os.path.exists(event_pkl_file):
raise IOError('Could not find event path for event: {}'.format(eventdir))
event = qml_from_obspyDMT(event_pkl_file)
return event
def get_event_pylot(eventdir, extension=''):
event_id = get_event_id(eventdir)
filename = os.path.join(eventdir, 'PyLoT_{}{}.xml'.format(event_id, extension))
if not os.path.isfile(filename):
return
cat = read_events(filename)
return cat[0]
def get_event_id(eventdir):
event_id = os.path.split(eventdir)[-1]
return event_id
def get_picks(eventdir, extension=''):
event_id = get_event_id(eventdir)
filename = 'PyLoT_{}{}.xml'
filename = filename.format(event_id, extension)
fpath = os.path.join(eventdir, filename)
fpaths = glob.glob(fpath)
if len(fpaths) == 1:
cat = read_events(fpaths[0])
picks = cat[0].picks
return picks
elif len(fpaths) == 0:
print('get_picks: File not found: {}'.format(fpath))
return
print(f'WARNING: Ambiguous pick file specification. Found the following pick files {fpaths}\nFilemask: {fpath}')
return
def init_sources_file(nsrc, filename='sources.in'):
infile_source = open(filename, 'w')
infile_source.write('{}\n'.format(nsrc))
return infile_source
def init_receivers_file(nrec, filename='receivers.in'):
infile_rec = open(filename, 'w')
infile_rec.write('{}\n'.format(nrec))
return infile_rec
def append_source(fid, origin):
pass
def append_receiver(fid, station_coords):
# TODO check if order is correct
fid.write('{rad:15} {lat:15} {lon:15} \n'.format(rad=station_coords['elevation'],
lat=station_coords['latitude'],
lon=station_coords['longitude']))
def organize_receivers(fnin, unique=False):
''' Open FMTOMO receivers.in file and read position of each receiver into a dict.'''
with open(fnin, 'r') as infile:
nRec = int(infile.readline())
rec_dict = {}
for rec_number in range(1, nRec + 1):
rad, lat, lon = [float(value) for value in infile.readline().split()]
# dummy read next 3 lines
for ind in range(3):
infile.readline()
receiver = {'rad': rad,
'lat': lat,
'lon': lon, }
if unique:
if receiver in rec_dict.values():
continue
rec_dict[rec_number] = receiver
return rec_dict
def organize_sources(fnin):
''' Open FMTOMO sources.in file and read position and phase of each source into a dict.'''
with open(fnin, 'r') as infile:
nSrc = int(infile.readline())
src_dict = {}
for src_number in range(nSrc):
src_number += 1
teleseismic_flag = int(infile.readline())
if teleseismic_flag != 1: raise ValueError('Source not teleseismic!')
phase = infile.readline().strip()
rad, lat, lon = [float(value) for value in infile.readline().split()[:3]]
# dummy read next 4 lines
for ind in range(4):
infile.readline()
src_dict[src_number] = {'phase': phase,
'depth': rad,
'lat': lat,
'lon': lon,}
return src_dict
def organize_event_names(fnin):
infile = open(fnin, 'r')
events = [line.split()[-1].strip() for line in infile.readlines()[1:]]
infile.close()
return events
def export_otimes(otimes, fn_out):
np.savetxt(fn_out, otimes, fmt=['%8d', '%8d', '%8d', '%8d', '% 4.6f', '% 4.6f'],
header=str(len(otimes)), comments='')
print('Wrote file:', fn_out)
if __name__ == '__main__':
# testing area
prepare_fmtomo_dir_first_run('/data/AdriaArray_Data/fmtomo_adriaarray/v0/test_init')
@@ -1,104 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# get traveltime residuals using synthetic 1D travel times from FMTOMO hybrid method
#
# this script is used to make sure that synthetic travel times are the same for synthetic data residuals (rtimes)
# and observed data residuals, because of small differences between hybrid 1D solver and taup method
# Therefore, correlation output times are absolute (minus source time) values and residuals are calcuated using
# FMTOMO hybrid reference times (e.g. rtimes.dat)
#
import os
import argparse
import shutil
import numpy as np
import matplotlib.pyplot as plt
from pylot.tomography.fmtomo_tools.fmtomo_teleseismic_utils import organize_event_names
# Note: weighting of mean might not be reasonable due to uncertainty distribution along the array
def main(infile_rtimes, fn_events, kde_file, demean=True, no_deref=False, weight_kde=True, weight=False):
eventnames = organize_event_names(fn_events)
assert not(weight and weight_kde), 'Cannot use two weights'
if not no_deref:
reftimes = np.genfromtxt(infile_rtimes)
if weight_kde:
kde_values = np.genfromtxt(kde_file)
assert len(kde_values) == len(reftimes), 'Missmatch in reftimes and kde file length'
nSrc = len(eventnames)
diff_in_means = []
# iterate over all sources
for index in range(nSrc):
srcid = index + 1
eventname = eventnames[index]
print('{} ({}/{})'.format(eventname, srcid, nSrc))
# get pick filename and read observed times
pickfile = os.path.join('picks', eventname)
obsdata_src = np.loadtxt(pickfile, skiprows=3)
# make safety copy
picksafedir = os.path.join('picks', 'save')
if not os.path.isdir(picksafedir):
os.mkdir(picksafedir)
shutil.copy(pickfile, picksafedir)
npicks = len(obsdata_src)
# read observed times from pickfile
tt_obs = obsdata_src[:, 3]
# read uncertainties from pickfile
uncs = obsdata_src[:, 4]
if no_deref:
tt_res = tt_obs
else:
indices = np.where(reftimes[:, 1] == srcid)[0]
assert (len(indices) == npicks), 'Missmatch in indices for srcids'
# read reference teleseismic times from FMTOMO run
tt_ref = reftimes[:, 4][indices]
# calculate residuals
tt_res = tt_obs - tt_ref
# set new residual to obsdata array
obsdata_src[:, 3] = tt_res
# get kde values
#weights = 1./kde_values[:, 2][indices] if weight_kde else None
#
weights = 1. / uncs ** 2 if weight else None
# demean residuals for current source
mean = np.average(tt_res, weights=weights)
mean_unweighted = np.mean(tt_res)
diff_in_means.append(mean - mean_unweighted)
print('Mean:', mean)
print('Unweighted Mean:', mean_unweighted)
print('Demean setting:', demean)
if demean:
obsdata_src[:, 3] -= mean
#obsdata_src[:, 3] = mtimes[:, 4][indices]
# Write new pickfiles
with open(pickfile, 'r') as infile_pick:
header = infile_pick.readlines()[:3]
with open(pickfile, 'w') as outfile_pick:
for line in header:
outfile_pick.write(line)
for line in obsdata_src:
outfile_pick.write('{:10.4f} {:10.4f} {:10.4f} {:15.8f} {:15.8f}\n'.format(*line))
plt.hist(diff_in_means, bins=100)
plt.title('Diffs in means (weighted - unweighted) [s]')
plt.show()
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Calculate residuals for absolute observation times using reference file from FMTOMO')
parser.add_argument('--rtimes', default='rtimes_tele.dat', help='reference_file')
parser.add_argument('--sourcefile', default='input_source_file_P.in', help='input_source_file')
#parser.add_argument('--kdefile', default='kde_weights.txt', help='input file with station kde values for weighting')
parser.add_argument('-nd', '--no_demean', action='store_true', default=False,
help='do not mean correct travel times')
parser.add_argument('-nr', '--no_reftimes', action='store_true', default=False,
help='do not use reference times (e.g. picks are already tt residuals). rtimes file still required at the moment.')
#parser.add_argument('-nwk', '--no_weight_kde', action='store_true', default=True, help='do not weight travel times')
args = parser.parse_args()
#args.kdefile
main(args.rtimes, args.sourcefile, None, not(args.no_demean), weight_kde=False, no_deref=args.no_reftimes) #not(args.no_weight))
@@ -1,174 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import os
import numpy as np
from obspy.geodetics import gps2dist_azimuth, locations2degrees
from pylot.tomography.utils import get_coordinate_from_dist_baz
R=6371.
def main():
profiles_infile = '/home/marcel/AlpArray/vtk_files/points_mark.txt'
gmtslice_dir = '/rscratch/minos13/marcel/fmtomo_alparray/v3.5/alparray_mantle_diehl_crust_included_hf_gradient_smoothing/plot'
####
# maximum point spacing in km (decreases with depth)
dpoints = 1.
dpi = 100
model_depth = 606.
###
with open(profiles_infile, 'r') as infile:
profiles = infile.readlines()
for profile in profiles:
print('Profile: ', profile)
name = profile.split()[0]
lon1, lat1, lon2, lat2 = [float(item) for item in profile.split()[1:]]
def get_gmtslice_gc(gmtplot_dir, lat1, lon1, lat2, lon2, model_depth=606., dpoints=1, fn_out_slice='grid2dvgc.z',
rel=True, fname_vgrid='../vgrids.in', fname_vgrid_ref='../vgridsref.in'):
parfile_str_len = 28
assert (len(fname_vgrid) < parfile_str_len), 'Check length of filename: {}'.format(fname_vgrid)
assert (len(fname_vgrid_ref) < parfile_str_len), 'Check length of filename: {}'.format(fname_vgrid_ref)
infile_default = 'gmtslice_default.in'
fn_out = 'gmtslice.in'
bounds_out_gmt = 'boundgc.gmt'
cwd = os.getcwd()
os.chdir(gmtplot_dir)
with open(infile_default, 'r') as infile:
gmt_infile = infile.readlines()
# calculate great circle distance
max_dist = gps2dist_azimuth(lat1, lon1, lat2, lon2, a=R * 1e3, f=0)[0]/1e3
npointsR = int(model_depth / dpoints + 1)
npointsLateral = int(max_dist / dpoints + 1)
print('nR, nLateral:', npointsR, npointsLateral)
# filename
gmt_infile[3] = '{} \n'.format(fname_vgrid)
gmt_infile[4] = '{} \n'.format(fname_vgrid_ref)
# activate gc generation
gmt_infile[51] = '1 \n'
# modify lines with lat lon boundaries
gmt_infile[52] = '{:5.2f} {:5.2f}\n'.format(lat1, lon1)
gmt_infile[53] = '{:5.2f} {:5.2f}\n'.format(lat2, lon2)
abs_rel = 1 if rel else 0
gmt_infile[58] = '{} \n'.format(abs_rel)
# modify lines with n Points
gmt_infile[65] = '{:<5d} {:<5d}\n'.format(npointsLateral, npointsR)
with open(fn_out, 'w') as outfile:
for line in gmt_infile:
outfile.write(line)
print('Executing gmtslice...')
os.system('gmtslice')
print('Done!')
with open(bounds_out_gmt, 'r') as infile:
bds = [float(bd) for bd in infile.readlines()]
bounds = '-R{bds[0]}/{bds[1]}/{bds[2]}/{bds[3]}'.format(bds=bds)
xyz_string = 'gmt xyz2grd {grid_out} -Ggrid2dvgc.grd -I{bds[4]}+/{bds[5]}+ -ZLB {bounds}'.format(
grid_out=fn_out_slice, bds=bds, bounds=bounds)
print(xyz_string)
os.system(xyz_string)
grid = np.loadtxt(fn_out_slice)
dist_grid = []
lon_grid = []
lat_grid = []
_, azim, bazim = gps2dist_azimuth(lat1, lon1, lat2, lon2, a=R * 1e3, f=0)
#ddist = / (npointsLateral - 1)
#ddepth = (bds[3] - bds[2]) / (npointsR - 1)
for depth in np.linspace(-bds[3], -bds[2], num=npointsR):
for dist in np.linspace(0, locations2degrees(lat1, lon1, lat2, lon2), num=npointsLateral):
lon, lat = get_coordinate_from_dist_baz((lon1, lat1), dist, azim)
lon_grid.append(lon)
lat_grid.append(lat)
#dist = ddist * indexLat
#depth = ddepth * indexR
dist_grid.append(np.array([dist, depth]))
dist_grid = np.array(dist_grid)
lat_grid = np.array(lat_grid)
lon_grid = np.array(lon_grid)
os.chdir(cwd)
return grid, dist_grid, lat_grid, lon_grid, max_dist
def get_gmtslice_depth(gmtplot_dir, depth, fn_out_slice='grid2dvd.z', fname_vgrid='../vgrids.in',
fname_vgrid_ref='../vgridsref.in'):
infile_default = 'gmtslice_default.in'
fn_out = 'gmtslice.in'
bounds_out_gmt = 'bounddp.gmt'
cwd = os.getcwd()
os.chdir(gmtplot_dir)
with open(infile_default, 'r') as infile:
gmt_infile = infile.readlines()
# filename
gmt_infile[3] = '{} \n'.format(fname_vgrid)
gmt_infile[4] = '{} \n'.format(fname_vgrid_ref)
# activate depth slice generation
gmt_infile[41] = '1 \n'
# set depth (negative for whatever reason)
gmt_infile[42] = '{:5.2f} \n'.format(-depth)
with open(fn_out, 'w') as outfile:
for line in gmt_infile:
outfile.write(line)
print('Executing gmtslice...')
os.system('gmtslice')
print('Done!')
with open(bounds_out_gmt, 'r') as infile:
bds = [float(bd) for bd in infile.readlines()]
bounds = '-R{bds[0]}/{bds[1]}/{bds[2]}/{bds[3]}'.format(bds=bds)
xyz_string = 'gmt xyz2grd {grid_out} -Ggrid2dvd.grd -I{bds[4]}+/{bds[5]}+ -ZLB {bounds}'.format(
grid_out=fn_out_slice, bds=bds, bounds=bounds)
print(xyz_string)
#os.system(xyz_string)
grid = np.loadtxt(fn_out_slice)
lonlat = []
lon0, lon1 = bds[:2]
lat0, lat1 = bds[2:4]
nlon = int(bds[4])
nlat = int(bds[5])
for lon in np.linspace(lon0, lon1, num=nlon):
for lat in np.linspace(lat0, lat1, num=nlat):
lonlat.append(np.array([lon, lat]))
lonlat = np.array(lonlat)
os.chdir(cwd)
return grid, lonlat
def grdimage_slice(lat1, lon1, lat2, lon2, bounds, name, npointsLateral, npointsR, dpi):
proj = "-JX{:05.2f}i/{:05.2f}i".format(npointsLateral / dpi, npointsR / dpi)
fnout = 'gmtslice_{}_{:.1f}_{:.1f}-{:.1f}_{:.1f}'.format(name, lat1, lon1, lat2, lon2)
grdimage_string = 'gmt grdimage grid2dvgc.grd {bounds} {proj} -Ba50f10/a50f10 -Cpolar_inv_3.cpt -K > {fnout}'.format(
bounds=bounds, proj=proj, fnout=fnout+'.ps')
print(grdimage_string)
os.system(grdimage_string)
print('Convert to png...')
os.system('convert {} {}'.format(fnout + '.ps', fnout + '.png'))
@@ -1,43 +0,0 @@
import sys
fnin1 = '/data/AlpArray_Data/fmtomo/v6/crust_incl_hf_sm_FIX_DTS_grad_sm30_dm10/it_12/vgrids.in'
fnin2 = '/data/AlpArray_Data/fmtomo/v6/crust_incl_hf_sm_FIX_TESAURO_grad_sm30_dm10/it_12/vgrids.in'
fnout = '/data/AlpArray_Data/fmtomo/v6/crust_incl_hf_sm_FIX_DTS_grad_sm30_dm10/vg_TES_i12sm30dm10.in'
def check_vgrids_header_line(l1, l2, epsilon=1e-6):
items1 = [float(item) for item in l1.split()]
items2 = [float(item) for item in l2.split()]
for i1, i2 in zip(items1, items2):
if not abs(i1 - i2) < epsilon:
return False
return True
def vgrids_diff(fnin1, fnin2, fnout):
diffs = []
with open(fnin1, 'r') as infile1:
with open(fnin2, 'r') as infile2:
with open(fnout, 'w') as outfile:
for index, l1 in enumerate(infile1):
l2 = infile2.readline()
if index < 4:
assert check_vgrids_header_line(l1, l2), 'Different grid dimensions!'
outfile.write(l1)
else:
try:
v1 = float(l1.split()[0])
v2 = float(l2.split()[0])
except Exception as e:
print('Read problem: {}'.format(e))
sys.exit()
vdiff = abs(v2 - v1)
diffs.append(vdiff)
outfile.write('{}\n'.format(vdiff))
print('Finished writing file', fnout)
print('Max diff:', max(diffs))
vgrids_diff(fnin1, fnin2, fnout)
@@ -1,126 +0,0 @@
import os
import json
import numpy as np
import matplotlib.pyplot as plt
from pylot.tomography.fmtomo_tools.fmtomo_teleseismic_utils import organize_receivers
# TODO: demeaning source by source??
def calc_misfit(data, synth, unc):
return np.sum(((data - synth) / unc) ** 2) / len(data)
def calc_mean_residuals(data, synth):
return np.sum(abs(data - synth)) / len(data)
def sort_stations_for_search(station_coords, receivers_dict):
epsilon = 1e-1 # very large epsilon actually...
coords_unique = coords_unique_receivers(receivers_dict)
latlon_dict = {}
for nwst_id, coords in station_coords.items():
lat = coords['latitude']
lon = coords['longitude']
for latu, lonu in coords_unique:
if abs(lat - latu) < epsilon and abs(lon - lonu) < epsilon:
latlon_dict[(latu, lonu)] = nwst_id
return latlon_dict
def extract_stations_for_network(station_coords, network_id):
station_coords_extracted = {}
for nwst_id, coords in station_coords.items():
nw, st = nwst_id.split('.')
if nw == network_id:
station_coords_extracted[nwst_id] = coords
return station_coords_extracted
def get_receiver_ids(latlon_list, receivers_dict):
receiver_ids = []
for recid, coords in receivers_dict.items():
lat, lon = (coords['lat'], coords['lon'])
if (lat, lon) in latlon_list:
receiver_ids.append(recid)
return receiver_ids
def coords_unique_receivers(receivers_dict):
coords_unique = []
for coords in receivers_dict.values():
latlon_tuple = (coords['lat'], coords['lon'])
if not latlon_tuple in coords_unique:
coords_unique.append(latlon_tuple)
return coords_unique
#def plot_residuals()
def main():
#wdir = '/rscratch/minos13/marcel/fmtomo_alparray/alparray_mantle_diehl_crust_included_v3_hf'
wdir = '/data/AlpArray_Data/fmtomo/v5/crust_incl_hf_sm_FIX_DTS_grad_sm30_dm10'
os.chdir(wdir)
receivers_dict = organize_receivers('receivers.in')
print(wdir)
misfits = {}
mean_residuals = {}
for extract_network in [None, 'Z3', 'ZS', ]:
misfits[extract_network] = []
mean_residuals[extract_network] = []
with open('/rscratch/minos13/marcel/alparray/station_coords.json', 'r') as infile:
station_coords = json.load(infile)
print('\nCalculating residuals for network:', extract_network)
if extract_network:
station_coords = extract_stations_for_network(station_coords, extract_network)
latlon_dict = sort_stations_for_search(station_coords, receivers_dict)
rec_ids = get_receiver_ids(list(latlon_dict.keys()), receivers_dict)
otimes = np.genfromtxt('otimes.dat', skip_header=1)
#otimes_orig = np.genfromtxt('otimes_orig.dat', skip_header=1)
ttimes = otimes[:, 4]
uncs = otimes[:, 5]
nsrc = int(otimes[-1, 1])
rtimes = np.genfromtxt('rtimes_tele.dat')[:, 4]
for itstep in range(0, 25):
nRays = 0
mtimes_all = np.genfromtxt('it_{}/arrivals.dat'.format(itstep))
mtimes = mtimes_all[:, 4]
mtimes_diff = mtimes - rtimes
for srcid in range(nsrc):
srcid += 1
# get all indices of current source id
indices = np.where(mtimes_all[:, 1] == srcid)
nRays += len(indices[0])
mtimes_diff[indices] -= np.mean(mtimes_diff[indices])
# get all indices that are in rec_ids list as well
mask_recs = np.isin(mtimes_all[:, 0].astype(int), rec_ids)
mf = calc_misfit(ttimes[mask_recs], mtimes_diff[mask_recs], uncs[mask_recs])
sr = calc_mean_residuals(ttimes[mask_recs], mtimes_diff[mask_recs])
misfits[extract_network].append(mf)
mean_residuals[extract_network].append(sr)
print('It: {}, misfit: {}, mean res: {}, nrays: {}'.format(itstep, mf, sr, nRays))
#plt.plot(mean_residuals[extract_network], label=extract_network)
plt.plot(misfits[extract_network], label=extract_network)
plt.title(wdir)
plt.ylabel('Mean residuals [s]')
plt.xlabel('Iteration')
plt.legend()
plt.show()
if __name__ == '__main__':
main()
@@ -1,69 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import glob, os, shutil
from fmtomo_tools.fmtomo_grid_utils import read_vgrid, write_vgrid
pjoin = os.path.join
pwd = '/data/AlpArray_Data/fmtomo/v6/crust_incl_hf_sm_FIX_DTS_grad_sm30_dm10_EASI_test_Plomerova/'
vgrid_file_in = pjoin(pwd, 'vgrids_dts_crust.in')
vgrid_file_out = pjoin(pwd, 'vgrids_dts_crust_variance_slice.in')
latmin_rec, latmax_rec = 44.8, 51.3
lonmin_rec, lonmax_rec = 11.94, 14.66
latmin_grid, latmax_grid = 44.45, 52.55
lonmin_grid, lonmax_grid = 10.83, 15.77
def modify_pickfiles():
picks_path = pjoin(pwd, 'picks_orig')
os.chdir(picks_path)
outdir = pjoin(pwd, 'picks')
infiles = glob.glob('*.ttf')
for infile in infiles:
lines_out = []
with open(infile, 'r') as fid:
eventid = infile.split('.ttf')[0]
npicks = int(fid.readline())
# copy source/phase header
for _ in range(2):
lines_out.append(fid.readline())
for line in fid:
lat, lon = [float(item) for item in line.split()[:2]]
if latmin_rec < lat < latmax_rec and lonmin_rec < lon < lonmax_rec:
lines_out.append(line)
fn_out = pjoin(outdir, infile)
with open(fn_out, 'w') as outfile:
# number of picks: list contents - 2 header lines
outfile.write(f'{len(lines_out) - 2}\n')
for line in lines_out:
outfile.write(line)
print(f'Modified {eventid}: Removed {npicks - len(lines_out)} out of {npicks} picks/stations')
os.chdir(pwd)
def modify_variance_slice():
grid, gridN, gridDelta, gridStart = read_vgrid(vgrid_file_in)
for index, latlon in enumerate(zip(grid['lats'], grid['lons'])):
lat, lon = latlon
if not latmin_grid < lat < latmax_grid or not lonmin_grid < lon < lonmax_grid:
grid['covs'][index] = 1e-6
write_vgrid(grid, gridN, gridDelta, gridStart, vgrid_file_out)
#modify_pickfiles()
modify_variance_slice()
@@ -1,294 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import numpy as np
from scipy.interpolate import RegularGridInterpolator
import matplotlib.pyplot as plt
from pylot.tomography.fmtomo_tools.fmtomo_teleseismic_utils import export_otimes, organize_receivers
def crustal_correction_using_differences(fname_otimes, fname_otimes_diff, fname_otimes_out):
otimes = np.loadtxt(fname_otimes, skiprows=1)
otimes_diff = np.loadtxt(fname_otimes_diff, skiprows=1)
src_means = source_means(otimes_diff)
#mean_diffs = np.mean([float(item.split()[4]) for item in otimes_diff[1:]])
print('Mean_diffs of all sources: ', np.mean(list(src_means.values())))
# TODO: Check if demeaning is useful for crustal correction using synthetics (was it b4 using ak135_diehl 1D?)
# Update 27.5.2020: If not demeaned, overall velocity perturbation shifted to negative in whole upper mantle
# BUT: demean has to be executed for each source, not with global mean!
with open(fname_otimes_out, 'w') as outfile:
outfile.write('{}\n'.format(len(otimes)))
for index, line in enumerate(otimes):
src_id = line[1]
ttime = line[4]
ttime_diff = otimes_diff[index][4]
new_time = ttime - ttime_diff + src_means[src_id]
line[4] = new_time
for col_index, item in enumerate(line):
if col_index < 4:
fmt = '{:10g} '
else:
fmt = '{:10.8f} '
outfile.write(fmt.format(item))
outfile.write('\n')
def source_means(otimes):
# catch all source ids from otimes file
src_ids = np.unique(otimes[:, 1])
print('Source IDs:', src_ids)
# create dictionary containing means of travel time (differences) for each source (key)
src_means = {src_id: np.mean(otimes[otimes[:, 1] == src_id][:, 4]) for src_id in src_ids}
print('Source means:')
for srcid, val in src_means.items():
print(srcid, ': ', val)
return src_means
def crustal_correction_using_residual_map(fname_otimes, fname_residuals, receivers_in, fname_otimes_out):
''' correct using residuals from numpy file with an array of shape (lons, lats, residuals)'''
otimes = np.loadtxt(fname_otimes, skiprows=1)
rec_dict = organize_receivers(receivers_in)
lons, lats, res = np.load(fname_residuals, allow_pickle=True)
lonsU = np.unique(lons)
latsU = np.unique(lats)
#grid = (lonsU, latsU)
#shape = [len(item) for item in grid]
#res = res.reshape(shape)
# not very efficient but very lazy (just interpolate value for each ray, i.e. receiver, not unique,
# which is quite redundant)
rginter = RegularGridInterpolator((lonsU, latsU), res, bounds_error=False, fill_value=0.)
test_rginter(rginter)
for line in otimes:
rec_id = int(line[0])
lonlat = (rec_dict[rec_id]['lon'], rec_dict[rec_id]['lat'])
res = rginter(lonlat)
line[4] -= res
src_means = source_means(otimes)
for src_id, src_mean in src_means.items():
otimes[otimes[:, 1] == src_id, 4] -= src_mean
with open(fname_otimes_out, 'w') as outfile:
outfile.write('{}\n'.format(len(otimes)))
for line in otimes:
for col_index, item in enumerate(line):
if col_index < 4:
fmt = '{:10g} '
else:
fmt = '{:10.8f} '
outfile.write(fmt.format(item))
outfile.write('\n')
def test_rginter(rginter):
lons = np.linspace(0, 22, 220)
lats = np.linspace(40, 52, 120)
lonsg, latsg = np.meshgrid(lons, lats)
data = rginter((lonsg, latsg))
pcm = plt.pcolormesh(lonsg, latsg, data)
plt.colorbar(pcm)
plt.show()
def get_otimes_diff(fname_arrivals1, fname_arrivals2, fname_out='otimes_diff.dat'):
'''
Calculate file containing travel time differences between fname_arrivals1 and fname_arrivals2, e.g. for crustal
correction.
:param fname_arrivals1:
:param fname_arrivals2:
:return:
'''
with open(fname_arrivals1, 'r') as infile:
arrivals1 = infile.readlines()
with open(fname_arrivals2, 'r') as infile:
arrivals2 = infile.readlines()
assert len(arrivals1) == len(arrivals2), 'Length of input arrival files differs'
print('Calculating differences between file {} and {}'.format(fname_arrivals1, fname_arrivals2))
columnString = '{} '
nArrivals = len(arrivals1)
with open(fname_out, 'w') as outfile:
outfile.write('{}\n'.format(nArrivals))
for index in range(nArrivals):
line1 = arrivals1[index]
line2 = arrivals2[index]
for item in line1.split()[:4]:
outfile.write(columnString.format(item))
diff = float(line1.split()[4]) - float(line2.split()[4])
outfile.write(columnString.format(diff))
outfile.write('\n')
print('Wrote {} lines to file {}'.format(nArrivals, fname_out))
def get_synthetic_obsdata_legacy(fname_m1, fname_m2, fname_otimes_orig, fname_out='otimes_modif.dat'):#, p_err=0.1):
'''
Create synthetic obsdata of model 1 relative to model 2 (usually 1D model synthetic travel times)
:param fname_m1: arrivals.dat file of synthetic travel times (e.g. from checkerboard test)
:param fname_m2: arrivals.dat file of synthetic travel times (e.g. ak135 model)
:param fname_otimes_orig: original otimes file for pick uncertainties
:param fname_out: otimes.dat file with output
:param p_err: picking error
:return:
'''
with open(fname_m1, 'r') as infile:
arrivals_model1 = infile.readlines()
with open(fname_m2, 'r') as infile:
arrivals_model2 = infile.readlines()
with open(fname_otimes_orig, 'r') as infile:
otimes = infile.readlines()[1:]
assert(len(arrivals_model1) == len(arrivals_model2) == len(otimes)), 'missmatch in lengths of files!'
diffs = []
with open(fname_out, 'w') as outfile:
outfile.write('{}\n'.format(len(arrivals_model1)))
for line_model1, line_model2, line_otimes in zip(arrivals_model1, arrivals_model2, otimes):
for item in line_model2.split()[:4]:
outfile.write('{} '.format(item))
ttime_model1 = float(line_model1.split()[4])
ttime_model2 = float(line_model2.split()[4])
pickerror = float(line_otimes.split()[5])
# pickerror = (p_err+2*p_err*abs(np.random.randn()))
ttime_diff = ttime_model1 - ttime_model2
diffs.append(ttime_diff)
outfile.write('{} {}\n'.format(ttime_diff, pickerror))
mean_diff = np.mean(diffs)
abs_mean_diff = np.mean(np.abs(diffs))
print('Mean_diff: {} - abs_mean_diff: {}'.format(mean_diff, abs_mean_diff))
print('Done with {} travel times. Output in file: {}'.format(len(arrivals_model1), fname_out))
def get_synthetic_obsdata(fname_m1, fname_m2, fname_otimes_orig, fname_out='otimes_modif.dat', sigma='original'):
'''
Create synthetic obsdata of model 1 relative to model 2 (usually 1D model synthetic travel times)
:param fname_m1: arrivals.dat file of synthetic travel times (e.g. from checkerboard test)
:param fname_m2: arrivals.dat file of synthetic travel times (e.g. ak135 model)
:param fname_otimes_orig: original otimes file for pick uncertainties
:param fname_out: otimes.dat file with output
:param p_err: picking error
:return:
'''
arrivals_model1 = np.genfromtxt(fname_m1)
arrivals_model2 = np.genfromtxt(fname_m2)
otimes = np.genfromtxt(fname_otimes_orig, skip_header=1)
assert(len(arrivals_model1) == len(arrivals_model2) == len(otimes)), 'missmatch in lengths of files!'
# get new array as copy from model1 after deleting last column (not needed for otimes)
arrivals_diff = np.delete(arrivals_model1, 6, 1)
# overwrite time column by diffs
arrivals_diff[:, 4] -= arrivals_model2[:, 4]
# overwrite last column by pick errors
arrivals_diff[:, 5] = otimes[:, 5]
# get max nSrc (in last line of sorted arrivals files)
nSrc = int(arrivals_diff[-1, 1])
print('N sources:', nSrc)
if sigma not in [None, False]:
print('Applying gaussian noise with sigma={}'.format(sigma))
if sigma == 'original':
sigma_val = otimes[:, 5]
else:
sigma_val = sigma
gauss_noise = np.random.normal(0., sigma_val, len(arrivals_diff[:, 4]))
plt.axhline(0., color='grey')
plt.vlines(np.arange(0, len(arrivals_diff)), arrivals_diff[:, 4], arrivals_diff[:, 4] + gauss_noise,
color='grey', linestyles='dashed')
plt.plot(arrivals_diff[:, 4], 'r.')
arrivals_diff[:, 4] += gauss_noise
for index in range(nSrc):
src_id = index + 1
# get indices for this source ID
indices = np.where(arrivals_diff[:, 1] == src_id)
# get mean for that srcid
mean = np.mean(arrivals_diff[:, 4][indices])
print('Srcid: {}, mean: {}'.format(src_id, mean))
# de-mean array
arrivals_diff[:, 4][indices] -= mean
if sigma not in [None, False]:
plt.axhline(0., color='grey')
#plt.vlines(np.arange(0, len(arrivals_diff)), arrivals_diff[:, 4], arrivals_diff[:, 4] + gauss_noise)
plt.plot(arrivals_diff[:, 4], 'b.')
plt.figure()
plt.hist(gauss_noise, bins=100)
plt.show()
export_otimes(arrivals_diff, fname_out)
def plot_histograms_for_crustal_corrections():
import matplotlib.pyplot as plt
ttdiffs_no_crust = []
ttdiffs_crust = []
ttdiffs_corrected = []
#get_synthetic_obsdata('it_synth_forward/arrivals.dat', 'arrivals_ak135_diehl.dat', 'otimes_three_boxes_no_crust.dat')
#get_synthetic_obsdata('it_synth_forward_with_crust/arrivals.dat', 'arrivals_ak135_diehl.dat', 'otimes_three_boxes_with_diehl_crust.dat')
with open('otimes_three_boxes_with_diehl_crust.dat', 'r') as infile:
lines_crust = infile.readlines()[1:]
with open('otimes_three_boxes_no_crust.dat', 'r') as infile:
lines_no_crust = infile.readlines()[1:]
with open('otimes_three_boxes_crustal_corrected.dat', 'r') as infile:
lines_corrected = infile.readlines()[1:]
for line in lines_crust:
ttdiffs_crust.append(float(line.split()[4]))
for line in lines_no_crust:
ttdiffs_no_crust.append(float(line.split()[4]))
for line in lines_corrected:
ttdiffs_corrected.append(float(line.split()[4]))
plt.hist(ttdiffs_crust, bins=100, label='tt-diff including crustal structure.')
plt.hist(ttdiffs_no_crust, bins=100, label='tt-diff without crustal structure')
plt.hist(ttdiffs_corrected, bins=100, label='tt-diff after correcting for crustal structure')
plt.xlabel('Travel time differences to ak135_diehl 1D model [s]')
plt.legend()
if __name__ == '__main__':
#wdir = '/rscratch/minos13/marcel/fmtomo_alparray/alparray_mantle_diehl_crustal_corrections_v3_hf'
#fname1 = os.path.join(wdir, 'arrivals_ak135di_crust.dat')
#fname2 = os.path.join(wdir, 'arrivals_ak135di.dat')
#get_otimes_diff(fname1, fname2, os.path.join(wdir, 'otimes_diff.dat'))
#get_synthetic_obsdata('arrivals_cb_N2.dat', 'arrivals_ak135.dat', 'otimes_cb_N2.dat')
#os.chdir('/data/AlpArray_Data/fmtomo/v4/different_test_runs/alparray_mantle_waldhauser_crust_corrected_covs_hf_gradient_smoothing')
#os.chdir('/data/AlpArray_Data/fmtomo/v4/different_test_runs/alparray_mantle_waldhauser_crust_corrected_covs_hf_gradient_smoothing')
#crustal_correction_using_residual_map('otimes.dat', 'wh_residuals.npy', 'receivers.in', 'otimes_corr_wh.dat')
#os.chdir('/data/AlpArray_Data/fmtomo/v4/different_test_runs/alparray_mantle_diehl_crust_corrected_residuals_stacked_gradient_smoothing')
#crustal_correction_using_residual_map('otimes.dat', 'diehl_2009_residuals.npy', 'receivers.in', 'otimes_corr_diehl.dat')
#os.chdir('/data/AlpArray_Data/fmtomo/v6/crust_corrected_VERTICAL_hf_sm_FIX_DTS_grad_sm30_dm10')
#crustal_correction_using_residual_map('otimes.dat', 'dts_filt_12.5_12.5_7.5_CRUST_ONLY_RESIDUALS.npy', 'receivers.in', 'otimes_corr_dts.dat')
os.chdir('/data/AlpArray_Data/fmtomo/v6/crust_corrected_WH_hf_sm_FIX_DTS_grad_sm30_dm10')
crustal_correction_using_residual_map('otimes.dat', 'wh_residuals_SORTED.npy', 'receivers.in', 'otimes_corr_wh.dat')
#crustal_correction_using_residual_map('otimes.dat', 'wh_residuals.npy', 'receivers.in', 'otimes_corr_wh.dat')
@@ -1,154 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Different functions to modify FMTOMO velocity(inversion) grid
import argparse
import numpy as np
from math import erf
from pylot.tomography.fmtomo_tools.fmtomo_grid_utils import read_vgrid, write_vgrid, write_vtk
def main(fname_in, fname_out, fname_vtk_out=None, cov_perc=0.15, bounds=[40, 60]):
vgrid, gridN, gridDelta, gridStart = read_vgrid(fname_in)
print('Modifying covariances...')
vgrid['covs'] = []
for depth, vp in zip(vgrid['depths'], vgrid['vps']):
vgrid['covs'].append(covariance_for_depth(depth, vp, cov_perc, bounds))
write_vgrid(vgrid, npts=gridN, delta=gridDelta, start=gridStart, fname=fname_out)
if fname_vtk_out:
write_vtk(vgrid, fname_vtk_out, write_data=['vps', 'covs'])
def modify_vgrid_box(vgrid, vgrid_key, min_lon, max_lon, min_lat, max_lat, min_depth, max_depth,
val_center, val_border, scale_factor, use_erf=True, extend_to_top=False):
'''
Modify a value (vgrid_key) of vgrids.in using an error function. Value will be increase smoothly to the borders
of the external model. This function was used to prevent changes of the inversion result in the region of the
initial crustal model that was corrected for. Value smoothly increases at the borders of the initial model.
'''
# get central points of external model (here value will be minimal)
c_lon = 0.5 * (min_lon + max_lon)
c_lat = 0.5 * (min_lat + max_lat)
c_depth = 0.5 * (min_depth + max_depth)
# get half the extent of the model dimensions for function scaling
dlon = 0.5 * (max_lon - min_lon)
dlat = 0.5 * (max_lat - min_lat)
ddepth = 0.5 * (max_depth - min_depth)
print('Modifying {}...'.format(vgrid_key))
print('Center {key}: {val_c}, border {key}: {val_b}'.format(key=vgrid_key, val_c=val_center, val_b=val_border))
if not vgrid_key in vgrid.keys() or not vgrid[vgrid_key]:
vgrid[vgrid_key] = list(np.ones(len(vgrid['depths'])))
for index, tup in enumerate(zip(vgrid['lons'], vgrid['lats'], vgrid['depths'])):
lon, lat, depth = tup
if (min_lon <= lon <= max_lon and min_lat <= lat <= max_lat and depth <= max_depth):
x = abs(lon - c_lon) / dlon
y = abs(lat - c_lat) / dlat
if extend_to_top and depth < c_depth:
z = 0
else:
z = abs(depth - c_depth) / ddepth
if use_erf:
point_val = smoothing_erf(x, y, z, val_center, val_border, scale_factor=scale_factor)
else:
point_val = val_center
else:
point_val = val_border
vgrid[vgrid_key][index] *= point_val
return vgrid
def modify_vgrid_gradient(vgrid, vgrid_key, val_top, val_bot):
'''
Modify a value (vgrid_key) of vgrids.in using a linear gradient from val_top to val_bot
'''
print('Modifying {} with linear gradient...'.format(vgrid_key))
print('Top: {}, bot: {}'.format(val_top, val_bot))
if not vgrid_key in vgrid.keys():
vgrid[vgrid_key] = list(np.ones(len(vgrid['depths'])))
depth_min = min(vgrid['depths'])
depth_max = max(vgrid['depths'])
for index, tup in enumerate(zip(vgrid['lons'], vgrid['lats'], vgrid['depths'])):
lon, lat, depth = tup
vgrid[vgrid_key][index] *= linear_gradient(depth, depth_min=depth_min, depth_max=depth_max, val_top=val_top,
val_bot=val_bot)
return vgrid
def linear_gradient(depth, depth_min, depth_max, val_top, val_bot):
return (val_bot - val_top) * depth / (depth_max - depth_min) + val_top
def smoothing_erf(x, y, z, val_border, val_center, scale_factor=1.):
a = val_center
b = val_border
sx = sy = sz = scale_factor
f = (a - b) * (1. / 3. * (erf(2. * sx * (x - 1)) + erf(2. * sy * (y - 1)) + erf(2. * sz * (z - 1))) + 1.) + b
return f
def covariance_for_depth(depth, vp, cov_perc, bounds):
'''
Function that returns covariance values for certain depths, written to give low variance to crust, intermediate
to an interlayer and high variance to everything else.
:param depth: depth in kilometers
:return: covariance
'''
if depth <= bounds[0]:
return 0.05
elif bounds[0] < depth <= bounds[1]:
return 0.5 * cov_perc * vp
else:
return cov_perc * vp
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Prepare grid for fm3d teleseismic hybrid calculation.')
parser.add_argument('fname_in', help='input filename (vgrids.in)')
parser.add_argument('fname_out', help='output filename (vgrids_new.in)')
parser.add_argument('--fname_out_vtk', default=None, help='vtk output filename')
parser.add_argument('--cov_border', default=1.0, help='covariance for the model outside crustal model boundaries')
parser.add_argument('--cov_center', default=0.05, help='maximum covariance in the center of the crustal model')
parser.add_argument('--smooth_border', default=1., help='smoothing factor for the rest of the box')
parser.add_argument('--smooth_center', default=0.5, help='smoothing factor inside SWATH-D box')
args = parser.parse_args()
vgrid, gridN, gridDelta, gridStart = read_vgrid(args.fname_in)
#main(args.fname_in, args.fname_out, args.fname_out_vtk)
#vgrid = modify_vgrid_gradient(vgrid, 'smoothfactors', 1.0, 2.0)
# bounds for waldhauser residual corrections
wh_bounds = dict(lon0 = 3.23, lon1 = 13.96, lat0 = 43.18, lat1 = 49.45)
vgrid = modify_vgrid_box(vgrid, vgrid_key='covs', min_lon=wh_bounds['lon0'], max_lon=wh_bounds['lon1'],
min_lat=wh_bounds['lat0'], max_lat=wh_bounds['lat1'], min_depth=-5.0, max_depth=60.0,
val_center=float(args.cov_center), val_border=float(args.cov_border),
scale_factor=3, use_erf=True, extend_to_top=True)
#vgrid = modify_vgrid_box(vgrid, vgrid_key='covs', min_lon=2.2547, max_lon=17.0999, min_lat=41.0517,
# max_lat=50.4984, min_depth=-5.0, max_depth=70.0, val_center=float(args.cov_center),
# val_border=float(args.cov_border), scale_factor=3, use_erf=True, extend_to_top=True)
#vgrid = modify_vgrid_box(vgrid, vgrid_key='smoothfactors', min_lon=8.9, max_lon=15.3, min_lat=45.,
# max_lat=48., min_depth=-15.0, max_depth=610.0, val_center=float(args.smooth_center),
# val_border=float(args.smooth_border), scale_factor=1., use_erf=True)
# MP MP TEST TEST TEST ++++++++++++++++++++++++++++++++++++++++++++++++
#grid = modify_vgrid_box(grid, vgrid_key='smoothfactors', min_lon=11., max_lon=35., min_lat=30.,
# max_lat=61., min_depth=-5.0, max_depth=600.0, val_center=float(args.smooth_center),
# val_border=float(args.smooth_border), scale_factor=.4)
# MP MP TEST TEST TEST ------------------------------------------
write_vgrid(vgrid, npts=gridN, delta=gridDelta, start=gridStart, fname=args.fname_out)
if args.fname_out_vtk:
write_vtk(vgrid, args.fname_out_vtk, write_data=['vps', 'covs', 'smoothfactors'])
@@ -1,26 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import matplotlib.pyplot as plt
def plot_otimes(otimes_fname):
with open(otimes_fname, 'r') as infile:
input_list = infile.readlines()[1:]
ray_id = [int(line.split()[0]) for line in input_list]
ttimes = [float(line.split()[-2]) for line in input_list]
uncertainties = [float(line.split()[-1]) for line in input_list]
plt.axhline(0, linestyle=':', color='k')
plt.errorbar(ray_id, ttimes, yerr=uncertainties, fmt='o', markersize=1, ecolor='0.5', elinewidth=0.5)
plt.show()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Plot ttimes with errors of FMTOMO file otimes.dat')
parser.add_argument('infile', help='inputfile')
args = parser.parse_args()
plot_otimes(args.infile)
@@ -1,341 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import json
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
from obspy.geodetics.base import gps2dist_azimuth
import cartopy.crs as ccrs
from pylot.tomography.fmtomo_tools.compare_arrivals_hybrid import organize_receivers, organize_sources, organize_event_names
from pylot.tomography.map_utils import make_map
from pylot.tomography.utils import normed_figure
def plot_map(otimes_fname, sources_fname, receivers_fname, isf, rtimes_fname=None, arrivals_fname=None, colorbar=True,
title=True, stack=False, source_ids=(), savefig_dir='', demean=True, absolute=False, clat=42.25, clon=17.5,#clat=46., clon=11.,
file_ext='png', max_abs=3., relative_to_otimes=False, only_otimes=False):
if savefig_dir:
if not os.path.isdir(savefig_dir):
os.mkdir(savefig_dir)
src_dict = organize_sources(sources_fname)
rec_dict = organize_receivers(receivers_fname)
eventnames = organize_event_names(isf)
residuals_dict = read_fmtomo_tt_file(otimes_fname, rec_dict, rtimes_fname=rtimes_fname, synth_fname=arrivals_fname,
demean=demean, absolute=absolute, height_correction_vp=5.5,
relative_to_otimes=relative_to_otimes, only_otimes=only_otimes)
if stack:
residuals_dict = stack_sources(residuals_dict)
with open('stacked_residuals.json', 'w') as outfile:
json.dump(residuals_dict, outfile)
count = 0
if savefig_dir:
fig = normed_figure(width_cm=12, ratio=12./9.)
#fig = plt.figure(figsize=(12, 9))
else:
fig = plt.figure()
if stack or source_ids is not [] or savefig_dir:
count = 1
# increase point size if not stacked
sizefactor_stacked = {True: 30,
False: .2e4}
for src_id, dic in residuals_dict.items():
eventname = eventnames[src_id - 1]
if source_ids != []:
if not src_id in source_ids:
continue
if max_abs == 'auto':
max_abs = np.max(np.abs(np.array(dic['ttimes'])))
# if not stack and not savefig_dir and source_ids == []:
# count += 1
# if count == 1:
# ax = fig.add_subplot(3, 3, count)
# ax0 = ax
# else:
# ax = fig.add_subplot(3, 3, count, sharex=ax0, sharey=ax0)
#
# ax.text(0.1, 0.9, 'Source ID {}, {}'.format(src_id, src_dict[src_id]['phase']), transform=ax.transAxes)
# else:
# ax = fig.add_subplot(111)
if stack and title:
plt.title('Stacked {} sources. Size relates to number of stacks per receiver.'.format(len(src_dict)),
y=1.05)
ax = make_map(draw_model=False, draw_faults=True, model_legends=False, clon=clon, clat=clat,
width = 30, height = 21,) # , width=6e6, height=5e6)
if not stack:
slat, slon = src_dict[src_id]['lat'], src_dict[src_id]['lon']
dist = plot_source(slat, slon)
baz = gps2dist_azimuth(clat, clon, slat, slon, a=6.371e6, f=0)[1]
if title:
plt.title(
'Plot of source {}. Distance: {:.0f}$^\circ$. BAZ: {:.0f}$^\circ$'.format(eventname, dist, baz),
y=1.05)
#ax.set_xlabel('Longitude [$^\circ$]')
#ax.set_ylabel('Latitude [$^\circ$]')
# prepare grids for contour plot
#lonaxis = np.linspace(min(dic['lons']), max(dic['lons']), 250)
#lataxis = np.linspace(min(dic['lats']), max(dic['lats']), 250)
#longrid, latgrid = np.meshgrid(lonaxis, lataxis)
#ttimes_grid = griddata((dic['lats'], dic['lons']), dic['ttimes'], (latgrid, longrid), method='linear')
#levels = np.linspace(min(dic['ttimes']), max(dic['ttimes']), 75)
cmap = plt.get_cmap('seismic') if not absolute else plt.get_cmap('viridis')
vmin = -max_abs if not absolute else None
vmax = max_abs if not absolute else None
sc = ax.scatter(dic['lons'], dic['lats'], c=np.array(dic['ttimes']), cmap=cmap,
vmin=vmin, vmax=vmax, edgecolors='grey', linewidths=0.2,
s=sizefactor_stacked[stack]*np.array(dic['nttimes'])/len(src_dict), zorder=10,
transform=ccrs.PlateCarree(), alpha=0.75)
sc.set_edgecolor('0.')
if colorbar:
cb = plt.colorbar(sc, label='ttime [s]', shrink=0.5)
if stack:
savefig_path = os.path.join(savefig_dir, 'stacked_events.{}'.format(file_ext))
else:
#fname = f'baz{baz:03.0f}_dist{dist:03.0f}_{eventname}_srcID{src_id}.{file_ext}'
fname = f'{eventname}_srcID{src_id}.{file_ext}'
savefig_path = os.path.join(savefig_dir, fname)
if not savefig_dir and not count % 9:
plt.show()
fig = plt.figure()#figsize=(16, 9), dpi=300.)
count = 0
if savefig_dir:
ax.figure.savefig(savefig_path, dpi=300., bbox_inches='tight', pad_inches=0.)
print('Wrote file {}'.format(savefig_path))
plt.clf()
if not savefig_dir:
plt.show()
def plot_source(lat, lon, clat=46., clon=11.):
#basemap.drawgreatcircle(lon, lat, clon, clat, color='k', zorder=15, linestyle='dashed')
dist, azim, bazim = gps2dist_azimuth(lat, lon, clat, clon, a=6.371e6, f=0)
dist_deg = dist/1000./np.pi/2./6371.*360.
return dist_deg
#x = np.cos(np.deg2rad(azim))
#y = np.sin(np.deg2rad(azim))
#print(x, y)
#ax.plot([0, x], [0, y], 'r', zorder=15)
def read_fmtomo_tt_file(otimes_fname, rec_dict, synth_fname=None, rtimes_fname=None, demean=True, absolute=False,
height_correction_vp=None, R=6371., relative_to_otimes=True, only_otimes=False):
#with open(otimes_fname, 'r') as infile:
# # skip first line for otimes.dat. Frist line contains N_rays
# obsarray = infile.readlines()[1:]
obsarray = np.loadtxt(otimes_fname, skiprows=1)
if height_correction_vp:
if absolute:
print('APPLICATION OF HEIGHT CORRECTION FOR ABS NOT IMPLEMENTED YET. Not needed!?')
#print('Applying height correction of {} km/s'.format(height_correction_vp))
else:
height_correction_vp = None
print('Will not apply height correction for relative values.')
if synth_fname:
synth_array = np.genfromtxt(synth_fname)
if rtimes_fname:
ref_array = np.genfromtxt(rtimes_fname)
if synth_fname and rtimes_fname:
#with open(synth_fname, 'r') as infile:
# synth_array = infile.readlines()
#with open(rtimes_fname, 'r') as infile:
# ref_array = infile.readlines()
#mean_obs = np.mean(obsarray[:, 4])
#mean_synth = np.mean(synth_array[:, 4])
#mean_ref = np.mean(ref_array[:, 4])
#mean_rel_synth = mean_synth - mean_ref
#print('Means:\nobserved: {}, relative {}'.format(mean_obs, mean_rel_synth))
synth_src_means = {}
nsrc = obsarray[-1, 1]
for index in range(int(nsrc)):
srcid = index + 1
indices = np.where(synth_array[:, 1].astype(int) == srcid)
synth_src_means[srcid] = np.mean(synth_array[indices, 4] - ref_array[indices, 4])
print('Average mean for sources: {} s'.format(np.mean(list(synth_src_means.values()))))
if demean:
print('Removing mean from synthetic times...')
else:
print('Will not mean-correct travel times')
# mean_rel_synth = 0.
residuals_dict = {}
for index, line in enumerate(obsarray):
rec_id = int(line[0])
src_id = int(line[1])
ttime = line[4] if relative_to_otimes or only_otimes else 0
# get residuals from reference file if fname is given
if synth_fname:
# get synthetic time
ttime_syn = synth_array[index][4]
if rtimes_fname:
# get reference time (1d travel time)
ttime_ref = ref_array[index][4]
if synth_fname and rtimes_fname:
# calculate synthetic time relative to 1d travel time
ttime_rel_syn = ttime_syn - ttime_ref
#print(ttime_ref, ttime_syn, ttime_rel_syn, ttime, ttime-ttime_rel_syn)
# calculate difference between relative observed and model times, multiply with -1 to get tsynth - tobs
mean_rel_src = synth_src_means[srcid] if demean else 0.
if not only_otimes:
ttime = -1 * (ttime_rel_syn - ttime - mean_rel_src)
if absolute:
ttime = ttime_syn
try:
uncertainty = line[5]
except:
uncertainty = 0
# create dictionary for source if not exists
if not src_id in residuals_dict.keys():
residuals_dict[src_id] = {'lats': [],
'lons': [],
'rads': [],
'ttimes':[],
'nttimes': [],
'uncerts': []}
# chose correct dictionary
dic = residuals_dict[src_id]
# get coordinates from organized receivers dictionary
dic['lats'].append(rec_dict[rec_id]['lat'])
dic['lons'].append(rec_dict[rec_id]['lon'])
dic['rads'].append(rec_dict[rec_id]['rad'])
# rad is depth?
#elev = - rec_dict[rec_id]['rad']
#height_correction_vp = 0
#station_height_corr = elev / (height_correction_vp) if height_correction_vp else 0.
#if elev < 0: print(elev, station_height_corr)
# MP MP NO HEIGHT CORRECTION FOR FMTOMO! REFTIMES CONTAIN STATION HIGHT!!!!!
dic['ttimes'].append(ttime) # - station_height_corr)
# number of ttimes will be set to 1 (determines size in scatter, only relevant for stacked ttimes)
dic['nttimes'].append(1)
dic['uncerts'].append(uncertainty)
return residuals_dict
def stack_sources(residuals_dict):
all_ttimes = {}
all_uncs = {}
for src_id, dic in residuals_dict.items():
for index in range(len(dic['lats'])):
lat = dic['lats'][index]
lon = dic['lons'][index]
rad = dic['rads'][index]
source_tuple = (lat, lon, rad)
if not source_tuple in all_ttimes.keys():
all_ttimes[source_tuple] = []
all_uncs[source_tuple] = []
all_ttimes[source_tuple].append(dic['ttimes'][index])
all_uncs[source_tuple].append(dic['uncerts'][index])
# create new dictionary in the shape of residuals dict with only one source
stacked_dict = {}
stacked_dict[1] = {'lats': [],
'lons': [],
'rads': [],
'ttimes':[],
'nttimes': [],
'misfits': []}
for source_tuple in all_ttimes.keys():
ttimes_list = all_ttimes[source_tuple]
uncs_list = all_uncs[source_tuple]
misfit = np.sum((np.array(ttimes_list) / np.array(uncs_list))**2) / len(ttimes_list)
lat, lon, rad = source_tuple
stacked_dict[1]['lats'].append(lat)
stacked_dict[1]['lons'].append(lon)
stacked_dict[1]['rads'].append(rad)
stacked_dict[1]['ttimes'].append(np.sum(np.mean(ttimes_list)))
stacked_dict[1]['nttimes'].append(len(ttimes_list))
stacked_dict[1]['misfits'].append(misfit)
#stacked_dict[1]['ttimes_list'].append(ttimes_list)
ttimes = [d['ttimes'] for d in stacked_dict.values()]
plt.hist(ttimes, 100)
plt.axvline(np.mean(ttimes), c='r')
plt.xlabel('ttime [s]')
return stacked_dict
def compare_residuals():
wdir = '/rscratch/minos13/marcel/fmtomo_alparray/'
os.chdir(wdir)
with open('alparray_mantle_diehl_crust_included_v3_hf/stacked_residuals.json', 'r') as infile:
sr = json.load(infile)
with open('alparray_mantle_diehl_crust_included_v3_no_density_hf/stacked_residuals.json', 'r') as infile:
srnd = json.load(infile)
mfdiff = np.array(sr['1']['misfits']) - np.array(srnd['1']['misfits'])
np.mean(mfdiff)
sc = plt.scatter(sr['1']['lons'], sr['1']['lats'], c=mfdiff, cmap='seismic', vmin=-7.5, vmax=7.5)
cb = plt.colorbar(sc)
title = 'Difference in station misfit after 12 iterations (density kernel - no density).' \
' Blue: decrease in residuals using density. Mean: {:.4f}'
plt.title(title.format(np.mean(mfdiff)))
plt.xlabel('Latitude (deg)')
plt.ylabel('Longitude (deg)')
cb.set_label('Misfit')
sc.set_linewidth(0.2)
sc.set_edgecolor('k')
plt.show()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Plot residuals of fm3d output file (arrivals.dat format) on map.')
parser.add_argument('--otimes', default='otimes.dat', help='otimes.dat file (default: otimes.dat)')
parser.add_argument('--sources', default='sources.in', help='sources.in file (default: sources.in)')
parser.add_argument('--receivers', default='receivers.in', help='receivers.in file (default receivers.in)')
parser.add_argument('--sourcefile', default='input_source_file.in', help='input_source_file (default: input_source_file.in)')
parser.add_argument('--arrivals', default=None, help='arrivals_file')
parser.add_argument('--rtimes', default=None, help='reference_file')
parser.add_argument('--fext', default='png', help='file extension for images (if -w)')
parser.add_argument('-s', '--stack', action='store_true', dest='stack', help='stack picks')
parser.add_argument('-w', '--write', action='store_true', default=False, help='write figures to disk')
parser.add_argument('-a', '--abs', action='store_true', dest='abs', default=False, help='compute absolute values')
parser.add_argument('-nd', '--no_demean', action='store_true', default=False, help='do not demean travel times')
parser.add_argument('-nc', '--no_colorbar', action='store_true', default=False, help='do not plot colorbar')
parser.add_argument('-nt', '--no_title', action='store_true', default=False, help='do not plot title')
parser.add_argument('-no', '--no_otimes', action='store_true', default=False, help='do not plot relative to otimes')
parser.add_argument('-oo', '--only_otimes', action='store_true', default=False, help='only plot observed times (otimes)')
parser.add_argument('-i', '--ids', dest='source_ids', type=int, default=[], nargs='*',
help='Plot only one source with FMTOMO internal id(s).')
args = parser.parse_args()
savefig_dir = 'residual_maps_out' if args.write else ''
plot_map(args.otimes, args.sources, args.receivers, args.sourcefile, arrivals_fname=args.arrivals,
rtimes_fname=args.rtimes, stack=args.stack, source_ids=args.source_ids, colorbar=not args.no_colorbar,
title=not args.no_title, savefig_dir=savefig_dir, demean=not args.no_demean, absolute=args.abs,
file_ext=args.fext, relative_to_otimes=not args.no_otimes, only_otimes= args.only_otimes)
@@ -1,270 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Estimate ray crossing at each depth using rays (as npy objects) precalculated from FMTOMO file rays.dat
(e.g. script: plot_rays_on_plane)
'''
import os
import glob
import json
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import RegularGridInterpolator
from pylot.tomography.fmtomo_tools.fmtomo_grid_utils import read_vgrid_regular, read_vgrid
from pylot.tomography.map_utils import angle_marker, make_map
pjoin = os.path.join
def main(fdir, it=1, station_coords_file='/data/AdriaArray_Data/various/station_coords.json'):
fnin_vgrid = pjoin(fdir, f'it_{it}/vgrids.in')
fnout_vtk = pjoin(fdir, f'vgrids_it{it}_w_ray_crossings.vtk')
fnout_npy = pjoin(fdir, f'vgrids_hf_it{it}' + '_crossing_bins_{}-{}_mincount_{}_STEP_{}.npy')
# binsize (degrees), min_count for each direction to raise quality by 1 increment
binsize_az = 90.
binsize_incl = 60.
min_count = 5
plot = False
write = True
draw_hists = True
draw_simple_hists = True
step = 2 # take nth sample of vgrid for calculating cells
# for stations plotting
with open(station_coords_file, 'r') as infile:
stations = json.load(infile)
lonsStations, latsStations = zip(*[(sta['longitude'], sta['latitude']) for sta in stations.values()])
# some constants etc.
R = 6371.
bins_azim = np.arange(0, 360 + binsize_az, binsize_az)
bins_incl = np.arange(0., 60. + binsize_incl, binsize_incl)
nbins_azim = len(bins_azim) - 1
nbins_incl = len(bins_incl) - 1
# for plotting:
bins = bins_azim
binsize = binsize_az
nbins = nbins_azim
# get vgrid and estimate dlat/dlon
vgrid_reg = read_vgrid_regular(fnin_vgrid)
lons, lats, rads = [array[::step] for array in vgrid_reg[0]]
vps, covs, sms, pdvs = [array[::step, ::step, ::step] for array in vgrid_reg[1:]]
dlat = lats[1] - lats[0]
dlon = lons[1] - lons[0]
# grid = init_dict()
# grid['vps'] = list(vps.ravel())
# grid['covs'] = list(covs.ravel())
# grid['sms'] = list(sms.ravel())
# grid['pdvs'] = list(pdvs.ravel())
# grid['res'] = []
#
# for rad in rads:
# for lat in lats:
# for lon in lons:
# depth = R - rad
# grid['lons'].append(lon)
# grid['lats'].append(lat)
# grid['depths'].append(depth)
# x, y, z = pol2cart(lat, lon, R - depth)
# grid['xs'].append(x)
# grid['ys'].append(y)
# grid['zs'].append(z)
# just for plotting at certain depths (not for write!!!)
depths = np.arange(0., 800., 100)
if not write:
rads = R - depths
resolutions = []
lons_export = []
lats_export = []
rads_export = []
print(rads)
for rad in rads:
# prepare dict containing horizontal angle for key tuple (ilat, ilon)
vgrid_azim_ids = {}
vgrid_incl_ids = {}
print('Working on radius', rad)
# iterate over rays
for fnin_rays in glob.glob1(fpath_events, '*.npz'):
rays = np.load(os.path.join(fpath_events, fnin_rays), allow_pickle=True)
# raypoints = np.zeros((len(rays), 3))
#for index in range(len(rays)):
for ray in rays.values():
#ray = rays[index]
# get index of closest depth here from ray (TAKE CARE OF ALIASING! Using nearest value)
ind_min = np.abs(ray[:, 0] - rad).argmin()
# in case ind_min is at upper boundary (surface)
if ind_min == len(ray[:, 0]) - 1:
ind_min -= 1
# get diffs to following ray index (km, deg, deg)!
ray_diff = np.diff(ray[ind_min:ind_min + 2], axis=0)[0]
lat = ray[ind_min, 1]
lat_diff_km = ray_diff[1] * (np.pi * R) / 180.
lon_diff_km = ray_diff[2] * (np.pi * np.cos(np.deg2rad(lat)) * R) / 180.
r_diff_km = ray_diff[0]
dlateral = np.sqrt(lat_diff_km ** 2 + lon_diff_km ** 2)
# calculate horizontal angle
azim = np.rad2deg(np.arctan2(lon_diff_km, lat_diff_km))
incl = np.rad2deg(np.arctan(dlateral / r_diff_km))
# correct angle from -180-180 to 0-360 and also change azim to bazim
bazim = azim + 180.
# angles[index] = angle
# raypoints[index] = ray[ind_min]
lat, lon = ray[ind_min, 1:]
lati = np.where((lats <= lat + dlat / 2.) & (lats > lat - dlat / 2.))[0][0]
loni = np.where((lons <= lon + dlon / 2.) & (lons > lon - dlon / 2.))[0][0]
key = (lati, loni)
if not key in vgrid_azim_ids.keys():
vgrid_azim_ids[key] = []
vgrid_incl_ids[key] = []
vgrid_azim_ids[key].append(bazim)
vgrid_incl_ids[key].append(incl)
# vgrid_ids[index] = np.array([lati, loni])
# plt.scatter(lons[loni], lats[lati], c='r', marker='o', facecolor='none', alpha=0.5)
# sc = plt.scatter(raypoints[:,2], raypoints[:,1], c=angles[:])
vgrid_angles_quality = {}
vgrid_azim_hist = {}
for inds in vgrid_azim_ids.keys():
azims = vgrid_azim_ids[inds]
incls = vgrid_incl_ids[inds]
lati, loni = inds
hist_az, _ = np.histogram(azims, bins=bins_azim)
hist_incl, _ = np.histogram(incls, bins=bins_incl)
hist2d, _, _ = np.histogram2d(azims, incls, bins=[bins_azim, bins_incl])
# hist_az, hist_inc = hist2d
hist = hist2d.ravel()
quality = len(hist[hist > min_count - 1]) / (nbins_azim * nbins_incl)
# quality = len(hist_az[hist_az > min_count - 1]) / nbins_azim
# quality = len(hist_incl[hist_incl > min_count - 1]) / nbins_incl
vgrid_angles_quality[inds] = quality
vgrid_azim_hist[inds] = hist_az
# LATS = []
# LONS = []
qualities = []
hists = []
for ilat, lat in enumerate(lats):
for ilon, lon in enumerate(lons):
# LATS.append(lat)
# LONS.append(lon)
key = (ilat, ilon)
quality = vgrid_angles_quality.get(key)
hist = vgrid_azim_hist.get(key)
# print(key, quality)
if not quality:
quality = 0.
# hist for plotting only!
if hist is None:
hist = np.zeros(nbins)
qualities.append(quality)
hists.append(hist)
lons_export.append(lon)
lats_export.append(lat)
rads_export.append(rad)
resolutions += qualities
if plot:
# TODO: still old basemap code
raise NotImplementedError('Still using old basemap code')
fig = plt.figure()
ax = fig.add_subplot(111)
bmap = make_map(ax, resolution='l')
LONS, LATS = np.meshgrid(lons, lats)
sc = bmap.pcolormesh(LONS - dlon / 2., LATS - dlat / 2.,
np.array(qualities).reshape(LATS.shape), latlon=True, zorder=1.5,
shading='nearest') # , s=np.array(qualities)*100)
# sc = plt.contourf(LONS, LATS, np.array(qualities).reshape(LATS.shape), levels=21)
if draw_hists:
for index, bin in enumerate(bins[:-1]):
marker = angle_marker(bin, bin + binsize)
s = np.array(hists)[:, index]
if draw_simple_hists:
s[s < min_count] = 0
s[s >= min_count] = 150
else:
s *= 10.
sc_angle = bmap.scatter(LONS, LATS, s=s, marker=marker, edgecolors='0.75', alpha=1., linewidths=0.6,
latlon=True, zorder=1.5, )
sc_angle.set_facecolor('none')
# sc_angle = plt.scatter(LONS, LATS, s=1, marker='.', edgecolors='1.', alpha=1., linewidths=1.)
bmap.scatter(lonsStations, latsStations, c='k', s=0.5, latlon=True, zorder=1.5, ) # , alpha=0.5)
plt.title('Azimuthal coverage at depth of {}km, {} bins'.format((R - rad), nbins_azim * nbins_incl))
# plt.xlim([0, 22])
# plt.ylim([40, 53])
# plt.gca().set_aspect('equal')
cbar = plt.colorbar(sc)
cbar.set_label('Azimuthal coverage')
plt.show()
if write:
rginter_res = RegularGridInterpolator((rads, lats, lons),
np.array(resolutions).reshape((len(rads), len(lats), len(lons))),
bounds_error=False, fill_value=0.)
grid = read_vgrid(fnin_vgrid)[0]
grid['res'] = []
for lon, lat, depth in zip(grid['lons'], grid['lats'], grid['depths']):
grid['res'].append(rginter_res((R - depth, lat, lon)))
a = np.array([lons_export, lats_export, rads_export, resolutions])
np.save(fnout_npy.format(nbins_azim, nbins_incl, min_count, step), a)
write_vtk(grid, fnout_vtk,
write_data=['vps', 'res', 'covs', 'frechs']) # , clon=11., clat=46., dlon=12., dlat=6., sort=True)
def rays_to_npy(infile, fnout_npy, n_points=10):
rays = {}
i = 0
src_id_old = 1
while True:
i += 1
l1 = infile.readline()
if l1 == '': break
rec_id, src_id, ray_id = [int(item) for item in l1.split()[:3]]
if not src_id in rays.keys():
rays[src_id] = []
l2 = infile.readline()
n = int(l2.split()[0])
ray = np.zeros((n, 3))
for index in range(n):
r, lat, lon = [float(item) for item in infile.readline().split()]
ray[index] = np.array([r, np.rad2deg(lat), np.rad2deg(lon)])
rays[src_id].append(ray[::n_points])
dirname = os.path.split(fnout_npy)[0]
if not os.path.isdir(dirname):
os.mkdir(dirname)
for src_id, ray in rays.items():
np.savez(fnout_npy.format(src_id), *ray)
if __name__ == '__main__':
fmtomodir = '/data/AdriaArray_Data/fmtomo_adriaarray/alpadege/crust_incl_TESAURO_sm30_dm1/'
it = 12
fpath_events = pjoin(fmtomodir, f'rays_npy_it{it}/')
infile = open(pjoin(fmtomodir, f'it_{it}/rays.dat'), 'r')
fnout_npy = pjoin(fpath_events, f'it_{it}_rays_event_' + '{}.npz')
rays_to_npy(infile, fnout_npy)
main(fmtomodir, it=it)
@@ -1,43 +0,0 @@
import os
import numpy as np
import matplotlib.pyplot as plt
fpaths = ['/data/AlpArray_Data/fmtomo/v6/fwi_model_wolfgang_test',
'/data/AlpArray_Data/fmtomo/v6/final']
arr_path_ref = 'rtimes_tele.dat'
iterations = [0, 1, 2, 3, 4]
labels = ['rel_1d'] + [f'rel_it{it}' for it in iterations]
colors = plt.get_cmap('viridis')(np.linspace(0,1, len(iterations)))
colors = np.vstack(((.5, .5, .5, 1), colors))
axes = []
for fpath in fpaths:
rtimes = np.genfromtxt(os.path.join(fpath, arr_path_ref))[:, 4]
otimes = np.genfromtxt(os.path.join(fpath, 'otimes.dat'), skip_header=1)[:, 4]
res = np.empty((len(rtimes), len(iterations) + 1))
res[:, 0] = otimes # = otimes + rtimes - rtimes
for index, itr in enumerate(iterations):
arr_path = f'it_{itr}/arrivals.dat'
arrivals = np.genfromtxt(os.path.join(fpath, arr_path))[:, 4]
res[:, index + 1] = (otimes + rtimes) - arrivals # otimes (rel) + rtimes => otimes (abs)
fig = plt.figure()
ax = fig.add_subplot(111)
axes.append(ax)
ax.hist(res, bins=np.linspace(-5, 5, 50), rwidth=0.9, color=colors, label=labels)
ax.set_xlim(-1.5, 1.5)
plt.title(fpath)
ax.legend()
ylim_max = max([ax.get_ylim()[1] for ax in axes])
for ax in axes:
ax.set_ylim(0, ylim_max)
plt.show()
@@ -1,187 +0,0 @@
# This script estimates density of station distribution using Gaussian KDE. For each point a Gaussian Kernel with
# sigma ~ grid size (?) is summed in 2D, calculating estimate density function. If the sum of all points evaluated
# at the data points increases that means there are more regions with high density
import os
import copy
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
from pylot.tomography.fmtomo_tools.fmtomo_teleseismic_utils import organize_receivers, organize_event_names, export_otimes
def get_events_dict(otimes, recs):
events_dict = {}
for otime in otimes:
rec_id, src_id = int(otime[0]), int(otime[1])
if not src_id in events_dict.keys():
events_dict[src_id] = dict(lons=[], lats=[], rec_ids=[])
events_dict[src_id]['lons'].append(recs[rec_id]['lon'])
events_dict[src_id]['lats'].append(recs[rec_id]['lat'])
events_dict[src_id]['rec_ids'].append(rec_id)
return events_dict
def transfer_kde_to_weight(kdes):
weights = 0.1 - kdes
indices_negative = np.where(weights < 0)[0]
if indices_negative:
print('Warning! {} negative indices in weights. Set to 0.'.format(len(indices_negative)))
weights[indices_negative] = 0.
return weights
def calc_event_kernels(events_dict, eventnames, kde_factor, plot_single=False, fdir_out=None):
kernels = {}
evaluated_kernels = {}
if plot_single:
fig = plt.figure(figsize=(16, 9))
for index in range(len(eventnames)):
eventname = eventnames[index]
source = index + 1
lons = events_dict[source]['lons']
lats = events_dict[source]['lats']
kernel = gaussian_kde(np.array([lons, lats]), bw_method=kde_factor)
evaluated_kernel = kernel((lons, lats))
kernels[source] = kernel
evaluated_kernels[source] = evaluated_kernel
if plot_single:
assert fdir_out, 'Need to specify output directory for plots'
if not os.path.isdir(fdir_out):
os.mkdir(fdir_out)
weights = transfer_kde_to_weight(evaluated_kernel)
iterdict = {'kde': evaluated_kernel, 'weight': weights}
for name, colorarray in iterdict.items():
if name == 'kde':
vmin=0
vmax=0.05
else:
vmin=None
vmax=None
scs = plt.scatter(lons, lats, marker='o', c=colorarray, lw=1.0, vmin=vmin, vmax=vmax)
cbar = plt.colorbar(scs)
plt.title('Station {} for event {}'.format(name, eventname))
fig.savefig(os.path.join(fdir_out, '{}_{}.svg'.format(eventname, name)))
fig.clear()
#plt.show()
if plot_single:
plt.close('all')
return kernels, evaluated_kernels
def plot_hist_kernels(evaluated_kernels):
all_kernels = np.array([])
for kernel in evaluated_kernels.values():
all_kernels = np.append(all_kernels, kernel)
plt.hist(all_kernels, bins=200, label='kernels')
plt.title('Distribution of all kernels.')
plt.show()
def plot_hist_uncertainties(otimes_new, otimes_orig, bins=200):
plt.hist(otimes_orig[:, -1], lw=1, bins=bins, label='Unmodified uncertainties', fc=(.5, .5, 0., 0.5))
plt.hist(otimes_new[:, -1], lw=1, bins=bins, label='New uncertainties', fc=(0., .5, .5, 0.5))
plt.legend()
plt.xlabel('Uncertainty [s]')
plt.title('Uncertainty distribution before and after correction.')
plt.show()
def plot_uncertainties(otimes, recs, eventnames, fdir_out, vmin=0.1, vmax=0.4):
if not os.path.isdir(fdir_out):
os.mkdir(fdir_out)
print('Writing output to directory:', fdir_out)
epsilon = 1e-6
fig = plt.figure(figsize=(16, 9))
for index, eventname in enumerate(eventnames):
src_id = index + 1
indices = np.where(abs(otimes[:, 1] - src_id) <= epsilon)
rec_ids = otimes[:, 0][indices]
uncs = otimes[:, -1][indices]
lats = [recs[rec_id]['lat'] for rec_id in rec_ids]
lons = [recs[rec_id]['lon'] for rec_id in rec_ids]
sc = plt.scatter(lons, lats, c=uncs, vmin=vmin, vmax=vmax)
plt.title(eventname)
cb = plt.colorbar(sc)
fig.savefig(os.path.join(fdir_out, '{}.svg'.format(eventname)))
fig.clear()
plt.close('all')
def exp_func(uncertainty, eval_kernel, exponent=30):
return uncertainty * np.exp(exponent * eval_kernel)
def modify_otimes(otimes, recs, kernels):
print('Applying Kernel on otimes and modifying uncertainties...')
for otime in otimes:
rec_id, src_id = int(otime[0]), int(otime[1])
lon = recs[rec_id]['lon']
lat = recs[rec_id]['lat']
eval_kernel = kernels[src_id]((lon, lat))
otime[-1] = exp_func(otime[-1], eval_kernel)
return otimes
def plot_average_kernel(evaluated_kernels, eventnames):
ids_names = [(index + 1, eventname) for index, eventname in enumerate(eventnames)]
sorted_events = sorted(ids_names, key=lambda x: x[1])
kernel_sums = {src_id: np.sum(kernel) for src_id, kernel in evaluated_kernels.items()}
src_ids = [item[0] for item in sorted_events]
eventnames = [item[1] for item in sorted_events]
sums = [kernel_sums[src_id] for src_id in src_ids]
plt.plot(sums)
xticks = np.arange(0, len(eventnames), step=len(eventnames)//10)
xticklabels = [eventname[:8] for index, eventname in enumerate(eventnames) if index in xticks]
plt.xticks(xticks, xticklabels)
plt.title('Average kernel per station. High value means inhomogeneous station distribution.')
plt.show()
def export_station_kdes(events_dict, evaluated_kernels, fnout):
with open(fnout, 'w') as outfile:
for src_id in range(1, len(events_dict) + 1):
kernel = evaluated_kernels[src_id]
for kde, rec_id in zip(kernel, events_dict[src_id]['rec_ids']):
outfile.write('{} {} {}\n'.format(rec_id, src_id, kde))
def main(plot=False, plot_detailed=False):
working_path = '/rscratch/minos13/marcel/fmtomo_alparray/v4/alparray_mantle_diehl_crust_included_hf_gradient_smoothing'
fdir_out = 'station_density'
fnout = os.path.join(fdir_out, 'station_kdes.txt')
os.chdir(working_path)
eventnames = organize_event_names('input_source_file_P.in')
recs = organize_receivers('receivers.in')
otimes_data = np.genfromtxt('otimes_orig.dat', skip_header=1)
# kernel width ~ grid size? or station spacing?
kde_size = 30 # km
kde_factor = kde_size / (6371. * np.pi / 180.)
print('KDE width (degree):', kde_factor)
events_dict = get_events_dict(otimes_data, recs)
kernels, evaluated_kernels = calc_event_kernels(events_dict, eventnames, kde_factor, plot_single=plot_detailed,
fdir_out=fdir_out)
export_station_kdes(events_dict, evaluated_kernels, fnout)
otimes_modif = modify_otimes(copy.deepcopy(otimes_data), recs, kernels)
#export_otimes(otimes_modif, os.path.join(working_path, 'otimes_modif_kernel.dat'))
if plot:
plot_average_kernel(evaluated_kernels, eventnames)
plot_hist_kernels(evaluated_kernels)
plot_hist_uncertainties(otimes_modif, otimes_data)
if plot_detailed:
plot_uncertainties(otimes_data, recs, eventnames, 'uncerts_old')
plot_uncertainties(otimes_modif, recs, eventnames, 'uncerts_new')
if __name__ == '__main__':
main(plot=True, plot_detailed=True)
@@ -1,17 +0,0 @@
#!/bin/bash
ulimit -s 8192
conda activate pylot_311
##qsub -l low -cwd -l "os=*stretch" -pe mpi-fu 40 submit_fmtomo.sh
#$ -l low
#$ -cwd
#$ -pe smp 40
#$ -q "*@minos11, *@minos12, *@minos15"
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/"
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/pylot/"
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/pylot_tools/"
python fmtomo.py
@@ -1,10 +0,0 @@
#!/bin/bash
conda activate py37
#qsub -l low -cwd -l "os=*stretch" -pe mpi-fu 40 submit_fmtomo_grid_utils.sh
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/"
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/pylot_tools/"
python fmtomo_grid_utils.py
@@ -1,21 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from pylot.tomography.fmtomo_utils import Tomo3d
#tomo = Tomo3d('/rscratch/minos13/marcel/fmtomo_alparray/alparray_mantle_from_m6.0_tesauro_model_on_top',
# '/rscratch/minos13/marcel/fmtomo_alparray/alparray_mantle_from_m6.0_tesauro_model_on_top',
# buildObs=False, saveRays=False)
wdir = '/rscratch/minos13/marcel/fmtomo_alparray/'
#directories = ['alparray_mantle_from_m6.0_diehl_crustal_corrections_sm1_damp3',
#'alparray_mantle_from_m6.0_diehl_crustal_corrections_sm1_damp30',]
directories= ['alparray_mantle_from_m6.0_diehl_crustal_corrections_sm10_damp3',
'alparray_mantle_from_m6.0_diehl_crustal_corrections_sm10_damp30']
for dire in directories:
path = os.path.join(wdir, dire)
tomo = Tomo3d(path, path, buildObs=False, saveRays=False)
tomo.runTOMO3D(40, 8)
@@ -1,12 +0,0 @@
#!/bin/bash
ulimit -s 8192
#$ -l low,os=*stretch
#$ -l h_vmem=5G
#$ -cwd
#$ -pe smp 40
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/"
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/pylot_tools/"
python submit_fmtomo_run.py
@@ -1,62 +0,0 @@
#!/bin/bash
ulimit -s 8192
conda activate pylot_311
##qsub -l low -cwd -l "os=*stretch" -pe mpi-fu 40 submit_fmtomo_teleseismic.sh
#$ -l low
##$ -l os=*stretch
#$ -cwd
#$ -pe smp 40
#$ -q "*@minos11, *@minos12, *@minos15"
### WARNING fm3d_prepare_tele not compiled correctly for all cluster machines (e.g. not working on minos12, minos15)
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/"
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/pylot/"
export PYTHONPATH="$PYTHONPATH:/home/marcel/git/pylot_tools/"
#python fmtomo_teleseismic.py '/data/AlpArray_Data/dmt_database_mantle_0.03-0.1_revised' \
#'/data/AlpArray_Data/fmtomo/v6/crust_incl_lf_sm_FIX_DTS_grad_sm30_dm10' \
#'_correlated_0.03-0.1' -n $NSLOTS --blacklist '/rscratch/minos22/marcel/alparray/station_blacklist.csv'
# --model 'ak135_diehl_v2'
#python fmtomo_teleseismic.py '/data/AlpArray_Data/dmt_database_mantle_0.03-0.5_revised' \
#'/data/AlpArray_Data/fmtomo/v6/crust_incl_hf_sm_FIX_DTS_grad_sm30_dm10' \
#'_correlated_0.03-0.5' -n $NSLOTS --blacklist '/rscratch/minos22/marcel/alparray/station_blacklist.csv'
# --model 'ak135_diehl_v2'
#python fmtomo_teleseismic.py '/data/AlpArray_Data/dmt_database_mantle_0.01-0.2_S_SKS' \
#'/data/AlpArray_Data/fmtomo/v6_S/crust_incl_hf_KSTL_grad_sm6_dm10/' \
#'_correlated_0.01-0.2_S*' -n $NSLOTS --blacklist '/data/AlpArray_Data/various/alparray/station_blacklist.csv'
# --model 'ak135_diehl_v2'
#
#python fmtomo_teleseismic.py '/data/AlpArray_Data/dmt_database_mantle_0.03-0.5_revised' \
# '/rscratch/minos13/marcel/fmtomo_alparray/v3.5/alparray_mantle_diehl_crust_included_hf_no_init' \
# '_correlated_0.03-0.5' -n $NSLOTS --no_write_init_nodes --model 'ak135_diehl_v2'
#python fmtomo_teleseismic.py '/data/AlpArray_Data/dmt_database_hybrid_test' \
# '/rscratch/minos13/marcel/fmtomo_alparray/v3/hybrid_method_test_pgrid_fine' \
# '' -n $NSLOTS #--blacklist '/rscratch/minos22/marcel/alparray/station_blacklist.csv' --model 'ak135_diehl_v2'
#python fmtomo_teleseismic.py '/data/AlpArray_Data/dmt_database_hybrid_test_diehl_v2' \
#'/data/AlpArray_Data/fmtomo/v6/hybrid_method_test' \
#'' -n $NSLOTS --model 'ak135_diehl_v2'
#--blacklist '/rscratch/minos22/marcel/alparray/station_blacklist.csv'
#python fmtomo_teleseismic.py '/data/AlpArray_Data/dmt_database_hybrid_test_diehl_v2_orig_box_more_stations' \
#'/data/AlpArray_Data/fmtomo/v5/hybrid_method_tests_diss/v5_orig_box_size_more_receiver_no_demean_CORRECTED_depth_sampling' \
#'' -n $NSLOTS --model 'ak135_diehl_v2'
#python fmtomo_teleseismic.py '/data/AlpArray_Data/dmt_database_synth_model_mk6_it3_no_rotation' \
#'/data/AlpArray_Data/fmtomo/v6_resolution_analysis/fwi_mk6_it3_P' \
#'_correlated_P' -n $NSLOTS --model 'ak135_diehl_v2'
#python fmtomo_teleseismic.py '/data/AdriaArray_Data/dmt_database_alpadege' \
#'/data/AdriaArray_Data/fmtomo_adriaarray/alpadege/no_crust_correction' \
#'_correlated_0.03-0.5' -n $NSLOTS --model 'ak135'
python fmtomo_teleseismic.py '/data/AdriaArray_Data/dmt_database_minimal' \
'/data/AdriaArray_Data/fmtomo_adriaarray/alpadege/test_minimal' \
'_correlated_0.03-0.5' -n $NSLOTS --model 'ak135'
@@ -1,266 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import glob
import subprocess
import json
import numpy as np
import numpy.polynomial.polynomial as poly
from scipy.sparse import spdiags
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from itertools import cycle
from pylot.tomography.fmtomo_tools.fmtomo_grid_utils import read_vgrid
# def calc_dampnorm(vgrid, vgrid_ref):
# # calculate m - m0
# m_m0 = np.array(vgrid['vps']) - np.array(vgrid_ref['vps'])
#
# # calculate inverse of diagonal elements of a priori model covariance matrix (which should be a diagonal matrix)
# # IMPORTANT: COVARIANCES ARE MOST LIKELY STANDARD DEVIATIONS -> square them
# covs = np.array(vgrid_ref['covs'])**2
#
# covs_inv = 1. / covs
#
# #cm_inv = spdiags(covs_inv, 0, covs_inv.size, covs_inv.size)#
#
# #norm_calc_old = np.dot(m_m0.transpose(), m_m0 * cm_inv)
#
# norm = np.dot(m_m0, m_m0 * covs_inv)
#
# return norm
#
#
# def calc_smoothnorm(vgrid, gridn, R=6371.):
# nR, nTheta, nPhi = gridn
#
# vps = np.array(vgrid['vps'])
# lats = np.array(vgrid['lats'])
# lons = np.array(vgrid['lons'])
# depths = np.array(vgrid['depths'])
# #vgridref = np.array(vgridref['vps'])
# #dvgrid = vgrid - vgridref
#
# vgarray = np.zeros((nR, nTheta, nPhi))
# lonsarray_km = np.zeros((nR, nTheta, nPhi))
# latsarray_km = np.zeros((nR, nTheta, nPhi))
# radsarray_km = np.zeros((nR, nTheta, nPhi))
# #vgarray_diff = np.zeros((nR, nTheta, nPhi))
# smootharray = np.zeros((nR, nTheta, nPhi))
# #for iLayer in range(nlayers):
# globInd = 0
# for iR in range(nR):
# for iTheta in range(nTheta):
# for iPhi in range(nPhi):
# r = R - depths[globInd]
# lat = lats[globInd]
# lon = lons[globInd]
# r_minor = np.cos(np.deg2rad(lat)) * r
# vgarray[iR, iTheta, iPhi] = vps[globInd]
# radsarray_km[iR, iTheta, iPhi] = r
# latsarray_km[iR, iTheta, iPhi] = np.pi * r * lat / 180.
# lonsarray_km[iR, iTheta, iPhi] = np.pi * r_minor * lon / 180.
# #vgarray_diff[iR, iTheta, iPhi] = vgrid[globInd]
# globInd += 1
#
# # iterate over grid diffs (correct?) and sum 1 * point left -2 * point + 1 * point right in all 3 dim.
# smsum = 0.
# for iR in range(nR):
# for iTheta in range(nTheta):
# for iPhi in range(nPhi):
# vg = vgarray[iR, iTheta, iPhi]
# sum1 = sum2 = sum3 = 0.
# if 0 < iPhi < nPhi - 1:
# h = abs(lonsarray_km[iR, iTheta, iPhi + 1] - lonsarray_km[iR, iTheta, iPhi - 1]) / 2
# sum1 = (vgarray[iR, iTheta, iPhi - 1] - 2 * vg + vgarray[iR, iTheta, iPhi + 1]) / h**2
# if 0 < iTheta < nTheta - 1:
# h = abs(latsarray_km[iR, iTheta + 1, iPhi] - latsarray_km[iR, iTheta - 1, iPhi]) / 2
# sum2 = (vgarray[iR, iTheta - 1, iPhi] - 2 * vg + vgarray[iR, iTheta + 1, iPhi]) / h**2
# if 0 < iR < nR - 1:
# h = abs(radsarray_km[iR - 1, iTheta, iPhi] - radsarray_km[iR + 1, iTheta, iPhi]) / 2
# sum3 = (vgarray[iR - 1, iTheta, iPhi] - 2 * vg + vgarray[iR + 1, iTheta, iPhi]) / h**2
# smsum += np.sqrt(sum1**2 + sum2**2 + sum3**2)
# #print(sum1, sum2, sum3, smsum)
# smootharray[iR, iTheta, iPhi] = smsum#sum1 + sum2 + sum3
#
# # m_T * D_T * D * m ?? todo: unsure
# norm = np.sum(smootharray ** 2)
#
# return norm, smootharray
from pylot.tomography.utils import normed_figure
def calc_smoothnorm(wdir, iter):
smv = np.loadtxt(os.path.join(wdir, 'it_{}/smv.out'.format(iter + 1)), skiprows=1)
dm = np.loadtxt(os.path.join(wdir, 'it_{}/dm.out'.format(iter + 1)), skiprows=1)
norm = np.sum(smv*dm)
return norm
def calc_dampnorm(wdir, iter):
ecmi = np.loadtxt(os.path.join(wdir, 'it_{}/ecmi.out'.format(iter + 1)), skiprows=1)
dm = np.loadtxt(os.path.join(wdir, 'it_{}/dm.out'.format(iter + 1)), skiprows=1)
norm = np.sum(ecmi * dm**2)
return norm
def calc_norm(wdir, iteration_number):
dampnorm = calc_dampnorm(wdir, iteration_number)
smoothnorm = calc_smoothnorm(wdir, iteration_number)
print('dampnorm: ', dampnorm)
print('smoothnorm: ', smoothnorm)
norm = dampnorm + smoothnorm
print('Calculated summed norm of', norm)
return norm, dampnorm, smoothnorm
def calc_tradeoff(fpath_in, fname_out=None, iteration_number = 12):
results = {}
for wdir in glob.glob(fpath_in):
#wdir = '/rscratch/minos13/marcel/fmtomo_alparray/alparray_mantle_from_m6.0_diehl_crustal_corrections_sm1000_damp100/'
smooth = float(wdir.split('_')[-2].split('sm')[-1])
damp = float(wdir.split('_damp')[-1].split('/')[0])
print('Calculating tradeoff for smoothing and damping of {}, {}'.format(smooth, damp))
if not smooth in results.keys():
results[smooth] = {}
iteration_number_new = iteration_number
ecmi_path = os.path.join(wdir, 'it_{}'.format(iteration_number_new + 1), 'ecmi.out')
smv_path = os.path.join(wdir, 'it_{}'.format(iteration_number_new + 1), 'smv.out')
while not os.path.isfile(ecmi_path) or not os.path.isfile(smv_path):
iteration_number_new -= 1
ecmi_path = os.path.join(wdir, 'it_{}'.format(iteration_number_new + 1), 'ecmi.out')
smv_path = os.path.join(wdir, 'it_{}'.format(iteration_number_new + 1), 'smv.out')
print('WARNING: Iteration number lowered by 1:', iteration_number_new)
if iteration_number_new <= 1:
break
if iteration_number_new <= 1:
continue
else:
iteration_number = iteration_number_new
#vgrid, gridn, griddelta, gridstart = read_vgrid(vgrid_path)
#vgrid_ref = read_vgrid(os.path.join(wdir, 'vgridsref.in'))[0]
norm, dampnorm, smoothnorm = calc_norm(wdir, iteration_number)
try:
fpath = os.path.join(wdir, 'residuals.dat')
chi = float(subprocess.check_output(['tail', fpath]).split()[-1])
except Exception as e:
print(e)
chi = np.nan
results[smooth][wdir] = {'dampnorm': dampnorm, 'smoothnorm': smoothnorm,
'norm': norm, 'chi': chi, 'damp': damp}
#print some output
for smooth, result in results.items():
print('Smoothing:', smooth)
for wdir, item in result.items():
print(item['chi'], item['norm'])
print(20*'#')
if fname_out:
with open(fname_out, 'w') as outfile:
json.dump(results, outfile)
return results
def quadratic_function(x, a, b, c):
return a * x ** 2 + b * x + c
def one_over_x(x, a, b, c):
return a / (x - b) + c
def exp_func(x, a, b, c):
return a * np.exp(-b * x) + c
def plot_tradeoff(fname_in, fix='smooth', plot_norm='both', min_smooth=0, min_damp=0, max_smooth=1e6, max_damp=1e6):
with open(fname_in, 'r') as infile:
results_smooth = json.load(infile)
lines = ["-", "--", "-.", ":"]
linecycler = cycle(lines)
# array will be built for each line: (smooth, damp, norm, chi)
plot_values = []
for smooth, result in results_smooth.items():
for item in result.values():
smooth = float(smooth)
damping = item['damp']
if smooth < min_smooth or damping < min_damp or smooth > max_smooth or damping > max_damp:
continue
plot_values.append(np.array([smooth, damping, item[plot_norm], item['chi']]))
plot_values = np.array(plot_values)
column_index = {'smooth': 0, 'damp': 1}
keys = np.unique(plot_values[:, column_index[fix]])
names = {'smooth': 'Smoothing', 'damp': 'Damping'}
for key in keys:
plot_line = plot_values[plot_values[:, column_index[fix]] == key]
second_index = column_index['smooth'] if fix == 'damp' else column_index['damp']
plot_line = np.array(sorted(plot_line, key=lambda x: x[second_index]))
norms = plot_line[:, 2]
chis = plot_line[:, 3]
#text = [str(item) for item in plot_line[:, second_index]]
x = np.linspace(min(norms), max(norms), num=100)
#popt, pcov = curve_fit(one_over_x, norms, chis, method='trf')#, bounds=[min(norms), max(norms)])
#fit_result = one_over_x(x, *popt)
#line = plt.plot(x, fit_result, ':', lw=0.8)[0]
fninfo = os.path.split(fname_in)[-1].replace('.json', '').split('_f')[-1]
label = '{}: {:g}'.format(names[fix], float(key))
line = plt.plot(norms, chis, linestyle=next(linecycler), lw=0.8, label=label)[0]
#coefs = poly.polyfit(norms, chis, 4)
#ffit = poly.polyval(x, coefs)
#line = plt.plot(x, ffit, ':', lw=0.8)[0]
#label = label='{}: {:g} (smgrad: {})'.format(names[fix], float(key), fninfo)
plt.plot(norms, chis, c=line.get_color(), marker='.', lw=0.)
#plt.text(norms, chis, text)
for item in plot_line:
plt.text(item[2], item[3], str(item[second_index]), horizontalalignment='left')
#plt.title('Plot of Misfit against Norm ({})'.format(plot_norm))
if __name__ == '__main__':
#calc_tradeoff('/data/AlpArray_Data/fmtomo/v5/tradeoff_curves/crust_included_grad_smooth_FIXED_dts_grad_1.5_sm*_damp*/',
# '/data/AlpArray_Data/various/alparray/tradeoff_v5_f1.5.json')
#calc_tradeoff('/data/AlpArray_Data/fmtomo/v5/tradeoff_curves/crust_included_grad_smooth_FIXED_dts_sm*_damp*/',
# '/data/AlpArray_Data/various/alparray/tradeoff_v5_f2.0.json')
fig = normed_figure(width_cm=10, ratio=1.)
#tradeoff_infiles = ['tradeoff_v4_f1.5.json', 'tradeoff_v4_f3.json', 'tradeoff_v4_f10.json']
tradeoff_infiles = ['tradeoff_v5_f2.0.json']#, 'tradeoff_v5_f1.5.json']
for infile in tradeoff_infiles:
infile = os.path.join('/data/AlpArray_Data/various/alparray/', infile)
plot_tradeoff(infile, fix='damp', plot_norm='norm')
plt.xlim([1900, 16200])
plt.ylim([2.72, 3.8])
plt.xlabel('Norm')
#plt.ylabel(r'Misfit($\frac{\chi^2}{N}$)')
plt.ylabel(r'Misfit($\chi^2/N$)')
#plt.title('Tradeoff curve Misfit vs Norm. Numbers in plot show smoothing values.')
plt.legend()
#plt.show()
plt.savefig('/data/AlpArray_Data/sciebo/AlpArray_home/pictures/paper_II/tradeoff.pdf', dpi=300)
@@ -1,63 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import json
from pylot.tomography.fmtomo_tools.fmtomo_grid_utils import read_vgrid, write_vtk, calculate_differences_grid, write_vgrid
def visualize_frechet_derivative(fname_vgrid, fname_frechet, fname_out_vtk=None, fname_out_json=None,
fname_out_vgrid=None, diff_model=None, fname_vgrid_ref=None):
vgrid, gridN, gridDelta, gridStart = read_vgrid(fname_vgrid, inv_index_frechet=True)
if diff_model and fname_vgrid_ref:
raise OverflowError('Cannot have both parameters set, diff_model and fname_vgrid_ref')
if diff_model:
vgrid = calculate_differences_grid(vgrid, earth_model=diff_model)
if fname_vgrid_ref:
vgrid_ref, gridN_ref, gridDelta_ref, gridStart_ref = read_vgrid(fname_vgrid_ref, inv_index_frechet=False)
grid_check = (gridN == gridN_ref,
compare_tuple(gridDelta, gridDelta_ref),
compare_tuple(gridStart, gridStart_ref))
assert(all(grid_check), 'Missmatch ref grid size')
vps = np.array(vgrid['vps'])
vps_ref = np.array(vgrid_ref['vps'])
vps_rel = (vps - vps_ref) / vps_ref * 100.
print('Min/Max change {}/{}%'.format(min(vps_rel), max(vps_rel)))
vgrid['vps'] = list(vps_rel)
add_frechet(vgrid, fname_frechet)
if fname_out_vgrid:
write_vgrid(vgrid, gridN, gridDelta, gridStart, fname_out_vgrid)
if fname_out_vtk:
write_vtk(vgrid, fname_out_vtk, ['vps', 'frechs', 'grid_indices', 'hit_count'])
if fname_out_json:
with open(fname_out_vtk, 'w') as outfile:
json.dump(vgrid, outfile)
def add_frechet(vgrid, fname_frechet):
vgrid['frechs'] = list(np.zeros(len(vgrid['xs'])))
vgrid['hit_count'] = list(np.zeros(len(vgrid['xs'])))
with open(fname_frechet, 'r') as infile:
while True:
try:
n, source_id, m, k, n_pdev = [int(item) for item in infile.readline().split()]
except:
break
#print(n, source_ids, m, k, n_pdev)
for _ in range(n_pdev):
pdev_index, pdev = infile.readline().split()
pdev_index = int(pdev_index)
pdev = float(pdev)
vgrid_index = vgrid['inv_index'][pdev_index]
vgrid['frechs'][vgrid_index] += pdev
# hit by ray count
vgrid['hit_count'][vgrid_index] += 1
def compare_tuple(t1, t2, epsilon=1e-6):
for item1, item2 in zip(t1, t2):
if abs(item1 - item2) > epsilon:
return False
return True
File diff suppressed because it is too large. Load diff
-160
View File
@@ -1,160 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
import os
import json
import numpy as np
import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
from cartopy.io.shapereader import Reader
from matplotlib.patches import Patch
#from cmcrameri import cm
from obspy.geodetics import gps2dist_azimuth
TRANSFORM = ccrs.PlateCarree()
def draw_schmid_faults(ax, fnin='schmidfaults.shp'):
reader = Reader(fnin)
lines = []
linestyles = []
for record in reader.records():
info = record.attributes
if info["fault_type"] == 1 or info["fault_type"] == 3:
linestyles.append('solid')
else:
linestyles.append('dashed')
line_arr = np.array(record.geometry.coords)
lines.append(line_arr)
# ax.add_collection(LineCollection(lines, linewidths=1.2, linestyles=linemarkers, colors='black', transform=ccrs.PlateCarree()))
for line, style in zip(lines, linestyles):
ax.plot(line[:, 0], line[:, 1], transform=TRANSFORM, ls=style, c='k', lw=1.2)
def draw_alcapadi_faults(ax, fnin='faults_alcapadi', color='black'):
reader = Reader(fnin)
lines = []
linestyles = []
linewidths = []
for record in reader.records():
info = record.attributes
if info["fault_type"] == 1:
linestyles.append('solid')
linewidths.append(.8)
elif info["fault_type"] == 2:
linestyles.append('solid')
linewidths.append(0.4)
else:
linestyles.append('dashed')
linewidths.append(.8)
line_arr = np.array(record.geometry.coords)
lines.append(line_arr)
for line, style, lwidth in zip(lines, linestyles, linewidths):
ax.plot(line[:, 0], line[:, 1], transform=TRANSFORM, ls=style, c='k', lw=lwidth)
def draw_alcapadi_model(ax, fnin='tect_units_alcapadi', alpha=0.2, add_legend=True):
reader = Reader(fnin)
color_dict = {"Adria accreted": (0.8, 0.7, 0.45, alpha),
"Adria autochton": (0.52, 0.32, 0.2, alpha),
"Europe accreted": (0.42, 0.67, 0.88, alpha),
"Flexural foredeep and graben fill": (0.6, 0.6, 0.6, alpha), # (1.0, 1.0, 220/255., alpha),
"Alpine Tethys": (0., 0.65, 0.3, alpha),
"Neotethys": (0.5, 0.8, 0.32, alpha)}
patches_legend = [Patch(color=value, label=key.capitalize()) for key, value in color_dict.items()]
for record in reader.records():
info = record.attributes
shape = record.geometry
color = color_dict.get(info['tect_unit'])
if not color:
color = (1.0, 1.0, 1.0, alpha)
ax.add_geometries(shape, crs=TRANSFORM, facecolor=color)
if add_legend:
ax.legend(handles=patches_legend, ncol=3, bbox_to_anchor=(0.5, -0.075), loc='center')
def init_cartopy_map(fig=None, draw_mapbound=True, fill_continents=False,
continents_color=None, mapbound_color=None, lakes_color=None, clon=None, clat=None):
if not fig:
fig = plt.figure()
#projection = ccrs.LambertConformal(central_longitude=clon, central_latitude=clat)
projection = ccrs.PlateCarree(central_longitude=clon)
ax = fig.add_subplot(111, projection=projection)
if fill_continents:
ax.add_feature(cartopy.feature.LAND, color=continents_color)
ax.add_feature(cartopy.feature.LAKES, color=lakes_color)
if draw_mapbound:
#ax.add_feature(cartopy.feature.OCEAN, color='w', linewidth=0.1)
ax.add_feature(cartopy.feature.BORDERS, linewidth=0.2, color='0.3')
ax.add_feature(cartopy.feature.COASTLINE, linewidth=0.3, color='0.3')
return ax
def make_map(fig=None, draw_model=False, model_legends=True, draw_faults=False, width=20,
height=14, clon=11, clat=46., draw_grid=True, continents='0.8', lakes='0.85', no_content=False,
no_fill=True, alpha_model=0.2, faults_color='k', station_file=None):
ax = init_cartopy_map(fig=fig, draw_mapbound=not no_content, fill_continents=not no_fill,
continents_color=continents, lakes_color=lakes, clon=clon, clat=clat)
if station_file:
with open(station_file, 'r') as fid:
stations = json.load(fid)
lons, lats = zip(*[(sta['longitude'], sta['latitude']) for sta in stations.values()])
ax.scatter(lons, lats, c='0.3', s=1, transform=ccrs.PlateCarree(), zorder=5, edgecolors='none', alpha=0.5)
# if draw_topo:
# draw_topo_model(basemap)
if draw_model:
fnin = '/home/marcel/sciebo/AlpArray_home/tectonic_maps_4dmb_2020_09_17/shape_files/tect_units_alcapadi'
draw_alcapadi_model(ax, fnin, add_legend=model_legends, alpha=alpha_model)
if draw_faults:
fnin = '/home/marcel/sciebo/AlpArray_home/tectonic_maps_4dmb_2020_09_17/shape_files/faults_alcapadi'
draw_alcapadi_faults(ax, fnin, faults_color)
# if not no_content:
# basemap.drawcountries(color=line_color, linewidth=0.2)
# basemap.drawcoastlines(color=line_color, linewidth=0.3)
if draw_grid:
gl = ax.gridlines(crs=TRANSFORM, draw_labels=True,
linewidth=0.5, color='gray', alpha=0.5, linestyle=':')
# dashes = [3, 6]
# parallels = list(np.arange(-90, 90, lgrid))
# parallels_small = [item for item in np.arange(-90, 90, sgrid) if not item in parallels]
# basemap.drawparallels(parallels_small, dashes=dashes, color=line_color, linewidth=0.1, zorder=7)
# basemap.drawparallels(parallels, dashes=[], color=line_color, linewidth=0.2, zorder=7, labels=[1, 1, 0, 0])
# meridians = list(np.arange(-180, 180, lgrid))
# meridians_small = [item for item in np.arange(-180, 180, sgrid) if not item in meridians]
# basemap.drawmeridians(meridians_small, dashes=dashes, color=line_color, linewidth=0.1, zorder=7)
# basemap.drawmeridians(meridians, dashes=[], color=line_color, linewidth=0.2, zorder=7, labels=[0, 0, 1, 1])
ax.set_extent([clon - width/2, clon + width/2, clat - height/2, clat + height/2])
return ax
def angle_marker(a1, a2, delta=1.):
a1 = np.deg2rad(a1)
a2 = np.deg2rad(a2)
delta = np.deg2rad(delta)
x_vals = [np.sin(angle) for angle in np.arange(a1, a2 + delta, delta)]
y_vals = [np.cos(angle) for angle in np.arange(a1, a2 + delta, delta)]
xy = zip(x_vals, y_vals)
#x1 = np.sin(a1)
#y1 = np.cos(a1)
#x2 = np.sin(a2)
#y2 = np.cos(a2)
marker = [(0, 0), *xy, (0, 0)]
return marker
-176
View File
@@ -1,176 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import glob
import numpy as np
import os
import json
import matplotlib.pyplot as plt
from obspy import Catalog, read_events
from pylot.core.util.dataprocessing import Metadata
def get_metadata(eventdir):
metadata_path = os.path.join(eventdir, 'resp')
metadata = Metadata(inventory=metadata_path, verbosity=0)
return metadata
def set_rc_params(textsize=7.):
plt.style.use('/home/marcel/solid_earth.mplstyle')
#plt.rcParams.update({'font.size': textsize,
# 'font.family': 'sans-serif'})
def normed_figure_ratio_width(width_cm, ratio):
width_inch = width_cm / 2.54
height_inch = width_inch / ratio
return width_inch, height_inch
def normed_figure_ratio_height(height_cm, ratio):
height_inch = height_cm / 2.54
width_inch = height_inch * ratio
return width_inch, height_inch
def normed_figure(width_cm=None, ratio=1.777):
#assert ((width_cm and not height_cm) or (height_cm and not width_cm)), 'Choose either of width or height!'
set_rc_params()
if width_cm:
fig = plt.figure(figsize=normed_figure_ratio_width(width_cm, ratio))
return fig
#elif height_cm:
# fig = plt.figure(figsize=normed_figure_ratio_height(height_cm, ratio))
return
def pol2cart(lat, lon, r):
x = r * np.cos(np.deg2rad(lat)) * np.cos(np.deg2rad(lon))
y = r * np.cos(np.deg2rad(lat)) * np.sin(np.deg2rad(lon))
z = r * np.sin(np.deg2rad(lat))
return x, y, z
def cart2pol(x, y, z):
r = np.sqrt(x**2 + y**2 + z**2)
theta = np.rad2deg(np.arccos(z/r))
phi = np.rad2deg(np.arctan2(y, x))
lat = 90. - theta
lon = phi
return lat, lon, r
def pol2cart_vector(lat, lon, north, east, r_comp):
if any(val is None for val in [north, east, r_comp]):
return None, None, None
phi = np.deg2rad(lon)
# change north components to common spherical coordinate convention
theta = np.deg2rad(90. - lat)
north *= -1
x = (np.sin(theta) * np.cos(phi) * r_comp +
np.cos(theta) * np.cos(phi) * north -
np.sin(phi) * east)
y = (np.sin(theta) * np.sin(phi) * r_comp +
np.cos(theta) * np.sin(phi) * north +
np.cos(phi) * east)
z = (np.cos(theta) * r_comp -
np.sin(theta) * north)
return x, y, z
def read_cat_obspy_dmt_database(databasedir, filemask):
infiles = glob.glob(os.path.join(databasedir, '*.a', filemask))
cat = Catalog()
nPicks = 0
for index, infile in enumerate(infiles):
print(f'Working on: {infile} ({index + 1}/{len(infiles)})')
event = read_events(infile)[0]
nPicks += len(event.picks)
cat += event
nEvents = len(cat)
print('Number of events: {} (filemask: {})'.format(nEvents, filemask))
print('Total # picks: {} ({:.2f} per event)'.format(nPicks, float(nPicks)/nEvents))
return cat
def get_event(cat, eventid):
for event in cat.events:
if event.resource_id.id.split('/')[-1] == eventid:
return event
def get_pick4station(picks, network_code, station_code, method='auto'):
for pick in picks:
if pick.waveform_id.network_code == network_code:
if pick.waveform_id.station_code == station_code:
if pick.method_id.id.endswith(method):
return pick
def delete_picks(picks, nwst_ids_delete):
''' Delete picks from list in picks containing ObsPy pick objects'''
for index, pick in list(reversed(list(enumerate(picks)))):
seed_id = pick.waveform_id.get_seed_string()
network, station = seed_id.split('.')[:2]
nwst_id = '{}.{}'.format(network, station)
if nwst_id in nwst_ids_delete:
picks.pop(index)
print('Removed pick: ', nwst_id)
return picks
def save_all_station_coordinates_dmt_database(dmt_database, fn_out):
'''
Get all station coordinates from dmt_database and write them (unique) to json outputfile
:param dmt_database:
:param fn_out:
:return:
'''
stations_dict = {}
eventdirs = glob.glob(os.path.join(dmt_database, '*.?'))
nEvents = len(eventdirs)
for index, eventdir in enumerate(eventdirs):
print('Working on event {} ({}/{})'.format(eventdir, index+1, nEvents))
metadata = get_metadata(eventdir)
current_stations_dict = metadata.get_all_coordinates()
for nwst_id, coords in current_stations_dict.items():
if not nwst_id in stations_dict.keys():
stations_dict[nwst_id] = coords
with open(fn_out, 'w') as outfile:
json.dump(stations_dict, outfile)
def get_metadata(eventdir):
metadata_path = os.path.join(eventdir, 'resp')
metadata = Metadata(inventory=metadata_path, verbosity=0)
return metadata
def get_coordinate_from_dist_baz(station_tmp, dist, baz, mode='deg'):
''' function copied from Andre'''
# station_tmp: [lon, lat]
if mode!='deg' and mode!='rad':
print('mode hast to be ether deg or rad!')
return None
else:
station = np.deg2rad(station_tmp)
epi_tmp=[0.,0.]
if mode=='deg':
dist = np.deg2rad(dist)
baz = np.deg2rad(baz)
az = baz - np.pi
if az < 0:
az += 2 * np.pi
epi_tmp[1] = np.arcsin(np.sin(station[1]) * np.cos(dist) - np.cos(station[1]) * np.sin(dist) * np.cos(az))
if (np.cos(dist) - np.sin(station[1]) * np.sin(epi_tmp[1])) / (np.cos(station[1]) * np.cos(epi_tmp[1])) >= 0.:
epi_tmp[0] = station[0] - np.arcsin(np.sin(dist) * np.sin(az) / np.cos(epi_tmp[1]))
else:
epi_tmp[0] = station[0] - np.pi + np.arcsin(np.sin(dist) * np.sin(az) / np.cos(epi_tmp[1]))
epi=np.rad2deg(epi_tmp)
return epi
-7
View File
@@ -1,7 +0,0 @@
Cartopy==0.23.0
joblib==1.4.2
obspy==1.4.1
pyaml==24.7.0
pyqtgraph==0.13.7
PySide2==5.15.8
pytest==8.3.2
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
setup(
name='PyLoT',
version='0.2',
packages=['pylot', 'pylot.core', 'pylot.core.loc', 'pylot.core.pick',
'pylot.core.io', 'pylot.core.util', 'pylot.core.active',
'pylot.core.analysis', 'pylot.testing'],
requires=['obspy', 'PySide', 'matplotlib', 'numpy', 'scipy', 'pyqtgraph'],
url='dummy',
license='LGPLv3',
author='Sebastian Wehling-Benatelli',
author_email='sebastian.wehling@rub.de',
description='Comprehensive Python picking and Location Toolbox for seismological data.'
)
File diff suppressed because it is too large. Load diff
+2 -4
View File
@@ -1,8 +1,6 @@
import unittest import unittest
from pylot.core.pick.autopick import PickingResults from pylot.core.pick.autopick import PickingResults
class TestPickingResults(unittest.TestCase): class TestPickingResults(unittest.TestCase):
def setUp(self): def setUp(self):
@@ -72,9 +70,9 @@ class TestPickingResults(unittest.TestCase):
curr_len = len(self.pr) curr_len = len(self.pr)
except Exception: except Exception:
self.fail("test_dunder_attributes overwrote an instance internal dunder method") self.fail("test_dunder_attributes overwrote an instance internal dunder method")
self.assertEqual(prev_len + 1, curr_len) # +1 for the added __len__ key/value-pair self.assertEqual(prev_len+1, curr_len) # +1 for the added __len__ key/value-pair
self.pr.__len__ = 42 self.pr.__len__ = 42
self.assertEqual(42, self.pr['__len__']) self.assertEqual(42, self.pr['__len__'])
self.assertEqual(prev_len + 1, curr_len, msg="__len__ was overwritten") self.assertEqual(prev_len+1, curr_len, msg="__len__ was overwritten")
+6 -9
View File
@@ -1,6 +1,5 @@
import os import os
import unittest import unittest
from obspy import UTCDateTime from obspy import UTCDateTime
from obspy.io.xseed import Parser from obspy.io.xseed import Parser
from obspy.io.xseed.utils import SEEDParserException from obspy.io.xseed.utils import SEEDParserException
@@ -28,7 +27,7 @@ class TestMetadata(unittest.TestCase):
result = {} result = {}
for channel in ('Z', 'N', 'E'): for channel in ('Z', 'N', 'E'):
with HidePrints(): with HidePrints():
coords = self.m.get_coordinates(self.station_id + channel, time=self.time) coords = self.m.get_coordinates(self.station_id+channel, time=self.time)
result[channel] = coords result[channel] = coords
self.assertDictEqual(result[channel], expected[channel]) self.assertDictEqual(result[channel], expected[channel])
@@ -43,7 +42,7 @@ class TestMetadata(unittest.TestCase):
result = {} result = {}
for channel in ('Z', 'N', 'E'): for channel in ('Z', 'N', 'E'):
with HidePrints(): with HidePrints():
coords = self.m.get_coordinates(self.station_id + channel) coords = self.m.get_coordinates(self.station_id+channel)
result[channel] = coords result[channel] = coords
self.assertDictEqual(result[channel], expected[channel]) self.assertDictEqual(result[channel], expected[channel])
@@ -146,7 +145,7 @@ class TestMetadata_read_single_file(unittest.TestCase):
def test_read_single_file(self): def test_read_single_file(self):
"""Test if reading a single file works""" """Test if reading a single file works"""
fname = os.path.join(self.metadata_folders[0], 'DATALESS.' + self.station_id) fname = os.path.join(self.metadata_folders[0], 'DATALESS.'+self.station_id)
with HidePrints(): with HidePrints():
res = self.m.read_single_file(fname) res = self.m.read_single_file(fname)
# method should return true if file is successfully read # method should return true if file is successfully read
@@ -173,7 +172,7 @@ class TestMetadata_read_single_file(unittest.TestCase):
def test_read_single_file_multiple_times(self): def test_read_single_file_multiple_times(self):
"""Test if reading a file twice doesnt add it twice to the metadata object""" """Test if reading a file twice doesnt add it twice to the metadata object"""
fname = os.path.join(self.metadata_folders[0], 'DATALESS.' + self.station_id) fname = os.path.join(self.metadata_folders[0], 'DATALESS.'+self.station_id)
with HidePrints(): with HidePrints():
res1 = self.m.read_single_file(fname) res1 = self.m.read_single_file(fname)
res2 = self.m.read_single_file(fname) res2 = self.m.read_single_file(fname)
@@ -198,8 +197,7 @@ class TestMetadataMultipleTime(unittest.TestCase):
def setUp(self): def setUp(self):
self.seed_id = 'LE.ROTT..HN' self.seed_id = 'LE.ROTT..HN'
path = os.path.dirname(__file__) # gets path to currently running script path = os.path.dirname(__file__) # gets path to currently running script
metadata = os.path.join('test_data', 'dless_multiple_times', metadata = os.path.join('test_data', 'dless_multiple_times', 'MAGS2_LE_ROTT.dless') # specific subfolder of test data
'MAGS2_LE_ROTT.dless') # specific subfolder of test data
metadata_path = os.path.join(path, metadata) metadata_path = os.path.join(path, metadata)
self.m = Metadata(metadata_path) self.m = Metadata(metadata_path)
self.p = Parser(metadata_path) self.p = Parser(metadata_path)
@@ -301,8 +299,7 @@ Channels:
def setUp(self): def setUp(self):
self.seed_id = 'KB.TMO07.00.HHZ' self.seed_id = 'KB.TMO07.00.HHZ'
path = os.path.dirname(__file__) # gets path to currently running script path = os.path.dirname(__file__) # gets path to currently running script
metadata = os.path.join('test_data', 'dless_multiple_instruments', metadata = os.path.join('test_data', 'dless_multiple_instruments', 'MAGS2_KB_TMO07.dless') # specific subfolder of test data
'MAGS2_KB_TMO07.dless') # specific subfolder of test data
metadata_path = os.path.join(path, metadata) metadata_path = os.path.join(path, metadata)
self.m = Metadata(metadata_path) self.m = Metadata(metadata_path)
self.p = Parser(metadata_path) self.p = Parser(metadata_path)
+35
View File
@@ -0,0 +1,35 @@
import unittest
from pylot.core.pick.autopick import PickingParameters
class TestPickingParameters(unittest.TestCase):
def setUp(self):
self.simple_dict = {'a': 3, 'b': 14}
self.nested_dict = {'a': self.simple_dict, 'b': self.simple_dict}
def assertParameterEquality(self, dic, instance):
"""Test wether all parameters given in dic are found in instance"""
for key, value in dic.items():
self.assertEqual(value, getattr(instance, key))
def test_add_params_from_dict_simple(self):
pickparam = PickingParameters()
pickparam.add_params_from_dict(self.simple_dict)
self.assertParameterEquality(self.simple_dict, pickparam)
def test_add_params_from_dict_nested(self):
pickparam = PickingParameters()
pickparam.add_params_from_dict(self.nested_dict)
self.assertParameterEquality(self.nested_dict, pickparam)
def test_init(self):
pickparam = PickingParameters(self.simple_dict)
self.assertParameterEquality(self.simple_dict, pickparam)
def test_dot_access(self):
pickparam = PickingParameters(self.simple_dict)
self.assertEqual(pickparam.a, self.simple_dict['a'])
if __name__ == '__main__':
unittest.main()
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more