blib/lib/Algorithm/Classifier/IsolationForest.pm

filter: Statementstmt 90.5% 1282 / 1416 Branchbran 81.4% 588 / 722 Conditioncond 72.3% 314 / 434 MC/DCmcdc 54.6% 136 / 249 Subroutinesub 96.4% 108 / 112 Podpod 100% 31 / 31 totaltotal 82.9% 2459 / 2964 CC 557 SCAR 27.6
CC
557
Cov
85%
__ANON__
56.0
validate_prototype
42.8
new
41.1
CRAP 15.8
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/predict.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/proto.pm »
1 package Algorithm::Classifier::IsolationForest;
2  
3 132 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 132 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 132 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 132 ▶use Config ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 132 ▶use List::Util qw(min);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 132 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 132 ▶use POSIX qw(ceil);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 132 ▶use JSON::PP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 132 ▶use File::Slurp qw(read_file write_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 132 our $VERSION = '0.7.0';
14  
15 132 ▶use constant EULER => 0.5772156649015329;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 # Narrowed to C double precision so _randn() multiplies by the exact
18 # constant _c_randn() uses. A no-op on nvsize == 8 perls.
19 132 ▶use constant TWO_PI => unpack( 'd', pack 'd', 6.283185307179586 );
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 # Node-type tags stored in index 0 of every tree node arrayref.
22 # 0 is falsy, so while ($node->[0]) acts as while (!leaf).
23 132 ▶use constant _NODE_LEAF => 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 132 ▶use constant _NODE_AXIS => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 132 ▶use constant _NODE_OBLIQUE => 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 # The Inline::C tree builder computes everything in C doubles. On a perl
28 # whose NV is wider than a double (-Duselongdouble / -Dusequadmath) the
29 # pure-Perl builder keeps extra low bits at every step, so the two
30 # backends would stop producing bit-identical trees for the same seed
31 # (the parity t/03-fit-determinism.t checks). _NV_IS_DOUBLE guards
32 # narrowing statements wherever the pure-Perl builder computes a value
33 # that gets STORED in a tree (split points, hyperplane coefficients and
34 # offsets, impute fills), rounding at the same points the C builder
35 # rounds. It is compile-time true on nvsize == 8 perls, so there the
36 # guarded statements are optimised away and cost nothing.
37 #
38 # The row-partition loops (v < split, dot <= b) are deliberately NOT
39 # narrowed: with both operands already double-exact an axis comparison
40 # is identical anyway, and an oblique dot product accumulated in a wider
41 # NV flips a comparison only when |dot - b| falls inside the NV-vs-double
42 # rounding gap (~1e-19 relative) -- negligible, and those are the hot
43 # loops.
44 132 ▶use constant _NV_IS_DOUBLE => $Config::Config{nvsize} == 8;
Subroutine BEGIN: called CC=1 SCAR=0.0
45  
46 # Round an NV to C double precision. Only ever reached on wide-NV
47 # perls -- see _NV_IS_DOUBLE.
48 #
49 # Args:
50 # $nv :: any number. On a -Duselongdouble / -Dusequadmath perl it may
51 # carry more precision than a C double can hold.
52 #
53 # Returns: the same number rounded to the nearest IEEE 754 double. A no-op
54 # for a value that is already double-exact.
55 #
56 # Example:
57 # _to_double( $lo + rand() * ( $hi - $lo ) ); # what the C builder stores
58 0 ▶sub _to_double { unpack 'd', pack 'd', $_[0] }
Subroutine _to_double: not called CC=1 SCAR=6.9
59  
60 # ---------------------------------------------------------------------------
61 # Optional Inline::C accelerator for the scoring hot path.
62 #
63 # pack_input_xs(data_sv, out_sv, n_pts, n_feats, miss_mode, fill_sv)
64 # Walks the Perl arrayref-of-arrayrefs and writes a packed double buffer
65 # into out_sv. Replaces the dominant per-call Perl map-pack loop.
66 # miss_mode selects how an undef cell is packed: 0 => 0.0, 1 => the
67 # per-feature fill from fill_sv (impute), 2 => NaN (nan strategy).
68 #
69 # score_all_xs(nodes_av, idx_av, val_av, x_sv, sm_sv,
70 # n_pts, n_feats, n_trees, use_openmp)
71 # Sums path lengths for all n_pts query points across all n_trees trees
72 # in one call. Outer loop over points is OpenMP-parallel when the
73 # module was built with OpenMP (each iteration writes to a unique sm[i],
74 # so no synchronisation is needed). Tree pointers are extracted from
75 # the AVs before the parallel region; the parallel region touches only
76 # raw int / double buffers.
77 #
78 # vote_all_xs(nodes_av, idx_av, val_av, x_sv, sm_sv,
79 # n_pts, n_feats, n_trees, depth_cut, min_votes, use_openmp)
80 # Majority-voting (voting => 'majority') counterpart of score_all_xs:
81 # instead of summing path lengths it counts, per point, how many trees
82 # "vote anomalous" (path length <= depth_cut). min_votes == 0 writes
83 # the full vote count into sm[i]; min_votes > 0 writes a 0.0/1.0 label
84 # with per-point early exit once the majority outcome is decided --
85 # the MVIForest scoring loop. See the function's own comment.
86 #
87 # Node layout (6 doubles per node, "IF_NZ = 6"):
88 # leaf: [0, size, c(size), 0, 0, 0]
89 # axis: [1, attr, split, li, ri, 0]
90 # oblique: [2, coff, nf, li, ri, b]
91 #
92 # c(size) is the expected-path-length adjustment for a leaf holding
93 # `size` points, precomputed by _pack_tree (it involves a log(); doing
94 # it at pack time keeps transcendentals out of the per-point per-tree
95 # scoring loop). The fit-time TreeBuf writer leaves that slot 0 --
96 # its buffers are unpacked into Perl trees and re-packed by
97 # _pack_tree before score_all_xs ever sees them.
98 #
99 # Coefficient storage uses a Structure-of-Arrays layout: one int32 array
100 # per tree (feature indices, packed with 'l*') and one double array per
101 # tree (coefficients, packed with 'd*'). Both are indexed by `coff` --
102 # the same offset addresses paired entries in the two arrays. Splitting
103 # them this way halves index bandwidth, removes the per-element
104 # (int)<double> cast inside the SIMD loop, and lets the value loads be
105 # contiguous so the compiler emits a clean FMA chain over val[k] with
106 # the feature gather on xi[idx[k]] kept separate.
107 #
108 # Dense-pack fast path: when an oblique node uses every feature (the
109 # common case in extended mode with extension_level == n_features - 1),
110 # _pack_tree writes its coefficients in feature order so val[k] is the
111 # coefficient for feature k. score_all_xs detects this via `nf ==
112 # n_feats` and uses a no-gather dot product (dot += val[k] * xi[k])
113 # that vectorizes cleanly with FMA -- substantially faster than the
114 # sparse gather path on high-feature-count models.
115 # x: row-major doubles, n_pts rows of n_feats each.
116 # sums: out double array of length n_pts; score_all_xs writes once per i.
117 #
118 # OpenMP is enabled at module load when the toolchain accepts -fopenmp and
119 # libgomp is linkable; otherwise the same C code compiles to a serial loop
120 # (the #pragma is silently ignored without _OPENMP defined).
121 # ---------------------------------------------------------------------------
122 132 our $HAS_C = 0;
123 132 our $HAS_OPENMP = 0;
124 132 our $HAS_SIMD = 0;
125 132 our $OPT_LEVEL = ''; # the actual -O.../-march=... flags used to build, if any
126 132 our $C_SOURCE = ''; # 'prebuilt' (object installed at `make` time) or
127 # 'runtime' (compiled at first load into _Inline/);
128 # '' when $HAS_C is 0
129 {
130 132 my $C_CODE = <<'__INLINE_C__';
131 #include <math.h>
132 #include <string.h>
133 #include <stdint.h>
134 #ifdef _OPENMP
135 #include <omp.h>
136 #endif
137 #define IF_NZ 6
138  
139 /* Data prefetch hint; a no-op on compilers without __builtin_prefetch.
140 * Purely a performance hint -- never affects results. */
141 #if defined(__GNUC__) || defined(__clang__)
142 #define IF_PREFETCH(p) __builtin_prefetch(p)
143 #else
144 #define IF_PREFETCH(p)
145 #endif
146  
147 int has_openmp_xs(){
148 #ifdef _OPENMP
149 return 1;
150 #else
151 return 0;
152 #endif
153 }
154  
155 /* SIMD on the extended-mode oblique dot product is enabled via
156 * `#pragma omp simd`, which OpenMP 4.0 (_OPENMP == 201307) introduced.
157 * Anything older silently ignores the pragma -- the loop still runs,
158 * just not auto-vectorised. So "simd available" really means the
159 * compiler is going to honour the pragma we put on that loop. */
160 int has_simd_xs(){
161 #if defined(_OPENMP) && _OPENMP >= 201307
162 return 1;
163 #else
164 return 0;
165 #endif
166 }
167  
168 /* pack_input_xs(data_sv, out_sv, n_pts, n_feats, miss_mode, fill_sv)
169 *
170 * Walks a Perl arrayref-of-arrayrefs (n_pts rows of n_feats doubles each)
171 * directly in C and writes the packed double buffer into out_sv (which the
172 * caller pre-allocates with "\0" x (n_pts*n_feats*8)). Replaces
173 *
174 * pack('d*', map { my $r=$_; map { $r->[$_] // 0 } 0..$nf-1 } @$data)
175 *
176 * which was the dominant per-call overhead for high feature counts.
177 *
178 * miss_mode selects what an undef cell (or missing row) becomes:
179 * 0 => 0.0 (the 'die'/'zero' missing strategies)
180 * 1 => fill[k] (the 'impute' strategy; fill_sv is a packed
181 * double buffer of n_feats per-feature fill values)
182 * 2 => NaN (the 'nan' strategy; the C scorer's `<` / `<=`
183 * comparisons are both false for NaN, so a point
184 * missing the split feature falls to the right
185 * child -- matching how fit() routes it)
186 * fill_sv is only dereferenced when miss_mode == 1. */
187 void pack_input_xs(SV* data_sv, SV* out_sv, int n_pts, int n_feats,
188 int miss_mode, SV* fill_sv){
189 STRLEN tl;
190 double* out;
191 const double* fill = NULL;
192 double missval;
193 AV* outer;
194 int i, k;
195  
196 if (!SvROK(data_sv) || SvTYPE(SvRV(data_sv)) != SVt_PVAV) {
197 croak("pack_input_xs: data must be an arrayref");
198 }
199 outer = (AV*)SvRV(data_sv);
200 out = (double*)SvPVbyte_force(out_sv, tl);
201  
202 if (miss_mode == 1) {
203 STRLEN fl;
204 fill = (const double*)SvPVbyte(fill_sv, fl);
205 }
206 missval = (miss_mode == 2) ? NAN : 0.0;
207  
208 for (i = 0; i < n_pts; i++) {
209 SV** row_pp = av_fetch(outer, i, 0);
210 double* dst = out + (size_t)i * (size_t)n_feats;
211 if (!row_pp || !*row_pp || !SvROK(*row_pp) ||
212 SvTYPE(SvRV(*row_pp)) != SVt_PVAV) {
213 for (k = 0; k < n_feats; k++)
214 dst[k] = (miss_mode == 1) ? fill[k] : missval;
215 continue;
216 }
217 {
218 AV* row = (AV*)SvRV(*row_pp);
219 for (k = 0; k < n_feats; k++) {
220 SV** v = av_fetch(row, k, 0);
221 if (v && *v && SvOK(*v)) {
222 dst[k] = SvNV(*v);
223 } else {
224 dst[k] = (miss_mode == 1) ? fill[k] : missval;
225 }
226 }
227 }
228 }
229 }
230  
231 /* first_missing_xs(data_sv, n_pts, n_feats, out_rv)
232 *
233 * C replacement for _prepare_fit_data's missing => 'die' scan, which is a
234 * pure-Perl double loop over every cell of the training set and, being the
235 * default strategy, the single largest fixed cost of a fit on wide or long
236 * data. Walks the same arrayref-of-arrayrefs pack_input_xs walks, in the
237 * same row-major order, and stops at the first cell that is undef or
238 * absent, pushing (row, col) into out_rv. Leaves out_rv empty when every
239 * cell is present.
240 *
241 * A row that is not an arrayref counts as missing at column 0 -- the same
242 * reading pack_input_xs gives it (it fills such a row entirely from the
243 * missing branch), so the two agree on what "present" means. */
244 void first_missing_xs(SV* data_sv, int n_pts, int n_feats, SV* out_rv){
245 dTHX;
246 AV *outer, *out;
247 int i, k;
248  
249 if (!SvROK(data_sv) || SvTYPE(SvRV(data_sv)) != SVt_PVAV) {
250 croak("first_missing_xs: data must be an arrayref");
251 }
252 if (!SvROK(out_rv) || SvTYPE(SvRV(out_rv)) != SVt_PVAV) {
253 croak("first_missing_xs: out must be an arrayref");
254 }
255 outer = (AV*)SvRV(data_sv);
256 out = (AV*)SvRV(out_rv);
257 av_clear(out);
258  
259 for (i = 0; i < n_pts; i++) {
260 SV** row_pp = av_fetch(outer, i, 0);
261 AV* row;
262 if (!row_pp || !*row_pp || !SvROK(*row_pp) ||
263 SvTYPE(SvRV(*row_pp)) != SVt_PVAV) {
264 av_push(out, newSViv(i));
265 av_push(out, newSViv(0));
266 return;
267 }
268 row = (AV*)SvRV(*row_pp);
269 for (k = 0; k < n_feats; k++) {
270 SV** v = av_fetch(row, k, 0);
271 if (!v || !*v || !SvOK(*v)) {
272 av_push(out, newSViv(i));
273 av_push(out, newSViv(k));
274 return;
275 }
276 }
277 }
278 }
279  
280 /* finalize_scores_xs(sm_sv, n_pts, inv, out_rv)
281 *
282 * Fills the pre-allocated arrayref out_rv with exp(-sm[i] * inv) for
283 * i in 0..n_pts-1. Replaces the trailing
284 *
285 * my @sums = unpack('d*', $sums_packed);
286 * return [ map { exp(-$_ * $inv) } @sums ];
287 *
288 * which allocated ~2*n_pts intermediate Perl SVs per scoring call. */
289 void finalize_scores_xs(SV* sm_sv, int n_pts, double inv, SV* out_rv){
290 STRLEN tl;
291 const double* sm;
292 AV* out;
293 int i;
294  
295 if (!SvROK(out_rv) || SvTYPE(SvRV(out_rv)) != SVt_PVAV) {
296 croak("finalize_scores_xs: out must be an arrayref");
297 }
298 sm = (const double*)SvPVbyte(sm_sv, tl);
299 out = (AV*)SvRV(out_rv);
300 av_clear(out);
301 if (n_pts > 0) av_extend(out, n_pts - 1);
302 for (i = 0; i < n_pts; i++) {
303 av_store(out, i, newSVnv(exp(-sm[i] * inv)));
304 }
305 }
306  
307 /* finalize_path_lengths_xs(sm_sv, n_pts, t, out_rv)
308 *
309 * Same idea as finalize_scores_xs but writes sm[i] / t (the average path
310 * length across n_trees=t trees) instead of the exp normalisation. */
311 void finalize_path_lengths_xs(SV* sm_sv, int n_pts, double t, SV* out_rv){
312 STRLEN tl;
313 const double* sm;
314 AV* out;
315 int i;
316  
317 if (!SvROK(out_rv) || SvTYPE(SvRV(out_rv)) != SVt_PVAV) {
318 croak("finalize_path_lengths_xs: out must be an arrayref");
319 }
320 sm = (const double*)SvPVbyte(sm_sv, tl);
321 out = (AV*)SvRV(out_rv);
322 av_clear(out);
323 if (n_pts > 0) av_extend(out, n_pts - 1);
324 for (i = 0; i < n_pts; i++) {
325 av_store(out, i, newSVnv(sm[i] / t));
326 }
327 }
328  
329 /* predict_sums_xs(sm_sv, n_pts, sum_threshold, out_rv)
330 *
331 * Fills out_rv with 0/1 IVs based on sm[i] <= sum_threshold. The caller
332 * pre-computes sum_threshold = -log(score_threshold) * c * n_trees / log(2),
333 * so this skips both the per-point exp() and the intermediate scores
334 * arrayref that the old "score_samples + map threshold" path created. */
335 void predict_sums_xs(SV* sm_sv, int n_pts, double sum_threshold, SV* out_rv){
336 STRLEN tl;
337 const double* sm;
338 AV* out;
339 int i;
340  
341 if (!SvROK(out_rv) || SvTYPE(SvRV(out_rv)) != SVt_PVAV) {
342 croak("predict_sums_xs: out must be an arrayref");
343 }
344 sm = (const double*)SvPVbyte(sm_sv, tl);
345 out = (AV*)SvRV(out_rv);
346 av_clear(out);
347 if (n_pts > 0) av_extend(out, n_pts - 1);
348 for (i = 0; i < n_pts; i++) {
349 av_store(out, i, newSViv(sm[i] <= sum_threshold ? 1 : 0));
350 }
351 }
352  
353 /* score_predict_xs(sm_sv, n_pts, inv, sum_threshold, out_rv)
354 *
355 * Combines finalize_scores_xs + predict_sums_xs: fills the pre-allocated
356 * out_rv with [score, label] pairs in one pass over sm_sv. Replaces the
357 * trailing Perl loop in score_predict_samples that built ~3*n_pts SVs
358 * (n_pts scores + n_pts labels + n_pts inner arrayrefs) via a Perl
359 * foreach -- here the same SVs are allocated directly inside C.
360 *
361 * Refcount note: newRV_noinc takes ownership of the inner AV without
362 * incrementing it, and av_store takes ownership of the RV. When the
363 * outer AV is destroyed it frees the RVs, which free the inner AVs,
364 * which free the score/label SVs. No leak. */
365 void score_predict_xs(SV* sm_sv, int n_pts, double inv,
366 double sum_threshold, SV* out_rv){
367 STRLEN tl;
368 const double* sm;
369 AV* out;
370 int i;
371  
372 if (!SvROK(out_rv) || SvTYPE(SvRV(out_rv)) != SVt_PVAV) {
373 croak("score_predict_xs: out must be an arrayref");
374 }
375 sm = (const double*)SvPVbyte(sm_sv, tl);
376 out = (AV*)SvRV(out_rv);
377 av_clear(out);
378 if (n_pts > 0) av_extend(out, n_pts - 1);
379 for (i = 0; i < n_pts; i++) {
380 AV* row = newAV();
381 av_extend(row, 1);
382 /* av_extend filled both slots with &PL_sv_undef. Since that
383 * sentinel is immortal (its refcount is never freed) we can
384 * overwrite the slots directly and bump AvFILLp, skipping the
385 * per-element bounds/magic checks av_store would do. */
386 AvARRAY(row)[0] = newSVnv(exp(-sm[i] * inv));
387 AvARRAY(row)[1] = newSViv(sm[i] <= sum_threshold ? 1 : 0);
388 AvFILLp(row) = 1;
389 av_store(out, i, newRV_noinc((SV*)row));
390 }
391 }
392  
393 /* score_predict_split_xs(sm_sv, n_pts, inv, sum_threshold,
394 * scores_rv, labels_rv)
395 *
396 * Parallel-arrays variant of score_predict_xs: fills two pre-allocated
397 * arrayrefs (scores: NV, labels: IV) instead of an AV-of-[score, label]
398 * pairs. Allocates ~2*n_pts SVs instead of ~4*n_pts -- no inner AV and
399 * no RV per point -- so it's about twice as cheap for callers that
400 * don't need the paired shape. */
401 void score_predict_split_xs(SV* sm_sv, int n_pts, double inv,
402 double sum_threshold,
403 SV* scores_rv, SV* labels_rv){
404 STRLEN tl;
405 const double* sm;
406 AV* scores;
407 AV* labels;
408 int i;
409  
410 if (!SvROK(scores_rv) || SvTYPE(SvRV(scores_rv)) != SVt_PVAV ||
411 !SvROK(labels_rv) || SvTYPE(SvRV(labels_rv)) != SVt_PVAV) {
412 croak("score_predict_split_xs: scores/labels must be arrayrefs");
413 }
414 sm = (const double*)SvPVbyte(sm_sv, tl);
415 scores = (AV*)SvRV(scores_rv);
416 labels = (AV*)SvRV(labels_rv);
417 av_clear(scores);
418 av_clear(labels);
419 if (n_pts > 0) {
420 av_extend(scores, n_pts - 1);
421 av_extend(labels, n_pts - 1);
422 }
423 for (i = 0; i < n_pts; i++) {
424 av_store(scores, i, newSVnv(exp(-sm[i] * inv)));
425 av_store(labels, i, newSViv(sm[i] <= sum_threshold ? 1 : 0));
426 }
427 }
428  
429 /* Walk one point through one tree; returns the path length (depth plus
430 * the precomputed c(leaf size) adjustment from the leaf record).
431 *
432 * Invariant: every feature index stored in a tree node is in
433 * [0, n_feats). fit() builds trees against n_features columns and
434 * pack_input_xs writes exactly that many doubles per row, and
435 * _resolve_input rejects PackedData with a mismatched feature count.
436 * So the loop can omit per-iteration bounds checks on attr / fi --
437 * this is what lets the oblique dot product vectorize cleanly under
438 * the omp-simd reductions below. */
439 #if defined(__GNUC__) || defined(__clang__)
440 __attribute__((always_inline))
441 #endif
442 static inline double if_walk_tree(const double *nd, const int *ico,
443 const double *vco, const double *xi,
444 int n_feats) {
445 int ni = 0, depth = 0;
446 for (;;) {
447 const double *node = nd + (size_t)ni * IF_NZ;
448 int type = (int)node[0];
449 if (type == 0) {
450 /* node[2] is c(leaf size), precomputed by _pack_tree; a
451 * log() here would otherwise run once per point per tree. */
452 return depth + node[2];
453 }
454 if (type == 1) {
455 double fv = xi[(int)node[1]];
456 ni = (fv < node[2]) ? (int)node[3] : (int)node[4];
457 } else {
458 int coff = (int)node[1], nf = (int)node[2];
459 double b = node[5], dot = 0.0;
460 const double *val_p = vco + (size_t)coff;
461  
462 /* Both children are known before the dot product resolves
463 * which one gets taken, so start pulling their records in
464 * now and let the FMA loop below hide the latency. One of
465 * the two prefetches is always wasted -- affordable here
466 * on the oblique path, where there is real work to hide it
467 * under, but not on the axis path, whose single compare
468 * resolves immediately. */
469 const int li = (int)node[3], ri = (int)node[4];
470 IF_PREFETCH(nd + (size_t)li * IF_NZ);
471 IF_PREFETCH(nd + (size_t)ri * IF_NZ);
472 if (nf == n_feats) {
473 /* Dense oblique split: this node uses every feature,
474 * so _pack_tree laid the coefficients out in feature
475 * order. No gather -- the inner loop is a textbook
476 * FMA-vectorizable dot product over two contiguous
477 * double streams. Common case in extended mode at
478 * the default extension_level (== n_feats-1). */
479 #ifdef _OPENMP
480 #pragma omp simd reduction(+:dot)
481 #endif
482 for (int k = 0; k < n_feats; k++) {
483 dot += val_p[k] * xi[k];
484 }
485 } else {
486 /* Sparse oblique split: only nf < n_feats features
487 * participate, so we still need the gather on
488 * xi[idx_p[k]]. Storing idx as contiguous int32
489 * (rather than interleaved doubles) keeps the gather
490 * pattern clean and the val[] load contiguous. */
491 const int *idx_p = ico + (size_t)coff;
492 #ifdef _OPENMP
493 #pragma omp simd reduction(+:dot)
494 #endif
495 for (int k = 0; k < nf; k++) {
496 dot += val_p[k] * xi[idx_p[k]];
497 }
498 }
499 ni = (dot <= b) ? li : ri;
500 }
501 depth++;
502 }
503 }
504  
505 /* score_all_xs(nodes_av, idx_av, val_av, x_sv, sm_sv,
506 * n_pts, n_feats, n_trees, use_openmp)
507 *
508 * Scores all points across all trees in one C call. See header comment
509 * above for the bigger picture. Writes sm[i] = sum_over_trees(path_len);
510 * the caller need not zero-init sm.
511 *
512 * idx_av holds per-tree packed int32 buffers of feature indices and
513 * val_av holds per-tree packed double buffers of coefficients (the SoA
514 * counterpart of the old interleaved layout). See the file-top
515 * comment for the rationale.
516 *
517 * Thread-safety: the parallel region only reads node/idx/val/x pointers
518 * (extracted before the region) and writes sm[i] for a unique i per
519 * iteration. No Perl API is called from inside the parallel region. */
520 void score_all_xs(SV* nodes_av_sv, SV* idx_av_sv, SV* val_av_sv,
521 SV* x_sv, SV* sm_sv,
522 int n_pts, int n_feats, int n_trees,
523 int use_openmp){
524 STRLEN tl;
525 AV *nodes_av, *idx_av, *val_av;
526 const double *xd;
527 double *sm;
528 int ti;
529  
530 if (!SvROK(nodes_av_sv) || SvTYPE(SvRV(nodes_av_sv)) != SVt_PVAV ||
531 !SvROK(idx_av_sv) || SvTYPE(SvRV(idx_av_sv)) != SVt_PVAV ||
532 !SvROK(val_av_sv) || SvTYPE(SvRV(val_av_sv)) != SVt_PVAV) {
533 croak("score_all_xs: nodes/idx/val must be arrayrefs");
534 }
535 nodes_av = (AV*)SvRV(nodes_av_sv);
536 idx_av = (AV*)SvRV(idx_av_sv);
537 val_av = (AV*)SvRV(val_av_sv);
538  
539 /* C99 VLAs -- n_trees is small (typ. 100) and fits on the stack. */
540 const double *node_ptrs[n_trees];
541 const int *idx_ptrs[n_trees];
542 const double *val_ptrs[n_trees];
543  
544 /* forest_bytes totals every buffer the tree walks touch; it decides
545 * between the two loop shapes below. */
546 size_t forest_bytes = 0;
547 for (ti = 0; ti < n_trees; ti++) {
548 SV** np = av_fetch(nodes_av, ti, 0);
549 SV** ip = av_fetch(idx_av, ti, 0);
550 SV** vp = av_fetch(val_av, ti, 0);
551 if (!np || !*np || !ip || !*ip || !vp || !*vp) {
552 croak("score_all_xs: missing tree %d", ti);
553 }
554 node_ptrs[ti] = (const double*)SvPVbyte(*np, tl); forest_bytes += tl;
555 idx_ptrs[ti] = (const int*) SvPVbyte(*ip, tl); forest_bytes += tl;
556 val_ptrs[ti] = (const double*)SvPVbyte(*vp, tl); forest_bytes += tl;
557 }
558  
559 xd = (const double*)SvPVbyte(x_sv, tl);
560 sm = (double*)SvPVbyte_force(sm_sv, tl);
561  
562 /* Two loop shapes over the same per-point ascending-t additions --
563 * bit-identical results either way, so the size heuristic choosing
564 * between them can never change scores.
565 *
566 * Point-major (small forests): each point walks all trees with its
567 * path-length sum held in a register. Cheapest per walk, and the
568 * whole forest stays cache-resident across points anyway.
569 *
570 * Tree-blocked (large forests): once the forest outgrows L3, the
571 * point-major loop re-streams every tree's nodes and coefficients
572 * from memory for every point -- an extended-mode tree is ~56 KB
573 * at 16 features (24 KB nodes + 32 KB dense coefficients), and its
574 * per-tree scoring cost measured 2.2x worse at 400 trees than at
575 * 100. Walking a block of points through ONE tree at a time keeps
576 * that tree hot in L1/L2 while the block's rows stream through it
577 * (measured 3.1x faster at 400 extended trees, 20k points). The
578 * blocked shape pays an sm[i] load+store per walk instead of a
579 * register add, which measurably hurts cheap axis walks while the
580 * forest still fits in cache -- hence the byte threshold rather
581 * than always tiling. */
582 if (forest_bytes <= (size_t)4 * 1024 * 1024) {
583 #ifdef _OPENMP
584 #pragma omp parallel for schedule(static) if(use_openmp)
585 #endif
586 for (int i = 0; i < n_pts; i++) {
587 const double *xi = xd + (size_t)i * (size_t)n_feats;
588 double sum = 0.0;
589 for (int t = 0; t < n_trees; t++) {
590 sum += if_walk_tree(node_ptrs[t], idx_ptrs[t],
591 val_ptrs[t], xi, n_feats);
592 }
593 sm[i] = sum;
594 }
595 }
596 else {
597 /* 256 rows x 16 features x 8 bytes = 32 KB of input per block
598 * -- comfortable in L2 next to one tree. Each OpenMP thread
599 * owns whole blocks and therefore a unique slice of sm[], so
600 * there is still no synchronisation. For small batches the
601 * tile shrinks to keep ~4 blocks per thread available; losing
602 * per-block tree reuse there is fine, since a small batch
603 * never re-streams much anyway. */
604 int tile = 256;
605 #ifdef _OPENMP
606 if (use_openmp) {
607 int min_blocks = omp_get_max_threads() * 4;
608 if (min_blocks > 0 && (n_pts + tile - 1) / tile < min_blocks) {
609 tile = (n_pts + min_blocks - 1) / min_blocks;
610 if (tile < 1) tile = 1;
611 }
612 }
613 #endif
614 int n_blocks = (n_pts + tile - 1) / tile;
615  
616 #ifdef _OPENMP
617 #pragma omp parallel for schedule(static) if(use_openmp)
618 #endif
619 for (int blk = 0; blk < n_blocks; blk++) {
620 const int i0 = blk * tile;
621 const int i1 = (i0 + tile < n_pts) ? i0 + tile : n_pts;
622 for (int i = i0; i < i1; i++) sm[i] = 0.0;
623 for (int t = 0; t < n_trees; t++) {
624 const double *nd = node_ptrs[t];
625 const int *ico = idx_ptrs[t];
626 const double *vco = val_ptrs[t];
627 for (int i = i0; i < i1; i++) {
628 sm[i] += if_walk_tree(nd, ico, vco,
629 xd + (size_t)i * (size_t)n_feats,
630 n_feats);
631 }
632 }
633 }
634 }
635 }
636  
637 /* vote_all_xs(nodes_av, idx_av, val_av, x_sv, sm_sv,
638 * n_pts, n_feats, n_trees, depth_cut, min_votes, use_openmp)
639 *
640 * Majority-voting (MVIForest) tree walk: a tree votes a point anomalous
641 * when the point's path length in that tree is <= depth_cut -- the
642 * depth-domain image of the per-tree score cutoff (the Perl side
643 * precomputes depth_cut = -c(psi) * log2(threshold), so no per-tree
644 * exp()/log() runs in here).
645 *
646 * min_votes == 0: sm[i] = the point's full vote count over all n_trees
647 * trees (a small integer stored as a double, so the existing
648 * finalize_* helpers work on the buffer unchanged).
649 * min_votes > 0: sm[i] = 1.0/0.0 anomaly label, with per-point early
650 * exit: the walk stops as soon as the point has min_votes votes (the
651 * remaining trees can't change the outcome) or can no longer reach
652 * min_votes. This is MVIForest's "stop at majority" scoring loop.
653 *
654 * Always point-major, unlike score_all_xs's two loop shapes: the vote
655 * count / early exit is per-point state, so a tree-blocked loop would
656 * have to re-load it per walk and could never exit a point early.
657 * Votes are integer counts, so there is no summation-order concern
658 * either way. Thread-safety matches score_all_xs: the parallel region
659 * reads extracted pointers and writes a unique sm[i] per iteration. */
660 void vote_all_xs(SV* nodes_av_sv, SV* idx_av_sv, SV* val_av_sv,
661 SV* x_sv, SV* sm_sv,
662 int n_pts, int n_feats, int n_trees,
663 double depth_cut, int min_votes, int use_openmp){
664 STRLEN tl;
665 AV *nodes_av, *idx_av, *val_av;
666 const double *xd;
667 double *sm;
668 int ti;
669  
670 if (!SvROK(nodes_av_sv) || SvTYPE(SvRV(nodes_av_sv)) != SVt_PVAV ||
671 !SvROK(idx_av_sv) || SvTYPE(SvRV(idx_av_sv)) != SVt_PVAV ||
672 !SvROK(val_av_sv) || SvTYPE(SvRV(val_av_sv)) != SVt_PVAV) {
673 croak("vote_all_xs: nodes/idx/val must be arrayrefs");
674 }
675 nodes_av = (AV*)SvRV(nodes_av_sv);
676 idx_av = (AV*)SvRV(idx_av_sv);
677 val_av = (AV*)SvRV(val_av_sv);
678  
679 const double *node_ptrs[n_trees];
680 const int *idx_ptrs[n_trees];
681 const double *val_ptrs[n_trees];
682  
683 for (ti = 0; ti < n_trees; ti++) {
684 SV** np = av_fetch(nodes_av, ti, 0);
685 SV** ip = av_fetch(idx_av, ti, 0);
686 SV** vp = av_fetch(val_av, ti, 0);
687 if (!np || !*np || !ip || !*ip || !vp || !*vp) {
688 croak("vote_all_xs: missing tree %d", ti);
689 }
690 node_ptrs[ti] = (const double*)SvPVbyte(*np, tl);
691 idx_ptrs[ti] = (const int*) SvPVbyte(*ip, tl);
692 val_ptrs[ti] = (const double*)SvPVbyte(*vp, tl);
693 }
694  
695 xd = (const double*)SvPVbyte(x_sv, tl);
696 sm = (double*)SvPVbyte_force(sm_sv, tl);
697  
698 #ifdef _OPENMP
699 #pragma omp parallel for schedule(static) if(use_openmp)
700 #endif
701 for (int i = 0; i < n_pts; i++) {
702 const double *xi = xd + (size_t)i * (size_t)n_feats;
703 int votes = 0;
704 if (min_votes > 0) {
705 double label = 0.0;
706 for (int t = 0; t < n_trees; t++) {
707 if (if_walk_tree(node_ptrs[t], idx_ptrs[t],
708 val_ptrs[t], xi, n_feats) <= depth_cut) {
709 votes++;
710 if (votes >= min_votes) { label = 1.0; break; }
711 }
712 if (votes + (n_trees - 1 - t) < min_votes) break;
713 }
714 sm[i] = label;
715 } else {
716 for (int t = 0; t < n_trees; t++) {
717 votes += (if_walk_tree(node_ptrs[t], idx_ptrs[t],
718 val_ptrs[t], xi, n_feats)
719 <= depth_cut) ? 1 : 0;
720 }
721 sm[i] = (double)votes;
722 }
723 }
724 }
725  
726 /* vote_labels_xs(sm_sv, n_pts, out_rv)
727 *
728 * Converts the 0.0/1.0 label buffer vote_all_xs writes in early-exit
729 * mode into an arrayref of 0/1 IVs -- the majority-voting counterpart
730 * of predict_sums_xs (whose <= comparison points the wrong way for
731 * vote counts, where HIGH means anomalous). */
732 void vote_labels_xs(SV* sm_sv, int n_pts, SV* out_rv){
733 STRLEN tl;
734 const double* sm;
735 AV* out;
736 int i;
737  
738 if (!SvROK(out_rv) || SvTYPE(SvRV(out_rv)) != SVt_PVAV) {
739 croak("vote_labels_xs: out must be an arrayref");
740 }
741 sm = (const double*)SvPVbyte(sm_sv, tl);
742 out = (AV*)SvRV(out_rv);
743 av_clear(out);
744 if (n_pts > 0) av_extend(out, n_pts - 1);
745 for (i = 0; i < n_pts; i++) {
746 av_store(out, i, newSViv(sm[i] != 0.0 ? 1 : 0));
747 }
748 }
749  
750 /* vote_score_predict_xs(sm_sv, n_pts, t, min_votes, out_rv)
751 *
752 * Fills out_rv with [vote_fraction, majority_label] pairs from a
753 * vote-count buffer (vote_all_xs with min_votes == 0): score is
754 * votes/t, label is votes >= min_votes. Same allocation pattern and
755 * refcount discipline as score_predict_xs. */
756 void vote_score_predict_xs(SV* sm_sv, int n_pts, double t,
757 double min_votes, SV* out_rv){
758 STRLEN tl;
759 const double* sm;
760 AV* out;
761 int i;
762  
763 if (!SvROK(out_rv) || SvTYPE(SvRV(out_rv)) != SVt_PVAV) {
764 croak("vote_score_predict_xs: out must be an arrayref");
765 }
766 sm = (const double*)SvPVbyte(sm_sv, tl);
767 out = (AV*)SvRV(out_rv);
768 av_clear(out);
769 if (n_pts > 0) av_extend(out, n_pts - 1);
770 for (i = 0; i < n_pts; i++) {
771 AV* row = newAV();
772 av_extend(row, 1);
773 AvARRAY(row)[0] = newSVnv(sm[i] / t);
774 AvARRAY(row)[1] = newSViv(sm[i] >= min_votes ? 1 : 0);
775 AvFILLp(row) = 1;
776 av_store(out, i, newRV_noinc((SV*)row));
777 }
778 }
779  
780 /* vote_score_predict_split_xs(sm_sv, n_pts, t, min_votes,
781 * scores_rv, labels_rv)
782 *
783 * Parallel-arrays variant of vote_score_predict_xs, mirroring
784 * score_predict_split_xs's shape for the majority-voting path. */
785 void vote_score_predict_split_xs(SV* sm_sv, int n_pts, double t,
786 double min_votes,
787 SV* scores_rv, SV* labels_rv){
788 STRLEN tl;
789 const double* sm;
790 AV* scores;
791 AV* labels;
792 int i;
793  
794 if (!SvROK(scores_rv) || SvTYPE(SvRV(scores_rv)) != SVt_PVAV ||
795 !SvROK(labels_rv) || SvTYPE(SvRV(labels_rv)) != SVt_PVAV) {
796 croak("vote_score_predict_split_xs: scores/labels must be arrayrefs");
797 }
798 sm = (const double*)SvPVbyte(sm_sv, tl);
799 scores = (AV*)SvRV(scores_rv);
800 labels = (AV*)SvRV(labels_rv);
801 av_clear(scores);
802 av_clear(labels);
803 if (n_pts > 0) {
804 av_extend(scores, n_pts - 1);
805 av_extend(labels, n_pts - 1);
806 }
807 for (i = 0; i < n_pts; i++) {
808 av_store(scores, i, newSVnv(sm[i] / t));
809 av_store(labels, i, newSViv(sm[i] >= min_votes ? 1 : 0));
810 }
811 }
812  
813 /* ---------------------------------------------------------------------
814 * build_forest_xs -- C-accelerated fit() tree builder.
815 *
816 * Replaces the pure-Perl _subsample + _build_tree + _axis_split /
817 * _oblique_split recursion with an equivalent C implementation that
818 * partitions plain `int` row-index arrays instead of copying arrayrefs
819 * of Perl SVs at every split. Random draws go through Drand01() --
820 * the exact generator Perl's own rand()/srand() use internally -- in
821 * the same call order the Perl code used, so a fit() with a given
822 * seed produces BIT-IDENTICAL trees whether use_c is on or off. This
823 * is what lets fit() reuse the existing `use_c` knob instead of a new
824 * one: switching backends never changes the model, only how fast it's
825 * built. (Verified by t/02-accel-selection.t's "identical seed =>
826 * identical trees" subtest, which exercises both backends.)
827 *
828 * Output trees are plain Perl arrayrefs in the same node shape
829 * _build_tree produces (leaf/axis/oblique -- see the file-top
830 * comment), so every downstream consumer (_pack_tree, to_json,
831 * from_json, the pure-Perl scorer) is unchanged.
832 *
833 * x_sv: packed row-major double buffer, n_pts rows of n_feats each
834 * (from pack_input_xs -- NaN marks a missing cell under the
835 * 'nan' missing-strategy).
836 * mode_flag: 0 => axis-parallel splits, 1 => oblique (extended).
837 * ext_level: extension_level_used (ignored when mode_flag == 0).
838 * out_rv: pre-existing arrayref; filled with n_trees tree roots.
839 * ------------------------------------------------------------------ */
840  
841 /* Box-Muller normal draw, in the same rand() call order as _randn(). */
842 static double _c_randn(pTHX) {
843 double u1 = Drand01();
844 double u2;
845 if (u1 == 0.0) u1 = 1e-12;
846 u2 = Drand01();
847 return sqrt(-2.0 * log(u1)) * cos(6.283185307179586 * u2);
848 }
849  
850 static SV* _mk_leaf(pTHX_ int size) {
851 AV* av = newAV();
852 av_extend(av, 1);
853 AvARRAY(av)[0] = newSVnv(0.0);
854 AvARRAY(av)[1] = newSViv(size);
855 AvFILLp(av) = 1;
856 return newRV_noinc((SV*)av);
857 }
858  
859 static SV* _mk_axis(pTHX_ int attr, double split, SV* left, SV* right) {
860 AV* av = newAV();
861 av_extend(av, 4);
862 AvARRAY(av)[0] = newSVnv(1.0);
863 AvARRAY(av)[1] = newSViv(attr);
864 AvARRAY(av)[2] = newSVnv(split);
865 AvARRAY(av)[3] = left;
866 AvARRAY(av)[4] = right;
867 AvFILLp(av) = 4;
868 return newRV_noinc((SV*)av);
869 }
870  
871 static SV* _mk_oblique(pTHX_ const int* idx, const double* coef, int n,
872 double b, SV* left, SV* right) {
873 AV *iav, *cav, *av;
874 int k;
875 iav = newAV();
876 cav = newAV();
877 if (n > 0) {
878 av_extend(iav, n - 1);
879 av_extend(cav, n - 1);
880 }
881 for (k = 0; k < n; k++) {
882 AvARRAY(iav)[k] = newSViv(idx[k]);
883 AvARRAY(cav)[k] = newSVnv(coef[k]);
884 }
885 AvFILLp(iav) = n - 1;
886 AvFILLp(cav) = n - 1;
887  
888 av = newAV();
889 av_extend(av, 5);
890 AvARRAY(av)[0] = newSVnv(2.0);
891 AvARRAY(av)[1] = newRV_noinc((SV*)iav);
892 AvARRAY(av)[2] = newRV_noinc((SV*)cav);
893 AvARRAY(av)[3] = newSVnv(b);
894 AvARRAY(av)[4] = left;
895 AvARRAY(av)[5] = right;
896 AvFILLp(av) = 5;
897 return newRV_noinc((SV*)av);
898 }
899  
900 /* Builds one node from the point set `idxs` (row indices into `x`,
901 * length `size`); recurses left-then-right, matching _build_tree's
902 * traversal order so nested splits draw random numbers in the same
903 * sequence the pure-Perl path would. Takes ownership of `idxs` --
904 * frees it before returning. */
905 static SV* _build_node_c(pTHX_ const double* x, int nf, int* idxs, int size,
906 int depth, int limit, int mode_flag,
907 int ext_active) {
908 double *lo, *hi;
909 int *varying, nv, f;
910 SV *result;
911  
912 if (depth >= limit || size <= 1) {
913 SV* leaf = _mk_leaf(aTHX_ size);
914 free(idxs);
915 return leaf;
916 }
917  
918 lo = (double*)malloc(nf * sizeof(double));
919 hi = (double*)malloc(nf * sizeof(double));
920 for (f = 0; f < nf; f++) {
921 lo[f] = HUGE_VAL;
922 hi[f] = -HUGE_VAL;
923 }
924 for (int i = 0; i < size; i++) {
925 const double* row = x + (size_t)idxs[i] * (size_t)nf;
926 /* No isnan() guard needed: NaN < x and NaN > x are always false
927 * under IEEE 754, so a NaN cell (the 'nan' missing strategy)
928 * already leaves lo/hi untouched without an explicit check --
929 * one less branch, and it's what lets this loop vectorize
930 * cleanly as a plain elementwise min/max scan. */
931 #ifdef _OPENMP
932 #pragma omp simd
933 #endif
934 for (int f2 = 0; f2 < nf; f2++) {
935 double v = row[f2];
936 if (v < lo[f2]) lo[f2] = v;
937 if (v > hi[f2]) hi[f2] = v;
938 }
939 }
940  
941 varying = (int*)malloc(nf * sizeof(int));
942 nv = 0;
943 for (f = 0; f < nf; f++) {
944 if (lo[f] < hi[f]) varying[nv++] = f;
945 }
946  
947 if (nv == 0) {
948 free(lo); free(hi); free(varying);
949 SV* leaf = _mk_leaf(aTHX_ size);
950 free(idxs);
951 return leaf;
952 }
953  
954 if (mode_flag == 0) {
955 /* Axis-parallel split: one varying feature, one threshold. */
956 int attr = varying[(int)(Drand01() * nv)];
957 double split = lo[attr] + Drand01() * (hi[attr] - lo[attr]);
958 int *lidx = (int*)malloc(size * sizeof(int));
959 int *ridx = (int*)malloc(size * sizeof(int));
960 int ln = 0, rn = 0, i;
961 SV *left, *right;
962  
963 for (i = 0; i < size; i++) {
964 int row = idxs[i];
965 double v = x[(size_t)row * (size_t)nf + attr];
966 if (v < split) lidx[ln++] = row; else ridx[rn++] = row;
967 }
968 free(idxs); free(lo); free(hi); free(varying);
969  
970 left = _build_node_c(aTHX_ x, nf, lidx, ln, depth + 1, limit,
971 mode_flag, ext_active);
972 right = _build_node_c(aTHX_ x, nf, ridx, rn, depth + 1, limit,
973 mode_flag, ext_active);
974 result = _mk_axis(aTHX_ attr, split, left, right);
975 } else {
976 /* Oblique split: a random hyperplane over `active` features. */
977 int active = ext_active + 1;
978 int *pool, *lidx, *ridx;
979 double *coef;
980 double b = 0.0;
981 int ln = 0, rn = 0, i, k;
982 SV *left, *right;
983  
984 if (active > nv) active = nv;
985 pool = (int*)malloc(nv * sizeof(int));
986 memcpy(pool, varying, nv * sizeof(int));
987 for (i = 0; i < active; i++) {
988 int j = i + (int)(Drand01() * (nv - i));
989 int tmp = pool[i]; pool[i] = pool[j]; pool[j] = tmp;
990 }
991  
992 coef = (double*)malloc(active * sizeof(double));
993 for (k = 0; k < active; k++) {
994 int ff = pool[k];
995 double c = _c_randn(aTHX);
996 double p = lo[ff] + Drand01() * (hi[ff] - lo[ff]);
997 coef[k] = c;
998 b += c * p;
999 }
1000  
1001 lidx = (int*)malloc(size * sizeof(int));
1002 ridx = (int*)malloc(size * sizeof(int));
1003 for (i = 0; i < size; i++) {
1004 int row = idxs[i];
1005 double dot = 0.0;
1006 for (k = 0; k < active; k++) {
1007 dot += coef[k] * x[(size_t)row * (size_t)nf + pool[k]];
1008 }
1009 if (dot <= b) lidx[ln++] = row; else ridx[rn++] = row;
1010 }
1011 free(idxs); free(lo); free(hi); free(varying);
1012  
1013 left = _build_node_c(aTHX_ x, nf, lidx, ln, depth + 1, limit,
1014 mode_flag, ext_active);
1015 right = _build_node_c(aTHX_ x, nf, ridx, rn, depth + 1, limit,
1016 mode_flag, ext_active);
1017 result = _mk_oblique(aTHX_ pool, coef, active, b, left, right);
1018 free(pool); free(coef);
1019 }
1020 return result;
1021 }
1022  
1023 void build_forest_xs(SV* x_sv, int n_pts, int n_feats, int n_trees,
1024 int psi, int limit, int mode_flag, int ext_level,
1025 SV* out_rv) {
1026 dTHX;
1027 STRLEN tl;
1028 const double* x;
1029 AV* out;
1030 int* all;
1031 int t, i;
1032  
1033 if (!SvROK(out_rv) || SvTYPE(SvRV(out_rv)) != SVt_PVAV) {
1034 croak("build_forest_xs: out must be an arrayref");
1035 }
1036 x = (const double*)SvPVbyte(x_sv, tl);
1037 out = (AV*)SvRV(out_rv);
1038 av_clear(out);
1039 if (n_trees > 0) av_extend(out, n_trees - 1);
1040  
1041 all = (int*)malloc(n_pts * sizeof(int));
1042 for (t = 0; t < n_trees; t++) {
1043 int* sample;
1044  
1045 for (i = 0; i < n_pts; i++) all[i] = i;
1046 for (i = 0; i < psi; i++) {
1047 int j = i + (int)(Drand01() * (n_pts - i));
1048 int tmp = all[i]; all[i] = all[j]; all[j] = tmp;
1049 }
1050 sample = (int*)malloc(psi * sizeof(int));
1051 memcpy(sample, all, psi * sizeof(int));
1052  
1053 av_store(out, t,
1054 _build_node_c(aTHX_ x, n_feats, sample, psi, 0, limit,
1055 mode_flag, ext_level));
1056 }
1057 free(all);
1058 }
1059  
1060 /* ---------------------------------------------------------------------
1061 * build_forest_openmp_xs -- OpenMP-parallel fit() tree builder.
1062 *
1063 * build_forest_xs (above) is bit-identical to the pure-Perl path
1064 * because every random draw goes through Drand01(), the same
1065 * generator Perl's rand()/srand() use -- but that generator is a
1066 * single mutable struct shared by the whole interpreter, so calling
1067 * it concurrently from multiple OpenMP threads would be a data race.
1068 * The same is true of any Perl API call (newAV, newSViv, ...): Perl's
1069 * SV allocator isn't safe to call from multiple OS threads sharing one
1070 * interpreter without a lock that would just serialise everything
1071 * anyway.
1072 *
1073 * So this builder trades the bit-identical guarantee for real thread
1074 * parallelism: each tree gets its own splitmix64 PRNG stream, seeded
1075 * from a tree index (not thread id or scheduling order), so results
1076 * are still reproducible for a fixed seed and n_trees regardless of
1077 * OMP_NUM_THREADS -- just different from what build_forest_xs or the
1078 * pure-Perl path would produce for the same seed. The one Drand01()
1079 * call in this function happens before the parallel region starts
1080 * (single-threaded), so the result still varies with the model's
1081 * `seed` the way every other code path does; it isn't used inside the
1082 * parallel loop.
1083 *
1084 * Each tree is built entirely with plain C data (row-index int arrays,
1085 * a growable TreeBuf of packed doubles/ints) -- no Perl API call
1086 * happens anywhere inside the parallel region. Each node record in
1087 * TreeBuf uses _pack_tree's 6-double SoA layout (see the file-top
1088 * comment), but the node ORDER differs: records are appended
1089 * post-order (a node is pushed after both its children, since child
1090 * indices must be known first), so the root is the last record --
1091 * _pack_tree's pre-order puts it at 0. _unpack_forest accounts for
1092 * this. Oblique coefficients are also always stored sparse (in the
1093 * random pool's order) -- the dense-pack fast path is skipped because
1094 * its only purpose is speeding up score_all_xs, and _rebuild_c_trees
1095 * reapplies it anyway once the caller unpacks these buffers back into
1096 * the standard Perl tree shape and re-derives the scoring buffers.
1097 *
1098 * After the parallel region, each tree's TreeBuf is copied into a Perl
1099 * string SV (one memcpy each, serially) and stored into nodes_rv /
1100 * idx_rv / val_rv -- the caller unpacks these into ordinary nested
1101 * Perl trees for $self->{trees} (so to_json/persistence/_rebuild_c_trees
1102 * are unaffected). ------------------------------------------------ */
1103  
1104 typedef struct {
1105 double *nodes; size_t n_nodes, cap_nodes;
1106 int *idx; size_t n_idx, cap_idx;
1107 double *val; size_t n_val, cap_val;
1108 } TreeBuf;
1109  
1110 static void tb_init(TreeBuf *b) {
1111 b->nodes = NULL; b->n_nodes = 0; b->cap_nodes = 0;
1112 b->idx = NULL; b->n_idx = 0; b->cap_idx = 0;
1113 b->val = NULL; b->n_val = 0; b->cap_val = 0;
1114 }
1115  
1116 static void tb_free(TreeBuf *b) {
1117 free(b->nodes); free(b->idx); free(b->val);
1118 }
1119  
1120 static int tb_push_node(TreeBuf *b, double f0, double f1, double f2,
1121 double f3, double f4, double f5) {
1122 double *slot;
1123 if (b->n_nodes == b->cap_nodes) {
1124 size_t newcap = b->cap_nodes ? b->cap_nodes * 2 : 64;
1125 b->nodes = (double*)realloc(b->nodes, newcap * 6 * sizeof(double));
1126 b->cap_nodes = newcap;
1127 }
1128 slot = b->nodes + b->n_nodes * 6;
1129 slot[0] = f0; slot[1] = f1; slot[2] = f2;
1130 slot[3] = f3; slot[4] = f4; slot[5] = f5;
1131 return (int)(b->n_nodes++);
1132 }
1133  
1134 /* Appends n (idx[k], val[k]) pairs and returns the offset they start
1135 * at -- the `coff` an oblique node record stores. */
1136 static int tb_push_coef(TreeBuf *b, const int *idx, const double *val,
1137 int n) {
1138 int off = (int)b->n_idx;
1139 if (b->n_idx + (size_t)n > b->cap_idx) {
1140 size_t newcap = b->cap_idx ? b->cap_idx * 2 : 64;
1141 if (newcap < b->n_idx + (size_t)n) newcap = b->n_idx + (size_t)n;
1142 b->idx = (int*)realloc(b->idx, newcap * sizeof(int));
1143 b->cap_idx = newcap;
1144 }
1145 if (b->n_val + (size_t)n > b->cap_val) {
1146 size_t newcap = b->cap_val ? b->cap_val * 2 : 64;
1147 if (newcap < b->n_val + (size_t)n) newcap = b->n_val + (size_t)n;
1148 b->val = (double*)realloc(b->val, newcap * sizeof(double));
1149 b->cap_val = newcap;
1150 }
1151 memcpy(b->idx + b->n_idx, idx, (size_t)n * sizeof(int));
1152 memcpy(b->val + b->n_val, val, (size_t)n * sizeof(double));
1153 b->n_idx += n;
1154 b->n_val += n;
1155 return off;
1156 }
1157  
1158 /* splitmix64 -- fast, well-mixed, and per-stream state fits in one
1159 * uint64_t, which is all a thread-private PRNG needs here. Not
1160 * cryptographic; doesn't need to be. */
1161 static uint64_t sm64_next(uint64_t *s) {
1162 uint64_t z = (*s += 0x9E3779B97F4A7C15ULL);
1163 z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
1164 z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
1165 return z ^ (z >> 31);
1166 }
1167  
1168 static double sm64_drand(uint64_t *s) {
1169 return (double)(sm64_next(s) >> 11) * (1.0 / 9007199254740992.0);
1170 }
1171  
1172 static double _ts_randn(uint64_t *s) {
1173 double u1 = sm64_drand(s);
1174 double u2;
1175 if (u1 == 0.0) u1 = 1e-12;
1176 u2 = sm64_drand(s);
1177 return sqrt(-2.0 * log(u1)) * cos(6.283185307179586 * u2);
1178 }
1179  
1180 /* Thread-safe twin of _build_node_c: same split algorithm, but reads
1181 * randomness from a thread-private splitmix64 stream instead of
1182 * Drand01(), and writes into a TreeBuf instead of allocating Perl AVs
1183 * -- so it touches no interpreter-global state and is safe to call
1184 * concurrently from an OpenMP parallel region, one tree per thread. */
1185 static int _build_node_packed(const double* x, int nf, int* idxs, int size,
1186 int depth, int limit, int mode_flag,
1187 int ext_active, TreeBuf *buf, uint64_t *rng) {
1188 double *lo, *hi;
1189 int *varying, nv, f, my_idx;
1190  
1191 if (depth >= limit || size <= 1) {
1192 my_idx = tb_push_node(buf, 0.0, (double)size, 0.0, 0.0, 0.0, 0.0);
1193 free(idxs);
1194 return my_idx;
1195 }
1196  
1197 lo = (double*)malloc(nf * sizeof(double));
1198 hi = (double*)malloc(nf * sizeof(double));
1199 for (f = 0; f < nf; f++) {
1200 lo[f] = HUGE_VAL;
1201 hi[f] = -HUGE_VAL;
1202 }
1203 for (int i = 0; i < size; i++) {
1204 const double* row = x + (size_t)idxs[i] * (size_t)nf;
1205 /* See the matching comment in _build_node_c: no isnan() guard
1206 * needed, since NaN < x / NaN > x are always false already --
1207 * that's what lets this vectorize as a plain min/max scan.
1208 * omp simd here is thread-safe to call from inside the caller's
1209 * omp parallel region: it's a per-thread vectorization hint,
1210 * not a team construct, so it doesn't nest into anything. */
1211 #ifdef _OPENMP
1212 #pragma omp simd
1213 #endif
1214 for (int f2 = 0; f2 < nf; f2++) {
1215 double v = row[f2];
1216 if (v < lo[f2]) lo[f2] = v;
1217 if (v > hi[f2]) hi[f2] = v;
1218 }
1219 }
1220  
1221 varying = (int*)malloc(nf * sizeof(int));
1222 nv = 0;
1223 for (f = 0; f < nf; f++) {
1224 if (lo[f] < hi[f]) varying[nv++] = f;
1225 }
1226  
1227 if (nv == 0) {
1228 free(lo); free(hi); free(varying);
1229 my_idx = tb_push_node(buf, 0.0, (double)size, 0.0, 0.0, 0.0, 0.0);
1230 free(idxs);
1231 return my_idx;
1232 }
1233  
1234 if (mode_flag == 0) {
1235 int attr = varying[(int)(sm64_drand(rng) * nv)];
1236 double split = lo[attr] + sm64_drand(rng) * (hi[attr] - lo[attr]);
1237 int *lidx = (int*)malloc(size * sizeof(int));
1238 int *ridx = (int*)malloc(size * sizeof(int));
1239 int ln = 0, rn = 0, i, li, ri;
1240  
1241 for (i = 0; i < size; i++) {
1242 int row = idxs[i];
1243 double v = x[(size_t)row * (size_t)nf + attr];
1244 if (v < split) lidx[ln++] = row; else ridx[rn++] = row;
1245 }
1246 free(idxs); free(lo); free(hi); free(varying);
1247  
1248 li = _build_node_packed(x, nf, lidx, ln, depth + 1, limit,
1249 mode_flag, ext_active, buf, rng);
1250 ri = _build_node_packed(x, nf, ridx, rn, depth + 1, limit,
1251 mode_flag, ext_active, buf, rng);
1252 my_idx = tb_push_node(buf, 1.0, (double)attr, split,
1253 (double)li, (double)ri, 0.0);
1254 } else {
1255 int active = ext_active + 1;
1256 int *pool, *lidx, *ridx;
1257 double *coef;
1258 double b = 0.0;
1259 int ln = 0, rn = 0, i, k, li, ri, coff;
1260  
1261 if (active > nv) active = nv;
1262 pool = (int*)malloc(nv * sizeof(int));
1263 memcpy(pool, varying, nv * sizeof(int));
1264 for (i = 0; i < active; i++) {
1265 int j = i + (int)(sm64_drand(rng) * (nv - i));
1266 int tmp = pool[i]; pool[i] = pool[j]; pool[j] = tmp;
1267 }
1268  
1269 coef = (double*)malloc(active * sizeof(double));
1270 for (k = 0; k < active; k++) {
1271 int ff = pool[k];
1272 double c = _ts_randn(rng);
1273 double p = lo[ff] + sm64_drand(rng) * (hi[ff] - lo[ff]);
1274 coef[k] = c;
1275 b += c * p;
1276 }
1277  
1278 lidx = (int*)malloc(size * sizeof(int));
1279 ridx = (int*)malloc(size * sizeof(int));
1280 for (i = 0; i < size; i++) {
1281 int row = idxs[i];
1282 double dot = 0.0;
1283 for (k = 0; k < active; k++) {
1284 dot += coef[k] * x[(size_t)row * (size_t)nf + pool[k]];
1285 }
1286 if (dot <= b) lidx[ln++] = row; else ridx[rn++] = row;
1287 }
1288 free(idxs); free(lo); free(hi); free(varying);
1289  
1290 li = _build_node_packed(x, nf, lidx, ln, depth + 1, limit,
1291 mode_flag, ext_active, buf, rng);
1292 ri = _build_node_packed(x, nf, ridx, rn, depth + 1, limit,
1293 mode_flag, ext_active, buf, rng);
1294 coff = tb_push_coef(buf, pool, coef, active);
1295 my_idx = tb_push_node(buf, 2.0, (double)coff, (double)active,
1296 (double)li, (double)ri, b);
1297 free(pool); free(coef);
1298 }
1299 return my_idx;
1300 }
1301  
1302 void build_forest_openmp_xs(SV* x_sv, int n_pts, int n_feats, int n_trees,
1303 int psi, int limit, int mode_flag,
1304 int ext_level, SV* nodes_rv, SV* idx_rv,
1305 SV* val_rv, int use_openmp) {
1306 dTHX;
1307 STRLEN tl;
1308 const double* x;
1309 AV *nodes_av, *idx_av, *val_av;
1310 TreeBuf *bufs;
1311 uint64_t base_seed;
1312 int t;
1313  
1314 if (!SvROK(nodes_rv) || SvTYPE(SvRV(nodes_rv)) != SVt_PVAV ||
1315 !SvROK(idx_rv) || SvTYPE(SvRV(idx_rv)) != SVt_PVAV ||
1316 !SvROK(val_rv) || SvTYPE(SvRV(val_rv)) != SVt_PVAV) {
1317 croak("build_forest_openmp_xs: nodes/idx/val must be arrayrefs");
1318 }
1319 x = (const double*)SvPVbyte(x_sv, tl);
1320 nodes_av = (AV*)SvRV(nodes_rv);
1321 idx_av = (AV*)SvRV(idx_rv);
1322 val_av = (AV*)SvRV(val_rv);
1323 av_clear(nodes_av); av_clear(idx_av); av_clear(val_av);
1324 if (n_trees > 0) {
1325 av_extend(nodes_av, n_trees - 1);
1326 av_extend(idx_av, n_trees - 1);
1327 av_extend(val_av, n_trees - 1);
1328 }
1329  
1330 /* Single Drand01() call, before the parallel region starts, so it's
1331 * still a plain serial call into the interpreter's RNG state. */
1332 base_seed = (uint64_t)(Drand01() * 18446744073709551615.0);
1333  
1334 bufs = (TreeBuf*)malloc((size_t)n_trees * sizeof(TreeBuf));
1335 for (t = 0; t < n_trees; t++) tb_init(&bufs[t]);
1336  
1337 #ifdef _OPENMP
1338 #pragma omp parallel for schedule(dynamic) if(use_openmp)
1339 #endif
1340 for (int t = 0; t < n_trees; t++) {
1341 /* Seeded from the tree index, not thread id or iteration order,
1342 * so the mapping from tree -> RNG stream is independent of
1343 * OMP_NUM_THREADS / scheduling. sm64_next() mixes once more so
1344 * adjacent tree indices (which differ by one golden-ratio step)
1345 * don't start from too-similar states. */
1346 uint64_t rng = base_seed + (uint64_t)t * 0x9E3779B97F4A7C15ULL;
1347 rng = sm64_next(&rng);
1348 int *all = (int*)malloc((size_t)n_pts * sizeof(int));
1349 int *sample;
1350 int i;
1351  
1352 for (i = 0; i < n_pts; i++) all[i] = i;
1353 for (i = 0; i < psi; i++) {
1354 int j = i + (int)(sm64_drand(&rng) * (n_pts - i));
1355 int tmp = all[i]; all[i] = all[j]; all[j] = tmp;
1356 }
1357 sample = (int*)malloc((size_t)psi * sizeof(int));
1358 memcpy(sample, all, (size_t)psi * sizeof(int));
1359 free(all);
1360  
1361 _build_node_packed(x, n_feats, sample, psi, 0, limit, mode_flag,
1362 ext_level, &bufs[t], &rng);
1363 }
1364  
1365 for (t = 0; t < n_trees; t++) {
1366 /* newSVpvn(NULL, 0) makes an undef SV, not an empty-string one --
1367 * axis-mode trees never call tb_push_coef, so idx/val stay NULL.
1368 * Pass "" instead so the Perl side's unpack('...', $sv) always
1369 * gets a defined (if empty) string, never undef. */
1370 av_store(nodes_av, t, newSVpvn((char*)bufs[t].nodes,
1371 bufs[t].n_nodes * 6 * sizeof(double)));
1372 av_store(idx_av, t, bufs[t].n_idx
1373 ? newSVpvn((char*)bufs[t].idx, bufs[t].n_idx * sizeof(int))
1374 : newSVpvn("", 0));
1375 av_store(val_av, t, bufs[t].n_val
1376 ? newSVpvn((char*)bufs[t].val, bufs[t].n_val * sizeof(double))
1377 : newSVpvn("", 0));
1378 tb_free(&bufs[t]);
1379 }
1380 free(bufs);
1381 }
1382  
1383 /* ---------------------------------------------------------------------
1384 * pack_tree_xs(root_rv, n_features, nodes_sv, idx_sv, val_sv)
1385 *
1386 * C image of _pack_tree: flattens one tree into the three packed buffers
1387 * the scorer walks. _rebuild_c_trees runs it once per tree at the end of
1388 * every fit() and every from_json(), and in Perl each node costs a
1389 * recursive closure call, an arrayref and six SVs, plus a trailing map
1390 * that pushes every one of those SVs back onto the stack for pack() --
1391 * which made it the largest single phase of an axis-mode fit. This is
1392 * the same walk done in C, appending into the TreeBuf above and handing
1393 * the three buffers back as plain strings.
1394 *
1395 * The layout is unchanged: nodes are numbered DFS pre-order (a node's
1396 * record is reserved before its children recurse, so the root is 0 and
1397 * every child index sits above its parent's -- unlike the post-order
1398 * _build_node_packed above), oblique coefficients dense-pack in feature
1399 * order when a node uses every feature, and a leaf's slot 2 carries
1400 * c(size). Output is byte-identical to the Perl path.
1401 *
1402 * The Perl side only calls this on nvsize == 8 perls: c(size) is computed
1403 * here in C doubles, and a wide-NV perl's _c() keeps extra low bits, so
1404 * the stored leaf adjustment would otherwise differ in the last ulp
1405 * between backends -- the same parity concern _NV_IS_DOUBLE guards
1406 * everywhere else.
1407 * ------------------------------------------------------------------ */
1408  
1409 /* Scratch reused across every node of a tree, so packing a node
1410 * allocates nothing. Grown on demand rather than sized once from
1411 * n_features: a model saved before n_features was persisted packs with
1412 * n_features == -1, which leaves no up-front bound on an oblique node's
1413 * coefficient count. */
1414 typedef struct {
1415 double *dense; /* coefficients by feature index, for the dense pack */
1416 int *order; /* 0..cap-1 -- the dense pack's index array */
1417 int *ix; /* sparse pack scratch */
1418 double *cv;
1419 int cap;
1420 } PackScratch;
1421  
1422 static void ps_init(PackScratch *s) {
1423 s->dense = NULL; s->order = NULL; s->ix = NULL; s->cv = NULL; s->cap = 0;
1424 }
1425  
1426 static void ps_free(PackScratch *s) {
1427 free(s->dense); free(s->order); free(s->ix); free(s->cv);
1428 }
1429  
1430 static void ps_reserve(PackScratch *s, int n) {
1431 int k;
1432 if (n <= s->cap) return;
1433 s->dense = (double*)realloc(s->dense, (size_t)n * sizeof(double));
1434 s->order = (int*) realloc(s->order, (size_t)n * sizeof(int));
1435 s->ix = (int*) realloc(s->ix, (size_t)n * sizeof(int));
1436 s->cv = (double*)realloc(s->cv, (size_t)n * sizeof(double));
1437 for (k = s->cap; k < n; k++) s->order[k] = k;
1438 s->cap = n;
1439 }
1440  
1441 /* c(n) -- the expression _c() evaluates, operation for operation. */
1442 static double _pt_c(double n) {
1443 double harmonic;
1444 if (n <= 1.0) return 0.0;
1445 if (n == 2.0) return 1.0;
1446 harmonic = log(n - 1.0) + 0.5772156649015329;
1447 return 2.0 * harmonic - (2.0 * (n - 1.0) / n);
1448 }
1449  
1450 /* Appends the subtree rooted at node_rv to buf; returns its node index. */
1451 static int _pack_node_xs(pTHX_ SV* node_rv, int n_features, TreeBuf* b,
1452 PackScratch* s) {
1453 AV* node;
1454 SV** slots;
1455 int type, my_idx;
1456 double* rec;
1457  
1458 if (!SvROK(node_rv) || SvTYPE(SvRV(node_rv)) != SVt_PVAV) {
1459 croak("pack_tree_xs: tree node is not an arrayref");
1460 }
1461 node = (AV*)SvRV(node_rv);
1462 slots = AvARRAY(node);
1463 type = (int)SvIV(slots[0]);
1464  
1465 /* Reserved before recursing so children are numbered above us. */
1466 my_idx = tb_push_node(b, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
1467  
1468 if (type == 0) {
1469 double size = SvNV(slots[1]);
1470 rec = b->nodes + (size_t)my_idx * IF_NZ;
1471 rec[1] = size;
1472 rec[2] = _pt_c(size); /* the rest of the record stays zero */
1473 } else if (type == 1) {
1474 double attr = SvNV(slots[1]);
1475 double split = SvNV(slots[2]);
1476 int li = _pack_node_xs(aTHX_ slots[3], n_features, b, s);
1477 int ri = _pack_node_xs(aTHX_ slots[4], n_features, b, s);
1478 /* tb_push_node reallocs, so the record's address is only valid
1479 * once the children are back. */
1480 rec = b->nodes + (size_t)my_idx * IF_NZ;
1481 rec[0] = 1.0; rec[1] = attr; rec[2] = split;
1482 rec[3] = (double)li; rec[4] = (double)ri;
1483 } else {
1484 AV *iav, *cav;
1485 double bcoef;
1486 int num, coff, li, ri, k, dense_ok;
1487  
1488 if (!SvROK(slots[1]) || SvTYPE(SvRV(slots[1])) != SVt_PVAV ||
1489 !SvROK(slots[2]) || SvTYPE(SvRV(slots[2])) != SVt_PVAV) {
1490 croak("pack_tree_xs: oblique node needs idx/coef arrayrefs");
1491 }
1492 iav = (AV*)SvRV(slots[1]);
1493 cav = (AV*)SvRV(slots[2]);
1494 bcoef = SvNV(slots[3]);
1495 num = (int)AvFILLp(iav) + 1;
1496 ps_reserve(s, num > n_features ? num : n_features);
1497  
1498 for (k = 0; k < num; k++) {
1499 s->ix[k] = (int)SvIV(AvARRAY(iav)[k]);
1500 s->cv[k] = SvNV(AvARRAY(cav)[k]);
1501 }
1502  
1503 /* Dense pack when the node uses every feature, so val[k] is the
1504 * coefficient for feature k and score_all_xs can take its
1505 * no-gather inner loop. For any tree this module builds the
1506 * indices are a permutation of 0..n_features-1; the range check
1507 * only stops a hand-edited model from walking off the scratch,
1508 * and the zero-fill covers a repeated index leaving a hole. */
1509 dense_ok = (n_features > 0 && num == n_features);
1510 for (k = 0; dense_ok && k < num; k++) {
1511 if (s->ix[k] < 0 || s->ix[k] >= n_features) dense_ok = 0;
1512 }
1513 if (dense_ok) {
1514 memset(s->dense, 0, (size_t)n_features * sizeof(double));
1515 for (k = 0; k < num; k++) s->dense[s->ix[k]] = s->cv[k];
1516 coff = tb_push_coef(b, s->order, s->dense, n_features);
1517 } else {
1518 coff = tb_push_coef(b, s->ix, s->cv, num);
1519 }
1520  
1521 li = _pack_node_xs(aTHX_ slots[4], n_features, b, s);
1522 ri = _pack_node_xs(aTHX_ slots[5], n_features, b, s);
1523 rec = b->nodes + (size_t)my_idx * IF_NZ;
1524 rec[0] = 2.0; rec[1] = (double)coff; rec[2] = (double)num;
1525 rec[3] = (double)li; rec[4] = (double)ri; rec[5] = bcoef;
1526 }
1527 return my_idx;
1528 }
1529  
1530 /* n_features may be -1 ("unknown"), which just disables the dense pack.
1531 * The three output SVs are overwritten with the packed bytes. */
1532 void pack_tree_xs(SV* root_rv, int n_features, SV* nodes_sv, SV* idx_sv,
1533 SV* val_sv) {
1534 dTHX;
1535 TreeBuf b;
1536 PackScratch s;
1537  
1538 tb_init(&b);
1539 ps_init(&s);
1540 _pack_node_xs(aTHX_ root_rv, n_features, &b, &s);
1541 ps_free(&s);
1542  
1543 /* An axis-only tree never calls tb_push_coef, so idx/val stay NULL --
1544 * pass "" so the Perl side always receives a defined string, matching
1545 * what build_forest_openmp_xs hands back. */
1546 sv_setpvn(nodes_sv, (char*)b.nodes, b.n_nodes * IF_NZ * sizeof(double));
1547 sv_setpvn(idx_sv, b.n_idx ? (char*)b.idx : "", b.n_idx * sizeof(int));
1548 sv_setpvn(val_sv, b.n_val ? (char*)b.val : "", b.n_val * sizeof(double));
1549 tb_free(&b);
1550 }
1551  
1552 /* ---------------------------------------------------------------------
1553 * impute_fill_xs(data_sv, n_pts, n_feats, how, out_rv)
1554 *
1555 * C replacement for _compute_impute_fill's Perl loop: walks the raw
1556 * arrayref-of-arrayrefs directly (like pack_input_xs), collecting each
1557 * feature's present (defined) values, then reduces them to one fill
1558 * value per feature -- mean (how == 0) or median (how == 1) -- and
1559 * writes n_feats doubles into out_rv.
1560 *
1561 * Values are collected in row order (i = 0..n_pts-1), the same order
1562 * the Perl version's `grep { defined } map { $_->[$f] } @data` walks
1563 * them in, so the mean's left-to-right summation lands on the exact
1564 * same float as the Perl path -- use_c toggles speed here, not the
1565 * computed fill, matching the rest of the module.
1566 *
1567 * The median is an exact order statistic (not summation-dependent), so
1568 * it matches the Perl path's sort-based median by definition regardless
1569 * of which selection algorithm finds it. Croaks with the same message
1570 * as the Perl fallback if a feature has no present values anywhere in
1571 * the dataset. */
1572 typedef struct { double *v; size_t n, cap; } DVec;
1573  
1574 static void dvec_push(DVec *d, double x) {
1575 if (d->n == d->cap) {
1576 size_t newcap = d->cap ? d->cap * 2 : 64;
1577 d->v = (double*)realloc(d->v, newcap * sizeof(double));
1578 d->cap = newcap;
1579 }
1580 d->v[d->n++] = x;
1581 }
1582  
1583 static void _dswap(double *a, double *b) { double t = *a; *a = *b; *b = t; }
1584  
1585 /* Lomuto partition with a median-of-three pivot (avoids the O(n^2)
1586 * worst case a fixed pivot hits on already-sorted or reverse-sorted
1587 * input, which real feature columns -- timestamps, counters -- often
1588 * are). Returns the pivot's final index. */
1589 static int _partition_lomuto(double *a, int lo, int hi) {
1590 int mid = lo + (hi - lo) / 2;
1591 double pivot;
1592 int i, j;
1593 if (a[mid] < a[lo]) _dswap(&a[lo], &a[mid]);
1594 if (a[hi] < a[lo]) _dswap(&a[lo], &a[hi]);
1595 if (a[hi] < a[mid]) _dswap(&a[mid], &a[hi]);
1596 _dswap(&a[mid], &a[hi]);
1597 pivot = a[hi];
1598 i = lo;
1599 for (j = lo; j < hi; j++) {
1600 if (a[j] < pivot) { _dswap(&a[i], &a[j]); i++; }
1601 }
1602 _dswap(&a[i], &a[hi]);
1603 return i;
1604 }
1605  
1606 /* Quickselect: returns the k-th smallest (0-indexed) of a[0..n-1],
1607 * reordering a[] in the process (fine -- it's a private scratch copy).
1608 * O(n) average case vs. a full O(n log n) sort. */
1609 static double _kth_smallest(double *a, int n, int k) {
1610 int lo = 0, hi = n - 1;
1611 while (lo < hi) {
1612 int p = _partition_lomuto(a, lo, hi);
1613 if (p == k) return a[p];
1614 if (p < k) lo = p + 1; else hi = p - 1;
1615 }
1616 return a[lo];
1617 }
1618  
1619 /* Median of a[0..n-1] (reorders a[]). Odd n: the single middle order
1620 * statistic. Even n: quickselect finds the lower-median at k = n/2-1,
1621 * which leaves every a[i > k] >= a[k] (the standard quickselect
1622 * post-condition) -- so the upper-median is just the min of that
1623 * remaining slice, one more linear scan instead of a second full
1624 * selection pass. */
1625 static double _median_select(double *a, int n) {
1626 if (n % 2 == 1) {
1627 return _kth_smallest(a, n, n / 2);
1628 } else {
1629 int k = n / 2 - 1;
1630 double lower = _kth_smallest(a, n, k);
1631 double upper = a[k + 1];
1632 int i;
1633 for (i = k + 2; i < n; i++) {
1634 if (a[i] < upper) upper = a[i];
1635 }
1636 return (lower + upper) / 2.0;
1637 }
1638 }
1639  
1640 void impute_fill_xs(SV* data_sv, int n_pts, int n_feats, int how,
1641 SV* out_rv) {
1642 dTHX;
1643 AV *outer, *out;
1644 DVec *cols;
1645 int i, f;
1646  
1647 if (!SvROK(data_sv) || SvTYPE(SvRV(data_sv)) != SVt_PVAV) {
1648 croak("impute_fill_xs: data must be an arrayref");
1649 }
1650 if (!SvROK(out_rv) || SvTYPE(SvRV(out_rv)) != SVt_PVAV) {
1651 croak("impute_fill_xs: out must be an arrayref");
1652 }
1653 outer = (AV*)SvRV(data_sv);
1654 out = (AV*)SvRV(out_rv);
1655  
1656 cols = (DVec*)calloc((size_t)n_feats, sizeof(DVec));
1657  
1658 for (i = 0; i < n_pts; i++) {
1659 SV** row_pp = av_fetch(outer, i, 0);
1660 AV* row;
1661 if (!row_pp || !*row_pp || !SvROK(*row_pp) ||
1662 SvTYPE(SvRV(*row_pp)) != SVt_PVAV) {
1663 continue;
1664 }
1665 row = (AV*)SvRV(*row_pp);
1666 for (f = 0; f < n_feats; f++) {
1667 SV** v = av_fetch(row, f, 0);
1668 if (v && *v && SvOK(*v)) {
1669 dvec_push(&cols[f], SvNV(*v));
1670 }
1671 }
1672 }
1673  
1674 /* Validate every column before freeing anything: croak() longjmps
1675 * out of this function, so any cleanup loop reachable after a
1676 * partial computation has already started (and already freed some
1677 * cols[i].v) risks a double free on those same pointers. Checking
1678 * all columns up front, before the computation loop below frees
1679 * anything, avoids that entirely. Matches the Perl fallback's
1680 * behaviour of reporting the first empty column in feature order. */
1681 for (f = 0; f < n_feats; f++) {
1682 if (cols[f].n == 0) {
1683 int col = f;
1684 for (i = 0; i < n_feats; i++) free(cols[i].v);
1685 free(cols);
1686 croak("impute: feature column %d has no present values", col);
1687 }
1688 }
1689  
1690 av_clear(out);
1691 if (n_feats > 0) av_extend(out, n_feats - 1);
1692  
1693 for (f = 0; f < n_feats; f++) {
1694 double result;
1695 if (how == 0) {
1696 double sum = 0.0;
1697 for (i = 0; i < (int)cols[f].n; i++) sum += cols[f].v[i];
1698 result = sum / (double)cols[f].n;
1699 } else {
1700 result = _median_select(cols[f].v, (int)cols[f].n);
1701 }
1702 av_store(out, f, newSVnv(result));
1703 free(cols[f].v);
1704 }
1705 free(cols);
1706 }
1707  
1708 /* ---------------------------------------------------------------------
1709 * Online Isolation Forest (Algorithm::Classifier::IsolationForest::
1710 * Online) learn / unlearn / score-row accelerators.
1711 *
1712 * Unlike everything above, these operate directly on LIVE Perl
1713 * arrayref trees: online trees mutate on every learned point, so there
1714 * is no immutable packed form to walk during learning. Node layout
1715 * (Online.pm's _N_* constants):
1716 *
1717 * leaf: [0, count, \@lo, \@hi]
1718 * internal: [1, count, \@lo, \@hi, attr, split, left, right]
1719 *
1720 * and a tree record is a hashref { root, count, depth_limit }; root is
1721 * undef until the tree learns its first point, and a leaf built from an
1722 * empty synthetic partition has undef lo/hi until a real point reaches
1723 * it.
1724 *
1725 * Random draws go through Drand01() in EXACTLY the order the pure-Perl
1726 * learn path calls rand(): an optional per-tree subsample gate (drawn
1727 * only when subsample < 1), and -- only when a leaf splits --
1728 * count * nf box-sample draws that SKIP zero-width features (the Perl
1729 * _sample_box never draws for those), then per synthetic internal node
1730 * one draw for the split feature and one for the split value, recursing
1731 * left before right. A learn() with a given seed therefore produces
1732 * BIT-IDENTICAL trees whether use_c is on or off (on nvsize == 8 perls;
1733 * wide-NV perls keep extra low bits in the pure-Perl path, as with
1734 * fit()), which is what lets the online class reuse the existing use_c
1735 * knob for learning instead of growing a new one.
1736 * ------------------------------------------------------------------ */
1737  
1738 #define OL_TYPE 0
1739 #define OL_COUNT 1
1740 #define OL_LO 2
1741 #define OL_HI 3
1742 #define OL_ATTR 4
1743 #define OL_SPLIT 5
1744 #define OL_LEFT 6
1745 #define OL_RIGHT 7
1746  
1747 /* ln(4) as the exact double Perl's compile-time log(4) produces --
1748 * spelled as a literal (like TWO_PI on the Perl side) so a compiler
1749 * that constant-folds log(4.0) differently from libm cannot introduce
1750 * a one-ulp parity break in the depth budget. */
1751 #define OL_LOG4 1.3862943611198906
1752  
1753 /* Depth budget for n points -- the C image of Online.pm's _rpl(). */
1754 static double _ol_rpl(double n, int eta) {
1755 if (n < (double)eta) return 0.0;
1756 return log(n / (double)eta) / OL_LOG4;
1757 }
1758  
1759 /* Points a node at `depth` needs before it may split (below which, on
1760 * forgetting, it collapses back into a leaf) -- _split_threshold().
1761 * ldexp keeps the adaptive 2**depth factor exact, matching Perl's
1762 * NV exponentiation. */
1763 static double _ol_split_threshold(int eta, int adaptive, int depth) {
1764 return (double)eta * (adaptive ? ldexp(1.0, depth) : 1.0);
1765 }
1766  
1767 /* Fresh [v0 .. v(nf-1)] arrayref (a bounding-box side). */
1768 static SV* _ol_mk_box(pTHX_ const double* v, int nf) {
1769 AV* av = newAV();
1770 int k;
1771 av_extend(av, nf - 1);
1772 for (k = 0; k < nf; k++) AvARRAY(av)[k] = newSVnv(v[k]);
1773 AvFILLp(av) = nf - 1;
1774 return newRV_noinc((SV*)av);
1775 }
1776  
1777 /* lo_rv/hi_rv may be NULL => undef box (leaf from an empty synthetic
1778 * partition). Takes ownership of non-NULL refs. */
1779 static SV* _ol_mk_leaf(pTHX_ IV count, SV* lo_rv, SV* hi_rv) {
1780 AV* av = newAV();
1781 av_extend(av, 3);
1782 AvARRAY(av)[0] = newSViv(0);
1783 AvARRAY(av)[1] = newSViv(count);
1784 AvARRAY(av)[2] = lo_rv ? lo_rv : &PL_sv_undef;
1785 AvARRAY(av)[3] = hi_rv ? hi_rv : &PL_sv_undef;
1786 AvFILLp(av) = 3;
1787 return newRV_noinc((SV*)av);
1788 }
1789  
1790 static SV* _ol_mk_axis(pTHX_ IV count, SV* lo_rv, SV* hi_rv, int attr,
1791 double split, SV* left, SV* right) {
1792 AV* av = newAV();
1793 av_extend(av, 7);
1794 AvARRAY(av)[0] = newSViv(1);
1795 AvARRAY(av)[1] = newSViv(count);
1796 AvARRAY(av)[2] = lo_rv;
1797 AvARRAY(av)[3] = hi_rv;
1798 AvARRAY(av)[4] = newSViv(attr);
1799 AvARRAY(av)[5] = newSVnv(split);
1800 AvARRAY(av)[6] = left;
1801 AvARRAY(av)[7] = right;
1802 AvFILLp(av) = 7;
1803 return newRV_noinc((SV*)av);
1804 }
1805  
1806 /* Recursively build a subtree over synthetic points (row indices into
1807 * pts, a rows x nf buffer) -- the C image of _build_from_points(), in
1808 * the same draw order: split feature, split value, left subtree, right
1809 * subtree. The partition is stable, matching the Perl push loop. */
1810 static SV* _ol_build(pTHX_ const double* pts, const int* idx, int n, int nf,
1811 int depth, double limit, int eta, int adaptive) {
1812 SV *lo_rv = NULL, *hi_rv = NULL;
1813 int i, f;
1814  
1815 if (n > 0) {
1816 double* lo = (double*)malloc(nf * sizeof(double));
1817 double* hi = (double*)malloc(nf * sizeof(double));
1818 const double* p0 = pts + (size_t)idx[0] * (size_t)nf;
1819 for (f = 0; f < nf; f++) { lo[f] = p0[f]; hi[f] = p0[f]; }
1820 for (i = 0; i < n; i++) {
1821 const double* p = pts + (size_t)idx[i] * (size_t)nf;
1822 for (f = 0; f < nf; f++) {
1823 if (p[f] < lo[f]) lo[f] = p[f];
1824 if (p[f] > hi[f]) hi[f] = p[f];
1825 }
1826 }
1827 lo_rv = _ol_mk_box(aTHX_ lo, nf);
1828 hi_rv = _ol_mk_box(aTHX_ hi, nf);
1829 free(lo);
1830 free(hi);
1831 }
1832  
1833 if ((double)n < _ol_split_threshold(eta, adaptive, depth) ||
1834 (double)depth >= limit) {
1835 return _ol_mk_leaf(aTHX_ (IV)n, lo_rv, hi_rv);
1836 }
1837  
1838 {
1839 int attr = (int)(Drand01() * nf);
1840 double pmin = pts[(size_t)idx[0] * (size_t)nf + attr];
1841 double pmax = pmin;
1842 double split;
1843 int *l, *r, ln = 0, rn = 0;
1844 SV *left, *right;
1845  
1846 for (i = 0; i < n; i++) {
1847 double v = pts[(size_t)idx[i] * (size_t)nf + attr];
1848 if (v < pmin) pmin = v;
1849 if (v > pmax) pmax = v;
1850 }
1851 split = pmin + Drand01() * (pmax - pmin);
1852  
1853 l = (int*)malloc(n * sizeof(int));
1854 r = (int*)malloc(n * sizeof(int));
1855 for (i = 0; i < n; i++) {
1856 if (pts[(size_t)idx[i] * (size_t)nf + attr] < split) l[ln++] = idx[i];
1857 else r[rn++] = idx[i];
1858 }
1859 left = _ol_build(aTHX_ pts, l, ln, nf, depth + 1, limit, eta, adaptive);
1860 right = _ol_build(aTHX_ pts, r, rn, nf, depth + 1, limit, eta, adaptive);
1861 free(l);
1862 free(r);
1863 return _ol_mk_axis(aTHX_ (IV)n, lo_rv, hi_rv, attr, split, left, right);
1864 }
1865 }
1866  
1867 /* Route one point down, growing counts and boxes -- _node_learn().
1868 * Returns the (possibly replaced) node ref; a changed return is stored
1869 * back by the caller, exactly like the Perl recursion's assignment.
1870 * When a leaf is replaced by a freshly built subtree the return value
1871 * is a new ref with refcount 1 and the caller's store drops the old
1872 * leaf's reference. */
1873 static SV* _ol_node_learn(pTHX_ SV* node_rv, const double* x, int nf,
1874 int depth, double limit, int eta, int adaptive) {
1875 AV* node = (AV*)SvRV(node_rv);
1876 SV** slots = AvARRAY(node);
1877 IV count = SvIV(slots[OL_COUNT]) + 1;
1878 int f;
1879  
1880 sv_setiv(slots[OL_COUNT], count);
1881  
1882 if (!SvOK(slots[OL_LO])) {
1883 /* Leaf born from an empty synthetic partition: the first real
1884 * point initialises the box. */
1885 av_store(node, OL_LO, _ol_mk_box(aTHX_ x, nf));
1886 av_store(node, OL_HI, _ol_mk_box(aTHX_ x, nf));
1887 slots = AvARRAY(node);
1888 } else {
1889 AV* lo = (AV*)SvRV(slots[OL_LO]);
1890 AV* hi = (AV*)SvRV(slots[OL_HI]);
1891 for (f = 0; f < nf; f++) {
1892 SV** lv = av_fetch(lo, f, 1);
1893 SV** hv = av_fetch(hi, f, 1);
1894 if (x[f] < SvNV(*lv)) sv_setnv(*lv, x[f]);
1895 if (x[f] > SvNV(*hv)) sv_setnv(*hv, x[f]);
1896 }
1897 }
1898  
1899 if (SvIV(slots[OL_TYPE]) == 0) { /* leaf */
1900 if ((double)count >= _ol_split_threshold(eta, adaptive, depth) &&
1901 (double)depth < limit) {
1902 AV* lo = (AV*)SvRV(AvARRAY(node)[OL_LO]);
1903 AV* hi = (AV*)SvRV(AvARRAY(node)[OL_HI]);
1904 double* lod = (double*)malloc(nf * sizeof(double));
1905 double* hid = (double*)malloc(nf * sizeof(double));
1906 double* pts = (double*)malloc((size_t)count * (size_t)nf * sizeof(double));
1907 int* idx = (int*)malloc((size_t)count * sizeof(int));
1908 SV* subtree;
1909 int i;
1910  
1911 for (f = 0; f < nf; f++) {
1912 SV** lv = av_fetch(lo, f, 0);
1913 SV** hv = av_fetch(hi, f, 0);
1914 lod[f] = (lv && *lv && SvOK(*lv)) ? SvNV(*lv) : 0.0;
1915 hid[f] = (hv && *hv && SvOK(*hv)) ? SvNV(*hv) : 0.0;
1916 }
1917 /* Synthetic points, point-major, one draw per feature with
1918 * width > 0 -- _sample_box's exact draw order. */
1919 for (i = 0; i < (int)count; i++) {
1920 for (f = 0; f < nf; f++) {
1921 double w = hid[f] - lod[f];
1922 pts[(size_t)i * (size_t)nf + f]
1923 = (w > 0) ? lod[f] + Drand01() * w : lod[f];
1924 }
1925 idx[i] = i;
1926 }
1927 subtree = _ol_build(aTHX_ pts, idx, (int)count, nf, depth, limit,
1928 eta, adaptive);
1929 free(lod);
1930 free(hid);
1931 free(pts);
1932 free(idx);
1933 return subtree;
1934 }
1935 return node_rv;
1936 }
1937  
1938 {
1939 int attr = (int)SvIV(slots[OL_ATTR]);
1940 double split = SvNV(slots[OL_SPLIT]);
1941 int ci = (x[attr] < split) ? OL_LEFT : OL_RIGHT;
1942 SV* child = AvARRAY(node)[ci];
1943 SV* nc = _ol_node_learn(aTHX_ child, x, nf, depth + 1, limit, eta,
1944 adaptive);
1945 if (nc != child) av_store(node, ci, nc);
1946 return node_rv;
1947 }
1948 }
1949  
1950 /* Union of two nodes' boxes into caller-provided arrays, matching
1951 * _box_union(): nodes without a box are skipped, the first boxed node
1952 * is copied and the second folded in. Returns 0 when neither node has
1953 * a box. */
1954 static int _ol_box_union(pTHX_ SV* a_rv, SV* b_rv, int nf,
1955 double* lo, double* hi) {
1956 SV* boxed[2];
1957 int nb = 0, bi, f;
1958  
1959 if (SvOK(AvARRAY((AV*)SvRV(a_rv))[OL_LO])) boxed[nb++] = a_rv;
1960 if (SvOK(AvARRAY((AV*)SvRV(b_rv))[OL_LO])) boxed[nb++] = b_rv;
1961 if (nb == 0) return 0;
1962  
1963 for (bi = 0; bi < nb; bi++) {
1964 AV* node = (AV*)SvRV(boxed[bi]);
1965 AV* blo = (AV*)SvRV(AvARRAY(node)[OL_LO]);
1966 AV* bhi = (AV*)SvRV(AvARRAY(node)[OL_HI]);
1967 for (f = 0; f < nf; f++) {
1968 SV** lv = av_fetch(blo, f, 0);
1969 SV** hv = av_fetch(bhi, f, 0);
1970 double l = (lv && *lv && SvOK(*lv)) ? SvNV(*lv) : 0.0;
1971 double h = (hv && *hv && SvOK(*hv)) ? SvNV(*hv) : 0.0;
1972 if (bi == 0) {
1973 lo[f] = l;
1974 hi[f] = h;
1975 } else {
1976 if (l < lo[f]) lo[f] = l;
1977 if (h > hi[f]) hi[f] = h;
1978 }
1979 }
1980 }
1981 return 1;
1982 }
1983  
1984 /* Aggregate a subtree back into one leaf -- _collapse(). Children are
1985 * collapsed first so their boxes can be unioned; intermediate leaves
1986 * built while collapsing internal children are temporaries and dropped
1987 * here. Returns a NEW leaf ref (refcount 1) for internal nodes, or the
1988 * node itself when it is already a leaf. */
1989 static SV* _ol_collapse(pTHX_ SV* node_rv, int nf) {
1990 AV* node = (AV*)SvRV(node_rv);
1991 SV *l_rv, *r_rv, *cl, *cr, *leaf;
1992 SV *lo_rv = NULL, *hi_rv = NULL;
1993 double *lo, *hi;
1994  
1995 if (SvIV(AvARRAY(node)[OL_TYPE]) == 0) return node_rv;
1996  
1997 l_rv = AvARRAY(node)[OL_LEFT];
1998 r_rv = AvARRAY(node)[OL_RIGHT];
1999 cl = _ol_collapse(aTHX_ l_rv, nf);
2000 cr = _ol_collapse(aTHX_ r_rv, nf);
2001  
2002 lo = (double*)malloc(nf * sizeof(double));
2003 hi = (double*)malloc(nf * sizeof(double));
2004 if (_ol_box_union(aTHX_ cl, cr, nf, lo, hi)) {
2005 lo_rv = _ol_mk_box(aTHX_ lo, nf);
2006 hi_rv = _ol_mk_box(aTHX_ hi, nf);
2007 } else if (SvOK(AvARRAY(node)[OL_LO])) {
2008 /* Both children boxless: keep the node's own box (the Perl code
2009 * moves the same arrayrefs into the new leaf). */
2010 lo_rv = SvREFCNT_inc(AvARRAY(node)[OL_LO]);
2011 hi_rv = SvREFCNT_inc(AvARRAY(node)[OL_HI]);
2012 }
2013 free(lo);
2014 free(hi);
2015  
2016 leaf = _ol_mk_leaf(aTHX_ SvIV(AvARRAY(node)[OL_COUNT]), lo_rv, hi_rv);
2017 if (cl != l_rv) SvREFCNT_dec(cl);
2018 if (cr != r_rv) SvREFCNT_dec(cr);
2019 return leaf;
2020 }
2021  
2022 /* Route the forgotten point down, decrementing counts -- _node_unlearn().
2023 * An internal node whose count no longer justifies its split collapses;
2024 * otherwise its box is refreshed to the union of its children's. */
2025 static SV* _ol_node_unlearn(pTHX_ SV* node_rv, const double* x, int nf,
2026 int depth, int eta, int adaptive) {
2027 AV* node = (AV*)SvRV(node_rv);
2028 SV** slots = AvARRAY(node);
2029 IV count = SvIV(slots[OL_COUNT]) - 1;
2030  
2031 sv_setiv(slots[OL_COUNT], count);
2032  
2033 if (SvIV(slots[OL_TYPE]) == 0) return node_rv;
2034 if ((double)count < _ol_split_threshold(eta, adaptive, depth)) {
2035 return _ol_collapse(aTHX_ node_rv, nf);
2036 }
2037  
2038 {
2039 int attr = (int)SvIV(slots[OL_ATTR]);
2040 double split = SvNV(slots[OL_SPLIT]);
2041 int ci = (x[attr] < split) ? OL_LEFT : OL_RIGHT;
2042 SV* child = AvARRAY(node)[ci];
2043 double *lo, *hi;
2044 SV* nc = _ol_node_unlearn(aTHX_ child, x, nf, depth + 1, eta,
2045 adaptive);
2046 if (nc != child) av_store(node, ci, nc);
2047  
2048 lo = (double*)malloc(nf * sizeof(double));
2049 hi = (double*)malloc(nf * sizeof(double));
2050 if (_ol_box_union(aTHX_ AvARRAY(node)[OL_LEFT],
2051 AvARRAY(node)[OL_RIGHT], nf, lo, hi)) {
2052 av_store(node, OL_LO, _ol_mk_box(aTHX_ lo, nf));
2053 av_store(node, OL_HI, _ol_mk_box(aTHX_ hi, nf));
2054 }
2055 free(lo);
2056 free(hi);
2057 return node_rv;
2058 }
2059 }
2060  
2061 /* Read one sample row (arrayref) into a dense double buffer; undef -> 0,
2062 * matching the pure-Perl paths (learn rows are pre-densified anyway). */
2063 static void _ol_read_row(pTHX_ SV* row_sv, double* x, int nf) {
2064 AV* row;
2065 int f;
2066 if (!SvROK(row_sv) || SvTYPE(SvRV(row_sv)) != SVt_PVAV)
2067 croak("online row must be an arrayref");
2068 row = (AV*)SvRV(row_sv);
2069 for (f = 0; f < nf; f++) {
2070 SV** v = av_fetch(row, f, 0);
2071 x[f] = (v && *v && SvOK(*v)) ? SvNV(*v) : 0.0;
2072 }
2073 }
2074  
2075 /* Fetch tree t of the trees arrayref as its underlying HV. */
2076 static HV* _ol_tree_hv(pTHX_ AV* trees, int t) {
2077 SV** tp = av_fetch(trees, t, 0);
2078 if (!tp || !*tp || !SvROK(*tp) || SvTYPE(SvRV(*tp)) != SVt_PVHV)
2079 croak("online tree %d is not a hashref", t);
2080 return (HV*)SvRV(*tp);
2081 }
2082  
2083 /* online_learn_row_xs(trees_av, row_av, nf, eta, adaptive, subsample)
2084 *
2085 * The C image of _learn_row's per-tree loop: every tree (subject to the
2086 * subsample gate) learns the row, with count / depth_limit bookkeeping
2087 * on the tree hash. Mutates the live trees in place. */
2088 void online_learn_row_xs(SV* trees_av_sv, SV* row_sv, int nf, int eta,
2089 int adaptive, double subsample) {
2090 dTHX;
2091 AV* trees;
2092 double* x;
2093 int t, n_trees;
2094  
2095 if (!SvROK(trees_av_sv) || SvTYPE(SvRV(trees_av_sv)) != SVt_PVAV)
2096 croak("online_learn_row_xs: trees must be an arrayref");
2097 trees = (AV*)SvRV(trees_av_sv);
2098 n_trees = (int)av_len(trees) + 1;
2099  
2100 x = (double*)malloc(nf * sizeof(double));
2101 _ol_read_row(aTHX_ row_sv, x, nf);
2102  
2103 for (t = 0; t < n_trees; t++) {
2104 HV* tree;
2105 SV **csv, **dsv, **rsv;
2106 IV count;
2107 double limit;
2108  
2109 if (subsample < 1.0 && Drand01() >= subsample) continue;
2110 tree = _ol_tree_hv(aTHX_ trees, t);
2111  
2112 csv = hv_fetch(tree, "count", 5, 1);
2113 count = (SvOK(*csv) ? SvIV(*csv) : 0) + 1;
2114 sv_setiv(*csv, count);
2115 limit = _ol_rpl((double)count, eta);
2116 dsv = hv_fetch(tree, "depth_limit", 11, 1);
2117 sv_setnv(*dsv, limit);
2118  
2119 rsv = hv_fetch(tree, "root", 4, 1);
2120 if (!SvOK(*rsv)) {
2121 (void)hv_store(tree, "root", 4,
2122 _ol_mk_leaf(aTHX_ 1, _ol_mk_box(aTHX_ x, nf),
2123 _ol_mk_box(aTHX_ x, nf)), 0);
2124 } else {
2125 SV* root = *rsv;
2126 SV* nr = _ol_node_learn(aTHX_ root, x, nf, 0, limit, eta,
2127 adaptive);
2128 if (nr != root) (void)hv_store(tree, "root", 4, nr, 0);
2129 }
2130 }
2131 free(x);
2132 }
2133  
2134 /* online_unlearn_row_xs(trees_av, row_av, nf, eta, adaptive, subsample)
2135 *
2136 * The C image of _learn_row's eviction loop (_tree_unlearn per tree,
2137 * behind the same independent subsample gate). */
2138 void online_unlearn_row_xs(SV* trees_av_sv, SV* row_sv, int nf, int eta,
2139 int adaptive, double subsample) {
2140 dTHX;
2141 AV* trees;
2142 double* x;
2143 int t, n_trees;
2144  
2145 if (!SvROK(trees_av_sv) || SvTYPE(SvRV(trees_av_sv)) != SVt_PVAV)
2146 croak("online_unlearn_row_xs: trees must be an arrayref");
2147 trees = (AV*)SvRV(trees_av_sv);
2148 n_trees = (int)av_len(trees) + 1;
2149  
2150 x = (double*)malloc(nf * sizeof(double));
2151 _ol_read_row(aTHX_ row_sv, x, nf);
2152  
2153 for (t = 0; t < n_trees; t++) {
2154 HV* tree;
2155 SV **csv, **dsv, **rsv;
2156 IV count;
2157  
2158 if (subsample < 1.0 && Drand01() >= subsample) continue;
2159 tree = _ol_tree_hv(aTHX_ trees, t);
2160  
2161 csv = hv_fetch(tree, "count", 5, 1);
2162 count = (SvOK(*csv) ? SvIV(*csv) : 0) - 1;
2163 sv_setiv(*csv, count);
2164 dsv = hv_fetch(tree, "depth_limit", 11, 1);
2165 sv_setnv(*dsv, _ol_rpl((double)count, eta));
2166  
2167 rsv = hv_fetch(tree, "root", 4, 0);
2168 if (rsv && *rsv && SvOK(*rsv)) {
2169 SV* root = *rsv;
2170 SV* nr = _ol_node_unlearn(aTHX_ root, x, nf, 0, eta, adaptive);
2171 if (nr != root) (void)hv_store(tree, "root", 4, nr, 0);
2172 }
2173 }
2174 free(x);
2175 }
2176  
2177 /* online_score_row_xs(trees_av, row_av, nf, eta)
2178 *
2179 * Depth sum of one row across the live trees (walk + per-leaf _rpl
2180 * adjustment) -- the C image of _score_row's loop, used by the
2181 * prequential score_learn path where trees mutate between rows and the
2182 * packed-snapshot scorer can never amortise. Draws nothing. */
2183 double online_score_row_xs(SV* trees_av_sv, SV* row_sv, int nf, int eta) {
2184 dTHX;
2185 AV* trees;
2186 double* x;
2187 double sum = 0.0;
2188 int t, n_trees;
2189  
2190 if (!SvROK(trees_av_sv) || SvTYPE(SvRV(trees_av_sv)) != SVt_PVAV)
2191 croak("online_score_row_xs: trees must be an arrayref");
2192 trees = (AV*)SvRV(trees_av_sv);
2193 n_trees = (int)av_len(trees) + 1;
2194  
2195 x = (double*)malloc(nf * sizeof(double));
2196 _ol_read_row(aTHX_ row_sv, x, nf);
2197  
2198 for (t = 0; t < n_trees; t++) {
2199 HV* tree = _ol_tree_hv(aTHX_ trees, t);
2200 SV** rsv = hv_fetch(tree, "root", 4, 0);
2201 AV* node;
2202 SV** slots;
2203 int depth = 0;
2204  
2205 if (!rsv || !*rsv || !SvOK(*rsv)) continue;
2206 node = (AV*)SvRV(*rsv);
2207 slots = AvARRAY(node);
2208 while (SvIV(slots[OL_TYPE]) != 0) {
2209 int attr = (int)SvIV(slots[OL_ATTR]);
2210 double split = SvNV(slots[OL_SPLIT]);
2211 node = (AV*)SvRV(slots[(x[attr] < split) ? OL_LEFT : OL_RIGHT]);
2212 slots = AvARRAY(node);
2213 depth++;
2214 }
2215 sum += (double)depth + _ol_rpl((double)SvIV(slots[OL_COUNT]), eta);
2216 }
2217 free(x);
2218 return sum;
2219 }
2220 __INLINE_C__
2221  
2222 # IF_NO_C=1 skips even attempting to set up the C backend -- useful for
2223 # forcing the pure-Perl path without touching every constructor call
2224 # (use_c => 0), e.g. to get a clean timing baseline or to avoid the
2225 # compile attempt's overhead/noise in a container known to lack a
2226 # compiler. Everything below is skipped and $HAS_C stays 0.
2227 132 ▶ unless ( $ENV{IF_NO_C} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ENV{"IF_NO_C"}) 130 2 132
2228  
2229 # Defaults recorded when `perl Makefile.PL` ran. Makefile.PL generates
2230 # Algorithm::Classifier::IsolationForest::BuildFlags, capturing the
2231 # IF_* values active at configure time plus whether a prebuilt object
2232 # was scheduled for install (see "Compile at install time" in the POD
2233 # below). From a plain source checkout the generated file is absent,
2234 # the hard defaults here apply, and no prebuilt object is looked for.
2235 130 my ( $def_opt, $def_arch, $def_no_omp, $prebuilt ) = ( '-O3', '', 0, 0 );
2236 {
2237 130 local $@;
2238 130 my $rec = eval {
2239 130 require Algorithm::Classifier::IsolationForest::BuildFlags;
2240 130 Algorithm::Classifier::IsolationForest::BuildFlags::flags();
2241 };
2242 130 ▶ if ( ref $rec eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rec eq "HASH") 130 0 130
2243 130 ▶ $def_opt = $rec->{opt} if defined $rec->{opt};
Branch: 1 branch
BranchTrueFalseTotal
if defined $rec->{"opt"} 130 0 130
2244 130 ▶ $def_arch = $rec->{arch} if defined $rec->{arch};
Branch: 1 branch
BranchTrueFalseTotal
if defined $rec->{"arch"} 130 0 130
2245 130 ▶ $def_no_omp = $rec->{no_openmp} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$rec->{'no_openmp'} ? : 0 130 130
2246 130 ▶ $prebuilt = $rec->{prebuilt} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$rec->{'prebuilt'} ? : 0 130 130
2247 }
2248 }
2249  
2250 # -O3 is the usual default: it's safe to enable unconditionally and
2251 # matters here -- the extended-mode oblique dot product is wrapped in
2252 # `#pragma omp simd`, but without aggressive optimization the compiler
2253 # may still emit scalar code. Use OPTIMIZE (not CCFLAGS) -- CCFLAGS is
2254 # prepended to the cc line and would be shadowed by Perl's own `-O2 -g`
2255 # that ExtUtils::MakeMaker appends afterward (last `-O` wins in gcc).
2256 # IF_OPT overrides the level itself (e.g. IF_OPT=-O2 to work around a
2257 # miscompile, or to shorten build time while developing); it's
2258 # validated against a fixed set of GCC/Clang -O flags rather than
2259 # interpolated as-is, since this string eventually reaches a shell
2260 # command line via ExtUtils::MakeMaker.
2261 130 my $opt = $def_opt;
2262 130 ▶ if ( defined $ENV{IF_OPT} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{"IF_OPT"}) 2 128 130
2263 2 ▶ if ( $ENV{IF_OPT} =~ /\A-O[0123sgz]\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'IF_OPT'} =~ /\A-O[0123sgz]\z/) { } 1 1 2
2264 1 $opt = $ENV{IF_OPT};
2265 } else {
2266 1 warn "Algorithm::Classifier::IsolationForest: ignoring invalid "
2267 . "IF_OPT value '$ENV{IF_OPT}' (expected one of -O0 -O1 -O2 "
2268 . "-O3 -Os -Og -Oz); using $opt\n";
2269 }
2270 }
2271  
2272 # -march=<value> lets the compiler target specific instruction-set
2273 # extensions (AVX2 gather + FMA, etc.) for the oblique dot product
2274 # and the fit-time min/max scan's `#pragma omp simd` loops.
2275 #
2276 # IF_ARCH=<value> sets it explicitly (e.g. "x86-64-v3", "skylake",
2277 # "znver3") -- validated against a conservative identifier charset
2278 # since, like IF_OPT, it flows into a compiler command line.
2279 # IF_NATIVE=1 remains as shorthand for IF_ARCH=native and is used
2280 # when IF_ARCH isn't set. Prefer a specific IF_ARCH value over
2281 # IF_NATIVE on a machine you don't control exclusively: blanket
2282 # -march=native pulls in whatever the build host has, including
2283 # AVX-512 on some Intel CPUs, which is known to trigger clock
2284 # throttling under sustained heavy use and can make throughput
2285 # *worse* than a conservative target like x86-64-v3 (AVX2, no
2286 # AVX-512). Either way, the cached artefact under _Inline/ is then
2287 # pinned to that instruction set, so leave both unset if the
2288 # directory is shared across machines with different CPUs.
2289 130 my $arch = $def_arch;
2290 130 ▶ if ( defined $ENV{IF_ARCH} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $ENV{'IF_ARCH'}) { } 4 126 130
elsif ($ENV{'IF_NATIVE'}) { } 1 125 126
2291 4 ▶ if ( $ENV{IF_ARCH} eq '' or $ENV{IF_ARCH} eq 'none' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ENV{'IF_ARCH'} eq '' or $ENV{'IF_ARCH'} eq 'none') { } 1 3 4
elsif ($ENV{'IF_ARCH'} =~ /\A[A-Za-z0-9_.+=-]+\z/) { } 2 1 3
Condition66%2/3
$ENV{"IF_ARCH"} eq "" or $ENV{"IF_ARCH"} eq "none"
l!l&&r!l&&!r
013
MC/DC50%1/2
$ENV{"IF_ARCH"} eq "" or $ENV{"IF_ARCH"} eq "none"
$ENV{"IF_ARCH"} eq "" $ENV{"IF_ARCH"} eq "none"
Truth table66%2/3
A or B
A= $ENV{"IF_ARCH"} eq ""B= $ENV{"IF_ARCH"} eq "none"
ABresult
1X1
011
000
2292  
2293 # Explicit opt-out: overrides an arch recorded at configure
2294 # time (there is no other way to request a plain build on
2295 # an install configured with IF_ARCH).
2296 1 $arch = '';
2297 } elsif ( $ENV{IF_ARCH} =~ /\A[A-Za-z0-9_.+=-]+\z/ ) {
2298 2 $arch = $ENV{IF_ARCH};
2299 } else {
2300 1 warn "Algorithm::Classifier::IsolationForest: ignoring invalid " . "IF_ARCH value '$ENV{IF_ARCH}'\n";
2301 }
2302 } elsif ( $ENV{IF_NATIVE} ) {
2303 1 $arch = 'native';
2304 }
2305 # -ffp-contract=off rides along with any -march: once the target
2306 # has FMA (x86-64-v3, most -march=native hosts), the compiler may
2307 # otherwise contract a*b+c expressions into fused multiply-adds
2308 # whose different rounding breaks the documented guarantee that
2309 # use_c => 1 and use_c => 0 build bit-identical trees (one ulp in a
2310 # split value cascades into a structurally different tree). The
2311 # -march speedup comes from AVX2 vectorization, not contraction,
2312 # so this costs little (verified against the fit-determinism and
2313 # scoring-parity tests).
2314 130 my $opt_level = $opt;
2315 130 ▶ $opt_level .= " -march=$arch -ffp-contract=off" if length $arch;
Branch: 1 branch
BranchTrueFalseTotal
if length $arch 3 127 130
2316  
2317 # IF_NO_OPENMP=1 forces the serial C build: the OpenMP compile attempt
2318 # is skipped, so the object has no libgomp linkage and never starts an
2319 # OpenMP runtime in the process. Distinct from OMP_NUM_THREADS=1,
2320 # which runs the parallel code on a single thread but still loads
2321 # libgomp. An explicit IF_NO_OPENMP=0 re-enables OpenMP over a
2322 # no-openmp configure-time default.
2323 my $no_omp
2324 = defined $ENV{IF_NO_OPENMP}
2325 130 ▶ ? ( $ENV{IF_NO_OPENMP} ? 1 : 0 )
Branch: 2 branches
BranchTrueFalseTotal
defined $ENV{'IF_NO_OPENMP'} ? : 1 129 130
$ENV{'IF_NO_OPENMP'} ? : 1 0 1
2326 : $def_no_omp;
2327  
2328 # The prebuilt object is only trusted when the effective flags match
2329 # what it was compiled with; any difference -- or an explicit
2330 # IF_RUNTIME_BUILD=1 -- falls through to the classic runtime Inline::C
2331 # build below, which honours the requested flags via the MD5-keyed
2332 # _Inline/ cache exactly as before prebuilt support existed.
2333 # IF_INSTALL_BUILD is the `make` rule driving the install-time compile
2334 # (see Makefile.PL); it must never short-circuit into loading an
2335 # older object.
2336 my $use_prebuilt
2337 = $prebuilt
2338 && !$ENV{IF_RUNTIME_BUILD}
2339 && !$ENV{IF_INSTALL_BUILD}
2340 130 ▶ && $opt eq $def_opt
Condition33%5/15
$prebuilt && !$ENV{'IF_RUNTIME_BUILD'} && !$ENV{'IF_INSTALL_BUILD'} && $opt eq $def_opt && $arch eq $def_arch && $no_omp == $def_no_omp
!ll&&!rl&&r
13000
$prebuilt and not $ENV{"IF_RUNTIME_BUILD"} and not $ENV{"IF_INSTALL_BUILD"} and $opt eq $def_opt and $arch eq $def_arch
!ll&&!rl&&r
13000
$prebuilt and not $ENV{"IF_RUNTIME_BUILD"} and not $ENV{"IF_INSTALL_BUILD"} and $opt eq $def_opt
!ll&&!rl&&r
13000
$prebuilt and not $ENV{"IF_RUNTIME_BUILD"} and not $ENV{"IF_INSTALL_BUILD"}
!ll&&!rl&&r
13000
$prebuilt and not $ENV{"IF_RUNTIME_BUILD"}
!ll&&!rl&&r
13000
MC/DC0%0/6
$prebuilt && !$ENV{'IF_RUNTIME_BUILD'} && !$ENV{'IF_INSTALL_BUILD'} && $opt eq $def_opt && $arch eq $def_arch && $no_omp == $def_no_omp
$prebuilt not $ENV{"IF_RUNTIME_BUILD"} not $ENV{"IF_INSTALL_BUILD"} $opt eq $def_opt $arch eq $def_arch $no_omp == $def_no_omp
Truth table14%1/7
A and not(B) and not(C) and D and E && F
A= $prebuiltB= not $ENV{"IF_RUNTIME_BUILD"}C= not $ENV{"IF_INSTALL_BUILD"}D= $opt eq $def_optE= $arch eq $def_archF= $no_omp == $def_no_omp
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
2341 && $arch eq $def_arch
2342 && $no_omp == $def_no_omp;
2343  
2344 # Inline::C hashes the C source to decide whether to rebuild but
2345 # does NOT include CCFLAGS / OPTIMIZE in that hash. Without the
2346 # tag below, toggling IF_NATIVE/IF_ARCH/IF_OPT (or editing the
2347 # optimisation flags here) would silently reuse a cached binary
2348 # built with stale flags. Embedding the active flags as a leading
2349 # comment forces the hash to differ when they change. The OpenMP
2350 # and serial builds get distinct tags so they cache to separate
2351 # artefacts.
2352 130 my $omp_tag = "/* if_build: openmp $opt_level */\n";
2353 130 my $serial_tag = "/* if_build: serial $opt_level */\n";
2354  
2355 130 ▶ if ( $ENV{IF_INSTALL_BUILD} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{'IF_INSTALL_BUILD'}) { } 0 130 130
2356  
2357 # `make` is driving: the rule Makefile.PL appended runs this load
2358 # with IF_INSTALL_BUILD=1 and @ARGV = (version, INST_ARCHLIB),
2359 # which is where Inline's install mode reads them from. _INSTALL_
2360 # makes Inline compile the backend and place the shared object
2361 # under blib/arch so `make install` ships it; NAME/VERSION give
2362 # the object a fixed identity XSLoader can find at run time
2363 # (Inline's install mode also requires both and checks VERSION
2364 # against $ARGV[0]). Same OpenMP-then-serial fallback as the
2365 # runtime build below.
2366 0 my @install = (
2367 NAME => __PACKAGE__,
2368 VERSION => $VERSION,
2369 _INSTALL_ => 1,
2370 );
2371 0 ▶ unless ($no_omp) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($no_omp) 0 0 0
2372 0 local $@;
2373 0 eval {
2374 0 require Inline;
2375 0 Inline->import(
2376 C => $omp_tag . $C_CODE,
2377 CCFLAGS => '-fopenmp',
2378 OPTIMIZE => $opt_level,
2379 LIBS => '-lm -lgomp',
2380 @install,
2381 );
2382 0 $HAS_C = 1;
2383 };
2384 } ## end unless ($no_omp)
2385 0 ▶ unless ($HAS_C) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Algorithm::Classifier::IsolationForest::HAS_C) 0 0 0
2386 0 local $@;
2387 0 eval {
2388 0 require Inline;
2389 0 Inline->import(
2390 C => $serial_tag . $C_CODE,
2391 OPTIMIZE => $opt_level,
2392 LIBS => '-lm',
2393 @install,
2394 );
2395 0 $HAS_C = 1;
2396 };
2397 } ## end unless ($HAS_C)
2398 0 ▶ $C_SOURCE = 'prebuilt' if $HAS_C;
Branch: 1 branch
BranchTrueFalseTotal
if $Algorithm::Classifier::IsolationForest::HAS_C 0 0 0
2399 } else {
2400  
2401 # Fast path: the object compiled at `make` time was installed
2402 # under auto/ like any XS module, so plain XSLoader digs it out of
2403 # @INC with no Inline involvement -- no compiler, no _Inline/
2404 # directory, and a few ms instead of a first-run compile. Any
2405 # failure (object deleted, different perl, version mismatch after
2406 # an upgrade, libgomp since removed) just falls through to the
2407 # runtime build.
2408 130 ▶ if ($use_prebuilt) {
Branch: 1 branch
BranchTrueFalseTotal
if ($use_prebuilt) 0 130 130
2409 0 local $@;
2410 0 eval {
2411 0 require XSLoader;
2412 0 XSLoader::load( __PACKAGE__, $VERSION );
2413 0 $HAS_C = 1;
2414 0 $C_SOURCE = 'prebuilt';
2415 };
2416 }
2417  
2418 # Classic runtime Inline::C build, MD5-cached under _Inline/.
2419 # Reached when there is no matching prebuilt object: a source
2420 # checkout, IF_RUNTIME_BUILD=1, or IF_* values differing from the
2421 # ones recorded at configure time. Try compiling with OpenMP
2422 # first; on any failure (compiler doesn't accept -fopenmp, libgomp
2423 # missing, etc.) fall back to a serial build.
2424 130 ▶ unless ( $HAS_C or $no_omp ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Algorithm::Classifier::IsolationForest::HAS_C or $no_omp) 129 1 130
Condition66%2/3
$Algorithm::Classifier::IsolationForest::HAS_C or $no_omp
l!l&&r!l&&!r
01129
MC/DC50%1/2
$Algorithm::Classifier::IsolationForest::HAS_C or $no_omp
$Algorithm::Classifier::IsolationForest::HAS_C $no_omp
Truth table66%2/3
A or B
A= $Algorithm::Classifier::IsolationForest::HAS_CB= $no_omp
ABresult
1X1
011
000
2425 129 local $@;
2426 129 eval {
2427 129 require Inline;
2428 129 Inline->import(
2429 C => $omp_tag . $C_CODE,
2430 CCFLAGS => '-fopenmp',
2431 OPTIMIZE => $opt_level,
2432 LIBS => '-lm -lgomp',
2433 );
2434 129 $HAS_C = 1;
2435 129 $C_SOURCE = 'runtime';
2436 };
2437 } ## end unless ( $HAS_C or $no_omp )
2438 130 ▶ unless ($HAS_C) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Algorithm::Classifier::IsolationForest::HAS_C) 1 129 130
2439 1 local $@;
2440 1 eval {
2441 1 require Inline;
2442 1 Inline->import(
2443 C => $serial_tag . $C_CODE,
2444 OPTIMIZE => $opt_level,
2445 LIBS => '-lm',
2446 );
2447 1 $HAS_C = 1;
2448 1 $C_SOURCE = 'runtime';
2449 };
2450 } ## end unless ($HAS_C)
2451 } ## end else [ if ( $ENV{IF_INSTALL_BUILD} ) ]
2452 130 ▶ $OPT_LEVEL = $opt_level if $HAS_C;
Branch: 1 branch
BranchTrueFalseTotal
if $Algorithm::Classifier::IsolationForest::HAS_C 130 0 130
2453  
2454 } ## end unless ( $ENV{IF_NO_C} )
2455 132 ▶ $HAS_OPENMP = ( $HAS_C && defined &has_openmp_xs && has_openmp_xs() ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$Algorithm::Classifier::IsolationForest::HAS_C && defined &Algorithm::Classifier::IsolationForest::has_openmp_xs && has_openmp_xs() ? : 129 3 132
Condition83%5/6
$Algorithm::Classifier::IsolationForest::HAS_C and defined &Algorithm::Classifier::IsolationForest::has_openmp_xs and has_openmp_xs()
!ll&&!rl&&r
21129
$Algorithm::Classifier::IsolationForest::HAS_C and defined &Algorithm::Classifier::IsolationForest::has_openmp_xs
!ll&&!rl&&r
20130
MC/DC66%2/3
$Algorithm::Classifier::IsolationForest::HAS_C and defined &Algorithm::Classifier::IsolationForest::has_openmp_xs and has_openmp_xs()
$Algorithm::Classifier::IsolationForest::HAS_C defined &Algorithm::Classifier::IsolationForest::has_openmp_xs has_openmp_xs()
Truth table75%3/4
A and B and C
A= $Algorithm::Classifier::IsolationForest::HAS_CB= defined &Algorithm::Classifier::IsolationForest::has_openmp_xsC= has_openmp_xs()
ABCresult
0XX0
10X0
1100
1111
2456 132 ▶ $HAS_SIMD = ( $HAS_C && defined &has_simd_xs && has_simd_xs() ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$Algorithm::Classifier::IsolationForest::HAS_C && defined &Algorithm::Classifier::IsolationForest::has_simd_xs && has_simd_xs() ? : 129 3 132
Condition83%5/6
$Algorithm::Classifier::IsolationForest::HAS_C and defined &Algorithm::Classifier::IsolationForest::has_simd_xs and has_simd_xs()
!ll&&!rl&&r
21129
$Algorithm::Classifier::IsolationForest::HAS_C and defined &Algorithm::Classifier::IsolationForest::has_simd_xs
!ll&&!rl&&r
20130
MC/DC66%2/3
$Algorithm::Classifier::IsolationForest::HAS_C and defined &Algorithm::Classifier::IsolationForest::has_simd_xs and has_simd_xs()
$Algorithm::Classifier::IsolationForest::HAS_C defined &Algorithm::Classifier::IsolationForest::has_simd_xs has_simd_xs()
Truth table75%3/4
A and B and C
A= $Algorithm::Classifier::IsolationForest::HAS_CB= defined &Algorithm::Classifier::IsolationForest::has_simd_xsC= has_simd_xs()
ABCresult
0XX0
10X0
1100
1111
2457 }
2458  
2459 =encoding UTF-8
2460  
2461 =head1 NAME
2462  
2463 Algorithm::Classifier::IsolationForest - unsupervised anomaly detection via Isolation Forest or Extended Isolation Forest
2464  
2465 =head1 SYNOPSIS
2466  
2467 use Algorithm::Classifier::IsolationForest;
2468  
2469 my @data = ([0.1, -0.2], [0.0, 0.1], [5.0, 6.0], ...);
2470  
2471 # Classic, axis-parallel Isolation Forest
2472 my $iforest = Algorithm::Classifier::IsolationForest->new(
2473 n_trees => 100,
2474 sample_size => 256,
2475 seed => 42,
2476 );
2477 $iforest->fit(\@data);
2478  
2479 my $scores = $iforest->score_samples(\@data); # arrayref, each in (0,1]
2480 my $flags = $iforest->predict(\@data, 0.6); # arrayref of 0/1
2481  
2482 # Save and reload
2483 $iforest->save('model.json');
2484 my $reloaded = Algorithm::Classifier::IsolationForest->load('model.json');
2485  
2486 # Extended Isolation Forest (oblique hyperplane splits)
2487 my $eif = Algorithm::Classifier::IsolationForest->new(
2488 mode => 'extended',
2489 seed => 42,
2490 );
2491 $eif->fit(\@data);
2492  
2493 # Parallel training (fork-based, Unix-like platforms): build the
2494 # n_trees across several worker processes.
2495 my $iforest = Algorithm::Classifier::IsolationForest->new(
2496 n_trees => 200,
2497 sample_size => 256,
2498 seed => 42,
2499 parallel_fit => 4, # 4 forked workers
2500 );
2501 $iforest->fit(\@data);
2502  
2503 # Pre-pack a dataset to skip the per-call input-walk cost when the
2504 # same data gets scored many times (interactive tuning, dashboards).
2505 my $packed = $iforest->pack_data(\@data);
2506 my $scores = $iforest->score_samples($packed);
2507 my $flags = $iforest->predict($packed, 0.6);
2508  
2509 # Get scores and labels as two flat arrayrefs in one call -- cheaper
2510 # than score_predict_samples when you don't need the paired shape.
2511 my ($s, $l) = $iforest->score_predict_split(\@data, 0.6);
2512  
2513 =head1 DESCRIPTION
2514  
2515 Isolation Forest (Liu, Fei Tony & Ting, Kai & Zhou, Zhi-Hua, 2008) detects anomalies by random
2516 partitioning rather than by modelling normal points. Each tree repeatedly
2517 splits the data. Points that get isolated after only a few splits are likely
2518 anomalies. The score is the average isolation depth across many trees,
2519 normalised so values approach 1 for anomalies and stay below 0.5 for normal
2520 points.
2521  
2522 In extended mode the module implements the Extended Isolation Forest
2523 variant. Each split is a random hyperplane instead of an axis-aligned cut,
2524 which removes the rectangular, axis-aligned bias in the score field and
2525 tends to help on elongated or multi-modal data.
2526  
2527 With C<< voting => 'majority' >> the module implements the Majority Voting
2528 Isolation Forest (MVIForest) aggregation: each tree votes a sample
2529 anomalous or normal against the decision threshold and the label is the
2530 majority of the votes, with prediction stopping early once the majority is
2531 reached. Trees are built identically either way, so this composes with
2532 both axis and extended mode, and an existing model can be flipped between
2533 the two modes with L</set_voting> without refitting; see C<voting> under
2534 L</new(%args)>.
2535  
2536 For data that arrives as a stream and may drift over time, the companion
2537 class L<Algorithm::Classifier::IsolationForest::Online> implements Online
2538 Isolation Forest (Leveni et al. 2024): no C<fit()>, instead points are
2539 learned as they arrive and forgotten once they age out of a sliding
2540 window. Models saved by either class can be loaded through L<load|/load($path)>,
2541 which dispatches on the stored format tag.
2542  
2543 Throughout these docs, B<psi> is the paper's ψ: the number of points each
2544 tree is built from, which C<sample_size> sets and which other
2545 implementations often call I<max samples>. See L</REFERENCES>.
2546  
2547 =head1 NATIVE ACCELERATION (Inline::C and OpenMP)
2548  
2549 Both the scoring hot path (C<score_samples>, C<predict>, C<path_lengths>,
2550 C<score_predict_samples>, and C<score_predict_split>) and the C<fit()>
2551 tree builder are automatically accelerated through
2552 L<Inline::C> when it is installed and a working C compiler is reachable.
2553 If the toolchain also accepts C<-fopenmp> and can link against
2554 C<libgomp>, the per-point tree walk runs in parallel across all
2555 available CPU cores using OpenMP, and the extended-mode oblique dot
2556 product is vectorised via C<#pragma omp simd> -- which on modern x86
2557 compilers translates to an unrolled FMA / AVX gather chain that's
2558 substantially faster for high-feature-count extended models.
2559  
2560 C<fit()>'s tree builder (subsampling plus the recursive axis/oblique
2561 split search) runs in C the same way when C<use_c> is on, replacing the
2562 per-node Perl arrayref copying with plain int-array partitioning --
2563 typically an order of magnitude faster, and dramatically more so at
2564 higher feature counts where the pure-Perl per-cell loop dominates. Its
2565 random draws go through the same generator C<rand()>/C<srand()> use
2566 internally, in the same call order the pure-Perl builder uses, so a
2567 given C<seed> produces bit-identical trees whether C<use_c> is on or
2568 off -- switching backends changes only how fast the model is built, not
2569 the model itself. On perls whose NV is wider than a C double
2570 (C<-Duselongdouble> / C<-Dusequadmath>) the pure-Perl builder rounds
2571 each stored value to double precision to preserve this parity; axis
2572 mode matches exactly, while extended mode can still differ on rare
2573 libm rounding ties (double vs long-double transcendentals).
2574  
2575 By default this C builder is single-threaded per call, because Perl's
2576 RNG state isn't safe to share across OpenMP threads. Two ways to scale
2577 fit() across cores are available (see below for why they don't compose):
2578  
2579 =over 4
2580  
2581 =item * C<parallel_fit> forks N worker processes, each building its
2582 share of the trees with the (still single-threaded) C builder. Fixed
2583 IPC/serialisation overhead per worker means this can cost more than it
2584 saves once a fit already completes in milliseconds; it's most useful
2585 once a single-process fit is large enough that the fork/Storable
2586 overhead is small relative to the work being split.
2587  
2588 =item * C<use_openmp_fit> builds trees across OpenMP threads within a
2589 single process (one tree per thread), using a separate, thread-safe
2590 PRNG seeded per tree index instead of Perl's C<rand()>. This means
2591 trees built with C<use_openmp_fit> are I<not> bit-identical to the
2592 default C<use_c> path for the same seed -- but a fixed seed and
2593 C<n_trees> still reproduce the same trees regardless of
2594 C<OMP_NUM_THREADS> or how OpenMP schedules the work. It's off by
2595 default (unlike C<use_c>/C<use_openmp>, which only ever change speed,
2596 this changes which trees get built) and only takes effect when C<use_c>
2597 is also on and OpenMP is linked in.
2598  
2599 =back
2600  
2601 These two do NOT compose, despite both existing to parallelise fit().
2602 A process that has run any OpenMP region -- including plain
2603 C<score_samples()>/C<predict()> with the default C<use_openmp> -- and
2604 then C<fork()>s (as C<parallel_fit> does) hands each child a copy of
2605 libgomp's thread pool whose worker threads did not survive the fork. A
2606 child that then starts its own C<#pragma omp parallel> region (as
2607 C<use_openmp_fit> would) tries to reuse that now-invalid pool and
2608 hangs. This is a general limitation of combining C<fork()> with OpenMP,
2609 not something fixable from Perl, so C<parallel_fit>'s forked workers
2610 always use the single-threaded C builder regardless of
2611 C<use_openmp_fit> -- setting both just means C<parallel_fit> wins and
2612 C<use_openmp_fit> has no effect for that call.
2613  
2614 Detection happens once when the module is loaded. When the
2615 distribution was installed with C<Inline::C> available, the C backend
2616 was already compiled during C<make> and the installed object is loaded
2617 directly (see L</Compile at install time (the prebuilt object)> below);
2618 otherwise the backend is compiled on first load and the artefact is
2619 cached under C<_Inline/> and reused on subsequent runs. Five package
2620 variables report what the load picked up:
2621  
2622 $Algorithm::Classifier::IsolationForest::HAS_C # 0/1
2623 $Algorithm::Classifier::IsolationForest::HAS_OPENMP # 0/1
2624 $Algorithm::Classifier::IsolationForest::HAS_SIMD # 0/1 (OpenMP 4.0+)
2625 $Algorithm::Classifier::IsolationForest::OPT_LEVEL # e.g. "-O3 -march=native", '' if HAS_C is 0
2626 $Algorithm::Classifier::IsolationForest::C_SOURCE # 'prebuilt' / 'runtime', '' if HAS_C is 0
2627  
2628 Neither dependency is required. Without C<Inline::C> the module falls
2629 back to a pure-Perl implementation that produces identical results, just
2630 slower; without OpenMP the C backend runs single-threaded.
2631  
2632 The bundled C<iforest accel> subcommand performs a tiny fit + score and
2633 prints which backend is active (including the build flags below), which
2634 is the recommended way to verify the build picked up the optional
2635 dependencies on a given machine.
2636  
2637 =head2 Compile at install time (the prebuilt object)
2638  
2639 When C<Inline::C> is usable while the distribution itself is being
2640 built, C<perl Makefile.PL> arranges for the C backend to be compiled
2641 once during C<make> and installed alongside the module like any XS
2642 object. At run time that object is loaded directly through
2643 L<XSLoader>: no C compiler, no C<Inline> modules, and no C<_Inline/>
2644 cache directory are needed on the machine the module ends up running
2645 on, and the first-load compile pause disappears entirely.
2646  
2647 On x86-64 hardware from roughly the last decade,
2648 C<IF_ARCH=x86-64-v3 perl Makefile.PL> is a reasonable configure line:
2649 it bakes AVX2 + FMA (without AVX-512) into the prebuilt object, which
2650 can speed up extended-mode scoring (how much is hardware-dependent --
2651 benchmark with C<iforest bench> before assuming) while avoiding the
2652 C<-march=native> caveats described under L</Tuning the C build>.
2653 Bit-for-bit result parity with the pure-Perl backend is preserved
2654 either way (see C<IF_ARCH> below).
2655  
2656 The C<IF_*> build flags described below are captured when
2657 C<perl Makefile.PL> runs -- set them in the environment of I<that>
2658 command, not of C<make> -- and recorded in the generated
2659 C<Algorithm::Classifier::IsolationForest::BuildFlags> module, which
2660 thereby also fixes what the prebuilt object was compiled with. At run
2661 time the recorded values serve as the defaults, so a process started
2662 with no C<IF_*> variables set uses the prebuilt object as-is.
2663  
2664 Setting C<IF_*> variables at run time keeps working exactly as in
2665 releases without prebuilt support: if the requested flags differ from
2666 the recorded ones, the prebuilt object (compiled with the wrong flags
2667 for the request) is skipped and the module compiles at first load into
2668 C<_Inline/> -- which does need C<Inline::C> and a compiler on that
2669 machine. Two related knobs exist:
2670  
2671 =over 4
2672  
2673 =item * C<IF_RUNTIME_BUILD=1> -- ignore the prebuilt object
2674 unconditionally and compile at first load even though the requested
2675 flags match the recorded ones. Useful when the installed object is
2676 suspect (built on a different CPU than it now runs on, linked against a
2677 libgomp that has since changed) or to A/B a fresh local build against
2678 the shipped one.
2679  
2680 =item * C<IF_INSTALL_BUILD=1> -- internal; set by the generated
2681 Makefile rule that performs the install-time compile. Not meant for
2682 manual use.
2683  
2684 =back
2685  
2686 If the prebuilt object cannot be loaded for any reason (deleted, built
2687 against a different perl, version mismatch after an upgrade), the
2688 module quietly falls through the same chain as always: runtime
2689 Inline::C build first, pure Perl last.
2690  
2691 =head2 Tuning the C build
2692  
2693 These environment variables are read once, the first time the module is
2694 loaded, so they must be set before that -- e.g. in the shell before
2695 running a script, not via C<%ENV> inside the script itself. They are
2696 also read by C<perl Makefile.PL> to pick the flags baked into the
2697 prebuilt object (see above); at run time they override the recorded
2698 configure-time values, at the price of a runtime compile.
2699  
2700 =over 4
2701  
2702 =item * C<IF_NO_C=1> -- skip attempting to build the C backend entirely.
2703 Equivalent to constructing every instance with C<use_c =E<gt> 0>, but
2704 without needing to touch every call site; useful for a clean pure-Perl
2705 timing baseline, or to avoid the compile attempt's overhead/noise on a
2706 host known to lack a C compiler (the attempt already fails gracefully
2707 without this, so it's a convenience, not a correctness fix).
2708  
2709 =item * C<IF_OPT=-O2> (or C<-O0>/C<-O1>/C<-Os>/C<-Og>/C<-Oz>) -- override
2710 the default C<-O3>, e.g. to shorten build time while iterating, or work
2711 around a miscompile on an unusual toolchain. Invalid values are ignored
2712 with a warning rather than passed through, since this string reaches a
2713 compiler command line.
2714  
2715 =item * C<IF_ARCH=E<lt>valueE<gt>> -- adds C<-march=E<lt>valueE<gt>> so the
2716 compiler can target specific instruction-set extensions (AVX2 gather +
2717 FMA, etc.) for the extended-mode oblique dot product and the fit-time
2718 min/max scan's C<#pragma omp simd> loops. Accepts values like
2719 C<x86-64-v3>, C<skylake>, or C<znver3> -- whatever your compiler's
2720 C<-march=> accepts. Also validated (a restricted character set, not
2721 passed through as-is) for the same reason as C<IF_OPT>. The special
2722 value C<none> (or an empty string) opts out of any arch recorded at
2723 configure time, yielding a plain build. Whenever a C<-march> is in
2724 effect the build also adds C<-ffp-contract=off>: with FMA available
2725 the compiler would otherwise contract C<a*b+c> into fused
2726 multiply-adds whose different rounding breaks the guarantee that
2727 C<use_c =E<gt> 1> and C<use_c =E<gt> 0> build bit-identical trees (the
2728 C<-march> speedup comes from vectorization, not contraction, so this
2729 costs essentially nothing).
2730  
2731 =item * C<IF_NATIVE=1> -- shorthand for C<IF_ARCH=native>; ignored if
2732 C<IF_ARCH> is also set. Prefer a specific C<IF_ARCH> value over this on
2733 a machine you don't control exclusively (a shared build host, a
2734 container base image): blanket C<-march=native> pulls in whatever
2735 instruction sets the build host happens to have, including AVX-512 on
2736 some Intel CPUs -- which is known to trigger clock throttling under
2737 sustained heavy use and can make throughput I<worse> than a
2738 conservative target like C<x86-64-v3> (AVX2, no AVX-512). If in doubt,
2739 benchmark both before committing to one.
2740  
2741 =item * C<IF_NO_OPENMP=1> -- build (or select) the serial C backend: the
2742 OpenMP compile attempt is skipped entirely, so the resulting object has
2743 no libgomp linkage and never starts an OpenMP runtime inside the
2744 process. This differs from C<OMP_NUM_THREADS=1>, which merely runs the
2745 parallel code on one thread but still loads libgomp. Set at
2746 C<perl Makefile.PL> time it yields a serial prebuilt object; set at run
2747 time against an OpenMP prebuilt install it triggers a runtime serial
2748 build (needing a compiler). An explicit C<IF_NO_OPENMP=0> re-enables
2749 OpenMP over a serial configure-time default.
2750  
2751 =back
2752  
2753 Whichever of these are used, the cached artefact under C<_Inline/> is
2754 pinned to that build's instruction set -- delete C<_Inline/> (or use a
2755 separate one per host) if the directory is shared across machines with
2756 different CPUs, or a stale binary built for a narrower instruction set
2757 than the current host will simply keep being reused.
2758  
2759 =head2 Tuning the OpenMP runtime
2760  
2761 These are standard OpenMP environment variables libgomp already reads
2762 at run time (set before running your script, no module-specific
2763 handling needed) -- listed here because they matter most for exactly
2764 the workloads this module has: C<score_all_xs>'s per-point parallel
2765 loop and C<use_openmp_fit>'s per-tree parallel loop.
2766  
2767 =over 4
2768  
2769 =item * C<OMP_NUM_THREADS=N> -- caps how many threads a parallel region
2770 uses. Useful to leave headroom for other work sharing the machine, or
2771 to pin down C<use_openmp_fit> reproducibility checks (see its docs
2772 above: results don't depend on this, but it's a natural thing to vary
2773 when confirming that).
2774  
2775 =item * C<OMP_PROC_BIND=close> / C<OMP_PLACES=cores> -- on multi-socket
2776 or otherwise NUMA machines, pins each thread to a core near where its
2777 data already lives instead of letting the OS scheduler migrate threads
2778 across sockets mid-run. Both C<score_all_xs> (each thread scans its own
2779 slice of the packed query buffer) and C<use_openmp_fit> (each thread
2780 builds one tree from packed training data) benefit from this when the
2781 input is large enough to not fit comfortably in one socket's cache.
2782  
2783 =back
2784  
2785 These cost nothing to try -- unlike C<IF_ARCH>/C<IF_NATIVE>, they're
2786 read fresh every run, not baked into a cached binary, so there's no
2787 downside to experimenting per invocation.
2788  
2789 =head1 GENERAL METHODS
2790  
2791 =head2 new(%args)
2792  
2793 Inits the object.
2794  
2795 - n_trees :: number of isolation trees in the ensemble
2796 default :: 100
2797  
2798 - sample_size :: sub-sample size used to build each tree... max samples
2799 default :: 256
2800  
2801 - max_depth :: per-tree height limit... if not defined is set to ceil(log2(psi))
2802 default :: undef
2803  
2804 - seed :: optional integer to seed srand with for reproducible trees...
2805 see perldoc -f srand for more info. This number is processed via abs(int()).
2806 default :: undef
2807  
2808 - mode :: if it should be IF or EIF
2809 axis :: classic axis-parallel splits (IF)
2810 extended :: oblique hyperplane splits (EIF)
2811 default :: axis
2812  
2813 - extension_level :: extended mode only... how many features take partin each
2814 split. 0 behaves like a single-feature (axis) cut; the
2815 maximum (n_features - 1) uses every varying feature. undef
2816 => maximum. Clamped to [0, n_features - 1] at fit time.
2817  
2818 - contamination :: expected fraction of anomalies, in (0, 0.5]. When given,
2819 fit() learns a score threshold that flags this fraction of
2820 the training set, and predict() uses it by default. undef
2821 => no learned threshold (predict() falls back to 0.5).
2822 default :: undef
2823  
2824 - missing :: how fit() treats undef (missing) feature cells. Scoring always
2825 tolerates undef regardless of this setting; it governs fit().
2826 die :: croak from fit() if the training data contains any
2827 undef cell. Scoring still maps undef to 0 (the
2828 long-standing behaviour), so a model fitted on clean
2829 data can still score rows with missing features.
2830 zero :: treat a missing cell as the value 0, at fit and score.
2831 impute :: replace a missing cell with the per-feature mean (or
2832 median, see impute_with) learned from the present
2833 values at fit time. The fill vector is stored on the
2834 model and reused for scoring and persistence.
2835 nan :: build feature ranges from present values only and route
2836 a point missing the split feature to the right child,
2837 consistently at fit and score time. Missingness is
2838 preserved as signal rather than filled.
2839 default :: die
2840  
2841 - impute_with :: 'mean' or 'median'; the statistic used to compute the
2842 per-feature fill under missing => 'impute'. Ignored otherwise.
2843 default :: mean
2844  
2845 - voting :: how the per-tree results are aggregated at scoring time.
2846 Trees are built identically in both settings -- only aggregation
2847 changes -- so the knob composes with either mode (axis or
2848 extended) and an existing model may switch it after the fact with
2849 set_voting() (which relearns a contamination threshold for the
2850 new mode).
2851 mean :: classic Isolation Forest: a sample's path lengths
2852 across all trees are averaged and normalised into
2853 one anomaly score; predict() thresholds that score.
2854 majority :: Majority Voting Isolation Forest (MVIForest;
2855 Chabchoub, Togbe, Boly & Chiky 2022 -- see
2856 REFERENCES). Each tree scores the sample on its own
2857 (s_i = 2**(-h_i / c(psi))) and votes it anomalous
2858 when s_i >= the decision threshold; predict() flags
2859 the sample when more than half of the trees
2860 (int(n_trees/2) + 1) vote anomalous, and stops
2861 walking trees per sample as soon as the outcome is
2862 decided. The threshold argument/default of the
2863 predict methods is therefore the PER-TREE cutoff
2864 here, not a forest-level score cutoff.
2865 score_samples() returns the fraction of trees
2866 voting anomalous -- still in [0, 1], but discrete
2867 in steps of 1/n_trees. contamination composes: fit()
2868 learns the per-tree cutoff that flags the requested
2869 fraction of the training set.
2870 default :: mean
2871  
2872 - parallel_fit :: positive integer N => build the trees across N forked
2873 worker processes during fit(). Each worker gets a derived seed
2874 (parent seed + worker_id * 1009) so the parallel fit is
2875 reproducible across runs at fixed worker count -- but the trees
2876 produced are NOT bit-identical to a serial fit with the same
2877 seed, because the RNG draws happen in a different order.
2878 Inference is unaffected. Falls back silently to serial on
2879 platforms without a real fork() (e.g. Windows without Cygwin).
2880 default :: undef (serial)
2881  
2882 - use_c :: boolean, override whether the Inline::C backend is used for
2883 both scoring and fit()'s tree builder. When false the instance
2884 falls back to pure Perl for both even if the C backend compiled
2885 successfully. When true (or unset) the C backend is used if
2886 available ($HAS_C). fit() with use_c on produces bit-identical
2887 trees to use_c off for the same seed -- only build speed differs.
2888 default :: $HAS_C
2889  
2890 - use_openmp :: boolean, override whether OpenMP parallel scoring is
2891 used inside score_all_xs(). When false the C tree walk runs
2892 single-threaded even if OpenMP was linked in. Ignored when
2893 use_c is false (pure Perl has no OpenMP path).
2894 default :: $HAS_OPENMP
2895  
2896 - use_openmp_fit :: boolean, build fit()'s trees across OpenMP threads
2897 (one tree per thread) instead of the single-threaded C builder.
2898 Opt-in and off by default: unlike use_c/use_openmp, this changes
2899 which trees get built. Perl's RNG isn't safe to call from
2900 multiple OS threads sharing one interpreter, so this path seeds
2901 an independent PRNG per tree from the tree index rather than
2902 Drand01() -- trees differ from the use_c (single-threaded)
2903 and pure-Perl paths even with the same seed, though a fixed
2904 seed and n_trees still reproduce the same trees regardless of
2905 OMP_NUM_THREADS or scheduling. Does NOT compose with
2906 parallel_fit: a forked child starting its own OpenMP region
2907 after the parent process has used OpenMP for anything can
2908 hang (a general fork()+libgomp limitation), so parallel_fit's
2909 workers always use the single-threaded C builder regardless
2910 of this setting -- setting both just means parallel_fit wins.
2911 Ignored (clamped to 0) when use_c is false or OpenMP isn't
2912 linked in.
2913 default :: 0
2914  
2915 - feature_names :: optional arrayref of per-feature labels enabling the
2916 *_tagged methods (and required by mungers below).
2917 default :: undef
2918  
2919 - mungers :: optional hashref of declarative L<Algorithm::ToNumberMunger>
2920 specs, keyed as that module's compile() expects (scalar mungers by
2921 their output tag, expanding mungers by any label with an 'into'
2922 list, combining mungers by their output tag with a 'from' list).
2923 When set, every tagged row -- the *_tagged methods, fit_tagged,
2924 and tagged_row_to_array -- is munged from raw values (strings,
2925 timestamps, status codes, ...) into numbers through the compiled
2926 plan, and munge_rows() applies the scalar mungers to positional
2927 rows. Requires feature_names; the plan compiles against them, so
2928 any spec error croaks here in new(). Algorithm::ToNumberMunger is
2929 an optional dependency, required only when a spec is given (or a
2930 loaded model carrying one is used with tagged data). The spec is
2931 saved with the model, so a loaded model munges scoring input
2932 exactly as it did training input. See L</MUNGERS> for details
2933 and caveats.
2934 default :: undef
2935  
2936 - schema_version :: optional opaque string identifying the revision of
2937 the variable schema this model was built against. Never parsed
2938 or compared numerically; saved with the model and shown by
2939 `iforest info`. Usually set from a prototype (see
2940 L</PROTOTYPES>) rather than passed directly.
2941 default :: undef
2942  
2943 - schema_description :: optional opaque free-text description of what
2944 the variable schema is. Same handling as schema_version.
2945 default :: undef
2946  
2947 - feature_descriptions :: optional hashref of 'feature name => free
2948 text' describing individual features. Requires feature_names;
2949 every key must name an entry there (a description for a feature
2950 that does not exist croaks -- it is either a typo or a stale
2951 leftover from a schema change). Partial coverage is fine.
2952 Saved with the model and shown beside each tag by
2953 `iforest info`.
2954 default :: undef
2955  
2956 Note: log2 under Perl is as below...
2957  
2958 log($psi) / log(2)
2959  
2960  
2961 =cut
2962  
2963 322 ▶sub new {
Subroutine new: called CC=41 SCAR=37.2
Pod documented
2964 322 my ( $class, %args ) = @_;
2965  
2966 322 ▶ my $mode = $args{mode} // 'axis';
Condition100%2/2
$args{"mode"} // "axis"
l!l
63259
MC/DC100%1/1
$args{"mode"} // "axis"
$args{"mode"}
Truth table100%2/2
A
A= $args{"mode"}
Aresult
11
00
2967 322 ▶ croak "mode must be 'axis' or 'extended'"
Branch: 1 branch
BranchTrueFalseTotal
unless $mode eq "axis" or $mode eq "extended" 1 321 322
Condition100%3/3
$mode eq "axis" or $mode eq "extended"
l!l&&r!l&&!r
285361
MC/DC100%2/2
$mode eq "axis" or $mode eq "extended"
$mode eq "axis" $mode eq "extended"
Truth table100%3/3
A or B
A= $mode eq "axis"B= $mode eq "extended"
ABresult
1X1
011
000
2968 unless $mode eq 'axis' || $mode eq 'extended';
2969  
2970 # How fit() treats undef (missing) feature cells. Scoring always
2971 # tolerates undef regardless of this setting -- it governs fit only.
2972 # die :: croak if the training data contains any undef cell (default)
2973 # zero :: treat a missing cell as the value 0
2974 # impute :: replace a missing cell with the per-feature mean/median
2975 # learned from the present values at fit time
2976 # nan :: build ranges over present values only and route a point
2977 # missing the split feature consistently to one branch, at
2978 # both fit and score time
2979 321 ▶ my $missing = $args{missing} // 'die';
Condition100%2/2
$args{"missing"} // "die"
l!l
41280
MC/DC100%1/1
$args{"missing"} // "die"
$args{"missing"}
Truth table100%2/2
A
A= $args{"missing"}
Aresult
11
00
2980 321 ▶ croak "missing must be one of: die, zero, impute, nan"
Branch: 1 branch
BranchTrueFalseTotal
unless $missing =~ /\A(?:die|zero|impute|nan)\z/ 1 320 321
2981 unless $missing =~ /\A(?:die|zero|impute|nan)\z/;
2982  
2983 320 ▶ my $impute_with = $args{impute_with} // 'mean';
Condition100%2/2
$args{"impute_with"} // "mean"
l!l
8312
MC/DC100%1/1
$args{"impute_with"} // "mean"
$args{"impute_with"}
Truth table100%2/2
A
A= $args{"impute_with"}
Aresult
11
00
2984 320 ▶ croak "impute_with must be 'mean' or 'median'"
Branch: 1 branch
BranchTrueFalseTotal
unless $impute_with =~ /\A(?:mean|median)\z/ 1 319 320
2985 unless $impute_with =~ /\A(?:mean|median)\z/;
2986  
2987 # How per-tree results are aggregated at scoring time. Trees are
2988 # built identically either way -- this knob never touches fit()'s
2989 # forest, only how score/predict combine the per-tree path lengths.
2990 # mean :: classic IForest: average path length across trees,
2991 # normalised into one score (the default)
2992 # majority :: MVIForest (Chabchoub et al. 2022): each tree votes
2993 # anomalous/normal against the decision threshold and
2994 # the label is the majority of the tree votes
2995 319 ▶ my $voting = $args{voting} // 'mean';
Condition100%2/2
$args{"voting"} // "mean"
l!l
25294
MC/DC100%1/1
$args{"voting"} // "mean"
$args{"voting"}
Truth table100%2/2
A
A= $args{"voting"}
Aresult
11
00
2996 319 ▶ croak "voting must be 'mean' or 'majority'"
Branch: 1 branch
BranchTrueFalseTotal
unless $voting =~ /\A(?:mean|majority)\z/ 1 318 319
2997 unless $voting =~ /\A(?:mean|majority)\z/;
2998  
2999 318 ▶ if ( defined( $args{seed} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"seed"}) 275 43 318
3000 275 $args{seed} = abs( int( $args{seed} ) );
3001 }
3002  
3003 # Clamp the accel knobs against what the build actually has. Passing
3004 # use_c => 1 on a machine where Inline::C never compiled would otherwise
3005 # leave score_samples() calling an undefined XS sub at first use.
3006 # OpenMP is meaningless without the C tree walk, so force it off
3007 # whenever the C backend is off -- matches the documented
3008 # "Ignored when use_c is false" semantics.
3009 my $use_c
3010 = defined $args{use_c}
3011 318 ▶ ? ( $args{use_c} && $HAS_C ? 1 : 0 )
Branch: 2 branches
BranchTrueFalseTotal
defined $args{'use_c'} ? : 212 106 318
$args{'use_c'} && $Algorithm::Classifier::IsolationForest::HAS_C ? : 109 103 212
Condition100%3/3
$args{"use_c"} and $Algorithm::Classifier::IsolationForest::HAS_C
!ll&&!rl&&r
1021109
MC/DC100%2/2
$args{"use_c"} and $Algorithm::Classifier::IsolationForest::HAS_C
$args{"use_c"} $Algorithm::Classifier::IsolationForest::HAS_C
Truth table100%3/3
A and B
A= $args{"use_c"}B= $Algorithm::Classifier::IsolationForest::HAS_C
ABresult
0X0
100
111
3012 : $HAS_C;
3013 my $use_openmp
3014 = defined $args{use_openmp}
3015 318 ▶ ? ( $args{use_openmp} && $HAS_OPENMP ? 1 : 0 )
Branch: 2 branches
BranchTrueFalseTotal
defined $args{'use_openmp'} ? : 5 313 318
$args{'use_openmp'} && $Algorithm::Classifier::IsolationForest::HAS_OPENMP ? : 2 3 5
Condition100%3/3
$args{"use_openmp"} and $Algorithm::Classifier::IsolationForest::HAS_OPENMP
!ll&&!rl&&r
122
MC/DC100%2/2
$args{"use_openmp"} and $Algorithm::Classifier::IsolationForest::HAS_OPENMP
$args{"use_openmp"} $Algorithm::Classifier::IsolationForest::HAS_OPENMP
Truth table100%3/3
A and B
A= $args{"use_openmp"}B= $Algorithm::Classifier::IsolationForest::HAS_OPENMP
ABresult
0X0
100
111
3016 : $HAS_OPENMP;
3017 318 ▶ $use_openmp = 0 unless $use_c;
Branch: 1 branch
BranchTrueFalseTotal
unless $use_c 105 213 318
3018  
3019 # Opt-in only (default 0, not $HAS_OPENMP): this path changes which
3020 # trees fit() builds (see docs above), unlike use_c/use_openmp which
3021 # only change speed. Clamped the same way use_openmp is.
3022 318 ▶ my $use_openmp_fit = ( $args{use_openmp_fit} && $HAS_OPENMP && $use_c ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$args{'use_openmp_fit'} && $Algorithm::Classifier::IsolationForest::HAS_OPENMP && $use_c ? : 9 309 318
Condition66%4/6
$args{"use_openmp_fit"} and $Algorithm::Classifier::IsolationForest::HAS_OPENMP and $use_c
!ll&&!rl&&r
30909
$args{"use_openmp_fit"} and $Algorithm::Classifier::IsolationForest::HAS_OPENMP
!ll&&!rl&&r
30909
MC/DC33%1/3
$args{"use_openmp_fit"} and $Algorithm::Classifier::IsolationForest::HAS_OPENMP and $use_c
$args{"use_openmp_fit"} $Algorithm::Classifier::IsolationForest::HAS_OPENMP $use_c
Truth table50%2/4
A and B and C
A= $args{"use_openmp_fit"}B= $Algorithm::Classifier::IsolationForest::HAS_OPENMPC= $use_c
ABCresult
0XX0
10X0
1100
1111
3023  
3024 my $self = {
3025 n_trees => $args{n_trees} // 100,
3026 sample_size => $args{sample_size} // 256,
3027 max_depth => $args{max_depth}, # undef => auto
3028 seed => $args{seed}, # undef => non-deterministic
3029 mode => $mode,
3030 extension_level => $args{extension_level}, # undef => max, resolved in fit()
3031 contamination => $args{contamination}, # undef => no learned threshold
3032 parallel_fit => $args{parallel_fit}, # undef/0/1 => serial; N>1 => fork
3033 missing => $missing, # die|zero|impute|nan
3034 impute_with => $impute_with, # mean|median (impute mode only)
3035 voting => $voting, # mean|majority (scoring-time aggregation)
3036 missing_fill => undef, # per-feature fill, learned in fit() if impute
3037 feature_baselines => undef, # per-feature medians, learned in fit();
3038 # the "typical row" ablation explanations
3039 # substitute against -- see explain_samples
3040 _use_c => $use_c,
3041 _use_openmp => $use_openmp,
3042 _use_openmp_fit => $use_openmp_fit,
3043 threshold => undef, # learned in fit() if contamination set
3044 trees => [],
3045 c_psi => undef, # c(psi), set during fit()
3046 n_features => undef,
3047 feature_names => $args{feature_names}, # optional arrayref of per-feature labels
3048 mungers => undef, # optional Algorithm::ToNumberMunger spec hash
3049 # Opaque schema metadata, usually set via new_from_prototype and
3050 # persisted with the model. Never parsed -- documentation that
3051 # travels with the model file.
3052 schema_version => $args{schema_version},
3053 schema_description => $args{schema_description},
3054 feature_descriptions => $args{feature_descriptions},
3055 318 ▶ };
Condition100%4/4
$args{"n_trees"} // 100
l!l
28038
$args{"sample_size"} // 256
l!l
22890
MC/DC100%1/1
$args{"n_trees"} // 100
$args{"n_trees"}
MC/DC100%1/1
$args{"sample_size"} // 256
$args{"sample_size"}
Truth table100%2/2
A
A= $args{"n_trees"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"sample_size"}
Aresult
11
00
3056  
3057 318 for my $doc (qw(schema_version schema_description)) {
3058 croak "$doc must be a plain string"
3059 635 ▶ if defined $self->{$doc} && ref $self->{$doc};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{$doc} and ref $self->{$doc} 1 634 635
Condition100%3/3
defined $self->{$doc} and ref $self->{$doc}
!ll&&!rl&&r
616181
MC/DC100%2/2
defined $self->{$doc} and ref $self->{$doc}
defined $self->{$doc} ref $self->{$doc}
Truth table100%3/3
A and B
A= defined $self->{$doc}B= ref $self->{$doc}
ABresult
0X0
100
111
3060 }
3061 _validate_feature_descriptions( $self->{feature_names}, $self->{feature_descriptions} )
3062 317 ▶ if defined $self->{feature_descriptions};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"feature_descriptions"} 6 311 317
3063  
3064 # Optional Algorithm::ToNumberMunger integration: a declarative spec
3065 # hash compiled into a plan that turns raw tagged values into numbers.
3066 # Compiled eagerly so every spec error surfaces here rather than at
3067 # first scoring; the module itself is only required when a spec is
3068 # actually given, keeping it an optional dependency.
3069 314 ▶ if ( defined $args{mungers} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"mungers"}) 9 305 314
3070 croak "mungers must be a hashref of 'tag => munger spec'"
3071 9 ▶ unless ref $args{mungers} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args{"mungers"} eq "HASH" 1 8 9
3072 croak "mungers requires feature_names (the munger plan compiles against them)"
3073 8 ▶ unless ref $self->{feature_names} eq 'ARRAY' && @{ $self->{feature_names} };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};} 1 7 8
Condition66%2/3
ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};}
!ll&&!rl&&r
107
MC/DC50%1/2
ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};}
ref $self->{"feature_names"} eq "ARRAY" @{$self->{"feature_names"};}
Truth table66%2/3
A and B
A= ref $self->{"feature_names"} eq "ARRAY"B= @{$self->{"feature_names"};}
ABresult
0X0
100
111
3074 7 $self->{mungers} = $args{mungers};
3075 7 $self->{_munger_plan} = _compile_mungers( $self->{feature_names}, $self->{mungers} );
3076 5 $self->{munger_module_version} = $Algorithm::ToNumberMunger::VERSION;
3077 }
3078  
3079 310 ▶ croak "n_trees must be >= 1" unless $self->{n_trees} >= 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"n_trees"} >= 1 1 309 310
3080 309 ▶ croak "sample_size must be >= 1" unless $self->{sample_size} >= 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"sample_size"} >= 1 1 308 309
3081 croak "extension_level must be >= 0"
3082 308 ▶ if defined $self->{extension_level} && $self->{extension_level} < 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"extension_level"} and $self->{"extension_level"} < 0 1 307 308
Condition100%3/3
defined $self->{"extension_level"} and $self->{"extension_level"} < 0
!ll&&!rl&&r
30251
MC/DC100%2/2
defined $self->{"extension_level"} and $self->{"extension_level"} < 0
defined $self->{"extension_level"} $self->{"extension_level"} < 0
Truth table100%3/3
A and B
A= defined $self->{"extension_level"}B= $self->{"extension_level"} < 0
ABresult
0X0
100
111
3083 croak "contamination must be a number in (0, 0.5]"
3084 if defined $self->{contamination}
3085 307 ▶ && !( $self->{contamination} > 0 && $self->{contamination} <= 0.5 );
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"contamination"} and not $self->{"contamination"} > 0 && $self->{"contamination"} <= "0.5" 3 304 307
Condition100%6/6
defined $self->{"contamination"} and not $self->{"contamination"} > 0 && $self->{"contamination"} <= "0.5"
!ll&&!rl&&r
255493
$self->{'contamination'} > 0 && $self->{'contamination'} <= 0.5
!ll&&!rl&&r
2149
MC/DC100%3/3
defined $self->{"contamination"} and not $self->{"contamination"} > 0 && $self->{"contamination"} <= "0.5"
defined $self->{"contamination"} $self->{'contamination'} > 0 $self->{'contamination'} <= 0.5
Truth table100%4/4
A and not(B && C)
A= defined $self->{"contamination"}B= $self->{'contamination'} > 0C= $self->{'contamination'} <= 0.5
ABCresult
0XX0
1110
10X1
1101
3086 croak "parallel_fit must be a positive integer"
3087 if defined $self->{parallel_fit}
3088 304 ▶ && ( $self->{parallel_fit} !~ /^\d+$/ || $self->{parallel_fit} < 1 );
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"parallel_fit"} and !($self->{"parallel_fit"} =~ /^\d+$/) || $self->{"parallel_fit"} < 1 2 302 304
Condition83%5/6
defined $self->{"parallel_fit"} and !($self->{"parallel_fit"} =~ /^\d+$/) || $self->{"parallel_fit"} < 1
!ll&&!rl&&r
29392
not $self->{"parallel_fit"} =~ /^\d+$/ or $self->{"parallel_fit"} < 1
l!l&&r!l&&!r
209
MC/DC66%2/3
defined $self->{"parallel_fit"} and !($self->{"parallel_fit"} =~ /^\d+$/) || $self->{"parallel_fit"} < 1
defined $self->{"parallel_fit"} not $self->{"parallel_fit"} =~ /^\d+$/ $self->{"parallel_fit"} < 1
Truth table75%3/4
A and not(B) or C
A= defined $self->{"parallel_fit"}B= not $self->{"parallel_fit"} =~ /^\d+$/C= $self->{"parallel_fit"} < 1
ABCresult
0XX0
1000
11X1
1011
3089  
3090 302 return bless $self, $class;
3091 } ## end sub new
3092  
3093 =head2 decision_threshold
3094  
3095 The score cutoff C<predict> uses by default; undef unless C<contamination> was
3096 set.
3097  
3098 =cut
3099  
3100 41 ▶sub decision_threshold { return $_[0]->{threshold} }
Subroutine decision_threshold: called CC=1 SCAR=0.0
Pod documented
3101  
3102 =head2 set_voting
3103  
3104 Switches the scoring-time aggregation between C<'mean'> and C<'majority'> on an
3105 existing model and returns C<$self> (so it chains). The forest itself is
3106 identical in both modes -- only the way per-tree results are combined changes
3107 -- so this never rebuilds a single tree.
3108  
3109 $iforest->set_voting('majority');
3110 $iforest->set_voting('mean', \@training_data);
3111  
3112 The one thing that does not carry over is a C<contamination>-learned
3113 L</decision_threshold>. That cutoff is a quantile of whichever per-point
3114 quantity the mode thresholds against -- the averaged anomaly score under
3115 C<'mean'>, the per-tree majority pivot under C<'majority'> -- and those live in
3116 different spaces, so a threshold learned in one mode flags the wrong fraction
3117 in the other. When the model was fitted with C<contamination>, C<set_voting>
3118 therefore relearns the threshold for the target mode, which requires the
3119 original training data to be passed as the second argument (the model does not
3120 retain it). Switching a model that had no C<contamination> needs no data:
3121 C<predict> falls back to C<0.5>, which is meaningful in both modes.
3122  
3123 Passing the current mode is a no-op (returns immediately, no data needed).
3124 Calling this before L</fit> just records the mode for the eventual fit.
3125  
3126 =cut
3127  
3128 10 ▶sub set_voting {
Subroutine set_voting: called CC=10 SCAR=23.1
Pod documented
3129 10 my ( $self, $voting, $data ) = @_;
3130  
3131 10 ▶ croak "set_voting: voting must be 'mean' or 'majority'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $voting and $voting =~ /\A(?:mean|majority)\z/ 1 9 10
Condition66%2/3
defined $voting and $voting =~ /\A(?:mean|majority)\z/
!ll&&!rl&&r
019
MC/DC50%1/2
defined $voting and $voting =~ /\A(?:mean|majority)\z/
defined $voting $voting =~ /\A(?:mean|majority)\z/
Truth table66%2/3
A and B
A= defined $votingB= $voting =~ /\A(?:mean|majority)\z/
ABresult
0X0
100
111
3132 unless defined $voting && $voting =~ /\A(?:mean|majority)\z/;
3133  
3134 9 ▶ return $self if $self->{voting} eq $voting;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"voting"} eq $voting 1 8 9
3135  
3136 # A learned threshold only exists once a contamination-fitted model has
3137 # been fit(); that value is mode-specific and must be relearned against
3138 # the same training set (see _learn_contamination_threshold). Everything
3139 # else -- pre-fit models, and fitted models without contamination -- just
3140 # flips the knob; predict()'s 0.5 fallback is valid in either mode.
3141 8 ▶ my $fitted = ref $self->{trees} eq 'ARRAY' && @{ $self->{trees} };
Condition66%2/3
ref $self->{'trees'} eq 'ARRAY' && @{$self->{'trees'};}
!ll&&!rl&&r
017
MC/DC50%1/2
ref $self->{'trees'} eq 'ARRAY' && @{$self->{'trees'};}
ref $self->{'trees'} eq 'ARRAY' @{$self->{'trees'};}
Truth table66%2/3
A && B
A= ref $self->{'trees'} eq 'ARRAY'B= @{$self->{'trees'};}
ABresult
0X0
100
111
3142 8 ▶ my $recalibrate = $fitted && defined $self->{contamination};
Condition100%3/3
$fitted && defined $self->{'contamination'}
!ll&&!rl&&r
134
MC/DC100%2/2
$fitted && defined $self->{'contamination'}
$fitted defined $self->{'contamination'}
Truth table100%3/3
A && B
A= $fittedB= defined $self->{'contamination'}
ABresult
0X0
100
111
3143 8 ▶ if ($recalibrate) {
Branch: 1 branch
BranchTrueFalseTotal
if ($recalibrate) 4 4 8
3144 4 ▶ croak "set_voting: switching a contamination-fitted model requires "
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "ARRAY" and @$data 1 3 4
Condition66%2/3
ref $data eq "ARRAY" and @$data
!ll&&!rl&&r
103
MC/DC50%1/2
ref $data eq "ARRAY" and @$data
ref $data eq "ARRAY" @$data
Truth table66%2/3
A and B
A= ref $data eq "ARRAY"B= @$data
ABresult
0X0
100
111
3145 . "the original training data as the second argument to "
3146 . "recalibrate the decision threshold"
3147 unless ref $data eq 'ARRAY' && @$data;
3148 }
3149  
3150 7 $self->{voting} = $voting;
3151 7 ▶ $self->_learn_contamination_threshold($data) if $recalibrate;
Branch: 1 branch
BranchTrueFalseTotal
if $recalibrate 3 4 7
3152  
3153 7 return $self;
3154 } ## end sub set_voting
3155  
3156 =head2 feature_names
3157  
3158 Returns the arrayref of feature name strings stored with the model, or undef
3159 if none were provided at fit time.
3160  
3161 my $names = $iforest->feature_names;
3162  
3163 =cut
3164  
3165 4 ▶sub feature_names { return $_[0]->{feature_names} }
Subroutine feature_names: called CC=1 SCAR=0.0
Pod documented
3166  
3167 =head2 schema_version
3168  
3169 Returns the user-owned schema version string stored with the model
3170 (usually via a prototype -- see L</PROTOTYPES>), or undef if none was
3171 recorded.
3172  
3173 my $sv = $iforest->schema_version;
3174  
3175 =cut
3176  
3177 3 ▶sub schema_version { return $_[0]->{schema_version} }
Subroutine schema_version: called CC=1 SCAR=0.0
Pod documented
3178  
3179 =head2 schema_description
3180  
3181 Returns the free-text description of the variable schema stored with the
3182 model, or undef if none was recorded.
3183  
3184 =cut
3185  
3186 3 ▶sub schema_description { return $_[0]->{schema_description} }
Subroutine schema_description: called CC=1 SCAR=0.0
Pod documented
3187  
3188 =head2 feature_descriptions
3189  
3190 Returns the hashref of per-feature description strings stored with the
3191 model, or undef if none were recorded. Keys are feature names; coverage
3192 may be partial.
3193  
3194 =cut
3195  
3196 1 ▶sub feature_descriptions { return $_[0]->{feature_descriptions} }
Subroutine feature_descriptions: called CC=1 SCAR=0.0
Pod documented
3197  
3198 =head2 fit
3199  
3200 Trains the model on the specified data.
3201  
3202 The data taken is an array of arrays. Each sub-array is one sample and must
3203 contain one or more numeric features. All samples must have the same number
3204 of features. There is no upper limit on dimensionality.
3205  
3206 @training_data = (
3207 [ 3, 5 ],
3208 [ 2.3, 1 ],
3209 [ 5, 9 ],
3210 ...
3211 );
3212  
3213 # Three-feature example
3214 @training_data = (
3215 [ 1.0, 2.0, 3.0 ],
3216 [ 1.1, 1.9, 3.1 ],
3217 ...
3218 );
3219  
3220 Below shows an example of building a gaussian cluster and using that for training.
3221  
3222 # so it is reproducible
3223 srand(7);
3224  
3225 # build a gaussian cluster and add a handful of outliers...
3226  
3227 use constant PI => 3.14159265358979;
3228 sub gaussian {
3229 my ($mu, $sigma) = @_;
3230 my $u1 = rand() || 1e-12;
3231 my $u2 = rand();
3232 my $z = sqrt(-2 * log($u1)) * cos(2 * PI * $u2);
3233 return $mu + $sigma * $z;
3234 }
3235  
3236 # add some normal items
3237 for (1 .. 500) {
3238 push @data, [ gaussian(0, 1), gaussian(0, 1) ];
3239 push @truth, 0;
3240 }
3241 # add some outliers
3242 for (1 .. 20) {
3243 my $angle = rand() * 2 * PI;
3244 my $radius = 5 + rand() * 3; # distance 5..8 from the origin
3245 push @data, [ $radius * cos($angle), $radius * sin($angle) ];
3246 push @truth, 1;
3247 }
3248  
3249 $iforest->fit(\@data);
3250  
3251 =cut
3252  
3253 216 ▶sub fit {
Subroutine fit: called CC=16 SCAR=27.7
Pod documented
3254 216 my ( $self, $data ) = @_;
3255  
3256 216 ▶ croak "fit() expects a non-empty arrayref of samples"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "ARRAY" and @$data 6 210 216
Condition100%3/3
ref $data eq "ARRAY" and @$data
!ll&&!rl&&r
42210
MC/DC100%2/2
ref $data eq "ARRAY" and @$data
ref $data eq "ARRAY" @$data
Truth table100%3/3
A and B
A= ref $data eq "ARRAY"B= @$data
ABresult
0X0
100
111
3257 unless ref $data eq 'ARRAY' && @$data;
3258 croak "each sample must be an arrayref of features"
3259 210 ▶ unless ref $data->[0] eq 'ARRAY' && @{ $data->[0] };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data->[0] eq "ARRAY" and @{$data->[0];} 4 206 210
Condition100%3/3
ref $data->[0] eq "ARRAY" and @{$data->[0];}
!ll&&!rl&&r
22206
MC/DC100%2/2
ref $data->[0] eq "ARRAY" and @{$data->[0];}
ref $data->[0] eq "ARRAY" @{$data->[0];}
Truth table100%3/3
A and B
A= ref $data->[0] eq "ARRAY"B= @{$data->[0];}
ABresult
0X0
100
111
3260  
3261 206 my $n_features = scalar @{ $data->[0] };
3262 206 $self->{n_features} = $n_features;
3263  
3264 # Apply the missing-value strategy before any tree is built. Depending
3265 # on the strategy this either croaks (die), returns a dense copy with
3266 # undef cells filled (zero/impute), or passes the data through with
3267 # undef preserved for the split logic to route (nan). Everything below
3268 # trains on $train, never the raw $data.
3269 206 my $train = $self->_prepare_fit_data($data);
3270  
3271 # Per-feature medians of the raw training data, stored for ablation
3272 # explanations (explain_samples). From $data, not $train: the pure-
3273 # Perl path's densified $train would bake fill values into the
3274 # medians while the C path's raw pass-through would not, and the
3275 # baselines must not depend on use_c.
3276 200 $self->{feature_baselines} = $self->_compute_feature_baselines($data);
3277  
3278 200 my $n = scalar @$train;
3279  
3280 # Resolve sub-sample size, extension level and height limit against the
3281 # data's shape. Shared with fit_from_csv(), which learns n from a census
3282 # pass before it ever holds the rows in RAM.
3283 200 my ( $psi, $limit ) = $self->_resolve_geometry( $n, $n_features );
3284  
3285 200 ▶ srand( $self->{seed} ) if defined $self->{seed};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"seed"} 198 2 200
3286  
3287 200 my $workers = $self->{parallel_fit};
3288 200 ▶ if ( defined $workers
Branch: 3 branches
BranchTrueFalseTotal
if (defined $workers and $workers > 1 and $self->{'n_trees'} > 1 and _fork_supported()) { } 8 192 200
elsif ($self->{'_use_c'} and $self->{'_use_openmp_fit'}) { } 7 185 192
elsif ($self->{'_use_c'}) { } 119 66 185
Condition77%7/9
defined $workers and $workers > 1 and $self->{"n_trees"} > 1 and _fork_supported()
!ll&&!rl&&r
19208
defined $workers and $workers > 1 and $self->{"n_trees"} > 1
!ll&&!rl&&r
19208
defined $workers and $workers > 1
!ll&&!rl&&r
19118
MC/DC50%2/4
defined $workers and $workers > 1 and $self->{"n_trees"} > 1 and _fork_supported()
defined $workers $workers > 1 $self->{"n_trees"} > 1 _fork_supported()
Truth table60%3/5
A and B and C and D
A= defined $workersB= $workers > 1C= $self->{"n_trees"} > 1D= _fork_supported()
ABCDresult
0XXX0
10XX0
110X0
11100
11111
3289 && $workers > 1
3290 && $self->{n_trees} > 1
3291 && _fork_supported() )
3292 {
3293 8 $self->{trees} = $self->_fit_trees_parallel( $train, $psi, $limit, $workers );
3294 ▶ } elsif ( $self->{_use_c} && $self->{_use_openmp_fit} ) {
Condition100%3/3
$self->{"_use_c"} and $self->{"_use_openmp_fit"}
!ll&&!rl&&r
661197
MC/DC100%2/2
$self->{"_use_c"} and $self->{"_use_openmp_fit"}
$self->{"_use_c"} $self->{"_use_openmp_fit"}
Truth table100%3/3
A and B
A= $self->{"_use_c"}B= $self->{"_use_openmp_fit"}
ABresult
0X0
100
111
3295 7 $self->{trees} = $self->_build_forest_openmp( $train, $psi, $limit, $self->{n_trees} );
3296 } elsif ( $self->{_use_c} ) {
3297 $self->{trees}
3298 119 = $self->_build_forest_c( $train, $psi, $limit, $self->{n_trees} );
3299 } else {
3300 66 my @trees;
3301 66 for ( 1 .. $self->{n_trees} ) {
3302 3899 my $sample = _subsample( $train, $psi );
3303 3899 push @trees, $self->_build_tree( $sample, 0, $limit );
3304 }
3305 66 $self->{trees} = \@trees;
3306 }
3307  
3308 # On a re-fit, packed scoring buffers from the previous fit are still
3309 # sitting on the object; score_samples() below would pick them up and
3310 # learn the contamination threshold against the OLD forest. Drop them
3311 # so the training-set scoring runs pure-Perl against the trees just
3312 # built; _rebuild_c_trees repacks from the new trees at the end.
3313 200 delete @$self{qw(_c_nodes _c_coef_idx _c_coef_val)};
3314  
3315 # If a contamination rate was requested, learn the score cutoff that flags
3316 # that fraction of the training set. The threshold lands midway inside a
3317 # real gap between flagged and unflagged training scores (ties at the
3318 # k-boundary shift the cut to the nearest gap -- see
3319 # _threshold_from_ranked), so it sits strictly between attainable values:
3320 # unambiguous and robust to the tiny float rounding introduced by JSON
3321 # serialisation.
3322 #
3323 # Under voting => 'majority' the value predict() thresholds against is
3324 # the PER-TREE score, so the quantity to rank is each training point's
3325 # majority pivot -- the per-tree cutoff at which that point loses its
3326 # majority (see _majority_pivot_scores). A point is flagged iff its
3327 # pivot >= threshold, exactly the relation the mean-mode score has, so
3328 # the midpoint selection below serves both modes unchanged.
3329 $self->_learn_contamination_threshold($train)
3330 200 ▶ if defined $self->{contamination};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"contamination"} 16 184 200
3331  
3332 200 ▶ $self->_rebuild_c_trees() if $self->{_use_c};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_use_c"} 134 66 200
3333 200 return $self;
3334 } ## end sub fit
3335  
3336 =head2 fit_tagged(\@rows)
3337  
3338 Trains the model on an arrayref of hashrefs of named feature values --
3339 the tagged counterpart of L</fit>. Each row goes through
3340 L<tagged_row_to_array|/tagged_row_to_array(\%row, $caller)> (and
3341 therefore through the munger plan when C<mungers> is configured, which is
3342 the point: training data and scoring data are munged by the identical
3343 plan), then the positional rows are handed to C<fit>.
3344  
3345 $iforest->fit_tagged([
3346 { cpu => 0.9, mem => 0.4, disk => 0.1 },
3347 { cpu => 0.2, mem => 0.3, disk => 0.2 },
3348 ...
3349 ]);
3350  
3351 Requires stored C<feature_names>. Croaks under the same conditions as
3352 L<tagged_row_to_array|/tagged_row_to_array(\%row, $caller)>, naming the offending row by index.
3353  
3354 =cut
3355  
3356 4 ▶sub fit_tagged {
Subroutine fit_tagged: called CC=4 SCAR=14.6
Pod documented
3357 4 my ( $self, $data ) = @_;
3358 4 ▶ croak "fit_tagged() expects a non-empty arrayref of hashref samples"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "ARRAY" and @$data 0 4 4
Condition33%1/3
ref $data eq "ARRAY" and @$data
!ll&&!rl&&r
004
MC/DC0%0/2
ref $data eq "ARRAY" and @$data
ref $data eq "ARRAY" @$data
Truth table33%1/3
A and B
A= ref $data eq "ARRAY"B= @$data
ABresult
0X0
100
111
3359 unless ref $data eq 'ARRAY' && @$data;
3360 4 my @rows;
3361 4 for my $i ( 0 .. $#$data ) {
3362 670 push @rows, $self->tagged_row_to_array( $data->[$i], "fit_tagged (row $i)" );
3363 }
3364 4 return $self->fit( \@rows );
3365 } ## end sub fit_tagged
3366  
3367 =head2 fit_from_csv($path, %opts)
3368  
3369 Trains the model directly from a CSV file B<without loading it into RAM>,
3370 for datasets too large to slurp. An Isolation Forest never trains on more
3371 than C<n_trees * sample_size> rows -- each tree uses one independent
3372 sub-sample of C<sample_size> points -- so the working set is bounded by the
3373 model's parameters, not the file size.
3374  
3375 The file is read in two (or three) passes:
3376  
3377 =over 4
3378  
3379 =item 1.
3380  
3381 B<Census> -- count the rows (this is the true C<n> that fixes C<psi =
3382 min(sample_size, n)>) and pin the feature width. By default this is an
3383 I<index> pass (see C<index> below): a fast block-scan that also records each
3384 data row's byte offset.
3385  
3386 =item 2.
3387  
3388 B<Gather> -- retain only the rows the trees actually sampled (chosen in
3389 bounded memory via Floyd's algorithm), then build each tree from its
3390 sub-sample exactly as L</fit> would. With the offset table from pass 1 this
3391 B<seeks straight to the sampled rows> instead of re-scanning the file.
3392  
3393 =item 3.
3394  
3395 B<Threshold> (only when C<contamination> is set) -- score every row against
3396 the built forest and place the cut at the contamination boundary. The cut
3397 is B<exact>, not estimated: a single min-heap of the C<k+1> largest scores
3398 (C<k = round(contamination * n)>) captures everything
3399 L</decision_threshold> selection needs, with a rare extra pass to resolve a
3400 tie block straddling the boundary. Under C<< use_c => 1 >> (the default when
3401 the C backend is present) this pass runs through the C scorer, so it stays
3402 fast even over millions of rows.
3403  
3404 =back
3405  
3406 Neither census variant parses cells into numbers or checks for missing
3407 values: only the rows that actually train (via gather) or are scored (the
3408 threshold pass) are validated, so a malformed or missing cell in a
3409 never-used row is not reported. In particular, under C<< missing => 'die' >>
3410 a missing cell is rejected exactly when it appears in a sampled training row.
3411  
3412 Because rows are addressed by their position across passes, C<$path> must be
3413 a stable, re-readable file (not a pipe or C<STDIN>).
3414  
3415 The first line is skipped as a header when it holds any non-numeric text (a
3416 feature-name row) or exactly matches the model's stored C<feature_names> --
3417 data rows contain only numbers and empty cells. Pass C<< header => 1 >> to
3418 force the first line to be skipped even when it is all-numeric.
3419  
3420 Options:
3421  
3422 =over 4
3423  
3424 =item * C<< header => 1 >> -- always skip the first line as a column header
3425 (otherwise a header is auto-detected as described above).
3426  
3427 =item * C<< index => 0 >> -- disable the offset-index pass and use the
3428 streaming two-pass reader instead. The index is on by default: it makes
3429 gather a random-access read of just the sampled rows rather than a second
3430 full scan, but costs an C<8 * n>-byte offset table. When that table would
3431 exceed C<index_max> it is dropped automatically and the fit falls back to
3432 streaming. (In index mode a blank line is one that is empty or contains only
3433 whitespace, judged cheaply; pass C<< index => 0 >> for files where that
3434 matters.)
3435  
3436 =item * C<< index_max => bytes >> -- ceiling on the offset table (default
3437 256 MiB). Above it, the index is abandoned mid-scan and gather streams.
3438  
3439 =item * C<< c_scan => 0 >> -- validate each scored cell with
3440 C<looks_like_number> in the threshold pass instead of letting the C packer
3441 coerce it. C<c_scan> is on by default and takes effect only on the C
3442 mean-voting scoring path, where it is a large saving over millions of rows;
3443 it produces the identical result on valid data, but coerces a non-numeric
3444 scored cell to C<0.0> (nudging the threshold) rather than dying on it.
3445  
3446 =back
3447  
3448 Every column is a feature; an empty cell is treated as a missing value and
3449 handled by the model's C<missing> strategy. The resulting model is
3450 identical in shape to one built by L</fit> and is fully deterministic given
3451 the same file, C<seed>, and parameters (though not bit-identical to
3452 L</fit>, whose RNG stream interleaves sampling and tree-building
3453 differently).
3454  
3455 Current limitations: C<mungers> and tagged/named columns are not supported
3456 (load such data through L<fit_tagged|/fit_tagged(\@rows)>), and the trees are always built
3457 serially in pure Perl -- C<parallel_fit>/C<use_openmp_fit> are ignored for
3458 the build, though scoring is still accelerated when C<use_c> is on.
3459  
3460 my $iforest = Algorithm::Classifier::IsolationForest->new(
3461 n_trees => 100,
3462 sample_size => 256,
3463 contamination => 0.01,
3464 seed => 42,
3465 );
3466 $iforest->fit_from_csv('huge.csv', header => 1);
3467  
3468 =cut
3469  
3470 70 ▶sub fit_from_csv {
Subroutine fit_from_csv: called CC=21 SCAR=30.5
Pod documented
3471 70 my ( $self, $path, %opt ) = @_;
3472  
3473 70 ▶ croak "fit_from_csv() requires a path to a CSV file"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and length $path 2 68 70
Condition100%3/3
defined $path and length $path
!ll&&!rl&&r
1168
MC/DC100%2/2
defined $path and length $path
defined $path length $path
Truth table100%3/3
A and B
A= defined $pathB= length $path
ABresult
0X0
100
111
3474 unless defined $path && length $path;
3475 68 ▶ croak "fit_from_csv(): '$path' is not a readable file"
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path and -r _ 1 67 68
Condition66%2/3
-f $path and -r _
!ll&&!rl&&r
1067
MC/DC50%1/2
-f $path and -r _
-f $path -r _
Truth table66%2/3
A and B
A= -f $pathB= -r _
ABresult
0X0
100
111
3476 unless -f $path && -r _;
3477 67 ▶ croak "fit_from_csv() does not support munger models; " . "load the data through fit_tagged/fit instead"
Branch: 1 branch
BranchTrueFalseTotal
if _plan($self) 0 67 67
3478 if _plan($self);
3479  
3480 # Decide once whether the first line is a header, so every pass skips the
3481 # same line and row indices stay aligned. header => 1 forces it; otherwise
3482 # a first line carrying any non-numeric text (or matching stored
3483 # feature_names) is a header -- data rows hold only numbers and blanks.
3484 67 my $skip_first = $self->_detect_header( $path, $opt{header} );
3485  
3486 # ---- Pass 1: census. Establish the true row count (which fixes psi) and
3487 # pin the feature width. Neither census variant parses cells into numbers
3488 # or checks for missing values -- only the rows that actually train
3489 # (_numify_row, in gather) or get scored (the threshold pass) are validated,
3490 # so a malformed or missing cell in a never-sampled row is not seen.
3491 #
3492 # By default the census is an "index" pass: a block-scan that also records
3493 # each data row's byte offset, letting Pass 2 seek straight to the sampled
3494 # rows instead of re-scanning the whole file. The offset table costs 8*n
3495 # bytes; when that would top index_max (or index => 0 was passed) it is not
3496 # built and both passes fall back to the streaming reader.
3497 67 ▶ my $use_index = exists $opt{index} ? $opt{index} : 1;
Branch: 1 branch
BranchTrueFalseTotal
exists $opt{'index'} ? : 4 63 67
3498 67 ▶ my $index_max = defined $opt{index_max} ? $opt{index_max} : ( 256 * 1024 * 1024 );
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'index_max'} ? : 2 65 67
3499  
3500 67 my ( $n, $n_features, $offsets );
3501 67 ▶ if ($use_index) {
Branch: 1 branch
BranchTrueFalseTotal
if ($use_index) { } 65 2 67
3502 65 ( $n, $n_features, $offsets ) = $self->_index_pass( $path, $skip_first, $index_max );
3503 } else {
3504 2 ( $n, $n_features ) = $self->_census_stream( $path, $skip_first );
3505 }
3506 67 ▶ croak "fit_from_csv(): no data rows in '$path'" unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 1 66 67
3507  
3508 # A stored feature_names schema fixes the expected column count.
3509 66 ▶ if ( ref $self->{feature_names} eq 'ARRAY' && @{ $self->{feature_names} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};}) 8 58 66
Condition66%2/3
ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};}
!ll&&!rl&&r
5808
MC/DC50%1/2
ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};}
ref $self->{"feature_names"} eq "ARRAY" @{$self->{"feature_names"};}
Truth table66%2/3
A and B
A= ref $self->{"feature_names"} eq "ARRAY"B= @{$self->{"feature_names"};}
ABresult
0X0
100
111
3510 8 my $want = scalar @{ $self->{feature_names} };
3511 8 ▶ croak "fit_from_csv(): $want feature_names but CSV has $n_features columns"
Branch: 1 branch
BranchTrueFalseTotal
unless $want == $n_features 2 6 8
3512 unless $want == $n_features;
3513 }
3514  
3515 64 $self->{n_features} = $n_features;
3516 64 my ( $psi, $limit ) = $self->_resolve_geometry( $n, $n_features );
3517  
3518 # ---- Choose which row indices each tree trains on: an independent,
3519 # uniform psi-subset drawn without replacement. Floyd's algorithm draws
3520 # each subset in O(psi) memory, never materialising the 0..n-1 index
3521 # vector _subsample() uses -- for an out-of-core n that vector would not
3522 # fit either. %want maps each needed row index to the (tree, slot) pairs
3523 # awaiting it, so a row several trees picked is gathered once and shared.
3524 64 ▶ srand( $self->{seed} ) if defined $self->{seed};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"seed"} 64 0 64
3525 64 my @tree_idx; # tree => [ chosen row indices ]
3526 my %want; # row index => [ [tree, slot], ... ]
3527 64 for my $t ( 0 .. $self->{n_trees} - 1 ) {
3528 2309 my @idx = _sample_indices_distinct( $n, $psi );
3529 2309 $tree_idx[$t] = \@idx;
3530 2309 push @{ $want{ $idx[$_] } }, [ $t, $_ ] for 0 .. $#idx;
3531 }
3532  
3533 # ---- Pass 2: gather the sampled rows (validated + coerced by _numify_row).
3534 # With an offset table this seeks straight to them; otherwise it re-scans.
3535 64 ▶ my $pool
Branch: 1 branch
BranchTrueFalseTotal
$offsets ? : 60 4 64
3536 = $offsets
3537 ? $self->_gather_indexed( $path, $offsets, \%want )
3538 : $self->_gather_stream( $path, $skip_first, \%want );
3539  
3540 # Baselines for ablation explanations, learned from the gathered
3541 # sub-sample -- like the impute fill below, the only rows bounded-
3542 # memory fitting ever holds. Before _apply_missing_to_pool, which
3543 # densifies the pool in place (the medians must come from present
3544 # values only, matching fit()). Median is an exact order statistic,
3545 # so the hash-order values() walk cannot change the result.
3546 60 $self->{feature_baselines} = $self->_compute_feature_baselines( [ values %$pool ] );
3547  
3548 # Apply the missing-value strategy to the retained rows (see fit()'s
3549 # _prepare_fit_data; the impute fill is learned from this training
3550 # sub-sample, the only value bounded-memory fitting can compute).
3551 60 $self->_apply_missing_to_pool($pool);
3552  
3553 # ---- Build. Each tree trains on its gathered sub-sample -- structurally
3554 # identical to fit()'s per-tree _build_tree(_subsample(...)).
3555 60 my @trees;
3556 60 for my $t ( 0 .. $self->{n_trees} - 1 ) {
3557 2283 my $sample = [ @{$pool}{ @{ $tree_idx[$t] } } ];
3558 2283 push @trees, $self->_build_tree( $sample, 0, $limit );
3559 }
3560 60 $self->{trees} = \@trees;
3561  
3562 # Repack the just-built trees for the C scorer up front. fit() scores its
3563 # learned threshold pure-Perl because its training set is small; the
3564 # streaming contamination pass here may score millions of rows, so paying
3565 # one repack now lets that pass run through the C path instead (bit-
3566 # identical result, minutes -> seconds). The delete first clears any stale
3567 # buffers from a prior fit so the repack reflects the new forest.
3568 60 delete @$self{qw(_c_nodes _c_coef_idx _c_coef_val)};
3569 60 ▶ $self->_rebuild_c_trees() if $self->{_use_c};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_use_c"} 33 27 60
3570  
3571 # c_scan (default on): let the C scorer's packer coerce raw cells via SvNV
3572 # in the contamination pass instead of validating each with looks_like_number
3573 # in Perl -- a large saving over millions of rows. It only takes effect on
3574 # the C mean-voting path; see _stream_scores.
3575 60 ▶ my $c_scan = exists $opt{c_scan} ? $opt{c_scan} : 1;
Branch: 1 branch
BranchTrueFalseTotal
exists $opt{'c_scan'} ? : 6 54 60
3576 $self->_learn_contamination_threshold_streaming( $path, $skip_first, $n, $c_scan )
3577 60 ▶ if defined $self->{contamination};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"contamination"} 31 29 60
3578  
3579 58 return $self;
3580 } ## end sub fit_from_csv
3581  
3582 =head2 pack_data(\@data)
3583  
3584 Returns an opaque, blessed wrapper around the input dataset that the
3585 scoring methods can use directly, skipping the per-call work of walking
3586 the arrayref-of-arrayrefs and converting each cell into a double. At
3587 high feature counts this is a meaningful win when the same dataset is
3588 scored repeatedly (e.g. interactive threshold tuning, dashboards,
3589 plotting that updates as parameters change).
3590  
3591 Requires the Inline::C backend; croaks if C<use_c> is false.
3592  
3593 my $packed = $forest->pack_data(\@data);
3594  
3595 # Now any of these accept either an arrayref or the packed wrapper:
3596 my $scores = $forest->score_samples($packed);
3597 my $flags = $forest->predict($packed, 0.6);
3598 my ($s, $l) = $forest->score_predict_split($packed);
3599  
3600 The wrapper has C<n_pts> and C<n_feats> accessors for introspection.
3601 The feature count is matched against the model on every call; passing a
3602 packed dataset built for a different feature count is a fatal error.
3603  
3604 =cut
3605  
3606 =head2 path_lengths(\@data)
3607  
3608 Returns an arrayref of the mean isolation depth per sample, for inspection.
3609  
3610 my $lengths = $forest->path_lengths(\@data);
3611  
3612 print "x, y, length\n";
3613  
3614 my $int=0;
3615 while (defined($data[$int])) {
3616 print $data[$int][0].', '.$data[$int][1].', '.$lengths->[$int]."\n";
3617  
3618 $int++;
3619 }
3620  
3621 =cut
3622  
3623 2340 ▶sub path_lengths {
Subroutine path_lengths: called CC=6 SCAR=17.9
Pod documented
3624 2340 my ( $self, $data ) = @_;
3625 2340 $self->_check_fitted;
3626 2338 my $trees = $self->{trees};
3627 2338 my $t = scalar @$trees;
3628  
3629 2338 ▶ if ( $self->{_use_c} && $self->{_c_nodes} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_use_c"} and $self->{"_c_nodes"}) 2337 1 2338
Condition66%2/3
$self->{"_use_c"} and $self->{"_c_nodes"}
!ll&&!rl&&r
102337
MC/DC50%1/2
$self->{"_use_c"} and $self->{"_c_nodes"}
$self->{"_use_c"} $self->{"_c_nodes"}
Truth table66%2/3
A and B
A= $self->{"_use_c"}B= $self->{"_c_nodes"}
ABresult
0X0
100
111
3630 2337 my ( $n_pts, $nf, $x_packed ) = $self->_resolve_input($data);
3631 2337 my $sums_packed = "\0" x ( $n_pts * 8 );
3632 score_all_xs(
3633 $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
3634 $x_packed, $sums_packed, $n_pts,
3635 $nf, $t, $self->{_use_openmp}
3636 2337 );
3637 2337 my $result = [];
3638 2337 finalize_path_lengths_xs( $sums_packed, $n_pts, $t + 0.0, $result );
3639 2337 return $result;
3640 } ## end if ( $self->{_use_c} && $self->{_c_nodes} )
3641  
3642 1 $data = $self->_prepare_perl_input($data);
3643 1 ▶ my $nan = $self->{missing} eq 'nan' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'missing'} eq 'nan' ? : 0 1 1
3644  
3645 # Pure-Perl fallback (tree-outer, sample-inner for cache locality).
3646 1 my @sums = (0) x @$data;
3647 1 for my $tree (@$trees) {
3648 60 for my $i ( 0 .. $#$data ) {
3649 6000 $sums[$i] += _path_length( $data->[$i], $tree, 0, $nan );
3650 }
3651 }
3652 1 return [ map { $_ / $t } @sums ];
3653 } ## end sub path_lengths
3654  
3655 =head2 predict(\@data, $threshold)
3656  
3657 Returns an arrayref of 0/1 labels for the specified data.
3658  
3659 If threshold is not specified it uses the contamination-learned cutoff (if
3660 C<fit> was called with C<contamination>), otherwise 0.5.
3661  
3662 Under C<< voting => 'majority' >> the threshold is the per-tree score
3663 cutoff each tree votes against, and a sample is labelled 1 when more than
3664 half of the trees (C<int(n_trees/2) + 1>) vote it anomalous. Tree walking
3665 stops per sample as soon as the outcome is decided, so this is typically
3666 cheaper than scoring.
3667  
3668 my $results = $forest->predict(\@data, $threshold);
3669  
3670 print "x, y, result\n";
3671  
3672 my $int=0;
3673 while (defined($data[$int])) {
3674 print $data[$int][0].', '.$data[$int][1].', '.$results->[$int]."\n";
3675  
3676 $int++;
3677 }
3678  
3679 =cut
3680  
3681 4613 ▶sub predict {
Subroutine predict: called CC=18 SCAR=28.9
Pod documented
3682 4613 my ( $self, $data, $threshold ) = @_;
3683 $threshold
3684 = defined $threshold ? $threshold
3685 : defined $self->{threshold} ? $self->{threshold}
3686 4613 ▶ : 0.5;
Branch: 2 branches
BranchTrueFalseTotal
defined $threshold ? : 4560 53 4613
defined $self->{'threshold'} ? : 12 41 53
3687 4613 $self->_check_fitted;
3688  
3689 # Majority voting: $threshold is the PER-TREE score cutoff and the
3690 # label is the majority of the tree votes (int(t/2) + 1). Both the C
3691 # and the Perl loop stop walking a sample's remaining trees as soon
3692 # as the outcome is decided -- MVIForest's "stop at majority" saving.
3693 4611 ▶ if ( $self->{voting} eq 'majority' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"voting"} eq "majority") 18 4593 4611
3694 18 my $trees = $self->{trees};
3695 18 my $t = scalar @$trees;
3696 18 my $cut = _depth_cut( $threshold, $self->{c_psi} );
3697 18 my $maj = _min_votes($t);
3698  
3699 18 ▶ if ( $self->{_use_c} && $self->{_c_nodes} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_use_c"} and $self->{"_c_nodes"}) 16 2 18
Condition66%2/3
$self->{"_use_c"} and $self->{"_c_nodes"}
!ll&&!rl&&r
2016
MC/DC50%1/2
$self->{"_use_c"} and $self->{"_c_nodes"}
$self->{"_use_c"} $self->{"_c_nodes"}
Truth table66%2/3
A and B
A= $self->{"_use_c"}B= $self->{"_c_nodes"}
ABresult
0X0
100
111
3700 16 my ( $n_pts, $nf, $x_packed ) = $self->_resolve_input($data);
3701 16 my $labels_packed = "\0" x ( $n_pts * 8 );
3702 vote_all_xs( $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
3703 16 $x_packed, $labels_packed, $n_pts, $nf, $t, $cut, $maj, $self->{_use_openmp} );
3704 16 my $result = [];
3705 16 vote_labels_xs( $labels_packed, $n_pts, $result );
3706 16 return $result;
3707 }
3708  
3709 2 my $rows = $self->_prepare_perl_input($data);
3710 2 ▶ my $nan = $self->{missing} eq 'nan' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'missing'} eq 'nan' ? : 0 2 2
3711 2 my @labels;
3712 2 for my $x (@$rows) {
3713 126 my $votes = 0;
3714 126 my $label = 0;
3715 126 for my $ti ( 0 .. $t - 1 ) {
3716 3397 ▶ if ( _path_length( $x, $trees->[$ti], 0, $nan ) <= $cut ) {
Branch: 1 branch
BranchTrueFalseTotal
if (_path_length($x, $trees->[$ti], 0, $nan) <= $cut) 1003 2394 3397
3717 1003 $votes++;
3718 1003 ▶ if ( $votes >= $maj ) { $label = 1; last }
Branch: 1 branch
BranchTrueFalseTotal
if ($votes >= $maj) 9 994 1003
3719 }
3720 3388 ▶ last if $votes + ( $t - 1 - $ti ) < $maj;
Branch: 1 branch
BranchTrueFalseTotal
if $votes + ($t - 1 - $ti) < $maj 117 3271 3388
3721 }
3722 126 push @labels, $label;
3723 } ## end for my $x (@$rows)
3724 2 return \@labels;
3725 } ## end if ( $self->{voting} eq 'majority' )
3726  
3727 # Fast path: threshold the raw path-length sums directly, skipping the
3728 # per-point exp() and the intermediate scores arrayref.
3729 # Derivation: score = exp(-sum * log(2) / (c*t))
3730 # so score >= T iff sum <= -log(T) * c * t / log(2)
3731 # Only valid for a normal threshold in (0, 1) and a positive c.
3732 4593 ▶ if ( $self->{_use_c}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0 and $threshold > 0 and $threshold < 1) 4574 19 4593
Condition83%10/12
$self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0 and $threshold > 0 and $threshold < 1
!ll&&!rl&&r
1724574
$self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0 and $threshold > 0
!ll&&!rl&&r
1614576
$self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0
!ll&&!rl&&r
1604577
$self->{"_use_c"} and $self->{"_c_nodes"}
!ll&&!rl&&r
1604577
MC/DC60%3/5
$self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0 and $threshold > 0 and $threshold < 1
$self->{"_use_c"} $self->{"_c_nodes"} $self->{"c_psi"} > 0 $threshold > 0 $threshold < 1
Truth table66%4/6
A and B and C and D and E
A= $self->{"_use_c"}B= $self->{"_c_nodes"}C= $self->{"c_psi"} > 0D= $threshold > 0E= $threshold < 1
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
3733 && $self->{_c_nodes}
3734 && $self->{c_psi} > 0
3735 && $threshold > 0
3736 && $threshold < 1 )
3737 {
3738 4574 my $trees = $self->{trees};
3739 4574 my $t = scalar @$trees;
3740 4574 my $c = $self->{c_psi};
3741 4574 my ( $n_pts, $nf, $x_packed ) = $self->_resolve_input($data);
3742 4574 my $sums_packed = "\0" x ( $n_pts * 8 );
3743 score_all_xs(
3744 $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
3745 $x_packed, $sums_packed, $n_pts,
3746 $nf, $t, $self->{_use_openmp}
3747 4574 );
3748 4574 my $sum_threshold = -log($threshold) * $c * $t / log(2);
3749 4574 my $result = [];
3750 4574 predict_sums_xs( $sums_packed, $n_pts, $sum_threshold, $result );
3751 4574 return $result;
3752 } ## end if ( $self->{_use_c} && $self->{_c_nodes} ...)
3753  
3754 # Fallback: edge thresholds, c==0, or no C backend.
3755 19 my $scores = $self->score_samples( $self->_to_arrayref($data) );
3756 19 ▶ return [ map { $_ >= $threshold ? 1 : 0 } @$scores ];
Branch: 1 branch
BranchTrueFalseTotal
$_ >= $threshold ? : 446 1671 2117
3757 } ## end sub predict
3758  
3759 =head2 predict_tagged(\%row, $threshold)
3760  
3761 Predicts whether a single sample is an anomaly using a hashref of named
3762 feature values. The model must have been fitted (or loaded from a model
3763 that was fitted) with feature names stored via C<feature_names>.
3764  
3765 C<$threshold> defaults the same way as in C<predict>.
3766  
3767 Returns a scalar 1 (anomaly) or 0 (normal).
3768  
3769 my $label = $forest->predict_tagged(
3770 { cpu => 0.9, mem => 0.4, disk => 0.1 },
3771 );
3772  
3773 Croaks if the model has no stored feature names, if the hashref contains a
3774 key that is not a known feature name, or if a feature name is absent from the
3775 hashref.
3776  
3777 =cut
3778  
3779 =head2 tagged_row_to_array(\%row, $caller)
3780  
3781 Validates a hashref of named feature values against the model's stored
3782 C<feature_names> and returns a positional arrayref ready to pass to any
3783 of the scoring or prediction methods.
3784  
3785 C<$caller> is a string used in error messages to identify which method
3786 triggered the validation (pass the calling method's name).
3787  
3788 my $vec = $forest->tagged_row_to_array(\%row, 'my_method');
3789 # returns e.g. [0.9, 0.4, 0.1] ordered by feature_names
3790  
3791 Croaks if:
3792  
3793 =over 4
3794  
3795 =item * C<$row> is not a hashref
3796  
3797 =item * the model has no stored C<feature_names>
3798  
3799 =item * the hashref contains a key that is not a known feature name
3800  
3801 =item * a feature name is absent from the hashref
3802  
3803 =back
3804  
3805 =cut
3806  
3807 1016 ▶sub tagged_row_to_array {
Subroutine tagged_row_to_array: called CC=9 SCAR=22.0
Pod documented
3808 1016 my ( $self, $row, $caller ) = @_;
3809 1016 ▶ croak "$caller requires a hashref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 5 1011 1016
3810 unless ref $row eq 'HASH';
3811  
3812 # With mungers configured the compiled plan owns the row assembly:
3813 # it knows the real input fields (munger 'from' sources included,
3814 # which need not be tags at all) and croaks on a missing one. Extra
3815 # keys are ignored -- with expanders and combiners in play, "the
3816 # exact key set" is the plan's knowledge, not feature_names'.
3817 1011 ▶ if ( my $plan = _plan($self) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $plan = _plan($self)) 945 65 1010
3818 945 my $vec = eval { $plan->apply_named($row) };
3819 945 ▶ croak "$caller: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 944 945
3820 944 return $vec;
3821 }
3822  
3823 croak "this model has no stored feature_names; " . "refit with -t tags or pass feature_names to new()"
3824 unless defined $self->{feature_names}
3825 && ref $self->{feature_names} eq 'ARRAY'
3826 65 ▶ && @{ $self->{feature_names} };
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"feature_names"} and ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};} 5 60 65
Condition66%4/6
defined $self->{"feature_names"} and ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};}
!ll&&!rl&&r
5060
defined $self->{"feature_names"} and ref $self->{"feature_names"} eq "ARRAY"
!ll&&!rl&&r
5060
MC/DC33%1/3
defined $self->{"feature_names"} and ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};}
defined $self->{"feature_names"} ref $self->{"feature_names"} eq "ARRAY" @{$self->{"feature_names"};}
Truth table50%2/4
A and B and C
A= defined $self->{"feature_names"}B= ref $self->{"feature_names"} eq "ARRAY"C= @{$self->{"feature_names"};}
ABCresult
0XX0
10X0
1100
1111
3827  
3828 60 my @names = @{ $self->{feature_names} };
3829  
3830 my @unknown = grep {
3831 60 my $k = $_;
3832 161 !grep { $_ eq $k } @names
3833 } keys %$row;
3834 60 ▶ croak "unknown feature name(s) in hashref: " . join( ', ', sort @unknown )
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 5 55 60
3835 if @unknown;
3836  
3837 55 my @missing = grep { !exists $row->{$_} } @names;
3838 55 ▶ croak "missing feature name(s) in hashref: " . join( ', ', @missing )
Branch: 1 branch
BranchTrueFalseTotal
if @missing 7 48 55
3839 if @missing;
3840  
3841 48 return [ map { $row->{$_} } @names ];
3842 } ## end sub tagged_row_to_array
3843  
3844 12 ▶sub predict_tagged {
Subroutine predict_tagged: called CC=1 SCAR=0.0
Pod documented
3845 12 my ( $self, $row, $threshold ) = @_;
3846 12 my $vec = $self->tagged_row_to_array( $row, 'predict_tagged' );
3847 8 my $result = $self->predict( [$vec], $threshold );
3848 8 return $result->[0];
3849 }
3850  
3851 =head2 munge_rows(\@rows)
3852  
3853 Applies the model's scalar mungers to positional rows (arrayrefs in
3854 C<feature_names> order), returning a new arrayref of munged rows. A
3855 model without C<mungers> returns the input unchanged, so callers such
3856 as the CLI can pass every dataset through unconditionally.
3857  
3858 Croaks if the munger set contains expanding or combining mungers --
3859 their inputs are named source fields that positional rows cannot
3860 express; use the tagged methods (or L<fit_tagged|/fit_tagged(\@rows)>) for those.
3861  
3862 my $numeric = $iforest->munge_rows(\@raw_rows);
3863  
3864 =cut
3865  
3866 6 ▶sub munge_rows {
Subroutine munge_rows: called CC=5 SCAR=16.2
Pod documented
3867 6 my ( $self, $rows ) = @_;
3868 6 ▶ croak "munge_rows() expects an arrayref of rows"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rows eq "ARRAY" 0 6 6
3869 unless ref $rows eq 'ARRAY';
3870 6 my $plan = _plan($self);
3871 6 ▶ return $rows unless $plan;
Branch: 1 branch
BranchTrueFalseTotal
unless $plan 0 6 6
3872 6 my @out;
3873 6 for my $i ( 0 .. $#$rows ) {
3874 326 my $munged = eval { $plan->apply_positional( $rows->[$i] ) };
3875 326 ▶ croak "munge_rows (row $i): $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 325 326
3876 325 push @out, $munged;
3877 }
3878 5 return \@out;
3879 } ## end sub munge_rows
3880  
3881 =head2 score_samples(\@data)
3882  
3883 Returns an arrayref of anomaly scores, between 0 and 1.
3884  
3885 Scores near 1 are strong anomalies (isolated quickly).
3886  
3887 Scores well below 0.5 are normal.
3888  
3889 Scores ~0.5 means the points are hard to tell apart.
3890  
3891 Under C<< voting => 'majority' >> the returned value is instead the
3892 fraction of trees voting the sample anomalous at the model's decision
3893 threshold (the contamination-learned cutoff if present, otherwise 0.5) --
3894 still in [0, 1], but discrete in steps of C<1/n_trees>, with a majority
3895 label corresponding to a fraction strictly above 0.5.
3896  
3897 my $scores = $forest->score_samples(\@data);
3898  
3899 print "x, y, score\n";
3900  
3901 my $int=0;
3902 while (defined($data[$int])) {
3903 print $data[$int][0].', '.$data[$int][1].', '.$scores->[$int]."\n";
3904  
3905 $int++;
3906 }
3907  
3908 =cut
3909  
3910 5077 ▶sub score_samples {
Subroutine score_samples: called CC=12 SCAR=25.1
Pod documented
3911 5077 my ( $self, $data ) = @_;
3912 5077 $self->_check_fitted;
3913 5075 my $c = $self->{c_psi};
3914 5075 my $trees = $self->{trees};
3915 5075 my $t = scalar @$trees;
3916  
3917 # Majority voting: the "score" is the fraction of trees voting the
3918 # sample anomalous at the model's decision threshold (contamination-
3919 # learned if present, else 0.5) -- discrete in steps of 1/t.
3920 5075 ▶ if ( $self->{voting} eq 'majority' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"voting"} eq "majority") 12 5063 5075
3921 12 ▶ my $theta = defined $self->{threshold} ? $self->{threshold} : 0.5;
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'threshold'} ? : 0 12 12
3922 12 my $cut = _depth_cut( $theta, $c );
3923  
3924 12 ▶ if ( $self->{_use_c} && $self->{_c_nodes} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_use_c"} and $self->{"_c_nodes"}) 10 2 12
Condition66%2/3
$self->{"_use_c"} and $self->{"_c_nodes"}
!ll&&!rl&&r
2010
MC/DC50%1/2
$self->{"_use_c"} and $self->{"_c_nodes"}
$self->{"_use_c"} $self->{"_c_nodes"}
Truth table66%2/3
A and B
A= $self->{"_use_c"}B= $self->{"_c_nodes"}
ABresult
0X0
100
111
3925 10 my ( $n_pts, $nf, $x_packed ) = $self->_resolve_input($data);
3926 10 my $votes_packed = "\0" x ( $n_pts * 8 );
3927 vote_all_xs( $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
3928 10 $x_packed, $votes_packed, $n_pts, $nf, $t, $cut, 0, $self->{_use_openmp} );
3929  
3930 # votes/t is exactly the "divide the sum buffer by t" shape
3931 # finalize_path_lengths_xs implements, so reuse it.
3932 10 my $result = [];
3933 10 finalize_path_lengths_xs( $votes_packed, $n_pts, $t + 0.0, $result );
3934 10 return $result;
3935 } ## end if ( $self->{_use_c} && $self->{_c_nodes} )
3936  
3937 2 my $votes = $self->_vote_counts_perl( $self->_prepare_perl_input($data), $cut );
3938 2 return [ map { $_ / $t } @$votes ] if _NV_IS_DOUBLE;
3939  
3940 # Wide-NV perls: the C finalizers divide in double, so narrow the
3941 # vote fraction to match -- see _NV_IS_DOUBLE.
3942 0 return [ map { _to_double( $_ / $t ) } @$votes ];
3943 } ## end if ( $self->{voting} eq 'majority' )
3944  
3945 5063 ▶ if ( $self->{_use_c} && $self->{_c_nodes} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_use_c"} and $self->{"_c_nodes"}) 4941 122 5063
Condition100%3/3
$self->{"_use_c"} and $self->{"_c_nodes"}
!ll&&!rl&&r
108144941
MC/DC100%2/2
$self->{"_use_c"} and $self->{"_c_nodes"}
$self->{"_use_c"} $self->{"_c_nodes"}
Truth table100%3/3
A and B
A= $self->{"_use_c"}B= $self->{"_c_nodes"}
ABresult
0X0
100
111
3946 4941 my ( $n_pts, $nf, $x_packed ) = $self->_resolve_input($data);
3947 4940 my $sums_packed = "\0" x ( $n_pts * 8 );
3948 score_all_xs(
3949 $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
3950 $x_packed, $sums_packed, $n_pts,
3951 $nf, $t, $self->{_use_openmp}
3952 4940 );
3953 4940 ▶ if ( $c > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c > 0) 4940 0 4940
3954 4940 my $inv = log(2) / ( $c * $t );
3955 4940 my $result = [];
3956 4940 finalize_scores_xs( $sums_packed, $n_pts, $inv, $result );
3957 4940 return $result;
3958 }
3959 0 return [ (0.5) x $n_pts ];
3960 } ## end if ( $self->{_use_c} && $self->{_c_nodes} )
3961  
3962 122 $data = $self->_prepare_perl_input($data);
3963 122 ▶ my $nan = $self->{missing} eq 'nan' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'missing'} eq 'nan' ? : 4 118 122
3964  
3965 # Pure-Perl fallback (tree-outer, sample-inner for cache locality).
3966 122 my @sums = (0) x @$data;
3967 122 for my $tree (@$trees) {
3968 8872 for my $i ( 0 .. $#$data ) {
3969 1584204 $sums[$i] += _path_length( $data->[$i], $tree, 0, $nan );
3970 }
3971 }
3972  
3973 # Precompute the single normalising factor; exp() is a direct FPU
3974 # instruction and faster than Perl's general-purpose 2**x (pow).
3975 # Derivation: 2**(-avg/c) = 2**(-(sum/t)/c) = exp(-sum * log(2)/(c*t))
3976 122 ▶ if ( $c > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c > 0) 122 0 122
3977 122 my $inv = log(2) / ( $c * $t );
3978 122 return [ map { exp( -$_ * $inv ) } @sums ];
3979 }
3980 0 return [ (0.5) x @sums ];
3981 } ## end sub score_samples
3982  
3983 =head2 score_sample_tagged(\%row)
3984  
3985 Scores a single sample supplied as a hashref of named feature values.
3986 The model must have stored feature names (set via C<feature_names> in
3987 C<new()> or the C<-t> CLI flag at fit time).
3988  
3989 Returns a scalar anomaly score in (0, 1].
3990  
3991 my $score = $forest->score_sample_tagged({ cpu => 0.9, mem => 0.4 });
3992  
3993 Croaks if the model has no stored feature names, if the hashref contains a
3994 key that is not a known feature name, or if a feature name is absent from the
3995 hashref.
3996  
3997 =cut
3998  
3999 22 ▶sub score_sample_tagged {
Subroutine score_sample_tagged: called CC=1 SCAR=0.0
Pod documented
4000 22 my ( $self, $row ) = @_;
4001 22 my $vec = $self->tagged_row_to_array( $row, 'score_sample_tagged' );
4002 16 my $result = $self->score_samples( [$vec] );
4003 16 return $result->[0];
4004 }
4005  
4006 =head2 explain_samples(\@data, %opts)
4007  
4008 Explains, per sample, which features drove its anomaly score -- the
4009 "why" to go with C<score_samples>' "how much". Returns an arrayref
4010 with one hashref per sample:
4011  
4012 my $explanations = $forest->explain_samples(\@data);
4013  
4014 for my $e (@$explanations) {
4015 my $top = $e->{features}[0];
4016 printf "score %.3f, mostly because of feature %s (weight %.2f)\n",
4017 $e->{score}, $top->{name} // $top->{index}, $top->{weight};
4018 }
4019  
4020 Each hashref is
4021  
4022 {
4023 score => 0.91, # same value score_samples returns
4024 method => 'ablation', # which attribution method produced this
4025 features => [ # every feature, most responsible first
4026 { index => 1, name => 'bytes_log', weight => 0.62, value => 9.3,
4027 delta => 0.31, baseline => 4.1 },
4028 { index => 0, name => 'method', weight => 0.21, value => 2.0,
4029 delta => 0.10, baseline => 1.0 },
4030 ...
4031 ],
4032 }
4033  
4034 C<name> is taken from the model's stored C<feature_names> and is undef
4035 when none were recorded. C<weight> is each feature's normalised share
4036 of the responsibility, in [0, 1] and summing to 1 (all weights are 0
4037 in the degenerate case where no attribution information exists).
4038 C<value> is the feature value the model actually scored.
4039  
4040 Options:
4041  
4042 - method :: how per-feature responsibility is computed
4043 ablation :: (default) counterfactual substitution. Each
4044 feature in turn is replaced by its baseline (the
4045 per-feature training-data median learned at fit time) and
4046 the sample is re-scored; the drop in anomaly score is that
4047 feature's C<delta>, and weights are the positive deltas
4048 normalised. Features whose substitution does not
4049 de-anomalise the sample get 0. Each feature entry
4050 additionally carries C<delta> (may be negative:
4051 substituting a correlated feature can make the sample MORE
4052 anomalous) and C<baseline> (the value swapped in). Costs
4053 n_samples * (n_features + 1) rows through the ordinary
4054 scorer -- C-accelerated when available.
4055 path :: split attribution (local DIFFI; Carletti, Terzi &
4056 Susto -- see REFERENCES). The sample walks every tree;
4057 each split node crossed credits its feature(s) with
4058 1/h_t - 1/h_max, where h_t is that tree's path length for
4059 the sample and h_max the longest across the forest -- so
4060 the trees that isolated the sample quickly speak loudest
4061 and trees that treated it as normal say nothing. An
4062 oblique (extended-mode) split spreads its credit across
4063 its features in proportion to |coefficient * value|.
4064 Needs nothing stored beyond the trees (so it works on
4065 models saved before baseline support) and runs pure Perl
4066 over the tree walks.
4067  
4068 Why ablation is the default: it directly answers "would this sample
4069 still be an outlier with feature j at a normal value?", and that
4070 question has an answer for ANY scored sample. C<path> can only
4071 apportion the splits the forest actually built, so it attributes well
4072 for samples that were IN the training data (post-fit forensics of
4073 flagged training rows) but degrades for unseen samples in the tails --
4074 an out-of-range sample walks through boundary regions whose splits
4075 mostly test OTHER features, and the attribution dilutes or even
4076 misleads. Prefer C<ablation> whenever the model has baselines;
4077 C<path> is the fallback for old saved models and a second opinion on
4078 training-set outliers. Neither method untangles strongly correlated
4079 features -- a sample anomalous only in the JOINT distribution of two
4080 features may show weak attributions on both.
4081  
4082 Under C<< voting => 'majority' >> the score (and ablation's deltas) are
4083 in vote-fraction space, matching C<score_samples>' semantics in that
4084 mode; the C<path> method is aggregation-independent and unchanged.
4085  
4086 C<ablation> requires stored baselines: models fitted before explanation
4087 support have none and croak (models with C<< missing => 'impute' >>
4088 fall back to their stored fill vector); refitting stores them.
4089  
4090 =cut
4091  
4092 40 ▶sub explain_samples {
Subroutine explain_samples: called CC=6 SCAR=17.9
Pod documented
4093 40 my ( $self, $data, %opts ) = @_;
4094 40 $self->_check_fitted;
4095  
4096 40 ▶ my $method = delete $opts{method} // 'ablation';
Condition100%2/2
delete $opts{"method"} // "ablation"
l!l
355
MC/DC100%1/1
delete $opts{"method"} // "ablation"
delete $opts{"method"}
Truth table100%2/2
A
A= delete $opts{"method"}
Aresult
11
00
4097 40 ▶ croak "explain_samples: method must be 'path' or 'ablation'"
Branch: 1 branch
BranchTrueFalseTotal
unless $method =~ /\A(?:path|ablation)\z/ 2 38 40
4098 unless $method =~ /\A(?:path|ablation)\z/;
4099 38 ▶ croak "explain_samples: unknown option(s): " . join( ', ', sort keys %opts )
Branch: 1 branch
BranchTrueFalseTotal
if %opts 2 36 38
4100 if %opts;
4101  
4102 36 my $rows = $self->_to_arrayref($data);
4103 36 ▶ croak "explain_samples() expects a non-empty arrayref of samples"
Branch: 1 branch
BranchTrueFalseTotal
unless @$rows 0 36 36
4104 unless @$rows;
4105  
4106 36 ▶ return $method eq 'ablation'
Branch: 1 branch
BranchTrueFalseTotal
$method eq 'ablation' ? : 23 13 36
4107 ? $self->_explain_ablation($rows)
4108 : $self->_explain_path($rows);
4109 } ## end sub explain_samples
4110  
4111 =head2 explain_sample_tagged(\%row, %opts)
4112  
4113 Explains a single sample supplied as a hashref of named feature values
4114 -- the tagged counterpart of
4115 L<explain_samples|/explain_samples(\@data, %opts)>, taking the same
4116 C<method> option and returning the single explanation hashref (with
4117 C<name> filled from the stored feature names).
4118  
4119 my $e = $forest->explain_sample_tagged({ cpu => 0.9, mem => 0.4 });
4120 print "worst feature: $e->{features}[0]{name}\n";
4121  
4122 Croaks under the same conditions as L<tagged_row_to_array|/tagged_row_to_array(\%row, $caller)>.
4123  
4124 =cut
4125  
4126 2 ▶sub explain_sample_tagged {
Subroutine explain_sample_tagged: called CC=1 SCAR=0.0
Pod documented
4127 2 my ( $self, $row, %opts ) = @_;
4128 2 my $vec = $self->tagged_row_to_array( $row, 'explain_sample_tagged' );
4129 2 return $self->explain_samples( [$vec], %opts )->[0];
4130 }
4131  
4132 =head2 score_predict_samples
4133  
4134 Returns an array ref of arrays. First value of each sub array is the score with the second being
4135 0/1 for if it is a anomaly or not.
4136  
4137 C<$threshold> defaults the same way as in C<predict>.
4138  
4139 Under C<< voting => 'majority' >> the score is the anomaly vote fraction at
4140 C<$threshold> (used as the per-tree cutoff) and the label is the majority
4141 vote, matching C<score_samples>/C<predict> semantics in that mode.
4142  
4143 my $results = $forest->score_predict_samples(\@data, $threshold);
4144  
4145 print "x, y, score, result\n";
4146  
4147 my $int=0;
4148 while (defined($data[$int])) {
4149 print $data[$int][0].', '.$data[$int][1].', '.$results->[$int][0].', '.$results->[$int][1]."\n";
4150  
4151 $int++;
4152 }
4153  
4154 =cut
4155  
4156 1173 ▶sub score_predict_samples {
Subroutine score_predict_samples: called CC=15 SCAR=28.7
Pod documented
4157 1173 my ( $self, $data, $threshold ) = @_;
4158 $threshold
4159 = defined $threshold ? $threshold
4160 : defined $self->{threshold} ? $self->{threshold}
4161 1173 ▶ : 0.5;
Branch: 2 branches
BranchTrueFalseTotal
defined $threshold ? : 1153 20 1173
defined $self->{'threshold'} ? : 2 18 20
4162 1173 $self->_check_fitted;
4163  
4164 # Majority voting: [vote_fraction, majority_label] pairs. Needs the
4165 # full vote counts (the fraction is part of the return shape), so no
4166 # early exit here -- that saving is predict()-only.
4167 1173 ▶ if ( $self->{voting} eq 'majority' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"voting"} eq "majority") 3 1170 1173
4168 3 my $trees = $self->{trees};
4169 3 my $t = scalar @$trees;
4170 3 my $cut = _depth_cut( $threshold, $self->{c_psi} );
4171 3 my $maj = _min_votes($t);
4172  
4173 3 ▶ if ( $self->{_use_c} && $self->{_c_nodes} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_use_c"} and $self->{"_c_nodes"}) 3 0 3
Condition33%1/3
$self->{"_use_c"} and $self->{"_c_nodes"}
!ll&&!rl&&r
003
MC/DC0%0/2
$self->{"_use_c"} and $self->{"_c_nodes"}
$self->{"_use_c"} $self->{"_c_nodes"}
Truth table33%1/3
A and B
A= $self->{"_use_c"}B= $self->{"_c_nodes"}
ABresult
0X0
100
111
4174 3 my ( $n_pts, $nf, $x_packed ) = $self->_resolve_input($data);
4175 3 my $votes_packed = "\0" x ( $n_pts * 8 );
4176 vote_all_xs( $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
4177 3 $x_packed, $votes_packed, $n_pts, $nf, $t, $cut, 0, $self->{_use_openmp} );
4178 3 my $result = [];
4179 3 vote_score_predict_xs( $votes_packed, $n_pts, $t + 0.0, $maj + 0.0, $result );
4180 3 return $result;
4181 }
4182  
4183 0 my $votes = $self->_vote_counts_perl( $self->_prepare_perl_input($data), $cut );
4184 0 ▶ return [ map { [ $_ / $t, ( $_ >= $maj ? 1 : 0 ) ] } @$votes ] if _NV_IS_DOUBLE;
Branch: 1 branch
BranchTrueFalseTotal
$_ >= $maj ? : 0 0 0
4185  
4186 # Wide-NV perls: match vote_score_predict_xs's double division --
4187 # see _NV_IS_DOUBLE.
4188 0 ▶ return [ map { [ _to_double( $_ / $t ), ( $_ >= $maj ? 1 : 0 ) ] } @$votes ];
Branch: 1 branch
BranchTrueFalseTotal
$_ >= $maj ? : 0 0 0
4189 } ## end if ( $self->{voting} eq 'majority' )
4190  
4191 # Fast path: build [score, label] pairs straight from the sum buffer
4192 # in one C call. Avoids the intermediate scores arrayref + Perl
4193 # foreach that allocates ~3*n_pts SVs. Gated identically to predict()
4194 # so the threshold conversion is valid.
4195 1170 ▶ if ( $self->{_use_c}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0 and $threshold > 0 and $threshold < 1) 1168 2 1170
Condition66%8/12
$self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0 and $threshold > 0 and $threshold < 1
!ll&&!rl&&r
201168
$self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0 and $threshold > 0
!ll&&!rl&&r
201168
$self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0
!ll&&!rl&&r
201168
$self->{"_use_c"} and $self->{"_c_nodes"}
!ll&&!rl&&r
201168
MC/DC20%1/5
$self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0 and $threshold > 0 and $threshold < 1
$self->{"_use_c"} $self->{"_c_nodes"} $self->{"c_psi"} > 0 $threshold > 0 $threshold < 1
Truth table33%2/6
A and B and C and D and E
A= $self->{"_use_c"}B= $self->{"_c_nodes"}C= $self->{"c_psi"} > 0D= $threshold > 0E= $threshold < 1
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
4196 && $self->{_c_nodes}
4197 && $self->{c_psi} > 0
4198 && $threshold > 0
4199 && $threshold < 1 )
4200 {
4201 1168 my $trees = $self->{trees};
4202 1168 my $t = scalar @$trees;
4203 1168 my $c = $self->{c_psi};
4204 1168 my ( $n_pts, $nf, $x_packed ) = $self->_resolve_input($data);
4205 1168 my $sums_packed = "\0" x ( $n_pts * 8 );
4206 score_all_xs(
4207 $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
4208 $x_packed, $sums_packed, $n_pts,
4209 $nf, $t, $self->{_use_openmp}
4210 1168 );
4211 1168 my $inv = log(2) / ( $c * $t );
4212 1168 my $sum_threshold = -log($threshold) * $c * $t / log(2);
4213 1168 my $result = [];
4214 1168 score_predict_xs( $sums_packed, $n_pts, $inv, $sum_threshold, $result );
4215 1168 return $result;
4216 } ## end if ( $self->{_use_c} && $self->{_c_nodes} ...)
4217  
4218 # Fallback: edge thresholds, c==0, or no C backend.
4219 2 my $scores = $self->score_samples( $self->_to_arrayref($data) );
4220  
4221 2 my @to_return;
4222 2 foreach my $score ( @{$scores} ) {
4223 12 ▶ if ( $score >= $threshold ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($score >= $threshold) { } 4 8 12
4224 4 push @to_return, [ $score, 1 ];
4225 } else {
4226 8 push @to_return, [ $score, 0 ];
4227 }
4228 }
4229  
4230 2 return \@to_return;
4231 } ## end sub score_predict_samples
4232  
4233 =head2 score_predict_sample_tagged(\%row, $threshold)
4234  
4235 Scores and classifies a single sample supplied as a hashref of named
4236 feature values. The model must have stored feature names.
4237  
4238 C<$threshold> defaults the same way as in C<predict>.
4239  
4240 Returns a two-element arrayref C<[$score, $label]>, matching the per-row
4241 shape that C<score_predict_samples> returns for each row.
4242  
4243 my $pair = $forest->score_predict_sample_tagged({ cpu => 0.9, mem => 0.4 });
4244 printf "score %.4f anomaly %d\n", $pair->[0], $pair->[1];
4245  
4246 Croaks if the model has no stored feature names, if the hashref contains a
4247 key that is not a known feature name, or if a feature name is absent from the
4248 hashref.
4249  
4250 =cut
4251  
4252 21 ▶sub score_predict_sample_tagged {
Subroutine score_predict_sample_tagged: called CC=1 SCAR=0.0
Pod documented
4253 21 my ( $self, $row, $threshold ) = @_;
4254 21 my $vec = $self->tagged_row_to_array( $row, 'score_predict_sample_tagged' );
4255 17 my $result = $self->score_predict_samples( [$vec], $threshold );
4256 17 return $result->[0];
4257 }
4258  
4259 =head2 score_predict_split(\@data, $threshold)
4260  
4261 Same data as L</score_predict_samples> but returned as two flat arrayrefs
4262 instead of an arrayref-of-pairs. Allocates roughly half as many Perl
4263 SVs per point (no inner AV, no RV per row), so it is meaningfully faster
4264 when both scores and labels are wanted but the paired shape is not.
4265  
4266 In list context returns C<($scores_aref, $labels_aref)>.
4267  
4268 my ($scores, $labels) = $forest->score_predict_split(\@data);
4269  
4270 for my $i (0 .. $#$scores) {
4271 printf "%s -> score %.4f, label %d\n",
4272 join(',', @{ $data[$i] }), $scores->[$i], $labels->[$i];
4273 }
4274  
4275 C<$threshold> defaults to the contamination-learned cutoff (if C<fit>
4276 was called with C<contamination>) or 0.5.
4277  
4278 =cut
4279  
4280 4363 ▶sub score_predict_split {
Subroutine score_predict_split: called CC=13 SCAR=25.7
Pod documented
4281 4363 my ( $self, $data, $threshold ) = @_;
4282 $threshold
4283 = defined $threshold ? $threshold
4284 : defined $self->{threshold} ? $self->{threshold}
4285 4363 ▶ : 0.5;
Branch: 2 branches
BranchTrueFalseTotal
defined $threshold ? : 4353 10 4363
defined $self->{'threshold'} ? : 0 10 10
4286 4363 $self->_check_fitted;
4287  
4288 # Majority voting: same values as the majority branch in
4289 # score_predict_samples, returned as two flat arrayrefs.
4290 4363 ▶ if ( $self->{voting} eq 'majority' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"voting"} eq "majority") 6 4357 4363
4291 6 my $trees = $self->{trees};
4292 6 my $t = scalar @$trees;
4293 6 my $cut = _depth_cut( $threshold, $self->{c_psi} );
4294 6 my $maj = _min_votes($t);
4295  
4296 6 ▶ if ( $self->{_use_c} && $self->{_c_nodes} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_use_c"} and $self->{"_c_nodes"}) 4 2 6
Condition66%2/3
$self->{"_use_c"} and $self->{"_c_nodes"}
!ll&&!rl&&r
204
MC/DC50%1/2
$self->{"_use_c"} and $self->{"_c_nodes"}
$self->{"_use_c"} $self->{"_c_nodes"}
Truth table66%2/3
A and B
A= $self->{"_use_c"}B= $self->{"_c_nodes"}
ABresult
0X0
100
111
4297 4 my ( $n_pts, $nf, $x_packed ) = $self->_resolve_input($data);
4298 4 my $votes_packed = "\0" x ( $n_pts * 8 );
4299 vote_all_xs( $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
4300 4 $x_packed, $votes_packed, $n_pts, $nf, $t, $cut, 0, $self->{_use_openmp} );
4301 4 my $scores = [];
4302 4 my $labels = [];
4303 4 vote_score_predict_split_xs( $votes_packed, $n_pts, $t + 0.0, $maj + 0.0, $scores, $labels );
4304 4 return ( $scores, $labels );
4305 } ## end if ( $self->{_use_c} && $self->{_c_nodes} )
4306  
4307 2 my $votes = $self->_vote_counts_perl( $self->_prepare_perl_input($data), $cut );
4308 my @scores = _NV_IS_DOUBLE
4309 126 ? map { $_ / $t }
4310 @$votes
4311 # Wide-NV perls: match vote_score_predict_split_xs's double
4312 # division -- see _NV_IS_DOUBLE.
4313 2 : map { _to_double( $_ / $t ) } @$votes;
4314 2 ▶ my @labels = map { $_ >= $maj ? 1 : 0 } @$votes;
Branch: 1 branch
BranchTrueFalseTotal
$_ >= $maj ? : 9 117 126
4315 2 return ( \@scores, \@labels );
4316 } ## end if ( $self->{voting} eq 'majority' )
4317  
4318 # Fast path: fill two flat arrayrefs (scores + labels) directly from
4319 # the sum buffer in one C call. Skips the inner AV + RV per point
4320 # that score_predict_samples has to allocate.
4321 4357 ▶ if ( $self->{_use_c}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0 and $threshold > 0 and $threshold < 1) 4355 2 4357
Condition66%8/12
$self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0 and $threshold > 0 and $threshold < 1
!ll&&!rl&&r
204355
$self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0 and $threshold > 0
!ll&&!rl&&r
204355
$self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0
!ll&&!rl&&r
204355
$self->{"_use_c"} and $self->{"_c_nodes"}
!ll&&!rl&&r
204355
MC/DC20%1/5
$self->{"_use_c"} and $self->{"_c_nodes"} and $self->{"c_psi"} > 0 and $threshold > 0 and $threshold < 1
$self->{"_use_c"} $self->{"_c_nodes"} $self->{"c_psi"} > 0 $threshold > 0 $threshold < 1
Truth table33%2/6
A and B and C and D and E
A= $self->{"_use_c"}B= $self->{"_c_nodes"}C= $self->{"c_psi"} > 0D= $threshold > 0E= $threshold < 1
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
4322 && $self->{_c_nodes}
4323 && $self->{c_psi} > 0
4324 && $threshold > 0
4325 && $threshold < 1 )
4326 {
4327 4355 my $trees = $self->{trees};
4328 4355 my $t = scalar @$trees;
4329 4355 my $c = $self->{c_psi};
4330 4355 my ( $n_pts, $nf, $x_packed ) = $self->_resolve_input($data);
4331 4355 my $sums_packed = "\0" x ( $n_pts * 8 );
4332 score_all_xs(
4333 $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
4334 $x_packed, $sums_packed, $n_pts,
4335 $nf, $t, $self->{_use_openmp}
4336 4355 );
4337 4355 my $inv = log(2) / ( $c * $t );
4338 4355 my $sum_threshold = -log($threshold) * $c * $t / log(2);
4339 4355 my $scores = [];
4340 4355 my $labels = [];
4341 4355 score_predict_split_xs( $sums_packed, $n_pts, $inv, $sum_threshold, $scores, $labels );
4342 4355 return ( $scores, $labels );
4343 } ## end if ( $self->{_use_c} && $self->{_c_nodes} ...)
4344  
4345 # Fallback: derive from score_samples.
4346 2 my $scores = $self->score_samples( $self->_to_arrayref($data) );
4347 2 ▶ my @labels = map { $_ >= $threshold ? 1 : 0 } @$scores;
Branch: 1 branch
BranchTrueFalseTotal
$_ >= $threshold ? : 4 8 12
4348 2 return ( $scores, \@labels );
4349 } ## end sub score_predict_split
4350  
4351 =head1 MUNGERS
4352  
4353 With the optional L<Algorithm::ToNumberMunger> module, a model can carry
4354 a declarative munger spec (see C<mungers> under L</new(%args)>) that
4355 turns raw tagged values -- strings, timestamps, status codes, IPs --
4356 into the numbers the forest needs, so callers hand the model the data
4357 they actually have:
4358  
4359 my $forest = Algorithm::Classifier::IsolationForest->new(
4360 feature_names => [ 'method', 'bytes_log', 'host_entropy' ],
4361 mungers => {
4362 method => { munger => 'http_method_enum', default => -1 },
4363 bytes_log => { munger => 'log', offset => 1, from => 'bytes' },
4364 host_entropy => { munger => 'entropy', from => 'host' },
4365 },
4366 );
4367 $forest->fit_tagged(\@raw_rows);
4368 my $score = $forest->score_sample_tagged(
4369 { method => 'POST', bytes => 51234, host => 'kq3xv9z2.example' } );
4370  
4371 The spec is pure data and is B<saved with the model>, so a loaded model
4372 munges scoring input exactly as it did training input -- the
4373 consistency that makes munging part of the model rather than an
4374 upstream preprocessing step. Points worth knowing:
4375  
4376 =over 4
4377  
4378 =item * Only tagged input is munged. Positional rows passed to C<fit>
4379 or the scoring methods are taken as already numeric; L<munge_rows|/munge_rows(\@rows)>
4380 applies the scalar mungers to positional rows for callers (like the
4381 CLI) that want the same transformation there. Packed datasets
4382 (L</pack_data(\@data)>) are never munged.
4383  
4384 =item * Under a munger plan, tagged-row validation is the plan's: a
4385 missing input field croaks (including munger C<from> sources, which
4386 need not be tags), while unknown extra keys are ignored rather than
4387 rejected.
4388  
4389 =item * Loading a model that carries mungers does not require
4390 Algorithm::ToNumberMunger -- inspection and positional scoring work
4391 without it; the first tagged call croaks with an install hint. A
4392 munger name unknown to an older installed Algorithm::ToNumberMunger
4393 croaks naming it; the model records C<munger_module_version> (the
4394 version that authored the spec) to make that diagnosable.
4395  
4396 =item * Munging happens before the C<missing> strategy: for munged
4397 columns the strategy sees the munger's output, and most mungers define
4398 their own undef handling (C<length> counts undef as 0, C<enum> takes a
4399 C<default>, ...). Raw columns behave exactly as without mungers.
4400  
4401 =item * Caveats inherited from the munger set: the C<eps> munger talks
4402 to an external service, so a saved model using it needs that service
4403 reachable wherever the model runs; C<frozen_freq_map>/C<ngram> count
4404 tables are part of the spec and therefore of the model file.
4405  
4406 =back
4407  
4408 The munger spec composes with everything else -- modes, voting,
4409 contamination, the C backend (munging is input-side; accelerated paths
4410 are unchanged) -- and works identically on
4411 L<Algorithm::Classifier::IsolationForest::Online>.
4412  
4413 =head1 MODEL SAVE/LOAD METHODS
4414  
4415 =head2 to_json
4416  
4417 Returns a JSON representation of the model.
4418  
4419 Requires fit to have been called.
4420  
4421 my $json = $iforest->to_json;
4422  
4423 =cut
4424  
4425 53 ▶sub to_json {
Subroutine to_json: called CC=1 SCAR=0.0
Pod documented
4426 53 my ($self) = @_;
4427 53 $self->_check_fitted;
4428 my $payload = {
4429 format => 'Algorithm::Classifier::IsolationForest',
4430 version => 1,
4431 params => {
4432 n_trees => $self->{n_trees},
4433 sample_size => $self->{sample_size},
4434 mode => $self->{mode},
4435 extension_level => $self->{extension_level_used},
4436 contamination => $self->{contamination},
4437 threshold => $self->{threshold},
4438 n_features => $self->{n_features},
4439 psi_used => $self->{psi_used},
4440 c_psi => $self->{c_psi},
4441 max_depth_used => $self->{max_depth_used},
4442 missing => $self->{missing},
4443 impute_with => $self->{impute_with},
4444 missing_fill => $self->{missing_fill},
4445 feature_baselines => $self->{feature_baselines},
4446 feature_names => $self->{feature_names},
4447 voting => $self->{voting},
4448 mungers => $self->{mungers},
4449 munger_module_version => $self->{munger_module_version},
4450 schema_version => $self->{schema_version},
4451 schema_description => $self->{schema_description},
4452 feature_descriptions => $self->{feature_descriptions},
4453 },
4454 trees => $self->{trees},
4455 51 };
4456 51 return JSON::PP->new->canonical(1)->encode($payload);
4457 } ## end sub to_json
4458  
4459 =head2 from_json($json)
4460  
4461 Init the object from the model in the specified JSON string.
4462  
4463 my $iforest = Algorithm::Classifier::IsolationForest->from_json($json);
4464  
4465 =cut
4466  
4467 59 ▶sub from_json {
Subroutine from_json: called CC=16 SCAR=27.9
Pod documented
4468 59 my ( $class, $text ) = @_;
4469 59 my $payload = JSON::PP->new->decode($text);
4470 croak "not an IsolationForest model"
4471 unless ref $payload eq 'HASH'
4472 59 ▶ && defined $payload->{format};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $payload eq "HASH" and defined $payload->{"format"} 2 57 59
Condition100%3/3
ref $payload eq "HASH" and defined $payload->{"format"}
!ll&&!rl&&r
1157
MC/DC100%2/2
ref $payload eq "HASH" and defined $payload->{"format"}
ref $payload eq "HASH" defined $payload->{"format"}
Truth table100%3/3
A and B
A= ref $payload eq "HASH"B= defined $payload->{"format"}
ABresult
0X0
100
111
4473  
4474 # Online models carry their own format tag; hand them to the class
4475 # that knows their shape so callers can load either model type
4476 # through this one entry point.
4477 57 ▶ if ( $payload->{format} eq 'Algorithm::Classifier::IsolationForest::Online' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($payload->{"format"} eq "Algorithm::Classifier::IsolationForest::Online") 14 43 57
4478 14 require Algorithm::Classifier::IsolationForest::Online;
4479 14 return Algorithm::Classifier::IsolationForest::Online->from_json($text);
4480 }
4481  
4482 croak "not an IsolationForest model"
4483 43 ▶ unless $payload->{format} eq 'Algorithm::Classifier::IsolationForest';
Branch: 1 branch
BranchTrueFalseTotal
unless $payload->{"format"} eq "Algorithm::Classifier::IsolationForest" 0 43 43
4484  
4485 43 ▶ my $p = $payload->{params} || {};
Condition100%2/2
$payload->{'params'} || {}
l!l
421
MC/DC100%1/1
$payload->{'params'} || {}
$payload->{'params'}
Truth table100%2/2
A
A= $payload->{'params'}
Aresult
11
00
4486  
4487 # version 0 used hash-based nodes; version 1+ uses array-based nodes.
4488 # Convert old models on load so the rest of the code only sees arrays.
4489 43 ▶ my $trees = $payload->{trees} || [];
Condition50%1/2
$payload->{'trees'} || []
l!l
430
MC/DC0%0/1
$payload->{'trees'} || []
$payload->{'trees'}
Truth table50%1/2
A
A= $payload->{'trees'}
Aresult
11
00
4490 43 ▶ if ( ( $payload->{version} // 0 ) < 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (($payload->{"version"} // 0) < 1) 1 42 43
Condition100%2/2
$payload->{"version"} // 0
l!l
421
MC/DC100%1/1
$payload->{"version"} // 0
$payload->{"version"}
Truth table100%2/2
A
A= $payload->{"version"}
Aresult
11
00
4491 0 $trees = [ map { _hash_node_to_array($_) } @$trees ];
4492 }
4493  
4494 my $self = {
4495 n_trees => $p->{n_trees},
4496 sample_size => $p->{sample_size},
4497 max_depth => undef,
4498 seed => undef,
4499 mode => $p->{mode} // 'axis',
4500 extension_level => $p->{extension_level},
4501 extension_level_used => $p->{extension_level},
4502 contamination => $p->{contamination},
4503 threshold => $p->{threshold},
4504 n_features => $p->{n_features},
4505 psi_used => $p->{psi_used},
4506 c_psi => $p->{c_psi},
4507 max_depth_used => $p->{max_depth_used},
4508 # Models saved before missing-value support lack these keys; default
4509 # to 'zero', which reproduces the old undef -> 0 scoring behaviour.
4510 missing => $p->{missing} // 'zero',
4511 impute_with => $p->{impute_with} // 'mean',
4512 missing_fill => $p->{missing_fill},
4513 # Absent in models saved before explanation support; ablation
4514 # explanations then fall back to missing_fill or croak with a
4515 # refit hint -- see _ablation_baselines.
4516 feature_baselines => $p->{feature_baselines},
4517 feature_names => $p->{feature_names},
4518 # The munger plan is recompiled lazily on first tagged use, so a
4519 # munger-bearing model still loads (and scores positional data)
4520 # where Algorithm::ToNumberMunger is not installed.
4521 mungers => $p->{mungers},
4522 munger_module_version => $p->{munger_module_version},
4523 # Opaque schema metadata; absent in models saved before prototype
4524 # support, which just means "none recorded".
4525 schema_version => $p->{schema_version},
4526 schema_description => $p->{schema_description},
4527 feature_descriptions => $p->{feature_descriptions},
4528 # Models saved before majority-voting support lack the key; 'mean'
4529 # reproduces their behaviour exactly.
4530 43 ▶ voting => $p->{voting} // 'mean',
Condition100%8/8
$p->{"mode"} // "axis"
l!l
421
$p->{"missing"} // "zero"
l!l
403
$p->{"impute_with"} // "mean"
l!l
403
$p->{"voting"} // "mean"
l!l
412
MC/DC100%1/1
$p->{"mode"} // "axis"
$p->{"mode"}
MC/DC100%1/1
$p->{"missing"} // "zero"
$p->{"missing"}
MC/DC100%1/1
$p->{"impute_with"} // "mean"
$p->{"impute_with"}
MC/DC100%1/1
$p->{"voting"} // "mean"
$p->{"voting"}
Truth table100%2/2
A
A= $p->{"mode"}
Aresult
11
00
Truth table100%2/2
A
A= $p->{"missing"}
Aresult
11
00
Truth table100%2/2
A
A= $p->{"impute_with"}
Aresult
11
00
Truth table100%2/2
A
A= $p->{"voting"}
Aresult
11
00
4531 trees => $trees,
4532 _use_c => $HAS_C,
4533 _use_openmp => $HAS_OPENMP,
4534 _use_openmp_fit => 0, # opt-in only; loaded models never re-fit implicitly
4535 };
4536 43 ▶ croak "model contains no trees" unless @{ $self->{trees} };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->{"trees"};} 1 42 43
4537  
4538 # Recompute the normalising constant from the (integer, exact) sub-sample
4539 # size rather than trusting the stored float, so a reloaded model's scores
4540 # are bit-for-bit identical to the original's.
4541 42 ▶ $self->{c_psi} = _c( $self->{psi_used} ) if defined $self->{psi_used};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"psi_used"} 42 0 42
4542  
4543 42 my $model = bless $self, $class;
4544 42 ▶ $model->_rebuild_c_trees() if $self->{_use_c};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_use_c"} 42 0 42
4545 42 return $model;
4546 } ## end sub from_json
4547  
4548 =head2 save($path)
4549  
4550 Saves the model to the specified path.
4551  
4552 $iforest->save($path);
4553  
4554 =cut
4555  
4556 3 ▶sub save {
Subroutine save: called CC=1 SCAR=0.0
Pod documented
4557 3 my ( $self, $path ) = @_;
4558 3 write_file( $path, { 'atomic' => 1 }, $self->to_json );
4559 }
4560  
4561 =head2 load($path)
4562  
4563 Init the object from the model in the specified file.
4564  
4565 my $iforest = Algorithm::Classifier::IsolationForest->load($path);
4566  
4567 =cut
4568  
4569 41 ▶sub load {
Subroutine load: called CC=1 SCAR=0.0
Pod documented
4570 41 my ( $class, $path ) = @_;
4571 41 my $raw_model = read_file($path);
4572 40 return $class->from_json($raw_model);
4573 }
4574  
4575 =head1 PROTOTYPES
4576  
4577 A prototype is a small JSON document that describes what a model should
4578 be before any data exists: the variable schema (feature names in column
4579 order, plus their munger specs, per-feature descriptions, and missing
4580 policy), a user-owned C<schema_version> string, a human-readable
4581 C<schema_description>, and optionally the tuning knobs. Creating a
4582 model from one -- L</new_from_prototype($proto, %overrides)> here, or
4583 C<--prototype> on C<iforest fit> / C<iforest stream> -- stamps the
4584 schema metadata into the model JSON, so every downstream consumer
4585 (C<iforest info>, resumed streams, your own tooling) can tell which
4586 revision of the input schema a model was built against.
4587  
4588 {
4589 "format": "Algorithm::Classifier::IsolationForest::Prototype",
4590 "version": 1,
4591 "class": "online",
4592 "schema_version": "2026.07.08-1",
4593 "schema_description": "HTTP request stream: method enum, path length, host entropy, raw byte count",
4594 "schema": {
4595 "feature_names": ["method", "path_len", "host_entropy", "bytes"],
4596 "feature_descriptions": {
4597 "method": "HTTP request method, mapped via http_method_enum (-1 = unknown)",
4598 "path_len": "character length of the request path",
4599 "host_entropy": "Shannon entropy of the Host header",
4600 "bytes": "raw response byte count, passed through unmunged"
4601 },
4602 "mungers": {
4603 "method": { "munger": "http_method_enum", "default": -1 },
4604 "path_len": { "munger": "length", "from": "path" },
4605 "host_entropy": { "munger": "entropy", "from": "host" }
4606 },
4607 "missing": "zero"
4608 },
4609 "params": {
4610 "n_trees": 150,
4611 "window_size": 4096,
4612 "max_leaf_samples": 32,
4613 "contamination": 0.02
4614 }
4615 }
4616  
4617 The fields, top to bottom...
4618  
4619 - format :: required, always the string
4620 'Algorithm::Classifier::IsolationForest::Prototype'. A prototype
4621 handed to load() (or a model handed to the prototype methods)
4622 dies with a clear message instead of half-working.
4623  
4624 - version :: the prototype format version; this release reads version 1.
4625 default :: 1
4626  
4627 - class :: required, 'batch' (this class) or 'online'
4628 (L<Algorithm::Classifier::IsolationForest::Online>). Prototypes
4629 are self-describing; `iforest fit` refuses an online prototype
4630 and `iforest stream` refuses a batch one. Two model types with
4631 the same variables means two prototype files.
4632  
4633 - schema_version :: required opaque string, never parsed or compared
4634 numerically. User-owned: bump it when the variable schema
4635 changes.
4636  
4637 - schema_description :: required opaque free-text string describing
4638 what this variable schema is, so a model file explains itself
4639 months later.
4640  
4641 - schema :: required object holding the variable schema.
4642 feature_names is required (order = CSV column order); the
4643 optional keys are feature_descriptions ('feature name => free
4644 text', every key must name an entry in feature_names, partial
4645 coverage fine), mungers (see L</MUNGERS>), missing, and -- batch
4646 prototypes only -- impute_with. Unknown keys croak.
4647  
4648 - params :: optional object of tuning knobs, whitelisted per class.
4649 Batch: n_trees, sample_size, max_depth, mode, extension_level,
4650 contamination, voting, seed. Online: n_trees, window_size,
4651 max_leaf_samples, growth, subsample, contamination, seed.
4652 Unknown keys croak -- a typo'd knob silently falling back to its
4653 default is exactly the failure mode a prototype exists to
4654 prevent. Machine-local knobs (use_c, use_openmp, use_openmp_fit,
4655 parallel_fit) are rejected: they describe the box the model runs
4656 on, not the model.
4657  
4658 =cut
4659  
4660 # Per-class whitelists for a prototype's params block (and
4661 # new_from_prototype's %overrides) and its schema block. Machine-local
4662 # knobs are deliberately absent from the params lists.
4663 my %PROTO_PARAM_KEYS = (
4664 1056 batch => { map { $_ => 1 } qw(n_trees sample_size max_depth mode extension_level contamination voting seed) },
4665 132 online => { map { $_ => 1 } qw(n_trees window_size max_leaf_samples growth subsample contamination seed) },
4666 );
4667 my %PROTO_SCHEMA_KEYS = (
4668 660 batch => { map { $_ => 1 } qw(feature_names feature_descriptions mungers missing impute_with) },
4669 132 online => { map { $_ => 1 } qw(feature_names feature_descriptions mungers missing) },
4670 );
4671  
4672 =head2 validate_prototype($proto)
4673  
4674 Structurally validates a prototype -- a hashref or a JSON string -- and
4675 returns the decoded hashref; croaks describing the first problem found.
4676 Validation is structural only (no munger compilation), so it does not
4677 require Algorithm::ToNumberMunger even for a munger-bearing prototype.
4678  
4679 my $proto = Algorithm::Classifier::IsolationForest->validate_prototype($json);
4680  
4681 =cut
4682  
4683 53 ▶sub validate_prototype {
Subroutine validate_prototype: called CC=40 SCAR=37.6
Pod documented
4684 53 my ( $class, $proto ) = @_;
4685  
4686 53 ▶ if ( !ref $proto ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $proto) 16 37 53
4687 16 my $decoded = eval { JSON::PP->new->decode($proto) };
4688 16 ▶ croak "prototype did not parse as JSON: $@" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 15 16
4689 15 $proto = $decoded;
4690 }
4691 52 ▶ croak "not an IsolationForest prototype (expected a JSON object)"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $proto eq "HASH" 1 51 52
4692 unless ref $proto eq 'HASH';
4693 croak "not an IsolationForest prototype (format is not " . "'Algorithm::Classifier::IsolationForest::Prototype')"
4694 unless defined $proto->{format}
4695 && !ref $proto->{format}
4696 51 ▶ && $proto->{format} eq 'Algorithm::Classifier::IsolationForest::Prototype';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $proto->{"format"} and not ref $proto->{"format"} and $proto->{"format"} eq "Algorithm::Classifier::IsolationForest::Prototype" 1 50 51
Condition50%3/6
defined $proto->{"format"} and not ref $proto->{"format"} and $proto->{"format"} eq "Algorithm::Classifier::IsolationForest::Prototype"
!ll&&!rl&&r
0150
defined $proto->{"format"} and not ref $proto->{"format"}
!ll&&!rl&&r
0051
MC/DC33%1/3
defined $proto->{"format"} and not ref $proto->{"format"} and $proto->{"format"} eq "Algorithm::Classifier::IsolationForest::Prototype"
defined $proto->{"format"} not ref $proto->{"format"} $proto->{"format"} eq "Algorithm::Classifier::IsolationForest::Prototype"
Truth table50%2/4
A and not(B) and C
A= defined $proto->{"format"}B= not ref $proto->{"format"}C= $proto->{"format"} eq "Algorithm::Classifier::IsolationForest::Prototype"
ABCresult
0XX0
10X0
1100
1111
4697  
4698 50 ▶ my $version = $proto->{version} // 1;
Condition100%2/2
$proto->{"version"} // 1
l!l
3614
MC/DC100%1/1
$proto->{"version"} // 1
$proto->{"version"}
Truth table100%2/2
A
A= $proto->{"version"}
Aresult
11
00
4699 50 ▶ croak "prototype format version '$version' is newer than this module understands (max 1)"
Branch: 1 branch
BranchTrueFalseTotal
if not ref $version and $version =~ /^\d+$/ and $version > 1 1 49 50
Condition50%3/6
not ref $version and $version =~ /^\d+$/ and $version > 1
!ll&&!rl&&r
0491
not ref $version and $version =~ /^\d+$/
!ll&&!rl&&r
0050
MC/DC33%1/3
not ref $version and $version =~ /^\d+$/ and $version > 1
not ref $version $version =~ /^\d+$/ $version > 1
Truth table50%2/4
not(A) and B and C
A= not ref $versionB= $version =~ /^\d+$/C= $version > 1
ABCresult
0XX0
10X0
1100
1111
4700 if !ref $version && $version =~ /^\d+$/ && $version > 1;
4701  
4702 49 for my $k ( sort keys %$proto ) {
4703 319 ▶ croak "prototype has unknown top-level key '$k'"
Branch: 1 branch
BranchTrueFalseTotal
unless $k =~ /\A(?:format|version|class|schema_version|schema_description|schema|params)\z/ 1 318 319
4704 unless $k =~ /\A(?:format|version|class|schema_version|schema_description|schema|params)\z/;
4705 }
4706  
4707 48 my $which = $proto->{class};
4708 48 ▶ croak "prototype needs a class of 'batch' or 'online'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $which and not ref $which and $which =~ /\A(?:batch|online)\z/ 2 46 48
Condition83%5/6
defined $which and not ref $which and $which =~ /\A(?:batch|online)\z/
!ll&&!rl&&r
1146
defined $which and not ref $which
!ll&&!rl&&r
1047
MC/DC66%2/3
defined $which and not ref $which and $which =~ /\A(?:batch|online)\z/
defined $which not ref $which $which =~ /\A(?:batch|online)\z/
Truth table75%3/4
A and not(B) and C
A= defined $whichB= not ref $whichC= $which =~ /\A(?:batch|online)\z/
ABCresult
0XX0
10X0
1100
1111
4709 unless defined $which && !ref $which && $which =~ /\A(?:batch|online)\z/;
4710  
4711 46 for my $req (qw(schema_version schema_description)) {
4712 croak "prototype needs a non-empty $req string"
4713 89 ▶ unless defined $proto->{$req} && !ref $proto->{$req} && length $proto->{$req};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $proto->{$req} and not ref $proto->{$req} and length $proto->{$req} 4 85 89
Condition83%5/6
defined $proto->{$req} and not ref $proto->{$req} and length $proto->{$req}
!ll&&!rl&&r
3185
defined $proto->{$req} and not ref $proto->{$req}
!ll&&!rl&&r
3086
MC/DC66%2/3
defined $proto->{$req} and not ref $proto->{$req} and length $proto->{$req}
defined $proto->{$req} not ref $proto->{$req} length $proto->{$req}
Truth table75%3/4
A and not(B) and C
A= defined $proto->{$req}B= not ref $proto->{$req}C= length $proto->{$req}
ABCresult
0XX0
10X0
1100
1111
4714 }
4715  
4716 42 my $schema = $proto->{schema};
4717 42 ▶ croak "prototype needs a schema object" unless ref $schema eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $schema eq "HASH" 1 41 42
4718 41 for my $k ( sort keys %$schema ) {
4719 croak "prototype schema has unknown key '$k' for a $which prototype (allowed: "
4720 2 . join( ', ', sort keys %{ $PROTO_SCHEMA_KEYS{$which} } ) . ')'
4721 90 ▶ unless $PROTO_SCHEMA_KEYS{$which}{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless $PROTO_SCHEMA_KEYS{$which}{$k} 2 88 90
4722 }
4723 39 my $tags = $schema->{feature_names};
4724 39 ▶ croak "prototype schema needs a non-empty feature_names array"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tags eq "ARRAY" and @$tags 2 37 39
Condition100%3/3
ref $tags eq "ARRAY" and @$tags
!ll&&!rl&&r
1137
MC/DC100%2/2
ref $tags eq "ARRAY" and @$tags
ref $tags eq "ARRAY" @$tags
Truth table100%3/3
A and B
A= ref $tags eq "ARRAY"B= @$tags
ABresult
0X0
100
111
4725 unless ref $tags eq 'ARRAY' && @$tags;
4726 37 for my $t (@$tags) {
4727 80 ▶ croak "prototype feature_names entries must be non-empty strings"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t and not ref $t and length $t 1 79 80
Condition66%4/6
defined $t and not ref $t and length $t
!ll&&!rl&&r
1079
defined $t and not ref $t
!ll&&!rl&&r
0179
MC/DC33%1/3
defined $t and not ref $t and length $t
defined $t not ref $t length $t
Truth table50%2/4
A and not(B) and C
A= defined $tB= not ref $tC= length $t
ABCresult
0XX0
10X0
1100
1111
4728 unless defined $t && !ref $t && length $t;
4729 }
4730 _validate_feature_descriptions( $tags, $schema->{feature_descriptions} )
4731 36 ▶ if defined $schema->{feature_descriptions};
Branch: 1 branch
BranchTrueFalseTotal
if defined $schema->{"feature_descriptions"} 22 14 36
4732 croak "prototype schema mungers must be an object of 'tag => munger spec'"
4733 35 ▶ if defined $schema->{mungers} && ref $schema->{mungers} ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if defined $schema->{"mungers"} and ref $schema->{"mungers"} ne "HASH" 1 34 35
Condition100%3/3
defined $schema->{"mungers"} and ref $schema->{"mungers"} ne "HASH"
!ll&&!rl&&r
2951
MC/DC100%2/2
defined $schema->{"mungers"} and ref $schema->{"mungers"} ne "HASH"
defined $schema->{"mungers"} ref $schema->{"mungers"} ne "HASH"
Truth table100%3/3
A and B
A= defined $schema->{"mungers"}B= ref $schema->{"mungers"} ne "HASH"
ABresult
0X0
100
111
4734 34 for my $str (qw(missing impute_with)) {
4735 croak "prototype schema $str must be a plain string"
4736 68 ▶ if defined $schema->{$str} && ref $schema->{$str};
Branch: 1 branch
BranchTrueFalseTotal
if defined $schema->{$str} and ref $schema->{$str} 0 68 68
Condition66%2/3
defined $schema->{$str} and ref $schema->{$str}
!ll&&!rl&&r
47210
MC/DC0%0/2
defined $schema->{$str} and ref $schema->{$str}
defined $schema->{$str} ref $schema->{$str}
Truth table66%2/3
A and B
A= defined $schema->{$str}B= ref $schema->{$str}
ABresult
0X0
100
111
4737 }
4738  
4739 34 my $params = $proto->{params};
4740 34 ▶ croak "prototype params must be an object of tuning knobs"
Branch: 1 branch
BranchTrueFalseTotal
if defined $params and ref $params ne "HASH" 1 33 34
Condition66%2/3
defined $params and ref $params ne "HASH"
!ll&&!rl&&r
0331
MC/DC50%1/2
defined $params and ref $params ne "HASH"
defined $params ref $params ne "HASH"
Truth table66%2/3
A and B
A= defined $paramsB= ref $params ne "HASH"
ABresult
0X0
100
111
4741 if defined $params && ref $params ne 'HASH';
4742 33 ▶ for my $k ( sort keys %{ $params || {} } ) {
Condition50%1/2
$params || {}
l!l
330
MC/DC0%0/1
$params || {}
$params
Truth table50%1/2
A
A= $params
Aresult
11
00
4743 croak "prototype params has unknown key '$k' for a $which prototype (allowed: "
4744 3 . join( ', ', sort keys %{ $PROTO_PARAM_KEYS{$which} } )
4745 . '; machine-local knobs like use_c are deliberately not allowed)'
4746 99 ▶ unless $PROTO_PARAM_KEYS{$which}{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless $PROTO_PARAM_KEYS{$which}{$k} 3 96 99
4747 }
4748  
4749 30 return $proto;
4750 } ## end sub validate_prototype
4751  
4752 =head2 new_from_prototype($proto, %overrides)
4753  
4754 Creates a fresh, unfitted model from a prototype (a hashref or a JSON
4755 string) and returns it -- an instance of whichever class the prototype's
4756 C<class> field names, so like C<load()> this is a single entry point for
4757 both model types. Croaks on any validation failure; a munger-bearing
4758 prototype compiles its plan here, so a bogus munger spec dies at
4759 creation (and needs Algorithm::ToNumberMunger installed).
4760  
4761 C<%overrides> merge over the prototype's C<params> block -- per-run
4762 knobs like C<seed> -- and are held to the same per-class whitelist.
4763 Overriding the schema itself (feature_names, feature_descriptions,
4764 mungers, missing, impute_with, schema_version, schema_description)
4765 croaks: the schema is the prototype's, full stop; edit the prototype.
4766  
4767 my $oif = Algorithm::Classifier::IsolationForest->new_from_prototype(
4768 $proto_json,
4769 seed => 42,
4770 );
4771  
4772 =cut
4773  
4774 17 ▶sub new_from_prototype {
Subroutine new_from_prototype: called CC=8 SCAR=20.8
Pod documented
4775 17 my ( $class, $proto, %overrides ) = @_;
4776  
4777 17 $proto = $class->validate_prototype($proto);
4778 17 my $which = $proto->{class};
4779 17 my $schema = $proto->{schema};
4780  
4781 17 for my $k ( sort keys %overrides ) {
4782 15 ▶ croak "new_from_prototype: '$k' is part of the prototype's schema and may not "
Branch: 1 branch
BranchTrueFalseTotal
if $k =~ /\A(?:feature_names|feature_descriptions|mungers|missing|impute_with|schema_version|schema_description)\z/ 1 14 15
4783 . "be overridden; edit the prototype instead"
4784 if $k
4785 =~ /\A(?:feature_names|feature_descriptions|mungers|missing|impute_with|schema_version|schema_description)\z/;
4786 croak "new_from_prototype: unknown override '$k' for a $which prototype (allowed: "
4787 1 . join( ', ', sort keys %{ $PROTO_PARAM_KEYS{$which} } ) . ')'
4788 14 ▶ unless $PROTO_PARAM_KEYS{$which}{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless $PROTO_PARAM_KEYS{$which}{$k} 1 13 14
4789 }
4790  
4791 my %args = (
4792 15 ▶ %{ $proto->{params} || {} },
Condition50%1/2
$proto->{'params'} || {}
l!l
150
MC/DC0%0/1
$proto->{'params'} || {}
$proto->{'params'}
Truth table50%1/2
A
A= $proto->{'params'}
Aresult
11
00
4793 %overrides,
4794 feature_names => $schema->{feature_names},
4795 schema_version => $proto->{schema_version},
4796 schema_description => $proto->{schema_description},
4797 15 );
4798 15 for my $k (qw(feature_descriptions mungers missing impute_with)) {
4799 60 ▶ $args{$k} = $schema->{$k} if defined $schema->{$k};
Branch: 1 branch
BranchTrueFalseTotal
if defined $schema->{$k} 17 43 60
4800 }
4801  
4802 15 ▶ if ( $which eq 'online' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($which eq "online") 7 8 15
4803 7 require Algorithm::Classifier::IsolationForest::Online;
4804 7 return Algorithm::Classifier::IsolationForest::Online->new(%args);
4805 }
4806 8 return Algorithm::Classifier::IsolationForest->new(%args);
4807 } ## end sub new_from_prototype
4808  
4809 =head2 load_prototype($path, %overrides)
4810  
4811 L</new_from_prototype($proto, %overrides)> from a file.
4812  
4813 my $iforest = Algorithm::Classifier::IsolationForest->load_prototype(
4814 'proto.json', seed => 42 );
4815  
4816 =cut
4817  
4818 1 ▶sub load_prototype {
Subroutine load_prototype: called CC=1 SCAR=0.0
Pod documented
4819 1 my ( $class, $path, %overrides ) = @_;
4820 1 my $raw = read_file($path);
4821 1 return $class->new_from_prototype( $raw, %overrides );
4822 }
4823  
4824 =head2 to_prototype
4825  
4826 Returns a prototype JSON string extracted from this model: its variable
4827 schema (feature_names, feature_descriptions, mungers, missing policy)
4828 plus its current tuning knobs. This closes the loop -- extract a
4829 prototype from a good model and periodically create fresh models with an
4830 identical schema, the natural retrain workflow -- and means hand-writing
4831 a prototype is never mandatory.
4832  
4833 Croaks when the model has no C<feature_names>: a prototype's variable
4834 schema needs named variables. A model with no recorded
4835 C<schema_version> / C<schema_description> (fitted before prototype
4836 support, or without the knobs) gets placeholder values, since both are
4837 required in the file -- edit them in and bump from there. C<seed> and
4838 C<max_depth> resolved at fit time are not emitted; pass such per-run
4839 knobs as overrides when creating from the prototype.
4840  
4841 my $proto_json = $iforest->to_prototype;
4842  
4843 =cut
4844  
4845 4 ▶sub to_prototype {
Subroutine to_prototype: called CC=16 SCAR=31.9
Pod documented
4846 4 my ($self) = @_;
4847 croak "to_prototype: this model has no feature_names; a prototype's variable " . "schema needs named features"
4848 4 ▶ unless ref $self->{feature_names} eq 'ARRAY' && @{ $self->{feature_names} };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};} 1 3 4
Condition66%2/3
ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};}
!ll&&!rl&&r
103
MC/DC50%1/2
ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};}
ref $self->{"feature_names"} eq "ARRAY" @{$self->{"feature_names"};}
Truth table66%2/3
A and B
A= ref $self->{"feature_names"} eq "ARRAY"B= @{$self->{"feature_names"};}
ABresult
0X0
100
111
4849  
4850 my $schema = {
4851 feature_names => $self->{feature_names},
4852 missing => $self->{missing},
4853 3 };
4854 $schema->{feature_descriptions} = $self->{feature_descriptions}
4855 3 ▶ if ref $self->{feature_descriptions} eq 'HASH' && %{ $self->{feature_descriptions} };
Branch: 1 branch
BranchTrueFalseTotal
if ref $self->{"feature_descriptions"} eq "HASH" and %{$self->{"feature_descriptions"};} 1 2 3
Condition66%2/3
ref $self->{"feature_descriptions"} eq "HASH" and %{$self->{"feature_descriptions"};}
!ll&&!rl&&r
201
MC/DC50%1/2
ref $self->{"feature_descriptions"} eq "HASH" and %{$self->{"feature_descriptions"};}
ref $self->{"feature_descriptions"} eq "HASH" %{$self->{"feature_descriptions"};}
Truth table66%2/3
A and B
A= ref $self->{"feature_descriptions"} eq "HASH"B= %{$self->{"feature_descriptions"};}
ABresult
0X0
100
111
4856 $schema->{mungers} = $self->{mungers}
4857 0 ▶ if ref $self->{mungers} eq 'HASH' && %{ $self->{mungers} };
Branch: 1 branch
BranchTrueFalseTotal
if ref $self->{"mungers"} eq "HASH" and %{$self->{"mungers"};} 0 3 3
Condition33%1/3
ref $self->{"mungers"} eq "HASH" and %{$self->{"mungers"};}
!ll&&!rl&&r
300
MC/DC0%0/2
ref $self->{"mungers"} eq "HASH" and %{$self->{"mungers"};}
ref $self->{"mungers"} eq "HASH" %{$self->{"mungers"};}
Truth table33%1/3
A and B
A= ref $self->{"mungers"} eq "HASH"B= %{$self->{"mungers"};}
ABresult
0X0
100
111
4858 $schema->{impute_with} = $self->{impute_with}
4859 3 ▶ if defined $self->{missing} && $self->{missing} eq 'impute';
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"missing"} and $self->{"missing"} eq "impute" 0 3 3
Condition33%1/3
defined $self->{"missing"} and $self->{"missing"} eq "impute"
!ll&&!rl&&r
030
MC/DC0%0/2
defined $self->{"missing"} and $self->{"missing"} eq "impute"
defined $self->{"missing"} $self->{"missing"} eq "impute"
Truth table33%1/3
A and B
A= defined $self->{"missing"}B= $self->{"missing"} eq "impute"
ABresult
0X0
100
111
4860  
4861 my $params = {
4862 n_trees => $self->{n_trees},
4863 sample_size => $self->{sample_size},
4864 mode => $self->{mode},
4865 voting => $self->{voting},
4866 3 };
4867 3 ▶ $params->{max_depth} = $self->{max_depth} if defined $self->{max_depth};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"max_depth"} 0 3 3
4868 $params->{extension_level} = $self->{extension_level_used} // $self->{extension_level}
4869 3 ▶ if defined( $self->{extension_level_used} // $self->{extension_level} );
Branch: 1 branch
BranchTrueFalseTotal
if defined($self->{"extension_level_used"} // $self->{"extension_level"}) 0 3 3
Condition16%1/6
$self->{"extension_level_used"} // $self->{"extension_level"}
l!l&&r!l&&!r
003
$self->{"extension_level_used"} // $self->{"extension_level"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"extension_level_used"} // $self->{"extension_level"}
$self->{"extension_level_used"} $self->{"extension_level"}
MC/DC0%0/2
$self->{"extension_level_used"} // $self->{"extension_level"}
$self->{"extension_level_used"} $self->{"extension_level"}
Truth table33%1/3
A // B
A= $self->{"extension_level_used"}B= $self->{"extension_level"}
ABresult
1X1
011
000
Truth table0%0/3
A // B
A= $self->{"extension_level_used"}B= $self->{"extension_level"}
ABresult
1X1
011
000
4870 3 ▶ $params->{contamination} = $self->{contamination} if defined $self->{contamination};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"contamination"} 1 2 3
4871  
4872 return JSON::PP->new->canonical(1)->encode(
4873 {
4874 format => 'Algorithm::Classifier::IsolationForest::Prototype',
4875 version => 1,
4876 class => 'batch',
4877 schema_version => $self->{schema_version} // '0',
4878 schema_description => $self->{schema_description}
4879 3 ▶ // '(none recorded; describe this schema and bump schema_version)',
Condition100%4/4
$self->{"schema_version"} // 0
l!l
21
$self->{"schema_description"} // "(none recorded; describe this schema and bump schema_version)"
l!l
21
MC/DC100%1/1
$self->{"schema_version"} // 0
$self->{"schema_version"}
MC/DC100%1/1
$self->{"schema_description"} // "(none recorded; describe this schema and bump schema_version)"
$self->{"schema_description"}
Truth table100%2/2
A
A= $self->{"schema_version"}
Aresult
11
00
Truth table100%2/2
A
A= $self->{"schema_description"}
Aresult
11
00
4880 schema => $schema,
4881 params => $params,
4882 }
4883 );
4884 } ## end sub to_prototype
4885  
4886 =head1 REFERENCES
4887  
4888 Liu, Fei Tony & Ting, Kai & Zhou, Zhi-Hua. (2008). Isolation Forest. 413 - 422. 10.1109/ICDM.2008.17.
4889  
4890 L<https://www.researchgate.net/publication/224384174_Isolation_Forest>
4891  
4892 L<https://ieeexplore.ieee.org/abstract/document/4781136>
4893  
4894 Sahand Hariri, Matias Carrasco Kind, Robert J. Brunner (2020). Extended Isolation Forest. 1479 - 1489. 10.1109/TKDE.2019.2947676
4895  
4896 L<https://ieeexplore.ieee.org/document/8888179>
4897  
4898 Yousra Chabchoub, Maurras Ulbricht Togbe, Aliou Boly, Raja Chiky (2022). An In-Depth Study and Improvement of Isolation Forest. IEEE Access, vol. 10, 10219 - 10237. 10.1109/ACCESS.2022.3144425 (the Majority Voting Isolation Forest implemented by C<< voting => 'majority' >>)
4899  
4900 L<https://ieeexplore.ieee.org/document/9684896>
4901  
4902 Mattia Carletti, Matteo Terzi, Gian Antonio Susto (2023). Interpretable Anomaly Detection with DIFFI: Depth-based feature importance of Isolation Forest. Engineering Applications of Artificial Intelligence, vol. 119. 10.1016/j.engappai.2022.105730 (the depth-weighted split attribution of C<explain_samples>' C<path> method is inspired by local DIFFI)
4903  
4904 L<https://arxiv.org/abs/2007.11117>
4905  
4906 L<https://www.sciencedirect.com/science/article/pii/S0952197622007205>
4907  
4908 Filippo Leveni, Guilherme Weigert Cassales, Bernhard Pfahringer, Albert Bifet, Giacomo Boracchi (2024). Online Isolation Forest. (the streaming variant implemented by L<Algorithm::Classifier::IsolationForest::Online>)
4909  
4910 L<https://arxiv.org/abs/2505.09593>
4911  
4912 L<https://github.com/ineveLoppiliF/Online-Isolation-Forest>
4913  
4914 L<https://proceedings.mlr.press/v235/leveni24a.html>
4915  
4916 =head1 AUTHOR
4917  
4918 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.net> >>
4919  
4920 =head1 LICENSE AND COPYRIGHT
4921  
4922 Copyright 2026 Zane C. Bowers-Hadley.
4923  
4924 This program is free software; you can redistribute it and/or modify it
4925 under the terms of the GNU Lesser General Public License version 2.1 as
4926 published by the Free Software Foundation.
4927  
4928 This program is distributed in the hope that it will be useful, but
4929 WITHOUT ANY WARRANTY; without even the implied warranty of
4930 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
4931 General Public License for more details.
4932  
4933 =cut
4934  
4935 ###
4936 ###
4937 ### internal stuff below
4938 ###
4939 ###
4940  
4941 #-------------------------------------------------------------------------------
4942 # c(n): the expected path length of an unsuccessful search in a binary search
4943 # tree of n nodes. Isolation Forest uses it (a) to adjust the path length when a
4944 # leaf still holds more than one point (depth limit reached), and (b) to
4945 # normalise the average path length into a 0..1 anomaly score.
4946 #
4947 # Args:
4948 # $n :: a point count, non-negative integer. Either a leaf's size or the
4949 # per-tree sub-sample size psi.
4950 #
4951 # Returns: the expected path length, a float. 0.0 for n <= 1 (nothing is
4952 # left to search) and 1.0 for n == 2, both special-cased because the
4953 # harmonic approximation is only accurate for larger n.
4954 #
4955 # Example:
4956 # _c(1); # 0.0
4957 # _c(256); # ~10.24 -- the normaliser for a default sample_size fit
4958 #-------------------------------------------------------------------------------
4959 1649157 ▶sub _c {
Subroutine _c: called CC=3 SCAR=11.0
4960 1649157 my ($n) = @_;
4961 1649157 ▶ return 0.0 if $n <= 1;
Branch: 1 branch
BranchTrueFalseTotal
if $n <= 1 385274 1263883 1649157
4962 1263883 ▶ return 1.0 if $n == 2;
Branch: 1 branch
BranchTrueFalseTotal
if $n == 2 114715 1149168 1263883
4963 1149168 my $harmonic = log( $n - 1 ) + EULER; # H(n-1) ~= ln(n-1) + gamma
4964 1149168 return 2.0 * $harmonic - ( 2.0 * ( $n - 1 ) / $n );
4965 }
4966  
4967 #-------------------------------------------------------------------------------
4968 # Majority-voting (voting => 'majority') helpers. MVIForest -- Chabchoub,
4969 # Togbe, Boly & Chiky 2022 (see REFERENCES) -- has each tree vote a point
4970 # anomalous when the tree's own score 2**(-h/c(psi)) clears the decision
4971 # threshold, and takes the majority of the votes as the label. Trees are
4972 # untouched; only these scoring-time aggregation helpers differ from the
4973 # classic mean-path-length pipeline.
4974 #-------------------------------------------------------------------------------
4975  
4976 # Depth-domain image of the per-tree score cutoff: a tree votes a point
4977 # anomalous when 2**(-h/c) >= theta, i.e. h <= -c * log2(theta). Doing the
4978 # log once here keeps exp/log out of the per-point per-tree loops (both C
4979 # and Perl compare raw path lengths against this cut). Degenerate inputs
4980 # pin the cut so `h <= cut` still behaves: theta <= 0 is cleared by every
4981 # per-tree score (all in (0, 1]), so +inf lets every tree vote; c <= 0 only
4982 # happens for psi <= 1 forests, whose score convention is a flat 0.5 (see
4983 # score_samples), so all trees vote iff theta is at or below that pivot.
4984 #
4985 # Args:
4986 # $theta :: the per-tree score cutoff, normally in (0, 1]. Degenerate
4987 # values are handled rather than rejected.
4988 # $c :: c(psi) for this forest, i.e. $self->{c_psi}. Only <= 0 for a
4989 # psi <= 1 forest.
4990 #
4991 # Returns: the path length at or below which a tree votes anomalous, a
4992 # float. +inf when every tree should vote, -1.0 when none should.
4993 #
4994 # Example:
4995 # _depth_cut( 0.6, 10.24 ); # ~7.55: isolate in <= 7.55 edges and vote
4996 39 ▶sub _depth_cut {
Subroutine _depth_cut: called CC=4 SCAR=16.1
4997 39 my ( $theta, $c ) = @_;
4998 39 ▶ return ( $theta <= 0.5 ? 9**9**9 : -1.0 ) if $c <= 0;
Branch: 2 branches
BranchTrueFalseTotal
if $c <= 0 0 39 39
$theta <= 0.5 ? : 0 0 0
4999 39 ▶ return 9**9**9 if $theta <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $theta <= 0 0 39 39
5000 39 return -$c * log($theta) / log(2);
5001 }
5002  
5003 # Smallest number of per-tree anomaly votes that constitutes a majority:
5004 # int(t/2) + 1, i.e. strictly more than half the trees for both odd and
5005 # even tree counts (the paper's "t/2 + 1").
5006 #
5007 # Args:
5008 # $n_trees :: the forest's tree count, an integer >= 1.
5009 #
5010 # Returns: the required vote count, an integer in [1, $n_trees].
5011 #
5012 # Example:
5013 # _min_votes(100); # 51
5014 # _min_votes(101); # 51
5015 36 ▶sub _min_votes { return int( $_[0] / 2 ) + 1 }
Subroutine _min_votes: called CC=1 SCAR=0.0
5016  
5017 #-------------------------------------------------------------------------------
5018 # Contamination threshold selection: given the training scores ranked
5019 # descending and the target flag count k, return a cutoff sitting midway
5020 # inside the gap between the last flagged and the first unflagged score.
5021 #
5022 # Tied scores at the k-boundary make an exact count of k unattainable (the
5023 # tie block can only go one way or the other) AND make the naive midpoint
5024 # degenerate -- it equals the tied value, leaving predict()'s >= comparison
5025 # balanced on exact float equality. Mean-mode scores are continuous enough
5026 # that this practically never happens, but majority-mode pivots are
5027 # structurally quantized (path lengths at the depth cap take few distinct
5028 # values -- see _majority_pivot_scores), so ties there are the norm, and
5029 # the score <-> depth-cut conversion adds an exp/log round trip that needs
5030 # real slack around the cutoff rather than exact-equality behaviour. The
5031 # whole tie block therefore goes to whichever side lands the flag count
5032 # closest to k, preferring the flagging side on a dead heat.
5033 #
5034 # Args:
5035 # $desc :: arrayref of the per-point statistic sorted DESCENDING -- the
5036 # mean-mode anomaly scores, or the majority pivots under
5037 # voting => 'majority'. Must be non-empty.
5038 # $k :: how many points the contamination rate wants flagged, an integer
5039 # in [1, scalar @$desc].
5040 #
5041 # Returns: the cutoff, a float positioned so that `statistic >= cutoff`
5042 # selects the intended points. Never equal to a value in $desc.
5043 #
5044 # Example:
5045 # _threshold_from_ranked( [ 0.71, 0.68, 0.52, 0.50 ], 2 ); # 0.60
5046 # _threshold_from_ranked( [ 0.71, 0.68, 0.68, 0.50 ], 2 ); # 0.59, tie
5047 #-------------------------------------------------------------------------------
5048 37 ▶sub _threshold_from_ranked {
Subroutine _threshold_from_ranked: called CC=10 SCAR=23.4
5049 37 my ( $desc, $k ) = @_;
5050 37 my $n = scalar @$desc;
5051 37 ▶ return $desc->[ $n - 1 ] - 1e-9 if $k >= $n; # flag everything
Branch: 1 branch
BranchTrueFalseTotal
if $k >= $n 0 37 37
5052  
5053 37 my $v = $desc->[ $k - 1 ];
5054 37 ▶ return ( $v + $desc->[$k] ) / 2.0 if $desc->[$k] < $v; # clean gap at k
Branch: 1 branch
BranchTrueFalseTotal
if $desc->[$k] < $v 29 8 37
5055  
5056 # Tie block straddling the k-boundary: locate its edges.
5057 8 my $i = $k - 1;
5058 8 ▶ $i-- while $i > 0 && $desc->[ $i - 1 ] == $v; # first index holding $v
Branch: 1 branch
BranchTrueFalseTotal
$i > 0 and $$desc[$i - 1] == $v and do { --$i } 20 8 28
Condition66%2/3
$i > 0 and $$desc[$i - 1] == $v
!ll&&!rl&&r
0820
MC/DC50%1/2
$i > 0 and $$desc[$i - 1] == $v
$i > 0 $$desc[$i - 1] == $v
Truth table66%2/3
A and B
A= $i > 0B= $$desc[$i - 1] == $v
ABresult
0X0
100
111
5059 8 my $j = $k;
5060 8 ▶ $j++ while $j < $n && $desc->[$j] == $v; # first index below $v
Branch: 1 branch
BranchTrueFalseTotal
$j < $n and $desc->[$j] == $v and do { ++$j } 73 8 81
Condition66%2/3
$j < $n and $desc->[$j] == $v
!ll&&!rl&&r
0873
MC/DC50%1/2
$j < $n and $desc->[$j] == $v
$j < $n $desc->[$j] == $v
Truth table66%2/3
A and B
A= $j < $nB= $desc->[$j] == $v
ABresult
0X0
100
111
5061  
5062 8 ▶ if ( $i > 0 && ( $k - $i ) < ( $j - $k ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i > 0 and $k - $i < $j - $k) 4 4 8
Condition66%2/3
$i > 0 and $k - $i < $j - $k
!ll&&!rl&&r
044
MC/DC50%1/2
$i > 0 and $k - $i < $j - $k
$i > 0 $k - $i < $j - $k
Truth table66%2/3
A and B
A= $i > 0B= $k - $i < $j - $k
ABresult
0X0
100
111
5063  
5064 # Excluding the block lands closer to k: flag the $i points above it.
5065 4 return ( $desc->[ $i - 1 ] + $v ) / 2.0;
5066 }
5067 4 ▶ return $j < $n
Branch: 1 branch
BranchTrueFalseTotal
$j < $n ? : 4 0 4
5068 ? ( $v + $desc->[$j] ) / 2.0 # include the block: flag $j
5069 : $desc->[ $n - 1 ] - 1e-9; # block runs to the end
5070 } ## end sub _threshold_from_ranked
5071  
5072 # Pure-Perl vote counter: votes[i] = how many trees give point i a path
5073 # length at or under the depth cut. Tree-outer / sample-inner for cache
5074 # locality, mirroring the mean-mode fallback loops. $data must already
5075 # be through _prepare_perl_input.
5076 #
5077 # Args:
5078 # $data :: arrayref of rows already through _prepare_perl_input -- dense
5079 # under impute, raw undef preserved under nan.
5080 # $cut :: the depth cut from _depth_cut.
5081 #
5082 # Returns: arrayref of per-point vote counts, integers in [0, n_trees],
5083 # positionally matching $data.
5084 #
5085 # Example:
5086 # my $cut = _depth_cut( 0.6, $self->{c_psi} );
5087 # my $votes = $self->_vote_counts_perl( $rows, $cut ); # [ 3, 97, 12, ... ]
5088 4 ▶sub _vote_counts_perl {
Subroutine _vote_counts_perl: called CC=5 SCAR=16.1
5089 4 my ( $self, $data, $cut ) = @_;
5090 4 my $trees = $self->{trees};
5091 4 ▶ my $nan = $self->{missing} eq 'nan' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'missing'} eq 'nan' ? : 0 4 4
5092 4 my @votes = (0) x @$data;
5093 4 for my $tree (@$trees) {
5094 160 for my $i ( 0 .. $#$data ) {
5095 10080 ▶ $votes[$i]++ if _path_length( $data->[$i], $tree, 0, $nan ) <= $cut;
Branch: 1 branch
BranchTrueFalseTotal
if _path_length($data->[$i], $tree, 0, $nan) <= $cut 2854 7226 10080
5096 }
5097 }
5098 4 return \@votes;
5099 } ## end sub _vote_counts_perl
5100  
5101 # Learn the contamination cutoff for the CURRENT voting mode from a training
5102 # set. Ranks the per-point quantity the active aggregation thresholds against
5103 # -- the mean-mode anomaly score, or the majority pivot under
5104 # voting => 'majority' -- and lands the cutoff midway inside a real gap between
5105 # flagged and unflagged values (ties at the k-boundary shift it to the nearest
5106 # gap; see _threshold_from_ranked), so it sits strictly between attainable
5107 # values: unambiguous and robust to the float rounding JSON introduces. A
5108 # point is flagged iff its statistic >= threshold in either mode, so the
5109 # midpoint selection serves both unchanged. Shared by fit() (which passes the
5110 # prepared training set after dropping any stale packed buffers) and
5111 # set_voting() (which passes the caller-supplied training set against the
5112 # live, fully packed forest); $data may hold raw undef cells either way, since
5113 # the scorers below densify from missing_fill.
5114 #
5115 # Args:
5116 # $data :: the training set, an arrayref of feature-value arrayrefs. Raw
5117 # undef cells are fine.
5118 #
5119 # Returns: nothing. Sets $self->{threshold} as its whole purpose.
5120 #
5121 # Example:
5122 # $self->{contamination} = 0.05;
5123 # $self->_learn_contamination_threshold( \@training_rows );
5124 # $self->decision_threshold; # the cutoff flagging ~5% of the training set
5125 31 ▶sub _learn_contamination_threshold {
Subroutine _learn_contamination_threshold: called CC=4 SCAR=13.9
5126 31 my ( $self, $data ) = @_;
5127 my $scores
5128 31 ▶ = $self->{voting} eq 'majority'
Branch: 1 branch
BranchTrueFalseTotal
$self->{'voting'} eq 'majority' ? : 9 22 31
5129 ? $self->_majority_pivot_scores($data)
5130 : $self->score_samples($data);
5131 31 my @desc = sort { $b <=> $a } @$scores;
5132 31 my $n_pts = scalar @desc;
5133 31 my $k = int( $self->{contamination} * $n_pts + 0.5 );
5134 31 ▶ $k = 1 if $k < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $k < 1 0 31 31
5135 31 ▶ $k = $n_pts if $k > $n_pts;
Branch: 1 branch
BranchTrueFalseTotal
if $k > $n_pts 0 31 31
5136 31 $self->{threshold} = _threshold_from_ranked( \@desc, $k );
5137 31 return;
5138 } ## end sub _learn_contamination_threshold
5139  
5140 #-------------------------------------------------------------------------------
5141 # Contamination support for majority voting: each training point's majority
5142 # pivot -- the per-tree score threshold at which the point loses its
5143 # majority. A point is flagged at cutoff theta iff at least min_votes of
5144 # its per-tree path lengths h satisfy h <= -c*log2(theta), which holds iff
5145 # its min_votes-th SMALLEST path length h_(maj) does, i.e. iff
5146 # 2**(-h_(maj)/c) >= theta. So the pivot m = 2**(-h_(maj)/c) relates to
5147 # the majority-mode threshold exactly as the mean-mode score relates to
5148 # its threshold, and fit()'s midpoint selection works on either unchanged.
5149 #
5150 # Pure Perl by necessity: the per-tree path lengths never cross the C
5151 # boundary individually (score_all_xs/vote_all_xs only return per-point
5152 # aggregates), and fit() has already dropped any stale packed buffers when
5153 # this runs -- the same situation as mean mode's training-set scoring pass.
5154 #
5155 # Args:
5156 # $data :: arrayref of feature-value arrayrefs, raw or prepared -- it goes
5157 # through _prepare_perl_input here either way.
5158 #
5159 # Returns: arrayref of per-point pivots, each a float in (0, 1],
5160 # positionally matching $data.
5161 #
5162 # Example:
5163 # my $pivots = $self->_majority_pivot_scores( \@training_rows );
5164 # # row i is flagged at per-tree cutoff theta exactly when
5165 # # $pivots->[$i] >= theta
5166 #-------------------------------------------------------------------------------
5167 9 ▶sub _majority_pivot_scores {
Subroutine _majority_pivot_scores: called CC=4 SCAR=13.9
5168 9 my ( $self, $data ) = @_;
5169 9 my $trees = $self->{trees};
5170 9 my $t = scalar @$trees;
5171 9 my $c = $self->{c_psi};
5172 9 my $maj = _min_votes($t);
5173 9 my $rows = $self->_prepare_perl_input($data);
5174 9 ▶ my $nan = $self->{missing} eq 'nan' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'missing'} eq 'nan' ? : 0 9 9
5175  
5176 # psi <= 1 degenerate forest: every per-tree score is pinned at 0.5
5177 # (matching score_samples' convention), so every pivot is too.
5178 9 ▶ return [ (0.5) x @$rows ] unless $c > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $c > 0 0 9 9
5179  
5180 9 my $inv = log(2) / $c;
5181 9 my @pivots;
5182 9 for my $x (@$rows) {
5183 828 my @paths = sort { $a <=> $b } map { _path_length( $x, $_, 0, $nan ) } @$trees;
5184 828 push @pivots, exp( -$paths[ $maj - 1 ] * $inv );
5185 }
5186 9 return \@pivots;
5187 } ## end sub _majority_pivot_scores
5188  
5189 # One draw from the standard normal N(0,1) via Box-Muller. Used to pick the
5190 # random hyperplane orientations in Extended Isolation Forest mode.
5191 #
5192 # Args: none. Draws two uniforms from Perl's rand(), so the caller controls
5193 # reproducibility through srand().
5194 #
5195 # Returns: one float from N(0,1), typically within +/-4. Consumes exactly
5196 # two rand() draws, which is what keeps the Perl and C builders in step.
5197 #
5198 # Example:
5199 # srand(42);
5200 # my $coef = _randn(); # a hyperplane coefficient for one feature
5201 57313 ▶sub _randn {
Subroutine _randn: called CC=2 SCAR=9.2
5202 57313 ▶ my $u1 = rand() || 1e-12;
Condition50%1/2
rand() || 1e-12
l!l
573130
MC/DC0%0/1
rand() || 1e-12
rand()
Truth table50%1/2
A
A= rand()
Aresult
11
00
5203 57313 my $u2 = rand();
5204 57313 return sqrt( -2.0 * log($u1) ) * cos( TWO_PI * $u2 ) if _NV_IS_DOUBLE;
5205  
5206 # Wide-NV perls: round after every operation _c_randn() performs in
5207 # double, so both backends draw the same coefficient bit patterns
5208 # (up to libm's own double-vs-long-double disagreements on rare
5209 # rounding ties).
5210 0 my $s = _to_double( sqrt( -2.0 * _to_double( log($u1) ) ) );
5211 0 my $c = _to_double( cos( _to_double( TWO_PI * $u2 ) ) );
5212 0 return _to_double( $s * $c );
5213 } ## end sub _randn
5214  
5215 #-------------------------------------------------------------------------------
5216 # Resolve the derived per-fit geometry from the sample count and feature width,
5217 # storing it on the object and returning ($psi, $limit) for the build loop.
5218 # Factored out of fit() so fit_from_csv() -- which learns n from a streaming
5219 # census rather than an in-RAM array -- produces byte-identical psi/extension/
5220 # depth values. Pure arithmetic: consumes no randomness.
5221 #
5222 # Args:
5223 # $n :: total training rows available, a positive integer. From
5224 # scalar @$data in fit(), or the census count in fit_from_csv().
5225 # $n_features :: the feature width, a positive integer.
5226 #
5227 # Returns: the two-element list ($psi, $limit) -- the per-tree sub-sample
5228 # size and the tree height limit. Also sets c_psi, psi_used,
5229 # extension_level_used (undef outside extended mode) and max_depth_used on
5230 # the object.
5231 #
5232 # Example:
5233 # my ( $psi, $limit ) = $self->_resolve_geometry( 10_000, 4 );
5234 # # ( 256, 8 ) at the default sample_size, since ceil(log2(256)) == 8
5235 #-------------------------------------------------------------------------------
5236 264 ▶sub _resolve_geometry {
Subroutine _resolve_geometry: called CC=7 SCAR=19.6
5237 264 my ( $self, $n, $n_features ) = @_;
5238  
5239 # The sub-sample cannot be larger than the data set itself.
5240 264 my $psi = min( $self->{sample_size}, $n );
5241 264 $self->{c_psi} = _c($psi);
5242 264 $self->{psi_used} = $psi;
5243  
5244 # Resolve the extension level against the data's dimensionality.
5245 264 ▶ if ( $self->{mode} eq 'extended' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'mode'} eq 'extended') { } 34 230 264
5246 34 my $max_ext = $n_features - 1;
5247 my $ext
5248 = defined $self->{extension_level}
5249 ? $self->{extension_level}
5250 34 ▶ : $max_ext;
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'extension_level'} ? : 4 30 34
5251 34 ▶ $ext = 0 if $ext < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $ext < 0 0 34 34
5252 34 ▶ $ext = $max_ext if $ext > $max_ext;
Branch: 1 branch
BranchTrueFalseTotal
if $ext > $max_ext 2 32 34
5253 34 $self->{extension_level_used} = $ext;
5254 } else {
5255 230 $self->{extension_level_used} = undef;
5256 }
5257  
5258 # Height limit: the average tree height ceil(log2(psi)). Past this depth the
5259 # remaining points are scored using the c(size) adjustment instead.
5260 my $limit
5261 = defined $self->{max_depth}
5262 ? $self->{max_depth}
5263 264 ▶ : ceil( log($psi) / log(2) );
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'max_depth'} ? : 0 264 264
5264 264 ▶ $limit = 1 if $limit < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $limit < 1 0 264 264
5265 264 $self->{max_depth_used} = $limit;
5266  
5267 264 return ( $psi, $limit );
5268 } ## end sub _resolve_geometry
5269  
5270 #-------------------------------------------------------------------------------
5271 # fit_from_csv() machinery.
5272 #-------------------------------------------------------------------------------
5273  
5274 # Inspect the first non-blank line and report whether it is a header to skip
5275 # rather than train on. $forced (the header => option) makes it unconditional;
5276 # otherwise a line is a header when it carries any non-numeric text -- data rows
5277 # hold only numbers and empty cells -- or exactly matches stored feature_names.
5278 #
5279 # Args:
5280 # $path :: path to the CSV file, which must be readable.
5281 # $forced :: the caller's header => option. True skips detection and
5282 # answers yes; undef or false runs the heuristic.
5283 #
5284 # Returns: 1 when the first non-blank line is a header to skip, 0 otherwise.
5285 # An empty file answers 0 and lets the census report the real problem.
5286 #
5287 # Example:
5288 # $self->_detect_header( 'train.csv', undef ); # 1 for "cpu,mem,disk"
5289 # $self->_detect_header( 'train.csv', undef ); # 0 for "0.9,0.4,0.1"
5290 67 ▶sub _detect_header {
Subroutine _detect_header: called CC=12 SCAR=25.0
5291 67 my ( $self, $path, $forced ) = @_;
5292 67 ▶ open my $fh, '<', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $path or croak("fit_from_csv(): cannot open '${path}': $!") 67 0 67
5293 or croak "fit_from_csv(): cannot open '$path': $!";
5294 67 my $first;
5295 67 ▶ while ( defined( my $line = <$fh> ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 66 1 67
5296 66 $line =~ s/\r?\n\z//;
5297 66 ▶ next if $line =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^\s*$/ 0 66 66
5298 66 $first = $line;
5299 66 last;
5300 }
5301 67 close $fh;
5302 67 ▶ return 0 unless defined $first; # empty file; the census will report it
Branch: 1 branch
BranchTrueFalseTotal
unless defined $first 1 66 67
5303 66 ▶ return 1 if $forced;
Branch: 1 branch
BranchTrueFalseTotal
if $forced 8 58 66
5304  
5305 58 my @f = split /,/, $first, -1;
5306 58 for my $x (@f) {
5307 111 ▶ next if !length $x; # empty cell: fine in data
Branch: 1 branch
BranchTrueFalseTotal
unless length $x 0 111 111
5308 111 ▶ return 1 unless looks_like_number($x); # text: it is a header
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($x) 6 105 111
5309 }
5310  
5311 # All-numeric first line: only a header if it reproduces feature_names.
5312 52 my $names = $self->{feature_names};
5313 52 ▶ if ( ref $names eq 'ARRAY' && @$names == @f ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $names eq "ARRAY" and @$names == @f) 2 50 52
Condition66%2/3
ref $names eq "ARRAY" and @$names == @f
!ll&&!rl&&r
5002
MC/DC50%1/2
ref $names eq "ARRAY" and @$names == @f
ref $names eq "ARRAY" @$names == @f
Truth table66%2/3
A and B
A= ref $names eq "ARRAY"B= @$names == @f
ABresult
0X0
100
111
5314 2 my $match = grep { $f[$_] eq $names->[$_] } 0 .. $#f;
5315 2 ▶ return 1 if $match == @f;
Branch: 1 branch
BranchTrueFalseTotal
if $match == @f 2 0 2
5316 }
5317 50 return 0;
5318 } ## end sub _detect_header
5319  
5320 # Return a closure that yields ($row, $line_number) per non-blank CSV line and
5321 # an empty list at EOF. An empty cell becomes undef (the missing-value marker).
5322 # With $parse true each non-empty cell is validated and coerced to a number (a
5323 # non-numeric cell dies); with $parse false the cells are left as raw strings --
5324 # the cheap mode the census uses, which needs only the column count and empties.
5325 # When $skip_first is set the first non-blank line (a header) is dropped. Blank
5326 # lines are skipped, so a row's index is its position among the non-blank data
5327 # lines -- stable across passes as long as the file does not change under us.
5328 #
5329 # Args:
5330 # $path :: path to the CSV file, which must be readable.
5331 # $skip_first :: true to drop the first non-blank line as a header.
5332 # $parse :: true to validate and numify each non-empty cell (croaking on a
5333 # non-numeric one), false to hand back raw strings.
5334 #
5335 # Returns: a closure. Each call returns the two-element list
5336 # (\@fields, $line_number) for the next data line, or the empty list at EOF
5337 # (where it also closes the handle). @fields holds numbers under
5338 # $parse, strings otherwise, with undef for an empty cell.
5339 #
5340 # Example:
5341 # my $reader = $self->_csv_reader( 'train.csv', 1, 1 );
5342 # while ( my ( $row, $line ) = $reader->() ) {
5343 # # $row = [ 0.9, undef, 0.1 ] for "0.9,,0.1" on line $line
5344 # }
5345 40 ▶sub _csv_reader {
Subroutine _csv_reader: called CC=2 SCAR=7.2
5346 40 my ( $self, $path, $skip_first, $parse ) = @_;
5347 40 ▶ open my $fh, '<', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $path or croak("fit_from_csv(): cannot open '${path}': $!") 40 0 40
5348 or croak "fit_from_csv(): cannot open '$path': $!";
5349 40 my $line_no = 0;
5350 40 my $skipped = 0;
5351 16286 ▶ return sub {
Subroutine __ANON__: called CC=9 SCAR=23.6
5352 16286 ▶ while ( defined( my $line = <$fh> ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 16248 38 16286
5353 16248 $line_no++;
5354 16248 $line =~ s/\r?\n\z//;
5355 16248 ▶ next if $line =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^\s*$/ 0 16248 16248
5356 0 ▶ if ( $skip_first && !$skipped ) { $skipped = 1; next; }
Branch: 1 branch
BranchTrueFalseTotal
if ($skip_first and not $skipped) 0 16248 16248
Condition33%1/3
$skip_first and not $skipped
!ll&&!rl&&r
1624800
MC/DC0%0/2
$skip_first and not $skipped
$skip_first not $skipped
Truth table33%1/3
A and not(B)
A= $skip_firstB= not $skipped
ABresult
0X0
100
111
5357 16248 my @fields = split /,/, $line, -1;
5358 16248 for my $f (@fields) {
5359 0 ▶ if ( !length $f ) { $f = undef; next; }
Branch: 1 branch
BranchTrueFalseTotal
unless (length $f) 0 32494 32494
5360 32494 ▶ next unless $parse;
Branch: 1 branch
BranchTrueFalseTotal
unless $parse 17912 14582 32494
5361 14582 ▶ croak "fit_from_csv(): line $line_no value '$f' is not a number"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($f) 2 14580 14582
5362 unless looks_like_number($f);
5363 14580 $f += 0;
5364 }
5365 16246 return ( \@fields, $line_no );
5366 } ## end while ( defined( my $line = <$fh> ) )
5367 38 close $fh;
5368 38 return;
5369 40 }; ## end sub
5370 } ## end sub _csv_reader
5371  
5372 # Validate and coerce a raw row (from a parse => 0 reader) into numbers in
5373 # place: defined cells must look like numbers. An undef cell (empty CSV marker)
5374 # passes through for zero/impute/nan, but croaks under the 'die' strategy -- so
5375 # 'die' rejects a missing value exactly when it lands in a sampled training row.
5376 # $where names the row for error messages. Only the rows a fit keeps are run
5377 # through here, which is why a bad cell elsewhere is never reported.
5378 #
5379 # Args:
5380 # $row :: arrayref of raw cells from a parse => 0 reader -- strings, with
5381 # undef for the empty cells. Modified in place.
5382 # $where :: a phrase naming the row for croak messages, e.g. "line 42" or
5383 # "sampled row 17".
5384 #
5385 # Returns: nothing. $row's defined cells come back as numbers; undef cells
5386 # stay undef unless missing => 'die', which croaks instead.
5387 #
5388 # Example:
5389 # my $row = [ '0.9', undef, '0.1' ];
5390 # $self->_numify_row( $row, 'line 42' ); # [ 0.9, undef, 0.1 ]
5391 13765 ▶sub _numify_row {
Subroutine _numify_row: called CC=5 SCAR=16.1
5392 13765 my ( $self, $row, $where ) = @_;
5393 13765 my $die = $self->{missing} eq 'die';
5394 13765 for my $f (@$row) {
5395 57467 ▶ if ( !defined $f ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $f) 14 57453 57467
5396 14 ▶ croak "fit_from_csv(): missing value in $where; construct with "
Branch: 1 branch
BranchTrueFalseTotal
if $die 2 12 14
5397 . "missing => 'zero', 'impute', or 'nan' to train on data "
5398 . "with missing values"
5399 if $die;
5400 12 next;
5401 }
5402 57453 ▶ croak "fit_from_csv(): $where value '$f' is not a number"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($f) 1 57452 57453
5403 unless looks_like_number($f);
5404 57452 $f += 0;
5405 } ## end for my $f (@$row)
5406 13762 return;
5407 } ## end sub _numify_row
5408  
5409 # Streaming census (index => 0 or offset table over budget): count the data
5410 # rows and pin the feature width via the cheap parse => 0 reader. No cell
5411 # validation -- that is deferred to the rows that train or get scored.
5412 #
5413 # Args:
5414 # $path :: path to the CSV file, which must be readable.
5415 # $skip_first :: true to drop the first non-blank line as a header.
5416 #
5417 # Returns: the two-element list ($n, $nf) -- the data row count and the
5418 # feature width taken from the first data row. Both undef-free, though $n
5419 # is 0 and $nf undef for a file with no data rows. Croaks on a row whose
5420 # column count disagrees with the first row's.
5421 #
5422 # Example:
5423 # my ( $n, $nf ) = $self->_census_stream( 'train.csv', 1 ); # ( 1_000_000, 4 )
5424 2 ▶sub _census_stream {
Subroutine _census_stream: called CC=4 SCAR=13.9
5425 2 my ( $self, $path, $skip_first ) = @_;
5426 2 my $reader = $self->_csv_reader( $path, $skip_first, 0 );
5427 2 my ( $n, $nf ) = ( 0, undef );
5428 2 ▶ while ( my ( $row, $line ) = $reader->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$reader()) 832 2 834
5429 832 ▶ $nf //= scalar @$row;
Condition100%2/2
$nf //= scalar @$row
l!l
8302
MC/DC100%1/1
$nf //= scalar @$row
$nf
Truth table100%2/2
A
A= $nf
Aresult
11
00
5430 832 ▶ croak "fit_from_csv(): line $line of '$path' has " . scalar(@$row) . " columns but expected $nf"
Branch: 1 branch
BranchTrueFalseTotal
unless @$row == $nf 0 832 832
5431 unless @$row == $nf;
5432 832 $n++;
5433 }
5434 2 return ( $n, $nf );
5435 } ## end sub _census_stream
5436  
5437 # Streaming gather (no offset table): re-scan the file, numifying only the
5438 # sampled rows. Companion to _census_stream.
5439 #
5440 # Args:
5441 # $path :: path to the CSV file, which must be readable.
5442 # $skip_first :: true to drop the first non-blank line as a header.
5443 # $want :: hashref used as a set -- its keys are the data row indices to
5444 # keep, counting from 0 over the non-blank data lines.
5445 #
5446 # Returns: hashref keyed by the same indices, each value the numified row as
5447 # an arrayref. Indices absent from the file simply do not appear.
5448 #
5449 # Example:
5450 # my $pool = $self->_gather_stream( 'train.csv', 1, { 0 => 1, 7 => 1 } );
5451 # # { 0 => [ 0.9, 0.4 ], 7 => [ 1.2, 0.3 ] }
5452 4 ▶sub _gather_stream {
Subroutine _gather_stream: called CC=3 SCAR=11.0
5453 4 my ( $self, $path, $skip_first, $want ) = @_;
5454 4 my $reader = $self->_csv_reader( $path, $skip_first, 0 );
5455 4 my %pool;
5456 4 my $i = 0;
5457 4 ▶ while ( my ( $row, $line ) = $reader->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$reader()) 1664 4 1668
5458 1664 ▶ if ( exists $want->{$i} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $want->{$i}) 1664 0 1664
5459 1664 $self->_numify_row( $row, "line $line" );
5460 1664 $pool{$i} = $row;
5461 }
5462 1664 $i++;
5463 }
5464 4 return \%pool;
5465 } ## end sub _gather_stream
5466  
5467 # Index census: one block-scan that counts the data rows, pins the feature
5468 # width, AND records each data row's byte offset so gather can seek straight to
5469 # the sampled rows. Blank lines are skipped and the header dropped exactly as
5470 # the reader does, so offset i is the i-th data row. The offset table costs
5471 # 8*n bytes; once it would exceed $max_off it is dropped (returning undef) and
5472 # only the count survives, so the caller falls back to the streaming gather.
5473 #
5474 # Args:
5475 # $path :: path to the CSV file, which must be readable.
5476 # $skip_first :: true to drop the first non-blank line as a header.
5477 # $max_off :: byte ceiling for the offset table. 0 disables the table
5478 # outright, making this a pure counting pass.
5479 #
5480 # Returns: the three-element list ($n, $nf, $offsets) -- the data row count,
5481 # the feature width, and either an arrayref of per-row byte offsets (element
5482 # i is data row i's start) or undef when the table was disabled or went over
5483 # budget.
5484 #
5485 # Example:
5486 # my ( $n, $nf, $off ) = $self->_index_pass( 'train.csv', 1, 64 * 1024 * 1024 );
5487 # # ( 1_000_000, 4, [ 12, 31, 49, ... ] ), or $off undef past 8 MB of table
5488 65 ▶sub _index_pass {
Subroutine _index_pass: called CC=9 SCAR=22.3
5489 65 my ( $self, $path, $skip_first, $max_off ) = @_;
5490 65 ▶ open my $fh, '<', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $path or croak("fit_from_csv(): cannot open '${path}': $!") 65 0 65
5491 or croak "fit_from_csv(): cannot open '$path': $!";
5492 65 binmode $fh;
5493  
5494 65 my @off;
5495 65 ▶ my $store = $max_off > 0 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$max_off > 0 ? : 65 0 65
5496 65 my $cap = int( $max_off / 8 );
5497 65 my $n = 0;
5498 65 my $skipped = 0;
5499 65 my $nf;
5500  
5501 # Consider the line at ($$sref, $off .. $off+$len). To stay fast we avoid
5502 # copying the line: a zero-length line is empty, and any line whose first
5503 # byte is a digit/sign/dot (>= '!') is non-blank without further checks --
5504 # only a line starting with whitespace (< '!') is materialised to apply the
5505 # reader's /^\s*$/ blank test. $abs is its absolute byte offset.
5506 15481 ▶ my $feed = sub {
Subroutine __ANON__: called CC=9 SCAR=22.3
5507 15481 my ( $abs, $sref, $off, $len ) = @_;
5508 15481 ▶ return if $len == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $len == 0 0 15481 15481
5509 15481 ▶ if ( substr( $$sref, $off, 1 ) lt '!' ) { # leading whitespace: maybe blank
Branch: 1 branch
BranchTrueFalseTotal
if (substr($$sref, $off, 1) lt "!") 0 15481 15481
5510 0 ▶ return if substr( $$sref, $off, $len ) !~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless substr($$sref, $off, $len) =~ /\S/ 0 0 0
5511 }
5512 15481 ▶ if ( $skip_first && !$skipped ) { $skipped = 1; return; }
Branch: 1 branch
BranchTrueFalseTotal
if ($skip_first and not $skipped) 16 15465 15481
Condition100%3/3
$skip_first and not $skipped
!ll&&!rl&&r
13761170416
MC/DC100%2/2
$skip_first and not $skipped
$skip_first not $skipped
Truth table100%3/3
A and not(B)
A= $skip_firstB= not $skipped
ABresult
0X0
100
111
5513 15465 ▶ $nf //= scalar( () = split /,/, substr( $$sref, $off, $len ), -1 ); # width from row 1
Condition100%2/2
$nf //= scalar(() = split(/,/, substr($$sref, $off, $len), -1))
l!l
1540164
MC/DC100%1/1
$nf //= scalar(() = split(/,/, substr($$sref, $off, $len), -1))
$nf
Truth table100%2/2
A
A= $nf
Aresult
11
00
5514 15465 $n++;
5515 15465 ▶ return unless $store;
Branch: 1 branch
BranchTrueFalseTotal
unless $store 830 14635 15465
5516 14635 push @off, $abs;
5517 14635 ▶ if ( @off > $cap ) { $store = 0; @off = () } # over budget: abandon the table
Branch: 1 branch
BranchTrueFalseTotal
if (@off > $cap) 2 14633 14635
5518 65 }; ## end $feed = sub
5519  
5520 65 my ( $carry, $file_pos ) = ( '', 0 ); # $file_pos = abs offset of $carry's start
5521 65 my $buf;
5522 65 ▶ while ( my $got = read( $fh, $buf, 1 << 20 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $got = read($fh, $buf, 1048576)) 64 65 129
5523 64 my $s = $carry . $buf;
5524 64 my $p = 0;
5525 64 my $nl;
5526 64 ▶ while ( ( $nl = index( $s, "\n", $p ) ) >= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (($nl = index($s, "\n", $p)) >= 0) 15481 64 15545
5527 15481 my $len = $nl - $p;
5528 15481 ▶ $len-- if $len && substr( $s, $nl - 1, 1 ) eq "\r"; # exclude a CRLF's CR
Branch: 1 branch
BranchTrueFalseTotal
if $len and substr($s, $nl - 1, 1) eq "\r" 0 15481 15481
Condition33%1/3
$len and substr($s, $nl - 1, 1) eq "\r"
!ll&&!rl&&r
0154810
MC/DC0%0/2
$len and substr($s, $nl - 1, 1) eq "\r"
$len substr($s, $nl - 1, 1) eq "\r"
Truth table33%1/3
A and B
A= $lenB= substr($s, $nl - 1, 1) eq "\r"
ABresult
0X0
100
111
5529 15481 $feed->( $file_pos + $p, \$s, $p, $len );
5530 15481 $p = $nl + 1;
5531 }
5532 64 $carry = substr( $s, $p );
5533 64 $file_pos += $p;
5534 } ## end while ( my $got = read( $fh, $buf, 1 << 20 ) )
5535 65 close $fh;
5536 65 ▶ $feed->( $file_pos, \$carry, 0, length $carry ) if length $carry; # final unterminated line
Branch: 1 branch
BranchTrueFalseTotal
if length $carry 0 65 65
5537  
5538 65 ▶ return ( $n, $nf, $store ? \@off : undef );
Branch: 1 branch
BranchTrueFalseTotal
$store ? : 63 2 65
5539 } ## end sub _index_pass
5540  
5541 # Random-access gather: seek to each sampled row's recorded offset and numify
5542 # it. Indices are visited in order for sequential-ish disk access.
5543 #
5544 # Args:
5545 # $path :: path to the CSV file, which must be readable.
5546 # $offsets :: the arrayref of per-row byte offsets from _index_pass.
5547 # $want :: hashref used as a set -- its keys are the data row indices to
5548 # keep.
5549 #
5550 # Returns: hashref keyed by the same indices, each value the numified row as
5551 # an arrayref. Croaks on a short read or a row whose column count
5552 # disagrees with the model's n_features, which is how a file changing
5553 # underneath the passes gets caught.
5554 #
5555 # Example:
5556 # my $pool = $self->_gather_indexed( 'train.csv', $offsets, { 0 => 1, 7 => 1 } );
5557 # # { 0 => [ 0.9, 0.4 ], 7 => [ 1.2, 0.3 ] }
5558 60 ▶sub _gather_indexed {
Subroutine _gather_indexed: called CC=8 SCAR=20.9
5559 60 my ( $self, $path, $offsets, $want ) = @_;
5560 60 ▶ open my $fh, '<', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $path or croak("fit_from_csv(): cannot open '${path}': $!") 60 0 60
5561 or croak "fit_from_csv(): cannot open '$path': $!";
5562 60 my $nf = $self->{n_features};
5563 60 my %pool;
5564 60 for my $i ( sort { $a <=> $b } keys %$want ) {
5565 12102 ▶ seek( $fh, $offsets->[$i], 0 )
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $offsets->[$i], 0 or croak("fit_from_csv(): seek failed for row ${i}: $!") 12102 0 12102
5566 or croak "fit_from_csv(): seek failed for row $i: $!";
5567 12102 my $line = <$fh>;
5568 12102 ▶ croak "fit_from_csv(): row $i is past the end of '$path'" unless defined $line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 0 12102 12102
5569 12102 $line =~ s/\r?\n\z//;
5570 12102 my @f = split /,/, $line, -1;
5571 12102 ▶ croak "fit_from_csv(): sampled row $i has " . scalar(@f) . " columns but expected $nf"
Branch: 1 branch
BranchTrueFalseTotal
unless @f == $nf 1 12101 12102
5572 unless @f == $nf;
5573 12101 ▶ for my $x (@f) { $x = undef if !length $x }
Branch: 1 branch
BranchTrueFalseTotal
unless length $x 14 54126 54140
5574 12101 $self->_numify_row( \@f, "sampled row $i" );
5575 12098 $pool{$i} = \@f;
5576 } ## end for my $i ( sort { $a <=> $b } keys %$want )
5577 56 close $fh;
5578 56 return \%pool;
5579 } ## end sub _gather_indexed
5580  
5581 # Draw $k distinct indices uniformly from [0, $n) via Floyd's algorithm --
5582 # O($k) time and memory, so it never allocates the 0..n-1 vector _subsample()
5583 # builds (the whole point: n may not fit in RAM). Returns them sorted, which
5584 # makes the per-tree sample order deterministic (independent of hash-key
5585 # randomisation) even though tree structure does not depend on row order.
5586 #
5587 # Args:
5588 # $n :: the population size, a non-negative integer.
5589 # $k :: how many distinct indices to draw. $k >= $n yields everything.
5590 #
5591 # Returns: the drawn indices as a sorted list (not a reference), each in
5592 # [0, $n).
5593 #
5594 # Example:
5595 # srand(42);
5596 # my @idx = _sample_indices_distinct( 1_000_000, 256 ); # 256 sorted rows
5597 2309 ▶sub _sample_indices_distinct {
Subroutine _sample_indices_distinct: called CC=4 SCAR=13.9
5598 2309 my ( $n, $k ) = @_;
5599 2309 ▶ return ( 0 .. $n - 1 ) if $k >= $n;
Branch: 1 branch
BranchTrueFalseTotal
if $k >= $n 318 1991 2309
5600 1991 my %seen;
5601 1991 for my $j ( $n - $k .. $n - 1 ) {
5602 309684 my $t = int( rand( $j + 1 ) ); # uniform in [0, $j]
5603 309684 ▶ $seen{ exists $seen{$t} ? $j : $t } = 1;
Branch: 1 branch
BranchTrueFalseTotal
exists $seen{$t} ? : 88683 221001 309684
5604 }
5605 1991 my @idx = sort { $a <=> $b } keys %seen;
5606 1991 return @idx;
5607 } ## end sub _sample_indices_distinct
5608  
5609 # Apply the missing-value strategy to the gathered pool (hashref index => row),
5610 # densifying in place so the pure-Perl _build_tree sees defined cells. Mirrors
5611 # _prepare_fit_data, except impute learns its fill from the training sub-sample
5612 # rather than the full file -- the only fill bounded-memory fitting can form.
5613 #
5614 # Args:
5615 # $pool :: hashref of row index => arrayref of cells, as returned by
5616 # _gather_stream or _gather_indexed. Rewritten in place.
5617 #
5618 # Returns: nothing. Under zero/impute every row in $pool comes back dense;
5619 # under impute the learned fill is also stored in $self->{missing_fill}.
5620 # die and nan return untouched (die data is already dense, nan wants its
5621 # undefs kept).
5622 #
5623 # Example:
5624 # my $pool = $self->_gather_indexed( $path, $offsets, $want );
5625 # $self->_apply_missing_to_pool($pool); # undef cells now carry the fill
5626 60 ▶sub _apply_missing_to_pool {
Subroutine _apply_missing_to_pool: called CC=6 SCAR=17.9
5627 60 my ( $self, $pool ) = @_;
5628 60 my $m = $self->{missing};
5629 60 ▶ return if $m eq 'die' || $m eq 'nan'; # die: already dense; nan: keep undef
Branch: 1 branch
BranchTrueFalseTotal
if $m eq "die" or $m eq "nan" 56 4 60
Condition100%3/3
$m eq "die" or $m eq "nan"
l!l&&r!l&&!r
5424
MC/DC100%2/2
$m eq "die" or $m eq "nan"
$m eq "die" $m eq "nan"
Truth table100%3/3
A or B
A= $m eq "die"B= $m eq "nan"
ABresult
1X1
011
000
5630  
5631 4 my $nf = $self->{n_features};
5632 4 my $fill;
5633 4 ▶ if ( $m eq 'impute' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($m eq 'impute') { } 2 2 4
5634 2 $fill = $self->_compute_impute_fill( [ values %$pool ] );
5635 2 $self->{missing_fill} = $fill;
5636 2 delete $self->{_fill_packed};
5637 } else { # zero
5638 2 $fill = [ (0) x $nf ];
5639 }
5640 4 for my $i ( keys %$pool ) {
5641 20 my $r = $pool->{$i};
5642 20 ▶ $pool->{$i} = [ map { defined $r->[$_] ? $r->[$_] : $fill->[$_] } 0 .. $nf - 1 ];
Branch: 1 branch
BranchTrueFalseTotal
defined $r->[$_] ? : 32 8 40
5643 }
5644 4 return;
5645 } ## end sub _apply_missing_to_pool
5646  
5647 # Streaming counterpart of _learn_contamination_threshold: learn the exact
5648 # score cutoff for the contamination rate without holding every score. k+1
5649 # largest scores are enough for _threshold_from_ranked's boundary logic; a
5650 # min-heap keeps them in one scoring pass, and (only under a boundary tie) one
5651 # extra pass resolves the tie block's edges.
5652 #
5653 # Args:
5654 # $path :: path to the CSV file the model was just fitted from.
5655 # $skip_first :: true to drop the first non-blank line as a header.
5656 # $n :: the census row count, which fixes how many rows k stands for.
5657 # $c_scan :: true to let the C packer coerce cells, skipping the Perl
5658 # numeric validation on the scoring passes. See _stream_scores.
5659 #
5660 # Returns: nothing. Sets $self->{threshold} to the same value the in-RAM
5661 # _learn_contamination_threshold would have produced for this data.
5662 #
5663 # Example:
5664 # $self->_learn_contamination_threshold_streaming( 'train.csv', 1, 1_000_000, 1 );
5665 31 ▶sub _learn_contamination_threshold_streaming {
Subroutine _learn_contamination_threshold_streaming: called CC=8 SCAR=21.9
5666 31 my ( $self, $path, $skip_first, $n, $c_scan ) = @_;
5667  
5668 31 my $k = int( $self->{contamination} * $n + 0.5 );
5669 31 ▶ $k = 1 if $k < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $k < 1 0 31 31
5670 31 ▶ $k = $n if $k > $n;
Branch: 1 branch
BranchTrueFalseTotal
if $k > $n 0 31 31
5671  
5672 # Whole set flagged: sit the cut just below the global minimum score.
5673 31 ▶ if ( $k >= $n ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k >= $n) 0 31 31
5674 0 my $min;
5675 0 ▶ $self->_stream_scores( $path, $skip_first, sub { $min = $_[0] if !defined $min || $_[0] < $min }, $c_scan );
Subroutine __ANON__: not called CC=3 SCAR=24.8
Branch: 1 branch
BranchTrueFalseTotal
if not defined $min or $_[0] < $min 0 0 0
Condition0%0/3
not defined $min or $_[0] < $min
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $min or $_[0] < $min
not defined $min $_[0] < $min
Truth table0%0/3
not(A) or B
A= not defined $minB= $_[0] < $min
ABresult
1X1
011
000
5676 0 $self->{threshold} = $min - 1e-9;
5677 0 return;
5678 }
5679  
5680 # One scoring pass keeps the k+1 largest scores (a min-heap rooted at the
5681 # smallest kept). contamination <= 0.5 bounds k at n/2, so this tail is
5682 # always the smaller side of the split.
5683 31 my @heap;
5684 31 my $cap = $k + 1;
5685 $self->_stream_scores(
5686 $path,
5687 $skip_first,
5688 11417 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
5689 11417 my $s = $_[0];
5690 11417 ▶ if ( @heap < $cap ) { _heap_push( \@heap, $s ) }
Branch: 2 branches
BranchTrueFalseTotal
if (@heap < $cap) { } 1183 10234 11417
elsif ($s > $heap[0]) { } 2541 7693 10234
5691 2541 elsif ( $s > $heap[0] ) { _heap_replace_root( \@heap, $s ) }
5692 },
5693 31 $c_scan
5694 );
5695  
5696 29 my @desc = sort { $b <=> $a } @heap; # k+1 largest, descending
5697 29 my $v = $desc[ $k - 1 ]; # k-th largest
5698 29 my $lo = $desc[$k]; # (k+1)-th largest
5699  
5700 # Clean gap at the boundary: cut midway, exactly as _threshold_from_ranked.
5701 29 ▶ if ( $lo < $v ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lo < $v) 26 3 29
5702 26 $self->{threshold} = ( $v + $lo ) / 2.0;
5703 26 return;
5704 }
5705  
5706 # A tie block of value $v straddles rank k. Reproduce _threshold_from_ranked's
5707 # tie branch: locate the block's edges (i = first index at $v, j = first
5708 # index below it) and the neighbouring scores with one more pass.
5709 3 my ( $cnt_gt, $cnt_eq, $above, $below ) = ( 0, 0, undef, undef );
5710 $self->_stream_scores(
5711 $path,
5712 $skip_first,
5713 1333 ▶ sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
5714 1333 my $s = $_[0];
5715 1333 ▶ if ( $s > $v ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($s > $v) { } 6 1327 1333
elsif ($s == $v) { } 55 1272 1327
5716 6 $cnt_gt++;
5717 6 ▶ $above = $s if !defined $above || $s < $above; # smallest > $v
Branch: 1 branch
BranchTrueFalseTotal
if not defined $above or $s < $above 2 4 6
Condition66%2/3
not defined $above or $s < $above
l!l&&r!l&&!r
204
MC/DC50%1/2
not defined $above or $s < $above
not defined $above $s < $above
Truth table66%2/3
not(A) or B
A= not defined $aboveB= $s < $above
ABresult
1X1
011
000
5718 } elsif ( $s == $v ) {
5719 55 $cnt_eq++;
5720 } else {
5721 1272 ▶ $below = $s if !defined $below || $s > $below; # largest < $v
Branch: 1 branch
BranchTrueFalseTotal
if not defined $below or $s > $below 19 1253 1272
Condition100%3/3
not defined $below or $s > $below
l!l&&r!l&&!r
3161253
MC/DC100%2/2
not defined $below or $s > $below
not defined $below $s > $below
Truth table100%3/3
not(A) or B
A= not defined $belowB= $s > $below
ABresult
1X1
011
000
5722 }
5723 },
5724 3 $c_scan
5725 );
5726  
5727 3 my $i = $cnt_gt; # first rank holding $v
5728 3 my $j = $cnt_gt + $cnt_eq; # first rank below $v
5729 3 ▶ if ( $i > 0 && ( $k - $i ) < ( $j - $k ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($i > 0 and $k - $i < $j - $k) { } 0 3 3
elsif ($j < $n) { } 3 0 3
Condition66%2/3
$i > 0 and $k - $i < $j - $k
!ll&&!rl&&r
120
MC/DC0%0/2
$i > 0 and $k - $i < $j - $k
$i > 0 $k - $i < $j - $k
Truth table66%2/3
A and B
A= $i > 0B= $k - $i < $j - $k
ABresult
0X0
100
111
5730 0 $self->{threshold} = ( $above + $v ) / 2.0; # exclude the block
5731 } elsif ( $j < $n ) {
5732 3 $self->{threshold} = ( $v + $below ) / 2.0; # include the block
5733 } else {
5734 0 $self->{threshold} = $v - 1e-9; # block runs to the end
5735 }
5736 3 return;
5737 } ## end sub _learn_contamination_threshold_streaming
5738  
5739 # Stream the CSV, score rows in flat batches (through the same mean/majority
5740 # path score_samples/predict use), and invoke $cb->($score) for each row.
5741 # c_scan fast path: when scoring runs through the C packer (mean voting, use_c,
5742 # trees packed) the packer coerces each cell via SvNV, so the reader can run
5743 # raw (parse => 0) and skip the Perl looks_like_number validation. Every other
5744 # path parses (parse => 1) so its Perl scorer sees real numbers.
5745 #
5746 # Args:
5747 # $path :: path to the CSV file, which must be readable.
5748 # $skip_first :: true to drop the first non-blank line as a header.
5749 # $cb :: coderef invoked once per data row as $cb->($score), in file order.
5750 # The score is the mean-mode anomaly score, or the majority pivot
5751 # under voting => 'majority'.
5752 # $c_scan :: true to allow the raw-cell fast path described above.
5753 #
5754 # Returns: nothing; everything is delivered through $cb.
5755 #
5756 # Example:
5757 # my $max;
5758 # $self->_stream_scores( 'train.csv', 1,
5759 # sub { $max = $_[0] if !defined $max || $_[0] > $max }, 1 );
5760 34 ▶sub _stream_scores {
Subroutine _stream_scores: called CC=9 SCAR=22.4
5761 34 my ( $self, $path, $skip_first, $cb, $c_scan ) = @_;
5762 34 ▶ my $majority = $self->{voting} eq 'majority' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'voting'} eq 'majority' ? : 0 34 34
5763 34 ▶ my $c_coerce = $c_scan && $self->{_use_c} && $self->{_c_nodes} && !$majority;
Condition77%7/9
$c_scan && $self->{'_use_c'} && $self->{'_c_nodes'} && !$majority
!ll&&!rl&&r
18016
$c_scan and $self->{"_use_c"} and $self->{"_c_nodes"}
!ll&&!rl&&r
18016
$c_scan and $self->{"_use_c"}
!ll&&!rl&&r
41416
MC/DC50%2/4
$c_scan && $self->{'_use_c'} && $self->{'_c_nodes'} && !$majority
$c_scan $self->{"_use_c"} $self->{"_c_nodes"} !$majority
Truth table60%3/5
A and B and C && not(D)
A= $c_scanB= $self->{"_use_c"}C= $self->{"_c_nodes"}D= !$majority
ABCDresult
0XXX0
10XX0
110X0
11100
11111
5764 34 ▶ my $reader = $self->_csv_reader( $path, $skip_first, $c_coerce ? 0 : 1 );
Branch: 1 branch
BranchTrueFalseTotal
$c_coerce ? : 16 18 34
5765  
5766 # The c_coerce path lets the C packer turn any non-numeric cell into 0.0 via
5767 # SvNV; silence the per-cell "isn't numeric" warnings that intentional
5768 # coercion raises (clean data produces none). Other warnings pass through.
5769 34 local $SIG{__WARN__};
5770 2 ▶ $SIG{__WARN__} = sub { $_[0] =~ /isn't numeric/ or warn $_[0] }
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /isn't numeric/ or warn $_[0] 2 0 2
5771 34 ▶ if $c_coerce;
Branch: 1 branch
BranchTrueFalseTotal
if $c_coerce 16 18 34
5772  
5773 34 my @batch;
5774 32 ▶ my $flush = sub {
Subroutine __ANON__: called CC=4 SCAR=14.5
5775 32 ▶ return unless @batch;
Branch: 1 branch
BranchTrueFalseTotal
unless @batch 0 32 32
5776 32 ▶ my $scores
Branch: 1 branch
BranchTrueFalseTotal
$majority ? : 0 32 32
5777 = $majority
5778 ? $self->_majority_pivot_scores( \@batch )
5779 : $self->score_samples( \@batch );
5780 32 $cb->($_) for @$scores;
5781 32 @batch = ();
5782 34 };
5783 34 ▶ while ( my ($row) = $reader->() ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($row) = &$reader()) 13750 32 13782
5784 13750 push @batch, $row;
5785 13750 ▶ $flush->() if @batch >= 8192;
Branch: 1 branch
BranchTrueFalseTotal
if @batch >= 8192 0 13750 13750
5786 }
5787 32 $flush->();
5788 32 return;
5789 } ## end sub _stream_scores
5790  
5791 # Minimal binary min-heap over a plain arrayref (root = smallest). Paired
5792 # with _heap_replace_root to keep the k+1 largest scores of a stream in
5793 # bounded memory -- push until full, then replace the root whenever a
5794 # bigger value turns up.
5795 #
5796 # Append a value and sift it up into place.
5797 #
5798 # Args:
5799 # $h :: the heap, an arrayref maintained by these two functions alone.
5800 # Modified in place.
5801 # $x :: the number to insert.
5802 #
5803 # Returns: nothing. $h->[0] is the smallest value held afterwards.
5804 #
5805 # Example:
5806 # my @heap;
5807 # _heap_push( \@heap, $_ ) for 0.7, 0.2, 0.5;
5808 # $heap[0]; # 0.2
5809 1183 ▶sub _heap_push {
Subroutine _heap_push: called CC=3 SCAR=11.0
5810 1183 my ( $h, $x ) = @_;
5811 1183 push @$h, $x;
5812 1183 my $i = $#$h;
5813 1183 ▶ while ( $i > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i > 0) 2140 131 2271
5814 2140 my $p = ( $i - 1 ) >> 1;
5815 2140 ▶ last if $h->[$p] <= $h->[$i];
Branch: 1 branch
BranchTrueFalseTotal
if $h->[$p] <= $h->[$i] 1052 1088 2140
5816 1088 @{$h}[ $p, $i ] = @{$h}[ $i, $p ];
5817 1088 $i = $p;
5818 }
5819 1183 return;
5820 } ## end sub _heap_push
5821  
5822 # Overwrite the smallest value held and sift the replacement down. Keeps
5823 # the heap at a fixed size, which is how the scoring pass retains only the
5824 # largest k+1 scores it has seen.
5825 #
5826 # Args:
5827 # $h :: the heap, a non-empty arrayref built by _heap_push. Modified in
5828 # place.
5829 # $x :: the number to put in the root's place. Callers only do this when
5830 # $x is larger than the current root, so the heap keeps the biggest
5831 # values.
5832 #
5833 # Returns: nothing. $h->[0] is the smallest of the retained values
5834 # afterwards.
5835 #
5836 # Example:
5837 # _heap_replace_root( \@heap, 0.9 ) if $score > $heap[0];
5838 2541 ▶sub _heap_replace_root {
Subroutine _heap_replace_root: called CC=6 SCAR=17.9
5839 2541 my ( $h, $x ) = @_;
5840 2541 $h->[0] = $x;
5841 2541 my $n = scalar @$h;
5842 2541 my $i = 0;
5843 2541 while (1) {
5844 11941 my $l = 2 * $i + 1;
5845 11941 my $r = 2 * $i + 2;
5846 11941 my $s = $i;
5847 11941 ▶ $s = $l if $l < $n && $h->[$l] < $h->[$s];
Branch: 1 branch
BranchTrueFalseTotal
if $l < $n and $h->[$l] < $h->[$s] 8641 3300 11941
Condition100%3/3
$l < $n and $h->[$l] < $h->[$s]
!ll&&!rl&&r
154417568641
MC/DC100%2/2
$l < $n and $h->[$l] < $h->[$s]
$l < $n $h->[$l] < $h->[$s]
Truth table100%3/3
A and B
A= $l < $nB= $h->[$l] < $h->[$s]
ABresult
0X0
100
111
5848 11941 ▶ $s = $r if $r < $n && $h->[$r] < $h->[$s];
Branch: 1 branch
BranchTrueFalseTotal
if $r < $n and $h->[$r] < $h->[$s] 4025 7916 11941
Condition100%3/3
$r < $n and $h->[$r] < $h->[$s]
!ll&&!rl&&r
169862184025
MC/DC100%2/2
$r < $n and $h->[$r] < $h->[$s]
$r < $n $h->[$r] < $h->[$s]
Truth table100%3/3
A and B
A= $r < $nB= $h->[$r] < $h->[$s]
ABresult
0X0
100
111
5849 11941 ▶ last if $s == $i;
Branch: 1 branch
BranchTrueFalseTotal
if $s == $i 2541 9400 11941
5850 9400 @{$h}[ $s, $i ] = @{$h}[ $i, $s ];
5851 9400 $i = $s;
5852 } ## end while (1)
5853 2541 return;
5854 } ## end sub _heap_replace_root
5855  
5856 #-------------------------------------------------------------------------------
5857 # Draw $k samples without replacement via a partial Fisher-Yates shuffle of the
5858 # index array.
5859 #
5860 # Args:
5861 # $data :: the training set, an arrayref of feature-value arrayrefs.
5862 # Never modified.
5863 # $k :: how many samples to draw, an integer in [1, scalar @$data].
5864 #
5865 # Returns: an arrayref of $k row references. The rows are SHARED with
5866 # $data, not copied, so nothing downstream may mutate them -- _build_tree
5867 # only ever reads.
5868 #
5869 # Example:
5870 # srand(42);
5871 # my $sample = _subsample( \@training_rows, 256 );
5872 # my $tree = $self->_build_tree( $sample, 0, 8 );
5873 #-------------------------------------------------------------------------------
5874 3899 ▶sub _subsample {
Subroutine _subsample: called CC=2 SCAR=6.9
5875 3899 my ( $data, $k ) = @_;
5876 3899 my $n = scalar @$data;
5877 3899 my @idx = ( 0 .. $n - 1 );
5878 3899 for my $i ( 0 .. $k - 1 ) {
5879 759208 my $j = $i + int( rand( $n - $i ) );
5880 759208 @idx[ $i, $j ] = @idx[ $j, $i ];
5881 }
5882 3899 my @chosen = @idx[ 0 .. $k - 1 ];
5883 3899 return [ @{$data}[@chosen] ];
5884 } ## end sub _subsample
5885  
5886 #-------------------------------------------------------------------------------
5887 # Recursively build one isolation tree.
5888 #
5889 # A node is one of:
5890 # leaf { leaf => 1, size => N }
5891 # axis { attr => A, split => S, left => ..., right => ... }
5892 # oblique { idx => [..], coef => [..], b => B, left => ..., right => ... }
5893 #
5894 # In both split styles the choice is restricted to features that actually vary
5895 # across the points reaching the node: this avoids wasted levels on constant
5896 # columns and lets a node leaf out exactly when its points are indistinguishable.
5897 #
5898 # Args:
5899 # $X :: the points reaching this node, an arrayref of feature-value
5900 # arrayrefs. Read-only; undef cells only appear under
5901 # missing => 'nan'.
5902 # $depth :: this node's depth, 0 at the root.
5903 # $limit :: the height limit from _resolve_geometry. At or past it the
5904 # node leafs out and c(size) covers the rest.
5905 #
5906 # Returns: the node as an arrayref in the layout above, with children
5907 # already recursed into -- so calling it on the root returns the whole tree.
5908 #
5909 # Example:
5910 # my $tree = $self->_build_tree( _subsample( \@rows, 256 ), 0, 8 );
5911 # # [ 1, 2, 0.37, [ ... ], [ ... ] ] -- an axis split on feature 2
5912 #-------------------------------------------------------------------------------
5913 734796 ▶sub _build_tree {
Subroutine _build_tree: called CC=21 SCAR=30.4
5914 734796 my ( $self, $X, $depth, $limit ) = @_;
5915  
5916 734796 my $size = scalar @$X;
5917 734796 ▶ return [ _NODE_LEAF, $size ]
Branch: 1 branch
BranchTrueFalseTotal
if $depth >= $limit or $size <= 1 367581 367215 734796
Condition100%3/3
$depth >= $limit or $size <= 1
l!l&&r!l&&!r
215560152021367215
MC/DC100%2/2
$depth >= $limit or $size <= 1
$depth >= $limit $size <= 1
Truth table100%3/3
A or B
A= $depth >= $limitB= $size <= 1
ABresult
1X1
011
000
5918 if $depth >= $limit || $size <= 1;
5919  
5920 367215 my $nf = $self->{n_features};
5921 367215 my $nan = $self->{missing} eq 'nan';
5922  
5923 # Per-feature min and max within this node, in a single pass. Missing
5924 # (undef) cells never reach here under die/zero/impute -- those fill the
5925 # data before fit -- so the "next unless defined" guard is only needed
5926 # in nan mode, where missing values must not constrain a feature's
5927 # range; every other strategy skips it since every cell is defined and
5928 # the check would never fire.
5929 367215 my ( @lo, @hi );
5930 367215 ▶ if ($nan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nan) { } 23378 343837 367215
5931 23378 for my $row (@$X) {
5932 383280 for my $f ( 0 .. $nf - 1 ) {
5933 771017 my $v = $row->[$f];
5934 771017 ▶ next unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 72297 698720 771017
5935 698720 ▶ $lo[$f] = $v if !defined $lo[$f] || $v < $lo[$f];
Branch: 1 branch
BranchTrueFalseTotal
if not defined $lo[$f] or $v < $lo[$f] 87528 611192 698720
Condition100%3/3
not defined $lo[$f] or $v < $lo[$f]
l!l&&r!l&&!r
4710640422611192
MC/DC100%2/2
not defined $lo[$f] or $v < $lo[$f]
not defined $lo[$f] $v < $lo[$f]
Truth table100%3/3
not(A) or B
A= not defined $lo[$f]B= $v < $lo[$f]
ABresult
1X1
011
000
5936 698720 ▶ $hi[$f] = $v if !defined $hi[$f] || $v > $hi[$f];
Branch: 1 branch
BranchTrueFalseTotal
if not defined $hi[$f] or $v > $hi[$f] 86686 612034 698720
Condition100%3/3
not defined $hi[$f] or $v > $hi[$f]
l!l&&r!l&&!r
4710639580612034
MC/DC100%2/2
not defined $hi[$f] or $v > $hi[$f]
not defined $hi[$f] $v > $hi[$f]
Truth table100%3/3
not(A) or B
A= not defined $hi[$f]B= $v > $hi[$f]
ABresult
1X1
011
000
5937 }
5938 }
5939 } else {
5940 343837 for my $row (@$X) {
5941 7953754 for my $f ( 0 .. $nf - 1 ) {
5942 73326189 my $v = $row->[$f];
5943 73326189 ▶ $lo[$f] = $v if !defined $lo[$f] || $v < $lo[$f];
Branch: 1 branch
BranchTrueFalseTotal
if not defined $lo[$f] or $v < $lo[$f] 6885215 66440974 73326189
Condition100%3/3
not defined $lo[$f] or $v < $lo[$f]
l!l&&r!l&&!r
2633682425153366440974
MC/DC100%2/2
not defined $lo[$f] or $v < $lo[$f]
not defined $lo[$f] $v < $lo[$f]
Truth table100%3/3
not(A) or B
A= not defined $lo[$f]B= $v < $lo[$f]
ABresult
1X1
011
000
5944 73326189 ▶ $hi[$f] = $v if !defined $hi[$f] || $v > $hi[$f];
Branch: 1 branch
BranchTrueFalseTotal
if not defined $hi[$f] or $v > $hi[$f] 6736785 66589404 73326189
Condition100%3/3
not defined $hi[$f] or $v > $hi[$f]
l!l&&r!l&&!r
2633682410310366589404
MC/DC100%2/2
not defined $hi[$f] or $v > $hi[$f]
not defined $hi[$f] $v > $hi[$f]
Truth table100%3/3
not(A) or B
A= not defined $hi[$f]B= $v > $hi[$f]
ABresult
1X1
011
000
5945 }
5946 }
5947 }
5948  
5949 # Features with spread are the only ones that can split the data. A
5950 # feature whose values are all missing within this node has an undef
5951 # range and is excluded.
5952 367215 ▶ my @varying = grep { defined $lo[$_] && $lo[$_] < $hi[$_] } 0 .. $nf - 1;
Condition100%3/3
defined $lo[$_] && $lo[$_] < $hi[$_]
!ll&&!rl&&r
552311852449603
MC/DC100%2/2
defined $lo[$_] && $lo[$_] < $hi[$_]
defined $lo[$_] $lo[$_] < $hi[$_]
Truth table100%3/3
A && B
A= defined $lo[$_]B= $lo[$_] < $hi[$_]
ABresult
0X0
100
111
5953  
5954 # No spread on any feature => all points identical => cannot isolate.
5955 367215 ▶ return [ _NODE_LEAF, $size ] unless @varying;
Branch: 1 branch
BranchTrueFalseTotal
unless @varying 2908 364307 367215
5956  
5957 my $node
5958 364307 ▶ = $self->{mode} eq 'extended'
Branch: 1 branch
BranchTrueFalseTotal
$self->{'mode'} eq 'extended' ? : 27450 336857 364307
5959 ? $self->_oblique_split( $X, \@varying, \@lo, \@hi, $nan )
5960 : _axis_split( $X, \@varying, \@lo, \@hi, $nan );
5961  
5962 # Split functions leave the raw point arrays at the child slots so that
5963 # _build_tree can recurse into them; the subtree refs replace them in-place.
5964 # Axis nodes: left at [3], right at [4]
5965 # Oblique nodes: left at [4], right at [5]
5966 364307 ▶ my ( $li, $ri ) = $node->[0] == _NODE_AXIS ? ( 3, 4 ) : ( 4, 5 );
Branch: 1 branch
BranchTrueFalseTotal
$node->[0] == 1 ? : 336857 27450 364307
5967 364307 $node->[$li] = $self->_build_tree( $node->[$li], $depth + 1, $limit );
5968 364307 $node->[$ri] = $self->_build_tree( $node->[$ri], $depth + 1, $limit );
5969  
5970 364307 return $node;
5971 } ## end sub _build_tree
5972  
5973 # Axis-parallel cut: random varying feature, random threshold in its range.
5974 #
5975 # Args:
5976 # $X :: the points reaching this node, an arrayref of feature-value
5977 # arrayrefs.
5978 # $varying :: arrayref of the feature indices that actually vary here --
5979 # the only ones worth cutting on. Must be non-empty.
5980 # $lo, $hi :: arrayrefs of per-feature minimum and maximum over $X,
5981 # indexed by feature number. Entries for features that are
5982 # absent throughout are undef and never consulted.
5983 # $nan :: true under missing => 'nan', which routes a point missing the
5984 # split feature right.
5985 #
5986 # Returns: [ _NODE_AXIS, $attr, $split, \@left_pts, \@right_pts ]. Slots 3
5987 # and 4 hold raw point arrays, which _build_tree overwrites with the
5988 # recursed subtrees.
5989 #
5990 # Example:
5991 # my $node = _axis_split( $X, [ 0, 2 ], \@lo, \@hi, 0 );
5992 # # [ 1, 2, 0.37, [ ...pts < 0.37... ], [ ...pts >= 0.37... ] ]
5993 336857 ▶sub _axis_split {
Subroutine _axis_split: called CC=7 SCAR=19.5
5994 336857 my ( $X, $varying, $lo, $hi, $nan ) = @_;
5995  
5996 336857 my $attr = $varying->[ int( rand( scalar @$varying ) ) ];
5997 336857 my $split;
5998 336857 if (_NV_IS_DOUBLE) {
5999 336857 $split = $lo->[$attr] + rand() * ( $hi->[$attr] - $lo->[$attr] );
6000 } else {
6001 # Same value, but rounded to double after each of the three ops
6002 # exactly as the C builder computes it -- see _NV_IS_DOUBLE.
6003 $split = _to_double( $hi->[$attr] - $lo->[$attr] );
6004 $split = _to_double( rand() * $split );
6005 $split = _to_double( $lo->[$attr] + $split );
6006 }
6007  
6008 # A point missing the split feature (nan mode only) routes to the right
6009 # child -- the same side NaN reaches in the C scorer, where (NaN < split)
6010 # is false. Under die/zero/impute every cell is defined, so the
6011 # "defined($v)" guard is dead weight there and skipped entirely.
6012 336857 my ( @left, @right );
6013 336857 ▶ if ($nan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nan) { } 15136 321721 336857
6014 15136 for my $row (@$X) {
6015 239487 my $v = $row->[$attr];
6016 239487 ▶ if ( defined($v) && $v < $split ) { push @left, $row }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $v and $v < $split) { } 111356 128131 239487
Condition100%3/3
defined $v and $v < $split
!ll&&!rl&&r
17355110776111356
MC/DC100%2/2
defined $v and $v < $split
defined $v $v < $split
Truth table100%3/3
A and B
A= defined $vB= $v < $split
ABresult
0X0
100
111
6017 128131 else { push @right, $row }
6018 }
6019 } else {
6020 321721 for my $row (@$X) {
6021 7458262 ▶ if ( $row->[$attr] < $split ) { push @left, $row }
Branch: 1 branch
BranchTrueFalseTotal
if ($row->[$attr] < $split) { } 4000693 3457569 7458262
6022 3457569 else { push @right, $row }
6023 }
6024 }
6025 336857 return [ _NODE_AXIS, $attr, $split, \@left, \@right ];
6026 } ## end sub _axis_split
6027  
6028 # Oblique cut (Extended Isolation Forest): a random hyperplane. We activate
6029 # (extension_level + 1) of the varying features, give each a Gaussian
6030 # coefficient, and place the plane through a random point in the bounding box.
6031 # A point goes left when coef . x <= b, where b = coef . p.
6032 #
6033 # Args:
6034 # $X :: the points reaching this node, an arrayref of feature-value
6035 # arrayrefs.
6036 # $varying :: arrayref of the feature indices that actually vary here.
6037 # The active set is drawn from these. Must be non-empty.
6038 # $lo, $hi :: arrayrefs of per-feature minimum and maximum over $X,
6039 # indexed by feature number.
6040 # $nan :: true under missing => 'nan', which routes a point missing any
6041 # feature on the hyperplane right.
6042 #
6043 # Returns: [ _NODE_OBLIQUE, \@idx, \@coef, $b, \@left_pts, \@right_pts ],
6044 # where @idx names the participating features and @coef holds their
6045 # coefficients one-for-one. Slots 4 and 5 hold raw point arrays, which
6046 # _build_tree overwrites with the recursed subtrees.
6047 #
6048 # Example:
6049 # my $node = $self->_oblique_split( $X, [ 0, 1, 2 ], \@lo, \@hi, 0 );
6050 # # [ 2, [ 0, 2 ], [ 0.81, -1.32 ], 0.44, [ ... ], [ ... ] ]
6051 27450 ▶sub _oblique_split {
Subroutine _oblique_split: called CC=13 SCAR=25.6
6052 27450 my ( $self, $X, $varying, $lo, $hi, $nan ) = @_;
6053  
6054 27450 my $active = $self->{extension_level_used} + 1;
6055 27450 ▶ $active = scalar @$varying if $active > scalar @$varying;
Branch: 1 branch
BranchTrueFalseTotal
if $active > scalar @$varying 4227 23223 27450
6056  
6057 # Pick which varying features take part (partial shuffle of their indices).
6058 27450 my @pool = @$varying;
6059 27450 for my $i ( 0 .. $active - 1 ) {
6060 57313 my $j = $i + int( rand( scalar(@pool) - $i ) );
6061 57313 @pool[ $i, $j ] = @pool[ $j, $i ];
6062 }
6063 27450 my @idx = @pool[ 0 .. $active - 1 ];
6064  
6065 27450 my ( @coef, $b );
6066 27450 $b = 0.0;
6067 27450 for my $f (@idx) {
6068 57313 my $c = _randn();
6069 57313 if (_NV_IS_DOUBLE) {
6070 57313 my $p = $lo->[$f] + rand() * ( $hi->[$f] - $lo->[$f] ); # point in the box
6071 57313 push @coef, $c;
6072 57313 $b += $c * $p;
6073 } else {
6074 # Round each op to double in the same order as the C builder's
6075 # p = lo + rand() * (hi - lo); b += c * p;
6076 # -- see _NV_IS_DOUBLE.
6077 my $p = _to_double( rand() * _to_double( $hi->[$f] - $lo->[$f] ) );
6078 $p = _to_double( $lo->[$f] + $p );
6079 push @coef, $c;
6080 $b = _to_double( $b + _to_double( $c * $p ) );
6081 }
6082 } ## end for my $f (@idx)
6083  
6084 # A point missing any feature on the hyperplane (nan mode only) routes
6085 # to the right child: in the C scorer the dot product becomes NaN and
6086 # (NaN <= b) is false, so this keeps fit and score consistent. Under
6087 # die/zero/impute every cell is defined, so the per-feature "defined"
6088 # check and early-exit are dead weight there and skipped entirely.
6089 27450 my ( @left, @right );
6090 27450 ▶ if ($nan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nan) { } 6947 20503 27450
6091 6947 for my $row (@$X) {
6092 139686 my $dot = 0.0;
6093 139686 my $missing = 0;
6094 139686 for ( 0 .. $#idx ) {
6095 262282 my $v = $row->[ $idx[$_] ];
6096 262282 ▶ if ( !defined $v ) { $missing = 1; last }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $v) 26240 236042 262282
6097 236042 $dot += $coef[$_] * $v;
6098 }
6099 139686 ▶ if ( !$missing && $dot <= $b ) { push @left, $row }
Branch: 1 branch
BranchTrueFalseTotal
if (not $missing and $dot <= $b) { } 57761 81925 139686
Condition100%3/3
not $missing and $dot <= $b
!ll&&!rl&&r
262405568557761
MC/DC100%2/2
not $missing and $dot <= $b
not $missing $dot <= $b
Truth table100%3/3
not(A) and B
A= not $missingB= $dot <= $b
ABresult
0X0
100
111
6100 81925 else { push @right, $row }
6101 } ## end for my $row (@$X)
6102 } else {
6103 20503 for my $row (@$X) {
6104 487564 my $dot = 0.0;
6105 487564 $dot += $coef[$_] * $row->[ $idx[$_] ] for 0 .. $#idx;
6106 487564 ▶ if ( $dot <= $b ) { push @left, $row }
Branch: 1 branch
BranchTrueFalseTotal
if ($dot <= $b) { } 240181 247383 487564
6107 247383 else { push @right, $row }
6108 }
6109 }
6110 27450 return [ _NODE_OBLIQUE, \@idx, \@coef, $b, \@left, \@right ];
6111 } ## end sub _oblique_split
6112  
6113 #-------------------------------------------------------------------------------
6114 # Path length of a single point in a single tree: edges traversed until a leaf,
6115 # plus c(leaf size) when the leaf still holds several points.
6116 #
6117 # Node layout (arrayref, slot 0 = type):
6118 # _NODE_LEAF [0, size]
6119 # _NODE_AXIS [1, attr, split, left, right]
6120 # _NODE_OBLIQUE [2, \@idx, \@coef, b, left, right]
6121 #
6122 # The type tag is also used as a loop sentinel: 0 (_NODE_LEAF) is falsy.
6123 # No $self argument -- the node type encodes everything needed.
6124 #-------------------------------------------------------------------------------
6125 # The optional $nan flag selects the nan-strategy routing: a point missing
6126 # the split feature goes to the right child (matching the C scorer, where
6127 # the NaN comparison is false). Without it, undef is coerced to 0 -- the
6128 # behaviour the die/zero/impute strategies rely on (their data is dense by
6129 # the time it reaches here, so the "// 0" is normally a no-op).
6130 #
6131 # Args:
6132 # $x :: one sample, an arrayref of feature values. undef cells are
6133 # allowed and handled per $nan.
6134 # $node :: the node to start walking from, normally a tree root.
6135 # $depth :: the depth credited to $node, 0 for a root. Callers only pass
6136 # anything else to resume a partial walk.
6137 # $nan :: true to use the nan-strategy routing described above; false or
6138 # omitted to coerce undef to 0.
6139 #
6140 # Returns: the path length, a float -- edges walked plus c(leaf size), so
6141 # it is not an integer whenever the walk ends in a multi-point leaf.
6142 #
6143 # Example:
6144 # _path_length( [ 0.9, 0.4 ], $tree, 0, 0 ); # e.g. 3.51
6145 1647691 ▶sub _path_length {
Subroutine _path_length: called CC=16 SCAR=27.7
6146 1647691 my ( $x, $node, $depth, $nan ) = @_;
6147 1647691 ▶ while ( $node->[0] ) { # false only for leaf (type 0)
Branch: 1 branch
BranchTrueFalseTotal
if ($node->[0]) 11825895 1647691 13473586
6148 11825895 ▶ if ( $node->[0] == _NODE_AXIS ) { # [1, attr, split, left, right]
Branch: 1 branch
BranchTrueFalseTotal
if ($node->[0] == 1) { } 11594104 231791 11825895
6149 11594104 ▶ if ($nan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nan) { } 4882 11589222 11594104
6150 4882 my $v = $x->[ $node->[1] ];
6151 4882 ▶ $node = ( defined($v) && $v < $node->[2] ) ? $node->[3] : $node->[4];
Branch: 1 branch
BranchTrueFalseTotal
defined $v && $v < $node->[2] ? : 979 3903 4882
Condition100%3/3
defined $v and $v < $node->[2]
!ll&&!rl&&r
17142189979
MC/DC100%2/2
defined $v and $v < $node->[2]
defined $v $v < $node->[2]
Truth table100%3/3
A and B
A= defined $vB= $v < $node->[2]
ABresult
0X0
100
111
6152 } else {
6153 11589222 ▶ $node = ( $x->[ $node->[1] ] // 0 ) < $node->[2] ? $node->[3] : $node->[4];
Branch: 1 branch
BranchTrueFalseTotal
($$x[$node->[1]] // 0) < $node->[2] ? : 6304612 5284610 11589222
Condition100%2/2
$$x[$node->[1]] // 0
l!l
11486825102397
MC/DC100%1/1
$$x[$node->[1]] // 0
$$x[$node->[1]]
Truth table100%2/2
A
A= $$x[$node->[1]]
Aresult
11
00
6154 }
6155 } else { # [2, \@idx, \@coef, b, left, right]
6156 231791 my ( $idx, $coef, $b ) = ( $node->[1], $node->[2], $node->[3] );
6157 231791 ▶ if ($nan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nan) { } 3034 228757 231791
6158 3034 my $dot = 0.0;
6159 3034 my $missing = 0;
6160 3034 for ( 0 .. $#$idx ) {
6161 4727 my $v = $x->[ $idx->[$_] ];
6162 4727 ▶ if ( !defined $v ) { $missing = 1; last }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $v) 1920 2807 4727
6163 2807 $dot += $coef->[$_] * $v;
6164 }
6165 3034 ▶ $node = ( !$missing && $dot <= $b ) ? $node->[4] : $node->[5];
Branch: 1 branch
BranchTrueFalseTotal
!$missing && $dot <= $b ? : 552 2482 3034
Condition100%3/3
not $missing and $dot <= $b
!ll&&!rl&&r
1920562552
MC/DC100%2/2
not $missing and $dot <= $b
not $missing $dot <= $b
Truth table100%3/3
not(A) and B
A= not $missingB= $dot <= $b
ABresult
0X0
100
111
6166 } else {
6167 228757 my $dot = 0.0;
6168 228757 ▶ $dot += $coef->[$_] * ( $x->[ $idx->[$_] ] // 0 ) for 0 .. $#$idx;
Condition100%2/2
$$x[$idx->[$_]] // 0
l!l
4922955238
MC/DC100%1/1
$$x[$idx->[$_]] // 0
$$x[$idx->[$_]]
Truth table100%2/2
A
A= $$x[$idx->[$_]]
Aresult
11
00
6169 228757 ▶ $node = $dot <= $b ? $node->[4] : $node->[5];
Branch: 1 branch
BranchTrueFalseTotal
$dot <= $b ? : 112612 116145 228757
6170 }
6171 } ## end else [ if ( $node->[0] == _NODE_AXIS ) ]
6172 11825895 $depth++;
6173 } ## end while ( $node->[0] )
6174 1647691 return $depth + _c( $node->[1] ); # leaf size at slot 1
6175 } ## end sub _path_length
6176  
6177 #-------------------------------------------------------------------------------
6178 # Explanation (explain_samples) internals.
6179 #-------------------------------------------------------------------------------
6180  
6181 # Instrumented twin of _path_length: routes $x through one tree with
6182 # EXACTLY _path_length's split logic while recording which feature(s)
6183 # each crossed node tested. Returns (path_length, \@pairs) where
6184 # path_length carries the usual c(leaf size) adjustment and each pair
6185 # is [feature_index, share] -- an axis node contributes one pair with
6186 # share 1, an oblique node one pair per participating feature with
6187 # shares proportional to |coef_k * x_k| (each feature's part of the
6188 # dot product), falling back to an even split when every term is 0.
6189 #
6190 # The caller (_explain_path) turns these walks into local-DIFFI credit
6191 # (Carletti, Terzi & Susto, see REFERENCES): every node of a tree's
6192 # walk is credited w_t = 1/h_t - 1/h_max, where h_t is this tree's
6193 # (adjusted) path length and h_max the longest walk any tree gave the
6194 # same sample -- so trees that isolated the sample quickly speak
6195 # loudest, trees that treated it as normal say nothing, and the credit
6196 # is a cross-TREE statistic. Within-tree positional weightings were
6197 # tried and rejected: root-anchored credit (1/(depth+1)) mostly
6198 # rediscovers the RNG (the root split's feature is drawn uniformly at
6199 # random regardless of the sample), and leaf-anchored credit
6200 # (1/(h-depth)) is diluted by the trees that never isolated the sample
6201 # at all.
6202 #
6203 # Args:
6204 # $x :: one sample, an arrayref of feature values. undef cells are
6205 # allowed and handled per $nan.
6206 # $node :: the node to start walking from, normally a tree root.
6207 # $nan :: true to use the nan-strategy routing, matching _path_length.
6208 #
6209 # Returns: the two-element list ($path_length, $pairs). $path_length is
6210 # the same float _path_length would return for this sample and tree.
6211 # $pairs is an arrayref of [ feature_index, share ] entries, one per axis
6212 # node crossed and one per participating feature at each oblique node, with
6213 # the shares at any one node summing to 1.
6214 #
6215 # Example:
6216 # my ( $h, $pairs ) = _path_length_explain( [ 0.9, 0.4 ], $tree, 0 );
6217 # # ( 3.51, [ [ 1, 1 ], [ 0, 1 ], [ 1, 1 ] ] ) for an axis-mode tree
6218 1160 ▶sub _path_length_explain {
Subroutine _path_length_explain: called CC=19 SCAR=33.8
6219 1160 my ( $x, $node, $nan ) = @_;
6220 1160 my $depth = 0;
6221 1160 my @pairs; # [feature, share] for every crossed node
6222 1160 ▶ while ( $node->[0] ) { # false only for leaf (type 0)
Branch: 1 branch
BranchTrueFalseTotal
if ($node->[0]) 5201 1160 6361
6223 5201 ▶ if ( $node->[0] == _NODE_AXIS ) { # [1, attr, split, left, right]
Branch: 1 branch
BranchTrueFalseTotal
if ($node->[0] == 1) { } 4495 706 5201
6224 4495 push @pairs, [ $node->[1], 1 ];
6225 4495 ▶ if ($nan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nan) { } 221 4274 4495
6226 221 my $v = $x->[ $node->[1] ];
6227 221 ▶ $node = ( defined($v) && $v < $node->[2] ) ? $node->[3] : $node->[4];
Branch: 1 branch
BranchTrueFalseTotal
defined $v && $v < $node->[2] ? : 43 178 221
Condition100%3/3
defined $v and $v < $node->[2]
!ll&&!rl&&r
6411443
MC/DC100%2/2
defined $v and $v < $node->[2]
defined $v $v < $node->[2]
Truth table100%3/3
A and B
A= defined $vB= $v < $node->[2]
ABresult
0X0
100
111
6228 } else {
6229 4274 ▶ $node = ( $x->[ $node->[1] ] // 0 ) < $node->[2] ? $node->[3] : $node->[4];
Branch: 1 branch
BranchTrueFalseTotal
($$x[$node->[1]] // 0) < $node->[2] ? : 1511 2763 4274
Condition50%1/2
$$x[$node->[1]] // 0
l!l
42740
MC/DC0%0/1
$$x[$node->[1]] // 0
$$x[$node->[1]]
Truth table50%1/2
A
A= $$x[$node->[1]]
Aresult
11
00
6230 }
6231 } else { # [2, \@idx, \@coef, b, left, right]
6232 706 my ( $idx, $coef, $b ) = ( $node->[1], $node->[2], $node->[3] );
6233  
6234 706 ▶ my @parts = map { abs( $coef->[$_] * ( $x->[ $idx->[$_] ] // 0 ) ) } 0 .. $#$idx;
Condition50%1/2
$$x[$idx->[$_]] // 0
l!l
20940
MC/DC0%0/1
$$x[$idx->[$_]] // 0
$$x[$idx->[$_]]
Truth table50%1/2
A
A= $$x[$idx->[$_]]
Aresult
11
00
6235 706 my $part_total = 0;
6236 706 $part_total += $_ for @parts;
6237 push @pairs, $part_total > 0
6238 2082 ? ( map { [ $idx->[$_], $parts[$_] / $part_total ] } 0 .. $#$idx )
6239 706 ▶ : ( map { [ $idx->[$_], 1 / scalar @$idx ] } 0 .. $#$idx );
Branch: 1 branch
BranchTrueFalseTotal
$part_total > 0 ? : 698 8 706
6240  
6241 706 ▶ if ($nan) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nan) { } 0 706 706
6242 0 my $dot = 0.0;
6243 0 my $missing = 0;
6244 0 for ( 0 .. $#$idx ) {
6245 0 my $v = $x->[ $idx->[$_] ];
6246 0 ▶ if ( !defined $v ) { $missing = 1; last }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $v) 0 0 0
6247 0 $dot += $coef->[$_] * $v;
6248 }
6249 0 ▶ $node = ( !$missing && $dot <= $b ) ? $node->[4] : $node->[5];
Branch: 1 branch
BranchTrueFalseTotal
!$missing && $dot <= $b ? : 0 0 0
Condition0%0/3
not $missing and $dot <= $b
!ll&&!rl&&r
000
MC/DC0%0/2
not $missing and $dot <= $b
not $missing $dot <= $b
Truth table0%0/3
not(A) and B
A= not $missingB= $dot <= $b
ABresult
0X0
100
111
6250 } else {
6251 706 my $dot = 0.0;
6252 706 ▶ $dot += $coef->[$_] * ( $x->[ $idx->[$_] ] // 0 ) for 0 .. $#$idx;
Condition50%1/2
$$x[$idx->[$_]] // 0
l!l
20940
MC/DC0%0/1
$$x[$idx->[$_]] // 0
$$x[$idx->[$_]]
Truth table50%1/2
A
A= $$x[$idx->[$_]]
Aresult
11
00
6253 706 ▶ $node = $dot <= $b ? $node->[4] : $node->[5];
Branch: 1 branch
BranchTrueFalseTotal
$dot <= $b ? : 352 354 706
6254 }
6255 } ## end else [ if ( $node->[0] == _NODE_AXIS ) ]
6256 5201 $depth++;
6257 } ## end while ( $node->[0] )
6258 1160 return ( $depth + _c( $node->[1] ), \@pairs ); # leaf size at slot 1
6259 } ## end sub _path_length_explain
6260  
6261 # Turn one sample's per-tree walks into local-DIFFI feature credit --
6262 # see _path_length_explain's comment for the weighting and what was
6263 # tried instead. A plain function so the Online class can reuse it on
6264 # its own walks.
6265 #
6266 # Args:
6267 # $walks :: arrayref of one [ $path_length, $pairs ] per tree, exactly as
6268 # _path_length_explain returns them. Trees that contributed no
6269 # walk are simply absent.
6270 # $nf :: the model's feature count, which fixes the returned width.
6271 #
6272 # Returns: arrayref of $nf raw credit totals, indexed by feature. These
6273 # are unnormalised -- _credit_to_features turns them into shares. All
6274 # zeroes when no tree isolated the sample faster than the slowest one.
6275 #
6276 # Example:
6277 # my @walks = map { [ _path_length_explain( $x, $_, 0 ) ] } @$trees;
6278 # my $credit = _walks_to_credit( \@walks, 2 ); # [ 0.51, 0.09 ]
6279 21 ▶sub _walks_to_credit {
Subroutine _walks_to_credit: called CC=9 SCAR=22.8
6280 21 my ( $walks, $nf ) = @_;
6281 21 my $hmax = 0;
6282 21 ▶ for (@$walks) { $hmax = $_->[0] if $_->[0] > $hmax }
Branch: 1 branch
BranchTrueFalseTotal
if $_->[0] > $hmax 70 1190 1260
6283 21 my $credit = [ (0) x $nf ];
6284 21 for my $walk (@$walks) {
6285 1260 my ( $h, $pairs ) = @$walk;
6286 1260 ▶ next unless @$pairs && $h > 0 && $hmax > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless @$pairs and $h > 0 and $hmax > 0 0 1260 1260
Condition33%2/6
@$pairs and $h > 0 and $hmax > 0
!ll&&!rl&&r
001260
@$pairs and $h > 0
!ll&&!rl&&r
001260
MC/DC0%0/3
@$pairs and $h > 0 and $hmax > 0
@$pairs $h > 0 $hmax > 0
Truth table25%1/4
A and B and C
A= @$pairsB= $h > 0C= $hmax > 0
ABCresult
0XX0
10X0
1100
1111
6287 1260 my $w = 1.0 / $h - 1.0 / $hmax;
6288 1260 ▶ next if $w <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $w <= 0 31 1229 1260
6289 1229 $credit->[ $_->[0] ] += $w * $_->[1] for @$pairs;
6290 }
6291 21 return $credit;
6292 } ## end sub _walks_to_credit
6293  
6294 # Turn one sample's accumulated per-feature path credit into the sorted
6295 # features list explain_samples returns. Weights are the credit shares
6296 # (summing to 1); a sample that never crossed a split node (all-leaf
6297 # trees) carries no information, so every weight stays 0 rather than
6298 # inventing a uniform split. A plain function, not a method: the
6299 # Online class shapes its explanations through this too.
6300 #
6301 # Args:
6302 # $names :: the model's feature_names arrayref, or undef when the model
6303 # has none -- then every name comes back undef.
6304 # $credit :: the raw per-feature credit from _walks_to_credit. Its
6305 # length fixes how many features are reported.
6306 # $row :: the sample being explained, an arrayref, so each feature can
6307 # report the value it actually had.
6308 #
6309 # Returns: arrayref of hashrefs, one per feature, sorted by descending
6310 # weight with the feature index breaking ties. Each holds index, name,
6311 # weight (a share in [0, 1], summing to 1 unless every credit was 0) and
6312 # value.
6313 #
6314 # Example:
6315 # _credit_to_features( [ 'cpu', 'mem' ], [ 0.51, 0.09 ], [ 0.9, 0.4 ] );
6316 # # [ { index => 0, name => 'cpu', weight => 0.85, value => 0.9 },
6317 # # { index => 1, name => 'mem', weight => 0.15, value => 0.4 } ]
6318 21 ▶sub _credit_to_features {
Subroutine _credit_to_features: called CC=5 SCAR=16.6
6319 21 my ( $names, $credit, $row ) = @_;
6320 21 my $total = 0;
6321 21 $total += $_ for @$credit;
6322 my @features = map {
6323 21 {
6324 63 ▶ index => $_,
Branch: 2 branches
BranchTrueFalseTotal
$names ? : 3 60 63
$total > 0 ? : 63 0 63
6325 name => $names ? $names->[$_] : undef,
6326 weight => $total > 0 ? $credit->[$_] / $total : 0,
6327 value => $row->[$_],
6328 }
6329 } 0 .. $#$credit;
6330 21 ▶ return [ sort { $b->{weight} <=> $a->{weight} || $a->{index} <=> $b->{index} } @features ];
Condition33%1/3
$Algorithm::Classifier::IsolationForest::b->{'weight'} <=> $Algorithm::Classifier::IsolationForest::a->{'weight'} || $Algorithm::Classifier::IsolationForest::a->{'index'} <=> $Algorithm::Classifier::IsolationForest::b->{'index'}
l!l&&r!l&&!r
4900
MC/DC0%0/2
$Algorithm::Classifier::IsolationForest::b->{'weight'} <=> $Algorithm::Classifier::IsolationForest::a->{'weight'} || $Algorithm::Classifier::IsolationForest::a->{'index'} <=> $Algorithm::Classifier::IsolationForest::b->{'index'}
$Algorithm::Classifier::IsolationForest::b->{'weight'} <=> $Algorithm::Classifier::IsolationForest::a->{'weight'} $Algorithm::Classifier::IsolationForest::a->{'index'} <=> $Algorithm::Classifier::IsolationForest::b->{'index'}
Truth table33%1/3
A || B
A= $Algorithm::Classifier::IsolationForest::b->{'weight'} <=> $Algorithm::Classifier::IsolationForest::a->{'weight'}B= $Algorithm::Classifier::IsolationForest::a->{'index'} <=> $Algorithm::Classifier::IsolationForest::b->{'index'}
ABresult
1X1
011
000
6331 } ## end sub _credit_to_features
6332  
6333 # Ablation counterpart of _credit_to_features: deltas are score drops
6334 # (score(original) - score(feature substituted with its baseline));
6335 # weight is each positive delta's share of the positive total, keeping
6336 # weights in [0, 1] like the path method's. A negative delta -- the
6337 # substitution made the sample MORE anomalous, possible with correlated
6338 # features -- keeps its sign in delta but contributes weight 0.
6339 #
6340 # Args:
6341 # $names :: the model's feature_names arrayref, or undef when the model
6342 # has none -- then every name comes back undef.
6343 # $deltas :: arrayref of per-feature score drops. Its length fixes how
6344 # many features are reported.
6345 # $row :: the sample being explained, an arrayref, so each feature can
6346 # report the value it actually had.
6347 # $baselines :: the per-feature substitution values the deltas were
6348 # measured against, reported alongside them.
6349 #
6350 # Returns: arrayref of hashrefs, one per feature, sorted by descending
6351 # weight with the feature index breaking ties. Each holds index, name,
6352 # delta (signed), weight (a share in [0, 1]), value and baseline.
6353 #
6354 # Example:
6355 # _deltas_to_features( [ 'cpu', 'mem' ], [ 0.21, -0.02 ],
6356 # [ 0.9, 0.4 ], [ 0.5, 0.5 ] );
6357 # # cpu first with weight 1; mem keeps delta -0.02 but weight 0
6358 32 ▶sub _deltas_to_features {
Subroutine _deltas_to_features: called CC=7 SCAR=19.5
6359 32 my ( $names, $deltas, $row, $baselines ) = @_;
6360 32 my $pos_total = 0;
6361 32 ▶ for (@$deltas) { $pos_total += $_ if $_ > 0 }
Branch: 1 branch
BranchTrueFalseTotal
if $_ > 0 48 48 96
6362 my @features = map {
6363 32 {
6364 96 ▶ index => $_,
Branch: 2 branches
BranchTrueFalseTotal
$names ? : 6 90 96
$pos_total > 0 && $deltas->[$_] > 0 ? : 48 48 96
Condition66%2/3
$pos_total > 0 and $deltas->[$_] > 0
!ll&&!rl&&r
04848
MC/DC50%1/2
$pos_total > 0 and $deltas->[$_] > 0
$pos_total > 0 $deltas->[$_] > 0
Truth table66%2/3
A and B
A= $pos_total > 0B= $deltas->[$_] > 0
ABresult
0X0
100
111
6365 name => $names ? $names->[$_] : undef,
6366 delta => $deltas->[$_],
6367 weight => ( $pos_total > 0 && $deltas->[$_] > 0 ) ? $deltas->[$_] / $pos_total : 0,
6368 value => $row->[$_],
6369 baseline => $baselines->[$_],
6370 }
6371 } 0 .. $#$deltas;
6372 32 ▶ return [ sort { $b->{weight} <=> $a->{weight} || $a->{index} <=> $b->{index} } @features ];
Condition66%2/3
$Algorithm::Classifier::IsolationForest::b->{'weight'} <=> $Algorithm::Classifier::IsolationForest::a->{'weight'} || $Algorithm::Classifier::IsolationForest::a->{'index'} <=> $Algorithm::Classifier::IsolationForest::b->{'index'}
l!l&&r!l&&!r
50220
MC/DC0%0/2
$Algorithm::Classifier::IsolationForest::b->{'weight'} <=> $Algorithm::Classifier::IsolationForest::a->{'weight'} || $Algorithm::Classifier::IsolationForest::a->{'index'} <=> $Algorithm::Classifier::IsolationForest::b->{'index'}
$Algorithm::Classifier::IsolationForest::b->{'weight'} <=> $Algorithm::Classifier::IsolationForest::a->{'weight'} $Algorithm::Classifier::IsolationForest::a->{'index'} <=> $Algorithm::Classifier::IsolationForest::b->{'index'}
Truth table66%2/3
A || B
A= $Algorithm::Classifier::IsolationForest::b->{'weight'} <=> $Algorithm::Classifier::IsolationForest::a->{'weight'}B= $Algorithm::Classifier::IsolationForest::a->{'index'} <=> $Algorithm::Classifier::IsolationForest::b->{'index'}
ABresult
1X1
011
000
6373 } ## end sub _deltas_to_features
6374  
6375 # The path-credit explanation: one pure-Perl instrumented walk per tree
6376 # per sample. The reported score still comes from score_samples so it
6377 # is bit-identical to what the user saw when the sample got flagged
6378 # (and carries the right semantics under voting => 'majority').
6379 #
6380 # Args:
6381 # $rows :: the samples to explain, an arrayref of feature-value
6382 # arrayrefs. Raw undef cells are fine.
6383 #
6384 # Returns: arrayref of one hashref per row, in input order, each holding
6385 # score, method (always 'path') and features -- the sorted per-feature
6386 # list _credit_to_features builds.
6387 #
6388 # Example:
6389 # my $out = $self->_explain_path( [ [ 8.1, 0.2 ] ] );
6390 # $out->[0]{features}[0]{name}; # the feature most responsible
6391 13 ▶sub _explain_path {
Subroutine _explain_path: called CC=3 SCAR=11.0
6392 13 my ( $self, $rows ) = @_;
6393 13 my $scores = $self->score_samples($rows);
6394 13 my $prepared = $self->_prepare_perl_input($rows);
6395 13 ▶ my $nan = $self->{missing} eq 'nan' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'missing'} eq 'nan' ? : 1 12 13
6396 13 my $nf = $self->{n_features};
6397 13 my $names = $self->{feature_names};
6398 13 my $trees = $self->{trees};
6399  
6400 13 my @out;
6401 13 for my $i ( 0 .. $#$prepared ) {
6402 19 my @walks = map { [ _path_length_explain( $prepared->[$i], $_, $nan ) ] } @$trees;
6403 19 push @out,
6404 {
6405 score => $scores->[$i],
6406 method => 'path',
6407 features => _credit_to_features( $names, _walks_to_credit( \@walks, $nf ), $prepared->[$i] ),
6408 };
6409 }
6410 13 return \@out;
6411 } ## end sub _explain_path
6412  
6413 # The counterfactual explanation: every row followed by its n_features
6414 # single-feature baseline substitutions, all scored as ONE batch so the
6415 # whole thing runs through score_samples once (C-accelerated when
6416 # available) instead of n_features+1 separate scoring calls.
6417 #
6418 # Args:
6419 # $rows :: the samples to explain, an arrayref of feature-value
6420 # arrayrefs. Raw undef cells are fine.
6421 #
6422 # Returns: arrayref of one hashref per row, in input order, each holding
6423 # score, method (always 'ablation') and features -- the sorted per-feature
6424 # list _deltas_to_features builds. Croaks by way of _ablation_baselines
6425 # when the model has no stored baselines.
6426 #
6427 # Example:
6428 # my $out = $self->_explain_ablation( [ [ 8.1, 0.2 ] ] );
6429 # $out->[0]{features}[0]{delta}; # score drop from neutralising it
6430 23 ▶sub _explain_ablation {
Subroutine _explain_ablation: called CC=4 SCAR=13.9
6431 23 my ( $self, $rows ) = @_;
6432 23 my $nf = $self->{n_features};
6433 23 my $names = $self->{feature_names};
6434 23 my $baselines = $self->_ablation_baselines;
6435  
6436 22 my @batch;
6437 22 for my $row (@$rows) {
6438 29 push @batch, $row;
6439 29 for my $f ( 0 .. $nf - 1 ) {
6440 87 my @variant = @$row;
6441 87 $variant[$f] = $baselines->[$f];
6442 87 push @batch, \@variant;
6443 }
6444 }
6445 22 my $scores = $self->score_samples( \@batch );
6446  
6447 22 my @out;
6448 22 for my $i ( 0 .. $#$rows ) {
6449 29 my $base = $i * ( $nf + 1 );
6450 29 my $score = $scores->[$base];
6451 29 my @deltas = map { $score - $scores->[ $base + 1 + $_ ] } 0 .. $nf - 1;
6452 29 push @out,
6453 {
6454 score => $score,
6455 method => 'ablation',
6456 features => _deltas_to_features( $names, \@deltas, $rows->[$i], $baselines ),
6457 };
6458 } ## end for my $i ( 0 .. $#$rows )
6459 22 return \@out;
6460 } ## end sub _explain_ablation
6461  
6462 # The per-feature substitution values ablation uses: the training-data
6463 # medians fit() stores, falling back to the impute fill for models
6464 # saved before baseline support (better than refusing outright -- the
6465 # fill IS a typical value, just impute_with's statistic rather than
6466 # always-median).
6467 #
6468 # Args: none beyond the model itself.
6469 #
6470 # Returns: an arrayref of n_features baseline values. Croaks when neither
6471 # the stored baselines nor an impute fill of the right width is available,
6472 # pointing the caller at method => 'path' or a refit.
6473 #
6474 # Example:
6475 # my $baselines = $self->_ablation_baselines; # [ 0.5, 0.5, 1.0 ]
6476 23 ▶sub _ablation_baselines {
Subroutine _ablation_baselines: called CC=4 SCAR=13.9
6477 23 my ($self) = @_;
6478 23 my $nf = $self->{n_features};
6479 23 for my $candidate ( $self->{feature_baselines}, $self->{missing_fill} ) {
6480 25 ▶ return $candidate if ref $candidate eq 'ARRAY' && @$candidate == $nf;
Branch: 1 branch
BranchTrueFalseTotal
if ref $candidate eq "ARRAY" and @$candidate == $nf 22 3 25
Condition66%2/3
ref $candidate eq "ARRAY" and @$candidate == $nf
!ll&&!rl&&r
3022
MC/DC50%1/2
ref $candidate eq "ARRAY" and @$candidate == $nf
ref $candidate eq "ARRAY" @$candidate == $nf
Truth table66%2/3
A and B
A= ref $candidate eq "ARRAY"B= @$candidate == $nf
ABresult
0X0
100
111
6481 }
6482 1 croak "explain_samples: this model has no stored feature baselines "
6483 . "(saved by a version before ablation explanation support?); "
6484 . "refit to enable method => 'ablation', or explain with "
6485 . "method => 'path'";
6486 } ## end sub _ablation_baselines
6487  
6488 # Recursively convert a version-0 hash-based tree node to the version-1
6489 # array format. Called by from_json when loading an old saved model.
6490 #
6491 # Args:
6492 # $node :: a version-0 node hashref. A leaf carries leaf and size; an
6493 # axis node attr, split, left and right; an oblique node idx,
6494 # coef, b, left and right.
6495 #
6496 # Returns: the same subtree in the version-1 arrayref layout -- [0, size],
6497 # [1, attr, split, left, right] or [2, \@idx, \@coef, b, left, right].
6498 #
6499 # Example:
6500 # _hash_node_to_array( { leaf => 1, size => 3 } ); # [ 0, 3 ]
6501 0 ▶sub _hash_node_to_array {
Subroutine _hash_node_to_array: not called CC=3 SCAR=24.8
6502 0 my ($node) = @_;
6503 0 ▶ if ( $node->{leaf} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($node->{'leaf'}) { } 0 0 0
elsif (exists $node->{'attr'}) { } 0 0 0
6504 0 return [ _NODE_LEAF, $node->{size} ];
6505 } elsif ( exists $node->{attr} ) {
6506 return [
6507 _NODE_AXIS, $node->{attr},
6508 $node->{split}, _hash_node_to_array( $node->{left} ),
6509 0 _hash_node_to_array( $node->{right} ),
6510 ];
6511 } else {
6512 return [
6513 _NODE_OBLIQUE, $node->{idx}, $node->{coef}, $node->{b},
6514 _hash_node_to_array( $node->{left} ),
6515 0 _hash_node_to_array( $node->{right} ),
6516 ];
6517 }
6518 } ## end sub _hash_node_to_array
6519  
6520 # ---------------------------------------------------------------------------
6521 # _pack_tree($root) -- flatten one tree into three packed buffers.
6522 #
6523 # Returns ($nodes_packed, $idx_packed, $val_packed) where:
6524 # nodes_packed: 6 doubles per node (see score_all_xs comment above)
6525 # idx_packed: int32 feature indices for every oblique-node coefficient
6526 # val_packed: double values matching idx_packed one-for-one
6527 #
6528 # Storing idx and val in separate buffers (SoA) instead of interleaved
6529 # doubles lets the oblique dot product's SIMD inner loop run over a
6530 # contiguous val[] stream without a per-iteration (int) cast, and
6531 # halves the index bandwidth (int32 vs double). The same `coff`
6532 # offset addresses paired entries in both buffers.
6533 #
6534 # Nodes are numbered in DFS pre-order: the root is always index 0 and
6535 # children always get indices larger than their parent's.
6536 #
6537 # The C backend does this walk in pack_tree_xs, which is what actually
6538 # runs whenever it is available -- the Perl body below is the fallback
6539 # (no C backend, or a wide-NV perl, where the two would disagree on
6540 # c(size) in the last ulp; see _NV_IS_DOUBLE). Both produce byte-
6541 # identical buffers on an nvsize == 8 perl.
6542 #
6543 # Args:
6544 # $root :: the tree's root node, in the nested arrayref layout
6545 # _build_tree produces.
6546 # $n_features :: the model's feature count, or undef. Only used to spot
6547 # the dense-pack opportunity described above; passing
6548 # undef just skips that optimisation.
6549 #
6550 # Returns: the three-element list ($nodes_packed, $idx_packed,
6551 # $val_packed) -- a 'd*' string of 6 doubles per node, an 'l*' string of
6552 # int32 feature indices, and a 'd*' string of the matching coefficients.
6553 # The latter two are empty strings for an axis-mode tree.
6554 #
6555 # Example:
6556 # my ( $np, $ip, $vp ) = _pack_tree( $self->{trees}[0], $self->{n_features} );
6557 # length($np) / ( 6 * 8 ); # node count
6558 # ---------------------------------------------------------------------------
6559 10725 ▶sub _pack_tree {
Subroutine _pack_tree: called CC=6 SCAR=33.6
6560 10725 my ( $root, $n_features ) = @_;
6561  
6562 10725 ▶ if ( $HAS_C && _NV_IS_DOUBLE ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Algorithm::Classifier::IsolationForest::HAS_C and !!1) 10725 0 10725
Condition50%1/2
$Algorithm::Classifier::IsolationForest::HAS_C and !!1
!ll
010725
MC/DC0%0/1
$Algorithm::Classifier::IsolationForest::HAS_C and !!1
$Algorithm::Classifier::IsolationForest::HAS_C
Truth table50%1/2
A
A= $Algorithm::Classifier::IsolationForest::HAS_C
Aresult
00
11
6563 10725 my ( $nodes_packed, $idx_packed, $val_packed ) = ( '', '', '' );
6564 10725 ▶ pack_tree_xs( $root, $n_features // -1, $nodes_packed, $idx_packed, $val_packed );
Condition50%1/2
$n_features // -1
l!l
107250
MC/DC0%0/1
$n_features // -1
$n_features
Truth table50%1/2
A
A= $n_features
Aresult
11
00
6565 10725 return ( $nodes_packed, $idx_packed, $val_packed );
6566 }
6567  
6568 0 my ( @node_data, @coef_idx, @coef_val );
6569  
6570 0 my $assign;
6571 0 ▶ $assign = sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
6572 0 my ($node) = @_;
6573 0 my $my_idx = scalar @node_data;
6574 0 push @node_data, undef; # reserve slot; filled in after children
6575  
6576 0 ▶ if ( $node->[0] == _NODE_LEAF ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($node->[0] == 0) { } 0 0 0
elsif ($node->[0] == 1) { } 0 0 0
6577  
6578 # Slot 2 carries c(size) precomputed, so the C scoring loop
6579 # adds it straight to the depth instead of paying a log()
6580 # per point per tree at every leaf hit. _c is the same
6581 # function the pure-Perl scorer uses, so both backends keep
6582 # producing bit-identical path lengths.
6583 0 $node_data[$my_idx] = [ 0.0, $node->[1] + 0.0, _c( $node->[1] ), 0.0, 0.0, 0.0 ];
6584 } elsif ( $node->[0] == _NODE_AXIS ) {
6585 0 my $li = $assign->( $node->[3] );
6586 0 my $ri = $assign->( $node->[4] );
6587 0 $node_data[$my_idx] = [
6588 1.0,
6589 $node->[1] + 0.0, # attr
6590 $node->[2] + 0.0, # split
6591 $li + 0.0,
6592 $ri + 0.0,
6593 0.0,
6594 ];
6595 } else { # _NODE_OBLIQUE
6596 0 my ( $idx_arr, $coef_arr, $b ) = ( $node->[1], $node->[2], $node->[3] );
6597 0 my $coef_off = scalar @coef_idx;
6598 0 my $num = scalar @$idx_arr;
6599  
6600 # Dense-pack opportunity: when this oblique split uses
6601 # every feature (extension_level == n_features - 1 and
6602 # all features vary), pack the coefficients in feature
6603 # order so val[k] is the coefficient for feature k. The
6604 # C scoring path then detects `nf == n_feats` and switches
6605 # to a no-gather inner loop (dot += val[k] * xi[k]) that
6606 # auto-vectorizes cleanly with FMA.
6607 0 ▶ if ( defined $n_features && $num == $n_features ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $n_features and $num == $n_features) { } 0 0 0
Condition0%0/3
defined $n_features and $num == $n_features
!ll&&!rl&&r
000
MC/DC0%0/2
defined $n_features and $num == $n_features
defined $n_features $num == $n_features
Truth table0%0/3
A and B
A= defined $n_featuresB= $num == $n_features
ABresult
0X0
100
111
6608 0 my %coef_for;
6609 0 @coef_for{@$idx_arr} = @$coef_arr;
6610 0 for my $k ( 0 .. $n_features - 1 ) {
6611 0 push @coef_idx, $k;
6612 0 push @coef_val, $coef_for{$k} + 0.0;
6613 }
6614 } else {
6615 0 for my $i ( 0 .. $num - 1 ) {
6616 0 push @coef_idx, int( $idx_arr->[$i] );
6617 0 push @coef_val, $coef_arr->[$i] + 0.0;
6618 }
6619 }
6620  
6621 0 my $li = $assign->( $node->[4] );
6622 0 my $ri = $assign->( $node->[5] );
6623 0 $node_data[$my_idx] = [ 2.0, $coef_off + 0.0, $num + 0.0, $li + 0.0, $ri + 0.0, $b + 0.0, ];
6624 } ## end else [ if ( $node->[0] == _NODE_LEAF ) ]
6625 0 return $my_idx;
6626 0 }; ## end $assign = sub
6627 0 $assign->($root);
6628  
6629 0 my $nodes_packed = pack( 'd*', map { @$_ } @node_data );
6630 0 ▶ my $idx_packed = @coef_idx ? pack( 'l*', @coef_idx ) : pack('l*');
Branch: 1 branch
BranchTrueFalseTotal
@coef_idx ? : 0 0 0
6631 0 ▶ my $val_packed = @coef_val ? pack( 'd*', @coef_val ) : pack('d*');
Branch: 1 branch
BranchTrueFalseTotal
@coef_val ? : 0 0 0
6632 0 return ( $nodes_packed, $idx_packed, $val_packed );
6633 } ## end sub _pack_tree
6634  
6635 # Build packed C-ready representations for all trees and store them in
6636 # $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val}.
6637 # Called after fit() and from_json() when _use_c is true. n_features is
6638 # threaded through so _pack_tree can spot the dense-pack opportunity.
6639 #
6640 # Args: none beyond the model itself, which must already hold its trees.
6641 #
6642 # Returns: nothing. Leaves _c_nodes, _c_coef_idx and _c_coef_val holding
6643 # one packed string per tree, in tree order -- the form score_all_xs and
6644 # friends expect.
6645 #
6646 # Example:
6647 # $self->{trees} = $self->_build_forest_c( $train, $psi, $limit, 100 );
6648 # $self->_rebuild_c_trees; # scoring can now take the C path
6649 209 ▶sub _rebuild_c_trees {
Subroutine _rebuild_c_trees: called CC=2 SCAR=6.9
6650 209 my ($self) = @_;
6651 209 my ( @c_nodes, @c_coef_idx, @c_coef_val );
6652 209 for my $tree ( @{ $self->{trees} } ) {
6653 10725 my ( $np, $ip, $vp ) = _pack_tree( $tree, $self->{n_features} );
6654 10725 push @c_nodes, $np;
6655 10725 push @c_coef_idx, $ip;
6656 10725 push @c_coef_val, $vp;
6657 }
6658 209 $self->{_c_nodes} = \@c_nodes;
6659 209 $self->{_c_coef_idx} = \@c_coef_idx;
6660 209 $self->{_c_coef_val} = \@c_coef_val;
6661 } ## end sub _rebuild_c_trees
6662  
6663 # Guard for every method that needs a forest to work with. Called at the
6664 # top of the scoring and packing entry points so an unfitted model fails
6665 # with one clear message instead of an obscure error deeper in.
6666 #
6667 # Args: none beyond the model itself.
6668 #
6669 # Returns: nothing on success. Croaks when the model holds no trees --
6670 # either never fitted, or constructed but not yet loaded from JSON.
6671 #
6672 # Example:
6673 # $self->_check_fitted; # croaks with "model is not fitted yet"
6674 17666 ▶sub _check_fitted {
Subroutine _check_fitted: called CC=3 SCAR=11.0
6675 17666 my ($self) = @_;
6676 croak "model is not fitted yet; call fit() first"
6677 17666 ▶ unless ref $self->{trees} eq 'ARRAY' && @{ $self->{trees} };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self->{"trees"} eq "ARRAY" and @{$self->{"trees"};} 9 17657 17666
Condition66%2/3
ref $self->{"trees"} eq "ARRAY" and @{$self->{"trees"};}
!ll&&!rl&&r
0917657
MC/DC50%1/2
ref $self->{"trees"} eq "ARRAY" and @{$self->{"trees"};}
ref $self->{"trees"} eq "ARRAY" @{$self->{"trees"};}
Truth table66%2/3
A and B
A= ref $self->{"trees"} eq "ARRAY"B= @{$self->{"trees"};}
ABresult
0X0
100
111
6678 }
6679  
6680 # ---------------------------------------------------------------------------
6681 # Optional Algorithm::ToNumberMunger integration -- see the MUNGERS POD
6682 # section. Both helpers are plain functions (not methods) so the Online
6683 # class's delegating methods can hand them their own $self: the plan and
6684 # spec live in the same hash slots on either class.
6685 # ---------------------------------------------------------------------------
6686  
6687 # Validate a feature_descriptions hash against the feature names: every
6688 # described feature must exist (a description for one that does not is
6689 # either a typo or a stale leftover from a schema change) and every
6690 # description must be a plain string. Partial coverage is fine. A plain
6691 # function, like the munger helpers, so both classes and the prototype
6692 # validator can call it.
6693 #
6694 # Args:
6695 # $tags :: the model's feature_names, an arrayref of strings. Must be
6696 # non-empty -- there is nothing to validate against otherwise.
6697 # $fd :: the feature_descriptions hashref, keyed by feature name with
6698 # plain strings as values.
6699 #
6700 # Returns: 1 when the descriptions are usable. Croaks naming the offending
6701 # key when one is not a known feature, when a value is a reference, or when
6702 # either argument is the wrong shape.
6703 #
6704 # Example:
6705 # _validate_feature_descriptions( [ 'cpu', 'mem' ],
6706 # { cpu => 'load average over 1m' } ); # 1; partial coverage is fine
6707 35 ▶sub _validate_feature_descriptions {
Subroutine _validate_feature_descriptions: called CC=7 SCAR=19.5
6708 35 my ( $tags, $fd ) = @_;
6709 35 ▶ croak "feature_descriptions must be a hashref of 'feature name => description'"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $fd eq "HASH" 0 35 35
6710 unless ref $fd eq 'HASH';
6711 35 ▶ croak "feature_descriptions requires feature_names to validate against"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tags eq "ARRAY" and @$tags 1 34 35
Condition66%2/3
ref $tags eq "ARRAY" and @$tags
!ll&&!rl&&r
1034
MC/DC50%1/2
ref $tags eq "ARRAY" and @$tags
ref $tags eq "ARRAY" @$tags
Truth table66%2/3
A and B
A= ref $tags eq "ARRAY"B= @$tags
ABresult
0X0
100
111
6712 unless ref $tags eq 'ARRAY' && @$tags;
6713 34 my %known = map { $_ => 1 } @$tags;
6714 34 for my $k ( sort keys %$fd ) {
6715 croak "feature_descriptions describes '$k', which is not in feature_names"
6716 34 ▶ unless $known{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless $known{$k} 3 31 34
6717 croak "feature_descriptions entry for '$k' must be a plain string"
6718 31 ▶ if ref $fd->{$k};
Branch: 1 branch
BranchTrueFalseTotal
if ref $fd->{$k} 1 30 31
6719 }
6720 30 return 1;
6721 } ## end sub _validate_feature_descriptions
6722  
6723 # Compile a munger spec against the model's feature names. Requires
6724 # Algorithm::ToNumberMunger on demand -- it is an optional dependency --
6725 # and lets its compile() croak on any spec problem.
6726 #
6727 # Args:
6728 # $tags :: the model's feature_names, an arrayref of strings in column
6729 # order. Must be non-empty.
6730 # $mungers :: the munger spec hashref, shaped as
6731 # Algorithm::ToNumberMunger->compile expects it.
6732 #
6733 # Returns: the compiled plan object. Croaks when feature_names are
6734 # missing, when the module cannot be loaded, or when compile() rejects the
6735 # spec.
6736 #
6737 # Example:
6738 # my $plan = _compile_mungers( [ 'method', 'path_len' ],
6739 # { method => { munger => 'http_method_enum', default => -1 } } );
6740 15 ▶sub _compile_mungers {
Subroutine _compile_mungers: called CC=4 SCAR=14.8
6741 15 my ( $tags, $mungers ) = @_;
6742 15 ▶ croak "this model has mungers but no feature_names to compile them against"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $tags eq "ARRAY" and @$tags 0 15 15
Condition33%1/3
ref $tags eq "ARRAY" and @$tags
!ll&&!rl&&r
0015
MC/DC0%0/2
ref $tags eq "ARRAY" and @$tags
ref $tags eq "ARRAY" @$tags
Truth table33%1/3
A and B
A= ref $tags eq "ARRAY"B= @$tags
ABresult
0X0
100
111
6743 unless ref $tags eq 'ARRAY' && @$tags;
6744 15 local $@;
6745 15 ▶ eval { require Algorithm::ToNumberMunger; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Algorithm::ToNumberMunger; 1 } } or croak('this model has mungers configured but Algorithm::ToNumberMunger ' . "could not be loaded; install it to use tagged data with this model: $@") 15 0 15
6746 or croak "this model has mungers configured but Algorithm::ToNumberMunger "
6747 . "could not be loaded; install it to use tagged data with this model: $@";
6748 15 return Algorithm::ToNumberMunger->compile(
6749 tags => $tags,
6750 mungers => $mungers,
6751 );
6752 } ## end sub _compile_mungers
6753  
6754 # The compiled plan for this model, or undef when no mungers are
6755 # configured. Compiled lazily (memoised in _munger_plan) so from_json
6756 # does not need Algorithm::ToNumberMunger installed unless tagged data
6757 # is actually used; new() populates the slot eagerly instead, surfacing
6758 # spec errors at construction.
6759 #
6760 # A plain function rather than a method, like the two helpers above, so the
6761 # Online class can hand it its own $self.
6762 #
6763 # Args: none beyond the model, which is passed positionally.
6764 #
6765 # Returns: the compiled Algorithm::ToNumberMunger plan, or undef when the
6766 # model carries no munger spec. The plan is memoised in _munger_plan, so
6767 # the compile happens at most once per model.
6768 #
6769 # Example:
6770 # if ( my $plan = _plan($self) ) {
6771 # my $vec = $plan->apply_named( { method => 'GET', host => 'h' } );
6772 # }
6773 1084 ▶sub _plan {
Subroutine _plan: called CC=3 SCAR=11.0
6774 1084 my ($self) = @_;
6775 1084 ▶ return undef unless $self->{mungers};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"mungers"} 132 952 1084
6776 952 ▶ $self->{_munger_plan} //= _compile_mungers( $self->{feature_names}, $self->{mungers} );
Condition66%2/3
$self->{"_munger_plan"} //= _compile_mungers($self->{"feature_names"}, $self->{"mungers"})
l!l&&r!l&&!r
94750
MC/DC0%0/2
$self->{"_munger_plan"} //= _compile_mungers($self->{"feature_names"}, $self->{"mungers"})
$self->{"_munger_plan"} _compile_mungers($self->{"feature_names"}, $self->{"mungers"})
Truth table66%2/3
A //= B
A= $self->{"_munger_plan"}B= _compile_mungers($self->{"feature_names"}, $self->{"mungers"})
ABresult
1X1
011
000
6777 951 return $self->{_munger_plan};
6778 }
6779  
6780 # Memoised "does this perl have a real fork()?". False on Windows
6781 # without Cygwin; true on every Unix-like platform. fit() consults it
6782 # before honouring parallel_fit, which is how that option degrades to a
6783 # serial fit instead of failing.
6784 #
6785 # Args: none.
6786 #
6787 # Returns: 1 when Config's d_fork is defined, 0 otherwise. Config is
6788 # loaded on the first call only and the answer cached for the process.
6789 #
6790 # Example:
6791 # $self->_fit_trees_parallel(...) if $workers > 1 && _fork_supported();
6792 {
6793 132 my $cached;
6794  
6795 8 ▶ sub _fork_supported {
Subroutine _fork_supported: called CC=4 SCAR=14.2
6796 8 ▶ return $cached if defined $cached;
Branch: 1 branch
BranchTrueFalseTotal
if defined $cached 6 2 8
6797 2 require Config;
6798 $cached
6799 2 ▶ = ( ( $Config::Config{d_fork} || '' ) eq 'define' ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
($Config::Config{'d_fork'} || '') eq 'define' ? : 2 0 2
Condition50%1/2
$Config::Config{'d_fork'} || ''
l!l
20
MC/DC0%0/1
$Config::Config{'d_fork'} || ''
$Config::Config{'d_fork'}
Truth table50%1/2
A
A= $Config::Config{'d_fork'}
Aresult
11
00
6800 2 return $cached;
6801 }
6802 }
6803  
6804 #-------------------------------------------------------------------------------
6805 # Fork-based parallel tree builder. Used by fit() when parallel_fit > 1
6806 # and the platform has a real fork(). Divides n_trees evenly among
6807 # workers; each child seeds its own RNG ($seed + worker_id * 1009 so
6808 # fixed-worker-count runs are reproducible), builds its share (via the
6809 # C builder when _use_c is on, same as the non-parallel path), and
6810 # returns the trees to the parent via Storable on a one-shot pipe.
6811 #
6812 # The trees that come back differ from a serial fit with the same seed
6813 # because the RNG draws happen in a different order -- this is documented
6814 # as part of the parallel_fit contract.
6815 #
6816 # Args:
6817 # $data :: the prepared training set, an arrayref of feature-value
6818 # arrayrefs. Each worker inherits it through the fork, so it is
6819 # never serialised.
6820 # $psi :: the per-tree sub-sample size from _resolve_geometry.
6821 # $limit :: the tree height limit from _resolve_geometry.
6822 # $workers :: how many children to fork. Clamped down to n_trees, since
6823 # a worker with no trees to build is pure overhead.
6824 #
6825 # Returns: an arrayref of all n_trees trees in worker order -- worker 0's
6826 # share first, then worker 1's, and so on, which is what makes the forest
6827 # reproducible. Croaks when a fork or pipe fails, when a worker exits
6828 # non-zero, or when its trees come back unreadable.
6829 #
6830 # Example:
6831 # $self->{trees} = $self->_fit_trees_parallel( $train, 256, 8, 4 );
6832 #-------------------------------------------------------------------------------
6833 132 ▶sub _fit_trees_parallel {
Subroutine _fit_trees_parallel: called CC=16 SCAR=33.1
6834 8 my ( $self, $data, $psi, $limit, $workers ) = @_;
6835 8 require Storable;
6836 8 require POSIX;
6837  
6838 8 my $n_trees = $self->{n_trees};
6839 8 ▶ $workers = $n_trees if $workers > $n_trees;
Branch: 1 branch
BranchTrueFalseTotal
if $workers > $n_trees 1 7 8
6840  
6841 # Divide n_trees as evenly as possible across workers.
6842 8 my @shares;
6843 {
6844 8 my $base = int( $n_trees / $workers );
6845 8 my $extras = $n_trees - $base * $workers;
6846 8 for my $w ( 0 .. $workers - 1 ) {
6847 26 ▶ push @shares, $base + ( $w < $extras ? 1 : 0 );
Branch: 1 branch
BranchTrueFalseTotal
$w < $extras ? : 3 23 26
6848 }
6849 }
6850  
6851 8 my @procs; # { pid, rh, share }
6852 8 for my $w ( 0 .. $workers - 1 ) {
6853 26 my $share = $shares[$w];
6854 26 ▶ next unless $share > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $share > 0 0 26 26
6855  
6856 26 ▶ pipe( my $rh, my $wh ) or croak "pipe failed: $!";
Branch: 1 branch
BranchTrueFalseTotal
pipe my $rh, my $wh or croak("pipe failed: $!") 26 0 26
6857 26 my $pid = fork();
6858 26 ▶ croak "fork failed: $!" unless defined $pid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid 0 26 26
6859  
6860 26 ▶ if ( $pid == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid == 0) 0 26 26
6861 # child
6862 0 close $rh;
6863 0 binmode $wh;
6864 0 ▶ if ( defined $self->{seed} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"seed"}) 0 0 0
6865 0 srand( $self->{seed} + $w * 1009 );
6866 }
6867 # Deliberately never _build_forest_openmp here, even when
6868 # use_openmp_fit is on: if this process (or the parent that
6869 # fork()ed us) already ran any OpenMP region before this
6870 # fork -- including plain score_samples()/predict() with
6871 # the default use_openmp -- libgomp's thread pool exists
6872 # but its worker threads didn't survive the fork. A child
6873 # starting its own #pragma omp parallel region then tries
6874 # to reuse that now-invalid pool and hangs. This is a
6875 # general fork()+libgomp limitation, not fixable from here,
6876 # so forked workers always use the single-threaded C
6877 # builder (or pure Perl) instead. See t/03-fit-determinism.t
6878 # and the NATIVE ACCELERATION docs for the observed hang and
6879 # why parallel_fit + use_openmp_fit isn't composed for real.
6880 0 my $trees;
6881 0 ▶ if ( $self->{_use_c} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_use_c'}) { } 0 0 0
6882 0 $trees = $self->_build_forest_c( $data, $psi, $limit, $share );
6883 } else {
6884 0 my @t;
6885 0 for ( 1 .. $share ) {
6886 0 my $sample = _subsample( $data, $psi );
6887 0 push @t, $self->_build_tree( $sample, 0, $limit );
6888 }
6889 0 $trees = \@t;
6890 }
6891 0 print $wh Storable::freeze($trees);
6892 0 close $wh;
6893 # _exit so we don't run parent END/DESTROY in the child.
6894 0 POSIX::_exit(0);
6895 } ## end if ( $pid == 0 )
6896  
6897 26 close $wh;
6898 26 binmode $rh;
6899 26 push @procs, { pid => $pid, rh => $rh, share => $share };
6900 } ## end for my $w ( 0 .. $workers - 1 )
6901  
6902 # Collect from each pipe in worker order so the canonical tree
6903 # ordering is deterministic (worker 0's trees first, then 1's, ...).
6904 8 my @all_trees;
6905 8 for my $p (@procs) {
6906 26 my $buf;
6907 {
6908 26 local $/;
6909 26 $buf = readline( $p->{rh} );
6910 }
6911 26 close $p->{rh};
6912 26 waitpid( $p->{pid}, 0 );
6913 26 my $exit = $? >> 8;
6914 26 ▶ croak "parallel_fit worker $p->{pid} exited with status $exit"
Branch: 1 branch
BranchTrueFalseTotal
if $exit != 0 0 26 26
6915 if $exit != 0;
6916 26 my $trees = eval { Storable::thaw($buf) };
6917 26 ▶ croak "parallel_fit worker $p->{pid} returned unparseable trees: $@"
Branch: 1 branch
BranchTrueFalseTotal
if $@ or ref $trees ne "ARRAY" 0 26 26
Condition33%1/3
$@ or ref $trees ne "ARRAY"
l!l&&r!l&&!r
0026
MC/DC0%0/2
$@ or ref $trees ne "ARRAY"
$@ ref $trees ne "ARRAY"
Truth table33%1/3
A or B
A= $@B= ref $trees ne "ARRAY"
ABresult
1X1
011
000
6918 if $@ || ref $trees ne 'ARRAY';
6919 26 push @all_trees, @$trees;
6920 } ## end for my $p (@procs)
6921  
6922 8 return \@all_trees;
6923 } ## end sub _fit_trees_parallel
6924  
6925 #-------------------------------------------------------------------------------
6926 # C-accelerated fit(): builds $n_trees trees against $data (a subset or
6927 # the full training set) via build_forest_xs, which does its own
6928 # per-tree subsampling internally. Random draws inside the C builder
6929 # go through Drand01() -- the same generator Perl's rand() uses -- in
6930 # the same call order _subsample/_build_tree used, so the returned
6931 # trees are bit-identical to what the pure-Perl path would build from
6932 # the same RNG state. That's what lets fit() switch backends on the
6933 # existing `use_c` knob instead of a new one.
6934 #
6935 # Args:
6936 # $data :: the prepared training set, an arrayref of feature-value
6937 # arrayrefs. Packed into a flat double buffer here, so undef
6938 # cells are resolved through _pack_args.
6939 # $psi :: the per-tree sub-sample size from _resolve_geometry.
6940 # $limit :: the tree height limit from _resolve_geometry.
6941 # $n_trees :: how many trees to build. A forked worker passes its own
6942 # share rather than the model's full n_trees.
6943 #
6944 # Returns: an arrayref of $n_trees trees in the nested arrayref layout
6945 # _build_tree produces, so callers cannot tell which backend built them.
6946 #
6947 # Example:
6948 # $self->{trees} = $self->_build_forest_c( $train, 256, 8, 100 );
6949 #-------------------------------------------------------------------------------
6950 119 ▶sub _build_forest_c {
Subroutine _build_forest_c: called CC=3 SCAR=11.0
6951 119 my ( $self, $data, $psi, $limit, $n_trees ) = @_;
6952 119 my $n = scalar @$data;
6953 119 my $nf = $self->{n_features};
6954 119 my $x_packed = "\0" x ( $n * $nf * 8 );
6955 119 my ( $mode, $fill ) = $self->_pack_args;
6956 119 pack_input_xs( $data, $x_packed, $n, $nf, $mode, $fill );
6957  
6958 119 ▶ my $mode_flag = $self->{mode} eq 'extended' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'mode'} eq 'extended' ? : 15 104 119
6959 119 ▶ my $ext_level = $self->{extension_level_used} // 0;
Condition100%2/2
$self->{"extension_level_used"} // 0
l!l
15104
MC/DC100%1/1
$self->{"extension_level_used"} // 0
$self->{"extension_level_used"}
Truth table100%2/2
A
A= $self->{"extension_level_used"}
Aresult
11
00
6960  
6961 119 my $trees = [];
6962 119 build_forest_xs( $x_packed, $n, $nf, $n_trees, $psi, $limit, $mode_flag, $ext_level, $trees );
6963 119 return $trees;
6964 } ## end sub _build_forest_c
6965  
6966 #-------------------------------------------------------------------------------
6967 # OpenMP-parallel fit(): builds $n_trees trees across OpenMP threads (one
6968 # tree per thread) via build_forest_openmp_xs. Unlike _build_forest_c,
6969 # random draws come from a thread-private PRNG seeded per tree index
6970 # rather than Drand01() -- Perl's RNG state can't be shared safely
6971 # across OpenMP threads -- so the resulting trees are NOT bit-identical
6972 # to the use_c (serial) or pure-Perl paths for the same seed, though a
6973 # fixed seed + n_trees still reproduce the same trees regardless of
6974 # OMP_NUM_THREADS. This is why it's gated by the separate, opt-in
6975 # use_openmp_fit knob rather than reusing use_c/use_openmp.
6976 #
6977 # Only called from fit()'s non-forked branch. _fit_trees_parallel's
6978 # workers never call this, even when use_openmp_fit is on: a forked
6979 # child starting its own OpenMP region after the parent process has
6980 # used OpenMP for anything (this includes plain score_samples()) can
6981 # hang -- see the comment above that branch for the fork()+libgomp
6982 # hazard this avoids.
6983 #
6984 # build_forest_openmp_xs hands back three arrayrefs of per-tree packed
6985 # buffers (the same SoA layout _pack_tree produces) instead of Perl tree
6986 # structures -- that's how it avoids any Perl API call inside its
6987 # parallel region. _unpack_forest converts them back into the ordinary
6988 # nested-arrayref tree shape so to_json/from_json/_rebuild_c_trees don't
6989 # need to know this path exists.
6990 #
6991 # Args:
6992 # $data :: the prepared training set, an arrayref of feature-value
6993 # arrayrefs. Packed into a flat double buffer here, so undef
6994 # cells are resolved through _pack_args.
6995 # $psi :: the per-tree sub-sample size from _resolve_geometry.
6996 # $limit :: the tree height limit from _resolve_geometry.
6997 # $n_trees :: how many trees to build.
6998 #
6999 # Returns: an arrayref of $n_trees trees in the same nested arrayref layout
7000 # _build_forest_c returns -- identical in shape, though not in content, to
7001 # what the other backends would have built for this seed.
7002 #
7003 # Example:
7004 # $self->{trees} = $self->_build_forest_openmp( $train, 256, 8, 100 );
7005 #-------------------------------------------------------------------------------
7006 7 ▶sub _build_forest_openmp {
Subroutine _build_forest_openmp: called CC=3 SCAR=11.0
7007 7 my ( $self, $data, $psi, $limit, $n_trees ) = @_;
7008 7 my $n = scalar @$data;
7009 7 my $nf = $self->{n_features};
7010 7 my $x_packed = "\0" x ( $n * $nf * 8 );
7011 7 my ( $mode, $fill ) = $self->_pack_args;
7012 7 pack_input_xs( $data, $x_packed, $n, $nf, $mode, $fill );
7013  
7014 7 ▶ my $mode_flag = $self->{mode} eq 'extended' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'mode'} eq 'extended' ? : 5 2 7
7015 7 ▶ my $ext_level = $self->{extension_level_used} // 0;
Condition100%2/2
$self->{"extension_level_used"} // 0
l!l
52
MC/DC100%1/1
$self->{"extension_level_used"} // 0
$self->{"extension_level_used"}
Truth table100%2/2
A
A= $self->{"extension_level_used"}
Aresult
11
00
7016  
7017 7 my ( @nodes, @idx, @val );
7018 7 build_forest_openmp_xs( $x_packed, $n, $nf, $n_trees, $psi, $limit,
7019 $mode_flag, $ext_level, \@nodes, \@idx, \@val, 1 );
7020  
7021 7 return _unpack_forest( \@nodes, \@idx, \@val );
7022 } ## end sub _build_forest_openmp
7023  
7024 # Inverse of _pack_tree's SoA layout: given one tree's packed node
7025 # buffer plus the shared idx/val coefficient buffers, reconstructs the
7026 # ordinary nested-arrayref tree structure _build_tree/_build_node_c
7027 # produce. li/ri fields hold the child's absolute node index, so this
7028 # just follows them recursively from whatever index the caller says the
7029 # root lives at. NOTE: _pack_tree numbers nodes DFS pre-order (root at
7030 # 0), but build_forest_openmp_xs appends nodes post-order (children
7031 # before parent), putting the root LAST -- the caller must pass the
7032 # right root index for the buffer's origin.
7033 #
7034 # Args:
7035 # $nodes :: arrayref of the tree's node doubles, already unpacked, 6 per
7036 # node.
7037 # $idx :: arrayref of the unpacked int32 coefficient feature indices.
7038 # $val :: arrayref of the unpacked coefficient values, matching $idx
7039 # one-for-one.
7040 # $node_i :: which node record to treat as this subtree's root, counting
7041 # in nodes not doubles.
7042 #
7043 # Returns: the subtree as a nested arrayref in _build_tree's layout.
7044 #
7045 # Example:
7046 # my $root = @nodes / 6 - 1; # post-order buffer: root is last
7047 # my $tree = _unpack_node( \@nodes, \@idx, \@val, $root );
7048 12844 ▶sub _unpack_node {
Subroutine _unpack_node: called CC=3 SCAR=11.0
7049 12844 my ( $nodes, $idx, $val, $node_i ) = @_;
7050 12844 my $off = $node_i * 6;
7051 12844 my $type = $nodes->[$off];
7052  
7053 12844 ▶ if ( $type == 0 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type == 0) { } 6582 6262 12844
elsif ($type == 1) { } 1604 4658 6262
7054 6582 return [ _NODE_LEAF, int( $nodes->[ $off + 1 ] ) ];
7055 } elsif ( $type == 1 ) {
7056 my ( $attr, $split, $li, $ri )
7057 1604 = @{$nodes}[ $off + 1 .. $off + 4 ];
7058 return [
7059 1604 _NODE_AXIS, int($attr), $split,
7060 _unpack_node( $nodes, $idx, $val, int($li) ),
7061 _unpack_node( $nodes, $idx, $val, int($ri) ),
7062 ];
7063 } else {
7064 4658 my ( $coff, $num, $li, $ri, $b ) = @{$nodes}[ $off + 1 .. $off + 5 ];
7065 4658 $coff = int($coff);
7066 4658 $num = int($num);
7067 return [
7068 _NODE_OBLIQUE,
7069 4658 [ @{$idx}[ $coff .. $coff + $num - 1 ] ],
7070 4658 [ @{$val}[ $coff .. $coff + $num - 1 ] ],
7071 $b,
7072 _unpack_node( $nodes, $idx, $val, int($li) ),
7073 _unpack_node( $nodes, $idx, $val, int($ri) ),
7074 ];
7075 } ## end else [ if ( $type == 0 ) ]
7076 } ## end sub _unpack_node
7077  
7078 # Unpacks every tree in the three per-tree packed-buffer arrayrefs
7079 # build_forest_openmp_xs returns into the ordinary nested tree shape.
7080 # The C builder pushes nodes post-order (a node is recorded after both
7081 # of its children), so each tree's root is the LAST node record, not
7082 # index 0 as in _pack_tree's pre-order layout.
7083 #
7084 # Args:
7085 # $nodes_list :: arrayref of one packed 'd*' node buffer per tree.
7086 # $idx_list :: arrayref of one packed 'l*' coefficient index buffer per
7087 # tree, positionally matching $nodes_list.
7088 # $val_list :: arrayref of one packed 'd*' coefficient value buffer per
7089 # tree, positionally matching $nodes_list.
7090 #
7091 # Returns: an arrayref of trees in the nested arrayref layout, in the same
7092 # order as the input buffers.
7093 #
7094 # Example:
7095 # build_forest_openmp_xs( ..., \@nodes, \@idx, \@val, 1 );
7096 # my $trees = _unpack_forest( \@nodes, \@idx, \@val );
7097 7 ▶sub _unpack_forest {
Subroutine _unpack_forest: called CC=2 SCAR=6.9
7098 7 my ( $nodes_list, $idx_list, $val_list ) = @_;
7099 7 my @trees;
7100 7 for my $i ( 0 .. $#$nodes_list ) {
7101 320 my @nodes = unpack( 'd*', $nodes_list->[$i] );
7102 320 my @idx = unpack( 'l*', $idx_list->[$i] );
7103 320 my @val = unpack( 'd*', $val_list->[$i] );
7104 320 my $root = @nodes / 6 - 1;
7105 320 push @trees, _unpack_node( \@nodes, \@idx, \@val, $root );
7106 }
7107 7 return \@trees;
7108 } ## end sub _unpack_forest
7109  
7110 #-------------------------------------------------------------------------------
7111 # Packed input wrapper. pack_data() returns one of these so callers can
7112 # score the same dataset many times without re-walking the AV/AV refs on
7113 # every call -- a meaningful win at high feature counts where
7114 # pack_input_xs is a non-trivial slice of total scoring time.
7115 #
7116 # It's a minimal blessed hashref: { packed, n_pts, n_feats }. The C
7117 # scoring functions only need the packed bytes + dimensions.
7118 #-------------------------------------------------------------------------------
7119 7 ▶sub pack_data {
Subroutine pack_data: called CC=3 SCAR=11.0
Pod documented
7120 7 my ( $self, $data ) = @_;
7121 7 $self->_check_fitted;
7122 croak "pack_data requires the Inline::C backend; install Inline::C"
7123 6 ▶ unless $self->{_use_c};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_use_c"} 1 5 6
7124 5 ▶ croak "pack_data() expects an arrayref of samples"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "ARRAY" 2 3 5
7125 unless ref $data eq 'ARRAY';
7126 3 my $n_pts = scalar @$data;
7127 3 my $nf = $self->{n_features};
7128 3 my $x_packed = "\0" x ( $n_pts * $nf * 8 );
7129 3 my ( $mode, $fill ) = $self->_pack_args;
7130 3 pack_input_xs( $data, $x_packed, $n_pts, $nf, $mode, $fill );
7131 3 return bless {
7132 packed => $x_packed,
7133 n_pts => $n_pts,
7134 n_feats => $nf,
7135 },
7136 'Algorithm::Classifier::IsolationForest::PackedData';
7137 } ## end sub pack_data
7138  
7139 # Internal helper: given $data that may be a raw arrayref OR a PackedData
7140 # instance, return the triple ready for score_all_xs. Called from every
7141 # scoring fast path, which is what lets those methods accept either shape
7142 # without each of them knowing about packing.
7143 #
7144 # Args:
7145 # $data :: either an arrayref of feature-value arrayrefs (packed here,
7146 # undef cells resolved through _pack_args) or a PackedData
7147 # instance from pack_data (used as-is, no repacking).
7148 #
7149 # Returns: the three-element list ($n_pts, $n_feats, $x_packed) -- the row
7150 # count, the feature width and the row-major 'd*' buffer. Croaks when a
7151 # PackedData's width disagrees with the model's.
7152 #
7153 # Example:
7154 # my ( $n_pts, $nf, $x ) = $self->_resolve_input($data);
7155 # score_all_xs( $self->{_c_nodes}, ..., $x, $sums, $n_pts, $nf, ... );
7156 17408 ▶sub _resolve_input {
Subroutine _resolve_input: called CC=3 SCAR=11.0
7157 17408 my ( $self, $data ) = @_;
7158 17408 ▶ if ( ref $data eq 'Algorithm::Classifier::IsolationForest::PackedData' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "Algorithm::Classifier::IsolationForest::PackedData") 7400 10008 17408
7159 croak "PackedData has $data->{n_feats} features but model expects " . $self->{n_features}
7160 7400 ▶ unless $data->{n_feats} == $self->{n_features};
Branch: 1 branch
BranchTrueFalseTotal
unless $data->{"n_feats"} == $self->{"n_features"} 1 7399 7400
7161 7399 return ( $data->{n_pts}, $data->{n_feats}, $data->{packed} );
7162 }
7163 10008 my $n_pts = scalar @$data;
7164 10008 my $nf = $self->{n_features};
7165 10008 my $x_packed = "\0" x ( $n_pts * $nf * 8 );
7166 10008 my ( $mode, $fill ) = $self->_pack_args;
7167 10008 pack_input_xs( $data, $x_packed, $n_pts, $nf, $mode, $fill );
7168 10008 return ( $n_pts, $nf, $x_packed );
7169 } ## end sub _resolve_input
7170  
7171 # Helper used by the pure-Perl fallback paths: convert either form back
7172 # to an arrayref-of-arrayrefs. Slow on PackedData -- the whole point of
7173 # packing is to keep things in C -- but lets the fallback path be
7174 # uniformly arrayref-driven.
7175 #
7176 # Args:
7177 # $data :: either an arrayref of feature-value arrayrefs (returned
7178 # unchanged, not copied) or a PackedData instance (unpacked into
7179 # fresh rows).
7180 #
7181 # Returns: an arrayref of feature-value arrayrefs. Rows unpacked from
7182 # PackedData hold plain doubles, so a NaN packed for a missing cell comes
7183 # back as NaN rather than undef. Croaks on anything else.
7184 #
7185 # Example:
7186 # my $rows = $self->_to_arrayref($data);
7187 # _path_length( $rows->[0], $tree, 0, 0 );
7188 210 ▶sub _to_arrayref {
Subroutine _to_arrayref: called CC=5 SCAR=29.4
7189 210 my ( $self, $data ) = @_;
7190 210 ▶ return $data if ref $data eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $data eq "ARRAY" 210 0 210
7191 0 ▶ if ( ref $data eq 'Algorithm::Classifier::IsolationForest::PackedData' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "Algorithm::Classifier::IsolationForest::PackedData") 0 0 0
7192 0 my $n_pts = $data->{n_pts};
7193 0 my $nf = $data->{n_feats};
7194 0 my @doubles = unpack( 'd*', $data->{packed} );
7195 0 my @rows;
7196 0 for my $i ( 0 .. $n_pts - 1 ) {
7197 0 push @rows, [ @doubles[ $i * $nf .. ( $i + 1 ) * $nf - 1 ] ];
7198 }
7199 0 return \@rows;
7200 } ## end if ( ref $data eq 'Algorithm::Classifier::IsolationForest::PackedData')
7201 0 ▶ croak "expected arrayref or PackedData, got " . ( ref($data) || 'scalar' );
Condition0%0/2
ref $data || 'scalar'
l!l
00
MC/DC0%0/1
ref $data || 'scalar'
ref $data
Truth table0%0/2
A
A= ref $data
Aresult
11
00
7202 } ## end sub _to_arrayref
7203  
7204 # ---------------------------------------------------------------------------
7205 # Missing-value handling.
7206 #
7207 # The `missing` strategy chosen at new() decides how undef feature cells are
7208 # treated. Scoring always tolerates undef; the strategy governs fit() and
7209 # how undef is represented for the scorer:
7210 #
7211 # die -- croak from fit() if the training data holds any undef cell.
7212 # Scoring still maps undef -> 0 (the long-standing behaviour).
7213 # zero -- undef counts as the value 0, at fit and score time.
7214 # impute -- undef is replaced by a learned per-feature mean/median; the
7215 # fill vector is stored on the model and reused at score time.
7216 # nan -- ranges are built over present values only and a point missing
7217 # the split feature is routed to the right child, consistently
7218 # at fit (Perl) and score (C packs NaN; `<`/`<=` send it right).
7219 # ---------------------------------------------------------------------------
7220  
7221 # Returns the training data to actually build trees on, after applying the
7222 # missing-value strategy.
7223 #
7224 # Args:
7225 # $data :: the caller's raw training set, an arrayref of feature-value
7226 # arrayrefs. Never modified -- zero/impute build a copy rather
7227 # than densifying in place.
7228 #
7229 # Returns: the arrayref of rows to build trees from. That is $data itself
7230 # under die (already dense) and nan (undef is meaningful there), and a
7231 # dense copy under zero/impute -- except on the C tree-building path, which
7232 # fills from missing_fill itself and so also gets $data through unchanged.
7233 # Under die it croaks instead, naming the first missing cell's row and
7234 # column. Under impute it also sets $self->{missing_fill}.
7235 #
7236 # Example:
7237 # my $train = $self->_prepare_fit_data($data);
7238 # my $tree = $self->_build_tree( _subsample( $train, $psi ), 0, $limit );
7239 206 ▶sub _prepare_fit_data {
Subroutine _prepare_fit_data: called CC=13 SCAR=25.7
7240 206 my ( $self, $data ) = @_;
7241 206 my $m = $self->{missing};
7242 206 my $nf = $self->{n_features};
7243  
7244 206 ▶ if ( $m eq 'die' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($m eq "die") 178 28 206
7245  
7246 # Locate the first missing cell, then report it. The scan is over
7247 # every cell of the training set, so with the C backend on it goes
7248 # through first_missing_xs -- same row-major order, same cell
7249 # reported, without the per-cell Perl loop overhead. Both paths
7250 # read a row that is not an arrayref as missing at column 0, which
7251 # is how pack_input_xs treats one downstream.
7252 178 my $where = [];
7253 178 ▶ if ( $self->{_use_c} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_use_c'}) { } 122 56 178
7254 122 first_missing_xs( $data, scalar @$data, $nf, $where );
7255 } else {
7256 56 my $i = 0;
7257 56 for my $row (@$data) {
7258 0 ▶ if ( ref $row ne 'ARRAY' ) { $where = [ $i, 0 ]; last }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $row ne "ARRAY") 0 10626 10626
7259 10626 my $f = 0;
7260 10626 ▶ $f++ while $f < $nf && defined $row->[$f];
Branch: 1 branch
BranchTrueFalseTotal
$f < $nf and defined $row->[$f] and do { ++$f } 114848 10626 125474
Condition100%3/3
$f < $nf and defined $row->[$f]
!ll&&!rl&&r
106251114848
MC/DC100%2/2
$f < $nf and defined $row->[$f]
$f < $nf defined $row->[$f]
Truth table100%3/3
A and B
A= $f < $nfB= defined $row->[$f]
ABresult
0X0
100
111
7261 10626 ▶ if ( $f < $nf ) { $where = [ $i, $f ]; last }
Branch: 1 branch
BranchTrueFalseTotal
if ($f < $nf) 1 10625 10626
7262 10625 $i++;
7263 }
7264 } ## end else [ if ( $self->{_use_c} ) ]
7265 178 ▶ croak "fit(): undef feature value at sample $where->[0], column $where->[1]; "
Branch: 1 branch
BranchTrueFalseTotal
if @$where 2 176 178
7266 . "construct with missing => 'zero', 'impute', or 'nan' "
7267 . "to train on data with missing values"
7268 if @$where;
7269  
7270 176 return $data;
7271 } ## end if ( $m eq 'die' )
7272  
7273 # nan: leave undef in place -- _build_tree / the split routers handle it.
7274 28 ▶ return $data if $m eq 'nan';
Branch: 1 branch
BranchTrueFalseTotal
if $m eq "nan" 9 19 28
7275  
7276 # zero / impute: undef has to become a real number somewhere before a
7277 # split can look at it. The fill vector is computed either way (it's
7278 # needed for persistence and for scoring later), but densifying $data
7279 # into a second, fully separate Perl array here is only necessary for
7280 # the pure-Perl tree builder (_build_tree assumes every cell is
7281 # defined once missing != 'nan' -- see its lo/hi scan). The C
7282 # tree-building path -- _build_forest_c/_build_forest_openmp, and
7283 # every parallel_fit worker, all of which go through pack_input_xs --
7284 # already fills undef cells itself from this same fill vector, so
7285 # skip the redundant whole-dataset copy when that's the path fit()
7286 # will actually take. Scoring the training set for a learned
7287 # contamination threshold (below, in fit()) is unaffected: it always
7288 # runs through the pure-Perl scorer regardless of use_c (fit() drops
7289 # any previous fit's packed buffers before that scoring, and
7290 # _rebuild_c_trees runs after), and that path already tolerates raw
7291 # undef cells
7292 # for both zero (_path_length's "// 0") and impute (_prepare_perl_input
7293 # densifies on demand from missing_fill).
7294 19 ▶ my $fill
Branch: 1 branch
BranchTrueFalseTotal
$m eq 'impute' ? : 13 6 19
7295 = $m eq 'impute'
7296 ? $self->_compute_impute_fill($data)
7297 : [ (0) x $nf ];
7298 15 ▶ $self->{missing_fill} = $fill if $m eq 'impute';
Branch: 1 branch
BranchTrueFalseTotal
if $m eq "impute" 9 6 15
7299 15 delete $self->{_fill_packed};
7300  
7301 15 ▶ return $data if $self->{_use_c};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_use_c"} 8 7 15
7302 7 return _densify( $data, $fill );
7303 } ## end sub _prepare_fit_data
7304  
7305 # Per-feature fill value (mean or median of the present values) for impute
7306 # mode. Croaks if a feature has no present value to learn from. The
7307 # optional $how_override selects the statistic independently of the
7308 # model's impute_with knob (used by _compute_feature_baselines, which
7309 # always wants the median).
7310 #
7311 # Args:
7312 # $data :: the rows to learn from, an arrayref of feature-value
7313 # arrayrefs. undef cells are skipped rather than counted.
7314 # $how_override :: 'mean' or 'median' to force the statistic, or undef to
7315 # follow the model's impute_with.
7316 #
7317 # Returns: an arrayref of n_features fill values. Croaks naming the column
7318 # when a feature has no present value anywhere in $data.
7319 #
7320 # Example:
7321 # $self->_compute_impute_fill( \@rows ); # per impute_with
7322 # $self->_compute_impute_fill( \@rows, 'median' ); # forced median
7323 275 ▶sub _compute_impute_fill {
Subroutine _compute_impute_fill: called CC=9 SCAR=22.0
7324 275 my ( $self, $data, $how_override ) = @_;
7325 275 my $nf = $self->{n_features};
7326 275 ▶ my $how = $how_override // $self->{impute_with};
Condition66%2/3
$how_override // $self->{"impute_with"}
l!l&&r!l&&!r
260150
MC/DC0%0/2
$how_override // $self->{"impute_with"}
$how_override $self->{"impute_with"}
Truth table66%2/3
A // B
A= $how_overrideB= $self->{"impute_with"}
ABresult
1X1
011
000
7327  
7328 # C fast path: walks the raw data directly and finds the median via
7329 # quickselect (O(n) average) instead of the Perl fallback's full sort
7330 # (O(n log n)). Produces the same fill values either way -- see
7331 # impute_fill_xs's file-top comment -- so use_c only changes speed
7332 # here, matching the rest of the module.
7333 275 ▶ if ( $self->{_use_c} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_use_c"}) 175 100 275
7334 175 my $n = scalar @$data;
7335 175 ▶ my $how_flag = $how eq 'median' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$how eq 'median' ? : 169 6 175
7336 175 my $fill = [];
7337 175 impute_fill_xs( $data, $n, $nf, $how_flag, $fill );
7338 173 return $fill;
7339 }
7340  
7341 100 my @fill;
7342 100 for my $f ( 0 .. $nf - 1 ) {
7343 448 my @vals = grep { defined } map { $_->[$f] } @$data;
7344 448 ▶ croak "impute: feature column $f has no present values"
Branch: 1 branch
BranchTrueFalseTotal
unless @vals 2 446 448
7345 unless @vals;
7346 446 ▶ if ( $how eq 'median' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($how eq 'median') { } 438 8 446
7347 438 my @s = sort { $a <=> $b } @vals;
7348 438 my $k = scalar @s;
7349 438 ▶ $fill[$f]
Branch: 1 branch
BranchTrueFalseTotal
$k % 2 ? : 281 157 438
7350 = $k % 2
7351 ? $s[ int( $k / 2 ) ]
7352 : ( $s[ $k / 2 - 1 ] + $s[ $k / 2 ] ) / 2.0;
7353 } else { # mean
7354 8 my $sum = 0;
7355 8 if (_NV_IS_DOUBLE) {
7356 8 $sum += $_ for @vals;
7357 } else {
7358 # impute_fill_xs accumulates the sum in double (over
7359 # SvNV-truncated cells); match its rounding step for step.
7360 $sum = _to_double( $sum + _to_double($_) ) for @vals;
7361 }
7362 8 $fill[$f] = $sum / scalar @vals;
7363 } ## end else [ if ( $how eq 'median' ) ]
7364  
7365 # The fill crosses into the C backend as a double (pack 'd' /
7366 # SvNV), so on wide-NV perls store it already narrowed and both
7367 # builders densify with the identical value.
7368 446 $fill[$f] = _to_double( $fill[$f] ) unless _NV_IS_DOUBLE;
7369 } ## end for my $f ( 0 .. $nf - 1 )
7370 98 return \@fill;
7371 } ## end sub _compute_impute_fill
7372  
7373 # Per-feature median of the present values of the training data -- the
7374 # "typical row" that ablation explanations (explain_samples with
7375 # method => 'ablation') substitute against, one feature at a time.
7376 # Always the median (not impute_with's statistic): a baseline should be
7377 # a robustly central value, and outliers in the training data drag a
7378 # mean around far more than a median.
7379 #
7380 # Computed from the RAW rows, never a densified copy, so the stored
7381 # baselines are identical whether use_c is on or off (the pure-Perl fit
7382 # path densifies $train before the trees are built; the C path does
7383 # not). A column with no present value at all -- legal under
7384 # missing => 'zero'/'nan' -- cannot yield a median, so the fast path's
7385 # croak falls back to a tolerant pure-Perl pass that gives such columns
7386 # the fill value scoring maps their undefs to anyway (0).
7387 #
7388 # Args:
7389 # $data :: the raw training rows, an arrayref of feature-value
7390 # arrayrefs. Must be the caller's data, never a densified copy.
7391 #
7392 # Returns: an arrayref of n_features medians. A column with no present
7393 # value at all gets 0 rather than causing a croak.
7394 #
7395 # Example:
7396 # $self->{feature_baselines} = $self->_compute_feature_baselines($data);
7397 # # later: explain_samples( \@rows, method => 'ablation' )
7398 260 ▶sub _compute_feature_baselines {
Subroutine _compute_feature_baselines: called CC=5 SCAR=28.6
7399 260 my ( $self, $data ) = @_;
7400 260 my $baselines = eval { $self->_compute_impute_fill( $data, 'median' ) };
7401 260 ▶ return $baselines if ref $baselines eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $baselines eq "ARRAY" 260 0 260
7402  
7403 0 my $nf = $self->{n_features};
7404 0 my @fallback;
7405 0 for my $f ( 0 .. $nf - 1 ) {
7406 0 my @vals = sort { $a <=> $b } grep { defined } map { $_->[$f] } @$data;
7407 0 my $k = scalar @vals;
7408 0 ▶ if ( $k == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k == 0) 0 0 0
7409 0 $fallback[$f] = 0;
7410 0 next;
7411 }
7412 0 ▶ $fallback[$f]
Branch: 1 branch
BranchTrueFalseTotal
$k % 2 ? : 0 0 0
7413 = $k % 2
7414 ? $vals[ int( $k / 2 ) ]
7415 : ( $vals[ $k / 2 - 1 ] + $vals[ $k / 2 ] ) / 2.0;
7416 0 $fallback[$f] = _to_double( $fallback[$f] ) unless _NV_IS_DOUBLE;
7417 } ## end for my $f ( 0 .. $nf - 1 )
7418 0 return \@fallback;
7419 } ## end sub _compute_feature_baselines
7420  
7421 # Return a dense copy of $data with every undef cell replaced by the
7422 # matching per-feature fill value. Leaves present cells untouched.
7423 #
7424 # Args:
7425 # $data :: the rows to densify, an arrayref of feature-value arrayrefs.
7426 # Never modified.
7427 # $fill :: the per-feature fill values, an arrayref. Its length fixes
7428 # the output width, so a row longer than $fill is truncated and
7429 # a shorter one padded.
7430 #
7431 # Returns: a fresh arrayref of fresh rows -- nothing is shared with $data,
7432 # so the caller may mutate either independently.
7433 #
7434 # Example:
7435 # _densify( [ [ 0.9, undef ] ], [ 0, 0.5 ] ); # [ [ 0.9, 0.5 ] ]
7436 11 ▶sub _densify {
Subroutine _densify: called CC=2 SCAR=6.9
7437 11 my ( $data, $fill ) = @_;
7438 11 my $nf = scalar @$fill;
7439 return [
7440 map {
7441 11 my $r = $_;
7442 1888 ▶ [ map { defined $r->[$_] ? $r->[$_] : $fill->[$_] } 0 .. $nf - 1 ]
Branch: 1 branch
BranchTrueFalseTotal
defined $r->[$_] ? : 3857 225 4082
7443 } @$data
7444 ];
7445 } ## end sub _densify
7446  
7447 # (miss_mode, fill_packed) pair for pack_input_xs, per the active strategy.
7448 # die/zero -> 0 (undef becomes 0.0); impute -> 1 (undef becomes fill[k]);
7449 # nan -> 2 (undef becomes NaN, which the C scorer routes right).
7450 #
7451 # Args: none beyond the model itself.
7452 #
7453 # Returns: the two-element list ($miss_mode, $fill_packed) -- the mode flag
7454 # above, and a 'd*' string of the per-feature fills under impute or the
7455 # empty string otherwise. The packed fill is memoised in _fill_packed, so
7456 # repeated scoring calls pack it once. Croaks when an impute model has
7457 # lost its fill vector.
7458 #
7459 # Example:
7460 # my ( $mode, $fill ) = $self->_pack_args;
7461 # pack_input_xs( $data, $x_packed, $n_pts, $nf, $mode, $fill );
7462 10137 ▶sub _pack_args {
Subroutine _pack_args: called CC=6 SCAR=18.1
7463 10137 my ($self) = @_;
7464 10137 my $m = $self->{missing};
7465 10137 ▶ return ( 2, '' ) if $m eq 'nan';
Branch: 1 branch
BranchTrueFalseTotal
if $m eq "nan" 13 10124 10137
7466 10124 ▶ if ( $m eq 'impute' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($m eq "impute") 12 10112 10124
7467 12 my $fill = $self->{missing_fill};
7468 croak "impute model is missing its fill vector"
7469 12 ▶ unless ref $fill eq 'ARRAY' && @$fill == $self->{n_features};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $fill eq "ARRAY" and @$fill == $self->{"n_features"} 0 12 12
Condition33%1/3
ref $fill eq "ARRAY" and @$fill == $self->{"n_features"}
!ll&&!rl&&r
0012
MC/DC0%0/2
ref $fill eq "ARRAY" and @$fill == $self->{"n_features"}
ref $fill eq "ARRAY" @$fill == $self->{"n_features"}
Truth table33%1/3
A and B
A= ref $fill eq "ARRAY"B= @$fill == $self->{"n_features"}
ABresult
0X0
100
111
7470 12 ▶ $self->{_fill_packed} //= pack( 'd*', @$fill );
Condition100%2/2
$self->{"_fill_packed"} //= pack("d*", @$fill)
l!l
48
MC/DC100%1/1
$self->{"_fill_packed"} //= pack("d*", @$fill)
$self->{"_fill_packed"}
Truth table100%2/2
A
A= $self->{"_fill_packed"}
Aresult
11
00
7471 12 return ( 1, $self->{_fill_packed} );
7472 }
7473 10112 return ( 0, '' ); # die, zero
7474 } ## end sub _pack_args
7475  
7476 # Pure-Perl fallback input prep: arrayref-ify, then fill for impute so the
7477 # tree walk sees dense rows. zero/die rely on _path_length's "// 0"; nan
7478 # keeps undef in place for _path_length to route.
7479 #
7480 # Args:
7481 # $data :: either an arrayref of feature-value arrayrefs or a PackedData
7482 # instance -- _to_arrayref normalises it either way.
7483 #
7484 # Returns: an arrayref of rows ready for _path_length. Under impute these
7485 # are a fresh dense copy; otherwise the rows are handed back as they came,
7486 # so the caller must not mutate them. The nan flag is NOT part of this --
7487 # callers pass it to _path_length themselves. Croaks when an impute model
7488 # has lost its fill vector.
7489 #
7490 # Example:
7491 # my $rows = $self->_prepare_perl_input($data);
7492 # my $nan = $self->{missing} eq 'nan' ? 1 : 0;
7493 # _path_length( $rows->[0], $tree, 0, $nan );
7494 151 ▶sub _prepare_perl_input {
Subroutine _prepare_perl_input: called CC=3 SCAR=11.0
7495 151 my ( $self, $data ) = @_;
7496 151 my $rows = $self->_to_arrayref($data);
7497 151 ▶ if ( $self->{missing} eq 'impute' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"missing"} eq "impute") 4 147 151
7498 croak "impute model is missing its fill vector"
7499 4 ▶ unless ref $self->{missing_fill} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self->{"missing_fill"} eq "ARRAY" 0 4 4
7500 4 $rows = _densify( $rows, $self->{missing_fill} );
7501 }
7502 151 return $rows;
7503 } ## end sub _prepare_perl_input
7504  
7505 # Minimal PackedData package: opaque token returned by pack_data(). The
7506 # scoring methods recognise it and hand its buffer straight to the C
7507 # scorer; the two accessors exist so callers holding one can still ask
7508 # what is in it without unpacking.
7509 {
7510  
7511 package Algorithm::Classifier::IsolationForest::PackedData;
7512  
7513 # How many samples the buffer holds.
7514 #
7515 # Args: none.
7516 #
7517 # Returns: the row count as an integer, fixed when pack_data built the
7518 # object.
7519 #
7520 # Example:
7521 # my $packed = $iforest->pack_data(\@data);
7522 # $packed->n_pts; # scalar @data
7523 4 ▶ sub n_pts { $_[0]->{n_pts} }
Subroutine n_pts: called CC=1 SCAR=0.0
7524  
7525 # How wide each packed sample is.
7526 #
7527 # Args: none.
7528 #
7529 # Returns: the feature count as an integer, always the n_features of
7530 # the model that packed the data.
7531 #
7532 # Example:
7533 # $packed->n_feats; # 2 for two-feature rows
7534 4 ▶ sub n_feats { $_[0]->{n_feats} }
Subroutine n_feats: called CC=1 SCAR=0.0
7535 }
7536  
7537 132 1;
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/predict.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/proto.pm »