wdflow 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. wdf/__init__.py +0 -0
  2. wdf/analysis/__init__.py +116 -0
  3. wdf/analysis/anomaly.py +266 -0
  4. wdf/analysis/background.py +195 -0
  5. wdf/analysis/baseline.py +147 -0
  6. wdf/analysis/cluster_coefficients.py +391 -0
  7. wdf/analysis/clustering.py +479 -0
  8. wdf/analysis/coefficients.py +337 -0
  9. wdf/analysis/coincidence.py +252 -0
  10. wdf/analysis/detector_graph.py +1519 -0
  11. wdf/analysis/detectors.py +52 -0
  12. wdf/analysis/evaluation.py +183 -0
  13. wdf/analysis/event_significance.py +437 -0
  14. wdf/analysis/event_store.py +181 -0
  15. wdf/analysis/gnn.py +550 -0
  16. wdf/analysis/injections.py +247 -0
  17. wdf/analysis/io.py +259 -0
  18. wdf/analysis/metaparameters.py +177 -0
  19. wdf/analysis/modes.py +163 -0
  20. wdf/analysis/network_graph.py +916 -0
  21. wdf/analysis/network_statistic.py +212 -0
  22. wdf/analysis/output_schema.py +37 -0
  23. wdf/analysis/pairs.py +220 -0
  24. wdf/analysis/pixel_graph.py +513 -0
  25. wdf/analysis/plots.py +309 -0
  26. wdf/analysis/reconstruction.py +426 -0
  27. wdf/analysis/report.py +222 -0
  28. wdf/analysis/review_report.py +261 -0
  29. wdf/analysis/ridge.py +177 -0
  30. wdf/analysis/robust_events.py +1185 -0
  31. wdf/analysis/roc.py +88 -0
  32. wdf/analysis/scale.py +383 -0
  33. wdf/analysis/significance.py +258 -0
  34. wdf/analysis/skymap.py +215 -0
  35. wdf/analysis/submission.py +233 -0
  36. wdf/analysis/timing.py +295 -0
  37. wdf/analysis/timing_prior.py +126 -0
  38. wdf/analysis/wavegram_match.py +693 -0
  39. wdf/analysis/wavelets.py +255 -0
  40. wdf/config/Parameters.py +113 -0
  41. wdf/config/__init__.py +0 -0
  42. wdf/filtering.py +71 -0
  43. wdf/mock/__init__.py +12 -0
  44. wdf/mock/dataset.py +1280 -0
  45. wdf/mock/noise.py +57 -0
  46. wdf/mock/real_data.py +218 -0
  47. wdf/mock/waveforms.py +318 -0
  48. wdf/observers/ParameterEstimationObserver.py +67 -0
  49. wdf/observers/SingleEventPrintFileObserver.py +70 -0
  50. wdf/observers/__init__.py +0 -0
  51. wdf/observers/observable.py +62 -0
  52. wdf/observers/observer.py +22 -0
  53. wdf/processes/BandPassDownSampling.py +251 -0
  54. wdf/processes/Coloring.py +58 -0
  55. wdf/processes/DWhitening.py +132 -0
  56. wdf/processes/Whitening.py +116 -0
  57. wdf/processes/__init__.py +0 -0
  58. wdf/processes/ar_lv_io.py +106 -0
  59. wdf/processes/wavelet_energy.py +32 -0
  60. wdf/processes/wdf.py +82 -0
  61. wdf/processes/wdfUnitDSWorker.py +334 -0
  62. wdf/processes/zero_phase_whitening.py +248 -0
  63. wdf/structures/__init__.py +0 -0
  64. wdf/structures/array2SeqView.py +111 -0
  65. wdf/structures/eventPE.py +99 -0
  66. wdflow-1.3.0.dist-info/METADATA +351 -0
  67. wdflow-1.3.0.dist-info/RECORD +69 -0
  68. wdflow-1.3.0.dist-info/WHEEL +4 -0
  69. wdflow-1.3.0.dist-info/licenses/LICENSE +674 -0
