Exemple #1
0
def get_event_radius(minradius, maxradius, minmag):
    '''
    Get all the events in time range
    Return:
        Event catalog
    '''
    
    maxlatitude = para["Map Info"].getfloat("maxlatitude")
    minlatitude = para["Map Info"].getfloat("minlatitude")
    maxlongitude = para["Map Info"].getfloat("maxlongitude")
    minlongitude = para["Map Info"].getfloat("minlongitude")
    
    cat = client.get_events(
        starttime=para["Station Info"].get("starttime", "19900101T00:00:00"),
        endtime=para["Station Info"].get("endtime", UTCDateTime.now()),
        latitude=(maxlatitude+minlatitude) / 2,
        longitude=(maxlongitude+minlongitude) / 2,
        minradius=minradius,
        maxradius=maxradius,
        minmagnitude=minmag)

    for event in cat:
        extra = {"downloaded": {"value": "False",
                "namespace":"http://test.org/xmlns/1.0"}}
        event.extra = extra
    
    if para["Save Data"].getboolean("eventcatlog"):
        cat.write(f'{para["DEFAULT"].get("projdir")}/evcatalog.xml', format="QUAKEML")
    
    return cat
Exemple #2
0
 def __init__(self,
              trace,
              time,
              name='',
              comments='',
              method=method_other,
              aic=None,
              n0_aic=None,
              *args, **kwargs):
     self.trace = trace
     if time < 0 or time >= len(self.trace.signal):
         raise ValueError("Event position must be a value between 0 and %d"
                          % len(self.trace.signal))
     self.stime = time
     self.name = name
     self.method = method
     self.aic = aic
     self.n0_aic = n0_aic
     super(ApasvoEvent, self).__init__(time=self.time,
                                       method_id=ResourceIdentifier(method),
                                       creation_info=CreationInfo(
                                           author=kwargs.get('author', ''),
                                           agency_id=kwargs.get('agency', ''),
                                           creation_time=UTCDateTime.now(),
                                       ),
                                       waveform_id=WaveformStreamID(
                                           network_code=self.trace.stats.get('network', ''),
                                           station_code=self.trace.stats.get('station', ''),
                                           location_code=self.trace.stats.get('location', ''),
                                           channel_code=self.trace.stats.get('channel', ''),
                                       ),
                                       *args,
                                       **kwargs)
     self.comments = comments
Exemple #3
0
def get_station():
    '''
    Get the info of all available networks and stations satisfying requirements
    Return:
        station inventory
    '''

    Netinv = client.get_stations(
        network = para["Station Info"].get("network", "*"),
        station = para["Station Info"].get("station", "*"),
        channel = para["Station Info"].get("channelpri", "*"),
        starttime = para["Station Info"].get("starttime", "19900101T00:00:00"),
        endtime = para["Station Info"].get("endtime", UTCDateTime.now()),
        maxlatitude = para["Map Info"].getfloat("maxlatitude"),
        minlatitude = para["Map Info"].getfloat("minlatitude"),
        maxlongitude = para["Map Info"].getfloat("maxlongitude"),
        minlongitude = para["Map Info"].getfloat("minlongitude")
    )

    filter_net = para["Station Info"].get("network_filter").split(",")
    for net in filter_net:
        Netinv = Netinv.remove(network=net)

    if para["Save Data"].getboolean("stationinfo"):
        Netinv.write(f'{para["DEFAULT"].get("projdir")}/station.txt', format="STATIONTXT", level='station')

    return Netinv
Exemple #4
0
def _get_nettime(nw):
    '''
    Calculate the time range of each network for downloading
    Return:
        starttime, endtime
    '''

    nwbegin = min([sta.start_date for sta in nw.stations])
    if None in [sta.end_date for sta in nw.stations]:
        nwend = UTCDateTime.now()
    else:
        nwend = max([sta.end_date for sta in nw.stations])

    return max(nwbegin, UTCDateTime(para["Station Info"].get("starttime"))), min(nwend, UTCDateTime(para["Station Info"].get("endtime")))
