blib/lib/Matplotlib/Simple/Matplotlib.pm

filter: Statementstmt 91.9% 2167 / 2356 Branchbran 83.7% 772 / 922 Conditioncond 81.0% 350 / 432 MC/DCmcdc 64.7% 165 / 255 Subroutinesub 100% 55 / 55 Podpod 0.0% 0 / 35 totaltotal 86.5% 3509 / 4055 CC 725 SCAR 40.6
CC
725
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 25 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 25 ▶use feature 'say';
Subroutine BEGIN: called CC=1 SCAR=0.0
3 25 ▶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 25 require 5.010;
15 25 our $VERSION = 0.3346;
16 25 ▶use Scalar::Util 'looks_like_number';
Subroutine BEGIN: called CC=1 SCAR=0.0
17 25 ▶use List::Util qw(max sum min);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 25 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 25 ▶use File::Temp;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 25 ▶use DDP { output => 'STDOUT', array_max => 10, show_memsize => 1 };
Subroutine BEGIN: called CC=1 SCAR=0.0
21 25 ▶use Capture::Tiny 'capture';
Subroutine BEGIN: called CC=1 SCAR=0.0
22 25 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 25 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 25 ▶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 25 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=7.2
31 25 ▶ $INC{'Matplotlib/Simple/Matplotlib.pm'} //= __FILE__;
Condition50%1/2
$INC{"Matplotlib/Simple/Matplotlib.pm"} //= __FILE__
l!l
250
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 25 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 25 ▶BEGIN {
Subroutine BEGIN: called CC=4 SCAR=13.9
38 25 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
39 25 *{$_} = \&{"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 25 *{$_} = \@{"Matplotlib::Simple::$_"} foreach qw(arg ax_methods cb_arg fig_methods plt_methods);
45 25 *{$_} = \%{"Matplotlib::Simple::$_"} foreach qw(opt opt_key_of_type);
46 }
47 25 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 25 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 10274 ▶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 10274 my ($n) = @_;
78 10274 my $nonfinite = nonfinite_name($n);
79 10274 ▶ return "float('$nonfinite')" if defined $nonfinite;
Branch: 1 branch
BranchTrueFalseTotal
if defined $nonfinite 8 10266 10274
80 10266 ▶ if ( $n =~ m/^\s*([-+]?)0*(\d+)\s*$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n =~ /^\s*([-+]?)0*(\d+)\s*$/) 7923 2343 10266
81 7923 return "$1$2";
82 }
83 2343 ▶ 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*$/ 2343 0 2343
84 0 return 0 + $n;
85 }
86 1025 ▶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 1025 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 748 ▶sub write_data {
Subroutine write_data: called CC=3 SCAR=11.3
Pod undocumented
147 748 my ($args) = @_;
148 748 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1];
149 748 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 748 748
150 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => ... })\"";
151 }
152 748 my @reqd_args = (
153 'data', # args to original function (scalar, hashref, or arrayref)
154 'fh', # file handle
155 'name' # python variable name
156 );
157 748 my @undef_args = grep { not defined $args->{$_} } @reqd_args;
158 748 ▶ if (scalar @undef_args > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 748 748
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 748 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 748 my $json_string = $json_encoder->encode( decoded_data( $args->{data} ) );
166 # 3. Base64 Encode the JSON String, not the reference
167 748 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 748 undef $json_string;
173 748 print {$args->{fh}} "$args->{name}_b64 = '", $b64_data, "'\n";
174 # Decode b64 -> bytes -> utf8 string -> json load -> python object
175 748 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 25 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 25 my $tooltips_drawn = 0; # 1 = output_file is an SVG, which the tooltips are written into; 0 = they are checked and left out
190 25 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 25 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 542 ▶sub plot_args { # this is a helper function to other matplotlib subroutines
Subroutine plot_args: called CC=29 SCAR=34.2
Pod undocumented
237 542 my ($args) = @_;
238 542 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1];
239 542 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 542 542
240 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
241 }
242 542 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 542 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
248 542 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 542 542
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 542 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 2073 my $key = $_;
257 2073 not grep { $_ eq $key } @defined_args
258 542 } keys %{$args};
259 542 ▶ if ( scalar @bad_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_args > 0) 0 542 542
260 0 bad_keyword_error({
261 bad => \@bad_args,
262 accepted => \@defined_args,
263 sub => $current_sub
264 });
265 }
266 542 ▶ $args->{ax} = $args->{ax} // 'ax';
Condition50%1/2
$args->{"ax"} // "ax"
l!l
5420
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 542 $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 542 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 542 ▶ $args->{emit_plt_fig} = $args->{emit_plt_fig} // 1;
Condition100%2/2
$args->{"emit_plt_fig"} // 1
l!l
440102
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 542 my @obj = ( $args->{ax} );
288 542 my @args = ( \@ax_methods );
289 542 ▶ if ( $args->{emit_plt_fig} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"emit_plt_fig"}) 102 440 542
290 102 push @obj, 'fig', 'plt';
291 102 push @args, \@fig_methods, \@plt_methods;
292 }
293 542 foreach my $i ( 0 .. $#args ) {
294 746 ▶ 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
739020320
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 746 ▶ if ( ( $obj[$i] eq 'plt' ) && ( grep { $_ ne 'show' } @methods ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($obj[$i] eq "plt" and grep {$_ ne "show";} @methods) 6 740 746
Condition100%3/3
$obj[$i] eq "plt" and grep {$_ ne "show";} @methods
!ll&&!rl&&r
644966
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 746 ▶ 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 644 746
305 746 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 542 ▶ return unless defined $args->{ax};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args->{"ax"} 0 542 542
325 542 ▶ my $legend = $args->{args}{legend} // '';
Condition100%2/2
$args->{"args"}{"legend"} // ""
l!l
1541
MC/DC100%1/1
$args->{"args"}{"legend"} // ""
$args->{"args"}{"legend"}
Truth table100%2/2
A
A= $args->{"args"}{"legend"}
Aresult
11
00
326 542 my $pie_plot = 0;
327 542 ▶ if ( ( defined $args->{args}{plot_type} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"args"}{"plot_type"} and $args->{"args"}{"plot_type"} eq "pie") 11 531 542
Condition100%3/3
defined $args->{"args"}{"plot_type"} and $args->{"args"}{"plot_type"} eq "pie"
!ll&&!rl&&r
752411
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 542 ▶ return 1 if $pie_plot == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $pie_plot == 1 11 531 542
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 531 ▶ return 1 if $args->{no_legend};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"no_legend"} 7 524 531
336 524 say { $args->{fh} }
337 "handles, labels = $args->{ax}.get_legend_handles_labels()";
338 524 my $twin = delete $twin_axes{ $args->{ax} };
339 524 ▶ if ( defined $twin ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $twin) 12 512 524
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 512 say { $args->{fh} } 'if len(labels) > 0:';
352 512 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 70 ▶sub hist_helper {
Subroutine hist_helper: called CC=31 SCAR=34.8
Pod undocumented
1202 70 my ($args) = @_;
1203 70 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 70 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 70 70
1206 0 die
1207 "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
1208 }
1209 70 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 70 my @undef = grep { !defined $args->{$_} } @reqd_args;
1215 70 ▶ if ( scalar @undef > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef > 0) 0 70 70
1216 0 p @undef;
1217 0 die 'the above args are necessary, but were not defined.';
1218 }
1219 70 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
1220 70 my $plot = $args->{plot};
1221 @undef = grep {
1222 358 my $key = $_;
1223 358 not grep { $_ eq $key } @opt
1224 70 } keys %{$plot};
1225 70 ▶ if ( scalar @undef > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef > 0) 0 70 70
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 70 my $options = ''; # these args go to the plt.hist call
1235 70 ▶ $plot->{alpha} = $plot->{alpha} // 0.5;
Condition100%2/2
$plot->{"alpha"} // "0.5"
l!l
367
MC/DC100%1/1
$plot->{"alpha"} // "0.5"
$plot->{"alpha"}
Truth table100%2/2
A
A= $plot->{"alpha"}
Aresult
11
00
1236 70 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 69 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 69 ▶ if ( ref $plot->{orientation} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"orientation"}) 1 68 69
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 68 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 67 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 64 ▶ if (ref $plot->{data} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"data"} eq "ARRAY") 12 52 64
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 64 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 62 my @key_order;
1283 62 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 3 59 62
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 59 @key_order = sort keys %{ $plot->{data} };
1292 }
1293 62 ▶ if (scalar keys %{ $plot->{data} } > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$$plot{'data'};} > 1) { } 17 45 62
1294 17 ▶ $plot->{show_legend} = bool_option( $plot->{show_legend} // 1, 'show_legend', $current_sub );
Condition100%2/2
$plot->{"show_legend"} // 1
l!l
116
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 62 foreach my $set (@key_order) {
1303 79 my @non_numeric = grep {not looks_like_number($_)} @{ $plot->{data}{$set} };
1304 79 ▶ if (scalar @non_numeric > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @non_numeric > 0) 1 78 79
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 78 ▶ my @infinite = grep { not ( is_nan($_) || is_finite($_) ) } @{ $plot->{data}{$set} };
Condition100%3/3
is_nan($_) || is_finite($_)
l!l&&r!l&&!r
35381
MC/DC100%2/2
is_nan($_) || is_finite($_)
is_nan($_) is_finite($_)
Truth table100%3/3
A || B
A= is_nan($_)B= is_finite($_)
ABresult
1X1
011
000
1312 78 ▶ if (scalar @infinite > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @infinite > 0) 1 77 78
1313 1 p @infinite;
1314 1 die "$set has the above infinite values, which $current_sub cannot bin";
1315 }
1316 # A set of NaN alone is written as the empty set it bins to, since
1317 # matplotlib cannot find a range in it ("autodetected range of [nan, nan]
1318 # is not finite", 3.11.2) but bins an empty set over 0 to 1.
1319 77 ▶ my @values = ( grep { is_finite($_) } @{ $plot->{data}{$set} } ) ? @{ $plot->{data}{$set} } : ();
Branch: 1 branch
BranchTrueFalseTotal
grep({is_finite($_);} @{$$plot{'data'}{$set};}) ? : 76 1 77
1320 77 my $set_options = '';
1321 77 foreach
1322 154 my $arg ( grep { ref $plot->{$_} eq 'HASH' } ( 'bins', 'color' ) )
1323 {
1324 10 ▶ next unless defined $plot->{$arg}{$set};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $plot->{$arg}{$set} 0 10 10
1325 10 my $ref = ref $plot->{$arg}{$set};
1326 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
1327 0 die "\"color\" for set \"$set\" is an array, but $current_sub draws each set in one color";
1328 } elsif ( $ref eq 'ARRAY' ) {
1329 # Bin edges for this set alone. The whole-plot "bins" has taken
1330 # an array since it was written; per set it fell through to the
1331 # single-value branch below and emitted "bins = ARRAY(0x55f0...)".
1332 1 $set_options .= ", $arg = [" . py_nums( @{ $plot->{$arg}{$set} } ) . ']';
1333 } elsif ( $ref ne '' ) {
1334 0 p $plot->{$arg};
1335 0 die "\"$arg\" for set \"$set\" is a $ref reference, but $current_sub takes a scalar or an array there";
1336 } else {
1337 9 $set_options .= ", $arg = " . hist_value( $arg, $plot->{$arg}{$set} );
1338 }
1339 }
1340 77 say {$args->{fh}} 'd = [' . py_nums(@values) . ']';
1341 # hist() returns (counts, bin edges, patches); the counts are the only
1342 # way to know a bin's height, since matplotlib, not this module, does
1343 # the binning. Naming them changes nothing about what is drawn.
1344 77 ▶ if ($plot->{show_legend}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{'show_legend'}) { } 32 45 77
1345 32 say { $args->{fh} } "hist_n, hist_edges, hist_patches = ax$args->{ax}.hist(d, alpha = $alpha, label = " . py_str($set) . " $options $set_options)";
1346 } else {
1347 45 say { $args->{fh} } "hist_n, hist_edges, hist_patches = ax$args->{ax}.hist(d, alpha = $alpha $options $set_options)";
1348 }
1349 77 say {$args->{fh}} "hist_counts$args->{ax} += list(hist_n)";
1350 }
1351 }
1352 713 ▶sub has_hist {
Subroutine has_hist: called CC=5 SCAR=17.0
Pod undocumented
1353 # Whether a plot, or one of its "add" graphs, is a hist. An "add" graph
1354 # with no "plot_type" of its own takes $type, the plot's.
1355 713 my ( $plot, $type ) = @_;
1356 713 ▶ my @graphs = ( $plot, ( ref $plot->{add} eq 'ARRAY' ) ? @{ $plot->{add} } : () );
Branch: 1 branch
BranchTrueFalseTotal
ref $plot->{'add'} eq 'ARRAY' ? : 109 604 713
1357 713 ▶ 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
066470
($_->{"plot_type"} // $type) // ""
l!l
7340
$_->{"plot_type"} // $type
l!l&&r!l&&!r
73400
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
1358 }
1359 118 ▶sub hist_range_report {
Subroutine hist_range_report: called CC=2 SCAR=6.9
Pod undocumented
1360 # Python that starts ($when = 'start') or reports ($when = 'report') the
1361 # range of the bin heights of every hist drawn into subplot $ax.
1362 #
1363 # plt() calls this around the whole subplot -- its "add" graphs and its own
1364 # plot -- rather than hist_helper around each hist, which reset the list for
1365 # each: a subplot with a hist overlay printed two ranges, the second
1366 # leaving out the overlay's bins, where one range over all its sets is
1367 # what the documentation promises.
1368 #
1369 # On STDOUT and nowhere else: nothing here is handed to matplotlib, so the
1370 # figure written to "output_file" is exactly what it was without this.
1371 # plt() prints the script's STDOUT back out.
1372 118 my ( $fh, $ax, $when ) = @_;
1373 118 ▶ if ( $when eq 'start' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($when eq "start") 64 54 118
1374 64 say {$fh} "hist_counts$ax = []";
1375 64 return;
1376 }
1377 # "%g" because hist() hands back its counts as float64, and "[1, 12]" for a
1378 # tally of whole things is what was counted; "[1.0, 12.0]" reads as though
1379 # it were not.
1380 # An empty subplot has no bins at all, and min() of an empty list raises
1381 # ValueError, so there is nothing to report.
1382 54 say {$fh} "if len(hist_counts$ax) > 0:";
1383 54 say {$fh} "\tprint(f'plot $ax hist range = [{min(hist_counts$ax):g}, {max(hist_counts$ax):g}]')";
1384 }
1385  
1386 43 ▶sub hist2d_helper {
Subroutine hist2d_helper: called CC=37 SCAR=37.4
Pod undocumented
1387 43 my ($args) = @_;
1388 43 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
1389 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
1390 43 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 43 43
1391 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
1392 }
1393 43 my @reqd_args = (
1394 'fh', # e.g. $py, $fh, which will be passed by the subroutine
1395 'plot', # args to original function
1396 );
1397 43 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
1398 43 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 43 43
1399 0 p @undef_args;
1400 0 die 'the above args are necessary, but were not defined.';
1401 }
1402 43 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
1403 43 my $plot = $args->{plot};
1404 @undef_args = grep {
1405 309 my $key = $_;
1406 309 not grep { $_ eq $key } @opt
1407 43 } keys %{$plot};
1408 43 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 43 43
1409 bad_keyword_error({
1410 bad => \@undef_args,
1411 accepted => \@opt,
1412 preferred => $opt{$current_sub},
1413 type => $plot->{plot_type},
1414 0 sub => $current_sub
1415 });
1416 }
1417 43 cb_limits( $plot, $current_sub );
1418 43 $plot->{cb_logscale} = bool_option( $plot->{cb_logscale}, 'cb_logscale', $current_sub );
1419 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
1420 43 bin_counts( $plot, $current_sub );
1421 41 my @keys;
1422 41 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 2 39 41
1423 @keys = check_key_order({
1424 keys => $plot->{key_order},
1425 data => $plot->{data},
1426 2 option => 'key_order',
1427 sub => $current_sub
1428 });
1429 } else {
1430 39 @keys = sort keys %{ $plot->{data} };
1431 }
1432 40 ▶ if ( scalar @keys != 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @keys != 2) 0 40 40
1433 0 p @keys;
1434 0 die "There must be exactly 2 keys for $current_sub";
1435 }
1436 40 my $n_points = scalar @{ $plot->{data}{ $keys[0] } };
1437 40 ▶ if ( scalar @{ $plot->{data}{ $keys[1] } } != $n_points ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$plot->{"data"}{$keys[1]};} != $n_points) 0 40 40
1438 0 say STDERR "$keys[0] has $n_points points.";
1439 say STDERR "$keys[1] has "
1440 0 . scalar @{ $plot->{data}{ $keys[1] } }
1441 . " points.";
1442 0 die 'The length of both keys must be equal.';
1443 }
1444 # quoted here because the key is data: the pass-through path that title and
1445 # label text otherwise take cannot tell an apostrophe from Python of the
1446 # user's own, and leaves it bare. See py_str.
1447 40 default_axis_labels( $plot, @keys );
1448 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
1449 40 my $options = ', cmap = ' . py_str($plot->{cmap}); # these args go to the plt.hist call
1450 40 ▶ if ( $plot->{cb_logscale} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"cb_logscale"}) 4 36 40
1451 4 say {$args->{fh}} 'from matplotlib.colors import LogNorm';
1452 # prevents "ValueError: Passing a Normalize instance simultaneously with vmin/vmax is not supported. Please pass vmin/vmax directly to the norm when creating it"
1453 4 my @logNorm_opt;
1454 4 foreach my $arg (grep {defined $plot->{$_}} ('vmin', 'vmax')) {
1455 2 ▶ if (not looks_like_number($plot->{$arg})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&looks_like_number($plot->{$arg})) 0 2 2
1456 0 die "$arg must be numeric for $current_sub, but was given \"$plot->{$arg}\"";
1457 }
1458 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
1459 0 die "\"cb_logscale\" cannot start at \"vmin\" = $plot->{$arg} in $current_sub: a log scale needs a minimum above 0";
1460 }
1461 2 push @logNorm_opt, "$arg = " . py_num( $plot->{$arg} ); # py_num: "vmax => 'inf'" was a NameError
1462 2 delete $plot->{$arg};
1463 }
1464 4 $options .= ', norm = LogNorm(' . join (',', @logNorm_opt) . ')';
1465 }
1466 # Checked here as the log-scale branch above checks its own: each was
1467 # written as given, so "vmin => 'low'" left "vmin = low" in the script.
1468 40 foreach my $opt ( grep { defined $plot->{$_} } ( 'cmin', 'cmax', 'vmin', 'vmax' ) ) {
1469 8 check_numbers( [ $plot->{$opt} ], "\"$opt\"", $current_sub );
1470 6 $options .= ", $opt = " . py_num( $plot->{$opt} );
1471 }
1472 38 ▶ if ( defined $plot->{density} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"density"}) 2 36 38
1473 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
1474 }
1475 38 my @bad_indices;
1476 38 my $bad_pts = 0;
1477 38 foreach my $i (0,1) {
1478 76 @{ $bad_indices[$i] } = grep {not defined $plot->{data}{$keys[$i]}[$_]} 0..$n_points-1;
1479 76 $bad_pts += scalar @{ $bad_indices[$i] };
1480 }
1481 38 ▶ if ($bad_pts > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bad_pts > 0) 0 38 38
1482 0 say STDERR "the above args have the following indices undefined ($n_points total)";
1483 0 p @bad_indices;
1484 0 die "Cannot proceed as there are $bad_pts undefined points.";
1485 }
1486 38 foreach my $i (0,1) {
1487 76 @{ $bad_indices[$i] } = grep {not looks_like_number($plot->{data}{$keys[$i]}[$_])} 0..$n_points-1;
1488 76 $bad_pts += scalar @{ $bad_indices[$i] };
1489 }
1490 38 ▶ if ($bad_pts > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bad_pts > 0) 0 38 38
1491 0 p $args;
1492 0 say STDERR "the above args have the following indices non-numeric ($n_points total)";
1493 0 p @bad_indices;
1494 0 die "Cannot proceed as there are $bad_pts non-numeric points.";
1495 }
1496 38 say { $args->{fh} } 'x = ['
1497 38 . py_nums( @{ $plot->{data}{ $keys[0] } } ) . ']';
1498 38 say { $args->{fh} } 'y = ['
1499 38 . py_nums( @{ $plot->{data}{ $keys[1] } } ) . ']';
1500 # The ends of the range binned over, each the caller's or the data's own.
1501 # Nothing here was checked, and each was written as given: "xmin => 'a'"
1502 # was a NameError, a column with no finite value left an undefined end that
1503 # died as "Use of uninitialized value in concatenation", and a log axis
1504 # that reached 0 died inside np.log10 as "invalid entry in coordinates
1505 # array".
1506 38 my %log_axis = map { $_ => 1 } logscale_axes( $plot->{logscale}, $current_sub );
1507 36 foreach my $i ( 0, 1 ) {
1508 68 my $axis = ( 'x', 'y' )[$i];
1509 68 my @finite = finite_values( @{ $plot->{data}{ $keys[$i] } } );
1510 68 foreach my $end ( 'min', 'max' ) {
1511 134 my $opt = "$axis$end";
1512 134 ▶ if ( defined $plot->{$opt} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $plot->{$opt}) { } 8 126 134
elsif (scalar @finite == 0) { } 1 125 126
1513 8 check_numbers( [ $plot->{$opt} ], "\"$opt\"", $current_sub );
1514 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
1515 } elsif ( scalar @finite == 0 ) {
1516 1 die "\"$keys[$i]\" has no finite value, so $current_sub has no range to bin it over; give \"${axis}min\" and \"${axis}max\"";
1517 } else {
1518 125 ▶ $plot->{$opt} = ( $end eq 'min' ) ? min(@finite) : max(@finite);
Branch: 1 branch
BranchTrueFalseTotal
$end eq 'min' ? : 62 63 125
1519 }
1520 }
1521 66 my ( $lo, $hi ) = @{$plot}{ "${axis}min", "${axis}max" };
1522 66 ▶ if ( $lo > $hi ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lo > $hi) 1 65 66
1523 1 die "\"${axis}min\" = $lo is above \"${axis}max\" = $hi in $current_sub";
1524 }
1525 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
1526 1 die "\"logscale\" puts $axis on a log scale, which cannot start at $lo in $current_sub: give a \"${axis}min\" above 0";
1527 }
1528 }
1529 32 my %end = map { $_ => py_num( $plot->{$_} ) } ( 'xmin', 'xmax', 'ymin', 'ymax' );
1530 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
1531 # the range argument ensures that there are no empty parts of the plot
1532 32 my $range = ", range = [($end{xmin}, $end{xmax}), ($end{ymin}, $end{ymax})]";
1533 # logscale complications
1534 32 say {$args->{fh}} 'import numpy as np';
1535 # Bin edges, one more than the bins: "xbins" and "ybins" count bins, as
1536 # they do on a linear plot, where they go to hist2d as counts. They were
1537 # written as the number of edges, so a log axis had one bin fewer than it
1538 # asked for, and "xbins => 1" gave one edge, no bins at all, and died in
1539 # np.max as "zero-size array". The test is on the axes, not on "logscale"
1540 # itself, which as an empty array was true and took this branch for none.
1541 32 ▶ if ( scalar keys %log_axis ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %log_axis) { } 5 27 32
1542 5 foreach my $axis ( 'x', 'y' ) {
1543 10 my $min = $end{ $axis . 'min' };
1544 10 my $max = $end{ $axis . 'max' };
1545 10 my $edges = $plot->{"${axis}bins"} + 1;
1546 10 ▶ if ( $log_axis{$axis} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($log_axis{$axis}) { } 5 5 10
1547 5 say {$args->{fh}} "ax$ax.set_$axis" . 'scale("log")';
1548 5 say {$args->{fh}} "${axis}bins = np.logspace(np.log10($min), np.log10($max), $edges)";
1549 } else {
1550 5 say {$args->{fh}} "${axis}bins = np.linspace($min, $max, $edges)";
1551 }
1552 }
1553 5 $options = ", bins = [xbins, ybins] $options";
1554 } else {
1555 27 $options = ", ($plot->{xbins}, $plot->{ybins}) $options";
1556 }
1557 32 say {$args->{fh}} "hist2d_n, hist2d_xedges, hist2d_yedges, im$ax = ax$ax.hist2d(x, y $options $range)";
1558 32 say {$args->{fh}} 'max_hist2d_box = np.max(hist2d_n)';
1559 32 say {$args->{fh}} 'min_hist2d_box = np.min(hist2d_n)';
1560 32 say {$args->{fh}} "print(f'plot $ax hist2d density range = [{min_hist2d_box}, {max_hist2d_box}]')";
1561 32 ▶ return 0 if $plot->{show_colorbar} == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $plot->{"show_colorbar"} == 0 2 30 32
1562 30 my $opts = colorbar_args($plot); # cblabel is written below
1563 # say { $args->{fh} } "cbar = fig.colorbar(im$ax $opts)" if $plot->{colorbar_on};
1564 # As in hexbin_helper: "colorbar_on" used to be read only for the shared
1565 # colorbar, so "colorbar_on => 0" drew one anyway and the documentation
1566 # had to tell the reader to use "show_colorbar" instead. Both now work, and
1567 # a subplot whose colorbar plt() turns off for sharing stays off.
1568 30 ▶ if ( $plot->{colorbar_on} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"colorbar_on"}) 28 2 30
1569 28 ▶ if ( defined $plot->{cblabel} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'cblabel'}) { } 2 26 28
1570 2 say { $args->{fh} } "plt.colorbar(im$ax, label = " . py_str($plot->{cblabel}) . " $opts)";
1571 } else {
1572 26 say { $args->{fh} } "plt.colorbar(im$ax, label = 'Density' $opts)";
1573 }
1574 }
1575 }
1576  
1577 44 ▶sub imshow_helper {
Subroutine imshow_helper: called CC=44 SCAR=38.0
Pod undocumented
1578 44 my ($args) = @_;
1579 44 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
1580 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
1581 44 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 44 44
1582 0 die
1583 "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
1584 }
1585 44 my @reqd_args = (
1586 'ax',
1587 'fh', # e.g. $py, $fh, which will be passed by the subroutine
1588 'plot', # args to original function
1589 );
1590 44 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
1591 44 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 44 44
1592 0 p @undef_args;
1593 0 die 'the above args are necessary, but were not defined.';
1594 }
1595 44 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
1596 44 my $plot = $args->{plot};
1597 @undef_args = grep {
1598 290 my $key = $_;
1599 290 not grep { $_ eq $key } @opt
1600 44 } keys %{$plot};
1601 44 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 44 44
1602 bad_keyword_error({
1603 bad => \@undef_args,
1604 accepted => \@opt,
1605 preferred => $opt{$current_sub},
1606 type => $plot->{plot_type},
1607 0 sub => $current_sub
1608 });
1609 }
1610 44 cb_limits( $plot, $current_sub );
1611 43 my $data_ref = ref $plot->{data};
1612 43 ▶ if ($data_ref ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($data_ref ne "ARRAY") 2 41 43
1613 2 p $args;
1614 2 die "$current_sub can only accept 2-D arrays as input in \"data\", but received $data_ref";
1615 }
1616 # An empty image is refused here, by name: it has nothing to draw, and it
1617 # used to reach Python as "vmin = inf", a NameError about nothing in the
1618 # data.
1619 41 my @bad_rows = grep { ref $plot->{data}[$_] ne 'ARRAY' } 0 .. $#{ $plot->{data} };
1620 41 ▶ if (scalar @bad_rows > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_rows > 0) 0 41 41
1621 0 p @bad_rows;
1622 0 die "the above rows of \"data\" are not array references, which $current_sub needs";
1623 }
1624 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
1625 1 die "$current_sub was given no data to draw";
1626 }
1627 # Every row the same length: numpy refused a ragged image from inside
1628 # matplotlib, as "setting an array element with a sequence ... inhomogeneous
1629 # shape", which named no row.
1630 40 my %row_lengths;
1631 40 $row_lengths{ scalar @{$_} } = 1 foreach @{ $plot->{data} };
1632 40 ▶ if ( scalar keys %row_lengths > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %row_lengths > 1) 1 39 40
1633 die "the rows of \"data\" have different lengths ("
1634 1 . join( ', ', map { scalar @{ $plot->{data}[$_] } } 0 .. $#{ $plot->{data} } )
1635 . "), but $current_sub draws a rectangle of cells";
1636 }
1637 # An undefined cell, refused by name. It was counted as a string, and
1638 # without a "stringmap" the image died as needing "a map to translate
1639 # strings to integers", for numeric data that held no strings.
1640 39 my @undef_cells;
1641 39 foreach my $r ( 0 .. $#{ $plot->{data} } ) {
1642 126 push @undef_cells, map { "[$r][$_]" } grep { not defined $plot->{data}[$r][$_] } 0 .. $#{ $plot->{data}[$r] };
1643 }
1644 39 ▶ if ( scalar @undef_cells > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_cells > 0) 1 38 39
1645 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
1646 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';
1647 }
1648 38 my $non_numeric_data = 0;
1649 38 my $any_nonfinite = 0; # 1 once a value of a numeric image is NaN or infinite
1650 38 foreach my $row (@{ $plot->{data} }) {
1651 113 ▶ if (grep {not looks_like_number($_)} @{ $row }) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {not &looks_like_number($_);} @{$row;}) 12 101 113
1652 12 $non_numeric_data = 1;
1653 12 last;
1654 }
1655 }
1656 38 $plot->{cb_logscale} = bool_option( $plot->{cb_logscale}, 'cb_logscale', $current_sub );
1657 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
1658 1 p $args;
1659 1 die "$current_sub needs a map to translate strings to integers";
1660 }
1661 # Each key of stringmap gets an integer, in sorted order. The integers come
1662 # from a range, not from "scalar @ytick_labels" as they were: perl returns
1663 # the count of an empty array as a shared 0 that also carries the string
1664 # "0", the first category's 0 was copied from it, and JSON::XS -- which
1665 # JSON::MaybeXS uses when it has no Cpanel::JSON::XS -- wrote it as "0".
1666 # One string among the integers made numpy read the whole image as text,
1667 # and imshow died as "Image data of dtype <U21 cannot be converted to
1668 # float".
1669 37 my @strings = sort keys %{ $plot->{stringmap} };
1670 37 my %intmap = map { $strings[$_] => $_ } 0 .. $#strings;
1671 37 my @ytick_labels = @{ $plot->{stringmap} }{@strings};
1672 # The rows drawn: the caller's own, or for string data a translated copy.
1673 # The strings used to be replaced in place, so the caller's array came back
1674 # holding integers; and a string that "stringmap" did not name became an
1675 # undefined cell, drawn blank with nothing said.
1676 37 my $data = $plot->{data};
1677 37 ▶ if ($non_numeric_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($non_numeric_data) { } 11 26 37
1678 11 my %unmapped;
1679 11 foreach my $row (@{ $data }) {
1680 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
1681 }
1682 11 ▶ if (scalar keys %unmapped > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %unmapped > 0) 1 10 11
1683 1 my @unmapped = sort keys %unmapped;
1684 1 p @unmapped;
1685 1 die "the above values of \"data\" are not keys of \"stringmap\", which $current_sub needs to give each one a color";
1686 }
1687 10 $data = [ map { [ map { $intmap{$_} } @{ $_ } ] } @{ $data } ];
1688 } else {
1689 # Numbers as numbers. write_data sends "d" through JSON, which writes a
1690 # scalar last used as a string -- a row split from a line of a file -- as
1691 # a JSON string, and numpy refused such rows as "Image data of dtype <U1
1692 # cannot be converted to float". A copy, since the rows are the caller's.
1693 # JSON has no NaN or infinity, and the encoder writes both as null, which
1694 # numpy refused as "Image data of dtype object"; they travel as the
1695 # strings "nan", "inf" and "-inf" instead, which the float conversion
1696 # written after the data below reads back as the numbers they were.
1697 #
1698 # Whether any value is not finite is noted as each is copied. It was
1699 # looked for afterwards with a regex over every value, which gave each
1700 # number a string as well, and for a 1500 x 1500 image cost 0.2 s and
1701 # about 140 MB.
1702 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
1703 }
1704 36 my ( $min_val, $max_val ); # the ends of a stringmap's scale; numbers are left to norm_args
1705 36 my $opts = '';
1706 36 ▶ if ($non_numeric_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($non_numeric_data) 10 26 36
1707 10 my @prop_cycle = ('#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2',
1708 '#7f7f7f', '#bcbd22', '#17becf'); #plt.rcParams['axes.prop_cycle']
1709 10 my $n_strings = scalar keys %intmap;
1710 10 ▶ if ( $n_strings > scalar @prop_cycle ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_strings > scalar @prop_cycle) { } 1 9 10
1711 # More categories than the default property cycle has colors. The
1712 # slice used to run off the end of @prop_cycle and die inside
1713 # join() as "Use of uninitialized value", naming neither
1714 # "stringmap" nor the number of categories, so an 11th category
1715 # was an unexplained crash. A continuous colormap resampled to the
1716 # number of categories gives that many distinct colors for any
1717 # number of them.
1718 1 say { $args->{fh} } 'import matplotlib';
1719 1 say { $args->{fh} } "this_cmap = matplotlib.colormaps['gist_rainbow'].resampled($n_strings)";
1720 } else {
1721 9 say { $args->{fh} } 'from matplotlib.colors import ListedColormap';
1722 9 say { $args->{fh} } 'colors = [' . py_list( @prop_cycle[ 0 .. $n_strings - 1 ] ) . ']';
1723 9 say { $args->{fh} } 'this_cmap = ListedColormap(colors)';
1724 }
1725 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
1726 10 delete $plot->{cmap};
1727 10 $min_val = 0;
1728 10 $max_val = max(values %intmap);
1729 10 $opts .= ', cmap = this_cmap';
1730 }
1731 write_data({
1732 data => $data,
1733 fh => $args->{fh},
1734 36 name => 'd',
1735 });
1736 # Only where a value needs it, so that an image of whole numbers is still
1737 # drawn from whole numbers.
1738 36 ▶ if ($any_nonfinite) {
Branch: 1 branch
BranchTrueFalseTotal
if ($any_nonfinite) 2 34 36
1739 2 say { $args->{fh} } 'import numpy as np';
1740 2 say { $args->{fh} } 'd = np.asarray(d, dtype = float)';
1741 }
1742 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
1743 36 foreach my $opt (grep {defined $plot->{$_}} ('cmap')) { # strings
1744 1 $opts .= ", $opt = " . py_str( $plot->{$opt} );
1745 }
1746 # Categories have no scale to put on a log axis.
1747 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
1748 1 die "\"cb_logscale\" means nothing for $current_sub with a \"stringmap\": its colors are categories, not a scale";
1749 }
1750 # vmin and vmax were written as given, so a word was a bare Python name,
1751 # and "cb_logscale" was accepted and never read. An image with no finite
1752 # value leaves the ends to matplotlib; they came out as "vmin = inf".
1753 35 foreach my $v ( grep { defined $plot->{$_} } ( 'vmin', 'vmax' ) ) {
1754 5 check_numbers( [ $plot->{$v} ], "\"$v\"", $current_sub );
1755 }
1756 $opts .= norm_args({
1757 lo => $plot->{vmin} // ( $non_numeric_data ? $min_val : undef ),
1758 hi => $plot->{vmax} // ( $non_numeric_data ? $max_val : undef ),
1759 rows => $non_numeric_data ? [] : $data,
1760 log => $plot->{cb_logscale},
1761 fh => $args->{fh},
1762 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
1763 });
1764 33 say { $args->{fh} } "im$ax = ax$ax.imshow(d, aspect = 'auto' $opts)";
1765 33 $opts = '';
1766 33 ▶ if ($non_numeric_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($non_numeric_data) 9 24 33
1767 # One tick per category, at the middle of its band of the colorbar.
1768 # The colormap has one color per category and spans [0, $max_val], so
1769 # category i covers [i/n, (i+1)/n] of that span and its middle sits at
1770 # $max_val * (2i+1) / 2n. The formula here was "$_ + 0.5 - $_/$max_val",
1771 # which divided by zero when there was a single category and put both
1772 # ticks in the same place when there were two.
1773 9 my $n_strings = $max_val + 1;
1774 $opts .= ', ticks = ['
1775 9 . join( ',', map { $max_val * ( 2 * $_ + 1 ) / ( 2 * $n_strings ) } 0 .. $max_val ) . ']';
1776 }
1777 # py_str, not "'$value'": a cblabel is prose, and "Farmer's yield" closed
1778 # the literal early and left the script unparseable.
1779 33 ▶ $opts .= ', label = ' . py_str( $plot->{cblabel} ) if defined $plot->{cblabel};
Branch: 1 branch
BranchTrueFalseTotal
if defined $plot->{"cblabel"} 2 31 33
1780 33 $opts .= colorbar_args($plot);
1781 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
1782 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
1783 # The colorbar's own set_ticklabels, which labels whichever axis its
1784 # ticks are on. cbar.ax.set_yticklabels was written whatever the
1785 # orientation, and a horizontal colorbar, whose ticks are on x, died as
1786 # "The number of FixedLocator locations (0) ... does not match the number
1787 # of labels".
1788 9 say { $args->{fh} } 'cbar.set_ticklabels([' . py_list(@ytick_labels) . '])';
1789 }
1790 }
1791  
1792 17 ▶sub pie_helper {
Subroutine pie_helper: called CC=14 SCAR=26.6
Pod undocumented
1793 17 my ($args) = @_;
1794 17 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
1795 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
1796 17 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 17 17
1797 0 die
1798 "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
1799 }
1800 17 my @reqd_args = (
1801 'ax',
1802 'fh', # e.g. $py, $fh, which will be passed by the subroutine
1803 'plot', # args to original function
1804 );
1805 17 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
1806 17 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 17 17
1807 0 p @undef_args;
1808 0 die 'the above args are necessary, but were not defined.';
1809 }
1810 17 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
1811 17 my $plot = $args->{plot};
1812 my @undef_opt = grep {
1813 100 my $key = $_;
1814 100 not grep { $_ eq $key } @opt
1815 17 } keys %{$plot};
1816 17 ▶ if ( scalar @undef_opt > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_opt > 0) 0 17 17
1817 bad_keyword_error({
1818 bad => \@undef_opt,
1819 accepted => \@opt,
1820 preferred => $opt{$current_sub},
1821 type => $plot->{plot_type},
1822 0 sub => $current_sub
1823 });
1824 }
1825 17 my @key_order;
1826 17 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 3 14 17
1827 @key_order = check_key_order({
1828 keys => $plot->{key_order},
1829 data => $plot->{data},
1830 3 option => 'key_order',
1831 sub => $current_sub
1832 });
1833 } else {
1834 14 @key_order = sort keys %{ $plot->{data} };
1835 }
1836 # As in barplot_helper: a wedge size is written into the script as it
1837 # stands, so a non-numeric one becomes a bare Python name and the script
1838 # dies as a NameError with nothing to say about the data.
1839 16 foreach my $key (@key_order) {
1840 35 ▶ if ( not looks_like_number( $plot->{data}{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&looks_like_number($plot->{"data"}{$key})) 1 34 35
1841 1 p $plot->{data};
1842 1 die "\"$key\" is not a number, which $current_sub needs to size a wedge";
1843 }
1844 # matplotlib refuses these as "Wedge sizes must be finite numbers"
1845 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
1846 # and these as "Wedge sizes 'x' must be non negative values"
1847 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
1848 }
1849 # and nothing at all, which matplotlib divides by: "x must have a positive sum"
1850 13 ▶ if ( not grep { $plot->{data}{$_} > 0 } @key_order ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$plot->{"data"}{$_} > 0;} @key_order) 1 12 13
1851 1 die "every wedge of $current_sub is 0, so there is no pie to divide between them";
1852 }
1853 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
1854 12 my $opt = '';
1855 12 ▶ if ( $plot->{autopct} ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"autopct"} ne "") 1 11 12
1856 1 $opt .= ", autopct = " . py_str( $plot->{autopct} );
1857 }
1858 12 foreach my $arg ( grep { defined $plot->{$_} } 'labeldistance', 'pctdistance' ) {
1859 3 check_numbers( [ $plot->{$arg} ], "\"$arg\"", $current_sub ); # written bare, so a word was a NameError
1860 2 $opt .= ", $arg = " . py_num( $plot->{$arg} );
1861 }
1862 write_data({
1863 data => \@key_order,
1864 fh => $args->{fh},
1865 11 name => 'labels',
1866 });
1867 11 say { $args->{fh} } 'vals = ['
1868 11 . py_nums( @{ $plot->{data} }{@key_order} ) . ']';
1869 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
1870 11 say { $args->{fh} } "ax$ax.pie(vals, labels = labels $opt)";
1871 }
1872  
1873 73 ▶sub plot_helper {
Subroutine plot_helper: called CC=71 SCAR=45.6
Pod undocumented
1874 73 my ($args) = @_;
1875 73 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
1876 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
1877 73 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 73 73
1878 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
1879 }
1880 73 my @reqd_args = (
1881 'ax', 'fh',# e.g. $py, $fh, which will be passed by the subroutine
1882 'plot', # args to original function
1883 );
1884 73 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
1885 73 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 73 73
1886 0 p @undef_args;
1887 0 die 'the above args are necessary, but were not defined.';
1888 }
1889 73 my @opt = (@ax_methods, @fig_methods, @arg, @plt_methods, 'ax', @{ $opt{$current_sub} });
1890 73 my $plot = $args->{plot};
1891 my @bad_opt = grep {
1892 450 my $key = $_;
1893 450 not grep { $_ eq $key } @opt
1894 73 } keys %{$plot};
1895 73 ▶ if ( scalar @bad_opt > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 73 73
1896 bad_keyword_error({
1897 bad => \@bad_opt,
1898 accepted => \@opt,
1899 preferred => $opt{$current_sub},
1900 type => $plot->{plot_type},
1901 0 sub => $current_sub
1902 });
1903 }
1904 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
1905 73 foreach my $axis ( logscale_axes( $plot->{logscale}, $current_sub ) ) { # x, y
1906 3 say {$args->{fh}} "ax$args->{ax}.set_$axis" . 'scale("log")';
1907 }
1908 70 my @twinx;
1909 # The one twin of these axes, made the first time a line asks for it and
1910 # shared by every twinned line after, including those of an "add" graph on
1911 # the same axes. Each twinned line used to get a twin of its own, so two of
1912 # them had two right-hand axes, each with its own limits, their ticks drawn
1913 # over one another on the same spine.
1914 14 ▶ my $twin = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1915 14 my $ax = "ax$args->{ax}";
1916 14 ▶ if ( not defined $twin_axes{$ax} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $twin_axes{$ax}) 12 2 14
1917 12 $twin_axes{$ax} = "twinx_$ax";
1918 12 say { $args->{fh} } "$twin_axes{$ax} = $ax.twinx() # " . __LINE__;
1919 }
1920 14 return $twin_axes{$ax};
1921 70 };
1922 # Allow a single line entered as two bare array refs, with no enclosing
1923 # pair-array and no hash key:
1924 # data => [ \@x, \@y ]
1925 # Promote it to the canonical array-of-pairs form so the array path below
1926 # handles it unchanged:
1927 # data => [ [ \@x, \@y ] ]
1928 # The discriminator vs. the multi-line form (data => [ [\@x,\@y], ... ]) is
1929 # data->[0][0]: a number here, an ARRAY ref in the multi-line form.
1930 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
1931 12 && ( scalar @{ $plot->{data} } == 2 )
1932 && ( ref $plot->{data}[0] eq 'ARRAY' )
1933 && ( ref $plot->{data}[1] eq 'ARRAY' )
1934 && ( ref $plot->{data}[0][0] ne 'ARRAY' ) )
1935 {
1936 4 $plot->{data} = [ $plot->{data} ];
1937 }
1938 70 ▶ if (ref $plot->{data} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"data"} eq "ARRAY") 12 58 70
1939 12 ▶ if (defined $plot->{set_options}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_options"}) 4 8 12
1940 4 my $ref_type = ref $plot->{set_options};
1941 # a scalar applies to every line (handy for the single-line form);
1942 # an array gives one option string per line (positional)
1943 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
1944 2 my $n_set_opt = scalar @{ $plot->{set_options} };
1945 2 my $n_data = scalar @{ $plot->{data} };
1946 2 ▶ if ($n_set_opt > $n_data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_set_opt > $n_data) 0 2 2
1947 0 p $args;
1948 0 die "there are $n_set_opt sets for options, but only $n_data data points.";
1949 }
1950 } elsif ($ref_type ne '') {
1951 0 p $args;
1952 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.";
1953 }
1954 }
1955 12 ▶ if (defined $plot->{twinx}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"twinx"}) 3 9 12
1956 3 my $twinx_ref = ref $plot->{twinx};
1957 3 ▶ if ($twinx_ref eq '') {
Branch: 2 branches
BranchTrueFalseTotal
if ($twinx_ref eq '') { } 1 2 3
elsif ($twinx_ref eq 'ARRAY') { } 1 1 2
1958 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
1959 1 @twinx = $plot->{twinx};
1960 } elsif ($twinx_ref eq 'ARRAY') {
1961 1 @bad_opt = grep {$_ !~ m/^\d+$/} @{ $plot->{twinx} };
1962 1 ▶ if (scalar @bad_opt > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 1 1
1963 0 p @bad_opt;
1964 0 die 'data that could not possibly be an array index for twinx is shown above';
1965 }
1966 1 @twinx = @{ $plot->{twinx} };
1967 } else {
1968 # Any other reference fell off the end of this chain and was
1969 # ignored without a word, so a twinx given in the hash form
1970 # ("twinx => { B => 1 }") against array data simply did not
1971 # draw a second axis.
1972 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";
1973 }
1974 }
1975 11 ▶ if (defined $plot->{twinx_args}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"twinx_args"}) 2 9 11
1976 2 my $ref = ref $plot->{twinx_args};
1977 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
1978 2 check_twinx_args( $plot->{twinx_args}, $current_sub );
1979 2 @bad_opt = grep {$_ !~ m/^\d+$/} keys %{ $plot->{twinx_args} };
1980 2 ▶ if (scalar @bad_opt > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 2 2
1981 0 p @bad_opt;
1982 0 die 'the above keys are not hash indices';
1983 }
1984 2 foreach my $idx (keys %{ $plot->{twinx_args} }) {
1985 0 ▶ next if grep {$idx == $_} @twinx;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$idx == $_;} @twinx 0 2 2
1986 2 push @twinx, $idx;
1987 }
1988 }
1989 # An index past the last line was ignored without a word, where the
1990 # hash form refuses a key that is not in "data".
1991 11 my $n_lines = scalar @{ $plot->{data} };
1992 0 my @past_end = sort { $a <=> $b } grep { $_ >= $n_lines } @twinx;
1993 11 ▶ if ( scalar @past_end > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @past_end > 0) 2 9 11
1994 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
1995 }
1996 9 my $arr_i = 0;
1997 9 foreach my $arr (@{ $plot->{data} }) {
1998 15 my $ref = ref $arr;
1999 15 ▶ if ($ref ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref ne "ARRAY") 0 15 15
2000 0 p $plot->{data}[$arr_i];
2001 0 die "index $arr_i is \"$ref\" but must be \"ARRAY\"";
2002 }
2003 15 my $n_elem = scalar @{ $arr };
2004 15 ▶ if ($n_elem != 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_elem != 2) 0 15 15
2005 0 p $arr;
2006 0 die "there must be 2 array references (x, y) but index $arr_i has $n_elem";
2007 }
2008 15 @bad_opt = map { scalar @{ $arr->[$_] } } (0,1);
2009 15 ▶ if ($bad_opt[0] != $bad_opt[1]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bad_opt[0] != $bad_opt[1]) 0 15 15
2010 0 say STDERR "index $arr_i must have arrays/array refs of equal length, but these lengths were given:";
2011 0 p @bad_opt;
2012 0 die 'the array/array ref lengths must be equal';
2013 }
2014 15 foreach my $i (0,1) {
2015 30 my $max_i = scalar @{ $arr->[$i] } - 1;
2016 30 @bad_opt = grep {not looks_like_number($arr->[$i][$_])} 0..$max_i;
2017 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
2018 0 p $plot->{data}[$arr_i];
2019 0 p @bad_opt;
2020 0 @bad_opt = @{ $arr->[$i] }[@bad_opt];
2021 0 say STDERR 'have these non-numeric values:';
2022 0 p @bad_opt;
2023 0 die "Array index $arr_i/axis $i has non-numeric values (above)";
2024 }
2025 15 my $options = '';
2026 15 say { $args->{fh} } 'x = [' . py_nums( @{ $arr->[0] } ) . ']';
2027 15 say { $args->{fh} } 'y = [' . py_nums( @{ $arr->[1] } ) . ']';
2028 15 ▶ if ( defined $plot->{set_options} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_options"}) 7 8 15
2029 7 my $so_ref = ref $plot->{set_options};
2030 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
2031 3 $options = ", $plot->{set_options}";
2032 ▶ } 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
2033 && ( defined $plot->{set_options}[$arr_i] ) ) {
2034 4 $options = ", $plot->{set_options}[$arr_i]"; # one per line
2035 }
2036 }
2037 15 my $ax = "ax$args->{ax}";
2038 15 ▶ if (grep {$arr_i == $_} @twinx) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$arr_i == $_;} @twinx) { } 3 12 15
2039 3 my $twin_ax = $twin->();
2040 3 say { $args->{fh} } "$twin_ax.plot(x, y $options) # " . __LINE__;
2041 3 ▶ if (defined $plot->{twinx_args}{$arr_i}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"twinx_args"}{$arr_i}) 1 2 3
2042 plot_args({
2043 fh => $args->{fh},
2044 1 args => $plot->{twinx_args}{$arr_i},
2045 ax => $twin_ax,
2046 no_legend => 1 # its lines go in the legend of $ax
2047 });
2048 }
2049 } else {
2050 12 say { $args->{fh} } "ax$args->{ax}.plot(x, y $options) # " . __LINE__;
2051 }
2052 15 $arr_i++;
2053 }
2054 9 return 1; # the rest only applies if $plot->{data} is a hash
2055 }
2056 58 my @key_order;
2057 58 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 4 54 58
2058 @key_order = check_key_order({
2059 keys => $plot->{key_order},
2060 data => $plot->{data},
2061 4 option => 'key_order',
2062 sub => $current_sub
2063 });
2064 } else {
2065 54 @key_order = sort keys %{ $plot->{data} };
2066 }
2067 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
2068 4 @bad_opt = sort grep {!defined $plot->{data}{$_}} keys %{ $plot->{set_options} };
2069 4 ▶ if (scalar @bad_opt > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 4 4
2070 0 p @bad_opt;
2071 0 die "the above options are defined for undefined data sets in $current_sub.";
2072 }
2073 }
2074 57 ▶ if (defined $plot->{twinx}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"twinx"}) 9 48 57
2075 9 my $twinx_ref = ref $plot->{twinx};
2076 9 ▶ if ($twinx_ref eq '') {
Branch: 2 branches
BranchTrueFalseTotal
if ($twinx_ref eq '') { } 7 2 9
elsif ($twinx_ref eq 'HASH') { } 1 1 2
2077 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
2078 7 @twinx = ($plot->{twinx});
2079 } elsif ($twinx_ref eq 'HASH') {
2080 1 @bad_opt = sort grep {!defined $plot->{data}{$_}} keys %{ $plot->{twinx} };
2081 1 ▶ if (scalar @bad_opt > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 1 1
2082 0 p @bad_opt;
2083 0 die 'data for undefined data keys is shown above';
2084 }
2085 1 @twinx = sort keys %{ $plot->{twinx} };
2086 } else {
2087 # As in the array branch above: anything else was ignored in
2088 # silence, so "twinx => ['B']" against a hash of sets drew nothing
2089 # and said nothing.
2090 1 die "$current_sub: \"data\" is a hash, so \"twinx\" is a data key or a hash of them, not a $twinx_ref reference";
2091 }
2092 }
2093 56 ▶ if (defined $plot->{twinx_args}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"twinx_args"}) 7 49 56
2094 7 my $ref = ref $plot->{twinx_args};
2095 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
2096 7 check_twinx_args( $plot->{twinx_args}, $current_sub );
2097 6 @bad_opt = sort grep {!defined $plot->{data}{$_}} keys %{ $plot->{twinx_args} };
2098 6 ▶ if (scalar @bad_opt > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @bad_opt > 0) 0 6 6
2099 0 p @bad_opt;
2100 0 die 'the above keys are not present in data keys';
2101 }
2102 6 foreach my $set (keys %{ $plot->{twinx_args} }) {
2103 6 ▶ next if grep {$set eq $_} @twinx;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$set eq $_;} @twinx 4 2 6
2104 2 push @twinx, $set;
2105 }
2106 }
2107 55 foreach my $set (@key_order) {
2108 72 my $set_ref = ref $plot->{data}{$set};
2109 72 ▶ if ( $set_ref ne 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($set_ref ne "ARRAY") 0 72 72
2110 0 p $plot->{data}{$set};
2111 0 die "$set must have two arrays, x and y coordinates, or one array of y values, but instead has a $set_ref";
2112 }
2113 # A set of plain values, with no array among them, is y alone, and is
2114 # drawn against 0 .. n-1. The pair is built here rather than written
2115 # back, so the caller's data is left as it was given.
2116 72 my $xy = $plot->{data}{$set};
2117 72 my $n_refs = grep { ref } @{$xy};
2118 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
2119 6 $xy = [ [ 0 .. $#{$xy} ], $xy ];
2120 66 } elsif ( $n_refs < scalar @{$xy} ) {
2121 1 p $xy;
2122 1 die "$current_sub: set \"$set\" mixes arrays with plain values: it must be [ \\\@x, \\\@y ] or one array of y values";
2123 }
2124 71 my $n_arrays = scalar @{ $xy };
2125 71 ▶ if ( $n_arrays != 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_arrays != 2) 1 70 71
2126 1 p $xy;
2127 1 die "$n_arrays were entered for $set, but there must be exactly 2";
2128 }
2129 70 my @n_elem = map { scalar @{ $xy->[$_] }} (0,1);
2130 70 ▶ if ( $n_elem[0] != $n_elem[1] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_elem[0] != $n_elem[1]) 0 70 70
2131 0 p $xy;
2132 0 p @n_elem;
2133 0 die "$set has length = $n_elem[0] for x; length = $n_elem[1] for y: x & y must be of equal length";
2134 }
2135 70 foreach my $ax (0,1) {
2136 140 my $n = scalar @{ $xy->[$ax] };
2137 140 my @undef_i = grep {not defined $xy->[$ax][$_]} 0..$n-1;
2138 140 ▶ if (scalar @undef_i > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_i > 0) 1 139 140
2139 1 p $plot;
2140 1 p @undef_i;
2141 1 my $max_i = scalar @{ $xy->[$ax] };
2142 1 die "set $set axis $ax has undefined indices, of max index $max_i in $current_sub";
2143 }
2144 # The array form of "data" has always refused these; the hash form
2145 # wrote them into the script, where 'a' became "y = [a,3]" and died
2146 # as a NameError.
2147 139 my @non_numeric = grep { not looks_like_number( $xy->[$ax][$_] ) } 0 .. $n - 1;
2148 139 ▶ if ( scalar @non_numeric > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @non_numeric > 0) 2 137 139
2149 2 my @values = @{ $xy->[$ax] }[@non_numeric];
2150 2 p @values;
2151 2 die "set \"$set\" axis $ax has the above non-numeric values, which $current_sub cannot plot";
2152 }
2153 }
2154 67 my $options = '';
2155 67 say { $args->{fh} } 'x = [' . py_nums( @{ $xy->[0] } ) . ']';
2156 67 say { $args->{fh} } 'y = [' . py_nums( @{ $xy->[1] } ) . ']';
2157 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
2158 && ( ref $plot->{set_options} eq '' ) )
2159 {
2160 2 $options = ", $plot->{set_options}";
2161 }
2162 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
2163 5 $options = ", $plot->{set_options}{$set}";
2164 }
2165 67 my $label = '';
2166 67 ▶ if ( $plot->{show_legend} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"show_legend"}) 60 7 67
2167 60 $label = ',label = ' . py_str($set);
2168 }
2169 67 my $ax = "ax$args->{ax}";
2170 67 ▶ if (grep {$set eq $_} @twinx) { # this set has
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$set eq $_;} @twinx) { } 11 56 67
2171 11 my $twin_ax = $twin->();
2172 11 say { $args->{fh} } "$twin_ax.plot(x, y $label $options) # " . __LINE__;
2173 11 ▶ if (defined $plot->{twinx_args}{$set}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"twinx_args"}{$set}) 6 5 11
2174 plot_args({
2175 fh => $args->{fh},
2176 6 args => $plot->{twinx_args}{$set},
2177 ax => $twin_ax,
2178 no_legend => 1 # its lines go in the legend of $ax
2179 });
2180 }
2181 } else {
2182 56 say { $args->{fh} } "ax$args->{ax}.plot(x, y $label $options) # " . __LINE__;
2183 }
2184 }
2185 50 return 1;
2186 }
2187  
2188 117 ▶sub scatter_tooltips {
Subroutine scatter_tooltips: called CC=11 SCAR=24.0
Pod undocumented
2189 # Check one set's "tooltips" against its number of points, and return the
2190 # url of each point, which ties a labelled point to its text -- or undef
2191 # when there is nothing to draw.
2192 #
2193 # A url per point, rather than counting the markers in the SVG afterwards:
2194 # matplotlib writes each point's url as a link around that point's marker,
2195 # and leaves out the url of a point it does not draw -- NaN, or not above
2196 # 0 on a log axis -- so each label stays with its own point. An undefined
2197 # label is a point without a tooltip, and gets no url.
2198 117 my ( $labels, $n_points, $options, $where, $current_sub ) = @_;
2199 117 ▶ return undef unless defined $labels; # no tooltips for this set
Branch: 1 branch
BranchTrueFalseTotal
unless defined $labels 68 49 117
2200 49 ▶ if ( ref $labels ne 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $labels ne "ARRAY") 3 46 49
2201 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
2202 . ( ref $labels ? 'a ' . ( ref $labels ) . ' reference' : "\"$labels\"" );
2203 }
2204 46 ▶ if ( scalar @{$labels} != $n_points ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$labels;} != $n_points) 7 39 46
2205 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";
2206 }
2207 39 my @refs = grep { ref $labels->[$_] } 0 .. $#{$labels};
2208 39 ▶ if ( scalar @refs > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @refs > 0) 1 38 39
2209 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
2210 }
2211 38 my @labelled = grep { defined $labels->[$_] } 0 .. $#{$labels};
2212 38 ▶ return undef if scalar @labelled == 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @labelled == 0 2 36 38
2213 36 ▶ if ( $options =~ m/\burls?\s*=/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options =~ /\burls?\s*=/) 2 34 36
2214 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\"";
2215 }
2216 34 my @urls = (undef) x $n_points;
2217 34 foreach my $i (@labelled) {
2218 124 $urls[$i] = $tooltip_url . scalar @tooltip_text;
2219 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)
2220 }
2221 # Checked and counted either way, so that plt can say they were left out;
2222 # a url in a PNG or PDF is a link to nowhere.
2223 34 ▶ return undef unless $tooltips_drawn;
Branch: 1 branch
BranchTrueFalseTotal
unless $tooltips_drawn 2 32 34
2224 32 return \@urls;
2225 }
2226 102 ▶sub write_tooltip_urls {
Subroutine write_tooltip_urls: called CC=2 SCAR=6.9
Pod undocumented
2227 # Write one set's urls from scatter_tooltips, and return the argument that
2228 # hands them to ax.scatter; '' for a set with none.
2229 102 my ( $urls, $fh ) = @_;
2230 102 ▶ return '' unless defined $urls;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $urls 71 31 102
2231 31 write_data({
2232 data => $urls,
2233 fh => $fh,
2234 name => 'tooltip_urls'
2235 });
2236 31 return ', urls = tooltip_urls';
2237 }
2238 118 ▶sub scatter_helper {
Subroutine scatter_helper: called CC=90 SCAR=47.0
Pod undocumented
2239 118 my ($args) = @_;
2240 118 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
2241 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
2242 118 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 118 118
2243 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
2244 }
2245 118 my @reqd_args = (
2246 'ax', 'fh', # e.g. $py, $fh, which will be passed by the subroutine
2247 'plot', # args to original function
2248 );
2249 118 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
2250 118 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 118 118
2251 0 p @undef_args;
2252 0 die 'the above args are necessary, but were not defined.';
2253 }
2254 118 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
2255 118 my $plot = $args->{plot};
2256 @undef_args = grep {
2257 785 my $key = $_;
2258 785 not grep { $_ eq $key } @opt
2259 118 } keys %{$plot};
2260 118 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 118 118
2261 bad_keyword_error({
2262 bad => \@undef_args,
2263 accepted => \@opt,
2264 preferred => $opt{$current_sub},
2265 type => $plot->{plot_type},
2266 0 sub => $current_sub
2267 });
2268 }
2269 118 foreach my $cb ( grep { defined $plot->{$_} } ( 'cb_min', 'cb_max' ) ) {
2270 3 check_numbers( [ $plot->{$cb} ], "\"$cb\"", $current_sub );
2271 }
2272 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
2273 117 my $overall_ref = ref $plot->{data};
2274 117 ▶ if ( $overall_ref ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($overall_ref ne "HASH") 1 116 117
2275 1 die
2276 "scatter only takes 1) hashes of arrays (single or 2) hash of hash of arrays; but $overall_ref was entered";
2277 }
2278 116 my ( %ref_counts, $plot_type );
2279 116 foreach my $set ( keys %{ $plot->{data} } ) {
2280 263 $ref_counts{ ref $plot->{data}{$set} }++;
2281 }
2282 116 my $ax = $args->{ax};
2283 116 ▶ if ( (scalar keys %ref_counts) > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %ref_counts > 1) 0 116 116
2284 0 p $plot->{data};
2285 0 die "different kinds of data were entered to plot $ax; should be simple hash or hash of arrays.";
2286 }
2287 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
2288 82 $plot_type = 'single';
2289 } elsif ( defined $ref_counts{HASH} ) {
2290 34 $plot_type = 'multiple';
2291 } else {
2292 0 p $plot->{data};
2293 0 p %ref_counts;
2294 0 die 'Could not determine scatter type for the above data.';
2295 }
2296 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
2297 116 $plot->{cb_logscale} = bool_option( $plot->{cb_logscale}, 'cb_logscale', $current_sub );
2298 116 foreach my $axis ( logscale_axes( $plot->{logscale}, $current_sub ) ) { # x, y
2299 4 say {$args->{fh}} "ax$ax.set_$axis" . 'scale("log")';
2300 }
2301 # "set_options" is one string of options for a single set, and a hash of
2302 # one per set for several. A string given to several sets died as "Can't
2303 # use string as a HASH ref"; a hash given to a single set was ignored.
2304 113 ▶ if ( defined $plot->{set_options} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_options"}) 10 103 113
2305 10 my $so_ref = ref $plot->{set_options};
2306 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
2307 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";
2308 }
2309 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
2310 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
2311 . ( $so_ref ? "a $so_ref reference" : 'a string' );
2312 }
2313 }
2314 # "key_order" is the order of the sets, which "keys" -- the order of the
2315 # axes within a set -- cannot say; a single set has only the one.
2316 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
2317 0 die "$current_sub: \"key_order\" orders the sets of a hash of sets; for the axes of a single set, use \"keys\"";
2318 }
2319 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
2320 78 my $options = '';
2321 78 my ( $color_key, @keys );
2322 78 ▶ if ( defined $plot->{'keys'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'keys'}) { } 9 69 78
2323 @keys = check_key_order({
2324 keys => $plot->{'keys'},
2325 data => $plot->{data},
2326 9 option => 'keys',
2327 sub => $current_sub
2328 });
2329 } else {
2330 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
11400
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
2331 }
2332 77 my $n_keys = scalar keys %{ $plot->{data} };
2333 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
2334 2 p $plot->{data};
2335 2 die "scatterplots can only take 2 or 3 keys as data, but $current_sub received $n_keys";
2336 }
2337 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
2338 10 $color_key = $plot->{color_key};
2339 # Asked here, before the keys are counted: a "color_key" that is not
2340 # a key of three took none of them away, so the count below died
2341 # first, as "needs one key for x and one for y, but "keys" and
2342 # "color_key" leave the 3 above", which never named the key that
2343 # was wrong.
2344 10 ▶ if ( not defined $plot->{data}{$color_key} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $plot->{"data"}{$color_key}) 3 7 10
2345 3 die "\"$color_key\" isn't defined for this scatter";
2346 }
2347 7 @keys = grep {$_ ne $plot->{color_key}} @keys;
2348 } elsif ( scalar @keys == 3 ) {
2349 22 $color_key = pop @keys;
2350 } elsif ( $n_keys == 3 ) {
2351 # As for several sets: "keys" named x and y of three keys, so the one
2352 # it left out is the color. It was drawn without one.
2353 1 my %named = map { $_ => 1 } @keys;
2354 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
300
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
2355 }
2356 72 ▶ if ( scalar @keys != 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @keys != 2) 1 71 72
2357 1 p @keys;
2358 1 die "$current_sub needs one key for x and one for y, but \"keys\" and \"color_key\" leave the " . scalar(@keys) . ' above';
2359 }
2360 71 foreach my $i (0,1) {
2361 141 check_scatter_values( $plot->{data}{ $keys[$i] }, "\"$keys[$i]\"", $current_sub );
2362 }
2363 70 ▶ check_scatter_lengths( $plot->{data}, [ @keys, ( defined $color_key ? $color_key : () ) ], '', $current_sub );
Branch: 1 branch
BranchTrueFalseTotal
defined $color_key ? : 29 41 70
2364 69 say { $args->{fh} } 'x = [' . py_nums( @{ $plot->{data}{ $keys[0] } } ) . ']';
2365 69 say { $args->{fh} } 'y = [' . py_nums( @{ $plot->{data}{ $keys[1] } } ) . ']';
2366 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
2367 && ( ref $plot->{set_options} eq '' ) )
2368 {
2369 3 $options = ", $plot->{set_options}";
2370 }
2371 69 $options .= write_tooltip_urls( scatter_tooltips( $plot->{tooltips}, scalar @{ $plot->{data}{ $keys[0] } }, $options, '', $current_sub ), $args->{fh} );
2372 60 ▶ if ( defined $color_key ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $color_key) { } 29 31 60
2373 29 ▶ if (not defined $plot->{data}{$color_key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $plot->{"data"}{$color_key}) 0 29 29
2374 0 die "\"$color_key\" isn't defined for this scatter";
2375 }
2376 29 check_scatter_values( $plot->{data}{$color_key}, "\"$color_key\"", $current_sub );
2377 28 say { $args->{fh} } 'z = [' . py_nums( @{ $plot->{data}{$color_key} } ) . ']';
2378 # cb_min, cb_max and cb_logscale, which were accepted here and not read.
2379 # Left out where set_options set a scale of their own, which matplotlib
2380 # would refuse beside this one.
2381 28 my $range = '';
2382 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
2383 $range = norm_args({
2384 lo => $plot->{vmin},
2385 hi => $plot->{vmax},
2386 values => $plot->{data}{$color_key},
2387 log => $plot->{cb_logscale},
2388 fh => $args->{fh},
2389 2 sub => $current_sub
2390 });
2391 }
2392 28 say { $args->{fh} }
2393 28 "im = ax$ax.scatter(x, y, c = z, cmap = " . py_str($plot->{cmap}) . "$range $options)";
2394 # The cb* options, "cblabel", "colorbar_on" and "shared_colorbar" were
2395 # all accepted here and none of them read: the colorbar was always drawn,
2396 # labelled with the color key, with only cbpad and cbdrawedges applied.
2397 28 my $cb_opts = colorbar_args($plot);
2398 28 ▶ if ( $plot->{colorbar_on} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"colorbar_on"}) 24 4 28
2399 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
2400 }
2401 } else {
2402 31 say { $args->{fh} } "ax$ax.scatter(x, y $options)";
2403 }
2404 # quoted here because the key is data; see py_str above
2405 59 default_axis_labels( $plot, @keys );
2406 } elsif ( $plot_type eq 'multiple' ) { # multiple sets
2407 33 my @undefined_opts;
2408 33 foreach my $set ( sort keys %{ $plot->{set_options} } ) {
2409 6 ▶ next if grep { $set eq $_ } keys %{ $plot->{data} };
Branch: 1 branch
BranchTrueFalseTotal
if grep {$set eq $_;} keys %{$$plot{"data"};} 6 0 6
2410 0 push @undefined_opts, $set;
2411 }
2412 33 ▶ if ( scalar @undefined_opts > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undefined_opts > 0) 0 33 33
2413 0 p $plot->{data};
2414 0 p $plot;
2415 0 say STDERR 'The data and options are above, but the following sets have options without data:';
2416 0 p @undefined_opts;
2417 0 die 'no data was defined for the above options';
2418 }
2419 # As "set_options": one array of labels per set, keyed by the set's name.
2420 33 ▶ if ( defined $plot->{tooltips} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"tooltips"}) 11 22 33
2421 11 my $tt_ref = ref $plot->{tooltips};
2422 11 ▶ if ( $tt_ref ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tt_ref ne "HASH") 1 10 11
2423 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
2424 . ( $tt_ref ? ( $tt_ref eq 'ARRAY' ? 'an' : 'a' ) . " $tt_ref reference" : 'a string' );
2425 }
2426 10 my @no_set = grep { not exists $plot->{data}{$_} } sort keys %{ $plot->{tooltips} };
2427 10 ▶ if ( scalar @no_set > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @no_set > 0) 1 9 10
2428 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
2429 }
2430 }
2431 # A set may be a single point, its values numbers rather than arrays:
2432 # catboost => { MAE => 0.41, R2 => 0.83 }. It is drawn as a scatter of
2433 # one point, labelled with the set's name. The wrapping goes into a copy
2434 # so that the caller's data is left as it was given.
2435 31 my %sets;
2436 31 foreach my $set ( keys %{ $plot->{data} } ) {
2437 58 my $inner = $plot->{data}{$set};
2438 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
2439 7 $sets{$set} = { map { $_ => [ $inner->{$_} ] } keys %{$inner} };
2440 } else {
2441 51 $sets{$set} = $inner;
2442 }
2443 }
2444 # The order the sets are drawn in, which is the order of the legend and
2445 # of the markers handed out below. Sorted by name before, with no way to
2446 # change it, so the groups that "df" makes with "by" came out with 10
2447 # before 2, though the documentation promised numeric order.
2448 31 my @set_order;
2449 31 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 4 27 31
2450 @set_order = check_key_order({
2451 keys => $plot->{key_order},
2452 data => $plot->{data},
2453 4 option => 'key_order',
2454 sub => $current_sub
2455 });
2456 } else {
2457 27 @set_order = sort keys %sets;
2458 }
2459 # Each set is labelled with its name, for the legend, unless this is
2460 # false. It was accepted and never read, so the legend was always drawn.
2461 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
2462 # Keys and color key of every set are settled, and every value checked,
2463 # before anything is written, because the color range is shared by all
2464 # sets and so has to be known before the first set is drawn.
2465 31 my ( %xy_keys, %color_key_of, %tooltip_urls_of );
2466 31 foreach my $set ( sort keys %sets ) {
2467 54 my ( @keys, $color_key );
2468 54 ▶ if ( defined $plot->{'keys'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'keys'}) { } 7 47 54
2469 @keys = check_key_order({
2470 keys => $plot->{'keys'},
2471 7 data => $sets{$set},
2472 option => 'keys',
2473 sub => "$current_sub set \"$set\""
2474 });
2475 } else { # automatically take the key from the first; further sets should have the same labels
2476 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
2477 }
2478 54 my $n_keys = scalar keys %{ $sets{$set} };
2479 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
2480 0 p $plot->{data}{$set};
2481 0 die "scatterplots can only take 2 or 3 keys as data, but $current_sub received $n_keys";
2482 }
2483 54 foreach my $key (@keys) {
2484 117 check_scatter_values( $sets{$set}{$key}, "\"$key\" of set \"$set\"", $current_sub );
2485 }
2486 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
2487 4 $color_key = $plot->{color_key};
2488 # before the keys are counted, as for a single set above
2489 4 ▶ if ( not defined $sets{$set}{$color_key} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $sets{$set}{$color_key}) 2 2 4
2490 2 die "\"$color_key\" isn't defined for set \"$set\"";
2491 }
2492 2 @keys = grep {$_ ne $plot->{color_key}} @keys;
2493 } elsif ( scalar @keys == 3 ) {
2494 7 $color_key = pop @keys;
2495 } elsif ( $n_keys == 3 ) {
2496 # "keys" named x and y of three inner keys, so the one it left out
2497 # is the color, as the third is when the keys are sorted. This
2498 # popped the y key off "keys" instead, and died as "Use of
2499 # uninitialized value $keys[1] in hash element".
2500 3 my %named = map { $_ => 1 } @keys;
2501 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
900
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
2502 }
2503 50 ▶ if ( scalar @keys != 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @keys != 2) 1 49 50
2504 1 p @keys;
2505 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';
2506 }
2507 49 ▶ if ( defined $color_key ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $color_key) 11 38 49
2508 11 ▶ if (not defined $sets{$set}{$color_key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $sets{$set}{$color_key}) 0 11 11
2509 0 die "\"$color_key\" isn't defined for set \"$set\"";
2510 }
2511 11 check_scatter_values( $sets{$set}{$color_key}, "\"$color_key\" of set \"$set\"", $current_sub );
2512 11 $color_key_of{$set} = $color_key;
2513 }
2514 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
2515 48 $xy_keys{$set} = \@keys;
2516 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
2517 }
2518 # One color scale for every set. Each ax.scatter normalises its own c to
2519 # its own minimum and maximum, so without this the same color meant a
2520 # different value in each set, the colorbar -- drawn from the last set --
2521 # was true only of that set, and a set of one point was always drawn in
2522 # the bottom color of the map whatever its value.
2523 21 my $color_range = '';
2524 21 ▶ if ( scalar keys %color_key_of > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %color_key_of > 0) 5 16 21
2525 5 my @z = finite_values( map { @{ $sets{$_}{ $color_key_of{$_} } } } keys %color_key_of );
2526 # cb_min, cb_max and cb_logscale, where given, set the ends and the
2527 # kind of the shared scale; they were accepted and not read.
2528 $color_range = norm_args({
2529 lo => $plot->{vmin},
2530 hi => $plot->{vmax},
2531 values => \@z,
2532 log => $plot->{cb_logscale},
2533 fh => $args->{fh},
2534 5 sub => $current_sub
2535 });
2536 }
2537 # The key the one colorbar is labelled with, from the last set that has
2538 # one. Kept apart from each set's own $color_key, which used to be this
2539 # same variable: a set with a third key left it defined for every set
2540 # after it, and a later set of only x and y died as '"z" isn't defined'.
2541 21 my $colorbar_key;
2542 # Sets colored by a third key are all drawn from the same colormap, so
2543 # color cannot tell them apart; each takes the next of these markers, in
2544 # the sorted order of the set names, unless its set_options name one. All
2545 # are filled, so each shows its color; the list repeats once it runs out. A
2546 # marker that set_options give to some set is left out, so that no other
2547 # set is given it too.
2548 4 my %taken = map { $_ => 1 } grep { defined }
2549 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
2550 21 my @markers = grep { not $taken{$_} } qw(o s ^ D v P X * < > p h d);
2551 21 ▶ @markers = ('o') if scalar @markers == 0; # all 13 taken: repeat the first
Branch: 1 branch
BranchTrueFalseTotal
if scalar @markers == 0 0 21 21
2552 21 my $marker_i = 0;
2553 21 foreach my $set (@set_order) {
2554 42 my $options = '';
2555 42 my @keys = @{ $xy_keys{$set} };
2556 42 my $color_key = $color_key_of{$set};
2557 42 ▶ if ( defined $plot->{set_options}{$set} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_options"}{$set}) 5 37 42
2558 5 $options = ", $plot->{set_options}{$set}";
2559 }
2560 42 say { $args->{fh} } 'x = [' . py_nums( @{ $sets{$set}{ $keys[0] } } ) . ']';
2561 42 say { $args->{fh} } 'y = [' . py_nums( @{ $sets{$set}{ $keys[1] } } ) . ']';
2562 # The set's name as its label, unless it has a label of its own: the
2563 # uncolored path below added one regardless, and a "label" in
2564 # "set_options" made "keyword argument repeated", a SyntaxError.
2565 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
2566 38 $options .= ', label = ' . py_str($set);
2567 }
2568 42 $options .= write_tooltip_urls( $tooltip_urls_of{$set}, $args->{fh} );
2569 42 ▶ if ( defined $color_key ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $color_key) { } 10 32 42
2570 10 $colorbar_key = $color_key;
2571 10 say { $args->{fh} } 'z = [' . py_nums( @{ $sets{$set}{$color_key} } ) . ']';
2572 10 ▶ unless ( $options =~ m/\bmarker\s*=/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options =~ /\bmarker\s*=/) 9 1 10
2573 9 $options .= ", marker = '$markers[ $marker_i % @markers ]'";
2574 9 $marker_i++;
2575 }
2576 # a set's own vmin, vmax or norm is its caller's decision, and
2577 # matplotlib refuses norm alongside vmin and vmax
2578 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
2579 10 say { $args->{fh} }
2580 10 "im = ax$ax.scatter(x, y, c = z, cmap = " . py_str($plot->{cmap}) . "$range $options)";
2581 } else {
2582 32 say { $args->{fh} } "ax$ax.scatter(x, y$options)";
2583 }
2584 # quoted here because the key is data; see py_str above
2585 42 default_axis_labels( $plot, @keys );
2586 }
2587 21 ▶ if ( defined $colorbar_key ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $colorbar_key) 5 16 21
2588 5 my $cb_opts = colorbar_args($plot);
2589 5 ▶ if ( $plot->{colorbar_on} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"colorbar_on"}) 5 0 5
2590 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
2591 }
2592 }
2593 }
2594 }
2595  
2596 28 ▶sub violin_helper {
Subroutine violin_helper: called CC=28 SCAR=33.4
Pod undocumented
2597 28 my ($args) = @_;
2598 28 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
2599 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
2600 28 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 28 28
2601 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
2602 }
2603 28 my @reqd_args = (
2604 'fh', # e.g. $py, $fh, which will be passed by the subroutine
2605 'plot', # args to original function
2606 );
2607 28 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
2608 28 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 28 28
2609 0 p @undef_args;
2610 0 die 'the above args are necessary, but were not defined.';
2611 }
2612 28 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
2613 28 my $plot = $args->{plot};
2614 my @undef_opt = grep {
2615 187 my $key = $_;
2616 187 not grep { $_ eq $key } @opt
2617 28 } keys %{$plot};
2618 28 ▶ if ( scalar @undef_opt > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_opt > 0) 0 28 28
2619 bad_keyword_error({
2620 bad => \@undef_opt,
2621 accepted => \@opt,
2622 preferred => $opt{$current_sub},
2623 type => $plot->{plot_type},
2624 0 sub => $current_sub
2625 });
2626 }
2627 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
2628 28 ▶ if ( $plot->{orientation} !~ m/^(?:horizontal|vertical)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($plot->{"orientation"} =~ /^(?:horizontal|vertical)$/) 0 28 28
2629 0 die "$current_sub needs either \"horizontal\" or \"vertical\", not \"$plot->{orientation}\"";
2630 }
2631 28 ▶ if (ref $plot->{data} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"data"} eq "ARRAY") 3 25 28
2632 3 my $tmp = delete $plot->{data};
2633 3 $plot->{data}{''} = $tmp;
2634 }
2635 28 my ( @xticks, @key_order );
2636 28 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 2 26 28
2637 @key_order = check_key_order({
2638 keys => $plot->{key_order},
2639 data => $plot->{data},
2640 2 option => 'key_order',
2641 sub => $current_sub
2642 });
2643 } else {
2644 26 @key_order = sort keys %{ $plot->{data} };
2645 }
2646 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
2647 # Read as Python bools, as boxplot's switches are: "medians" was written as
2648 # given, so "medians => 'yes'" left "showmedians = yes" in the script, and
2649 # "whiskers" was tested for Perl truth, in which 'False' is true.
2650 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
2651 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
2652 # As in boxplot_helper: a hash here was written as 'HASH(0x...)'.
2653 26 ▶ if ( ref $plot->{color} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"color"}) 1 25 26
2654 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\' }';
2655 }
2656 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
2657 25 my $options = ''; # these args go to the plt.hist call
2658 25 say { $args->{fh} } 'd = []';
2659 # %values, rather than writing the filtered list back into $plot->{data}:
2660 # the arrays in there belong to the caller, and dropping the undefined and
2661 # non-numeric elements in place left the caller's own array shorter than
2662 # they wrote it.
2663 25 my %values;
2664 25 foreach my $key (@key_order) {
2665 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
2666 # A group left with nothing in it has no mean to draw, and the mean is
2667 # computed by dividing by this count: it died as "Use of uninitialized
2668 # value in division", which named neither the group nor the filtering
2669 # that emptied it.
2670 37 ▶ if ( scalar @{ $values{$key} } == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$values{$key};} == 0) 1 36 37
2671 1 my $n_given = scalar @{ $plot->{data}{$key} };
2672 1 die "\"$key\" has no numeric values for $current_sub to plot ($n_given value(s) given, all undefined, NaN or non-numeric)";
2673 }
2674 # An infinity gives the density estimate nothing to spread over and made
2675 # the mean below "Inf", written into the script as a bare name.
2676 36 my @infinite = grep { not is_finite($_) } @{ $values{$key} };
2677 36 ▶ if ( scalar @infinite > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @infinite > 0) 1 35 36
2678 1 p @infinite;
2679 1 die "\"$key\" has the above infinite values, which $current_sub cannot draw a density for";
2680 }
2681 35 say { $args->{fh} } 'd.append(['
2682 35 . py_nums( @{ $values{$key} } ) . '])';
2683 }
2684 23 foreach my $axis ( logscale_axes( $plot->{logscale}, $current_sub ) ) { # x, y
2685 2 say {$args->{fh}} "ax$ax.set_$axis" . 'scale("log")';
2686 }
2687 # No "points": it is how many points the density curve is evaluated at,
2688 # not a count of data, and it used to be set to the size of the smallest
2689 # group, so a group of 5 values drew every violin as a 5-sided polygon.
2690 # matplotlib's default is 100.
2691 20 say { $args->{fh} } "vp = ax$ax.violinplot(d, showmeans=False, orientation = '$plot->{orientation}', showmedians = $plot->{medians})";
2692 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
2693 # the below code helps to provide better error messages in case I make an error in calling the sub
2694 2 my @wrong_keys = grep { not defined $plot->{colors}{$_} } keys %{ $plot->{data} };
2695 2 ▶ if ( scalar @wrong_keys > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @wrong_keys > 0) 1 1 2
2696 1 p $plot;
2697 1 p @wrong_keys;
2698 1 die 'the above data keys have no defined color';
2699 }
2700 # list of pre-defined colors: https://matplotlib.org/stable/gallery/color/named_colors.html
2701 1 say { $args->{fh} } 'colors = ['
2702 1 . py_list( @{ $plot->{colors} }{@key_order} ) . ']';
2703  
2704 # the above color list will have the same order, via the above hash slice
2705 1 say { $args->{fh} } 'for i, pc in enumerate(vp["bodies"], 1):';
2706 1 say { $args->{fh} } "\tpc.set_facecolor(colors[i-1])";
2707 1 say { $args->{fh} } "\tpc.set_edgecolor(" . py_str( $plot->{edgecolor} ) . ')';
2708 } else {
2709 18 say { $args->{fh} } 'for pc in vp["bodies"]:';
2710 18 ▶ if ( defined $plot->{color} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"color"}) 1 17 18
2711 1 say { $args->{fh} } "\tpc.set_facecolor(" . py_str($plot->{color}) . ')';
2712 }
2713 18 say { $args->{fh} } "\tpc.set_edgecolor(" . py_str( $plot->{edgecolor} ) . ')';
2714  
2715 # say {$args->{fh}} "\tpc.set_alpha(1)";
2716 }
2717 19 ▶ if ( $plot->{whiskers} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{"whiskers"}) 17 2 19
2718 # https://matplotlib.org/stable/gallery/statistics/customized_violin.html
2719 17 say {$args->{fh} } 'import numpy as np';
2720 17 say {$args->{fh} } 'def adjacent_values(vals, q1, q3):';
2721 17 say {$args->{fh} } ' upper_adjacent_value = q3 + (q3 - q1) * 1.5';
2722 17 say {$args->{fh} }
2723 ' upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])';
2724 17 say {$args->{fh} } ' lower_adjacent_value = q1 - (q3 - q1) * 1.5';
2725 17 say {$args->{fh} }
2726 ' lower_adjacent_value = np.clip(lower_adjacent_value, vals[0], q1)';
2727 17 say {$args->{fh} }
2728 ' return lower_adjacent_value, upper_adjacent_value';
2729 17 say {$args->{fh} } 'np_data = np.array(d, dtype = object)';
2730 17 say {$args->{fh} } 'quartile1 = []';
2731 17 say {$args->{fh} } 'medians = []';
2732 17 say {$args->{fh} } 'quartile3 = []';
2733 17 say {$args->{fh} } 'for subset in list(range(0, len(np_data))):';
2734 17 say {$args->{fh}} ' local_quartile1, local_medians, local_quartile3 = np.percentile(d[subset], [25, 50, 75])' . "\n";
2735 17 say {$args->{fh}} ' quartile1.append(local_quartile1)';
2736 17 say {$args->{fh}} ' medians.append(local_medians)';
2737 17 say {$args->{fh}} ' quartile3.append(local_quartile3)';
2738 # sorted(): adjacent_values reads the smallest and largest values as
2739 # vals[0] and vals[-1]. matplotlib's example sorts its data first; this
2740 # passed "d" in the caller's order, so for [10, 9, ..., 1, 100] the
2741 # lower whisker was clipped to q1 and not drawn at all.
2742 17 say {$args->{fh}} 'whiskers = np.array([';
2743 17 say {$args->{fh}} ' adjacent_values(sorted(subset), q1, q3)';
2744 17 say {$args->{fh}} ' for subset, q1, q3 in zip(d, quartile1, quartile3)])';
2745 17 say {$args->{fh}} 'whiskers_min, whiskers_max = whiskers[:, 0], whiskers[:, 1]';
2746 17 say {$args->{fh}} 'inds = np.arange(1, len(medians) + 1)';
2747 17 ▶ if ( $plot->{orientation} eq 'vertical' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{'orientation'} eq 'vertical') { } 16 1 17
2748 16 say { $args->{fh} } "ax$ax"
2749 . '.vlines(inds, quartile1, quartile3, color="k", linestyle="-", lw=5)';
2750 16 say { $args->{fh} } "ax$ax"
2751 . '.vlines(inds, whiskers_min, whiskers_max, color="k", linestyle="-", lw=1)';
2752 } else {
2753 1 say { $args->{fh} } "ax$ax"
2754 . '.hlines(inds, quartile1, quartile3, color="k", linestyle="-", lw=5)';
2755 1 say { $args->{fh} } "ax$ax"
2756 . '.hlines(inds, whiskers_min, whiskers_max, color="k", linestyle="-", lw=1)';
2757 }
2758 }
2759 19 foreach my $key (@key_order) {
2760 push @xticks, "$key ("
2761 28 . format_commas( scalar @{ $values{$key} }, '%.0u' ) . ')';
2762 28 my $mean = sum( @{ $values{$key} } ) / scalar @{ $values{$key} };
2763 28 ▶ if ( $plot->{orientation} eq 'vertical' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{'orientation'} eq 'vertical') { } 26 2 28
2764 26 say { $args->{fh} } "ax$ax.plot("
2765 . scalar @xticks . ", $mean"
2766 . ', "ro")'; # plot mean point, which is red
2767 } else { # orientation = horizontal
2768 2 say { $args->{fh} } "ax$ax.plot($mean, "
2769 . scalar @xticks . ', "ro")'; # plot mean point, which is red
2770 }
2771 }
2772 19 ▶ if ( $plot->{orientation} eq 'vertical' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plot->{'orientation'} eq 'vertical') { } 18 1 19
2773 18 say { $args->{fh} } "ax$ax.set_xticks(["
2774 . join( ',', 1 .. scalar @key_order ) . '], ['
2775 . py_list(@xticks) . '])';
2776 } else {
2777 1 say { $args->{fh} } "ax$ax.set_yticks(["
2778 . join( ',', 1 .. scalar @key_order ) . '], ['
2779 . py_list(@xticks) . '])';
2780 }
2781 }
2782  
2783 15 ▶sub write_wide_group {
Subroutine write_wide_group: called CC=4 SCAR=13.9
Pod undocumented
2784 # Emit the Python drawing one group of runs: every run faint, the mean of
2785 # the runs solid, and mean +/- 1 standard deviation as a ribbon.
2786 #
2787 # The runs need not share an x grid, so they are interpolated onto 101
2788 # evenly spaced points (the number the documentation promises) spanning
2789 # the group's own x range. Two properties of np.interp drive the code
2790 # below: it needs its sample points ascending, and by default it holds the
2791 # end values flat outside them. Left alone, the first silently returns a
2792 # flat line for a run whose x descends, and the second folds an invented
2793 # horizontal line into the mean and the s.d. wherever a run stops short of
2794 # the group's range. So each run is sorted by x first, and asked for NaN
2795 # outside its own range; the summary below then averages, at each point,
2796 # only the runs that actually reach it.
2797 15 my ($args) = @_;
2798 my ( $fh, $ax, $runs, $color, $label ) =
2799 15 @{$args}{qw(fh ax runs color label)};
2800 15 my ( $min_x, $max_x ) = ( 'inf', '-inf' );
2801 15 foreach my $run ( @{$runs} ) {
2802 35 $min_x = min( $min_x, finite_values( @{ $run->[0] } ) );
2803 35 $max_x = max( $max_x, finite_values( @{ $run->[0] } ) );
2804 }
2805 15 my $py_color = py_str($color);
2806 15 say {$fh} 'ys = []';
2807 15 say {$fh} 'base_x = np.linspace(' . py_num($min_x) . ', ' . py_num($max_x) . ', 101)';
2808 15 foreach my $run ( @{$runs} ) {
2809 35 say {$fh} 'x = [' . py_nums( @{ $run->[0] } ) . ']';
2810 35 say {$fh} 'y = [' . py_nums( @{ $run->[1] } ) . ']';
2811 35 say {$fh} "order = np.argsort(x, kind = 'stable')";
2812 35 say {$fh} 'x = np.asarray(x)[order]';
2813 35 say {$fh} 'y = np.asarray(y)[order]';
2814 35 say {$fh} "ax$ax.plot(x, y, $py_color, alpha=0.15)";
2815 35 say {$fh} 'ys.append(np.interp(base_x, x, y, left = np.nan, right = np.nan))';
2816 }
2817 15 say {$fh} 'ys = np.array(ys)';
2818 15 say {$fh} 'covered = ~np.isnan(ys)'; # which runs reach each point of base_x
2819 15 say {$fh} 'n_runs = covered.sum(axis = 0)';
2820 15 say {$fh} 'divisor = np.maximum(n_runs, 1)'; # a point no run reaches would divide by 0
2821 15 say {$fh} 'mean_ys = np.where(covered, ys, 0.0).sum(axis = 0) / divisor';
2822 15 say {$fh} 'var_ys = np.where(covered, (ys - mean_ys) ** 2, 0.0).sum(axis = 0) / divisor';
2823 15 say {$fh} 'std = np.where(n_runs > 0, np.sqrt(var_ys), np.nan)';
2824 15 say {$fh} 'mean_ys = np.where(n_runs > 0, mean_ys, np.nan)'; # after var_ys, which needs the unmasked mean
2825 15 say {$fh} 'ys_upper = mean_ys + std';
2826 15 say {$fh} 'ys_lower = mean_ys - std';
2827 15 ▶ if ( defined $label ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $label) { } 9 6 15
2828 9 say {$fh} "ax$ax.plot(base_x, mean_ys, $py_color, label = " . py_str($label) . ')';
2829 } else {
2830 6 say {$fh} "ax$ax.plot(base_x, mean_ys, $py_color)";
2831 }
2832 15 say {$fh} "ax$ax.fill_between(base_x, ys_lower, ys_upper, color=$py_color, alpha=0.3)";
2833 }
2834 18 ▶sub wide_helper {
Subroutine wide_helper: called CC=15 SCAR=27.8
Pod undocumented
2835 18 my ($args) = @_;
2836 18 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
2837 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
2838 18 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 18 18
2839 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
2840 }
2841 18 my @reqd_args = (
2842 'fh', # e.g. $py, $fh, which will be passed by the subroutine
2843 'plot', # args to original function
2844 );
2845 18 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
2846 18 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 18 18
2847 0 p @undef_args;
2848 0 die "the above args are necessary for $current_sub, but were not defined.";
2849 }
2850 18 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
2851 18 my $plot = $args->{plot};
2852 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
2853 my @undef_opt = grep {
2854 135 my $key = $_;
2855 135 not grep { $_ eq $key } @opt
2856 18 } keys %{$plot};
2857 18 ▶ if ( scalar @undef_opt > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_opt > 0) 0 18 18
2858 bad_keyword_error({
2859 bad => \@undef_opt,
2860 accepted => \@opt,
2861 preferred => $opt{$current_sub},
2862 type => $plot->{plot_type},
2863 0 sub => $current_sub
2864 });
2865 }
2866 18 say { $args->{fh} } 'import numpy as np';
2867 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
2868 18 my $ref_type = ref $plot->{data};
2869 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
2870 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
2871 1 die "$current_sub: \"data\" is a HASH of groups, so \"color\" must be a HASH of one color per group";
2872 }
2873 # Sorted, as every other plot type orders its keys: in hash order the
2874 # groups, and so the legend, came out in a different order from one
2875 # run to the next.
2876 8 my $group_i = 0;
2877 8 foreach my $group ( sort keys %{ $plot->{data} } ) {
2878 14 check_wide_runs( $plot->{data}{$group}, "group \"$group\"", $current_sub );
2879 # An uncolored group takes the next color of matplotlib's own
2880 # cycle, "C0", "C1" and on. Every group used to default to 'b', so
2881 # without a "color" hash the groups could not be told apart.
2882 write_wide_group({
2883 fh => $args->{fh},
2884 ax => $ax,
2885 runs => $plot->{data}{$group},
2886 color => $plot->{color}{$group} // 'C' . ( $group_i % 10 ), # the default cycle has 10 colors
2887 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
2888 });
2889 11 $group_i++;
2890 }
2891 } elsif ( $ref_type eq 'ARRAY' ) { # one unlabelled group
2892 9 ▶ if ( ref $plot->{color} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"color"}) 1 8 9
2893 1 die "$current_sub: \"data\" is one unlabelled group, so \"color\" must be a single color, not a " . ( ref $plot->{color} ) . ' reference';
2894 }
2895 8 check_wide_runs( $plot->{data}, '"data"', $current_sub );
2896 write_wide_group({
2897 fh => $args->{fh},
2898 ax => $ax,
2899 runs => $plot->{data},
2900 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
2901 label => undef # the array form carries no group name to label
2902 });
2903 } else {
2904 0 die "$current_sub cannot take ref type \"$ref_type\" for \"data\"";
2905 }
2906 }
2907  
2908 25 ▶sub print_type {
Subroutine print_type: called CC=15 SCAR=29.1
Pod undocumented
2909 # Whether a value has to be quoted on its way into the generated Python.
2910 25 my $str = shift;
2911 25 my $type = 'no quotes';
2912 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
2913 2 return 'no quotes';
2914 }
2915 # An argument list of bare values, such as "0, 10" for "ylim" or "0.5, 0, 1"
2916 # for "axhline", is Python rather than text. The comma tests below quoted
2917 # it, so a single plot's "ylim => '0, 10'" wrote plt.ylim('0, 10') and died
2918 # as "ValueError: too many values to unpack". None, True and False are bare
2919 # values too, so that
2920 # "ylim => 'None, 10'" leaves the bottom where matplotlib puts it.
2921 23 my @items = split /,/, $str, -1;
2922 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
2923 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
2924 2 return 'no quotes';
2925 }
2926 # A single Python value: None, True or False; one bracketed group, such as
2927 # "(0, 10)" or "[]"; or one call, such as "np.arange(0, 1, 0.1)". Each was
2928 # quoted below, which a single plot always did and a subplot does now that
2929 # it quotes as well. The bracket must close at the very end, so that
2930 # "f(x), g(x)" is still text.
2931 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
2932 || ( $str =~ m/^\h*(?:[A-Za-z_][\w.]*)?(\((?:[^()]++|(?1))*\))\h*$/ )
2933 || ( $str =~ m/^\h*(\[(?:[^\[\]]++|(?1))*\])\h*$/ ) ) {
2934 7 return 'no quotes';
2935 }
2936 # Text that already carries a quote of its own is Python the caller wrote
2937 # -- a quoted label ('"Counts, by book"', the form the documentation asks
2938 # for when the text holds a comma), a mathtext raw string, or a whole
2939 # argument list such as '0.5, 0.01, "note"'. Quoting it again nests the
2940 # quotes and emits plt.suptitle(''Counts, by book''), a SyntaxError. This
2941 # generalises the "keyword = <quote>" test below, which caught the same
2942 # thing only when the quote followed an "=".
2943 14 ▶ if ($str =~ m/['"]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /['"]/) 10 4 14
2944 10 return 'no quotes';
2945 }
2946 # A keyword argument, e.g. "hspace = 0.5" or "loc = 'upper left'": already
2947 # Python, whether or not its value is quoted.
2948 4 ▶ if ($str =~ m/\w\h*=\h*\S/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /\w\h*=\h*\S/) 0 4 4
2949 0 return 'no quotes';
2950 }
2951 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
2952 3 return 'single quotes';
2953 } elsif ($str =~ m/^\[\h*\-?\d.+\d\h*\]$/) {
2954 0 return 'no quotes';
2955 } elsif ($str =~ m/[!@#\$\%^&*\(\)\{\}\[\]\<\>,\/\-\h:;\+=\w]+$/) {
2956 1 return 'single quotes';
2957 ▶ } 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
2958 0 return 'single quotes';
2959 }
2960 0 return $type;
2961 }
2962 25 ▶sub pyplot_arg {
Subroutine pyplot_arg: called CC=2 SCAR=6.9
Pod undocumented
2963 # A pyplot option's value as the text between the parentheses of its call.
2964 #
2965 # A single plot and a subplot both write their pyplot options through
2966 # this. A subplot used to write every value exactly as given, so
2967 # "xscale => 'log'" left plt.xscale(log) and raised "NameError: name 'log'
2968 # is not defined", while the same option at a single plot was quoted.
2969 # py_str, not "'$value'": a backslash in '...' went through as a python
2970 # escape, so "C:\new" came out with a newline in it.
2971 25 my ($value) = @_;
2972 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
2973 }
2974 # The interpreters tried on MSWin32, in order. "python" first, because it is
2975 # what a stock install from python.org and an activated venv both put on PATH,
2976 # and the venv is the one that has matplotlib; "py -3", the launcher, next,
2977 # since an install can leave python off PATH but always installs the
2978 # launcher; "python3" last, for MSYS2 and the like. A stock Windows install has
2979 # no "python3" at all, which is why running it failed wherever Python *was*
2980 # present, and never showed up in a CPAN Testers report because the smokers
2981 # have none.
2982 25 my @windows_python_candidates = ( ['python'], [ 'py', '-3' ], ['python3'] );
2983 # The command plt runs, as a list for system(). undef = not yet looked for;
2984 # [] = looked for, and none found. A package variable rather than a lexical so
2985 # that the test suite can point it at a stand-in interpreter.
2986 25 our $python_command;
2987 34 ▶sub python_command {
Subroutine python_command: called CC=7 SCAR=19.5
Pod undocumented
2988 # The interpreter plt runs scripts with, as a list.
2989 # $ENV{MATPLOTLIB_SIMPLE_PYTHON}, when set and not empty, is that
2990 # interpreter, taken whole and neither searched for nor checked: it names a venv or a module-loaded Python
2991 # without changing PATH, and is not split on spaces because a path such as
2992 # "C:\Program Files\Python312\python.exe" has them. One that does not
2993 # run is reported by plt as "failed to start". Otherwise it is
2994 # ('python3') on everything but MSWin32, as it always was, and there the
2995 # first of @windows_python_candidates that reports itself as Python 3, or
2996 # an empty list if none does. The result is kept, so the search runs once.
2997 #
2998 # "--version" rather than trusting that the name resolves: on Windows 10
2999 # and 11 "python" with no Python installed is a Microsoft Store stub,
3000 # which prints "Python was not found" and exits 9009. Both streams are
3001 # read, since Python 3 before 3.4 printed its version to STDERR.
3002 34 ▶ return @{$python_command} if defined $python_command;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Matplotlib::Simple::Matplotlib::python_command 7 27 34
3003 27 my $named = program_from_env('MATPLOTLIB_SIMPLE_PYTHON');
3004 27 ▶ if ( defined $named ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $named) 3 24 27
3005 3 $python_command = [$named];
3006 3 return @{$python_command};
3007 }
3008 24 ▶ if ( $^O ne 'MSWin32' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O ne "MSWin32") 19 5 24
3009 19 $python_command = ['python3'];
3010 19 return @{$python_command};
3011 }
3012 5 foreach my $candidate (@windows_python_candidates) {
3013 10 ▶ my ( $out, $err, $status ) = capture {
Subroutine __ANON__: called CC=1 SCAR=0.0
3014 25 ▶ no warnings 'exec'; # a candidate that is not installed is expected; see the call in plt
Subroutine BEGIN: called CC=1 SCAR=0.0
3015 10 system( @{$candidate}, '--version' );
3016 10 };
3017 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
3018 4 $python_command = [ @{$candidate} ];
3019 4 return @{$python_command};
3020 }
3021 1 $python_command = [];
3022 1 return ();
3023 }
3024 507 ▶sub savefig_takes_metadata {
Subroutine savefig_takes_metadata: called CC=3 SCAR=11.0
Pod undocumented
3025 # Whether matplotlib's savefig accepts "metadata" for a file of this name:
3026 # 1 for .png, .pdf, .svg, .svgz, .eps and .ps, in any case, and for a name
3027 # with no extension, which matplotlib saves as its default format, a PNG;
3028 # 0 for every other extension. The extension is what follows the last "."
3029 # of the file's own name, as pathlib's suffix reads it, so a "." in a
3030 # directory's name, or one that leads the file's name, is not one.
3031 507 my ($file) = @_;
3032 507 ▶ return 1 unless $file =~ m{[^/\\.][^/\\]*\.([^./\\]*)\z}s;
Branch: 1 branch
BranchTrueFalseTotal
unless $file =~ m([^/\\.][^/\\]*\.([^./\\]*)\z)s 6 501 507
3033 501 ▶ 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/ ? : 476 25 501
3034 }
3035 10 ▶sub shared_color_scale {
Subroutine shared_color_scale: called CC=3 SCAR=11.0
Pod undocumented
3036 # Python giving every color-mapped artist of the subplots that share a
3037 # colorbar one scale: the lowest bottom and the highest top of any of
3038 # them.
3039 #
3040 # Each subplot scaled its colors to its own data -- hexbin and hist2d to
3041 # their own counts, which only matplotlib knows -- so the same color meant
3042 # a different value in each, and the one colorbar, drawn from the last of
3043 # them, was true only of that one. set_clim on each brings them to one
3044 # scale, and the colorbar follows the artist it was drawn from. The margins
3045 # a hexbin draws with "marginals" are left alone, being densities of their
3046 # own. colored_table is left to shared_table_range.
3047 10 my ( $fh, $args ) = @_;
3048 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
3049 10 ▶ return if scalar @axes < 2;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @axes < 2 3 7 10
3050 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]';
3051 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]';
3052 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]';
3053 7 say $fh 'if len(shared_mappables) > 1:';
3054 7 say $fh "\tshared_lo = min(m.norm.vmin for m in shared_mappables)";
3055 7 say $fh "\tshared_hi = max(m.norm.vmax for m in shared_mappables)";
3056 7 say $fh "\tfor m in shared_mappables:";
3057 7 say $fh "\t\tm.set_clim(shared_lo, shared_hi)";
3058 }
3059 664 ▶sub render {
Subroutine render: called CC=79 SCAR=44.8
Pod undocumented
3060 # plt's figure as a Python script, which is run unless "execute" is false.
3061 # Returns the script's path.
3062 #
3063 # args: plt's arguments once Matplotlib::Simple has checked them: "p" and "df"
3064 # folded in, "nrows", "ncols" and "execute" set, every plot_type
3065 # checked and every plot given "data"
3066 # context: sub => the name the caller called ("plt", "bar", ...)
3067 # single_plot => 1 = one plot, its keywords at the top level;
3068 # 0 = "plots", one hash per subplot
3069 # style => "matplotlib" or "native" (%Matplotlib::Simple::styles), which
3070 # draw the same figure here
3071 # dpi => the dots per inch to save "output_file" at, a
3072 # finite number above 0, or undef for matplotlib's own
3073 664 my ( $args, $context ) = @_;
3074 664 my $current_sub = $context->{sub};
3075 664 my $single_plot = $context->{single_plot};
3076 664 %twin_axes = (); # see its declaration
3077 664 @tooltip_text = (); # and this one's
3078 # matplotlib picks the format by the extension, in any case, and ".svgz"
3079 # is a gzipped SVG.
3080 664 ▶ $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 ? : 630 34 664
Condition100%3/3
defined $args->{"output_file"} and $args->{"output_file"} =~ /\.svgz?\z/i
!ll&&!rl&&r
727630
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
3081 664 my @ax = map { "ax$_" } 0 .. $args->{nrows} * $args->{ncols} - 1;
3082 664 my ( @py, @y, $fh);
3083 664 my $i = 0;
3084 664 foreach my $ax (@ax) {
3085 723 my $a1i = int $i / $args->{ncols}; # 1st index
3086 723 my $a2i = $i % $args->{ncols}; # 2nd index
3087 723 $y[$a1i][$a2i] = $ax;
3088 723 $i++;
3089 }
3090 664 foreach my $y (@y) {
3091 673 push @py, '(' . join( ',', @{$y} ) . ')';
3092 }
3093 664 $fh = script_handle( $args, '.py', $current_sub );
3094 664 say $fh 'import matplotlib.pyplot as plt';
3095 664 say $fh 'import json, base64';
3096 664 ▶ if ( $single_plot == 0 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($single_plot == 0) { } 53 611 664
elsif ($single_plot == 1) { } 611 0 611
3097 # matplotlib takes a bool or one of the words "row", "col", "all" and
3098 # "none". A word was written bare, so "sharey => 'row'" left
3099 # "sharey = row" in the script and died as a NameError.
3100 53 foreach my $share ('sharex', 'sharey') {
3101 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
3102 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
3103 1 $args->{$share} = py_str($value);
3104 ▶ } 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
3105 102 $args->{$share} = py_num($value); # matplotlib reads a number as a bool
3106 } else {
3107 2 ▶ $args->{$share} = bool_option( $value, $share, $current_sub ) ? 'True' : 'False';
Branch: 1 branch
BranchTrueFalseTotal
bool_option($value, $share, $current_sub) ? : 1 0 1
3108 }
3109 }
3110 52 say $fh 'fig, ('
3111 . join( ',', @py )
3112 . ") = plt.subplots($args->{nrows}, $args->{ncols}, sharex = $args->{sharex}, sharey = $args->{sharey}, layout = 'constrained') #" . __LINE__;
3113 } elsif ( $single_plot == 1 ) {
3114 611 say $fh 'fig, ax0 = plt.subplots(1,1, layout = "constrained")';
3115 } else {
3116 0 die "\$single_plot = $single_plot breaks pigeonholes";
3117 }
3118 663 my %dispatch = (
3119 bar => \&barplot_helper, barh => \&barplot_helper,
3120 boxplot => \&boxplot_helper, colored_table=> \&colored_table_helper,
3121 hexbin => \&hexbin_helper, hist => \&hist_helper,
3122 hist2d => \&hist2d_helper, imshow => \&imshow_helper,
3123 pie => \&pie_helper, plot => \&plot_helper,
3124 scatter => \&scatter_helper, violin => \&violin_helper,
3125 venn_proportional_area => \&venn_proportional_area_helper,
3126 violinplot => \&violin_helper,
3127 wide => \&wide_helper
3128 );
3129 663 ▶ if ($single_plot == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($single_plot == 1) 611 52 663
3130 611 my $has_hist = has_hist( $args, $args->{plot_type} );
3131 611 ▶ hist_range_report( $fh, 0, 'start' ) if $has_hist;
Branch: 1 branch
BranchTrueFalseTotal
if $has_hist 38 573 611
3132 611 foreach my $graph (@{ $args->{add} }) {
3133 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
3134 8 my $type = $graph->{plot_type};
3135 8 ▶ die 'plot_type not defined for "add" graph' unless defined $type;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type 0 8 8
3136 8 check_plot_type({ type => $type, where => 'for an "add" graph' });
3137 7 $dispatch{$type}->({
3138 fh => $fh,
3139 ax => 0,
3140 plot => $graph
3141 });
3142 }
3143 610 delete $args->{add};
3144 610 my $type = $args->{plot_type};
3145 # check_plot_type above has already refused anything outside
3146 # %opt_key_of_type, which lists the same 15 types as %dispatch, so this
3147 # fires only if the two are edited out of step.
3148 610 ▶ die "no helper is registered for plot_type \"$type\"" unless defined $dispatch{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dispatch{$type} 0 610 610
3149 610 $dispatch{$type}->({
3150 fh => $fh,
3151 ax => 0,
3152 plot => $args
3153 });
3154 440 ▶ hist_range_report( $fh, 0, 'report' ) if $has_hist;
Branch: 1 branch
BranchTrueFalseTotal
if $has_hist 28 412 440
3155 # "xlim" is not here, though it was: no keyword list accepts it, so it
3156 # is refused long before this as an option that isn't defined (the
3157 # documentation uses that refusal as its worked example), and the
3158 # rename could never fire.
3159 440 my %rename = (
3160 xlabel => 'set_xlabel',
3161 title => 'set_title',
3162 ylabel => 'set_ylabel',
3163 legend => 'legend',
3164 );
3165 440 foreach my $opt ( grep { defined $rename{$_} } keys %{$args} ) {
3166 262 $args->{ $rename{$opt} } = delete $args->{$opt};
3167 }
3168 # emit_plt_fig => 0: the "fig." and "plt." methods in this same hash
3169 # are written by the two loops below, which quote through print_type.
3170 # Letting both passes run emitted every one of them twice.
3171 plot_args({
3172 440 fh => $fh,
3173 args => $args,
3174 ax => 'ax0',
3175 emit_plt_fig => 0
3176 });
3177 }
3178 492 my $ax = 0;
3179 492 foreach my $plot (@{ $args->{plots} } ) {
3180 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
3181 (defined $args->{shared_colorbar}) && # shared_colorbar is defined
3182 44 (grep {$_ == $ax} @{ $args->{shared_colorbar} }) # subplot's colorbar is shared w other plots
3183 ) {
3184 20 ▶ if ($ax == max( @{ $args->{shared_colorbar} } )) { # this is the max
Branch: 1 branch
BranchTrueFalseTotal
if ($ax == &max(@{$$args{'shared_colorbar'};})) { } 10 10 20
3185 10 $plot->{colorbar_on} = 1; # turn on if this is the max plot
3186 10 $plot->{shared_colorbar} = $args->{shared_colorbar};
3187 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
3188 } else {
3189 10 $plot->{colorbar_on} = 0; # turn off, its colorbar will be shared later
3190 }
3191 }
3192 102 my $has_hist = has_hist( $plot, $plot->{plot_type} );
3193 102 ▶ hist_range_report( $fh, $ax, 'start' ) if $has_hist;
Branch: 1 branch
BranchTrueFalseTotal
if $has_hist 26 76 102
3194 102 foreach my $graph (@{ $plot->{add} }) {
3195 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
3196 13 my $type = $graph->{plot_type};
3197 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
3198 # "at subplot $ax", not "at ax = $ax": the up-front check above
3199 # words it that way, and this line and that one describe the same
3200 # graph.
3201 13 check_plot_type({ type => $type, where => "for an \"add\" graph at subplot $ax" });
3202 13 $dispatch{$type}->({
3203 fh => $fh,
3204 ax => $ax,
3205 plot => $graph
3206 });
3207 }
3208 # As above: the type was checked before the figure was written, so this
3209 # is a guard on %dispatch alone. Without it an unknown type died as
3210 # "Can't use an undefined value as a subroutine reference".
3211 die "no helper is registered for plot_type \"$plot->{plot_type}\" at ax = $ax"
3212 102 ▶ unless defined $dispatch{ $plot->{plot_type} };
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dispatch{$plot->{"plot_type"}} 0 102 102
3213 102 $dispatch{$plot->{plot_type}}->({
3214 fh => $fh,
3215 ax => $ax,
3216 plot => $plot
3217 });
3218 95 ▶ hist_range_report( $fh, $ax, 'report' ) if $has_hist;
Branch: 1 branch
BranchTrueFalseTotal
if $has_hist 26 69 95
3219 95 my %rename = (
3220 xlabel => 'set_xlabel', title => 'set_title',
3221 ylabel => 'set_ylabel', legend => 'legend',
3222 # xlim => 'set_xlim',
3223 );
3224 95 foreach my $opt ( grep { defined $rename{$_} } keys %{$plot} ) {
3225 32 $plot->{ $rename{$opt} } = delete $plot->{$opt};
3226 }
3227 plot_args({
3228 95 fh => $fh,
3229 args => $plot,
3230 ax => "ax$ax"
3231 });
3232 95 $ax++;
3233 }
3234 485 ▶ shared_color_scale( $fh, $args ) if defined $args->{shared_colorbar};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"shared_colorbar"} 10 475 485
3235 485 foreach my $ax (@ax) {
3236 542 say $fh "if $ax.has_data() == False:"; # remove empty plots
3237 542 say $fh "\t$ax.remove()"; # remove empty plots
3238 }
3239 485 my %methods = map { $_ => 1 } @plt_methods;
3240 # Text is quoted as plot_args quotes it before print_type sees it. For a
3241 # single plot this is what always happened, though by accident: plot_args
3242 # quoted the caller's own hash in place, and this loop read the result.
3243 # plot_args now works on a copy, so the step is written out here, where it
3244 # now also reaches the "suptitle" of a figure of several subplots, and the
3245 # figure's own "supxlabel" and "supylabel", written by the fig. loop below.
3246 485 my %written_here = map { $_ => 1 } ( @plt_methods, @fig_methods );
3247 485 ▶ foreach my $text_method ( grep { ( $written_here{$_} ) && ( defined $args->{$_} ) } @text_methods ) {
Condition100%3/3
$written_here{$_} && defined $args->{$_}
!ll&&!rl&&r
145529019
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
3248 9 my $text = $args->{$text_method};
3249 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
3250 }
3251 # As in plot_args: a single plot's "twinx" leaves the twin current, and its
3252 # "axhline" was drawn on the twin. A figure of several subplots is left
3253 # alone, since its own pyplot options are figure-wide ones like "suptitle".
3254 485 ▶ 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 474 485
Condition100%6/6
$single_plot == 1 and grep {defined $methods{$_} and $_ ne "show";} keys %{$args;}
!ll&&!rl&&r
4542911
defined $methods{$_} && $_ ne 'show'
!ll&&!rl&&r
4926414
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
3255 11 say $fh 'plt.sca(ax0) #' . __LINE__;
3256 }
3257 # A single plot's "legend" was written by plot_args above, and only if
3258 # something carries a label; writing it here too drew it a second time, and
3259 # warned "No artists with labels found to put in legend" when nothing did.
3260 485 ▶ 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
5250126
$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
3261 26 my $ref = ref $args->{$plt_method};
3262 26 ▶ if ( $ref eq '' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ref eq '') { } 26 0 26
elsif ($ref eq 'ARRAY') { } 0 0 0
3263 26 ▶ if ($plt_method eq 'show') {
Branch: 1 branch
BranchTrueFalseTotal
if ($plt_method eq "show") 10 16 26
3264 10 next; # plt.show() is emitted after plt.savefig() below
3265 }
3266 16 say $fh "plt.$plt_method(" . pyplot_arg( $args->{$plt_method} ) . ')#' . __LINE__;
3267 } elsif ( $ref eq 'ARRAY' ) {
3268 0 foreach my $j ( @{ $args->{$plt_method} } ) {
3269 0 say $fh "plt.$plt_method(" . pyplot_arg($j) . ')#' . __LINE__;
3270 }
3271 } else {
3272 0 p $args;
3273 0 die "$plt_method = \"$ref\" only accepts scalar or array types";
3274 }
3275 }
3276 485 %methods = map { $_ => 1 } @fig_methods;
3277 485 foreach my $fig_method ( grep { defined $methods{$_} } keys %{$args} ) {
3278 6 my $ref = ref $args->{$fig_method};
3279 6 ▶ if ( $ref eq '' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ref eq '') { } 6 0 6
elsif ($ref eq 'ARRAY') { } 0 0 0
3280 6 say $fh "fig.$fig_method($args->{$fig_method})#" . __LINE__;
3281 } elsif ( $ref eq 'ARRAY' ) {
3282 0 foreach my $j ( @{ $args->{$fig_method} } ) { # say $fh "plt.$method($plt)";
3283 0 say $fh "fig.$fig_method($j)";
3284 }
3285 } else {
3286 0 p $args;
3287 0 die "$fig_method = \"$ref\" only accepts scalar or array types";
3288 }
3289 }
3290 485 ▶ if (defined $args->{scale}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"scale"}) 1 484 485
3291 1 say $fh "fig.set_figheight(plt.rcParams['figure.figsize'][1] * $args->{scale}) #" . __LINE__;
3292 1 say $fh "fig.set_figwidth(plt.rcParams['figure.figsize'][0] * $args->{scale}) #" . __LINE__;
3293 }
3294 485 ▶ if (defined $args->{scalex}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"scalex"}) 1 484 485
3295 1 say $fh "fig.set_figwidth(plt.rcParams['figure.figsize'][0] * $args->{scalex}) #" . __LINE__;
3296 }
3297 485 ▶ if (defined $args->{scaley}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"scaley"}) 1 484 485
3298 1 say $fh "fig.set_figheight(plt.rcParams['figure.figsize'][1] * $args->{scaley}) #" . __LINE__;
3299 }
3300 485 ▶ if (defined $args->{output_file}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"output_file"}) 478 7 485
3301 write_data({
3302 data => $args->{output_file},
3303 478 fh => $fh,
3304 name => 'output_file'
3305 });
3306 # py_str, not interpolation: on MSWin32 the paths in creator_note are
3307 # backslash paths, so "C:\build\..." pasted into a Python literal
3308 # reads "\b" as a backspace and "\c" as an invalid escape
3309 # (SyntaxWarning in 3.12, SyntaxError from 3.15). An apostrophe
3310 # anywhere in the path would close the literal early.
3311 478 my $creator = py_str( creator_note($current_sub) );
3312 # The Python and matplotlib versions, the user and the host are read by
3313 # the script as it runs, not by Perl as it writes: with "execute => 0"
3314 # the script may be run later, or elsewhere, by an interpreter Perl
3315 # never sees, and it is whoever runs it that writes the file.
3316 478 say $fh 'import matplotlib, platform, getpass';
3317 # getpass.getuser() raises when no LOGNAME, USER, LNAME or USERNAME is
3318 # set and there is no password database to fall back on -- OSError
3319 # from Python 3.13, KeyError or ImportError before -- so an unknown
3320 # user must not stop the figure from being saved.
3321 478 say $fh 'try:';
3322 478 say $fh "\tcreator_user = getpass.getuser()";
3323 478 say $fh 'except Exception:';
3324 478 say $fh "\tcreator_user = 'unknown user'";
3325 478 say $fh "creator_host = platform.node() or 'unknown host' # node() is '' when the name cannot be found";
3326 # An SVG keeps only the Creator. matplotlib also writes the time it was
3327 # saved, its own "image/svg+xml" and a link to the Dublin Core "StillImage"
3328 # type, each of which a None leaves out (backend_svg._write_metadata,
3329 # matplotlib 3.11.2). Only for an SVG: the PDF backend warns about
3330 # "Format" and "Type" as keys it does not know.
3331 #
3332 # And only for a format that keeps metadata. The note was handed to
3333 # savefig whatever the file, and matplotlib refuses it for the formats
3334 # that have nowhere to put one -- "ValueError: metadata not supported
3335 # for format 'jpeg'", and the like for tiff, webp, gif, avif, raw and
3336 # rgba, and a TypeError for pgf -- so no .jpg, .tif, .webp, .gif or
3337 # .pgf could be written at all (matplotlib 3.11.2). Those are saved
3338 # without a note. matplotlib picks the format by the extension, in any
3339 # case, and a name with none is the PNG it has always been.
3340 # "dpi" is plt's own keyword for the resolution, checked there to be a
3341 # finite number above 0. Without it savefig is called as it always
3342 # was, at matplotlib's own "savefig.dpi".
3343 478 ▶ my $dpi = defined $context->{dpi} ? ', dpi = ' . py_num( $context->{dpi} ) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $context->{'dpi'} ? : 10 468 478
3344 # $tooltips_drawn is 1 exactly when output_file is an SVG (or SVGZ),
3345 # which is drawn into memory, finished there, and written to the file
3346 # once, below. It was saved, read back, and written again, once to cut
3347 # the DOCTYPE and once more for tooltips, so that a viewer watching the
3348 # file saw it change two or three times, and empty between: Eye of
3349 # GNOME 45.3, which reloads a PNG matplotlib has written over, stopped
3350 # reloading such an SVG at all. "format" because a buffer has no
3351 # extension to read it from.
3352 478 ▶ my $target = $tooltips_drawn ? "svg_buffer, format = 'svg'," : 'output_file,';
Branch: 1 branch
BranchTrueFalseTotal
$tooltips_drawn ? : 452 26 478
3353 478 ▶ print {$fh} <<'PYTHON' if $tooltips_drawn;
Branch: 1 branch
BranchTrueFalseTotal
if $tooltips_drawn 452 26 478
3354 import gzip, io, re
3355 svg_buffer = io.BytesIO()
3356 PYTHON
3357 478 ▶ if ( savefig_takes_metadata( $args->{output_file} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (savefig_takes_metadata($args->{'output_file'})) { } 468 10 478
3358 468 ▶ say $fh "plt.savefig($target bbox_inches = 'tight'$dpi, metadata={'Creator': $creator"
Branch: 1 branch
BranchTrueFalseTotal
$tooltips_drawn ? : 452 16 468
3359 . " + ', Python ' + platform.python_version() + ', matplotlib ' + matplotlib.__version__"
3360 . " + ', by ' + creator_user + ' on ' + creator_host"
3361 . ( $tooltips_drawn ? ", 'Date': None, 'Format': None, 'Type': None" : '' ) . '})';
3362 } else {
3363 10 say $fh "plt.savefig($target bbox_inches = 'tight'$dpi) # no metadata: this format keeps none";
3364 }
3365 # matplotlib writes <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ...>
3366 # from a fixed string, svgProlog in backend_svg.py, that no option turns
3367 # off, so it is cut from what was drawn. SVG 2 has no DOCTYPE, and no
3368 # browser reads it. It holds no ">" of its own: there is no internal
3369 # subset.
3370 478 ▶ print {$fh} <<'PYTHON' if $tooltips_drawn;
Branch: 1 branch
BranchTrueFalseTotal
if $tooltips_drawn 452 26 478
3371 svg_bytes = re.sub(rb'<!DOCTYPE[^>]*>\s*', b'', svg_buffer.getvalue(), count = 1)
3372 PYTHON
3373 }
3374 485 ▶ if ( ( scalar @tooltip_text > 0 ) && ( not $tooltips_drawn ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @tooltip_text > 0 and not $tooltips_drawn) 2 483 485
Condition100%3/3
scalar @tooltip_text > 0 and not $tooltips_drawn
!ll&&!rl&&r
458252
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
3375 warn '"tooltips" are drawn only into an SVG, so they are left out of '
3376 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
3377 . ': give "output_file" a name ending in ".svg"';
3378 }
3379 485 ▶ if ( ( scalar @tooltip_text > 0 ) && $tooltips_drawn ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @tooltip_text > 0 and $tooltips_drawn) 25 460 485
Condition100%3/3
scalar @tooltip_text > 0 and $tooltips_drawn
!ll&&!rl&&r
458225
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
3380 25 write_data({
3381 data => \@tooltip_text,
3382 fh => $fh,
3383 name => 'tooltip_text'
3384 });
3385 25 write_data({
3386 data => $tooltip_url,
3387 fh => $fh,
3388 name => 'tooltip_url'
3389 });
3390 # Each labelled point was drawn inside <a xlink:href="#...-<n>"
3391 # target="_blank">, which becomes a bare <g> whose first child is a
3392 # <title> holding text n. The namespaces are registered so that the
3393 # file is written back with matplotlib's own prefixes rather than ns0,
3394 # ns1, ...
3395 #
3396 # A <title> alone was not enough: whether a browser shows it on
3397 # hovering is up to the browser and the desktop, and in 0.321 neither
3398 # Firefox nor Chromium showed one on the author's machine. So the <g>
3399 # is also given the class matplotlib-simple-tooltip, and a script at
3400 # the end of the SVG draws the label itself, in a box beside the point
3401 # under the mouse. The script takes each <title> out as it starts, so
3402 # that a browser that does show titles does not show the label twice;
3403 # a viewer that runs no script -- Inkscape, Eye of GNOME, an <img> on
3404 # a web page -- keeps the <title>s in the file.
3405 25 print {$fh} <<'PYTHON';
3406 # Placement, in the SVG's own units, which are points: the box sits 4 from the
3407 # marker and 3 outside its text, above and to the right of the point, and is
3408 # moved left of or below it wherever it would leave the figure.
3409 tooltip_script = r'''(function () {
3410 var ns = 'http://www.w3.org/2000/svg';
3411 var me = document.currentScript;
3412 var svg = (me && me.ownerSVGElement) || document.documentElement;
3413 var points = svg.querySelectorAll('g.matplotlib-simple-tooltip');
3414 var gap = 4, pad = 3;
3415 var tip = document.createElementNS(ns, 'g');
3416 tip.setAttribute('pointer-events', 'none');
3417 tip.setAttribute('display', 'none');
3418 var box = document.createElementNS(ns, 'rect');
3419 box.setAttribute('rx', '2');
3420 box.setAttribute('style', 'fill: #ffffe1; stroke: #555555; stroke-width: 0.5');
3421 var text = document.createElementNS(ns, 'text');
3422 text.setAttribute('style', 'font-family: sans-serif; font-size: 10px; fill: #000000');
3423 tip.appendChild(box);
3424 tip.appendChild(text);
3425 svg.appendChild(tip);
3426 function show(point, label) {
3427 while (text.firstChild) text.removeChild(text.firstChild);
3428 label.split('\n').forEach(function (line, i) {
3429 var span = document.createElementNS(ns, 'tspan');
3430 span.setAttribute('x', '0');
3431 span.setAttribute('dy', i ? '1.2em' : '0');
3432 span.textContent = line;
3433 text.appendChild(span);
3434 });
3435 tip.removeAttribute('display');
3436 var ctm = svg.getScreenCTM();
3437 if (!ctm) return;
3438 var t = text.getBBox(), w = t.width + 2 * pad, h = t.height + 2 * pad;
3439 var bx = t.x - pad, by = t.y - pad;
3440 var r = point.getBoundingClientRect(), inv = ctm.inverse(), p = svg.createSVGPoint();
3441 p.x = r.left; p.y = r.top;
3442 var lo = p.matrixTransform(inv);
3443 p.x = r.right; p.y = r.bottom;
3444 var hi = p.matrixTransform(inv);
3445 var vb = svg.viewBox.baseVal;
3446 var left = vb ? vb.x : 0, top = vb ? vb.y : 0;
3447 var right = vb ? vb.x + vb.width : Infinity, bottom = vb ? vb.y + vb.height : Infinity;
3448 var x = hi.x + gap, y = lo.y - gap - h;
3449 if (x + w > right) x = lo.x - gap - w;
3450 if (x < left) x = left;
3451 if (y < top) y = hi.y + gap;
3452 if (y + h > bottom) y = Math.max(top, bottom - h);
3453 box.setAttribute('x', bx);
3454 box.setAttribute('y', by);
3455 box.setAttribute('width', w);
3456 box.setAttribute('height', h);
3457 tip.setAttribute('transform', 'translate(' + (x - bx) + ' ' + (y - by) + ')');
3458 }
3459 function hide() {
3460 tip.setAttribute('display', 'none');
3461 }
3462 Array.prototype.forEach.call(points, function (point) {
3463 var title = point.querySelector('title');
3464 if (!title) return;
3465 var label = title.textContent;
3466 point.removeChild(title);
3467 if (label === '') return;
3468 point.addEventListener('mouseenter', function () { show(point, label); });
3469 point.addEventListener('mouseleave', hide);
3470 });
3471 })();'''
3472 import xml.etree.ElementTree as ET
3473 svg_ns = 'http://www.w3.org/2000/svg'
3474 xlink_href = '{http://www.w3.org/1999/xlink}href'
3475 for prefix, uri in (('', svg_ns), ('xlink', 'http://www.w3.org/1999/xlink'),
3476 ('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'),
3477 ('cc', 'http://creativecommons.org/ns#'), ('dc', 'http://purl.org/dc/elements/1.1/')):
3478 ET.register_namespace(prefix, uri)
3479 svg_tree = ET.parse(io.BytesIO(svg_bytes))
3480 for link in list(svg_tree.iter('{%s}a' % svg_ns)):
3481 href = link.get(xlink_href, '')
3482 if not href.startswith(tooltip_url):
3483 continue
3484 link.tag = '{%s}g' % svg_ns
3485 link.attrib.clear()
3486 link.set('class', 'matplotlib-simple-tooltip')
3487 title = ET.Element('{%s}title' % svg_ns)
3488 title.text = tooltip_text[int(href[len(tooltip_url):])]
3489 link.insert(0, title)
3490 # last, so that every point is in the document when it runs, and the box it
3491 # draws is on top of everything else
3492 ET.SubElement(svg_tree.getroot(), '{%s}script' % svg_ns, {'type': 'text/javascript'}).text = tooltip_script
3493 svg_buffer = io.BytesIO()
3494 svg_tree.write(svg_buffer, encoding = 'utf-8', xml_declaration = True)
3495 svg_bytes = svg_buffer.getvalue()
3496 PYTHON
3497 }
3498 # The one write of an SVG, finished above (see $target).
3499 485 ▶ print {$fh} <<'PYTHON' if ( defined $args->{output_file} ) && $tooltips_drawn;
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"output_file"} and $tooltips_drawn 452 33 485
Condition100%3/3
defined $args->{"output_file"} and $tooltips_drawn
!ll&&!rl&&r
726452
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
3500 with (gzip.open if output_file.lower().endswith('.svgz') else open)(output_file, 'wb') as svg:
3501 svg.write(svg_bytes)
3502 PYTHON
3503 485 ▶ 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 476 485
3504 485 ▶ say $fh 'plt.close()' if $args->{execute} == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"execute"} == 0 478 7 485
3505 485 ▶ if ( $args->{execute} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{'execute'}) { } 7 478 485
3506 7 my @python = python_command();
3507 7 ▶ if ( scalar @python == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @python == 0) 1 6 7
3508 die 'no Python 3 interpreter was found to run ' . $fh->filename
3509 1 . ': tried ' . join( ', ', map { '"' . join( ' ', @{$_} ) . '"' } @windows_python_candidates )
3510 . '. 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';
3511 }
3512 # What the script wrote to STDERR as it ran and succeeded: matplotlib's
3513 # warnings, which are the only word the caller gets that a figure was
3514 # written but is not what was asked for -- "Data has no positive
3515 # values, and therefore cannot be log-scaled", a font with no glyph for
3516 # a label, a deprecation. run_script captured them and returned them,
3517 # and they were dropped here, so only a script that failed ever showed
3518 # its STDERR. Printed as they came, to STDERR, and not with warn(),
3519 # which this file's fatal warnings would make a death after the figure
3520 # was written.
3521 6 my $stderr = run_script( [ @python, $fh->filename ] );
3522 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
3523 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
3524 } else { # not running yet
3525 478 ▶ 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"} 471 7 478
3526 }
3527 482 return $fh->filename;
3528 }
3529 16 ▶sub venn_proportional_area_helper {
Subroutine venn_proportional_area_helper: called CC=19 SCAR=29.9
Pod undocumented
3530 16 my ($args) = @_;
3531 16 my $current_sub = ( split( /::/, ( caller(0) )[3] ) )[-1]
3532 ; # https://stackoverflow.com/questions/2559792/how-can-i-get-the-name-of-the-current-subroutine-in-perl
3533 16 ▶ if ( ref $args ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args ne "HASH") 0 16 16
3534 0 die "args must be given as a hash ref, e.g. \"$current_sub({ data => \@blah })\"";
3535 }
3536 16 my @reqd_args = (
3537 'ax', # e.g. 0, 1, 2 ... the subplot index, passed in by plt
3538 'fh', # the File::Temp filehandle, passed in by plt
3539 'plot', # the per-plot args from the caller
3540 );
3541 16 my @undef_args = grep { !defined $args->{$_} } @reqd_args;
3542 16 ▶ if ( scalar @undef_args > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_args > 0) 0 16 16
3543 0 p @undef_args;
3544 0 die 'the above args are necessary, but were not defined.';
3545 }
3546 16 my @opt = (@ax_methods, @plt_methods, @fig_methods, @arg, 'ax', @{ $opt{$current_sub} });
3547 16 my $plot = $args->{plot};
3548 my @undef_opt = grep {
3549 106 my $key = $_;
3550 106 not grep { $_ eq $key } @opt
3551 16 } keys %{$plot};
3552 16 ▶ if ( scalar @undef_opt > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @undef_opt > 0) 0 16 16
3553 bad_keyword_error({
3554 bad => \@undef_opt,
3555 accepted => \@opt,
3556 preferred => $opt{$current_sub},
3557 type => $plot->{plot_type},
3558 0 sub => $current_sub
3559 });
3560 }
3561 # Each of these died as Perl's own error, or as a Python traceback, naming
3562 # no option: "Not a HASH reference" for array data, and below, "Can't use
3563 # string as an ARRAY ref" for a string "set_colors".
3564 16 ▶ if ( ref $plot->{data} ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"data"} ne "HASH") 1 15 16
3565 die "$current_sub takes a hash of sets, one array of members per set, e.g. { A => [1, 2], B => [2, 3] }, not "
3566 1 ▶ . ( ref $plot->{data} ? 'a ' . ref( $plot->{data} ) . ' reference' : 'a scalar' );
Branch: 1 branch
BranchTrueFalseTotal
ref $plot->{'data'} ? : 1 0 1
3567 }
3568 # matplotlib_venn only draws area-proportional diagrams for 2 or 3 sets
3569 15 my $n_keys = scalar keys %{ $plot->{data} };
3570 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
3571 2 p $plot->{data};
3572 2 die "$current_sub only takes 2 or 3 sets of data.";
3573 }
3574 13 foreach my $key ( keys %{ $plot->{data} } ) {
3575 25 ▶ if ( ref $plot->{data}{$key} ne 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $plot->{"data"}{$key} ne "ARRAY") 1 24 25
3576 1 p $plot->{data};
3577 1 die "\"$key\" must be an array reference in $current_sub";
3578 }
3579 24 ▶ if ( grep { !defined } @{ $plot->{data}{$key} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {not defined $_;} @{$$plot{"data"}{$key};}) 0 24 24
3580 0 p $plot->{data}{$key}, array_max => scalar @{ $plot->{data}{$key} };
3581 0 die "\"$key\" has undefined values in $current_sub, there may be undefined values in other keys";
3582 }
3583 }
3584 12 my @keys;
3585 12 ▶ if ( defined $plot->{key_order} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{'key_order'}) { } 5 7 12
3586 @keys = check_key_order({
3587 keys => $plot->{key_order},
3588 data => $plot->{data},
3589 5 option => 'key_order',
3590 sub => $current_sub
3591 });
3592 2 ▶ if ( scalar @keys != $n_keys ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @keys != $n_keys) 1 1 2
3593 1 p $plot;
3594 1 die "\"key_order\" has " . scalar(@keys) . " keys, but data has $n_keys in $current_sub";
3595 }
3596 } else {
3597 7 @keys = sort keys %{ $plot->{data} };
3598 }
3599 # The import is emitted at the point of use; a duplicate "from matplotlib_venn
3600 # import ..." across several subplots is harmless in Python.
3601 8 say { $args->{fh} } "from matplotlib_venn import venn$n_keys";
3602 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
3603 8 my @sets;
3604 8 foreach my $i ( 0 .. $#keys ) { # "each @array" requires perl 5.12
3605 16 my $key = $keys[$i];
3606 16 my $name = "venn_ax${ax}_set$i";
3607 16 say { $args->{fh} } "$name = set(["
3608 16 . py_list( @{ $plot->{data}{$key} } ) . '])';
3609 16 push @sets, $name;
3610 }
3611 8 my $opt = '';
3612 8 ▶ if ( defined $plot->{set_colors} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"set_colors"}) 3 5 8
3613 # One color per set, which matplotlib_venn reads by position; a list of
3614 # any other length was a TypeError from inside it.
3615 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
3616 2 die "\"set_colors\" is an array of one color per set in $current_sub, and there are $n_keys sets";
3617 }
3618 1 $opt .= ', set_colors=(' . py_list( @{ $plot->{set_colors} } ) . ')';
3619 }
3620 6 ▶ if ( defined $plot->{alpha} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $plot->{"alpha"}) 2 4 6
3621 2 check_numbers( [ $plot->{alpha} ], '"alpha"', $current_sub ); # written bare, so a word was a NameError
3622 1 $opt .= ", alpha=" . py_num( $plot->{alpha} );
3623 }
3624 5 say { $args->{fh} } "venn$n_keys(["
3625 . join( ',', @sets ) . '],('
3626 . py_list(@keys) . "), ax=ax$ax$opt)";
3627 }
3628 25 1;
« blib/lib/Matplotlib/Simple.pm ↑ Summary blib/lib/Matplotlib/Simple/Gnuplot.pm »