1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
#[cfg(not(feature = "std"))]
use alloc::{vec, vec::Vec};
use rand::prelude::*;
use rand::rngs::Xoshiro256PlusPlus;
use super::{
RcfTree, blend_with_cut_probability, child_for_query, consider_impute_candidate, nn_threshold,
should_descend_primary, should_descend_secondary, split_children,
};
use crate::rcf::{
forest::NeighborCandidate,
node_arena::Node,
point_store::PointStore,
score::{Attribution, ScoreMode},
};
impl RcfTree {
// -----------------------------------------------------------------------
// Score traversal
// -----------------------------------------------------------------------
/// Compute the anomaly score for `query` using the given `mode`.
///
/// Returns the normalized anomaly score as an `f64`.
pub fn raw_score(&self, query: &[f32], point_store: &PointStore, mode: &ScoreMode) -> f64 {
if self.is_effectively_empty() {
return 0.0;
}
let raw = self.score_recursive(self.root, query, point_store, 0, mode);
mode.normalize(raw, self.tree_mass)
}
fn score_recursive(
&self,
node_id: usize,
query: &[f32],
point_store: &PointStore,
depth: usize,
mode: &ScoreMode,
) -> f64 {
match self.arena.get(node_id) {
Node::Leaf { point_idx, mass } => {
if point_store.is_equal(query, *point_idx) {
mode.damp(*mass, self.tree_mass) * mode.score_seen(depth, *mass)
} else {
mode.score_unseen(depth, *mass)
}
}
Node::Internal {
left,
right,
cut_dim,
cut_val,
mass,
bbox,
} => {
// Shared branch-choice helper keeps traversal expressions uniform.
let child = child_for_query(query, *cut_dim, *cut_val, *left, *right);
let child_score = self.score_recursive(child, query, point_store, depth + 1, mode);
let prob = bbox.probability_of_cut(query);
blend_with_cut_probability(prob, child_score, mode.score_unseen(depth, *mass))
}
}
}
// -----------------------------------------------------------------------
// Attribution traversal
// -----------------------------------------------------------------------
/// Compute per-dimension anomaly attribution.
///
/// Returns a `Vec<Attribution>` of length `dims`.
pub fn attribution(&self, query: &[f32], mode: &ScoreMode) -> Vec<Attribution> {
let mut attr = vec![Attribution::default(); self.dims];
if self.is_effectively_empty() {
return attr;
}
let norm = mode.normalize(1.0, self.tree_mass);
self.attribution_recursive(self.root, query, 0, mode, 1.0, norm, &mut attr);
attr
}
/// Accumulate attribution contributions weighted by the path probability.
///
/// `weight` = product of `(1 - prob)` for all ancestors, starts at 1.0.
/// `norm` = mode normalizer pre-computed as `normalize(1.0, tree_mass)`.
#[allow(clippy::too_many_arguments)]
fn attribution_recursive(
&self,
node_id: usize,
query: &[f32],
depth: usize,
mode: &ScoreMode,
weight: f64,
norm: f64,
attr: &mut Vec<Attribution>,
) {
match self.arena.get(node_id) {
Node::Leaf { .. } => {
// Leaf contribution is not attributed to a specific dimension;
// it represents the expected score of a point already in the tree.
}
Node::Internal {
left,
right,
cut_dim,
cut_val,
mass,
bbox,
} => {
let child = child_for_query(query, *cut_dim, *cut_val, *left, *right);
let prob = bbox.probability_of_cut(query);
if prob > 0.0 {
let base = mode.score_unseen(depth, *mass);
// contribution = weight * prob * base * norm
let contribution = weight * prob * base * norm;
if query[*cut_dim] <= *cut_val {
attr[*cut_dim].above += contribution;
} else {
attr[*cut_dim].below += contribution;
}
// Recurse with reduced weight.
self.attribution_recursive(
child,
query,
depth + 1,
mode,
weight * (1.0 - prob),
norm,
attr,
);
} else {
// No probability of isolation at this node; continue descent.
self.attribution_recursive(child, query, depth + 1, mode, weight, norm, attr);
}
}
}
}
// -----------------------------------------------------------------------
// Density traversal
// -----------------------------------------------------------------------
/// Density estimate at `query` (uses the displacement score function).
pub fn density(&self, query: &[f32], point_store: &PointStore) -> f64 {
if self.is_effectively_empty() {
return 0.0;
}
self.density_recursive(self.root, query, point_store)
}
fn density_recursive(&self, node_id: usize, query: &[f32], point_store: &PointStore) -> f64 {
// Density uses score_unseen_displacement = y (tree mass), normalizer = identity.
match self.arena.get(node_id) {
Node::Leaf { point_idx, mass } => {
if point_store.is_equal(query, *point_idx) {
*mass as f64
} else {
0.0
}
}
Node::Internal {
left,
right,
cut_dim,
cut_val,
mass,
bbox,
} => {
let child = child_for_query(query, *cut_dim, *cut_val, *left, *right);
let child_density = self.density_recursive(child, query, point_store);
let prob = bbox.probability_of_cut(query);
// density mode: score_unseen(depth, mass) = mass (weighted by depth-inverse)
blend_with_cut_probability(prob, child_density, *mass as f64)
}
}
}
// -----------------------------------------------------------------------
// Near-neighbor traversal
// -----------------------------------------------------------------------
/// Collect candidate neighbours from this tree.
///
/// Candidates are leaf points that would receive a high isolation score
/// relative to `query`. Callers should deduplicate/merge across trees.
pub fn near_neighbors(
&self,
query: &[f32],
point_store: &PointStore,
mode: &ScoreMode,
percentile: usize,
) -> Vec<NeighborCandidate> {
let mut results = Vec::new();
self.near_neighbors_into(query, point_store, mode, percentile, &mut results);
results
}
pub(crate) fn near_neighbors_into(
&self,
query: &[f32],
point_store: &PointStore,
mode: &ScoreMode,
percentile: usize,
results: &mut Vec<NeighborCandidate>,
) {
if self.is_effectively_empty() {
return;
}
let threshold = nn_threshold(percentile);
self.nn_recursive(self.root, query, point_store, 0, mode, threshold, results);
}
#[allow(clippy::too_many_arguments)]
fn nn_recursive(
&self,
node_id: usize,
query: &[f32],
point_store: &PointStore,
depth: usize,
mode: &ScoreMode,
threshold: f64,
results: &mut Vec<NeighborCandidate>,
) {
match self.arena.get(node_id) {
Node::Leaf { point_idx, mass } => {
let score = mode.normalize(mode.score_unseen(depth, *mass), self.tree_mass);
let dist = point_store.l1_distance(query, *point_idx);
results.push(NeighborCandidate {
score,
point_idx: *point_idx,
distance: dist,
});
}
Node::Internal {
left,
right,
cut_dim,
cut_val,
mass: _,
bbox,
} => {
let prob = bbox.probability_of_cut(query);
// Only descend if this subtree is a viable candidate
if should_descend_primary(prob, depth, threshold) {
let (primary, secondary) =
split_children(query[*cut_dim], *cut_val, *left, *right);
self.nn_recursive(
primary,
query,
point_store,
depth + 1,
mode,
threshold,
results,
);
if should_descend_secondary(prob) {
self.nn_recursive(
secondary,
query,
point_store,
depth + 1,
mode,
threshold,
results,
);
}
}
}
}
}
// -----------------------------------------------------------------------
// Conditional field / Imputation traversal
// -----------------------------------------------------------------------
/// Find the leaf that best matches `query` with the given `missing_dims`.
///
/// Returns the best matching candidate. Missing dimensions are
/// treated as marginalized out (both children are explored when the cut
/// falls on a missing dimension).
pub fn conditional_field(
&self,
query: &[f32],
missing: &[bool],
point_store: &PointStore,
centrality: f64,
seed: u64,
) -> Option<NeighborCandidate> {
if self.is_effectively_empty() {
return None;
}
let mut rng = Xoshiro256PlusPlus::seed_from_u64(seed);
self.impute_recursive(
self.root,
query,
missing,
point_store,
centrality,
&mut rng,
None,
)
}
#[allow(clippy::too_many_arguments)]
fn impute_recursive(
&self,
node_id: usize,
query: &[f32],
missing: &[bool],
point_store: &PointStore,
centrality: f64,
rng: &mut Xoshiro256PlusPlus,
best: Option<NeighborCandidate>,
) -> Option<NeighborCandidate> {
match self.arena.get(node_id) {
Node::Leaf { point_idx, mass } => {
let dist = point_store.l1_distance_ignore_missing(query, *point_idx, missing);
let score = *mass as f64;
let candidate = NeighborCandidate {
score,
point_idx: *point_idx,
distance: dist,
};
consider_impute_candidate(best, candidate, centrality, rng)
}
Node::Internal {
left,
right,
cut_dim,
cut_val,
..
} => {
if missing[*cut_dim] {
// Explore both branches while carrying forward the current best.
let best = self.impute_recursive(
*left,
query,
missing,
point_store,
centrality,
rng,
best,
);
self.impute_recursive(
*right,
query,
missing,
point_store,
centrality,
rng,
best,
)
} else {
let child = child_for_query(query, *cut_dim, *cut_val, *left, *right);
self.impute_recursive(child, query, missing, point_store, centrality, rng, best)
}
}
}
}
}