27 from bisect
import bisect_right
28 from ligo
import segments
34 from ligo.lw
import ligolw
35 from ligo.lw
import array
as ligolw_array
38 __all__ = [
"ratebin",
"ratebinlist",
"triggerrates"]
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.
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.
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
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.
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.
83 >>> # initialize from two boundary values without count
84 >>> x = ratebin(0, 10)
89 >>> x.density # count of None --> density = 0, not None
91 >>> # initialize from two boundary values with count
92 >>> x = ratebin(0, 10, count = 5)
97 >>> # intialize from a sequence without count
98 >>> y = ratebin((5, 15))
101 >>> # intialize from a sequence with count
102 >>> y = ratebin((5, 15), count = 2.5)
105 >>> # initialize from a ratebin without count
108 >>> # initialize from a ratebin with count
109 >>> ratebin(y, count = 5)
111 >>> # arithmetic examples
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
141 >>> x = ratebin(0, 10, count = 5)
143 >>> y = ratebin(0, 10, count = 10)
152 >>> # x and y compare as equal, so d gets only one entry
153 >>> d = {x: "a", y: "b"}
160 def __init__(self, arg0 = None, arg1 = None, count = None):
164 if isinstance(arg0, self.__class__)
and count
is None:
175 return (self.
_count or 0) / float(abs(self))
178 return "%s@[%s,%s)" % ((
"%.16g" % self.
_count if self.
_count is not None else "None"), str(self[0]), str(self[1]))
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)))
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))
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))))
208 def protract(self, x):
209 return self.__class__(self[0] - x, self[1] + x, count = self.
_count)
211 def contract(self, x):
212 return self.__class__(self[0] + x, self[1] - x, count = self.
_count)
215 return self.__class__(self[0] + x, self[1] + x, count = self.
_count)
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.
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.
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)])
237 >>> x0 | x1 | x2 | x3
242 [5@[0,10), 2.5@[15,25)]
243 >>> (x0 | x2).density
249 >>> (x0 - x1).density
253 >>> y = ratebinlist(x0)
258 [5@[0,10), 2.5@[5,15), 2.5@[15,25), 5@[20,30)]
261 >>> # slices are ratebinlist objects
262 >>> (x0 | x3)[1:].density
264 >>> # density is 0 at times with no segments
265 >>> x0.density_at(15)
267 >>> # and empty lists have a mean density of 0 (not NaN)
268 >>> (x0 & x2).density
271 NOTE: the XML I/O feature of this class will only work correctly
272 for float-valued boundaries and integer counts.
274 def __getitem__(self, index):
277 val = super(ratebinlist, self).__getitem__(index)
278 return self.__class__(val)
if isinstance(index, slice)
else val
281 def __getslice__(self, *args, **kwargs):
284 return self.__class__(super(ratebinlist, self).__getslice__(*args, **kwargs))
288 return sum(seg.count
for seg
in self)
294 return self.
count / float(abs(self))
if self
else 0.
298 Construct and return a segments.segmentlist of
299 segments.segment objects by type-casting the contents.
301 return segments.segmentlist(segments.segment(seg)
for seg
in self)
305 Convenience method. Equivalent to
307 self |= type(self)([ratebin(seg, count = count)])
311 >>> x = ratebinlist()
312 >>> x.add_ratebin((0, 10), 5)
313 >>> x.add_ratebin((10, 20), 5)
317 seg =
ratebin(seg, count = count)
321 elif not seg.disjoint(self[-1]):
323 elif seg.disjoint(self[-1]) > 0:
332 Return the smallest i such that i is the index of an
333 element that wholly contains item. Raises ValueError if no
336 NOTE: unlike the segmentlist class from which ratebinlist
337 is derived, this implementation requires the ratebinlist to
342 >>> x = ratebinlist([ratebin(0, 10, count = 5), ratebin(15, 25, count = 2.5)])
344 Traceback (most recent call last):
351 >>> # upper bounds of segments not included in span
353 Traceback (most recent call last):
357 Traceback (most recent call last):
365 Traceback (most recent call last):
369 i = bisect_right(self, item)
370 if i
and item
in self[i - 1]:
372 raise IndexError(item)
374 def density_at(self, x):
380 return self[i].density
382 def __iand__(self, other):
383 if not other
or not self:
387 self[:] = (
ratebin(seg, seg.count * 2)
for seg
in 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()
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()
405 self_seg = self_next()
406 except StopIteration:
408 i = bisect_right(self, other[0][0])
410 self[(i - 1
if i
else 0):bisect_right(self, other[-1][1])],
415 def __ior__(self, other):
417 self[:] = (
ratebin(seg, count = 2 * seg.count)
for seg
in self)
421 i = j = bisect_right(self, seg, i)
423 if i
and self[i - 1][1] >= lo:
427 while j < n
and self[j][0] <= hi:
430 self[i] =
ratebin(lo, max(hi, self[j - 1][1]), count = sum((s.count
for s
in self[i:j]), seg.count))
437 def __isub__(self, other):
444 other_lo, other_hi = other[j]
446 self_lo, self_hi = self[i]
447 while other_hi <= self_lo:
451 other_lo, other_hi = other[j]
452 if self_hi <= other_lo:
454 elif other_lo <= self_lo:
455 if other_hi >= self_hi:
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))
468 def __invert__(self):
469 raise NotImplementedError
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).
482 count = self[j].count
484 while j < n
and hi >= self[j][0]:
485 hi = max(hi, self[j][1])
486 count += self[j].count
489 self[i] =
ratebin(lo, hi, count = count)
495 def from_xml(cls, xml, name):
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[:])
500 def to_xml(self, name):
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"))
519 >>> x = triggerrates({
520 ... "H1": ratebinlist([
521 ... ratebin((0, 10), count = 5),
522 ... ratebin((20, 30), count = 5)
524 ... "V1": ratebinlist([
525 ... ratebin((0, 15), count = 7),
526 ... ratebin((25, 35), count = 7)
531 {'H1': [5@[0,10), 5@[20,30)], 'V1': [7@[0,15), 7@[25,35)]}
534 {'H1': [5@[0,10), 5@[20,30)], 'V1': [7@[0,15), 7@[25,35)]}
539 >>> y = triggerrates.from_xml(x.to_xml("test"), "test")
541 {'H1': [5@[0.0,10.0), 5@[20.0,30.0)], 'V1': [7@[0.0,15.0), 7@[25.0,35.0)]}
549 return dict((key, value.count)
for key, value
in self.items())
553 return dict((key, value.density)
for key, value
in self.items())
555 def segmentlistdict(self):
556 return segments.segmentlistdict((key, value.segmentlist())
for key, value
in self.items())
558 def __iand__(self, other):
559 raise NotImplementedError
561 def intersection(self, keys):
562 raise NotImplementedError
564 def union(self, keys):
565 raise NotImplementedError
567 def density_at(self, x):
568 return dict((key, value.density_at(x))
for key, value
in self.items())
570 def random_uniform(self):
571 lo, hi = self.extent_all()
572 uniform = random.uniform
573 lnP = -math.log(hi - lo)
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]
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")]
588 self[key] = ratebinlist.from_xml(xml, key)
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))