wdf/__init__.py ADDED
File without changes
@@ -0,0 +1,116 @@
1
+ """wdf.analysis: trigger clustering, multi-detector coincidence (classical +
2
+ GNN), background/false-alarm-probability and ROC analysis for WDF triggers.
3
+
4
+ Operates on plain pandas DataFrames / saved trigger files -- no dependency on
5
+ `wdf`'s own trigger-generation modules or on py4tsa, so it works standalone.
6
+ """
7
+ from wdf.analysis.clustering import (
8
+ TriggerClusterer,
9
+ WaveletPixelClusterer,
10
+ collect_significant_pixels,
11
+ wavegram_events,
12
+ )
13
+ from wdf.analysis.cluster_coefficients import (
14
+ ClusterCoefficients,
15
+ collect_cluster_coefficients,
16
+ iter_cluster_coefficients,
17
+ score_events_by_reconstruction,
18
+ )
19
+ from wdf.analysis.reconstruction import (
20
+ combined_snr,
21
+ phase_residual,
22
+ reconstruct_clusters,
23
+ stitch,
24
+ waveform_overlap,
25
+ )
26
+ from wdf.analysis.wavelets import wavegram_ridge
27
+ from wdf.analysis.coincidence import CoincidenceFinder as LegacyCoincidenceFinder
28
+ from wdf.analysis.evaluation import (
29
+ compare_statistics,
30
+ efficiency_at_far,
31
+ temporal_split,
32
+ threshold_at_far,
33
+ )
34
+ from wdf.analysis.event_significance import EventCalibration
35
+ from wdf.analysis.injections import unclaimed_candidates
36
+ from wdf.analysis.ridge import (
37
+ RIDGE_FEATURES,
38
+ event_ridge,
39
+ event_ridge_features,
40
+ )
41
+ from wdf.analysis.skymap import credible_area, localise, sky_grid
42
+ from wdf.analysis.modes import (
43
+ DetectionMode,
44
+ compare_modes,
45
+ mode_roc,
46
+ mode_threshold,
47
+ )
48
+ from wdf.analysis.output_schema import ensure_enwdf_column
49
+ from wdf.analysis.robust_events import (
50
+ BackgroundEstimator as RobustBackgroundEstimator,
51
+ ClusterConfig,
52
+ CoincidenceConfig,
53
+ FARConfig,
54
+ IndexedCoincidenceFinder,
55
+ TimeSlideFAR,
56
+ cluster_detector_triggers,
57
+ select_events_for_coincidence,
58
+ )
59
+
60
+ # The canonical names are the current implementations. The two earlier ones
61
+ # differ scientifically, not only in interface: `coincidence.CoincidenceFinder`
62
+ # pairs each event with its nearest neighbour without consuming it, so one
63
+ # event can appear in several candidates, and `significance.BackgroundEstimator`
64
+ # divides by the number of background candidates rather than by the background
65
+ # livetime, which is a tail percentile and not a rate. They stay importable
66
+ # under `Legacy*` for comparison and are not what a caller gets by default.
67
+ CoincidenceFinder = IndexedCoincidenceFinder
68
+ BackgroundEstimator = TimeSlideFAR
69
+
70
+ __all__ = [
71
+ "BackgroundEstimator",
72
+ "LegacyCoincidenceFinder",
73
+ "ClusterConfig",
74
+ "CoincidenceConfig",
75
+ "FARConfig",
76
+ "IndexedCoincidenceFinder",
77
+ "RobustBackgroundEstimator",
78
+ "TimeSlideFAR",
79
+ "TriggerClusterer",
80
+ "WaveletPixelClusterer",
81
+ "collect_significant_pixels",
82
+ "wavegram_events",
83
+ "ClusterCoefficients",
84
+ "collect_cluster_coefficients",
85
+ "iter_cluster_coefficients",
86
+ "score_events_by_reconstruction",
87
+ "combined_snr",
88
+ "reconstruct_clusters",
89
+ "stitch",
90
+ "phase_residual",
91
+ "waveform_overlap",
92
+ "wavegram_ridge",
93
+ "CoincidenceFinder",
94
+ "compare_statistics",
95
+ "efficiency_at_far",
96
+ "temporal_split",
97
+ "threshold_at_far",
98
+ "DetectionMode",
99
+ "compare_modes",
100
+ "mode_roc",
101
+ "mode_threshold",
102
+ "EventCalibration",
103
+ "unclaimed_candidates",
104
+ "event_ridge",
105
+ "event_ridge_features",
106
+ "RIDGE_FEATURES",
107
+ "localise",
108
+ "credible_area",
109
+ "sky_grid",
110
+ "localise",
111
+ "credible_area",
112
+ "sky_grid",
113
+ "ensure_enwdf_column",
114
+ "cluster_detector_triggers",
115
+ "select_events_for_coincidence",
116
+ ]
@@ -0,0 +1,266 @@
1
+ """Ranking a coincidence by how unlike an accidental one it is.
2
+
3
+ The network stage has to say which candidates are worth keeping without being
4
+ told what a signal looks like. Fitting a classifier on injections would make the
5
+ search's own selection depend on the waveform family it was shown, which is what
6
+ an un-modelled search exists not to do.
7
+
8
+ Time slides give the alternative. Shifting one detector against the other by far
9
+ more than the light travel time destroys every real coincidence and leaves the
10
+ detectors' noise intact, so every candidate built from slid data is accidental
11
+ by construction, and there are as many of them as the background needs. A model
12
+ fitted to reconstruct only those learns the shape of an accidental coincidence.
13
+ What it cannot reconstruct is what does not belong to that population, so the
14
+ reconstruction error ranks candidates without any signal ever being shown.
15
+
16
+ No labels are involved and no injection is read. The same time slides that
17
+ measure the false-alarm rate are what the model is fitted on, so the ranking and
18
+ its calibration come from one population.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+ import torch
25
+ from torch import nn
26
+
27
+ from wdf.analysis.gnn import (_IntraMessagePassing, _to_pyg_data,
28
+ usable_device)
29
+
30
+
31
+ class BackgroundAnomalyScorer(nn.Module):
32
+ """A graph autoencoder fitted on accidental coincidences only.
33
+
34
+ Intra-detector message passing gives each event an embedding that carries
35
+ its neighbourhood, as in `GNNCoincidenceScorer`; the two embeddings of a
36
+ candidate pair are then asked to reproduce the pair's own edge features. On
37
+ the population it was fitted to, they can. The score is how badly they fail.
38
+ """
39
+
40
+ def __init__(self, node_dim: int, cross_edge_dim: int, hidden: int = 16,
41
+ seed: int = 0, device: str | None = None):
42
+ """
43
+ :type node_dim: int
44
+ :param node_dim: width of a node's feature vector.
45
+ :type cross_edge_dim: int
46
+ :param cross_edge_dim: number of features on a candidate edge.
47
+ :type hidden: int
48
+ :param hidden: width of the hidden representation.
49
+ :type seed: int
50
+ :param seed: torch seed, for a reproducible initialisation.
51
+ :type device: str or None
52
+ :param device: torch device; CUDA when available if None.
53
+ """
54
+ super().__init__()
55
+ torch.manual_seed(seed)
56
+ self.device = usable_device(device)
57
+ self.encoder = nn.Sequential(nn.Linear(node_dim, hidden), nn.ReLU())
58
+ self.intra_mp = _IntraMessagePassing(hidden)
59
+ self.decoder = nn.Sequential(
60
+ nn.Linear(hidden * 2, hidden), nn.ReLU(), nn.Linear(hidden, cross_edge_dim))
61
+ # The scaling is part of the fitted model. Measured per graph instead,
62
+ # the foreground and the background would be read on two different
63
+ # scales, which is the comparison this exists to make.
64
+ self.register_buffer("feature_mean", torch.zeros(node_dim))
65
+ self.register_buffer("feature_scale", torch.ones(node_dim))
66
+ self.register_buffer("edge_mean", torch.zeros(cross_edge_dim))
67
+ self.register_buffer("edge_scale", torch.ones(cross_edge_dim))
68
+ self.to(self.device)
69
+
70
+ def save(self, path: str) -> None:
71
+ """Write the fitted model, with the widths needed to rebuild it.
72
+
73
+ The feature scaling is written with the weights because it is part of
74
+ the fitted model: a scaling re-measured on whatever graph the model is
75
+ later shown would read the accidental population and the candidates on
76
+ two different scales, which is the comparison it exists to make.
77
+
78
+ :type path: str
79
+ :param path: file to write.
80
+ :return: None
81
+ """
82
+ hidden = int(self.encoder[0].out_features)
83
+ torch.save({
84
+ "state_dict": self.state_dict(),
85
+ "node_dim": int(self.encoder[0].in_features),
86
+ "hidden": hidden,
87
+ "cross_edge_dim": int(self.decoder[-1].out_features),
88
+ }, path)
89
+
90
+ @classmethod
91
+ def load(cls, path: str, device: str | None = None):
92
+ """Rebuild a model written by `save`, in evaluation mode.
93
+
94
+ A model fitted on one stretch of data and read on another is only
95
+ meaningful where the two are the same instrument in the same state: the
96
+ accidental population is a property of the noise, and noise that has
97
+ moved makes the reconstruction error mean something else.
98
+
99
+ :type path: str
100
+ :param path: file to read.
101
+ :type device: str or None
102
+ :param device: torch device; CUDA when available if None.
103
+ :return: BackgroundAnomalyScorer -- ready to `score`. Fitting it
104
+ further continues from these weights and is no longer a fresh
105
+ model.
106
+ :raises KeyError: if the file was not written by `save`.
107
+ """
108
+ blob = torch.load(path, map_location="cpu", weights_only=False)
109
+ model = cls(node_dim=blob["node_dim"], hidden=blob["hidden"],
110
+ cross_edge_dim=blob["cross_edge_dim"], device=device)
111
+ model.load_state_dict(blob["state_dict"])
112
+ model.eval()
113
+ return model
114
+
115
+ def _residuals(self, data) -> torch.Tensor:
116
+ """Per-edge reconstruction error of the edge features."""
117
+ x = (data.x.to(self.device) - self.feature_mean) / self.feature_scale
118
+ h = self.encoder(x)
119
+ h = self.intra_mp(h, data.edge_index.to(self.device),
120
+ data.edge_attr.to(self.device))
121
+ if data.cross_edge_index.numel() == 0:
122
+ return torch.zeros(0, device=self.device)
123
+ i, j = (data.cross_edge_index[0].to(self.device),
124
+ data.cross_edge_index[1].to(self.device))
125
+ target = (data.cross_edge_attr.to(self.device) - self.edge_mean) / self.edge_scale
126
+ # The pair is unordered --- which detector is named first is an accident
127
+ # of the loop that built the graph --- so both orders are reconstructed
128
+ # and the model cannot learn to rely on the order.
129
+ forward = self.decoder(torch.cat([h[i], h[j]], dim=1))
130
+ backward = self.decoder(torch.cat([h[j], h[i]], dim=1))
131
+ return (0.5 * ((forward - target) ** 2 + (backward - target) ** 2)).mean(dim=1)
132
+
133
+ def fit(self, graphs, epochs: int = 100, lr: float = 1e-2):
134
+ """Fit on background graphs only.
135
+
136
+ :param graphs: iterable of `TriggerGraph` built from time-slid events.
137
+ :type epochs: int
138
+ :param epochs: passes over the data.
139
+ :type lr: float
140
+ :param lr: learning rate.
141
+ :return: list[float] -- the loss at each epoch.
142
+ :raises ValueError: if the graphs carry no candidate edges.
143
+ """
144
+ data = [_to_pyg_data(graph) for graph in graphs
145
+ if graph.cross_edges.shape[0] > 0]
146
+ if not data:
147
+ raise ValueError("no accidental coincidences to fit on; the slides "
148
+ "produced no candidate edges")
149
+
150
+ # Accumulated over the graphs rather than concatenated across them. The
151
+ # node features of a slid graph are the same array as the unslid one's
152
+ # --- a time shift changes which events pair, not the events --- so a
153
+ # concatenation is one copy per slide of a matrix that can be gigabytes,
154
+ # and it is allocated only to be reduced to a mean and a deviation.
155
+ def standardise(mean_buffer, scale_buffer, pick):
156
+ total = None
157
+ squares = None
158
+ count = 0
159
+ for one in data:
160
+ values = pick(one).to(dtype=torch.float64)
161
+ if not values.numel():
162
+ continue
163
+ summed = values.sum(dim=0)
164
+ total = summed if total is None else total + summed
165
+ squared = (values * values).sum(dim=0)
166
+ squares = squared if squares is None else squares + squared
167
+ count += values.shape[0]
168
+ if not count:
169
+ return
170
+ mean = total / count
171
+ variance = torch.clamp(squares / count - mean * mean, min=0.0)
172
+ mean_buffer.copy_(mean.to(mean_buffer.dtype))
173
+ scale_buffer.copy_(variance.sqrt().clamp_min(1e-6).to(
174
+ scale_buffer.dtype))
175
+
176
+ standardise(self.feature_mean, self.feature_scale, lambda d: d.x)
177
+ standardise(self.edge_mean, self.edge_scale, lambda d: d.cross_edge_attr)
178
+
179
+ # The gradient is accumulated one graph at a time. Computing every
180
+ # graph's residuals before the backward pass keeps every graph's
181
+ # activations alive at once, which for a set of slides over a long
182
+ # segment is gigabytes; taking the backward pass per graph holds one.
183
+ # The sum of the per-graph losses weighted by their edge counts is the
184
+ # loss over all the edges, so the two agree.
185
+ edges = [int(d.cross_edge_attr.shape[0]) for d in data]
186
+ total_edges = float(sum(edges)) or 1.0
187
+
188
+ # A shared card can have less free memory than one graph's features need,
189
+ # and that is not a reason to lose the fit: every stage here runs on the
190
+ # processor in minutes. The fallback is taken once, on the first
191
+ # allocation that fails, rather than guessed at beforehand.
192
+ def out_of_memory(reason):
193
+ return "out of memory" in str(reason).lower()
194
+
195
+ optimiser = torch.optim.Adam(self.parameters(), lr=lr)
196
+ history = []
197
+ self.train()
198
+ for _ in range(int(epochs)):
199
+ optimiser.zero_grad()
200
+ epoch_loss = 0.0
201
+ for one, count in zip(data, edges):
202
+ if not count:
203
+ continue
204
+ try:
205
+ loss = self._residuals(one).sum() / total_edges
206
+ loss.backward()
207
+ except (RuntimeError, torch.OutOfMemoryError) as reason:
208
+ if self.device == "cpu" or not out_of_memory(reason):
209
+ raise
210
+ import warnings
211
+
212
+ warnings.warn(
213
+ f"the graphics device could not hold the fit "
214
+ f"({reason}); continuing on the processor",
215
+ RuntimeWarning)
216
+ torch.cuda.empty_cache()
217
+ self.device = "cpu"
218
+ self.to("cpu")
219
+ optimiser = torch.optim.Adam(self.parameters(), lr=lr)
220
+ optimiser.zero_grad()
221
+ epoch_loss = 0.0
222
+ for again, count_again in zip(data, edges):
223
+ if not count_again:
224
+ continue
225
+ loss = self._residuals(again).sum() / total_edges
226
+ loss.backward()
227
+ epoch_loss += float(loss.detach().cpu())
228
+ break
229
+ epoch_loss += float(loss.detach().cpu())
230
+ optimiser.step()
231
+ history.append(epoch_loss)
232
+ return history
233
+
234
+ def release(self):
235
+ """Give the graphics device its memory back.
236
+
237
+ Two things hold it. The tensors this object owns stay alive as long as
238
+ it does, and the allocator keeps what it has freed in a cache rather
239
+ than returning it, so a device can read as full when nothing is using
240
+ it. Both are released here, which matters on a shared card and between
241
+ two fits in one session.
242
+
243
+ :return: None
244
+ """
245
+ self.to("cpu")
246
+ if torch.cuda.is_available():
247
+ torch.cuda.empty_cache()
248
+
249
+
250
+ @torch.no_grad()
251
+ def score(self, graph) -> pd.DataFrame:
252
+ """The candidate table with `anomaly_score` added.
253
+
254
+ The score is the reconstruction error, so it grows with how unlike an
255
+ accidental coincidence the candidate is. It is ranked and thresholded
256
+ exactly as any other statistic, against the same background.
257
+
258
+ :param graph: a `TriggerGraph`.
259
+ :return: pandas.DataFrame -- one row per candidate edge.
260
+ """
261
+ self.eval()
262
+ table = graph.candidate_table()
263
+ if not len(table):
264
+ return table
265
+ residual = self._residuals(_to_pyg_data(graph)).cpu().numpy()
266
+ return table.assign(anomaly_score=np.asarray(residual, dtype=float))
@@ -0,0 +1,195 @@
1
+ """Order statistics of a slid population, kept without the population.
2
+
3
+ A time-slide background is read for two things: the value a rate corresponds
4
+ to, and how far into the tail a candidate sits. Both are order statistics, and
5
+ an order statistic does not need the sample to be held --- only the part of it
6
+ that can still reach the top. A slide's candidates are therefore reduced as
7
+ they are formed and released, and what stays is bounded by the number of
8
+ values a rate can ask for rather than by the number of slides run.
9
+
10
+ Two structures do it. The largest `keep` values of every ranking are held
11
+ exactly, so a threshold at any rate whose count falls inside them is the same
12
+ number the whole population would have given. A histogram over the rest
13
+ answers the looser rates, where the count exceeds `keep`, at the resolution of
14
+ its bins. Both say which of the two they came from, so a reader is never left
15
+ to guess whether a threshold is exact.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+
22
+ __all__ = ["BackgroundAccumulator"]
23
+
24
+
25
+ class BackgroundAccumulator:
26
+ """Accumulate a slid population's order statistics slide by slide.
27
+
28
+ :type statistics: sequence of str
29
+ :param statistics: the ranking columns to accumulate. A column absent from
30
+ a slide's table contributes nothing rather than raising: a background
31
+ that never carried a ranking is empty for it, which
32
+ :meth:`threshold` reports as `nan`.
33
+ :type keep: int
34
+ :param keep: how many of the largest values of each ranking to hold
35
+ exactly. A threshold whose count is at most this is exact; above it the
36
+ histogram answers. Memory is `keep` floats per ranking, plus the same
37
+ again while a slide is merged.
38
+ :type bins: int
39
+ :param bins: bins of the histogram that covers the values below the kept
40
+ tail.
41
+ :type extras: sequence of str
42
+ :param extras: columns carried alongside the kept tail, for what the tail
43
+ is made of --- the slide it came from, the events it paired. They are
44
+ held only for the rows that are kept.
45
+ """
46
+
47
+ def __init__(self, statistics, keep: int = 1_000_000, bins: int = 4096,
48
+ extras=()):
49
+ self.statistics = [str(s) for s in statistics]
50
+ self.keep = int(keep)
51
+ self.n_bins = int(bins)
52
+ self.extras = [str(e) for e in extras]
53
+ self.n_slides = 0
54
+ self.livetime_s = 0.0
55
+ self.total = 0
56
+ self._kept = {s: np.empty(0, dtype=float) for s in self.statistics}
57
+ self._kept_extras = {s: {e: np.empty(0) for e in self.extras}
58
+ for s in self.statistics}
59
+ self._edges = {}
60
+ self._counts = {}
61
+ self._below = {s: 0 for s in self.statistics}
62
+
63
+ def add(self, candidates, livetime_s: float = 0.0) -> None:
64
+ """Absorb one slide's candidates and let them go.
65
+
66
+ :type candidates: pandas.DataFrame
67
+ :param candidates: the accidental candidates of one displacement.
68
+ :type livetime_s: float
69
+ :param livetime_s: the livetime that displacement credits, seconds.
70
+ """
71
+ self.n_slides += 1
72
+ self.livetime_s += float(livetime_s)
73
+ if candidates is None or not len(candidates):
74
+ return
75
+ self.total += len(candidates)
76
+ for statistic in self.statistics:
77
+ if statistic not in candidates:
78
+ continue
79
+ values = np.asarray(candidates[statistic], dtype=float)
80
+ finite = np.isfinite(values)
81
+ values = values[finite]
82
+ if not values.size:
83
+ continue
84
+ extras = {e: np.asarray(candidates[e])[finite]
85
+ for e in self.extras if e in candidates}
86
+ self._absorb(statistic, values, extras)
87
+
88
+ def _absorb(self, statistic, values, extras) -> None:
89
+ """Merge one slide's values into the kept tail and the histogram."""
90
+ kept = np.concatenate([self._kept[statistic], values])
91
+ held = {e: np.concatenate([self._kept_extras[statistic].get(
92
+ e, np.empty(0, dtype=np.asarray(v).dtype)), v])
93
+ for e, v in extras.items()}
94
+ if kept.size > self.keep:
95
+ # Partition rather than sort: the tail is what is kept and its
96
+ # order does not matter until a threshold is read from it.
97
+ cut = kept.size - self.keep
98
+ order = np.argpartition(kept, cut)
99
+ dropped, keep_index = order[:cut], order[cut:]
100
+ self._histogram(statistic, kept[dropped])
101
+ kept = kept[keep_index]
102
+ held = {e: v[keep_index] for e, v in held.items()}
103
+ self._kept[statistic] = kept
104
+ self._kept_extras[statistic] = held
105
+
106
+ def _histogram(self, statistic, values) -> None:
107
+ """Bin the values that fall out of the kept tail."""
108
+ if statistic not in self._edges:
109
+ lo = float(np.min(values))
110
+ hi = float(np.max(values))
111
+ if not np.isfinite(lo) or not np.isfinite(hi) or hi <= lo:
112
+ hi = lo + 1.0
113
+ self._edges[statistic] = np.linspace(lo, hi, self.n_bins + 1)
114
+ self._counts[statistic] = np.zeros(self.n_bins, dtype=np.int64)
115
+ edges = self._edges[statistic]
116
+ below = int(np.sum(values < edges[0]))
117
+ self._below[statistic] += below
118
+ inside = values[values >= edges[0]]
119
+ if inside.size:
120
+ index = np.clip(np.searchsorted(edges, inside, side="right") - 1,
121
+ 0, self.n_bins - 1)
122
+ np.add.at(self._counts[statistic], index, 1)
123
+
124
+ @property
125
+ def livetime_days(self) -> float:
126
+ """The livetime the slides credited, days."""
127
+ return self.livetime_s / 86400.0
128
+
129
+ def threshold(self, statistic: str, far_per_day: float,
130
+ livetime_days: float | None = None):
131
+ """The value a rate corresponds to, and whether it is exact.
132
+
133
+ The threshold is the k-th largest accidental with k the whole part of
134
+ the rate times the livetime, which is the same rule
135
+ :func:`wdf.analysis.evaluation.threshold_at_far` applies to a held
136
+ population.
137
+
138
+ :type statistic: str
139
+ :param statistic: the ranking to read.
140
+ :type far_per_day: float
141
+ :param far_per_day: the rate, per day.
142
+ :type livetime_days: float or None
143
+ :param livetime_days: the accidental livetime; the accumulated one when
144
+ not given.
145
+ :return: tuple[float, bool] -- the threshold and whether it came from
146
+ the exactly kept tail. `nan` when the livetime cannot resolve the
147
+ rate or the ranking was never seen.
148
+ """
149
+ livetime = (self.livetime_days if livetime_days is None
150
+ else float(livetime_days))
151
+ k = int(far_per_day * livetime)
152
+ kept = self._kept.get(statistic, np.empty(0))
153
+ if k < 1 or not kept.size:
154
+ return float("nan"), False
155
+ if k <= kept.size:
156
+ return float(np.sort(kept)[-k]), True
157
+ counts = self._counts.get(statistic)
158
+ if counts is None:
159
+ return float("nan"), False
160
+ # The kept tail holds the loudest; the histogram continues below it.
161
+ remaining = k - kept.size
162
+ cumulative = np.cumsum(counts[::-1])
163
+ index = int(np.searchsorted(cumulative, remaining))
164
+ edges = self._edges[statistic]
165
+ if index >= counts.size:
166
+ return float(edges[0]), False
167
+ return float(edges[counts.size - index - 1]), False
168
+
169
+ def tail(self, statistic: str) -> pd.DataFrame:
170
+ """The kept tail of one ranking, with whatever was carried beside it.
171
+
172
+ :param statistic: the ranking to read.
173
+ :return: pandas.DataFrame -- one row per kept accidental, the ranking
174
+ in a column of its name.
175
+ """
176
+ kept = self._kept.get(statistic, np.empty(0))
177
+ frame = pd.DataFrame({statistic: kept})
178
+ for name, values in self._kept_extras.get(statistic, {}).items():
179
+ frame[name] = values
180
+ return frame.sort_values(statistic, ascending=False,
181
+ ignore_index=True)
182
+
183
+ def summary(self) -> pd.DataFrame:
184
+ """What was accumulated, one row per ranking."""
185
+ rows = []
186
+ for statistic in self.statistics:
187
+ kept = self._kept.get(statistic, np.empty(0))
188
+ rows.append(dict(statistic=statistic, accidentals=self.total,
189
+ kept=int(kept.size),
190
+ binned=int(self._counts.get(
191
+ statistic, np.zeros(1)).sum()),
192
+ below_bins=int(self._below.get(statistic, 0)),
193
+ slides=self.n_slides,
194
+ livetime_days=self.livetime_days))
195
+ return pd.DataFrame(rows)