#! /usr/bin/env python

import numpy as np
from obspy.core import UTCDateTime, read
from obspy.arclink import Client #ArcLink
from MouseTrap import *

# constants
t_before = 120 # records start `t_before` seconds before the event
t_after = 300 # records end `t_after` seconds after the event

t = UTCDateTime('2013-12-12 10:34:21')
net = 'CH'; sta = 'VANNI'; loc=''; channels='HH*'

# download data
try:
	client = Client(host="arclink.ethz.ch", user="MouseTrap example 2 (http://geo.mff.cuni.cz/~vackar/mouse/)")
	st = client.getWaveform(net, sta, loc, channels, t-t_before, t + t_after)
except:
	print('Downloading waveform unsuccessful.')
	exit()
if (st.__len__() != 3):
	print('Gap in data.')
	exit()

# download poles and zeros
try:
	paz = client.getPAZ(net, sta, loc, st[0].stats.channel, t)
except:
	print('Downloading poles-and-zeros unsuccessful.')
	exit()

# demean, integrate, check signal-to-noise ratio
error = PrepareRecord(st, t_before)
if error:
	print ('    %s' % error)
	exit()

# create synthetic mouse
length = max(len(st[0]), len(st[1]), len(st[2]))
dt = st[0].stats.delta
mouse = mouse()
mouse.create(paz, length*2, dt, length*dt, 1)

# fit waveform by synthetic mouse
mouse.fit_3D(st, t_min=105, t_max=210)

# plot the fit
mouse.plot(st, outfile='VANNI.png', xmax=300, ylabel='raw displacement')

if mouse.exist(t_before):
	print '=== MOUSE DETECTED ==='
	print 'time of onset:   %6.1f s' % mouse.onset
	print 'amplitude:   %10.2e m s^-2' % mouse.amplitude
	print 'phi:             %6.1f deg' % (mouse.phi*180./np.pi)
	print 'theta:           %6.1f deg' % (mouse.theta*180./np.pi)
	print 'fit:            %7.2f' % mouse.fit
else:
	print '=== no mouse detected ==='