NDBin.pm

filter: Statementstmt 92.5% 25 / 27 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 9 / 9 Podpod n/a totaltotal 94.4% 34 / 36 CC 1 SCAR 0.3
CC
1
Cov
93%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« NDBin/Action/Sum.pm ↑ Summary NDBin/Actions_PP.pm »
1 package PDL::NDBin;
2 # ABSTRACT: Multidimensional binning & histogramming
3 $PDL::NDBin::VERSION = '0.016';
4 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use List::Util qw( reduce );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use List::MoreUtils qw( pairwise );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use Math::Round qw( nlowmult nhimult );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use PDL::Lite; # do not import any functions into this namespace
Subroutine BEGIN: called CC=1 SCAR=0.0
11 3 ▶use PDL::NDBin::Iterator;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use PDL::NDBin::Actions_PP;
Subroutine BEGIN: called CC=1 SCAR=2.6
13 use Log::Any qw( $log );
14 use Data::Dumper;
15 use UUID::Tiny qw( :std );
16 use POSIX qw( ceil );
17 use Params::Validate qw( validate validate_pos validate_with ARRAYREF CODEREF HASHREF SCALAR );
18 use Carp;
19 use Class::Load qw( load_class );
20  
21  
22 our @ISA = qw( Exporter );
23 our @EXPORT = qw( );
24 our @EXPORT_OK = qw( ndbinning ndbin );
25 our %EXPORT_TAGS = ( all => [ qw( ndbinning ndbin ) ] );
26  
27 # the list of valid keys
28 my %valid_key = map { $_ => 1 } qw( axes vars );
29  
30  
31 sub add_axis
32 {
33 my $self = shift;
34 my %params = validate( @_, {
35 max => 0,
36 min => 0,
37 n => 0,
38 name => 1,
39 pdl => 0,
40 round => 0,
41 step => 0,
42 } );
43 $log->tracef( 'adding axis with specs %s', \%params );
44 push @{ $self->{axes} }, \%params;
45 }
46  
47  
48 sub add_var
49 {
50 my $self = shift;
51 my %params = validate( @_, {
52 action => { type => CODEREF | HASHREF | SCALAR },
53 name => 1,
54 pdl => 0,
55 } );
56 $log->tracef( 'adding variable with specs %s', \%params );
57 push @{ $self->{vars} }, \%params;
58 }
59  
60  
61 sub new
62 {
63 my $class = shift;
64 my %params = validate( @_, {
65 axes => { optional => 1, type => ARRAYREF },
66 vars => { optional => 1, type => ARRAYREF },
67 } );
68 $log->debug( 'new: arguments = ' . Dumper \%params ) if $log->is_debug;
69 my $self = bless { axes => [], vars => [] }, $class;
70 # axes
71 $params{axes} ||= []; # be sure we can dereference
72 my @axes = @{ $params{axes} };
73 for my $axis ( @axes ) {
74 my @pat = ( 1 ); # one mandatory argument
75 if( @$axis > 1 ) { push @pat, (0) x (@$axis - 1) } # followed by n-1 optional arguments
76 my( $name ) = validate_pos( @$axis, @pat );
77 shift @$axis; # remove name
78 $self->add_axis( name => $name, @$axis );
79 }
80 # vars
81 $params{vars} ||= []; # be sure we can dereference
82 my @vars = @{ $params{vars} };
83 for my $var ( @vars ) {
84 my( $name, $action ) = validate_pos( @$var, 1, 1 );
85 $self->add_var( name => $name, action => $action );
86 }
87 return $self;
88 }
89  
90  
91 sub axes { wantarray ? @{ $_[0]->{axes} } : $_[0]->{axes} }
92 sub vars { wantarray ? @{ $_[0]->{vars} } : $_[0]->{vars} }
93  
94 sub _make_instance_hashref
95 {
96 my %params = validate_with(
97 params => \@_,
98 spec => {
99 N => 1,
100 class => 1,
101 coderef => 0,
102 },
103 allow_extra => 1,
104 );
105 my $short_class = delete $params{class};
106 my $full_class = substr( $short_class, 0, 1 ) eq '+'
107 ? substr( $short_class, 1 )
108 : "PDL::NDBin::Action::$short_class";
109 load_class( $full_class );
110 return $full_class->new( %params );
111 }
112  
113 sub _make_instance
114 {
115 my %params = validate( @_, {
116 action => 1,
117 N => 1,
118 } );
119 if( ref $params{action} eq 'CODE' ) {
120 return _make_instance_hashref(
121 class => '+PDL::NDBin::Action::CodeRef',
122 N => $params{N},
123 coderef => $params{action},
124 );
125 }
126 elsif( ref $params{action} eq 'HASH' ) {
127 return _make_instance_hashref(
128 %{ $params{action} },
129 N => $params{N},
130 );
131 }
132 else {
133 return _make_instance_hashref(
134 class => $params{action},
135 N => $params{N},
136 );
137 }
138 }
139  
140  
141 sub feed
142 {
143 my $self = shift;
144 my %pdls = @_;
145 while( my( $name, $pdl ) = each %pdls ) {
146 for my $v ( $self->axes, $self->vars ) {
147 $v->{pdl} = $pdl if $v->{name} eq $name;
148 }
149 }
150 }
151  
152 sub _check_all_pdls_present
153 {
154 my $self = shift;
155 my %warned_for;
156 for my $v ( $self->axes, $self->vars ) {
157 next if defined $v->{pdl};
158 next if $v->{action} eq 'Count'; # those variables don't need data
159 my $name = $v->{name};
160 next if $warned_for{ $name };
161 $log->error( "no data for $name" );
162 $warned_for{ $name }++;
163 }
164 }
165  
166 sub _check_pdl_length
167 {
168 my $self = shift;
169 # checking whether the lengths of all axes and variables are equal can
170 # only be done here (in a loop), and not in autoscale_axis()
171 my $length;
172 for my $v ( $self->axes, $self->vars ) {
173 $length = $v->{pdl}->nelem unless defined $length;
174 # variables don't always need a pdl, or may be happy with a
175 # null pdl; let the action figure it out.
176 # note that the test isempty() is not a good test for null
177 # pdls, but until I have a better one, this will have to do
178 next if $v->{action} && ( ! defined $v->{pdl} || $v->{pdl}->isempty );
179 if( $v->{pdl}->nelem != $length ) {
180 croak( join '', 'number of elements (',
181 $v->{pdl}->nelem, ") of '$v->{name}'",
182 " is different from previous ($length)" );
183 }
184 }
185 }
186  
187  
188 sub autoscale_axis
189 {
190 my $axis = shift;
191 # return early if step, min, and n have already been calculated
192 if( defined $axis->{step} && defined $axis->{min} && defined $axis->{n} ) {
193 $log->tracef( 'step, min, n already calculated for %s; not recalculating', $axis );
194 return;
195 }
196 # first get & sanify the arguments
197 croak( 'need coordinates' ) unless defined $axis->{pdl};
198 # return if axis is empty
199 if( $axis->{pdl}->isempty ) {
200 $axis->{n} = 0;
201 return;
202 }
203 $axis->{min} = $axis->{pdl}->min unless defined $axis->{min};
204  
205  
206 $axis->{max} = $axis->{pdl}->max unless defined $axis->{max};
207 if( defined $axis->{round} and $axis->{round} > 0 ) {
208 $axis->{min} = nlowmult( $axis->{round}, $axis->{min} );
209 $axis->{max} = nhimult( $axis->{round}, $axis->{max} );
210 }
211 croak( 'max < min is invalid' ) if $axis->{max} < $axis->{min};
212 if( $axis->{pdl}->type >= PDL::float ) {
213 croak( 'cannot bin with min = max' ) if $axis->{min} == $axis->{max};
214 }
215 # calculate the range
216 # for floating-point data, we need to augment the range by 1 unit - see
217 # the discussion under IMPLEMENTATION NOTES for more details
218 my $range = $axis->{max} - $axis->{min};
219 if( $axis->{pdl}->type < PDL::float ) {
220 $range += 1;
221 }
222 # if step size has been supplied by user, check it
223 if( defined $axis->{step} ) {
224 croak( 'step size must be > 0' ) unless $axis->{step} > 0;
225 if( $axis->{pdl}->type < PDL::float && $axis->{step} < 1 ) {
226 croak( "step size = $axis->{step} < 1 is not allowed when binning integral data" );
227 }
228 }
229 # number of bins I<n>
230 if( defined $axis->{n} ) {
231 croak( 'number of bins must be > 0' ) unless $axis->{n} > 0;
232 croak( 'number of bins must be integral' ) if ceil( $axis->{n} ) - $axis->{n} > 0;
233 }
234 else {
235 if( defined $axis->{step} ) {
236 # data range and step size were verified above,
237 # so the result of this calculation is
238 # guaranteed to be > 0
239 $axis->{n} = ceil( $range / $axis->{step} );
240 }
241 else {
242 # if neither number of bins nor step size is defined,
243 # use some reasonable default (which used to be the
244 # behaviour of hist() in versions of PDL inferior to
245 # 2.4.12) (see F<Basic.pm>)
246 $axis->{n} = $axis->{pdl}->nelem > 100 ? 100 : $axis->{pdl}->nelem;
247 }
248 }
249 # step size I<step>
250 # if we get here, the data range is certain to be larger than
251 # zero, and I<n> is sure to be defined and valid (either
252 # because it was supplied explicitly and verified to be valid,
253 # or because it was calculated automatically)
254 if( ! defined $axis->{step} ) {
255 # result of this calculation is guaranteed to be > 0
256 $axis->{step} = $range / $axis->{n};
257 if( $axis->{pdl}->type < PDL::float ) {
258 croak( 'there are more bins than distinct values' ) if $axis->{step} < 1;
259 }
260 }
261 }
262  
263  
264 sub autoscale
265 {
266 my $self = shift;
267 $self->feed( @_ );
268 $self->_check_all_pdls_present;
269 $self->_check_pdl_length;
270 autoscale_axis( $_ ) for $self->axes;
271 }
272  
273  
274 sub labels
275 {
276 my $self = shift;
277 $self->autoscale( @_ );
278 my @list = map {
279 my $axis = $_;
280 my ( $pdl, $min, $step ) = @{ $axis }{ qw( pdl min step ) };
281 [ map {
282 { # anonymous hash
283 range => $pdl->type() >= PDL::float()
284 ? [ $min + $step*$_, $min + $step*($_+1) ]
285 : $step > 1
286 ? [ nhimult( 1, $min + $step*$_ ), nhimult( 1, $min + $step*($_+1) - 1 ) ]
287 : $min + $step*$_
288 }
289 } 0 .. $axis->{n}-1 ];
290 } $self->axes;
291 return wantarray ? @list : \@list;
292 }
293  
294  
295 sub process
296 {
297 my $self = shift;
298  
299 # sanity check
300 croak( 'no axes supplied' ) unless @{ $self->axes };
301 # default action, when no variables are given, is to produce a histogram
302 $self->add_var( name => 'histogram', action => 'Count' ) unless @{ $self->vars };
303  
304 #
305 $self->autoscale( @_ );
306  
307 # process axes
308 my $idx = 0; # flattened bin number
309 my @n; # number of bins in each direction
310 # find the last axis and flatten all axes into one dimension, working
311 # our way backwards from the last to the first axis
312 for my $axis ( reverse $self->axes ) {
313 $log->debug( 'input (' . $axis->{pdl}->info . ') = ' . $axis->{pdl} ) if $log->is_debug;
314 $log->debug( "bin with parameters step=$axis->{step}, min=$axis->{min}, n=$axis->{n}" )
315 if $log->is_debug;
316 croak( 'I cannot bin unless n > 0' ) unless $axis->{n} > 0;
317 unshift @n, $axis->{n}; # remember that we are working backwards!
318 $idx = $axis->{pdl}->_flatten_into( $idx, $axis->{step}, $axis->{min}, $axis->{n} );
319 }
320 $log->debug( 'idx (' . $idx->info . ') = ' . $idx ) if $log->is_debug;
321 $self->{n} = \@n;
322  
323 my $N = reduce { $a * $b } @n; # total number of bins
324 croak( 'I need at least one bin' ) unless $N;
325 my @vars = map $_->{pdl}, $self->vars;
326 $self->{instances} ||= [ map { _make_instance( N => $N, action => $_->{action} ) } $self->vars ];
327  
328 #
329 {
330 local $Data::Dumper::Terse = 1;
331 $log->trace( 'process: $self = ' . Dumper $self );
332 }
333  
334 # now visit all the bins
335 my $iter = PDL::NDBin::Iterator->new( bins => \@n, array => \@vars, idx => $idx );
336 $log->debug( 'iterator object created: ' . Dumper $iter );
337 while( $iter->advance ) {
338 my $i = $iter->var;
339 $self->{instances}->[ $i ]->process( $iter );
340 }
341  
342 return $self;
343 }
344  
345  
346 sub output
347 {
348 my $self = shift;
349 return unless defined wantarray;
350 unless( defined $self->{result} ) {
351 # reshape output
352 my $n = $self->{n};
353 my @output = map { $_->result } @{ $self->{instances} };
354 for my $pdl ( @output ) { $pdl->reshape( @$n ) }
355 if( $log->is_debug ) { $log->debug( 'output: output (' . $_->info . ') = ' . $_ ) for @output }
356 $self->{result} = { pairwise { $a->{name} => $b } @{ $self->vars }, @output };
357 if( $log->is_debug ) { $log->debug( 'output: result = ' . Dumper $self->{result} ) }
358 }
359 return wantarray ? %{ $self->{result} } : $self->{result};
360 }
361  
362  
363 sub _consume (&\@)
364 {
365 my ( $f, $list ) = @_;
366 for my $i ( 0 .. $#$list ) {
367 local *_ = \$list->[$i];
368 if( not $f->() ) { return splice @$list, 0, $i }
369 }
370 # If we get here, either the list is empty, or all values in the list
371 # meet the condition. In either case, splicing the entire list does
372 # what we want.
373 return splice @$list;
374 }
375  
376 sub _expand_axes
377 {
378 my ( @out, $hash, @num );
379 while( @_ ) {
380 if( eval { $_[0]->isa('PDL') } ) {
381 # a new axis; push the existing one on the output list
382 push @out, $hash if $hash;
383 $hash = { pdl => shift };
384 }
385 elsif( ref $_[0] eq 'HASH' ) {
386 # the user has supplied a hash directly, which may or
387 # may not yet contain a key-value pair pdl => $pdl
388 $hash = { } unless $hash;
389 push @out, { %$hash, %{ +shift } };
390 undef $hash; # do not collapse consecutive hashes into one, too confusing
391 }
392 elsif( @num = _consume { /^[-+]?(\d+(\.\d*)?|\.\d+)([Ee][-+]?\d+)?$/ } @_ ) {
393 croak( 'no axis given' ) unless $hash;
394 croak( "too many arguments to axis in `@num'" ) if @num > 3;
395 # a series of floating-point numbers
396 $hash->{min} = $num[0] if @num > 0;
397 $hash->{max} = $num[1] if @num > 1;
398 $hash->{step} = $num[2] if @num > 2;
399 }
400 #elsif( @num = ( $_[0] =~ m{^((?:\d+(?:\.\d*)?|\.\d+)(?:[Ee][-+]?\d+)?/)+$}g ) and shift ) {
401 # DOES NOT WORK YET - TODO
402 # print "GMT-style axis spec found! (@num)\n";
403 # croak( 'no axis given' ) unless $hash;
404 # croak( "too many arguments to axis in `@num'" ) if @num > 3;
405 # # a string specification of the form 'min/max/step', a la GMT
406 # $hash->{min} = $num[0] if @num > 0;
407 # $hash->{max} = $num[1] if @num > 1;
408 # $hash->{step} = $num[2] if @num > 2;
409 #}
410 else {
411 croak( "while expanding axes: invalid argument at `@_'" );
412 }
413 }
414 push @out, $hash if $hash;
415 return @out;
416 }
417  
418  
419 sub _random_name { create_uuid( UUID_RANDOM ) }
420  
421  
422 sub ndbinning
423 {
424 #
425 my $binner = __PACKAGE__->new;
426  
427 # leading arguments are axes and axis specifications
428 #
429 # PDL overloads the `eq' and `ne' operators; by checking for a PDL
430 # first, we avoid (invalid) comparisons between piddles and strings in
431 # the `grep'
432 my @leading = _consume { eval { $_->isa('PDL') } || ! $valid_key{ $_ } } @_;
433  
434 # consume and process axes
435 # axes require three numerical specifications following it
436 while( @leading > 3 && eval { $leading[0]->isa('PDL') } && ! grep ref, @leading[ 1 .. 3 ] ) {
437 my( $pdl, $step, $min, $n ) = splice @leading, 0, 4;
438 $binner->add_axis( name => _random_name, pdl => $pdl, step => $step, min => $min, n => $n );
439 }
440 if( @leading ) { croak( "error parsing arguments in `@leading'" ) }
441  
442 # remaining arguments are key => value pairs
443 my $args = { @_ };
444 my @invalid_keys = grep ! $valid_key{ $_ }, keys %$args;
445 croak( "invalid key(s) @invalid_keys" ) if @invalid_keys;
446  
447 # axes
448 $args->{axes} ||= [];
449 my @axes = @{ $args->{axes} };
450 for my $axis ( @axes ) {
451 my $pdl = shift @$axis;
452 $binner->add_axis( name => _random_name, pdl => $pdl, @$axis );
453 }
454  
455 # variables
456 $args->{vars} ||= [];
457 for my $var ( @{ $args->{vars} } ) {
458 if( @$var == 2 ) {
459 my( $pdl, $action ) = @$var;
460 $binner->add_var( name => _random_name, pdl => $pdl, action => $action );
461 }
462 else { croak( "wrong number of arguments for var: @$var" ) }
463 }
464  
465 #
466 $binner->process;
467 my $output = $binner->output;
468 my @result = map $output->{ $_->{name} }, @{ $binner->vars };
469 return wantarray ? @result : $result[0];
470 }
471  
472  
473 sub ndbin
474 {
475 #
476 my $binner = __PACKAGE__->new;
477  
478 # leading arguments are axes and axis specifications
479 #
480 # PDL overloads the `eq' and `ne' operators; by checking for a PDL
481 # first, we avoid (invalid) comparisons between piddles and strings in
482 # the `grep'
483 if( my @leading = _consume { eval { $_->isa('PDL') } || ! $valid_key{ $_ } } @_ ) {
484 my @axes = _expand_axes( @leading );
485 $binner->add_axis( name => _random_name, %$_ ) for @axes;
486 }
487  
488 # remaining arguments are key => value pairs
489 my $args = { @_ };
490 my @invalid_keys = grep ! $valid_key{ $_ }, keys %$args;
491 croak( "invalid key(s) @invalid_keys" ) if @invalid_keys;
492  
493 # axes
494 $args->{axes} ||= [];
495 my @axes = @{ $args->{axes} };
496 for my $axis ( @axes ) {
497 my $pdl = shift @$axis;
498 $binner->add_axis( name => _random_name, pdl => $pdl, @$axis );
499 }
500  
501 # variables
502 $args->{vars} ||= [];
503 for my $var ( @{ $args->{vars} } ) {
504 if( @$var == 2 ) {
505 my( $pdl, $action ) = @$var;
506 $binner->add_var( name => _random_name, pdl => $pdl, action => $action );
507 }
508 else { croak( "wrong number of arguments for var: @$var" ) }
509 }
510  
511 $binner->process;
512 my $output = $binner->output;
513 my @result = map $output->{ $_->{name} }, @{ $binner->vars };
514 return wantarray ? @result : $result[0];
515 }
516  
517 1;
518  
519 __END__
« NDBin/Action/Sum.pm ↑ Summary NDBin/Actions_PP.pm »