Exemple #5
0
def shakeview(request):
	DEFAULTSTATION = 'NE.ORNO.00.HHZ'
	try:
		if request.GET['sta'] == 'AM.R6A3B.00.EHZ':
			DEFAULTSTATION = request.GET['sta']
		if request.GET['sta'] == 'AM.R35E7.00.SHZ':
			DEFAULTSTATION = request.GET['sta']
		if request.GET['sta'] == 'AM.RCB43.00.SHZ':
			DEFAULTSTATION = request.GET['sta']
		if request.GET['sta'] == 'AM.R4989.00.EHZ':
			DEFAULTSTATION = request.GET['sta']
		if request.GET['sta'] == 'NE.ORNO.00.HHZ':
			DEFAULTSTATION = request.GET['sta']
	except MultiValueDictKeyError as e:
		pass
	JULIANDATE = UTCDateTime.now().strftime('%Y.%j')
	AVAIL = '/media/shakedown/avail/%s.png' % JULIANDATE
	HELI = '/media/shakedown/cronplots/%s.%s-heli.png' % (DEFAULTSTATION, JULIANDATE)
	SPEC = '/media/shakedown/cronplots/%s.%s-spec.png' % (DEFAULTSTATION, JULIANDATE)
	SPECBP = '/media/shakedown/cronplots/%s.%s-spec-band.png' % (DEFAULTSTATION, JULIANDATE)
	HELIBP = '/media/shakedown/cronplots/%s.%s-heli-band.png' % (DEFAULTSTATION, JULIANDATE)


	try:
		lmtime = os.path.getmtime('/var/www/nezsite/nezsite/nezsite/media/shakedown/cronplots/%s.%s-heli.png' % (DEFAULTSTATION, JULIANDATE))
	except OSError:
		lmtime = 0
	mtime = datetime.utcfromtimestamp(lmtime)

	context = {
	    'sta': DEFAULTSTATION,
	    'heli': HELI,
	    'spec': SPEC,
	    'helibp': HELIBP,
	    'specbp': SPECBP,
		'avail': AVAIL,
		'mtime': mtime,
		'time': timezone.now(),
		'page': 'Seismic Monitor',
	}
	return render(request, 'shake/shake.html', context)
Exemple #6
0
 def __init__(self,
              trace,
              time,
              name='',
              comments='',
              method=method_other,
              phase_hint=None,
              polarity='undecidable',
              aic=None,
              n0_aic=None,
              *args, **kwargs):
     self.trace = trace
     if time < 0 or time >= len(self.trace.signal):
         raise ValueError("Event position must be a value between 0 and %d"
                          % len(self.trace.signal))
     self.stime = time
     self.name = name
     self.method = method
     self.aic = aic
     self.n0_aic = n0_aic
     phase_hint = phase_hint if phase_hint in PHASE_VALUES else PHASE_VALUES[0]
     super(ApasvoEvent, self).__init__(time=self.time,
                                       method_id=ResourceIdentifier(method),
                                       phase_hint=phase_hint,
                                       polarity=polarity,
                                       creation_info=CreationInfo(
                                           author=kwargs.get('author', ''),
                                           agency_id=kwargs.get('agency', ''),
                                           creation_time=UTCDateTime.now(),
                                       ),
                                       waveform_id=WaveformStreamID(
                                           network_code=self.trace.stats.get('network', ''),
                                           station_code=self.trace.stats.get('station', ''),
                                           location_code=self.trace.stats.get('location', ''),
                                           channel_code=self.trace.stats.get('channel', ''),
                                       ),
                                       *args,
                                       **kwargs)
     self.comments = comments
