LALBurst 2.0.7.1-eeff03c
lalburst_power_plot_binjtf.py
Go to the documentation of this file.
1##python
2#
3# Copyright (C) 2007 Kipp Cannon
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#
21# =============================================================================
22#
23# Preamble
24#
25# =============================================================================
26#
27
28
29import math
30from matplotlib import cm, colors, collections
31import numpy
32from optparse import OptionParser
33import sqlite3
34import sys
35
36
37from lalburst import git_version
38from lalburst import SnglBurstUtils
39
40
41__author__ = "Kipp Cannon <kipp.cannon@ligo.org>"
42__version__ = "git id %s" % git_version.id
43__date__ = git_version.date
44
45
46#
47# =============================================================================
48#
49# Command Line
50#
51# =============================================================================
52#
53
54
56 parser = OptionParser(
57 version = "Name: %%prog\n%s" % git_version.verbose_msg
58 )
59 parser.add_option("-b", "--base", metavar = "base", default = "plotbinjtf_", help = "set the prefix for output filenames (default = plotbinj_)")
60 parser.add_option("-f", "--format", metavar = "format", default = "png", help = "set the output image format (default = png)")
61 parser.add_option("-v", "--verbose", action = "store_true", help = "be verbose")
62 options, filenames = parser.parse_args()
63
64 return options, (filenames or [None])
65
66options, filenames = parse_command_line()
67
68
69#
70# =============================================================================
71#
72# Time-Frequency Plane
73#
74# =============================================================================
75#
76
77
78def time_freq_plot(database, instrument, sim):
79 fig = SnglBurstUtils.figure.Figure()
80 SnglBurstUtils.FigureCanvas(fig)
81 # 6.5" wide, golden ratio high
82 fig.set_size_inches(6.5, 6.5 / ((1 + math.sqrt(5)) / 2))
83
84 #
85 # top plot --- triggers that matched injection
86 #
87
88 t_sim = sim.time_at_instrument(instrument)
89
90 axes = fig.add_subplot(211)
91 axes.grid(True)
92 #axes.set_xlabel("$t - t_{\\mathrm{injection}}$ (s)")
93 axes.set_ylabel("$f - f_{\\mathrm{injection}}$ (Hz)")
94 axes.set_title("%s Triggers Matching %g Hz Injection at GPS %s" % (instrument, sim.frequency, t_sim))
95
96 xmin = xmax = 0.0
97 ymin = ymax = 0.0
98 verts = []
99 colours = []
100 peakx = []
101 peaky = []
102 match_ids = []
103 # find triggers from the desired instrument that are coincident
104 # with the injection, and iterate over them in order from least to
105 # most confident
106 for burst in map(database.sngl_burst_table.row_from_cols, database.connection.cursor().execute("""
107SELECT sngl_burst.* FROM
108 sngl_burst
109 JOIN coinc_event_map AS a ON (
110 sngl_burst.event_id == a.event_id
111 AND a.table_name == 'sngl_burst'
112 )
113 JOIN coinc_event_map AS b ON (
114 a.coinc_event_id == b.coinc_event_id
115 AND b.table_name == 'sim_burst'
116 )
117WHERE
118 sngl_burst.ifo == ?
119 AND b.event_id == ?
120ORDER BY
121 sngl_burst.confidence ASC
122 """, (instrument, sim.simulation_id))):
123 match_ids.append(burst.event_id)
124
125 # Add time-frequency tile to collection
126 tmin = float(burst.start - t_sim)
127 tmax = float(burst.start + burst.duration - t_sim)
128 fmin = burst.central_freq - burst.bandwidth / 2 - sim.frequency
129 fmax = burst.central_freq + burst.bandwidth / 2 - sim.frequency
130 verts.append(((tmin, fmin), (tmax, fmin), (tmax, fmax), (tmin, fmax)))
131 colours.append(burst.confidence)
132
133 try:
134 # draw most significant tile if there is one
135 tmin = float(burst.ms_start - t_sim)
136 tmax = float(burst.ms_start + burst.ms_duration - t_sim)
137 fmin = burst.ms_flow - sim.frequency
138 fmax = burst.ms_flow + burst.ms_bandwidth - sim.frequency
139 verts.append(((tmin, fmin), (tmax, fmin), (tmax, fmax), (tmin, fmax)))
140 colours.append(burst.ms_confidence)
141 except AttributeError:
142 pass
143
144 peakx.append(float(burst.peak - t_sim))
145 try:
146 # use peak_frequency col if it exists
147 peaky.append(burst.peak_frequency - sim.frequency)
148 except AttributeError:
149 peaky.append(burst.central_freq - sim.frequency)
150
151 # update bounding box
152 tmin = float(burst.start - t_sim)
153 tmax = float(burst.start + burst.duration - t_sim)
154 fmin = burst.central_freq - burst.bandwidth / 2 - sim.frequency
155 fmax = burst.central_freq + burst.bandwidth / 2 - sim.frequency
156 xmin = min(xmin, tmin)
157 xmax = max(xmax, tmax)
158 ymin = min(ymin, fmin)
159 ymax = max(ymax, fmax)
160
161 polys = collections.PolyCollection(verts)
162 polys.set_array(numpy.array(colours))
163 polys.set_alpha(0.3)
164 polys.set_cmap(cm.get_cmap())
165 polys.set_norm(colors.normalize())
166 axes.add_collection(polys)
167
168 axes.plot(peakx, peaky, "k+")
169
170 axes.axvline(0, color = "k")
171 axes.axhline(0, color = "k")
172
173 # set the bounding box
174 axes.set_xlim([1.4 * xmin, 1.4 * xmax])
175 axes.set_ylim([1.4 * ymin, 1.4 * ymax])
176
177 #
178 # bottom plot --- triggers near injection
179 #
180
181 axes = fig.add_subplot(212)
182 axes.grid(True)
183 axes.set_xlabel("$t - t_{\\mathrm{injection}}$ (s)")
184 axes.set_ylabel("$f - f_{\\mathrm{injection}}$ (Hz)")
185
186 xmin = xmax = 0.0
187 ymin = ymax = 0.0
188 verts = []
189 colours = []
190 edgecolours = []
191 peakx = []
192 peaky = []
193 # find triggers from the desired instrument that are near the
194 # injection, and iterate over them in order from least to most
195 # confident
196 for burst in map(database.sngl_burst_table.row_from_cols, database.connection.cursor().execute("""
197SELECT * FROM
198 sngl_burst
199WHERE
200 ifo == ?
201 AND start_time BETWEEN ? AND ?
202 AND central_freq BETWEEN ? AND ?
203ORDER BY
204 sngl_burst.confidence ASC
205 """, (instrument, int(t_sim - 2), int(t_sim + 2), sim.frequency - 300, sim.frequency + 300))):
206 # Add time-frequency tile to collection
207 tmin = float(burst.start - t_sim)
208 tmax = float(burst.start + burst.duration - t_sim)
209 fmin = burst.central_freq - burst.bandwidth / 2 - sim.frequency
210 fmax = burst.central_freq + burst.bandwidth / 2 - sim.frequency
211 verts.append(((tmin, fmin), (tmax, fmin), (tmax, fmax), (tmin, fmax)))
212 colours.append(burst.confidence)
213 if burst.event_id in match_ids:
214 edgecolours.append("g")
215 else:
216 edgecolours.append("k")
217
218 peakx.append(float(burst.peak - t_sim))
219 try:
220 # use peak_frequency col if it exists
221 peaky.append(burst.peak_frequency - sim.frequency)
222 except:
223 peaky.append(burst.central_freq - sim.frequency)
224
225 # update bounding box
226 xmin = min(xmin, tmin)
227 xmax = max(xmax, tmax)
228 ymin = min(ymin, fmin)
229 ymax = max(ymax, fmax)
230
231 polys = collections.PolyCollection(verts, edgecolors = edgecolours)
232 polys.set_array(numpy.array(colours))
233 polys.set_alpha(0.3)
234 polys.set_cmap(cm.get_cmap())
235 polys.set_norm(colors.normalize())
236 axes.add_collection(polys)
237
238 axes.plot(peakx, peaky, "k+")
239
240 axes.axvline(0, color = "k")
241 axes.axhline(0, color = "k")
242
243 # set the bounding box
244 axes.set_xlim([1.4 * xmin, 1.4 * xmax])
245 axes.set_ylim([1.4 * ymin, 1.4 * ymax])
246
247
248 return fig
249
250
251#
252# =============================================================================
253#
254# Plot
255#
256# =============================================================================
257#
258
259
260def found_injections(contents, instrument):
261 for values in contents.connection.cursor().execute("""
262SELECT
263 *
264FROM
265 sim_burst
266WHERE
267 EXISTS (
268 -- Find a link through the coinc_event_map table to a row
269 -- in the sngl_burst table with the correct ifo value.
270 SELECT
271 *
272 FROM
273 coinc_event_map AS a
274 JOIN coinc_event_map AS b ON (
275 a.coinc_event_id == b.coinc_event_id
276 )
277 JOIN sngl_burst ON (
278 b.table_name == 'sngl_burst'
279 AND b.event_id == sngl_burst.event_id
280 )
281 WHERE
282 a.table_name == 'sim_burst'
283 AND a.event_id == sim_burst.simulation_id
284 AND sngl_burst.ifo == ?
285 )
286 """, (instrument,)):
287 yield contents.sim_burst_table.row_from_cols(values)
288
289
290for n, filename in enumerate(filenames):
291 if options.verbose:
292 print("%d/%d: %s" % (n + 1, len(filenames), filename), file=sys.stderr)
293 database = SnglBurstUtils.CoincDatabase(sqlite3.connect(filename), "lalapps_power")
294 if options.verbose:
295 SnglBurstUtils.summarize_coinc_database(database)
296 for instrument in database.instruments:
297 for sim in found_injections(database, instrument):
298 plotname = "%s%d_%s.%s" % (options.base, sim.time_at_instrument(instrument).seconds, instrument, options.format)
299 if options.verbose:
300 print("--> %s" % plotname, file=sys.stderr)
301 time_freq_plot(database, instrument, sim).savefig(plotname)
302 database.connection.close()
static double max(double a, double b)
Definition: EPFilters.c:43
static double min(double a, double b)
Definition: EPFilters.c:42
def found_injections(contents, instrument)
def time_freq_plot(database, instrument, sim)