blib/lib/Term/Fabulous/Widget/Histogram.pm untested

filter: Statementstmt 0.0% 0 / 178 Branchbran 0.0% 0 / 70 Conditioncond 0.0% 0 / 49 MC/DCmcdc 0.0% 0 / 26 Subroutinesub 0.0% 0 / 14 Podpod n/a totaltotal 0.0% 0 / 337 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package Term::Fabulous::Widget::Histogram;
2  
3 use v5.32;
4 use warnings;
5 use feature 'signatures';
6 no warnings 'experimental::signatures';
7  
8 our $VERSION = '0.05';
9  
10 use Object::Pad 0.825;
11  
12 use Term::Fabulous::Widget::XYChart;
13  
14 class Term::Fabulous::Widget::Histogram
15 :isa(Term::Fabulous::Widget::XYChart)
16 :strict(params)
17 {
18 use Carp qw(croak);
19 use List::Util ();
20 use POSIX qw(ceil floor);
21 use Term::Fabulous::Check qw(boolean one_of);
22 use Term::Fabulous::Chart::Format qw(format_value);
23 use Term::Fabulous::Chart::Transform qw(apply_transforms);
24 use Term::Fabulous::Widget::Table::Value qw(number_of);
25  
26 use constant {
27 MOST_AUTO_BINS => 50,
28 MOST_BINS => 1000,
29 OVERLAP_OPACITY => 0.6,
30 };
31  
32 my @MEASURE = qw(count percent density);
33  
34 field $bins :param = 'auto';
35 field $bin_width :param = undef;
36 field $range :param = undef;
37 field $measure :param = 'count';
38 field $cumulative :param = 0;
39  
40 ADJUST {
41 $bins = $self->_checked_bins($bins);
42 $bin_width = $self->_checked_bin_width($bin_width);
43 $range = $self->_checked_range($range);
44 $measure = one_of( $self, measure => $measure, @MEASURE );
45 $cumulative = boolean( $self, cumulative => $cumulative );
46 }
47  
48 method default_series_type () { return 'bar' }
49 method series_types :override () { return 'bar' }
50  
51 method _checked_bins ($value) {
52 return 'auto' if defined $value && !ref $value && $value eq 'auto';
53 $self->_fail( 'bins', "'auto' or a positive integer up to " . MOST_BINS, $value ) unless defined $value && !ref $value && $value =~ /\A[1-9][0-9]*\z/ && $value <= MOST_BINS;
54 return $value + 0;
55 }
56  
57 # A histogram counts plain numbers: it has no x values of its own.
58 method check_series_points :override ( $name, $points ) {
59 croak ref($self) . ": series '$name' of a histogram takes plain numbers, not [ x, y ] points" if grep { defined $_->[0] } @$points;
60 return;
61 }
62  
63 method _checked_bin_width ($value) {
64 return undef unless defined $value;
65 $self->_fail( 'bin_width', 'a positive number or undef', $value ) unless defined number_of($value) && $value > 0;
66 return $value + 0;
67 }
68  
69 method _checked_range ($value) {
70 return undef unless defined $value;
71 $self->_fail( 'range', 'an array reference [ low, high ] with low below high, or undef', $value )
72 unless ref $value eq 'ARRAY' && @$value == 2 && ( grep { defined number_of($_) } @$value ) == 2 && $value->[0] < $value->[1];
73 return [ map { $_ + 0 } @$value ];
74 }
75  
76 method _set ( $field_ref, $value ) {
77 $$field_ref = $value;
78 $self->mark_changed;
79 return $value;
80 }
81  
82 method bins (@new) { return @new ? $self->_set( \$bins, $self->_checked_bins( $new[0] ) ) : $bins }
83 method bin_width (@new) { return @new ? $self->_set( \$bin_width, $self->_checked_bin_width( $new[0] ) ) : $bin_width }
84 method measure (@new) { return @new ? $self->_set( \$measure, one_of( $self, measure => $new[0], @MEASURE ) ) : $measure }
85 method cumulative (@new) { return @new ? $self->_set( \$cumulative, boolean( $self, cumulative => $new[0] ) ) : $cumulative }
86  
87 method range (@new) {
88 return defined $range ? [@$range] : undef unless @new;
89 $self->_set( \$range, $self->_checked_range( $new[0] ) );
90 return $self->range;
91 }
92  
93 # ---------------------------------------------------------------------
94 # Bins
95 # ---------------------------------------------------------------------
96  
97 # The observations of a series: its y values (plain numbers), after its
98 # transform.
99 method _observations ($series) {
100 my @values;
101 foreach my $point ( $series->points->@* ) {
102 push @values, $point->[1] if defined $point->[1];
103 }
104 if ( my $steps = $self->series_option( $series, 'transform' ) ) {
105 ( undef, my $ys ) = apply_transforms( $steps, [ 0 .. $#values ], \@values );
106 @values = grep { defined } @$ys;
107 }
108 return \@values;
109 }
110  
111 # A nice width near $width: 1, 2, 2.5 or 5 times a power of ten.
112 sub _nice_width ($width) {
113 my $power = 10**floor( log($width) / log(10) );
114 foreach my $mantissa ( 1, 2, 2.5, 5, 10 ) {
115 return $mantissa * $power if $mantissa * $power >= $width * 0.75;
116 }
117 return 10 * $power;
118 }
119  
120 # The next nice width above $width.
121 sub _wider_nice_width ($width) {
122 my $power = 10**floor( log($width) / log(10) );
123 foreach my $mantissa ( 1, 2, 2.5, 5, 10 ) {
124 return $mantissa * $power if $mantissa * $power > $width * ( 1 + 1e-9 );
125 }
126 return 20 * $power;
127 }
128  
129 # The edges of the bins over all observations.
130 method bin_edges (@samples) {
131 my @all = map { @$_ } @samples;
132 my ( $low, $high ) = $range ? @$range : @all ? ( List::Util::min(@all), List::Util::max(@all) ) : ( 0, 1 );
133 $high = $low + 1 if $high <= $low;
134 return map { $low + ( $high - $low ) * $_ / $bins } 0 .. $bins unless defined $bin_width || $bins eq 'auto';
135  
136 # A given width too small for the data widens to a nice width that
137 # makes at most MOST_BINS bins.
138 my $width = $bin_width // _nice_width( _auto_width( \@all, $low, $high ) );
139 $width = _nice_width( ( $high - $low ) / MOST_BINS ) if ( $high - $low ) / $width > MOST_BINS;
140 my ( $first, $last, $count ) = $self->_bins_of_width( $low, $high, $width );
141 ( $first, $last, $count ) = $self->_bins_of_width( $low, $high, $width = _wider_nice_width($width) ) while $count > MOST_BINS;
142 return map { List::Util::min( $first + $_ * $width, $last ) } 0 .. $count;
143 }
144  
145 # The first and the last edge and the number of bins $width wide from
146 # $low to $high: rounded out to multiples of the width without a range.
147 method _bins_of_width ( $low, $high, $width ) {
148 my $first = $range ? $low : floor( $low / $width + 1e-9 ) * $width;
149 my $last = $range ? $high : ceil( $high / $width - 1e-9 ) * $width;
150 $last += $width if $last <= $first;
151 return ( $first, $last, List::Util::max( 1, ceil( ( $last - $first ) / $width - 1e-9 ) ) );
152 }
153  
154 # Freedman-Diaconis (twice the interquartile range over the cube root
155 # of the count), or Sturges' rule when the quartiles coincide.
156 sub _auto_width ( $values, $low, $high ) {
157 my @sorted = sort { $a <=> $b } @$values;
158 my $count = @sorted;
159 return ( $high - $low ) / 10 if $count < 2;
160 my $quartile = sub ($p) {
161 my $at = ( $count - 1 ) * $p;
162 my $below = floor($at);
163 return $sorted[$below] + ( $sorted[ List::Util::min( $below + 1, $#sorted ) ] - $sorted[$below] ) * ( $at - $below );
164 };
165 my $spread = $quartile->(0.75) - $quartile->(0.25);
166 my $width = $spread > 0 ? 2 * $spread / $count**( 1 / 3 ) : ( $high - $low ) / ( ceil( log($count) / log(2) ) + 1 );
167 my $least = ( $high - $low ) / MOST_AUTO_BINS;
168 return List::Util::max( $width, $least ) || 1;
169 }
170  
171 # The counts of the series per bin, as the measure says.
172 method prepare_series :override () {
173 my @series = $self->visible_series;
174 my @samples = map { $self->_observations($_) } @series;
175 my @edges = $self->bin_edges(@samples);
176 my $last = $#edges - 1;
177 my @labels = map { format_value( $edges[$_] ) . "\x{2013}" . format_value( $edges[ $_ + 1 ] ) } 0 .. $last;
178 my @prepared;
179 foreach my $index ( 0 .. $#series ) {
180 my @counts = (0) x ( $last + 1 );
181 foreach my $value ( $samples[$index]->@* ) {
182 next if $value < $edges[0] || $value > $edges[-1];
183 my $bin = 0;
184 my ( $low, $high ) = ( 0, $last );
185 while ( $low < $high ) {
186 my $middle = int( ( $low + $high + 1 ) / 2 );
187 $edges[$middle] <= $value ? ( $low = $middle ) : ( $high = $middle - 1 );
188 }
189 $counts[$low]++;
190 }
191 my $total = List::Util::sum0(@counts) || 1;
192 my @values
193 = $measure eq 'percent' ? map { $_ / $total } @counts
194 : $measure eq 'density' ? map { $counts[$_] / $total / ( $edges[ $_ + 1 ] - $edges[$_] ) } 0 .. $last
195 : @counts;
196 if ($cumulative) {
197 my $sum = 0;
198 @values = map { $sum += $_ } @values;
199 }
200 push @prepared, {
201 series => $series[$index],
202 name => $series[$index]->name,
203 type => 'bar',
204 xs => [ map { ( $edges[$_] + $edges[ $_ + 1 ] ) / 2 } 0 .. $last ],
205 ys => \@values,
206 edges => [ map { [ $edges[$_], $edges[ $_ + 1 ] ] } 0 .. $last ],
207 labels => \@labels,
208 };
209 }
210 $self->stack_series( \@prepared );
211 return ( 'linear', [], \@prepared );
212 }
213  
214 # Overlapping datasets show through each other; stacked ones are opaque.
215 method default_bar_opacity :override ($bars) {
216 my @overlapping = grep { !defined $_->{group} } @$bars;
217 return @overlapping > 1 ? OVERLAP_OPACITY : 1;
218 }
219  
220 method value_format :override () {
221 my $format = $self->SUPER::value_format;
222 return $format // ( $measure eq 'percent' ? 'percent' : undef );
223 }
224  
225 method layout_properties :common () {
226 return (
227 $class->SUPER::layout_properties,
228 bins => 'scalar',
229 bin_width => 'scalar',
230 measure => 'scalar',
231 cumulative => 'boolean',
232 range => \&_parse_range,
233 );
234 }
235  
236 # range 0 100
237 method _parse_range ($kid) {
238 my @args = map { $_->as_perl } $kid->args->@*;
239 croak ref($self) . ": layout property 'range' takes a low and a high value" unless @args == 2 && !$kid->props->@* && !$kid->children->@*;
240 $self->range( \@args );
241 return;
242 }
243 }
244  
245 1;
246  
247 __END__