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

filter: Statementstmt 89.5% 77 / 86 Branchbran 47.5% 19 / 40 Conditioncond 50.0% 3 / 6 MC/DCmcdc 25.0% 1 / 4 Subroutinesub 88.8% 16 / 18 Podpod 100% 7 / 7 totaltotal 76.4% 123 / 161 CC 25 SCAR 21.8
CC
25
Cov
75%
validate
22.6
_read_packed
9.7
execute
8.3
CRAP 8.9
« blib/lib/Algorithm/Classifier/IsolationForest/Online.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/bench.pm »
1 package Algorithm::Classifier::IsolationForest::App::Command::pack;
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 # .iforest-packed v1 file layout (all little-endian):
11 #
12 # offset size field
13 # -----------------------------------------------------------
14 # 0 8 magic -- ASCII "IFPKD\0\0\0"
15 # 8 2 version (uint16, currently 1)
16 # 10 2 reserved (uint16, must be 0)
17 # 12 4 n_pts (uint32)
18 # 16 4 n_feats (uint32)
19 # 20 ... n_pts * n_feats packed doubles ('d' pack format,
20 # little-endian per the IEEE-754 native layout)
21 #
22 # The format is intentionally minimal: the goal is to skip the CSV
23 # parse + pack_input_xs cost on subsequent scoring runs. Models are
24 # not embedded -- the caller must pair the .iforest-packed file with a
25 # model that has the same n_features at score time.
26 86 ▶use constant MAGIC => 'IFPKD' . "\0\0\0"; # 8 bytes
Subroutine BEGIN: called CC=1 SCAR=0.0
27 86 ▶use constant VERSION => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 86 ▶use constant HEADER_LEN => 20;
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 # Read a .iforest-packed file back into the pieces a scoring command
31 # needs. Every field in the header above is checked, so a truncated or
32 # foreign file is reported by name rather than silently scored as noise.
33 #
34 # Args:
35 # $path :: path to the .iforest-packed file, which must be readable.
36 #
37 # Returns: the three-element list ($n_pts, $n_feats, $bytes) -- the row
38 # count, the feature width, and the raw row-major double buffer as a
39 # string. Dies with a message naming $path on a bad magic, an unsupported
40 # version, a non-zero reserved field, or a short read.
41 #
42 # Example:
43 # my ( $n_pts, $n_feats, $bytes ) = _read_packed('data.iforest-packed');
44 # length($bytes) == $n_pts * $n_feats * 8; # true
45 2 ▶sub _read_packed {
Subroutine _read_packed: called CC=8 SCAR=22.7
46 2 my ($path) = @_;
47 2 ▶ open my $fh, '<:raw', $path or die "open '$path' for read: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or die "open '${path}' for read: $!\n" 2 0 2
48 2 my $hdr;
49 2 ▶ read( $fh, $hdr, HEADER_LEN ) == HEADER_LEN
Branch: 1 branch
BranchTrueFalseTotal
read($fh, $hdr, 20) == 20 or die "'${path}' is shorter than a packed-file header\n" 2 0 2
50 or die "'$path' is shorter than a packed-file header\n";
51 2 my ( $magic, $version, $reserved, $n_pts, $n_feats ) = unpack( 'a8 v v V V', $hdr );
52 2 ▶ die "'$path' does not look like a .iforest-packed file\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $magic eq "IFPKD\0\0\0" 0 2 2
53 unless $magic eq MAGIC;
54 2 ▶ die "'$path' is .iforest-packed version $version; only " . VERSION . " is supported\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $version == 1 0 2 2
55 unless $version == VERSION;
56 2 ▶ die "'$path' has non-zero reserved field $reserved\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $reserved == 0 0 2 2
57 unless $reserved == 0;
58 2 my $bytes;
59 2 my $want = $n_pts * $n_feats * 8;
60 2 ▶ read( $fh, $bytes, $want ) == $want
Branch: 2 branches
BranchTrueFalseTotal
read($fh, $bytes, $want) == $want or die "'${path}' truncated: wanted $want bytes, got " . (defined $bytes ? length $bytes : 0) . "\n" 2 0 2
defined $bytes ? : 0 0 0
61 or die "'$path' truncated: wanted $want bytes, got " . ( defined $bytes ? length($bytes) : 0 ) . "\n";
62 2 close $fh;
63 2 return ( $n_pts, $n_feats, $bytes );
64 } ## end sub _read_packed
65  
66 # Write a .iforest-packed file: the header above followed by the buffer.
67 # The write is atomic, so a consumer never sees a half-written file even
68 # if the pack is interrupted.
69 #
70 # Args:
71 # $path :: where to write. An existing file is replaced.
72 # $n_pts :: the row count, recorded in the header.
73 # $n_feats :: the feature width, recorded in the header.
74 # $bytes :: the row-major double buffer as a string, normally straight
75 # from pack_data. Must be $n_pts * $n_feats * 8 bytes long --
76 # nothing re-checks that here.
77 #
78 # Returns: nothing. Dies through File::Slurp if the write fails.
79 #
80 # Example:
81 # _write_packed( 'data.iforest-packed', $n_pts, $n_feats, $packed->{packed} );
82 1 ▶sub _write_packed {
Subroutine _write_packed: called CC=1 SCAR=0.0
83 1 my ( $path, $n_pts, $n_feats, $bytes ) = @_;
84 1 my $hdr = pack( 'a8 v v V V', MAGIC, VERSION, 0, $n_pts, $n_feats );
85 1 write_file( $path, { 'atomic' => 1, 'binmode' => ':raw' }, $hdr . $bytes );
86 }
87  
88 # The public face of _read_packed; see the POD below. Exists so predict,
89 # explain and bench all read the format the same way rather than each
90 # reaching for the underscore name.
91 2 ▶sub read_packed_file { _read_packed(@_) }
Subroutine read_packed_file: called CC=1 SCAR=0.0
Pod documented
92  
93 # Cheap, allocation-light magic check; see the POD below. This is how -i
94 # decides between a CSV and a packed file without being told which it was
95 # handed.
96 7 ▶sub is_packed_file {
Subroutine is_packed_file: called CC=3 SCAR=11.2
Pod documented
97 7 my ($path) = @_;
98 7 ▶ open my $fh, '<:raw', $path or return 0;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or return 0 7 0 7
99 7 my $magic;
100 7 my $ok = read( $fh, $magic, 8 ) == 8;
101 7 close $fh;
102 7 ▶ return $ok && $magic eq MAGIC;
Condition66%2/3
$ok && $magic eq "IFPKD\000\000\000"
!ll&&!rl&&r
052
MC/DC50%1/2
$ok && $magic eq "IFPKD\000\000\000"
$ok $magic eq "IFPKD\000\000\000"
Truth table66%2/3
A && B
A= $okB= $magic eq "IFPKD\000\000\000"
ABresult
0X0
100
111
103 }
104  
105 1 ▶sub opt_spec {
Subroutine opt_spec: called CC=1 SCAR=0.0
Pod documented
106 return (
107 [
108 1 'm=s',
109 'Model JSON to validate n_features against.',
110 { 'default' => 'iforest_model.json', 'completion' => 'files' }
111 ],
112 [ 'i=s', 'Input CSV to pack.', { 'completion' => 'files' } ],
113 [ 'o=s', 'Output .iforest-packed file path.', { 'completion' => 'files' } ],
114 [ 'w', 'Overwrite -o if it already exists.' ],
115 );
116 } ## end sub opt_spec
117  
118 0 ▶sub abstract { 'Pre-pack a CSV dataset into a binary file the scoring commands can read directly' }
Subroutine abstract: not called CC=1 SCAR=6.9
Pod documented
119  
120 0 ▶sub description {
Subroutine description: not called CC=1 SCAR=6.9
Pod documented
121 0 'Reads a CSV, validates that every row has the same numeric
122 column count as the model expects, runs the data through pack_data, and
123 writes a self-contained binary (.iforest-packed) the other iforest
124 commands can consume directly.
125  
126 This skips the CSV parse + pack_input_xs cost on subsequent scoring
127 runs. It is most useful when the same data set is scored repeatedly
128 with different thresholds, e.g. during interactive tuning:
129  
130 iforest pack -m model.json -i data.csv -o data.packed
131 iforest predict -m model.json -i data.packed -t 0.55 -o pred-55.csv
132 iforest predict -m model.json -i data.packed -t 0.65 -o pred-65.csv
133 iforest predict -m model.json -i data.packed -t 0.75 -o pred-75.csv
134  
135 The file format begins with the magic bytes "IFPKD\0\0\0". predict
136 auto-detects it on its -i input.
137  
138 Requires the Inline::C backend; pure-Perl installs cannot produce or
139 consume the packed format.
140 ';
141 } ## end sub description
142  
143 1 ▶sub validate {
Subroutine validate: called CC=9 SCAR=31.2
Pod documented
144 1 my ( $self, $opt, $args ) = @_;
145  
146 1 ▶ if ( !defined $opt->{'i'} ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $opt->{'i'}) { } 0 1 1
elsif (not -f $opt->{'i'}) { } 0 1 1
elsif (not -r $opt->{'i'}) { } 0 1 1
147 0 $self->usage_error('-i has not been specified');
148 } elsif ( !-f $opt->{'i'} ) {
149 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not a file or does not exist' );
150 } elsif ( !-r $opt->{'i'} ) {
151 0 $self->usage_error( '-i, "' . $opt->{'i'} . '", is not readable' );
152 }
153  
154 1 ▶ if ( !defined $opt->{'o'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $opt->{'o'}) { } 0 1 1
elsif (-e $opt->{'o'} and not $opt->{'w'}) { } 0 2 2
155 0 $self->usage_error('-o has not been specified');
156 ▶ } elsif ( -e $opt->{'o'} && !$opt->{'w'} ) {
Condition33%1/3
-e $opt->{"o"} and not $opt->{"w"}
!ll&&!rl&&r
100
MC/DC0%0/2
-e $opt->{"o"} and not $opt->{"w"}
-e $opt->{"o"} not $opt->{"w"}
Truth table33%1/3
A and not(B)
A= -e $opt->{"o"}B= not $opt->{"w"}
ABresult
0X0
100
111
157 0 $self->usage_error( '-o, "' . $opt->{'o'} . '", already exists and -w was not specified' );
158 }
159  
160 1 ▶ if ( !-f $opt->{'m'} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not -f $opt->{'m'}) { } 0 1 1
elsif (not -r $opt->{'m'}) { } 0 1 1
161 0 $self->usage_error( '-m, "' . $opt->{'m'} . '", is not a file or does not exist' );
162 } elsif ( !-r $opt->{'m'} ) {
163 0 $self->usage_error( '-m, "' . $opt->{'m'} . '", is not readable' );
164 }
165  
166 1 return 1;
167 } ## end sub validate
168  
169 1 ▶sub execute {
Subroutine execute: called CC=8 SCAR=21.2
Pod documented
170 1 my ( $self, $opt, $args ) = @_;
171  
172 1 ▶ die "iforest pack requires the Inline::C backend\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $Algorithm::Classifier::IsolationForest::HAS_C 0 1 1
173 unless $Algorithm::Classifier::IsolationForest::HAS_C;
174  
175 1 my $model = Algorithm::Classifier::IsolationForest->load( $opt->{'m'} );
176 1 my $nf = $model->{n_features};
177  
178 1 my @data;
179 1 my $line = 0;
180 1 for my $row ( read_file( $opt->{'i'} ) ) {
181 7 $line++;
182 7 chomp $row;
183 7 ▶ next if $row =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $row =~ /^\s*$/ 0 7 7
184 7 my @f = split /,/, $row, -1;
185 7 ▶ die "line $line of '$opt->{i}' has " . scalar(@f) . " columns but model has $nf features\n"
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @f == $nf 0 7 7
186 unless scalar @f == $nf;
187 7 for my $v (@f) {
188 21 ▶ die "line $line of '$opt->{i}' value '$v' is not numeric\n"
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($v) 0 21 21
189 unless looks_like_number($v);
190 }
191 7 push @data, \@f;
192 } ## end for my $row ( read_file( $opt->{'i'} ) )
193 1 ▶ die "input '$opt->{i}' contains no rows\n" unless @data;
Branch: 1 branch
BranchTrueFalseTotal
unless @data 0 1 1
194  
195 1 my $packed = $model->pack_data( \@data );
196 1 _write_packed( $opt->{'o'}, $packed->n_pts, $packed->n_feats, $packed->{packed} );
197  
198 printf "wrote %s (%d rows, %d features, %d bytes payload)\n",
199 1 $opt->{'o'}, $packed->n_pts, $packed->n_feats,
200 $packed->n_pts * $packed->n_feats * 8;
201  
202 1 return 1;
203 } ## end sub execute
204  
205 =head1 NAME
206  
207 Algorithm::Classifier::IsolationForest::App::Command::pack - Pre-pack a CSV dataset into a binary file the scoring commands can read directly
208  
209 =head1 DESCRIPTION
210  
211 Converts a CSV into the C<.iforest-packed> binary format, so repeated
212 scoring runs over the same dataset skip the CSV parse and the input-packing
213 step. C<iforest predict> and C<iforest explain> detect the format by its
214 magic bytes and take it wherever they take a CSV.
215  
216 The file holds only the packed doubles and their dimensions -- no model is
217 embedded, so it is on the caller to pair it with a model of the same
218 feature width.
219  
220 Run it as C<iforest pack>; C<iforest help pack> lists every option.
221  
222 =head1 METHODS
223  
224 L<App::Cmd> calls these while dispatching the subcommand. Nothing else
225 should.
226  
227 =head2 opt_spec
228  
229 Returns this command's option specifications, as the list of arrayrefs
230 L<Getopt::Long::Descriptive> expects.
231  
232 =head2 abstract
233  
234 Returns the one-line summary C<iforest commands> prints beside the
235 command name.
236  
237 =head2 description
238  
239 Returns the long help text C<iforest help pack> prints under the option
240 list.
241  
242 =head2 validate
243  
244 Checks the parsed options before anything is read or written, so a
245 mistake costs nothing.
246  
247 Checks that C<-i> and C<-o> were given, that C<-i> is readable, and that
248 C<-m> names a readable model.
249  
250 Takes the parsed options hashref and the arrayref of remaining
251 arguments. Calls C<usage_error>, which prints the usage and exits, on
252 the first problem it finds, and returns 1 when everything checks out.
253  
254 =head2 execute
255  
256 Reads the CSV, packs it through the model, and writes the binary to C<-o>.
257  
258 Takes the parsed options hashref and the arrayref of remaining
259 arguments, and returns 1.
260  
261 =head2 read_packed_file
262  
263 Reads a C<.iforest-packed> file, so the scoring commands all parse the
264 format the same way.
265  
266 Takes the path and returns the three-element list of the row count, the
267 feature width, and the raw row-major double buffer. It dies naming the
268 path on a bad magic number, an unsupported version, or a truncated file.
269  
270 my ( $n_pts, $n_feats, $bytes ) = $class->read_packed_file($path);
271  
272 =head2 is_packed_file
273  
274 Cheap check for whether a path holds a C<.iforest-packed> file, so a
275 command can tell a packed input from a CSV without slurping either.
276  
277 Takes the path and returns true when the first eight bytes are the
278 format's magic number. A missing or unreadable path is simply false, so
279 this never dies and needs no C<-f> test first.
280  
281 if ( is_packed_file($input) ) { ... }
282  
283 =cut
284  
285 86 return 1;
« blib/lib/Algorithm/Classifier/IsolationForest/Online.pm ↑ Summary blib/lib/Algorithm/Classifier/IsolationForest/App/Command/bench.pm »