blib/lib/Matplotlib/Simple/Matplotlib.pm

filter: Statementstmt 91.9% 2164 / 2353 Branchbran 83.7% 770 / 920 Conditioncond 80.7% 349 / 432 MC/DCmcdc 64.3% 164 / 255 Subroutinesub 100% 55 / 55 Podpod 0.0% 0 / 35 totaltotal 86.4% 3502 / 4050 CC 724 SCAR 40.6
CC
724
Cov
89%
barplot_helper
110.2
scatter_helper
109.8
plot_helper
95.6
CRAP 58.0
« blib/lib/Matplotlib/Simple.pm ↑ Summary blib/lib/Matplotlib/Simple/Gnuplot.pm »
1 24 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 24 ▶use feature 'say';
Subroutine BEGIN: called CC=1 SCAR=0.0
3 24 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 package Matplotlib::Simple::Matplotlib;
6 # The matplotlib engine, Matplotlib::Simple's default: it writes plt's figure as a Python
7 # 3 script that draws it with matplotlib, and runs that script. Everything
8 # here was in Matplotlib::Simple itself until 0.33, when it was split out so
9 # that other engines could draw the same figures; Matplotlib::Simple checks the
10 # arguments, and calls render() below once they are good.
11 #
12 # The helpers keep checking their own keywords, against the same lists Matplotlib::Simple
13 # checks them with, which are shared below rather than copied.
14 24 require 5.010;
15 24 our $VERSION = 0.3345;
16 24 ▶use Scalar::Util 'looks_like_number';
Subroutine BEGIN: called CC=1 SCAR=0.0
17 24 ▶use List::Util qw(max sum min);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 24 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 24 ▶use File::Temp;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 24 ▶use DDP { output => 'STDOUT', array_max => 10, show_memsize => 1 };
Subroutine BEGIN: called CC=1 SCAR=0.0
21 24 ▶use Capture::Tiny 'capture';
Subroutine BEGIN: called CC=1 SCAR=0.0
22 24 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 24 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 24 ▶use Encode ();
Subroutine BEGIN: called CC=1 SCAR=0.0
25 # Loaded first, even when this module is the one asked for, so that the names
26 # below have something to alias. Matplotlib::Simple requires this module at its end, and
27 # must find it already in %INC, or it compiles it a second time and dies on
28 # "Subroutine py_list redefined". require puts it there, but "perl -c" on this
29 # file does not, so it is put there here.
30 24 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=7.2
31 24 ▶ $INC{'Matplotlib/Simple/Matplotlib.pm'} //= __FILE__;
Condition50%1/2
$INC{"Matplotlib/Simple/Matplotlib.pm"} //= __FILE__
l!l
240
MC/DC0%0/1
$INC{"Matplotlib/Simple/Matplotlib.pm"} //= __FILE__
$INC{"Matplotlib/Simple/Matplotlib.pm"}
Truth table50%1/2
A
A= $INC{"Matplotlib/Simple/Matplotlib.pm"}
Aresult
11
00
32 24 require Matplotlib::Simple;
33 }
34 # The parts of Matplotlib::Simple the helpers use under their old names: the checks that
35 # do not depend on the engine, and the keyword lists. Aliases, not copies, so
36 # a list Matplotlib::Simple changes is the list checked here.
37 24 ▶BEGIN {
Subroutine BEGIN: called CC=4 SCAR=13.9
38 24 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
39 24 *{$_} = \&{"Matplotlib::Simple::$_"} foreach qw(bad_keyword_error bar_series bin_counts bool_option cb_limits
40 check_key_order check_numbers check_plot_type check_scatter_lengths creator_note
41 check_scatter_values check_twinx_args check_wide_runs decoded_data
42 decoded_text finite_values is_finite is_nan logscale_axes nonfinite_name
43 program_from_env py_str run_script script_handle table_cells);
44 24 *{$_} = \@{"Matplotlib::Simple::$_"} foreach qw(arg ax_methods cb_arg fig_methods plt_methods);
45 24 *{$_} = \%{"Matplotlib::Simple::$_"} foreach qw(opt opt_key_of_type);
46 }
47 24 our ( @arg, @ax_methods, @cb_arg, @fig_methods, @plt_methods, %opt, %opt_key_of_type );
48 # Every plot type and keyword Matplotlib::Simple accepts is drawn here, so check_engine
49 # has nothing to refuse; the other engines list what they draw instead.
50 24 our $draws_everything = 1;
51 179 ▶sub py_list {
Subroutine py_list: called CC=1 SCAR=0.0
Pod undocumented
52 # The contents of a Python sequence literal: every item rendered by py_str
53 # and joined with commas, so the caller wraps it in the [] or () it needs.
54 #
55 # The sites that take this are the ones that write user data -- data keys,
56 # tick labels, set members -- into a list. Written by hand as
57 # '["' . join('","', @keys) . '"]' they broke on a key holding a double
58 # quote (a SyntaxError) and, worse, silently on one holding a backslash:
59 # a "$\alpha$" key reached matplotlib as "$<BEL>lpha$", because Python read
60 # the "\a" of a double-quoted literal as an escape.
61 179 return join( ',', map { py_str($_) } @_ );
62 }
63 10271 ▶sub py_num {
Subroutine py_num: called CC=4 SCAR=14.0
Pod undocumented
64 # A value that passed looks_like_number, as a Python numeric literal.
65 #
66 # looks_like_number accepts "nan", "inf", "Infinity" and a Perl NaN, and
67 # each was written into the script as Perl stringifies it: "y = [1,NaN,3]"
68 # died as "NameError: name 'NaN' is not defined". It also accepts
69 # "0 but true", which is not Python either. A
70 # finite value written in Python's own float syntax goes through as given,
71 # so that no digits are lost to Perl's 15-digit stringification.
72 #
73 # Except for the leading zeros of a whole number, which are dropped: Python 3
74 # refuses "007" as "leading zeros in decimal integer literals are not
75 # permitted", and a column read from a file can hold such values. A float
76 # such as "00.5" or "007e3" is legal Python and is left alone.
77 10271 my ($n) = @_;
78 10271 my $nonfinite = nonfinite_name($n);
79 10271 ▶ return "float('$nonfinite')" if defined $nonfinite;
Branch: 1 branch
BranchTrueFalseTotal
if defined $nonfinite 7 10264 10271
80 10264 ▶ if ( $n =~ m/^\s*([-+]?)0*(\d+)\s*$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n =~ /^\s*([-+]?)0*(\d+)\s*$/) 7922 2342 10264
81 7922 return "$1$2";
82 }
83 2342 ▶ return $n if $n =~ m/^\s*[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $n =~ /^\s*[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?\s*$/ 2342 0 2342
84 0 return 0 + $n;
85 }
86 1023 ▶sub py_nums {
Subroutine py_nums: called CC=1 SCAR=0.0
Pod undocumented
87 # py_num of each value, joined with commas, for the caller to bracket.
88 1023 return join( ',', map { py_num($_) } @_ );
89 }
90 53 ▶sub norm_args {
Subroutine norm_args: called CC=24 SCAR=31.8
Pod undocumented
91 # The keyword arguments of a drawing call that set its color scale,
92 # each led by ", ": "vmin" and "vmax", or with "log" a LogNorm holding
93 # them, since matplotlib refuses vmin and vmax beside a norm.
94 #
95 # args: lo, hi => the ends of the scale, either undef to take it from
96 # "values", or from matplotlib if there are none
97 # values => array ref, optional: the values being colored
98 # rows => array ref of array refs, optional, in place of
99 # "values": the values being colored, a row at a time
100 # log => Perl true for a log scale
101 # fh, sub => the script, and the helper, for the import and errors
102 # A log scale cannot start at 0 or below, so its default bottom is the
103 # smallest value above 0, as LogNorm would choose for itself.
104 #
105 # The range is kept a row at a time, and looked for only where an end is
106 # not given. imshow passed its image flattened into one list, which was
107 # copied twice more here: with the rest of its work, a 1500 x 1500 image
108 # took 956 MB at its peak.
109 53 my ($args) = @_;
110 53 my ( $lo, $hi ) = @{$args}{qw(lo hi)};
111 53 my ( $min, $min_above_0, $max );
112 53 ▶ if ( ( not defined $lo ) || ( not defined $hi ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $lo and defined $hi) 40 13 53
Condition100%3/3
defined $lo and defined $hi
!ll&&!rl&&r
37313
MC/DC100%2/2
defined $lo and defined $hi
defined $lo defined $hi
Truth table100%3/3
A and B
A= defined $loB= defined $hi
ABresult
0X0
100
111
113 40 ▶ foreach my $row ( defined $args->{rows} ? @{ $args->{rows} } : ( $args->{values} // [] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'rows'} ? : 30 10 40
Condition50%1/2
$args->{"values"} // []
l!l
100
MC/DC0%0/1
$args->{"values"} // []
$args->{"values"}
Truth table50%1/2
A
A= $args->{"values"}
Aresult
11
00
114 132 my @values = finite_values( @{$row} );
115 132 ▶ next if scalar @values == 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @values == 0 7 125 132
116 125 my ( $row_min, $row_max ) = ( min(@values), max(@values) );
117 125 ▶ $min = $row_min if ( not defined $min ) || ( $row_min < $min );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $min or $row_min < $min 39 86 125
Condition66%2/3
not defined $min or $row_min < $min
l!l&&r!l&&!r
39086
MC/DC50%1/2
not defined $min or $row_min < $min
not defined $min $row_min < $min
Truth table66%2/3
not(A) or B
A= not defined $minB= $row_min < $min
ABresult
1X1
011
000
118 125 ▶ $max = $row_max if ( not defined $max ) || ( $row_max > $max );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $max or $row_max > $max 119 6 125
Condition100%3/3
not defined $max or $row_max > $max
l!l&&r!l&&!r
39806
MC/DC100%2/2
not defined $max or $row_max > $max
not defined $max $row_max > $max
Truth table100%3/3
not(A) or B
A= not defined $maxB= $row_max > $max
ABresult
1X1
011
000
119 125 ▶ next unless $args->{log};
Branch: 1 branch
BranchTrueFalseTotal
unless $args->{"log"} 113 12 125
120 12 my $row_min_above_0 = min( grep { $_ > 0 } @values );
121 12 ▶ next unless defined $row_min_above_0;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_min_above_0 1 11 12
122 11 ▶ $min_above_0 = $row_min_above_0 if ( not defined $min_above_0 ) || ( $row_min_above_0 < $min_above_0 );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $min_above_0 or $row_min_above_0 < $min_above_0 8 3 11
Condition100%3/3
not defined $min_above_0 or $row_min_above_0 < $min_above_0
l!l&&r!l&&!r
623
MC/DC100%2/2
not defined $min_above_0 or $row_min_above_0 < $min_above_0
not defined $min_above_0 $row_min_above_0 < $min_above_0
Truth table100%3/3
not(A) or B
A= not defined $min_above_0B= $row_min_above_0 < $min_above_0
ABresult
1X1
011
000
123 }
124 }
125 53 ▶ if ( $args->{log} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{'log'}) { } 9 44 53
126 9 ▶ $lo = $lo // $min_above_0;
Condition100%3/3
$lo // $min_above_0
l!l&&r!l&&!r
261
MC/DC100%2/2
$lo // $min_above_0
$lo $min_above_0
Truth table100%3/3
A // B
A= $loB= $min_above_0
ABresult
1X1
011
000
127 9 ▶ if ( not defined $lo ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $lo) 1 8 9
128 1 die "\"cb_logscale\" needs a color value above 0 to start the scale at, or a \"vmin\" or \"cb_min\" above 0, and $args->{sub} has neither";
129 }
130 8 ▶ if ( $lo <= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lo <= 0) 0 8 8
131 0 die "\"cb_logscale\" cannot start at $lo in $args->{sub}: a log scale needs a minimum above 0";
132 }
133 } else {
134 44 ▶ $lo = $lo // $min;
Condition100%3/3
$lo // $min
l!l&&r!l&&!r
14291
MC/DC100%2/2
$lo // $min
$lo $min
Truth table100%3/3
A // B
A= $loB= $min
ABresult
1X1
011
000
135 }
136 52 ▶ $hi = $hi // $max;
Condition100%3/3
$hi // $max
l!l&&r!l&&!r
16351
MC/DC100%2/2
$hi // $max
$hi $max
Truth table100%3/3
A // B
A= $hiB= $max
ABresult
1X1
011
000
137 52 my @kw;
138 52 ▶ push @kw, 'vmin = ' . py_num($lo) if defined $lo;
Branch: 1 branch
BranchTrueFalseTotal
if defined $lo 51 1 52
139 52 ▶ push @kw, 'vmax = ' . py_num($hi) if defined $hi;
Branch: 1 branch
BranchTrueFalseTotal
if defined $hi 51 1 52
140 52 ▶ if ( $args->{log} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"log"}) 8 44 52
141 8 say { $args->{fh} } 'from matplotlib.colors import LogNorm';
142 8 return ', norm = LogNorm(' . join( ', ', @kw ) . ')';
143 }
144 44 return join( '', map { ", $_" } @kw );
145 }
146 747 ▶sub write_data {
Subroutine write_data: called CC=3 SCAR=11.3
Pod undocumented
147 747 my ($args) = @_;
148 747 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1];
149 747 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 747 747
150 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => ... })\"";
151 }
152 747 my @reqd_args = (
153 'data', # args to original function (scalar, hashref, or arrayref)
154 'fh', # file handle
155 'name' # python variable name
156 );
157 747 my @undef_args = grep { not defined $args->{$_} } @reqd_args;
158 747 ▶ if (scalar @undef_args > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 747 747
159 0 p @undef_args;
160 0 die "the above args are required for $current_sub, but weren't defined";
161 }
162 # 1. Create the JSON Encoder; allow_nonref: allows scalars (strings/numbers) to be encoded
163 747 my $json_encoder = JSON::MaybeXS->new->utf8->allow_nonref;
164 # 2. Serialize Perl Data -> JSON String; Passing data directly. JSON::MaybeXS handles refs + scalars automatically.
165 747 my $json_string = $json_encoder->encode( decoded_data( $args->{data} ) );
166 # 3. Base64 Encode the JSON String, not the reference
167 747 my $b64_data = encode_base64($json_string, '');
168 # Assign the b64 string to a temp python variable. The JSON is let go
169 # first, and the line printed in pieces rather than interpolated, which
170 # made a third copy: for a 1500 x 1500 imshow that took the peak from
171 # 299 MB to 247 MB.
172 747 undef $json_string;
173 747 print {$args->{fh}} "$args->{name}_b64 = '", $b64_data, "'\n";
174 # Decode b64 -> bytes -> utf8 string -> json load -> python object
175 747 say {$args->{fh}} "$args->{name} = json.loads(base64.b64decode($args->{name}_b64).decode('utf-8'))";
176 }
177 # The twin axis of each axes that has one, by the axes' python name: "ax0" =>
178 # "twinx_ax0". plot_helper makes one twin per axes and draws every twinned line
179 # on it, and plot_args reads (and deletes) the entry when it writes that axes'
180 # legend, so that the legend holds the twin's lines as well. plt empties it
181 # before it writes a figure, so a call that died part way leaves nothing behind.
182 24 my %twin_axes;
183 # The text of every scatter "tooltips" label in the figure, numbered by its
184 # place here. scatter_helper draws a labelled point with the url
185 # "#matplotlib-simple-tooltip-<n>", and once the SVG is written plt turns each
186 # such link into a group whose <title> is the text, which a browser shows on
187 # hovering. plt empties it, and sets $tooltips_drawn, before it writes a figure.
188 my @tooltip_text;
189 24 my $tooltips_drawn = 0; # 1 = output_file is an SVG, which the tooltips are written into; 0 = they are checked and left out
190 24 my $tooltip_url = '#matplotlib-simple-tooltip-';
191 # The methods whose argument is usually bare text, which quote_text quotes.
192 # "supxlabel" and "supylabel" are figure methods, which are otherwise written
193 # as given: until 0.32 they were not here, so "supxlabel => 'Time'" wrote
194 # fig.supxlabel(Time), a NameError, where "suptitle => 'Time'" was quoted.
195 24 my @text_methods = ( 'set_title', 'set_xlabel', 'set_ylabel', 'suptitle', 'supxlabel', 'supylabel', 'xlabel', 'ylabel', 'title' );
196 327 ▶sub quote_text {
Subroutine quote_text: called CC=4 SCAR=13.9
Pod undocumented
197 # A title or axis label as python: quoted, unless it is already python.
198 #
199 # Text holding a quote or a comma may be python of the caller's own --
200 # "'Counts, by book'", "'title', fontsize = 20", 'r"$\it{anno}$"' or
201 # 'label = "x", loc = "left"' -- and is left as written when it opens as
202 # python does: with a string literal, which may carry a prefix such as r or
203 # f, or with a keyword argument. Anything else is prose and is quoted. All
204 # such text used to be left as written, so "Bob's data" became
205 # set_xlabel(Bob's data), a SyntaxError, and "" became set_title(), a
206 # TypeError for want of an argument.
207 #
208 # The literal has to close, and be all of the text or be followed by a
209 # comma and the next argument. An opening quote was enough until 0.32, so
210 # "'Tis the season" became set_title('Tis the season) and '"A" vs "B"'
211 # became set_title("A" vs "B"), both SyntaxErrors.
212 327 my ($text) = @_;
213 327 $text = decoded_text($text);
214 # py_str, not "'$text'": a backslash went through unescaped, so a
215 # mathtext '$\alpha$' reached matplotlib with a bell character in it.
216 327 ▶ return py_str($text) if $text =~ m/^([^\"\',]+)$/;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /^([^\"\',]+)$/ 45 282 327
217 282 ▶ return $text if $text =~ m/^\s*[rRbBuUfF]{0,2}(['"])(?:\\.|(?!\1)[^\\])*\1\s*(?:,|$)/s;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /^\s*[rRbBuUfF]{0,2}(['"])(?:\\.|(?!\1)[^\\])*\1\s*(?:,|$)/s 272 10 282
218 10 ▶ return $text if $text =~ m/^\s*[A-Za-z_]\w*\s*=[^=]/;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /^\s*[A-Za-z_]\w*\s*=[^=]/ 1 9 10
219 9 return py_str($text);
220 }
221 166 ▶sub default_axis_labels {
Subroutine default_axis_labels: called CC=4 SCAR=13.9
Pod undocumented
222 # "xlabel" and "ylabel" from the names of the two data keys of hexbin,
223 # hist2d or scatter, for each axis the caller labelled in neither form.
224 #
225 # Only "xlabel" was looked at, so "set_xlabel => 'Custom'" got an "xlabel"
226 # beside it, and plt's rename of "xlabel" to "set_xlabel" then wrote the
227 # key's name over the caller's label. frame_to_data's $label_axis already
228 # looked at both.
229 166 my ( $plot, $x_key, $y_key ) = @_;
230 166 foreach my $label ( [ 'xlabel', $x_key ], [ 'ylabel', $y_key ] ) {
231 332 my ( $axis, $key ) = @{$label};
232 332 ▶ next if ( defined $plot->{$axis} ) || ( defined $plot->{"set_$axis"} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $plot->{$axis} or defined $$plot{"set_$axis"} 49 283 332
Condition100%3/3
defined $plot->{$axis} or defined $$plot{"set_$axis"}
l!l&&r!l&&!r
418283
MC/DC100%2/2
defined $plot->{$axis} or defined $$plot{"set_$axis"}
defined $plot->{$axis} defined $$plot{"set_$axis"}
Truth table100%3/3
A or B
A= defined $plot->{$axis}B= defined $$plot{"set_$axis"}
ABresult
1X1
011
000
233 283 $plot->{$axis} = py_str($key);
234 }
235 }
236 541 ▶sub plot_args { # this is a helper function to other matplotlib subroutines
Subroutine plot_args: called CC=29 SCAR=34.2
Pod undocumented
237 541 my ($args) = @_;
238 541 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1];
239 541 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 541 541
240 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
241 }
242 541 my @reqd_args = (
243 'ax', # ax1, ax2, etc. when there are multiple plots
244 'fh', # e.g. $py, $fh, which will be passed by the subroutine
245 'args', # args to original function
246 );
247 541 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
248 541 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 541 541
249 0 p @undef_args;
250 0 die 'the above args are necessary, but were not defined.';
251 }
252 # "emit_plt_fig" and "no_legend" are this sub's own arguments, not plot
253 # options; see below.
254 541 my @defined_args = ( @reqd_args, 'emit_plt_fig', 'no_legend', @ax_methods, @fig_methods, @plt_methods, @arg, @cb_arg );
255 my @bad_args = grep {
256 2069 my $key = $_;
257 2069 not grep { $_ eq $key } @defined_args
258 541 } keys %{$args};
259 541 ▶ if ( scalar @bad_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_args > 0) 0 541 541
260 0 bad_keyword_error({
261 bad => \@bad_args,
262 accepted => \@defined_args,
263 sub => $current_sub
264 });
265 }
266 541 ▶ $args->{ax} = $args->{ax} // 'ax';
Condition50%1/2
$args->{"ax"} // "ax"
l!l
5410
MC/DC0%0/1
$args->{"ax"} // "ax"
$args->{"ax"}
Truth table50%1/2
A
A= $args->{"ax"}
Aresult
11
00
267 # A copy, because the quoting below writes back into it: the hash can be
268 # the caller's own ("twinx_args" hands one in untouched), and a second plot
269 # drawn from it found its titles already wrapped in quotes.
270 541 $args->{args} = { %{ $args->{args} } };
271 # An array is one call per element, as for every other method below, so
272 # each element is quoted. The array itself used to be, and
273 # "set_title => ['First', 'Second']" wrote set_title('ARRAY(0x5b95...)').
274 541 foreach my $item ( grep { defined $args->{args}{$_} } @text_methods ) {
275 315 my $text = $args->{args}{$item};
276 315 ▶ $args->{args}{$item} = ( ref $text eq 'ARRAY' ) ? [ map { quote_text($_) } @{$text} ] : ( ref $text ) ? $text : quote_text($text);
Branch: 2 branches
BranchTrueFalseTotal
ref $text eq 'ARRAY' ? : 2 313 315
ref $text ? : 0 313 313
277 }
278 # Whether the "fig." and "plt." methods in this hash are written here as
279 # well as the "ax." ones. 1 (the default) is what a subplot needs, since
280 # nothing else writes them for it; plt() passes 0 for a single plot, whose
281 # hash it walks itself afterwards. Both passes used to run over that one
282 # hash, so every figure-wide and pyplot-wide option was written twice, and
283 # the second pass ran print_type over text the first had already quoted:
284 # suptitle => "'Counts, by book'" left plt.suptitle(''Counts, by book'')
285 # in the script, a SyntaxError.
286 541 ▶ $args->{emit_plt_fig} = $args->{emit_plt_fig} // 1;
Condition100%2/2
$args->{"emit_plt_fig"} // 1
l!l
439102
MC/DC100%1/1
$args->{"emit_plt_fig"} // 1
$args->{"emit_plt_fig"}
Truth table100%2/2
A
A= $args->{"emit_plt_fig"}
Aresult
11
00
287 541 my @obj = ( $args->{ax} );
288 541 my @args = ( \@ax_methods );
289 541 ▶ if ( $args->{emit_plt_fig} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"emit_plt_fig"}) 102 439 541
290 102 push @obj, 'fig', 'plt';
291 102 push @args, \@fig_methods, \@plt_methods;
292 }
293 541 foreach my $i ( 0 .. $#args ) {
294 745 ▶ my @methods = grep { defined $args->{args}{$_} && ( $_ ne 'legend' ) } @{ $args[$i] }; # "legend" is written below, and only when something has a label
Condition66%2/3
defined $args->{'args'}{$_} && $_ ne 'legend'
!ll&&!rl&&r
738170320
MC/DC50%1/2
defined $args->{'args'}{$_} && $_ ne 'legend'
defined $args->{'args'}{$_} $_ ne 'legend'
Truth table66%2/3
A && B
A= defined $args->{'args'}{$_}B= $_ ne 'legend'
ABresult
0X0
100
111
295 # pyplot's functions act on the current axes, which after plt.subplots is
296 # the last subplot and after a twinx() is the twin, so a subplot's own
297 # "ylim" or "axhline" was drawn on some other subplot. This one is made
298 # current first.
299 745 ▶ if ( ( $obj[$i] eq 'plt' ) && ( grep { $_ ne 'show' } @methods ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj[$i] eq "plt" and grep {$_ ne "show";} @methods) 6 739 745
Condition100%3/3
$obj[$i] eq "plt" and grep {$_ ne "show";} @methods
!ll&&!rl&&r
643966
MC/DC100%2/2
$obj[$i] eq "plt" and grep {$_ ne "show";} @methods
$obj[$i] eq "plt" grep {$_ ne "show";} @methods
Truth table100%3/3
A and B
A= $obj[$i] eq "plt"B= grep {$_ ne "show";} @methods
ABresult
0X0
100
111
300 6 say {$args->{fh}} "plt.sca($args->{ax}) #line" . __LINE__;
301 }
302 # Only the pyplot calls are quoted, as plt() quotes a single plot's; the
303 # axes and figure methods are written as given in both.
304 745 ▶ my $arg_text = ( $obj[$i] eq 'plt' ) ? \&pyplot_arg : sub { $_[0] };
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$obj[$i] eq 'plt' ? : 102 643 745
305 745 foreach my $method (@methods) {
306 320 my $ref = ref $args->{args}{$method};
307 320 ▶ if ( ( $ref ne 'ARRAY' ) && ( $ref ne '' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref ne "ARRAY" and $ref ne "") 0 320 320
Condition66%2/3
$ref ne "ARRAY" and $ref ne ""
!ll&&!rl&&r
43160
MC/DC0%0/2
$ref ne "ARRAY" and $ref ne ""
$ref ne "ARRAY" $ref ne ""
Truth table66%2/3
A and B
A= $ref ne "ARRAY"B= $ref ne ""
ABresult
0X0
100
111
308 0 die "$current_sub only accepts scalar or array types, but \"$ref\" was entered.";
309 }
310 320 ▶ if ( $ref eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref eq "") 316 4 320
311 316 ▶ if ($method eq 'show') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq 'show') { } 0 316 316
312 0 next; # plt.show() is emitted by plt() after plt.savefig()
313 } else {
314 316 say {$args->{fh}} "$obj[$i].$method(" . $arg_text->( $args->{args}{$method} ) . ') #line' . __LINE__;
315 }
316 316 next;
317 }
318 # can only be ARRAY
319 4 foreach my $j ( @{ $args->{args}{$method} } ) {
320 6 say { $args->{fh} } "$obj[$i].$method(" . $arg_text->($j) . ') #line' . __LINE__;
321 }
322 }
323 }
324 541 ▶ return unless defined $args->{ax};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args->{"ax"} 0 541 541
325 541 ▶ my $legend = $args->{args}{legend} // '';
Condition100%2/2
$args->{"args"}{"legend"} // ""
l!l
1540
MC/DC100%1/1
$args->{"args"}{"legend"} // ""
$args->{"args"}{"legend"}
Truth table100%2/2
A
A= $args->{"args"}{"legend"}
Aresult
11
00
326 541 my $pie_plot = 0;
327 541 ▶ if ( ( defined $args->{args}{plot_type} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"args"}{"plot_type"} and $args->{"args"}{"plot_type"} eq "pie") 11 530 541
Condition100%3/3
defined $args->{"args"}{"plot_type"} and $args->{"args"}{"plot_type"} eq "pie"
!ll&&!rl&&r
752311
MC/DC100%2/2
defined $args->{"args"}{"plot_type"} and $args->{"args"}{"plot_type"} eq "pie"
defined $args->{"args"}{"plot_type"} $args->{"args"}{"plot_type"} eq "pie"
Truth table100%3/3
A and B
A= defined $args->{"args"}{"plot_type"}B= $args->{"args"}{"plot_type"} eq "pie"
ABresult
0X0
100
111
328 && ( $args->{args}{plot_type} eq 'pie' ) ) {
329 11 $pie_plot = 1;
330 }
331 541 ▶ return 1 if $pie_plot == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $pie_plot == 1 11 530 541
332 # pie charts don't get legends
333 # A twin axis (see %twin_axes) is given no legend of its own: its lines go
334 # in the legend of the axes it twins.
335 530 ▶ return 1 if $args->{no_legend};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"no_legend"} 7 523 530
336 523 say { $args->{fh} }
337 "handles, labels = $args->{ax}.get_legend_handles_labels()";
338 523 my $twin = delete $twin_axes{ $args->{ax} };
339 523 ▶ if ( defined $twin ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $twin) 12 511 523
340 # One legend for both axes, drawn on the twin because the twin is drawn
341 # over the axes it twins, and would cover a legend drawn on them. The
342 # twin's lines were in no legend at all, or -- with "twinx_args" -- in a
343 # second one drawn on top of the first, in the same "best" place.
344 12 say { $args->{fh} } "twin_handles, twin_labels = $twin.get_legend_handles_labels()";
345 12 say { $args->{fh} } 'handles += twin_handles';
346 12 say { $args->{fh} } 'labels += twin_labels';
347 12 say { $args->{fh} } 'if len(labels) > 0:';
348 12 ▶ say { $args->{fh} } "\t$twin.legend(handles, labels" . ( length $legend ? ", $legend" : '' ) . ')';
Branch: 1 branch
BranchTrueFalseTotal
length $legend ? : 0 12 12
349 12 return 1;
350 }
351 511 say { $args->{fh} } 'if len(labels) > 0:';
352 511 say { $args->{fh} } "\t$args->{ax}.legend($legend)";
353 }
354 201 ▶sub barplot_helper { # this is a helper function to other matplotlib subroutines
Subroutine barplot_helper: called CC=92 SCAR=47.0
Pod undocumented
355 201 my ($args) = @_;
356 201 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
357 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
358 201 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 201 201
359 0 die
360 "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
361 }
362 201 my @reqd_args = (
363 'fh', # e.g. $py, $fh, which will be passed by the subroutine
364 'plot', # args to original function
365 );
366 201 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
367 201 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 201 201
368 0 p @undef_args;
369 0 die 'the above args are necessary, but were not defined.';
370 }
371 201 my @opt = ('ax', @reqd_args, @ax_methods, @plt_methods, @fig_methods, @arg, @{ $opt{$current_sub} } );
372 201 my $plot = $args->{plot};
373 my @bad_opt = grep {
374 1214 my $key = $_;
375 1214 not grep { $_ eq $key } @opt
376 201 } keys %{$plot};
377 201 ▶ my $ax = $args->{ax} // '';
Condition50%1/2
$args->{"ax"} // ""
l!l
2010
MC/DC0%0/1
$args->{"ax"} // ""
$args->{"ax"}
Truth table50%1/2
A
A= $args->{"ax"}
Aresult
11
00
378 201 ▶ if ( scalar @bad_opt > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 7 194 201
379 bad_keyword_error({
380 bad => \@bad_opt,
381 accepted => \@opt,
382 preferred => $opt{$current_sub},
383 type => $plot->{plot_type},
384 7 sub => $current_sub
385 });
386 }
387 194 my ( %ref_counts, $plot_type );
388 194 foreach my $set ( keys %{ $plot->{data} } ) {
389 335 $ref_counts{ ref $plot->{data}{$set} }++;
390 }
391 194 ▶ if ( scalar keys %ref_counts > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %ref_counts > 1) 0 194 194
392 0 p $plot->{data};
393 0 p %ref_counts;
394 0 die
395 "different kinds of data were entered to plot $ax which should be simple hash or hash of arrays.";
396 }
397 194 ▶ if ( defined $ref_counts{''} ) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $ref_counts{''}) { } 156 38 194
elsif (defined $ref_counts{'ARRAY'}) { } 17 21 38
elsif (defined $ref_counts{'HASH'}) { } 21 0 21
398 156 $plot_type = 'simple';
399 } elsif ( defined $ref_counts{'ARRAY'} ) {
400 17 $plot_type = 'grouped';
401 } elsif ( defined $ref_counts{'HASH'} ) {
402 21 $plot_type = 'grouped'; # now make the hash of hash into a ARRAY structure
403 21 my @key2 = bar_series({ plot => $plot, sub => $current_sub });
404 17 my %new_structure;
405 17 foreach my $k1 ( keys %{ $plot->{data} } ) {
406 22 @{ $new_structure{$k1} } = @{ $plot->{data}{$k1} }{@key2};
407 }
408 # The inner keys are the series, so a color given as a hash can be
409 # answered here: turn it into the positional array the series loop
410 # below reads. Given as a hash it was silently dropped, since that
411 # loop only ever looked at an ARRAY.
412 17 ▶ if ( ( defined $plot->{color} ) && ( ref $plot->{color} eq 'HASH' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"color"} and ref $plot->{"color"} eq "HASH") 2 15 17
Condition100%3/3
defined $plot->{"color"} and ref $plot->{"color"} eq "HASH"
!ll&&!rl&&r
1412
MC/DC100%2/2
defined $plot->{"color"} and ref $plot->{"color"} eq "HASH"
defined $plot->{"color"} ref $plot->{"color"} eq "HASH"
Truth table100%3/3
A and B
A= defined $plot->{"color"}B= ref $plot->{"color"} eq "HASH"
ABresult
0X0
100
111
413 2 my @uncolored = grep { not defined $plot->{color}{$_} } @key2;
414 2 ▶ if ( scalar @uncolored > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @uncolored > 0) 0 2 2
415 0 p @uncolored;
416 0 die "the above series have no color defined in \"color\" in $current_sub";
417 }
418 2 $plot->{color} = [ @{ $plot->{color} }{@key2} ];
419 }
420 # A new array rather than "@{ $plot->{label} } = ...", which wrote the
421 # series names into an array the caller may have passed as "label".
422 # The same names as any "label" given, which bar_series has checked.
423 17 $plot->{label} = [@key2];
424 17 $plot->{data} = \%new_structure;
425 } else {
426 0 p %ref_counts;
427 0 p $plot->{data};
428 0 die 'the above plot type is not yet programmed in to bar/barh';
429 }
430 # Read as a Python bool, as "log" is: it was compared with "==", so
431 # "stacked => 'True'" died as 'Argument "True" isn't numeric', and a
432 # negative number shifted the bars as though unstacked while keeping the
433 # full width of stacked ones.
434 190 $plot->{stacked} = bool_option( $plot->{stacked}, 'stacked', $current_sub );
435 # "float only", as documented, and written bare: "width => 'wide'" was a
436 # NameError in Python.
437 189 ▶ if ( defined $plot->{width} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"width"}) 6 183 189
438 6 ▶ if ( ref $plot->{width} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"width"}) 0 6 6
439 0 die "\"width\" is one number for every bar in $current_sub, not a " . ref( $plot->{width} ) . ' reference';
440 }
441 6 check_numbers( [ $plot->{width} ], '"width"', $current_sub );
442 5 ▶ die "\"width\" must be a finite number for $current_sub, not \"$plot->{width}\"" unless is_finite( $plot->{width} );
Branch: 1 branch
BranchTrueFalseTotal
unless is_finite($plot->{"width"}) 1 4 5
443 }
444 187 ▶ if ( ( $plot_type eq 'grouped' )
Branch: 1 branch
BranchTrueFalseTotal
if ($plot_type eq "grouped" and defined $plot->{"width"} and $plot->{"stacked"} == 0) 0 187 187
Condition83%5/6
$plot_type eq "grouped" and defined $plot->{"width"} and $plot->{"stacked"} == 0
!ll&&!rl&&r
18610
$plot_type eq "grouped" and defined $plot->{"width"}
!ll&&!rl&&r
155311
MC/DC0%0/3
$plot_type eq "grouped" and defined $plot->{"width"} and $plot->{"stacked"} == 0
$plot_type eq "grouped" defined $plot->{"width"} $plot->{"stacked"} == 0
Truth table75%3/4
A and B and C
A= $plot_type eq "grouped"B= defined $plot->{"width"}C= $plot->{"stacked"} == 0
ABCresult
0XX0
10X0
1100
1111
445 && ( defined $plot->{width} )
446 && ( $plot->{stacked} == 0 ) )
447 {
448 0 say STDERR 'grouped, non-stacked barplots ignore width settings';
449 0 delete $plot->{width};
450 }
451 187 my @key_order;
452 187 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 7 180 187
453 @key_order = check_key_order({
454 keys => $plot->{key_order},
455 data => $plot->{data},
456 7 option => 'key_order',
457 sub => $current_sub
458 });
459 } else {
460 180 @key_order = sort keys %{ $plot->{data} };
461 }
462 # A color per data key only means something for the simple form, where one
463 # key is one bar, and for the hash-of-hashes form, whose inner keys named
464 # the series and were turned into an array above. The hash-of-arrays form
465 # has nothing to key a color hash by, and used to ignore it in silence.
466 184 ▶ if ( ( $plot_type eq 'grouped' ) && ( ref $plot->{color} eq 'HASH' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot_type eq "grouped" and ref $plot->{"color"} eq "HASH") 1 183 184
Condition100%3/3
$plot_type eq "grouped" and ref $plot->{"color"} eq "HASH"
!ll&&!rl&&r
152311
MC/DC100%2/2
$plot_type eq "grouped" and ref $plot->{"color"} eq "HASH"
$plot_type eq "grouped" ref $plot->{"color"} eq "HASH"
Truth table100%3/3
A and B
A= $plot_type eq "grouped"B= ref $plot->{"color"} eq "HASH"
ABresult
0X0
100
111
467 1 die "$current_sub: \"color\" is a HASH, but this data is a hash of arrays, whose series have no names to key it by: give one color per series as an array, e.g. color => ['red','blue']";
468 }
469 # Every value reaches the script as it stands, so a non-numeric one
470 # becomes a bare Python name: "data => { A => 'abc' }" wrote "vals = [abc]"
471 # and died as a NameError when the script ran, pointing at the generated
472 # file rather than at the data.
473 183 foreach my $key (@key_order) {
474 316 ▶ my @values = ( $plot_type eq 'simple' ) ? ( $plot->{data}{$key} ) : @{ $plot->{data}{$key} };
Branch: 1 branch
BranchTrueFalseTotal
$plot_type eq 'simple' ? : 267 49 316
475 316 ▶ my @bad = grep { defined && !looks_like_number($_) } @values;
Condition100%3/3
defined $_ && !&looks_like_number($_)
!ll&&!rl&&r
23591
MC/DC100%2/2
defined $_ && !&looks_like_number($_)
defined $_ !&looks_like_number($_)
Truth table100%3/3
A && not(B)
A= defined $_B= !&looks_like_number($_)
ABresult
0X0
100
111
476 316 ▶ if ( scalar @bad > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad > 0) 1 315 316
477 1 p @bad;
478 1 die "the above values of \"$key\" are not numbers, which $current_sub needs";
479 }
480 315 ▶ next unless $plot_type eq 'simple';
Branch: 1 branch
BranchTrueFalseTotal
unless $plot_type eq "simple" 49 266 315
481 die "\"$key\" has an undefined value, which $current_sub cannot plot"
482 266 ▶ unless defined $plot->{data}{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $plot->{"data"}{$key} 1 265 266
483 }
484 181 ▶ if ( $plot_type eq 'grouped' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot_type eq "grouped") 31 150 181
485 # One bar per key per series, so a short array leaves a series with
486 # more x positions than heights, which matplotlib rejects with a shape
487 # mismatch naming neither the key nor the length it expected.
488 31 my %n_values = map { $_ => scalar @{ $plot->{data}{$_} } } @key_order;
489 31 my %lengths = map { $_ => 1 } values %n_values;
490 31 ▶ if ( scalar keys %lengths > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %lengths > 1) 1 30 31
491 1 p %n_values;
492 1 die "the above keys hold different numbers of values; every key of a grouped $plot->{plot_type} needs the same number";
493 }
494 # Nothing to draw, which died as "Can't use an undefined value as an
495 # ARRAY reference" where the first series was looked for.
496 30 ▶ if ( ( scalar keys %lengths == 1 ) && ( ( keys %lengths )[0] == 0 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %lengths == 1 and (keys %lengths)[0] == 0) 1 29 30
Condition66%2/3
scalar keys %lengths == 1 and (keys %lengths)[0] == 0
!ll&&!rl&&r
0291
MC/DC50%1/2
scalar keys %lengths == 1 and (keys %lengths)[0] == 0
scalar keys %lengths == 1 (keys %lengths)[0] == 0
Truth table66%2/3
A and B
A= scalar keys %lengths == 1B= (keys %lengths)[0] == 0
ABresult
0X0
100
111
497 1 die "every key of \"data\" holds an empty array, so $current_sub has no bars to draw";
498 }
499 }
500 179 my $options = ''; # these args go to the plt.bar call
501 179 ▶ if ( bool_option( $plot->{'log'}, 'log', $current_sub ) || $plot->{logscale} ) { # "logscale" is documented as taking Perl truth, "log" as a Python bool
Branch: 1 branch
BranchTrueFalseTotal
if (bool_option($plot->{"log"}, "log", $current_sub) or $plot->{"logscale"}) 5 173 178
Condition100%3/3
bool_option($plot->{"log"}, "log", $current_sub) or $plot->{"logscale"}
l!l&&r!l&&!r
32173
MC/DC100%2/2
bool_option($plot->{"log"}, "log", $current_sub) or $plot->{"logscale"}
bool_option($plot->{"log"}, "log", $current_sub) $plot->{"logscale"}
Truth table100%3/3
A or B
A= bool_option($plot->{"log"}, "log", $current_sub)B= $plot->{"logscale"}
ABresult
1X1
011
000
502 5 $options .= ', log = True';
503 } # args that can be either arrays or strings below; STRINGS:
504 178 foreach my $c ( grep { defined $plot->{$_} } ( 'color', 'edgecolor' ) ) {
505 11 ▶ next if ( ( $c eq 'color' ) && ( $plot_type eq 'grouped' ) && ( ref $plot->{$c} ne '' ) );
Branch: 1 branch
BranchTrueFalseTotal
if $c eq "color" and $plot_type eq "grouped" and ref $plot->{$c} ne "" 3 8 11
Condition100%6/6
$c eq "color" and $plot_type eq "grouped" and ref $plot->{$c} ne ""
!ll&&!rl&&r
713
$c eq "color" and $plot_type eq "grouped"
!ll&&!rl&&r
524
MC/DC100%3/3
$c eq "color" and $plot_type eq "grouped" and ref $plot->{$c} ne ""
$c eq "color" $plot_type eq "grouped" ref $plot->{$c} ne ""
Truth table100%4/4
A and B and C
A= $c eq "color"B= $plot_type eq "grouped"C= ref $plot->{$c} ne ""
ABCresult
0XX0
10X0
1100
1111
506 8 my $ref = ref $plot->{$c};
507 8 ▶ if ( $ref eq '' ) { # single color
Branch: 3 branches
BranchTrueFalseTotal
if ($ref eq '') { } 4 4 8
elsif ($ref eq 'ARRAY') { } 0 4 4
elsif ($ref eq 'HASH') { } 4 0 4
508 4 $options .= ", $c = " . py_str( $plot->{$c} );
509 } elsif ( $ref eq 'ARRAY' ) {
510 0 $options .= ", $c = [" . py_list( @{ $plot->{$c} } ) . ']';
511 } elsif ( $ref eq 'HASH' ) {
512 # One color per bar, keyed as the bars are, as "color" is. An
513 # "edgecolor" hash fell into an empty branch here and was dropped
514 # without a word. Every bar of a grouped plot is one key of one
515 # series, and the hash has nothing to say which.
516 4 ▶ if ( ( $c eq 'edgecolor' ) && ( $plot_type eq 'grouped' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq "edgecolor" and $plot_type eq "grouped") 1 3 4
Condition100%3/3
$c eq "edgecolor" and $plot_type eq "grouped"
!ll&&!rl&&r
121
MC/DC100%2/2
$c eq "edgecolor" and $plot_type eq "grouped"
$c eq "edgecolor" $plot_type eq "grouped"
Truth table100%3/3
A and B
A= $c eq "edgecolor"B= $plot_type eq "grouped"
ABresult
0X0
100
111
517 1 die "$current_sub: \"edgecolor\" is a HASH, which is keyed by bar and so only fits a simple hash of one bar per key: give a grouped plot one color, or an array of one per key";
518 }
519 3 ▶ next if $c eq 'color'; # written with the bars, below
Branch: 1 branch
BranchTrueFalseTotal
if $c eq "color" 1 2 3
520 2 my @uncolored = grep { not defined $plot->{$c}{$_} } @key_order;
521 2 ▶ if ( scalar @uncolored > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @uncolored > 0) 1 1 2
522 1 p @uncolored;
523 1 die "the above keys have no color defined in \"$c\" in $current_sub";
524 }
525 1 $options .= ", $c = [" . py_list( @{ $plot->{$c} }{@key_order} ) . ']';
526 } else {
527 0 die "ref \"$ref\" isn't defined";
528 }
529 } # args that can be either arrays or strings below; NUMERIC:
530 # One width for every bar edge, or one per bar. Nothing checked it, so
531 # "linewidth => 'thick'" was written as a bare Python name.
532 176 foreach my $c ( grep { defined $plot->{$_} } ('linewidth') ) {
533 2 my $ref = ref $plot->{$c};
534 2 ▶ if ( ( $ref ne '' ) && ( $ref ne 'ARRAY' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref ne "" and $ref ne "ARRAY") 0 2 2
Condition33%1/3
$ref ne "" and $ref ne "ARRAY"
!ll&&!rl&&r
200
MC/DC0%0/2
$ref ne "" and $ref ne "ARRAY"
$ref ne "" $ref ne "ARRAY"
Truth table33%1/3
A and B
A= $ref ne ""B= $ref ne "ARRAY"
ABresult
0X0
100
111
535 0 p $args;
536 0 die "$ref for $c isn't acceptable";
537 }
538 0 ▶ my @values = ( $ref eq 'ARRAY' ) ? @{ $plot->{$c} } : ( $plot->{$c} );
Branch: 1 branch
BranchTrueFalseTotal
$ref eq 'ARRAY' ? : 0 2 2
539 2 check_numbers( \@values, "\"$c\"", $current_sub );
540 1 ▶ $options .= ( $ref eq 'ARRAY' ) ? ", $c = [" . py_nums(@values) . ']' : ", $c = " . py_num( $plot->{$c} );
Branch: 1 branch
BranchTrueFalseTotal
$ref eq 'ARRAY' ? : 0 1 1
541 }
542 # Error bars take the shapes matplotlib does -- one number for every bar,
543 # an array of one per bar, or an array of two such arrays, lower then upper
544 # -- and a hash keyed by the data keys, each value one number or a
545 # [ lower, upper ] pair. An array died as "ARRAY for yerr isn't acceptable"
546 # though the options table offered it, and a hash value that was one number,
547 # or a key left out of the hash, died dereferencing it.
548 175 my $n_bars = scalar @key_order;
549 # An error bar across the bars of a simple plot -- "yerr" on a barh, "xerr"
550 # on a bar -- lies along the axis that holds the labels, which are strings.
551 # matplotlib draws one there from one number, or one per bar, but not from
552 # a lower and an upper row: it adds the errors to the labels and dies as
553 # "ConversionError: Failed to convert value(s) to axis units". The hash
554 # form always wrote two rows, so barh(yerr => { A => 1, B => 1 }) died
555 # that way though its errors were the same on both sides. Two rows that
556 # are equal are written as the one row they amount to, and two that
557 # differ are refused here, by name. A grouped plot is drawn at numbers and
558 # takes either.
559 15 ▶ my $across = sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
560 15 my ( $err, $low, $high ) = @_;
561 15 ▶ return 0 unless ( $plot_type eq 'simple' ) && ( $err eq ( ( $plot->{plot_type} eq 'barh' ) ? 'yerr' : 'xerr' ) );
Branch: 2 branches
BranchTrueFalseTotal
unless $plot_type eq "simple" and $err eq ($plot->{"plot_type"} eq "barh" ? "yerr" : "xerr") 9 6 15
$plot->{'plot_type'} eq 'barh' ? : 6 8 14
Condition100%3/3
$plot_type eq "simple" and $err eq ($plot->{"plot_type"} eq "barh" ? "yerr" : "xerr")
!ll&&!rl&&r
186
MC/DC100%2/2
$plot_type eq "simple" and $err eq ($plot->{"plot_type"} eq "barh" ? "yerr" : "xerr")
$plot_type eq "simple" $err eq ($plot->{"plot_type"} eq "barh" ? "yerr" : "xerr")
Truth table100%3/3
A and B
A= $plot_type eq "simple"B= $err eq ($plot->{"plot_type"} eq "barh" ? "yerr" : "xerr")
ABresult
0X0
100
111
562 6 ▶ if ( grep { ( 0 + $low->[$_] ) != ( 0 + $high->[$_] ) } 0 .. $#{$low} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {0 + $low->[$_] != 0 + $high->[$_];} 0 .. $#{$low;}) 3 3 6
563 3 ▶ die "\"$err\" on a $plot->{plot_type} lies along the axis of its labels, where matplotlib draws the same error on both sides of a bar and not a lower and an upper one, in $current_sub: give one number per bar, or \""
Branch: 1 branch
BranchTrueFalseTotal
$err eq 'yerr' ? : 2 1 3
564 . ( ( $err eq 'yerr' ) ? 'xerr' : 'yerr' ) . '" for an error in the bars\' own direction';
565 }
566 3 return 1;
567 175 };
568 175 foreach my $err ( grep { defined $plot->{$_} } ( 'xerr', 'yerr' ) ) {
569 22 my $ref = ref $plot->{$err};
570 22 ▶ if ( $ref eq '' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($ref eq '') { } 3 19 22
elsif ($ref eq 'ARRAY') { } 8 11 19
elsif ($ref eq 'HASH') { } 11 0 11
571 3 check_numbers( [ $plot->{$err} ], "\"$err\"", $current_sub );
572 2 $options .= ", $err = " . py_num( $plot->{$err} );
573 } elsif ( $ref eq 'ARRAY' ) {
574 8 ▶ my @rows = ( grep { ref } @{ $plot->{$err} } ) ? @{ $plot->{$err} } : ( $plot->{$err} );
Branch: 1 branch
BranchTrueFalseTotal
grep({ref $_;} @{$$plot{$err};}) ? : 5 3 8
575 8 ▶ if ( ( scalar @rows > 2 ) || ( grep { ref $_ ne 'ARRAY' } @rows ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @rows > 2 or grep {ref $_ ne "ARRAY";} @rows) 0 8 8
Condition33%1/3
scalar @rows > 2 or grep {ref $_ ne "ARRAY";} @rows
l!l&&r!l&&!r
008
MC/DC0%0/2
scalar @rows > 2 or grep {ref $_ ne "ARRAY";} @rows
scalar @rows > 2 grep {ref $_ ne "ARRAY";} @rows
Truth table33%1/3
A or B
A= scalar @rows > 2B= grep {ref $_ ne "ARRAY";} @rows
ABresult
1X1
011
000
576 0 die "\"$err\" is an array of one error per bar, or of two such arrays (lower, then upper), in $current_sub";
577 }
578 8 foreach my $row (@rows) {
579 13 ▶ if ( scalar @{$row} != $n_bars ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$row;} != $n_bars) 1 12 13
580 1 die "\"$err\" has " . scalar( @{$row} ) . " values in a row, but $current_sub has $n_bars bars";
581 }
582 12 check_numbers( $row, "\"$err\"", $current_sub );
583 }
584 7 ▶ pop @rows if ( scalar @rows == 2 ) && $across->( $err, @rows );
Branch: 1 branch
BranchTrueFalseTotal
if scalar @rows == 2 and &$across($err, @rows) 1 5 6
Condition100%3/3
scalar @rows == 2 and &$across($err, @rows)
!ll&&!rl&&r
241
MC/DC100%2/2
scalar @rows == 2 and &$across($err, @rows)
scalar @rows == 2 &$across($err, @rows)
Truth table100%3/3
A and B
A= scalar @rows == 2B= &$across($err, @rows)
ABresult
0X0
100
111
585 6 my @py = map { '[' . py_nums( @{$_} ) . ']' } @rows;
586 6 ▶ $options .= ", $err = " . ( ( scalar @rows == 1 ) ? $py[0] : '[' . join( ',', @py ) . ']' );
Branch: 1 branch
BranchTrueFalseTotal
scalar @rows == 1 ? : 3 3 6
587 } elsif ( $ref eq 'HASH' ) {
588 11 my @missing = grep { not defined $plot->{$err}{$_} } @key_order;
589 11 ▶ if ( scalar @missing > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @missing > 0) 1 10 11
590 1 p @missing;
591 1 die "the above keys have no \"$err\" in $current_sub";
592 }
593 10 my ( @low, @high );
594 10 foreach my $i (@key_order) {
595 22 my $e = $plot->{$err}{$i};
596 22 ▶ my @pair = ( ref $e eq 'ARRAY' ) ? @{$e} : ( ref $e eq '' ) ? ( $e, $e ) : ();
Branch: 2 branches
BranchTrueFalseTotal
ref $e eq 'ARRAY' ? : 14 8 22
ref $e eq '' ? : 8 0 8
597 22 ▶ if ( scalar @pair != 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @pair != 2) 0 22 22
598 0 p $e;
599 0 die "$err/$i should be one number, or exactly 2 items: low and high error bars";
600 }
601 22 check_numbers( \@pair, "\"$err\" of \"$i\"", $current_sub );
602 22 push @low, $pair[0];
603 22 push @high, $pair[1];
604 }
605 10 ▶ $options .= $across->( $err, \@low, \@high )
Branch: 1 branch
BranchTrueFalseTotal
&$across($err, \@low, \@high) ? : 2 6 8
606 ? ", $err = [" . py_nums(@low) . ']'
607 : ", $err = [[" . py_nums(@low) . '],[' . py_nums(@high) . ']]';
608 } else {
609 0 p $args;
610 0 die "$ref for $err isn't acceptable";
611 }
612 }
613 169 ▶ if ( $plot_type eq 'simple' ) { # a simple hash -> simple bar plot
Branch: 2 branches
BranchTrueFalseTotal
if ($plot_type eq 'simple') { } 141 28 169
elsif ($plot_type eq 'grouped') { } 28 0 28
614 write_data({
615 data => \@key_order,
616 fh => $args->{fh},
617 141 name => 'labels'
618 });
619 141 say { $args->{fh} } 'vals = [' . py_nums( @{ $plot->{data} }{@key_order} ) . ']';
620 141 ▶ if ((defined $plot->{color}) && (ref $plot->{color} eq 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"color"} and ref $plot->{"color"} eq "HASH") 1 140 141
Condition100%3/3
defined $plot->{"color"} and ref $plot->{"color"} eq "HASH"
!ll&&!rl&&r
13911
MC/DC100%2/2
defined $plot->{"color"} and ref $plot->{"color"} eq "HASH"
defined $plot->{"color"} ref $plot->{"color"} eq "HASH"
Truth table100%3/3
A and B
A= defined $plot->{"color"}B= ref $plot->{"color"} eq "HASH"
ABresult
0X0
100
111
621 1 @undef_args = grep {not defined $plot->{color}{$_}} @key_order;
622 1 ▶ if (scalar @undef_args > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 1 1
623 0 p @undef_args;
624 0 die 'the above keys were not defined in the colors hash';
625 }
626 1 $options .= ',color = [' . py_list( @{ $plot->{color} }{@key_order} ) . ']';
627 }
628 # "width" was read only by the grouped, stacked path, so a simple bar
629 # plot was drawn at matplotlib's 0.8 whatever it said. barh calls the
630 # same dimension "height".
631 141 ▶ if ( defined $plot->{width} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"width"}) 3 138 141
632 3 ▶ $options .= ', ' . ( $plot->{plot_type} eq 'barh' ? 'height' : 'width' ) . ' = ' . py_num( $plot->{width} );
Branch: 1 branch
BranchTrueFalseTotal
$plot->{'plot_type'} eq 'barh' ? : 1 2 3
633 }
634 141 say { $args->{fh} } "ax$ax.$plot->{plot_type}(labels, vals $options)";
635 } elsif ( $plot_type eq 'grouped' ) { # grouped bar plot; hash of array
636 28 my @val;
637 28 foreach my $k (@key_order) {
638 43 foreach my $i ( 0 .. scalar @{ $plot->{data}{$k} } - 1 ) {
639 # 0 for a missing value, so that every series has a bar at
640 # every key. Not written back: the array is the caller's.
641 86 ▶ push @{ $val[$i] }, $plot->{data}{$k}[$i] // 0;
Condition100%2/2
$plot->{"data"}{$k}[$i] // 0
l!l
851
MC/DC100%1/1
$plot->{"data"}{$k}[$i] // 0
$plot->{"data"}{$k}[$i]
Truth table100%2/2
A
A= $plot->{"data"}{$k}[$i]
Aresult
11
00
642 }
643 }
644 28 ▶ my $barwidth = $plot->{width} // 0.8;
Condition100%2/2
$plot->{"width"} // "0.8"
l!l
127
MC/DC100%1/1
$plot->{"width"} // "0.8"
$plot->{"width"}
Truth table100%2/2
A
A= $plot->{"width"}
Aresult
11
00
645 28 ▶ if ( $plot->{stacked} == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"stacked"} == 0) 14 14 28
646 14 $barwidth /= ( scalar @val + 1 ); # @val holds one array per bar series
647 }
648 28 my @xticks = 0 .. scalar @{ $val[0] } - 1;
649 28 my @mean_pos = map { 0 } 0 .. scalar @{ $val[0] } - 1; # initialize
650 28 my $hw = 'height';
651 28 ▶ $hw = 'width' if $plot->{plot_type} eq 'bar';
Branch: 1 branch
BranchTrueFalseTotal
if $plot->{"plot_type"} eq "bar" 21 7 28
652 28 my @bottom = map { 0 } 0 .. scalar @{ $val[0] } - 1; # initialize
653 28 my $i = 0;
654 28 foreach my $arr (@val) {
655 56 my $x = '[' . join( ',', @xticks ) . ']';
656 56 foreach my $p ( 0 .. $#mean_pos ) {
657 86 $mean_pos[$p] += $xticks[$p];
658 }
659 56 my $set_options = '';
660 56 foreach
661 112 ▶ my $f ( grep { ( ref $plot->{$_} eq 'ARRAY' ) && defined $plot->{$_}[$i] } ( 'color', 'label' ) )
Condition66%2/3
ref $plot->{$_} eq 'ARRAY' && defined $plot->{$_}[$i]
!ll&&!rl&&r
68044
MC/DC50%1/2
ref $plot->{$_} eq 'ARRAY' && defined $plot->{$_}[$i]
ref $plot->{$_} eq 'ARRAY' defined $plot->{$_}[$i]
Truth table66%2/3
A && B
A= ref $plot->{$_} eq 'ARRAY'B= defined $plot->{$_}[$i]
ABresult
0X0
100
111
662 {
663 # py_str: a label is a series name, which for the
664 # hash-of-hashes form is one of the caller's own inner keys.
665 44 $set_options .= ", $f = " . py_str( $plot->{$f}[$i] );
666 }
667 56 ▶ if ( $plot->{stacked} > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"stacked"} > 0) 28 28 56
668 28 ▶ my $stack_kwarg = $plot->{plot_type} eq 'barh' ? 'left' : 'bottom';
Branch: 1 branch
BranchTrueFalseTotal
$plot->{'plot_type'} eq 'barh' ? : 12 16 28
669 28 $set_options .= ", $stack_kwarg = [" . py_nums(@bottom) . ']';
670 }
671 56 say { $args->{fh} } "ax$ax.$plot->{plot_type}($x, ["
672 56 . py_nums( @{$arr} )
673 . "], $hw = " . py_num($barwidth) . " $options $set_options)";
674 @bottom =
675 38 map { $bottom[$_] + $arr->[$_] } 0 .. scalar @{ $val[0] } - 1
676 56 ▶ if $plot->{stacked} > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $plot->{"stacked"} > 0 28 28 56
677 48 @xticks = map { $_ + $barwidth } @xticks
678 56 ▶ if $plot->{stacked} <= 0; # for next iteration
Branch: 1 branch
BranchTrueFalseTotal
if $plot->{"stacked"} <= 0 28 28 56
679 56 $i++;
680 }
681 28 my $xticks = '[' . py_list(@key_order) . ']';
682 28 my $ticks = 'yticks';
683 28 ▶ $ticks = 'xticks' if $plot->{plot_type} eq 'bar';
Branch: 1 branch
BranchTrueFalseTotal
if $plot->{"plot_type"} eq "bar" 21 7 28
684 28 $_ /= scalar @val for @mean_pos;
685 28 say { $args->{fh} } "ax$ax.set_$ticks(["
686 . join( ',', @mean_pos )
687 . "], $xticks)";
688 } else {
689 0 die
690 "\$plot_type = $plot_type & stacked = $plot->{stacked}and isn't defined.";
691 }
692 }
693  
694 30 ▶sub boxplot_helper {
Subroutine boxplot_helper: called CC=25 SCAR=32.3
Pod undocumented
695 30 my ($args) = @_;
696 30 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
697 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
698 30 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 30 30
699 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
700 }
701 30 my @reqd_args = (
702 'fh', # e.g. $py, $fh, which will be passed by the subroutine
703 'plot', # args to original function
704 );
705 30 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
706 30 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 30 30
707 0 p @undef_args;
708 0 die 'the above args are necessary, but were not defined.';
709 }
710 my @opt = (
711 30 @ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} }
712 );
713 30 my $plot = $args->{plot};
714 my @bad_opt = grep {
715 197 my $key = $_;
716 197 not grep { $_ eq $key } @opt
717 30 } keys %{$plot};
718 30 ▶ if ( scalar @bad_opt > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 30 30
719 bad_keyword_error({
720 bad => \@bad_opt,
721 accepted => \@opt,
722 preferred => $opt{$current_sub},
723 type => $plot->{plot_type},
724 0 sub => $current_sub
725 });
726 }
727 30 ▶ $plot->{orientation} = $plot->{orientation} // 'vertical';
Condition100%2/2
$plot->{"orientation"} // "vertical"
l!l
129
MC/DC100%1/1
$plot->{"orientation"} // "vertical"
$plot->{"orientation"}
Truth table100%2/2
A
A= $plot->{"orientation"}
Aresult
11
00
728 30 ▶ if ( $plot->{orientation} !~ m/^(?:horizontal|vertical)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($plot->{"orientation"} =~ /^(?:horizontal|vertical)$/) 0 30 30
729 0 die
730 "$current_sub needs either \"horizontal\" or \"vertical\", not \"$plot->{orientation}\"";
731 }
732 30 ▶ if (ref $plot->{data} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"data"} eq "ARRAY") 3 27 30
733 3 my $tmp = delete $plot->{data};
734 3 $plot->{data}{''} = $tmp;
735 }
736 30 my ( @xticks, @key_order );
737 30 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 2 28 30
738 @key_order = check_key_order({
739 keys => $plot->{key_order},
740 data => $plot->{data},
741 2 option => 'key_order',
742 sub => $current_sub
743 });
744 } else {
745 28 @key_order = sort keys %{ $plot->{data} };
746 }
747 29 ▶ my $ax = $args->{ax} // '';
Condition50%1/2
$args->{"ax"} // ""
l!l
290
MC/DC0%0/1
$args->{"ax"} // ""
$args->{"ax"}
Truth table50%1/2
A
A= $args->{"ax"}
Aresult
11
00
748 29 ▶ $plot->{notch} = $plot->{notch} // 'False';
Condition100%2/2
$plot->{"notch"} // "False"
l!l
326
MC/DC100%1/1
$plot->{"notch"} // "False"
$plot->{"notch"}
Truth table100%2/2
A
A= $plot->{"notch"}
Aresult
11
00
749 29 ▶ $plot->{showcaps} = $plot->{showcaps} // 'True';
Condition100%2/2
$plot->{"showcaps"} // "True"
l!l
128
MC/DC100%1/1
$plot->{"showcaps"} // "True"
$plot->{"showcaps"}
Truth table100%2/2
A
A= $plot->{"showcaps"}
Aresult
11
00
750 29 ▶ $plot->{showfliers} = $plot->{showfliers} // 'True';
Condition100%2/2
$plot->{"showfliers"} // "True"
l!l
128
MC/DC100%1/1
$plot->{"showfliers"} // "True"
$plot->{"showfliers"}
Truth table100%2/2
A
A= $plot->{"showfliers"}
Aresult
11
00
751 29 ▶ $plot->{showmeans} = $plot->{showmeans} // 'True';
Condition100%2/2
$plot->{"showmeans"} // "True"
l!l
227
MC/DC100%1/1
$plot->{"showmeans"} // "True"
$plot->{"showmeans"}
Truth table100%2/2
A
A= $plot->{"showmeans"}
Aresult
11
00
752 29 my $options = "orientation = '$plot->{orientation}'";
753 # Through bool_option, as bar's "log" is: each was written as given, so
754 # "notch => 'false'" left "notch = false" in the script, a NameError.
755 29 foreach my $arg ( 'showcaps', 'showfliers', 'showmeans', 'notch') {
756 116 ▶ $options .= ", $arg = " . ( bool_option( $plot->{$arg}, $arg, $current_sub ) ? 'True' : 'False' );
Branch: 1 branch
BranchTrueFalseTotal
bool_option($plot->{$arg}, $arg, $current_sub) ? : 84 31 115
757 }
758 # A color per box is "colors"; "color" is one color for them all, and a
759 # hash given here was written into the script as 'HASH(0x...)'.
760 28 ▶ if ( ref $plot->{color} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"color"}) 1 27 28
761 1 die "\"color\" is one color for every box in $current_sub, not a " . ref( $plot->{color} ) . ' reference; give one color per key in "colors", e.g. colors => { A => \'red\' }';
762 }
763 27 foreach my $axis ( logscale_axes( $plot->{logscale}, $current_sub ) ) { # x, y
764 2 say {$args->{fh}} "ax$ax.set_$axis" . 'scale("log")';
765 }
766 24 say { $args->{fh} } 'd = []';
767 # %values, rather than writing the filtered list back into $plot->{data}:
768 # the arrays in there belong to the caller, and dropping the undefined
769 # elements in place left the caller's own array shorter than they wrote it.
770 24 my %values;
771 24 foreach my $key (@key_order) {
772 36 ▶ @{ $values{$key} } = grep { ( defined ) && ( not is_nan($_) ) } @{ $plot->{data}{$key} }; # NaN is a missing value, as undef is
Condition100%3/3
defined $_ && !is_nan($_)
!ll&&!rl&&r
11365
MC/DC100%2/2
defined $_ && !is_nan($_)
defined $_ !is_nan($_)
Truth table100%3/3
A && not(B)
A= defined $_B= !is_nan($_)
ABresult
0X0
100
111
773 36 my @non_numeric = grep {!looks_like_number($_)} @{ $values{$key} };
774 36 ▶ if (scalar @non_numeric > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @non_numeric > 0) 1 35 36
775 1 p @non_numeric;
776 1 die "$key has non-numeric values";
777 }
778 35 say { $args->{fh} } 'd.append([' . py_nums( @{ $values{$key} } ) . '])';
779 }
780 23 say { $args->{fh} } "bp = ax$ax.boxplot(d, patch_artist = True, $options)";
781 23 ▶ if ( defined $plot->{colors} ){ # every hash key should have its own color defined
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'colors'}) { } 2 21 23
782 # the below code helps to provide better error messages in case I make an error in calling the sub
783 my @bad_keys =
784 2 grep { not defined $plot->{colors}{$_} } keys %{ $plot->{data} };
785 2 ▶ if ( scalar @bad_keys > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_keys > 0) 1 1 2
786 1 p @bad_keys;
787 1 die 'the above data keys have no defined color';
788 }
789  
790 # list of pre-defined colors: https://matplotlib.org/stable/gallery/color/named_colors.html
791 1 print { $args->{fh} } 'colors = ['
792 1 . py_list( @{ $plot->{colors} }{@key_order} ) . ']' . "\n";
793  
794 # the above color list will have the same order, via the above hash slice
795 1 say { $args->{fh} } 'for patch, color in zip(bp["boxes"], colors):';
796 1 say { $args->{fh} } "\tpatch.set_facecolor(color)";
797 1 say { $args->{fh} } "\tpatch.set_edgecolor('black')";
798 } else {
799 21 say { $args->{fh} } 'for pc in bp["boxes"]:';
800 21 ▶ if ( defined $plot->{color} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"color"}) 1 20 21
801 1 say { $args->{fh} } "\tpc.set_facecolor(" . py_str($plot->{color}) . ')';
802 }
803 21 say { $args->{fh} } "\tpc.set_edgecolor('black')";
804 }
805 22 foreach my $key (@key_order) {
806 push @xticks, "$key ("
807 33 . format_commas( scalar @{ $values{$key} }, '%.0u' ) . ')';
808 }
809 22 ▶ if ( $plot->{orientation} eq 'vertical' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{'orientation'} eq 'vertical') { } 21 1 22
810 21 say { $args->{fh} } "ax$ax.set_xticks(["
811 . join( ',', 1 .. scalar @key_order ) . '], ['
812 . py_list(@xticks) . '])';
813 } else {
814 1 say { $args->{fh} } "ax$ax.set_yticks(["
815 . join( ',', 1 .. scalar @key_order ) . '], ['
816 . py_list(@xticks) . '])';
817 }
818 }
819  
820 40 ▶sub colored_table_helper {
Subroutine colored_table_helper: called CC=41 SCAR=37.7
Pod undocumented
821 40 my ($args) = @_;
822 40 my $current_sub = (split(/::/,(caller(0))[3]))[-1]; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
823 40 ▶ if (ref $args ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 40 40
824 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
825 }
826 40 my @reqd_args = (
827 'fh', # e.g. $py, $fh, which will be passed by the subroutine
828 'plot', # args to original function
829 );
830 40 my @undef_args = grep {!defined $args->{$_}} @reqd_args;
831 40 ▶ if (scalar @undef_args > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 40 40
832 0 p @undef_args;
833 0 die "The arguments above are necessary for proper function of $current_sub and weren't defined.";
834 }
835 # optional args are below
836 my @defined_args = (@reqd_args, @ax_methods, @plt_methods, @fig_methods, @arg,
837 40 'ax', @{ $opt{$current_sub} });
838 40 my @bad_args = grep { my $key = $_; not grep {$_ eq $key} @defined_args} keys %{ $args };
839 40 ▶ if (scalar @bad_args > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_args > 0) 0 40 40
840 0 bad_keyword_error({
841 bad => \@bad_args,
842 accepted => \@defined_args,
843 sub => $current_sub
844 });
845 }
846 40 my $plot = $args->{plot};
847 # The check above is on this sub's own arguments (fh, plot, ax), not on the
848 # caller's plot keywords, which live one level down in "plot" and were going
849 # unchecked here while every other helper checked its own.
850 40 my @bad_opt = grep { my $key = $_; not grep {$_ eq $key} @defined_args} keys %{ $plot };
851 40 ▶ if (scalar @bad_opt > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 40 40
852 bad_keyword_error({
853 bad => \@bad_opt,
854 accepted => \@defined_args,
855 preferred => $opt{$current_sub},
856 type => $plot->{plot_type},
857 0 sub => $current_sub
858 });
859 }
860 40 $plot->{mirror} = bool_option( $plot->{mirror}, 'mirror', $current_sub );
861 40 my ( $row_keys, $cols, $cells ) = table_cells( $plot, $current_sub );
862 38 my @row_keys = @{$row_keys};
863 38 my @cols = @{$cols};
864 38 my %data = %{$cells};
865 38 my @rows;
866 38 ▶ if (defined $plot->{row_labels}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'row_labels'}) { } 3 35 38
867 3 @rows = @{ $plot->{row_labels} };
868 # matplotlib refuses a count that differs, with an error naming neither
869 # option.
870 3 ▶ if ( scalar @rows != scalar @row_keys ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @rows != scalar @row_keys) 1 2 3
871 1 die "\"row_labels\" has " . scalar(@rows) . ' labels, but the table has ' . scalar(@row_keys) . " rows in $current_sub";
872 }
873 } else {
874 35 @rows = @row_keys;
875 }
876 37 my ($min, $max) = ('inf', '-inf');
877 37 my $min_positive = 'inf'; # the floor of a log scale, which cannot start at 0 or below
878 37 my $n_numeric = 0; # cells that hold a number, for the check below
879 37 say {$args->{fh}} 'd = []';
880 37 say {$args->{fh}} 'import numpy as np';
881 # What a cell with no value in "data" gets. np.nan, which a NaN cell also
882 # becomes, is drawn in "undef_color" by the colormap's set_bad below and
883 # left blank by "show_numbers"; a "default_undefined" given by the caller
884 # is an ordinary value instead, counting towards the color scale like any
885 # other. The option was read and then ignored -- the line below assigned
886 # np.nan with "$plot->{default_undefined}" commented out beside it -- so a
887 # table asked to call its holes 0 still drew them as holes.
888 37 ▶ if (defined $plot->{default_undefined}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"default_undefined"}) 4 33 37
889 4 ▶ unless (looks_like_number($plot->{default_undefined})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&looks_like_number($plot->{"default_undefined"})) 0 4 4
890 0 die "\"default_undefined\" = $plot->{default_undefined} must be a number";
891 }
892 }
893 # A cell that holds something other than a number is written into the
894 # script as it stands, so "NA" became "d.append([1,NA])" and died as a
895 # NameError. Checked before anything is written.
896 37 my @non_numeric;
897 37 foreach my $k1 (@row_keys) {
898 70 ▶ foreach my $k2 (grep { (defined $data{$k1}{$_}) && (not looks_like_number($data{$k1}{$_})) } @cols) {
Condition100%3/3
defined $data{$k1}{$_} && !&looks_like_number($data{$k1}{$_})
!ll&&!rl&&r
231251
MC/DC100%2/2
defined $data{$k1}{$_} && !&looks_like_number($data{$k1}{$_})
defined $data{$k1}{$_} !&looks_like_number($data{$k1}{$_})
Truth table100%3/3
A && not(B)
A= defined $data{$k1}{$_}B= !&looks_like_number($data{$k1}{$_})
ABresult
0X0
100
111
899 1 push @non_numeric, "$k1/$k2 = \"$data{$k1}{$k2}\"";
900 }
901 }
902 37 ▶ if (scalar @non_numeric > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @non_numeric > 0) 1 36 37
903 1 p @non_numeric;
904 1 die "the above cells are not numbers, which $current_sub needs; leave a cell out, or undefined, to draw it in \"undef_color\"";
905 }
906 36 foreach my $k1 (@row_keys) {
907 68 my @cells;
908 68 foreach my $k2 (@cols) {
909 145 ▶ my $value = $data{$k1}{$k2} // $plot->{default_undefined};
Condition100%3/3
$data{$k1}{$k2} // $plot->{"default_undefined"}
l!l&&r!l&&!r
122419
MC/DC100%2/2
$data{$k1}{$k2} // $plot->{"default_undefined"}
$data{$k1}{$k2} $plot->{"default_undefined"}
Truth table100%3/3
A // B
A= $data{$k1}{$k2}B= $plot->{"default_undefined"}
ABresult
1X1
011
000
910 145 ▶ push @cells, defined $value ? py_num($value) : 'np.nan';
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 126 19 145
911 # A NaN or an infinity is drawn, but cannot be an end of the scale.
912 145 ▶ next unless ( defined $value ) && is_finite($value);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and is_finite($value) 20 125 145
Condition100%3/3
defined $value and is_finite($value)
!ll&&!rl&&r
191125
MC/DC100%2/2
defined $value and is_finite($value)
defined $value is_finite($value)
Truth table100%3/3
A and B
A= defined $valueB= is_finite($value)
ABresult
0X0
100
111
913 125 $min = min($min, $value);
914 125 $max = max($max, $value);
915 125 ▶ $min_positive = min($min_positive, $value) if $value > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $value > 0 120 5 125
916 125 $n_numeric++;
917 }
918 68 say {$args->{fh}} 'd.append([' . join( ',', @cells ) . '])';
919 }
920 # Nothing to scale the colors by. $min and $max are still the strings they
921 # started as, and "plt.Normalize(inf, -inf)" is a NameError in Python,
922 # which said nothing about the table being empty.
923 36 ▶ if (($n_numeric == 0) && ((not defined $plot->{cb_min}) || (not defined $plot->{cb_max}))) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_numeric == 0 and not defined $plot->{"cb_min"} && defined $plot->{"cb_max"}) 1 35 36
Condition50%3/6
$n_numeric == 0 and not defined $plot->{"cb_min"} && defined $plot->{"cb_max"}
!ll&&!rl&&r
3501
defined $plot->{'cb_min'} && defined $plot->{'cb_max'}
!ll&&!rl&&r
100
MC/DC33%1/3
$n_numeric == 0 and not defined $plot->{"cb_min"} && defined $plot->{"cb_max"}
$n_numeric == 0 defined $plot->{'cb_min'} defined $plot->{'cb_max'}
Truth table50%2/4
A and not(B && C)
A= $n_numeric == 0B= defined $plot->{'cb_min'}C= defined $plot->{'cb_max'}
ABCresult
0XX0
1110
10X1
1101
924 1 p $plot->{data};
925 1 die "no cell of the above data holds a number, so $current_sub has nothing to color by";
926 }
927 35 foreach my $opt (grep {defined $plot->{$_}} 'cb_min', 'cb_max'){
928 16 ▶ unless (looks_like_number( $plot->{$opt} )) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&looks_like_number($plot->{$opt})) 0 16 16
929 0 die "\"$opt\" = $plot->{$opt} must be a number";
930 }
931 # An end of the scale at infinity leaves no finite range to color by.
932 16 ▶ die "\"$opt\" = $plot->{$opt} must be a finite number" unless is_finite( $plot->{$opt} );
Branch: 1 branch
BranchTrueFalseTotal
unless is_finite($plot->{$opt}) 1 15 16
933 }
934 34 ▶ $plot->{cmap} = $plot->{cmap} // 'gist_rainbow';
Condition100%2/2
$plot->{"cmap"} // "gist_rainbow"
l!l
133
MC/DC100%1/1
$plot->{"cmap"} // "gist_rainbow"
$plot->{"cmap"}
Truth table100%2/2
A
A= $plot->{"cmap"}
Aresult
11
00
935 34 $plot->{cb_logscale} = bool_option( $plot->{cb_logscale}, 'cb_logscale', $current_sub );
936 34 ▶ my $ax = $args->{ax} // '';
Condition50%1/2
$args->{"ax"} // ""
l!l
340
MC/DC0%0/1
$args->{"ax"} // ""
$args->{"ax"}
Truth table50%1/2
A
A= $args->{"ax"}
Aresult
11
00
937 # One norm, used both to color the cells and by the hidden image that the
938 # colorbar is drawn from. The cells used to be colored through a linear
939 # plt.Normalize whatever "cb_logscale" said, so only the colorbar was
940 # logarithmic, and a table of 1, 10, 100 and 1000 drew three of its four
941 # cells in nearly the same color.
942 34 my $norm;
943 34 ▶ if ($plot->{cb_logscale}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{'cb_logscale'}) { } 4 30 34
944 # LogNorm refuses a vmin at or below 0; the one it chose for itself,
945 # when it was left to autoscale, was the smallest positive value.
946 4 ▶ $min = $plot->{cb_min} // $min_positive;
Condition66%2/3
$plot->{"cb_min"} // $min_positive
l!l&&r!l&&!r
130
MC/DC0%0/2
$plot->{"cb_min"} // $min_positive
$plot->{"cb_min"} $min_positive
Truth table66%2/3
A // B
A= $plot->{"cb_min"}B= $min_positive
ABresult
1X1
011
000
947 4 ▶ if ($min eq 'inf') {
Branch: 1 branch
BranchTrueFalseTotal
if ($min eq "inf") 0 4 4
948 0 die "\"cb_logscale\" needs a cell above 0 to start the scale at, or a \"cb_min\" above 0, and $current_sub has neither";
949 }
950 4 ▶ if ($min <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($min <= 0) 1 3 4
951 1 die "\"cb_logscale\" cannot start at \"cb_min\" = $min: a log scale needs a minimum above 0";
952 }
953 3 ▶ $max = $plot->{cb_max} // $max;
Condition33%1/3
$plot->{"cb_max"} // $max
l!l&&r!l&&!r
030
MC/DC0%0/2
$plot->{"cb_max"} // $max
$plot->{"cb_max"} $max
Truth table33%1/3
A // B
A= $plot->{"cb_max"}B= $max
ABresult
1X1
011
000
954 3 say {$args->{fh}} 'from matplotlib import colors';
955 3 $norm = 'colors.LogNorm(vmin = ' . py_num($min) . ', vmax = ' . py_num($max) . ')';
956 } else {
957 30 ▶ $min = $plot->{cb_min} // $min;
Condition66%2/3
$plot->{"cb_min"} // $min
l!l&&r!l&&!r
7230
MC/DC0%0/2
$plot->{"cb_min"} // $min
$plot->{"cb_min"} $min
Truth table66%2/3
A // B
A= $plot->{"cb_min"}B= $min
ABresult
1X1
011
000
958 30 ▶ $max = $plot->{cb_max} // $max;
Condition66%2/3
$plot->{"cb_max"} // $max
l!l&&r!l&&!r
7230
MC/DC0%0/2
$plot->{"cb_max"} // $max
$plot->{"cb_max"} $max
Truth table66%2/3
A // B
A= $plot->{"cb_max"}B= $max
ABresult
1X1
011
000
959 30 $norm = 'plt.Normalize(' . py_num($min) . ', ' . py_num($max) . ')'; # py_num: a cb_min such as "007" was written as given
960 }
961 33 ▶ $plot->{undef_color} = $plot->{undef_color} // 'gray';
Condition100%2/2
$plot->{"undef_color"} // "gray"
l!l
231
MC/DC100%1/1
$plot->{"undef_color"} // "gray"
$plot->{"undef_color"}
Truth table100%2/2
A
A= $plot->{"undef_color"}
Aresult
11
00
962 33 say {$args->{fh}} 'import matplotlib';
963 33 say {$args->{fh}} 'table_cmap = matplotlib.colormaps[' . py_str($plot->{cmap}) . '].copy()';
964 33 say {$args->{fh}} 'table_cmap.set_bad(' . py_str($plot->{undef_color}) . ')';
965 33 say {$args->{fh}} "norm = $norm";
966 33 say {$args->{fh}} 'datacolors = table_cmap(norm(d))';
967 33 say {$args->{fh}} "img = ax$ax.imshow(d, cmap=table_cmap, norm=norm)";
968 33 ▶ $plot->{colorbar_on} = bool_option( $plot->{colorbar_on} // 1, 'colorbar_on', $current_sub );
Condition100%2/2
$plot->{"colorbar_on"} // 1
l!l
924
MC/DC100%1/1
$plot->{"colorbar_on"} // 1
$plot->{"colorbar_on"}
Truth table100%2/2
A
A= $plot->{"colorbar_on"}
Aresult
11
00
969 # "colorbar_on" decides, and "cblabel" only says what to write on it. A
970 # cblabel used to draw the colorbar even against "colorbar_on => 0",
971 # which the documentation recorded rather than fixed: nobody passes a label
972 # for a colorbar they have just turned off, so it read as a typo that the
973 # module honoured.
974 33 ▶ if ($plot->{colorbar_on}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"colorbar_on"}) 27 6 33
975 # colorbar_args: the cb* options, documented as working here, were
976 # accepted and never written.
977 27 ▶ my $label = defined $plot->{cblabel} ? ', label = ' . py_str($plot->{cblabel}) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $plot->{'cblabel'} ? : 2 25 27
978 27 say {$args->{fh}} "fig.colorbar(img$label" . colorbar_args($plot) . ')';
979 }
980 33 say {$args->{fh}} 'img.set_visible(False)';
981 33 $plot->{show_numbers} = bool_option( $plot->{show_numbers}, 'show_numbers', $current_sub );
982 33 say {$args->{fh}} 'for ri, row in enumerate(d):';
983 33 say {$args->{fh}} ' for ii, item in enumerate(row):';
984 33 say {$args->{fh}} ' if np.isnan(item):';
985 33 say {$args->{fh}} ' d[ri][ii] = ""';
986 33 ▶ if ($plot->{show_numbers}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{'show_numbers'}) { } 2 31 33
987 2 say {$args->{fh}} "table = ax$ax" . '.table(cellText=d, rowLabels=[' . py_list(@rows) . '], colLabels = [' . py_list(@cols) . '], cellColours = datacolors, loc = "center", bbox=[0,0,1,1])';
988 } else {
989 31 say {$args->{fh}} "table = ax$ax" . '.table(rowLabels=[' . py_list(@rows) . '], colLabels = [' . py_list(@cols) . '], cellColours = datacolors, loc = "center", bbox=[0,0,1,1])';
990 }
991 # No title written here, though there was one: it emitted "ax0.title('..')",
992 # and "title" is a Text attribute of the axes rather than a method, so a
993 # colored_table given a title died with "TypeError: 'Text' object is not
994 # callable". plt() renames "title" to "set_title" for every plot type once
995 # its helper has run, which is what actually draws it.
996 # No logscale loop here, though there was one: "logscale" is not among the
997 # options colored_table accepts, so the loop could never run, and a log
998 # scale would mean nothing on a table whose axes are the row and column
999 # labels -- both sets of ticks are emptied a few lines below.
1000 # say {$args->{fh}} "fig.clim(vmin = $plot->{cb_min})" if defined $plot->{cb_min};
1001 # say {$args->{fh}} "fig.clim(vmax = $plot->{cb_max})" if defined $plot->{cb_max};
1002 33 foreach my $axis ('x','y') {
1003 66 say {$args->{fh}} "ax$ax.set_${axis}ticks" . '([])';
1004 66 say {$args->{fh}} "ax$ax.set_${axis}ticklabels" . '([])';
1005 }
1006 }
1007  
1008 34 ▶sub hexbin_helper {
Subroutine hexbin_helper: called CC=26 SCAR=32.8
Pod undocumented
1009 34 my ($args) = @_;
1010 34 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
1011 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
1012 34 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 34 34
1013 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
1014 }
1015 34 my @reqd_args = (
1016 'fh', # e.g. $py, $fh, which will be passed by the subroutine
1017 'plot', # args to original function
1018 );
1019 34 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
1020 34 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 34 34
1021 0 p @undef_args;
1022 0 die 'the above args are necessary, but were not defined.';
1023 }
1024 my @opt = (
1025 @ax_methods, @fig_methods, @arg, @plt_methods,
1026 34 'ax', @{ $opt{$current_sub} }
1027 );
1028 34 my $plot = $args->{plot};
1029 @undef_args = grep {
1030 236 my $key = $_;
1031 236 not grep { $_ eq $key } @opt
1032 34 } keys %{$plot};
1033 34 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 34 34
1034 bad_keyword_error({
1035 bad => \@undef_args,
1036 accepted => \@opt,
1037 preferred => $opt{$current_sub},
1038 type => $plot->{plot_type},
1039 0 sub => $current_sub
1040 });
1041 }
1042 34 cb_limits( $plot, $current_sub );
1043 34 $plot->{cb_logscale} = bool_option( $plot->{cb_logscale}, 'cb_logscale', $current_sub );
1044 34 ▶ $plot->{marginals} = $plot->{marginals} // 0;
Condition100%2/2
$plot->{"marginals"} // 0
l!l
133
MC/DC100%1/1
$plot->{"marginals"} // 0
$plot->{"marginals"}
Truth table100%2/2
A
A= $plot->{"marginals"}
Aresult
11
00
1045 34 bin_counts( $plot, $current_sub );
1046 30 my @keys;
1047 30 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 3 27 30
1048 @keys = check_key_order({
1049 keys => $plot->{key_order},
1050 data => $plot->{data},
1051 3 option => 'key_order',
1052 sub => $current_sub
1053 });
1054 } else {
1055 27 @keys = sort keys %{ $plot->{data} };
1056 }
1057 29 ▶ if ( scalar @keys != 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @keys != 2) 1 28 29
1058 1 p @keys;
1059 1 die "There must be exactly 2 keys for $current_sub";
1060 }
1061 28 my $n_points = scalar @{ $plot->{data}{ $keys[0] } };
1062 28 ▶ if ( scalar @{ $plot->{data}{ $keys[1] } } != $n_points ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$plot->{"data"}{$keys[1]};} != $n_points) 1 27 28
1063 1 say STDERR "\"$keys[0]\" has $n_points points.";
1064 say STDERR "\"$keys[1]\" has "
1065 1 . scalar @{ $plot->{data}{ $keys[1] } }
1066 . " points.";
1067 1 die 'The length of both keys must be equal.';
1068 }
1069 # Every point is written into the script as it stands, and nothing checked
1070 # them: an undefined one came out as an empty list element and a string
1071 # as a bare python name, each dying as a python error about the temp file.
1072 27 foreach my $key (@keys) {
1073 53 my @bad = grep { not looks_like_number( $plot->{data}{$key}[$_] ) } 0 .. $n_points - 1;
1074 53 ▶ next if scalar @bad == 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @bad == 0 51 2 53
1075 2 p @bad;
1076 2 die "\"$key\" is undefined or not a number at the above indices, which $current_sub needs";
1077 }
1078 # quoted here because the key is data: the pass-through path that title and
1079 # label text otherwise take cannot tell an apostrophe from Python of the
1080 # user's own, and leaves it bare. See py_str.
1081 25 default_axis_labels( $plot, @keys );
1082 25 ▶ $plot->{cmap} = $plot->{cmap} // 'gist_rainbow';
Condition100%2/2
$plot->{"cmap"} // "gist_rainbow"
l!l
124
MC/DC100%1/1
$plot->{"cmap"} // "gist_rainbow"
$plot->{"cmap"}
Truth table100%2/2
A
A= $plot->{"cmap"}
Aresult
11
00
1083 my $options =
1084 ", gridsize = ($plot->{xbins}, $plot->{ybins}), cmap = " . py_str($plot->{cmap})
1085 25 ; # these args go to the plt.hist call
1086 25 foreach my $opt ( grep { defined $plot->{$_} } ( 'vmin', 'vmax', 'mincnt' ) ) {
1087 9 ▶ if ( not looks_like_number( $plot->{$opt} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&looks_like_number($plot->{$opt})) 1 8 9
1088 1 die "\"$opt\" must be a number for $current_sub, but was given \"$plot->{$opt}\"";
1089 }
1090 }
1091 # A log scale cannot start at 0 or below, which LogNorm refused from inside
1092 # matplotlib, naming neither option.
1093 24 ▶ if ( ( $plot->{cb_logscale} ) && ( defined $plot->{vmin} ) && ( $plot->{vmin} <= 0 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"cb_logscale"} and defined $plot->{"vmin"} and $plot->{"vmin"} <= 0) 1 23 24
Condition100%6/6
$plot->{"cb_logscale"} and defined $plot->{"vmin"} and $plot->{"vmin"} <= 0
!ll&&!rl&&r
2211
$plot->{"cb_logscale"} and defined $plot->{"vmin"}
!ll&&!rl&&r
2112
MC/DC100%3/3
$plot->{"cb_logscale"} and defined $plot->{"vmin"} and $plot->{"vmin"} <= 0
$plot->{"cb_logscale"} defined $plot->{"vmin"} $plot->{"vmin"} <= 0
Truth table100%4/4
A and B and C
A= $plot->{"cb_logscale"}B= defined $plot->{"vmin"}C= $plot->{"vmin"} <= 0
ABCresult
0XX0
10X0
1100
1111
1094 1 die "\"cb_logscale\" cannot start at \"vmin\" = $plot->{vmin} in $current_sub: a log scale needs a minimum above 0";
1095 }
1096 # py_num, here and below: each was written as given, so "vmax => 'inf'",
1097 # which looks_like_number accepts, was a NameError in the script.
1098 23 ▶ if ( $plot->{cb_logscale} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{'cb_logscale'}) { } 2 21 23
1099 # vmin and vmax go to the LogNorm, as in hist2d_helper: passed beside
1100 # it they raised "ValueError: Passing a Normalize instance
1101 # simultaneously with vmin/vmax is not supported".
1102 2 say { $args->{fh} } 'from matplotlib.colors import LogNorm';
1103 2 my @lognorm_opt = map { "$_ = " . py_num( $plot->{$_} ) } grep { defined $plot->{$_} } ( 'vmin', 'vmax' );
1104 2 $options .= ', norm = LogNorm(' . join( ', ', @lognorm_opt ) . ')';
1105 2 foreach my $opt ( grep { defined $plot->{$_} } ('mincnt') ) {
1106 0 $options .= ", $opt = " . py_num( $plot->{$opt} );
1107 }
1108 } else {
1109 21 foreach my $opt ( grep { defined $plot->{$_} } ( 'vmin', 'vmax', 'mincnt' ) ) {
1110 5 $options .= ", $opt = " . py_num( $plot->{$opt} );
1111 }
1112 }
1113 23 foreach my $opt (grep {defined $plot->{$_} } ('xscale_hexbin', 'yscale_hexbin')) {
1114 2 ▶ if (($plot->{$opt} ne 'log') && ($plot->{$opt} ne 'linear')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{$opt} ne "log" and $plot->{$opt} ne "linear") 0 2 2
Condition33%1/3
$plot->{$opt} ne "log" and $plot->{$opt} ne "linear"
!ll&&!rl&&r
200
MC/DC0%0/2
$plot->{$opt} ne "log" and $plot->{$opt} ne "linear"
$plot->{$opt} ne "log" $plot->{$opt} ne "linear"
Truth table33%1/3
A and B
A= $plot->{$opt} ne "log"B= $plot->{$opt} ne "linear"
ABresult
0X0
100
111
1115 0 die "\"$opt\" is neither \"log\" nor \"linear\"";
1116 }
1117 2 my $opth = $opt;
1118 2 $opth =~ s/_hexbin$//; # "xscale_hexbin" is hexbin's own "xscale"
1119 2 $options .= ", $opth = '$plot->{$opt}'";
1120 }
1121 23 ▶ if ( bool_option( $plot->{marginals}, 'marginals', $current_sub ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (bool_option($plot->{"marginals"}, "marginals", $current_sub)) 1 22 23
1122 1 $options .= ', marginals = True';
1123 }
1124 23 say { $args->{fh} } 'x = ['
1125 23 . py_nums( @{ $plot->{data}{ $keys[0] } } ) . ']';
1126 23 say { $args->{fh} } 'y = ['
1127 23 . py_nums( @{ $plot->{data}{ $keys[1] } } ) . ']';
1128 23 ▶ my $ax = $args->{ax} // '';
Condition50%1/2
$args->{"ax"} // ""
l!l
230
MC/DC0%0/1
$args->{"ax"} // ""
$args->{"ax"}
Truth table50%1/2
A
A= $args->{"ax"}
Aresult
11
00
1129 23 say { $args->{fh} } "im$ax = ax$ax.hexbin(x, y $options)\n";
1130 23 my $opts = colorbar_args($plot); # cblabel is written below
1131 # "colorbar_on" is read here, and not only for the shared-colorbar test
1132 # above: the colorbar was drawn whatever it said, so "colorbar_on => 0"
1133 # did nothing, and a figure sharing one colorbar between subplots got the
1134 # shared one *and* the per-subplot one plt() had asked to be turned off.
1135 23 ▶ if ( $plot->{colorbar_on} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"colorbar_on"}) 21 2 23
1136 21 ▶ if ( defined $plot->{cblabel} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'cblabel'}) { } 1 20 21
1137 write_data({
1138 data => $plot->{cblabel},
1139 fh => $args->{fh},
1140 1 name => 'cblabel',
1141 });
1142 1 say { $args->{fh} } "plt.colorbar(im$ax, label = cblabel $opts)";
1143 } else {
1144 20 say { $args->{fh} } "plt.colorbar(im$ax, label = 'Density' $opts)";
1145 }
1146 }
1147 }
1148  
1149 146 ▶sub colorbar_args {
Subroutine colorbar_args: called CC=8 SCAR=20.8
Pod undocumented
1150 # The keyword arguments of a colorbar call that the cb* options and
1151 # "shared_colorbar" ask for, each led by ", ". "cblabel" is left to the
1152 # caller, since each helper has a default label of its own.
1153 #
1154 # hexbin, hist2d and imshow each wrote this out for themselves; scatter
1155 # and colored_table accepted the same options and wrote none of them.
1156 # Sets "colorbar_on" to its default, 1, as each of those did.
1157 146 my ($plot) = @_;
1158 146 my $opts = '';
1159 146 foreach my $o (grep {defined $plot->{$_}} ('cblocation', 'cborientation')) { # str
1160 6 my $mpl_opt = $o;
1161 6 $mpl_opt =~ s/^cb//;
1162 6 $opts .= ", $mpl_opt = " . py_str( $plot->{$o} );
1163 }
1164 146 foreach my $o (grep {defined $plot->{$_}} ('cbdrawedges', 'cbpad')) { # numeric
1165 8 ▶ die "$o = $plot->{$o} must be numeric" unless (looks_like_number($plot->{$o}));
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($plot->{$o}) 0 8 8
1166 8 my $mpl_opt = $o;
1167 8 $mpl_opt =~ s/^cb//;
1168 8 $opts .= ", $mpl_opt = " . py_num( $plot->{$o} );
1169 }
1170 # Read as a Python bool: tested for Perl truth, "colorbar_on => 'False'"
1171 # drew the colorbar.
1172 146 ▶ $plot->{colorbar_on} = bool_option( $plot->{colorbar_on} // 1, 'colorbar_on', "plot_type \"" . ( $plot->{plot_type} // '' ) . '"' );
Condition75%3/4
$plot->{"colorbar_on"} // 1
l!l
46100
$plot->{"plot_type"} // ""
l!l
1460
MC/DC100%1/1
$plot->{"colorbar_on"} // 1
$plot->{"colorbar_on"}
MC/DC0%0/1
$plot->{"plot_type"} // ""
$plot->{"plot_type"}
Truth table100%2/2
A
A= $plot->{"colorbar_on"}
Aresult
11
00
Truth table50%1/2
A
A= $plot->{"plot_type"}
Aresult
11
00
1173 146 ▶ if (($plot->{colorbar_on}) && (defined $plot->{shared_colorbar})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"colorbar_on"} and defined $plot->{"shared_colorbar"}) 10 136 146
Condition100%3/3
$plot->{"colorbar_on"} and defined $plot->{"shared_colorbar"}
!ll&&!rl&&r
1212410
MC/DC100%2/2
$plot->{"colorbar_on"} and defined $plot->{"shared_colorbar"}
$plot->{"colorbar_on"} defined $plot->{"shared_colorbar"}
Truth table100%3/3
A and B
A= $plot->{"colorbar_on"}B= defined $plot->{"shared_colorbar"}
ABresult
0X0
100
111
1174 10 my @ax = map {"ax$_"} @{ $plot->{shared_colorbar} };
1175 10 $opts .= ', ax = [' . join (',', @ax) . '] ';
1176 }
1177 146 return $opts;
1178 }
1179 sub format_commas
1180 61 ▶{ #($n, $format = '.%02d') { # https://stackoverflow.com/questions/33442240/perl-printf-to-use-commas-as-thousands-separator
Subroutine format_commas: called CC=2 SCAR=7.1
Pod undocumented
1181 # $format should be '%.0u' for integers
1182 61 my ( $n, $format ) = @_;
1183 61 ▶ $format = '.%02d' if not defined $format;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $format 0 61 61
1184 return
1185 61 reverse( join( ",", unpack( "(A3)*", reverse int($n) ) ) )
1186 . sprintf( $format, int( 100 * ( .005 + ( $n - int($n) ) ) ) );
1187 }
1188  
1189 19 ▶sub hist_value {
Subroutine hist_value: called CC=3 SCAR=11.0
Pod undocumented
1190 # A scalar "bins", "color" or "orientation" for hist(), as python.
1191 #
1192 # A number of bins is the one bare value; everything else is text. The
1193 # test this replaces quoted only /^[A-Za-z]+$/, so a color such as
1194 # "#ff0000" went in bare and python read the rest of the line as a comment,
1195 # and "tab:blue" or a grayscale "0.5" went in as python rather than as a
1196 # color.
1197 19 my ( $arg, $value ) = @_;
1198 19 ▶ return py_num($value) if ( $arg eq 'bins' ) && looks_like_number($value); # py_num: "010" bins was a SyntaxError
Branch: 1 branch
BranchTrueFalseTotal
if $arg eq "bins" and &looks_like_number($value) 7 12 19
Condition100%3/3
$arg eq "bins" and &looks_like_number($value)
!ll&&!rl&&r
1027
MC/DC100%2/2
$arg eq "bins" and &looks_like_number($value)
$arg eq "bins" &looks_like_number($value)
Truth table100%3/3
A and B
A= $arg eq "bins"B= &looks_like_number($value)
ABresult
0X0
100
111
1199 12 return py_str($value);
1200 }
1201 69 ▶sub hist_helper {
Subroutine hist_helper: called CC=30 SCAR=34.6
Pod undocumented
1202 69 my ($args) = @_;
1203 69 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
1204 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
1205 69 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 69 69
1206 0 die
1207 "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
1208 }
1209 69 my @reqd_args = (
1210 'ax', # used for multiple plots
1211 'fh', # e.g. $py, $fh, which will be passed by the subroutine
1212 'plot', # args to original function
1213 );
1214 69 my @undef = grep { !defined $args->{$_} } @reqd_args;
1215 69 ▶ if ( scalar @undef > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef > 0) 0 69 69
1216 0 p @undef;
1217 0 die 'the above args are necessary, but were not defined.';
1218 }
1219 69 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
1220 69 my $plot = $args->{plot};
1221 @undef = grep {
1222 352 my $key = $_;
1223 352 not grep { $_ eq $key } @opt
1224 69 } keys %{$plot};
1225 69 ▶ if ( scalar @undef > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef > 0) 0 69 69
1226 bad_keyword_error({
1227 bad => \@undef,
1228 accepted => \@opt,
1229 preferred => $opt{$current_sub},
1230 type => $plot->{plot_type},
1231 0 sub => $current_sub
1232 });
1233 }
1234 69 my $options = ''; # these args go to the plt.hist call
1235 69 ▶ $plot->{alpha} = $plot->{alpha} // 0.5;
Condition100%2/2
$plot->{"alpha"} // "0.5"
l!l
366
MC/DC100%1/1
$plot->{"alpha"} // "0.5"
$plot->{"alpha"}
Truth table100%2/2
A
A= $plot->{"alpha"}
Aresult
11
00
1236 69 check_numbers( [ $plot->{alpha} ], '"alpha"', $current_sub ); # written into every hist() call
1237 # Through py_num: "alpha => 'nan'" passes looks_like_number and was written
1238 # as given, a NameError in the script.
1239 68 my $alpha = py_num( $plot->{alpha} );
1240 # All the sets are drawn on one axes, so they share one orientation. A hash
1241 # was skipped as though it held a setting per set, and then never read.
1242 68 ▶ if ( ref $plot->{orientation} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"orientation"}) 1 67 68
1243 1 die "\"orientation\" is one of \"vertical\" or \"horizontal\" for every set in $current_sub, not a " . ref( $plot->{orientation} ) . ' reference';
1244 }
1245 # "color" is here as well as below: a single color for every set was
1246 # accepted and then never written, since only the per-set hash was read.
1247 67 foreach my $arg ( grep { defined $plot->{$_} } ( 'bins', 'color', 'orientation' ) ) {
1248 20 ▶ next if ref $plot->{$arg} eq 'HASH'; # set-specific setting exists
Branch: 1 branch
BranchTrueFalseTotal
if ref $plot->{$arg} eq "HASH" 7 13 20
1249 13 my $ref = ref $plot->{$arg};
1250 13 ▶ if ( $ref eq '' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($ref eq '') { } 10 3 13
elsif ($arg eq 'color') { } 1 2 3
elsif ($ref eq 'ARRAY') { } 2 0 2
1251 10 $options .= ", $arg = " . hist_value( $arg, $plot->{$arg} );
1252 } elsif ( $arg eq 'color' ) {
1253 # hist() is called once per set, so there is no position in a list
1254 # of colors that means a set; the hash names them.
1255 1 die "\"color\" for $current_sub is one color for every set, or a hash of one color per set, not a $ref reference";
1256 } elsif ( $ref eq 'ARRAY' ) {
1257 2 $options .= ", $arg = [" . py_nums( @{ $plot->{$arg} } ) . ']';
1258 } else {
1259 0 p $plot;
1260 0 die "$ref for $arg isn't acceptable";
1261 }
1262 }
1263 66 foreach my $axis ( logscale_axes( $plot->{logscale}, $current_sub ) ) { # x, y
1264 2 say {$args->{fh}} "ax$args->{ax}.set_$axis" . 'scale("log")';
1265 }
1266 63 ▶ if (ref $plot->{data} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"data"} eq "ARRAY") 12 51 63
1267 12 my $tmp = delete $plot->{data};
1268 12 $plot->{data}{A} = $tmp;
1269 }
1270 # A per-set "bins" or "color" keyed by a set that is not in "data" -- a
1271 # typo, most often -- was ignored, and that set drawn with the defaults.
1272 63 foreach my $arg ( grep { ref $plot->{$_} eq 'HASH' } ( 'bins', 'color' ) ) {
1273 7 my @stray = sort grep { not exists $plot->{data}{$_} } keys %{ $plot->{$arg} };
1274 7 ▶ next if scalar @stray == 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @stray == 0 5 2 7
1275 2 p @stray;
1276 2 die "the above keys of \"$arg\" are not sets of \"data\" in $current_sub";
1277 }
1278 # The order the sets are drawn in, and so the order of the legend. Sorted
1279 # by name before, with no way to change it, so the groups that "df" makes
1280 # with "by" came out with 10 before 2, though the documentation promised
1281 # numeric order.
1282 61 my @key_order;
1283 61 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 3 58 61
1284 @key_order = check_key_order({
1285 keys => $plot->{key_order},
1286 data => $plot->{data},
1287 3 option => 'key_order',
1288 sub => $current_sub
1289 });
1290 } else {
1291 58 @key_order = sort keys %{ $plot->{data} };
1292 }
1293 61 ▶ if (scalar keys %{ $plot->{data} } > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$$plot{'data'};} > 1) { } 16 45 61
1294 16 ▶ $plot->{show_legend} = bool_option( $plot->{show_legend} // 1, 'show_legend', $current_sub );
Condition100%2/2
$plot->{"show_legend"} // 1
l!l
115
MC/DC100%1/1
$plot->{"show_legend"} // 1
$plot->{"show_legend"}
Truth table100%2/2
A
A= $plot->{"show_legend"}
Aresult
11
00
1295 } else {
1296 45 ▶ $plot->{show_legend} = bool_option( $plot->{show_legend} // 0, 'show_legend', $current_sub );
Condition100%2/2
$plot->{"show_legend"} // 0
l!l
144
MC/DC100%1/1
$plot->{"show_legend"} // 0
$plot->{"show_legend"}
Truth table100%2/2
A
A= $plot->{"show_legend"}
Aresult
11
00
1297 }
1298 # Every bin height drawn into this subplot goes into hist_counts<ax>, for
1299 # the range that plt() reports once the subplot is drawn; see
1300 # hist_range_report. Named for the subplot because a figure's subplots all
1301 # write into the one script, in order, and each has to report its own range.
1302 61 foreach my $set (@key_order) {
1303 77 my @non_numeric = grep {not looks_like_number($_)} @{ $plot->{data}{$set} };
1304 77 ▶ if (scalar @non_numeric > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @non_numeric > 0) 1 76 77
1305 1 p @non_numeric;
1306 1 die "$set has non-numeric values; which for hist must be numeric";
1307 }
1308 # NaN is left for matplotlib, which bins around it; an infinity leaves it
1309 # no finite range to bin, and died as "supplied range of [1.0, inf] is not
1310 # finite".
1311 76 ▶ my @infinite = grep { not ( is_nan($_) || is_finite($_) ) } @{ $plot->{data}{$set} };
Condition66%2/3
is_nan($_) || is_finite($_)
l!l&&r!l&&!r
05371
MC/DC50%1/2
is_nan($_) || is_finite($_)
is_nan($_) is_finite($_)
Truth table66%2/3
A || B
A= is_nan($_)B= is_finite($_)
ABresult
1X1
011
000
1312 76 ▶ if (scalar @infinite > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @infinite > 0) 1 75 76
1313 1 p @infinite;
1314 1 die "$set has the above infinite values, which $current_sub cannot bin";
1315 }
1316 75 my $set_options = '';
1317 75 foreach
1318 150 my $arg ( grep { ref $plot->{$_} eq 'HASH' } ( 'bins', 'color' ) )
1319 {
1320 10 ▶ next unless defined $plot->{$arg}{$set};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $plot->{$arg}{$set} 0 10 10
1321 10 my $ref = ref $plot->{$arg}{$set};
1322 10 ▶ if ( ( $ref eq 'ARRAY' ) && ( $arg eq 'color' ) ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($ref eq 'ARRAY' and $arg eq 'color') { } 0 10 10
elsif ($ref eq 'ARRAY') { } 1 9 10
elsif ($ref ne '') { } 0 9 9
Condition66%2/3
$ref eq "ARRAY" and $arg eq "color"
!ll&&!rl&&r
910
MC/DC0%0/2
$ref eq "ARRAY" and $arg eq "color"
$ref eq "ARRAY" $arg eq "color"
Truth table66%2/3
A and B
A= $ref eq "ARRAY"B= $arg eq "color"
ABresult
0X0
100
111
1323 0 die "\"color\" for set \"$set\" is an array, but $current_sub draws each set in one color";
1324 } elsif ( $ref eq 'ARRAY' ) {
1325 # Bin edges for this set alone. The whole-plot "bins" has taken
1326 # an array since it was written; per set it fell through to the
1327 # single-value branch below and emitted "bins = ARRAY(0x55f0...)".
1328 1 $set_options .= ", $arg = [" . py_nums( @{ $plot->{$arg}{$set} } ) . ']';
1329 } elsif ( $ref ne '' ) {
1330 0 p $plot->{$arg};
1331 0 die "\"$arg\" for set \"$set\" is a $ref reference, but $current_sub takes a scalar or an array there";
1332 } else {
1333 9 $set_options .= ", $arg = " . hist_value( $arg, $plot->{$arg}{$set} );
1334 }
1335 }
1336 75 say {$args->{fh}} 'd = [' . py_nums( @{ $plot->{data}{$set} } ) . ']';
1337 # hist() returns (counts, bin edges, patches); the counts are the only
1338 # way to know a bin's height, since matplotlib, not this module, does
1339 # the binning. Naming them changes nothing about what is drawn.
1340 75 ▶ if ($plot->{show_legend}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{'show_legend'}) { } 30 45 75
1341 30 say { $args->{fh} } "hist_n, hist_edges, hist_patches = ax$args->{ax}.hist(d, alpha = $alpha, label = " . py_str($set) . " $options $set_options)";
1342 } else {
1343 45 say { $args->{fh} } "hist_n, hist_edges, hist_patches = ax$args->{ax}.hist(d, alpha = $alpha $options $set_options)";
1344 }
1345 75 say {$args->{fh}} "hist_counts$args->{ax} += list(hist_n)";
1346 }
1347 }
1348 712 ▶sub has_hist {
Subroutine has_hist: called CC=5 SCAR=17.0
Pod undocumented
1349 # Whether a plot, or one of its "add" graphs, is a hist. An "add" graph
1350 # with no "plot_type" of its own takes $type, the plot's.
1351 712 my ( $plot, $type ) = @_;
1352 712 ▶ my @graphs = ( $plot, ( ref $plot->{add} eq 'ARRAY' ) ? @{ $plot->{add} } : () );
Branch: 1 branch
BranchTrueFalseTotal
ref $plot->{'add'} eq 'ARRAY' ? : 109 603 712
1353 712 ▶ return scalar grep { ( ref $_ eq 'HASH' ) && ( ( $_->{plot_type} // $type // '' ) eq 'hist' ) } @graphs;
Condition50%4/8
ref $_ eq 'HASH' && (($_->{'plot_type'} // $type) // '') eq 'hist'
!ll&&!rl&&r
066469
($_->{"plot_type"} // $type) // ""
l!l
7330
$_->{"plot_type"} // $type
l!l&&r!l&&!r
73300
MC/DC0%0/3
ref $_ eq 'HASH' && (($_->{'plot_type'} // $type) // '') eq 'hist'
ref $_ eq 'HASH' $_->{"plot_type"} $type
Truth table25%1/4
A && B // C
A= ref $_ eq 'HASH'B= $_->{"plot_type"}C= $type
ABCresult
0XX0
1000
11X1
1011
1354 }
1355 116 ▶sub hist_range_report {
Subroutine hist_range_report: called CC=2 SCAR=6.9
Pod undocumented
1356 # Python that starts ($when = 'start') or reports ($when = 'report') the
1357 # range of the bin heights of every hist drawn into subplot $ax.
1358 #
1359 # plt() calls this around the whole subplot -- its "add" graphs and its own
1360 # plot -- rather than hist_helper around each hist, which reset the list for
1361 # each: a subplot with a hist overlay printed two ranges, the second
1362 # leaving out the overlay's bins, where one range over all its sets is
1363 # what the documentation promises.
1364 #
1365 # On STDOUT and nowhere else: nothing here is handed to matplotlib, so the
1366 # figure written to "output_file" is exactly what it was without this.
1367 # plt() prints the script's STDOUT back out.
1368 116 my ( $fh, $ax, $when ) = @_;
1369 116 ▶ if ( $when eq 'start' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($when eq "start") 63 53 116
1370 63 say {$fh} "hist_counts$ax = []";
1371 63 return;
1372 }
1373 # "%g" because hist() hands back its counts as float64, and "[1, 12]" for a
1374 # tally of whole things is what was counted; "[1.0, 12.0]" reads as though
1375 # it were not.
1376 # An empty subplot has no bins at all, and min() of an empty list raises
1377 # ValueError, so there is nothing to report.
1378 53 say {$fh} "if len(hist_counts$ax) > 0:";
1379 53 say {$fh} "\tprint(f'plot $ax hist range = [{min(hist_counts$ax):g}, {max(hist_counts$ax):g}]')";
1380 }
1381  
1382 43 ▶sub hist2d_helper {
Subroutine hist2d_helper: called CC=37 SCAR=37.4
Pod undocumented
1383 43 my ($args) = @_;
1384 43 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
1385 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
1386 43 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 43 43
1387 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
1388 }
1389 43 my @reqd_args = (
1390 'fh', # e.g. $py, $fh, which will be passed by the subroutine
1391 'plot', # args to original function
1392 );
1393 43 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
1394 43 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 43 43
1395 0 p @undef_args;
1396 0 die 'the above args are necessary, but were not defined.';
1397 }
1398 43 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
1399 43 my $plot = $args->{plot};
1400 @undef_args = grep {
1401 309 my $key = $_;
1402 309 not grep { $_ eq $key } @opt
1403 43 } keys %{$plot};
1404 43 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 43 43
1405 bad_keyword_error({
1406 bad => \@undef_args,
1407 accepted => \@opt,
1408 preferred => $opt{$current_sub},
1409 type => $plot->{plot_type},
1410 0 sub => $current_sub
1411 });
1412 }
1413 43 cb_limits( $plot, $current_sub );
1414 43 $plot->{cb_logscale} = bool_option( $plot->{cb_logscale}, 'cb_logscale', $current_sub );
1415 43 ▶ $plot->{show_colorbar} = bool_option( $plot->{show_colorbar} // 1, 'show_colorbar', $current_sub );
Condition100%2/2
$plot->{"show_colorbar"} // 1
l!l
241
MC/DC100%1/1
$plot->{"show_colorbar"} // 1
$plot->{"show_colorbar"}
Truth table100%2/2
A
A= $plot->{"show_colorbar"}
Aresult
11
00
1416 43 bin_counts( $plot, $current_sub );
1417 41 my @keys;
1418 41 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 2 39 41
1419 @keys = check_key_order({
1420 keys => $plot->{key_order},
1421 data => $plot->{data},
1422 2 option => 'key_order',
1423 sub => $current_sub
1424 });
1425 } else {
1426 39 @keys = sort keys %{ $plot->{data} };
1427 }
1428 40 ▶ if ( scalar @keys != 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @keys != 2) 0 40 40
1429 0 p @keys;
1430 0 die "There must be exactly 2 keys for $current_sub";
1431 }
1432 40 my $n_points = scalar @{ $plot->{data}{ $keys[0] } };
1433 40 ▶ if ( scalar @{ $plot->{data}{ $keys[1] } } != $n_points ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$plot->{"data"}{$keys[1]};} != $n_points) 0 40 40
1434 0 say STDERR "$keys[0] has $n_points points.";
1435 say STDERR "$keys[1] has "
1436 0 . scalar @{ $plot->{data}{ $keys[1] } }
1437 . " points.";
1438 0 die 'The length of both keys must be equal.';
1439 }
1440 # quoted here because the key is data: the pass-through path that title and
1441 # label text otherwise take cannot tell an apostrophe from Python of the
1442 # user's own, and leaves it bare. See py_str.
1443 40 default_axis_labels( $plot, @keys );
1444 40 ▶ $plot->{cmap} = $plot->{cmap} // 'gist_rainbow';
Condition100%2/2
$plot->{"cmap"} // "gist_rainbow"
l!l
238
MC/DC100%1/1
$plot->{"cmap"} // "gist_rainbow"
$plot->{"cmap"}
Truth table100%2/2
A
A= $plot->{"cmap"}
Aresult
11
00
1445 40 my $options = ', cmap = ' . py_str($plot->{cmap}); # these args go to the plt.hist call
1446 40 ▶ if ( $plot->{cb_logscale} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"cb_logscale"}) 4 36 40
1447 4 say {$args->{fh}} 'from matplotlib.colors import LogNorm';
1448 # prevents "ValueError: Passing a Normalize instance simultaneously with vmin/vmax is not supported. Please pass vmin/vmax directly to the norm when creating it"
1449 4 my @logNorm_opt;
1450 4 foreach my $arg (grep {defined $plot->{$_}} ('vmin', 'vmax')) {
1451 2 ▶ if (not looks_like_number($plot->{$arg})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&looks_like_number($plot->{$arg})) 0 2 2
1452 0 die "$arg must be numeric for $current_sub, but was given \"$plot->{$arg}\"";
1453 }
1454 2 ▶ if ( ( $arg eq 'vmin' ) && ( $plot->{$arg} <= 0 ) ) { # as in hexbin_helper
Branch: 1 branch
BranchTrueFalseTotal
if ($arg eq "vmin" and $plot->{$arg} <= 0) 0 2 2
Condition66%2/3
$arg eq "vmin" and $plot->{$arg} <= 0
!ll&&!rl&&r
110
MC/DC0%0/2
$arg eq "vmin" and $plot->{$arg} <= 0
$arg eq "vmin" $plot->{$arg} <= 0
Truth table66%2/3
A and B
A= $arg eq "vmin"B= $plot->{$arg} <= 0
ABresult
0X0
100
111
1455 0 die "\"cb_logscale\" cannot start at \"vmin\" = $plot->{$arg} in $current_sub: a log scale needs a minimum above 0";
1456 }
1457 2 push @logNorm_opt, "$arg = " . py_num( $plot->{$arg} ); # py_num: "vmax => 'inf'" was a NameError
1458 2 delete $plot->{$arg};
1459 }
1460 4 $options .= ', norm = LogNorm(' . join (',', @logNorm_opt) . ')';
1461 }
1462 # Checked here as the log-scale branch above checks its own: each was
1463 # written as given, so "vmin => 'low'" left "vmin = low" in the script.
1464 40 foreach my $opt ( grep { defined $plot->{$_} } ( 'cmin', 'cmax', 'vmin', 'vmax' ) ) {
1465 8 check_numbers( [ $plot->{$opt} ], "\"$opt\"", $current_sub );
1466 6 $options .= ", $opt = " . py_num( $plot->{$opt} );
1467 }
1468 38 ▶ if ( defined $plot->{density} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"density"}) 2 36 38
1469 2 ▶ $options .= ', density = ' . ( bool_option( $plot->{density}, 'density', $current_sub ) ? 'True' : 'False' );
Branch: 1 branch
BranchTrueFalseTotal
bool_option($plot->{'density'}, 'density', $current_sub) ? : 2 0 2
1470 }
1471 38 my @bad_indices;
1472 38 my $bad_pts = 0;
1473 38 foreach my $i (0,1) {
1474 76 @{ $bad_indices[$i] } = grep {not defined $plot->{data}{$keys[$i]}[$_]} 0..$n_points-1;
1475 76 $bad_pts += scalar @{ $bad_indices[$i] };
1476 }
1477 38 ▶ if ($bad_pts > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bad_pts > 0) 0 38 38
1478 0 say STDERR "the above args have the following indices undefined ($n_points total)";
1479 0 p @bad_indices;
1480 0 die "Cannot proceed as there are $bad_pts undefined points.";
1481 }
1482 38 foreach my $i (0,1) {
1483 76 @{ $bad_indices[$i] } = grep {not looks_like_number($plot->{data}{$keys[$i]}[$_])} 0..$n_points-1;
1484 76 $bad_pts += scalar @{ $bad_indices[$i] };
1485 }
1486 38 ▶ if ($bad_pts > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bad_pts > 0) 0 38 38
1487 0 p $args;
1488 0 say STDERR "the above args have the following indices non-numeric ($n_points total)";
1489 0 p @bad_indices;
1490 0 die "Cannot proceed as there are $bad_pts non-numeric points.";
1491 }
1492 38 say { $args->{fh} } 'x = ['
1493 38 . py_nums( @{ $plot->{data}{ $keys[0] } } ) . ']';
1494 38 say { $args->{fh} } 'y = ['
1495 38 . py_nums( @{ $plot->{data}{ $keys[1] } } ) . ']';
1496 # The ends of the range binned over, each the caller's or the data's own.
1497 # Nothing here was checked, and each was written as given: "xmin => 'a'"
1498 # was a NameError, a column with no finite value left an undefined end that
1499 # died as "Use of uninitialized value in concatenation", and a log axis
1500 # that reached 0 died inside np.log10 as "invalid entry in coordinates
1501 # array".
1502 38 my %log_axis = map { $_ => 1 } logscale_axes( $plot->{logscale}, $current_sub );
1503 36 foreach my $i ( 0, 1 ) {
1504 68 my $axis = ( 'x', 'y' )[$i];
1505 68 my @finite = finite_values( @{ $plot->{data}{ $keys[$i] } } );
1506 68 foreach my $end ( 'min', 'max' ) {
1507 134 my $opt = "$axis$end";
1508 134 ▶ if ( defined $plot->{$opt} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $plot->{$opt}) { } 8 126 134
elsif (scalar @finite == 0) { } 1 125 126
1509 8 check_numbers( [ $plot->{$opt} ], "\"$opt\"", $current_sub );
1510 7 ▶ die "\"$opt\" must be a finite number for $current_sub, not \"$plot->{$opt}\"" unless is_finite( $plot->{$opt} );
Branch: 1 branch
BranchTrueFalseTotal
unless is_finite($plot->{$opt}) 0 7 7
1511 } elsif ( scalar @finite == 0 ) {
1512 1 die "\"$keys[$i]\" has no finite value, so $current_sub has no range to bin it over; give \"${axis}min\" and \"${axis}max\"";
1513 } else {
1514 125 ▶ $plot->{$opt} = ( $end eq 'min' ) ? min(@finite) : max(@finite);
Branch: 1 branch
BranchTrueFalseTotal
$end eq 'min' ? : 62 63 125
1515 }
1516 }
1517 66 my ( $lo, $hi ) = @{$plot}{ "${axis}min", "${axis}max" };
1518 66 ▶ if ( $lo > $hi ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lo > $hi) 1 65 66
1519 1 die "\"${axis}min\" = $lo is above \"${axis}max\" = $hi in $current_sub";
1520 }
1521 65 ▶ if ( ( $log_axis{$axis} ) && ( $lo <= 0 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($log_axis{$axis} and $lo <= 0) 1 64 65
Condition100%3/3
$log_axis{$axis} and $lo <= 0
!ll&&!rl&&r
5951
MC/DC100%2/2
$log_axis{$axis} and $lo <= 0
$log_axis{$axis} $lo <= 0
Truth table100%3/3
A and B
A= $log_axis{$axis}B= $lo <= 0
ABresult
0X0
100
111
1522 1 die "\"logscale\" puts $axis on a log scale, which cannot start at $lo in $current_sub: give a \"${axis}min\" above 0";
1523 }
1524 }
1525 32 my %end = map { $_ => py_num( $plot->{$_} ) } ( 'xmin', 'xmax', 'ymin', 'ymax' );
1526 32 ▶ my $ax = $args->{ax} // '';
Condition50%1/2
$args->{"ax"} // ""
l!l
320
MC/DC0%0/1
$args->{"ax"} // ""
$args->{"ax"}
Truth table50%1/2
A
A= $args->{"ax"}
Aresult
11
00
1527 # the range argument ensures that there are no empty parts of the plot
1528 32 my $range = ", range = [($end{xmin}, $end{xmax}), ($end{ymin}, $end{ymax})]";
1529 # logscale complications
1530 32 say {$args->{fh}} 'import numpy as np';
1531 # Bin edges, one more than the bins: "xbins" and "ybins" count bins, as
1532 # they do on a linear plot, where they go to hist2d as counts. They were
1533 # written as the number of edges, so a log axis had one bin fewer than it
1534 # asked for, and "xbins => 1" gave one edge, no bins at all, and died in
1535 # np.max as "zero-size array". The test is on the axes, not on "logscale"
1536 # itself, which as an empty array was true and took this branch for none.
1537 32 ▶ if ( scalar keys %log_axis ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %log_axis) { } 5 27 32
1538 5 foreach my $axis ( 'x', 'y' ) {
1539 10 my $min = $end{ $axis . 'min' };
1540 10 my $max = $end{ $axis . 'max' };
1541 10 my $edges = $plot->{"${axis}bins"} + 1;
1542 10 ▶ if ( $log_axis{$axis} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($log_axis{$axis}) { } 5 5 10
1543 5 say {$args->{fh}} "ax$ax.set_$axis" . 'scale("log")';
1544 5 say {$args->{fh}} "${axis}bins = np.logspace(np.log10($min), np.log10($max), $edges)";
1545 } else {
1546 5 say {$args->{fh}} "${axis}bins = np.linspace($min, $max, $edges)";
1547 }
1548 }
1549 5 $options = ", bins = [xbins, ybins] $options";
1550 } else {
1551 27 $options = ", ($plot->{xbins}, $plot->{ybins}) $options";
1552 }
1553 32 say {$args->{fh}} "hist2d_n, hist2d_xedges, hist2d_yedges, im$ax = ax$ax.hist2d(x, y $options $range)";
1554 32 say {$args->{fh}} 'max_hist2d_box = np.max(hist2d_n)';
1555 32 say {$args->{fh}} 'min_hist2d_box = np.min(hist2d_n)';
1556 32 say {$args->{fh}} "print(f'plot $ax hist2d density range = [{min_hist2d_box}, {max_hist2d_box}]')";
1557 32 ▶ return 0 if $plot->{show_colorbar} == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $plot->{"show_colorbar"} == 0 2 30 32
1558 30 my $opts = colorbar_args($plot); # cblabel is written below
1559 # say { $args->{fh} } "cbar = fig.colorbar(im$ax $opts)" if $plot->{colorbar_on};
1560 # As in hexbin_helper: "colorbar_on" used to be read only for the shared
1561 # colorbar, so "colorbar_on => 0" drew one anyway and the documentation
1562 # had to tell the reader to use "show_colorbar" instead. Both now work, and
1563 # a subplot whose colorbar plt() turns off for sharing stays off.
1564 30 ▶ if ( $plot->{colorbar_on} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"colorbar_on"}) 28 2 30
1565 28 ▶ if ( defined $plot->{cblabel} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'cblabel'}) { } 2 26 28
1566 2 say { $args->{fh} } "plt.colorbar(im$ax, label = " . py_str($plot->{cblabel}) . " $opts)";
1567 } else {
1568 26 say { $args->{fh} } "plt.colorbar(im$ax, label = 'Density' $opts)";
1569 }
1570 }
1571 }
1572  
1573 44 ▶sub imshow_helper {
Subroutine imshow_helper: called CC=44 SCAR=38.0
Pod undocumented
1574 44 my ($args) = @_;
1575 44 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
1576 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
1577 44 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 44 44
1578 0 die
1579 "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
1580 }
1581 44 my @reqd_args = (
1582 'ax',
1583 'fh', # e.g. $py, $fh, which will be passed by the subroutine
1584 'plot', # args to original function
1585 );
1586 44 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
1587 44 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 44 44
1588 0 p @undef_args;
1589 0 die 'the above args are necessary, but were not defined.';
1590 }
1591 44 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
1592 44 my $plot = $args->{plot};
1593 @undef_args = grep {
1594 290 my $key = $_;
1595 290 not grep { $_ eq $key } @opt
1596 44 } keys %{$plot};
1597 44 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 44 44
1598 bad_keyword_error({
1599 bad => \@undef_args,
1600 accepted => \@opt,
1601 preferred => $opt{$current_sub},
1602 type => $plot->{plot_type},
1603 0 sub => $current_sub
1604 });
1605 }
1606 44 cb_limits( $plot, $current_sub );
1607 43 my $data_ref = ref $plot->{data};
1608 43 ▶ if ($data_ref ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($data_ref ne "ARRAY") 2 41 43
1609 2 p $args;
1610 2 die "$current_sub can only accept 2-D arrays as input in \"data\", but received $data_ref";
1611 }
1612 # An empty image is refused here, by name: it has nothing to draw, and it
1613 # used to reach Python as "vmin = inf", a NameError about nothing in the
1614 # data.
1615 41 my @bad_rows = grep { ref $plot->{data}[$_] ne 'ARRAY' } 0 .. $#{ $plot->{data} };
1616 41 ▶ if (scalar @bad_rows > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_rows > 0) 0 41 41
1617 0 p @bad_rows;
1618 0 die "the above rows of \"data\" are not array references, which $current_sub needs";
1619 }
1620 41 ▶ if ((scalar @{ $plot->{data} } == 0) || (scalar grep { scalar @{$_} > 0 } @{ $plot->{data} }) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$plot->{"data"};} == 0 or scalar grep({scalar @{$_;} > 0;} @{$$plot{"data"};}) == 0) 1 40 41
Condition66%2/3
scalar @{$plot->{"data"};} == 0 or scalar grep({scalar @{$_;} > 0;} @{$$plot{"data"};}) == 0
l!l&&r!l&&!r
1040
MC/DC50%1/2
scalar @{$plot->{"data"};} == 0 or scalar grep({scalar @{$_;} > 0;} @{$$plot{"data"};}) == 0
scalar @{$plot->{"data"};} == 0 scalar grep({scalar @{$_;} > 0;} @{$$plot{"data"};}) == 0
Truth table66%2/3
A or B
A= scalar @{$plot->{"data"};} == 0B= scalar grep({scalar @{$_;} > 0;} @{$$plot{"data"};}) == 0
ABresult
1X1
011
000
1621 1 die "$current_sub was given no data to draw";
1622 }
1623 # Every row the same length: numpy refused a ragged image from inside
1624 # matplotlib, as "setting an array element with a sequence ... inhomogeneous
1625 # shape", which named no row.
1626 40 my %row_lengths;
1627 40 $row_lengths{ scalar @{$_} } = 1 foreach @{ $plot->{data} };
1628 40 ▶ if ( scalar keys %row_lengths > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %row_lengths > 1) 1 39 40
1629 die "the rows of \"data\" have different lengths ("
1630 1 . join( ', ', map { scalar @{ $plot->{data}[$_] } } 0 .. $#{ $plot->{data} } )
1631 . "), but $current_sub draws a rectangle of cells";
1632 }
1633 # An undefined cell, refused by name. It was counted as a string, and
1634 # without a "stringmap" the image died as needing "a map to translate
1635 # strings to integers", for numeric data that held no strings.
1636 39 my @undef_cells;
1637 39 foreach my $r ( 0 .. $#{ $plot->{data} } ) {
1638 126 push @undef_cells, map { "[$r][$_]" } grep { not defined $plot->{data}[$r][$_] } 0 .. $#{ $plot->{data}[$r] };
1639 }
1640 39 ▶ if ( scalar @undef_cells > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_cells > 0) 1 38 39
1641 1 ▶ splice @undef_cells, 5, scalar(@undef_cells) - 5, '...' if scalar @undef_cells > 5; # enough to find them by
Branch: 1 branch
BranchTrueFalseTotal
if scalar @undef_cells > 5 0 1 1
1642 1 die "$current_sub cannot draw an undefined cell, and \"data\" has them at " . join( ', ', @undef_cells ) . '; a NaN is drawn as an empty cell';
1643 }
1644 38 my $non_numeric_data = 0;
1645 38 my $any_nonfinite = 0; # 1 once a value of a numeric image is NaN or infinite
1646 38 foreach my $row (@{ $plot->{data} }) {
1647 113 ▶ if (grep {not looks_like_number($_)} @{ $row }) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {not &looks_like_number($_);} @{$row;}) 12 101 113
1648 12 $non_numeric_data = 1;
1649 12 last;
1650 }
1651 }
1652 38 $plot->{cb_logscale} = bool_option( $plot->{cb_logscale}, 'cb_logscale', $current_sub );
1653 38 ▶ if (($non_numeric_data) && (not defined $plot->{stringmap})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($non_numeric_data and not defined $plot->{"stringmap"}) 1 37 38
Condition100%3/3
$non_numeric_data and not defined $plot->{"stringmap"}
!ll&&!rl&&r
26111
MC/DC100%2/2
$non_numeric_data and not defined $plot->{"stringmap"}
$non_numeric_data not defined $plot->{"stringmap"}
Truth table100%3/3
A and not(B)
A= $non_numeric_dataB= not defined $plot->{"stringmap"}
ABresult
0X0
100
111
1654 1 p $args;
1655 1 die "$current_sub needs a map to translate strings to integers";
1656 }
1657 # Each key of stringmap gets an integer, in sorted order. The integers come
1658 # from a range, not from "scalar @ytick_labels" as they were: perl returns
1659 # the count of an empty array as a shared 0 that also carries the string
1660 # "0", the first category's 0 was copied from it, and JSON::XS -- which
1661 # JSON::MaybeXS uses when it has no Cpanel::JSON::XS -- wrote it as "0".
1662 # One string among the integers made numpy read the whole image as text,
1663 # and imshow died as "Image data of dtype <U21 cannot be converted to
1664 # float".
1665 37 my @strings = sort keys %{ $plot->{stringmap} };
1666 37 my %intmap = map { $strings[$_] => $_ } 0 .. $#strings;
1667 37 my @ytick_labels = @{ $plot->{stringmap} }{@strings};
1668 # The rows drawn: the caller's own, or for string data a translated copy.
1669 # The strings used to be replaced in place, so the caller's array came back
1670 # holding integers; and a string that "stringmap" did not name became an
1671 # undefined cell, drawn blank with nothing said.
1672 37 my $data = $plot->{data};
1673 37 ▶ if ($non_numeric_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($non_numeric_data) { } 11 26 37
1674 11 my %unmapped;
1675 11 foreach my $row (@{ $data }) {
1676 21 ▶ $unmapped{ $_ // 'undef' }++ foreach grep { ( not defined $_ ) || ( not defined $intmap{$_} ) } @{ $row };
Condition60%3/5
defined $_ && defined $intmap{$_}
!ll&&!rl&&r
0159
$_ // "undef"
l!l
10
MC/DC50%1/2
defined $_ && defined $intmap{$_}
defined $_ defined $intmap{$_}
MC/DC0%0/1
$_ // "undef"
$_
Truth table66%2/3
A && B
A= defined $_B= defined $intmap{$_}
ABresult
0X0
100
111
Truth table50%1/2
A
A= $_
Aresult
11
00
1677 }
1678 11 ▶ if (scalar keys %unmapped > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %unmapped > 0) 1 10 11
1679 1 my @unmapped = sort keys %unmapped;
1680 1 p @unmapped;
1681 1 die "the above values of \"data\" are not keys of \"stringmap\", which $current_sub needs to give each one a color";
1682 }
1683 10 $data = [ map { [ map { $intmap{$_} } @{ $_ } ] } @{ $data } ];
1684 } else {
1685 # Numbers as numbers. write_data sends "d" through JSON, which writes a
1686 # scalar last used as a string -- a row split from a line of a file -- as
1687 # a JSON string, and numpy refused such rows as "Image data of dtype <U1
1688 # cannot be converted to float". A copy, since the rows are the caller's.
1689 # JSON has no NaN or infinity, and the encoder writes both as null, which
1690 # numpy refused as "Image data of dtype object"; they travel as the
1691 # strings "nan", "inf" and "-inf" instead, which the float conversion
1692 # written after the data below reads back as the numbers they were.
1693 #
1694 # Whether any value is not finite is noted as each is copied. It was
1695 # looked for afterwards with a regex over every value, which gave each
1696 # number a string as well, and for a 1500 x 1500 image cost 0.2 s and
1697 # about 140 MB.
1698 26 ▶ $data = [ map { [ map { my $name = nonfinite_name($_); $any_nonfinite = 1 if defined $name; $name // 0 + $_ } @{ $_ } ] } @{ $data } ];
Branch: 1 branch
BranchTrueFalseTotal
if defined $name 4 636 640
Condition100%2/2
$name // 0 + $_
l!l
4636
MC/DC100%1/1
$name // 0 + $_
$name
Truth table100%2/2
A
A= $name
Aresult
11
00
1699 }
1700 36 my ( $min_val, $max_val ); # the ends of a stringmap's scale; numbers are left to norm_args
1701 36 my $opts = '';
1702 36 ▶ if ($non_numeric_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($non_numeric_data) 10 26 36
1703 10 my @prop_cycle = ('#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2',
1704 '#7f7f7f', '#bcbd22', '#17becf'); #plt.rcParams['axes.prop_cycle']
1705 10 my $n_strings = scalar keys %intmap;
1706 10 ▶ if ( $n_strings > scalar @prop_cycle ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_strings > scalar @prop_cycle) { } 1 9 10
1707 # More categories than the default property cycle has colors. The
1708 # slice used to run off the end of @prop_cycle and die inside
1709 # join() as "Use of uninitialized value", naming neither
1710 # "stringmap" nor the number of categories, so an 11th category
1711 # was an unexplained crash. A continuous colormap resampled to the
1712 # number of categories gives that many distinct colors for any
1713 # number of them.
1714 1 say { $args->{fh} } 'import matplotlib';
1715 1 say { $args->{fh} } "this_cmap = matplotlib.colormaps['gist_rainbow'].resampled($n_strings)";
1716 } else {
1717 9 say { $args->{fh} } 'from matplotlib.colors import ListedColormap';
1718 9 say { $args->{fh} } 'colors = [' . py_list( @prop_cycle[ 0 .. $n_strings - 1 ] ) . ']';
1719 9 say { $args->{fh} } 'this_cmap = ListedColormap(colors)';
1720 }
1721 10 ▶ warn "deleting \"$plot->{cmap}\" because string data is present" if defined $plot->{cmap};
Branch: 1 branch
BranchTrueFalseTotal
if defined $plot->{"cmap"} 0 10 10
1722 10 delete $plot->{cmap};
1723 10 $min_val = 0;
1724 10 $max_val = max(values %intmap);
1725 10 $opts .= ', cmap = this_cmap';
1726 }
1727 write_data({
1728 data => $data,
1729 fh => $args->{fh},
1730 36 name => 'd',
1731 });
1732 # Only where a value needs it, so that an image of whole numbers is still
1733 # drawn from whole numbers.
1734 36 ▶ if ($any_nonfinite) {
Branch: 1 branch
BranchTrueFalseTotal
if ($any_nonfinite) 2 34 36
1735 2 say { $args->{fh} } 'import numpy as np';
1736 2 say { $args->{fh} } 'd = np.asarray(d, dtype = float)';
1737 }
1738 36 ▶ my $ax = $args->{ax} // '';
Condition50%1/2
$args->{"ax"} // ""
l!l
360
MC/DC0%0/1
$args->{"ax"} // ""
$args->{"ax"}
Truth table50%1/2
A
A= $args->{"ax"}
Aresult
11
00
1739 36 foreach my $opt (grep {defined $plot->{$_}} ('cmap')) { # strings
1740 1 $opts .= ", $opt = " . py_str( $plot->{$opt} );
1741 }
1742 # Categories have no scale to put on a log axis.
1743 36 ▶ if ( $non_numeric_data && $plot->{cb_logscale} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($non_numeric_data and $plot->{"cb_logscale"}) 1 35 36
Condition100%3/3
$non_numeric_data and $plot->{"cb_logscale"}
!ll&&!rl&&r
2691
MC/DC100%2/2
$non_numeric_data and $plot->{"cb_logscale"}
$non_numeric_data $plot->{"cb_logscale"}
Truth table100%3/3
A and B
A= $non_numeric_dataB= $plot->{"cb_logscale"}
ABresult
0X0
100
111
1744 1 die "\"cb_logscale\" means nothing for $current_sub with a \"stringmap\": its colors are categories, not a scale";
1745 }
1746 # vmin and vmax were written as given, so a word was a bare Python name,
1747 # and "cb_logscale" was accepted and never read. An image with no finite
1748 # value leaves the ends to matplotlib; they came out as "vmin = inf".
1749 35 foreach my $v ( grep { defined $plot->{$_} } ( 'vmin', 'vmax' ) ) {
1750 5 check_numbers( [ $plot->{$v} ], "\"$v\"", $current_sub );
1751 }
1752 $opts .= norm_args({
1753 lo => $plot->{vmin} // ( $non_numeric_data ? $min_val : undef ),
1754 hi => $plot->{vmax} // ( $non_numeric_data ? $max_val : undef ),
1755 rows => $non_numeric_data ? [] : $data,
1756 log => $plot->{cb_logscale},
1757 fh => $args->{fh},
1758 34 ▶ sub => $current_sub
Branch: 3 branches
BranchTrueFalseTotal
$non_numeric_data ? : 9 23 32
$non_numeric_data ? : 9 23 32
$non_numeric_data ? : 9 25 34
Condition100%6/6
$plot->{"vmin"} // ($non_numeric_data ? $min_val : undef)
l!l&&r!l&&!r
2923
$plot->{"vmax"} // ($non_numeric_data ? $max_val : undef)
l!l&&r!l&&!r
2923
MC/DC100%2/2
$plot->{"vmin"} // ($non_numeric_data ? $min_val : undef)
$plot->{"vmin"} ($non_numeric_data ? $min_val : undef)
MC/DC100%2/2
$plot->{"vmax"} // ($non_numeric_data ? $max_val : undef)
$plot->{"vmax"} ($non_numeric_data ? $max_val : undef)
Truth table100%3/3
A // B
A= $plot->{"vmin"}B= ($non_numeric_data ? $min_val : undef)
ABresult
1X1
011
000
Truth table100%3/3
A // B
A= $plot->{"vmax"}B= ($non_numeric_data ? $max_val : undef)
ABresult
1X1
011
000
1759 });
1760 33 say { $args->{fh} } "im$ax = ax$ax.imshow(d, aspect = 'auto' $opts)";
1761 33 $opts = '';
1762 33 ▶ if ($non_numeric_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($non_numeric_data) 9 24 33
1763 # One tick per category, at the middle of its band of the colorbar.
1764 # The colormap has one color per category and spans [0, $max_val], so
1765 # category i covers [i/n, (i+1)/n] of that span and its middle sits at
1766 # $max_val * (2i+1) / 2n. The formula here was "$_ + 0.5 - $_/$max_val",
1767 # which divided by zero when there was a single category and put both
1768 # ticks in the same place when there were two.
1769 9 my $n_strings = $max_val + 1;
1770 $opts .= ', ticks = ['
1771 9 . join( ',', map { $max_val * ( 2 * $_ + 1 ) / ( 2 * $n_strings ) } 0 .. $max_val ) . ']';
1772 }
1773 # py_str, not "'$value'": a cblabel is prose, and "Farmer's yield" closed
1774 # the literal early and left the script unparseable.
1775 33 ▶ $opts .= ', label = ' . py_str( $plot->{cblabel} ) if defined $plot->{cblabel};
Branch: 1 branch
BranchTrueFalseTotal
if defined $plot->{"cblabel"} 2 31 33
1776 33 $opts .= colorbar_args($plot);
1777 33 ▶ say { $args->{fh} } "cbar = fig.colorbar(im$ax $opts)" if $plot->{colorbar_on};
Branch: 1 branch
BranchTrueFalseTotal
if $plot->{"colorbar_on"} 29 4 33
1778 33 ▶ if (($non_numeric_data) && ($plot->{colorbar_on})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($non_numeric_data and $plot->{"colorbar_on"}) 9 24 33
Condition66%2/3
$non_numeric_data and $plot->{"colorbar_on"}
!ll&&!rl&&r
2409
MC/DC50%1/2
$non_numeric_data and $plot->{"colorbar_on"}
$non_numeric_data $plot->{"colorbar_on"}
Truth table66%2/3
A and B
A= $non_numeric_dataB= $plot->{"colorbar_on"}
ABresult
0X0
100
111
1779 # The colorbar's own set_ticklabels, which labels whichever axis its
1780 # ticks are on. cbar.ax.set_yticklabels was written whatever the
1781 # orientation, and a horizontal colorbar, whose ticks are on x, died as
1782 # "The number of FixedLocator locations (0) ... does not match the number
1783 # of labels".
1784 9 say { $args->{fh} } 'cbar.set_ticklabels([' . py_list(@ytick_labels) . '])';
1785 }
1786 }
1787  
1788 17 ▶sub pie_helper {
Subroutine pie_helper: called CC=14 SCAR=26.6
Pod undocumented
1789 17 my ($args) = @_;
1790 17 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
1791 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
1792 17 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 17 17
1793 0 die
1794 "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
1795 }
1796 17 my @reqd_args = (
1797 'ax',
1798 'fh', # e.g. $py, $fh, which will be passed by the subroutine
1799 'plot', # args to original function
1800 );
1801 17 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
1802 17 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 17 17
1803 0 p @undef_args;
1804 0 die 'the above args are necessary, but were not defined.';
1805 }
1806 17 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
1807 17 my $plot = $args->{plot};
1808 my @undef_opt = grep {
1809 100 my $key = $_;
1810 100 not grep { $_ eq $key } @opt
1811 17 } keys %{$plot};
1812 17 ▶ if ( scalar @undef_opt > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_opt > 0) 0 17 17
1813 bad_keyword_error({
1814 bad => \@undef_opt,
1815 accepted => \@opt,
1816 preferred => $opt{$current_sub},
1817 type => $plot->{plot_type},
1818 0 sub => $current_sub
1819 });
1820 }
1821 17 my @key_order;
1822 17 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 3 14 17
1823 @key_order = check_key_order({
1824 keys => $plot->{key_order},
1825 data => $plot->{data},
1826 3 option => 'key_order',
1827 sub => $current_sub
1828 });
1829 } else {
1830 14 @key_order = sort keys %{ $plot->{data} };
1831 }
1832 # As in barplot_helper: a wedge size is written into the script as it
1833 # stands, so a non-numeric one becomes a bare Python name and the script
1834 # dies as a NameError with nothing to say about the data.
1835 16 foreach my $key (@key_order) {
1836 35 ▶ if ( not looks_like_number( $plot->{data}{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&looks_like_number($plot->{"data"}{$key})) 1 34 35
1837 1 p $plot->{data};
1838 1 die "\"$key\" is not a number, which $current_sub needs to size a wedge";
1839 }
1840 # matplotlib refuses these as "Wedge sizes must be finite numbers"
1841 34 ▶ die "\"$key\" is not a finite number, which $current_sub needs to size a wedge" unless is_finite( $plot->{data}{$key} );
Branch: 1 branch
BranchTrueFalseTotal
unless is_finite($plot->{"data"}{$key}) 1 33 34
1842 # and these as "Wedge sizes 'x' must be non negative values"
1843 33 ▶ die "\"$key\" is $plot->{data}{$key}, but $current_sub cannot size a wedge below 0" if $plot->{data}{$key} < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $plot->{"data"}{$key} < 0 1 32 33
1844 }
1845 # and nothing at all, which matplotlib divides by: "x must have a positive sum"
1846 13 ▶ if ( not grep { $plot->{data}{$_} > 0 } @key_order ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$plot->{"data"}{$_} > 0;} @key_order) 1 12 13
1847 1 die "every wedge of $current_sub is 0, so there is no pie to divide between them";
1848 }
1849 12 ▶ $plot->{autopct} = $plot->{autopct} // '';
Condition100%2/2
$plot->{"autopct"} // ""
l!l
111
MC/DC100%1/1
$plot->{"autopct"} // ""
$plot->{"autopct"}
Truth table100%2/2
A
A= $plot->{"autopct"}
Aresult
11
00
1850 12 my $opt = '';
1851 12 ▶ if ( $plot->{autopct} ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"autopct"} ne "") 1 11 12
1852 1 $opt .= ", autopct = " . py_str( $plot->{autopct} );
1853 }
1854 12 foreach my $arg ( grep { defined $plot->{$_} } 'labeldistance', 'pctdistance' ) {
1855 3 check_numbers( [ $plot->{$arg} ], "\"$arg\"", $current_sub ); # written bare, so a word was a NameError
1856 2 $opt .= ", $arg = " . py_num( $plot->{$arg} );
1857 }
1858 write_data({
1859 data => \@key_order,
1860 fh => $args->{fh},
1861 11 name => 'labels',
1862 });
1863 11 say { $args->{fh} } 'vals = ['
1864 11 . py_nums( @{ $plot->{data} }{@key_order} ) . ']';
1865 11 ▶ my $ax = $args->{ax} // '';
Condition50%1/2
$args->{"ax"} // ""
l!l
110
MC/DC0%0/1
$args->{"ax"} // ""
$args->{"ax"}
Truth table50%1/2
A
A= $args->{"ax"}
Aresult
11
00
1866 11 say { $args->{fh} } "ax$ax.pie(vals, labels = labels $opt)";
1867 }
1868  
1869 73 ▶sub plot_helper {
Subroutine plot_helper: called CC=71 SCAR=45.6
Pod undocumented
1870 73 my ($args) = @_;
1871 73 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
1872 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
1873 73 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 73 73
1874 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
1875 }
1876 73 my @reqd_args = (
1877 'ax', 'fh',# e.g. $py, $fh, which will be passed by the subroutine
1878 'plot', # args to original function
1879 );
1880 73 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
1881 73 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 73 73
1882 0 p @undef_args;
1883 0 die 'the above args are necessary, but were not defined.';
1884 }
1885 73 my @opt = (@ax_methods, @fig_methods, @arg, @plt_methods, 'ax', @{ $opt{$current_sub} });
1886 73 my $plot = $args->{plot};
1887 my @bad_opt = grep {
1888 450 my $key = $_;
1889 450 not grep { $_ eq $key } @opt
1890 73 } keys %{$plot};
1891 73 ▶ if ( scalar @bad_opt > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 73 73
1892 bad_keyword_error({
1893 bad => \@bad_opt,
1894 accepted => \@opt,
1895 preferred => $opt{$current_sub},
1896 type => $plot->{plot_type},
1897 0 sub => $current_sub
1898 });
1899 }
1900 73 ▶ $plot->{show_legend} = bool_option( $plot->{show_legend} // 1, 'show_legend', $current_sub );
Condition100%2/2
$plot->{"show_legend"} // 1
l!l
766
MC/DC100%1/1
$plot->{"show_legend"} // 1
$plot->{"show_legend"}
Truth table100%2/2
A
A= $plot->{"show_legend"}
Aresult
11
00
1901 73 foreach my $axis ( logscale_axes( $plot->{logscale}, $current_sub ) ) { # x, y
1902 3 say {$args->{fh}} "ax$args->{ax}.set_$axis" . 'scale("log")';
1903 }
1904 70 my @twinx;
1905 # The one twin of these axes, made the first time a line asks for it and
1906 # shared by every twinned line after, including those of an "add" graph on
1907 # the same axes. Each twinned line used to get a twin of its own, so two of
1908 # them had two right-hand axes, each with its own limits, their ticks drawn
1909 # over one another on the same spine.
1910 14 ▶ my $twin = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1911 14 my $ax = "ax$args->{ax}";
1912 14 ▶ if ( not defined $twin_axes{$ax} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $twin_axes{$ax}) 12 2 14
1913 12 $twin_axes{$ax} = "twinx_$ax";
1914 12 say { $args->{fh} } "$twin_axes{$ax} = $ax.twinx() # " . __LINE__;
1915 }
1916 14 return $twin_axes{$ax};
1917 70 };
1918 # Allow a single line entered as two bare array refs, with no enclosing
1919 # pair-array and no hash key:
1920 # data => [ \@x, \@y ]
1921 # Promote it to the canonical array-of-pairs form so the array path below
1922 # handles it unchanged:
1923 # data => [ [ \@x, \@y ] ]
1924 # The discriminator vs. the multi-line form (data => [ [\@x,\@y], ... ]) is
1925 # data->[0][0]: a number here, an ARRAY ref in the multi-line form.
1926 70 ▶ if ( ( ref $plot->{data} eq 'ARRAY' )
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"data"} eq "ARRAY" and scalar @{$plot->{"data"};} == 2 and ref $plot->{"data"}[0] eq "ARRAY" and ref $plot->{"data"}[1] eq "ARRAY" and ref $plot->{"data"}[0][0] ne "ARRAY") 4 66 70
Condition83%10/12
ref $plot->{"data"} eq "ARRAY" and scalar @{$plot->{"data"};} == 2 and ref $plot->{"data"}[0] eq "ARRAY" and ref $plot->{"data"}[1] eq "ARRAY" and ref $plot->{"data"}[0][0] ne "ARRAY"
!ll&&!rl&&r
6064
ref $plot->{"data"} eq "ARRAY" and scalar @{$plot->{"data"};} == 2 and ref $plot->{"data"}[0] eq "ARRAY" and ref $plot->{"data"}[1] eq "ARRAY"
!ll&&!rl&&r
60010
ref $plot->{"data"} eq "ARRAY" and scalar @{$plot->{"data"};} == 2 and ref $plot->{"data"}[0] eq "ARRAY"
!ll&&!rl&&r
60010
ref $plot->{"data"} eq "ARRAY" and scalar @{$plot->{"data"};} == 2
!ll&&!rl&&r
58210
MC/DC60%3/5
ref $plot->{"data"} eq "ARRAY" and scalar @{$plot->{"data"};} == 2 and ref $plot->{"data"}[0] eq "ARRAY" and ref $plot->{"data"}[1] eq "ARRAY" and ref $plot->{"data"}[0][0] ne "ARRAY"
ref $plot->{"data"} eq "ARRAY" scalar @{$plot->{"data"};} == 2 ref $plot->{"data"}[0] eq "ARRAY" ref $plot->{"data"}[1] eq "ARRAY" ref $plot->{"data"}[0][0] ne "ARRAY"
Truth table66%4/6
A and B and C and D and E
A= ref $plot->{"data"} eq "ARRAY"B= scalar @{$plot->{"data"};} == 2C= ref $plot->{"data"}[0] eq "ARRAY"D= ref $plot->{"data"}[1] eq "ARRAY"E= ref $plot->{"data"}[0][0] ne "ARRAY"
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
1927 12 && ( scalar @{ $plot->{data} } == 2 )
1928 && ( ref $plot->{data}[0] eq 'ARRAY' )
1929 && ( ref $plot->{data}[1] eq 'ARRAY' )
1930 && ( ref $plot->{data}[0][0] ne 'ARRAY' ) )
1931 {
1932 4 $plot->{data} = [ $plot->{data} ];
1933 }
1934 70 ▶ if (ref $plot->{data} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"data"} eq "ARRAY") 12 58 70
1935 12 ▶ if (defined $plot->{set_options}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_options"}) 4 8 12
1936 4 my $ref_type = ref $plot->{set_options};
1937 # a scalar applies to every line (handy for the single-line form);
1938 # an array gives one option string per line (positional)
1939 4 ▶ if ($ref_type eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if ($ref_type eq 'ARRAY') { } 2 2 4
elsif ($ref_type ne '') { } 0 2 2
1940 2 my $n_set_opt = scalar @{ $plot->{set_options} };
1941 2 my $n_data = scalar @{ $plot->{data} };
1942 2 ▶ if ($n_set_opt > $n_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_set_opt > $n_data) 0 2 2
1943 0 p $args;
1944 0 die "there are $n_set_opt sets for options, but only $n_data data points.";
1945 }
1946 } elsif ($ref_type ne '') {
1947 0 p $args;
1948 0 die "\"set_options\" must be a scalar (applied to every line) or an array (one per line) when data is an array, but \"$ref_type\" was given.";
1949 }
1950 }
1951 12 ▶ if (defined $plot->{twinx}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"twinx"}) 3 9 12
1952 3 my $twinx_ref = ref $plot->{twinx};
1953 3 ▶ if ($twinx_ref eq '') {
Branch: 2 branches
BranchTrueFalseTotal
if ($twinx_ref eq '') { } 1 2 3
elsif ($twinx_ref eq 'ARRAY') { } 1 1 2
1954 1 ▶ die "twinx must be an array index, not \"$plot->{twinx}\"" unless $plot->{twinx} =~ m/^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $plot->{"twinx"} =~ /^\d+$/ 0 1 1
1955 1 @twinx = $plot->{twinx};
1956 } elsif ($twinx_ref eq 'ARRAY') {
1957 1 @bad_opt = grep {$_ !~ m/^\d+$/} @{ $plot->{twinx} };
1958 1 ▶ if (scalar @bad_opt > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 1 1
1959 0 p @bad_opt;
1960 0 die 'data that could not possibly be an array index for twinx is shown above';
1961 }
1962 1 @twinx = @{ $plot->{twinx} };
1963 } else {
1964 # Any other reference fell off the end of this chain and was
1965 # ignored without a word, so a twinx given in the hash form
1966 # ("twinx => { B => 1 }") against array data simply did not
1967 # draw a second axis.
1968 1 die "$current_sub: \"data\" is an array, so \"twinx\" is an index or an array of indices into it, not a $twinx_ref reference";
1969 }
1970 }
1971 11 ▶ if (defined $plot->{twinx_args}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"twinx_args"}) 2 9 11
1972 2 my $ref = ref $plot->{twinx_args};
1973 2 ▶ die "\"twinx_args\" must be a hash, but $ref was entered" unless $ref eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $ref eq "HASH" 0 2 2
1974 2 check_twinx_args( $plot->{twinx_args}, $current_sub );
1975 2 @bad_opt = grep {$_ !~ m/^\d+$/} keys %{ $plot->{twinx_args} };
1976 2 ▶ if (scalar @bad_opt > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 2 2
1977 0 p @bad_opt;
1978 0 die 'the above keys are not hash indices';
1979 }
1980 2 foreach my $idx (keys %{ $plot->{twinx_args} }) {
1981 0 ▶ next if grep {$idx == $_} @twinx;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$idx == $_;} @twinx 0 2 2
1982 2 push @twinx, $idx;
1983 }
1984 }
1985 # An index past the last line was ignored without a word, where the
1986 # hash form refuses a key that is not in "data".
1987 11 my $n_lines = scalar @{ $plot->{data} };
1988 0 my @past_end = sort { $a <=> $b } grep { $_ >= $n_lines } @twinx;
1989 11 ▶ if ( scalar @past_end > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @past_end > 0) 2 9 11
1990 2 ▶ die "$current_sub: \"twinx\" or \"twinx_args\" names line " . join( ', ', @past_end ) . ", but \"data\" has $n_lines line" . ( $n_lines == 1 ? '' : 's' ) . ', indexed from 0';
Branch: 1 branch
BranchTrueFalseTotal
$n_lines == 1 ? : 0 2 2
1991 }
1992 9 my $arr_i = 0;
1993 9 foreach my $arr (@{ $plot->{data} }) {
1994 15 my $ref = ref $arr;
1995 15 ▶ if ($ref ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref ne "ARRAY") 0 15 15
1996 0 p $plot->{data}[$arr_i];
1997 0 die "index $arr_i is \"$ref\" but must be \"ARRAY\"";
1998 }
1999 15 my $n_elem = scalar @{ $arr };
2000 15 ▶ if ($n_elem != 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_elem != 2) 0 15 15
2001 0 p $arr;
2002 0 die "there must be 2 array references (x, y) but index $arr_i has $n_elem";
2003 }
2004 15 @bad_opt = map { scalar @{ $arr->[$_] } } (0,1);
2005 15 ▶ if ($bad_opt[0] != $bad_opt[1]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bad_opt[0] != $bad_opt[1]) 0 15 15
2006 0 say STDERR "index $arr_i must have arrays/array refs of equal length, but these lengths were given:";
2007 0 p @bad_opt;
2008 0 die 'the array/array ref lengths must be equal';
2009 }
2010 15 foreach my $i (0,1) {
2011 30 my $max_i = scalar @{ $arr->[$i] } - 1;
2012 30 @bad_opt = grep {not looks_like_number($arr->[$i][$_])} 0..$max_i;
2013 30 ▶ next if scalar @bad_opt == 0; # it's fine, don't worry
Branch: 1 branch
BranchTrueFalseTotal
if scalar @bad_opt == 0 30 0 30
2014 0 p $plot->{data}[$arr_i];
2015 0 p @bad_opt;
2016 0 @bad_opt = @{ $arr->[$i] }[@bad_opt];
2017 0 say STDERR 'have these non-numeric values:';
2018 0 p @bad_opt;
2019 0 die "Array index $arr_i/axis $i has non-numeric values (above)";
2020 }
2021 15 my $options = '';
2022 15 say { $args->{fh} } 'x = [' . py_nums( @{ $arr->[0] } ) . ']';
2023 15 say { $args->{fh} } 'y = [' . py_nums( @{ $arr->[1] } ) . ']';
2024 15 ▶ if ( defined $plot->{set_options} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_options"}) 7 8 15
2025 7 my $so_ref = ref $plot->{set_options};
2026 7 ▶ if ( $so_ref eq '' ) { # scalar: same options for every line
Branch: 2 branches
BranchTrueFalseTotal
if ($so_ref eq '') { } 3 4 7
elsif ($so_ref eq 'ARRAY' and defined $plot->{'set_options'}[$arr_i]) { } 4 0 4
2027 3 $options = ", $plot->{set_options}";
2028 ▶ } elsif ( ( $so_ref eq 'ARRAY' )
Condition33%1/3
$so_ref eq "ARRAY" and defined $plot->{"set_options"}[$arr_i]
!ll&&!rl&&r
004
MC/DC0%0/2
$so_ref eq "ARRAY" and defined $plot->{"set_options"}[$arr_i]
$so_ref eq "ARRAY" defined $plot->{"set_options"}[$arr_i]
Truth table33%1/3
A and B
A= $so_ref eq "ARRAY"B= defined $plot->{"set_options"}[$arr_i]
ABresult
0X0
100
111
2029 && ( defined $plot->{set_options}[$arr_i] ) ) {
2030 4 $options = ", $plot->{set_options}[$arr_i]"; # one per line
2031 }
2032 }
2033 15 my $ax = "ax$args->{ax}";
2034 15 ▶ if (grep {$arr_i == $_} @twinx) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$arr_i == $_;} @twinx) { } 3 12 15
2035 3 my $twin_ax = $twin->();
2036 3 say { $args->{fh} } "$twin_ax.plot(x, y $options) # " . __LINE__;
2037 3 ▶ if (defined $plot->{twinx_args}{$arr_i}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"twinx_args"}{$arr_i}) 1 2 3
2038 plot_args({
2039 fh => $args->{fh},
2040 1 args => $plot->{twinx_args}{$arr_i},
2041 ax => $twin_ax,
2042 no_legend => 1 # its lines go in the legend of $ax
2043 });
2044 }
2045 } else {
2046 12 say { $args->{fh} } "ax$args->{ax}.plot(x, y $options) # " . __LINE__;
2047 }
2048 15 $arr_i++;
2049 }
2050 9 return 1; # the rest only applies if $plot->{data} is a hash
2051 }
2052 58 my @key_order;
2053 58 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 4 54 58
2054 @key_order = check_key_order({
2055 keys => $plot->{key_order},
2056 data => $plot->{data},
2057 4 option => 'key_order',
2058 sub => $current_sub
2059 });
2060 } else {
2061 54 @key_order = sort keys %{ $plot->{data} };
2062 }
2063 57 ▶ if ((defined $plot->{set_options}) && (ref $plot->{set_options} eq 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_options"} and ref $plot->{"set_options"} eq "HASH") 4 53 57
Condition100%3/3
defined $plot->{"set_options"} and ref $plot->{"set_options"} eq "HASH"
!ll&&!rl&&r
5214
MC/DC100%2/2
defined $plot->{"set_options"} and ref $plot->{"set_options"} eq "HASH"
defined $plot->{"set_options"} ref $plot->{"set_options"} eq "HASH"
Truth table100%3/3
A and B
A= defined $plot->{"set_options"}B= ref $plot->{"set_options"} eq "HASH"
ABresult
0X0
100
111
2064 4 @bad_opt = sort grep {!defined $plot->{data}{$_}} keys %{ $plot->{set_options} };
2065 4 ▶ if (scalar @bad_opt > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 4 4
2066 0 p @bad_opt;
2067 0 die "the above options are defined for undefined data sets in $current_sub.";
2068 }
2069 }
2070 57 ▶ if (defined $plot->{twinx}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"twinx"}) 9 48 57
2071 9 my $twinx_ref = ref $plot->{twinx};
2072 9 ▶ if ($twinx_ref eq '') {
Branch: 2 branches
BranchTrueFalseTotal
if ($twinx_ref eq '') { } 7 2 9
elsif ($twinx_ref eq 'HASH') { } 1 1 2
2073 7 ▶ die "twinx \"$plot->{twinx}\" is not a key in data" unless defined $plot->{data}{ $plot->{twinx} };
Branch: 1 branch
BranchTrueFalseTotal
unless defined $plot->{"data"}{$plot->{"twinx"}} 0 7 7
2074 7 @twinx = ($plot->{twinx});
2075 } elsif ($twinx_ref eq 'HASH') {
2076 1 @bad_opt = sort grep {!defined $plot->{data}{$_}} keys %{ $plot->{twinx} };
2077 1 ▶ if (scalar @bad_opt > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 1 1
2078 0 p @bad_opt;
2079 0 die 'data for undefined data keys is shown above';
2080 }
2081 1 @twinx = sort keys %{ $plot->{twinx} };
2082 } else {
2083 # As in the array branch above: anything else was ignored in
2084 # silence, so "twinx => ['B']" against a hash of sets drew nothing
2085 # and said nothing.
2086 1 die "$current_sub: \"data\" is a hash, so \"twinx\" is a data key or a hash of them, not a $twinx_ref reference";
2087 }
2088 }
2089 56 ▶ if (defined $plot->{twinx_args}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"twinx_args"}) 7 49 56
2090 7 my $ref = ref $plot->{twinx_args};
2091 7 ▶ die "\"twinx_args\" must be a hash, but $ref was entered" unless $ref eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $ref eq "HASH" 0 7 7
2092 7 check_twinx_args( $plot->{twinx_args}, $current_sub );
2093 6 @bad_opt = sort grep {!defined $plot->{data}{$_}} keys %{ $plot->{twinx_args} };
2094 6 ▶ if (scalar @bad_opt > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 6 6
2095 0 p @bad_opt;
2096 0 die 'the above keys are not present in data keys';
2097 }
2098 6 foreach my $set (keys %{ $plot->{twinx_args} }) {
2099 6 ▶ next if grep {$set eq $_} @twinx;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$set eq $_;} @twinx 4 2 6
2100 2 push @twinx, $set;
2101 }
2102 }
2103 55 foreach my $set (@key_order) {
2104 72 my $set_ref = ref $plot->{data}{$set};
2105 72 ▶ if ( $set_ref ne 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($set_ref ne "ARRAY") 0 72 72
2106 0 p $plot->{data}{$set};
2107 0 die "$set must have two arrays, x and y coordinates, or one array of y values, but instead has a $set_ref";
2108 }
2109 # A set of plain values, with no array among them, is y alone, and is
2110 # drawn against 0 .. n-1. The pair is built here rather than written
2111 # back, so the caller's data is left as it was given.
2112 72 my $xy = $plot->{data}{$set};
2113 72 my $n_refs = grep { ref } @{$xy};
2114 72 ▶ if ( ( $n_refs == 0 ) && ( scalar @{$xy} > 0 ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($n_refs == 0 and scalar @{$xy;} > 0) { } 6 66 72
elsif ($n_refs < scalar @{$xy;}) { } 1 65 66
Condition100%3/3
$n_refs == 0 and scalar @{$xy;} > 0
!ll&&!rl&&r
6516
MC/DC100%2/2
$n_refs == 0 and scalar @{$xy;} > 0
$n_refs == 0 scalar @{$xy;} > 0
Truth table100%3/3
A and B
A= $n_refs == 0B= scalar @{$xy;} > 0
ABresult
0X0
100
111
2115 6 $xy = [ [ 0 .. $#{$xy} ], $xy ];
2116 66 } elsif ( $n_refs < scalar @{$xy} ) {
2117 1 p $xy;
2118 1 die "$current_sub: set \"$set\" mixes arrays with plain values: it must be [ \\\@x, \\\@y ] or one array of y values";
2119 }
2120 71 my $n_arrays = scalar @{ $xy };
2121 71 ▶ if ( $n_arrays != 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_arrays != 2) 1 70 71
2122 1 p $xy;
2123 1 die "$n_arrays were entered for $set, but there must be exactly 2";
2124 }
2125 70 my @n_elem = map { scalar @{ $xy->[$_] }} (0,1);
2126 70 ▶ if ( $n_elem[0] != $n_elem[1] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_elem[0] != $n_elem[1]) 0 70 70
2127 0 p $xy;
2128 0 p @n_elem;
2129 0 die "$set has length = $n_elem[0] for x; length = $n_elem[1] for y: x & y must be of equal length";
2130 }
2131 70 foreach my $ax (0,1) {
2132 140 my $n = scalar @{ $xy->[$ax] };
2133 140 my @undef_i = grep {not defined $xy->[$ax][$_]} 0..$n-1;
2134 140 ▶ if (scalar @undef_i > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_i > 0) 1 139 140
2135 1 p $plot;
2136 1 p @undef_i;
2137 1 my $max_i = scalar @{ $xy->[$ax] };
2138 1 die "set $set axis $ax has undefined indices, of max index $max_i in $current_sub";
2139 }
2140 # The array form of "data" has always refused these; the hash form
2141 # wrote them into the script, where 'a' became "y = [a,3]" and died
2142 # as a NameError.
2143 139 my @non_numeric = grep { not looks_like_number( $xy->[$ax][$_] ) } 0 .. $n - 1;
2144 139 ▶ if ( scalar @non_numeric > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @non_numeric > 0) 2 137 139
2145 2 my @values = @{ $xy->[$ax] }[@non_numeric];
2146 2 p @values;
2147 2 die "set \"$set\" axis $ax has the above non-numeric values, which $current_sub cannot plot";
2148 }
2149 }
2150 67 my $options = '';
2151 67 say { $args->{fh} } 'x = [' . py_nums( @{ $xy->[0] } ) . ']';
2152 67 say { $args->{fh} } 'y = [' . py_nums( @{ $xy->[1] } ) . ']';
2153 67 ▶ if ( ( defined $plot->{set_options} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_options"} and ref $plot->{"set_options"} eq "") 2 65 67
Condition100%3/3
defined $plot->{"set_options"} and ref $plot->{"set_options"} eq ""
!ll&&!rl&&r
5872
MC/DC100%2/2
defined $plot->{"set_options"} and ref $plot->{"set_options"} eq ""
defined $plot->{"set_options"} ref $plot->{"set_options"} eq ""
Truth table100%3/3
A and B
A= defined $plot->{"set_options"}B= ref $plot->{"set_options"} eq ""
ABresult
0X0
100
111
2154 && ( ref $plot->{set_options} eq '' ) )
2155 {
2156 2 $options = ", $plot->{set_options}";
2157 }
2158 67 ▶ if ( ( ref $plot->{set_options} eq 'HASH' ) && ( defined $plot->{set_options}{$set} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"set_options"} eq "HASH" and defined $plot->{"set_options"}{$set}) 5 62 67
Condition100%3/3
ref $plot->{"set_options"} eq "HASH" and defined $plot->{"set_options"}{$set}
!ll&&!rl&&r
6025
MC/DC100%2/2
ref $plot->{"set_options"} eq "HASH" and defined $plot->{"set_options"}{$set}
ref $plot->{"set_options"} eq "HASH" defined $plot->{"set_options"}{$set}
Truth table100%3/3
A and B
A= ref $plot->{"set_options"} eq "HASH"B= defined $plot->{"set_options"}{$set}
ABresult
0X0
100
111
2159 5 $options = ", $plot->{set_options}{$set}";
2160 }
2161 67 my $label = '';
2162 67 ▶ if ( $plot->{show_legend} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"show_legend"}) 60 7 67
2163 60 $label = ',label = ' . py_str($set);
2164 }
2165 67 my $ax = "ax$args->{ax}";
2166 67 ▶ if (grep {$set eq $_} @twinx) { # this set has
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$set eq $_;} @twinx) { } 11 56 67
2167 11 my $twin_ax = $twin->();
2168 11 say { $args->{fh} } "$twin_ax.plot(x, y $label $options) # " . __LINE__;
2169 11 ▶ if (defined $plot->{twinx_args}{$set}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"twinx_args"}{$set}) 6 5 11
2170 plot_args({
2171 fh => $args->{fh},
2172 6 args => $plot->{twinx_args}{$set},
2173 ax => $twin_ax,
2174 no_legend => 1 # its lines go in the legend of $ax
2175 });
2176 }
2177 } else {
2178 56 say { $args->{fh} } "ax$args->{ax}.plot(x, y $label $options) # " . __LINE__;
2179 }
2180 }
2181 50 return 1;
2182 }
2183  
2184 117 ▶sub scatter_tooltips {
Subroutine scatter_tooltips: called CC=11 SCAR=24.0
Pod undocumented
2185 # Check one set's "tooltips" against its number of points, and return the
2186 # url of each point, which ties a labelled point to its text -- or undef
2187 # when there is nothing to draw.
2188 #
2189 # A url per point, rather than counting the markers in the SVG afterwards:
2190 # matplotlib writes each point's url as a link around that point's marker,
2191 # and leaves out the url of a point it does not draw -- NaN, or not above
2192 # 0 on a log axis -- so each label stays with its own point. An undefined
2193 # label is a point without a tooltip, and gets no url.
2194 117 my ( $labels, $n_points, $options, $where, $current_sub ) = @_;
2195 117 ▶ return undef unless defined $labels; # no tooltips for this set
Branch: 1 branch
BranchTrueFalseTotal
unless defined $labels 68 49 117
2196 49 ▶ if ( ref $labels ne 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $labels ne "ARRAY") 3 46 49
2197 3 ▶ die "$current_sub: \"tooltips\"$where must be an array of one label per point, not "
Branch: 1 branch
BranchTrueFalseTotal
ref $labels ? : 1 2 3
2198 . ( ref $labels ? 'a ' . ( ref $labels ) . ' reference' : "\"$labels\"" );
2199 }
2200 46 ▶ if ( scalar @{$labels} != $n_points ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$labels;} != $n_points) 7 39 46
2201 7 die "$current_sub: \"tooltips\"$where has " . scalar @{$labels} . " labels, but there are $n_points points: give one per point, and undef for a point that has none";
2202 }
2203 39 my @refs = grep { ref $labels->[$_] } 0 .. $#{$labels};
2204 39 ▶ if ( scalar @refs > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @refs > 0) 1 38 39
2205 1 ▶ die "$current_sub: \"tooltips\"$where holds text, but index " . join( ', ', @refs ) . ( scalar @refs == 1 ? ' is a reference' : ' are references' );
Branch: 1 branch
BranchTrueFalseTotal
scalar @refs == 1 ? : 0 1 1
2206 }
2207 38 my @labelled = grep { defined $labels->[$_] } 0 .. $#{$labels};
2208 38 ▶ return undef if scalar @labelled == 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @labelled == 0 2 36 38
2209 36 ▶ if ( $options =~ m/\burls?\s*=/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options =~ /\burls?\s*=/) 2 34 36
2210 2 die "$current_sub: \"tooltips\"$where are drawn through the points' urls, so they cannot be given with a \"url\" or \"urls\" in \"set_options\"";
2211 }
2212 34 my @urls = (undef) x $n_points;
2213 34 foreach my $i (@labelled) {
2214 124 $urls[$i] = $tooltip_url . scalar @tooltip_text;
2215 124 push @tooltip_text, "$labels->[$i]"; # as text: ElementTree cannot write a python int as a <title>, and a number may be a dualvar to JSON::XS (see CLAUDE.md)
2216 }
2217 # Checked and counted either way, so that plt can say they were left out;
2218 # a url in a PNG or PDF is a link to nowhere.
2219 34 ▶ return undef unless $tooltips_drawn;
Branch: 1 branch
BranchTrueFalseTotal
unless $tooltips_drawn 2 32 34
2220 32 return \@urls;
2221 }
2222 102 ▶sub write_tooltip_urls {
Subroutine write_tooltip_urls: called CC=2 SCAR=6.9
Pod undocumented
2223 # Write one set's urls from scatter_tooltips, and return the argument that
2224 # hands them to ax.scatter; '' for a set with none.
2225 102 my ( $urls, $fh ) = @_;
2226 102 ▶ return '' unless defined $urls;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $urls 71 31 102
2227 31 write_data({
2228 data => $urls,
2229 fh => $fh,
2230 name => 'tooltip_urls'
2231 });
2232 31 return ', urls = tooltip_urls';
2233 }
2234 118 ▶sub scatter_helper {
Subroutine scatter_helper: called CC=90 SCAR=47.0
Pod undocumented
2235 118 my ($args) = @_;
2236 118 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
2237 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
2238 118 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 118 118
2239 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
2240 }
2241 118 my @reqd_args = (
2242 'ax', 'fh', # e.g. $py, $fh, which will be passed by the subroutine
2243 'plot', # args to original function
2244 );
2245 118 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
2246 118 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 118 118
2247 0 p @undef_args;
2248 0 die 'the above args are necessary, but were not defined.';
2249 }
2250 118 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
2251 118 my $plot = $args->{plot};
2252 @undef_args = grep {
2253 785 my $key = $_;
2254 785 not grep { $_ eq $key } @opt
2255 118 } keys %{$plot};
2256 118 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 118 118
2257 bad_keyword_error({
2258 bad => \@undef_args,
2259 accepted => \@opt,
2260 preferred => $opt{$current_sub},
2261 type => $plot->{plot_type},
2262 0 sub => $current_sub
2263 });
2264 }
2265 118 foreach my $cb ( grep { defined $plot->{$_} } ( 'cb_min', 'cb_max' ) ) {
2266 3 check_numbers( [ $plot->{$cb} ], "\"$cb\"", $current_sub );
2267 }
2268 117 cb_limits( $plot, $current_sub ); # scatter has no vmin or vmax of its own, so cb_min and cb_max are its only way to set them
2269 117 my $overall_ref = ref $plot->{data};
2270 117 ▶ if ( $overall_ref ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($overall_ref ne "HASH") 1 116 117
2271 1 die
2272 "scatter only takes 1) hashes of arrays (single or 2) hash of hash of arrays; but $overall_ref was entered";
2273 }
2274 116 my ( %ref_counts, $plot_type );
2275 116 foreach my $set ( keys %{ $plot->{data} } ) {
2276 263 $ref_counts{ ref $plot->{data}{$set} }++;
2277 }
2278 116 my $ax = $args->{ax};
2279 116 ▶ if ( (scalar keys %ref_counts) > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %ref_counts > 1) 0 116 116
2280 0 p $plot->{data};
2281 0 die "different kinds of data were entered to plot $ax; should be simple hash or hash of arrays.";
2282 }
2283 116 ▶ if ( defined $ref_counts{ARRAY} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $ref_counts{'ARRAY'}) { } 82 34 116
elsif (defined $ref_counts{'HASH'}) { } 34 0 34
2284 82 $plot_type = 'single';
2285 } elsif ( defined $ref_counts{HASH} ) {
2286 34 $plot_type = 'multiple';
2287 } else {
2288 0 p $plot->{data};
2289 0 p %ref_counts;
2290 0 die 'Could not determine scatter type for the above data.';
2291 }
2292 116 ▶ $plot->{cmap} = $plot->{cmap} // 'gist_rainbow';
Condition100%2/2
$plot->{"cmap"} // "gist_rainbow"
l!l
1115
MC/DC100%1/1
$plot->{"cmap"} // "gist_rainbow"
$plot->{"cmap"}
Truth table100%2/2
A
A= $plot->{"cmap"}
Aresult
11
00
2293 116 $plot->{cb_logscale} = bool_option( $plot->{cb_logscale}, 'cb_logscale', $current_sub );
2294 116 foreach my $axis ( logscale_axes( $plot->{logscale}, $current_sub ) ) { # x, y
2295 4 say {$args->{fh}} "ax$ax.set_$axis" . 'scale("log")';
2296 }
2297 # "set_options" is one string of options for a single set, and a hash of
2298 # one per set for several. A string given to several sets died as "Can't
2299 # use string as a HASH ref"; a hash given to a single set was ignored.
2300 113 ▶ if ( defined $plot->{set_options} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_options"}) 10 103 113
2301 10 my $so_ref = ref $plot->{set_options};
2302 10 ▶ if ( ( $plot_type eq 'single' ) && ( $so_ref ne '' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot_type eq "single" and $so_ref ne "") 1 9 10
Condition100%3/3
$plot_type eq "single" and $so_ref ne ""
!ll&&!rl&&r
631
MC/DC100%2/2
$plot_type eq "single" and $so_ref ne ""
$plot_type eq "single" $so_ref ne ""
Truth table100%3/3
A and B
A= $plot_type eq "single"B= $so_ref ne ""
ABresult
0X0
100
111
2303 1 die "$current_sub: \"data\" is a single set, so \"set_options\" is one string of options, e.g. 'marker = \"v\"', not a $so_ref reference";
2304 }
2305 9 ▶ if ( ( $plot_type eq 'multiple' ) && ( $so_ref ne 'HASH' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot_type eq "multiple" and $so_ref ne "HASH") 1 8 9
Condition100%3/3
$plot_type eq "multiple" and $so_ref ne "HASH"
!ll&&!rl&&r
351
MC/DC100%2/2
$plot_type eq "multiple" and $so_ref ne "HASH"
$plot_type eq "multiple" $so_ref ne "HASH"
Truth table100%3/3
A and B
A= $plot_type eq "multiple"B= $so_ref ne "HASH"
ABresult
0X0
100
111
2306 1 ▶ die "$current_sub: \"data\" is a hash of sets, so \"set_options\" is a hash of one string of options per set, e.g. { A => 'marker = \"v\"' }, not "
Branch: 1 branch
BranchTrueFalseTotal
$so_ref ? : 0 1 1
2307 . ( $so_ref ? "a $so_ref reference" : 'a string' );
2308 }
2309 }
2310 # "key_order" is the order of the sets, which "keys" -- the order of the
2311 # axes within a set -- cannot say; a single set has only the one.
2312 111 ▶ if ( ( defined $plot->{key_order} ) && ( $plot_type eq 'single' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"key_order"} and $plot_type eq "single") 0 111 111
Condition66%2/3
defined $plot->{"key_order"} and $plot_type eq "single"
!ll&&!rl&&r
10740
MC/DC0%0/2
defined $plot->{"key_order"} and $plot_type eq "single"
defined $plot->{"key_order"} $plot_type eq "single"
Truth table66%2/3
A and B
A= defined $plot->{"key_order"}B= $plot_type eq "single"
ABresult
0X0
100
111
2313 0 die "$current_sub: \"key_order\" orders the sets of a hash of sets; for the axes of a single set, use \"keys\"";
2314 }
2315 111 ▶ if ( $plot_type eq 'single' ) { # only a single set of data
Branch: 2 branches
BranchTrueFalseTotal
if ($plot_type eq 'single') { } 78 33 111
elsif ($plot_type eq 'multiple') { } 33 0 33
2316 78 my $options = '';
2317 78 my ( $color_key, @keys );
2318 78 ▶ if ( defined $plot->{'keys'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'keys'}) { } 9 69 78
2319 @keys = check_key_order({
2320 keys => $plot->{'keys'},
2321 data => $plot->{data},
2322 9 option => 'keys',
2323 sub => $current_sub
2324 });
2325 } else {
2326 69 ▶ @keys = sort { lc $a cmp lc $b || $a cmp $b } keys %{ $plot->{data} }; # tie-broken, or "x" and "X" came in hash order
Condition33%1/3
lc $a cmp lc $b || $a cmp $b
l!l&&r!l&&!r
12100
MC/DC0%0/2
lc $a cmp lc $b || $a cmp $b
lc $a cmp lc $b $a cmp $b
Truth table33%1/3
A || B
A= lc $a cmp lc $bB= $a cmp $b
ABresult
1X1
011
000
2327 }
2328 77 my $n_keys = scalar keys %{ $plot->{data} };
2329 77 ▶ if ( ( $n_keys != 2 ) && ( $n_keys != 3 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_keys != 2 and $n_keys != 3) 2 75 77
Condition100%3/3
$n_keys != 2 and $n_keys != 3
!ll&&!rl&&r
44312
MC/DC100%2/2
$n_keys != 2 and $n_keys != 3
$n_keys != 2 $n_keys != 3
Truth table100%3/3
A and B
A= $n_keys != 2B= $n_keys != 3
ABresult
0X0
100
111
2330 2 p $plot->{data};
2331 2 die "scatterplots can only take 2 or 3 keys as data, but $current_sub received $n_keys";
2332 }
2333 75 ▶ if ( defined $plot->{color_key} ) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $plot->{'color_key'}) { } 10 65 75
elsif (scalar @keys == 3) { } 22 43 65
elsif ($n_keys == 3) { } 1 42 43
2334 10 $color_key = $plot->{color_key};
2335 # Asked here, before the keys are counted: a "color_key" that is not
2336 # a key of three took none of them away, so the count below died
2337 # first, as "needs one key for x and one for y, but "keys" and
2338 # "color_key" leave the 3 above", which never named the key that
2339 # was wrong.
2340 10 ▶ if ( not defined $plot->{data}{$color_key} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $plot->{"data"}{$color_key}) 3 7 10
2341 3 die "\"$color_key\" isn't defined for this scatter";
2342 }
2343 7 @keys = grep {$_ ne $plot->{color_key}} @keys;
2344 } elsif ( scalar @keys == 3 ) {
2345 22 $color_key = pop @keys;
2346 } elsif ( $n_keys == 3 ) {
2347 # As for several sets: "keys" named x and y of three keys, so the one
2348 # it left out is the color. It was drawn without one.
2349 1 my %named = map { $_ => 1 } @keys;
2350 1 ▶ ($color_key) = grep { not $named{$_} } sort { lc $a cmp lc $b || $a cmp $b } keys %{ $plot->{data} };
Condition33%1/3
lc $a cmp lc $b || $a cmp $b
l!l&&r!l&&!r
200
MC/DC0%0/2
lc $a cmp lc $b || $a cmp $b
lc $a cmp lc $b $a cmp $b
Truth table33%1/3
A || B
A= lc $a cmp lc $bB= $a cmp $b
ABresult
1X1
011
000
2351 }
2352 72 ▶ if ( scalar @keys != 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @keys != 2) 1 71 72
2353 1 p @keys;
2354 1 die "$current_sub needs one key for x and one for y, but \"keys\" and \"color_key\" leave the " . scalar(@keys) . ' above';
2355 }
2356 71 foreach my $i (0,1) {
2357 141 check_scatter_values( $plot->{data}{ $keys[$i] }, "\"$keys[$i]\"", $current_sub );
2358 }
2359 70 ▶ check_scatter_lengths( $plot->{data}, [ @keys, ( defined $color_key ? $color_key : () ) ], '', $current_sub );
Branch: 1 branch
BranchTrueFalseTotal
defined $color_key ? : 29 41 70
2360 69 say { $args->{fh} } 'x = [' . py_nums( @{ $plot->{data}{ $keys[0] } } ) . ']';
2361 69 say { $args->{fh} } 'y = [' . py_nums( @{ $plot->{data}{ $keys[1] } } ) . ']';
2362 69 ▶ if ( ( defined $plot->{set_options} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_options"} and ref $plot->{"set_options"} eq "") 3 66 69
Condition66%2/3
defined $plot->{"set_options"} and ref $plot->{"set_options"} eq ""
!ll&&!rl&&r
6603
MC/DC50%1/2
defined $plot->{"set_options"} and ref $plot->{"set_options"} eq ""
defined $plot->{"set_options"} ref $plot->{"set_options"} eq ""
Truth table66%2/3
A and B
A= defined $plot->{"set_options"}B= ref $plot->{"set_options"} eq ""
ABresult
0X0
100
111
2363 && ( ref $plot->{set_options} eq '' ) )
2364 {
2365 3 $options = ", $plot->{set_options}";
2366 }
2367 69 $options .= write_tooltip_urls( scatter_tooltips( $plot->{tooltips}, scalar @{ $plot->{data}{ $keys[0] } }, $options, '', $current_sub ), $args->{fh} );
2368 60 ▶ if ( defined $color_key ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $color_key) { } 29 31 60
2369 29 ▶ if (not defined $plot->{data}{$color_key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $plot->{"data"}{$color_key}) 0 29 29
2370 0 die "\"$color_key\" isn't defined for this scatter";
2371 }
2372 29 check_scatter_values( $plot->{data}{$color_key}, "\"$color_key\"", $current_sub );
2373 28 say { $args->{fh} } 'z = [' . py_nums( @{ $plot->{data}{$color_key} } ) . ']';
2374 # cb_min, cb_max and cb_logscale, which were accepted here and not read.
2375 # Left out where set_options set a scale of their own, which matplotlib
2376 # would refuse beside this one.
2377 28 my $range = '';
2378 28 ▶ if ( ( ( defined $plot->{vmin} ) || ( defined $plot->{vmax} ) || $plot->{cb_logscale} ) && ( $options !~ m/\b(?:vmin|vmax|norm)\s*=/ ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"vmin"} || defined $plot->{"vmax"} || $plot->{"cb_logscale"} and not $options =~ /\b(?:vmin|vmax|norm)\s*=/) 2 26 28
Condition77%7/9
defined $plot->{"vmin"} || defined $plot->{"vmax"} || $plot->{"cb_logscale"} and not $options =~ /\b(?:vmin|vmax|norm)\s*=/
!ll&&!rl&&r
2602
defined $plot->{"vmin"} or defined $plot->{"vmax"} or $plot->{"cb_logscale"}
l!l&&r!l&&!r
1126
defined $plot->{"vmin"} or defined $plot->{"vmax"}
l!l&&r!l&&!r
1027
MC/DC50%2/4
defined $plot->{"vmin"} || defined $plot->{"vmax"} || $plot->{"cb_logscale"} and not $options =~ /\b(?:vmin|vmax|norm)\s*=/
defined $plot->{"vmin"} defined $plot->{"vmax"} $plot->{"cb_logscale"} not $options =~ /\b(?:vmin|vmax|norm)\s*=/
Truth table42%3/7
A or B or C and not(D)
A= defined $plot->{"vmin"}B= defined $plot->{"vmax"}C= $plot->{"cb_logscale"}D= not $options =~ /\b(?:vmin|vmax|norm)\s*=/
ABCDresult
000X0
1XX00
01X00
00100
1XX11
01X11
00111
2379 $range = norm_args({
2380 lo => $plot->{vmin},
2381 hi => $plot->{vmax},
2382 values => $plot->{data}{$color_key},
2383 log => $plot->{cb_logscale},
2384 fh => $args->{fh},
2385 2 sub => $current_sub
2386 });
2387 }
2388 28 say { $args->{fh} }
2389 28 "im = ax$ax.scatter(x, y, c = z, cmap = " . py_str($plot->{cmap}) . "$range $options)";
2390 # The cb* options, "cblabel", "colorbar_on" and "shared_colorbar" were
2391 # all accepted here and none of them read: the colorbar was always drawn,
2392 # labelled with the color key, with only cbpad and cbdrawedges applied.
2393 28 my $cb_opts = colorbar_args($plot);
2394 28 ▶ if ( $plot->{colorbar_on} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"colorbar_on"}) 24 4 28
2395 24 ▶ say { $args->{fh} } "fig.colorbar(im, label = " . py_str( $plot->{cblabel} // $color_key ) . " $cb_opts)";
Condition66%2/3
$plot->{"cblabel"} // $color_key
l!l&&r!l&&!r
2220
MC/DC0%0/2
$plot->{"cblabel"} // $color_key
$plot->{"cblabel"} $color_key
Truth table66%2/3
A // B
A= $plot->{"cblabel"}B= $color_key
ABresult
1X1
011
000
2396 }
2397 } else {
2398 31 say { $args->{fh} } "ax$ax.scatter(x, y $options)";
2399 }
2400 # quoted here because the key is data; see py_str above
2401 59 default_axis_labels( $plot, @keys );
2402 } elsif ( $plot_type eq 'multiple' ) { # multiple sets
2403 33 my @undefined_opts;
2404 33 foreach my $set ( sort keys %{ $plot->{set_options} } ) {
2405 6 ▶ next if grep { $set eq $_ } keys %{ $plot->{data} };
Branch: 1 branch
BranchTrueFalseTotal
if grep {$set eq $_;} keys %{$$plot{"data"};} 6 0 6
2406 0 push @undefined_opts, $set;
2407 }
2408 33 ▶ if ( scalar @undefined_opts > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undefined_opts > 0) 0 33 33
2409 0 p $plot->{data};
2410 0 p $plot;
2411 0 say STDERR 'The data and options are above, but the following sets have options without data:';
2412 0 p @undefined_opts;
2413 0 die 'no data was defined for the above options';
2414 }
2415 # As "set_options": one array of labels per set, keyed by the set's name.
2416 33 ▶ if ( defined $plot->{tooltips} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"tooltips"}) 11 22 33
2417 11 my $tt_ref = ref $plot->{tooltips};
2418 11 ▶ if ( $tt_ref ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tt_ref ne "HASH") 1 10 11
2419 1 ▶ die "$current_sub: \"data\" is a hash of sets, so \"tooltips\" is a hash of one array of labels per set, e.g. { A => ['first', 'second'] }, not "
Branch: 2 branches
BranchTrueFalseTotal
$tt_ref ? : 1 0 1
$tt_ref eq 'ARRAY' ? : 1 0 1
2420 . ( $tt_ref ? ( $tt_ref eq 'ARRAY' ? 'an' : 'a' ) . " $tt_ref reference" : 'a string' );
2421 }
2422 10 my @no_set = grep { not exists $plot->{data}{$_} } sort keys %{ $plot->{tooltips} };
2423 10 ▶ if ( scalar @no_set > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @no_set > 0) 1 9 10
2424 1 ▶ die "$current_sub: \"tooltips\" names " . join( ', ', map { "\"$_\"" } @no_set ) . ', which ' . ( scalar @no_set == 1 ? 'is not a set' : 'are not sets' ) . ' of "data"';
Branch: 1 branch
BranchTrueFalseTotal
scalar @no_set == 1 ? : 0 1 1
2425 }
2426 }
2427 # A set may be a single point, its values numbers rather than arrays:
2428 # catboost => { MAE => 0.41, R2 => 0.83 }. It is drawn as a scatter of
2429 # one point, labelled with the set's name. The wrapping goes into a copy
2430 # so that the caller's data is left as it was given.
2431 31 my %sets;
2432 31 foreach my $set ( keys %{ $plot->{data} } ) {
2433 58 my $inner = $plot->{data}{$set};
2434 58 ▶ if ( ( scalar keys %{$inner} > 0 ) && ( not grep { ref } values %{$inner} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$inner;} > 0 and not grep({ref $_;} values %{$inner;})) { } 7 51 58
Condition66%2/3
scalar keys %{$inner;} > 0 and not grep({ref $_;} values %{$inner;})
!ll&&!rl&&r
0517
MC/DC50%1/2
scalar keys %{$inner;} > 0 and not grep({ref $_;} values %{$inner;})
scalar keys %{$inner;} > 0 not grep({ref $_;} values %{$inner;})
Truth table66%2/3
A and not(B)
A= scalar keys %{$inner;} > 0B= not grep({ref $_;} values %{$inner;})
ABresult
0X0
100
111
2435 7 $sets{$set} = { map { $_ => [ $inner->{$_} ] } keys %{$inner} };
2436 } else {
2437 51 $sets{$set} = $inner;
2438 }
2439 }
2440 # The order the sets are drawn in, which is the order of the legend and
2441 # of the markers handed out below. Sorted by name before, with no way to
2442 # change it, so the groups that "df" makes with "by" came out with 10
2443 # before 2, though the documentation promised numeric order.
2444 31 my @set_order;
2445 31 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 4 27 31
2446 @set_order = check_key_order({
2447 keys => $plot->{key_order},
2448 data => $plot->{data},
2449 4 option => 'key_order',
2450 sub => $current_sub
2451 });
2452 } else {
2453 27 @set_order = sort keys %sets;
2454 }
2455 # Each set is labelled with its name, for the legend, unless this is
2456 # false. It was accepted and never read, so the legend was always drawn.
2457 31 ▶ $plot->{show_legend} = bool_option( $plot->{show_legend} // 1, 'show_legend', $current_sub );
Condition100%2/2
$plot->{"show_legend"} // 1
l!l
130
MC/DC100%1/1
$plot->{"show_legend"} // 1
$plot->{"show_legend"}
Truth table100%2/2
A
A= $plot->{"show_legend"}
Aresult
11
00
2458 # Keys and color key of every set are settled, and every value checked,
2459 # before anything is written, because the color range is shared by all
2460 # sets and so has to be known before the first set is drawn.
2461 31 my ( %xy_keys, %color_key_of, %tooltip_urls_of );
2462 31 foreach my $set ( sort keys %sets ) {
2463 54 my ( @keys, $color_key );
2464 54 ▶ if ( defined $plot->{'keys'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'keys'}) { } 7 47 54
2465 @keys = check_key_order({
2466 keys => $plot->{'keys'},
2467 7 data => $sets{$set},
2468 option => 'keys',
2469 sub => "$current_sub set \"$set\""
2470 });
2471 } else { # automatically take the key from the first; further sets should have the same labels
2472 47 ▶ @keys = sort { lc $a cmp lc $b || $a cmp $b } keys %{ $sets{$set} };
Condition33%1/3
lc $a cmp lc $b || $a cmp $b
l!l&&r!l&&!r
6200
MC/DC0%0/2
lc $a cmp lc $b || $a cmp $b
lc $a cmp lc $b $a cmp $b
Truth table33%1/3
A || B
A= lc $a cmp lc $bB= $a cmp $b
ABresult
1X1
011
000
2473 }
2474 54 my $n_keys = scalar keys %{ $sets{$set} };
2475 54 ▶ if ( ( $n_keys != 2 ) && ( $n_keys != 3 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_keys != 2 and $n_keys != 3) 0 54 54
Condition66%2/3
$n_keys != 2 and $n_keys != 3
!ll&&!rl&&r
40140
MC/DC0%0/2
$n_keys != 2 and $n_keys != 3
$n_keys != 2 $n_keys != 3
Truth table66%2/3
A and B
A= $n_keys != 2B= $n_keys != 3
ABresult
0X0
100
111
2476 0 p $plot->{data}{$set};
2477 0 die "scatterplots can only take 2 or 3 keys as data, but $current_sub received $n_keys";
2478 }
2479 54 foreach my $key (@keys) {
2480 117 check_scatter_values( $sets{$set}{$key}, "\"$key\" of set \"$set\"", $current_sub );
2481 }
2482 52 ▶ if ( defined $plot->{color_key} ) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $plot->{'color_key'}) { } 4 48 52
elsif (scalar @keys == 3) { } 7 41 48
elsif ($n_keys == 3) { } 3 38 41
2483 4 $color_key = $plot->{color_key};
2484 # before the keys are counted, as for a single set above
2485 4 ▶ if ( not defined $sets{$set}{$color_key} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $sets{$set}{$color_key}) 2 2 4
2486 2 die "\"$color_key\" isn't defined for set \"$set\"";
2487 }
2488 2 @keys = grep {$_ ne $plot->{color_key}} @keys;
2489 } elsif ( scalar @keys == 3 ) {
2490 7 $color_key = pop @keys;
2491 } elsif ( $n_keys == 3 ) {
2492 # "keys" named x and y of three inner keys, so the one it left out
2493 # is the color, as the third is when the keys are sorted. This
2494 # popped the y key off "keys" instead, and died as "Use of
2495 # uninitialized value $keys[1] in hash element".
2496 3 my %named = map { $_ => 1 } @keys;
2497 3 ▶ ($color_key) = grep { not $named{$_} } sort { lc $a cmp lc $b || $a cmp $b } keys %{ $sets{$set} };
Condition33%1/3
lc $a cmp lc $b || $a cmp $b
l!l&&r!l&&!r
800
MC/DC0%0/2
lc $a cmp lc $b || $a cmp $b
lc $a cmp lc $b $a cmp $b
Truth table33%1/3
A || B
A= lc $a cmp lc $bB= $a cmp $b
ABresult
1X1
011
000
2498 }
2499 50 ▶ if ( scalar @keys != 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @keys != 2) 1 49 50
2500 1 p @keys;
2501 1 die "$current_sub set \"$set\" needs one key for x and one for y, but \"keys\" and \"color_key\" leave the " . scalar(@keys) . ' above';
2502 }
2503 49 ▶ if ( defined $color_key ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $color_key) 11 38 49
2504 11 ▶ if (not defined $sets{$set}{$color_key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $sets{$set}{$color_key}) 0 11 11
2505 0 die "\"$color_key\" isn't defined for set \"$set\"";
2506 }
2507 11 check_scatter_values( $sets{$set}{$color_key}, "\"$color_key\" of set \"$set\"", $current_sub );
2508 11 $color_key_of{$set} = $color_key;
2509 }
2510 49 ▶ check_scatter_lengths( $sets{$set}, [ @keys, ( defined $color_key ? $color_key : () ) ], " of set \"$set\"", $current_sub );
Branch: 1 branch
BranchTrueFalseTotal
defined $color_key ? : 11 38 49
2511 48 $xy_keys{$set} = \@keys;
2512 48 ▶ $tooltip_urls_of{$set} = scatter_tooltips( ( $plot->{tooltips} // {} )->{$set}, scalar @{ $sets{$set}{ $keys[0] } }, ( $plot->{set_options} // {} )->{$set} // '', " of set \"$set\"", $current_sub );
Condition83%5/6
$plot->{"tooltips"} // {}
l!l
1830
+($plot->{"set_options"} // {})->{$set} // ""
l!l
642
$plot->{"set_options"} // {}
l!l
480
MC/DC100%1/1
$plot->{"tooltips"} // {}
$plot->{"tooltips"}
MC/DC0%0/1
+($plot->{"set_options"} // {})->{$set} // ""
$plot->{"set_options"}
Truth table100%2/2
A
A= $plot->{"tooltips"}
Aresult
11
00
Truth table50%1/2
A
A= $plot->{"set_options"}
Aresult
11
00
2513 }
2514 # One color scale for every set. Each ax.scatter normalises its own c to
2515 # its own minimum and maximum, so without this the same color meant a
2516 # different value in each set, the colorbar -- drawn from the last set --
2517 # was true only of that set, and a set of one point was always drawn in
2518 # the bottom color of the map whatever its value.
2519 21 my $color_range = '';
2520 21 ▶ if ( scalar keys %color_key_of > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %color_key_of > 0) 5 16 21
2521 5 my @z = finite_values( map { @{ $sets{$_}{ $color_key_of{$_} } } } keys %color_key_of );
2522 # cb_min, cb_max and cb_logscale, where given, set the ends and the
2523 # kind of the shared scale; they were accepted and not read.
2524 $color_range = norm_args({
2525 lo => $plot->{vmin},
2526 hi => $plot->{vmax},
2527 values => \@z,
2528 log => $plot->{cb_logscale},
2529 fh => $args->{fh},
2530 5 sub => $current_sub
2531 });
2532 }
2533 # The key the one colorbar is labelled with, from the last set that has
2534 # one. Kept apart from each set's own $color_key, which used to be this
2535 # same variable: a set with a third key left it defined for every set
2536 # after it, and a later set of only x and y died as '"z" isn't defined'.
2537 21 my $colorbar_key;
2538 # Sets colored by a third key are all drawn from the same colormap, so
2539 # color cannot tell them apart; each takes the next of these markers, in
2540 # the sorted order of the set names, unless its set_options name one. All
2541 # are filled, so each shows its color; the list repeats once it runs out. A
2542 # marker that set_options give to some set is left out, so that no other
2543 # set is given it too.
2544 4 my %taken = map { $_ => 1 } grep { defined }
2545 21 ▶ map { m/\bmarker\s*=\s*['"]([^'"]+)['"]/ ? $1 : undef } values %{ $plot->{set_options} // {} };
Branch: 1 branch
BranchTrueFalseTotal
/\bmarker\s*=\s*['"]([^'"]+)['"]/ ? : 4 1 5
Condition50%1/2
$plot->{"set_options"} // {}
l!l
210
MC/DC0%0/1
$plot->{"set_options"} // {}
$plot->{"set_options"}
Truth table50%1/2
A
A= $plot->{"set_options"}
Aresult
11
00
2546 21 my @markers = grep { not $taken{$_} } qw(o s ^ D v P X * < > p h d);
2547 21 ▶ @markers = ('o') if scalar @markers == 0; # all 13 taken: repeat the first
Branch: 1 branch
BranchTrueFalseTotal
if scalar @markers == 0 0 21 21
2548 21 my $marker_i = 0;
2549 21 foreach my $set (@set_order) {
2550 42 my $options = '';
2551 42 my @keys = @{ $xy_keys{$set} };
2552 42 my $color_key = $color_key_of{$set};
2553 42 ▶ if ( defined $plot->{set_options}{$set} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_options"}{$set}) 5 37 42
2554 5 $options = ", $plot->{set_options}{$set}";
2555 }
2556 42 say { $args->{fh} } 'x = [' . py_nums( @{ $sets{$set}{ $keys[0] } } ) . ']';
2557 42 say { $args->{fh} } 'y = [' . py_nums( @{ $sets{$set}{ $keys[1] } } ) . ']';
2558 # The set's name as its label, unless it has a label of its own: the
2559 # uncolored path below added one regardless, and a "label" in
2560 # "set_options" made "keyword argument repeated", a SyntaxError.
2561 42 ▶ if ( ( $plot->{show_legend} ) && ( $options !~ m/\blabel\s*=/ ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"show_legend"} and not $options =~ /\blabel\s*=/) 38 4 42
Condition100%3/3
$plot->{"show_legend"} and not $options =~ /\blabel\s*=/
!ll&&!rl&&r
2238
MC/DC100%2/2
$plot->{"show_legend"} and not $options =~ /\blabel\s*=/
$plot->{"show_legend"} not $options =~ /\blabel\s*=/
Truth table100%3/3
A and not(B)
A= $plot->{"show_legend"}B= not $options =~ /\blabel\s*=/
ABresult
0X0
100
111
2562 38 $options .= ', label = ' . py_str($set);
2563 }
2564 42 $options .= write_tooltip_urls( $tooltip_urls_of{$set}, $args->{fh} );
2565 42 ▶ if ( defined $color_key ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $color_key) { } 10 32 42
2566 10 $colorbar_key = $color_key;
2567 10 say { $args->{fh} } 'z = [' . py_nums( @{ $sets{$set}{$color_key} } ) . ']';
2568 10 ▶ unless ( $options =~ m/\bmarker\s*=/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options =~ /\bmarker\s*=/) 9 1 10
2569 9 $options .= ", marker = '$markers[ $marker_i % @markers ]'";
2570 9 $marker_i++;
2571 }
2572 # a set's own vmin, vmax or norm is its caller's decision, and
2573 # matplotlib refuses norm alongside vmin and vmax
2574 10 ▶ my $range = ( $options =~ m/\b(?:vmin|vmax|norm)\s*=/ ) ? '' : $color_range;
Branch: 1 branch
BranchTrueFalseTotal
$options =~ /\b(?:vmin|vmax|norm)\s*=/ ? : 1 9 10
2575 10 say { $args->{fh} }
2576 10 "im = ax$ax.scatter(x, y, c = z, cmap = " . py_str($plot->{cmap}) . "$range $options)";
2577 } else {
2578 32 say { $args->{fh} } "ax$ax.scatter(x, y$options)";
2579 }
2580 # quoted here because the key is data; see py_str above
2581 42 default_axis_labels( $plot, @keys );
2582 }
2583 21 ▶ if ( defined $colorbar_key ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $colorbar_key) 5 16 21
2584 5 my $cb_opts = colorbar_args($plot);
2585 5 ▶ if ( $plot->{colorbar_on} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"colorbar_on"}) 5 0 5
2586 5 ▶ say { $args->{fh} } 'plt.colorbar(im, label = ' . py_str( $plot->{cblabel} // $colorbar_key ) . "$cb_opts)";
Condition33%1/3
$plot->{"cblabel"} // $colorbar_key
l!l&&r!l&&!r
050
MC/DC0%0/2
$plot->{"cblabel"} // $colorbar_key
$plot->{"cblabel"} $colorbar_key
Truth table33%1/3
A // B
A= $plot->{"cblabel"}B= $colorbar_key
ABresult
1X1
011
000
2587 }
2588 }
2589 }
2590 }
2591  
2592 28 ▶sub violin_helper {
Subroutine violin_helper: called CC=28 SCAR=33.4
Pod undocumented
2593 28 my ($args) = @_;
2594 28 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
2595 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
2596 28 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 28 28
2597 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
2598 }
2599 28 my @reqd_args = (
2600 'fh', # e.g. $py, $fh, which will be passed by the subroutine
2601 'plot', # args to original function
2602 );
2603 28 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
2604 28 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 28 28
2605 0 p @undef_args;
2606 0 die 'the above args are necessary, but were not defined.';
2607 }
2608 28 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
2609 28 my $plot = $args->{plot};
2610 my @undef_opt = grep {
2611 187 my $key = $_;
2612 187 not grep { $_ eq $key } @opt
2613 28 } keys %{$plot};
2614 28 ▶ if ( scalar @undef_opt > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_opt > 0) 0 28 28
2615 bad_keyword_error({
2616 bad => \@undef_opt,
2617 accepted => \@opt,
2618 preferred => $opt{$current_sub},
2619 type => $plot->{plot_type},
2620 0 sub => $current_sub
2621 });
2622 }
2623 28 ▶ $plot->{orientation} = $plot->{orientation} // 'vertical';
Condition100%2/2
$plot->{"orientation"} // "vertical"
l!l
127
MC/DC100%1/1
$plot->{"orientation"} // "vertical"
$plot->{"orientation"}
Truth table100%2/2
A
A= $plot->{"orientation"}
Aresult
11
00
2624 28 ▶ if ( $plot->{orientation} !~ m/^(?:horizontal|vertical)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($plot->{"orientation"} =~ /^(?:horizontal|vertical)$/) 0 28 28
2625 0 die "$current_sub needs either \"horizontal\" or \"vertical\", not \"$plot->{orientation}\"";
2626 }
2627 28 ▶ if (ref $plot->{data} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"data"} eq "ARRAY") 3 25 28
2628 3 my $tmp = delete $plot->{data};
2629 3 $plot->{data}{''} = $tmp;
2630 }
2631 28 my ( @xticks, @key_order );
2632 28 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 2 26 28
2633 @key_order = check_key_order({
2634 keys => $plot->{key_order},
2635 data => $plot->{data},
2636 2 option => 'key_order',
2637 sub => $current_sub
2638 });
2639 } else {
2640 26 @key_order = sort keys %{ $plot->{data} };
2641 }
2642 27 ▶ my $ax = $args->{ax} // '';
Condition50%1/2
$args->{"ax"} // ""
l!l
270
MC/DC0%0/1
$args->{"ax"} // ""
$args->{"ax"}
Truth table50%1/2
A
A= $args->{"ax"}
Aresult
11
00
2643 # Read as Python bools, as boxplot's switches are: "medians" was written as
2644 # given, so "medians => 'yes'" left "showmedians = yes" in the script, and
2645 # "whiskers" was tested for Perl truth, in which 'False' is true.
2646 27 ▶ $plot->{medians} = bool_option( $plot->{medians} // 1, 'medians', $current_sub ) ? 'True' : 'False'; # by default, show median values
Branch: 1 branch
BranchTrueFalseTotal
bool_option($plot->{'medians'} // 1, 'medians', $current_sub) ? : 24 2 26
Condition100%2/2
$plot->{"medians"} // 1
l!l
324
MC/DC100%1/1
$plot->{"medians"} // 1
$plot->{"medians"}
Truth table100%2/2
A
A= $plot->{"medians"}
Aresult
11
00
2647 26 ▶ $plot->{whiskers} = bool_option( $plot->{whiskers} // 1, 'whiskers', $current_sub ); # by default, make whiskers
Condition100%2/2
$plot->{"whiskers"} // 1
l!l
224
MC/DC100%1/1
$plot->{"whiskers"} // 1
$plot->{"whiskers"}
Truth table100%2/2
A
A= $plot->{"whiskers"}
Aresult
11
00
2648 # As in boxplot_helper: a hash here was written as 'HASH(0x...)'.
2649 26 ▶ if ( ref $plot->{color} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"color"}) 1 25 26
2650 1 die "\"color\" is one color for every violin in $current_sub, not a " . ref( $plot->{color} ) . ' reference; give one color per key in "colors", e.g. colors => { A => \'red\' }';
2651 }
2652 25 ▶ $plot->{edgecolor} = $plot->{edgecolor} // 'black';
Condition100%2/2
$plot->{"edgecolor"} // "black"
l!l
223
MC/DC100%1/1
$plot->{"edgecolor"} // "black"
$plot->{"edgecolor"}
Truth table100%2/2
A
A= $plot->{"edgecolor"}
Aresult
11
00
2653 25 my $options = ''; # these args go to the plt.hist call
2654 25 say { $args->{fh} } 'd = []';
2655 # %values, rather than writing the filtered list back into $plot->{data}:
2656 # the arrays in there belong to the caller, and dropping the undefined and
2657 # non-numeric elements in place left the caller's own array shorter than
2658 # they wrote it.
2659 25 my %values;
2660 25 foreach my $key (@key_order) {
2661 37 ▶ @{ $values{$key} } = grep { ( defined ) && looks_like_number($_) && ( not is_nan($_) ) } @{ $plot->{data}{$key} };
Condition83%5/6
defined $_ && &looks_like_number($_) && !is_nan($_)
!ll&&!rl&&r
40381
defined $_ and &looks_like_number($_)
!ll&&!rl&&r
22381
MC/DC66%2/3
defined $_ && &looks_like_number($_) && !is_nan($_)
defined $_ &looks_like_number($_) !is_nan($_)
Truth table75%3/4
A and B && not(C)
A= defined $_B= &looks_like_number($_)C= !is_nan($_)
ABCresult
0XX0
10X0
1100
1111
2662 # A group left with nothing in it has no mean to draw, and the mean is
2663 # computed by dividing by this count: it died as "Use of uninitialized
2664 # value in division", which named neither the group nor the filtering
2665 # that emptied it.
2666 37 ▶ if ( scalar @{ $values{$key} } == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$values{$key};} == 0) 1 36 37
2667 1 my $n_given = scalar @{ $plot->{data}{$key} };
2668 1 die "\"$key\" has no numeric values for $current_sub to plot ($n_given value(s) given, all undefined, NaN or non-numeric)";
2669 }
2670 # An infinity gives the density estimate nothing to spread over and made
2671 # the mean below "Inf", written into the script as a bare name.
2672 36 my @infinite = grep { not is_finite($_) } @{ $values{$key} };
2673 36 ▶ if ( scalar @infinite > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @infinite > 0) 1 35 36
2674 1 p @infinite;
2675 1 die "\"$key\" has the above infinite values, which $current_sub cannot draw a density for";
2676 }
2677 35 say { $args->{fh} } 'd.append(['
2678 35 . py_nums( @{ $values{$key} } ) . '])';
2679 }
2680 23 foreach my $axis ( logscale_axes( $plot->{logscale}, $current_sub ) ) { # x, y
2681 2 say {$args->{fh}} "ax$ax.set_$axis" . 'scale("log")';
2682 }
2683 # No "points": it is how many points the density curve is evaluated at,
2684 # not a count of data, and it used to be set to the size of the smallest
2685 # group, so a group of 5 values drew every violin as a 5-sided polygon.
2686 # matplotlib's default is 100.
2687 20 say { $args->{fh} } "vp = ax$ax.violinplot(d, showmeans=False, orientation = '$plot->{orientation}', showmedians = $plot->{medians})";
2688 20 ▶ if ( defined $plot->{colors} ) { # every hash key should have its own color defined
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'colors'}) { } 2 18 20
2689 # the below code helps to provide better error messages in case I make an error in calling the sub
2690 2 my @wrong_keys = grep { not defined $plot->{colors}{$_} } keys %{ $plot->{data} };
2691 2 ▶ if ( scalar @wrong_keys > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @wrong_keys > 0) 1 1 2
2692 1 p $plot;
2693 1 p @wrong_keys;
2694 1 die 'the above data keys have no defined color';
2695 }
2696 # list of pre-defined colors: https://matplotlib.org/stable/gallery/color/named_colors.html
2697 1 say { $args->{fh} } 'colors = ['
2698 1 . py_list( @{ $plot->{colors} }{@key_order} ) . ']';
2699  
2700 # the above color list will have the same order, via the above hash slice
2701 1 say { $args->{fh} } 'for i, pc in enumerate(vp["bodies"], 1):';
2702 1 say { $args->{fh} } "\tpc.set_facecolor(colors[i-1])";
2703 1 say { $args->{fh} } "\tpc.set_edgecolor(" . py_str( $plot->{edgecolor} ) . ')';
2704 } else {
2705 18 say { $args->{fh} } 'for pc in vp["bodies"]:';
2706 18 ▶ if ( defined $plot->{color} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"color"}) 1 17 18
2707 1 say { $args->{fh} } "\tpc.set_facecolor(" . py_str($plot->{color}) . ')';
2708 }
2709 18 say { $args->{fh} } "\tpc.set_edgecolor(" . py_str( $plot->{edgecolor} ) . ')';
2710  
2711 # say {$args->{fh}} "\tpc.set_alpha(1)";
2712 }
2713 19 ▶ if ( $plot->{whiskers} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"whiskers"}) 17 2 19
2714 # https://matplotlib.org/stable/gallery/statistics/customized_violin.html
2715 17 say {$args->{fh} } 'import numpy as np';
2716 17 say {$args->{fh} } 'def adjacent_values(vals, q1, q3):';
2717 17 say {$args->{fh} } ' upper_adjacent_value = q3 + (q3 - q1) * 1.5';
2718 17 say {$args->{fh} }
2719 ' upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])';
2720 17 say {$args->{fh} } ' lower_adjacent_value = q1 - (q3 - q1) * 1.5';
2721 17 say {$args->{fh} }
2722 ' lower_adjacent_value = np.clip(lower_adjacent_value, vals[0], q1)';
2723 17 say {$args->{fh} }
2724 ' return lower_adjacent_value, upper_adjacent_value';
2725 17 say {$args->{fh} } 'np_data = np.array(d, dtype = object)';
2726 17 say {$args->{fh} } 'quartile1 = []';
2727 17 say {$args->{fh} } 'medians = []';
2728 17 say {$args->{fh} } 'quartile3 = []';
2729 17 say {$args->{fh} } 'for subset in list(range(0, len(np_data))):';
2730 17 say {$args->{fh}} ' local_quartile1, local_medians, local_quartile3 = np.percentile(d[subset], [25, 50, 75])' . "\n";
2731 17 say {$args->{fh}} ' quartile1.append(local_quartile1)';
2732 17 say {$args->{fh}} ' medians.append(local_medians)';
2733 17 say {$args->{fh}} ' quartile3.append(local_quartile3)';
2734 # sorted(): adjacent_values reads the smallest and largest values as
2735 # vals[0] and vals[-1]. matplotlib's example sorts its data first; this
2736 # passed "d" in the caller's order, so for [10, 9, ..., 1, 100] the
2737 # lower whisker was clipped to q1 and not drawn at all.
2738 17 say {$args->{fh}} 'whiskers = np.array([';
2739 17 say {$args->{fh}} ' adjacent_values(sorted(subset), q1, q3)';
2740 17 say {$args->{fh}} ' for subset, q1, q3 in zip(d, quartile1, quartile3)])';
2741 17 say {$args->{fh}} 'whiskers_min, whiskers_max = whiskers[:, 0], whiskers[:, 1]';
2742 17 say {$args->{fh}} 'inds = np.arange(1, len(medians) + 1)';
2743 17 ▶ if ( $plot->{orientation} eq 'vertical' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{'orientation'} eq 'vertical') { } 16 1 17
2744 16 say { $args->{fh} } "ax$ax"
2745 . '.vlines(inds, quartile1, quartile3, color="k", linestyle="-", lw=5)';
2746 16 say { $args->{fh} } "ax$ax"
2747 . '.vlines(inds, whiskers_min, whiskers_max, color="k", linestyle="-", lw=1)';
2748 } else {
2749 1 say { $args->{fh} } "ax$ax"
2750 . '.hlines(inds, quartile1, quartile3, color="k", linestyle="-", lw=5)';
2751 1 say { $args->{fh} } "ax$ax"
2752 . '.hlines(inds, whiskers_min, whiskers_max, color="k", linestyle="-", lw=1)';
2753 }
2754 }
2755 19 foreach my $key (@key_order) {
2756 push @xticks, "$key ("
2757 28 . format_commas( scalar @{ $values{$key} }, '%.0u' ) . ')';
2758 28 my $mean = sum( @{ $values{$key} } ) / scalar @{ $values{$key} };
2759 28 ▶ if ( $plot->{orientation} eq 'vertical' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{'orientation'} eq 'vertical') { } 26 2 28
2760 26 say { $args->{fh} } "ax$ax.plot("
2761 . scalar @xticks . ", $mean"
2762 . ', "ro")'; # plot mean point, which is red
2763 } else { # orientation = horizontal
2764 2 say { $args->{fh} } "ax$ax.plot($mean, "
2765 . scalar @xticks . ', "ro")'; # plot mean point, which is red
2766 }
2767 }
2768 19 ▶ if ( $plot->{orientation} eq 'vertical' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{'orientation'} eq 'vertical') { } 18 1 19
2769 18 say { $args->{fh} } "ax$ax.set_xticks(["
2770 . join( ',', 1 .. scalar @key_order ) . '], ['
2771 . py_list(@xticks) . '])';
2772 } else {
2773 1 say { $args->{fh} } "ax$ax.set_yticks(["
2774 . join( ',', 1 .. scalar @key_order ) . '], ['
2775 . py_list(@xticks) . '])';
2776 }
2777 }
2778  
2779 15 ▶sub write_wide_group {
Subroutine write_wide_group: called CC=4 SCAR=13.9
Pod undocumented
2780 # Emit the Python drawing one group of runs: every run faint, the mean of
2781 # the runs solid, and mean +/- 1 standard deviation as a ribbon.
2782 #
2783 # The runs need not share an x grid, so they are interpolated onto 101
2784 # evenly spaced points (the number the documentation promises) spanning
2785 # the group's own x range. Two properties of np.interp drive the code
2786 # below: it needs its sample points ascending, and by default it holds the
2787 # end values flat outside them. Left alone, the first silently returns a
2788 # flat line for a run whose x descends, and the second folds an invented
2789 # horizontal line into the mean and the s.d. wherever a run stops short of
2790 # the group's range. So each run is sorted by x first, and asked for NaN
2791 # outside its own range; the summary below then averages, at each point,
2792 # only the runs that actually reach it.
2793 15 my ($args) = @_;
2794 my ( $fh, $ax, $runs, $color, $label ) =
2795 15 @{$args}{qw(fh ax runs color label)};
2796 15 my ( $min_x, $max_x ) = ( 'inf', '-inf' );
2797 15 foreach my $run ( @{$runs} ) {
2798 35 $min_x = min( $min_x, finite_values( @{ $run->[0] } ) );
2799 35 $max_x = max( $max_x, finite_values( @{ $run->[0] } ) );
2800 }
2801 15 my $py_color = py_str($color);
2802 15 say {$fh} 'ys = []';
2803 15 say {$fh} 'base_x = np.linspace(' . py_num($min_x) . ', ' . py_num($max_x) . ', 101)';
2804 15 foreach my $run ( @{$runs} ) {
2805 35 say {$fh} 'x = [' . py_nums( @{ $run->[0] } ) . ']';
2806 35 say {$fh} 'y = [' . py_nums( @{ $run->[1] } ) . ']';
2807 35 say {$fh} "order = np.argsort(x, kind = 'stable')";
2808 35 say {$fh} 'x = np.asarray(x)[order]';
2809 35 say {$fh} 'y = np.asarray(y)[order]';
2810 35 say {$fh} "ax$ax.plot(x, y, $py_color, alpha=0.15)";
2811 35 say {$fh} 'ys.append(np.interp(base_x, x, y, left = np.nan, right = np.nan))';
2812 }
2813 15 say {$fh} 'ys = np.array(ys)';
2814 15 say {$fh} 'covered = ~np.isnan(ys)'; # which runs reach each point of base_x
2815 15 say {$fh} 'n_runs = covered.sum(axis = 0)';
2816 15 say {$fh} 'divisor = np.maximum(n_runs, 1)'; # a point no run reaches would divide by 0
2817 15 say {$fh} 'mean_ys = np.where(covered, ys, 0.0).sum(axis = 0) / divisor';
2818 15 say {$fh} 'var_ys = np.where(covered, (ys - mean_ys) ** 2, 0.0).sum(axis = 0) / divisor';
2819 15 say {$fh} 'std = np.where(n_runs > 0, np.sqrt(var_ys), np.nan)';
2820 15 say {$fh} 'mean_ys = np.where(n_runs > 0, mean_ys, np.nan)'; # after var_ys, which needs the unmasked mean
2821 15 say {$fh} 'ys_upper = mean_ys + std';
2822 15 say {$fh} 'ys_lower = mean_ys - std';
2823 15 ▶ if ( defined $label ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $label) { } 9 6 15
2824 9 say {$fh} "ax$ax.plot(base_x, mean_ys, $py_color, label = " . py_str($label) . ')';
2825 } else {
2826 6 say {$fh} "ax$ax.plot(base_x, mean_ys, $py_color)";
2827 }
2828 15 say {$fh} "ax$ax.fill_between(base_x, ys_lower, ys_upper, color=$py_color, alpha=0.3)";
2829 }
2830 18 ▶sub wide_helper {
Subroutine wide_helper: called CC=15 SCAR=27.8
Pod undocumented
2831 18 my ($args) = @_;
2832 18 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
2833 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
2834 18 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 18 18
2835 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
2836 }
2837 18 my @reqd_args = (
2838 'fh', # e.g. $py, $fh, which will be passed by the subroutine
2839 'plot', # args to original function
2840 );
2841 18 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
2842 18 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 18 18
2843 0 p @undef_args;
2844 0 die "the above args are necessary for $current_sub, but were not defined.";
2845 }
2846 18 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
2847 18 my $plot = $args->{plot};
2848 18 ▶ $plot->{show_legend} = bool_option( $plot->{show_legend} // 1, 'show_legend', $current_sub );
Condition100%2/2
$plot->{"show_legend"} // 1
l!l
117
MC/DC100%1/1
$plot->{"show_legend"} // 1
$plot->{"show_legend"}
Truth table100%2/2
A
A= $plot->{"show_legend"}
Aresult
11
00
2849 my @undef_opt = grep {
2850 135 my $key = $_;
2851 135 not grep { $_ eq $key } @opt
2852 18 } keys %{$plot};
2853 18 ▶ if ( scalar @undef_opt > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_opt > 0) 0 18 18
2854 bad_keyword_error({
2855 bad => \@undef_opt,
2856 accepted => \@opt,
2857 preferred => $opt{$current_sub},
2858 type => $plot->{plot_type},
2859 0 sub => $current_sub
2860 });
2861 }
2862 18 say { $args->{fh} } 'import numpy as np';
2863 18 ▶ my $ax = $args->{ax} // '';
Condition50%1/2
$args->{"ax"} // ""
l!l
180
MC/DC0%0/1
$args->{"ax"} // ""
$args->{"ax"}
Truth table50%1/2
A
A= $args->{"ax"}
Aresult
11
00
2864 18 my $ref_type = ref $plot->{data};
2865 18 ▶ if ( $ref_type eq 'HASH' ) { # one labelled group per key
Branch: 2 branches
BranchTrueFalseTotal
if ($ref_type eq 'HASH') { } 9 9 18
elsif ($ref_type eq 'ARRAY') { } 9 0 9
2866 9 ▶ if ( ( defined $plot->{color} ) && ( ref $plot->{color} ne 'HASH' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"color"} and ref $plot->{"color"} ne "HASH") 1 8 9
Condition100%3/3
defined $plot->{"color"} and ref $plot->{"color"} ne "HASH"
!ll&&!rl&&r
531
MC/DC100%2/2
defined $plot->{"color"} and ref $plot->{"color"} ne "HASH"
defined $plot->{"color"} ref $plot->{"color"} ne "HASH"
Truth table100%3/3
A and B
A= defined $plot->{"color"}B= ref $plot->{"color"} ne "HASH"
ABresult
0X0
100
111
2867 1 die "$current_sub: \"data\" is a HASH of groups, so \"color\" must be a HASH of one color per group";
2868 }
2869 # Sorted, as every other plot type orders its keys: in hash order the
2870 # groups, and so the legend, came out in a different order from one
2871 # run to the next.
2872 8 my $group_i = 0;
2873 8 foreach my $group ( sort keys %{ $plot->{data} } ) {
2874 14 check_wide_runs( $plot->{data}{$group}, "group \"$group\"", $current_sub );
2875 # An uncolored group takes the next color of matplotlib's own
2876 # cycle, "C0", "C1" and on. Every group used to default to 'b', so
2877 # without a "color" hash the groups could not be told apart.
2878 write_wide_group({
2879 fh => $args->{fh},
2880 ax => $ax,
2881 runs => $plot->{data}{$group},
2882 color => $plot->{color}{$group} // 'C' . ( $group_i % 10 ), # the default cycle has 10 colors
2883 11 ▶ label => $plot->{show_legend} ? $group : undef
Branch: 1 branch
BranchTrueFalseTotal
$plot->{'show_legend'} ? : 9 2 11
Condition100%2/2
$plot->{"color"}{$group} // 'C' . $group_i % 10
l!l
56
MC/DC100%1/1
$plot->{"color"}{$group} // 'C' . $group_i % 10
$plot->{"color"}{$group}
Truth table100%2/2
A
A= $plot->{"color"}{$group}
Aresult
11
00
2884 });
2885 11 $group_i++;
2886 }
2887 } elsif ( $ref_type eq 'ARRAY' ) { # one unlabelled group
2888 9 ▶ if ( ref $plot->{color} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"color"}) 1 8 9
2889 1 die "$current_sub: \"data\" is one unlabelled group, so \"color\" must be a single color, not a " . ( ref $plot->{color} ) . ' reference';
2890 }
2891 8 check_wide_runs( $plot->{data}, '"data"', $current_sub );
2892 write_wide_group({
2893 fh => $args->{fh},
2894 ax => $ax,
2895 runs => $plot->{data},
2896 4 ▶ color => $plot->{color} // 'b',
Condition50%1/2
$plot->{"color"} // "b"
l!l
40
MC/DC0%0/1
$plot->{"color"} // "b"
$plot->{"color"}
Truth table50%1/2
A
A= $plot->{"color"}
Aresult
11
00
2897 label => undef # the array form carries no group name to label
2898 });
2899 } else {
2900 0 die "$current_sub cannot take ref type \"$ref_type\" for \"data\"";
2901 }
2902 }
2903  
2904 25 ▶sub print_type {
Subroutine print_type: called CC=15 SCAR=29.1
Pod undocumented
2905 # Whether a value has to be quoted on its way into the generated Python.
2906 25 my $str = shift;
2907 25 my $type = 'no quotes';
2908 25 ▶ if (looks_like_number($str)) { # numbers (e.g. 0.8) must not be quoted
Branch: 1 branch
BranchTrueFalseTotal
if (&looks_like_number($str)) 2 23 25
2909 2 return 'no quotes';
2910 }
2911 # An argument list of bare values, such as "0, 10" for "ylim" or "0.5, 0, 1"
2912 # for "axhline", is Python rather than text. The comma tests below quoted
2913 # it, so a single plot's "ylim => '0, 10'" wrote plt.ylim('0, 10') and died
2914 # as "ValueError: too many values to unpack". None, True and False are bare
2915 # values too, so that
2916 # "ylim => 'None, 10'" leaves the bottom where matplotlib puts it.
2917 23 my @items = split /,/, $str, -1;
2918 23 ▶ if ( ( scalar @items > 1 )
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @items > 1 and not grep({not &looks_like_number($_) || $_ =~ /^\h*(?:None|True|False)\h*$/;} @items)) 2 21 23
Condition100%3/3
scalar @items > 1 and not grep({not &looks_like_number($_) || $_ =~ /^\h*(?:None|True|False)\h*$/;} @items)
!ll&&!rl&&r
1382
MC/DC100%2/2
scalar @items > 1 and not grep({not &looks_like_number($_) || $_ =~ /^\h*(?:None|True|False)\h*$/;} @items)
scalar @items > 1 not grep({not &looks_like_number($_) || $_ =~ /^\h*(?:None|True|False)\h*$/;} @items)
Truth table100%3/3
A and not(B)
A= scalar @items > 1B= not grep({not &looks_like_number($_) || $_ =~ /^\h*(?:None|True|False)\h*$/;} @items)
ABresult
0X0
100
111
2919 20 ▶ && ( not grep { ( not looks_like_number($_) ) && ( $_ !~ m/^\h*(?:None|True|False)\h*$/ ) } @items ) ) {
Condition100%3/3
&looks_like_number($_) || $_ =~ /^\h*(?:None|True|False)\h*$/
l!l&&r!l&&!r
4115
MC/DC100%2/2
&looks_like_number($_) || $_ =~ /^\h*(?:None|True|False)\h*$/
&looks_like_number($_) $_ =~ /^\h*(?:None|True|False)\h*$/
Truth table100%3/3
A || B
A= &looks_like_number($_)B= $_ =~ /^\h*(?:None|True|False)\h*$/
ABresult
1X1
011
000
2920 2 return 'no quotes';
2921 }
2922 # A single Python value: None, True or False; one bracketed group, such as
2923 # "(0, 10)" or "[]"; or one call, such as "np.arange(0, 1, 0.1)". Each was
2924 # quoted below, which a single plot always did and a subplot does now that
2925 # it quotes as well. The bracket must close at the very end, so that
2926 # "f(x), g(x)" is still text.
2927 21 ▶ if ( ( $str =~ m/^\h*(?:None|True|False)\h*$/ )
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /^\h*(?:None|True|False)\h*$/ or $str =~ /^\h*(?:[A-Za-z_][\w.]*)?(\((?:[^()]++|(?1))*\))\h*$/ or $str =~ /^\h*(\[(?:[^\[\]]++|(?1))*\])\h*$/) 7 14 21
Condition83%5/6
$str =~ /^\h*(?:None|True|False)\h*$/ or $str =~ /^\h*(?:[A-Za-z_][\w.]*)?(\((?:[^()]++|(?1))*\))\h*$/ or $str =~ /^\h*(\[(?:[^\[\]]++|(?1))*\])\h*$/
l!l&&r!l&&!r
7014
$str =~ /^\h*(?:None|True|False)\h*$/ or $str =~ /^\h*(?:[A-Za-z_][\w.]*)?(\((?:[^()]++|(?1))*\))\h*$/
l!l&&r!l&&!r
3414
MC/DC66%2/3
$str =~ /^\h*(?:None|True|False)\h*$/ or $str =~ /^\h*(?:[A-Za-z_][\w.]*)?(\((?:[^()]++|(?1))*\))\h*$/ or $str =~ /^\h*(\[(?:[^\[\]]++|(?1))*\])\h*$/
$str =~ /^\h*(?:None|True|False)\h*$/ $str =~ /^\h*(?:[A-Za-z_][\w.]*)?(\((?:[^()]++|(?1))*\))\h*$/ $str =~ /^\h*(\[(?:[^\[\]]++|(?1))*\])\h*$/
Truth table75%3/4
A or B or C
A= $str =~ /^\h*(?:None|True|False)\h*$/B= $str =~ /^\h*(?:[A-Za-z_][\w.]*)?(\((?:[^()]++|(?1))*\))\h*$/C= $str =~ /^\h*(\[(?:[^\[\]]++|(?1))*\])\h*$/
ABCresult
1XX1
01X1
0011
0000
2928 || ( $str =~ m/^\h*(?:[A-Za-z_][\w.]*)?(\((?:[^()]++|(?1))*\))\h*$/ )
2929 || ( $str =~ m/^\h*(\[(?:[^\[\]]++|(?1))*\])\h*$/ ) ) {
2930 7 return 'no quotes';
2931 }
2932 # Text that already carries a quote of its own is Python the caller wrote
2933 # -- a quoted label ('"Counts, by book"', the form the documentation asks
2934 # for when the text holds a comma), a mathtext raw string, or a whole
2935 # argument list such as '0.5, 0.01, "note"'. Quoting it again nests the
2936 # quotes and emits plt.suptitle(''Counts, by book''), a SyntaxError. This
2937 # generalises the "keyword = <quote>" test below, which caught the same
2938 # thing only when the quote followed an "=".
2939 14 ▶ if ($str =~ m/['"]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /['"]/) 10 4 14
2940 10 return 'no quotes';
2941 }
2942 # A keyword argument, e.g. "hspace = 0.5" or "loc = 'upper left'": already
2943 # Python, whether or not its value is quoted.
2944 4 ▶ if ($str =~ m/\w\h*=\h*\S/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /\w\h*=\h*\S/) 0 4 4
2945 0 return 'no quotes';
2946 }
2947 4 ▶ if ($str =~ m/^\w+$/) {
Branch: 4 branches
BranchTrueFalseTotal
if ($str =~ /^\w+$/) { } 3 1 4
elsif ($str =~ /^\[\h*\-?\d.+\d\h*\]$/) { } 0 1 1
elsif ($str =~ m"[!\@#\$\%^&*\(\)\{\}\[\]\<\>,/\-\h:;\+=\w]+$") { } 1 0 1
elsif ($str =~ /,/ and not $str =~ /[\]\[]/) { } 0 0 0
2948 3 return 'single quotes';
2949 } elsif ($str =~ m/^\[\h*\-?\d.+\d\h*\]$/) {
2950 0 return 'no quotes';
2951 } elsif ($str =~ m/[!@#\$\%^&*\(\)\{\}\[\]\<\>,\/\-\h:;\+=\w]+$/) {
2952 1 return 'single quotes';
2953 ▶ } elsif (($str =~ m/,/) && ($str !~ m/[\]\[]/)) {
Condition0%0/3
$str =~ /,/ and not $str =~ /[\]\[]/
!ll&&!rl&&r
000
MC/DC0%0/2
$str =~ /,/ and not $str =~ /[\]\[]/
$str =~ /,/ not $str =~ /[\]\[]/
Truth table0%0/3
A and not(B)
A= $str =~ /,/B= not $str =~ /[\]\[]/
ABresult
0X0
100
111
2954 0 return 'single quotes';
2955 }
2956 0 return $type;
2957 }
2958 25 ▶sub pyplot_arg {
Subroutine pyplot_arg: called CC=2 SCAR=6.9
Pod undocumented
2959 # A pyplot option's value as the text between the parentheses of its call.
2960 #
2961 # A single plot and a subplot both write their pyplot options through
2962 # this. A subplot used to write every value exactly as given, so
2963 # "xscale => 'log'" left plt.xscale(log) and raised "NameError: name 'log'
2964 # is not defined", while the same option at a single plot was quoted.
2965 # py_str, not "'$value'": a backslash in '...' went through as a python
2966 # escape, so "C:\new" came out with a newline in it.
2967 25 my ($value) = @_;
2968 25 ▶ return print_type($value) eq 'single quotes' ? py_str($value) : $value;
Branch: 1 branch
BranchTrueFalseTotal
print_type($value) eq 'single quotes' ? : 4 21 25
2969 }
2970 # The interpreters tried on MSWin32, in order. "python" first, because it is
2971 # what a stock install from python.org and an activated venv both put on PATH,
2972 # and the venv is the one that has matplotlib; "py -3", the launcher, next,
2973 # since an install can leave python off PATH but always installs the
2974 # launcher; "python3" last, for MSYS2 and the like. A stock Windows install has
2975 # no "python3" at all, which is why running it failed wherever Python *was*
2976 # present, and never showed up in a CPAN Testers report because the smokers
2977 # have none.
2978 24 my @windows_python_candidates = ( ['python'], [ 'py', '-3' ], ['python3'] );
2979 # The command plt runs, as a list for system(). undef = not yet looked for;
2980 # [] = looked for, and none found. A package variable rather than a lexical so
2981 # that the test suite can point it at a stand-in interpreter.
2982 24 our $python_command;
2983 33 ▶sub python_command {
Subroutine python_command: called CC=7 SCAR=19.5
Pod undocumented
2984 # The interpreter plt runs scripts with, as a list.
2985 # $ENV{MATPLOTLIB_SIMPLE_PYTHON}, when set and not empty, is that
2986 # interpreter, taken whole and neither searched for nor checked: it names a venv or a module-loaded Python
2987 # without changing PATH, and is not split on spaces because a path such as
2988 # "C:\Program Files\Python312\python.exe" has them. One that does not
2989 # run is reported by plt as "failed to start". Otherwise it is
2990 # ('python3') on everything but MSWin32, as it always was, and there the
2991 # first of @windows_python_candidates that reports itself as Python 3, or
2992 # an empty list if none does. The result is kept, so the search runs once.
2993 #
2994 # "--version" rather than trusting that the name resolves: on Windows 10
2995 # and 11 "python" with no Python installed is a Microsoft Store stub,
2996 # which prints "Python was not found" and exits 9009. Both streams are
2997 # read, since Python 3 before 3.4 printed its version to STDERR.
2998 33 ▶ return @{$python_command} if defined $python_command;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Matplotlib::Simple::Matplotlib::python_command 7 26 33
2999 26 my $named = program_from_env('MATPLOTLIB_SIMPLE_PYTHON');
3000 26 ▶ if ( defined $named ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $named) 3 23 26
3001 3 $python_command = [$named];
3002 3 return @{$python_command};
3003 }
3004 23 ▶ if ( $^O ne 'MSWin32' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O ne "MSWin32") 18 5 23
3005 18 $python_command = ['python3'];
3006 18 return @{$python_command};
3007 }
3008 5 foreach my $candidate (@windows_python_candidates) {
3009 10 ▶ my ( $out, $err, $status ) = capture {
Subroutine __ANON__: called CC=1 SCAR=0.0
3010 24 ▶ no warnings 'exec'; # a candidate that is not installed is expected; see the call in plt
Subroutine BEGIN: called CC=1 SCAR=0.0
3011 10 system( @{$candidate}, '--version' );
3012 10 };
3013 10 ▶ next unless ( $status == 0 ) && ( "$out$err" =~ m/^Python 3\./m );
Branch: 1 branch
BranchTrueFalseTotal
unless $status == 0 and "$out$err" =~ /^Python 3\./m 6 4 10
Condition100%3/3
$status == 0 and "$out$err" =~ /^Python 3\./m
!ll&&!rl&&r
514
MC/DC100%2/2
$status == 0 and "$out$err" =~ /^Python 3\./m
$status == 0 "$out$err" =~ /^Python 3\./m
Truth table100%3/3
A and B
A= $status == 0B= "$out$err" =~ /^Python 3\./m
ABresult
0X0
100
111
3014 4 $python_command = [ @{$candidate} ];
3015 4 return @{$python_command};
3016 }
3017 1 $python_command = [];
3018 1 return ();
3019 }
3020 506 ▶sub savefig_takes_metadata {
Subroutine savefig_takes_metadata: called CC=3 SCAR=11.0
Pod undocumented
3021 # Whether matplotlib's savefig accepts "metadata" for a file of this name:
3022 # 1 for .png, .pdf, .svg, .svgz, .eps and .ps, in any case, and for a name
3023 # with no extension, which matplotlib saves as its default format, a PNG;
3024 # 0 for every other extension. The extension is what follows the last "."
3025 # of the file's own name, as pathlib's suffix reads it, so a "." in a
3026 # directory's name, or one that leads the file's name, is not one.
3027 506 my ($file) = @_;
3028 506 ▶ return 1 unless $file =~ m{[^/\\.][^/\\]*\.([^./\\]*)\z}s;
Branch: 1 branch
BranchTrueFalseTotal
unless $file =~ m([^/\\.][^/\\]*\.([^./\\]*)\z)s 6 500 506
3029 500 ▶ return ( lc($1) =~ m/\A(?:|png|pdf|svgz?|eps|ps)\z/ ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
lc($1) =~ /\A(?:|png|pdf|svgz?|eps|ps)\z/ ? : 475 25 500
3030 }
3031 10 ▶sub shared_color_scale {
Subroutine shared_color_scale: called CC=3 SCAR=11.0
Pod undocumented
3032 # Python giving every color-mapped artist of the subplots that share a
3033 # colorbar one scale: the lowest bottom and the highest top of any of
3034 # them.
3035 #
3036 # Each subplot scaled its colors to its own data -- hexbin and hist2d to
3037 # their own counts, which only matplotlib knows -- so the same color meant
3038 # a different value in each, and the one colorbar, drawn from the last of
3039 # them, was true only of that one. set_clim on each brings them to one
3040 # scale, and the colorbar follows the artist it was drawn from. The margins
3041 # a hexbin draws with "marginals" are left alone, being densities of their
3042 # own. colored_table is left to shared_table_range.
3043 10 my ( $fh, $args ) = @_;
3044 10 ▶ my @axes = map { "ax$_" } grep { ( $args->{plots}[$_]{plot_type} // '' ) ne 'colored_table' } @{ $args->{shared_colorbar} };
Condition50%1/2
$args->{"plots"}[$_]{"plot_type"} // ""
l!l
200
MC/DC0%0/1
$args->{"plots"}[$_]{"plot_type"} // ""
$args->{"plots"}[$_]{"plot_type"}
Truth table50%1/2
A
A= $args->{"plots"}[$_]{"plot_type"}
Aresult
11
00
3045 10 ▶ return if scalar @axes < 2;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @axes < 2 3 7 10
3046 7 say $fh 'shared_mappables = [m for a in [' . join( ', ', @axes ) . '] for m in a.collections + a.images if m.get_array() is not None]';
3047 7 say $fh 'shared_margins = [id(b) for m in shared_mappables for b in (getattr(m, "hbar", None), getattr(m, "vbar", None)) if b is not None]';
3048 7 say $fh 'shared_mappables = [m for m in shared_mappables if id(m) not in shared_margins and m.norm.vmin is not None and m.norm.vmax is not None]';
3049 7 say $fh 'if len(shared_mappables) > 1:';
3050 7 say $fh "\tshared_lo = min(m.norm.vmin for m in shared_mappables)";
3051 7 say $fh "\tshared_hi = max(m.norm.vmax for m in shared_mappables)";
3052 7 say $fh "\tfor m in shared_mappables:";
3053 7 say $fh "\t\tm.set_clim(shared_lo, shared_hi)";
3054 }
3055 663 ▶sub render {
Subroutine render: called CC=79 SCAR=44.8
Pod undocumented
3056 # plt's figure as a Python script, which is run unless "execute" is false.
3057 # Returns the script's path.
3058 #
3059 # args: plt's arguments once Matplotlib::Simple has checked them: "p" and "df"
3060 # folded in, "nrows", "ncols" and "execute" set, every plot_type
3061 # checked and every plot given "data"
3062 # context: sub => the name the caller called ("plt", "bar", ...)
3063 # single_plot => 1 = one plot, its keywords at the top level;
3064 # 0 = "plots", one hash per subplot
3065 # style => "matplotlib" or "native" (%Matplotlib::Simple::styles), which
3066 # draw the same figure here
3067 # dpi => the dots per inch to save "output_file" at, a
3068 # finite number above 0, or undef for matplotlib's own
3069 663 my ( $args, $context ) = @_;
3070 663 my $current_sub = $context->{sub};
3071 663 my $single_plot = $context->{single_plot};
3072 663 %twin_axes = (); # see its declaration
3073 663 @tooltip_text = (); # and this one's
3074 # matplotlib picks the format by the extension, in any case, and ".svgz"
3075 # is a gzipped SVG.
3076 663 ▶ $tooltips_drawn = ( ( defined $args->{output_file} ) && ( $args->{output_file} =~ m/\.svgz?\z/i ) ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'output_file'} && $args->{'output_file'} =~ /\.svgz?\z/i ? : 629 34 663
Condition100%3/3
defined $args->{"output_file"} and $args->{"output_file"} =~ /\.svgz?\z/i
!ll&&!rl&&r
727629
MC/DC100%2/2
defined $args->{"output_file"} and $args->{"output_file"} =~ /\.svgz?\z/i
defined $args->{"output_file"} $args->{"output_file"} =~ /\.svgz?\z/i
Truth table100%3/3
A and B
A= defined $args->{"output_file"}B= $args->{"output_file"} =~ /\.svgz?\z/i
ABresult
0X0
100
111
3077 663 my @ax = map { "ax$_" } 0 .. $args->{nrows} * $args->{ncols} - 1;
3078 663 my ( @py, @y, $fh);
3079 663 my $i = 0;
3080 663 foreach my $ax (@ax) {
3081 722 my $a1i = int $i / $args->{ncols}; # 1st index
3082 722 my $a2i = $i % $args->{ncols}; # 2nd index
3083 722 $y[$a1i][$a2i] = $ax;
3084 722 $i++;
3085 }
3086 663 foreach my $y (@y) {
3087 672 push @py, '(' . join( ',', @{$y} ) . ')';
3088 }
3089 663 $fh = script_handle( $args, '.py', $current_sub );
3090 663 say $fh 'import matplotlib.pyplot as plt';
3091 663 say $fh 'import json, base64';
3092 663 ▶ if ( $single_plot == 0 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($single_plot == 0) { } 53 610 663
elsif ($single_plot == 1) { } 610 0 610
3093 # matplotlib takes a bool or one of the words "row", "col", "all" and
3094 # "none". A word was written bare, so "sharey => 'row'" left
3095 # "sharey = row" in the script and died as a NameError.
3096 53 foreach my $share ('sharex', 'sharey') {
3097 105 ▶ my $value = $args->{$share} // 0;
Condition100%2/2
$args->{$share} // 0
l!l
798
MC/DC100%1/1
$args->{$share} // 0
$args->{$share}
Truth table100%2/2
A
A= $args->{$share}
Aresult
11
00
3098 105 ▶ if ( ( ref $value eq '' ) && ( $value =~ m/^(?:row|col|all|none)$/ ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $value eq '' and $value =~ /^(?:row|col|all|none)$/) { } 1 104 105
elsif (ref $value eq '' and &looks_like_number($value)) { } 102 2 104
Condition66%2/3
ref $value eq "" and $value =~ /^(?:row|col|all|none)$/
!ll&&!rl&&r
01041
MC/DC50%1/2
ref $value eq "" and $value =~ /^(?:row|col|all|none)$/
ref $value eq "" $value =~ /^(?:row|col|all|none)$/
Truth table66%2/3
A and B
A= ref $value eq ""B= $value =~ /^(?:row|col|all|none)$/
ABresult
0X0
100
111
3099 1 $args->{$share} = py_str($value);
3100 ▶ } elsif ( ( ref $value eq '' ) && looks_like_number($value) ) {
Condition66%2/3
ref $value eq "" and &looks_like_number($value)
!ll&&!rl&&r
02102
MC/DC50%1/2
ref $value eq "" and &looks_like_number($value)
ref $value eq "" &looks_like_number($value)
Truth table66%2/3
A and B
A= ref $value eq ""B= &looks_like_number($value)
ABresult
0X0
100
111
3101 102 $args->{$share} = py_num($value); # matplotlib reads a number as a bool
3102 } else {
3103 2 ▶ $args->{$share} = bool_option( $value, $share, $current_sub ) ? 'True' : 'False';
Branch: 1 branch
BranchTrueFalseTotal
bool_option($value, $share, $current_sub) ? : 1 0 1
3104 }
3105 }
3106 52 say $fh 'fig, ('
3107 . join( ',', @py )
3108 . ") = plt.subplots($args->{nrows}, $args->{ncols}, sharex = $args->{sharex}, sharey = $args->{sharey}, layout = 'constrained') #" . __LINE__;
3109 } elsif ( $single_plot == 1 ) {
3110 610 say $fh 'fig, ax0 = plt.subplots(1,1, layout = "constrained")';
3111 } else {
3112 0 die "\$single_plot = $single_plot breaks pigeonholes";
3113 }
3114 662 my %dispatch = (
3115 bar => \&barplot_helper, barh => \&barplot_helper,
3116 boxplot => \&boxplot_helper, colored_table=> \&colored_table_helper,
3117 hexbin => \&hexbin_helper, hist => \&hist_helper,
3118 hist2d => \&hist2d_helper, imshow => \&imshow_helper,
3119 pie => \&pie_helper, plot => \&plot_helper,
3120 scatter => \&scatter_helper, violin => \&violin_helper,
3121 venn_proportional_area => \&venn_proportional_area_helper,
3122 violinplot => \&violin_helper,
3123 wide => \&wide_helper
3124 );
3125 662 ▶ if ($single_plot == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($single_plot == 1) 610 52 662
3126 610 my $has_hist = has_hist( $args, $args->{plot_type} );
3127 610 ▶ hist_range_report( $fh, 0, 'start' ) if $has_hist;
Branch: 1 branch
BranchTrueFalseTotal
if $has_hist 37 573 610
3128 610 foreach my $graph (@{ $args->{add} }) {
3129 8 ▶ $graph->{plot_type} = $graph->{plot_type} // $args->{plot_type};
Condition33%1/3
$graph->{"plot_type"} // $args->{"plot_type"}
l!l&&r!l&&!r
800
MC/DC0%0/2
$graph->{"plot_type"} // $args->{"plot_type"}
$graph->{"plot_type"} $args->{"plot_type"}
Truth table33%1/3
A // B
A= $graph->{"plot_type"}B= $args->{"plot_type"}
ABresult
1X1
011
000
3130 8 my $type = $graph->{plot_type};
3131 8 ▶ die 'plot_type not defined for "add" graph' unless defined $type;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type 0 8 8
3132 8 check_plot_type({ type => $type, where => 'for an "add" graph' });
3133 7 $dispatch{$type}->({
3134 fh => $fh,
3135 ax => 0,
3136 plot => $graph
3137 });
3138 }
3139 609 delete $args->{add};
3140 609 my $type = $args->{plot_type};
3141 # check_plot_type above has already refused anything outside
3142 # %opt_key_of_type, which lists the same 15 types as %dispatch, so this
3143 # fires only if the two are edited out of step.
3144 609 ▶ die "no helper is registered for plot_type \"$type\"" unless defined $dispatch{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dispatch{$type} 0 609 609
3145 609 $dispatch{$type}->({
3146 fh => $fh,
3147 ax => 0,
3148 plot => $args
3149 });
3150 439 ▶ hist_range_report( $fh, 0, 'report' ) if $has_hist;
Branch: 1 branch
BranchTrueFalseTotal
if $has_hist 27 412 439
3151 # "xlim" is not here, though it was: no keyword list accepts it, so it
3152 # is refused long before this as an option that isn't defined (the
3153 # documentation uses that refusal as its worked example), and the
3154 # rename could never fire.
3155 439 my %rename = (
3156 xlabel => 'set_xlabel',
3157 title => 'set_title',
3158 ylabel => 'set_ylabel',
3159 legend => 'legend',
3160 );
3161 439 foreach my $opt ( grep { defined $rename{$_} } keys %{$args} ) {
3162 262 $args->{ $rename{$opt} } = delete $args->{$opt};
3163 }
3164 # emit_plt_fig => 0: the "fig." and "plt." methods in this same hash
3165 # are written by the two loops below, which quote through print_type.
3166 # Letting both passes run emitted every one of them twice.
3167 plot_args({
3168 439 fh => $fh,
3169 args => $args,
3170 ax => 'ax0',
3171 emit_plt_fig => 0
3172 });
3173 }
3174 491 my $ax = 0;
3175 491 foreach my $plot (@{ $args->{plots} } ) {
3176 102 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"shared_colorbar"} and grep {$_ == $ax;} @{$$args{"shared_colorbar"};}) 20 82 102
Condition100%3/3
defined $args->{"shared_colorbar"} and grep {$_ == $ax;} @{$$args{"shared_colorbar"};}
!ll&&!rl&&r
80220
MC/DC100%2/2
defined $args->{"shared_colorbar"} and grep {$_ == $ax;} @{$$args{"shared_colorbar"};}
defined $args->{"shared_colorbar"} grep {$_ == $ax;} @{$$args{"shared_colorbar"};}
Truth table100%3/3
A and B
A= defined $args->{"shared_colorbar"}B= grep {$_ == $ax;} @{$$args{"shared_colorbar"};}
ABresult
0X0
100
111
3177 (defined $args->{shared_colorbar}) && # shared_colorbar is defined
3178 44 (grep {$_ == $ax} @{ $args->{shared_colorbar} }) # subplot's colorbar is shared w other plots
3179 ) {
3180 20 ▶ if ($ax == max( @{ $args->{shared_colorbar} } )) { # this is the max
Branch: 1 branch
BranchTrueFalseTotal
if ($ax == &max(@{$$args{'shared_colorbar'};})) { } 10 10 20
3181 10 $plot->{colorbar_on} = 1; # turn on if this is the max plot
3182 10 $plot->{shared_colorbar} = $args->{shared_colorbar};
3183 10 ▶ $plot->{cbpad} = $args->{cbpad} if defined $args->{cbpad}; # not undef: an undef key is still a key, and was refused as an option
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"cbpad"} 0 10 10
3184 } else {
3185 10 $plot->{colorbar_on} = 0; # turn off, its colorbar will be shared later
3186 }
3187 }
3188 102 my $has_hist = has_hist( $plot, $plot->{plot_type} );
3189 102 ▶ hist_range_report( $fh, $ax, 'start' ) if $has_hist;
Branch: 1 branch
BranchTrueFalseTotal
if $has_hist 26 76 102
3190 102 foreach my $graph (@{ $plot->{add} }) {
3191 13 ▶ $graph->{plot_type} = $graph->{plot_type} // $plot->{plot_type};
Condition33%1/3
$graph->{"plot_type"} // $plot->{"plot_type"}
l!l&&r!l&&!r
1300
MC/DC0%0/2
$graph->{"plot_type"} // $plot->{"plot_type"}
$graph->{"plot_type"} $plot->{"plot_type"}
Truth table33%1/3
A // B
A= $graph->{"plot_type"}B= $plot->{"plot_type"}
ABresult
1X1
011
000
3192 13 my $type = $graph->{plot_type};
3193 13 ▶ die "plot_type not defined for \"add\" graph at ax = $ax" unless defined $type;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type 0 13 13
3194 # "at subplot $ax", not "at ax = $ax": the up-front check above
3195 # words it that way, and this line and that one describe the same
3196 # graph.
3197 13 check_plot_type({ type => $type, where => "for an \"add\" graph at subplot $ax" });
3198 13 $dispatch{$type}->({
3199 fh => $fh,
3200 ax => $ax,
3201 plot => $graph
3202 });
3203 }
3204 # As above: the type was checked before the figure was written, so this
3205 # is a guard on %dispatch alone. Without it an unknown type died as
3206 # "Can't use an undefined value as a subroutine reference".
3207 die "no helper is registered for plot_type \"$plot->{plot_type}\" at ax = $ax"
3208 102 ▶ unless defined $dispatch{ $plot->{plot_type} };
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dispatch{$plot->{"plot_type"}} 0 102 102
3209 102 $dispatch{$plot->{plot_type}}->({
3210 fh => $fh,
3211 ax => $ax,
3212 plot => $plot
3213 });
3214 95 ▶ hist_range_report( $fh, $ax, 'report' ) if $has_hist;
Branch: 1 branch
BranchTrueFalseTotal
if $has_hist 26 69 95
3215 95 my %rename = (
3216 xlabel => 'set_xlabel', title => 'set_title',
3217 ylabel => 'set_ylabel', legend => 'legend',
3218 # xlim => 'set_xlim',
3219 );
3220 95 foreach my $opt ( grep { defined $rename{$_} } keys %{$plot} ) {
3221 32 $plot->{ $rename{$opt} } = delete $plot->{$opt};
3222 }
3223 plot_args({
3224 95 fh => $fh,
3225 args => $plot,
3226 ax => "ax$ax"
3227 });
3228 95 $ax++;
3229 }
3230 484 ▶ shared_color_scale( $fh, $args ) if defined $args->{shared_colorbar};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"shared_colorbar"} 10 474 484
3231 484 foreach my $ax (@ax) {
3232 541 say $fh "if $ax.has_data() == False:"; # remove empty plots
3233 541 say $fh "\t$ax.remove()"; # remove empty plots
3234 }
3235 484 my %methods = map { $_ => 1 } @plt_methods;
3236 # Text is quoted as plot_args quotes it before print_type sees it. For a
3237 # single plot this is what always happened, though by accident: plot_args
3238 # quoted the caller's own hash in place, and this loop read the result.
3239 # plot_args now works on a copy, so the step is written out here, where it
3240 # now also reaches the "suptitle" of a figure of several subplots, and the
3241 # figure's own "supxlabel" and "supylabel", written by the fig. loop below.
3242 484 my %written_here = map { $_ => 1 } ( @plt_methods, @fig_methods );
3243 484 ▶ foreach my $text_method ( grep { ( $written_here{$_} ) && ( defined $args->{$_} ) } @text_methods ) {
Condition100%3/3
$written_here{$_} && defined $args->{$_}
!ll&&!rl&&r
145228959
MC/DC100%2/2
$written_here{$_} && defined $args->{$_}
$written_here{$_} defined $args->{$_}
Truth table100%3/3
A && B
A= $written_here{$_}B= defined $args->{$_}
ABresult
0X0
100
111
3244 9 my $text = $args->{$text_method};
3245 0 ▶ $args->{$text_method} = ( ref $text eq 'ARRAY' ) ? [ map { quote_text($_) } @{$text} ] : ( ref $text ) ? $text : quote_text($text); # an array element by element, as in plot_args
Branch: 2 branches
BranchTrueFalseTotal
ref $text eq 'ARRAY' ? : 0 9 9
ref $text ? : 0 9 9
3246 }
3247 # As in plot_args: a single plot's "twinx" leaves the twin current, and its
3248 # "axhline" was drawn on the twin. A figure of several subplots is left
3249 # alone, since its own pyplot options are figure-wide ones like "suptitle".
3250 484 ▶ if ( ( $single_plot == 1 ) && ( grep { ( defined $methods{$_} ) && ( $_ ne 'show' ) } keys %{$args} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($single_plot == 1 and grep {defined $methods{$_} and $_ ne "show";} keys %{$args;}) 11 473 484
Condition100%6/6
$single_plot == 1 and grep {defined $methods{$_} and $_ ne "show";} keys %{$args;}
!ll&&!rl&&r
4542811
defined $methods{$_} && $_ ne 'show'
!ll&&!rl&&r
4917414
MC/DC100%2/2
$single_plot == 1 and grep {defined $methods{$_} and $_ ne "show";} keys %{$args;}
$single_plot == 1 grep {defined $methods{$_} and $_ ne "show";} keys %{$args;}
MC/DC100%2/2
defined $methods{$_} && $_ ne 'show'
defined $methods{$_} $_ ne 'show'
Truth table100%3/3
A and B
A= $single_plot == 1B= grep {defined $methods{$_} and $_ ne "show";} keys %{$args;}
ABresult
0X0
100
111
Truth table100%3/3
A && B
A= defined $methods{$_}B= $_ ne 'show'
ABresult
0X0
100
111
3251 11 say $fh 'plt.sca(ax0) #' . __LINE__;
3252 }
3253 # A single plot's "legend" was written by plot_args above, and only if
3254 # something carries a label; writing it here too drew it a second time, and
3255 # warned "No artists with labels found to put in legend" when nothing did.
3256 484 ▶ foreach my $plt_method ( grep { defined $methods{$_} && ( ( $single_plot == 0 ) || ( $_ ne 'legend' ) ) } keys %{$args} ) {
Condition100%6/6
defined $methods{$_} && ($single_plot == 0 || $_ ne 'legend')
!ll&&!rl&&r
5241126
$single_plot == 0 or $_ ne "legend"
l!l&&r!l&&!r
9171
MC/DC100%3/3
defined $methods{$_} && ($single_plot == 0 || $_ ne 'legend')
defined $methods{$_} $single_plot == 0 $_ ne "legend"
Truth table100%4/4
A && B or C
A= defined $methods{$_}B= $single_plot == 0C= $_ ne "legend"
ABCresult
0XX0
1000
11X1
1011
3257 26 my $ref = ref $args->{$plt_method};
3258 26 ▶ if ( $ref eq '' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ref eq '') { } 26 0 26
elsif ($ref eq 'ARRAY') { } 0 0 0
3259 26 ▶ if ($plt_method eq 'show') {
Branch: 1 branch
BranchTrueFalseTotal
if ($plt_method eq "show") 10 16 26
3260 10 next; # plt.show() is emitted after plt.savefig() below
3261 }
3262 16 say $fh "plt.$plt_method(" . pyplot_arg( $args->{$plt_method} ) . ')#' . __LINE__;
3263 } elsif ( $ref eq 'ARRAY' ) {
3264 0 foreach my $j ( @{ $args->{$plt_method} } ) {
3265 0 say $fh "plt.$plt_method(" . pyplot_arg($j) . ')#' . __LINE__;
3266 }
3267 } else {
3268 0 p $args;
3269 0 die "$plt_method = \"$ref\" only accepts scalar or array types";
3270 }
3271 }
3272 484 %methods = map { $_ => 1 } @fig_methods;
3273 484 foreach my $fig_method ( grep { defined $methods{$_} } keys %{$args} ) {
3274 6 my $ref = ref $args->{$fig_method};
3275 6 ▶ if ( $ref eq '' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ref eq '') { } 6 0 6
elsif ($ref eq 'ARRAY') { } 0 0 0
3276 6 say $fh "fig.$fig_method($args->{$fig_method})#" . __LINE__;
3277 } elsif ( $ref eq 'ARRAY' ) {
3278 0 foreach my $j ( @{ $args->{$fig_method} } ) { # say $fh "plt.$method($plt)";
3279 0 say $fh "fig.$fig_method($j)";
3280 }
3281 } else {
3282 0 p $args;
3283 0 die "$fig_method = \"$ref\" only accepts scalar or array types";
3284 }
3285 }
3286 484 ▶ if (defined $args->{scale}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"scale"}) 1 483 484
3287 1 say $fh "fig.set_figheight(plt.rcParams['figure.figsize'][1] * $args->{scale}) #" . __LINE__;
3288 1 say $fh "fig.set_figwidth(plt.rcParams['figure.figsize'][0] * $args->{scale}) #" . __LINE__;
3289 }
3290 484 ▶ if (defined $args->{scalex}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"scalex"}) 1 483 484
3291 1 say $fh "fig.set_figwidth(plt.rcParams['figure.figsize'][0] * $args->{scalex}) #" . __LINE__;
3292 }
3293 484 ▶ if (defined $args->{scaley}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"scaley"}) 1 483 484
3294 1 say $fh "fig.set_figheight(plt.rcParams['figure.figsize'][1] * $args->{scaley}) #" . __LINE__;
3295 }
3296 484 ▶ if (defined $args->{output_file}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"output_file"}) 477 7 484
3297 write_data({
3298 data => $args->{output_file},
3299 477 fh => $fh,
3300 name => 'output_file'
3301 });
3302 # py_str, not interpolation: on MSWin32 the paths in creator_note are
3303 # backslash paths, so "C:\build\..." pasted into a Python literal
3304 # reads "\b" as a backspace and "\c" as an invalid escape
3305 # (SyntaxWarning in 3.12, SyntaxError from 3.15). An apostrophe
3306 # anywhere in the path would close the literal early.
3307 477 my $creator = py_str( creator_note($current_sub) );
3308 # The Python and matplotlib versions, the user and the host are read by
3309 # the script as it runs, not by Perl as it writes: with "execute => 0"
3310 # the script may be run later, or elsewhere, by an interpreter Perl
3311 # never sees, and it is whoever runs it that writes the file.
3312 477 say $fh 'import matplotlib, platform, getpass';
3313 # getpass.getuser() raises when no LOGNAME, USER, LNAME or USERNAME is
3314 # set and there is no password database to fall back on -- OSError
3315 # from Python 3.13, KeyError or ImportError before -- so an unknown
3316 # user must not stop the figure from being saved.
3317 477 say $fh 'try:';
3318 477 say $fh "\tcreator_user = getpass.getuser()";
3319 477 say $fh 'except Exception:';
3320 477 say $fh "\tcreator_user = 'unknown user'";
3321 477 say $fh "creator_host = platform.node() or 'unknown host' # node() is '' when the name cannot be found";
3322 # An SVG keeps only the Creator. matplotlib also writes the time it was
3323 # saved, its own "image/svg+xml" and a link to the Dublin Core "StillImage"
3324 # type, each of which a None leaves out (backend_svg._write_metadata,
3325 # matplotlib 3.11.2). Only for an SVG: the PDF backend warns about
3326 # "Format" and "Type" as keys it does not know.
3327 #
3328 # And only for a format that keeps metadata. The note was handed to
3329 # savefig whatever the file, and matplotlib refuses it for the formats
3330 # that have nowhere to put one -- "ValueError: metadata not supported
3331 # for format 'jpeg'", and the like for tiff, webp, gif, avif, raw and
3332 # rgba, and a TypeError for pgf -- so no .jpg, .tif, .webp, .gif or
3333 # .pgf could be written at all (matplotlib 3.11.2). Those are saved
3334 # without a note. matplotlib picks the format by the extension, in any
3335 # case, and a name with none is the PNG it has always been.
3336 # "dpi" is plt's own keyword for the resolution, checked there to be a
3337 # finite number above 0. Without it savefig is called as it always
3338 # was, at matplotlib's own "savefig.dpi".
3339 477 ▶ my $dpi = defined $context->{dpi} ? ', dpi = ' . py_num( $context->{dpi} ) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $context->{'dpi'} ? : 10 467 477
3340 # $tooltips_drawn is 1 exactly when output_file is an SVG (or SVGZ),
3341 # which is drawn into memory, finished there, and written to the file
3342 # once, below. It was saved, read back, and written again, once to cut
3343 # the DOCTYPE and once more for tooltips, so that a viewer watching the
3344 # file saw it change two or three times, and empty between: Eye of
3345 # GNOME 45.3, which reloads a PNG matplotlib has written over, stopped
3346 # reloading such an SVG at all. "format" because a buffer has no
3347 # extension to read it from.
3348 477 ▶ my $target = $tooltips_drawn ? "svg_buffer, format = 'svg'," : 'output_file,';
Branch: 1 branch
BranchTrueFalseTotal
$tooltips_drawn ? : 451 26 477
3349 477 ▶ print {$fh} <<'PYTHON' if $tooltips_drawn;
Branch: 1 branch
BranchTrueFalseTotal
if $tooltips_drawn 451 26 477
3350 import gzip, io, re
3351 svg_buffer = io.BytesIO()
3352 PYTHON
3353 477 ▶ if ( savefig_takes_metadata( $args->{output_file} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (savefig_takes_metadata($args->{'output_file'})) { } 467 10 477
3354 467 ▶ say $fh "plt.savefig($target bbox_inches = 'tight'$dpi, metadata={'Creator': $creator"
Branch: 1 branch
BranchTrueFalseTotal
$tooltips_drawn ? : 451 16 467
3355 . " + ', Python ' + platform.python_version() + ', matplotlib ' + matplotlib.__version__"
3356 . " + ', by ' + creator_user + ' on ' + creator_host"
3357 . ( $tooltips_drawn ? ", 'Date': None, 'Format': None, 'Type': None" : '' ) . '})';
3358 } else {
3359 10 say $fh "plt.savefig($target bbox_inches = 'tight'$dpi) # no metadata: this format keeps none";
3360 }
3361 # matplotlib writes <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ...>
3362 # from a fixed string, svgProlog in backend_svg.py, that no option turns
3363 # off, so it is cut from what was drawn. SVG 2 has no DOCTYPE, and no
3364 # browser reads it. It holds no ">" of its own: there is no internal
3365 # subset.
3366 477 ▶ print {$fh} <<'PYTHON' if $tooltips_drawn;
Branch: 1 branch
BranchTrueFalseTotal
if $tooltips_drawn 451 26 477
3367 svg_bytes = re.sub(rb'<!DOCTYPE[^>]*>\s*', b'', svg_buffer.getvalue(), count = 1)
3368 PYTHON
3369 }
3370 484 ▶ if ( ( scalar @tooltip_text > 0 ) && ( not $tooltips_drawn ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @tooltip_text > 0 and not $tooltips_drawn) 2 482 484
Condition100%3/3
scalar @tooltip_text > 0 and not $tooltips_drawn
!ll&&!rl&&r
457252
MC/DC100%2/2
scalar @tooltip_text > 0 and not $tooltips_drawn
scalar @tooltip_text > 0 not $tooltips_drawn
Truth table100%3/3
A and not(B)
A= scalar @tooltip_text > 0B= not $tooltips_drawn
ABresult
0X0
100
111
3371 warn '"tooltips" are drawn only into an SVG, so they are left out of '
3372 2 ▶ . ( defined $args->{output_file} ? "\"$args->{output_file}\"" : 'a figure that is only shown' )
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'output_file'} ? : 1 1 2
3373 . ': give "output_file" a name ending in ".svg"';
3374 }
3375 484 ▶ if ( ( scalar @tooltip_text > 0 ) && $tooltips_drawn ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @tooltip_text > 0 and $tooltips_drawn) 25 459 484
Condition100%3/3
scalar @tooltip_text > 0 and $tooltips_drawn
!ll&&!rl&&r
457225
MC/DC100%2/2
scalar @tooltip_text > 0 and $tooltips_drawn
scalar @tooltip_text > 0 $tooltips_drawn
Truth table100%3/3
A and B
A= scalar @tooltip_text > 0B= $tooltips_drawn
ABresult
0X0
100
111
3376 25 write_data({
3377 data => \@tooltip_text,
3378 fh => $fh,
3379 name => 'tooltip_text'
3380 });
3381 25 write_data({
3382 data => $tooltip_url,
3383 fh => $fh,
3384 name => 'tooltip_url'
3385 });
3386 # Each labelled point was drawn inside <a xlink:href="#...-<n>"
3387 # target="_blank">, which becomes a bare <g> whose first child is a
3388 # <title> holding text n. The namespaces are registered so that the
3389 # file is written back with matplotlib's own prefixes rather than ns0,
3390 # ns1, ...
3391 #
3392 # A <title> alone was not enough: whether a browser shows it on
3393 # hovering is up to the browser and the desktop, and in 0.321 neither
3394 # Firefox nor Chromium showed one on the author's machine. So the <g>
3395 # is also given the class matplotlib-simple-tooltip, and a script at
3396 # the end of the SVG draws the label itself, in a box beside the point
3397 # under the mouse. The script takes each <title> out as it starts, so
3398 # that a browser that does show titles does not show the label twice;
3399 # a viewer that runs no script -- Inkscape, Eye of GNOME, an <img> on
3400 # a web page -- keeps the <title>s in the file.
3401 25 print {$fh} <<'PYTHON';
3402 # Placement, in the SVG's own units, which are points: the box sits 4 from the
3403 # marker and 3 outside its text, above and to the right of the point, and is
3404 # moved left of or below it wherever it would leave the figure.
3405 tooltip_script = r'''(function () {
3406 var ns = 'http://www.w3.org/2000/svg';
3407 var me = document.currentScript;
3408 var svg = (me && me.ownerSVGElement) || document.documentElement;
3409 var points = svg.querySelectorAll('g.matplotlib-simple-tooltip');
3410 var gap = 4, pad = 3;
3411 var tip = document.createElementNS(ns, 'g');
3412 tip.setAttribute('pointer-events', 'none');
3413 tip.setAttribute('display', 'none');
3414 var box = document.createElementNS(ns, 'rect');
3415 box.setAttribute('rx', '2');
3416 box.setAttribute('style', 'fill: #ffffe1; stroke: #555555; stroke-width: 0.5');
3417 var text = document.createElementNS(ns, 'text');
3418 text.setAttribute('style', 'font-family: sans-serif; font-size: 10px; fill: #000000');
3419 tip.appendChild(box);
3420 tip.appendChild(text);
3421 svg.appendChild(tip);
3422 function show(point, label) {
3423 while (text.firstChild) text.removeChild(text.firstChild);
3424 label.split('\n').forEach(function (line, i) {
3425 var span = document.createElementNS(ns, 'tspan');
3426 span.setAttribute('x', '0');
3427 span.setAttribute('dy', i ? '1.2em' : '0');
3428 span.textContent = line;
3429 text.appendChild(span);
3430 });
3431 tip.removeAttribute('display');
3432 var ctm = svg.getScreenCTM();
3433 if (!ctm) return;
3434 var t = text.getBBox(), w = t.width + 2 * pad, h = t.height + 2 * pad;
3435 var bx = t.x - pad, by = t.y - pad;
3436 var r = point.getBoundingClientRect(), inv = ctm.inverse(), p = svg.createSVGPoint();
3437 p.x = r.left; p.y = r.top;
3438 var lo = p.matrixTransform(inv);
3439 p.x = r.right; p.y = r.bottom;
3440 var hi = p.matrixTransform(inv);
3441 var vb = svg.viewBox.baseVal;
3442 var left = vb ? vb.x : 0, top = vb ? vb.y : 0;
3443 var right = vb ? vb.x + vb.width : Infinity, bottom = vb ? vb.y + vb.height : Infinity;
3444 var x = hi.x + gap, y = lo.y - gap - h;
3445 if (x + w > right) x = lo.x - gap - w;
3446 if (x < left) x = left;
3447 if (y < top) y = hi.y + gap;
3448 if (y + h > bottom) y = Math.max(top, bottom - h);
3449 box.setAttribute('x', bx);
3450 box.setAttribute('y', by);
3451 box.setAttribute('width', w);
3452 box.setAttribute('height', h);
3453 tip.setAttribute('transform', 'translate(' + (x - bx) + ' ' + (y - by) + ')');
3454 }
3455 function hide() {
3456 tip.setAttribute('display', 'none');
3457 }
3458 Array.prototype.forEach.call(points, function (point) {
3459 var title = point.querySelector('title');
3460 if (!title) return;
3461 var label = title.textContent;
3462 point.removeChild(title);
3463 if (label === '') return;
3464 point.addEventListener('mouseenter', function () { show(point, label); });
3465 point.addEventListener('mouseleave', hide);
3466 });
3467 })();'''
3468 import xml.etree.ElementTree as ET
3469 svg_ns = 'http://www.w3.org/2000/svg'
3470 xlink_href = '{http://www.w3.org/1999/xlink}href'
3471 for prefix, uri in (('', svg_ns), ('xlink', 'http://www.w3.org/1999/xlink'),
3472 ('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'),
3473 ('cc', 'http://creativecommons.org/ns#'), ('dc', 'http://purl.org/dc/elements/1.1/')):
3474 ET.register_namespace(prefix, uri)
3475 svg_tree = ET.parse(io.BytesIO(svg_bytes))
3476 for link in list(svg_tree.iter('{%s}a' % svg_ns)):
3477 href = link.get(xlink_href, '')
3478 if not href.startswith(tooltip_url):
3479 continue
3480 link.tag = '{%s}g' % svg_ns
3481 link.attrib.clear()
3482 link.set('class', 'matplotlib-simple-tooltip')
3483 title = ET.Element('{%s}title' % svg_ns)
3484 title.text = tooltip_text[int(href[len(tooltip_url):])]
3485 link.insert(0, title)
3486 # last, so that every point is in the document when it runs, and the box it
3487 # draws is on top of everything else
3488 ET.SubElement(svg_tree.getroot(), '{%s}script' % svg_ns, {'type': 'text/javascript'}).text = tooltip_script
3489 svg_buffer = io.BytesIO()
3490 svg_tree.write(svg_buffer, encoding = 'utf-8', xml_declaration = True)
3491 svg_bytes = svg_buffer.getvalue()
3492 PYTHON
3493 }
3494 # The one write of an SVG, finished above (see $target).
3495 484 ▶ print {$fh} <<'PYTHON' if ( defined $args->{output_file} ) && $tooltips_drawn;
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"output_file"} and $tooltips_drawn 451 33 484
Condition100%3/3
defined $args->{"output_file"} and $tooltips_drawn
!ll&&!rl&&r
726451
MC/DC100%2/2
defined $args->{"output_file"} and $tooltips_drawn
defined $args->{"output_file"} $tooltips_drawn
Truth table100%3/3
A and B
A= defined $args->{"output_file"}B= $tooltips_drawn
ABresult
0X0
100
111
3496 with (gzip.open if output_file.lower().endswith('.svgz') else open)(output_file, 'wb') as svg:
3497 svg.write(svg_bytes)
3498 PYTHON
3499 484 ▶ say $fh 'plt.show()' if $args->{show}; # after savefig, so the file is written even if the window is never closed
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"show"} 9 475 484
3500 484 ▶ say $fh 'plt.close()' if $args->{execute} == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"execute"} == 0 477 7 484
3501 484 ▶ if ( $args->{execute} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{'execute'}) { } 7 477 484
3502 7 my @python = python_command();
3503 7 ▶ if ( scalar @python == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @python == 0) 1 6 7
3504 die 'no Python 3 interpreter was found to run ' . $fh->filename
3505 1 . ': tried ' . join( ', ', map { '"' . join( ' ', @{$_} ) . '"' } @windows_python_candidates )
3506 . '. Install Python 3 and matplotlib, set MATPLOTLIB_SIMPLE_PYTHON to the path of a Python 3 that has them, or pass "execute => 0" to write the script without running it';
3507 }
3508 # What the script wrote to STDERR as it ran and succeeded: matplotlib's
3509 # warnings, which are the only word the caller gets that a figure was
3510 # written but is not what was asked for -- "Data has no positive
3511 # values, and therefore cannot be log-scaled", a font with no glyph for
3512 # a label, a deprecation. run_script captured them and returned them,
3513 # and they were dropped here, so only a script that failed ever showed
3514 # its STDERR. Printed as they came, to STDERR, and not with warn(),
3515 # which this file's fatal warnings would make a death after the figure
3516 # was written.
3517 6 my $stderr = run_script( [ @python, $fh->filename ] );
3518 4 ▶ print STDERR $stderr if ( defined $stderr ) && ( length $stderr );
Branch: 1 branch
BranchTrueFalseTotal
if defined $stderr and length $stderr 1 3 4
Condition66%2/3
defined $stderr and length $stderr
!ll&&!rl&&r
031
MC/DC50%1/2
defined $stderr and length $stderr
defined $stderr length $stderr
Truth table66%2/3
A and B
A= defined $stderrB= length $stderr
ABresult
0X0
100
111
3519 4 ▶ say 'will write ' . "\e[36;103m$args->{output_file}\e[0m" if defined $args->{output_file};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"output_file"} 4 0 4
3520 } else { # not running yet
3521 477 ▶ say 'will write ' . "\e[36;103m$args->{output_file}\e[0m" if defined $args->{output_file};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"output_file"} 470 7 477
3522 }
3523 481 return $fh->filename;
3524 }
3525 16 ▶sub venn_proportional_area_helper {
Subroutine venn_proportional_area_helper: called CC=19 SCAR=29.9
Pod undocumented
3526 16 my ($args) = @_;
3527 16 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
3528 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
3529 16 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 16 16
3530 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
3531 }
3532 16 my @reqd_args = (
3533 'ax', # e.g. 0, 1, 2 ... the subplot index, passed in by plt
3534 'fh', # the File::Temp filehandle, passed in by plt
3535 'plot', # the per-plot args from the caller
3536 );
3537 16 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
3538 16 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 16 16
3539 0 p @undef_args;
3540 0 die 'the above args are necessary, but were not defined.';
3541 }
3542 16 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
3543 16 my $plot = $args->{plot};
3544 my @undef_opt = grep {
3545 106 my $key = $_;
3546 106 not grep { $_ eq $key } @opt
3547 16 } keys %{$plot};
3548 16 ▶ if ( scalar @undef_opt > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_opt > 0) 0 16 16
3549 bad_keyword_error({
3550 bad => \@undef_opt,
3551 accepted => \@opt,
3552 preferred => $opt{$current_sub},
3553 type => $plot->{plot_type},
3554 0 sub => $current_sub
3555 });
3556 }
3557 # Each of these died as Perl's own error, or as a Python traceback, naming
3558 # no option: "Not a HASH reference" for array data, and below, "Can't use
3559 # string as an ARRAY ref" for a string "set_colors".
3560 16 ▶ if ( ref $plot->{data} ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"data"} ne "HASH") 1 15 16
3561 die "$current_sub takes a hash of sets, one array of members per set, e.g. { A => [1, 2], B => [2, 3] }, not "
3562 1 ▶ . ( ref $plot->{data} ? 'a ' . ref( $plot->{data} ) . ' reference' : 'a scalar' );
Branch: 1 branch
BranchTrueFalseTotal
ref $plot->{'data'} ? : 1 0 1
3563 }
3564 # matplotlib_venn only draws area-proportional diagrams for 2 or 3 sets
3565 15 my $n_keys = scalar keys %{ $plot->{data} };
3566 15 ▶ if ( ( $n_keys != 2 ) && ( $n_keys != 3 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_keys != 2 and $n_keys != 3) 2 13 15
Condition66%2/3
$n_keys != 2 and $n_keys != 3
!ll&&!rl&&r
1302
MC/DC50%1/2
$n_keys != 2 and $n_keys != 3
$n_keys != 2 $n_keys != 3
Truth table66%2/3
A and B
A= $n_keys != 2B= $n_keys != 3
ABresult
0X0
100
111
3567 2 p $plot->{data};
3568 2 die "$current_sub only takes 2 or 3 sets of data.";
3569 }
3570 13 foreach my $key ( keys %{ $plot->{data} } ) {
3571 25 ▶ if ( ref $plot->{data}{$key} ne 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"data"}{$key} ne "ARRAY") 1 24 25
3572 1 p $plot->{data};
3573 1 die "\"$key\" must be an array reference in $current_sub";
3574 }
3575 24 ▶ if ( grep { !defined } @{ $plot->{data}{$key} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {not defined $_;} @{$$plot{"data"}{$key};}) 0 24 24
3576 0 p $plot->{data}{$key}, array_max => scalar @{ $plot->{data}{$key} };
3577 0 die "\"$key\" has undefined values in $current_sub, there may be undefined values in other keys";
3578 }
3579 }
3580 12 my @keys;
3581 12 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 5 7 12
3582 @keys = check_key_order({
3583 keys => $plot->{key_order},
3584 data => $plot->{data},
3585 5 option => 'key_order',
3586 sub => $current_sub
3587 });
3588 2 ▶ if ( scalar @keys != $n_keys ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @keys != $n_keys) 1 1 2
3589 1 p $plot;
3590 1 die "\"key_order\" has " . scalar(@keys) . " keys, but data has $n_keys in $current_sub";
3591 }
3592 } else {
3593 7 @keys = sort keys %{ $plot->{data} };
3594 }
3595 # The import is emitted at the point of use; a duplicate "from matplotlib_venn
3596 # import ..." across several subplots is harmless in Python.
3597 8 say { $args->{fh} } "from matplotlib_venn import venn$n_keys";
3598 8 ▶ my $ax = $args->{ax} // '';
Condition50%1/2
$args->{"ax"} // ""
l!l
80
MC/DC0%0/1
$args->{"ax"} // ""
$args->{"ax"}
Truth table50%1/2
A
A= $args->{"ax"}
Aresult
11
00
3599 8 my @sets;
3600 8 foreach my $i ( 0 .. $#keys ) { # "each @array" requires perl 5.12
3601 16 my $key = $keys[$i];
3602 16 my $name = "venn_ax${ax}_set$i";
3603 16 say { $args->{fh} } "$name = set(["
3604 16 . py_list( @{ $plot->{data}{$key} } ) . '])';
3605 16 push @sets, $name;
3606 }
3607 8 my $opt = '';
3608 8 ▶ if ( defined $plot->{set_colors} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_colors"}) 3 5 8
3609 # One color per set, which matplotlib_venn reads by position; a list of
3610 # any other length was a TypeError from inside it.
3611 3 ▶ if ( ( ref $plot->{set_colors} ne 'ARRAY' ) || ( scalar @{ $plot->{set_colors} } != $n_keys ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"set_colors"} ne "ARRAY" or scalar @{$plot->{"set_colors"};} != $n_keys) 2 1 3
Condition100%3/3
ref $plot->{"set_colors"} ne "ARRAY" or scalar @{$plot->{"set_colors"};} != $n_keys
l!l&&r!l&&!r
111
MC/DC100%2/2
ref $plot->{"set_colors"} ne "ARRAY" or scalar @{$plot->{"set_colors"};} != $n_keys
ref $plot->{"set_colors"} ne "ARRAY" scalar @{$plot->{"set_colors"};} != $n_keys
Truth table100%3/3
A or B
A= ref $plot->{"set_colors"} ne "ARRAY"B= scalar @{$plot->{"set_colors"};} != $n_keys
ABresult
1X1
011
000
3612 2 die "\"set_colors\" is an array of one color per set in $current_sub, and there are $n_keys sets";
3613 }
3614 1 $opt .= ', set_colors=(' . py_list( @{ $plot->{set_colors} } ) . ')';
3615 }
3616 6 ▶ if ( defined $plot->{alpha} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"alpha"}) 2 4 6
3617 2 check_numbers( [ $plot->{alpha} ], '"alpha"', $current_sub ); # written bare, so a word was a NameError
3618 1 $opt .= ", alpha=" . py_num( $plot->{alpha} );
3619 }
3620 5 say { $args->{fh} } "venn$n_keys(["
3621 . join( ',', @sets ) . '],('
3622 . py_list(@keys) . "), ax=ax$ax$opt)";
3623 }
3624 24 1;
« blib/lib/Matplotlib/Simple.pm ↑ Summary blib/lib/Matplotlib/Simple/Gnuplot.pm »