gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
imr_utils.py
1 # Copyright (C) 2012 Chad Hanna
2 #
3 # This program is free software; you can redistribute it and/or modify it
4 # under the terms of the GNU General Public License as published by the
5 # Free Software Foundation; either version 2 of the License, or (at your
6 # option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
11 # Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 
17 import sys
18 from ligo.lw import lsctables
19 from ligo.lw import dbtables
20 from ligo.lw import table
21 from lal import rate
22 from ligo import segments
23 from ligo.segments import utils as segmentsUtils
24 import numpy
25 import math
26 import copy
27 from ligo.lw.utils import search_summary as ligolw_search_summary
28 from ligo.lw.utils import segments as ligolw_segments
29 from ligo.lw.utils import process
30 from lalsimulation import SimInspiralTaylorF2ReducedSpinComputeChi, SimIMRPhenomBComputeChi
31 
32 import sqlite3
33 
34 def get_thinca_zero_lag_segments(connection, program_name = "thinca"):
35  """
36  Return the thinca rings from the database at the given connection.
37  The rings are returned as a coalesced ligo.segments.segmentlistdict
38  indexed by instrument.
39 
40  Example:
41 
42  >>> seglists = get_thinca_zero_lag_segments(connection)
43  >>> print(seglists.keys())
44  ['H1', 'L1']
45 
46  This function is most useful if only zero-lag segments are desired
47  because it allows for more convenient manipulation of the segment lists
48  using the methods in ligo.segments. If information about background
49  segments or the original ring boundaries is desired the data returned by
50  get_thinca_rings_by_available_instruments() is required.
51  """
52  # extract the raw rings indexed by instrument
53 
54  xmldoc = dbtables.get_xml(connection)
55  seglists = ligolw_search_summary.segmentlistdict_fromsearchsummary(xmldoc, program_name)
56  xmldoc.unlink()
57 
58  # remove rings that are exact duplicates on the assumption that there are
59  # zero-lag and time-slide thinca jobs represented in the same document
60 
61  seglists = segments.segmentlistdict((key, segments.segmentlist(set(value))) for key, value in seglists.items())
62 
63  # coalesce the remaining segments making sure we don't loose livetime in
64  # the process
65 
66  durations_before = abs(seglists)
67  seglists.coalesce()
68  if abs(seglists) != durations_before:
69  raise ValueError("detected overlapping thinca rings")
70 
71  # done
72 
73  return seglists
74 
75 
76 def get_veto_segments(connection, name):
77  """
78  Return a coalesced ligo.segments.segmentlistdict object containing the
79  segments of the given name extracted from the database at the given
80  connection.
81  """
82  xmldoc = dbtables.get_xml(connection)
83  seglists = ligolw_segments.segmenttable_get_by_name(xmldoc, name).coalesce()
84  xmldoc.unlink()
85  return seglists
86 
87 
88 def allowed_analysis_table_names():
89  return (dbtables.lsctables.MultiBurstTable.tableName, dbtables.lsctables.CoincInspiralTable.tableName, dbtables.lsctables.CoincRingdownTable.tableName)
90 
91 
92 def make_sim_inspiral_row_from_columns_in_db(connection):
93  """
94  get the unique mapping of a sim inspiral row from columns in this
95  database
96  """
97  return lsctables.SimInspiralTable.get_table(dbtables.get_xml(connection)).row_from_cols
98 
99 
100 def time_within_segments(geocent_end_time, geocent_end_time_ns, zero_lag_segments = None):
101  """
102  Return True if injection was made in the given segmentlist, if no
103  segments just return True
104  """
105  if zero_lag_segments is None:
106  return True
107  else:
108  return lsctables.LIGOTimeGPS(geocent_end_time, geocent_end_time_ns) in zero_lag_segments
109 
110 
111 def get_min_far_inspiral_injections(connection, segments = None, table_name = "coinc_inspiral"):
112  """
113  This function returns the found injections from a database and the
114  minimum far associated with them as tuple of the form (far, sim). It also tells
115  you all of the injections that should have been injected. Subtracting the two
116  outputs should tell you the missed injections
117  """
118 
119  if table_name == dbtables.lsctables.CoincInspiralTable.tableName:
120  found_query = 'SELECT sim_inspiral.*, coinc_inspiral.combined_far FROM sim_inspiral JOIN coinc_event_map AS mapA ON mapA.event_id == sim_inspiral.simulation_id JOIN coinc_event_map AS mapB ON mapB.coinc_event_id == mapA.coinc_event_id JOIN coinc_inspiral ON coinc_inspiral.coinc_event_id == mapB.event_id JOIN coinc_event on coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id WHERE mapA.table_name = "sim_inspiral" AND mapB.table_name = "coinc_event" AND injection_in_segments(sim_inspiral.geocent_end_time, sim_inspiral.geocent_end_time_ns)'
121 
122  elif table_name == dbtables.lsctables.CoincRingdownTable.tableName:
123  found_query = 'SELECT sim_inspiral.*, coinc_ringdown.false_alarm_rate FROM sim_inspiral JOIN coinc_event_map AS mapA ON mapA.event_id == sim_inspiral.simulation_id JOIN coinc_event_map AS mapB ON mapB.coinc_event_id == mapA.coinc_event_id JOIN coinc_ringdown ON coinc_ringdown.coinc_event_id == mapB.event_id JOIN coinc_event on coinc_event.coinc_event_id == coinc_ringdown.coinc_event_id WHERE mapA.table_name = "sim_inspiral" AND mapB.table_name = "coinc_event" AND injection_in_segments(sim_inspiral.geocent_end_time, sim_inspiral.geocent_end_time_ns)'
124 
125  elif table_name == dbtables.lsctables.MultiBurstTable.tableName:
126  found_query = 'SELECT sim_inspiral.*, multi_burst.false_alarm_rate FROM sim_inspiral JOIN coinc_event_map AS mapA ON mapA.event_id == sim_inspiral.simulation_id JOIN coinc_event_map AS mapB ON mapB.coinc_event_id == mapA.coinc_event_id JOIN multi_burst ON multi_burst.coinc_event_id == mapB.event_id JOIN coinc_event on coinc_event.coinc_event_id == multi_burst.coinc_event_id WHERE mapA.table_name = "sim_inspiral" AND mapB.table_name = "coinc_event" AND injection_in_segments(sim_inspiral.geocent_end_time, sim_inspiral.geocent_end_time_ns)'
127 
128  else:
129  raise ValueError("table must be in " + " ".join(allowed_analysis_table_names()))
130 
131  def injection_was_made(end_time, end_time_ns, segments = segments):
132  return time_within_segments(end_time, end_time_ns, segments)
133 
134  # restrict the found injections to only be within certain segments
135  connection.create_function("injection_in_segments", 2, injection_was_made)
136 
137  # get the mapping of a record returned by the database to a sim
138  # inspiral row. Note that this is DB dependent potentially, so always
139  # do this!
140  make_sim_inspiral = make_sim_inspiral_row_from_columns_in_db(connection)
141 
142  found_injections = {}
143 
144  for values in connection.cursor().execute(found_query):
145  # all but the last column is used to build a sim inspiral object
146  sim = make_sim_inspiral(values[:-1])
147  far = values[-1]
148  # update with the minimum far seen until now
149  this_inj = found_injections.setdefault(sim.simulation_id, (far, sim))
150  if far < this_inj[0]:
151  found_injections[sim.simulation_id] = (far, sim)
152 
153  total_query = 'SELECT * FROM sim_inspiral WHERE injection_in_segments(geocent_end_time, geocent_end_time_ns)'
154 
155  total_injections = {}
156  # Missed injections start as a copy of the found injections
157  missed_injections = {}
158  for values in connection.cursor().execute(total_query):
159  sim = make_sim_inspiral(values)
160  total_injections[sim.simulation_id] = sim
161  missed_injections[sim.simulation_id] = sim
162 
163  # now actually remove the missed injections
164  for k in found_injections:
165  del missed_injections[k]
166 
167 
168  return found_injections.values(), total_injections.values(), missed_injections.values()
169 
170 
171 def get_max_snr_inspiral_injections(connection, segments = None, table_name = "coinc_inspiral"):
172  """
173  Like get_min_far_inspiral_injections but uses SNR to rank injections.
174  """
175 
176  if table_name == dbtables.lsctables.CoincInspiralTable.tableName:
177  found_query = 'SELECT sim_inspiral.*, coinc_inspiral.snr FROM sim_inspiral JOIN coinc_event_map AS mapA ON mapA.event_id == sim_inspiral.simulation_id JOIN coinc_event_map AS mapB ON mapB.coinc_event_id == mapA.coinc_event_id JOIN coinc_inspiral ON coinc_inspiral.coinc_event_id == mapB.event_id JOIN coinc_event on coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id WHERE mapA.table_name = "sim_inspiral" AND mapB.table_name = "coinc_event" AND injection_in_segments(sim_inspiral.geocent_end_time, sim_inspiral.geocent_end_time_ns)'
178 
179  elif table_name in allowed_analysis_table_names():
180  raise NotImplementedError("get_max_snr_inspiral_injections has not yet implemented querying against the table %s. Please consider submitting a patch. See get_min_far_inspiral_injections for how to construct your query." % table_name)
181  else:
182  raise ValueError("table must be in " + " ".join(allowed_analysis_table_names()))
183 
184 
185  def injection_was_made(end_time, end_time_ns, segments = segments):
186  return time_within_segments(end_time, end_time_ns, segments)
187 
188  # restrict the found injections to only be within certain segments
189  connection.create_function("injection_in_segments", 2, injection_was_made)
190 
191  # get the mapping of a record returned by the database to a sim
192  # inspiral row. Note that this is DB dependent potentially, so always
193  # do this!
194  make_sim_inspiral = make_sim_inspiral_row_from_columns_in_db(connection)
195 
196  found_injections = {}
197 
198  for values in connection.cursor().execute(found_query):
199  # all but the last column is used to build a sim inspiral object
200  sim = make_sim_inspiral(values[:-1])
201  snr = values[-1]
202  # update with the minimum far seen until now
203  this_inj = found_injections.setdefault(sim.simulation_id, (snr, sim))
204  if snr > this_inj[0]:
205  found_injections[sim.simulation_id] = (snr, sim)
206 
207  total_query = 'SELECT * FROM sim_inspiral WHERE injection_in_segments(geocent_end_time, geocent_end_time_ns)'
208 
209  total_injections = {}
210  # Missed injections start as a copy of the found injections
211  missed_injections = {}
212  for values in connection.cursor().execute(total_query):
213  sim = make_sim_inspiral(values)
214  total_injections[sim.simulation_id] = sim
215  missed_injections[sim.simulation_id] = sim
216 
217  # now actually remove the missed injections
218  for k in found_injections:
219  del missed_injections[k]
220 
221  return found_injections.values(), total_injections.values(), missed_injections.values()
222 
223 
224 def get_instruments_from_coinc_event_table(connection):
225  """
226  This function returns a list of the instruments analyzed according to the coinc_event_table
227  """
228  instruments = []
229  for ifos in connection.cursor().execute('SELECT DISTINCT(instruments) FROM coinc_event WHERE instruments!=""'):
230  # ignore null columns
231  if ifos[0]:
232  instruments.append(frozenset(lsctables.instrument_set_from_ifos(ifos[0])))
233  return instruments
234 
235 
236 def get_segments(connection, xmldoc, table_name, live_time_program, veto_segments_name = None, data_segments_name = "datasegments"):
237  segs = segments.segmentlistdict()
238 
239  if table_name == dbtables.lsctables.CoincInspiralTable.tableName:
240  if live_time_program == "gstlal_inspiral":
241  segs = ligolw_segments.segmenttable_get_by_name(xmldoc, data_segments_name).coalesce()
242  elif live_time_program == "thinca":
243  segs = get_thinca_zero_lag_segments(connection, program_name = live_time_program).coalesce()
244  else:
245  raise ValueError("for burst tables livetime program must be one of gstlal_inspiral, thinca")
246  if veto_segments_name is not None:
247  veto_segs = get_veto_segments(connection, veto_segments_name)
248  segs -= veto_segs
249  return segs
250  elif table_name == dbtables.lsctables.CoincRingdownTable.tableName:
251  segs = ligolw_search_summary.segmentlistdict_fromsearchsummary(xmldoc, live_time_program).coalesce()
252  if veto_segments_name is not None:
253  veto_segs = ligolw_segments.segmenttable_get_by_name(xmldoc, veto_segments_name).coalesce()
254  segs -= veto_segs
255  return segs
256  elif table_name == dbtables.lsctables.MultiBurstTable.tableName:
257  if live_time_program == "omega_to_coinc":
258  segs = ligolw_search_summary.segmentlistdict_fromsearchsummary(xmldoc, live_time_program).coalesce()
259  if veto_segments_name is not None:
260  veto_segs = ligolw_segments.segmenttable_get_by_name(xmldoc, veto_segments_name).coalesce()
261  segs -= veto_segs
262  elif live_time_program == "waveburst":
263  segs = get_thinca_zero_lag_segments(connection, program_name = live_time_program).coalesce()
264  if veto_segments_name is not None:
265  veto_segs = get_veto_segments(connection, veto_segments_name)
266  segs -= veto_segs
267  else:
268  raise ValueError("for burst tables livetime program must be one of omega_to_coinc, waveburst")
269  return segs
270  else:
271  raise ValueError("table must be in " + " ".join(allowed_analysis_table_names()))
272 
273 
274 def get_event_fars(connection, table_name, segments = None):
275  """
276  return the false alarm rate of the most rare zero-lag coinc by instruments
277  """
278 
279  def event_in_requested_segments(end_time, end_time_ns, segments = segments):
280  return time_within_segments(end_time, end_time_ns, segments)
281 
282  connection.create_function("event_in_requested_segments", 2, event_in_requested_segments)
283 
284  if table_name == dbtables.lsctables.CoincInspiralTable.tableName:
285  query = 'SELECT coinc_event.instruments, coinc_inspiral.combined_far AS combined_far, EXISTS(SELECT * FROM time_slide WHERE time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0) FROM coinc_inspiral JOIN coinc_event ON (coinc_inspiral.coinc_event_id == coinc_event.coinc_event_id) WHERE event_in_requested_segments(coinc_inspiral.end_time, coinc_inspiral.end_time_ns);'
286 
287  elif table_name == dbtables.lsctables.MultiBurstTable.tableName:
288  query = 'SELECT coinc_event.instruments, multi_burst.false_alarm_rate AS combined_far, EXISTS(SELECT * FROM time_slide WHERE time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0) FROM multi_burst JOIN coinc_event ON (multi_burst.coinc_event_id == coinc_event.coinc_event_id) WHERE event_in_requested_segments(multi_burst.peak_time, multi_burst.peak_time_ns);'
289 
290  elif table_name == dbtables.lsctables.CoincRingdownTable.tableName:
291  query = 'SELECT coinc_event.instruments, coinc_ringdown.false_alarm_rate AS combined_far, EXISTS(SELECT * FROM time_slide WHERE time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0) FROM coinc_ringdown JOIN coinc_event ON (coinc_ringdown.coinc_event_id == coinc_event.coinc_event_id) WHERE event_in_requested_segments(coinc_ringdown.start_time, coinc_ringdown.start_time_ns);'
292 
293  else:
294  raise ValueError("table must be in " + " ".join(allowed_analysis_table_names()))
295 
296  for inst, far, ts in connection.cursor().execute(query):
297  inst = frozenset(lsctables.instrument_set_from_ifos(inst))
298  yield (inst, far, ts)
299 
300 
301 def compute_search_efficiency_in_bins(found, total, ndbins, sim_to_bins_function = lambda sim: (sim.distance,), sim_to_found_weight_function = lambda sim: 1.):
302  """
303  This program creates the search efficiency in the provided ndbins. The
304  first dimension of ndbins must be the distance. You also must provide a
305  function that maps a sim inspiral row to the correct tuple to index the ndbins.
306  """
307 
308  num = rate.BinnedArray(ndbins)
309  den = rate.BinnedArray(ndbins)
310 
311  # increment the numerator with the found injections
312  for sim in found:
313  num[sim_to_bins_function(sim)] += sim_to_found_weight_function(sim)
314 
315  # increment the denominator with the total injections
316  for sim in total:
317  den[sim_to_bins_function(sim)] += 1.
318 
319  # sanity check
320  assert (num.array <= den.array).all(), "some bins have more found injections than were made"
321 
322  # regularize by setting empty bins to zero efficiency
323  # FIXME: the following was set for zero efficiency bins but it
324  # results in efficiency error bars that are too large at zero
325  # efficiencies. Replacing for now.
326  #den.array[numpy.logical_and(num.array == 0, den.array == 0)] = 1
327  den.array[num.array < 1e-35] = 1e35
328 
329  # pull out the efficiency array, it is the ratio
330  eff = rate.BinnedArray(rate.NDBins(ndbins), array = num.array / den.array)
331 
332  # compute binomial uncertainties in each bin
333  k = num.array
334  N = den.array
335  eff_lo_arr = ( N*(2*k + 1) - numpy.sqrt(4*N*k*(N - k) + N**2) ) / (2*N*(N + 1))
336  eff_hi_arr = ( N*(2*k + 1) + numpy.sqrt(4*N*k*(N - k) + N**2) ) / (2*N*(N + 1))
337 
338  eff_lo = rate.BinnedArray(rate.NDBins(ndbins), array = eff_lo_arr)
339  eff_hi = rate.BinnedArray(rate.NDBins(ndbins), array = eff_hi_arr)
340 
341  return eff_lo, eff, eff_hi
342 
343 
344 def compute_search_volume(eff):
345  """
346  Integrate efficiency to get search volume.
347  """
348  # get distance bins
349  ndbins = eff.bins
350  dx = ndbins[0].upper() - ndbins[0].lower()
351  r = ndbins[0].centres()
352 
353  # we have one less dimension on the output
354  vol = rate.BinnedArray(rate.NDBins(ndbins[1:]))
355 
356  # integrate efficiency to obtain volume
357  vol.array = numpy.trapz(eff.array.T * 4. * numpy.pi * r**2, r, dx)
358 
359  return vol
360 
361 
362 def guess_nd_bins(sims, bin_dict = {"distance": (200, rate.LinearBins)}):
363  """
364  Given a dictionary of bin counts and bin objects keyed by sim
365  attribute, come up with a sensible NDBins scheme
366  """
367  return rate.NDBins([bintup[1](min([getattr(sim, attr) for sim in sims]), max([getattr(sim, attr) for sim in sims]) + sys.float_info.min, bintup[0]) for attr, bintup in bin_dict.items()])
368 
369 
370 def guess_distance_mass1_mass2_bins_from_sims(sims, mass1bins = 11, mass2bins = 11, distbins = 200):
371  """
372  Given a list of the injections, guess at the mass1, mass2 and distance
373  bins.
374  """
375  return guess_nd_bins(sims, bin_dict = {"distance": (distbins, rate.LinearBins), "mass1": (mass1bins, rate.LinearBins), "mass2": (mass2bins, rate.LinearBins)})
376 
377 
378 def guess_distance_spin1z_spin2z_bins_from_sims(sims, spin1bins = 11, spin2bins = 11, distbins = 200):
379  """
380  Given a list of the injections, guess at the spin1, spin2 and distance
381  bins.
382  """
383  return guess_nd_bins(sims, bin_dict = {"distance": (distbins, rate.LinearBins), "spin1z": (spin1bins, rate.LinearBins), "spin2z": (spin2bins, rate.LinearBins)})
384 
385 
386 def guess_distance_effective_spin_parameter_bins_from_sims(sims, chibins = 11, distbins = 200):
387  """
388  Given a list of the injections, guess at the chi = (m1*s1z +
389  m2*s2z)/(m1+m2) and distance bins.
390  """
391  dist_chi_vals = map(sim_to_distance_effective_spin_parameter_bins_function, sims)
392 
393  distances = [tup[0] for tup in dist_chi_vals]
394  chis = [tup[1] for tup in dist_chi_vals]
395 
396  return rate.NDBins([rate.LinearBins(min(distances), max(distances), distbins), rate.LinearBins(min(chis), max(chis), chibins)])
397 
398 
399 def guess_distance_mass_ratio_bins_from_sims(sims, qbins = 11, distbins = 200):
400  """
401  Given a list of the injections, guess at the chi and distance
402  bins.
403  """
404  dist_mratio_vals = map(sim_to_distance_mass_ratio_bins_function, sims)
405 
406  distances = [tup[0] for tup in dist_mratio_vals]
407  mratios = [tup[1] for tup in dist_mratio_vals]
408 
409  return rate.NDBins([rate.LinearBins(min(distances), max(distances), distbins), rate.LinearBins(min(mratios), max(mratios), qbins)])
410 
411 
412 def guess_distance_chirp_mass_bins_from_sims(sims, mbins = 11, distbins = 200):
413  """
414  Given a list of the injections, guess at the chirp mass and distance
415  bins.
416  """
417  dist_mchirp_vals = map(sim_to_distance_chirp_mass_bins_function, sims)
418 
419  distances = [tup[0] for tup in dist_mchirp_vals]
420  mchirps = [tup[1] for tup in dist_mchirp_vals]
421 
422  return rate.NDBins([rate.LinearBins(min(distances), max(distances), distbins), rate.LinearBins(min(mchirps), max(mchirps), mbins)])
423 
424 
425 def guess_distance_total_mass_bins_from_sims(sims, nbins = 11, distbins = 200):
426  """
427  Given a list of the injections, guess at the mass1, mass2 and distance
428  bins. Floor and ceil will be used to round down to the nearest integers.
429  """
430 
431  total_lo = numpy.floor(min([sim.mass1 + sim.mass2 for sim in sims]))
432  total_hi = numpy.ceil(max([sim.mass1 + sim.mass2 for sim in sims]))
433  mindist = numpy.floor(min([sim.distance for sim in sims]))
434  maxdist = numpy.ceil(max([sim.distance for sim in sims]))
435 
436  return rate.NDBins((rate.LinearBins(mindist, maxdist, distbins), rate.LinearBins(total_lo, total_hi, nbins)))
437 
438 
439 def sim_to_distance_mass1_mass2_bins_function(sim):
440  """
441  create a function to map a sim to a distance, mass1, mass2 NDBins based object
442  """
443 
444  return (sim.distance, sim.mass1, sim.mass2)
445 
446 
447 def sim_to_distance_total_mass_bins_function(sim):
448  """
449  create a function to map a sim to a distance, total mass NDBins based object
450  """
451  return (sim.distance, sim.mass1 + sim.mass2)
452 
453 
454 def sim_to_distance_spin1z_spin2z_bins_function(sim):
455  """
456  create a function to map a sim to a distance, spin1z, spin2z NDBins based object
457  """
458 
459  return (sim.distance, sim.spin1z, sim.spin2z)
460 
461 
462 def sim_to_distance_effective_spin_parameter_bins_function(sim):
463  """
464  Map a sim_inspiral row to a distance, "chi" spin parameter
465  bin. For IMR waveforms, "chi" refers to the effective spin,
466 
467  chi = (m1*s1z + m2*s2z)/(m1 + m2)
468 
469  where s1z, s2z are the components of the spins along the
470  direction of the total angular momentum. For inspiral
471  waveforms, "chi" refers to the reduced spin,
472 
473  chi_red = chi_s + delta*chi_a - 76.*eta/113*chi_s,
474 
475  where chi_s and chi_a are the symmetric and anti-symmetric
476  combinations of the spins, and delta=(m1-m2)/(m1+m2). Some
477  waveforms, e.g., SpinTaylorT4, use different coordinate
478  conventions and require a coordinate transformation before
479  applying these definitions.
480  """
481 
482  if sim.waveform.startswith("SpinTaylorT4"):
483  chi1 = sim.spin1x * math.sin(sim.inclination) + sim.spin1z * math.cos(sim.inclination)
484  chi2 = sim.spin2x * math.sin(sim.inclination) + sim.spin2z * math.cos(sim.inclination)
485  chi = SimInspiralTaylorF2ReducedSpinComputeChi(sim.mass1, sim.mass2, chi1, chi2)
486 
487  elif sim.waveform.startswith("SpinTaylorT5"):
488  chi1 = sim.spin1z
489  chi2 = sim.spin2z
490  chi = SimInspiralTaylorF2ReducedSpinComputeChi(sim.mass1, sim.mass2, chi1, chi2)
491 
492  elif sim.waveform.startswith("IMRPhenomB") or sim.waveform.startswith("IMRPhenomC") or sim.waveform.startswith("SEOBNR"):
493  chi = SimIMRPhenomBComputeChi(sim.mass1, sim.mass2, sim.spin1z, sim.spin2z)
494 
495  else:
496  raise ValueError(sim.waveform)
497 
498  return (sim.distance, chi)
499 
500 
501 def sim_to_distance_mass_ratio_bins_function(sim):
502  """
503  create a function to map a sim to a distance, mass ratio NDBins based object
504  """
505  # note that if you use symmetrize_sims() below, m2/m1 > 1
506  # which just strikes me as more intuitive
507  return (sim.distance, sim.mass2/sim.mass1)
508 
509 
510 def sim_to_distance_chirp_mass_bins_function(sim):
511  """
512  create a function to map a sim to a distance, chirp mass NDBins based object
513  """
514  return (sim.distance, sim.mchirp)
515 
516 
517 def sim_to_distance_duration_bins_function(sim, f_low = 15.):
518  """
519  create a function to map a sim to a distance, duration NDBins based object
520  """
521  template_duration = chirptime.imr_time(
522  f_low,
523  sim.mass1*lal.MSUN_SI,
524  sim.mass2*lal.MSUN_SI,
525  numpy.sqrt(numpy.dot(sim.spin1, sim.spin1)),
526  numpy.sqrt(numpy.dot(sim.spin2, sim.spin2))
527  )
528  return (sim.distance, template_duration)
529 
530 
531 def symmetrize_sims(sims, col1, col2):
532  """
533  symmetrize by two columns that should be symmetric. For example mass1 and mass2
534  """
535  for sim in sims:
536  c1 = getattr(sim, col1)
537  c2 = getattr(sim, col2)
538  if c1 > c2:
539  setattr(sim, col1, c2)
540  setattr(sim, col2, c1)
541  return sims
542 
543 class DataBaseSummary(object):
544  """
545  This class stores summary information gathered across the databases
546  """
547 
548  def __init__(self, filelist, live_time_program = None, veto_segments_name = None, data_segments_name = "datasegments", tmp_path = None, verbose = False):
549 
550  self.segments = segments.segmentlistdict()
551  self.instruments = set()
552  self.table_name = None
557  self.ts_fars_by_instrument_set = {}
558  self.numslides = set()
559 
560  for f in filelist:
561  if verbose:
562  print >> sys.stderr, "Gathering stats from: %s...." % (f,)
563  with dbtables.workingcopy(f, tmp_path = tmp_path, discard = True, verbose = verbose) as working_filename:
564  connection = sqlite3.connect(str(working_filename))
565  xmldoc = dbtables.get_xml(connection)
566 
567  sim = False
568 
569  # look for a sim inspiral table. This is IMR work we have to have one of these :)
570  try:
571  sim_inspiral_table = table.get_table(xmldoc, dbtables.lsctables.SimInspiralTable.tableName)
572  sim = True
573  except ValueError:
574  pass
575 
576  # look for the relevant table for analyses
577  for table_name in allowed_analysis_table_names():
578  try:
579  setattr(self, table_name, table.get_table(xmldoc, table_name))
580  if self.table_name is None or self.table_name == table_name:
581  self.table_name = table_name
582  else:
583  raise ValueError("detected more than one table type out of " + " ".join(allowed_analysis_table_names()))
584  except ValueError:
585  setattr(self, table_name, None)
586 
587  # the non simulation databases are where we get information about segments
588  if not sim:
589  self.numslides.add(connection.cursor().execute('SELECT count(DISTINCT(time_slide_id)) FROM time_slide').fetchone()[0])
590  [self.instruments.add(ifos) for ifos in get_instruments_from_coinc_event_table(connection)]
591  # save a reference to the segments for this file, needed to figure out the missed and found injections
592  self.this_segments = get_segments(connection, xmldoc, self.table_name, live_time_program, veto_segments_name, data_segments_name = data_segments_name)
593  # FIXME we don't really have any reason to use playground segments, but I put this here as a reminder
594  # self.this_playground_segments = segmentsUtils.S2playground(self.this_segments.extent_all())
595  self.segments += self.this_segments
596 
597  # get the far thresholds for the loudest events in these databases
598  for (instruments_set, far, ts) in get_event_fars(connection, self.table_name):
599  if not ts:
600  self.zerolag_fars_by_instrument_set.setdefault(instruments_set, []).append(far)
601  else:
602  self.ts_fars_by_instrument_set.setdefault(instruments_set, []).append(far)
603  # get the injections
604  else:
605  # We need to know the segments in this file to determine which injections are found
606  self.this_injection_segments = get_segments(connection, xmldoc, self.table_name, live_time_program, veto_segments_name, data_segments_name = data_segments_name)
608  distinct_instruments = connection.cursor().execute('SELECT DISTINCT(instruments) FROM coinc_event WHERE instruments!=""').fetchall()
609  for instruments, in distinct_instruments:
610  instruments_set = frozenset(lsctables.instrument_set_from_ifos(instruments))
611  self.this_injection_instruments.append(instruments_set)
612  segments_to_consider_for_these_injections = self.this_injection_segments.intersection(instruments_set) - self.this_injection_segments.union(set(self.this_injection_segments.keys()) - instruments_set)
613  found, total, missed = get_min_far_inspiral_injections(connection, segments = segments_to_consider_for_these_injections, table_name = self.table_name)
614  if verbose:
615  print >> sys.stderr, "%s total injections: %d; Found injections %d: Missed injections %d" % (instruments, len(total), len(found), len(missed))
616  self.found_injections_by_instrument_set.setdefault(instruments_set, []).extend(found)
617  self.total_injections_by_instrument_set.setdefault(instruments_set, []).extend(total)
618  self.missed_injections_by_instrument_set.setdefault(instruments_set, []).extend(missed)
619  if len(self.numslides) > 1:
620  raise ValueError('number of slides differs between input files')
621  elif self.numslides:
622  self.numslides = min(self.numslides)
623  else:
624  self.numslides = 0
625 
626  # FIXME
627  # Things left to do
628  # 1) summarize the far threshold over the entire dataset
def imr_time
Definition: chirptime.py:126