52 from fpconst
import NaN, NegInf, PosInf
57 NegInf = float(
"-inf")
58 PosInf = float(
"+inf")
64 from ligo.lw
import ligolw
65 from ligo.lw
import array
as ligolw_array
68 __all__ = [
"NearestLeafTree",
"HorizonHistories"]
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.
88 >>> x = NearestLeafTree()
114 >>> x.to_xml(u"H1").write(sys.stdout) # doctest: +NORMALIZE_WHITESPACE
115 <Array Type="real_8" Name="H1:nearestleaftree:array">
118 <Stream Type="Local" Delimiter=" ">
126 Initialize a NearestLeafTree.
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())
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")
145 >>> x = NearestLeafTree()
146 >>> x[100.:200.] = 0.
149 NearestLeafTree([(100, 0), (150, 1), (200, 0)])
153 NearestLeafTree([(90, 5), (100, 0), (150, 1), (200, 0), (210, 5)])
155 if isinstance(x, slice):
162 if x.step
is not None:
163 raise ValueError(
"%s: step not supported" % repr(x))
166 raise IndexError(
"open-ended slice not supported with empty tree")
167 x = slice(
min(self.
minkey(), x.stop), x.stop)
170 raise IndexError(
"open-ended slice not supported with empty tree")
171 x = slice(x.start,
max(self.
maxkey(), x.start))
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),)
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),)
184 def __getitem__(self, x):
187 if isinstance(x, slice):
188 raise ValueError(
"slices not supported")
189 hi = bisect.bisect_right(self.
tree, (x, PosInf))
191 x_hi, val_hi = self.
tree[hi]
193 x_hi, val_hi = self.
tree[-1]
195 x_lo, val_lo = self.
tree[hi - 1]
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
204 >>> x = NearestLeafTree([(100., 0.), (150., 1.), (200., 0.)])
207 NearestLeafTree([(100, 0), (200, 0)])
209 Traceback (most recent call last):
216 if isinstance(x, slice):
217 if x.step
is not None:
218 raise ValueError(
"%s: step not supported" % repr(x))
223 x = slice(self.
minkey(), x.stop)
228 x = slice(x.start, self.
maxkey())
232 lo = bisect.bisect_left(self.
tree, (x.start, NegInf))
233 hi = bisect.bisect_right(self.
tree, (x.stop, PosInf))
238 lo = bisect.bisect_left(self.
tree, (x, NegInf))
239 if self.
tree[lo][0] != x:
245 True if the tree is not empty, False otherwise.
247 return bool(self.
tree)
251 For every (key, value) pair in other, assign self[key]=value.
253 for x, val
in other.tree:
258 return [x
for x, val
in self.
tree]
261 return [val
for x, val
in self.
tree]
264 return list(self.
tree)
268 Return the minimum value stored in the tree. This is O(n).
271 raise ValueError(
"empty tree")
272 return min(val
for x, val
in self.
tree)
276 Return the minimum key stored in the tree. This is O(1).
279 raise ValueError(
"empty tree")
280 return self.
tree[0][0]
284 Return the maximum value stored in the tree. This is O(n).
287 raise ValueError(
"empty tree")
288 return max(val
for x, val
in self.
tree)
292 Return the maximum key stored in the tree. This is O(1).
295 raise ValueError(
"empty tree")
296 return self.
tree[-1][0]
300 True if a key in self equals x, False otherwise.
303 return bool(self.
tree)
and self.
tree[bisect.bisect_left(self.
tree, (x, NegInf))][0] == x
309 The number of (key, value) pairs in self.
311 return len(self.
tree)
314 return "NearestLeafTree([%s])" %
", ".join(
"(%g, %g)" % item
for item
in self.
tree)
318 Given the function f(x) = self[x], compute
320 \int_{lo}^{hi} w(f(x)) dx
322 The arguments are the lo and hi bounds and the functional
323 w(f). The default functional is w(f) = f.
327 >>> x = NearestLeafTree([(100., 0.), (150., 2.), (200., 0.)])
328 >>> x.functional_integral((130., 170.))
330 >>> x.functional_integral((100., 150.))
332 >>> x.functional_integral((300., 500.))
334 >>> x.functional_integral((100., 150.), lambda f: f**3)
340 raise ValueError(
"empty tree")
344 return NaN
if math.isinf(w(self[lo]))
else 0.
356 i = bisect.bisect_right(self.
tree, (lo, NegInf))
357 j = bisect.bisect_right(self.
tree, (hi, PosInf))
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:])]
363 samples = [(lo, self[lo])]
364 elif samples[0][0] > lo:
365 samples.insert(0, (lo, self[lo]))
367 samples[0] = lo, self[lo]
368 if samples[-1][0] < hi:
369 samples.append((hi, self[hi]))
371 samples[-1] = hi, self[hi]
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
378 Given the function f(x) = self[x], compute
380 \int_{lo}^{hi} w(f(x)) f(x) dx
381 ------------------------------
382 \int_{lo}^{hi} w(f(x)) dx
384 where w(y) is a weighting function. The default weight
385 function is w(y) = 1.
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
393 >>> x = NearestLeafTree([(100., 0.), (150., 2.), (200., 0.)])
394 >>> x.weighted_mean((130., 170.))
396 >>> x.weighted_mean((100., 150.))
398 >>> x.weighted_mean((300., 500.))
400 >>> x.weighted_mean((100., 150.), lambda x: x**3)
405 raise ValueError(
"empty tree")
418 return num / den
if num
or den
else 0.0
421 def from_xml(cls, xml, name):
422 return cls(map(tuple, ligolw_array.get_array(xml,
u"%s:nearestleaftree" % name).array[:]))
424 def to_xml(self, name):
425 return ligolw_array.Array.build(
u"%s:nearestleaftree" % name, numpy.array(self.
tree, dtype =
"double"))
431 Override of dict's .copy() that (a) returns the correct
432 type and (b) makes copies of the HorizonHistories'
435 return type(self)((key, copy.deepcopy(value))
for key, value
in self.items())
437 def __iadd__(self, other):
438 for key, history
in other.items():
442 self[key] = copy.deepcopy(history)
447 Return the minimum key stored in the trees.
449 minkeys = tuple(history.minkey()
for history
in self.values()
if history)
451 raise ValueError(
"empty trees")
456 Return the maximum key stored in the trees.
458 maxkeys = tuple(history.maxkey()
for history
in self.values()
if history)
460 raise ValueError(
"empty trees")
463 def getdict(self, x):
464 return dict((key, value[x])
for key, value
in self.items())
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.
479 yield getdict(rnd(x_min, x_max))
483 Returns a list of the unique sets of horizon distances
484 recorded in the histories.
488 all_x = set(x
for value
in self.values()
for x
in value.keys())
492 result = set(frozenset(self.
getdict(x).items())
for x
in all_x)
496 return map(dict, result)
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
506 return dict((key, value.functional_integral(*args, **kwargs))
for key, value
in self.items())
510 Given the function f(x) = self.getdict(x), compute
512 \int_{lo}^{hi} w(f(x)) dx
514 The arguments are the lo and hi bounds and the functional
515 w(f). The default functional is w(f) = max(f.values()).
519 >>> x = HorizonHistories({
520 ... "H1": NearestLeafTree([(100., 0.), (150., 2.), (200., 0.)]),
521 ... "L1": NearestLeafTree([(100., 0.), (150., 20.), (200., 0.)]),
523 >>> x.functional_integral((130., 170.))
525 >>> x.functional_integral((100., 150.))
527 >>> x.functional_integral((300., 500.))
529 >>> x["H1"].functional_integral((100., 150.), w = lambda f: f**3)
533 if not self
or not all(self.values()):
534 raise ValueError(
"empty tree or no trees")
538 return NaN
if math.isinf(w(self.
getdict(lo)))
else 0.
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)
556 samples = samples[i:j+1]
557 samples = [((a + b) / 2., self.
getdict(b))
for a, b
in zip(samples[:-1], samples[1:])]
559 samples = [(lo, self.
getdict(lo))]
560 elif samples[0][0] > lo:
561 samples.insert(0, (lo, self.
getdict(lo)))
563 samples[0] = lo, self.
getdict(lo)
564 if samples[-1][0] < hi:
565 samples.append((hi, self.
getdict(hi)))
567 samples[-1] = hi, self.
getdict(hi)
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
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.
580 return dict((key, value.weighted_mean(*args, **kwargs))
for key, value
in self.items())
582 def compress(self, threshold = 0.03, remove_deviations = False, deviation_percent = 0.50, verbose = False):
584 Remove distances that are non-zero and differ
585 fractionally from both neighbours by less than
586 the selected threshold.
588 Also allows removal of uncharacteristic horizon
591 abs_ln_thresh = math.log1p(threshold)
592 for instrument, horizon_history
in list(self.items()):
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))]
602 for i
in range(1, len(items) - 1):
603 values = items[j - 1][1], items[i][1], items[i + 1][1]
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):
615 if values == (0., 0., 0.):
621 print(
"\"%s\": %s horizon history reduced to %.3g%% of original size" % (filename, instrument, 100. * j / (i + 1.)), file=sys.stderr)
624 self[instrument] = type(horizon_history)(items)
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]
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")]
636 self[key] = NearestLeafTree.from_xml(xml, key)
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))
def functional_integral_dict