Exemple #7
0
    def addStreams(self, event, streams, label=None):
        """Add a sequence of StationStream objects to an ASDF file.

        Args:
            event (Event):
                Obspy event object.
            streams (list):
                List of StationStream objects.
            label (str):
                Label to attach to stream sequence. Cannot contain an
                underscore.
        """
        if label is not None:
            if '_' in label:
                raise ValueError(
                    'Stream label cannot contain an underscore.')

        # To allow for multiple processed versions of the same Stream
        # let's keep a dictionary of stations and sequence number.
        eventid = _get_id(event)
        if not self.hasEvent(eventid):
            self.addEvent(event)

        # Creating a new provenance document and filling in the software
        # information for every trace can be slow, so here we create a
        # base provenance document that will be copied and used as a template
        base_prov = prov.model.ProvDocument()
        base_prov.add_namespace(*NS_SEIS)
        base_prov = _get_person_agent(base_prov)
        base_prov = _get_software_agent(base_prov)

        logging.debug(streams)
        for stream in streams:
            station = stream[0].stats['station']
            logging.info('Adding waveforms for station %s' % station)
            # is this a raw file? Check the trace for provenance info.
            is_raw = not len(stream[0].getProvenanceKeys())

            if label is None:
                tfmt = '%Y%m%d%H%M%S'
                tnow = UTCDateTime.now().strftime(tfmt)
                label = 'processed%s' % tnow
            tag = '{}_{}'.format(eventid, label)
            if is_raw:
                level = 'raw'
            else:
                level = 'processed'
            self.dataset.add_waveforms(stream, tag=tag, event_id=event)

            # add processing provenance info from traces
            if level == 'processed':
                provdocs = stream.getProvenanceDocuments(base_prov)
                for provdoc, trace in zip(provdocs, stream):
                    provname = format_nslct(trace.stats, tag)
                    self.dataset.add_provenance_document(
                        provdoc,
                        name=provname
                    )

            # add processing parameters from streams
            jdict = {}
            for key in stream.getStreamParamKeys():
                value = stream.getStreamParam(key)
                jdict[key] = value

            if len(jdict):
                # NOTE: We would store this dictionary just as
                # the parameters dictionary, but HDF cannot handle
                # nested dictionaries.
                # Also, this seems like a lot of effort
                # just to store a string in HDF, but other
                # approaches failed. Suggestions are welcome.
                jdict = _stringify_dict(jdict)
                jsonbytes = json.dumps(jdict).encode('utf-8')
                jsonarray = np.frombuffer(jsonbytes, dtype=np.uint8)
                dtype = 'StreamProcessingParameters'
                parampath = '/'.join([
                    format_netsta(stream[0].stats),
                    format_nslit(stream[0].stats, stream.get_inst(), tag)
                ])
                self.dataset.add_auxiliary_data(
                    jsonarray,
                    data_type=dtype,
                    path=parampath,
                    parameters={}
                )

            # add processing parameters from traces
            for trace in stream:
                procname = '/'.join([format_netsta(trace.stats),
                                     format_nslct(trace.stats, tag),
                                     ])
                jdict = {}
                for key in trace.getParameterKeys():
                    value = trace.getParameter(key)
                    jdict[key] = value
                if len(jdict):
                    # NOTE: We would store this dictionary just as
                    # the parameters dictionary, but HDF cannot handle
                    # nested dictionaries.
                    # Also, this seems like a lot of effort
                    # just to store a string in HDF, but other
                    # approached failed. Suggestions are welcome.
                    jdict = _stringify_dict(jdict)
                    jsonbytes = json.dumps(jdict).encode('utf-8')
                    jsonarray = np.frombuffer(jsonbytes, dtype=np.uint8)
                    dtype = 'TraceProcessingParameters'
                    self.dataset.add_auxiliary_data(
                        jsonarray,
                        data_type=dtype,
                        path=procname,
                        parameters={}
                    )

                # Some processing data is computationally intensive to
                # compute, so we store it in the 'Cache' group.
                for specname in trace.getCachedNames():
                    spectrum = trace.getCached(specname)
                    # we expect many of these specnames to
                    # be joined with underscores.
                    name_parts = specname.split('_')
                    base_dtype = ''.join([part.capitalize()
                                          for part in name_parts])
                    for array_name, array in spectrum.items():
                        path = base_dtype + array_name.capitalize() \
                            + "/" + procname
                        try:
                            self.dataset.add_auxiliary_data(
                                array,
                                data_type='Cache',
                                path=path,
                                parameters={}
                            )
                        except BaseException:
                            pass

            inventory = stream.getInventory()
            self.dataset.add_stationxml(inventory)
