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

filter: Statementstmt 87.5% 77 / 88 Branchbran 65.2% 30 / 46 Conditioncond 53.3% 8 / 15 MC/DCmcdc 11.1% 1 / 9 Subroutinesub 83.3% 10 / 12 Podpod 100% 5 / 5 totaltotal 74.8% 131 / 175 CC 35 SCAR 31.3
CC
35
Cov
77%
validate
37.3
execute
24.0
abstract
2.0
CRAP 22.8
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/gblob.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest.pm »
1 package Algorithm::Classifier::IsolationForest::App::Command::predict;
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 Algorithm::Classifier::IsolationForest::App::Command::pack ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 86 ▶use File::Slurp qw(read_file write_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 86 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 4 ▶sub opt_spec {
Subroutine opt_spec: called CC=1 SCAR=0.0
Pod documented
12 return (
13 [
14 4 'm=s',
15 'Input model JSON file path/name.',
16 { 'default' => 'iforest_model.json', 'completion' => 'files' }
17 ],
18 [ 'i=s', 'Input CSV for processing.', { 'completion' => 'files' } ],
19 [ 'o=s', 'Output to this file instead of printing.', { 'completion' => 'files' } ],
20 [ 'w', 'If the file specified via -o exists, over write it.', { 'completion' => 'files' } ],
21 [ 't=f', 'Alternative threshold value to use. 0 < $val < 1' ],
22 [ 'd', 'Include the input data in the output.' ],
23 );
24 } ## end sub opt_spec
25  
26 0 ▶sub abstract { 'Processes the data using the score_predict_samples using the specified model' }
Subroutine abstract: not called CC=1 SCAR=6.9
Pod documented
27  
28 0 ▶sub description {
Subroutine description: not called CC=1 SCAR=6.9
Pod documented
29 0 'Processes the data using the score_predict_samples using the specified model.
30  
31 The input may be either a CSV (one row of features per line) or a
32 .iforest-packed binary produced by `iforest pack` (auto-detected via
33 its magic bytes; cuts the CSV parse + pack_input_xs cost on repeated
34 runs against the same dataset).
35  
36 The input CSV may have any number of feature columns; every row must have the
37 same column count and every value must be numeric.
38  
39 Output format is as below per line.
40  
41 $score,$predict
42  
43 If -d is specified all input feature columns are prepended. When the
44 input is a .iforest-packed file the columns come from unpacking the
45 stored doubles.
46  
47 $feat1,...,$featN,$score,$predict
48 ';
49 } ## end sub description
50  
51 4 ▶sub validate {
Subroutine validate: called CC=13 SCAR=36.2
Pod documented
52 4 my ( $self, $opt, $args ) = @_;
53  
54 4 ▶ if ( !defined( $opt->{'i'} ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opt->{'i'}) { } 0 4 4
elsif (not -f $opt->{'i'}) { } 0 4 4
elsif (not -r $opt->{'i'}) { } 0 4 4
55 0 $self->usage_error('-i has not been specified for a file to process');
56 } elsif ( !-f $opt->{'i'} ) {
57 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not a file or does not exist' );
58 } elsif ( !-r $opt->{'i'} ) {
59 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not readable' );
60 }
61  
62 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
63 0 $self->usage_error( '-m, "' . $opt->{'m'} . '", is not a file or does not exist' );
64 } elsif ( !-r $opt->{'m'} ) {
65 0 $self->usage_error( '-m, "' . $opt->{'m'} . '", is not readable' );
66 }
67  
68 4 ▶ 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 4 4
Condition66%4/6
defined $opt->{"o"} and not $opt->{"w"} and -e $opt->{"o"}
!ll&&!rl&&r
220
defined $opt->{"o"} and not $opt->{"w"}
!ll&&!rl&&r
202
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 table50%2/4
A and not(B) and C
A= defined $opt->{"o"}B= not $opt->{"w"}C= -e $opt->{"o"}
ABCresult
0XX0
10X0
1100
1111
69 0 $self->usage_error( '-o, "' . $opt->{'o'} . '", already exists and -w is not specified' );
70 }
71  
72 4 ▶ if ( defined( $opt->{'t'} ) && $opt->{'t'} <= 0 ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opt->{'t'} and $opt->{'t'} <= 0) { } 0 4 4
elsif (defined $opt->{'t'} and $opt->{'t'} >= 1) { } 0 8 8
Condition33%1/3
defined $opt->{"t"} and $opt->{"t"} <= 0
!ll&&!rl&&r
400
MC/DC0%0/2
defined $opt->{"t"} and $opt->{"t"} <= 0
defined $opt->{"t"} $opt->{"t"} <= 0
Truth table33%1/3
A and B
A= defined $opt->{"t"}B= $opt->{"t"} <= 0
ABresult
0X0
100
111
73 0 $self->usage_error( '-t, "' . $opt->{'t'} . '", needs to be greater than 0 and less than 1' );
74 ▶ } elsif ( defined( $opt->{'t'} ) && $opt->{'t'} >= 1 ) {
Condition33%1/3
defined $opt->{"t"} and $opt->{"t"} >= 1
!ll&&!rl&&r
400
MC/DC0%0/2
defined $opt->{"t"} and $opt->{"t"} >= 1
defined $opt->{"t"} $opt->{"t"} >= 1
Truth table33%1/3
A and B
A= defined $opt->{"t"}B= $opt->{"t"} >= 1
ABresult
0X0
100
111
75 0 $self->usage_error( '-t, "' . $opt->{'t'} . '", needs to be greater than 0 and less than 1' );
76 }
77  
78 4 return 1;
79 } ## end sub validate
80  
81 4 ▶sub execute {
Subroutine execute: called CC=23 SCAR=31.8
Pod documented
82 4 my ( $self, $opt, $args ) = @_;
83  
84 4 my $iforest = Algorithm::Classifier::IsolationForest->load( $opt->{'m'} );
85  
86 # A model carrying Algorithm::ToNumberMunger specs takes raw values in
87 # its munged CSV columns: skip the per-field numeric check at read
88 # time and munge the rows before scoring (re-checking numerics after).
89 # Packed input is never munged -- it is already doubles.
90 4 ▶ my $has_mungers = ref $iforest->{mungers} eq 'HASH' && %{ $iforest->{mungers} } ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $iforest->{'mungers'} eq 'HASH' && %{$iforest->{'mungers'};} ? : 1 3 4
Condition66%2/3
ref $iforest->{"mungers"} eq "HASH" and %{$iforest->{"mungers"};}
!ll&&!rl&&r
301
MC/DC50%1/2
ref $iforest->{"mungers"} eq "HASH" and %{$iforest->{"mungers"};}
ref $iforest->{"mungers"} eq "HASH" %{$iforest->{"mungers"};}
Truth table66%2/3
A and B
A= ref $iforest->{"mungers"} eq "HASH"B= %{$iforest->{"mungers"};}
ABresult
0X0
100
111
91  
92 4 my @data; # arrayref-of-arrayrefs OR re-derived on demand from $packed
93 my $score_input; # what we hand to score_predict_samples
94  
95 4 ▶ if ( Algorithm::Classifier::IsolationForest::App::Command::pack::is_packed_file( $opt->{'i'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (Algorithm::Classifier::IsolationForest::App::Command::pack::is_packed_file($opt->{'i'})) { } 2 2 4
96 my ( $n_pts, $n_feats, $bytes )
97 2 = Algorithm::Classifier::IsolationForest::App::Command::pack::read_packed_file( $opt->{'i'} );
98 die "packed input has $n_feats features but model expects " . $iforest->{n_features} . "\n"
99 2 ▶ if $n_feats != $iforest->{n_features};
Branch: 1 branch
BranchTrueFalseTotal
if $n_feats != $iforest->{"n_features"} 0 2 2
100  
101 # Build a PackedData wrapper directly from the on-disk bytes --
102 # no CSV parse, no pack_input_xs.
103 2 $score_input = bless {
104 packed => $bytes,
105 n_pts => $n_pts,
106 n_feats => $n_feats,
107 },
108 'Algorithm::Classifier::IsolationForest::PackedData';
109  
110 # Only unpack to per-row arrayrefs when -d asks for it, since
111 # that work undoes the whole point of using a packed file.
112 2 ▶ if ( $opt->{'d'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"d"}) 1 1 2
113 1 my @doubles = unpack( 'd*', $bytes );
114 1 for my $i ( 0 .. $n_pts - 1 ) {
115 7 push @data, [ @doubles[ $i * $n_feats .. ( $i + 1 ) * $n_feats - 1 ] ];
116 }
117 }
118 } else {
119 # CSV path
120 2 my $expected_cols;
121 2 my $line_int = 1;
122 2 foreach my $line ( read_file( $opt->{'i'} ) ) {
123 88 chomp($line);
124 88 ▶ next if $line =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^\s*$/ 0 88 88
125  
126 88 my @fields = split( /,/, $line, -1 );
127  
128 88 ▶ if ( !defined($expected_cols) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $expected_cols) { } 2 86 88
elsif (scalar @fields != $expected_cols) { } 0 86 86
129 2 $expected_cols = scalar @fields;
130 2 ▶ die( 'Line ' . $line_int . ' of "' . $opt->{'i'} . '" has no columns' )
Branch: 1 branch
BranchTrueFalseTotal
if $expected_cols < 1 0 2 2
131 if $expected_cols < 1;
132 } elsif ( scalar @fields != $expected_cols ) {
133 die( 'Line '
134 . $line_int . ' of "'
135 0 . $opt->{'i'}
136 . '" has '
137 . scalar(@fields)
138 . ' columns but expected '
139 . $expected_cols );
140 }
141  
142 88 ▶ if ( !$has_mungers ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_mungers) 7 81 88
143 7 my $col_int = 1;
144 7 for my $field (@fields) {
145 die( 'Line '
146 . $line_int . ' of "'
147 21 ▶ . $opt->{'i'}
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($field) 0 21 21
148 . '" value for column '
149 . $col_int . ',"'
150 . $field
151 . '", does not appear to be a number' )
152 unless looks_like_number($field);
153 21 $col_int++;
154 } ## end for my $field (@fields)
155 } ## end if ( !$has_mungers )
156  
157 88 push @data, \@fields;
158  
159 88 $line_int++;
160 } ## end foreach my $line ( read_file( $opt->{'i'} ) )
161 2 ▶ if ($has_mungers) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_mungers) { } 1 1 2
162  
163 # Munge into a separate structure so -d still prints the raw
164 # input columns as given.
165 1 my $munged = $iforest->munge_rows( \@data );
166 1 for my $i ( 0 .. $#$munged ) {
167 81 for my $col ( 0 .. $#{ $munged->[$i] } ) {
168 die( 'Line '
169 . ( $i + 1 ) . ' of "'
170 243 ▶ . $opt->{'i'}
Branch: 2 branches
BranchTrueFalseTotal
unless &looks_like_number($munged->[$i][$col]) 0 243 243
defined $munged->[$i][$col] ? : 0 0 0
171 . '" value for column '
172 . ( $col + 1 ) . ',"'
173 . ( defined $munged->[$i][$col] ? $munged->[$i][$col] : 'undef' )
174 . '", is not a number after munging' )
175 unless looks_like_number( $munged->[$i][$col] );
176 } ## end for my $col ( 0 .. $#{ $munged->[$i] } )
177 } ## end for my $i ( 0 .. $#$munged )
178 1 $score_input = $munged;
179 } else {
180 1 $score_input = \@data;
181 }
182 } ## end else [ if ( Algorithm::Classifier::IsolationForest::App::Command::pack::is_packed_file...)]
183  
184 4 my $results = $iforest->score_predict_samples( $score_input, $opt->{'t'} );
185  
186 4 my $results_string = '';
187  
188 # Drive the loop off $results rather than @data so the packed-input
189 # path (which only populates @data when -d is set) still produces
190 # one output row per scored point.
191 4 for my $i ( 0 .. $#$results ) {
192 102 ▶ if ( $opt->{'d'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{'d'}) { } 7 95 102
193 7 $results_string .= join( ',', @{ $data[$i] } ) . ',' . $results->[$i][0] . ',' . $results->[$i][1] . "\n";
194 } else {
195 95 $results_string .= $results->[$i][0] . ',' . $results->[$i][1] . "\n";
196 }
197 }
198  
199 4 ▶ if ( !defined( $opt->{'o'} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $opt->{"o"}) 2 2 4
200 2 print $results_string;
201 2 exit 0;
202 }
203  
204 2 write_file( $opt->{'o'}, { 'atomic' => 1 }, $results_string );
205 } ## end sub execute
206  
207 =head1 NAME
208  
209 Algorithm::Classifier::IsolationForest::App::Command::predict - Processes the data using the score_predict_samples using the specified model
210  
211 =head1 DESCRIPTION
212  
213 Scores every input row and labels it, printing one line per row:
214  
215 $score,$predict
216  
217 With C<-d> the input feature columns are prepended, which is the form
218 C<iforest csv2plot> expects:
219  
220 $feat1,...,$featN,$score,$predict
221  
222 Input may be a CSV or a C<.iforest-packed> binary from C<iforest pack>,
223 detected by its magic bytes; with a packed input the C<-d> columns come
224 from unpacking the stored doubles.
225  
226 Run it as C<iforest predict>; C<iforest help predict> lists every option.
227  
228 =head1 METHODS
229  
230 L<App::Cmd> calls these while dispatching the subcommand. Nothing else
231 should.
232  
233 =head2 opt_spec
234  
235 Returns this command's option specifications, as the list of arrayrefs
236 L<Getopt::Long::Descriptive> expects.
237  
238 =head2 abstract
239  
240 Returns the one-line summary C<iforest commands> prints beside the
241 command name.
242  
243 =head2 description
244  
245 Returns the long help text C<iforest help predict> prints under the option
246 list.
247  
248 =head2 validate
249  
250 Checks the parsed options before anything is read or written, so a
251 mistake costs nothing.
252  
253 Checks that C<-i> and C<-m> name readable files, that C<-o> may be
254 written, and that C<-t> lies in (0, 1).
255  
256 Takes the parsed options hashref and the arrayref of remaining
257 arguments. Calls C<usage_error>, which prints the usage and exits, on
258 the first problem it finds, and returns 1 when everything checks out.
259  
260 =head2 execute
261  
262 Loads the model, scores the input, and writes the result lines to STDOUT
263 or to C<-o>.
264  
265 Takes the parsed options hashref and the arrayref of remaining
266 arguments, and returns 1.
267  
268 =cut
269  
270 86 return 1;
« blib/lib/Algorithm/Classifier/IsolationForest/App/Command/gblob.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest.pm »