blib/lib/Algorithm/Classifier/IsolationForest/App/Command/set_voting.pm

filter: Statementstmt 86.1% 56 / 65 Branchbran 69.4% 25 / 36 Conditioncond 58.3% 7 / 12 MC/DCmcdc 33.3% 2 / 6 Subroutinesub 81.8% 9 / 11 Podpod 100% 5 / 5 totaltotal 77.0% 104 / 135 CC 25 SCAR 26.2
CC
25
Cov
78%
validate
21.6
execute
15.5
abstract
2.0
CRAP 13.7
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/proto.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/streamc.pm »
1 package Algorithm::Classifier::IsolationForest::App::Command::set_voting;
2  
3 86 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 86 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 86 ▶use Algorithm::Classifier::IsolationForest ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 86 ▶use Algorithm::Classifier::IsolationForest::App -command;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 86 ▶use File::Slurp qw(read_file write_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 86 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 4 ▶sub opt_spec {
Subroutine opt_spec: called CC=1 SCAR=0.0
Pod documented
11 return (
12 [
13 4 'm=s',
14 'Input model JSON file path/name.',
15 { 'default' => 'iforest_model.json', 'completion' => 'files' }
16 ],
17 [
18 'voting=s',
19 "Target scoring-time aggregation: 'mean' (classic averaged score) or 'majority' (MVIForest per-tree vote)."
20 ],
21 [
22 'i=s',
23 'CSV training data. Required only when the model was fit with contamination, so the decision threshold can be recalibrated for the new mode.',
24 { 'completion' => 'files' }
25 ],
26 [ 'o=s', 'Write the updated model here instead of overwriting -m.', { 'completion' => 'files' } ],
27 [ 'p', 'Print the updated model JSON instead of saving it.' ],
28 [ 'w', 'Overwrite the -o file if it already exists.' ],
29 );
30 } ## end sub opt_spec
31  
32 0 ▶sub abstract { 'Switch a saved model between mean and majority voting' }
Subroutine abstract: not called CC=1 SCAR=6.9
Pod documented
33  
34 0 ▶sub description {
Subroutine description: not called CC=1 SCAR=6.9
Pod documented
35 0 'Switches the scoring-time aggregation of a saved model between "mean" and
36 "majority" and writes it back (in place over -m by default, or to -o / stdout).
37  
38 The forest itself is voting-independent, so no tree is rebuilt. The one thing
39 that does not carry over is a contamination-learned decision threshold: it is a
40 quantile of whichever per-point quantity the mode thresholds against (the
41 averaged anomaly score under mean, the per-tree majority pivot under majority),
42 so switching relearns it for the target mode. That recalibration needs the
43 original training data, supplied as a CSV via -i. Models fit without
44 contamination carry no threshold and switch without -i.
45  
46 Switches to new args are like below...
47  
48 --voting -> voting
49 -i -> training CSV (contamination models only)
50  
51 ';
52 } ## end sub description
53  
54 4 ▶sub validate {
Subroutine validate: called CC=11 SCAR=30.7
Pod documented
55 4 my ( $self, $opt, $args ) = @_;
56  
57 4 ▶ if ( !-f $opt->{'m'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not -f $opt->{'m'}) { } 0 4 4
elsif (not -r $opt->{'m'}) { } 0 4 4
58 0 $self->usage_error( '-m, "' . $opt->{'m'} . '", is not a file or does not exist' );
59 } elsif ( !-r $opt->{'m'} ) {
60 0 $self->usage_error( '-m, "' . $opt->{'m'} . '", is not readable' );
61 }
62  
63 4 ▶ if ( !defined( $opt->{'voting'} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $opt->{'voting'}) { } 0 4 4
elsif (not $opt->{'voting'} =~ /\A(?:mean|majority)\z/) { } 1 3 4
64 0 $self->usage_error('--voting has not been specified');
65 } elsif ( $opt->{'voting'} !~ /\A(?:mean|majority)\z/ ) {
66 1 $self->usage_error( '--voting, "' . $opt->{'voting'} . '", must be either mean or majority' );
67 }
68  
69 3 ▶ if ( defined( $opt->{'i'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"i"}) 1 2 3
70 1 ▶ if ( !-f $opt->{'i'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not -f $opt->{'i'}) { } 0 1 1
elsif (not -r $opt->{'i'}) { } 0 1 1
71 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not a file or does not exist' );
72 } elsif ( !-r $opt->{'i'} ) {
73 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not readable' );
74 }
75 }
76  
77 3 ▶ if ( defined( $opt->{'o'} ) && !$opt->{'w'} && -e $opt->{'o'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"o"} and not $opt->{"w"} and -e $opt->{"o"}) 0 3 3
Condition33%2/6
defined $opt->{"o"} and not $opt->{"w"} and -e $opt->{"o"}
!ll&&!rl&&r
300
defined $opt->{"o"} and not $opt->{"w"}
!ll&&!rl&&r
300
MC/DC0%0/3
defined $opt->{"o"} and not $opt->{"w"} and -e $opt->{"o"}
defined $opt->{"o"} not $opt->{"w"} -e $opt->{"o"}
Truth table25%1/4
A and not(B) and C
A= defined $opt->{"o"}B= not $opt->{"w"}C= -e $opt->{"o"}
ABCresult
0XX0
10X0
1100
1111
78 0 $self->usage_error( '-o, "' . $opt->{'o'} . '", already exists and -w is not specified' );
79 }
80  
81 3 return 1;
82 } ## end sub validate
83  
84 3 ▶sub execute {
Subroutine execute: called CC=15 SCAR=27.4
Pod documented
85 3 my ( $self, $opt, $args ) = @_;
86  
87 3 my $iforest = Algorithm::Classifier::IsolationForest->load( $opt->{'m'} );
88  
89 # A contamination-fitted model needs its training data to relearn the
90 # threshold for the target mode; without it set_voting would croak, so
91 # surface the requirement as a friendly usage error pointing at -i. Only
92 # an actual mode change triggers this -- a no-op switch never recalibrates.
93 3 my $changing = $iforest->{voting} ne $opt->{'voting'};
94 3 ▶ if ( $changing && defined( $iforest->{contamination} ) && !defined( $opt->{'i'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($changing and defined $iforest->{"contamination"} and not defined $opt->{"i"}) 1 2 3
Condition83%5/6
$changing and defined $iforest->{"contamination"} and not defined $opt->{"i"}
!ll&&!rl&&r
111
$changing and defined $iforest->{"contamination"}
!ll&&!rl&&r
012
MC/DC66%2/3
$changing and defined $iforest->{"contamination"} and not defined $opt->{"i"}
$changing defined $iforest->{"contamination"} not defined $opt->{"i"}
Truth table75%3/4
A and B and not(C)
A= $changingB= defined $iforest->{"contamination"}C= not defined $opt->{"i"}
ABCresult
0XX0
10X0
1100
1111
95 $self->usage_error( 'model "'
96 . $opt->{'m'}
97 . '" was fit with contamination; -i CSV training data is required to recalibrate the threshold for --voting '
98 1 . $opt->{'voting'} );
99 }
100  
101 2 my @data;
102 2 ▶ if ( defined( $opt->{'i'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"i"}) 1 1 2
103 1 my $expected_cols;
104 1 my $line_int = 1;
105 1 foreach my $line ( read_file( $opt->{'i'} ) ) {
106 63 chomp($line);
107 63 ▶ next if $line =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^\s*$/ 0 63 63
108  
109 63 my @fields = split( /,/, $line, -1 );
110  
111 63 ▶ if ( !defined($expected_cols) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $expected_cols) { } 1 62 63
elsif (scalar @fields != $expected_cols) { } 0 62 62
112 1 $expected_cols = scalar @fields;
113 1 ▶ die( 'Line ' . $line_int . ' of "' . $opt->{'i'} . '" has no columns' )
Branch: 1 branch
BranchTrueFalseTotal
if $expected_cols < 1 0 1 1
114 if $expected_cols < 1;
115 } elsif ( scalar @fields != $expected_cols ) {
116 die( 'Line '
117 . $line_int . ' of "'
118 0 . $opt->{'i'}
119 . '" has '
120 . scalar(@fields)
121 . ' columns but expected '
122 . $expected_cols );
123 }
124  
125 63 my $col_int = 1;
126 63 for my $field (@fields) {
127 die( 'Line '
128 . $line_int . ' of "'
129 189 ▶ . $opt->{'i'}
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($field) 0 189 189
130 . '" value for column '
131 . $col_int . ',"'
132 . $field
133 . '", does not appear to be a number' )
134 unless looks_like_number($field);
135 189 $col_int++;
136 } ## end for my $field (@fields)
137  
138 63 push @data, \@fields;
139  
140 63 $line_int++;
141 } ## end foreach my $line ( read_file( $opt->{'i'} ) )
142 } ## end if ( defined( $opt->{'i'} ) )
143  
144 # set_voting ignores the data argument unless it actually recalibrates, so
145 # passing an (undef) empty list for the no-recalibration cases is fine.
146 2 ▶ $iforest->set_voting( $opt->{'voting'}, @data ? \@data : undef );
Branch: 1 branch
BranchTrueFalseTotal
@data ? : 1 1 2
147  
148 2 my $model = $iforest->to_json;
149  
150 2 ▶ if ( $opt->{'p'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"p"}) 1 1 2
151 1 print $model. "\n";
152 1 exit 0;
153 }
154  
155 # Default to writing back over the input model; -o redirects elsewhere.
156 1 ▶ write_file( defined( $opt->{'o'} ) ? $opt->{'o'} : $opt->{'m'}, { 'atomic' => 1 }, $model );
Branch: 1 branch
BranchTrueFalseTotal
defined $opt->{'o'} ? : 0 1 1
157 } ## end sub execute
158  
159 =head1 NAME
160  
161 Algorithm::Classifier::IsolationForest::App::Command::set_voting - Switch a saved model between mean and majority voting
162  
163 =head1 DESCRIPTION
164  
165 Switches a saved model's scoring-time aggregation between C<mean> and
166 C<majority> and writes it back -- in place over C<-m> by default, or to
167 C<-o>.
168  
169 The forest itself is aggregation-independent, so no tree is rebuilt. The
170 one thing that does not carry over is a contamination-learned decision
171 threshold: it is a quantile of whichever per-point quantity the mode
172 thresholds against -- the averaged anomaly score under C<mean>, the
173 per-tree majority pivot under C<majority> -- so switching relearns it for
174 the target mode. That recalibration needs the original training data,
175 supplied as a CSV via C<-i>. A model fit without contamination carries no
176 threshold and switches without C<-i>.
177  
178 Run it as C<iforest set_voting>; C<iforest help set_voting> lists every option.
179  
180 =head1 METHODS
181  
182 L<App::Cmd> calls these while dispatching the subcommand. Nothing else
183 should.
184  
185 =head2 opt_spec
186  
187 Returns this command's option specifications, as the list of arrayrefs
188 L<Getopt::Long::Descriptive> expects.
189  
190 =head2 abstract
191  
192 Returns the one-line summary C<iforest commands> prints beside the
193 command name.
194  
195 =head2 description
196  
197 Returns the long help text C<iforest help set_voting> prints under the option
198 list.
199  
200 =head2 validate
201  
202 Checks the parsed options before anything is read or written, so a
203 mistake costs nothing.
204  
205 Checks that C<-m> names a readable model, that C<--voting> is C<mean> or
206 C<majority>, that C<-i> (when given) is readable, and that C<-o> does not
207 already exist unless C<-w> was given.
208  
209 Takes the parsed options hashref and the arrayref of remaining
210 arguments. Calls C<usage_error>, which prints the usage and exits, on
211 the first problem it finds, and returns 1 when everything checks out.
212  
213 =head2 execute
214  
215 Loads the model, switches its aggregation, recalibrating the threshold
216 from C<-i> when the model needs it, and writes the model back.
217  
218 Takes the parsed options hashref and the arrayref of remaining
219 arguments, and returns 1.
220  
221 =cut
222  
223 86 return 1;
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/proto.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/streamc.pm »