Exemple #8
0
    station_list=[]

    # here we collect station names but maybe ID is more appropriate in case of having the same station names
    # in different deployments
    
    for i in xrange(len(selected_stream)):
         station_list.append(selected_stream[i].stats.station)
         net = selected_stream[i].stats.network

    pdffile = net + '-' + rf_type.strip() + '-rf-vespagrams.pdf'

    exists = os.path.isfile(pdffile)

    if exists:
         # we add the time stamp to identify the file that can be read in linux command line as date -d @number (date -d @1542926631)
         pdffile = net + '-' + rf_type.strip() + '-' + str(int(UTC.now()._get_timestamp())) + '-rf-vespagrams.pdf'

    pdf = PdfPages(pdffile)
    pdf.attach_note(rf_type+filter_type+' '+str(freqmin)+'-'+str(freqmax)+' Hz') 
    d = pdf.infodict()
    d['Title'] = rf_type+'RF vespagrams of '+net+' network'
    d['Keywords'] =  rf_type+filter_type+' '+str(freqmin)+'-'+str(freqmax)+' Hz'

    station_list=np.unique(np.array(station_list))
    print("Gathered ",len(station_list)," stations")

#   Define layout of the page outer_grid
    columns=3
    rows=2
    frame=0
    figure=1
Exemple #9
0
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from obspy import read
from obspy.core.utcdatetime import UTCDateTime
from datetime import datetime
import pytz

net = 'AM' # network. usually AM "amateur"
sta = 'R0000' # station callsign. 5 uppercase alphanumeric characters beginning with R
ch = 'SHZ' # channel. should be either SHZ or EHZ depending on the model
loc = '00' # location. usually 00

now = UTCDateTime.now()
yr = now.year
day = now.strftime('%Y.%j')
skip = 60 * 5 # the number of seconds to skip back
short = now - (60*5) # datetime of analysis stary
tz = int(datetime.now(pytz.timezone('America/New_York')).strftime('%z'))/100
fmin = 0.1 # min frequency
fmax = 25 # max freq (should not exceed 25)
fminbp = 0.7 # lower bandpass limit
fmaxbp = 2 # upper bandpass limit

# output locations and filenames
outdir = '/opt/data/obs'
heli = os.path.join(outdir, day + '.png')
heliband = os.path.join(outdir, day + '-lowband.png')
spec = os.path.join(outdir, 'spec.png')
Exemple #10
0
    station_list = []

    # here we collect station names but maybe ID is more appropriate in case of having the same station names in different deployments

    for i in xrange(len(selected_stream)):
        station_list.append(selected_stream[i].stats.station.encode('utf-8'))
        net = selected_stream[i].stats.network.encode('utf-8')

    pdffile = net + '-' + rf_type.strip() + '-rf-vespagrams.pdf'

    exists = os.path.isfile(pdffile)

    if exists:
        # we add the time stamp to identify the file that can be read in linux command line as date -d @number (date -d @1542926631)
        pdffile = net + '-' + rf_type.strip() + '-' + str(
            int(UTC.now()._get_timestamp())) + '-rf-vespagrams.pdf'

    pdf = PdfPages(pdffile)
    pdf.attach_note(rf_type + filter_type + ' ' + str(freqmin) + '-' +
                    str(freqmax) + ' Hz')
    d = pdf.infodict()
    d['Title'] = rf_type + 'RF vespagrams of ' + net + ' network'
    d['Keywords'] = rf_type + filter_type + ' ' + str(freqmin) + '-' + str(
        freqmax) + ' Hz'

    station_list = np.unique(np.array(station_list))
    print "Gathered ", len(station_list), " stations"

    #   Define layout of the page outer_grid
    columns = 3
    rows = 2
