gstlal-inspiral  0.4.2
 All Classes Namespaces Files Functions Variables Pages
gstlal_llsnrhistory
1 #!/usr/bin/env python
2 #
3 # Copyright (C) 2011 Chad Hanna
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 2 of the License, or (at your
8 # option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 # Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 
19 import sys
20 import cgi
21 import cgitb
22 import os
23 os.environ["MPLCONFIGDIR"] = "/tmp"
24 import matplotlib
25 matplotlib.use('Agg')
26 import numpy
27 import matplotlib.pyplot as plt
28 import time
29 import StringIO
30 import base64
31 from urlparse import urlparse
32 cgitb.enable()
33 form = cgi.FieldStorage()
34 import pylab
35 from pylal import rate
36 import lal
37 
38 
39 def now():
40  return float(lal.UTCToGPS(time.gmtime()))
41 
42 def to_png_image():
43  f = StringIO.StringIO()
44  plt.savefig(f, format="png")
45  sys.stdout.write( "Content-type: image/png\r\n\r\n" + f.getvalue() )
46  f.close()
47 
48 def read_registry(dir, dataurl, ids):
49  nodedict = {}
50  for id in ids:
51  url = '%s/%s%s' % (dir, id, dataurl)
52  try:
53  tmp = open(url,"r")
54  nodedict[id] = urlparse(tmp.readline()).netloc
55  tmp.close()
56  except IOError:
57  nodedict[id] = ""
58  return nodedict
59 
60 def setup_plot():
61  fig = plt.figure(figsize=(20,5),)
62  fig.patch.set_alpha(0.0)
63  h = fig.add_subplot(111, axisbg = 'k')
64  plt.subplots_adjust(left = .062, right = 0.98, bottom = 0.3)
65  return fig, h
66 
67 def finish_plot(ids, registry, ylim, title=''):
68  plt.grid(color=(0.1,0.4,0.5), linewidth=2)
69  ticks = ["%s : %s " % (id, registry[id]) for id in ids]
70  plt.xticks(numpy.arange(len(ids))+.3, ticks, rotation=90, fontsize = 10)
71  plt.xlim([0, len(ids)])
72  plt.ylim(ylim)
73  tickpoints = numpy.linspace(ylim[0], ylim[1], 8)
74  ticks = ["%.1e" % (10.**t,) for t in tickpoints]
75  plt.yticks(tickpoints, ticks, fontsize = 14)
76  plt.title(title, fontsize = 18)
77  to_png_image()
78 
79 
80 def get_ids(form):
81  idrange = [int(n) for n in form.getvalue("id").split(",")]
82  #FIXME relies on 4 digit ids
83  ids = ['%04d' % (job,) for job in range(idrange[0], idrange[1]+1)]
84  return ids
85 
86 if "dir" not in form:
87  raise ValueError("must specify dir")
88 if "id" not in form:
89  raise ValueError("must specify id")
90 
91 ids = get_ids(form)
92 directory = form.getvalue("dir")
93 start = form.getvalue("start")
94 stop = form.getvalue("stop")
95 reg = read_registry(form.getvalue("dir"), "_registry.txt", ids)
96 
97 time_now = now()
98 yaxis = []
99 
100 for i, id in enumerate(ids):
101  try:
102  fname = "%s/%s/%s.txt" % (directory, id, "snr_history")
103  yaxis.append(float(open("%s/%s/%s.txt" % (directory, id, "bank")).readline().split()[2]))
104 
105  except IOError as e:
106  print>>sys.stderr, "couldn't open ", fname
107 
108 yaxis = numpy.array(sorted(set(yaxis)))
109 
110 
111 if start is not None and stop is not None:
112  ba = rate.BinnedArray(rate.NDBins((rate.LinearBins(float(start) - time_now, float(stop) - time_now, 900), rate.IrregularBins(yaxis))))
113 else:
114  ba = rate.BinnedArray(rate.NDBins((rate.LinearBins(-4500,-900,900), rate.IrregularBins(yaxis))))
115 
116 print >>sys.stderr, min(yaxis), max(yaxis)
117 
118 window = rate.gaussian_window(10, 1, sigma = 3)
119 print >> sys.stderr, ba.array.shape
120 ba.array[:] = 1.
121 
122 for i, id in enumerate(ids):
123  try:
124  fname = "%s/%s/%s.txt" % (directory, id, "snr_history")
125  dur = float(open("%s/%s/%s.txt" % (directory, id, "bank")).readline().split()[2])
126  for line in open(fname):
127  thist, thissnr = line.split()
128  t = float(thist)-time_now
129  try:
130  if ba[t,dur] < thissnr:
131  ba[t,dur] = thissnr
132  except IndexError:
133  pass
134 
135  except IOError as e:
136  print>>sys.stderr, "couldn't open ", fname
137 
138 matplotlib.rcParams.update({"text.usetex": True})
139 
140 rate.filter_array(ba.array, window)
141 fig = pylab.figure(figsize=(20,4.0))
142 pylab.title('max $\\rho_c$ in coincidence')
143 pylab.xlabel("time since %d (s)" % (int(time_now),))
144 pylab.ylabel("$\mathcal{M} (M_\odot)$")
145 pylab.xlim([ba.centres()[0][0], ba.centres()[0][-1]])
146 pylab.ylim([ba.centres()[1][0], ba.centres()[1][-1]])
147 pylab.pcolormesh(ba.centres()[0], ba.centres()[1], ba.array.T, norm = matplotlib.colors.LogNorm())
148 pylab.colorbar()
149 to_png_image()