3 # Copyright (C) 2019-2020 Hiroaki Ohta
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.
21 from matplotlib
import pyplot
22 pyplot.style.use(
'classic')
23 matplotlib.rcParams.update({
"text.usetex": True})
24 pyplot.rc(
'font',**{
'family':
'serif',
'serif':[
'Computer Modern Roman']})
25 from matplotlib.backends.backend_pdf
import PdfPages
27 from optparse
import OptionParser
32 from lal
import iterutils
34 from lal.utils
import CacheEntry
35 from ligo.lw
import dbtables
36 from ligo.lw
import ligolw
37 from ligo.lw
import lsctables
38 from ligo.lw
import utils as ligolw_utils
39 from gstlal
import far
40 from gstlal
import imr_utils
41 from gstlal
import inspiral_pipe
42 from gstlal.plots
import util as plotutil
45 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
48 def parse_command_line():
49 parser = OptionParser(description = __doc__)
51 # FAR range and resolution
52 parser.add_option(
"--min-far", metavar =
"Hertz", default = 1.0e-6/lal.YRJUL_SI, type =
"float", help =
"Specify the minimum false-alarm rate in Hertz. Default is 1 per million years.") # one per million years is probably detection worthy
53 parser.add_option(
"--max-far", metavar =
"Hertz", default = 12.0/lal.YRJUL_SI, type =
"float", help =
"Specify the maximum false-alarm rate in Hertz. Default is 1 per month.") # one per month is possibly EM-followup worthy
56 parser.add_option(
"--injection-database", default = [], action =
"append", help =
"Name of database containing injection parameters and triggers (required if --check-vt is activated).")
57 parser.add_option(
"--injection-files", default = [], action =
"append", help =
"XML files containing injection list (required if --check-vt is not activated).")
58 parser.add_option(
"--instrument", action =
"append", help =
"Append to a list of instruments to create dist stats for. List must be whatever instruments you intend to analyze.")
59 parser.add_option(
"--lnlrcdf-cache", metavar =
"url", help =
"The urls of lnlrcdf_signal data (required).")
60 parser.add_option(
"--ranking-stat-pdf", metavar =
"filename", action =
"append", help =
"Load ranking statistic PDFs for the signal and noise models from this file (required). The file must include the zero-lag count data. This is typically in a file named \"post_marginalized_likelihood.xml.gz\". Can be given multiple times.")
61 parser.add_option(
"-c",
"--check-vt", action =
"store_true", help =
"Compare VT results (optional).")
64 parser.add_option(
"--output-dir", default =
"./", metavar =
"name", help =
"Select a directory to place output files.")
65 parser.add_option(
"-v",
"--verbose", action =
"store_true", help =
"Be verbose (optional).")
67 options, filenames = parser.parse_args()
69 required_options = (
"instrument",
"lnlrcdf_cache",
"ranking_stat_pdf")
71 required_options += (
"injection_database",)
72 options.injection_database.extend(filenames)
74 required_options += (
"injection_files",)
75 options.injection_files.extend(filenames)
77 missing_options = [option for option in required_options if not getattr(options, option)]
79 raise ValueError(
"%s must be set" %
", ".join(
"--%s" % option.replace(
"_",
"-") for option in missing_options))
81 urls = [CacheEntry(line).url.replace(
"file://localhost",
"") for line in open(options.lnlrcdf_cache)]
83 raise ValueError(
"no input documents")
91 mbins = [0.5, 2.0, 4.5, 45., 450]
98 options, urls = parse_command_line()
101 # Read caluculation data
104 print(
"reading calculation data")
106 injs, inj_files = [], []
109 for f in options.injection_database:
110 inj_file = f.split(
"-")[1].replace(
"ALL_LLOID_",
"")
111 inj_files.append(inj_file)
112 connection[inj_file] = sqlite3.connect(f)
113 injs += lsctables.SimInspiralTable.get_table(dbtables.get_xml(connection[inj_file]))
115 for injection_file in options.injection_files:
116 inj_files.append(inspiral_pipe.sim_tag_from_inj_file(injection_file))
117 injs += lsctables.SimInspiralTable.get_table(ligolw_utils.load_filename(injection_file, contenthandler = LIGOLWContentHandler, verbose = options.verbose))
119 distance_mchirps = [tup
for tup in map(imr_utils.sim_to_distance_chirp_mass_bins_function, injs)]
120 if min(list(zip(*distance_mchirps))[1]) < mbins[0]:
121 mbins[0] = min(list(zip(*distance_mchirps))[1])
122 if max(list(zip(*distance_mchirps))[1]) > mbins[-1]:
123 mbins[-1] = max(list(zip(*distance_mchirps))[1])
124 bins = rate.NDBins([rate.LinearBins(min(list(zip(*distance_mchirps))[0]), max(list(zip(*distance_mchirps))[0]), 200), rate.IrregularBins(mbins)])
127 total_injections = [tuple(((inj.distance, inj.mchirp),)) for inj in injs]
128 found_injections = []
131 with open(url, "rb") as f:
132 lnlrcdfsignals = pickle.load(f)
133 found_injections.extend(lnlrcdfsignals["lnlrcdf"])
135 assert (lnL_th == lnlrcdfsignals["lnL_th"]).all()
137 lnL_th = lnlrcdfsignals["lnL_th"]
139 assert len(total_injections) == len(found_injections), "There is a problem with %s. The number of injections analyzed dosen't match up."%(options.lnlrcdf_cache)
142 # scale lnL to false alarm rate
145 print(
"scaling lnL to FAR")
147 rankingstatpdf = far.marginalize_pdf_urls(options.ranking_stat_pdf, "RankingStatPDF", verbose = options.verbose)
148 fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
149 fars = np.array([fapfar.far_from_rank(val) for val in lnL_th])
150 mask = (fars >= options.min_far*0.1) & (fars <= options.max_far*10)
151 livetime_yr = fapfar.livetime/lal.YRJUL_SI
154 # Compute sensitivity
157 print(
"computing sensitivity")
159 vols_lo_calc, vols_calc, vols_hi_calc = [], [], []
160 for k, far in enumerate(fars):
163 eff_lo, eff, eff_hi = imr_utils.compute_search_efficiency_in_bins(found_injections, total_injections, bins, sim_to_bins_function = lambda sim: sim[0], sim_to_found_weight_function = lambda sim: sim[1][k])
164 vol_lo = imr_utils.compute_search_volume(eff_lo)
165 vol_lo.array *= livetime_yr
166 vols_lo_calc.append(vol_lo)
168 vol = imr_utils.compute_search_volume(eff)
169 vol.array *= livetime_yr
170 vols_calc.append(vol)
172 vol_hi = imr_utils.compute_search_volume(eff_hi)
173 vol_hi.array *= livetime_yr
174 vols_hi_calc.append(vol_hi)
180 # Search injection data
183 print(
"Searching injection data")
185 found_injections = []
186 total_injections = []
187 for conn in connection.values():
188 #found, total, missed = imr_utils.get_min_far_inspiral_injections(conn, segments = zero_lag_segments, table_name="coinc_inspiral")
189 found, total, missed = imr_utils.get_min_far_inspiral_injections(conn, table_name=
"coinc_inspiral")
190 found_injections += found
191 total_injections += total
193 total_injections = imr_utils.symmetrize_sims(total_injections,
"mass1",
"mass2")
195 vols_lo_far, vols_far, vols_hi_far = [], [], []
197 found_by_far = [s
for f, s in found_injections
if f < far]
198 eff_lo, eff, eff_hi = imr_utils.compute_search_efficiency_in_bins(found_by_far, total_injections, bins, imr_utils.sim_to_distance_chirp_mass_bins_function)
199 vol_lo = imr_utils.compute_search_volume(eff_lo)
200 vol_lo.array *= livetime_yr
201 vols_lo_far.append(vol_lo)
203 vol = imr_utils.compute_search_volume(eff)
204 vol.array *= livetime_yr
207 vol_hi = imr_utils.compute_search_volume(eff_hi)
208 vol_hi.array *= livetime_yr
209 vols_hi_far.append(vol_hi)
212 # plot injection and calculation result
215 print(
"plotting calculation and injection results")
217 fig_far = pyplot.figure()
218 fig_far.set_size_inches((8., 8./plotutil.golden_ratio))
219 ax_far = fig_far.gca()
220 colors = ["b", "g" ,"r", "c"]
221 another_colors = ["darkblue", "darkgreen", "darkred", "darkcyan"]
223 mbins = rate.NDBins(bins[1:])
224 for n, (mlo, mmid, mhi) in enumerate(zip(iterutils.MultiIter(*mbins.lower()),
225 iterutils.MultiIter(*mbins.centres()),
226 iterutils.MultiIter(*mbins.upper()))):
228 label =
"Analytic Result : $M_{\mathrm{chirp}} \in [%.2f, %.2f] \,\mathrm{M}_\odot$" % (mlo[0], mhi[0])
229 center = np.array([v[mmid]
for v in vols_calc])
230 lo = np.array([v[mmid]
for v in vols_lo_calc])
231 hi = np.array([v[mmid]
for v in vols_hi_calc])
232 if (center == 0).all():
234 line, = ax_far.plot(fars, center, label=label, linewidth=2, color=another_colors[n])
235 ax_far.fill_between(fars, lo, hi, alpha=0.5, color=line.get_color())
239 label =
"Injection Result : $M_{\mathrm{chirp}} \in [%.2f, %.2f] \,\mathrm{M}_\odot$" % (mlo[0], mhi[0])
240 center = np.array([v[mmid]
for v in vols_far])
241 lo = np.array([v[mmid]
for v in vols_lo_far])
242 hi = np.array([v[mmid]
for v in vols_hi_far])
243 line, = ax_far.plot(fars, center, label=label, linewidth=2, color=colors[n])
244 ax_far.fill_between(fars, lo, hi, alpha=0.5, color=line.get_color())
246 if len(inj_files) > 1:
247 inj_files = [
"COMBINED"]
248 ax_far.set_xlabel(
"Combined FAR (Hz)")
249 ax_far.set_ylabel(r
"Volume $\times$ Time ($\mathrm{Mpc}^3 \mathrm{yr}$)")
250 ax_far.set_xscale(
"log")
251 ax_far.set_yscale(
"log")
252 ax_far.set_xlim(options.min_far, options.max_far)
253 ax_far.invert_xaxis()
254 ax_far.legend(loc=
'upper left', fontsize=8)
257 vol_tix = ax_far.get_yticks()
258 tx = ax_far.twinx() # map volume to distance
259 tx.set_yticks(vol_tix)
261 tx.set_ylim(ax_far.get_ylim())
262 tx.set_yticklabels([
"%.3g" % ((
float(k)/(4.*np.pi*livetime_yr/3.))**(1./3.))
for k in vol_tix])
263 tx.set_ylabel(
"Range (Mpc)")
264 ax_far.set_title(
"%s Observing (%.2f days)" % (observer, livetime_yr*lal.YRJUL_SI/lal.DAYJUL_SI))
265 fig_far.tight_layout(pad = .8)
267 pdf = PdfPages(
"%s/%s_%s-SEARCH_SENSITIVITY_%s_CHECK.pdf" %(options.output_dir,
"".join(sorted(options.instrument)), observer, inj_files[0]))
270 pdf = PdfPages("%s/%s_%s-SEARCH_SENSITIVITY_%s.pdf" %(options.output_dir, "".join(sorted(options.instrument)), observer, inj_files[0]))
273 pyplot.close(fig_far)