def processor(sta, start, end, dbscale, filtmin, filtmax, inpath='/var/www/nezsite/nezsite/nezsite/media/seismic', OUTPATH='/var/www/nezsite/nezsite/nezsite/media/shakedown'):
	#global INPATH
	day = start.strftime('%Y.%j')
	yday = (start - timedelta(days=1)).strftime('%Y.%j')
	daystart = UTCDateTime(start.year, start.month, start.day)
	dayend = daystart + timedelta(days=1)
	if dayend > datetime.now():
		now = UTCDateTime.now()
		mins = 0
		hourdelta = timedelta(hours=0)
		if 14 >= now.minute >= 0:
			mins = 15
		elif 29 >= now.minute >= 15:
			mins = 30
		elif 44 >= now.minute >= 30:
			mins = 45
		else:
			mins = 0
			hourdelta = timedelta(hours=1)
		now += hourdelta
		dayend = UTCDateTime(now.year, now.month, now.day, now.hour, mins)
		daystart = dayend - timedelta(days=1)
	avail = day + '.png'
	avail = os.path.join(AVAILPATH, avail)

	if sta:
		stn = sta
		#sta = sta + '.D.'
	else:
		stn = str(STA_DEF[0:-2])
		#sta = STA_DEF
		sta = stn

	stc = stn.split('.')
	net = stc[0]
	sta = stc[1]
	loc = stc[2]
	ch = stc[3]

	fn = '%s.%s.%s.%s.%s' % (sta, net, loc, ch, day)
	yfn = '%s.%s.%s.%s.%s' % (sta, net, loc, ch, yday)

	inpath = os.path.join(inpath, stc[0], stc[1])
	if os.path.isdir(os.path.join(inpath, 'proc')):
		pass
	else:
		os.mkdir(os.path.join(inpath, 'proc'))

	shutil.copy2(os.path.join(inpath, fn), os.path.join(inpath, 'proc'))
	shutil.copy2(os.path.join(inpath, yfn), os.path.join(inpath, 'proc'))
	ypath = inpath
	inpath = os.path.join(inpath, 'proc')


	tz = int(datetime.now(pytz.timezone('America/New_York')).strftime('%z'))/100
	fmin = 0.1
	fmax = 25
	fminbp = filtmin
	fmaxbp = filtmax
	if 'ORNO' in sta:
		fminbp = 0.03 # 33.3 seconds
		fmaxbp = 0.1  # 10 seconds

	heli = os.path.join(OUTPATH, stn + '.' + day + '-heli.png')
	helibp = os.path.join(OUTPATH, stn + '.' + day + '-heli-band.png')
	dur, spec = '', ''

	st = read().clear()
	yst = st.copy()
	try:
		yst = read(os.path.join(ypath, yfn))
	except:
		print("error reading yesterday's miniSEED file. may be further errors...")

	try:
		st = read(os.path.join(inpath, fn))
		os.remove(os.path.join(inpath, fn))
	except:
		print("error reading today's miniSEED file. may be further errors...")

	net = str(st[0].stats.network)
	sta = str(st[0].stats.station)
	loc = str(st[0].stats.location)
	ch = str(st[0].stats.channel)
	startt = str(st[0].stats.starttime)
	sr = str(st[0].stats.sampling_rate)

	st = yst + st
	#st.merge()
	st = st.slice(starttime=daystart, endtime=dayend)

	sbp = st.copy()
	sbp = sbp.filter('bandpass', freqmin=fminbp, freqmax=fmaxbp, zerophase=True)
	spu = st.slice(starttime=start, endtime=end)
	sps = sbp.slice(starttime=start, endtime=end) # slice for bandpass spectrogram

	cat = Catalog()
	try:
		cat.extend(read_events(pathname_or_url='/var/www/nezsite/nezsite/nezsite/media/seismic/events/evtmajor30days.xml', format='QUAKEML'))
	except:
		pass
	try:
		cat.extend(read_events(pathname_or_url='/var/www/nezsite/nezsite/nezsite/media/seismic/events/evtlocal30days.xml', format='QUAKEML'))
	except:
		pass

	'''
	# get events
	client = Client("USGS")
	cat = Catalog()
	try:
		cat += client.get_events(starttime=daystart, endtime=dayend, latitude=44.036114, longitude=-70.439856, maxradius=10)
	except FDSNException:
		pass
	try:
		cat += client.get_events(starttime=daystart, endtime=dayend, latitude=44.036114, longitude=-70.439856,
									minradius=10, maxradius=15, minmagnitude=2.5)
	except FDSNException:
		pass
	try:
		cat += client.get_events(starttime=daystart, endtime=dayend, minmagnitude=6.5)
	except FDSNException:
		pass
	'''

	title = net + '.' + sta + '.' + loc + '.' + ch + ' - ' + startt + ' - rate: ' + sr

	st.plot(type="dayplot", size=(1600, 1200), title=title + 'Hz - band: 0-25Hz', vertical_scaling_range=2000,
		tick_format='%H:%M', outfile=heli, color=['k', 'r', 'b', 'g'], linewidth=0.3, time_offset=tz, events=cat)
	sbp.plot(type="dayplot", size=(1600, 1200), title=title + 'Hz - band: '+ str(fminbp) + '-' + str(fmaxbp) + 'Hz', vertical_scaling_range=200,
		tick_format='%H:%M', outfile=helibp, color=['k', 'r', 'b', 'g'], linewidth=0.3, time_offset=tz, events=cat)

	#st.plot(type="dayplot", title=net + '.' + sta + '.' + loc + '.' + ch + ' - ' + startt + ' - rate: ' + sr + 'Hz - band: 0-25Hz', vertical_scaling_range=8e3, outfile=heli, color=['k', 'r', 'b', 'g'], time_offset=tz, events={'min_magnitude': 6.5})
	#sbp.plot(type="dayplot", title=net + '.' + sta + '.' + loc + '.' + ch + ' - ' + startt + ' - rate: ' + sr + 'Hz - band: '+ str(fminbp) + '-' + str(fmaxbp) + 'Hz', vertical_scaling_range=7e2, outfile=helibp, color=['k', 'r', 'b', 'g'], time_offset=tz, events={'min_magnitude': 6.5})

	heli = WEBPATH + os.path.split(heli)[1]
	helibp = WEBPATH + os.path.split(helibp)[1]

	if end:
		dur = end - start


	sp = spu.detrend(type='constant')
	ss = sps.detrend(type='constant')

	startt = str(sp[0].stats.starttime)


	## ------------------------- ##
	# make spectrogram figure 1
	fig = plt.figure(figsize=(16,6), dpi=100)
	ax1 = fig.add_axes([0.068, 0.75, 0.85, 0.2]) #[left bottom width height]
	ax2 = fig.add_axes([0.068, 0.1, 0.85, 0.6], sharex=ax1)
	ax3 = fig.add_axes([0.931, 0.1, 0.03, 0.6])

	# labels
	fig.suptitle(net + '.' + sta + '.' + loc + '.' + ch + ' - ' + startt + ' - samplerate: ' + sr + 'Hz - frequency band: 0-25 Hz')
	ax1.set_ylabel('Traces')
	ax2.set_xlabel('Time [s]')
	ax2.set_ylabel('Frequency [Hz]')
	ax3.set_ylabel('Energy density [dimensionless]') # doesn't work

	# make time vector
	t = np.arange(sp[0].stats.npts) / sp[0].stats.sampling_rate

	# plot waveform (top subfigure)
	ax1.plot(t, sp[0].data, 'k', linewidth=0.5)

	# plot spectrogram (bottom subfigure)
	fig = sp[0].spectrogram(show=False, axes=ax2, log=False, dbscale=dbscale, cmap='viridis')
	mappable = ax2.images[0]
	plt.colorbar(mappable=mappable, cax=ax3)

	ax2.set_ylim(fmin, fmax)

	if 'cronplots' in OUTPATH:
		spec = os.path.join(OUTPATH, stn + '.' + start.strftime('%Y.%j') + "-spec.png")
	else:
		spec = os.path.join(OUTPATH, stn + '.' + start.strftime('%Y.%j.%H%M%S-') + str(dur) + "-spec.png")
	plt.savefig(spec)
	spec = WEBPATH + os.path.split(spec)[1]


	## ------------------------- ##
	# make spectrogram figure 2
	sfig2 = plt.figure(figsize=(16,4), dpi=100)
	ax1 = sfig2.add_axes([0.068, 0.600, 0.85, 0.3]) #[left bottom width height]
	ax2 = sfig2.add_axes([0.068, 0.115, 0.85, 0.4], sharex=ax1)
	ax3 = sfig2.add_axes([0.932, 0.115, 0.03, 0.4])

	# labels
	sfig2.suptitle(net + '.' + sta + '.' + loc + '.' + ch + ' - ' + startt + ' - samplerate: ' + sr + 'Hz - bandpass: '******'-' + str(fmaxbp) + ' Hz')
	ax1.set_ylabel('Counts')
	ax2.set_xlabel('Time [s]')
	ax2.set_ylabel('Frequency [Hz]')
	ax3.set_ylabel('Energy density [dimensionless]') # doesn't work

	# make time vector
	t = np.arange(ss[0].stats.npts) / ss[0].stats.sampling_rate

	# plot waveform (top subfigure)
	ax1.plot(t, ss[0].data, 'k', linewidth=0.5)

	# plot spectrogram (bottom subfigure)
	sfig2 = ss[0].spectrogram(show=False, axes=ax2, log=False, dbscale=dbscale, cmap='viridis')
	mappable = ax2.images[0]
	plt.colorbar(mappable=mappable, cax=ax3)

	ax2.set_ylim(fminbp, fmaxbp)


	if 'cronplots' in OUTPATH:
		specbp = os.path.join(OUTPATH, stn + '.' + start.strftime('%Y.%j') + "-spec-band.png")
	else:
		specbp = os.path.join(OUTPATH, stn + '.' + start.strftime('%Y.%j.%H%M%S-') + str(dur) + "-spec-band.png")
	plt.savefig(specbp)
	specbp = WEBPATH + os.path.split(specbp)[1]



	imgpaths = {
		'avail': avail,
		'filtmin': fminbp,
		'filtmax': fmaxbp,
		'heli': heli,
		'helibp': helibp,
		'spec': spec,
		'specbp': specbp,
	}
	return imgpaths
