Updating plotting app.

This commit is contained in:
Kasper D. Fischer 2015-04-10 08:51:58 +00:00
parent 52b55705b8
commit b074f0e695
Notes: subgit 2018-03-07 17:59:10 +01:00
r824 www/trunk
3 changed files with 157 additions and 74 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
wsgi/.idea
www/dlsv www/dlsv
www/event.xml www/event.xml
www/events.xml www/events.xml

View File

@ -1,8 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
Get waveformdata from FDSN web service and create a fancy plot Get waveform data from FDSN web service and create a fancy plot
This programm runs as a script or as a WSGI application. This programme runs as a script or as a WSGI application.
Subversion information: Subversion information:
$Id$ $Id$
@ -41,6 +41,7 @@ def utc2local(utctime, timezone='Europe/Berlin'):
utctime = utc.localize(utctime.datetime) utctime = utc.localize(utctime.datetime)
return local.normalize(utctime.astimezone(local)) return local.normalize(utctime.astimezone(local))
def fancy_plot(st, wsgi=False, img_format='png', color=True): def fancy_plot(st, wsgi=False, img_format='png', color=True):
""" """
creating fancy plot from ObsPy stream st creating fancy plot from ObsPy stream st
@ -131,6 +132,61 @@ def fancy_plot(st, wsgi=False, img_format='png', color=True):
plt.show() plt.show()
def trace_dayplot(st, deltat = None,
ftype='bandpass', fmin=1.0, fmax=7.0,
col=('b', 'r', 'g'), interval=20, outpattern='',
wsgi=False):
"""
:type st: object
:type ftype: str
:type fmin: float
:type fmax: float
:type col: tuple
:type interval: float
:type outpattern: str
:type wsgi: bool
"""
if wsgi:
try:
import cStringIO as StringIO
except ImportError:
import StringIO as StringIO
# filter
if (ftype == 'bandpass') or (ftype == 'bandstop'):
st.filter(ftype, freqmin=fmin, freqmax=fmax)
elif (ftype == 'lowpass') or (ftype == 'highpass'):
st.filter(ftype, freq=fmin)
st.merge()
stime = st[0].stats.starttime
if deltat:
etime = stime + deltat
else:
etime = st[0].stats.endtime
# plot
for i in range(0, len(st)):
if wsgi:
buf = StringIO.StringIO()
st[i].plot(outfile=buf, format=outpattern, type='dayplot', color=col, interval=interval,
starttime=stime, endtime=etime)
return buf
else:
if outpattern != '':
imagefile = outpattern.format(st[i].stats.network,
st[i].stats.station,
st[i].stats.channel,
st[i].stats.starttime.year,
st[i].stats.starttime.julday)
st[i].plot(type='dayplot', color=col, interval=interval,
outfile=imagefile)
else:
st[i].plot(type='dayplot', color=col, interval=interval)
def get_fdsn(bulk_request, output='VEL', base_url='https://ariadne.geophysik.ruhr-uni-bochum.de'): def get_fdsn(bulk_request, output='VEL', base_url='https://ariadne.geophysik.ruhr-uni-bochum.de'):
""" """
Fetches waveform data from FDSN web service and returns Fetches waveform data from FDSN web service and returns
@ -172,18 +228,18 @@ def get_fdsn(bulk_request, output='VEL', base_url='https://ariadne.geophysik.ruh
return None return None
def main(backend=None, cla=None, wsgi=False): def main(backend=None, args=None, wsgi=False):
""" """
Main function to create a waveform plot. Main function to create a waveform plot.
This functions calls get_fdsn and fancy_plot to create the figure. This functions calls get_fdsn and fancy_plot to create the figure.
If wsgi == True it returns an ioString object containing the figure. If wsgi == True it returns an ioString object containing the figure.
:type backend: str :type backend: str
:type cla: dict :type args: dict
:type wsgi: bool :type wsgi: bool
:rtype : object :rtype : object
:param backend: :param backend:
:param cla: :param args:
:param wsgi: :param wsgi:
:return: ioString object with created image :return: ioString object with created image
""" """
@ -199,32 +255,48 @@ def main(backend=None, cla=None, wsgi=False):
mpl.use(backend) mpl.use(backend)
from obspy import UTCDateTime from obspy import UTCDateTime
if cla: if args:
deltat = cla['length'] deltat = args['length']
if cla['stime']: if args['stime']:
otime = UTCDateTime(cla['stime']) otime = UTCDateTime(args['stime'])
else: else:
otime = UTCDateTime() - 3600 - deltat otime = UTCDateTime() - 3600 - deltat
network = cla['station'].split('.')[0] network = args['station'].split('.')[0]
station = cla['station'].split('.')[1] station = args['station'].split('.')[1]
if args['type'] == 'dayplot':
channel = 'BHZ'
else:
if args['length'] < 3600:
channel = 'HH?'
else:
channel = 'BH?'
else: else:
otime = UTCDateTime('2014-11-15T11:35:25Z') otime = UTCDateTime('2014-11-15T11:35:25Z')
deltat = 30 deltat = 30
network = 'GR' network = 'GR'
station = 'BUG' station = 'BUG'
channel = 'HH?'
st = get_fdsn([(network, station, '*', 'HH?', otime, otime + deltat)], base_url=cla['server']) st = get_fdsn([(network, station, '*', channel, otime, otime + deltat)], base_url=args['server'])
if st is not None: if st is not None:
stime = max(st[0].stats.starttime, otime) stime = max(st[0].stats.starttime, otime)
etime = min(st[0].stats.endtime, otime + deltat) etime = min(st[0].stats.endtime, otime + deltat)
st.trim(starttime=stime, endtime=etime) st.trim(starttime=stime, endtime=etime)
if wsgi: if wsgi:
# noinspection PyUnresolvedReferences if args['type'] == 'dayplot':
return fancy_plot(st, wsgi=wsgi, img_format=cla['format'], color=cla['color']) with warnings.catch_warnings():
warnings.simplefilter("ignore")
return trace_dayplot(st, outpattern=args['format'], wsgi=wsgi, deltat=deltat)
else:
return fancy_plot(st, wsgi=wsgi, img_format=args['format'], color=args['color'])
else: else:
# noinspection PyUnresolvedReferences if args['type'] == 'dayplot':
fancy_plot(st, color=cla['color']) with warnings.catch_warnings():
warnings.simplefilter("ignore")
trace_dayplot(st, wsgi=wsgi)
else:
fancy_plot(st, color=args['color'])
elif not wsgi: elif not wsgi:
warnings.warn('No data available!') warnings.warn('No data available!')
@ -253,34 +325,39 @@ def application(environ, start_response):
# fake command line arguments # fake command line arguments
# setting needed default values # setting needed default values
cla = {'server': 'http://localhost/'} wsgi_args = {'server': 'http://localhost/'}
# fill cla with environment variables # fill wsgi_args with environment variables
form = FieldStorage(fp=environ['wsgi.input'], environ=environ) form = FieldStorage(fp=environ['wsgi.input'], environ=environ)
cla['station'] = form.getfirst('station', 'GR.BUG').upper() wsgi_args['station'] = form.getfirst('station', 'GR.BUG').upper()
cla['stime'] = form.getfirst('start_time', []) wsgi_args['stime'] = form.getfirst('start_time', [])
cla['length'] = form.getfirst('length', '30') wsgi_args['length'] = form.getfirst('length', '30')
cla['length'] = abs(int(cla['length'])) wsgi_args['length'] = abs(int(wsgi_args['length']))
cla['format'] = form.getfirst('format', 'png').lower() wsgi_args['format'] = form.getfirst('format', 'png').lower()
if cla['format'] != 'png' and cla['format'] != 'svg': if wsgi_args['format'] != 'png' and wsgi_args['format'] != 'svg':
cla['format'] = 'png' wsgi_args['format'] = 'png'
cla['color'] = form.getfirst('color', 'TRUE').upper() wsgi_args['color'] = form.getfirst('color', 'TRUE').upper()
if cla['color'] == 'FALSE': if wsgi_args['color'] == 'FALSE':
cla['color'] = False wsgi_args['color'] = False
else: else:
cla['color'] = True wsgi_args['color'] = True
wsgi_args['type'] = form.getfirst('type', '').lower()
if (wsgi_args['type'] != 'dayplot' and wsgi_args['type'] != 'normal') or wsgi_args['type'] == '':
if wsgi_args['length'] < 43200:
wsgi_args['type'] = 'normal'
else:
wsgi_args['type'] = 'dayplot'
# process the request # process the request
buf = main(cla=cla, backend='Agg', wsgi=True) buf = main(args=wsgi_args, backend='Agg', wsgi=True)
if buf is not None: if buf is not None:
data = buf.getvalue() data = buf.getvalue()
# noinspection PyUnresolvedReferences
buf.close() buf.close()
data_length = len(data) data_length = len(data)
if cla['format'] == u'svg': if wsgi_args['format'] == 'svg':
cla['format'] = u'svg+xml' wsgi_args['format'] = 'svg+xml'
start_response('200 OK', [('Content-Type', 'image/%s' % cla['format']), ('Content-Length', '%d' % data_length)]) start_response('200 OK', [('Content-Type', 'image/%s' % wsgi_args['format']), ('Content-Length', '%d' % data_length)])
return [data] return [data]
else: else:
start_response('400 Bad Request', []) start_response('400 Bad Request', [])
@ -301,6 +378,8 @@ if __name__ == "__main__":
parser.add_argument(u'-u', u'--url', action='store', dest='server', parser.add_argument(u'-u', u'--url', action='store', dest='server',
default=u'https://ariadne.geophysik.ruhr-uni-bochum.de', default=u'https://ariadne.geophysik.ruhr-uni-bochum.de',
help=u'Base URL of the FDSN web service (https://ariadne.geophysik.ruhr-uni-bochum.de).') help=u'Base URL of the FDSN web service (https://ariadne.geophysik.ruhr-uni-bochum.de).')
parser.add_argument(u'-t', u'--type', action='store', dest='type', metavar='TYPE',
help=u'Type of plot: normal or dayplot.')
parser.add_argument(u'-f', u'--file', action='store', dest='filename', metavar='FILENAME', parser.add_argument(u'-f', u'--file', action='store', dest='filename', metavar='FILENAME',
help=u'Save plot to file FILENAME') help=u'Save plot to file FILENAME')
parser.add_argument(u'-c', u'--color', action='store_true', help=u'Create color plot.') parser.add_argument(u'-c', u'--color', action='store_true', help=u'Create color plot.')
@ -317,6 +396,6 @@ if __name__ == "__main__":
cla = vars(parser.parse_args()) cla = vars(parser.parse_args())
if os.getenv('DISPLAY'): if os.getenv('DISPLAY'):
main(cla=cla) main(args=cla)
else: else:
main('Agg', cla) main('Agg', cla)

View File

@ -1,13 +1,13 @@
#! /usr/bin/env python #! /usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
Produce a dayplot Produce a dayplot from seismogram recordings
Subversion information: Subversion information:
$Id$ $Id$
"""
""" license: gpl3
Copyright 2012 Seismological Observatory, Ruhr-University Bochum Copyright 2012-2015 Seismological Observatory, Ruhr-University Bochum
http://www.gmg.ruhr-uni-bochum.de/geophysik/seisobs http://www.gmg.ruhr-uni-bochum.de/geophysik/seisobs
Contributors: Contributors:
Martina Rische <martina.rische@rub.de> Martina Rische <martina.rische@rub.de>
@ -28,28 +28,30 @@ You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/. with this program. If not, see http://www.gnu.org/licenses/.
""" """
def traceDayplot(datafile, ftype='bandpass', fmin=1.0, fmax=7.0,
col=('b','r','g'), interval=20.0, outpattern=''):
''' def trace_dayplot(st, ftype='bandpass', fmin=1.0, fmax=7.0,
''' col=('b', 'r', 'g'), interval=20.0, outpattern=''):
"""
:type st: object
:type ftype: str
:type fmin: float
:type fmax: float
:type col: tuple
:type interval: float
:type outpattern: str
"""
from obspy.core import read # filter
st = read(datafile)
#filter
if (ftype == 'bandpass') or (ftype == 'bandstop'): if (ftype == 'bandpass') or (ftype == 'bandstop'):
st.filter(ftype, freqmin=fmin, freqmax=fmax) st.filter(ftype, freqmin=fmin, freqmax=fmax)
elif (ftype == 'lowpass') or (ftype == 'highpass'): elif (ftype == 'lowpass') or (ftype == 'highpass'):
st.filter(ftype, freq=fmin) st.filter(ftype, freq=fmin)
st.merge() st.merge()
#plot # plot
for i in range(0,len(st)): for i in range(0, len(st)):
if (outpattern != ''): if outpattern != '':
imagefile = outpattern.format(st[i].stats.network, imagefile = outpattern.format(st[i].stats.network,
st[i].stats.station, st[i].stats.station,
st[i].stats.channel, st[i].stats.channel,
@ -66,37 +68,39 @@ if __name__ == "__main__":
# parse arguments # parse arguments
import argparse import argparse
from obspy.core import read
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description='Produce filtered 24h-plot (dayplot).', description='Produce filtered 24h-plot (dayplot).',
epilog='$Rev: 403 $ ($Date: 2012-04-13 12:16:22 +0200 (Fri, 13 Apr 2012) $, $Author: kasper $)') epilog='$Rev: 403 $ ($Date: 2012-04-13 12:16:22 +0200 (Fri, 13 Apr 2012) $, $Author: kasper $)')
parser.add_argument('-v', '-V','--version', action='version', parser.add_argument('-v', '-V', '--version', action='version',
version='$Rev: 403 $ ($Date: 2012-04-13 12:16:22 +0200 (Fri, 13 Apr 2012) $, $Author: kasper $)') version='$Rev: 403 $ ($Date: 2012-04-13 12:16:22 +0200 (Fri, 13 Apr 2012) $, $Author: kasper $)')
parser.add_argument('file', action='store', metavar='FILE', nargs='+', parser.add_argument('file', action='store', metavar='FILE', nargs='+',
help='File(s) to use for the dayplot. One dayplot will be used for every file. \ help='File(s) to use for the dayplot. One dayplot will be used for every file. \
Use wildcards to use multiple file for one plot') Use wildcards to use multiple file for one plot')
parser.add_argument('-f', '--filter', action='store', dest='ftype', parser.add_argument('-f', '--filter', action='store', dest='ftype',
default='bandpass', default='bandpass',
choices=['none', 'bandpass', 'bandstop', 'lowpass', 'highpass'], choices=['none', 'bandpass', 'bandstop', 'lowpass', 'highpass'],
help='Select filtertype to filter the data (default: bandpass)\ help='Select filtertype to filter the data (default: bandpass)\
Note: For low- and highpass only fmin is used.') Note: For low- and highpass only fmin is used.')
parser.add_argument('--fmin', action='store', type=float, dest='fmin', parser.add_argument('--fmin', action='store', type=float, dest='fmin',
default=1.0, default=1.0,
help='Lower frequency of the filter in Hz (default: 1.0)') help='Lower frequency of the filter in Hz (default: 1.0)')
parser.add_argument('--fmax', action='store', type=float, dest='fmax', parser.add_argument('--fmax', action='store', type=float, dest='fmax',
default=7.0, default=7.0,
help='Upper frequency of the filter in Hz (default: 7.0)') help='Upper frequency of the filter in Hz (default: 7.0)')
parser.add_argument('-c', '--color', '--colour', action='store', dest='color', parser.add_argument('-c', '--color', '--colour', action='store', dest='color',
default=('b', 'r', 'g'), default=('b', 'r', 'g'),
help='Color selection to use in the dayplot (default: brg)') help='Color selection to use in the dayplot (default: brg)')
parser.add_argument('-i', '--interval', action='store', type=int, dest='interval', parser.add_argument('-i', '--interval', action='store', type=int, dest='interval',
default=20, default=20,
help='Interval length to show in each line of the dayplot in minutes (default: 20)') help='Interval length to show in each line of the dayplot in minutes (default: 20)')
parser.add_argument('-o', '--output', action='store', dest='outpattern', parser.add_argument('-o', '--output', action='store', dest='outpattern',
default='', default='',
help="Output filename pattern for the plot. (default: unset, show plot on screen only), \ help="Output filename pattern for the plot. (default: unset, show plot on screen only), \
Use {0} to substitute network code, \ Use {0} to substitute network code, \
{1} to substitute station code, \ {1} to substitute station code, \
{2} to subsitute station channel, \ {2} to substitute station channel, \
{3} to substitute year, \ {3} to substitute year, \
{4} to substitute doy number \ {4} to substitute doy number \
.format (supported formats: emf, eps, pdf, png, ps, raw, rgba, svg, svgz)") .format (supported formats: emf, eps, pdf, png, ps, raw, rgba, svg, svgz)")
@ -107,8 +111,7 @@ if __name__ == "__main__":
if cla.fmax < 0: if cla.fmax < 0:
cla.fmax = -cla.fmax cla.fmax = -cla.fmax
# call traceDayplot(...) for each file # call trace_dayplot(...) for each file
for datafile in cla.file: for datafile in cla.file:
traceDayplot(datafile, cla.ftype, cla.fmin, cla.fmax, cla.color, trace_dayplot(read(datafile), cla.ftype, cla.fmin, cla.fmax, cla.color,
cla.interval, cla.outpattern) cla.interval, cla.outpattern)