gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_lvalert_sngls_plotter
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2015 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 
20 import sys
21 import os
22 import re
23 import time
24 import logging
25 import urllib.parse as urlparse
26 import json
27 from optparse import OptionParser
28 import numpy
29 import matplotlib
30 matplotlib.use('Agg')
31 from matplotlib import pyplot
32 import multiprocessing
33 import glob
34 
35 
36 matplotlib.rcParams.update({
37  "font.size": 10.0,
38  "axes.titlesize": 10.0,
39  "axes.labelsize": 10.0,
40  "xtick.labelsize": 8.0,
41  "ytick.labelsize": 8.0,
42  "figure.dpi": 600,
43  "savefig.dpi": 600,
44  "legend.fontsize": 8.0,
45  "text.usetex": True
46 })
47 
48 
49 import lal
50 from lal import LIGOTimeGPS
51 from lal import rate
52 from lal.utils import CacheEntry
53 from ligo.lw import ligolw
54 from ligo.lw import table
55 from ligo.lw import lsctables
56 from ligo.lw import utils as ligolw_utils
57 from gstlal import lvalert_helper
58 from ligo.gracedb import rest as gracedb
59 
60 
61 # define a content handler
62 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
63  pass
64 lsctables.use_in(LIGOLWContentHandler)
65 
66 
67 def now():
68  return LIGOTimeGPS(lal.UTCToGPS(time.gmtime()), 0)
69 
70 
71 def parse_command_line():
72  parser = OptionParser()
73  parser.add_option("--gracedb-service-url", default="%s" % gracedb.DEFAULT_SERVICE_URL, help = "GraceDb service url to upload to (default: %s)" % gracedb.DEFAULT_SERVICE_URL)
74 
75  options, gid_list = parser.parse_args()
76 
77  if len(gid_list) > 1:
78  raise ValueError("%d graceids specified, no more than one allowed" % len(gid_list))
79 
80  if len(gid_list) == 0:
81  lvalert_data = json.loads(sys.stdin.read())
82  logging.info("%(alert_type)s-type alert for event %(uid)s" % lvalert_data)
83  logging.info("lvalert data: %s" % repr(lvalert_data))
84  filename = os.path.split(urlparse.urlparse(lvalert_data["file"]).path)[-1]
85  if filename not in (u"psd.xml.gz",):
86  logging.info("filename is not 'psd.xml.gz'. skipping")
87  sys.exit()
88  gid = str(lvalert_data["uid"])
89  else:
90  gid = gid_list[0]
91 
92  return options, gid
93 
94 
95 options, graceid = parse_command_line()
96 
97 
98 # Connect to gracedb and extract the coinc document
99 gracedb_client = gracedb.GraceDb(service_url = options.gracedb_service_url)
100 coinc_xmldoc = lvalert_helper.get_coinc_xmldoc(gracedb_client, graceid)
101 coinc_inspiral, = lsctables.CoincInspiralTable.get_table(coinc_xmldoc)
102 gps = coinc_inspiral.get_end()
103 
104 
105 # FIXME there must be a better way to do this
106 # If the event is not older than five hours, wait till it is.
107 sleep = 3600 * 5 - abs(now() - gps)
108 if sleep > 0:
109  print("sleeping for %d seconds" % sleep, file=sys.stderr)
110  time.sleep(sleep)
111 
112 
113 def parse(c, gps = gps):
114  xmldoc = ligolw_utils.load_filename(c.path, contenthandler = LIGOLWContentHandler, verbose = True)
115  sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
116  return [row for row in sngl_inspiral_table if row.end < gps + 600 and row.end >= gps - 600]
117 
118 
119 def mchirp(m1,m2):
120  return (m1*m2)**.6 / (m1+m2)**.2
121 
122 
123 # FIXME assumes we are in the analysis directory
124 try:
125  os.mkdir("followups")
126 except OSError:
127  pass
128 try:
129  wd = "followups/%d" % gps
130  os.mkdir(wd)
131 except OSError:
132  print("The directory for this event already exists, continuing anyway.")
133 
134 
135 # FIXME hardcodes gps digits to 5 to match current
136 ce = map(CacheEntry.from_T050017, sum((glob.glob(pattern) for pattern in [os.path.join(str(gps)[:5],"*.xml.gz"), os.path.join(str(gps - 100000)[:5],"*.xml.gz"), os.path.join(str(gps + 100000)[:5],"*.xml.gz")]), []))
137 
138 
139 # Parse the files in many threads
140 # FIXME don't hard code this regex
141 pattern = re.compile("0[0-9]{3}_LLOID$")
142 pool = multiprocessing.Pool(8)
143 sngl = []
144 for res in pool.map(parse, [c for c in ce if gps in c.segment and pattern.match(c.description)]):
145  sngl.extend(res)
146 
147 
148 mchirps = numpy.array([mchirp(r.mass1, r.mass2) for r in sngl])
149 snrs = [r.snr for r in sngl]
150 chisqs = [r.chisq for r in sngl]
151 maxchisq, minchisq = max(chisqs), min(chisqs)
152 maxsnr, minsnr = max(snrs), min(snrs)
153 maxmchirp, minmchirp = max(mchirps), min(mchirps)
154 
155 
156 # FIXME don't hardocde
157 # Get various data by IFO
158 times, snrs, mchirps, chisqs, ba = {}, {}, {}, {}, {}
159 for n,ifo in enumerate(["H1", "L1"]):
160  times[ifo] = numpy.array([float(r.end - gps) for r in sngl if r.ifo == ifo])
161  snrs[ifo] = numpy.array([r.snr for r in sngl if r.ifo == ifo])
162  chisqs[ifo] = numpy.array([r.chisq for r in sngl if r.ifo == ifo])
163  mchirps[ifo] = numpy.array([mchirp(r.mass1, r.mass2) for r in sngl if r.ifo == ifo])
164  ba[ifo] = rate.BinnedArray(rate.NDBins((rate.LinearBins(-600,600,401), rate.LogarithmicBins(minmchirp, maxmchirp, 100))))
165  ba[ifo].array[:] = 4.0
166  for t,s,m in zip(times[ifo], snrs[ifo], mchirps[ifo]):
167  if ba[ifo][t, m] < s:
168  ba[ifo][t, m] = s
169 
170 
171 # SNR heatmap
172 fig = pyplot.figure(figsize=(9,3.0))
173 for n, ifo in enumerate(["H1", "L1"]):
174  axes = pyplot.subplot(2,1,n+1)
175  pyplot.pcolormesh(ba[ifo].centres()[0], ba[ifo].centres()[1], ba[ifo].array.T, cmap='coolwarm', norm=matplotlib.colors.LogNorm(vmin=4, vmax=maxsnr))
176  cb = pyplot.colorbar()
177  cb.set_label("$\mathrm{SNR}$")
178  axes.set_yscale('log')
179  pyplot.ylim([minmchirp, maxmchirp])
180  if n==1:
181  pyplot.xlabel("$\mathrm{Time \, since \, %d}$" % int(gps))
182  pyplot.ylabel("$\mathrm{%s} \, \mathcal{M}$ $(M_{\odot})$" % ifo)
183 pyplot.minorticks_on()
184 lvalert_helper.upload_fig(fig, gracedb_client, graceid, filename = "snrheatmap.png", log_message = "SNR heat map: Computed from single detector triggers plus/minus 600 seconds around the event", tagname = "background")
185 
186 
187 # chisq vs SNR
188 fig = pyplot.figure(figsize=(9, 4.0))
189 for n, ifo in enumerate(["H1", "L1"]):
190  axes = pyplot.subplot(1,2,n+1)
191  pyplot.loglog(snrs[ifo], chisqs[ifo], 'k.')
192  if n==0:
193  pyplot.ylabel("$\chi^2$")
194  pyplot.xlabel("$\mathrm{%s \, SNR}$" % ifo)
195  pyplot.xlim(minsnr, maxsnr)
196  pyplot.ylim(minchisq, maxchisq)
197  pyplot.grid()
198 pyplot.minorticks_on()
199 lvalert_helper.upload_fig(fig, gracedb_client, graceid, filename = "chisqvsSNR.png", log_message = "Chi-squared vs. SNR: Computed from single detector triggers plus/minus 600 seconds around the event", tagname = "background")