Exemple #12
0
def shakedown(request):
	DEFAULTSTATION = 'NE.ORNO.00.HHZ'
	JULIANDATE = UTCDateTime.now().strftime('%Y.%j')
	AVAIL = '/media/shakedown/avail/%s.png' % JULIANDATE
	HELI = '/media/shakedown/cronplots/%s.%s-heli.png' % (DEFAULTSTATION, JULIANDATE)
	SPEC = '/media/shakedown/cronplots/%s.%s-spec.png' % (DEFAULTSTATION, JULIANDATE)
	SPECBP = '/media/shakedown/cronplots/%s.%s-spec-band.png' % (DEFAULTSTATION, JULIANDATE)
	HELIBP = '/media/shakedown/cronplots/%s.%s-heli-band.png' % (DEFAULTSTATION, JULIANDATE)
	
	initialtime = (UTCDateTime.now() - 90).strftime('%Y%m%d%H%M%S')
	initialdur = 30
	initialdbscale = ''
	r35e7, r4989, r6a3b, rcb43, orno = '', '', '', '', ''
	sta, start, dur, end, dbscale, logscale, status = False, False, False, False, False, False, False
	userstart, userdur = '', ''
	filtmin, filtmax = 0.7, 2
	procimg = {
		'heli': HELI,
		'avail': AVAIL,
		'spec': SPEC,
		'helibp': HELIBP,
		'specbp': SPECBP,
		'filtmin': filtmin,
		'filtmax': filtmax,
	}
	try:
		userstart = int(request.GET['start'])
		start = datetime.strptime(str(userstart), '%Y%m%d%H%M%S')
		initialtime = start.strftime('%Y%m%d%H%M%S')
		try:
			userdur = int(request.GET['dur'])
		except (ValueError, MultiValueDictKeyError) as e:
			status = e
		try:
			dbscale = request.GET['dbscale']
			if dbscale == 'on':
				dbscale = True
				initialdbscale = 'checked'
			else:
				dbscale = False
		except (ValueError, MultiValueDictKeyError) as e:
			pass
		try:
			logscale = request.GET['logscale']
			if logscale == 'on':
				logscale = True
			else:
				logscale = False
		except (ValueError, MultiValueDictKeyError) as e:
			pass
		try:
			sta = request.GET['sta']
			if 'AM.R6A3B.00.EHZ' == sta:
				r6a3b = ' selected'
			if 'AM.RCB43.00.SHZ' == sta:
				rcb43 = ' selected'
			if 'AM.R35E7.00.SHZ' == sta:
				r4989 = ' selected'
			if 'AM.R4989.00.EHZ' == sta:
				r35e7z = ' selected'
			if 'AM.ORNO.00.HHZ' == sta:
				orno = ' selected'
		except (ValueError, MultiValueDictKeyError) as e:
			sta = False
		try:
			filtmin = float(request.GET['filtmin'])
			filtmax = float(request.GET['filtmax'])
			if filtmax < filtmin:
				tmp = filtmin
				filtmin = filtmax
				filtmax = tmp
			if filtmax >= 25:
				filtmax = 25
			if filtmax < 0.1:
				filtmax = 0.1
			if filtmin <= 0:
				filtmin = 0
			if filtmin > 24.9:
				filtmin = 24.9
		except (ValueError, MultiValueDictKeyError) as e:
			filtmin = 0.7
			filtmax = 2
	except ValueError as e:
		status = e
	except MultiValueDictKeyError as e:
		status = e

	if userstart and userdur:
		initialdur = userdur
		start = UTCDateTime(start)
		try:
			dur = timedelta(0, userdur)
			end = start + dur
			procimg = processor(sta, start, end, dbscale, filtmin, filtmax)
		except ValueError as e:
			pass
	elif userstart:
		try:
			end = start + timedelta(0, 60)
			procimg = processor(sta, start, end, dbscale, filtmin, filtmax)
		except:
			pass
	else:
		pass

	if procimg['spec']:
		SPEC = procimg['spec']
		AVAIL = procimg['avail']
		HELI = procimg['heli']
		SPECBP = procimg['specbp']
		HELIBP = procimg['helibp']
		filtmin = procimg['filtmin']
		filtmax = procimg['filtmax']
	elif procimg['heli']:
		HELI = procimg['heli']

	context = {
		'sta': sta,
		'r4989': r4989,
		'r6a3b': r6a3b,
		'rcb43': rcb43,
		'r35e7': r35e7,
		'orno': orno,
		'filtmin': filtmin,
		'filtmax': filtmax,
		'status': status,
		'form': ShakeForm,
		'start': start,
		'dur': dur,
		'end': end,
		'avail': AVAIL,
		'heliimg': HELI,
		'specimg': SPEC,
		'helibpimg': HELIBP,
		'specbpimg': SPECBP,
		'initialtime': initialtime,
		'initialdur': initialdur,
		'initialdbscale': initialdbscale,
		'time': timezone.now(),
		'page': 'Shakedown - The Seismic Data Archive Browser',
	}
	return render(request, 'shake/shakedown.html', context)