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

filter: Statementstmt 0.0% 0 / 325 Branchbran 0.0% 0 / 98 Conditioncond 0.0% 0 / 84 MC/DCmcdc 0.0% 0 / 51 Subroutinesub 0.0% 0 / 21 Podpod n/a totaltotal 0.0% 0 / 579 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::RadarChart;
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::Role::HasSeries;
13 use Term::Fabulous::Widget::Chart;
14  
15 class Term::Fabulous::Widget::RadarChart
16 :isa(Term::Fabulous::Widget::Chart)
17 :does(Term::Fabulous::Role::HasSeries)
18 :strict(params)
19 {
20 use Carp qw(croak);
21 use List::Util ();
22 use POSIX qw(floor ceil);
23 use Scalar::Util qw(looks_like_number);
24 use Term::Fabulous::Check qw(boolean one_of);
25 use Term::Fabulous::Chart::Format qw(check_number_format format_value);
26 use Term::Fabulous::Chart::Marker;
27 use Term::Fabulous::Chart::Radial qw(CELL_ASPECT TAU circle_frame point_at);
28 use Term::Fabulous::Chart::Raster;
29 use Term::Fabulous::Chart::Scale::Linear;
30 use Term::Fabulous::Chart::Surface;
31 use Term::Fabulous::Chart::Transform qw(apply_transforms);
32 use Term::Fabulous::Widget::Table::Value qw(number_of);
33  
34 use constant {
35 FILL_OPACITY => 0.25,
36 DOT_POINT => 'dot',
37 SQUARE_POINT => 'square',
38 POINT => "\x{2022}",
39 LEGEND_POINT => "\x{25CF}",
40 };
41  
42 my @GRID = qw(polygon circle none);
43 my @DEFAULTS = qw(marker line_style points point fill_opacity transform);
44  
45 field $initial_series :param(series) = [];
46 field $labels :param = [];
47 field $min :param = undef;
48 field $max :param = undef;
49 field $ticks :param = undef;
50 field $grid :param = 'polygon';
51 field $format :param = undef;
52 field $start_angle :param = 0;
53  
54 ADJUST :params ( :$marker = undef, :$line_style = undef, :$points = undef, :$point = undef, :$fill_opacity = undef, :$transform = undef ) {
55 my %given = ( marker => $marker, line_style => $line_style, points => $points, point => $point, fill_opacity => $fill_opacity, transform => $transform );
56 $self->_set_default( $_ => $given{$_} ) foreach grep { defined $given{$_} } @DEFAULTS;
57 $labels = $self->_checked_labels($labels);
58 $self->_check_ends( $self->_checked_end( min => $min ), $self->_checked_end( max => $max ) );
59 $self->_fail( 'ticks', 'a positive integer or undef', $ticks ) if defined $ticks && ( ref $ticks || $ticks !~ /\A[1-9][0-9]*\z/ );
60 one_of( $self, grid => $grid, @GRID );
61 $format = check_number_format( ref $self, 'format', $format );
62 $self->_fail( 'start_angle', 'a number of degrees', $start_angle ) unless defined number_of($start_angle);
63 croak ref($self) . ": series must be an array reference of series hashes" unless ref $initial_series eq 'ARRAY';
64 $self->add_series($_) foreach @$initial_series;
65 $initial_series = undef;
66 }
67  
68 method default_series_type () { return 'area' }
69 method series_types () { return qw(area line) }
70 method series_default_names () { return @DEFAULTS }
71 method check_series_type ( $name, $type ) { return }
72  
73 # A point given by label needs an axis of that name.
74 method check_series_points ( $name, $points ) {
75 $self->_check_axes_of( $labels, $name, $points );
76 return;
77 }
78  
79 method _check_axes_of ( $axes, $name, $points ) {
80 my %is_axis = map { $_ => 1 } @$axes;
81 foreach my $point (@$points) {
82 my $x = $point->[0] // next;
83 croak ref($self) . ": series '$name' has a value for '$x', which is not one of the labels" unless $is_axis{$x};
84 }
85 return;
86 }
87  
88 method _checked_labels ($value) {
89 croak ref($self) . ": labels must be an array reference of strings" unless ref $value eq 'ARRAY' && !grep { !defined || ref } @$value;
90 return [ map { "$_" } @$value ];
91 }
92  
93 method _checked_end ( $name, $value ) {
94 $self->_fail( $name, 'a number or undef', $value ) if defined $value && !defined number_of($value);
95 return $value;
96 }
97  
98 # Dies unless a min and a max, when both are given, leave room between
99 # them.
100 method _check_ends ( $low, $high ) {
101 return unless defined $low && defined $high;
102 croak ref($self) . ": min ($low) must be less than max ($high)" unless $low < $high;
103 return;
104 }
105  
106 # ---------------------------------------------------------------------
107 # Accessors
108 # ---------------------------------------------------------------------
109  
110 method _set ( $field_ref, $value ) {
111 $$field_ref = $value;
112 $self->mark_changed;
113 return $value;
114 }
115  
116 method min (@new) {
117 return $min unless @new;
118 $self->_check_ends( $self->_checked_end( min => $new[0] ), $max );
119 return $self->_set( \$min, $new[0] );
120 }
121  
122 method max (@new) {
123 return $max unless @new;
124 $self->_check_ends( $min, $self->_checked_end( max => $new[0] ) );
125 return $self->_set( \$max, $new[0] );
126 }
127  
128 method grid (@new) { return @new ? $self->_set( \$grid, one_of( $self, grid => $new[0], @GRID ) ) : $grid }
129 method format (@new) { return @new ? $self->_set( \$format, check_number_format( ref $self, 'format', $new[0] ) ) : $format }
130 method marker (@new) { return $self->series_default( marker => @new ) }
131 method line_style (@new) { return $self->series_default( line_style => @new ) }
132 method points (@new) { return $self->series_default( points => @new ) }
133 method point (@new) { return $self->series_default( point => @new ) }
134 method fill_opacity (@new) { return $self->series_default( fill_opacity => @new ) }
135  
136 # New labels must still give every value its axis.
137 method labels (@new) {
138 return [@$labels] unless @new;
139 my $axes = $self->_checked_labels( $new[0] );
140 $self->_check_axes_of( $axes, $_->name, $_->points ) foreach $self->all_series;
141 return [ $self->_set( \$labels, $axes )->@* ];
142 }
143  
144 method ticks (@new) {
145 return $ticks unless @new;
146 $self->_fail( 'ticks', 'a positive integer or undef', $new[0] ) if defined $new[0] && ( ref $new[0] || $new[0] !~ /\A[1-9][0-9]*\z/ );
147 return $self->_set( \$ticks, $new[0] );
148 }
149  
150 method start_angle (@new) {
151 return $start_angle unless @new;
152 $self->_fail( 'start_angle', 'a number of degrees', $new[0] ) unless defined number_of( $new[0] );
153 return $self->_set( \$start_angle, $new[0] + 0 );
154 }
155  
156 method transform (@new) {
157 $self->_set_default( transform => $new[0] ) if @new;
158 return;
159 }
160  
161 # ---------------------------------------------------------------------
162 # Data
163 # ---------------------------------------------------------------------
164  
165 # The values of each visible series by axis: a number per label, in
166 # the order of the labels ([ label, value ] points name their axis;
167 # check_series_points saw to it that the label is one).
168 method _prepared () {
169 my %axis_of = map { $labels->[$_] => $_ } 0 .. $#$labels;
170 my @prepared;
171 foreach my $series ( $self->visible_series ) {
172 my @values = (undef) x @$labels;
173 my $index = 0;
174 foreach my $point ( $series->points->@* ) {
175 my ( $x, $y ) = @$point;
176 my $axis = defined $x ? $axis_of{$x} : $index;
177 $values[$axis] = $y if $axis < @$labels;
178 $index++;
179 }
180 if ( my $steps = $self->series_option( $series, 'transform' ) ) {
181 ( undef, my $ys ) = apply_transforms( $steps, [ 0 .. $#values ], \@values );
182 @values = @$ys;
183 }
184 push @prepared, { series => $series, name => $series->name, values => \@values };
185 }
186 return @prepared;
187 }
188  
189 # ---------------------------------------------------------------------
190 # Drawing
191 # ---------------------------------------------------------------------
192  
193 method default_legend_position () {
194 return 'top';
195 }
196  
197 method legend_entries ($look) {
198 return map { { series => $_->name, label => $_->name, color => $_->color // $self->slot_color( $look, $_->slot ), symbol => $_->type eq 'line' ? 'line' : 'fill' } } $self->visible_series;
199 }
200  
201 method draw_plot ( $surface, $x, $y, $width, $height, $look ) {
202 my $count = @$labels;
203 return if $count < 3;
204 my @prepared = $self->_prepared;
205 my $measure = sub ($text) { Term::Fabulous::Chart::Surface->text_columns($text) };
206  
207 # Room for the axis labels around the circle: their width at the
208 # sides, a row above and below.
209 my $label_columns = List::Util::max( map { $measure->($_) } @$labels ) + 1;
210 my $circle = circle_frame( $label_columns, 1, $width - 2 * $label_columns, $height - 2 );
211 return if $circle->{radius} < 2;
212 my $radius = $circle->{radius};
213 my $start = $start_angle / 360;
214  
215 my @all = grep { defined } map { $_->{values}->@* } @prepared;
216 my $scale = Term::Fabulous::Chart::Scale::Linear->fit(
217 extent => @all ? [ List::Util::min(@all), List::Util::max(@all) ] : undef,
218 cells => List::Util::max( 2, floor( $radius / 2 ) + 1 ),
219 zero => 1,
220 align => 0,
221 integer => !grep( { $_ != int } @all ) ? 1 : 0,
222 format => $format,
223 ( defined $min ? ( min => $min ) : () ),
224 ( defined $max ? ( max => $max ) : () ),
225 ( defined $ticks ? ( ticks => $ticks ) : () ),
226 );
227 my $distance_of = sub ($value) { List::Util::max( 0, $scale->position($value) ) * $radius };
228 my $vertex = sub ( $axis, $distance ) { [ point_at( $circle, $distance, $axis / $count, $start ) ] };
229  
230 # The web: rings at the ticks and a spoke to every axis.
231 my $web = Term::Fabulous::Chart::Raster->new( marker => Term::Fabulous::Chart::Marker->named('braille'), columns => $width, rows => $height );
232 if ( $grid ne 'none' ) {
233 foreach my $tick ( $scale->ticks ) {
234 my $distance = $distance_of->( $tick->{value} );
235 next unless $distance > 0;
236 my @ring
237 = $grid eq 'circle'
238 ? map { [ point_at( $circle, $distance, $_ / List::Util::max( 24, floor( TAU * $distance * 2 ) ), $start ) ] } 0 .. List::Util::max( 24, floor( TAU * $distance * 2 ) )
239 : map { $vertex->( $_ % $count, $distance ) } 0 .. $count;
240 _polyline( $web, \@ring, $look->{grid}, undef );
241 }
242 _polyline( $web, [ $vertex->( $_, 0 ), $vertex->( $_, $radius ) ], $look->{grid}, undef ) foreach 0 .. $count - 1;
243 }
244  
245 # The series: translucent fills, the web over them (its dots keep a
246 # fill's color as their background), the outlines on top.
247 my @order = sort { $self->is_emphasized( $look, $a->{name} ) <=> $self->is_emphasized( $look, $b->{name} ) } @prepared;
248 my %fills;
249 my @fill_order;
250 my $lines = Term::Fabulous::Chart::Raster->new( marker => Term::Fabulous::Chart::Marker->named('braille'), columns => $width, rows => $height );
251 my @points;
252 foreach my $entry (@order) {
253 my $series = $entry->{series};
254 my $color = $self->shown_color( $look, $entry->{name}, $series->color // $self->slot_color( $look, $series->slot ) );
255 my @targets = map { $self->register_target( series => $entry->{name}, index => $_, label => $labels->[$_], value => $entry->{values}[$_] ) } 0 .. $count - 1;
256 my @corners = map { $vertex->( $_, $distance_of->( $entry->{values}[$_] // $scale->min ) ) } 0 .. $count - 1;
257  
258 # Between two corners the nearer one owns the fill and the
259 # outline, so the pointer reports the nearest axis.
260 my @midpoints = map { _midpoint( $corners[$_], $corners[ ( $_ + 1 ) % $count ] ) } 0 .. $count - 1;
261 if ( $series->type eq 'area' ) {
262 my $marker = $self->series_option( $series, 'marker' ) // 'quadrant';
263 my $fill = $fills{$marker} //= do {
264 push @fill_order, $marker;
265 Term::Fabulous::Chart::Raster->new( marker => Term::Fabulous::Chart::Marker->named($marker), columns => $width, rows => $height );
266 };
267 my ( $sx, $sy ) = ( $fill->marker->columns, $fill->marker->rows );
268 my $opacity = ( $self->series_option( $series, 'fill_opacity' ) // FILL_OPACITY ) * $series->color_opacity;
269 my $center = [ $circle->{center_x}, $circle->{center_y} ];
270 foreach my $axis ( 0 .. $count - 1 ) {
271 my @sector = ( $center, $midpoints[ ( $axis - 1 ) % $count ], $corners[$axis], $midpoints[$axis] );
272 $fill->fill_polygon( [ map { [ $_->[0] * $sx, $_->[1] * $sy ] } @sector ], $color, $targets[$axis], $opacity, $look->{base} );
273 }
274 }
275 $lines->start_pattern( $series->dash_pattern( $self->series_option( $series, 'line_style' ) // 'solid' ) );
276 foreach my $axis ( 0 .. $count - 1 ) {
277 my ( $from, $middle, $to ) = ( $corners[$axis], $midpoints[$axis], $corners[ ( $axis + 1 ) % $count ] );
278 $lines->line( $from->[0] * 2, $from->[1] * 4, $middle->[0] * 2, $middle->[1] * 4, $color, $targets[$axis] );
279 $lines->line( $middle->[0] * 2, $middle->[1] * 4, $to->[0] * 2, $to->[1] * 4, $color, $targets[ ( $axis + 1 ) % $count ] );
280 }
281 $lines->start_pattern(undef);
282 if ( $self->series_option( $series, 'points' ) ) {
283 my $glyph = $self->series_option( $series, 'point' ) // POINT;
284 my @valued = grep { defined $entry->{values}[$_] } 0 .. $count - 1;
285 if ( $glyph eq DOT_POINT || $glyph eq SQUARE_POINT ) {
286 _raster_point( $lines, $glyph, $corners[$_], $color, $targets[$_] ) foreach @valued;
287 }
288 else {
289 push @points, map { [ floor( $corners[$_][0] ), floor( $corners[$_][1] ), $glyph, $color, $targets[$_] ] } @valued;
290 }
291 }
292 }
293 $surface->composite( $fills{$_}, 'fill', $x, $y ) foreach @fill_order;
294 $surface->composite( $web, 'stroke', $x, $y );
295 $surface->composite( $lines, 'stroke', $x, $y );
296 foreach my $point (@points) {
297 my ( $column, $row, $glyph, $color, $owner ) = @$point;
298 $surface->put( $x + $column, $y + $row, $glyph, $color );
299 $surface->set_owner( $x + $column, $y + $row, 'stroke', $owner );
300 }
301  
302 # The axis labels around the web, and the values of the rings along
303 # the first spoke: right of it when it is upright, above it when it
304 # lies flat; never over an axis label.
305 my @taken; # [ row, first column, last column ] of each axis label
306 foreach my $axis ( 0 .. $count - 1 ) {
307 my $text = $labels->[$axis];
308 my ( $at_x, $at_y ) = point_at( $circle, $radius + 1, $axis / $count, $start );
309 my $dx = $at_x - $circle->{center_x};
310 my $width_of_text = $measure->($text);
311 my $column
312 = abs($dx) < 1 ? floor( $at_x - $width_of_text / 2 + 0.5 )
313 : $dx > 0 ? ceil($at_x)
314 : floor($at_x) - $width_of_text + 1;
315 $column = List::Util::max( 0, $column );
316 $surface->text( $x + $column, $y + floor($at_y), $text, $look->{text}, max => $width - $column );
317 push @taken, [ floor($at_y), $column, $column + $width_of_text - 1 ];
318 }
319 my ( $end_x, $end_y ) = point_at( $circle, $radius, 0, $start );
320 my $spoke_is_flat = abs( $end_x - $circle->{center_x} ) > abs( $end_y - $circle->{center_y} ) * CELL_ASPECT;
321  
322 # A ring label needs a free column around it; axis labels and the
323 # ring labels placed before it take their cells.
324 foreach my $tick ( reverse $scale->ticks ) {
325 my $distance = $distance_of->( $tick->{value} );
326 next unless $distance > 0;
327 my ( $at_x, $at_y ) = point_at( $circle, $distance, 0, $start );
328 my $width_of_text = $measure->( $tick->{label} );
329 my ( $column, $row ) = $spoke_is_flat ? ( floor( $at_x - $width_of_text / 2 + 0.5 ), floor($at_y) - 1 ) : ( floor($at_x) + 1, floor($at_y) );
330 next if $row < 0 || $column < 0;
331 my $last = $column + $width_of_text - 1;
332 next if grep { $_->[0] == $row && $column <= $_->[2] + 1 && $last >= $_->[1] - 1 } @taken;
333 $surface->text( $x + $column, $y + $row, $tick->{label}, $look->{label}, max => $width - $column );
334 push @taken, [ $row, $column, $last ];
335 }
336 return;
337 }
338  
339 # A dot or square point drawn into a raster: the subpixel at the
340 # corner, or the two by two around it.
341 sub _raster_point ( $raster, $glyph, $corner, $color, $owner ) {
342 my ( $sx, $sy ) = ( $raster->marker->columns, $raster->marker->rows );
343 if ( $glyph eq DOT_POINT ) {
344 $raster->set( floor( $corner->[0] * $sx ), floor( $corner->[1] * $sy ), $color, $owner );
345 return;
346 }
347 my ( $left, $top ) = ( floor( $corner->[0] * $sx - 0.5 ), floor( $corner->[1] * $sy - 0.5 ) );
348 $raster->set( $left + $_ % 2, $top + int( $_ / 2 ), $color, $owner ) foreach 0 .. 3;
349 return;
350 }
351  
352 sub _midpoint ( $from, $to ) {
353 return [ ( $from->[0] + $to->[0] ) / 2, ( $from->[1] + $to->[1] ) / 2 ];
354 }
355  
356 sub _polyline ( $raster, $points, $color, $owner ) {
357 foreach my $index ( 1 .. $#$points ) {
358 my ( $from, $to ) = @$points[ $index - 1, $index ];
359 $raster->line( $from->[0] * 2, $from->[1] * 4, $to->[0] * 2, $to->[1] * 4, $color, $owner );
360 }
361 return;
362 }
363  
364 # ---------------------------------------------------------------------
365 # KDL
366 # ---------------------------------------------------------------------
367  
368 method layout_properties :common () {
369 return (
370 $class->SUPER::layout_properties,
371 min => 'scalar',
372 max => 'scalar',
373 ticks => 'scalar',
374 grid => 'scalar',
375 format => 'scalar',
376 start_angle => 'scalar',
377 marker => 'scalar',
378 line_style => 'scalar',
379 points => 'boolean',
380 point => 'scalar',
381 fill_opacity => 'scalar',
382 labels => \&_parse_labels,
383 series => \&_parse_series,
384 );
385 }
386  
387 method apply_layout_settings :override (@settings) {
388 my @ordered = map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { [ $_->[0] eq 'series' ? 1 : 0, $_ ] } @settings;
389 return $self->SUPER::apply_layout_settings(@ordered);
390 }
391  
392 method _parse_labels ($kid) {
393 my @labels = map { $_->as_perl } $kid->args->@*;
394 croak ref($self) . ": layout property 'labels' takes one or more labels" unless @labels && !$kid->props->@* && !$kid->children->@*;
395 $self->labels( \@labels );
396 return;
397 }
398  
399 # series "Alice" type="line" color="#3987e5" { data 4 5 3 4 2 }
400 # series "Bob" { point "Speed" 4; point "Power" 3 }
401 method _parse_series ($kid) {
402 my @args = map { $_->as_perl } $kid->args->@*;
403 croak ref($self) . ": layout property 'series' needs the series name as its one argument" unless @args == 1 && defined $args[0] && !ref $args[0];
404 my %spec = ( name => "$args[0]", map { $_->[0] => $_->[1]->as_perl } $kid->props->@* );
405 my @data;
406 foreach my $child ( $kid->children->@* ) {
407 my $name = $child->name;
408 my @values = map { $_->as_perl } $child->args->@*;
409 croak ref($self) . ": a series node holds 'data' and 'point' nodes, got '$name'" unless $name eq 'data' || $name eq 'point';
410 croak ref($self) . ": '$name' in series '$args[0]' takes no properties or children" if $child->props->@* || $child->children->@*;
411 if ( $name eq 'point' ) {
412 croak ref($self) . ": 'point' in series '$args[0]' takes a label and a value" unless @values == 2 && defined $values[0] && !ref $values[0];
413 push @data, [ "$values[0]", $values[1] ];
414 }
415 else {
416 push @data, @values;
417 }
418 }
419 $self->add_series( %spec, data => \@data );
420 return;
421 }
422 }
423  
424 1;
425  
426 __END__