#!/usr/bin/env python
#
# Copyright (C) 2011  Chad Hanna
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

## @file

## @package gstlalcbcnode
# This program will monitor the output of a single job in the gstlal inspiral
# low latency analysis; See gstlal_llcbcnode for help and usage.
#
# ## USAGE:
# This program is never meant to be executed by a user, but rather on a
# webserver via a url such as:
# 
#               https://ldas-jobs.ligo.caltech.edu/~gstlalcbc/cgi-bin/gstlal_llcbcnode?dir=/path/to/analysis/dir/&id=<jobids>&url=/path/to/likelihood.xml&ifos=<IFOS>
#
# e.g.,
#
#               https://ldas-jobs.ligo.caltech.edu/~gstlalcbc/cgi-bin/gstlal_llcbcnode?dir=/mnt/qfs3/gstlalcbc/engineering/5/bns_trigs_40Hz&id=0009,0009&url=/mnt/qfs3/gstlalcbc/engineering/5/bns_trigs_40Hz/0009_likelihood.xml&ifos=H1,L1,V1
#
#
# ## Interpretation of the output page
#
# ### Trigger stats
#
# \image html gstlal_llcbcnode01.png
#
# - The leftmost plot is trigger latency vs time.  It should be flat. If it is
# rising as a function of time that indicates that the job may be falling
# behind.  Occasional spikes are expected 
#
# - The next plot is a trigger latency histogram over the entire duration of
# the run.
#
# - The next plot is a SNR vs time. It should be relatively flat and below 10
# for well behaved noise.  An occasional spike might be caused from a signal or
# a glitch, but long term features indicate poor data quality
#
# - The rightmost plot is the maximum RAM usage history. It can only ever go
# up, but it is a problem if it nears the maximum RAM available on the machine.
#
# ### Live time
#
# \image html gstlal_llcbcnode02.png
#
# These per IFO pie charts indicate time when the detectors were on (white) off (gray) and times when the data was missing (MIA) blue.  The blue fraction should be << 1%
#
# ### PSDs
#
# \image html gstlal_llcbcnode03.png
#
# These represent the instantaneous PSD estimates of the running job.  The horizon distance is also computed.
#
# ### SNR / Chi-squared stats
#
# \image html gstlal_llcbcnode04.png
#
# These represent the instantaneous, cumulative SNR/chi-squared statistics for the job as well as the likelihood ranking plot.
#


import sys
import cgi
import cgitb
import os
os.environ["MPLCONFIGDIR"] = "/tmp"
import time
import urlparse

from gstlal import llweb
from gstlal import plotpsd
from gstlal import plotfar

cgitb.enable()

# Header
print >>sys.stdout, 'Cache-Control: no-cache, must-revalidate'
print >>sys.stdout, 'Expires: Mon, 26 Jul 1997 05:00:00 GMT'
print >>sys.stdout, 'Content-type: text/html\r\n'


form = cgi.parse()
web = llweb.GstlalWebSummary(form = form)

print """
<html>
<head>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE">
<meta http-equiv="refresh" content="300">
<title>GstLAL CBC</title>
"""

print llweb.css

print """
<div class=topbox> 
	<table>
	<tr><th rowspan=2><img width=100px src="http://www.lsc-group.phys.uwm.edu/cgit/gstlal/plain/gstlal/doc/gstlal.png"></th><th>Nodes</th><th>IFOs</th><th>GPS</th><th>Date</th><th>Status</th></tr>
	<tr><td>%s</td><td>%s</td><td>%d</td><td>%s</td><td>%s</td></tr>
	</table>
<hr>
</div>
<div class="tabs">
""" % (",".join(web.registry.keys()), "".join(sorted(web.ifos)), int(llweb.now()), time.strftime("%a, %d %b %Y %H:%M:%S %Z", time.localtime()), web.status()[1])

cnt = 0
for (label, plot) in(
	("PSDs", web.psdplot()), 
	("Live Time", web.livetime_pie()), 
	("SNR/chi Noise", web.snrchiplot("background_pdf")), 
	("SNR/chi Signal", web.snrchiplot("injection_pdf")), 
	("SNR/chi LR", web.snrchiplot("LR")),
	("Joint SNR", web.jointsnrplot()),
	("Rates", web.rateplot()),
	("Latency history", web.plothistory("latency_history", ylabel = "Latency (s)", xlabel = "Time since last trigger (s)")),
	("SNR history", web.plothistory('snr_history', ylabel = "SNR", xlabel = "Time since last trigger (s)")),
	("Segment History", web.plotcumulativesegments()),
	):
	print """
<div class=tab>
	<input type="radio" id="tab-%d" name="tab-group-1">
	<label for="tab-%d">%s</label>
	<div class="content">%s</div>
</div>
	""" % (cnt, cnt, label, plot)
	cnt+=1
try:
	print """
<div class=tab>
        <input type="radio" id="tab-%d" name="tab-group-1">
        <label for="tab-%d">%s</label>
        <div class="content">%s</div>
</div>
        """ % (cnt, cnt, "likelihood CCDF", web.plotccdf())
        cnt+=1
except ValueError:
	print """
<div class=tab>
        <input type="radio" id="tab-%d" name="tab-group-1">
        <label for="tab-%d">%s</label>
        <div class="content">Not enough counts to generate likelihood ccdf</div>
</div>
        """ % (cnt, cnt, "likelihood CCDF")
        cnt+=1
	

print """
</div>
</html>
</body>	
"""
