3 # Copyright (C) 2012--2016 Kipp Cannon, Chad Hanna, Drew Keppel, Cody Messick
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.
23 from matplotlib
import figure
24 from matplotlib.backends.backend_agg
import FigureCanvasAgg as FigureCanvas
25 matplotlib.rcParams.update({
27 "axes.titlesize": 10.0,
28 "axes.labelsize": 10.0,
29 "xtick.labelsize": 10.0,
30 "ytick.labelsize": 10.0,
31 "legend.fontsize": 10.0,
36 from optparse
import OptionParser
39 import urllib.parse as urlparse
41 from glue.ligolw
import ligolw
42 from glue.ligolw
import lsctables
43 from glue.ligolw
import array as ligolw_array
44 from glue.ligolw
import param as ligolw_param
45 from glue.ligolw
import utils as ligolw_utils
46 from gstlal
import inspiral
47 from gstlal
import lvalert_helper
48 from gstlal
import svd_bank
49 from lal
import series as lalseries
50 from ligo.gracedb
import rest as gracedb
59 class ligolwcontenthandler(ligolw.LIGOLWContentHandler):
65 def parse_command_line():
66 parser = OptionParser()
68 parser.add_option(
"--gracedb-service-url", metavar =
"URL", default = gracedb.DEFAULT_SERVICE_URL, help =
"GraceDb service url to upload to (default: %s)" % gracedb.DEFAULT_SERVICE_URL)
69 parser.add_option(
"--verbose", action =
"store_true", help =
"Be verbose.")
70 parser.add_option(
"--output-path", metavar =
"PATH", help =
"Write local copies of the plots to this directory (default = dont).")
71 parser.add_option(
"--no-upload", action =
"store_true", help =
"Disable upload of plots to gracedb, e.g., for testing new plots.")
73 options, gid_list = parser.parse_args()
77 # FIXME: lvalert_listen doesn
"t allow command-line
78 # options, enable logging for online analysis
79 options.verbose = True
80 logging.basicConfig(format = "%(asctime)s:%(message)s
", level = logging.INFO)
82 lvalert_data = json.loads(sys.stdin.read())
83 logging.info("%(alert_type)s-type alert for event %(uid)s
" % lvalert_data)
84 logging.info("lvalert data: %s
" % repr(lvalert_data))
85 if "filename
" in lvalert_data["data
"]:
86 filename = path.split(urlparse.urlparse(lvalert_data["data
"]["filename
"]).path)[-1]
87 if filename not in (u"psd.xml.gz
",):
88 logging.info("filename is not
'psd.xml.gz'. skipping
")
90 gid_list = [str(lvalert_data["uid
"])]
92 logging.info("json key filename not in lvalert data, skipping
")
95 logging.basicConfig(format = "%(asctime)s:%(message)s
", level = logging.INFO)
98 logging.basicConfig(format = "%(asctime)s:%(message)s
")
100 if options.no_upload and options.output_path is None:
101 raise ValueError("--no-upload without setting --ouput-path disables all output
")
103 return options, gid_list
105 options, gid_list = parse_command_line()
107 gracedb_client = gracedb.GraceDb(options.gracedb_service_url)
112 # # Download and parse the coinc document for the time series and svd bank information
114 xmldoc = lvalert_helper.get_coinc_xmldoc(gracedb_client, gid)
115 #xmldoc = ligolw_utils.load_filename(coinc_xmldoc, contenthandler=ligolwcontenthandler)
117 # create two dicts keyed by event id: the first dict contains
118 # COMPLEX8TimeSeries which contain the snr time series, the second dict
119 # contains the template row
120 timeseries_ligolw_dict = dict((ligolw_param.get_pyvalue(elem, u"event_id
"), lalseries.parse_COMPLEX8TimeSeries(elem)) for elem in xmldoc.getElementsByTagName(ligolw.LIGO_LW.tagName) if elem.hasAttribute(u"Name
") and elem.Name == u"COMPLEX8TimeSeries
")
121 eventid_trigger_dict = dict((row.event_id, row) for row in lsctables.SnglInspiralTable.get_table(xmldoc))
123 # Parse the bank files
124 # NOTE This assumes --svd-bank will also be provided once in the ProcessParamsTable
125 banks = inspiral.parse_bank_files(inspiral.parse_svdbank_string([row.value for row in lsctables.ProcessParamsTable.get_table(xmldoc) if row.param == "--svd-bank
"].pop()), verbose=True)
129 # # Find the template (to retrieve the autocorrelation later)
132 for i, bank in enumerate(banks.values()[0]):
133 for j, row in enumerate(bank.sngl_inspiral_table):
134 # The templates should all have the same template_id, so just grab one
135 if row.Gamma0 == eventid_trigger_dict.values()[0].Gamma0:
139 if banknum is not None:
143 raise ValueError("The svd banks in the process params table do not contain the template the event was found with
")
147 # # Plot the time series and the expected snr
149 fig = figure.Figure()
153 for i, (eventid, complex8timeseries) in enumerate(timeseries_ligolw_dict.items()):
154 ifo = eventid_trigger_dict[eventid].ifo
155 autocorr_length = complex8timeseries.data.length
156 auto = banks[ifo][banknum].autocorrelation_bank[tmpltnum]
157 auto = numpy.concatenate([numpy.zeros(zero_pad), auto, numpy.zeros(zero_pad)])
158 complex_snr_timeseries = numpy.concatenate([numpy.zeros(zero_pad), complex8timeseries.data.data, numpy.zeros(zero_pad)])
159 time = numpy.linspace(float(complex8timeseries.epoch) - zero_pad * complex8timeseries.deltaT, float(complex8timeseries.epoch)+(autocorr_length+zero_pad-1)*complex8timeseries.deltaT, autocorr_length + zero_pad * 2)
161 peakoffset = numpy.argmin(abs(time - eventid_trigger_dict[eventid].end))
162 peakoffset_auto = numpy.argmax(auto.real)
163 phase = numpy.angle(complex_snr_timeseries[peakoffset])
164 snr = (complex_snr_timeseries * numpy.exp(-1.j * phase)).real
165 snrsigma = numpy.sqrt(2)
166 peaktime = time[peakoffset]
170 ax = fig.add_subplot(len(timeseries_ligolw_dict.items()),1,i+1)
171 ax.fill_between(time[int(peakoffset-(autocorr_length-1)/2):int(peakoffset+(autocorr_length+1)/2+1)], snr[int(peakoffset-(autocorr_length-1)/2):int(peakoffset+(autocorr_length+1)/2+1)]-snrsigma, snr[int(peakoffset-(autocorr_length-1)/2):int(peakoffset+(autocorr_length+1)/2+1)]+snrsigma, color="0.75
")
172 ax.plot(time[int(peakoffset-(autocorr_length-1)/2):int(peakoffset+(autocorr_length+1)/2+1)], snr[int(peakoffset-(autocorr_length-1)/2):int(peakoffset+(autocorr_length+1)/2+1)], "k
", label = r"$\mathrm{Measured}\,\rho(t)$
")
173 ax.plot(time[int(peakoffset-(autocorr_length-1)/2):int(peakoffset+(autocorr_length+1)/2+1)], auto.real[int(peakoffset_auto-(autocorr_length-1)/2):int(peakoffset_auto+(autocorr_length+1)/2+1)]*maxsnr, "b--
", label = r"$\mathrm{Scaled\,Autocorrelation}$
")
174 ax.set_ylabel(r"$\mathrm{%s}\,\rho(t)$
" % ifo)
175 ax.set_xlabel(r"$\mathrm{Time\,from\,%f}$
" % peaktime)
176 ax.legend(loc="best
")
180 filename = "%s_snrtimeseries.png
" % gid
182 if not options.no_upload:
183 lvalert_helper.upload_fig(fig, gracedb_client, gid, filename = filename, log_message = "SNR time series
", tagname = "background
")
185 if options.output_path is not None:
186 filename = path.join(options.output_path, filename)
187 logging.info("writing %s ...
" % filename)
188 fig.savefig(filename)