3 # Copyright (C) 2015 Chad Hanna
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.
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.
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.
25 import urllib.parse as urlparse
27 from optparse
import OptionParser
31 from matplotlib
import pyplot
32 import multiprocessing
36 matplotlib.rcParams.update({
38 "axes.titlesize": 10.0,
39 "axes.labelsize": 10.0,
40 "xtick.labelsize": 8.0,
41 "ytick.labelsize": 8.0,
44 "legend.fontsize": 8.0,
50 from lal
import LIGOTimeGPS
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
61 # define a content handler
62 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
64 lsctables.use_in(LIGOLWContentHandler)
68 return LIGOTimeGPS(lal.UTCToGPS(time.gmtime()), 0)
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)
75 options, gid_list = parser.parse_args()
78 raise ValueError(
"%d graceids specified, no more than one allowed" % len(gid_list))
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")
88 gid = str(lvalert_data[
"uid"])
95 options, graceid = parse_command_line()
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()
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)
109 print(
"sleeping for %d seconds" % sleep, file=sys.stderr)
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]
120 return (m1*m2)**.6 / (m1+m2)**.2
123 # FIXME assumes we are in the analysis directory
125 os.mkdir(
"followups")
129 wd =
"followups/%d" % gps
132 print(
"The directory for this event already exists, continuing anyway.")
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")]), []))
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)
144 for res in pool.map(parse, [c for c in ce if gps in c.segment and pattern.match(c.description)]):
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)
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:
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])
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")
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.')
193 pyplot.ylabel(
"$\chi^2$")
194 pyplot.xlabel(
"$\mathrm{%s \, SNR}$" % ifo)
195 pyplot.xlim(minsnr, maxsnr)
196 pyplot.ylim(minchisq, maxchisq)
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")