gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
trigger_rate.py
1 # Copyright (C) 2017,2018 Kipp Cannon
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 
18 #
19 # =============================================================================
20 #
21 # Preamble
22 #
23 # =============================================================================
24 #
25 
26 
27 from bisect import bisect_right
28 from ligo import segments
29 import math
30 import numpy
31 import random
32 
33 
34 from ligo.lw import ligolw
35 from ligo.lw import array as ligolw_array
36 
37 
38 __all__ = ["ratebin", "ratebinlist", "triggerrates"]
39 
40 
41 #
42 # =============================================================================
43 #
44 # segment and segmentlist with event rate tracking
45 #
46 # =============================================================================
47 #
48 
49 
50 class ratebin(segments.segment):
51  """
52  A version of the segment class (see ligo.segments) that carries a
53  count of things. Arithmetic operations update the count by
54  interpreting the count as a uniform density of things throughout
55  the interval spanned by the segment. For example, the intersection
56  of two ratebins is the interval they have in common, and the
57  intersection's count is given by the sum of the densities of the
58  two multiplied by the size of the intersection.
59 
60  The implementation does not enforce the use of numeric values for
61  boundaries and counts, but is unlikely to behave sensibly unless
62  numeric values are used. One will also encounter problems with
63  (semi-)open intervals due to the mean density being 0 for all
64  finite counts in such intervals, and undefined otherwise.
65 
66  Negative counts are allowed, and in particular the subtraction
67  operation can yield a ratebin with a negative count if the density
68  in the ratebin being subtracted is sufficiently high. If this is a
69  concern, it is left as an excercise for the calling code to check
70  for this condition.
71 
72  Some behaviour has been selected to accomodate the specific needs
73  of the intended application, and might not be sensible for general
74  use outside of that application. For example, if the count is None
75  then the density reported is 0, not None.
76 
77  Like the segment class from which it is derived, ratebin objects
78  are immutable: neither the boundaries, nor the count, can be
79  modified after creation.
80 
81  Example:
82 
83  >>> # initialize from two boundary values without count
84  >>> x = ratebin(0, 10)
85  >>> x
86  None@[0,10)
87  >>> print(x.count)
88  None
89  >>> x.density # count of None --> density = 0, not None
90  0.0
91  >>> # initialize from two boundary values with count
92  >>> x = ratebin(0, 10, count = 5)
93  >>> x
94  5@[0,10)
95  >>> x.density
96  0.5
97  >>> # intialize from a sequence without count
98  >>> y = ratebin((5, 15))
99  >>> y
100  None@[5,15)
101  >>> # intialize from a sequence with count
102  >>> y = ratebin((5, 15), count = 2.5)
103  >>> y.density
104  0.25
105  >>> # initialize from a ratebin without count
106  >>> ratebin(y)
107  2.5@[5,15)
108  >>> # initialize from a ratebin with count
109  >>> ratebin(y, count = 5)
110  5@[5,15)
111  >>> # arithmetic examples
112  >>> x | y
113  7.5@[0,15)
114  >>> x + y
115  7.5@[0,15)
116  >>> (x + y).density
117  0.5
118  >>> x - y
119  3.75@[0,5)
120  >>> (x - y).density
121  0.75
122  >>> x & y
123  3.75@[5,10)
124  >>> (x & y).density
125  0.75
126  >>> x & x
127  10@[0,10)
128  >>> x
129  5@[0,10)
130 
131  BUGS: comparisons and hash behaviour are inherited from the
132  segment class, specifically this means the count attribute is
133  ignored for the purpose of comparisons. For example, a set will
134  believe a ratebin object is already in the set if its boundaries
135  match those of a ratebin in the set, regardless of what their
136  counts are. A dictionary will do key look-up using the ratebin
137  boundaries, only.
138 
139  Example:
140 
141  >>> x = ratebin(0, 10, count = 5)
142  >>> s = set([x])
143  >>> y = ratebin(0, 10, count = 10)
144  >>> y in s
145  True
146  >>> y == x
147  True
148  >>> x
149  5@[0,10)
150  >>> y
151  10@[0,10)
152  >>> # x and y compare as equal, so d gets only one entry
153  >>> d = {x: "a", y: "b"}
154  >>> d
155  {5@[0,10): 'b'}
156  """
157 
158  # basic methods
159 
160  def __init__(self, arg0 = None, arg1 = None, count = None):
161  # parent class' .__init__() is a no-op, so don't bother
162  # chaining to it. need to accomodate 0, 1, or 2 optional
163  # arguments before the optional count keyword
164  if isinstance(arg0, self.__class__) and count is None:
165  self._count = arg0._count
166  else:
167  self._count = count
168 
169  @property
170  def count(self):
171  return self._count
172 
173  @property
174  def density(self):
175  return (self._count or 0) / float(abs(self))
176 
177  def __str__(self):
178  return "%s@[%s,%s)" % (("%.16g" % self._count if self._count is not None else "None"), str(self[0]), str(self[1]))
179 
180  __repr__ = __str__
181 
182  # arithmetic
183 
184  def __and__(self, other):
185  new = super(ratebin, self).__and__(other)
186  if self._count is not None or other._count is not None:
187  return type(self)(new, count = (self.density + other.density) * float(abs(new)))
188  return new
189 
190  def __or__(self, other):
191  new = super(ratebin, self).__or__(other)
192  if self._count is not None or other._count is not None:
193  return type(self)(new, count = (self._count or 0) + (other._count or 0))
194  return new
195 
196  __add__ = __or__
197 
198  def __sub__(self, other):
199  new = super(ratebin, self).__sub__(other)
200  if self._count is not None:
201  return type(self)(new, count = self._count - other.density * (float(abs(self)) - float(abs(new))))
202  return new
203 
204  #
205  # overrides to preserve count
206  #
207 
208  def protract(self, x):
209  return self.__class__(self[0] - x, self[1] + x, count = self._count)
210 
211  def contract(self, x):
212  return self.__class__(self[0] + x, self[1] - x, count = self._count)
213 
214  def shift(self, x):
215  return self.__class__(self[0] + x, self[1] + x, count = self._count)
216 
217 
218 class ratebinlist(segments.segmentlist):
219  """
220  Modified version of the segmentlist type (see ligo.segments) whose
221  arithmetic operations implement the segment-and-count arithmetic
222  operations defined by the ratebin type.
223 
224  This implemention has only been optimized for performance for the
225  specific use cases for which it has been designed. It will likely
226  be found to have unacceptable performance if used as a
227  general-purpose segmentlist implementation.
228 
229  Example:
230 
231  >>> x0 = ratebinlist([ratebin(0, 10, count = 5)])
232  >>> x1 = ratebinlist([ratebin(5, 15, count = 2.5)])
233  >>> x2 = ratebinlist([ratebin(15, 25, count = 2.5)])
234  >>> x3 = ratebinlist([ratebin(20, 30, count = 5)])
235  >>> x0 | x1
236  [7.5@[0,15)]
237  >>> x0 | x1 | x2 | x3
238  [15@[0,30)]
239  >>> x0 - x1
240  [3.75@[0,5)]
241  >>> x0 | x2
242  [5@[0,10), 2.5@[15,25)]
243  >>> (x0 | x2).density
244  0.375
245  >>> x0 - x1
246  [3.75@[0,5)]
247  >>> x0.density
248  0.5
249  >>> (x0 - x1).density
250  0.75
251  >>> x0 - x2
252  [5@[0,10)]
253  >>> y = ratebinlist(x0)
254  >>> y.extend(x1)
255  >>> y.extend(x2)
256  >>> y.extend(x3)
257  >>> y
258  [5@[0,10), 2.5@[5,15), 2.5@[15,25), 5@[20,30)]
259  >>> y.coalesce()
260  [15@[0,30)]
261  >>> # slices are ratebinlist objects
262  >>> (x0 | x3)[1:].density
263  0.5
264  >>> # density is 0 at times with no segments
265  >>> x0.density_at(15)
266  0.0
267  >>> # and empty lists have a mean density of 0 (not NaN)
268  >>> (x0 & x2).density
269  0.0
270 
271  NOTE: the XML I/O feature of this class will only work correctly
272  for float-valued boundaries and integer counts.
273  """
274  def __getitem__(self, index):
275  # make sure to return slices as ratebinlist objects, not
276  # native list objects
277  val = super(ratebinlist, self).__getitem__(index)
278  return self.__class__(val) if isinstance(index, slice) else val
279 
280  # FIXME: delete after porting to 3
281  def __getslice__(self, *args, **kwargs):
282  # make sure to return slices as ratebinlist objects, not
283  # native list objects
284  return self.__class__(super(ratebinlist, self).__getslice__(*args, **kwargs))
285 
286  @property
287  def count(self):
288  return sum(seg.count for seg in self)
289 
290  @property
291  def density(self):
292  # NOTE: event density at times when there are no segments
293  # is 0., not NaN!
294  return self.count / float(abs(self)) if self else 0.
295 
296  def segmentlist(self):
297  """
298  Construct and return a segments.segmentlist of
299  segments.segment objects by type-casting the contents.
300  """
301  return segments.segmentlist(segments.segment(seg) for seg in self)
302 
303  def add_ratebin(self, seg, count):
304  """
305  Convenience method. Equivalent to
306 
307  self |= type(self)([ratebin(seg, count = count)])
308 
309  Example:
310 
311  >>> x = ratebinlist()
312  >>> x.add_ratebin((0, 10), 5)
313  >>> x.add_ratebin((10, 20), 5)
314  >>> x
315  [10@[0,20)]
316  """
317  seg = ratebin(seg, count = count)
318  # tail optimization cases
319  if not self:
320  self.append(seg)
321  elif not seg.disjoint(self[-1]):
322  self[-1] |= seg
323  elif seg.disjoint(self[-1]) > 0:
324  self.append(seg)
325  else:
326  # general case. implementation of .__ior__()
327  # allows us to use a tuple here
328  self |= (seg,)
329 
330  def find(self, item):
331  """
332  Return the smallest i such that i is the index of an
333  element that wholly contains item. Raises ValueError if no
334  such element exists.
335 
336  NOTE: unlike the segmentlist class from which ratebinlist
337  is derived, this implementation requires the ratebinlist to
338  be coalesced.
339 
340  Example:
341 
342  >>> x = ratebinlist([ratebin(0, 10, count = 5), ratebin(15, 25, count = 2.5)])
343  >>> x.find(-1)
344  Traceback (most recent call last):
345  ...
346  IndexError: -1
347  >>> x.find(0)
348  0
349  >>> x.find(5)
350  0
351  >>> # upper bounds of segments not included in span
352  >>> x.find(10)
353  Traceback (most recent call last):
354  ...
355  IndexError: 10
356  >>> x.find(12)
357  Traceback (most recent call last):
358  ...
359  IndexError: 12
360  >>> x.find(15)
361  1
362  >>> x.find(20)
363  1
364  >>> x.find(26)
365  Traceback (most recent call last):
366  ...
367  IndexError: 26
368  """
369  i = bisect_right(self, item)
370  if i and item in self[i - 1]:
371  return i - 1
372  raise IndexError(item)
373 
374  def density_at(self, x):
375  try:
376  i = self.find(x)
377  except IndexError:
378  # density is 0 at times not covered by segments
379  return 0.
380  return self[i].density
381 
382  def __iand__(self, other):
383  if not other or not self:
384  del self[:]
385  return self
386  if other is self:
387  self[:] = (ratebin(seg, seg.count * 2) for seg in self)
388  return self
389  def andgen(self, other):
390  self_next = iter(self).__next__
391  other_next = iter(other).__next__
392  self_seg = self_next()
393  other_seg = other_next()
394  try:
395  while 1:
396  while self_seg[1] <= other_seg[0]:
397  self_seg = self_next()
398  while other_seg[1] <= self_seg[0]:
399  other_seg = other_next()
400  if self_seg.intersects(other_seg):
401  yield self_seg & other_seg
402  if self_seg[1] > other_seg[1]:
403  other_seg = other_next()
404  else:
405  self_seg = self_next()
406  except StopIteration:
407  pass
408  i = bisect_right(self, other[0][0])
409  self[:] = andgen(
410  self[(i - 1 if i else 0):bisect_right(self, other[-1][1])],
411  other
412  )
413  return self
414 
415  def __ior__(self, other):
416  if other is self:
417  self[:] = (ratebin(seg, count = 2 * seg.count) for seg in self)
418  return self
419  i = 0
420  for seg in other:
421  i = j = bisect_right(self, seg, i)
422  lo, hi = seg
423  if i and self[i - 1][1] >= lo:
424  i -= 1
425  lo = self[i][0]
426  n = len(self)
427  while j < n and self[j][0] <= hi:
428  j += 1
429  if j > i:
430  self[i] = ratebin(lo, max(hi, self[j - 1][1]), count = sum((s.count for s in self[i:j]), seg.count))
431  del self[i + 1 : j]
432  else:
433  self.insert(i, seg)
434  i += 1
435  return self
436 
437  def __isub__(self, other):
438  if not other:
439  return self
440  if other is self:
441  del self[:]
442  return self
443  i = j = 0
444  other_lo, other_hi = other[j]
445  while i < len(self):
446  self_lo, self_hi = self[i]
447  while other_hi <= self_lo:
448  j += 1
449  if j >= len(other):
450  return self
451  other_lo, other_hi = other[j]
452  if self_hi <= other_lo:
453  i += 1
454  elif other_lo <= self_lo:
455  if other_hi >= self_hi:
456  del self[i]
457  else:
458  self[i] -= other[j]
459  elif other_hi < self_hi:
460  density = (self[i].count - other[j].count) / (float(abs(self[i])) - float(abs(other[j])))
461  self[i:i+1] = (ratebin(self_lo, other_lo, count = (other_lo - self_lo) * density), ratebin(other_hi, self_hi, count = (self_hi - other_hi) * density))
462  i += 1
463  else:
464  self[i] -= other[j]
465  i += 1
466  return self
467 
468  def __invert__(self):
469  raise NotImplementedError
470 
471  def coalesce(self):
472  """
473  Sort the elements of the list into ascending order, and merge
474  continuous segments into single segments. Segmentlist is
475  modified in place. This operation is O(n log n).
476  """
477  self.sort()
478  i = j = 0
479  n = len(self)
480  while j < n:
481  lo, hi = self[j]
482  count = self[j].count
483  j += 1
484  while j < n and hi >= self[j][0]:
485  hi = max(hi, self[j][1])
486  count += self[j].count
487  j += 1
488  if lo != hi:
489  self[i] = ratebin(lo, hi, count = count)
490  i += 1
491  del self[i : ]
492  return self
493 
494  @classmethod
495  def from_xml(cls, xml, name):
496  # need to cast start and stop to floats, otherwise they are
497  # numpy.float64 objects and confuse things
498  return cls(ratebin((float(start), float(stop)), count = int(count)) for (start, stop, count) in ligolw_array.get_array(xml, u"%s:ratebinlist" % name).array[:])
499 
500  def to_xml(self, name):
501  # I/O is only safe for integer counts
502  assert all(isinstance(seg.count, int) for seg in self), "counts must be type int for XML I/O"
503  return ligolw_array.Array.build(u"%s:ratebinlist" % name, numpy.array([(seg[0], seg[1], seg.count) for seg in self], dtype = "double"))
504 
505 
506 #
507 # =============================================================================
508 #
509 # trigger rate tracking for a detector network
510 #
511 # =============================================================================
512 #
513 
514 
515 class triggerrates(segments.segmentlistdict):
516  """
517  Example:
518 
519  >>> x = triggerrates({
520  ... "H1": ratebinlist([
521  ... ratebin((0, 10), count = 5),
522  ... ratebin((20, 30), count = 5)
523  ... ]),
524  ... "V1": ratebinlist([
525  ... ratebin((0, 15), count = 7),
526  ... ratebin((25, 35), count = 7)
527  ... ])
528  ... })
529  ...
530  >>> x
531  {'H1': [5@[0,10), 5@[20,30)], 'V1': [7@[0,15), 7@[25,35)]}
532  >>> y = x.copy()
533  >>> y
534  {'H1': [5@[0,10), 5@[20,30)], 'V1': [7@[0,15), 7@[25,35)]}
535  >>> y == x
536  True
537  >>> y is x
538  False
539  >>> y = triggerrates.from_xml(x.to_xml("test"), "test")
540  >>> y
541  {'H1': [5@[0.0,10.0), 5@[20.0,30.0)], 'V1': [7@[0.0,15.0), 7@[25.0,35.0)]}
542  >>> y == x
543  True
544  >>> y is x
545  False
546  """
547  @property
548  def counts(self):
549  return dict((key, value.count) for key, value in self.items())
550 
551  @property
552  def densities(self):
553  return dict((key, value.density) for key, value in self.items())
554 
555  def segmentlistdict(self):
556  return segments.segmentlistdict((key, value.segmentlist()) for key, value in self.items())
557 
558  def __iand__(self, other):
559  raise NotImplementedError
560 
561  def intersection(self, keys):
562  raise NotImplementedError
563 
564  def union(self, keys):
565  raise NotImplementedError
566 
567  def density_at(self, x):
568  return dict((key, value.density_at(x)) for key, value in self.items())
569 
570  def random_uniform(self):
571  lo, hi = self.extent_all()
572  uniform = random.uniform
573  lnP = -math.log(hi - lo)
574  while 1:
575  x = uniform(lo, hi)
576  yield x, self.density_at(x), lnP
577 
578  @classmethod
579  def from_xml(cls, xml, name):
580  xml = [elem for elem in xml.getElementsByTagName(ligolw.LIGO_LW.tagName) if elem.hasAttribute(u"Name") and elem.Name == u"%s:triggerrates" % name]
581  try:
582  xml, = xml
583  except ValueError:
584  raise ValueError("document must contain exactly 1 triggerrates named '%s'" % name)
585  keys = [elem.Name.replace(u":ratebinlist", u"") for elem in xml.getElementsByTagName(ligolw.Array.tagName) if elem.hasAttribute(u"Name") and elem.Name.endswith(u":ratebinlist")]
586  self = cls()
587  for key in keys:
588  self[key] = ratebinlist.from_xml(xml, key)
589  return self
590 
591  def to_xml(self, name):
592  xml = ligolw.LIGO_LW({u"Name": u"%s:triggerrates" % name})
593  for key, value in self.items():
594  xml.appendChild(value.to_xml(key))
595  return xml