gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
horizonhistory.py
Go to the documentation of this file.
1 # Copyright (C) 2011--2014 Kipp Cannon, Chad Hanna, Drew Keppel
2 # Copyright (C) 2013 Jacob Peoples
3 #
4 # This program is free software; you can redistribute it and/or modify it
5 # under the terms of the GNU General Public License as published by the
6 # Free Software Foundation; either version 2 of the License, or (at your
7 # option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
12 # Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 
18 ## @file
19 # The python module to implement false alarm probability and false alarm rate
20 #
21 # ### Review Status
22 #
23 # STATUS: reviewed with actions
24 #
25 # | Names | Hash | Date | Diff to Head of Master |
26 # | ------------------------------------------- | ------------------------------------------- | ---------- | --------------------------- |
27 # | Hanna, Cannon, Meacher, Creighton J, Robinet, Sathyaprakash, Messick, Dent, Blackburn | 7fb5f008afa337a33a72e182d455fdd74aa7aa7a | 2014-11-05 |<a href="@gstlal_inspiral_cgit_diff/python/far.py?id=HEAD&id2=7fb5f008afa337a33a72e182d455fdd74aa7aa7a">far.py</a> |
28 # | Hanna, Cannon, Meacher, Creighton J, Sathyaprakash, | 72875f5cb241e8d297cd9b3f9fe309a6cfe3f716 | 2015-11-06 |<a href="@gstlal_inspiral_cgit_diff/python/far.py?id=HEAD&id2=72875f5cb241e8d297cd9b3f9fe309a6cfe3f716">far.py</a> |
29 #
30 # #### Action items
31 #
32 
33 # - Address the fixed SNR PDF using median PSD which could be pre-computed and stored on disk. (Store database of SNR pdfs for a variety of horizon)
34 # - The binning parameters are hard-coded too; Could it be a problem?
35 # - Chisquare binning hasn't been tuned to be a good representation of the PDFs; could be improved in future
36 
37 ## @package far
38 
39 
40 #
41 # =============================================================================
42 #
43 # Preamble
44 #
45 # =============================================================================
46 #
47 
48 
49 import bisect
50 import copy
51 try:
52  from fpconst import NaN, NegInf, PosInf
53 except ImportError:
54  # fpconst is not part of the standard library and might not be
55  # available
56  NaN = float("nan")
57  NegInf = float("-inf")
58  PosInf = float("+inf")
59 import math
60 import numpy
61 import random
62 
63 
64 from ligo.lw import ligolw
65 from ligo.lw import array as ligolw_array
66 
67 
68 __all__ = ["NearestLeafTree", "HorizonHistories"]
69 
70 
71 #
72 # =============================================================================
73 #
74 # Horizon Distance Record Keeping
75 #
76 # =============================================================================
77 #
78 
79 
80 class NearestLeafTree(object):
81  """
82  A simple binary tree in which look-ups return the value of the
83  closest leaf. Only float objects are supported for the keys and
84  values. Look-ups raise KeyError if the tree is empty.
85 
86  Example:
87 
88  >>> x = NearestLeafTree()
89  >>> bool(x)
90  False
91  >>> x[100.0] = 120.
92  >>> bool(x)
93  True
94  >>> x[104.0] = 100.
95  >>> x[102.0] = 110.
96  >>> x[90.]
97  120.0
98  >>> x[100.999]
99  120.0
100  >>> x[101.001]
101  110.0
102  >>> x[200.]
103  100.0
104  >>> del x[104]
105  >>> x[200.]
106  110.0
107  >>> x.keys()
108  [100.0, 102.0]
109  >>> 102 in x
110  True
111  >>> 103 in x
112  False
113  >>> import sys
114  >>> x.to_xml(u"H1").write(sys.stdout) # doctest: +NORMALIZE_WHITESPACE
115  <Array Type="real_8" Name="H1:nearestleaftree:array">
116  <Dim>2</Dim>
117  <Dim>2</Dim>
118  <Stream Type="Local" Delimiter=" ">
119  100 102
120  120 110
121  </Stream>
122  </Array>
123  """
124  def __init__(self, items = ()):
125  """
126  Initialize a NearestLeafTree.
127 
128  Example:
129 
130  >>> x = NearestLeafTree()
131  >>> x = NearestLeafTree([(100., 120.), (104., 100.), (102., 110.)])
132  >>> y = {100.: 120., 104.: 100., 102.: 100.}
133  >>> x = NearestLeafTree(y.items())
134  """
135  # make a copy to ensure we have a stable object
136  self.tree = list(map(tuple, items))
137  if any(len(item) != 2 for item in self.tree):
138  raise ValueError("items must be sequence of two-element sequences")
139  self.tree.sort()
140 
141  def __setitem__(self, x, val):
142  """
143  Example:
144 
145  >>> x = NearestLeafTree()
146  >>> x[100.:200.] = 0.
147  >>> x[150.] = 1.
148  >>> x
149  NearestLeafTree([(100, 0), (150, 1), (200, 0)])
150  >>> x[210:] = 5.
151  >>> x[:90] = 5.
152  >>> x
153  NearestLeafTree([(90, 5), (100, 0), (150, 1), (200, 0), (210, 5)])
154  """
155  if isinstance(x, slice):
156  # replace all entries in the requested range of
157  # co-ordiantes with two entries, each with the
158  # given value, one at the start of the range and
159  # one at the end of the range. thus, after this
160  # all queries within that range will return this
161  # value.
162  if x.step is not None:
163  raise ValueError("%s: step not supported" % repr(x))
164  if x.start is None:
165  if not self.tree:
166  raise IndexError("open-ended slice not supported with empty tree")
167  x = slice(min(self.minkey(), x.stop), x.stop)
168  if x.stop is None:
169  if not self.tree:
170  raise IndexError("open-ended slice not supported with empty tree")
171  x = slice(x.start, max(self.maxkey(), x.start))
172  if x.start > x.stop:
173  raise ValueError("%s: bounds out of order" % repr(x))
174  lo = bisect.bisect_left(self.tree, (x.start, NegInf))
175  hi = bisect.bisect_right(self.tree, (x.stop, PosInf))
176  self.tree[lo:hi] = ((x.start, val), (x.stop, val)) if x.start != x.stop else ((x.start, val),)
177  else:
178  # replace all entries having the same co-ordinate
179  # with this one
180  lo = bisect.bisect_left(self.tree, (x, NegInf))
181  hi = bisect.bisect_right(self.tree, (x, PosInf))
182  self.tree[lo:hi] = ((x, val),)
183 
184  def __getitem__(self, x):
185  if not self.tree:
186  raise KeyError(x)
187  if isinstance(x, slice):
188  raise ValueError("slices not supported")
189  hi = bisect.bisect_right(self.tree, (x, PosInf))
190  try:
191  x_hi, val_hi = self.tree[hi]
192  except IndexError:
193  x_hi, val_hi = self.tree[-1]
194  if hi:
195  x_lo, val_lo = self.tree[hi - 1]
196  else:
197  x_lo, val_lo = x_hi, val_hi
198  return val_lo if abs(x - x_lo) < abs(x_hi - x) else val_hi
199 
200  def __delitem__(self, x):
201  """
202  Example:
203 
204  >>> x = NearestLeafTree([(100., 0.), (150., 1.), (200., 0.)])
205  >>> del x[150.]
206  >>> x
207  NearestLeafTree([(100, 0), (200, 0)])
208  >>> del x[190.]
209  Traceback (most recent call last):
210  ...
211  IndexError: 190.0
212  >>> del x[:]
213  >>> x
214  NearestLeafTree([])
215  """
216  if isinstance(x, slice):
217  if x.step is not None:
218  raise ValueError("%s: step not supported" % repr(x))
219  if x.start is None:
220  if not self.tree:
221  # no-op
222  return
223  x = slice(self.minkey(), x.stop)
224  if x.stop is None:
225  if not self.tree:
226  # no-op
227  return
228  x = slice(x.start, self.maxkey())
229  if x.stop < x.start:
230  # no-op
231  return
232  lo = bisect.bisect_left(self.tree, (x.start, NegInf))
233  hi = bisect.bisect_right(self.tree, (x.stop, PosInf))
234  del self.tree[lo:hi]
235  elif not self.tree:
236  raise IndexError(x)
237  else:
238  lo = bisect.bisect_left(self.tree, (x, NegInf))
239  if self.tree[lo][0] != x:
240  raise IndexError(x)
241  del self.tree[lo]
242 
243  def __bool__(self):
244  """
245  True if the tree is not empty, False otherwise.
246  """
247  return bool(self.tree)
248 
249  def __iadd__(self, other):
250  """
251  For every (key, value) pair in other, assign self[key]=value.
252  """
253  for x, val in other.tree:
254  self[x] = val
255  return self
256 
257  def keys(self):
258  return [x for x, val in self.tree]
259 
260  def values(self):
261  return [val for x, val in self.tree]
262 
263  def items(self):
264  return list(self.tree)
265 
266  def min(self):
267  """
268  Return the minimum value stored in the tree. This is O(n).
269  """
270  if not self.tree:
271  raise ValueError("empty tree")
272  return min(val for x, val in self.tree)
273 
274  def minkey(self):
275  """
276  Return the minimum key stored in the tree. This is O(1).
277  """
278  if not self.tree:
279  raise ValueError("empty tree")
280  return self.tree[0][0]
281 
282  def max(self):
283  """
284  Return the maximum value stored in the tree. This is O(n).
285  """
286  if not self.tree:
287  raise ValueError("empty tree")
288  return max(val for x, val in self.tree)
289 
290  def maxkey(self):
291  """
292  Return the maximum key stored in the tree. This is O(1).
293  """
294  if not self.tree:
295  raise ValueError("empty tree")
296  return self.tree[-1][0]
297 
298  def __contains__(self, x):
299  """
300  True if a key in self equals x, False otherwise.
301  """
302  try:
303  return bool(self.tree) and self.tree[bisect.bisect_left(self.tree, (x, NegInf))][0] == x
304  except IndexError:
305  return False
306 
307  def __len__(self):
308  """
309  The number of (key, value) pairs in self.
310  """
311  return len(self.tree)
312 
313  def __repr__(self):
314  return "NearestLeafTree([%s])" % ", ".join("(%g, %g)" % item for item in self.tree)
315 
316  def functional_integral(self, lohi, w = lambda f: f):
317  """
318  Given the function f(x) = self[x], compute
319 
320  \int_{lo}^{hi} w(f(x)) dx
321 
322  The arguments are the lo and hi bounds and the functional
323  w(f). The default functional is w(f) = f.
324 
325  Example:
326 
327  >>> x = NearestLeafTree([(100., 0.), (150., 2.), (200., 0.)])
328  >>> x.functional_integral((130., 170.))
329  80.0
330  >>> x.functional_integral((100., 150.))
331  50.0
332  >>> x.functional_integral((300., 500.))
333  0.0
334  >>> x.functional_integral((100., 150.), lambda f: f**3)
335  200.0
336  """
337  lo, hi = lohi
338 
339  if not self.tree:
340  raise ValueError("empty tree")
341  if lo < hi:
342  swapped = False
343  elif lo == hi:
344  return NaN if math.isinf(w(self[lo])) else 0.
345  else:
346  # lo > hi. remove a factor of -1 from the integral
347  lo, hi = hi, lo
348  swapped = True
349  # now we are certain that lo < hi and that there is at
350  # least one entry in the tree
351 
352  # construct an array of (x,y) pairs such that f(x) = y and
353  # continues to equal y until the next x. ensure the 0th
354  # and last entries in the array are the left and right
355  # edges of the integration domain.
356  i = bisect.bisect_right(self.tree, (lo, NegInf))
357  j = bisect.bisect_right(self.tree, (hi, PosInf))
358  if i > 0:
359  i -= 1
360  samples = self.tree[i:j+1]
361  samples = [((a_key + b_key) / 2., b_val) for (a_key, a_val), (b_key, b_val) in zip(samples[:-1], samples[1:])]
362  if not samples:
363  samples = [(lo, self[lo])]
364  elif samples[0][0] > lo:
365  samples.insert(0, (lo, self[lo]))
366  else:
367  samples[0] = lo, self[lo]
368  if samples[-1][0] < hi:
369  samples.append((hi, self[hi]))
370  else:
371  samples[-1] = hi, self[hi]
372  # return the integral
373  result = sum((b_key - a_key) * w(a_val) for (a_key, a_val), (b_key, b_val) in zip(samples[:-1], samples[1:]))
374  return -result if swapped else result
375 
376  def weighted_mean(self, lohi, weight = lambda y: 1.):
377  """
378  Given the function f(x) = self[x], compute
379 
380  \int_{lo}^{hi} w(f(x)) f(x) dx
381  ------------------------------
382  \int_{lo}^{hi} w(f(x)) dx
383 
384  where w(y) is a weighting function. The default weight
385  function is w(y) = 1.
386 
387  If the numerator is identically 0 and the denominator is
388  also 0 then a value of 0 is returned rather than raising a
389  divide-by-0 error.
390 
391  Example:
392 
393  >>> x = NearestLeafTree([(100., 0.), (150., 2.), (200., 0.)])
394  >>> x.weighted_mean((130., 170.))
395  2.0
396  >>> x.weighted_mean((100., 150.))
397  1.0
398  >>> x.weighted_mean((300., 500.))
399  0.0
400  >>> x.weighted_mean((100., 150.), lambda x: x**3)
401  2.0
402  """
403  lo, hi = lohi
404  if not self.tree:
405  raise ValueError("empty tree")
406  if lo > hi:
407  # remove a common factor of -1 from the numerator
408  # and denominator
409  lo, hi = hi, lo
410  elif lo == hi:
411  return self[lo]
412  # now we are certain that lo < hi and that there is at
413  # least one entry in the tree
414 
415  # return the ratio of the two integrals
416  num = self.functional_integral((lo, hi), lambda f: weight(f) * f)
417  den = self.functional_integral((lo, hi), weight)
418  return num / den if num or den else 0.0
419 
420  @classmethod
421  def from_xml(cls, xml, name):
422  return cls(map(tuple, ligolw_array.get_array(xml, u"%s:nearestleaftree" % name).array[:]))
423 
424  def to_xml(self, name):
425  return ligolw_array.Array.build(u"%s:nearestleaftree" % name, numpy.array(self.tree, dtype = "double"))
426 
427 
428 class HorizonHistories(dict):
429  def copy(self):
430  """
431  Override of dict's .copy() that (a) returns the correct
432  type and (b) makes copies of the HorizonHistories'
433  contents.
434  """
435  return type(self)((key, copy.deepcopy(value)) for key, value in self.items())
436 
437  def __iadd__(self, other):
438  for key, history in other.items():
439  try:
440  self[key] += history
441  except KeyError:
442  self[key] = copy.deepcopy(history)
443  return self
444 
445  def minkey(self):
446  """
447  Return the minimum key stored in the trees.
448  """
449  minkeys = tuple(history.minkey() for history in self.values() if history)
450  if not minkeys:
451  raise ValueError("empty trees")
452  return min(minkeys)
453 
454  def maxkey(self):
455  """
456  Return the maximum key stored in the trees.
457  """
458  maxkeys = tuple(history.maxkey() for history in self.values() if history)
459  if not maxkeys:
460  raise ValueError("empty trees")
461  return max(maxkeys)
462 
463  def getdict(self, x):
464  return dict((key, value[x]) for key, value in self.items())
465 
466  def randhorizons(self):
467  """
468  Generator yielding a sequence of random horizon distance
469  dictionaries chosen by drawing random times uniformly
470  distributed between the lowest and highest times recorded
471  in the history and returning the dictionary of horizon
472  distances for each of those times.
473  """
474  x_min = self.minkey()
475  x_max = self.maxkey()
476  getdict = self.getdict
477  rnd = random.uniform
478  while 1:
479  yield getdict(rnd(x_min, x_max))
480 
481  def all(self):
482  """
483  Returns a list of the unique sets of horizon distances
484  recorded in the histories.
485  """
486  # unique times for which a horizon distance measurement is
487  # available
488  all_x = set(x for value in self.values() for x in value.keys())
489 
490  # the unique horizon distances from those times, expressed
491  # as frozensets of instrument/distance pairs
492  result = set(frozenset(self.getdict(x).items()) for x in all_x)
493 
494  # return a list of the results converted back to
495  # dictionaries
496  return map(dict, result)
497 
498  def functional_integral_dict(self, *args, **kwargs):
499  """
500  Return a dictionary of the result of invoking
501  .functional_integral() on each of the histories. args and
502  kwargs are passed to the .functional_integral() method of
503  the histories objects, see their documentation for more
504  information.
505  """
506  return dict((key, value.functional_integral(*args, **kwargs)) for key, value in self.items())
507 
508  def functional_integral(self, lohi, w = lambda f: max(f.values())):
509  """
510  Given the function f(x) = self.getdict(x), compute
511 
512  \int_{lo}^{hi} w(f(x)) dx
513 
514  The arguments are the lo and hi bounds and the functional
515  w(f). The default functional is w(f) = max(f.values()).
516 
517  Example:
518 
519  >>> x = HorizonHistories({
520  ... "H1": NearestLeafTree([(100., 0.), (150., 2.), (200., 0.)]),
521  ... "L1": NearestLeafTree([(100., 0.), (150., 20.), (200., 0.)]),
522  ... })
523  >>> x.functional_integral((130., 170.))
524  800.0
525  >>> x.functional_integral((100., 150.))
526  500.0
527  >>> x.functional_integral((300., 500.))
528  0.0
529  >>> x["H1"].functional_integral((100., 150.), w = lambda f: f**3)
530  200.0
531  """
532  lo, hi = lohi
533  if not self or not all(self.values()):
534  raise ValueError("empty tree or no trees")
535  if lo < hi:
536  swapped = False
537  elif lo == hi:
538  return NaN if math.isinf(w(self.getdict(lo))) else 0.
539  else:
540  # lo > hi. remove a factor of -1 from the integral
541  lo, hi = hi, lo
542  swapped = True
543  # now we are certain that lo < hi and that there is at
544  # least one entry in the tree
545 
546  # construct an array of (x,y) pairs such that f(x) = y and
547  # continues to equal y until the next x. ensure the 0th
548  # and last entries in the array are the left and right
549  # edges of the integration domain.
550 
551  samples = sorted(set(x for value in self.values() for x in value.keys()))
552  i = bisect.bisect_right(samples, lo)
553  j = bisect.bisect_right(samples, hi)
554  if i > 0:
555  i -= 1
556  samples = samples[i:j+1]
557  samples = [((a + b) / 2., self.getdict(b)) for a, b in zip(samples[:-1], samples[1:])]
558  if not samples:
559  samples = [(lo, self.getdict(lo))]
560  elif samples[0][0] > lo:
561  samples.insert(0, (lo, self.getdict(lo)))
562  else:
563  samples[0] = lo, self.getdict(lo)
564  if samples[-1][0] < hi:
565  samples.append((hi, self.getdict(hi)))
566  else:
567  samples[-1] = hi, self.getdict(hi)
568 
569  # return the integral
570  result = sum((b_key - a_key) * w(a_val) for (a_key, a_val), (b_key, b_val) in zip(samples[:-1], samples[1:]))
571  return -result if swapped else result
572 
573  def weighted_mean_dict(self, *args, **kwargs):
574  """
575  Return a dictionary of the result of invoking
576  .weighted_mean() on each of the histories. args and kwargs
577  are passed to the .weighted_mean() method of the histories
578  objects, see their documentation for more information.
579  """
580  return dict((key, value.weighted_mean(*args, **kwargs)) for key, value in self.items())
581 
582  def compress(self, threshold = 0.03, remove_deviations = False, deviation_percent = 0.50, verbose = False):
583  """
584  Remove distances that are non-zero and differ
585  fractionally from both neighbours by less than
586  the selected threshold.
587 
588  Also allows removal of uncharacteristic horizon
589  distance values.
590  """
591  abs_ln_thresh = math.log1p(threshold)
592  for instrument, horizon_history in list(self.items()):
593  # GPS time / distance pairs
594  items = horizon_history.items()
595  if remove_deviations:
596  values = numpy.array(items)[:,1]
597  mean_horizon = values[values!=0].mean()
598  items = [item for item in items if item[1] < (mean_horizon * (1. + deviation_percent))]
599 
600  # compress array
601  j = 1
602  for i in range(1, len(items) - 1):
603  values = items[j - 1][1], items[i][1], items[i + 1][1]
604  # remove distances that are non-zero and differ
605  # fractionally from both neighbours by less than
606  # the selected threshold. always keep the first
607  # and last values
608  if (values[0] > 0. and values[1] > 0. and values[2] > 0. and
609  abs(math.log(values[1] / values[0])) < abs_ln_thresh and
610  abs(math.log(values[1] / values[2])) < abs_ln_thresh):
611  continue
612  # remove distances that are 0 and surrounded by 0
613  # on both sides (basically the same as the last
614  # test, but we can't take log(0)).
615  if values == (0., 0., 0.):
616  continue
617  items[j] = items[i]
618  j += 1
619  del items[j:]
620  if verbose:
621  print("\"%s\": %s horizon history reduced to %.3g%% of original size" % (filename, instrument, 100. * j / (i + 1.)), file=sys.stderr)
622 
623  # replace
624  self[instrument] = type(horizon_history)(items)
625 
626  @classmethod
627  def from_xml(cls, xml, name):
628  xml = [elem for elem in xml.getElementsByTagName(ligolw.LIGO_LW.tagName) if elem.hasAttribute(u"Name") and elem.Name == u"%s:horizonhistories" % name]
629  try:
630  xml, = xml
631  except ValueError:
632  raise ValueError("document must contain exactly 1 HorizonHistories named '%s'" % name)
633  keys = [elem.Name.replace(u":nearestleaftree", u"") for elem in xml.getElementsByTagName(ligolw.Array.tagName) if elem.hasAttribute(u"Name") and elem.Name.endswith(u":nearestleaftree")]
634  self = cls()
635  for key in keys:
636  self[key] = NearestLeafTree.from_xml(xml, key)
637  return self
638 
639  def to_xml(self, name):
640  xml = ligolw.LIGO_LW({u"Name": u"%s:horizonhistories" % name})
641  for key, value in self.items():
642  xml.appendChild(value.to_xml(key))
643  return xml