blib/lib/Algorithm/Classifier/IsolationForest/Online.pm

filter: Statementstmt 99.0% 546 / 551 Branchbran 84.9% 192 / 226 Conditioncond 67.1% 90 / 134 MC/DCmcdc 45.4% 35 / 77 Subroutinesub 98.7% 77 / 78 Podpod 100% 30 / 30 totaltotal 88.5% 970 / 1096 CC 189 SCAR 23.6
CC
189
Cov
91%
new
36.5
from_json
19.8
to_prototype
16.7
CRAP 10.6
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/info.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/pack.pm »
1 package Algorithm::Classifier::IsolationForest::Online;
2  
3 96 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 96 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 96 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 96 ▶use JSON::PP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 96 ▶use File::Slurp qw(read_file write_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # Runtime-only dependency: tagged_row_to_array is delegated to the parent
10 # class (identical semantics, no point duplicating it) and the
11 # contamination threshold selection reuses _threshold_from_ranked. The
12 # parent never loads this module at compile time (its from_json requires
13 # it on demand), so there is no cycle.
14 96 ▶use Algorithm::Classifier::IsolationForest ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 96 our $VERSION = '0.6.0';
17  
18 # Node layout. Unlike the batch forest's nodes, online nodes are mutable
19 # and carry a running point count plus the bounding box (per-feature
20 # lo/hi) of every point that has passed through them -- that box is what
21 # split simulation samples from, since points themselves are never stored
22 # in the tree. Both node types share the first four slots so the
23 # learn/unlearn bookkeeping never has to branch on type:
24 #
25 # leaf: [0, count, \@lo, \@hi]
26 # internal: [1, count, \@lo, \@hi, attr, split, left, right]
27 #
28 # The type tag mirrors the parent's convention (0 is falsy, so
29 # while ($node->[0]) walks to a leaf). A leaf built from an empty
30 # synthetic partition has count 0 and an undef box (slots 2/3); the box
31 # is initialised from the first real point that reaches it.
32 96 ▶use constant _N_TYPE => 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 96 ▶use constant _N_COUNT => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 96 ▶use constant _N_LO => 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
35 96 ▶use constant _N_HI => 3;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 96 ▶use constant _N_ATTR => 4;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 96 ▶use constant _N_SPLIT => 5;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 96 ▶use constant _N_LEFT => 6;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 96 ▶use constant _N_RIGHT => 7;
Subroutine BEGIN: called CC=1 SCAR=0.0
40  
41 96 ▶use constant _NT_LEAF => 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 96 ▶use constant _NT_AXIS => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
43  
44 # Trees are binary (the reference implementation's branching_factor == 2),
45 # which fixes the depth-budget log base at log(2 * 2). Spelled as the
46 # exact-double literal rather than log(4) so it is bit-identical to the
47 # OL_LOG4 literal the C learn path uses regardless of the platform's
48 # libm rounding -- a one-ulp disagreement would flip `depth < limit`
49 # split decisions exactly when a tree's count is eta * 4**k (the same
50 # TWO_PI trick the parent uses for _randn parity).
51 96 ▶use constant _LOG4 => unpack( 'd', pack 'd', 1.3862943611198906 );
Subroutine BEGIN: called CC=1 SCAR=0.0
52 96 ▶use constant _LOG2 => log(2);
Subroutine BEGIN: called CC=1 SCAR=0.0
53  
54 # DBL_EPSILON, added to the normalisation factor before dividing so a
55 # just-started model (normaliser 0) yields well-defined scores instead of
56 # a division by zero -- the same guard the reference implementation uses.
57 96 ▶use constant _EPS => 2.220446049250313e-16;
Subroutine BEGIN: called CC=1 SCAR=0.0
58  
59 # The online learn/unlearn/score-row XS functions were added to the C
60 # backend after the batch-scoring ones, so a prebuilt object installed
61 # from an older release can back $HAS_C while lacking them (the parent
62 # trusts a flag-matched prebuilt object without inspecting its symbol
63 # set). Probe once at load: without them, use_c still accelerates the
64 # packed-snapshot batch scoring -- those functions have been in the
65 # object all along -- and learning quietly stays pure Perl instead of
66 # crashing on an undefined XS sub. Rebuilding/reinstalling (or
67 # IF_RUNTIME_BUILD=1) restores the full set.
68 96 ▶use constant _HAS_ONLINE_XS => defined &Algorithm::Classifier::IsolationForest::online_learn_row_xs ? 1 : 0;
Subroutine BEGIN: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
defined &Algorithm::Classifier::IsolationForest::online_learn_row_xs ? : 96 0 96
69  
70 =head1 NAME
71  
72 Algorithm::Classifier::IsolationForest::Online - Online (streaming) Isolation Forest anomaly detection
73  
74 =head1 SYNOPSIS
75  
76 use Algorithm::Classifier::IsolationForest::Online;
77  
78 my $oif = Algorithm::Classifier::IsolationForest::Online->new(
79 n_trees => 100,
80 window_size => 2048,
81 max_leaf_samples => 32,
82 seed => 42,
83 );
84  
85 # stream data through the model; each point is learned and old
86 # points beyond the window are forgotten automatically
87 $oif->learn(\@warmup_rows);
88  
89 # prequential operation: score each point against the model as it
90 # stood BEFORE that point was learned, then learn it
91 my $scores = $oif->score_learn(\@new_rows);
92  
93 # or score without learning
94 my $scores2 = $oif->score_samples(\@query_rows);
95 my $labels = $oif->predict(\@query_rows);
96  
97 # persistence keeps the window, so a reloaded model keeps forgetting
98 # correctly as the stream continues
99 $oif->save('oiforest_model.json');
100 my $resumed = Algorithm::Classifier::IsolationForest::Online->load('oiforest_model.json');
101  
102 =head1 DESCRIPTION
103  
104 Implements Online Isolation Forest (Online-iForest; Leveni, Weigert
105 Cassales, Pfahringer, Bifet & Boracchi 2024 -- see REFERENCES), a
106 streaming variant of Isolation Forest for data that arrives continuously
107 and whose distribution may drift. There is no C<fit()>: the model
108 C<learn>s points as they arrive and, once more than C<window_size> points
109 have been seen, forgets the oldest point for every new one so the model
110 always reflects the most recent C<window_size> points of the stream.
111  
112 Trees never store data points. Each node keeps only a running count of
113 the points that passed through it and the bounding box of their feature
114 values. A leaf splits once enough points have accumulated (see
115 C<max_leaf_samples> and C<growth>); because the actual points are gone,
116 the split simulates them by sampling uniformly inside the leaf's bounding
117 box. Forgetting reverses the process: counts are decremented along the
118 forgotten point's path and a subtree whose count falls below its split
119 requirement is collapsed back into a leaf.
120  
121 Scoring follows the classic Isolation Forest intuition -- anomalies
122 isolate at shallow depth -- but normalises by the depth budget
123 C<log(n/max_leaf_samples) / log(4)> of the current window rather than the
124 batch model's C<c(psi)>. Scores are in (0, 1] with high values
125 anomalous, directly comparable in spirit (though not numerically) to the
126 parent class's scores.
127  
128 Both learning and scoring are accelerated through the parent class's
129 Inline::C backend when it is available; C<use_c> covers them together.
130  
131 Learning (and the per-row walks inside C<score_learn>) runs in C
132 directly against the live trees, drawing randomness through the same
133 generator in the same order as the pure-Perl path -- so, like the
134 parent's C<fit()>, a C<learn()> with a given seed produces bit-identical
135 trees whether C<use_c> is on or off (on C<nvsize == 8> perls; wide-NV
136 perls keep extra low bits in the pure-Perl path). The knob changes
137 speed, never results.
138  
139 Batch scoring lazily flattens the mutable trees into the same packed
140 node layout the batch scorer walks -- online trees are axis-only, and
141 the online per-leaf depth adjustment rides in the slot the batch packer
142 uses for its own leaf adjustment -- so C<score_samples>, C<predict>,
143 C<path_lengths>, C<score_predict_samples>, and C<score_predict_split>
144 all run through the same C (and OpenMP, when linked) tree walk the
145 parent uses, with identical results to the pure-Perl fallback. Any
146 C<learn> invalidates the packed snapshot; the next batch-scoring call
147 repacks once. C<score_learn> never touches the snapshot: it mutates
148 the trees after every single point, so its rows are scored by walking
149 the live trees in C instead.
150  
151 A model needs to have seen at least C<max_leaf_samples> points before
152 tree structure exists at all; until then every point scores 1.0. Give
153 the model a warm-up C<learn()> pass before trusting scores or labels.
154  
155 Models saved by this class carry their own C<format> tag.
156 C<< Algorithm::Classifier::IsolationForest->load >> recognises it and
157 dispatches here, so callers can load either model type through the
158 parent class.
159  
160 =head1 GENERAL METHODS
161  
162 =head2 new(%args)
163  
164 Inits the object.
165  
166 - n_trees :: number of isolation trees in the ensemble
167 default :: 100
168  
169 - window_size :: how many of the most recent points the model reflects.
170 Once the stream exceeds this, learning a point forgets the
171 oldest retained point. 0 or undef disables forgetting: the
172 model then learns from the whole stream and retains no window
173 (so nothing is ever unlearned and threshold relearning needs
174 caller-supplied data).
175 default :: 2048
176  
177 - max_leaf_samples :: how many points a leaf must accumulate before it
178 splits (eta in the paper). Also the unit of the depth budget:
179 trees stop splitting past log(n/eta)/log(4).
180 default :: 32
181  
182 - growth :: how the split requirement scales with depth (the reference
183 implementation's `type` parameter).
184 adaptive :: a leaf at depth k needs max_leaf_samples * 2**k
185 points to split -- deeper splits need
186 exponentially more evidence
187 fixed :: max_leaf_samples points regardless of depth
188 default :: adaptive
189  
190 - subsample :: probability in (0, 1] that a given tree learns (or
191 forgets) a given point, drawn independently per tree per point.
192 Values below 1 increase diversity among trees on very dense
193 streams. Note that, as in the reference implementation, learn
194 and forget draws are independent, so per-tree counts are only
195 approximate under subsampling.
196 default :: 1.0
197  
198 - seed :: optional integer to seed srand with, for reproducible trees
199 given the same stream in the same order. Processed via
200 abs(int()). Seeding happens here in new(), since there is no
201 fit() to do it in.
202 default :: undef
203  
204 - contamination :: expected fraction of anomalies, in (0, 0.5]. When
205 set, the first predict()-family call learns a score threshold
206 that flags this fraction of the current window, and uses it as
207 the default cutoff. The threshold does NOT track the stream
208 automatically afterwards; call relearn_threshold() to refresh
209 it. undef => no learned threshold (predict() falls back to
210 0.5).
211 default :: undef
212  
213 - missing :: how learn() treats undef (missing) feature cells. Scoring
214 always tolerates undef (mapped to 0), matching the parent
215 class's long-standing behaviour.
216 die :: croak if a learned point contains an undef cell
217 zero :: treat a missing cell as the value 0
218 default :: die
219  
220 - feature_names :: optional arrayref of per-feature labels enabling the
221 *_tagged methods (and required by mungers below).
222 default :: undef
223  
224 - mungers :: optional hashref of declarative L<Algorithm::ToNumberMunger>
225 specs; every tagged row (learn_tagged, score_learn_tagged, the
226 scoring *_tagged methods, tagged_row_to_array) is munged from
227 raw values into numbers through the compiled plan, and
228 munge_rows() applies the scalar mungers to positional rows.
229 Requires feature_names; spec errors croak here. The spec is
230 saved with the model. Identical semantics to the parent
231 class's knob -- see MUNGERS in
232 L<Algorithm::Classifier::IsolationForest> for details and
233 caveats.
234 default :: undef
235  
236 - schema_version :: optional opaque string identifying the revision of
237 the variable schema this model was built against. Never
238 parsed; saved with the model. Usually set via a prototype --
239 see PROTOTYPES in L<Algorithm::Classifier::IsolationForest>
240 (whose new_from_prototype creates online models too).
241 default :: undef
242  
243 - schema_description :: optional opaque free-text description of what
244 the variable schema is. Same handling as schema_version.
245 default :: undef
246  
247 - feature_descriptions :: optional hashref of 'feature name => free
248 text' describing individual features. Requires feature_names;
249 every key must name an entry there or new() croaks. Partial
250 coverage is fine. Saved with the model.
251 default :: undef
252  
253 - use_c :: boolean, override whether the parent class's Inline::C
254 backend is used, for learning and scoring both (see
255 DESCRIPTION). When false the instance runs pure Perl even if
256 the C backend compiled. Results are identical either way --
257 learn() builds bit-identical trees for the same seed (on
258 nvsize == 8 perls) and scoring matches exactly -- so only
259 speed differs.
260 default :: $Algorithm::Classifier::IsolationForest::HAS_C
261  
262 - use_openmp :: boolean, override whether OpenMP parallel scoring is
263 used inside the C tree walk. Ignored when use_c is false.
264 default :: $Algorithm::Classifier::IsolationForest::HAS_OPENMP
265  
266 =cut
267  
268 76 ▶sub new {
Subroutine new: called CC=36 SCAR=36.0
Pod documented
269 76 my ( $class, %args ) = @_;
270  
271 76 ▶ my $growth = $args{growth} // 'adaptive';
Condition100%2/2
$args{"growth"} // "adaptive"
l!l
472
MC/DC100%1/1
$args{"growth"} // "adaptive"
$args{"growth"}
Truth table100%2/2
A
A= $args{"growth"}
Aresult
11
00
272 76 ▶ croak "growth must be 'adaptive' or 'fixed'"
Branch: 1 branch
BranchTrueFalseTotal
unless $growth =~ /\A(?:adaptive|fixed)\z/ 1 75 76
273 unless $growth =~ /\A(?:adaptive|fixed)\z/;
274  
275 75 ▶ my $missing = $args{missing} // 'die';
Condition100%2/2
$args{"missing"} // "die"
l!l
966
MC/DC100%1/1
$args{"missing"} // "die"
$args{"missing"}
Truth table100%2/2
A
A= $args{"missing"}
Aresult
11
00
276 75 ▶ croak "missing must be one of: die, zero"
Branch: 1 branch
BranchTrueFalseTotal
unless $missing =~ /\A(?:die|zero)\z/ 1 74 75
277 unless $missing =~ /\A(?:die|zero)\z/;
278  
279 74 ▶ if ( defined( $args{seed} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"seed"}) 47 27 74
280 47 $args{seed} = abs( int( $args{seed} ) );
281 }
282  
283 # window_size => 0 and window_size => undef both mean "no forgetting";
284 # normalise to 0 so the rest of the code has one falsy spelling.
285 74 ▶ my $window_size = exists $args{window_size} ? ( $args{window_size} // 0 ) : 2048;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'window_size'} ? : 55 19 74
Condition100%2/2
$args{"window_size"} // 0
l!l
541
MC/DC100%1/1
$args{"window_size"} // 0
$args{"window_size"}
Truth table100%2/2
A
A= $args{"window_size"}
Aresult
11
00
286  
287 # Clamp the accel knobs against what the parent's build actually has,
288 # exactly as the parent's new() does: use_c => 1 without a compiled
289 # backend would otherwise call undefined XS subs at first scoring, and
290 # OpenMP is meaningless without the C tree walk.
291 my $use_c
292 = defined $args{use_c}
293 74 ▶ ? ( $args{use_c} && $Algorithm::Classifier::IsolationForest::HAS_C ? 1 : 0 )
Branch: 2 branches
BranchTrueFalseTotal
defined $args{'use_c'} ? : 17 57 74
$args{'use_c'} && $Algorithm::Classifier::IsolationForest::HAS_C ? : 8 9 17
Condition66%2/3
$args{"use_c"} and $Algorithm::Classifier::IsolationForest::HAS_C
!ll&&!rl&&r
908
MC/DC50%1/2
$args{"use_c"} and $Algorithm::Classifier::IsolationForest::HAS_C
$args{"use_c"} $Algorithm::Classifier::IsolationForest::HAS_C
Truth table66%2/3
A and B
A= $args{"use_c"}B= $Algorithm::Classifier::IsolationForest::HAS_C
ABresult
0X0
100
111
294 : $Algorithm::Classifier::IsolationForest::HAS_C;
295 my $use_openmp
296 = defined $args{use_openmp}
297 74 ▶ ? ( $args{use_openmp} && $Algorithm::Classifier::IsolationForest::HAS_OPENMP ? 1 : 0 )
Branch: 2 branches
BranchTrueFalseTotal
defined $args{'use_openmp'} ? : 1 73 74
$args{'use_openmp'} && $Algorithm::Classifier::IsolationForest::HAS_OPENMP ? : 1 0 1
Condition33%1/3
$args{"use_openmp"} and $Algorithm::Classifier::IsolationForest::HAS_OPENMP
!ll&&!rl&&r
001
MC/DC0%0/2
$args{"use_openmp"} and $Algorithm::Classifier::IsolationForest::HAS_OPENMP
$args{"use_openmp"} $Algorithm::Classifier::IsolationForest::HAS_OPENMP
Truth table33%1/3
A and B
A= $args{"use_openmp"}B= $Algorithm::Classifier::IsolationForest::HAS_OPENMP
ABresult
0X0
100
111
298 : $Algorithm::Classifier::IsolationForest::HAS_OPENMP;
299 74 ▶ $use_openmp = 0 unless $use_c;
Branch: 1 branch
BranchTrueFalseTotal
unless $use_c 9 65 74
300  
301 my $self = {
302 n_trees => $args{n_trees} // 100,
303 window_size => $window_size,
304 max_leaf_samples => $args{max_leaf_samples} // 32,
305 growth => $growth,
306 subsample => $args{subsample} // 1.0,
307 seed => $args{seed},
308 contamination => $args{contamination},
309 missing => $missing,
310 feature_names => $args{feature_names},
311 threshold => undef, # learned lazily if contamination set
312 n_features => undef, # learned from the first row
313 seen => 0, # total points learned over the model's lifetime
314 window => [], # the retained rows, oldest first
315 trees => [],
316 mungers => undef, # optional Algorithm::ToNumberMunger spec hash
317 # Opaque schema metadata, usually set via the parent class's
318 # new_from_prototype and persisted with the model.
319 schema_version => $args{schema_version},
320 schema_description => $args{schema_description},
321 feature_descriptions => $args{feature_descriptions},
322 74 ▶ _use_c => $use_c,
Condition100%6/6
$args{"n_trees"} // 100
l!l
5816
$args{"max_leaf_samples"} // 32
l!l
5321
$args{"subsample"} // 1
l!l
668
MC/DC100%1/1
$args{"n_trees"} // 100
$args{"n_trees"}
MC/DC100%1/1
$args{"max_leaf_samples"} // 32
$args{"max_leaf_samples"}
MC/DC100%1/1
$args{"subsample"} // 1
$args{"subsample"}
Truth table100%2/2
A
A= $args{"n_trees"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"max_leaf_samples"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"subsample"}
Aresult
11
00
323 _use_openmp => $use_openmp,
324 };
325  
326 74 for my $doc (qw(schema_version schema_description)) {
327 croak "$doc must be a plain string"
328 148 ▶ if defined $self->{$doc} && ref $self->{$doc};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{$doc} and ref $self->{$doc} 0 148 148
Condition66%2/3
defined $self->{$doc} and ref $self->{$doc}
!ll&&!rl&&r
132160
MC/DC0%0/2
defined $self->{$doc} and ref $self->{$doc}
defined $self->{$doc} ref $self->{$doc}
Truth table66%2/3
A and B
A= defined $self->{$doc}B= ref $self->{$doc}
ABresult
0X0
100
111
329 }
330 Algorithm::Classifier::IsolationForest::_validate_feature_descriptions( $self->{feature_names},
331 $self->{feature_descriptions} )
332 74 ▶ if defined $self->{feature_descriptions};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"feature_descriptions"} 7 67 74
333  
334 # Optional Algorithm::ToNumberMunger integration, identical to the
335 # parent's: compiled eagerly so spec errors surface here; the module
336 # is only required when a spec is actually given.
337 73 ▶ if ( defined $args{mungers} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"mungers"}) 4 69 73
338 croak "mungers must be a hashref of 'tag => munger spec'"
339 4 ▶ unless ref $args{mungers} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args{"mungers"} eq "HASH" 0 4 4
340 croak "mungers requires feature_names (the munger plan compiles against them)"
341 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
342 3 $self->{mungers} = $args{mungers};
343 $self->{_munger_plan}
344 3 = Algorithm::Classifier::IsolationForest::_compile_mungers( $self->{feature_names}, $self->{mungers} );
345 3 $self->{munger_module_version} = $Algorithm::ToNumberMunger::VERSION;
346 } ## end if ( defined $args{mungers} )
347  
348 72 ▶ croak "n_trees must be >= 1" unless $self->{n_trees} >= 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"n_trees"} >= 1 1 71 72
349 71 ▶ croak "max_leaf_samples must be >= 1" unless $self->{max_leaf_samples} >= 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"max_leaf_samples"} >= 1 1 70 71
350 croak "window_size must be 0 (unbounded) or >= max_leaf_samples"
351 70 ▶ if $self->{window_size} && $self->{window_size} < $self->{max_leaf_samples};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"window_size"} and $self->{"window_size"} < $self->{"max_leaf_samples"} 1 69 70
Condition100%3/3
$self->{"window_size"} and $self->{"window_size"} < $self->{"max_leaf_samples"}
!ll&&!rl&&r
7621
MC/DC100%2/2
$self->{"window_size"} and $self->{"window_size"} < $self->{"max_leaf_samples"}
$self->{"window_size"} $self->{"window_size"} < $self->{"max_leaf_samples"}
Truth table100%3/3
A and B
A= $self->{"window_size"}B= $self->{"window_size"} < $self->{"max_leaf_samples"}
ABresult
0X0
100
111
352 croak "subsample must be in (0, 1]"
353 69 ▶ unless $self->{subsample} > 0 && $self->{subsample} <= 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"subsample"} > 0 and $self->{"subsample"} <= 1 3 66 69
Condition100%3/3
$self->{"subsample"} > 0 and $self->{"subsample"} <= 1
!ll&&!rl&&r
1266
MC/DC100%2/2
$self->{"subsample"} > 0 and $self->{"subsample"} <= 1
$self->{"subsample"} > 0 $self->{"subsample"} <= 1
Truth table100%3/3
A and B
A= $self->{"subsample"} > 0B= $self->{"subsample"} <= 1
ABresult
0X0
100
111
354 croak "contamination must be a number in (0, 0.5]"
355 if defined $self->{contamination}
356 66 ▶ && !( $self->{contamination} > 0 && $self->{contamination} <= 0.5 );
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"contamination"} and not $self->{"contamination"} > 0 && $self->{"contamination"} <= "0.5" 2 64 66
Condition100%6/6
defined $self->{"contamination"} and not $self->{"contamination"} > 0 && $self->{"contamination"} <= "0.5"
!ll&&!rl&&r
5682
$self->{'contamination'} > 0 && $self->{'contamination'} <= 0.5
!ll&&!rl&&r
118
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
357  
358 64 $self->{trees} = [ map { { root => undef, count => 0, depth_limit => 0 } } 1 .. $self->{n_trees} ];
359  
360 64 ▶ srand( $self->{seed} ) if defined $self->{seed};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"seed"} 47 17 64
361  
362 64 return bless $self, $class;
363 } ## end sub new
364  
365 =head2 learn(\@data)
366  
367 Learns the passed samples, in order, as the next points of the stream.
368 Once the model has seen more than C<window_size> points, each learned
369 point also forgets the oldest retained point, so the model tracks the
370 most recent C<window_size> points.
371  
372 The data format matches the parent class's C<fit>: an arrayref of
373 arrayrefs, each inner arrayref one sample of numeric features. All
374 samples must have the same feature count; the count is locked in by the
375 first sample ever learned.
376  
377 Returns C<$self>, so it chains.
378  
379 $oif->learn(\@rows);
380  
381 =cut
382  
383 265 ▶sub learn {
Subroutine learn: called CC=4 SCAR=14.9
Pod documented
384 265 my ( $self, $data ) = @_;
385 265 ▶ croak "learn() expects a non-empty arrayref of samples"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "ARRAY" and @$data 0 265 265
Condition33%1/3
ref $data eq "ARRAY" and @$data
!ll&&!rl&&r
00265
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
386 unless ref $data eq 'ARRAY' && @$data;
387 265 for my $row (@$data) {
388 15168 $self->_learn_row( $self->_prep_row( $row, 'learn' ) );
389 }
390 263 return $self;
391 }
392  
393 =head2 learn_tagged(\%row or \@rows)
394  
395 Learns one sample supplied as a hashref of named feature values, or a
396 whole batch supplied as an arrayref of such hashrefs, in stream order.
397 The model must have C<feature_names> set. Rows go through
398 L<tagged_row_to_array|/tagged_row_to_array(\%row, $caller)> (and
399 therefore through the munger plan when C<mungers> is configured).
400 Returns C<$self>.
401  
402 $oif->learn_tagged({ cpu => 0.9, mem => 0.4, disk => 0.1 });
403 $oif->learn_tagged(\@hashref_rows);
404  
405 Croaks under the same conditions as
406 L<tagged_row_to_array|/tagged_row_to_array(\%row, $caller)>, naming the
407 offending row by index in the batch form.
408  
409 =cut
410  
411 3 ▶sub learn_tagged {
Subroutine learn_tagged: called CC=3 SCAR=11.0
Pod documented
412 3 my ( $self, $row ) = @_;
413 3 ▶ if ( ref $row eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $row eq "ARRAY") 1 2 3
414 1 my @rows;
415 1 for my $i ( 0 .. $#$row ) {
416 200 push @rows, $self->tagged_row_to_array( $row->[$i], "learn_tagged (row $i)" );
417 }
418 1 return $self->learn( \@rows );
419 }
420 2 my $vec = $self->tagged_row_to_array( $row, 'learn_tagged' );
421 2 return $self->learn( [$vec] );
422 } ## end sub learn_tagged
423  
424 =head2 score_learn(\@data)
425  
426 Prequential (test-then-train) operation, the usual way to run a streaming
427 detector: each sample is scored against the model as it stood I<before>
428 that sample was learned, then learned. Returns an arrayref of anomaly
429 scores, one per sample, in input order.
430  
431 Unlike the pure scoring methods this works on a brand-new model too (the
432 first points of a stream simply score 1.0, as nothing is known yet).
433  
434 my $scores = $oif->score_learn(\@rows);
435  
436 =cut
437  
438 35 ▶sub score_learn {
Subroutine score_learn: called CC=4 SCAR=14.3
Pod documented
439 35 my ( $self, $data ) = @_;
440 35 ▶ croak "score_learn() expects a non-empty arrayref of samples"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "ARRAY" and @$data 0 35 35
Condition33%1/3
ref $data eq "ARRAY" and @$data
!ll&&!rl&&r
0035
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
441 unless ref $data eq 'ARRAY' && @$data;
442 35 my @scores;
443 35 for my $row (@$data) {
444 1925 my $r = $self->_prep_row( $row, 'score_learn' );
445 1924 push @scores, $self->_score_row($r);
446 1924 $self->_learn_row($r);
447 }
448 34 return \@scores;
449 } ## end sub score_learn
450  
451 =head2 score_learn_tagged(\%row)
452  
453 Prequential score-then-learn for a single sample supplied as a hashref of
454 named feature values. Returns the scalar anomaly score the sample had
455 before it was learned.
456  
457 my $score = $oif->score_learn_tagged({ cpu => 0.9, mem => 0.4 });
458  
459 Croaks under the same conditions as L<tagged_row_to_array|/tagged_row_to_array(\%row, $caller)>.
460  
461 =cut
462  
463 2 ▶sub score_learn_tagged {
Subroutine score_learn_tagged: called CC=1 SCAR=0.0
Pod documented
464 2 my ( $self, $row ) = @_;
465 2 my $vec = $self->tagged_row_to_array( $row, 'score_learn_tagged' );
466 2 my $result = $self->score_learn( [$vec] );
467 2 return $result->[0];
468 }
469  
470 =head2 score_samples(\@data)
471  
472 Returns an arrayref of anomaly scores in (0, 1] without learning
473 anything. Scores near 1 are strong anomalies (isolated at shallow
474 depth); scores well below 0.5 are normal.
475  
476 my $scores = $oif->score_samples(\@data);
477  
478 =cut
479  
480 74 ▶sub score_samples {
Subroutine score_samples: called CC=3 SCAR=11.0
Pod documented
481 74 my ( $self, $data ) = @_;
482 74 $self->_check_learned;
483 73 ▶ croak "score_samples() expects an arrayref of samples"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "ARRAY" 0 73 73
484 unless ref $data eq 'ARRAY';
485  
486 73 ▶ if ( $self->_ensure_c_trees ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_ensure_c_trees) 60 13 73
487 60 my ( $n_pts, $x_packed ) = $self->_pack_input($data);
488 60 my $sums_packed = "\0" x ( $n_pts * 8 );
489 Algorithm::Classifier::IsolationForest::score_all_xs(
490 $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
491 $x_packed, $sums_packed, $n_pts,
492 60 $self->{n_features}, scalar @{ $self->{trees} }, $self->{_use_openmp}
493 60 );
494 60 my $result = [];
495 60 Algorithm::Classifier::IsolationForest::finalize_scores_xs( $sums_packed, $n_pts, $self->_score_inv, $result );
496 60 return $result;
497 } ## end if ( $self->_ensure_c_trees )
498  
499 13 my $sums = $self->_depth_sums($data);
500 13 my $inv = $self->_score_inv;
501 13 return [ map { exp( -$_ * $inv ) } @$sums ];
502 } ## end sub score_samples
503  
504 =head2 score_sample_tagged(\%row)
505  
506 Scores a single sample supplied as a hashref of named feature values,
507 without learning it. Returns a scalar anomaly score in (0, 1].
508  
509 my $score = $oif->score_sample_tagged({ cpu => 0.9, mem => 0.4 });
510  
511 Croaks under the same conditions as L<tagged_row_to_array|/tagged_row_to_array(\%row, $caller)>.
512  
513 =cut
514  
515 7 ▶sub score_sample_tagged {
Subroutine score_sample_tagged: called CC=1 SCAR=0.0
Pod documented
516 7 my ( $self, $row ) = @_;
517 7 my $vec = $self->tagged_row_to_array( $row, 'score_sample_tagged' );
518 4 my $result = $self->score_samples( [$vec] );
519 4 return $result->[0];
520 }
521  
522 =head2 explain_samples(\@data, %opts)
523  
524 Explains, per sample, which features drove its anomaly score, without
525 learning anything -- the streaming counterpart of the parent class's
526 method of the same name, returning the identical structure (see
527 C<explain_samples> in L<Algorithm::Classifier::IsolationForest> for the
528 full description of the output shape and the C<method> option):
529  
530 my $explanations = $oif->explain_samples(\@data);
531 my $top = $explanations->[0]{features}[0];
532  
533 Differences from the batch class:
534  
535 The default C<ablation> method substitutes per-feature medians of the
536 currently retained window (there is no fit() to store baselines at;
537 the window IS the model's view of normal, and it tracks drift for
538 free). It therefore requires C<< window_size > 0 >> with learned
539 points and croaks otherwise -- use C<path> on a windowless model.
540  
541 The C<path> method carries an extra caveat on top of the batch class's
542 (see the parent POD): online trees are shallow by construction (the
543 depth budget is C<log(n/max_leaf_samples)/log(4)>) and most of a
544 sample's anomalousness lives in the per-leaf count adjustment rather
545 than in which splits it crossed, so path attributions here are coarse.
546 Treat them as a rough second opinion; prefer C<ablation> whenever a
547 window exists.
548  
549 A model that has not yet accumulated tree structure (fewer than
550 C<max_leaf_samples> points seen) scores everything 1.0 and has no
551 splits to attribute; every weight comes back 0.
552  
553 =cut
554  
555 6 ▶sub explain_samples {
Subroutine explain_samples: called CC=7 SCAR=20.5
Pod documented
556 6 my ( $self, $data, %opts ) = @_;
557 6 $self->_check_learned;
558 6 ▶ croak "explain_samples() expects a non-empty arrayref of samples"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "ARRAY" and @$data 0 6 6
Condition33%1/3
ref $data eq "ARRAY" and @$data
!ll&&!rl&&r
006
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
559 unless ref $data eq 'ARRAY' && @$data;
560  
561 6 ▶ my $method = delete $opts{method} // 'ablation';
Condition100%2/2
delete $opts{"method"} // "ablation"
l!l
33
MC/DC100%1/1
delete $opts{"method"} // "ablation"
delete $opts{"method"}
Truth table100%2/2
A
A= delete $opts{"method"}
Aresult
11
00
562 6 ▶ croak "explain_samples: method must be 'path' or 'ablation'"
Branch: 1 branch
BranchTrueFalseTotal
unless $method =~ /\A(?:path|ablation)\z/ 0 6 6
563 unless $method =~ /\A(?:path|ablation)\z/;
564 6 ▶ croak "explain_samples: unknown option(s): " . join( ', ', sort keys %opts )
Branch: 1 branch
BranchTrueFalseTotal
if %opts 0 6 6
565 if %opts;
566  
567 6 ▶ return $method eq 'ablation'
Branch: 1 branch
BranchTrueFalseTotal
$method eq 'ablation' ? : 4 2 6
568 ? $self->_explain_ablation($data)
569 : $self->_explain_path($data);
570 } ## end sub explain_samples
571  
572 =head2 explain_sample_tagged(\%row, %opts)
573  
574 Explains a single sample supplied as a hashref of named feature values,
575 without learning it. Takes the same C<method> option as
576 L<explain_samples|/explain_samples(\@data, %opts)> and returns the single explanation hashref.
577  
578 my $e = $oif->explain_sample_tagged({ cpu => 0.9, mem => 0.4 });
579  
580 Croaks under the same conditions as L<tagged_row_to_array|/tagged_row_to_array(\%row, $caller)>.
581  
582 =cut
583  
584 1 ▶sub explain_sample_tagged {
Subroutine explain_sample_tagged: called CC=1 SCAR=0.0
Pod documented
585 1 my ( $self, $row, %opts ) = @_;
586 1 my $vec = $self->tagged_row_to_array( $row, 'explain_sample_tagged' );
587 1 return $self->explain_samples( [$vec], %opts )->[0];
588 }
589  
590 =head2 path_lengths(\@data)
591  
592 Returns an arrayref of the mean isolation depth per sample across the
593 trees, for inspection -- the streaming counterpart of the parent class's
594 method of the same name. Depths include the per-leaf count adjustment.
595  
596 my $depths = $oif->path_lengths(\@data);
597  
598 =cut
599  
600 4 ▶sub path_lengths {
Subroutine path_lengths: called CC=3 SCAR=11.0
Pod documented
601 4 my ( $self, $data ) = @_;
602 4 $self->_check_learned;
603 3 ▶ croak "path_lengths() expects an arrayref of samples"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "ARRAY" 0 3 3
604 unless ref $data eq 'ARRAY';
605 3 my $t = scalar @{ $self->{trees} };
606  
607 3 ▶ if ( $self->_ensure_c_trees ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_ensure_c_trees) 2 1 3
608 2 my ( $n_pts, $x_packed ) = $self->_pack_input($data);
609 2 my $sums_packed = "\0" x ( $n_pts * 8 );
610 Algorithm::Classifier::IsolationForest::score_all_xs(
611 $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
612 $x_packed, $sums_packed, $n_pts,
613 $self->{n_features}, $t, $self->{_use_openmp}
614 2 );
615 2 my $result = [];
616 2 Algorithm::Classifier::IsolationForest::finalize_path_lengths_xs( $sums_packed, $n_pts, $t + 0.0, $result );
617 2 return $result;
618 } ## end if ( $self->_ensure_c_trees )
619  
620 1 my $sums = $self->_depth_sums($data);
621 1 return [ map { $_ / $t } @$sums ];
622 } ## end sub path_lengths
623  
624 =head2 predict(\@data, $threshold)
625  
626 Returns an arrayref of 0/1 labels for the specified data, without
627 learning it.
628  
629 If C<$threshold> is not given, the contamination-learned cutoff is used
630 when available (learned from the current window on first use -- see
631 C<contamination> in L<new|/new(%args)>), otherwise 0.5.
632  
633 Note that absolute score levels depend on C<window_size> and
634 C<max_leaf_samples> (shallower depth budgets compress scores downward),
635 so the 0.5 fallback is a blunt default here -- anomalies reliably rank
636 above normal points, but may sit below 0.5. Setting C<contamination>,
637 or passing a threshold calibrated from observed scores, is recommended.
638  
639 my $labels = $oif->predict(\@data);
640  
641 =cut
642  
643 17 ▶sub predict {
Subroutine predict: called CC=7 SCAR=19.5
Pod documented
644 17 my ( $self, $data, $threshold ) = @_;
645 17 $self->_check_learned;
646 16 $self->_ensure_threshold;
647 $threshold
648 = defined $threshold ? $threshold
649 : defined $self->{threshold} ? $self->{threshold}
650 16 ▶ : 0.5;
Branch: 2 branches
BranchTrueFalseTotal
defined $threshold ? : 9 7 16
defined $self->{'threshold'} ? : 7 0 7
651  
652 # Fast path: threshold the raw depth sums directly, skipping the
653 # per-point exp() -- score >= T iff sum <= -log(T)/inv. Only valid
654 # for a normal threshold in (0, 1), like the parent's gate.
655 16 ▶ if ( $threshold > 0 && $threshold < 1 && $self->_ensure_c_trees ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($threshold > 0 and $threshold < 1 and $self->_ensure_c_trees) 9 7 16
Condition83%5/6
$threshold > 0 and $threshold < 1 and $self->_ensure_c_trees
!ll&&!rl&&r
259
$threshold > 0 and $threshold < 1
!ll&&!rl&&r
0214
MC/DC66%2/3
$threshold > 0 and $threshold < 1 and $self->_ensure_c_trees
$threshold > 0 $threshold < 1 $self->_ensure_c_trees
Truth table75%3/4
A and B and C
A= $threshold > 0B= $threshold < 1C= $self->_ensure_c_trees
ABCresult
0XX0
10X0
1100
1111
656 9 my ( $n_pts, $x_packed ) = $self->_pack_input($data);
657 9 my $sums_packed = "\0" x ( $n_pts * 8 );
658 Algorithm::Classifier::IsolationForest::score_all_xs(
659 $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
660 $x_packed, $sums_packed, $n_pts,
661 9 $self->{n_features}, scalar @{ $self->{trees} }, $self->{_use_openmp}
662 9 );
663 9 my $sum_threshold = -log($threshold) / $self->_score_inv;
664 9 my $result = [];
665 9 Algorithm::Classifier::IsolationForest::predict_sums_xs( $sums_packed, $n_pts, $sum_threshold, $result );
666 9 return $result;
667 } ## end if ( $threshold > 0 && $threshold < 1 && $self...)
668  
669 7 my $scores = $self->score_samples($data);
670 7 ▶ return [ map { $_ >= $threshold ? 1 : 0 } @$scores ];
Branch: 1 branch
BranchTrueFalseTotal
$_ >= $threshold ? : 9 26 35
671 } ## end sub predict
672  
673 =head2 predict_tagged(\%row, $threshold)
674  
675 Predicts whether a single sample, supplied as a hashref of named feature
676 values, is an anomaly. Returns a scalar 1 (anomaly) or 0 (normal).
677 C<$threshold> defaults the same way as in L<predict|/predict(\@data, $threshold)>.
678  
679 my $label = $oif->predict_tagged({ cpu => 0.9, mem => 0.4 });
680  
681 Croaks under the same conditions as L<tagged_row_to_array|/tagged_row_to_array(\%row, $caller)>.
682  
683 =cut
684  
685 1 ▶sub predict_tagged {
Subroutine predict_tagged: called CC=1 SCAR=0.0
Pod documented
686 1 my ( $self, $row, $threshold ) = @_;
687 1 my $vec = $self->tagged_row_to_array( $row, 'predict_tagged' );
688 1 my $result = $self->predict( [$vec], $threshold );
689 1 return $result->[0];
690 }
691  
692 =head2 score_predict_samples(\@data, $threshold)
693  
694 Returns an arrayref of C<[$score, $label]> pairs, one per sample, without
695 learning. C<$threshold> defaults the same way as in L<predict|/predict(\@data, $threshold)>.
696  
697 my $results = $oif->score_predict_samples(\@data);
698  
699 =cut
700  
701 4 ▶sub score_predict_samples {
Subroutine score_predict_samples: called CC=7 SCAR=19.6
Pod documented
702 4 my ( $self, $data, $threshold ) = @_;
703 4 $self->_check_learned;
704 4 $self->_ensure_threshold;
705 $threshold
706 = defined $threshold ? $threshold
707 : defined $self->{threshold} ? $self->{threshold}
708 4 ▶ : 0.5;
Branch: 2 branches
BranchTrueFalseTotal
defined $threshold ? : 2 2 4
defined $self->{'threshold'} ? : 2 0 2
709  
710 # Fast path: [score, label] pairs built straight from the sum buffer
711 # in one C call; gated identically to predict().
712 4 ▶ if ( $threshold > 0 && $threshold < 1 && $self->_ensure_c_trees ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($threshold > 0 and $threshold < 1 and $self->_ensure_c_trees) 3 1 4
Condition50%3/6
$threshold > 0 and $threshold < 1 and $self->_ensure_c_trees
!ll&&!rl&&r
013
$threshold > 0 and $threshold < 1
!ll&&!rl&&r
004
MC/DC33%1/3
$threshold > 0 and $threshold < 1 and $self->_ensure_c_trees
$threshold > 0 $threshold < 1 $self->_ensure_c_trees
Truth table50%2/4
A and B and C
A= $threshold > 0B= $threshold < 1C= $self->_ensure_c_trees
ABCresult
0XX0
10X0
1100
1111
713 3 my ( $n_pts, $x_packed ) = $self->_pack_input($data);
714 3 my $sums_packed = "\0" x ( $n_pts * 8 );
715 Algorithm::Classifier::IsolationForest::score_all_xs(
716 $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
717 $x_packed, $sums_packed, $n_pts,
718 3 $self->{n_features}, scalar @{ $self->{trees} }, $self->{_use_openmp}
719 3 );
720 3 my $inv = $self->_score_inv;
721 3 my $sum_threshold = -log($threshold) / $inv;
722 3 my $result = [];
723 3 Algorithm::Classifier::IsolationForest::score_predict_xs( $sums_packed, $n_pts, $inv, $sum_threshold, $result );
724 3 return $result;
725 } ## end if ( $threshold > 0 && $threshold < 1 && $self...)
726  
727 1 my $scores = $self->score_samples($data);
728 1 ▶ return [ map { [ $_, ( $_ >= $threshold ? 1 : 0 ) ] } @$scores ];
Branch: 1 branch
BranchTrueFalseTotal
$_ >= $threshold ? : 2 3 5
729 } ## end sub score_predict_samples
730  
731 =head2 score_predict_sample_tagged(\%row, $threshold)
732  
733 Scores and classifies a single sample supplied as a hashref of named
734 feature values. Returns a two-element arrayref C<[$score, $label]>.
735 C<$threshold> defaults the same way as in L<predict|/predict(\@data, $threshold)>.
736  
737 my $pair = $oif->score_predict_sample_tagged({ cpu => 0.9, mem => 0.4 });
738  
739 Croaks under the same conditions as L<tagged_row_to_array|/tagged_row_to_array(\%row, $caller)>.
740  
741 =cut
742  
743 1 ▶sub score_predict_sample_tagged {
Subroutine score_predict_sample_tagged: called CC=1 SCAR=0.0
Pod documented
744 1 my ( $self, $row, $threshold ) = @_;
745 1 my $vec = $self->tagged_row_to_array( $row, 'score_predict_sample_tagged' );
746 1 my $result = $self->score_predict_samples( [$vec], $threshold );
747 1 return $result->[0];
748 }
749  
750 =head2 score_predict_split(\@data, $threshold)
751  
752 Same values as
753 L<score_predict_samples|/score_predict_samples(\@data, $threshold)>
754 but returned as two flat
755 arrayrefs. In list context returns C<($scores_aref, $labels_aref)>.
756  
757 my ($scores, $labels) = $oif->score_predict_split(\@data);
758  
759 =cut
760  
761 3 ▶sub score_predict_split {
Subroutine score_predict_split: called CC=7 SCAR=19.6
Pod documented
762 3 my ( $self, $data, $threshold ) = @_;
763 3 $self->_check_learned;
764 3 $self->_ensure_threshold;
765 $threshold
766 = defined $threshold ? $threshold
767 : defined $self->{threshold} ? $self->{threshold}
768 3 ▶ : 0.5;
Branch: 2 branches
BranchTrueFalseTotal
defined $threshold ? : 1 2 3
defined $self->{'threshold'} ? : 2 0 2
769  
770 # Fast path: two flat arrayrefs straight from the sum buffer; gated
771 # identically to predict().
772 3 ▶ if ( $threshold > 0 && $threshold < 1 && $self->_ensure_c_trees ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($threshold > 0 and $threshold < 1 and $self->_ensure_c_trees) 2 1 3
Condition50%3/6
$threshold > 0 and $threshold < 1 and $self->_ensure_c_trees
!ll&&!rl&&r
012
$threshold > 0 and $threshold < 1
!ll&&!rl&&r
003
MC/DC33%1/3
$threshold > 0 and $threshold < 1 and $self->_ensure_c_trees
$threshold > 0 $threshold < 1 $self->_ensure_c_trees
Truth table50%2/4
A and B and C
A= $threshold > 0B= $threshold < 1C= $self->_ensure_c_trees
ABCresult
0XX0
10X0
1100
1111
773 2 my ( $n_pts, $x_packed ) = $self->_pack_input($data);
774 2 my $sums_packed = "\0" x ( $n_pts * 8 );
775 Algorithm::Classifier::IsolationForest::score_all_xs(
776 $self->{_c_nodes}, $self->{_c_coef_idx}, $self->{_c_coef_val},
777 $x_packed, $sums_packed, $n_pts,
778 2 $self->{n_features}, scalar @{ $self->{trees} }, $self->{_use_openmp}
779 2 );
780 2 my $inv = $self->_score_inv;
781 2 my $sum_threshold = -log($threshold) / $inv;
782 2 my $scores = [];
783 2 my $labels = [];
784 2 Algorithm::Classifier::IsolationForest::score_predict_split_xs( $sums_packed, $n_pts, $inv,
785 $sum_threshold, $scores, $labels );
786 2 return ( $scores, $labels );
787 } ## end if ( $threshold > 0 && $threshold < 1 && $self...)
788  
789 1 my $scores = $self->score_samples($data);
790 1 ▶ my @labels = map { $_ >= $threshold ? 1 : 0 } @$scores;
Branch: 1 branch
BranchTrueFalseTotal
$_ >= $threshold ? : 2 3 5
791 1 return ( $scores, \@labels );
792 } ## end sub score_predict_split
793  
794 =head2 relearn_threshold(\@data)
795  
796 Re-derives the contamination decision threshold so it flags the requested
797 fraction of the current window (or of C<\@data>, when passed). Call this
798 after the stream has drifted, or on whatever cadence threshold freshness
799 matters; learning alone never moves the threshold.
800  
801 Requires C<contamination> to have been set. With C<< window_size => 0 >>
802 no window is retained, so C<\@data> must be supplied.
803  
804 Returns C<$self>, so it chains.
805  
806 $oif->relearn_threshold;
807  
808 =cut
809  
810 9 ▶sub relearn_threshold {
Subroutine relearn_threshold: called CC=7 SCAR=19.6
Pod documented
811 9 my ( $self, $data ) = @_;
812 croak "relearn_threshold requires contamination to have been set in new()"
813 9 ▶ unless defined $self->{contamination};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"contamination"} 2 7 9
814 7 ▶ my $rows = defined $data ? $data : $self->{window};
Branch: 1 branch
BranchTrueFalseTotal
defined $data ? : 1 6 7
815 7 ▶ croak "relearn_threshold: no retained window to learn a threshold from "
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rows eq "ARRAY" and @$rows 1 6 7
Condition66%2/3
ref $rows eq "ARRAY" and @$rows
!ll&&!rl&&r
016
MC/DC50%1/2
ref $rows eq "ARRAY" and @$rows
ref $rows eq "ARRAY" @$rows
Truth table66%2/3
A and B
A= ref $rows eq "ARRAY"B= @$rows
ABresult
0X0
100
111
816 . "(window_size is 0); pass an arrayref of recent data"
817 unless ref $rows eq 'ARRAY' && @$rows;
818  
819 6 my $scores = $self->score_samples($rows);
820 6 my @desc = sort { $b <=> $a } @$scores;
821 6 my $n_pts = scalar @desc;
822 6 my $k = int( $self->{contamination} * $n_pts + 0.5 );
823 6 ▶ $k = 1 if $k < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $k < 1 0 6 6
824 6 ▶ $k = $n_pts if $k > $n_pts;
Branch: 1 branch
BranchTrueFalseTotal
if $k > $n_pts 0 6 6
825 6 $self->{threshold} = Algorithm::Classifier::IsolationForest::_threshold_from_ranked( \@desc, $k );
826 6 return $self;
827 } ## end sub relearn_threshold
828  
829 =head2 decision_threshold
830  
831 The score cutoff the predict methods use by default; undef unless
832 C<contamination> was set and a predict-family method or
833 L<relearn_threshold|/relearn_threshold(\@data)> has run.
834  
835 =cut
836  
837 43 ▶sub decision_threshold { return $_[0]->{threshold} }
Subroutine decision_threshold: called CC=1 SCAR=0.0
Pod documented
838  
839 =head2 feature_names
840  
841 Returns the arrayref of feature name strings stored with the model, or
842 undef if none were provided.
843  
844 =cut
845  
846 2 ▶sub feature_names { return $_[0]->{feature_names} }
Subroutine feature_names: called CC=1 SCAR=0.0
Pod documented
847  
848 =head2 schema_version
849  
850 Returns the user-owned schema version string stored with the model
851 (usually via a prototype -- see PROTOTYPES in
852 L<Algorithm::Classifier::IsolationForest>), or undef if none was
853 recorded.
854  
855 =cut
856  
857 2 ▶sub schema_version { return $_[0]->{schema_version} }
Subroutine schema_version: called CC=1 SCAR=0.0
Pod documented
858  
859 =head2 schema_description
860  
861 Returns the free-text description of the variable schema stored with the
862 model, or undef if none was recorded.
863  
864 =cut
865  
866 0 ▶sub schema_description { return $_[0]->{schema_description} }
Subroutine schema_description: not called CC=1 SCAR=6.9
Pod documented
867  
868 =head2 feature_descriptions
869  
870 Returns the hashref of per-feature description strings stored with the
871 model, or undef if none were recorded. Keys are feature names; coverage
872 may be partial.
873  
874 =cut
875  
876 3 ▶sub feature_descriptions { return $_[0]->{feature_descriptions} }
Subroutine feature_descriptions: called CC=1 SCAR=0.0
Pod documented
877  
878 =head2 window_count
879  
880 Returns how many points the model currently retains in its sliding
881 window (0 when C<< window_size => 0 >>).
882  
883 =cut
884  
885 22 ▶sub window_count { return scalar @{ $_[0]->{window} } }
Subroutine window_count: called CC=1 SCAR=0.0
Pod documented
886  
887 =head2 seen
888  
889 Returns the total number of points learned over the model's lifetime,
890 including points that have since been forgotten.
891  
892 =cut
893  
894 37 ▶sub seen { return $_[0]->{seen} }
Subroutine seen: called CC=1 SCAR=0.0
Pod documented
895  
896 =head2 tagged_row_to_array(\%row, $caller)
897  
898 Validates a hashref of named feature values against the model's stored
899 C<feature_names> and returns a positional arrayref. Identical semantics
900 to the parent class's method of the same name (to which it delegates);
901 see there for the croak conditions.
902  
903 =cut
904  
905 281 ▶sub tagged_row_to_array {
Subroutine tagged_row_to_array: called CC=1 SCAR=0.0
Pod documented
906 281 my $self = shift;
907 281 return Algorithm::Classifier::IsolationForest::tagged_row_to_array( $self, @_ );
908 }
909  
910 =head2 munge_rows(\@rows)
911  
912 Applies the model's scalar mungers to positional rows, exactly as the
913 parent class's method of the same name (to which it delegates); a model
914 without C<mungers> returns the input unchanged.
915  
916 =cut
917  
918 2 ▶sub munge_rows {
Subroutine munge_rows: called CC=1 SCAR=0.0
Pod documented
919 2 my $self = shift;
920 2 return Algorithm::Classifier::IsolationForest::munge_rows( $self, @_ );
921 }
922  
923 =head1 MODEL SAVE/LOAD METHODS
924  
925 Persistence keeps the sliding window alongside the trees, so a reloaded
926 model continues forgetting correctly as the stream resumes. This makes
927 saved online models larger than batch models by O(window_size *
928 n_features). Perl's RNG state is not persisted: a save/reload point
929 breaks bit-for-bit reproducibility of subsequent learning versus an
930 uninterrupted run, though scoring of the reloaded model is exact.
931  
932 =head2 to_json
933  
934 Returns a JSON representation of the model.
935  
936 my $json = $oif->to_json;
937  
938 =cut
939  
940 32 ▶sub to_json {
Subroutine to_json: called CC=1 SCAR=0.0
Pod documented
941 32 my ($self) = @_;
942 my $payload = {
943 format => 'Algorithm::Classifier::IsolationForest::Online',
944 version => 1,
945 params => {
946 n_trees => $self->{n_trees},
947 window_size => $self->{window_size},
948 max_leaf_samples => $self->{max_leaf_samples},
949 growth => $self->{growth},
950 subsample => $self->{subsample},
951 contamination => $self->{contamination},
952 threshold => $self->{threshold},
953 n_features => $self->{n_features},
954 missing => $self->{missing},
955 feature_names => $self->{feature_names},
956 seen => $self->{seen},
957 mungers => $self->{mungers},
958 munger_module_version => $self->{munger_module_version},
959 schema_version => $self->{schema_version},
960 schema_description => $self->{schema_description},
961 feature_descriptions => $self->{feature_descriptions},
962 },
963 630 trees => [ map { { count => $_->{count}, root => $_->{root} } } @{ $self->{trees} } ],
964 window => $self->{window},
965 32 };
966 32 return JSON::PP->new->canonical(1)->encode($payload);
967 } ## end sub to_json
968  
969 =head2 from_json($json)
970  
971 Init the object from the model in the specified JSON string.
972  
973 my $oif = Algorithm::Classifier::IsolationForest::Online->from_json($json);
974  
975 =cut
976  
977 18 ▶sub from_json {
Subroutine from_json: called CC=13 SCAR=29.8
Pod documented
978 18 my ( $class, $text ) = @_;
979 18 my $payload = JSON::PP->new->decode($text);
980 croak "not an online IsolationForest model"
981 unless ref $payload eq 'HASH'
982 && defined $payload->{format}
983 18 ▶ && $payload->{format} eq 'Algorithm::Classifier::IsolationForest::Online';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $payload eq "HASH" and defined $payload->{"format"} and $payload->{"format"} eq "Algorithm::Classifier::IsolationForest::Online" 2 16 18
Condition50%3/6
ref $payload eq "HASH" and defined $payload->{"format"} and $payload->{"format"} eq "Algorithm::Classifier::IsolationForest::Online"
!ll&&!rl&&r
0216
ref $payload eq "HASH" and defined $payload->{"format"}
!ll&&!rl&&r
0018
MC/DC33%1/3
ref $payload eq "HASH" and defined $payload->{"format"} and $payload->{"format"} eq "Algorithm::Classifier::IsolationForest::Online"
ref $payload eq "HASH" defined $payload->{"format"} $payload->{"format"} eq "Algorithm::Classifier::IsolationForest::Online"
Truth table50%2/4
A and B and C
A= ref $payload eq "HASH"B= defined $payload->{"format"}C= $payload->{"format"} eq "Algorithm::Classifier::IsolationForest::Online"
ABCresult
0XX0
10X0
1100
1111
984  
985 16 ▶ my $p = $payload->{params} || {};
Condition50%1/2
$payload->{'params'} || {}
l!l
160
MC/DC0%0/1
$payload->{'params'} || {}
$payload->{'params'}
Truth table50%1/2
A
A= $payload->{'params'}
Aresult
11
00
986  
987 my $self = {
988 n_trees => $p->{n_trees},
989 window_size => $p->{window_size} // 0,
990 max_leaf_samples => $p->{max_leaf_samples},
991 growth => $p->{growth} // 'adaptive',
992 subsample => $p->{subsample} // 1.0,
993 seed => undef,
994 contamination => $p->{contamination},
995 threshold => $p->{threshold},
996 n_features => $p->{n_features},
997 missing => $p->{missing} // 'die',
998 feature_names => $p->{feature_names},
999 # Recompiled lazily on first tagged use, like the parent.
1000 mungers => $p->{mungers},
1001 munger_module_version => $p->{munger_module_version},
1002 # Opaque schema metadata; absent in models saved before prototype
1003 # support, which just means "none recorded".
1004 schema_version => $p->{schema_version},
1005 schema_description => $p->{schema_description},
1006 feature_descriptions => $p->{feature_descriptions},
1007 seen => $p->{seen} // 0,
1008 16 ▶ window => $payload->{window} // [],
Condition50%6/12
$p->{"window_size"} // 0
l!l
160
$p->{"growth"} // "adaptive"
l!l
160
$p->{"subsample"} // 1
l!l
160
$p->{"missing"} // "die"
l!l
160
$p->{"seen"} // 0
l!l
160
$payload->{"window"} // []
l!l
160
MC/DC0%0/1
$p->{"window_size"} // 0
$p->{"window_size"}
MC/DC0%0/1
$p->{"growth"} // "adaptive"
$p->{"growth"}
MC/DC0%0/1
$p->{"subsample"} // 1
$p->{"subsample"}
MC/DC0%0/1
$p->{"missing"} // "die"
$p->{"missing"}
MC/DC0%0/1
$p->{"seen"} // 0
$p->{"seen"}
MC/DC0%0/1
$payload->{"window"} // []
$payload->{"window"}
Truth table50%1/2
A
A= $p->{"window_size"}
Aresult
11
00
Truth table50%1/2
A
A= $p->{"growth"}
Aresult
11
00
Truth table50%1/2
A
A= $p->{"subsample"}
Aresult
11
00
Truth table50%1/2
A
A= $p->{"missing"}
Aresult
11
00
Truth table50%1/2
A
A= $p->{"seen"}
Aresult
11
00
Truth table50%1/2
A
A= $payload->{"window"}
Aresult
11
00
1009 trees => [],
1010 _use_c => $Algorithm::Classifier::IsolationForest::HAS_C,
1011 _use_openmp => $Algorithm::Classifier::IsolationForest::HAS_OPENMP,
1012 };
1013  
1014 16 my $trees = $payload->{trees};
1015 16 ▶ croak "model contains no trees" unless ref $trees eq 'ARRAY' && @$trees;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $trees eq "ARRAY" and @$trees 0 16 16
Condition33%1/3
ref $trees eq "ARRAY" and @$trees
!ll&&!rl&&r
0016
MC/DC0%0/2
ref $trees eq "ARRAY" and @$trees
ref $trees eq "ARRAY" @$trees
Truth table33%1/3
A and B
A= ref $trees eq "ARRAY"B= @$trees
ABresult
0X0
100
111
1016  
1017 16 my $model = bless $self, $class;
1018  
1019 # depth_limit is a pure function of the tree's count, so recompute it
1020 # rather than trusting a stored float.
1021 $self->{trees}
1022 16 = [ map { { count => $_->{count}, root => $_->{root}, depth_limit => $model->_rpl( $_->{count} ) } } @$trees ];
1023  
1024 16 return $model;
1025 } ## end sub from_json
1026  
1027 =head2 save($path)
1028  
1029 Saves the model to the specified path.
1030  
1031 $oif->save($path);
1032  
1033 =cut
1034  
1035 11 ▶sub save {
Subroutine save: called CC=1 SCAR=0.0
Pod documented
1036 11 my ( $self, $path ) = @_;
1037 11 write_file( $path, { 'atomic' => 1 }, $self->to_json );
1038 }
1039  
1040 =head2 load($path)
1041  
1042 Init the object from the model in the specified file.
1043  
1044 my $oif = Algorithm::Classifier::IsolationForest::Online->load($path);
1045  
1046 =cut
1047  
1048 2 ▶sub load {
Subroutine load: called CC=1 SCAR=0.0
Pod documented
1049 2 my ( $class, $path ) = @_;
1050 2 my $raw_model = read_file($path);
1051 2 return $class->from_json($raw_model);
1052 }
1053  
1054 =head2 to_prototype
1055  
1056 Returns a prototype JSON string extracted from this model: its variable
1057 schema (feature_names, feature_descriptions, mungers, missing policy)
1058 plus its current tuning knobs, with C<"class": "online">. Identical
1059 semantics to the parent class's method -- see PROTOTYPES in
1060 L<Algorithm::Classifier::IsolationForest> for the file format and the
1061 croak/placeholder rules. C<seed> is not emitted; pass it as an override
1062 when creating from the prototype.
1063  
1064 my $proto_json = $oif->to_prototype;
1065  
1066 =cut
1067  
1068 1 ▶sub to_prototype {
Subroutine to_prototype: called CC=10 SCAR=28.2
Pod documented
1069 1 my ($self) = @_;
1070 croak "to_prototype: this model has no feature_names; a prototype's variable " . "schema needs named features"
1071 1 ▶ 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"};} 0 1 1
Condition33%1/3
ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};}
!ll&&!rl&&r
001
MC/DC0%0/2
ref $self->{"feature_names"} eq "ARRAY" and @{$self->{"feature_names"};}
ref $self->{"feature_names"} eq "ARRAY" @{$self->{"feature_names"};}
Truth table33%1/3
A and B
A= ref $self->{"feature_names"} eq "ARRAY"B= @{$self->{"feature_names"};}
ABresult
0X0
100
111
1072  
1073 my $schema = {
1074 feature_names => $self->{feature_names},
1075 missing => $self->{missing},
1076 1 };
1077 $schema->{feature_descriptions} = $self->{feature_descriptions}
1078 1 ▶ 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 0 1
Condition33%1/3
ref $self->{"feature_descriptions"} eq "HASH" and %{$self->{"feature_descriptions"};}
!ll&&!rl&&r
001
MC/DC0%0/2
ref $self->{"feature_descriptions"} eq "HASH" and %{$self->{"feature_descriptions"};}
ref $self->{"feature_descriptions"} eq "HASH" %{$self->{"feature_descriptions"};}
Truth table33%1/3
A and B
A= ref $self->{"feature_descriptions"} eq "HASH"B= %{$self->{"feature_descriptions"};}
ABresult
0X0
100
111
1079 $schema->{mungers} = $self->{mungers}
1080 0 ▶ if ref $self->{mungers} eq 'HASH' && %{ $self->{mungers} };
Branch: 1 branch
BranchTrueFalseTotal
if ref $self->{"mungers"} eq "HASH" and %{$self->{"mungers"};} 0 1 1
Condition33%1/3
ref $self->{"mungers"} eq "HASH" and %{$self->{"mungers"};}
!ll&&!rl&&r
100
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
1081  
1082 my $params = {
1083 n_trees => $self->{n_trees},
1084 window_size => $self->{window_size},
1085 max_leaf_samples => $self->{max_leaf_samples},
1086 growth => $self->{growth},
1087 subsample => $self->{subsample},
1088 1 };
1089 1 ▶ $params->{contamination} = $self->{contamination} if defined $self->{contamination};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"contamination"} 0 1 1
1090  
1091 return JSON::PP->new->canonical(1)->encode(
1092 {
1093 format => 'Algorithm::Classifier::IsolationForest::Prototype',
1094 version => 1,
1095 class => 'online',
1096 schema_version => $self->{schema_version} // '0',
1097 schema_description => $self->{schema_description}
1098 1 ▶ // '(none recorded; describe this schema and bump schema_version)',
Condition50%2/4
$self->{"schema_version"} // 0
l!l
10
$self->{"schema_description"} // "(none recorded; describe this schema and bump schema_version)"
l!l
10
MC/DC0%0/1
$self->{"schema_version"} // 0
$self->{"schema_version"}
MC/DC0%0/1
$self->{"schema_description"} // "(none recorded; describe this schema and bump schema_version)"
$self->{"schema_description"}
Truth table50%1/2
A
A= $self->{"schema_version"}
Aresult
11
00
Truth table50%1/2
A
A= $self->{"schema_description"}
Aresult
11
00
1099 schema => $schema,
1100 params => $params,
1101 }
1102 );
1103 } ## end sub to_prototype
1104  
1105 =head1 REFERENCES
1106  
1107 Filippo Leveni, Guilherme Weigert Cassales, Bernhard Pfahringer, Albert
1108 Bifet, Giacomo Boracchi (2024). Online Isolation Forest.
1109  
1110 L<https://arxiv.org/abs/2505.09593>
1111  
1112 L<https://github.com/ineveLoppiliF/Online-Isolation-Forest>
1113  
1114 L<https://proceedings.mlr.press/v235/leveni24a.html>
1115  
1116 =cut
1117  
1118 ###
1119 ###
1120 ### internal stuff below
1121 ###
1122 ###
1123  
1124 # Guard for every method that needs a model with something in it. The
1125 # online counterpart of the parent's _check_fitted: there is no fit() here,
1126 # so "usable" means at least one point has been learned.
1127 #
1128 # Args: none beyond the model itself.
1129 #
1130 # Returns: nothing on success. Croaks when the model has seen no points --
1131 # a fresh model that has not been fed anything yet.
1132 #
1133 # Example:
1134 # $self->_check_learned; # croaks with "model has not learned any data yet"
1135 108 ▶sub _check_learned {
Subroutine _check_learned: called CC=2 SCAR=6.9
1136 108 my ($self) = @_;
1137 croak "model has not learned any data yet; call learn() first"
1138 108 ▶ unless $self->{seen} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"seen"} > 0 3 105 108
1139 }
1140  
1141 # Validate one incoming sample, apply the missing-value strategy, and
1142 # return a fresh dense copy (the window owns its rows; the caller may
1143 # reuse or mutate the original). Locks in n_features on first contact.
1144 #
1145 # Args:
1146 # $row :: one sample, a non-empty arrayref of feature values. undef
1147 # cells are allowed only under missing => 'zero'.
1148 # $caller :: the public method's name, used to prefix croak messages so
1149 # the error names what the user actually called.
1150 #
1151 # Returns: a fresh dense arrayref, safe for the window to keep. Croaks
1152 # when $row is not a non-empty arrayref, when its width disagrees with the
1153 # width the first row established, or when it holds an undef cell under
1154 # missing => 'die'.
1155 #
1156 # Example:
1157 # my $r = $self->_prep_row( [ 0.9, undef ], 'learn' ); # [ 0.9, 0 ]
1158 17093 ▶sub _prep_row {
Subroutine _prep_row: called CC=9 SCAR=22.1
1159 17093 my ( $self, $row, $caller ) = @_;
1160 17093 ▶ croak "$caller: each sample must be an arrayref of features"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "ARRAY" and @$row 0 17093 17093
Condition33%1/3
ref $row eq "ARRAY" and @$row
!ll&&!rl&&r
0017093
MC/DC0%0/2
ref $row eq "ARRAY" and @$row
ref $row eq "ARRAY" @$row
Truth table33%1/3
A and B
A= ref $row eq "ARRAY"B= @$row
ABresult
0X0
100
111
1161 unless ref $row eq 'ARRAY' && @$row;
1162  
1163 17093 ▶ if ( !defined $self->{n_features} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $self->{'n_features'}) { } 51 17042 17093
elsif (scalar @$row != $self->{'n_features'}) { } 2 17040 17042
1164 51 $self->{n_features} = scalar @$row;
1165 } elsif ( scalar @$row != $self->{n_features} ) {
1166 2 croak "$caller: sample has " . scalar(@$row) . " features but model expects " . $self->{n_features};
1167 }
1168  
1169 17091 ▶ if ( $self->{missing} eq 'die' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"missing"} eq "die") 16041 1050 17091
1170 16041 for my $f ( 0 .. $#$row ) {
1171 33793 ▶ next if defined $row->[$f];
Branch: 1 branch
BranchTrueFalseTotal
if defined $row->[$f] 33792 1 33793
1172 1 croak "$caller: undef feature value at column $f; "
1173 . "construct with missing => 'zero' to learn from data with missing values";
1174 }
1175 16040 return [@$row];
1176 }
1177  
1178 # zero: a missing cell counts as the value 0.
1179 1050 ▶ return [ map { $_ // 0 } @$row ];
Condition100%2/2
$_ // 0
l!l
1959141
MC/DC100%1/1
$_ // 0
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
1180 } ## end sub _prep_row
1181  
1182 # The depth budget for n points: how deep a tree fed n points is allowed
1183 # (learn) or expected (scoring normalisation, per-leaf adjustment) to
1184 # go. log base 4 = log(2 * branching_factor) with binary trees. Under
1185 # max_leaf_samples points there is nothing to isolate: 0.
1186 #
1187 # Args:
1188 # $n :: a point count, non-negative. A tree's count when budgeting its
1189 # depth, a leaf's count when adjusting a path length.
1190 #
1191 # Returns: the depth budget as a float, 0 for n below max_leaf_samples and
1192 # growing logarithmically past it.
1193 #
1194 # Example:
1195 # $self->_rpl(32); # 0 at the default max_leaf_samples of 32
1196 # $self->_rpl(2048); # ~3.0
1197 111953 ▶sub _rpl {
Subroutine _rpl: called CC=2 SCAR=6.9
1198 111953 my ( $self, $n ) = @_;
1199 111953 my $eta = $self->{max_leaf_samples};
1200 111953 ▶ return 0 if $n < $eta;
Branch: 1 branch
BranchTrueFalseTotal
if $n < $eta 5804 106149 111953
1201 106149 return log( $n / $eta ) / _LOG4;
1202 }
1203  
1204 # How many points a node at $depth needs before it may split (or below
1205 # which, on forgetting, it collapses back into a leaf). Learning and
1206 # forgetting both go through it, which is what keeps a tree's shape a
1207 # function of its current contents rather than of the order it saw them.
1208 #
1209 # Args:
1210 # $depth :: the node's depth, 0 at the root.
1211 #
1212 # Returns: the required point count. A flat max_leaf_samples under
1213 # growth => 'fixed'; doubling per level under 'adaptive', so deep nodes
1214 # need proportionally more evidence before splitting.
1215 #
1216 # Example:
1217 # $self->_split_threshold(0); # 32 at the default max_leaf_samples
1218 # $self->_split_threshold(3); # 256 under growth => 'adaptive'
1219 86917 ▶sub _split_threshold {
Subroutine _split_threshold: called CC=2 SCAR=6.9
1220 86917 my ( $self, $depth ) = @_;
1221 86917 ▶ return $self->{max_leaf_samples} * ( $self->{growth} eq 'adaptive' ? 2**$depth : 1 );
Branch: 1 branch
BranchTrueFalseTotal
$self->{'growth'} eq 'adaptive' ? : 70435 16482 86917
1222 }
1223  
1224 # Number of points the model currently reflects: the window fill, or the
1225 # whole stream when forgetting is disabled. This is the population the
1226 # score normaliser is computed against, so it moves as the stream does.
1227 #
1228 # Args: none beyond the model itself.
1229 #
1230 # Returns: the point count as an integer -- the retained window's length,
1231 # or the lifetime seen count under window_size 0.
1232 #
1233 # Example:
1234 # $self->_data_size; # 2048 once a default window has filled
1235 2011 ▶sub _data_size {
Subroutine _data_size: called CC=2 SCAR=6.9
1236 2011 my ($self) = @_;
1237 2011 ▶ return $self->{window_size} ? scalar @{ $self->{window} } : $self->{seen};
Branch: 1 branch
BranchTrueFalseTotal
$self->{'window_size'} ? : 1908 103 2011
1238 }
1239  
1240 # exp() multiplier turning a per-sample depth SUM into the normalised
1241 # anomaly score: 2**(-(sum/t)/norm) == exp(-sum * log(2)/(t*norm)).
1242 # _EPS keeps a zero normaliser (fewer than max_leaf_samples points seen)
1243 # well-defined; every depth is 0 then, so everything scores 1.0.
1244 #
1245 # Args: none beyond the model itself. The value tracks the current window
1246 # fill, so it has to be recomputed whenever the stream has moved.
1247 #
1248 # Returns: the multiplier as a float. Feed it a depth sum and exp() turns
1249 # the product into the anomaly score.
1250 #
1251 # Example:
1252 # my $inv = $self->_score_inv;
1253 # my $score = exp( -$depth_sum * $inv ); # in (0, 1]
1254 2011 ▶sub _score_inv {
Subroutine _score_inv: called CC=1 SCAR=0.0
1255 2011 my ($self) = @_;
1256 2011 my $norm = $self->_rpl( $self->_data_size * $self->{subsample} );
1257 2011 return _LOG2 / ( $self->{n_trees} * ( $norm + _EPS ) );
1258 }
1259  
1260 #-------------------------------------------------------------------------------
1261 # Learning.
1262 #-------------------------------------------------------------------------------
1263  
1264 # Advance the stream by one (already prepped) row: every tree learns it
1265 # (subject to subsampling), it enters the window, and the oldest point
1266 # beyond the window is forgotten. This is the single choke point through
1267 # which every tree mutation flows, so it is also where the packed C
1268 # scoring snapshot gets invalidated.
1269 #
1270 # With use_c the per-tree learn and eviction loops run inside the
1271 # parent's C backend (online_learn_row_xs / online_unlearn_row_xs),
1272 # mutating the same live trees this file's Perl recursion would. Random
1273 # draws go through the same generator in the same order, so the trees
1274 # built are bit-identical either way (on nvsize == 8 perls) -- use_c
1275 # only changes speed, matching fit()'s guarantee.
1276 #
1277 # Args:
1278 # $r :: one sample, already through _prep_row -- dense, width-checked,
1279 # and owned by the model, since the window keeps this very
1280 # reference rather than a copy.
1281 #
1282 # Returns: nothing. Advances seen, mutates the trees, appends to the
1283 # window and evicts the oldest point once the window is over size.
1284 #
1285 # Example:
1286 # $self->_learn_row( $self->_prep_row( [ 0.9, 0.4 ], 'learn' ) );
1287 # $self->seen; # one higher than before
1288 17090 ▶sub _learn_row {
Subroutine _learn_row: called CC=13 SCAR=25.6
1289 17090 my ( $self, $r ) = @_;
1290 17090 my $sub = $self->{subsample};
1291  
1292 17090 $self->_invalidate_c_trees;
1293  
1294 17090 ▶ if ( _HAS_ONLINE_XS && $self->{_use_c} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_use_c'}) { } 14090 3000 17090
1295 Algorithm::Classifier::IsolationForest::online_learn_row_xs(
1296 $self->{trees}, $r, $self->{n_features},
1297 $self->{max_leaf_samples},
1298 14090 ▶ ( $self->{growth} eq 'adaptive' ? 1 : 0 ), $sub
Branch: 1 branch
BranchTrueFalseTotal
$self->{'growth'} eq 'adaptive' ? : 13440 650 14090
1299 );
1300 } else {
1301 3000 for my $tree ( @{ $self->{trees} } ) {
1302 46500 ▶ next if $sub < 1 && rand() >= $sub;
Branch: 1 branch
BranchTrueFalseTotal
if $sub < 1 and rand() >= $sub 2029 44471 46500
Condition100%3/3
$sub < 1 and rand() >= $sub
!ll&&!rl&&r
3975047212029
MC/DC100%2/2
$sub < 1 and rand() >= $sub
$sub < 1 rand() >= $sub
Truth table100%3/3
A and B
A= $sub < 1B= rand() >= $sub
ABresult
0X0
100
111
1303 44471 $self->_tree_learn( $tree, $r );
1304 }
1305 }
1306 17090 $self->{seen}++;
1307  
1308 17090 ▶ if ( $self->{window_size} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"window_size"}) 15565 1525 17090
1309 15565 push @{ $self->{window} }, $r;
1310 15565 ▶ if ( @{ $self->{window} } > $self->{window_size} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"window"};} > $self->{"window_size"}) 8463 7102 15565
1311 8463 my $old = shift @{ $self->{window} };
1312 8463 ▶ if ( _HAS_ONLINE_XS && $self->{_use_c} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_use_c'}) { } 7003 1460 8463
1313 Algorithm::Classifier::IsolationForest::online_unlearn_row_xs(
1314 $self->{trees}, $old, $self->{n_features},
1315 $self->{max_leaf_samples},
1316 7003 ▶ ( $self->{growth} eq 'adaptive' ? 1 : 0 ), $sub
Branch: 1 branch
BranchTrueFalseTotal
$self->{'growth'} eq 'adaptive' ? : 6609 394 7003
1317 );
1318 } else {
1319 1460 for my $tree ( @{ $self->{trees} } ) {
1320 22760 ▶ next if $sub < 1 && rand() >= $sub;
Branch: 1 branch
BranchTrueFalseTotal
if $sub < 1 and rand() >= $sub 1490 21270 22760
Condition100%3/3
$sub < 1 and rand() >= $sub
!ll&&!rl&&r
1793033401490
MC/DC100%2/2
$sub < 1 and rand() >= $sub
$sub < 1 rand() >= $sub
Truth table100%3/3
A and B
A= $sub < 1B= rand() >= $sub
ABresult
0X0
100
111
1321 21270 $self->_tree_unlearn( $tree, $old );
1322 }
1323 }
1324 } ## end if ( @{ $self->{window} } > $self->{window_size...})
1325 } ## end if ( $self->{window_size} )
1326 17090 return;
1327 } ## end sub _learn_row
1328  
1329 # Teach one tree a single point: bump its count, refresh its depth budget
1330 # from that count, and route the point down from the root. A tree that has
1331 # never seen anything is given a one-point leaf instead, which is how a
1332 # root comes into being.
1333 #
1334 # Args:
1335 # $tree :: one tree record, a hashref of root, count and depth_limit.
1336 # Mutated in place.
1337 # $x :: one prepped sample, an arrayref of feature values. Copied into
1338 # any leaf box it initialises, never retained by reference.
1339 #
1340 # Returns: nothing. The tree's root may be replaced (a leaf that reached
1341 # its split requirement becomes a subtree), which is why the recursion
1342 # hands the node back rather than mutating it blindly.
1343 #
1344 # Example:
1345 # $self->_tree_learn( $self->{trees}[0], [ 0.9, 0.4 ] );
1346 44471 ▶sub _tree_learn {
Subroutine _tree_learn: called CC=2 SCAR=6.9
1347 44471 my ( $self, $tree, $x ) = @_;
1348 44471 $tree->{count}++;
1349 44471 $tree->{depth_limit} = $self->_rpl( $tree->{count} );
1350 44471 ▶ if ( !defined $tree->{root} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $tree->{'root'}) { } 110 44361 44471
1351 110 $tree->{root} = [ _NT_LEAF, 1, [@$x], [@$x] ];
1352 } else {
1353 44361 $tree->{root} = $self->_node_learn( $tree->{root}, $x, 0, $tree->{depth_limit} );
1354 }
1355 44471 return;
1356 } ## end sub _tree_learn
1357  
1358 # Route $x down to its leaf, growing counts and bounding boxes along the
1359 # path. A leaf that has accumulated its split requirement (and still has
1360 # depth budget) is replaced by a subtree built from synthetic points
1361 # sampled inside its box -- the return value replaces the node in the
1362 # parent, which is how leaves turn into subtrees in place.
1363 #
1364 # Args:
1365 # $node :: the node the point has reached, in the layout at the top of
1366 # this file. Mutated in place.
1367 # $x :: one prepped sample, an arrayref of feature values.
1368 # $depth :: this node's depth, 0 at the root.
1369 # $limit :: the tree's current depth budget, from _rpl of its count.
1370 #
1371 # Returns: the node that should occupy this slot afterwards -- usually
1372 # $node itself, but a freshly built subtree when a leaf just split. The
1373 # caller MUST store it back, which is why every call site assigns.
1374 #
1375 # Example:
1376 # $tree->{root} = $self->_node_learn( $tree->{root}, $x, 0, $tree->{depth_limit} );
1377 125393 ▶sub _node_learn {
Subroutine _node_learn: called CC=9 SCAR=22.0
1378 125393 my ( $self, $node, $x, $depth, $limit ) = @_;
1379  
1380 125393 $node->[_N_COUNT]++;
1381 125393 ▶ if ( !defined $node->[_N_LO] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $node->[2]) { } 0 125393 125393
1382  
1383 # Leaf born from an empty synthetic partition: first real point
1384 # initialises the box.
1385 0 $node->[_N_LO] = [@$x];
1386 0 $node->[_N_HI] = [@$x];
1387 } else {
1388 125393 my ( $lo, $hi ) = ( $node->[_N_LO], $node->[_N_HI] );
1389 125393 for my $f ( 0 .. $#$x ) {
1390 250786 my $v = $x->[$f];
1391 250786 ▶ $lo->[$f] = $v if $v < $lo->[$f];
Branch: 1 branch
BranchTrueFalseTotal
if $v < $lo->[$f] 5904 244882 250786
1392 250786 ▶ $hi->[$f] = $v if $v > $hi->[$f];
Branch: 1 branch
BranchTrueFalseTotal
if $v > $hi->[$f] 6190 244596 250786
1393 }
1394 }
1395  
1396 125393 ▶ if ( $node->[_N_TYPE] == _NT_LEAF ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->[0] == 0) 44361 81032 125393
1397 44361 ▶ if ( $node->[_N_COUNT] >= $self->_split_threshold($depth) && $depth < $limit ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->[1] >= $self->_split_threshold($depth) and $depth < $limit) 449 43912 44361
Condition100%3/3
$node->[1] >= $self->_split_threshold($depth) and $depth < $limit
!ll&&!rl&&r
2293120981449
MC/DC100%2/2
$node->[1] >= $self->_split_threshold($depth) and $depth < $limit
$node->[1] >= $self->_split_threshold($depth) $depth < $limit
Truth table100%3/3
A and B
A= $node->[1] >= $self->_split_threshold($depth)B= $depth < $limit
ABresult
0X0
100
111
1398 449 my $pts = $self->_sample_box( $node->[_N_LO], $node->[_N_HI], $node->[_N_COUNT] );
1399 449 return $self->_build_from_points( $pts, $depth, $limit );
1400 }
1401 43912 return $node;
1402 }
1403  
1404 81032 ▶ my $ci = $x->[ $node->[_N_ATTR] ] < $node->[_N_SPLIT] ? _N_LEFT : _N_RIGHT;
Branch: 1 branch
BranchTrueFalseTotal
$$x[$node->[4]] < $node->[5] ? : 36112 44920 81032
1405 81032 $node->[$ci] = $self->_node_learn( $node->[$ci], $x, $depth + 1, $limit );
1406 81032 return $node;
1407 } ## end sub _node_learn
1408  
1409 # $n synthetic points drawn uniformly inside the box -- the stand-in for
1410 # the real points the tree never stored.
1411 #
1412 # Args:
1413 # $lo, $hi :: the box corners, arrayrefs of per-feature minimum and
1414 # maximum. Both must be defined and the same width; a
1415 # feature with zero width contributes its single value.
1416 # $n :: how many points to draw, normally the splitting leaf's count so
1417 # the subtree is built from as much evidence as the leaf held.
1418 #
1419 # Returns: an arrayref of $n fresh arrayrefs, each a point inside the box.
1420 #
1421 # Example:
1422 # my $pts = $self->_sample_box( [ 0, 0 ], [ 1, 4 ], 32 );
1423 # # 32 points with feature 0 in [0, 1] and feature 1 in [0, 4]
1424 449 ▶sub _sample_box {
Subroutine _sample_box: called CC=3 SCAR=11.0
1425 449 my ( $self, $lo, $hi, $n ) = @_;
1426 449 my @pts;
1427 449 for ( 1 .. $n ) {
1428 15686 ▶ push @pts, [ map { my $w = $hi->[$_] - $lo->[$_]; $w > 0 ? $lo->[$_] + rand() * $w : $lo->[$_] } 0 .. $#$lo ];
Branch: 1 branch
BranchTrueFalseTotal
$w > 0 ? : 31372 0 31372
1429 }
1430 449 return \@pts;
1431 }
1432  
1433 # Recursively build a subtree over (synthetic) points: random feature,
1434 # uniform split value within the points' range on it, recurse on the
1435 # partitions. Leaves keep the partition's count and box.
1436 #
1437 # Args:
1438 # $pts :: the points this subtree covers, an arrayref of arrayrefs --
1439 # normally the synthetic set from _sample_box. May be empty,
1440 # which yields a count-0 leaf with an undef box.
1441 # $depth :: this subtree's root depth, so the split requirement scales
1442 # correctly under growth => 'adaptive'.
1443 # $limit :: the tree's current depth budget.
1444 #
1445 # Returns: the subtree's root node in the layout at the top of this file --
1446 # a leaf when the points are too few or the budget is spent, otherwise an
1447 # axis node with both children already built.
1448 #
1449 # Example:
1450 # my $sub = $self->_build_from_points( $pts, $depth, $limit );
1451 1347 ▶sub _build_from_points {
Subroutine _build_from_points: called CC=8 SCAR=20.8
1452 1347 my ( $self, $pts, $depth, $limit ) = @_;
1453 1347 my $n = scalar @$pts;
1454 1347 my ( $lo, $hi ) = _box_of($pts);
1455  
1456 1347 ▶ if ( $n < $self->_split_threshold($depth) || $depth >= $limit ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n < $self->_split_threshold($depth) or $depth >= $limit) 898 449 1347
Condition100%3/3
$n < $self->_split_threshold($depth) or $depth >= $limit
l!l&&r!l&&!r
86929449
MC/DC100%2/2
$n < $self->_split_threshold($depth) or $depth >= $limit
$n < $self->_split_threshold($depth) $depth >= $limit
Truth table100%3/3
A or B
A= $n < $self->_split_threshold($depth)B= $depth >= $limit
ABresult
1X1
011
000
1457 898 return [ _NT_LEAF, $n, $lo, $hi ];
1458 }
1459  
1460 449 my $attr = int( rand( $self->{n_features} ) );
1461 449 my ( $pmin, $pmax ) = ( $pts->[0][$attr], $pts->[0][$attr] );
1462 449 for my $p (@$pts) {
1463 15686 ▶ $pmin = $p->[$attr] if $p->[$attr] < $pmin;
Branch: 1 branch
BranchTrueFalseTotal
if $p->[$attr] < $pmin 1315 14371 15686
1464 15686 ▶ $pmax = $p->[$attr] if $p->[$attr] > $pmax;
Branch: 1 branch
BranchTrueFalseTotal
if $p->[$attr] > $pmax 1360 14326 15686
1465 }
1466 449 my $split = $pmin + rand() * ( $pmax - $pmin );
1467  
1468 449 my ( @l, @r );
1469 449 for my $p (@$pts) {
1470 15686 ▶ if ( $p->[$attr] < $split ) { push @l, $p }
Branch: 1 branch
BranchTrueFalseTotal
if ($p->[$attr] < $split) { } 7769 7917 15686
1471 7917 else { push @r, $p }
1472 }
1473  
1474 449 my $left = $self->_build_from_points( \@l, $depth + 1, $limit );
1475 449 my $right = $self->_build_from_points( \@r, $depth + 1, $limit );
1476 449 return [ _NT_AXIS, $n, $lo, $hi, $attr, $split, $left, $right ];
1477 } ## end sub _build_from_points
1478  
1479 #-------------------------------------------------------------------------------
1480 # Forgetting.
1481 #-------------------------------------------------------------------------------
1482  
1483 # Make one tree forget a single point: drop its count, refresh its depth
1484 # budget from that count, and route the point down from the root undoing
1485 # the bookkeeping as it goes. The mirror image of _tree_learn, and the
1486 # reason a tree's shape reflects its current contents rather than its
1487 # history.
1488 #
1489 # Args:
1490 # $tree :: one tree record, a hashref of root, count and depth_limit.
1491 # Mutated in place.
1492 # $x :: the point being evicted, an arrayref of feature values. Must be
1493 # a point this tree actually learned, otherwise the counts it
1494 # decrements are not the ones it incremented.
1495 #
1496 # Returns: nothing. A tree that never grew a root is left alone.
1497 #
1498 # Example:
1499 # my $old = shift @{ $self->{window} };
1500 # $self->_tree_unlearn( $self->{trees}[0], $old );
1501 21270 ▶sub _tree_unlearn {
Subroutine _tree_unlearn: called CC=2 SCAR=7.0
1502 21270 my ( $self, $tree, $x ) = @_;
1503 21270 $tree->{count}--;
1504 21270 $tree->{depth_limit} = $self->_rpl( $tree->{count} );
1505 21270 ▶ return unless defined $tree->{root};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tree->{"root"} 0 21270 21270
1506 21270 $tree->{root} = $self->_node_unlearn( $tree->{root}, $x, 0 );
1507 21270 return;
1508 }
1509  
1510 # Route the forgotten point down its (current) path, decrementing counts.
1511 # An internal node whose count no longer justifies its split collapses
1512 # back into a leaf; otherwise its box is refreshed to the union of its
1513 # children's, which is how boxes shrink as old extremes age out.
1514 #
1515 # Args:
1516 # $node :: the node the point has reached, in the layout at the top of
1517 # this file. Mutated in place.
1518 # $x :: the point being evicted, an arrayref of feature values.
1519 # $depth :: this node's depth, 0 at the root.
1520 #
1521 # Returns: the node that should occupy this slot afterwards -- $node
1522 # itself, or the leaf it just collapsed into. The caller MUST store it
1523 # back, exactly as with _node_learn.
1524 #
1525 # Example:
1526 # $tree->{root} = $self->_node_unlearn( $tree->{root}, $old, 0 );
1527 62358 ▶sub _node_unlearn {
Subroutine _node_unlearn: called CC=5 SCAR=16.1
1528 62358 my ( $self, $node, $x, $depth ) = @_;
1529  
1530 62358 $node->[_N_COUNT]--;
1531 62358 ▶ return $node if $node->[_N_TYPE] == _NT_LEAF;
Branch: 1 branch
BranchTrueFalseTotal
if $node->[0] == 0 21149 41209 62358
1532 41209 ▶ return _collapse($node) if $node->[_N_COUNT] < $self->_split_threshold($depth);
Branch: 1 branch
BranchTrueFalseTotal
if $node->[1] < $self->_split_threshold($depth) 121 41088 41209
1533  
1534 41088 ▶ my $ci = $x->[ $node->[_N_ATTR] ] < $node->[_N_SPLIT] ? _N_LEFT : _N_RIGHT;
Branch: 1 branch
BranchTrueFalseTotal
$$x[$node->[4]] < $node->[5] ? : 19952 21136 41088
1535 41088 $node->[$ci] = $self->_node_unlearn( $node->[$ci], $x, $depth + 1 );
1536  
1537 41088 my ( $lo, $hi ) = _box_union( $node->[_N_LEFT], $node->[_N_RIGHT] );
1538 41088 ▶ if ( defined $lo ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lo) 41088 0 41088
1539 41088 $node->[_N_LO] = $lo;
1540 41088 $node->[_N_HI] = $hi;
1541 }
1542 41088 return $node;
1543 } ## end sub _node_unlearn
1544  
1545 # Aggregate a subtree back into a single leaf holding the subtree's
1546 # (already decremented) count and the union of its descendants' boxes.
1547 #
1548 # Args:
1549 # $node :: the subtree root to fold up, in the layout at the top of this
1550 # file. Its count must already reflect the eviction that
1551 # triggered the collapse.
1552 #
1553 # Returns: a fresh leaf node carrying $node's count and a box covering
1554 # everything below it. A node that is already a leaf comes back
1555 # untouched.
1556 #
1557 # Example:
1558 # return _collapse($node) if $node->[_N_COUNT] < $self->_split_threshold($depth);
1559 363 ▶sub _collapse {
Subroutine _collapse: called CC=3 SCAR=11.1
1560 363 my ($node) = @_;
1561 363 ▶ return $node if $node->[_N_TYPE] == _NT_LEAF;
Branch: 1 branch
BranchTrueFalseTotal
if $node->[0] == 0 242 121 363
1562 121 my $l = _collapse( $node->[_N_LEFT] );
1563 121 my $r = _collapse( $node->[_N_RIGHT] );
1564 121 my ( $lo, $hi ) = _box_union( $l, $r );
1565 121 ▶ if ( !defined $lo ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $lo) 0 121 121
1566  
1567 # Both children empty: keep the node's own box.
1568 0 ( $lo, $hi ) = ( $node->[_N_LO], $node->[_N_HI] );
1569 }
1570 121 return [ _NT_LEAF, $node->[_N_COUNT], $lo, $hi ];
1571 } ## end sub _collapse
1572  
1573 # (lo, hi) of the union of two nodes' boxes, as fresh arrays (parent
1574 # boxes grow in place, so they must never alias a child's). Nodes with
1575 # no box yet (empty leaves) are skipped; (undef, undef) if neither has
1576 # one.
1577 #
1578 # Args:
1579 # $a, $b :: two nodes, in the layout at the top of this file. Either may
1580 # be an empty leaf whose box slots are still undef.
1581 #
1582 # Returns: the two-element list ($lo, $hi) of fresh arrayrefs covering both
1583 # nodes, or (undef, undef) when neither has a box yet.
1584 #
1585 # Example:
1586 # my ( $lo, $hi ) = _box_union( $node->[_N_LEFT], $node->[_N_RIGHT] );
1587 # if ( defined $lo ) { $node->[_N_LO] = $lo; $node->[_N_HI] = $hi }
1588 41209 ▶sub _box_union {
Subroutine _box_union: called CC=6 SCAR=18.0
1589 41209 my ( $a, $b ) = @_;
1590 41209 my @boxed = grep { defined $_->[_N_LO] } ( $a, $b );
1591 41209 ▶ return ( undef, undef ) unless @boxed;
Branch: 1 branch
BranchTrueFalseTotal
unless @boxed 0 41209 41209
1592 41209 my $lo = [ @{ $boxed[0][_N_LO] } ];
1593 41209 my $hi = [ @{ $boxed[0][_N_HI] } ];
1594 41209 ▶ if ( @boxed == 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@boxed == 2) 41209 0 41209
1595 41209 my ( $blo, $bhi ) = ( $boxed[1][_N_LO], $boxed[1][_N_HI] );
1596 41209 for my $f ( 0 .. $#$lo ) {
1597 82418 ▶ $lo->[$f] = $blo->[$f] if $blo->[$f] < $lo->[$f];
Branch: 1 branch
BranchTrueFalseTotal
if $blo->[$f] < $lo->[$f] 24674 57744 82418
1598 82418 ▶ $hi->[$f] = $bhi->[$f] if $bhi->[$f] > $hi->[$f];
Branch: 1 branch
BranchTrueFalseTotal
if $bhi->[$f] > $hi->[$f] 61232 21186 82418
1599 }
1600 }
1601 41209 return ( $lo, $hi );
1602 } ## end sub _box_union
1603  
1604 # (lo, hi) bounding box of a point set; (undef, undef) when empty.
1605 #
1606 # Args:
1607 # $pts :: the points to bound, an arrayref of arrayrefs. May be empty.
1608 #
1609 # Returns: the two-element list ($lo, $hi) of fresh arrayrefs holding the
1610 # per-feature minimum and maximum, or (undef, undef) for an empty set.
1611 #
1612 # Example:
1613 # my ( $lo, $hi ) = _box_of( [ [ 0.9, 0.4 ], [ 0.2, 0.7 ] ] );
1614 # # ( [ 0.2, 0.4 ], [ 0.9, 0.7 ] )
1615 1347 ▶sub _box_of {
Subroutine _box_of: called CC=6 SCAR=17.9
1616 1347 my ($pts) = @_;
1617 1347 ▶ return ( undef, undef ) unless @$pts;
Branch: 1 branch
BranchTrueFalseTotal
unless @$pts 0 1347 1347
1618 1347 my $lo = [ @{ $pts->[0] } ];
1619 1347 my $hi = [ @{ $pts->[0] } ];
1620 1347 for my $p (@$pts) {
1621 31372 for my $f ( 0 .. $#$p ) {
1622 62744 ▶ $lo->[$f] = $p->[$f] if $p->[$f] < $lo->[$f];
Branch: 1 branch
BranchTrueFalseTotal
if $p->[$f] < $lo->[$f] 6522 56222 62744
1623 62744 ▶ $hi->[$f] = $p->[$f] if $p->[$f] > $hi->[$f];
Branch: 1 branch
BranchTrueFalseTotal
if $p->[$f] > $hi->[$f] 6522 56222 62744
1624 }
1625 }
1626 1347 return ( $lo, $hi );
1627 } ## end sub _box_of
1628  
1629 #-------------------------------------------------------------------------------
1630 # Scoring.
1631 #-------------------------------------------------------------------------------
1632  
1633 # Depth of the leaf $x lands in, plus the leaf's own depth budget -- the
1634 # streaming analogue of the batch scorer's c(leaf size) adjustment.
1635 # Scoring tolerates undef cells (mapped to 0), matching the parent class.
1636 #
1637 # Args:
1638 # $x :: one sample, an arrayref of feature values. undef cells are
1639 # allowed and count as 0.
1640 # $node :: the node to start walking from, normally a tree's root. Must
1641 # be defined -- callers skip trees that have not grown one.
1642 #
1643 # Returns: the path length as a float: edges walked plus the leaf's
1644 # _rpl(count), so it is rarely a whole number.
1645 #
1646 # Example:
1647 # $self->_depth_of( [ 0.9, 0.4 ], $self->{trees}[0]{root} ); # e.g. 2.8
1648 39080 ▶sub _depth_of {
Subroutine _depth_of: called CC=4 SCAR=13.9
1649 39080 my ( $self, $x, $node ) = @_;
1650 39080 my $depth = 0;
1651 39080 ▶ while ( $node->[_N_TYPE] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->[0]) 98226 39080 137306
1652 98226 ▶ $node = ( $x->[ $node->[_N_ATTR] ] // 0 ) < $node->[_N_SPLIT] ? $node->[_N_LEFT] : $node->[_N_RIGHT];
Branch: 1 branch
BranchTrueFalseTotal
($$x[$node->[4]] // 0) < $node->[5] ? : 44692 53534 98226
Condition100%2/2
$$x[$node->[4]] // 0
l!l
97554672
MC/DC100%1/1
$$x[$node->[4]] // 0
$$x[$node->[4]]
Truth table100%2/2
A
A= $$x[$node->[4]]
Aresult
11
00
1653 98226 $depth++;
1654 }
1655 39080 return $depth + $self->_rpl( $node->[_N_COUNT] );
1656 }
1657  
1658 # Per-sample depth sums across all trees (tree-outer, sample-inner for
1659 # cache locality, mirroring the parent's pure-Perl loops).
1660 #
1661 # Args:
1662 # $data :: the samples to walk, an arrayref of feature-value arrayrefs
1663 # already through _prep_row or otherwise known dense-ish (undef
1664 # cells count as 0).
1665 #
1666 # Returns: arrayref of per-sample depth sums, positionally matching $data.
1667 # Trees with no root contribute nothing, so a brand-new model yields all
1668 # zeroes.
1669 #
1670 # Example:
1671 # my $sums = $self->_depth_sums( \@rows );
1672 # my $inv = $self->_score_inv;
1673 # my @scores = map { exp( -$_ * $inv ) } @$sums;
1674 14 ▶sub _depth_sums {
Subroutine _depth_sums: called CC=4 SCAR=13.9
1675 14 my ( $self, $data ) = @_;
1676 14 my @sums = (0) x @$data;
1677 14 for my $tree ( @{ $self->{trees} } ) {
1678 700 my $root = $tree->{root};
1679 700 ▶ next unless defined $root;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $root 0 700 700
1680 700 for my $i ( 0 .. $#$data ) {
1681 28600 $sums[$i] += $self->_depth_of( $data->[$i], $root );
1682 }
1683 }
1684 14 return \@sums;
1685 } ## end sub _depth_sums
1686  
1687 # Single-row score against the current model state; used by the
1688 # prequential score_learn loop, where the normaliser moves as points are
1689 # learned and so must be recomputed per row.
1690 #
1691 # Args:
1692 # $r :: one sample, already through _prep_row.
1693 #
1694 # Returns: the anomaly score as a float in (0, 1] -- near 1 for an
1695 # anomaly, well under 0.5 for a normal point.
1696 #
1697 # Example:
1698 # my $r = $self->_prep_row( $row, 'score_learn' );
1699 # my $score = $self->_score_row($r);
1700 # $self->_learn_row($r); # prequential: score, then learn
1701 1924 ▶sub _score_row {
Subroutine _score_row: called CC=4 SCAR=13.9
1702 1924 my ( $self, $r ) = @_;
1703 1924 ▶ if ( _HAS_ONLINE_XS && $self->{_use_c} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_use_c"}) 1324 600 1924
1704  
1705 # Walks the live trees in C -- no packed snapshot involved, so
1706 # this stays fast even though score_learn mutates the trees
1707 # between rows.
1708 my $sum = Algorithm::Classifier::IsolationForest::online_score_row_xs( $self->{trees}, $r,
1709 1324 $self->{n_features}, $self->{max_leaf_samples} );
1710 1324 return exp( -$sum * $self->_score_inv );
1711 }
1712 600 my $sum = 0;
1713 600 for my $tree ( @{ $self->{trees} } ) {
1714 10500 ▶ $sum += $self->_depth_of( $r, $tree->{root} ) if defined $tree->{root};
Branch: 1 branch
BranchTrueFalseTotal
if defined $tree->{"root"} 10480 20 10500
1715 }
1716 600 return exp( -$sum * $self->_score_inv );
1717 } ## end sub _score_row
1718  
1719 #-------------------------------------------------------------------------------
1720 # Explanation (explain_samples) internals. The output shaping is shared
1721 # with the parent class (_credit_to_features / _deltas_to_features) so
1722 # both classes return the identical structure; only the walks and the
1723 # baseline source differ.
1724 #-------------------------------------------------------------------------------
1725  
1726 # Path-credit explanation: _depth_of's exact routing recorded as
1727 # (path length, crossed features) walks, turned into local-DIFFI
1728 # credit by the parent's _walks_to_credit (see _path_length_explain
1729 # there for the weighting and its rationale). Path lengths carry the
1730 # per-leaf _rpl(count) adjustment, exactly as scoring's do -- with the
1731 # shallow trees online models build, most of the between-tree contrast
1732 # lives in that adjustment, not the raw depth. Online trees are
1733 # axis-only, so each node credits exactly one feature (share 1).
1734 #
1735 # Args:
1736 # $data :: the samples to explain, an arrayref of feature-value
1737 # arrayrefs, already prepped by the caller.
1738 #
1739 # Returns: arrayref of one hashref per row, in input order, each holding
1740 # score, method (always 'path') and features -- the same sorted structure
1741 # the parent class returns, so callers cannot tell the two apart.
1742 #
1743 # Example:
1744 # my $out = $self->_explain_path( [ [ 8.1, 0.2 ] ] );
1745 # $out->[0]{features}[0]{name}; # the feature most responsible
1746 2 ▶sub _explain_path {
Subroutine _explain_path: called CC=7 SCAR=19.5
1747 2 my ( $self, $data ) = @_;
1748 2 my $scores = $self->score_samples($data);
1749 2 my $nf = $self->{n_features};
1750 2 my $names = $self->{feature_names};
1751  
1752 2 my @out;
1753 2 for my $i ( 0 .. $#$data ) {
1754 2 my $x = $data->[$i];
1755 2 my @walks;
1756 2 for my $tree ( @{ $self->{trees} } ) {
1757 100 my $node = $tree->{root};
1758 100 ▶ next unless defined $node;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $node 0 100 100
1759 100 my @pairs;
1760 100 ▶ while ( $node->[_N_TYPE] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->[0]) 200 100 300
1761 200 push @pairs, [ $node->[_N_ATTR], 1 ];
1762 200 ▶ $node = ( $x->[ $node->[_N_ATTR] ] // 0 ) < $node->[_N_SPLIT] ? $node->[_N_LEFT] : $node->[_N_RIGHT];
Branch: 1 branch
BranchTrueFalseTotal
($$x[$node->[4]] // 0) < $node->[5] ? : 36 164 200
Condition50%1/2
$$x[$node->[4]] // 0
l!l
2000
MC/DC0%0/1
$$x[$node->[4]] // 0
$$x[$node->[4]]
Truth table50%1/2
A
A= $$x[$node->[4]]
Aresult
11
00
1763 }
1764 100 push @walks, [ scalar(@pairs) + $self->_rpl( $node->[_N_COUNT] ), \@pairs ];
1765 } ## end for my $tree ( @{ $self->{trees} } )
1766 2 my $credit = Algorithm::Classifier::IsolationForest::_walks_to_credit( \@walks, $nf );
1767 2 push @out,
1768 {
1769 score => $scores->[$i],
1770 method => 'path',
1771 features => Algorithm::Classifier::IsolationForest::_credit_to_features( $names, $credit, $x ),
1772 };
1773 } ## end for my $i ( 0 .. $#$data )
1774 2 return \@out;
1775 } ## end sub _explain_path
1776  
1777 # Counterfactual explanation: every row followed by its n_features
1778 # single-feature baseline substitutions, scored as one batch (which
1779 # rides the packed-snapshot C scorer when available). Mirrors the
1780 # parent's _explain_ablation with the window medians as baselines.
1781 #
1782 # Args:
1783 # $data :: the samples to explain, an arrayref of feature-value
1784 # arrayrefs, already prepped by the caller.
1785 #
1786 # Returns: arrayref of one hashref per row, in input order, each holding
1787 # score, method (always 'ablation') and features. Croaks by way of
1788 # _window_baselines when the model has no retained window to take medians
1789 # from.
1790 #
1791 # Example:
1792 # my $out = $self->_explain_ablation( [ [ 8.1, 0.2 ] ] );
1793 # $out->[0]{features}[0]{delta}; # score drop from neutralising it
1794 4 ▶sub _explain_ablation {
Subroutine _explain_ablation: called CC=4 SCAR=13.9
1795 4 my ( $self, $data ) = @_;
1796 4 my $nf = $self->{n_features};
1797 4 my $names = $self->{feature_names};
1798 4 my $baselines = $self->_window_baselines;
1799  
1800 3 my @batch;
1801 3 for my $row (@$data) {
1802 3 push @batch, $row;
1803 3 for my $f ( 0 .. $nf - 1 ) {
1804 9 my @variant = @$row;
1805 9 $variant[$f] = $baselines->[$f];
1806 9 push @batch, \@variant;
1807 }
1808 }
1809 3 my $scores = $self->score_samples( \@batch );
1810  
1811 3 my @out;
1812 3 for my $i ( 0 .. $#$data ) {
1813 3 my $base = $i * ( $nf + 1 );
1814 3 my $score = $scores->[$base];
1815 3 my @deltas = map { $score - $scores->[ $base + 1 + $_ ] } 0 .. $nf - 1;
1816 3 push @out,
1817 {
1818 score => $score,
1819 method => 'ablation',
1820 features => Algorithm::Classifier::IsolationForest::_deltas_to_features(
1821 $names, \@deltas, $data->[$i], $baselines
1822 ),
1823 };
1824 } ## end for my $i ( 0 .. $#$data )
1825 3 return \@out;
1826 } ## end sub _explain_ablation
1827  
1828 # Per-feature medians of the retained window -- the streaming
1829 # equivalent of the batch class's fit-time baselines, and better in one
1830 # way: they track drift for free because the window does. Recomputed
1831 # per explanation call (the window moves with the stream); a sort per
1832 # feature over at most window_size values, dwarfed by the scoring batch
1833 # it feeds. Window rows are always dense (missing => die/zero), so no
1834 # undef handling is needed. Without a retained window there is nothing
1835 # to take a median of.
1836 #
1837 # Args: none beyond the model itself.
1838 #
1839 # Returns: an arrayref of n_features medians taken over the retained
1840 # window. Croaks when the window is empty or absent (window_size 0, or
1841 # nothing learned yet), pointing the caller at method => 'path'.
1842 #
1843 # Example:
1844 # my $baselines = $self->_window_baselines; # [ 0.5, 0.5 ]
1845 4 ▶sub _window_baselines {
Subroutine _window_baselines: called CC=5 SCAR=16.2
1846 4 my ($self) = @_;
1847 4 my $win = $self->{window};
1848 4 ▶ croak "explain_samples: ablation explanations need retained window data "
Branch: 1 branch
BranchTrueFalseTotal
unless ref $win eq "ARRAY" and @$win 1 3 4
Condition66%2/3
ref $win eq "ARRAY" and @$win
!ll&&!rl&&r
013
MC/DC50%1/2
ref $win eq "ARRAY" and @$win
ref $win eq "ARRAY" @$win
Truth table66%2/3
A and B
A= ref $win eq "ARRAY"B= @$win
ABresult
0X0
100
111
1849 . "(window_size > 0 and learned points); use method => 'path' instead"
1850 unless ref $win eq 'ARRAY' && @$win;
1851  
1852 3 my $nf = $self->{n_features};
1853 3 my @baselines;
1854 3 for my $f ( 0 .. $nf - 1 ) {
1855 9 my @vals = sort { $a <=> $b } map { $_->[$f] } @$win;
1856 9 my $k = scalar @vals;
1857 9 ▶ $baselines[$f]
Branch: 1 branch
BranchTrueFalseTotal
$k % 2 ? : 9 0 9
1858 = $k % 2
1859 ? $vals[ int( $k / 2 ) ]
1860 : ( $vals[ $k / 2 - 1 ] + $vals[ $k / 2 ] ) / 2.0;
1861 }
1862 3 return \@baselines;
1863 } ## end sub _window_baselines
1864  
1865 #-------------------------------------------------------------------------------
1866 # C-accelerated scoring.
1867 #
1868 # The parent class's Inline::C scorer walks immutable packed node buffers;
1869 # online trees mutate on every learned point. The bridge is a lazily
1870 # built snapshot: the first scoring call after any mutation flattens the
1871 # live trees into the parent's packed node layout (below) and every
1872 # scoring call until the next mutation reuses it. _learn_row -- the one
1873 # choke point all mutations flow through -- drops the snapshot.
1874 #
1875 # Online trees are axis-only, so they map onto the parent's 6-double node
1876 # records directly:
1877 #
1878 # leaf: [0, count, _rpl(count), 0, 0, 0]
1879 # axis: [1, attr, split, li, ri, 0]
1880 #
1881 # The parent packs c(leaf size) into slot 2 and its C walker returns
1882 # depth + slot2 at a leaf; packing the online depth-budget adjustment
1883 # _rpl(count) there instead makes score_all_xs compute exactly the
1884 # pure-Perl _depth_of value, so every downstream C helper (finalize_*,
1885 # predict_sums_xs, score_predict_*) applies unchanged. The per-tree
1886 # coefficient buffers are empty -- there are no oblique nodes -- and only
1887 # exist because score_all_xs expects them.
1888 #
1889 # score_learn deliberately never uses this path: it mutates the trees
1890 # after every single point, so the snapshot could never be reused and
1891 # repacking per point would cost more than the walks it replaces.
1892 #-------------------------------------------------------------------------------
1893  
1894 # Drop the packed snapshot; called on every mutation. _learn_row is the
1895 # single choke point every tree mutation flows through, so one call there
1896 # is enough to keep the snapshot from ever going stale.
1897 #
1898 # Args: none beyond the model itself.
1899 #
1900 # Returns: nothing. Removes _c_nodes, _c_coef_idx and _c_coef_val, which
1901 # is what makes the next _ensure_c_trees rebuild rather than reuse.
1902 #
1903 # Example:
1904 # $self->_invalidate_c_trees; # next scoring call repacks
1905 17090 ▶sub _invalidate_c_trees {
Subroutine _invalidate_c_trees: called CC=1 SCAR=0.0
1906 17090 delete @{ $_[0] }{qw(_c_nodes _c_coef_idx _c_coef_val)};
1907 17090 return;
1908 }
1909  
1910 # Build (or reuse) the packed snapshot of the live trees.
1911 #
1912 # Args: none beyond the model itself.
1913 #
1914 # Returns: 1 when the C scoring path may be taken -- the snapshot is
1915 # present and current afterwards -- and 0 when the caller must fall back to
1916 # the pure-Perl walk because use_c is off. Repacking only happens on the
1917 # first call after a mutation; later calls just confirm the snapshot.
1918 #
1919 # Example:
1920 # if ( $self->_ensure_c_trees ) {
1921 # my ( $n_pts, $x ) = $self->_pack_input($data);
1922 # # ... score through the parent's score_all_xs
1923 # }
1924 97 ▶sub _ensure_c_trees {
Subroutine _ensure_c_trees: called CC=4 SCAR=13.9
1925 97 my ($self) = @_;
1926 97 ▶ return 0 unless $self->{_use_c};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_use_c"} 21 76 97
1927 76 ▶ return 1 if $self->{_c_nodes};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_c_nodes"} 46 30 76
1928  
1929 30 my ( @c_nodes, @c_coef_idx, @c_coef_val );
1930 30 my $empty_idx = pack('l*');
1931 30 my $empty_val = pack('d*');
1932 30 for my $tree ( @{ $self->{trees} } ) {
1933 1055 push @c_nodes, $self->_pack_online_tree( $tree->{root} );
1934 1055 push @c_coef_idx, $empty_idx;
1935 1055 push @c_coef_val, $empty_val;
1936 }
1937 30 $self->{_c_nodes} = \@c_nodes;
1938 30 $self->{_c_coef_idx} = \@c_coef_idx;
1939 30 $self->{_c_coef_val} = \@c_coef_val;
1940 30 return 1;
1941 } ## end sub _ensure_c_trees
1942  
1943 # Flatten one live tree into the parent's packed node buffer (DFS
1944 # pre-order, root at index 0 -- the origin score_all_xs walks from).
1945 #
1946 # Args:
1947 # $root :: the tree's root node, or undef for a tree that has not learned
1948 # anything yet.
1949 #
1950 # Returns: a packed 'd*' string of 6 doubles per node, in the parent's node
1951 # layout. An undef root yields the single zeroed leaf record described
1952 # above, which walks as depth 0 with no adjustment.
1953 #
1954 # Example:
1955 # my $buf = $self->_pack_online_tree( $tree->{root} );
1956 # length($buf) / ( 6 * 8 ); # node count
1957 1055 ▶sub _pack_online_tree {
Subroutine _pack_online_tree: called CC=2 SCAR=6.9
1958 1055 my ( $self, $root ) = @_;
1959  
1960 # A tree that has not learned anything walks as depth 0 with a zero
1961 # adjustment: one empty leaf record.
1962 1055 ▶ return pack( 'd*', 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ) unless defined $root;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $root 0 1055 1055
1963  
1964 1055 my @node_data;
1965 my $assign;
1966 8187 ▶ $assign = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1967 8187 my ($node) = @_;
1968 8187 my $my_idx = scalar @node_data;
1969 8187 push @node_data, undef; # reserve slot; filled in after children
1970 8187 ▶ if ( $node->[_N_TYPE] == _NT_LEAF ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($node->[0] == 0) { } 4621 3566 8187
1971 4621 $node_data[$my_idx]
1972 = [ 0.0, $node->[_N_COUNT] + 0.0, $self->_rpl( $node->[_N_COUNT] ) + 0.0, 0.0, 0.0, 0.0 ];
1973 } else {
1974 3566 my $li = $assign->( $node->[_N_LEFT] );
1975 3566 my $ri = $assign->( $node->[_N_RIGHT] );
1976 3566 $node_data[$my_idx]
1977 = [ 1.0, $node->[_N_ATTR] + 0.0, $node->[_N_SPLIT] + 0.0, $li + 0.0, $ri + 0.0, 0.0 ];
1978 }
1979 8187 return $my_idx;
1980 1055 }; ## end $assign = sub
1981 1055 $assign->($root);
1982 1055 return pack( 'd*', map { @$_ } @node_data );
1983 } ## end sub _pack_online_tree
1984  
1985 # Pack the query rows into the row-major double buffer score_all_xs
1986 # reads, via the parent's C row walker. miss_mode 0 maps an undef cell
1987 # to 0.0, matching the pure-Perl walk's "// 0".
1988 #
1989 # Args:
1990 # $data :: the samples to pack, an arrayref of feature-value arrayrefs.
1991 # Each must be n_features wide.
1992 #
1993 # Returns: the two-element list ($n_pts, $x_packed) -- the row count and
1994 # the row-major 'd*' buffer. There is no online counterpart to the
1995 # parent's PackedData: the snapshot goes stale on every learn, so buffers
1996 # are built per call.
1997 #
1998 # Example:
1999 # my ( $n_pts, $x ) = $self->_pack_input( \@rows );
2000 76 ▶sub _pack_input {
Subroutine _pack_input: called CC=1 SCAR=0.0
2001 76 my ( $self, $data ) = @_;
2002 76 my $n_pts = scalar @$data;
2003 76 my $nf = $self->{n_features};
2004 76 my $x_packed = "\0" x ( $n_pts * $nf * 8 );
2005 76 Algorithm::Classifier::IsolationForest::pack_input_xs( $data, $x_packed, $n_pts, $nf, 0, '' );
2006 76 return ( $n_pts, $x_packed );
2007 }
2008  
2009 # Lazily learn the contamination threshold from the current window the
2010 # first time a predict-family method needs it. A model with no retained
2011 # window (window_size 0) stays on the 0.5 fallback until the caller runs
2012 # relearn_threshold with data.
2013 #
2014 # Args: none beyond the model itself.
2015 #
2016 # Returns: nothing. Sets $self->{threshold} on the first call that finds a
2017 # contamination rate, no threshold yet, and a non-empty window; every other
2018 # call is a no-op, so predict-family methods can call it unconditionally.
2019 #
2020 # Example:
2021 # $self->_ensure_threshold;
2022 # my $cut = $self->{threshold} // 0.5;
2023 23 ▶sub _ensure_threshold {
Subroutine _ensure_threshold: called CC=4 SCAR=13.9
2024 23 my ($self) = @_;
2025 return
2026 if !defined $self->{contamination}
2027 || defined $self->{threshold}
2028 23 ▶ || !@{ $self->{window} };
Branch: 1 branch
BranchTrueFalseTotal
if not defined $self->{"contamination"} or defined $self->{"threshold"} or not @{$self->{"window"};} 19 4 23
Condition83%5/6
not defined $self->{"contamination"} or defined $self->{"threshold"} or not @{$self->{"window"};}
l!l&&r!l&&!r
1904
not defined $self->{"contamination"} or defined $self->{"threshold"}
l!l&&r!l&&!r
4154
MC/DC66%2/3
not defined $self->{"contamination"} or defined $self->{"threshold"} or not @{$self->{"window"};}
not defined $self->{"contamination"} defined $self->{"threshold"} not @{$self->{"window"};}
Truth table75%3/4
not(A) or B or not(C)
A= not defined $self->{"contamination"}B= defined $self->{"threshold"}C= not @{$self->{"window"};}
ABCresult
1XX1
01X1
0011
0000
2029 4 $self->relearn_threshold;
2030 4 return;
2031 }
2032  
2033 96 1;
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/info.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/pack.pm »