blib/lib/Stats/LikeR.pm

filter: Statementstmt 97.2% 3271 / 3363 Branchbran 86.8% 2117 / 2438 Conditioncond 78.6% 909 / 1156 MC/DCmcdc 64.2% 427 / 665 Subroutinesub 99.0% 203 / 205 Podpod 97.3% 36 / 37 totaltotal 88.5% 6963 / 7864 CC 1832 SCAR 39.1
CC
1832
Cov
91%
_agg_reduce_named
506.0
read_table
163.0
__ANON__
86.6
CRAP 49.8
↑ Summary LikeR.xs »
1 #!/usr/bin/env perl
2 # ABSTRACT: Get basic statistical functions, like in R, but with Perl using XS for performance
3 508 require 5.010001;
4 508 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 package Stats::LikeR;
6 508 our $VERSION = '0.3427'; # quoted: a bare version ending in 0, such as 0.320, is the number 0.32, which the dist would be named
7 508 require XSLoader;
8 508 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 508 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 508 ▶use Scalar::Util qw(reftype looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 508 XSLoader::load('Stats::LikeR', $VERSION);
12 508 our @EXPORT_OK = qw(h add_data age_standardize agg anova aoh2h aoh2hoa aoh2hoh aov assign auc auroc avals bedroc bfill binom_test cfilter chisq_test chunk col col2col colnames concat cmh_test cor cor_test cov csort density df2h dftype bw_nrd0 bw_nrd bw_ucv bw_bcv bw_sj dnorm cohen_d cramers_v eta_squared drop_cols drop_duplicates dropna epi_2x2 ffill fillna filter fisher_test get_union glm group_by h2aoh hoa2aoh hoa2hoh hoh2hoa hist interpolate intersection is_equivalent kruskal_test ks_test kurtosis Lonly ljoin lm map_cell matrix max mean median melt merge min mode ncol nrow oneway_test p_adjust pivot_table pnorm pt qt pchisq qchisq pf qf pbinom qnorm power_t_test predict prop_test mcnemar_test friedman_test dunn_test prcomp ptukey qcut qtukey quantile rank roc Ronly rbind rbinom read_table rename_cols rnorm rownames runif sample scale sd select_cols seq shapiro_test skew smd sum summary survfit logrank_test coxph table_one t_test transpose TukeyHSD uniq vals value_counts var var_test vif hosmer_lemeshow view wilcox_test write_table zerotrunc hurdle svyglm ivreg lmer);
13 508 our @EXPORT = @EXPORT_OK;
14  
15 # File operations: failure reporting
16 #
17 # Before 0.316 this file ran under `use autodie ':default';', which replaced
18 # open() and close() with versions that threw an autodie::exception the moment
19 # either failed. 0.316 drops the dependency; _open_read() and _close() take its
20 # place, raising the same failure at the same points with the same text, so a
21 # caller's eval sees the message it has always seen. The one visible difference
22 # is that $@ is now a plain string rather than an autodie::exception object,
23 # which nothing in the module, the tests or the documentation ever inspected.
24 #
25 # The wording is autodie::exception 2.37's: _format_open() (through
26 # _FORMAT_OPEN and _format_open_with_mode()) for the open, _format_close() for
27 # the close, each followed by add_file_and_line(). That last method is where the
28 # trailing newline comes from, and it is also what stops perl appending a second,
29 # differently punctuated " at ... line ..." of its own.
30  
31 # autodie reported the caller's file and line, not its own, so build the message
32 # one frame up.
33 0 ▶sub _io_die {
Subroutine _io_die: not called CC=1 SCAR=6.9
34 0 my ($msg) = @_;
35 0 my (undef, $file, $line) = caller(1);
36 0 die sprintf("%s at %s line %d\n", $msg, $file, $line);
37 }
38  
39 14130 ▶sub _open_read {
Subroutine _open_read: called CC=2 SCAR=7.0
40 14130 my ($file) = @_;
41 14130 my $fh;
42 14130 ▶ open $fh, '<', $file
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<", $file or _io_die("Can't open '${file}' for reading: '$!'") 14130 0 14130
43 or _io_die("Can't open '$file' for reading: '$!'");
44 14130 return $fh;
45 }
46  
47 14500 ▶sub _close {
Subroutine _close: called CC=2 SCAR=7.1
48 14500 my ($fh) = @_;
49 14500 ▶ close $fh or _io_die("Can't close($fh) filehandle: '$!'");
Branch: 1 branch
BranchTrueFalseTotal
close $fh or _io_die("Can't close($fh) filehandle: '$!'") 14500 0 14500
50 14500 return;
51 }
52  
53 # Help
54 #
55 # h() is the way in, and it works for every function in the distribution, XS
56 # and pure Perl alike, because it looks the name up rather than watching an
57 # argument list:
58 #
59 # h('agg'); h(*agg); h(\&agg); h();
60 #
61 # It prints that function's own section of the documentation -- the same text
62 # as the matching heading in README.md -- to STDOUT, and returns.
63 #
64 # h() is the only way in. No function reads its own arguments for a help flag:
65 # a bare 'h' or '?' cannot be told apart from a column, file or option value
66 # that really is that string, and one help route that works everywhere beats
67 # two that behave differently depending on whether the callee is XS or Perl.
68 #
69 # The help text is not duplicated in the source. It is rendered from this
70 # file's own POD at run time (that POD is generated from README.md by
71 # md2pod.pl), so the help can never drift out of sync with the shipped
72 # documentation. Functions without a documentation section of their own fall
73 # back to listing every topic that does have one.
74  
75 # Functions that share another function's section, either because they are the
76 # very same subroutine under a second name (rbind/concat) or because they are
77 # the internal engine behind a documented front end.
78 508 my %HELP_ALIAS = (
79 rbind => 'concat',
80 bw_nrd0 => 'density',
81 bw_nrd => 'density',
82 bw_ucv => 'density',
83 bw_bcv => 'density',
84 bw_sj => 'density',
85 map_cell => 'assign',
86 _hoa_assign => 'assign',
87 col => 'filter',
88 _rename_inplace => 'rename_cols',
89 aoh2h => 'df2h',
90 _df2h => 'df2h',
91 _cols_select => 'select_cols',
92 _cols_drop => 'drop_cols',
93 _cols_rename => 'rename_cols',
94 _drop_dups_core => 'drop_duplicates',
95 _aoh_key_union => 'drop_duplicates',
96 _qcut_core => 'qcut',
97 _interp_column_xs => 'interpolate',
98 _parse_csv_file => 'read_table',
99 _impute_prop => 'fillna',
100 _render_grid => 'view',
101 _view_size => 'view',
102 _view_size_fmt => 'view',
103 _df_shape => 'agg',
104 _agg_combine => 'agg',
105 _agg_mode => 'agg',
106 _pivot_split => 'pivot_table',
107 _group_order => 'pivot_table',
108 _melt_xs => 'melt',
109 _impute_xs => 'fillna',
110 _numeric_cells => 'summary',
111 _t1_col => 'table_one',
112 _aoh2hoh_xs => 'aoh2hoh',
113 _dropna_xs => 'dropna',
114 _xtab => 'cramers_v',
115 # The eight R distribution functions share one section, since what is
116 # worth saying about tails, log_p and accuracy is the same for all of
117 # them; pnorm and dnorm keep their own, older sections.
118 qnorm => 'Distribution functions',
119 pt => 'Distribution functions',
120 qt => 'Distribution functions',
121 pchisq => 'Distribution functions',
122 qchisq => 'Distribution functions',
123 pf => 'Distribution functions',
124 qf => 'Distribution functions',
125 pbinom => 'Distribution functions',
126 );
127  
128 # _help_show($name) -- print $name's documentation to STDOUT. Returns the
129 # name it showed.
130 148 ▶sub _help_show {
Subroutine _help_show: called CC=2 SCAR=7.0
131 148 my ($name) = @_;
132 148 ▶ $name = defined($name) ? $name : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 148 0 148
133 148 $name =~ s/\A.*:://; # accept Stats::LikeR::agg
134 148 my $old = select STDOUT; local $| = 1; select $old;
135 148 print STDOUT _help_text($name);
136 148 return $name;
137 }
138  
139 # h() -- ask for documentation by name. It never dies over the name it is
140 # given (an undocumented one lists the documented ones instead), and it never
141 # stands in the way of a call: no function here reads its arguments for a help
142 # flag, so a column, file or option value really named 'h' is just data.
143 #
144 # h('bedroc'); # by name
145 # h(*bedroc); # by name, unquoted
146 # h(\&bedroc); # by reference
147 # h(); # the general help, and the list of topics
148 #
149 # h(bedroc), with no quotes and no sigil, cannot be made to work: every
150 # function here is exported, so Perl parses the bareword as a call to bedroc()
151 # before h() is ever reached. Use one of the four forms above.
152 #
153 # Returns the name whose documentation was shown.
154 150 ▶sub h {
Subroutine h: called CC=10 SCAR=23.0
Pod documented
155 150 my ($what) = @_;
156 150 my $name;
157  
158 150 ▶ if (!@_ || !defined $what) { # h() -- the general help
Branch: 4 branches
BranchTrueFalseTotal
if (not @_ && defined $what) { } 2 148 150
elsif (ref \$what eq 'GLOB') { } 4 144 148
elsif (ref $what eq 'CODE') { } 5 139 144
elsif (ref $what) { } 1 138 139
Condition100%3/3
@_ && defined $what
!ll&&!rl&&r
11148
MC/DC100%2/2
@_ && defined $what
@_ defined $what
Truth table100%3/3
A && B
A= @_B= defined $what
ABresult
0X0
100
111
159 2 $name = '';
160 }
161 elsif (ref \$what eq 'GLOB') { # h(*bedroc)
162 4 ($name = "$what") =~ s/\A\*//;
163 }
164 elsif (ref $what eq 'CODE') { # h(\&bedroc)
165 508 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
166 5 for my $cand (@EXPORT_OK) {
167 400 my $slot = *{"Stats::LikeR::$cand"}{CODE};
168 400 ▶ next unless $slot && $slot == $what;
Branch: 1 branch
BranchTrueFalseTotal
unless $slot and $slot == $what 396 4 400
Condition66%2/3
$slot and $slot == $what
!ll&&!rl&&r
03964
MC/DC50%1/2
$slot and $slot == $what
$slot $slot == $what
Truth table66%2/3
A and B
A= $slotB= $slot == $what
ABresult
0X0
100
111
169 4 $name = $cand;
170 4 last;
171 }
172 5 ▶ die "h: that code reference is not a Stats::LikeR function\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 1 4 5
173 unless defined $name;
174 }
175 elsif (ref $what) {
176 1 die 'h: expected a function name, a glob or a code reference, not a '
177 . ref($what) . " reference\n";
178 }
179 else { # h('bedroc'), h($name)
180 138 $name = $what;
181 138 $name =~ s/\A&//; # h('&bedroc')
182 }
183  
184 148 $name =~ s/\A.*:://; # h('Stats::LikeR::bedroc')
185 148 $name =~ s/\A\s+//; $name =~ s/\s+\z//;
186 148 return _help_show($name);
187 }
188  
189 # terminal width to wrap to
190 148 ▶sub _help_width {
Subroutine _help_width: called CC=5 SCAR=16.6
191 148 my $w = $ENV{COLUMNS};
192 148 ▶ $w = 80 unless defined($w) && $w =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $w and $w =~ /\A[0-9]+\z/ 146 2 148
Condition66%2/3
defined $w and $w =~ /\A[0-9]+\z/
!ll&&!rl&&r
14602
MC/DC50%1/2
defined $w and $w =~ /\A[0-9]+\z/
defined $w $w =~ /\A[0-9]+\z/
Truth table66%2/3
A and B
A= defined $wB= $w =~ /\A[0-9]+\z/
ABresult
0X0
100
111
193 148 ▶ $w = 40 if $w < 40;
Branch: 1 branch
BranchTrueFalseTotal
if $w < 40 0 148 148
194 148 ▶ $w = 100 if $w > 100;
Branch: 1 branch
BranchTrueFalseTotal
if $w > 100 0 148 148
195 148 return $w;
196 }
197  
198 # display length of a UTF-8 byte string: count everything that is not a
199 # continuation byte. Keeps wrapping honest without pulling in Encode.
200 213104 ▶sub _help_len {
Subroutine _help_len: called CC=2 SCAR=6.9
201 213104 my $n = 0;
202 213104 ▶ $n++ while $_[0] =~ /[^\x80-\xbf]/g;
Branch: 1 branch
BranchTrueFalseTotal
$_[0] =~ /[^\x80-\xbf]/g and do { ++$n } 4198835 213104 4411939
203 213104 return $n;
204 }
205  
206 148 ▶sub _help_text {
Subroutine _help_text: called CC=10 SCAR=23.0
207 148 my ($name) = @_;
208 148 my $width = _help_width();
209 148 ▶ my $topic = exists $HELP_ALIAS{$name} ? $HELP_ALIAS{$name} : $name;
Branch: 1 branch
BranchTrueFalseTotal
exists $HELP_ALIAS{$name} ? : 12 136 148
210 148 ▶ my @sect = length($name) ? _pod_section($topic) : ();
Branch: 1 branch
BranchTrueFalseTotal
length $name ? : 146 2 148
211 148 ▶ my $body = @sect ? _pod_render(\@sect, $width)
Branch: 2 branches
BranchTrueFalseTotal
@sect ? : 145 3 148
length $name ? : 1 2 3
212 : length($name) ? _help_fallback($name, $width)
213 : _help_general($width);
214  
215 148 ▶ my $title = length($name) ? "Stats::LikeR::$name" : 'Stats::LikeR';
Branch: 1 branch
BranchTrueFalseTotal
length $name ? : 146 2 148
216 148 ▶ $title .= " (documented under \`$topic')" if $topic ne $name && @sect;
Branch: 1 branch
BranchTrueFalseTotal
if $topic ne $name and @sect 12 136 148
Condition66%2/3
$topic ne $name and @sect
!ll&&!rl&&r
136012
MC/DC50%1/2
$topic ne $name and @sect
$topic ne $name @sect
Truth table66%2/3
A and B
A= $topic ne $nameB= @sect
ABresult
0X0
100
111
217 148 my $rule = '=' x $width;
218  
219 148 ▶ return join('',
Branch: 2 branches
BranchTrueFalseTotal
$body =~ /\n\n\z/ ? : 3 145 148
length $name ? : 146 2 148
220 "\n", $rule, "\n", $title, "\n", $rule, "\n\n",
221 $body,
222 ($body =~ /\n\n\z/ ? '' : "\n"),
223 '-' x $width, "\n",
224 _pod_wrap(length($name)
225 ? "Call h('$name') for this page at any time; h(*$name) and "
226 . "h(\\&$name) are the same call, and h() lists every documented "
227 . 'function.'
228 : "Call h('name') for any one function's documentation -- "
229 . "h('agg'), h(*agg) and h(\\&agg) are the same call.",
230 $width, 1),
231 _pod_wrap("The full manual is `perldoc Stats::LikeR'.", $width, 1),
232 $rule, "\n\n",
233 );
234 }
235  
236 # Recognise a heading. Returns (level, text), or the empty list when the line
237 # is not one. Text carrying braces or a fat comma is a code comment that the
238 # markdown-to-POD generator mistook for a heading (README.md has a few inside
239 # indented examples); treating those as sections would cut a function's
240 # documentation short, so they are ignored here.
241 1965011 ▶sub _pod_heading {
Subroutine _pod_heading: called CC=4 SCAR=14.0
242 1965011 my ($line) = @_;
243 1965011 ▶ return () unless defined $line && $line =~ /^=head([1-6])[ \t]+(\S.*?)\s*\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line and $line =~ /^=head([1-6])[ \t]+(\S.*?)\s*\z/ 1929608 35403 1965011
Condition66%2/3
defined $line and $line =~ /^=head([1-6])[ \t]+(\S.*?)\s*\z/
!ll&&!rl&&r
0192960835403
MC/DC50%1/2
defined $line and $line =~ /^=head([1-6])[ \t]+(\S.*?)\s*\z/
defined $line $line =~ /^=head([1-6])[ \t]+(\S.*?)\s*\z/
Truth table66%2/3
A and B
A= defined $lineB= $line =~ /^=head([1-6])[ \t]+(\S.*?)\s*\z/
ABresult
0X0
100
111
244 35403 my ($level, $text) = ($1, $2);
245 35403 ▶ return () if $text =~ /[{};]|=>/;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /[{};]|=>/ 0 35403 35403
246 35403 return ($level, $text);
247 }
248  
249 # every =head2 in the Functions section, for the "nothing documented" path
250 3 ▶sub _pod_topics {
Subroutine _pod_topics: called CC=10 SCAR=23.0
251 3 my @t;
252 3 ▶ my $fh = _pod_open() or return @t;
Branch: 1 branch
BranchTrueFalseTotal
my $fh = _pod_open() or return @t 3 0 3
253 3 my $in = 0;
254 3 ▶ while (my $line = <$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 56856 3 56859
255 56856 my ($level, $text) = _pod_heading($line);
256 56856 ▶ next unless defined $level;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $level 55527 1329 56856
257 1329 ▶ if ($level == 1) { $in = ($text =~ /Functions/i) ? 1 : 0; next }
Branch: 2 branches
BranchTrueFalseTotal
if ($level == 1) 33 1296 1329
$text =~ /Functions/i ? : 3 30 33
258 1296 ▶ next unless $in && $level == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless $in and $level == 2 930 366 1296
Condition100%3/3
$in and $level == 2
!ll&&!rl&&r
6924366
MC/DC100%2/2
$in and $level == 2
$in $level == 2
Truth table100%3/3
A and B
A= $inB= $level == 2
ABresult
0X0
100
111
259 366 my $n = _pod_plain($text);
260 366 $n =~ s/\s*\(.*\z//s;
261 366 $n =~ s/\A\s+//; $n =~ s/\s+\z//;
262 # only names a caller can actually use; this also drops the one
263 # heading the POD generator mangled (_rename_inplace, a private
264 # helper, comes out as I<rename>inplace)
265 366 ▶ push @t, $n if length($n) && grep { $_ eq $n } @EXPORT_OK;
Branch: 1 branch
BranchTrueFalseTotal
if length $n and grep {$_ eq $n;} @Stats::LikeR::EXPORT_OK 360 6 366
Condition66%2/3
length $n and grep {$_ eq $n;} @Stats::LikeR::EXPORT_OK
!ll&&!rl&&r
06360
MC/DC50%1/2
length $n and grep {$_ eq $n;} @Stats::LikeR::EXPORT_OK
length $n grep {$_ eq $n;} @Stats::LikeR::EXPORT_OK
Truth table66%2/3
A and B
A= length $nB= grep {$_ eq $n;} @Stats::LikeR::EXPORT_OK
ABresult
0X0
100
111
266 }
267 3 _close($fh);
268 3 return @t;
269 }
270  
271 # the documented function names, in aligned columns
272 3 ▶sub _help_topic_block {
Subroutine _help_topic_block: called CC=6 SCAR=17.9
273 3 my ($width) = @_;
274 3 my @topics = _pod_topics();
275 3 ▶ return '' unless @topics;
Branch: 1 branch
BranchTrueFalseTotal
unless @topics 0 3 3
276  
277 3 my $col = 0;
278 3 ▶ $col = _help_len($_) > $col ? _help_len($_) : $col for @topics;
Branch: 1 branch
BranchTrueFalseTotal
_help_len($_) > $col ? : 6 354 360
279 3 $col += 2;
280 3 ▶ my $per = int(($width - 2) / $col) || 1;
Condition50%1/2
int(($width - 2) / $col) || 1
l!l
30
MC/DC0%0/1
int(($width - 2) / $col) || 1
int(($width - 2) / $col)
Truth table50%1/2
A
A= int(($width - 2) / $col)
Aresult
11
00
281 3 my $out = '';
282 3 my $i = 0;
283 3 ▶ while ($i < @topics) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @topics) 90 3 93
284 90 my @row = grep { defined } @topics[$i .. $i + $per - 1];
285 90 my $line = ' ' . join('', map { $_ . ' ' x ($col - _help_len($_)) } @row);
286 90 $line =~ s/\s+\z//;
287 90 $out .= $line . "\n";
288 90 $i += $per;
289 }
290 3 return $out;
291 }
292  
293 1 ▶sub _help_fallback {
Subroutine _help_fallback: called CC=4 SCAR=14.9
294 1 my ($name, $width) = @_;
295 1 my $list = _help_topic_block($width);
296 1 ▶ my $out = _pod_wrap("There is no documentation section for "
Branch: 2 branches
BranchTrueFalseTotal
length $name ? : 1 0 1
length $list ? : 1 0 1
297 . (length($name) ? "`$name'" : 'that name')
298 . '.'
299 . (length($list) ? ' These functions have one, and h()'
300 . ' will show any of them:' : ''),
301 $width, 1);
302 1 ▶ return length($list) ? $out . "\n" . $list . "\n" : $out;
Branch: 1 branch
BranchTrueFalseTotal
length $list ? : 1 0 1
303 }
304  
305 # h() with nothing to look up: how to ask, then every topic.
306 #
307 # README.md's own "Getting help" section is used when the POD has been
308 # regenerated from it (md2pod.pl); until then the short version below stands in,
309 # so h() is never empty.
310 2 ▶sub _help_general {
Subroutine _help_general: called CC=3 SCAR=11.3
311 2 my ($width) = @_;
312 2 my @sect = _pod_section('Getting help', 1);
313 2 my $out;
314 2 ▶ if (@sect) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sect) { } 2 0 2
315 2 $out = _pod_render(\@sect, $width);
316 }
317 else {
318 0 $out = _pod_wrap('Ask for a function by name, and its section of the '
319 . 'documentation is printed here:', $width, 1)
320 . "\n"
321 . " h('quantile'); # by name\n"
322 . " h(*quantile); # by name, unquoted\n"
323 . " h(\\&quantile); # by reference\n"
324 . "\n"
325 . _pod_wrap('h() is the only way to ask: no function reads its own '
326 . 'arguments for a help flag, so a column, file or option '
327 . "value really named 'h' is just data.", $width, 1);
328 }
329 2 my $list = _help_topic_block($width);
330 2 ▶ if (length $list) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $list) 2 0 2
331 2 $out .= "\n" . _pod_wrap('Documented functions, each of which h() will '
332 . 'show in full:', $width, 1) . "\n" . $list . "\n";
333 }
334 2 return $out;
335 }
336  
337 # POD extraction
338  
339 508 our $POD_FILE; # set only by t/help.t, to read a fixture
340  
341 156 ▶sub _pod_open {
Subroutine _pod_open: called CC=6 SCAR=20.7
342 156 ▶ my $file = defined($POD_FILE) ? $POD_FILE : __FILE__;
Branch: 1 branch
BranchTrueFalseTotal
defined $Stats::LikeR::POD_FILE ? : 1 155 156
343 156 ▶ $file = $INC{'Stats/LikeR.pm'} unless defined($file) && -r $file;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file and -r $file 0 156 156
Condition33%1/3
defined $file and -r $file
!ll&&!rl&&r
00156
MC/DC0%0/2
defined $file and -r $file
defined $file -r $file
Truth table33%1/3
A and B
A= defined $fileB= -r $file
ABresult
0X0
100
111
344 156 ▶ return undef unless defined($file) && -r $file;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file and -r $file 0 156 156
Condition33%1/3
defined $file and -r $file
!ll&&!rl&&r
00156
MC/DC0%0/2
defined $file and -r $file
defined $file -r $file
Truth table33%1/3
A and B
A= defined $fileB= -r $file
ABresult
0X0
100
111
345 156 return _open_read($file);
346 }
347  
348 # Reduce a heading or a function name to a comparison key. Dropping every
349 # non-alphanumeric makes the match immune to a signature in the heading
350 # (`hoa2hoh( \%hoa, $key )'), to C<> wrapping (`C<aoh2hoh>') and to POD
351 # generated from markdown that read an underscore as italics
352 # (`I<rename>inplace' for `_rename_inplace').
353 9156 ▶sub _pod_key {
Subroutine _pod_key: called CC=2 SCAR=7.0
354 9156 my ($s) = @_;
355 9156 ▶ return '' unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 9156 9156
356 9156 $s =~ s/\s*\(.*\z//s;
357 9156 $s = _pod_plain($s);
358 9156 $s =~ s/[^A-Za-z0-9]+//g;
359 9156 return lc $s;
360 }
361  
362 # the raw POD lines of the section headed $name, its subsections included.
363 # $want is the heading level to match, 2 (a function) unless asked otherwise.
364 153 ▶sub _pod_section {
Subroutine _pod_section: called CC=13 SCAR=25.7
365 153 my ($name, $want) = @_;
366 153 ▶ $want = 2 unless defined $want;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $want 151 2 153
367 153 my $key = _pod_key($name);
368 153 ▶ return () unless length $key;
Branch: 1 branch
BranchTrueFalseTotal
unless length $key 0 153 153
369 153 ▶ my $fh = _pod_open() or return ();
Branch: 1 branch
BranchTrueFalseTotal
my $fh = _pod_open() or return () 153 0 153
370 153 my (@out, $in);
371 153 ▶ while (my $line = <$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 1908155 2 1908157
372 1908155 my ($level, $title) = _pod_heading($line);
373 1908155 ▶ if (defined $level && $level <= $want) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $level and $level <= $want) 9917 1898238 1908155
Condition100%3/3
defined $level and $level <= $want
!ll&&!rl&&r
1874081241579917
MC/DC100%2/2
defined $level and $level <= $want
defined $level $level <= $want
Truth table100%3/3
A and B
A= defined $levelB= $level <= $want
ABresult
0X0
100
111
374 9917 ▶ if ($level == $want && _pod_key($title) eq $key) {
Branch: 1 branch
BranchTrueFalseTotal
if ($level == $want and _pod_key($title) eq $key) 151 9766 9917
Condition100%3/3
$level == $want and _pod_key($title) eq $key
!ll&&!rl&&r
9148852151
MC/DC100%2/2
$level == $want and _pod_key($title) eq $key
$level == $want _pod_key($title) eq $key
Truth table100%3/3
A and B
A= $level == $wantB= _pod_key($title) eq $key
ABresult
0X0
100
111
375 151 $in = 1;
376 151 push @out, $line;
377 151 next;
378 }
379 9766 ▶ last if $in;
Branch: 1 branch
BranchTrueFalseTotal
if $in 150 9616 9766
380 9616 next;
381 }
382 1898238 ▶ last if $in && $line =~ /^=cut\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $in and $line =~ /^=cut\s*$/ 1 1898237 1898238
Condition100%3/3
$in and $line =~ /^=cut\s*$/
!ll&&!rl&&r
1880524177131
MC/DC100%2/2
$in and $line =~ /^=cut\s*$/
$in $line =~ /^=cut\s*$/
Truth table100%3/3
A and B
A= $inB= $line =~ /^=cut\s*$/
ABresult
0X0
100
111
383 1898237 ▶ push @out, $line if $in;
Branch: 1 branch
BranchTrueFalseTotal
if $in 17713 1880524 1898237
384 }
385 153 _close($fh);
386 153 return @out;
387 }
388  
389 # POD -> plain text
390  
391 508 my %POD_ENTITY = (
392 lt => '<', gt => '>', 'verbar' => '|', sol => '/', amp => '&',
393 quot => '"', apos => "'", lchevron => '<<', rchevron => '>>',
394 nbsp => ' ', ndash => '-', mdash => '--', 'eacute' => 'e',
395 );
396  
397 8558 ▶sub _pod_seq {
Subroutine _pod_seq: called CC=10 SCAR=28.7
398 8558 my ($code, $text) = @_;
399 8558 ▶ if ($code eq 'E') {
Branch: 1 branch
BranchTrueFalseTotal
if ($code eq "E") 753 7805 8558
400 753 ▶ return $POD_ENTITY{$text} if exists $POD_ENTITY{$text};
Branch: 1 branch
BranchTrueFalseTotal
if exists $POD_ENTITY{$text} 753 0 753
401 0 ▶ return chr(hex $1) if $text =~ /\A0?[xX]([0-9a-fA-F]+)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /\A0?[xX]([0-9a-fA-F]+)\z/ 0 0 0
402 0 ▶ return chr($text) if $text =~ /\A[0-9]+\z/ && $text < 128;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /\A[0-9]+\z/ and $text < 128 0 0 0
Condition0%0/3
$text =~ /\A[0-9]+\z/ and $text < 128
!ll&&!rl&&r
000
MC/DC0%0/2
$text =~ /\A[0-9]+\z/ and $text < 128
$text =~ /\A[0-9]+\z/ $text < 128
Truth table0%0/3
A and B
A= $text =~ /\A[0-9]+\z/B= $text < 128
ABresult
0X0
100
111
403 0 return $text;
404 }
405 7805 ▶ if ($code eq 'L') { # L<text|target>, L<target>, L<#anchor>
Branch: 1 branch
BranchTrueFalseTotal
if ($code eq "L") 116 7689 7805
406 116 ▶ $text =~ s/\|.*\z//s if $text =~ /\|/;
Branch: 1 branch
BranchTrueFalseTotal
if $text =~ /\|/ 84 32 116
407 116 $text =~ s{\A/?#}{};
408 116 $text =~ s{\A/}{};
409 116 return $text;
410 }
411 7689 ▶ return '' if $code eq 'X' || $code eq 'Z';
Branch: 1 branch
BranchTrueFalseTotal
if $code eq "X" or $code eq "Z" 0 7689 7689
Condition33%1/3
$code eq "X" or $code eq "Z"
l!l&&r!l&&!r
007689
MC/DC0%0/2
$code eq "X" or $code eq "Z"
$code eq "X" $code eq "Z"
Truth table33%1/3
A or B
A= $code eq "X"B= $code eq "Z"
ABresult
1X1
011
000
412 7689 return $text; # B, C, I, F, S and anything else
413 }
414  
415 # strip POD formatting codes, innermost first, doubled delimiters included
416 14898 ▶sub _pod_plain {
Subroutine _pod_plain: called CC=4 SCAR=13.9
417 14898 my ($s) = @_;
418 14898 ▶ return '' unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 14898 14898
419 14898 for (1 .. 24) {
420 16904 my $before = $s;
421 16904 $s =~ s/([A-Z])<<+[ \t\n]+(.*?)[ \t\n]+>>+/_pod_seq($1, $2)/ges;
422 16904 $s =~ s/([A-Z])<([^<>]*)>/_pod_seq($1, $2)/ge;
423 16904 ▶ last if $s eq $before;
Branch: 1 branch
BranchTrueFalseTotal
if $s eq $before 14898 2006 16904
424 }
425 14898 return $s;
426 }
427  
428 2316 ▶sub _pod_wrap {
Subroutine _pod_wrap: called CC=6 SCAR=17.9
429 2316 my ($text, $width, $indent, $lead) = @_;
430 2316 ▶ $lead = '' unless defined $lead;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lead 1706 610 2316
431 2316 my $pad = ' ' x $indent;
432 2316 my $first = $pad . $lead;
433 2316 my $cont = $pad . (' ' x _help_len($lead));
434 2316 my $limit = $width;
435 2316 my $floor = _help_len($first) + 20;
436 2316 ▶ $limit = $floor if $limit < $floor;
Branch: 1 branch
BranchTrueFalseTotal
if $limit < $floor 0 2316 2316
437  
438 2316 my @words = grep { length } split /\s+/, $text;
439 2316 ▶ return "" unless @words;
Branch: 1 branch
BranchTrueFalseTotal
unless @words 0 2316 2316
440 2316 my $out = '';
441 2316 my $line = $first . shift @words;
442 2316 for my $w (@words) {
443 83233 ▶ if (_help_len($line) + 1 + _help_len($w) > $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (_help_len($line) + 1 + _help_len($w) > $limit) { } 5033 78200 83233
444 5033 $out .= $line . "\n";
445 5033 $line = $cont . $w;
446 } else {
447 78200 $line .= ' ' . $w;
448 }
449 }
450 2316 return $out . $line . "\n";
451 }
452  
453 # Split POD lines into typed blocks: command paragraphs, verbatim paragraphs,
454 # ordinary paragraphs and =begin/=end data blocks.
455 147 ▶sub _pod_blocks {
Subroutine _pod_blocks: called CC=29 SCAR=36.1
456 147 my ($lines) = @_;
457 147 my (@blocks, $i);
458 147 my $n = scalar @$lines;
459 147 ▶ for ($i = 0; $i < $n; ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $n) 7295 147 7442
460 7295 my $line = $lines->[$i];
461 7295 ▶ if ($line =~ /^\s*$/) { $i++; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^\s*$/) 3647 3648 7295
462 3648 ▶ if ($line =~ /^=begin\s+(\S+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^=begin\s+(\S+)/) 0 3648 3648
463 0 my $fmt = lc $1;
464 0 $i++;
465 0 my @buf;
466 0 ▶ push @buf, $lines->[$i++] while $i < $n && $lines->[$i] !~ /^=end\b/;
Branch: 1 branch
BranchTrueFalseTotal
$i < $n and not $lines->[$i] =~ /^=end\b/ and do { push @buf, $$lines[$i++] } 0 0 0
Condition0%0/3
$i < $n and not $lines->[$i] =~ /^=end\b/
!ll&&!rl&&r
000
MC/DC0%0/2
$i < $n and not $lines->[$i] =~ /^=end\b/
$i < $n not $lines->[$i] =~ /^=end\b/
Truth table0%0/3
A and not(B)
A= $i < $nB= not $lines->[$i] =~ /^=end\b/
ABresult
0X0
100
111
467 0 ▶ $i++ if $i < $n;
Branch: 1 branch
BranchTrueFalseTotal
if $i < $n 0 0 0
468 0 push @blocks, { type => 'data', fmt => $fmt, lines => \@buf };
469 0 next;
470 }
471 # Pod::Weaver rewrites every "=begin FMT ... =end FMT" into a single
472 # "=for FMT ..." paragraph when the distribution is built, so the
473 # shipped copy of this file carries the tables in that spelling. Both
474 # mean the same thing -- the rest of the paragraph is data for FMT --
475 # and the help has to read the tables either way.
476 3648 ▶ if ($line =~ /^=for[ \t]+(\S+)[ \t]*(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^=for[ \t]+(\S+)[ \t]*(.*)$/) 143 3505 3648
477 143 my ($fmt, $first) = (lc $1, $2);
478 143 $i++;
479 143 ▶ my @buf = length($first) ? ($first . "\n") : ();
Branch: 1 branch
BranchTrueFalseTotal
length $first ? : 143 0 143
480 143 ▶ push @buf, $lines->[$i++]
Branch: 1 branch
BranchTrueFalseTotal
$i < $n and not $lines->[$i] =~ /^\s*$/ and not $lines->[$i] =~ /^=/ and do { push @buf, $$lines[$i++] } 4174 143 4317
Condition66%4/6
$i < $n and not $lines->[$i] =~ /^\s*$/ and not $lines->[$i] =~ /^=/
!ll&&!rl&&r
14304174
$i < $n and not $lines->[$i] =~ /^\s*$/
!ll&&!rl&&r
01434174
MC/DC33%1/3
$i < $n and not $lines->[$i] =~ /^\s*$/ and not $lines->[$i] =~ /^=/
$i < $n not $lines->[$i] =~ /^\s*$/ not $lines->[$i] =~ /^=/
Truth table50%2/4
A and not(B) and not(C)
A= $i < $nB= not $lines->[$i] =~ /^\s*$/C= not $lines->[$i] =~ /^=/
ABCresult
0XX0
10X0
1100
1111
481 while $i < $n && $lines->[$i] !~ /^\s*$/ && $lines->[$i] !~ /^=/;
482 143 push @blocks, { type => 'data', fmt => $fmt, lines => \@buf };
483 143 next;
484 }
485 3505 ▶ if ($line =~ /^=/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^=/) 1487 2018 3505
486 1487 my @buf = ($line);
487 1487 $i++;
488 1487 ▶ push @buf, $lines->[$i++]
Branch: 1 branch
BranchTrueFalseTotal
$i < $n and not $lines->[$i] =~ /^\s*$/ and not $lines->[$i] =~ /^=/ and do { push @buf, $$lines[$i++] } 871 1487 2358
Condition66%4/6
$i < $n and not $lines->[$i] =~ /^\s*$/ and not $lines->[$i] =~ /^=/
!ll&&!rl&&r
14870871
$i < $n and not $lines->[$i] =~ /^\s*$/
!ll&&!rl&&r
01487871
MC/DC33%1/3
$i < $n and not $lines->[$i] =~ /^\s*$/ and not $lines->[$i] =~ /^=/
$i < $n not $lines->[$i] =~ /^\s*$/ not $lines->[$i] =~ /^=/
Truth table50%2/4
A and not(B) and not(C)
A= $i < $nB= not $lines->[$i] =~ /^\s*$/C= not $lines->[$i] =~ /^=/
ABCresult
0XX0
10X0
1100
1111
489 while $i < $n && $lines->[$i] !~ /^\s*$/ && $lines->[$i] !~ /^=/;
490 1487 push @blocks, { type => 'cmd', lines => \@buf };
491 1487 next;
492 }
493 2018 ▶ if ($line =~ /^[ \t]/) { # verbatim
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^[ \t]/) 617 1401 2018
494 617 my @buf;
495 617 ▶ while ($i < $n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $n) 3393 0 3393
496 3393 my $s = $lines->[$i];
497 3393 ▶ if ($s =~ /^\s*$/) { # keep interior blank lines
Branch: 1 branch
BranchTrueFalseTotal
if ($s =~ /^\s*$/) 811 2582 3393
498 811 my $j = $i;
499 811 ▶ $j++ while $j < $n && $lines->[$j] =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
$j < $n and $lines->[$j] =~ /^\s*$/ and do { ++$j } 811 811 1622
Condition100%3/3
$j < $n and $lines->[$j] =~ /^\s*$/
!ll&&!rl&&r
13798811
MC/DC100%2/2
$j < $n and $lines->[$j] =~ /^\s*$/
$j < $n $lines->[$j] =~ /^\s*$/
Truth table100%3/3
A and B
A= $j < $nB= $lines->[$j] =~ /^\s*$/
ABresult
0X0
100
111
500 811 ▶ last if $j >= $n || $lines->[$j] !~ /^[ \t]/;
Branch: 1 branch
BranchTrueFalseTotal
if $j >= $n or not $lines->[$j] =~ /^[ \t]/ 616 195 811
Condition100%3/3
$j >= $n or not $lines->[$j] =~ /^[ \t]/
l!l&&r!l&&!r
13603195
MC/DC100%2/2
$j >= $n or not $lines->[$j] =~ /^[ \t]/
$j >= $n not $lines->[$j] =~ /^[ \t]/
Truth table100%3/3
A or not(B)
A= $j >= $nB= not $lines->[$j] =~ /^[ \t]/
ABresult
1X1
011
000
501 195 push @buf, "\n" for $i .. $j - 1;
502 195 $i = $j;
503 195 next;
504 }
505 2582 ▶ last if $s =~ /^=/ || $s !~ /^[ \t]/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /^=/ or not $s =~ /^[ \t]/ 1 2581 2582
Condition66%2/3
$s =~ /^=/ or not $s =~ /^[ \t]/
l!l&&r!l&&!r
012581
MC/DC50%1/2
$s =~ /^=/ or not $s =~ /^[ \t]/
$s =~ /^=/ not $s =~ /^[ \t]/
Truth table66%2/3
A or not(B)
A= $s =~ /^=/B= not $s =~ /^[ \t]/
ABresult
1X1
011
000
506 2581 push @buf, $s;
507 2581 $i++;
508 }
509 617 push @blocks, { type => 'verb', lines => \@buf };
510 617 next;
511 }
512 1401 my @buf; # ordinary paragraph
513 1401 ▶ push @buf, $lines->[$i++]
Branch: 1 branch
BranchTrueFalseTotal
$i < $n and not $lines->[$i] =~ /^\s*$/ and not $lines->[$i] =~ /^=/ and do { push @buf, $$lines[$i++] } 4326 1401 5727
Condition66%4/6
$i < $n and not $lines->[$i] =~ /^\s*$/ and not $lines->[$i] =~ /^=/
!ll&&!rl&&r
140104326
$i < $n and not $lines->[$i] =~ /^\s*$/
!ll&&!rl&&r
014014326
MC/DC33%1/3
$i < $n and not $lines->[$i] =~ /^\s*$/ and not $lines->[$i] =~ /^=/
$i < $n not $lines->[$i] =~ /^\s*$/ not $lines->[$i] =~ /^=/
Truth table50%2/4
A and not(B) and not(C)
A= $i < $nB= not $lines->[$i] =~ /^\s*$/C= not $lines->[$i] =~ /^=/
ABCresult
0XX0
10X0
1100
1111
514 while $i < $n && $lines->[$i] !~ /^\s*$/ && $lines->[$i] !~ /^=/;
515 1401 push @blocks, { type => 'text', lines => \@buf };
516 }
517 147 return @blocks;
518 }
519  
520 147 ▶sub _pod_render {
Subroutine _pod_render: called CC=27 SCAR=33.3
521 147 my ($lines, $width) = @_;
522 147 my @out;
523 147 my @indent = (1); # =over stack; 1 = one space of margin
524  
525 147 for my $b (_pod_blocks($lines)) {
526 3648 ▶ if ($b->{type} eq 'verb') {
Branch: 1 branch
BranchTrueFalseTotal
if ($b->{"type"} eq "verb") 617 3031 3648
527 # A markdown blockquote arrives here as verbatim text, but it is
528 # prose and reads far better wrapped than left at its source
529 # width, so pull those out and treat them as a paragraph.
530 617 my @body = grep { /\S/ } @{ $b->{lines} };
531 617 ▶ if (@body && !grep { !/^\s*>/ } @body) {
Branch: 1 branch
BranchTrueFalseTotal
if (@body and not grep({not /^\s*>/;} @body)) 6 611 617
Condition66%2/3
@body and not grep({not /^\s*>/;} @body)
!ll&&!rl&&r
06116
MC/DC50%1/2
@body and not grep({not /^\s*>/;} @body)
@body not grep({not /^\s*>/;} @body)
Truth table66%2/3
A and not(B)
A= @bodyB= not grep({not /^\s*>/;} @body)
ABresult
0X0
100
111
532 6 s/^\s*>\s?// for @body;
533 6 push @out, "\n", _pod_wrap(_pod_plain(join ' ', @body),
534 $width, $indent[-1] + 2);
535 6 next;
536 }
537 611 push @out, "\n";
538 611 my $pad = ' ' x $indent[-1];
539 # Formatting codes are not supposed to appear in a verbatim
540 # block, but the generated POD does leave a few behind; expand
541 # them rather than showing C<...> to the reader.
542 611 for my $v (@{ $b->{lines} }) {
543 2746 my $s = _pod_plain($v);
544 2746 $s =~ s/\s+\z//;
545 2746 ▶ push @out, length($s) ? $pad . $s . "\n" : "\n";
Branch: 1 branch
BranchTrueFalseTotal
length $s ? : 2561 185 2746
546 }
547 611 next;
548 }
549 3031 ▶ if ($b->{type} eq 'text') {
Branch: 1 branch
BranchTrueFalseTotal
if ($b->{"type"} eq "text") 1401 1630 3031
550 1401 push @out, "\n", _pod_wrap(_pod_plain(join ' ', @{ $b->{lines} }),
551 $width, $indent[-1]);
552 1401 next;
553 }
554 1630 ▶ if ($b->{type} eq 'data') {
Branch: 1 branch
BranchTrueFalseTotal
if ($b->{"type"} eq "data") 143 1487 1630
555 143 ▶ next unless $b->{fmt} =~ /^(?:html|text)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $b->{"fmt"} =~ /^(?:html|text)$/ 0 143 143
556 143 push @out, _pod_data(join('', @{ $b->{lines} }), $b->{fmt},
557 143 $width, $indent[-1]);
558 143 next;
559 }
560  
561 # command paragraph
562 1487 my @l = @{ $b->{lines} };
563 1487 my $head = shift @l;
564 1487 ▶ $head =~ /^=(\w+)[ \t]*(.*)$/s or next;
Branch: 1 branch
BranchTrueFalseTotal
$head =~ /^=(\w+)[ \t]*(.*)$/s or next 1479 8 1487
565 1479 my ($cmd, $arg) = ($1, $2);
566 1479 $arg =~ s/\s+\z//;
567  
568 1479 ▶ if ($cmd =~ /^head([1-6])\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd =~ /^head([1-6])\z/) 613 866 1479
569 613 my $level = $1;
570 613 my $t = _pod_plain(join ' ', $arg, @l);
571 613 $t =~ s/\s+/ /g; $t =~ s/\A\s+//; $t =~ s/\s+\z//;
572 613 ▶ next unless length $t;
Branch: 1 branch
BranchTrueFalseTotal
unless length $t 0 613 613
573 613 push @out, "\n";
574 613 ▶ if ($level <= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($level <= 2) { } 147 466 613
575 147 push @out, uc($t) . "\n";
576 } else {
577 466 push @out, $t . "\n", ('-' x _help_len($t)) . "\n";
578 }
579 613 next;
580 }
581 866 ▶ if ($cmd eq 'over') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd eq "over") 128 738 866
582 128 ▶ my $by = ($arg =~ /([0-9]+)/) ? $1 : 4;
Branch: 1 branch
BranchTrueFalseTotal
$arg =~ /([0-9]+)/ ? : 0 128 128
583 128 ▶ $by = 2 if $by < 2;
Branch: 1 branch
BranchTrueFalseTotal
if $by < 2 0 128 128
584 128 ▶ $by = 8 if $by > 8;
Branch: 1 branch
BranchTrueFalseTotal
if $by > 8 0 128 128
585 128 push @indent, $indent[-1] + $by;
586 128 next;
587 }
588 738 ▶ if ($cmd eq 'back') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd eq "back") 128 610 738
589 128 ▶ pop @indent if @indent > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @indent > 1 128 0 128
590 128 next;
591 }
592 610 ▶ if ($cmd eq 'item') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cmd eq "item") 610 0 610
593 610 my $bullet = '*';
594 610 ▶ if ($arg =~ s/\A\*\s*//) { $bullet = '*' }
Branch: 2 branches
BranchTrueFalseTotal
if ($arg =~ s/\A\*\s*//) { } 598 12 610
elsif ($arg =~ s/\A([0-9]+\.?)(?:\s+|\z)//) { } 12 0 12
595 elsif ($arg =~ s/\A([0-9]+\.?)(?:\s+|\z)//) {
596 12 $bullet = $1; # numbered list: "1." or "1"
597 12 ▶ $bullet .= '.' unless $bullet =~ /\.\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $bullet =~ /\.\z/ 0 12 12
598 }
599 610 my $t = _pod_plain(join ' ', $arg, @l);
600 610 ▶ my $ind = $indent[-1] > 2 ? $indent[-1] - 2 : $indent[-1];
Branch: 1 branch
BranchTrueFalseTotal
$indent[-1] > 2 ? : 610 0 610
601 610 push @out, "\n";
602 610 ▶ if ($t =~ /\S/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($t =~ /\S/) { } 610 0 610
603 610 push @out, _pod_wrap($t, $width, $ind, "$bullet ");
604 } else {
605 0 push @out, (' ' x $ind) . $bullet . "\n";
606 }
607 610 next;
608 }
609 # =pod, =cut, =encoding, =begin without =end: nothing to show
610 }
611  
612 147 my $text = join '', @out;
613 147 $text =~ s/\A\n+//;
614 147 $text =~ s/\n{3,}/\n\n/g;
615 147 $text =~ s/\n*\z/\n/;
616 147 return $text;
617 }
618  
619 # =begin html / =begin text data blocks (and their =for spelling, which is what
620 # Pod::Weaver leaves behind in the built distribution). The generated POD uses
621 # these for one thing only: parameter and output tables. Render them as aligned
622 # plain text so the help shows the same information the HTML documentation does.
623  
624 508 my %HTML_ENTITY = (
625 amp => '&', lt => '<', gt => '>', quot => '"', apos => "'", nbsp => ' ',
626 ndash => '-', mdash => '--', hellip => '...',
627 );
628  
629 2282 ▶sub _html_text {
Subroutine _html_text: called CC=4 SCAR=14.9
630 2282 my ($s) = @_;
631 2282 ▶ $s = '' unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 2282 2282
632 2282 $s =~ s{<br\s*/?>}{ }gi;
633 2282 $s =~ s/<[^>]*>//g;
634 0 $s =~ s/&#x([0-9a-fA-F]+);/chr(hex $1)/ge;
635 0 ▶ $s =~ s/&#([0-9]+);/$1 < 128 ? chr($1) : '?'/ge;
Branch: 1 branch
BranchTrueFalseTotal
$1 < 128 ? : 0 0 0
636 2282 ▶ $s =~ s/&([a-zA-Z]+);/exists $HTML_ENTITY{$1} ? $HTML_ENTITY{$1} : "&$1;"/ge;
Branch: 1 branch
BranchTrueFalseTotal
exists $HTML_ENTITY{$1} ? : 193 0 193
637 2282 $s =~ s/\s+/ /g;
638 2282 $s =~ s/\A\s+//; $s =~ s/\s+\z//;
639 2282 return $s;
640 }
641  
642 143 ▶sub _pod_data {
Subroutine _pod_data: called CC=6 SCAR=21.4
643 143 my ($raw, $fmt, $width, $indent) = @_;
644 143 ▶ if ($fmt eq 'text') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fmt eq "text") 0 143 143
645 0 my $pad = ' ' x $indent;
646 0 my $out = "\n";
647 0 for my $line (split /\n/, $raw, -1) {
648 0 $line =~ s/\s+\z//;
649 0 ▶ $out .= length($line) ? $pad . $line . "\n" : "\n";
Branch: 1 branch
BranchTrueFalseTotal
length $line ? : 0 0 0
650 }
651 0 return $out;
652 }
653  
654 143 my $out = '';
655 143 my $seen = 0;
656 143 ▶ while ($raw =~ m{<table[^>]*>(.*?)</table>}gis) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw =~ m[<table[^>]*>(.*?)</table>]sig) 100 143 243
657 100 $out .= _html_table($1, $width, $indent);
658 100 $seen = 1;
659 }
660 # HTML that is not a table carries nothing the plain-text help can use
661 143 ▶ return $seen ? $out : '';
Branch: 1 branch
BranchTrueFalseTotal
$seen ? : 100 43 143
662 }
663  
664 100 ▶sub _html_table {
Subroutine _html_table: called CC=32 SCAR=35.7
665 100 my ($html, $width, $indent) = @_;
666 100 my (@rows, @isheader);
667 100 ▶ while ($html =~ m{<tr[^>]*>(.*?)</tr>}gis) {
Branch: 1 branch
BranchTrueFalseTotal
if ($html =~ m[<tr[^>]*>(.*?)</tr>]sig) 696 100 796
668 696 my $tr = $1;
669 696 my (@cells, $hdr);
670 696 ▶ while ($tr =~ m{<t([dh])[^>]*>(.*?)</t\1\s*>}gis) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tr =~ m[<t([dh])[^>]*>(.*?)</t\1\s*>]sig) 2282 696 2978
671 2282 ▶ $hdr = 1 if lc($1) eq 'h';
Branch: 1 branch
BranchTrueFalseTotal
if lc $1 eq "h" 326 1956 2282
672 2282 push @cells, _html_text($2);
673 }
674 696 ▶ next unless @cells;
Branch: 1 branch
BranchTrueFalseTotal
unless @cells 0 696 696
675 696 push @rows, \@cells;
676 696 ▶ push @isheader, ($hdr ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$hdr ? : 100 596 696
677 }
678 100 ▶ return '' unless @rows;
Branch: 1 branch
BranchTrueFalseTotal
unless @rows 0 100 100
679  
680 # The header decides how many columns there are. A body row with more
681 # cells than that came from a markdown table whose source had an escaped
682 # pipe inside a cell, so fold the strays back into the last column
683 # instead of stretching the whole table to fit the accident.
684 100 my $ncol = 0;
685 100 for my $i (0 .. $#rows) {
686 100 ▶ next unless $isheader[$i];
Branch: 1 branch
BranchTrueFalseTotal
unless $isheader[$i] 0 100 100
687 100 $ncol = scalar @{ $rows[$i] };
688 100 last;
689 }
690 100 ▶ for my $r (@rows) { $ncol = @$r if !$ncol || (!grep { $_ } @isheader) && @$r > $ncol }
Branch: 1 branch
BranchTrueFalseTotal
if not $ncol or not grep({$_;} @isheader) and @$r > $ncol 0 696 696
Condition33%2/6
not $ncol or not grep({$_;} @isheader) and @$r > $ncol
l!l&&r!l&&!r
00696
not grep({$_;} @isheader) and @$r > $ncol
!ll&&!rl&&r
69600
MC/DC0%0/3
not $ncol or not grep({$_;} @isheader) and @$r > $ncol
not $ncol not grep({$_;} @isheader) @$r > $ncol
Truth table25%1/4
not(A) or not(B) and C
A= not $ncolB= not grep({$_;} @isheader)C= @$r > $ncol
ABCresult
1XX1
0111
00X0
0100
691 100 for my $r (@rows) {
692 696 ▶ if (@$r > $ncol) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$r > $ncol) 0 696 696
693 0 my @tail = splice @$r, $ncol - 1;
694 0 $r->[$ncol - 1] = join ' ', grep { length } @tail;
695 }
696 696 ▶ $r->[$ncol - 1] = '' unless defined $r->[$ncol - 1];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$r[$ncol - 1] 0 696 696
697 }
698  
699 # natural column widths, then shrink the widest until the table fits
700 100 my @w = (0) x $ncol;
701 100 for my $r (@rows) {
702 696 for my $c (0 .. $ncol - 1) {
703 2282 ▶ my $l = _help_len(defined $r->[$c] ? $r->[$c] : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $r->[$c] ? : 2282 0 2282
704 2282 ▶ $w[$c] = $l if $l > $w[$c];
Branch: 1 branch
BranchTrueFalseTotal
if $l > $w[$c] 828 1454 2282
705 }
706 }
707 100 my $gap = 2;
708 100 my $avail = $width - $indent - $gap * ($ncol - 1);
709 100 ▶ $avail = 8 * $ncol if $avail < 8 * $ncol;
Branch: 1 branch
BranchTrueFalseTotal
if $avail < 8 * $ncol 0 100 100
710 100 my $total = 0; $total += $_ for @w;
711 100 ▶ while ($total > $avail) {
Branch: 1 branch
BranchTrueFalseTotal
if ($total > $avail) 11478 100 11578
712 11478 my ($worst, $max) = (0, -1);
713 11478 ▶ for my $c (0 .. $ncol - 1) { ($worst, $max) = ($c, $w[$c]) if $w[$c] > $max }
Branch: 1 branch
BranchTrueFalseTotal
if $w[$c] > $max 31354 10993 42347
714 11478 ▶ last if $w[$worst] <= 8;
Branch: 1 branch
BranchTrueFalseTotal
if $w[$worst] <= 8 0 11478 11478
715 11478 $w[$worst]--;
716 11478 $total--;
717 }
718  
719 100 my $pad = ' ' x $indent;
720 100 my $out = "\n";
721 100 for my $i (0 .. $#rows) {
722 # wrap every cell to its column width, then print line by line
723 696 my @cell = map { [ _html_fold($rows[$i][$_], $w[$_]) ] } 0 .. $ncol - 1;
724 696 my $high = 0;
725 696 ▶ for my $c (@cell) { $high = scalar @$c if @$c > $high }
Branch: 1 branch
BranchTrueFalseTotal
if @$c > $high 1075 1207 2282
726 696 for my $line (0 .. $high - 1) {
727 my $s = $pad . join ' ' x $gap,
728 2227 ▶ map { my $t = defined $cell[$_][$line] ? $cell[$_][$line] : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $cell[$_][$line] ? : 3916 4363 8279
729 8279 $t . ' ' x ($w[$_] - _help_len($t)) } 0 .. $ncol - 1;
730 2227 $s =~ s/\s+\z//;
731 2227 $out .= $s . "\n";
732 }
733 696 ▶ if ($isheader[$i]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($isheader[$i]) 100 596 696
734 100 $out .= $pad . join(' ' x $gap, map { '-' x $w[$_] } 0 .. $ncol - 1) . "\n";
735 }
736 }
737 100 return $out . "\n";
738 }
739  
740 # greedy wrap of one table cell to $w display columns
741 2282 ▶sub _html_fold {
Subroutine _html_fold: called CC=11 SCAR=24.2
742 2282 my ($s, $w) = @_;
743 2282 ▶ $s = '' unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 2282 2282
744 2282 ▶ return ('') unless length $s;
Branch: 1 branch
BranchTrueFalseTotal
unless length $s 8 2274 2282
745 2274 my @lines;
746 2274 my $cur = '';
747 2274 for my $word (split /\s+/, $s) {
748 11585 ▶ next unless length $word;
Branch: 1 branch
BranchTrueFalseTotal
unless length $word 0 11585 11585
749 11585 ▶ if (!length $cur) {
Branch: 2 branches
BranchTrueFalseTotal
if (not length $cur) { } 2274 9311 11585
elsif (_help_len($cur) + 1 + _help_len($word) <= $w) { } 7700 1611 9311
750 2274 $cur = $word;
751 } elsif (_help_len($cur) + 1 + _help_len($word) <= $w) {
752 7700 $cur .= ' ' . $word;
753 } else {
754 1611 push @lines, $cur;
755 1611 $cur = $word;
756 }
757 11585 ▶ while (_help_len($cur) > $w) { # a single over-long word
Branch: 1 branch
BranchTrueFalseTotal
if (_help_len($cur) > $w) 23 11585 11608
758 23 my $keep = $cur;
759 23 $keep = substr $keep, 0, $w;
760 23 ▶ $keep =~ s/[\x80-\xbf]+\z// if _help_len($keep) > $w;
Branch: 1 branch
BranchTrueFalseTotal
if _help_len($keep) > $w 0 23 23
761 23 push @lines, $keep;
762 23 $cur = substr $cur, length $keep;
763 }
764 }
765 2274 ▶ push @lines, $cur if length $cur;
Branch: 1 branch
BranchTrueFalseTotal
if length $cur 2274 0 2274
766 2274 ▶ return @lines ? @lines : ('');
Branch: 1 branch
BranchTrueFalseTotal
@lines ? : 2274 0 2274
767 }
768  
769 # colnames($df) / rownames($df)
770 #
771 # Return the column names and row names of any of the four Stats::LikeR
772 # frame shapes, as a list (R's colnames()/rownames()). In scalar context
773 # each returns the count, so `scalar colnames($df) == ncol($df)` and
774 # `scalar rownames($df) == nrow($df)` on a rectangular frame.
775 #
776 # Ordering mirrors view() exactly, so what you name is what you would see:
777 # * positional axes are 0-based integer indices --
778 # AoA columns, and the rows of AoA / AoH / HoA
779 # * key-based axes are the string-sorted union of keys --
780 # AoH / HoH columns (union across every row), HoA columns,
781 # and HoH rows (the outer keys)
782 #
783 # Shape is classified by _df_shape (the same detector agg() uses), so a
784 # ragged AoA/HoA is tolerated for enumeration: colnames() spans the widest
785 # row and rownames() the longest column. Empty frames yield an empty list.
786 # Like agg()/view(), the classifier is ref-based (not reftype), so hand it
787 # an unblessed frame -- blessed frames are the one case ncol()/nrow() take
788 # that this family does not.
789  
790 5338 ▶sub colnames {
Subroutine colnames: called CC=9 SCAR=22.0
Pod documented
791 5338 my ($df) = @_;
792 5338 ▶ _usage_error('colnames', 'undefined data in first position') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 3 5335 5338
793 5335 my $shape = _df_shape($df, 'colnames');
794 5330 my @cols;
795 5330 ▶ if ($shape eq 'AoA') { # widest row -> 0 .. m-1
Branch: 2 branches
BranchTrueFalseTotal
if ($shape eq 'AoA') { } 15 5315 5330
elsif ($shape eq 'HoA') { } 5231 84 5315
796 15 my $m = 0;
797 15 for my $row (@$df) {
798 34 ▶ next unless ref $row eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "ARRAY" 2 32 34
799 32 ▶ $m = scalar @$row if scalar @$row > $m;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @$row > $m 15 17 32
800 }
801 15 @cols = (0 .. $m - 1);
802 } elsif ($shape eq 'HoA') { # keys ARE the columns
803 5231 @cols = sort keys %$df;
804 } else { # AoH / HoH: union of row keys
805 # The union is _aoh_key_union (LikeR.xs), which up to 0.3424 was a
806 # perl loop over every key of every row, and on a 200,000 x 8 AoH took
807 # 0.10 s of the 0.12 s colnames() did. A HoH's rows go to it as a
808 # list of their references.
809 84 ▶ @cols = sort @{ _aoh_key_union($shape eq 'AoH' ? $df : [ values %$df ]) };
Branch: 1 branch
BranchTrueFalseTotal
$shape eq 'AoH' ? : 75 9 84
810 }
811 5330 ▶ return wantarray ? @cols : scalar @cols;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 5328 2 5330
812 }
813  
814 20 ▶sub rownames {
Subroutine rownames: called CC=8 SCAR=20.8
Pod documented
815 20 my ($df) = @_;
816 20 ▶ _usage_error('rownames', 'undefined data in first position') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 3 17 20
817 17 my $shape = _df_shape($df, 'rownames');
818 12 my @rows;
819 12 ▶ if ($shape eq 'HoH') { # outer keys ARE the rows
Branch: 2 branches
BranchTrueFalseTotal
if ($shape eq 'HoH') { } 3 9 12
elsif ($shape eq 'HoA') { } 4 5 9
820 3 @rows = sort keys %$df;
821 } elsif ($shape eq 'HoA') { # longest column -> 0 .. n-1
822 4 my $n = 0;
823 4 for my $v (values %$df) {
824 6 ▶ next unless ref $v eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $v eq "ARRAY" 1 5 6
825 5 ▶ $n = scalar @$v if scalar @$v > $n;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @$v > $n 3 2 5
826 }
827 4 @rows = (0 .. $n - 1);
828 } else { # AoA / AoH: one row per element
829 5 @rows = (0 .. $#$df);
830 }
831 12 ▶ return wantarray ? @rows : scalar @rows;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 10 2 12
832 }
833  
834 # The XSUBs _cols_select / _cols_drop / _cols_rename are PRIVATE -- do NOT
835 # export them. (See select_drop_rename_cols.xs for the C side.)
836 #
837 # NAMING: `select` and `rename` are Perl core builtins, so exporting bare
838 # `select`/`rename` would shadow them in the caller. The `_cols` suffix
839 # avoids that and reads as a trio.
840  
841  
842 # select_cols($df, @cols) | select_cols($df, \@cols)
843 # drop_cols($df, @cols) | drop_cols($df, \@cols)
844 # rename_cols($df, old => new, ...) | rename_cols($df, { old => new, ... })
845 #
846 # Column subset / drop / rename over the four frame shapes -- the Stats::LikeR
847 # form of pandas df[['a','b']] / df.drop(columns=..) / df.rename(columns=..).
848 #
849 # * AoA -- identifiers are 0-based integer positions; rename_cols dies
850 # (an AoA has no labels; convert to AoH/HoA first).
851 # * AoH -- identifiers are the row-hash keys.
852 # * HoA -- identifiers are the top-level keys (the columns themselves).
853 # * HoH -- identifiers are the inner-row keys.
854 #
855 # VIEW SEMANTICS (fast + low RAM). Every result is a shallow view of the
856 # source, so huge frames cost almost nothing to slice:
857 # * the row shapes (AoH/HoH/AoA) build fresh row containers but SHARE the
858 # cell scalars by reference -- no per-cell copy, no duplicate scalar
859 # bodies (this is the XS path; see below);
860 # * HoA shares the whole column arrayrefs (a pure-Perl alias).
861 # The operation never mutates the source. But because cells/columns are
862 # shared, later IN-PLACE mutation of a result cell (e.g. $r->[0]{a}++) or a
863 # push/splice on a result HoA column reaches the source. Assigning a whole
864 # cell ($r->[0]{a} = ...) is always safe. Need an independent copy? Clone
865 # the result (e.g. Storable::dclone).
866 #
867 # IN-PLACE RENAME (rename_cols only). Called in VOID context, rename_cols
868 # mutates the source frame in place -- it renames the keys inside each AoH/HoH
869 # row, or the column keys of a HoA -- and returns nothing. In ANY other
870 # context it returns a fresh view (as above) and never touches the source:
871 #
872 # rename_cols(\%d, resolution => 'Resolution (A)'); # void -> %d in place
873 # %d = %{ rename_cols(\%d, resolution => 'Resolution (A)') }; # capture view
874 #
875 # (select_cols/drop_cols are always pure and ignore calling context -- a void
876 # call to either is a no-op.) Note: `\%d = rename_cols(...)` is not valid Perl
877 # (a reference constructor is not an lvalue before 5.22 refaliasing); use one
878 # of the two forms above.
879 #
880 # The row shapes are dispatched to XS (_cols_* ), which shares cells and
881 # hashes each column key once instead of once per row -- ~2x (select), ~3x
882 # (drop), ~4x (rename) faster than the pure-Perl rebuild at scale, and lower
883 # peak RAM (no copied cells). HoA/AoA-by-alias need no XS. All validation
884 # stays here in Perl, so the XS never has to croak mid-build.
885 #
886 # STRICT: a missing/renamed-away column, a duplicate in a select/drop list,
887 # or a rename whose targets are not distinct, all die with a labelled message.
888 # A column present in only some AoH/HoH rows is filled with undef by
889 # select_cols (rectangular); drop_cols/rename_cols leave ragged frames ragged.
890  
891 46 ▶sub _cols_arg { # normalise + validate a column list
Subroutine _cols_arg: called CC=7 SCAR=19.5
892 46 my ($fn, @a) = @_;
893 46 ▶ my @cols = (@a == 1 && ref $a[0] eq 'ARRAY') ? @{ $a[0] } : @a;
Branch: 1 branch
BranchTrueFalseTotal
@a == 1 && ref $a[0] eq 'ARRAY' ? : 1 45 46
Condition100%3/3
@a == 1 and ref $a[0] eq "ARRAY"
!ll&&!rl&&r
14311
MC/DC100%2/2
@a == 1 and ref $a[0] eq "ARRAY"
@a == 1 ref $a[0] eq "ARRAY"
Truth table100%3/3
A and B
A= @a == 1B= ref $a[0] eq "ARRAY"
ABresult
0X0
100
111
894 46 ▶ _usage_error($fn, 'at least one column is required') unless @cols;
Branch: 1 branch
BranchTrueFalseTotal
unless @cols 6 40 46
895 40 my %seen;
896 40 for my $c (@cols) {
897 49 ▶ _usage_error($fn, 'column identifier is undefined') unless defined $c;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $c 0 49 49
898 49 ▶ _usage_error($fn, "duplicate column '$c' in the list") if $seen{$c}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$c}++ 1 48 49
899 }
900 39 return @cols;
901 }
902  
903 31 ▶sub _aoa_width { # widest row of an AoA (ragged-safe)
Subroutine _aoa_width: called CC=4 SCAR=13.9
904 31 my $df = shift;
905 31 my $w = 0;
906 31 ▶ for my $r (@$df) { $w = scalar @$r if ref $r eq 'ARRAY' && @$r > $w }
Branch: 1 branch
BranchTrueFalseTotal
if ref $r eq "ARRAY" and @$r > $w 31 82 113
Condition66%2/3
ref $r eq "ARRAY" and @$r > $w
!ll&&!rl&&r
08231
MC/DC50%1/2
ref $r eq "ARRAY" and @$r > $w
ref $r eq "ARRAY" @$r > $w
Truth table66%2/3
A and B
A= ref $r eq "ARRAY"B= @$r > $w
ABresult
0X0
100
111
907 31 return $w;
908 }
909  
910 11 ▶sub _aoa_int_cols { # validate integer positions in range
Subroutine _aoa_int_cols: called CC=4 SCAR=13.9
911 11 my ($fn, $df, @cols) = @_;
912 11 my $w = _aoa_width($df);
913 11 for my $c (@cols) {
914 14 ▶ _usage_error($fn, "AoA column '$c' is not a non-negative integer")
Branch: 1 branch
BranchTrueFalseTotal
unless $c =~ /^\d+$/ 2 12 14
915 unless $c =~ /^\d+$/;
916 12 ▶ _usage_error($fn, "AoA column index $c out of range (max index " . ($w - 1) . ")")
Branch: 1 branch
BranchTrueFalseTotal
if $c >= $w 2 10 12
917 if $c >= $w;
918 }
919 7 return $w;
920 }
921  
922 43 ▶sub _present_keys { # union of keys over AoH/HoH rows, as a set
Subroutine _present_keys: called CC=2 SCAR=6.9
923 43 my ($df, $shape) = @_;
924 43 ▶ my %seen = map { $_ => 1 } @{ _aoh_key_union($shape eq 'AoH' ? $df : [ values %$df ]) };
Branch: 1 branch
BranchTrueFalseTotal
$shape eq 'AoH' ? : 23 20 43
925 43 return \%seen;
926 }
927  
928 5 ▶sub _rename_inplace { # VOID-context rename: mutate the source
Subroutine _rename_inplace: called CC=8 SCAR=20.8
929 5 my ($df, $shape, $map) = @_;
930 5 ▶ if ($shape eq 'HoA') { # rename the column keys
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "HoA") 1 4 5
931 1 my %vals; # gather-then-set = swap-safe
932 1 for my $o (keys %$map) {
933 1 ▶ next unless exists $df->{$o};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $df->{$o} 0 1 1
934 1 $vals{ $map->{$o} } = delete $df->{$o};
935 }
936 1 $df->{$_} = $vals{$_} for keys %vals;
937 1 return;
938 }
939 7 ▶ my $one = sub { # AoH / HoH row hashes
Subroutine __ANON__: called CC=5 SCAR=16.1
940 7 my ($row) = @_;
941 7 ▶ return unless ref $row eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 0 7 7
942 7 my %vals; # gather-then-set = swap-safe
943 7 for my $o (keys %$map) {
944 8 ▶ next unless exists $row->{$o};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $row->{$o} 1 7 8
945 7 $vals{ $map->{$o} } = delete $row->{$o};
946 }
947 7 $row->{$_} = $vals{$_} for keys %vals;
948 4 };
949 4 ▶ if ($shape eq 'AoH') { $one->($_) for @$df } # no list copy: see colnames
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq 'AoH') { } 2 2 4
950 2 else { $one->($_) for values %$df }
951 4 return;
952 }
953  
954 33 ▶sub select_cols {# shape code passed to the XS: 1 = AoH, 2 = HoH, 3 = AoA
Subroutine select_cols: called CC=10 SCAR=23.0
Pod documented
955 33 my $df = _untied(shift);
956 33 ▶ _usage_error('select_cols', 'undefined data in first position') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 3 30 33
957 30 my @cols = _cols_arg('select_cols', @_);
958 25 my $shape = _df_shape($df, 'select_cols');
959  
960 25 ▶ if ($shape eq 'HoA') { # alias columns (pure Perl)
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "HoA") 6 19 25
961 6 for my $c (@cols) {
962 7 ▶ die "select_cols: column '$c' not found\n" unless exists $df->{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $df->{$c} 1 6 7
963 }
964 5 my %out;
965 5 $out{$_} = $df->{$_} for @cols;
966 5 return \%out;
967 }
968 19 ▶ if ($shape eq 'AoA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "AoA") 4 15 19
969 4 _aoa_int_cols('select_cols', $df, @cols);
970 2 return _cols_select($df, 3, [ @cols ]);
971 }
972 15 my $present = _present_keys($df, $shape);
973 15 for my $c (@cols) {
974 19 ▶ die "select_cols: column '$c' not found\n" unless $present->{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $present->{$c} 1 18 19
975 }
976 14 ▶ return _cols_select($df, $shape eq 'AoH' ? 1 : 2, [ @cols ]);
Branch: 1 branch
BranchTrueFalseTotal
$shape eq 'AoH' ? : 8 6 14
977 }
978  
979 18 ▶sub drop_cols {
Subroutine drop_cols: called CC=11 SCAR=24.0
Pod documented
980 18 my $df = _untied(shift);
981 18 ▶ _usage_error('drop_cols', 'undefined data in first position') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 2 16 18
982 16 my @cols = _cols_arg('drop_cols', @_);
983 14 my %drop = map { $_ => 1 } @cols;
984 14 my $shape = _df_shape($df, 'drop_cols');
985  
986 13 ▶ if ($shape eq 'HoA') { # alias survivors (pure Perl)
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "HoA") 2 11 13
987 2 for my $c (@cols) {
988 2 ▶ die "drop_cols: column '$c' not found\n" unless exists $df->{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $df->{$c} 0 2 2
989 }
990 2 my %out;
991 2 ▶ for my $k (keys %$df) { next if $drop{$k}; $out{$k} = $df->{$k} }
Branch: 1 branch
BranchTrueFalseTotal
if $drop{$k} 2 4 6
992 2 return \%out;
993 }
994 11 ▶ if ($shape eq 'AoA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "AoA") 1 10 11
995 1 my $w = _aoa_int_cols('drop_cols', $df, @cols);
996 1 my @keep = grep { !$drop{$_} } 0 .. $w - 1;
997 1 return _cols_select($df, 3, [ @keep ]); # keep == select the rest
998 }
999 10 my $present = _present_keys($df, $shape);
1000 10 for my $c (@cols) {
1001 11 ▶ die "drop_cols: column '$c' not found\n" unless $present->{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $present->{$c} 1 10 11
1002 }
1003 9 ▶ return _cols_drop($df, $shape eq 'AoH' ? 1 : 2, \%drop);
Branch: 1 branch
BranchTrueFalseTotal
$shape eq 'AoH' ? : 4 5 9
1004 }
1005  
1006 27 ▶sub rename_cols {
Subroutine rename_cols: called CC=21 SCAR=30.4
Pod documented
1007 27 my $df = shift;
1008 27 ▶ $df = _untied($df) if defined wantarray; # void context renames the frame itself
Branch: 1 branch
BranchTrueFalseTotal
if defined wantarray 15 12 27
1009 27 ▶ _usage_error('rename_cols', 'undefined data in first position') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 1 26 27
1010 26 my %map;
1011 26 ▶ if (@_ == 1 && ref $_[0] eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 and ref $_[0] eq 'HASH') { } 1 25 26
Condition100%3/3
@_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
2411
MC/DC100%2/2
@_ == 1 and ref $_[0] eq "HASH"
@_ == 1 ref $_[0] eq "HASH"
Truth table100%3/3
A and B
A= @_ == 1B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
1012 1 %map = %{ $_[0] };
1013 } else {
1014 25 ▶ _usage_error('rename_cols', 'arguments after the data frame must be old => new pairs (or one hashref)')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 1 24 25
1015 if @_ % 2;
1016 24 %map = @_;
1017 }
1018 25 ▶ _usage_error('rename_cols', 'at least one old => new mapping is required') unless %map;
Branch: 1 branch
BranchTrueFalseTotal
unless %map 3 22 25
1019 22 for my $o (keys %map) {
1020 25 ▶ _usage_error('rename_cols', "new name for '$o' is undefined") unless defined $map{$o};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $map{$o} 0 25 25
1021 }
1022 22 my $shape = _df_shape($df, 'rename_cols');
1023 21 ▶ die "rename_cols: an AoA has no column names to rename (convert to AoH/HoA first)\n"
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "AoA" 1 20 21
1024 if $shape eq 'AoA';
1025  
1026 my @present = $shape eq 'HoA' ? keys %$df
1027 20 ▶ : keys %{ _present_keys($df, $shape) };
Branch: 1 branch
BranchTrueFalseTotal
$shape eq 'HoA' ? : 2 18 20
1028 20 my %present = map { $_ => 1 } @present;
1029 20 for my $o (keys %map) {
1030 23 ▶ die "rename_cols: column '$o' not found\n" unless $present{$o};
Branch: 1 branch
BranchTrueFalseTotal
unless $present{$o} 1 22 23
1031 }
1032 19 my %final; # target names stay distinct
1033 19 for my $c (@present) {
1034 49 ▶ my $nn = exists $map{$c} ? $map{$c} : $c;
Branch: 1 branch
BranchTrueFalseTotal
exists $map{$c} ? : 22 27 49
1035 die "rename_cols: rename collides -- two columns would both become '$nn'\n"
1036 49 ▶ if $final{$nn}++;
Branch: 1 branch
BranchTrueFalseTotal
if $final{$nn}++ 2 47 49
1037 }
1038  
1039 # VOID context -> mutate the source in place and return nothing; any other
1040 # context returns a fresh shallow view exactly as before.
1041 17 ▶ unless (defined wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined wantarray) 5 12 17
1042 5 _rename_inplace($df, $shape, \%map);
1043 5 return;
1044 }
1045  
1046 12 ▶ if ($shape eq 'HoA') { # alias under new keys
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "HoA") 1 11 12
1047 1 my %out;
1048 1 for my $k (keys %$df) {
1049 3 ▶ my $nk = exists $map{$k} ? $map{$k} : $k;
Branch: 1 branch
BranchTrueFalseTotal
exists $map{$k} ? : 1 2 3
1050 3 $out{$nk} = $df->{$k};
1051 }
1052 1 return \%out;
1053 }
1054 11 ▶ return _cols_rename($df, $shape eq 'AoH' ? 1 : 2, \%map);
Branch: 1 branch
BranchTrueFalseTotal
$shape eq 'AoH' ? : 5 6 11
1055 }
1056  
1057 24 ▶sub aoh2hoh {
Subroutine aoh2hoh: called CC=4 SCAR=13.9
Pod documented
1058 24 my ($aoh, $key) = @_;
1059 24 ▶ _usage_error('aoh2hoh', 'first argument is undefined') unless defined $aoh;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $aoh 2 22 24
1060 22 ▶ _usage_error('aoh2hoh', 'first argument must be an arrayref of hashrefs')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $aoh eq "ARRAY" 4 18 22
1061 unless ref($aoh) eq 'ARRAY';
1062 18 ▶ _usage_error('aoh2hoh', 'a row key must be defined') unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 2 16 18
1063 # each row copied as { %$row } under its key, in XS; up to 0.3424 a perl loop
1064 16 return _aoh2hoh_xs($aoh, $key);
1065 }
1066  
1067 # h2aoh / df2h -- the flat hash as a two-column frame
1068 #
1069 # A plain hash is a two-column table that has been folded shut: every pair is
1070 # one row, the key in one cell and the value in the other. value_counts() and
1071 # table() hand one back, and none of the frame functions will take it, because
1072 # they all want nested data. h2aoh unfolds the hash into a real AoH; df2h
1073 # folds any frame back down -- an AoH, and also an AoA, HoA or HoH. It was
1074 # aoh2h, for an AoH alone, up to 0.3218, and aoh2h is still a name for it.
1075 # R spells this pair enframe()/deframe() (tibble);
1076 # pandas spells it pd.Series(d).rename_axis(..).reset_index(name => ..) and
1077 # Series.to_dict().
1078 #
1079 # The column names are var_name / value_name, the same two options melt() uses
1080 # to name the columns it emits, since the shape they describe is the same.
1081 #
1082 # The pair are exact inverses under their defaults, so
1083 # is_deeply( df2h( h2aoh(\%h) ), \%h )
1084 # holds for any flat hash whose keys are defined.
1085  
1086 # _kv_names($caller, \%arg) -- var_name / value_name, defaulted and checked.
1087 # Shared so the two directions cannot drift apart on the names they agree on.
1088 184 ▶sub _kv_names {
Subroutine _kv_names: called CC=4 SCAR=13.9
1089 184 my ($caller, $arg) = @_;
1090 184 ▶ my $var = defined $arg->{var_name} ? $arg->{var_name} : 'variable';
Branch: 1 branch
BranchTrueFalseTotal
defined $arg->{'var_name'} ? : 31 153 184
1091 184 ▶ my $value = defined $arg->{value_name} ? $arg->{value_name} : 'value';
Branch: 1 branch
BranchTrueFalseTotal
defined $arg->{'value_name'} ? : 22 162 184
1092 184 ▶ _usage_error($caller, 'var_name and value_name must differ') if $var eq $value;
Branch: 1 branch
BranchTrueFalseTotal
if $var eq $value 2 182 184
1093 182 return ($var, $value);
1094 }
1095  
1096 # _usage_text($fn) -- $fn's argparse-style help screen, from
1097 # Stats::LikeR::Usage, which is compiled only here, on the way to an error. A
1098 # name with no screen gets none, so that the error is still raised rather than
1099 # lost to a second one; t/usage.t keeps every exported name covered.
1100 1586 ▶sub _usage_text {
Subroutine _usage_text: called CC=3 SCAR=11.0
1101 1586 my ($fn) = @_;
1102 1586 require Stats::LikeR::Usage;
1103 1586 ▶ my $name = exists $Stats::LikeR::Usage::ALIAS{$fn} ? $Stats::LikeR::Usage::ALIAS{$fn} : $fn;
Branch: 1 branch
BranchTrueFalseTotal
exists $Stats::LikeR::Usage::ALIAS{$fn} ? : 3 1583 1586
1104 1586 my $screen = $Stats::LikeR::Usage::SCREEN{$name};
1105 1586 ▶ return defined $screen ? $screen : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $screen ? : 1585 1 1586
1106 }
1107  
1108 # _xlsx_provenance() -- ($user, $lines) for write_table's .xlsx document
1109 # properties (xlsx_written_by() in the XS). $user is the login name, undef when
1110 # none can be found; $lines is "user: ...", "host: ...", "perl: ..." and
1111 # "Stats::LikeR: ..." joined by newlines, leaving out any that is unknown.
1112 # getpwuid() dies "unimplemented" on Windows, so getlogin() and the environment
1113 # are the fallbacks there; Sys::Hostname (core) croaks when it finds no name.
1114 # $@ is local: a successful eval clears it, and this runs inside the caller's
1115 # write_table(), whose $@ up to 0.341 came back empty.
1116 169 ▶sub _xlsx_provenance {
Subroutine _xlsx_provenance: called CC=12 SCAR=29.5
1117 169 local $@;
1118 169 my $user = eval { scalar getpwuid($<) };
1119 169 ▶ $user = getlogin() unless defined $user && length $user;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $user and length $user 0 169 169
Condition33%1/3
defined $user and length $user
!ll&&!rl&&r
00169
MC/DC0%0/2
defined $user and length $user
defined $user length $user
Truth table33%1/3
A and B
A= defined $userB= length $user
ABresult
0X0
100
111
1120 169 for my $k (qw(USER USERNAME LOGNAME)) {
1121 169 ▶ last if defined $user && length $user;
Branch: 1 branch
BranchTrueFalseTotal
if defined $user and length $user 169 0 169
Condition33%1/3
defined $user and length $user
!ll&&!rl&&r
00169
MC/DC0%0/2
defined $user and length $user
defined $user length $user
Truth table33%1/3
A and B
A= defined $userB= length $user
ABresult
0X0
100
111
1122 0 $user = $ENV{$k};
1123 }
1124 169 ▶ $user = undef unless defined $user && length $user;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $user and length $user 0 169 169
Condition33%1/3
defined $user and length $user
!ll&&!rl&&r
00169
MC/DC0%0/2
defined $user and length $user
defined $user length $user
Truth table33%1/3
A and B
A= defined $userB= length $user
ABresult
0X0
100
111
1125 169 my $host = eval { require Sys::Hostname; Sys::Hostname::hostname() };
1126 169 ▶ $host = undef unless defined $host && length $host;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $host and length $host 0 169 169
Condition33%1/3
defined $host and length $host
!ll&&!rl&&r
00169
MC/DC0%0/2
defined $host and length $host
defined $host length $host
Truth table33%1/3
A and B
A= defined $hostB= length $host
ABresult
0X0
100
111
1127 169 my @lines;
1128 169 ▶ push @lines, "user: $user" if defined $user;
Branch: 1 branch
BranchTrueFalseTotal
if defined $user 169 0 169
1129 169 ▶ push @lines, "host: $host" if defined $host;
Branch: 1 branch
BranchTrueFalseTotal
if defined $host 169 0 169
1130 169 push @lines, sprintf('perl: v%vd', $^V), "Stats::LikeR: $VERSION";
1131 169 return ($user, join("\n", @lines));
1132 }
1133  
1134 # _sheet_name_clash(@names) -- the first two of a workbook's worksheet names
1135 # that are the same with case ignored, or nothing. Excel cannot open a
1136 # workbook holding both; write_table's XS (wt_sheet_names_distinct()) calls this
1137 # because lc() folds every character of a UTF-8 string, which C cannot do
1138 # portably. lc() is what Excel::Writer::XLSX 1.15 compares with too.
1139 26 ▶sub _sheet_name_clash {
Subroutine _sheet_name_clash: called CC=3 SCAR=11.0
1140 26 my %seen;
1141 26 for my $name (@_) {
1142 63 my $k = lc $name;
1143 63 ▶ return ($seen{$k}, $name) if exists $seen{$k};
Branch: 1 branch
BranchTrueFalseTotal
if exists $seen{$k} 4 59 63
1144 59 $seen{$k} = $name;
1145 }
1146 22 return;
1147 }
1148  
1149 # _usage_error($fn, $msg) -- die over an argument $fn was called with as
1150 # argparse does: the help screen, then "$fn: error: $msg" as the last line.
1151 # For the form of a call only (a missing or mistyped argument, an unknown
1152 # option, a value outside its choices); an error in the data keeps its own
1153 # one-line message. The XS raises the same through usage_croak().
1154 403 ▶sub _usage_error {
Subroutine _usage_error: called CC=1 SCAR=0.0
1155 403 my ($fn, $msg) = @_;
1156 403 die _usage_text($fn) . "$fn: error: $msg\n";
1157 }
1158  
1159 # _opt_names_defined($caller, @pairs) -- die, in the caller's name, on an undef
1160 # option name. Without it `my %arg = @_` raises perl's own "Use of
1161 # uninitialized value", which the FATAL warnings above make fatal and which
1162 # names a line of this file rather than the option. Up to 0.3217 that was what
1163 # h2aoh({}, undef, 1) and aoh2h([], undef, 1) died with.
1164 578 ▶sub _opt_names_defined {
Subroutine _opt_names_defined: called CC=3 SCAR=11.0
1165 578 my $caller = shift;
1166 578 ▶ for (my $j = 0; $j < @_; $j += 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < @_) 334 575 909
1167 334 ▶ _usage_error($caller, 'an option name is undefined') unless defined $_[$j];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[$j] 3 331 334
1168 }
1169 }
1170  
1171 42 ▶sub h2aoh {
Subroutine h2aoh: called CC=18 SCAR=28.9
Pod documented
1172 42 my $h = shift;
1173 42 ▶ _usage_error('h2aoh', 'first argument is undefined') unless defined $h;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $h 2 40 42
1174 40 ▶ _usage_error('h2aoh', 'first argument must be a hashref') unless ref($h) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $h eq "HASH" 4 36 40
1175 36 ▶ _usage_error('h2aoh', 'arguments after the hash must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 1 35 36
1176 if @_ % 2;
1177 35 _opt_names_defined('h2aoh', @_);
1178 34 my %arg = @_;
1179 34 my %known = ( var_name => 1, value_name => 1, sort => 1 );
1180 34 my @bad = sort grep { !$known{$_} } keys %arg;
1181 34 ▶ _usage_error('h2aoh', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 33 34
1182  
1183 33 my ($var_name, $value_name) = _kv_names('h2aoh', \%arg);
1184  
1185 # A reference value means the caller has a nested frame in hand, not a flat
1186 # hash, and one of the shape converters is the function they wanted. Say
1187 # which, rather than quietly stringifying the ref into a cell.
1188 32 for my $k (sort keys %$h) {
1189 78 ▶ next unless ref $h->{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $h->{$k} 75 3 78
1190 3 die "h2aoh: the value for key '$k' is a " . ref($h->{$k})
1191 . " reference; h2aoh takes a flat hash (hoa2aoh converts a "
1192 . "hash-of-arrays, hoh2hoa a hash-of-hashes)\n";
1193 }
1194  
1195 29 ▶ my $how = defined $arg{sort} ? lc $arg{sort} : 'key';
Branch: 1 branch
BranchTrueFalseTotal
defined $arg{'sort'} ? : 11 18 29
1196 29 my @keys = keys %$h;
1197 29 ▶ if ($how eq 'key') {
Branch: 3 branches
BranchTrueFalseTotal
if ($how eq 'key') { } 19 10 29
elsif ($how eq 'value') { } 6 4 10
elsif ($how ne 'none') { } 2 2 4
1198 # numeric when every key is a number, else string -- the rule agg()
1199 # already uses for its group keys
1200 44 @keys = ( grep { !looks_like_number($_) } @keys )
1201 ? sort @keys
1202 19 ▶ : sort { $a <=> $b } @keys;
Branch: 1 branch
BranchTrueFalseTotal
grep({not &looks_like_number($_);} @keys) ? : 17 2 19
1203 }
1204 elsif ($how eq 'value') {
1205 # biggest first for counts, which is what value_counts() output is for
1206 # and what pandas' Series.value_counts() gives. Non-numeric values have
1207 # no such convention, so they go up in string order. undef sorts last
1208 # either way, and ties break on the key so the order is total.
1209 13 my $numeric = !grep { !looks_like_number($_) }
1210 6 grep { defined } values %$h;
1211 @keys = sort {
1212 6 ( defined $h->{$a} ? 0 : 1 ) <=> ( defined $h->{$b} ? 0 : 1 )
1213 || ( !defined $h->{$a} ? 0
1214 : $numeric ? $h->{$b} <=> $h->{$a}
1215 14 ▶ : $h->{$a} cmp $h->{$b} )
Branch: 4 branches
BranchTrueFalseTotal
defined $h->{$a} ? : 11 3 14
defined $h->{$b} ? : 13 1 14
!defined($h->{$a}) ? : 0 10 10
$numeric ? : 9 1 10
Condition83%5/6
(defined $h->{$a} ? 0 : 1) <=> (defined $h->{$b} ? 0 : 1) || (!defined($h->{$a}) ? 0 : ($numeric ? $h->{$b} <=> $h->{$a} : $h->{$a} cmp $h->{$b})) || $a cmp $b
l!l&&r!l&&!r
1310
(defined $h->{$a} ? 0 : 1) <=> (defined $h->{$b} ? 0 : 1) or !defined($h->{$a}) ? 0 : ($numeric ? $h->{$b} <=> $h->{$a} : $h->{$a} cmp $h->{$b})
l!l&&r!l&&!r
491
MC/DC0%0/3
(defined $h->{$a} ? 0 : 1) <=> (defined $h->{$b} ? 0 : 1) || (!defined($h->{$a}) ? 0 : ($numeric ? $h->{$b} <=> $h->{$a} : $h->{$a} cmp $h->{$b})) || $a cmp $b
(defined $h->{$a} ? 0 : 1) <=> (defined $h->{$b} ? 0 : 1) !defined($h->{$a}) ? 0 : ($numeric ? $h->{$b} <=> $h->{$a} : $h->{$a} cmp $h->{$b}) $a cmp $b
Truth table75%3/4
A or not(B) || C
A= (defined $h->{$a} ? 0 : 1) <=> (defined $h->{$b} ? 0 : 1)B= !defined($h->{$a}) ? 0 : ($numeric ? $h->{$b} <=> $h->{$a} : $h->{$a} cmp $h->{$b})C= $a cmp $b
ABCresult
1XX1
01X1
0011
0000
1216 || $a cmp $b
1217 } @keys;
1218 }
1219 elsif ($how ne 'none') {
1220 2 _usage_error('h2aoh', "sort '$how' isn't allowed (key, value, none)");
1221 }
1222  
1223 27 return [ map { { $var_name => $_, $value_name => $h->{$_} } } @keys ];
1224 }
1225  
1226 # The rows are read by the XSUB _df2h, which also makes every check on them;
1227 # the shape and the options are read here.
1228 #
1229 # aoh2h is the same sub under the name it had up to 0.3218, when it took an AoH
1230 # alone. It is a glob alias, as rbind is of concat, so its messages say df2h.
1231 226 ▶sub df2h {
Subroutine df2h: called CC=44 SCAR=37.8
Pod documented
1232 226 my $df = shift;
1233 226 ▶ _usage_error('df2h', 'first argument is undefined') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 5 221 226
1234 # reftype, not ref: a blessed frame or row is still one, as aoh2hoa
1235 # already took it. Up to 0.3217 aoh2h refused them.
1236 221 ▶ my $type = reftype($df) || '';
Condition100%2/2
builtin::reftype($df) || ''
l!l
2165
MC/DC100%1/1
builtin::reftype($df) || ''
builtin::reftype($df)
Truth table100%2/2
A
A= builtin::reftype($df)
Aresult
11
00
1237 221 ▶ _usage_error('df2h', 'first argument must be a data frame (AoA, AoH, HoA or HoH)')
Branch: 1 branch
BranchTrueFalseTotal
unless $type eq "ARRAY" or $type eq "HASH" 6 215 221
Condition100%3/3
$type eq "ARRAY" or $type eq "HASH"
l!l&&r!l&&!r
153626
MC/DC100%2/2
$type eq "ARRAY" or $type eq "HASH"
$type eq "ARRAY" $type eq "HASH"
Truth table100%3/3
A or B
A= $type eq "ARRAY"B= $type eq "HASH"
ABresult
1X1
011
000
1238 unless $type eq 'ARRAY' || $type eq 'HASH';
1239 215 ▶ _usage_error('df2h', 'arguments after the data frame must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 1 214 215
1240 if @_ % 2;
1241 214 _opt_names_defined('df2h', @_);
1242 212 my %arg = @_;
1243 212 my %known = ( var_name => 1, value_name => 1, duplicates => 1 );
1244 212 my @bad = sort grep { !$known{$_} } keys %arg;
1245 212 ▶ _usage_error('df2h', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 211 212
1246  
1247 # A tied frame is copied once, as _untied() does, so that deciding its
1248 # shape here does not FETCH a row the XS then FETCHes again. _untied()
1249 # itself is not used because it asks ref(), which a blessed frame fails.
1250 211 ▶ if ($type eq 'ARRAY') { $df = [ @$df ] if tied @$df }
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'ARRAY') { } 149 62 211
if tied @$df 6 143 149
1251 62 ▶ else { $df = { %$df } if tied %$df }
Branch: 1 branch
BranchTrueFalseTotal
if tied %$df 2 60 62
1252  
1253 # The shape, by _df_shape()'s rules but with reftype(). An array is an
1254 # AoA when its first defined element is an array, and is otherwise read as
1255 # an AoH, so that the XS names the first row that is not a hash.
1256 211 my $shape; # 'AoA', 'AoH', 'HoA' or 'HoH'
1257 211 ▶ if ($type eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq 'ARRAY') { } 149 62 211
1258 149 $shape = 'AoH';
1259 149 for my $r (@$df) {
1260 148 ▶ next unless defined $r;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r 3 145 148
1261 145 ▶ $shape = 'AoA' if (reftype($r) || '') eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::reftype($r) || "") eq "ARRAY" 54 91 145
Condition100%2/2
builtin::reftype($r) || ''
l!l
1432
MC/DC100%1/1
builtin::reftype($r) || ''
builtin::reftype($r)
Truth table100%2/2
A
A= builtin::reftype($r)
Aresult
11
00
1262 145 last;
1263 }
1264 } else {
1265 62 ▶ return {} unless %$df; # no rows, whichever of HoA or HoH it is
Branch: 1 branch
BranchTrueFalseTotal
unless %$df 1 61 62
1266 61 my ($saw_arr, $saw_hash) = (0, 0);
1267 61 for my $v (values %$df) {
1268 998 ▶ my $t = reftype($v) || next;
Condition100%2/2
builtin::reftype($v) || (next)
l!l
98810
MC/DC100%1/1
builtin::reftype($v) || (next)
builtin::reftype($v)
Truth table100%2/2
A
A= builtin::reftype($v)
Aresult
11
00
1269 988 ▶ $saw_arr = 1 if $t eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if $t eq "ARRAY" 66 922 988
1270 988 ▶ $saw_hash = 1 if $t eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if $t eq "HASH" 922 66 988
1271 }
1272 61 ▶ die "df2h: hashref mixes array and hash values (ambiguous HoA/HoH)\n"
Branch: 1 branch
BranchTrueFalseTotal
if $saw_arr and $saw_hash 1 60 61
Condition100%3/3
$saw_arr and $saw_hash
!ll&&!rl&&r
26341
MC/DC100%2/2
$saw_arr and $saw_hash
$saw_arr $saw_hash
Truth table100%3/3
A and B
A= $saw_arrB= $saw_hash
ABresult
0X0
100
111
1273 if $saw_arr && $saw_hash;
1274 # most likely df2h's own output, handed back to it
1275 60 ▶ die "df2h: first argument is a flat hash, not a data frame: none of "
Branch: 1 branch
BranchTrueFalseTotal
unless $saw_arr or $saw_hash 4 56 60
Condition100%3/3
$saw_arr or $saw_hash
l!l&&r!l&&!r
34224
MC/DC100%2/2
$saw_arr or $saw_hash
$saw_arr $saw_hash
Truth table100%3/3
A or B
A= $saw_arrB= $saw_hash
ABresult
1X1
011
000
1276 . "its values is an array or hash ref\n"
1277 unless $saw_arr || $saw_hash;
1278 56 ▶ $shape = $saw_hash ? 'HoH' : 'HoA';
Branch: 1 branch
BranchTrueFalseTotal
$saw_hash ? : 22 34 56
1279 }
1280  
1281 205 my ($var_name, $value_name);
1282 205 ▶ if ($shape eq 'AoA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq 'AoA') { } 54 151 205
1283 # positions, Perl's own negative indexing as in agg(); the bound keeps
1284 # the XS's SvIV() from saturating, which a 32-bit IV would at 2**31
1285 ($var_name, $value_name) = map {
1286 99 my $c = $_;
1287 99 ▶ die "df2h: an AoA's columns are integer positions, not '$c'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $c =~ /\A-?[0-9]+\z/ 9 90 99
1288 unless $c =~ /\A-?[0-9]+\z/;
1289 90 ▶ die "df2h: column position $c is past the end of any array\n"
Branch: 1 branch
BranchTrueFalseTotal
if abs $c > '9223372036854775807' 1 89 90
1290 if abs($c) > ~0 >> 1;
1291 89 ▶ 0 + $c; # '01' and '-0' are the positions 1 and 0
Branch: 2 branches
BranchTrueFalseTotal
defined $arg{'var_name'} ? : 22 32 54
defined $arg{'value_name'} ? : 12 42 54
1292 } ( defined $arg{var_name} ? $arg{var_name} : 0,
1293 54 defined $arg{value_name} ? $arg{value_name} : 1 );
1294 44 ▶ die "df2h: var_name and value_name must differ\n"
Branch: 1 branch
BranchTrueFalseTotal
if $var_name == $value_name 2 42 44
1295 if $var_name == $value_name;
1296 } else {
1297 151 ($var_name, $value_name) = _kv_names('df2h', \%arg);
1298 }
1299  
1300 192 ▶ my $dup = defined $arg{duplicates} ? lc $arg{duplicates} : 'die';
Branch: 1 branch
BranchTrueFalseTotal
defined $arg{'duplicates'} ? : 40 152 192
1301 192 my %dup_code = ( die => 0, first => 1, last => 2 ); # _df2h's `dup`
1302 die "df2h: duplicates '$dup' isn't allowed (die, first, last)\n"
1303 192 ▶ unless exists $dup_code{$dup};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $dup_code{$dup} 1 191 192
1304 # 'first' and 'last' mean an order, and a HoH has none: they would keep
1305 # whichever row hash order reached first, which differs from run to run
1306 191 ▶ die "df2h: duplicates '$dup' needs ordered rows, and a HoH's are not; "
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "HoH" and $dup ne "die" 4 187 191
Condition100%3/3
$shape eq "HoH" and $dup ne "die"
!ll&&!rl&&r
169184
MC/DC100%2/2
$shape eq "HoH" and $dup ne "die"
$shape eq "HoH" $dup ne "die"
Truth table100%3/3
A and B
A= $shape eq "HoH"B= $dup ne "die"
ABresult
0X0
100
111
1307 . "use 'die', or give an AoH, AoA or HoA\n"
1308 if $shape eq 'HoH' && $dup ne 'die';
1309  
1310 # _df2h's `shape`: 1 = AoH, 2 = HoH, 3 = AoA, 4 = HoA
1311 187 ▶ if ($shape eq 'HoA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "HoA") 34 153 187
1312 34 for my $c ($var_name, $value_name) {
1313 64 ▶ die "df2h: no '$c' column\n" unless exists $df->{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $df->{$c} 4 60 64
1314 die "df2h: column '$c' is not an arrayref\n"
1315 60 ▶ unless (reftype($df->{$c}) || '') eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($df->{$c}) || "") eq "ARRAY" 2 58 60
Condition100%2/2
builtin::reftype($df->{$c}) || ''
l!l
582
MC/DC100%1/1
builtin::reftype($df->{$c}) || ''
builtin::reftype($df->{$c})
Truth table100%2/2
A
A= builtin::reftype($df->{$c})
Aresult
11
00
1316 }
1317 28 my ($nk, $nv) = map { scalar @{ $df->{$_} } } $var_name, $value_name;
1318 28 ▶ die "df2h: column '$var_name' has length $nk and '$value_name' has "
Branch: 1 branch
BranchTrueFalseTotal
if $nk != $nv 3 25 28
1319 . "length $nv; the two must be the same length\n" if $nk != $nv;
1320 return _df2h([ $df->{$var_name}, $df->{$value_name} ], 4,
1321 25 $var_name, $value_name, $dup_code{$dup}, undef);
1322 }
1323 153 ▶ if ($shape eq 'HoH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "HoH") 18 135 153
1324 # Hash order first, which costs no sort. Should that croak, the rows
1325 # are read again in sorted order, the one deterministic order a HoH has,
1326 # so that which bad row the message names is the same on every run.
1327 18 my $h;
1328 18 ▶ return $h if eval { $h = _df2h($df, 2, $var_name, $value_name, 0, [ keys %$df ]); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $h = _df2h($df, 2, $var_name, $value_name, 0, [keys %$df]); 1 } } 8 10 18
1329 10 my $err = $@;
1330 10 _df2h($df, 2, $var_name, $value_name, 0, [ sort keys %$df ]);
1331 0 die $err; # reached only if the second reading did not croak
1332 }
1333 return _df2h($df, $shape eq 'AoA' ? 3 : 1, $var_name, $value_name,
1334 135 ▶ $dup_code{$dup}, undef);
Branch: 1 branch
BranchTrueFalseTotal
$shape eq 'AoA' ? : 42 93 135
1335 }
1336 508 ▶{ no warnings 'once'; *aoh2h = \&df2h; } # true synonym
Subroutine BEGIN: called CC=1 SCAR=0.0
1337 # agg / concat / rbind -- additions to lib/Stats/LikeR.pm
1338 # Splice these in after the dropna sub. Also add agg concat rbind to
1339 # @EXPORT_OK. rbind is a true glob-alias synonym for concat.
1340  
1341 # A tied frame, as a plain copy of it; anything else, as it is. Each pass over a
1342 # tied frame -- _df_shape, _present_keys, the XS read -- FETCHes every row or
1343 # column again, so a read-only function copies it once, here, and makes its
1344 # passes over the copy. The copy holds the same row and column references.
1345 # Only for functions that leave the frame unchanged: one that writes to it
1346 # must write to the frame it was given.
1347 473 ▶sub _untied {
Subroutine _untied: called CC=5 SCAR=16.1
1348 473 my $df = shift;
1349 473 ▶ return { %$df } if ref $df eq 'HASH' && tied %$df;
Branch: 1 branch
BranchTrueFalseTotal
if ref $df eq "HASH" and tied %$df 15 458 473
Condition100%3/3
ref $df eq "HASH" and tied %$df
!ll&&!rl&&r
29216615
MC/DC100%2/2
ref $df eq "HASH" and tied %$df
ref $df eq "HASH" tied %$df
Truth table100%3/3
A and B
A= ref $df eq "HASH"B= tied %$df
ABresult
0X0
100
111
1350 458 ▶ return [ @$df ] if ref $df eq 'ARRAY' && tied @$df;
Branch: 1 branch
BranchTrueFalseTotal
if ref $df eq "ARRAY" and tied @$df 9 449 458
Condition100%3/3
ref $df eq "ARRAY" and tied @$df
!ll&&!rl&&r
1892609
MC/DC100%2/2
ref $df eq "ARRAY" and tied @$df
ref $df eq "ARRAY" tied @$df
Truth table100%3/3
A and B
A= ref $df eq "ARRAY"B= tied @$df
ABresult
0X0
100
111
1351 449 return $df;
1352 }
1353  
1354 # _df_shape($df [, $caller]) is in LikeR.xs, where its rules are written out.
1355  
1356 # agg($df, agg => { col => 'mean' | [ 'mean', 'sd', .. ] | \&code, .. }, %opts)
1357 #
1358 # Split-apply-combine over any of the four data-frame shapes. With `by` it is
1359 # the combine half of group_by (which only splits); without `by` it collapses
1360 # the whole frame to a single row, like pandas df.agg(...).
1361 #
1362 # $df : AoA | AoH | HoA | HoH. For AoA the column identifiers in `by` and in
1363 # the `agg` spec are integer positions (negative from the end); for the
1364 # other three they are column names. A column no row has dies.
1365 #
1366 # OPTIONS
1367 # agg => { col => spec, .. } REQUIRED. spec is one aggregator name, an
1368 # arrayref of names, or a coderef. Named aggregators:
1369 # mean median sum sd var min max (numeric; call the XS functions)
1370 # count number of defined (non-undef) cells
1371 # n number of cells, undef included
1372 # nunique number of distinct defined cells
1373 # first first defined cell (undef if none)
1374 # last last defined cell (undef if none)
1375 # mode modal defined cell; ties resolved deterministically
1376 # (smallest number, else lowest string)
1377 # A coderef is called as $code->(\@cells), in scalar context, with a
1378 # copy of every cell for that column in the group (undef included).
1379 # by => $col | \@cols optional grouping column(s).
1380 # skipna => 0|1 default 1. When 0, a numeric named aggregator
1381 # (mean median sum sd var min max mode) over a group with any undef
1382 # yields undef, matching pandas skipna=False; count/n/nunique/first/
1383 # last always ignore this flag.
1384 # sort => 0|1 default 1. Sort output groups by key, each
1385 # by column numerically if all its values look like numbers, else as
1386 # strings, undef last (see go_order() in LikeR.xs); 0 keeps first-seen order.
1387 # 'output_type' => aoa|aoh|hoa|hoh default: same family as $df.
1388 #
1389 # OUTPUT COLUMN ORDER is deterministic: the `by` columns in the given order,
1390 # then the aggregated columns sorted (numerically for AoA integer columns, else
1391 # as strings), each expanded over its aggregator list in the order supplied. A
1392 # column reduced by a single aggregator keeps its own name; with two or more, or
1393 # when it is also a `by` column, it becomes "<col>_<func>" (e.g. age_mean,
1394 # age_sd), a coderef's func being fn (fn1, fn2, .. for several). A name
1395 # generated twice dies, except for positional aoa output. For hoh output the row label
1396 # is the group value (multiple `by` columns joined with '.'), 'all' when there
1397 # is no grouping, and made unique with a .N suffix on collision.
1398 #
1399 # Numeric aggregators need enough defined cells or the cell is undef: mean /
1400 # median / sum / min / max need >= 1, sd / var need >= 2. Ungrouped, a frame with
1401 # no rows is still one row. The original $df is never modified. The split
1402 # is the XS _agg_split() (see the comment above ag_set in LikeR.xs), and the
1403 # combine the XS _agg_combine().
1404 {
1405 508 my %AGG_MIN = ( # minimum defined count for the XS numeric reducers
1406 mean => 1, median => 1, sum => 1, min => 1, max => 1,
1407 sd => 2, var => 2,
1408 );
1409 # the reducers an undef poisons under skipna => 0 (pandas skipna=False)
1410 508 my %AGG_NUMERIC = map { $_ => 1 } qw(mean median sum sd var min max mode);
1411 508 my %AGG_OTHER = map { $_ => 1 } qw(count n nunique first last mode);
1412 # reducers that stringify their cells: a cell they read is copied, not shared
1413 # with the caller's frame, because stringifying caches a PV on the SV
1414 508 my %AGG_STRINGIFY = ( mode => 1, nunique => 1 );
1415  
1416 # a named reducer over the defined cells $def, of which the group had $nna
1417 # more that were undef
1418 0 ▶ sub _agg_reduce_named {
Subroutine _agg_reduce_named: not called CC=22 SCAR=62.3
1419 0 my ($func, $def, $nna, $skipna) = @_;
1420 # NA policy for numeric reducers when the caller asked for skipna => 0
1421 0 ▶ return undef if !$skipna && $nna && $AGG_NUMERIC{$func};
Branch: 1 branch
BranchTrueFalseTotal
if not $skipna and $nna and $AGG_NUMERIC{$func} 0 0 0
Condition0%0/6
not $skipna and $nna and $AGG_NUMERIC{$func}
!ll&&!rl&&r
000
not $skipna and $nna
!ll&&!rl&&r
000
MC/DC0%0/3
not $skipna and $nna and $AGG_NUMERIC{$func}
not $skipna $nna $AGG_NUMERIC{$func}
Truth table0%0/4
not(A) and B and C
A= not $skipnaB= $nnaC= $AGG_NUMERIC{$func}
ABCresult
0XX0
10X0
1100
1111
1422 0 ▶ if ($func eq 'count') { return scalar @$def }
Branch: 1 branch
BranchTrueFalseTotal
if ($func eq "count") 0 0 0
1423 0 ▶ if ($func eq 'n') { return @$def + $nna }
Branch: 1 branch
BranchTrueFalseTotal
if ($func eq "n") 0 0 0
1424 0 ▶ if ($func eq 'nunique') { my %s; @s{ @$def } = (); return scalar keys %s }
Branch: 1 branch
BranchTrueFalseTotal
if ($func eq "nunique") 0 0 0
1425 0 ▶ if ($func eq 'first') { return @$def ? $def->[0] : undef }
Branch: 2 branches
BranchTrueFalseTotal
if ($func eq "first") 0 0 0
@$def ? : 0 0 0
1426 0 ▶ if ($func eq 'last') { return @$def ? $def->[-1] : undef }
Branch: 2 branches
BranchTrueFalseTotal
if ($func eq "last") 0 0 0
@$def ? : 0 0 0
1427 0 ▶ if ($func eq 'mode') {
Branch: 1 branch
BranchTrueFalseTotal
if ($func eq "mode") 0 0 0
1428 0 ▶ return undef unless @$def;
Branch: 1 branch
BranchTrueFalseTotal
unless @$def 0 0 0
1429 0 return _agg_mode($def);
1430 }
1431 0 ▶ die "agg: unknown aggregator '$func'\n" unless exists $AGG_MIN{$func};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $AGG_MIN{$func} 0 0 0
1432 0 ▶ return undef if @$def < $AGG_MIN{$func};
Branch: 1 branch
BranchTrueFalseTotal
if @$def < $AGG_MIN{$func} 0 0 0
1433 0 ▶ return mean($def) if $func eq 'mean';
Branch: 1 branch
BranchTrueFalseTotal
if $func eq "mean" 0 0 0
1434 0 ▶ return median($def) if $func eq 'median';
Branch: 1 branch
BranchTrueFalseTotal
if $func eq "median" 0 0 0
1435 0 ▶ return sum($def) if $func eq 'sum';
Branch: 1 branch
BranchTrueFalseTotal
if $func eq "sum" 0 0 0
1436 0 ▶ return sd($def) if $func eq 'sd';
Branch: 1 branch
BranchTrueFalseTotal
if $func eq "sd" 0 0 0
1437 0 ▶ return var($def) if $func eq 'var';
Branch: 1 branch
BranchTrueFalseTotal
if $func eq "var" 0 0 0
1438 0 ▶ return min($def) if $func eq 'min';
Branch: 1 branch
BranchTrueFalseTotal
if $func eq "min" 0 0 0
1439 0 ▶ return max($def) if $func eq 'max';
Branch: 1 branch
BranchTrueFalseTotal
if $func eq "max" 0 0 0
1440 }
1441  
1442 # the mode of the defined cells $def, ties going to the smallest number, or
1443 # the lowest string when any is not a number; _agg_combine() (LikeR.xs)
1444 # calls it too
1445 6 ▶ sub _agg_mode {
Subroutine _agg_mode: called CC=2 SCAR=6.9
1446 6 my @m = mode($_[0]);
1447 35 return (grep { !looks_like_number($_) } @m)
1448 ? (sort @m)[0]
1449 6 ▶ : (sort { $a <=> $b } @m)[0];
Branch: 1 branch
BranchTrueFalseTotal
grep({not &looks_like_number($_);} @m) ? : 1 5 6
1450 }
1451  
1452 323 ▶ sub agg {
Subroutine agg: called CC=51 SCAR=39.3
Pod documented
1453 323 my $df = _untied(shift);
1454 323 ▶ _usage_error('agg', 'undefined data in first position') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 2 321 323
1455 321 my $shape = _df_shape($df, 'agg');
1456 318 ▶ _usage_error('agg', 'arguments after the data frame must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 1 317 318
1457 if @_ % 2;
1458 317 my %arg = @_;
1459 317 my %known = ( agg => 1, by => 1, skipna => 1, sort => 1, 'output_type' => 1 );
1460 317 my @bad = sort grep { !$known{$_} } keys %arg;
1461 317 ▶ _usage_error('agg', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 2 315 317
1462  
1463 315 my $spec = $arg{agg};
1464 315 ▶ _usage_error('agg', "an 'agg' spec (hashref of column => aggregator) is required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" and %$spec 2 313 315
Condition66%2/3
ref $spec eq "HASH" and %$spec
!ll&&!rl&&r
20313
MC/DC50%1/2
ref $spec eq "HASH" and %$spec
ref $spec eq "HASH" %$spec
Truth table66%2/3
A and B
A= ref $spec eq "HASH"B= %$spec
ABresult
0X0
100
111
1465 unless ref $spec eq 'HASH' and %$spec;
1466  
1467 my @by = !defined $arg{by} ? ()
1468 220 : ref $arg{by} eq 'ARRAY' ? @{ $arg{by} }
1469 313 ▶ : ( $arg{by} );
Branch: 2 branches
BranchTrueFalseTotal
!defined($arg{'by'}) ? : 47 266 313
ref $arg{'by'} eq 'ARRAY' ? : 220 46 266
1470 313 ▶ _usage_error('agg', "'by' contains an undefined column") if grep { !defined } @by;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not defined $_;} @by 1 312 313
1471 312 ▶ my $skipna = exists $arg{skipna} ? ($arg{skipna} ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $arg{'skipna'} ? : 216 96 312
$arg{'skipna'} ? : 158 58 216
1472 312 ▶ my $dosort = exists $arg{sort} ? ($arg{sort} ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $arg{'sort'} ? : 2 310 312
$arg{'sort'} ? : 0 2 2
1473 312 ▶ my $otype = defined $arg{'output_type'} ? lc $arg{'output_type'}
Branch: 1 branch
BranchTrueFalseTotal
defined $arg{'output_type'} ? : 236 76 312
1474 : lc $shape;
1475 312 my %ok_otype = ( aoa => 1, aoh => 1, hoa => 1, hoh => 1 );
1476 _usage_error('agg', "output_type '$otype' isn't allowed (aoa, aoh, hoa, hoh)")
1477 312 ▶ unless $ok_otype{$otype};
Branch: 1 branch
BranchTrueFalseTotal
unless $ok_otype{$otype} 1 311 312
1478  
1479 311 my @agg_cols = keys %$spec;
1480 {
1481 311 my $all_num = !grep { !looks_like_number($_) } @agg_cols;
1482 311 ▶ @agg_cols = $all_num ? sort { $a <=> $b } @agg_cols : sort @agg_cols;
Branch: 1 branch
BranchTrueFalseTotal
$all_num ? : 61 250 311
1483 }
1484 311 ▶ if ($shape eq 'AoA') { # positions; Perl's own negative indexing
Branch: 2 branches
BranchTrueFalseTotal
if ($shape eq 'AoA') { } 62 249 311
elsif ($shape eq 'HoA') { } 74 175 249
1485 62 for my $c (@by, @agg_cols) {
1486 175 ▶ _usage_error('agg', "AoA columns are integer positions, not '$c'")
Branch: 1 branch
BranchTrueFalseTotal
unless $c =~ /\A-?[0-9]+\z/ 1 174 175
1487 unless $c =~ /\A-?[0-9]+\z/;
1488 }
1489 } elsif ($shape eq 'HoA') {
1490 74 for my $c (@by, @agg_cols) {
1491 201 ▶ die "agg: column '$c' not found\n" unless exists $df->{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $df->{$c} 2 199 201
1492 die "agg: column '$c' is not an ARRAY reference\n"
1493 199 ▶ unless ref $df->{$c} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $df->{$c} eq "ARRAY" 1 198 199
1494 }
1495 }
1496  
1497 # output plan: by-columns pass through, then each agg column with its
1498 # aggregator list contiguous. A single aggregator keeps the column name; two
1499 # or more, or a column that is also a `by` column, become "<col>_<func>". More
1500 # than one coderef on a column are numbered fn1, fn2, ..; one is just fn.
1501 307 my %is_by = map { $_ => 1 } @by;
1502 307 my (@agg_plan, @how); # [ col, [funcs], [out_names] ]; @how: _agg_split's modes
1503 307 for my $c (@agg_cols) {
1504 422 my $s = $spec->{$c};
1505 422 ▶ my @funcs = ref $s eq 'ARRAY' ? @$s : ($s);
Branch: 1 branch
BranchTrueFalseTotal
ref $s eq 'ARRAY' ? : 50 372 422
1506 422 ▶ _usage_error('agg', "empty aggregator list for column '$c'") unless @funcs;
Branch: 1 branch
BranchTrueFalseTotal
unless @funcs 2 420 422
1507 420 for my $f (@funcs) {
1508 531 ▶ next if ref $f eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $f eq "CODE" 9 522 531
1509 522 ▶ _usage_error('agg', "aggregator for column '$c' must be a name or a coderef")
Branch: 1 branch
BranchTrueFalseTotal
if not defined $f or ref $f 1 521 522
Condition66%2/3
not defined $f or ref $f
l!l&&r!l&&!r
10521
MC/DC50%1/2
not defined $f or ref $f
not defined $f ref $f
Truth table66%2/3
not(A) or B
A= not defined $fB= ref $f
ABresult
1X1
011
000
1510 if !defined $f || ref $f;
1511 _usage_error('agg', "unknown aggregator '$f'")
1512 521 ▶ unless exists $AGG_MIN{$f} || $AGG_OTHER{$f};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $AGG_MIN{$f} or $AGG_OTHER{$f} 2 519 521
Condition100%3/3
exists $AGG_MIN{$f} or $AGG_OTHER{$f}
l!l&&r!l&&!r
4111082
MC/DC100%2/2
exists $AGG_MIN{$f} or $AGG_OTHER{$f}
exists $AGG_MIN{$f} $AGG_OTHER{$f}
Truth table100%3/3
A or B
A= exists $AGG_MIN{$f}B= $AGG_OTHER{$f}
ABresult
1X1
011
000
1513 }
1514 417 my $ncode = grep { ref $_ eq 'CODE' } @funcs;
1515 417 my $ci = 0;
1516 417 ▶ my $multi = @funcs > 1 || $is_by{$c};
Condition100%3/3
@funcs > 1 || $is_by{$c}
l!l&&r!l&&!r
472368
MC/DC100%2/2
@funcs > 1 || $is_by{$c}
@funcs > 1 $is_by{$c}
Truth table100%3/3
A || B
A= @funcs > 1B= $is_by{$c}
ABresult
1X1
011
000
1517 my @names = map {
1518 417 ▶ my $l = ref $_ ne 'CODE' ? $_ : $ncode > 1 ? 'fn' . ++$ci : 'fn';
Branch: 2 branches
BranchTrueFalseTotal
ref $_ ne 'CODE' ? : 519 9 528
$ncode > 1 ? : 2 7 9
1519 528 ▶ $multi ? "${c}_${l}" : $c;
Branch: 1 branch
BranchTrueFalseTotal
$multi ? : 160 368 528
1520 } @funcs;
1521 417 push @agg_plan, [ $c, \@funcs, \@names ];
1522 528 ▶ push @how, ( grep { ref $_ eq 'CODE' } @funcs ) ? 0 # cells incl. undef, copied
Branch: 1 branch
BranchTrueFalseTotal
grep({$AGG_STRINGIFY{$_};} @funcs) ? : 23 386 409
1523 417 ▶ : ( grep { $AGG_STRINGIFY{$_} } @funcs ) ? 1 # defined cells, copied
Branch: 1 branch
BranchTrueFalseTotal
grep({ref $_ eq 'CODE';} @funcs) ? : 8 409 417
1524 : 2; # defined cells, shared
1525 }
1526 302 my @out_names = ( @by, map { @{ $_->[2] } } @agg_plan );
1527 302 ▶ if ($otype ne 'aoa') { # aoa is positional: a repeat costs nothing
Branch: 1 branch
BranchTrueFalseTotal
if ($otype ne "aoa") 285 17 302
1528 285 my (%seen, @dup);
1529 285 ▶ for my $n (@out_names) { push @dup, $n if $seen{$n}++ == 1 }
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$n}++ == 1 3 860 863
1530 285 ▶ die "agg: output column name(s) generated twice: @dup\n" if @dup;
Branch: 1 branch
BranchTrueFalseTotal
if @dup 3 282 285
1531 }
1532  
1533 # split, in XS: every row's group, and each aggregated cell dropped straight
1534 # into its group's array -- every cell for a column a coderef reads, only the
1535 # defined ones otherwise, with the undef cells counted instead
1536 my ($src, $code) = $shape eq 'AoA' ? ( $df, 3 )
1537 : $shape eq 'AoH' ? ( $df, 1 )
1538 : $shape eq 'HoA' ? ( $df, 4 )
1539 299 ▶ : ( [ @{$df}{ sort keys %$df } ], 1 ); # HoH: its rows, key order
Branch: 3 branches
BranchTrueFalseTotal
$shape eq 'AoA' ? : 61 238 299
$shape eq 'AoH' ? : 112 126 238
$shape eq 'HoA' ? : 69 57 126
1540 299 my ($groups, $seen) = @{ _agg_split($src, $code, [ @by ], [ @agg_cols ], \@how) };
1541 298 ▶ if (@$groups) { # a frame with no rows has no columns to miss
Branch: 2 branches
BranchTrueFalseTotal
if (@$groups) { } 295 3 298
elsif (not @by) { } 2 1 3
1542 295 my @all = ( @by, @agg_cols );
1543 295 for my $j (0 .. $#all) {
1544 791 ▶ die "agg: column '$all[$j]' not found\n" unless $seen->[$j];
Branch: 1 branch
BranchTrueFalseTotal
unless $seen->[$j] 5 786 791
1545 }
1546 } elsif (!@by) { # ungrouped: always one row, as pandas df.agg
1547 2 push @$groups, [ [], [ (0) x @agg_cols ], map { [] } @agg_cols ];
1548 }
1549  
1550 # combine, in XS: each group reduced, in key order when sorting, and laid
1551 # straight out in the requested shape. Up to 0.3424 this was a perl loop with
1552 # an eval around every named reducer, and its group sort ran a perl comparator.
1553 293 my %otype_code = ( aoa => 0, aoh => 1, hoa => 2, hoh => 3 ); # _agg_combine's `otype`
1554 return _agg_combine($groups, ($dosort && @by) ? 1 : 0,
1555 293 ▶ [ map { $_->[1] } @agg_plan ], \@how, $skipna, $otype_code{$otype},
Branch: 1 branch
BranchTrueFalseTotal
$dosort && @by ? : 258 35 293
Condition100%3/3
$dosort and @by
!ll&&!rl&&r
233258
MC/DC100%2/2
$dosort and @by
$dosort @by
Truth table100%3/3
A and B
A= $dosortB= @by
ABresult
0X0
100
111
1556 \@out_names, [ @by ], [ @agg_cols ]);
1557 }
1558 }
1559  
1560  
1561 # assign($df, name => \&code, name2 => \&code2, ...)
1562 #
1563 # Add (or overwrite) columns derived from existing ones, dplyr-mutate style.
1564 # Each coderef is called once per row with the row as $_ (a hashref) and also
1565 # as $_[0]; $_[1] is the 0-based row index. For HoH inputs, $_[2] is the row key.
1566 # It is called in list context on every row and returns the new cell value; a
1567 # list of more than one value from row 0 is the whole column instead.
1568 #
1569 # Works on all three data-frame shapes:
1570 # AoH [ {weight=>70, height=>1.8}, ... ] (arrayref of row hashrefs)
1571 # HoA { weight=>[70,...], height=>[1.8,...] } (hashref of column arrayrefs)
1572 # HoH { r1 => {weight=>70}, r2 => {...} } (hashref of row hashrefs)
1573 #
1574 # Pairs are applied in order, so a later column may use an earlier new one.
1575 # Modifies $df in place (lowest RAM/CPU) and returns it for chaining.
1576 # To keep the original intact, hand it a copy: assign(clone($df), ...).
1577 #
1578 # A value may also be a map_cell { ... } block (see below) for an in-place
1579 # per-cell edit of the named column, instead of a CODE ref or ready-made ARRAY.
1580 #
1581  
1582 # map_cell { ... } -- in-place per-cell transform for assign().
1583 #
1584 # Wraps a block so assign() runs it once per row with $_ aliased to a copy of
1585 # the NAMED column's current cell; the (possibly modified) $_ is stored back and
1586 # the block's return value is ignored. This makes an in-place edit read
1587 # naturally, without the "copy, substitute, return" dance a plain sub needs
1588 # (perl 5.10 has no s///r):
1589 #
1590 # assign($tbl, 'Res.' => map_cell { s/^[A-Z]:// }); # strip a leading "X:"
1591 # assign($tbl, 'Res.' => map_cell { $_ = uc }); # upper-case in place
1592 #
1593 # The row is still available as $_[0] (and the index as $_[1]) if the transform
1594 # needs a sibling column. A plain sub { ... } keeps its existing meaning
1595 # ($_ = the whole row, the return value is stored), so map_cell is purely
1596 # additive and changes nothing for existing callers.
1597 #
1598 # An undef cell is left untouched (undef in -> undef out): the block never runs
1599 # on it, so s/// and friends don't warn on uninitialized values and a missing
1600 # cell stays missing rather than becoming ''.
1601 508 ▶sub map_cell (&) {
Subroutine map_cell: called CC=2 SCAR=6.9
Pod documented
1602 19 my ($code) = @_;
1603 19 ▶ _usage_error('map_cell', 'expects a code block')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $code eq "CODE" 1 18 19
1604 unless ref $code eq 'CODE';
1605 18 return bless { code => $code }, 'Stats::LikeR::map_cell';
1606 }
1607  
1608 157 ▶sub assign {
Subroutine assign: called CC=85 SCAR=44.6
Pod documented
1609 157 my $df = shift;
1610 157 my $current_sub = (split(/::/,(caller(0))[3]))[-1];
1611 157 ▶ _usage_error($current_sub, 'first argument is undefined') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 2 155 157
1612 155 ▶ _usage_error($current_sub, 'first argument must be a data frame (AoH arrayref or HoA/HoH hashref)')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $df 6 149 155
1613 unless ref $df;
1614 149 ▶ _usage_error($current_sub, 'expected an even list of (name => value) pairs') if @_ % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 5 144 149
1615  
1616 144 my $r = ref $df;
1617 144 my $shape; # 'AoH', 'HoA' or 'HoH'
1618 144 ▶ if ($r eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if ($r eq 'ARRAY') { } 31 113 144
elsif ($r eq 'HASH') { } 113 0 113
1619 31 $shape = 'AoH';
1620 } elsif ($r eq 'HASH') {
1621 # Every value is looked at, not just the first one values() yields: a
1622 # HoA may carry scalar (or undef) entries, which the row view passes
1623 # through unchanged, and deciding on whichever value came first made the
1624 # same frame work or die from one run to the next with hash order.
1625 #
1626 # For a HoH the same pass is the row check: every value has to be a
1627 # hash, and counting them here saves a second pass over the rows, which
1628 # on 200000 rows cost 0.039s -- a fifth of the whole call.
1629 # A statement-modifier count runs in 0.013s on 200000 rows, against 0.019s
1630 # for the same test written as a loop with if/elsif.
1631 113 my %kind; # ref() of each value => how many
1632 113 $kind{ ref $_ }++ for values %$df;
1633 113 ▶ my $saw_arr = $kind{ARRAY} || 0;
Condition100%2/2
$kind{'ARRAY'} || 0
l!l
8726
MC/DC100%1/1
$kind{'ARRAY'} || 0
$kind{'ARRAY'}
Truth table100%2/2
A
A= $kind{'ARRAY'}
Aresult
11
00
1634 113 ▶ my $n_hash = $kind{HASH} || 0;
Condition100%2/2
$kind{'HASH'} || 0
l!l
2093
MC/DC100%1/1
$kind{'HASH'} || 0
$kind{'HASH'}
Truth table100%2/2
A
A= $kind{'HASH'}
Aresult
11
00
1635 113 ▶ die "$current_sub: hashref mixes array and hash values (ambiguous HoA/HoH)"
Branch: 1 branch
BranchTrueFalseTotal
if $saw_arr and $n_hash 1 112 113
Condition100%3/3
$saw_arr and $n_hash
!ll&&!rl&&r
26861
MC/DC100%2/2
$saw_arr and $n_hash
$saw_arr $n_hash
Truth table100%3/3
A and B
A= $saw_arrB= $n_hash
ABresult
0X0
100
111
1636 if $saw_arr and $n_hash;
1637 112 ▶ die "$current_sub: hashref holds no ARRAY (HoA) or HASH (HoH) values"
Branch: 1 branch
BranchTrueFalseTotal
if %$df and not $saw_arr and not $n_hash 3 109 112
Condition100%6/6
%$df and not $saw_arr and not $n_hash
!ll&&!rl&&r
90193
%$df and not $saw_arr
!ll&&!rl&&r
48622
MC/DC100%3/3
%$df and not $saw_arr and not $n_hash
%$df not $saw_arr not $n_hash
Truth table100%4/4
A and not(B) and not(C)
A= %$dfB= not $saw_arrC= not $n_hash
ABCresult
0XX0
10X0
1100
1111
1638 if %$df and not $saw_arr and not $n_hash;
1639 109 ▶ $shape = $n_hash ? 'HoH' : 'HoA'; # empty hash -> HoA
Branch: 1 branch
BranchTrueFalseTotal
$n_hash ? : 19 90 109
1640 109 ▶ if ($n_hash and @_ and $n_hash != keys %$df) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_hash and @_ and $n_hash != keys %$df) 1 108 109
Condition83%5/6
$n_hash and @_ and $n_hash != keys %$df
!ll&&!rl&&r
90181
$n_hash and @_
!ll&&!rl&&r
90019
MC/DC66%2/3
$n_hash and @_ and $n_hash != keys %$df
$n_hash @_ $n_hash != keys %$df
Truth table75%3/4
A and B and C
A= $n_hashB= @_C= $n_hash != keys %$df
ABCresult
0XX0
10X0
1100
1111
1641 # Name the first bad row in visiting (sorted) order, as the row loops would.
1642 1 for my $k (sort keys %$df) {
1643 2 ▶ die "$current_sub: row '$k' is not a hashref" unless ref $df->{$k} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $df->{$k} eq "HASH" 1 1 2
1644 }
1645 }
1646 } else {
1647 0 _usage_error($current_sub, 'data frame must be an arrayref (AoH) or hashref (HoA/HoH)');
1648 }
1649  
1650 # Row count. For a HoA it is the longest column; with no column at all yet
1651 # (an empty hash) it is undef until the first arrayref value fixes it.
1652 139 my (@rk, $n); # @rk: HoH row keys, in visiting order
1653 139 ▶ if ($shape eq 'AoH') {
Branch: 2 branches
BranchTrueFalseTotal
if ($shape eq 'AoH') { } 31 108 139
elsif ($shape eq 'HoH') { } 18 90 108
1654 31 $n = @$df;
1655 } elsif ($shape eq 'HoH') {
1656 18 @rk = sort keys %$df;
1657 18 $n = @rk;
1658 } else {
1659 90 for my $v (values %$df) {
1660 560 ▶ next unless ref $v eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $v eq "ARRAY" 452 108 560
1661 108 ▶ $n = @$v if not defined $n or @$v > $n;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $n or @$v > $n 87 21 108
Condition100%3/3
not defined $n or @$v > $n
l!l&&r!l&&!r
86121
MC/DC100%2/2
not defined $n or @$v > $n
not defined $n @$v > $n
Truth table100%3/3
not(A) or B
A= not defined $nB= @$v > $n
ABresult
1X1
011
000
1662 }
1663 }
1664  
1665 # Everything that can be checked before the first cell is written is checked
1666 # here, so that a bad row or a bad third pair cannot leave the first two
1667 # applied and the frame half-modified.
1668 139 my %hoa_col; # HoA: columns that exist by each pair
1669 139 ▶ if ($shape eq 'HoA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "HoA") 90 49 139
1670 90 $hoa_col{$_} = 1 for grep { ref $df->{$_} eq 'ARRAY' } keys %$df;
1671 }
1672 139 ▶ for (my $p = 0; $p < @_; $p += 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p < @_) 153 123 276
1673 153 my ($name, $spec) = @_[$p, $p + 1];
1674 153 my $sref = ref $spec;
1675 153 ▶ if ($sref eq 'Stats::LikeR::map_cell') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sref eq "Stats::LikeR::map_cell") 18 135 153
1676 die "$current_sub: map_cell target column '$name' must already exist as an ARRAY ref\n"
1677 18 ▶ if $shape eq 'HoA' and not $hoa_col{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "HoA" and not $hoa_col{$name} 2 16 18
Condition100%3/3
$shape eq "HoA" and not $hoa_col{$name}
!ll&&!rl&&r
792
MC/DC100%2/2
$shape eq "HoA" and not $hoa_col{$name}
$shape eq "HoA" not $hoa_col{$name}
Truth table100%3/3
A and not(B)
A= $shape eq "HoA"B= not $hoa_col{$name}
ABresult
0X0
100
111
1678 16 next;
1679 }
1680 135 ▶ _usage_error($current_sub, "value for '$name' must be a CODE or ARRAY ref")
Branch: 1 branch
BranchTrueFalseTotal
unless $sref eq "CODE" or $sref eq "ARRAY" 8 127 135
Condition100%3/3
$sref eq "CODE" or $sref eq "ARRAY"
l!l&&r!l&&!r
111168
MC/DC100%2/2
$sref eq "CODE" or $sref eq "ARRAY"
$sref eq "CODE" $sref eq "ARRAY"
Truth table100%3/3
A or B
A= $sref eq "CODE"B= $sref eq "ARRAY"
ABresult
1X1
011
000
1681 unless $sref eq 'CODE' or $sref eq 'ARRAY';
1682 127 ▶ if ($sref eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sref eq "ARRAY") 16 111 127
1683 16 ▶ $n = @$spec unless defined $n;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 2 14 16
1684 16 ▶ die "$current_sub: column '$name' has " . @$spec . " values but data frame has $n rows"
Branch: 1 branch
BranchTrueFalseTotal
unless @$spec == $n 6 10 16
1685 unless @$spec == $n;
1686 }
1687 121 ▶ $n = 0 unless defined $n; # a coderef on a column-less HoA sees no rows
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 2 119 121
1688 121 $hoa_col{$name} = 1;
1689 }
1690 123 ▶ $n = 0 unless defined $n;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 0 123 123
1691 123 ▶ if ($shape ne 'HoA' and @_) {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape ne "HoA" and @_) 39 84 123
Condition66%2/3
$shape ne "HoA" and @_
!ll&&!rl&&r
84039
MC/DC50%1/2
$shape ne "HoA" and @_
$shape ne "HoA" @_
Truth table66%2/3
A and B
A= $shape ne "HoA"B= @_
ABresult
0X0
100
111
1692 # A HoH's rows were checked by the shape scan above.
1693 39 ▶ if ($shape eq 'AoH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "AoH") 24 15 39
1694 24 for my $i (0 .. $n - 1) {
1695 54 ▶ die "$current_sub: row $i is not a hashref" unless ref $df->[$i] eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $df->[$i] eq "HASH" 4 50 54
1696 }
1697 }
1698 }
1699  
1700 # One save of $_ for the whole call; each row below only stores into it.
1701 # Assigning to the localized $_ copies the row reference, so a block that
1702 # writes to $_ changes nothing in $df.
1703 119 local $_;
1704  
1705 # A coderef is called in list context for every row, row 0 included. Row 0
1706 # used to be called in list context (to tell a whole-column return from a
1707 # per-row one) and every later row in scalar context, so any expression that
1708 # answers differently in the two -- a match with captures, a bare match, an
1709 # array -- gave row 0 one kind of value and the rest another:
1710 # sub { $_->{s} =~ /(\d+)/ } stored the digits in row 0 and 1 everywhere else.
1711 #
1712 # The store is a list assignment, (($cell) = $spec->(...)), whose value in
1713 # scalar context is how many values the call returned. That keeps list
1714 # context for the price of one comparison: on 200000 rows it ran 7% behind
1715 # the old scalar-context store, which hoisting `local $_` out of the row
1716 # loop (8%) more than pays for.
1717 2 ▶ my $too_many = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1718 2 my ($name, $got, $i) = @_;
1719 2 die "$current_sub: '$name' returned $got values for row $i; a per-row coderef "
1720 . "must return one value per row (a whole-column list is told apart on row 0)";
1721 119 };
1722  
1723 119 ▶ if ($shape ne 'HoA') { # ----- AoH / HoH -----
Branch: 1 branch
BranchTrueFalseTotal
if ($shape ne "HoA") 35 84 119
1724 35 my $is_hoh = $shape eq 'HoH';
1725 35 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 40 31 71
1726 40 my ($name, $spec) = (shift, shift);
1727 40 my $sref = ref $spec;
1728 40 ▶ if ($sref eq 'Stats::LikeR::map_cell') { # in-place per-cell edit; $_ = current cell
Branch: 1 branch
BranchTrueFalseTotal
if ($sref eq "Stats::LikeR::map_cell") 6 34 40
1729 6 my $code = $spec->{code};
1730 6 for my $i (0 .. $n - 1) {
1731 15 ▶ my $row = $is_hoh ? $df->{ $rk[$i] } : $df->[$i];
Branch: 1 branch
BranchTrueFalseTotal
$is_hoh ? : 7 8 15
1732 15 $_ = $row->{$name};
1733 15 ▶ next unless defined $_; # undef cells pass through untouched (undef in -> undef out)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 4 11 15
1734 11 ▶ $is_hoh ? $code->($row, $i, $rk[$i]) : $code->($row, $i);
Branch: 1 branch
BranchTrueFalseTotal
$is_hoh ? : 5 6 11
1735 11 $row->{$name} = $_;
1736 }
1737 6 next;
1738 }
1739 34 ▶ if ($sref eq 'ARRAY') { # ready-made column
Branch: 1 branch
BranchTrueFalseTotal
if ($sref eq "ARRAY") 3 31 34
1740 3 ▶ if ($is_hoh) { $df->{ $rk[$_] }{$name} = $spec->[$_] for 0 .. $n - 1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($is_hoh) { } 1 2 3
1741 2 else { $df->[$_]{$name} = $spec->[$_] for 0 .. $n - 1 }
1742 3 next;
1743 }
1744 31 ▶ next unless $n; # empty frame: nothing to compute
Branch: 1 branch
BranchTrueFalseTotal
unless $n 1 30 31
1745  
1746 30 ▶ my $row0 = $is_hoh ? $df->{ $rk[0] } : $df->[0];
Branch: 1 branch
BranchTrueFalseTotal
$is_hoh ? : 13 17 30
1747 30 $_ = $row0;
1748 30 ▶ my @out = $is_hoh ? $spec->($row0, 0, $rk[0]) : $spec->($row0, 0);
Branch: 1 branch
BranchTrueFalseTotal
$is_hoh ? : 13 17 30
1749 30 ▶ if (@out > 1) { # whole-column list (e.g. rank())
Branch: 1 branch
BranchTrueFalseTotal
if (@out > 1) 6 24 30
1750 6 ▶ die "$current_sub: column '$name' produced " . @out . " values but data frame has $n rows"
Branch: 1 branch
BranchTrueFalseTotal
unless @out == $n 2 4 6
1751 unless @out == $n;
1752 4 ▶ if ($is_hoh) { $df->{ $rk[$_] }{$name} = $out[$_] for 0 .. $n - 1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($is_hoh) { } 2 2 4
1753 2 else { $df->[$_]{$name} = $out[$_] for 0 .. $n - 1 }
1754 4 next;
1755 }
1756 24 $row0->{$name} = $out[0]; # per-row: row 0 already computed
1757 # Two copies of the loop so the hot path does not test $is_hoh per row.
1758 24 ▶ if ($is_hoh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_hoh) { } 10 14 24
1759 10 for my $i (1 .. $n - 1) {
1760 11 my $row = $df->{ $rk[$i] };
1761 11 $_ = $row;
1762 11 my $got = (($row->{$name}) = $spec->($row, $i, $rk[$i]));
1763 11 ▶ $too_many->($name, $got, $i) if $got > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $got > 1 1 10 11
1764 }
1765 } else {
1766 14 for my $i (1 .. $n - 1) {
1767 20 my $row = $df->[$i];
1768 20 $_ = $row;
1769 20 my $got = (($row->{$name}) = $spec->($row, $i));
1770 20 ▶ $too_many->($name, $got, $i) if $got > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $got > 1 1 19 20
1771 }
1772 }
1773 }
1774 31 return $df;
1775 }
1776  
1777 # ----- HoA -----
1778 # The block sees each row as a hash built from the columns. Array columns
1779 # supply cell $i; any other value (a scalar, undef) is passed through as is.
1780 #
1781 # _hoa_assign (LikeR.xs) runs the loop with one view whose values alias the
1782 # frame's cells, so a write through $_->{col} lands in the frame, as it does
1783 # for an AoH or HoH. A tied frame or column keeps the perl loop below, which
1784 # hands the block copies: aliasing a tied element would alias the proxy SV
1785 # FETCH returns, not the element.
1786 my $tied = tied(%$df)
1787 84 ▶ || grep { ref $df->{$_} eq 'ARRAY' and tied @{ $df->{$_} } } keys %$df;
Condition83%5/6
tied %$df || grep({ref $df->{$_} eq 'ARRAY' and tied @{$$df{$_};};} keys %$df)
l!l&&r!l&&!r
0381
ref $df->{$_} eq 'ARRAY' && tied @{$$df{$_};}
!ll&&!rl&&r
4521013
MC/DC50%1/2
tied %$df || grep({ref $df->{$_} eq 'ARRAY' and tied @{$$df{$_};};} keys %$df)
tied %$df grep({ref $df->{$_} eq 'ARRAY' and tied @{$$df{$_};};} keys %$df)
MC/DC100%2/2
ref $df->{$_} eq 'ARRAY' && tied @{$$df{$_};}
ref $df->{$_} eq 'ARRAY' tied @{$$df{$_};}
Truth table66%2/3
A || B
A= tied %$dfB= grep({ref $df->{$_} eq 'ARRAY' and tied @{$$df{$_};};} keys %$df)
ABresult
1X1
011
000
Truth table100%3/3
A && B
A= ref $df->{$_} eq 'ARRAY'B= tied @{$$df{$_};}
ABresult
0X0
100
111
1788 3 ▶ my $snapshot = sub {
Subroutine __ANON__: called CC=3 SCAR=11.6
1789 3 my (@akeys, @acols, @skeys, @svals);
1790 3 for my $k (keys %$df) {
1791 5 my $c = $df->{$k};
1792 5 ▶ if (ref $c eq 'ARRAY') { push @akeys, $k; push @acols, $c }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $c eq 'ARRAY') { } 5 0 5
1793 0 else { push @skeys, $k; push @svals, $c }
1794 }
1795 3 return (\@akeys, \@acols, \@skeys, \@svals);
1796 84 };
1797 84 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 88 81 169
1798 88 my ($name, $spec) = (shift, shift);
1799 88 my $sref = ref $spec;
1800 88 ▶ if ($sref eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sref eq "ARRAY") 4 84 88
1801 4 $df->{$name} = [ @$spec ]; # copied, so the caller's array stays theirs
1802 4 next;
1803 }
1804 84 ▶ if (not $n and $sref eq 'CODE') { $df->{$name} = []; next }
Branch: 1 branch
BranchTrueFalseTotal
if (not $n and $sref eq "CODE") 2 82 84
Condition66%2/3
not $n and $sref eq "CODE"
!ll&&!rl&&r
8202
MC/DC50%1/2
not $n and $sref eq "CODE"
not $n $sref eq "CODE"
Truth table66%2/3
not(A) and B
A= not $nB= $sref eq "CODE"
ABresult
0X0
100
111
1805  
1806 82 ▶ if (not $tied) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tied) 79 3 82
1807 79 ▶ if ($sref eq 'Stats::LikeR::map_cell') {
Branch: 1 branch
BranchTrueFalseTotal
if ($sref eq "Stats::LikeR::map_cell") 7 72 79
1808 7 _hoa_assign($df, $name, $spec->{code}, $n, 1);
1809 7 next;
1810 }
1811 72 my ($whole, $col) = _hoa_assign($df, $name, $spec, $n, 0);
1812 70 ▶ die "$current_sub: column '$name' produced " . @$col . " values but data frame has $n rows"
Branch: 1 branch
BranchTrueFalseTotal
if $whole and @$col != $n 1 69 70
Condition100%3/3
$whole and @$col != $n
!ll&&!rl&&r
6721
MC/DC100%2/2
$whole and @$col != $n
$whole @$col != $n
Truth table100%3/3
A and B
A= $wholeB= @$col != $n
ABresult
0X0
100
111
1813 if $whole and @$col != $n;
1814 69 $df->{$name} = $col;
1815 69 next;
1816 }
1817  
1818 # The perl loop, for a tied frame only (see $tied above).
1819 3 my ($akeys, $acols, $skeys, $svals) = $snapshot->();
1820 3 ▶ if ($sref eq 'Stats::LikeR::map_cell') { # in-place per-cell edit; $_ = current cell
Branch: 1 branch
BranchTrueFalseTotal
if ($sref eq "Stats::LikeR::map_cell") 2 1 3
1821 2 my $code = $spec->{code};
1822 2 my $tgt = $df->{$name};
1823 # One row view, refilled per row, and only for the rows the block
1824 # will actually see.
1825 #
1826 # Assembling it was the whole cost of the call: on a 64-column frame
1827 # of 20000 rows, a target column that is entirely undef -- so the
1828 # block never runs once -- still took 0.161s of the 0.165s a full
1829 # pass took, every bit of it spent building views that were then
1830 # thrown away unread, because the "is this cell undef" test sat after
1831 # the build instead of before it.
1832 #
1833 # The key set is the same for every row, so the hash is refilled
1834 # rather than reallocated. The block therefore sees one hash for the
1835 # whole pass instead of a fresh one per row, which is the shape the
1836 # other two frame layouts already have: the AoH and HoH branches above
1837 # hand the block the row hash itself, not a copy of it.
1838 2 my %view;
1839 2 for my $i (0 .. $n - 1) {
1840 6 $_ = $tgt->[$i];
1841 6 ▶ next unless defined $_; # undef cells pass through untouched (undef in -> undef out)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 3 3 6
1842 3 @view{@$akeys} = map { $_->[$i] } @$acols;
1843 3 @view{@$skeys} = @$svals;
1844 3 $code->(\%view, $i);
1845 3 $tgt->[$i] = $_;
1846 }
1847 2 next;
1848 }
1849  
1850 # Unlike the map_cell view above, this one is a fresh hash every row:
1851 # a plain coderef may keep the hash it is given (return it, push it
1852 # somewhere), and a reused one would then change under it.
1853 1 my %v0;
1854 1 @v0{@$akeys} = map { $_->[0] } @$acols;
1855 1 @v0{@$skeys} = @$svals;
1856 1 $_ = \%v0;
1857 1 my @out = $spec->(\%v0, 0);
1858 1 ▶ if (@out > 1) { # whole-column list
Branch: 1 branch
BranchTrueFalseTotal
if (@out > 1) 0 1 1
1859 0 ▶ die "$current_sub: column '$name' produced " . @out . " values but data frame has $n rows"
Branch: 1 branch
BranchTrueFalseTotal
unless @out == $n 0 0 0
1860 unless @out == $n;
1861 0 $df->{$name} = \@out; # @out is this pair's own array: no second copy
1862 0 next;
1863 }
1864 1 my @new;
1865 1 $#new = $n - 1; # preallocate
1866 1 $new[0] = $out[0];
1867 1 for my $i (1 .. $n - 1) {
1868 2 my %view;
1869 2 @view{@$akeys} = map { $_->[$i] } @$acols;
1870 2 @view{@$skeys} = @$svals;
1871 2 $_ = \%view;
1872 2 my $got = (($new[$i]) = $spec->(\%view, $i));
1873 2 ▶ $too_many->($name, $got, $i) if $got > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $got > 1 0 2 2
1874 }
1875 1 $df->{$name} = \@new;
1876 }
1877 81 return $df;
1878 }
1879  
1880 22 ▶sub chunk {
Subroutine chunk: called CC=15 SCAR=27.1
Pod documented
1881 22 my ($aref, @rest) = @_;
1882 22 ▶ _usage_error('chunk', 'first argument must be an ARRAY reference')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $aref eq "ARRAY" 4 18 22
1883 unless ref $aref eq 'ARRAY';
1884 # Own the message for an odd argument list. Falling straight into a hash
1885 # assignment left perl to report it, and under `warnings FATAL => 'all'`
1886 # chunk($aref, 2) died as "Odd number of elements in hash assignment at
1887 # LikeR.pm line 1686" -- naming neither chunk nor the option it wanted.
1888 18 ▶ _usage_error('chunk', 'arguments after the array reference must be name => value '
Branch: 1 branch
BranchTrueFalseTotal
if @rest % 2 2 16 18
1889 . 'pairs; pass exactly one of size => N or parts => K')
1890 if @rest % 2;
1891 16 my %opt = @rest;
1892  
1893 _usage_error('chunk', 'pass exactly one of size => N or parts => K')
1894 if (defined $opt{size} && defined $opt{parts})
1895 16 ▶ || (!defined $opt{size} && !defined $opt{parts});
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{"size"} and defined $opt{"parts"} or not defined $opt{"size"} || defined $opt{"parts"} 3 13 16
Condition100%9/9
defined $opt{"size"} and defined $opt{"parts"} or not defined $opt{"size"} || defined $opt{"parts"}
l!l&&r!l&&!r
1213
defined $opt{"size"} and defined $opt{"parts"}
!ll&&!rl&&r
871
defined $opt{'size'} || defined $opt{'parts'}
l!l&&r!l&&!r
762
MC/DC75%3/4
defined $opt{"size"} and defined $opt{"parts"} or not defined $opt{"size"} || defined $opt{"parts"}
defined $opt{"size"} defined $opt{"parts"} defined $opt{'size'} defined $opt{'parts'}
Truth table57%4/7
A and B or not(C || D)
A= defined $opt{"size"}B= defined $opt{"parts"}C= defined $opt{'size'}D= defined $opt{'parts'}
ABCDresult
11XX1
0X001
10001
0X1X0
0X010
101X0
10010
1896  
1897 13 my $n = scalar @$aref;
1898 13 my @groups;
1899 # Validated before the empty-input return, so a bad option is refused for [] too.
1900 13 for my $o (qw(size parts)) {
1901 _usage_error('chunk', "$o must be a positive integer")
1902 24 ▶ if defined $opt{$o} && $opt{$o} !~ /\A[1-9][0-9]*\z/;
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{$o} and not $opt{$o} =~ /\A[1-9][0-9]*\z/ 4 20 24
Condition100%3/3
defined $opt{$o} and not $opt{$o} =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
1194
MC/DC100%2/2
defined $opt{$o} and not $opt{$o} =~ /\A[1-9][0-9]*\z/
defined $opt{$o} not $opt{$o} =~ /\A[1-9][0-9]*\z/
Truth table100%3/3
A and not(B)
A= defined $opt{$o}B= not $opt{$o} =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
1903 }
1904 # Empty input has no groups. Returning @groups rather than () keeps scalar
1905 # context a count (0), as it is for non-empty input, not undef.
1906 9 ▶ return @groups unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 2 7 9
1907  
1908 7 ▶ if (defined $opt{size}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt{'size'}) { } 4 3 7
1909 4 my $sz = $opt{size};
1910 4 ▶ for (my $i = 0; $i < $n; $i += $sz) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $n) 15 4 19
1911 15 my $hi = $i + $sz - 1;
1912 15 ▶ $hi = $n - 1 if $hi > $n - 1;
Branch: 1 branch
BranchTrueFalseTotal
if $hi > $n - 1 3 12 15
1913 15 push @groups, [ @{$aref}[$i .. $hi] ];
1914 }
1915 } else {
1916 3 my $k = $opt{parts};
1917 3 for my $i (0 .. $k - 1) {
1918 15 my $lo = int( $i * $n / $k );
1919 15 my $hi = int( ($i + 1) * $n / $k );
1920 15 push @groups, [ @{$aref}[$lo .. $hi - 1] ];
1921 }
1922 }
1923 7 return @groups;
1924 }
1925  
1926 # A caller's qr//, as one the match operator can be handed on any perl.
1927 #
1928 # Before perl 5.18, `$x =~ $rx` with an empty $rx -- qr//, qr//i, or a qr/$s/
1929 # of an empty $s -- does not match the empty string: pp_match() swaps in the
1930 # last pattern that matched successfully, whatever it was. This prints 1 on
1931 # 5.10.1, 5.12.5 and 5.16.3 (only "bob" holds a b) and 3 on 5.18.4 and later:
1932 # perl -e 'my $rx = qr//; "abc" =~ /b/;
1933 # print scalar(grep { $_ =~ $rx } qw(NPI name bob)), "\n"'
1934 # read_table(drop_cols => qr//) failed t/read_table.drop_cols.t 923-930 on
1935 # those three perls for it, leaving out no column where it should have left
1936 # out every one. An empty pattern matches every string under any flags, so it
1937 # is exchanged for one that says so in a pattern that is not empty.
1938 #
1939 # The exchange compiles nothing: re::regexp_pattern() (in perl's core since
1940 # 5.10.0, with no `use re`) reads the pattern text, and $RX_EVERY is evaluated
1941 # once, when the module loads. Wrapping every pattern as qr/(?:$rx)/ would
1942 # evaluate a qr// on each call instead, which leaks an SV on perl 5.10.0
1943 # (pp_qr()) and inversion lists on 5.32 (regcomp), inside the callers'
1944 # no_leaks_ok checks.
1945 508 my $RX_EVERY = qr/(?:)/;
1946 1117 ▶sub _rx_for_match {
Subroutine _rx_for_match: called CC=3 SCAR=11.0
1947 1117 my ($rx) = @_;
1948 1117 my ($text) = re::regexp_pattern($rx);
1949 1117 ▶ return defined $text && $text eq '' ? $RX_EVERY : $rx;
Branch: 1 branch
BranchTrueFalseTotal
defined $text && $text eq '' ? : 142 975 1117
Condition66%2/3
defined $text and $text eq ""
!ll&&!rl&&r
0975142
MC/DC50%1/2
defined $text and $text eq ""
defined $text $text eq ""
Truth table66%2/3
A and B
A= defined $textB= $text eq ""
ABresult
0X0
100
111
1950 }
1951  
1952 # filter DSL: col() builds a predicate via overloading (pure Perl)
1953 # col('name') returns an overloaded object; comparing it (col('age') >= 18) or
1954 # combining comparisons with & | ! builds a predicate that carries its per-row
1955 # test in a {code} closure, and -- when C can reproduce it exactly -- in a
1956 # {plan} that filter() (XS) compiles and runs without calling the closure.
1957 #
1958 # Rules: numeric ops > < >= <= == != compare as numbers; string ops gt lt ge le
1959 # eq ne compare as strings; & | ! combine; operands may be in either order; a
1960 # missing/undef cell (and, for numeric ops, a non-numeric cell) never matches.
1961 #
1962 # Every predicate also carries {cols}, the distinct column names it reads, in
1963 # the order they first appear. filter() checks them against the frame before
1964 # testing a row, so a misspelt column dies instead of quietly keeping nothing
1965 # (or, under !, everything).
1966 279 ▶sub col { Stats::LikeR::col::_new(@_) }
Subroutine col: called CC=1 SCAR=0.0
Pod documented
1967 {
1968 package Stats::LikeR::col;
1969 508 ▶ use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
1970 508 ▶ use Scalar::Util qw(blessed looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
1971 use overload
1972 118 ▶ '>' => sub { _num($_[0], '>', $_[1], $_[2]) },
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
1973 14 ▶ '<' => sub { _num($_[0], '<', $_[1], $_[2]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1974 17 ▶ '>=' => sub { _num($_[0], '>=', $_[1], $_[2]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1975 7 ▶ '<=' => sub { _num($_[0], '<=', $_[1], $_[2]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1976 15 ▶ '==' => sub { _num($_[0], '==', $_[1], $_[2]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1977 5 ▶ '!=' => sub { _num($_[0], '!=', $_[1], $_[2]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1978 4 ▶ 'gt' => sub { _str($_[0], 'gt', $_[1], $_[2]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1979 7 ▶ 'lt' => sub { _str($_[0], 'lt', $_[1], $_[2]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1980 3 ▶ 'ge' => sub { _str($_[0], 'ge', $_[1], $_[2]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1981 3 ▶ 'le' => sub { _str($_[0], 'le', $_[1], $_[2]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1982 25 ▶ 'eq' => sub { _str($_[0], 'eq', $_[1], $_[2]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1983 5 ▶ 'ne' => sub { _str($_[0], 'ne', $_[1], $_[2]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1984 20 ▶ '&' => sub { _logic($_[0], '&', $_[1]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1985 14 ▶ '|' => sub { _logic($_[0], '|', $_[1]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1986 13 ▶ '!' => sub { _not($_[0]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1987 1 ▶ '""' => sub { 'Stats::LikeR::col predicate' },
Subroutine __ANON__: called CC=1 SCAR=0.0
1988 # A predicate has no truth value of its own. Up to 0.3216 this returned
1989 # 1, so col('a') > 1 && col('b') > 2 -- && and || test their left
1990 # operand for truth -- quietly became just col('b') > 2.
1991 5 ▶ 'bool' => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1992 5 die "col(): a predicate has no truth value; combine predicates with & | ! "
1993 . "(not && || and or), e.g. (col('x') > 0) & (col('y') < 5)\n";
1994 },
1995 508 fallback => 0;
1996  
1997 279 ▶ sub _new {
Subroutine _new: called CC=3 SCAR=11.0
1998 279 my ($name) = @_;
1999 279 ▶ Stats::LikeR::_usage_error('col', 'expects a single column name') if !defined($name) || ref $name;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $name or ref $name 5 274 279
Condition100%3/3
not defined $name or ref $name
l!l&&r!l&&!r
41274
MC/DC100%2/2
not defined $name or ref $name
not defined $name ref $name
Truth table100%3/3
not(A) or B
A= not defined $nameB= ref $name
ABresult
1X1
011
000
2000 274 return bless { name => $name }, __PACKAGE__;
2001 }
2002  
2003 # The operand of a comparison may not be another column: up to 0.3216
2004 # col('x') > col('y') compared every cell with the col object, whose own
2005 # overloaded > returned a (true) predicate, and so kept every numeric row.
2006 223 ▶ sub _literal {
Subroutine _literal: called CC=3 SCAR=11.1
2007 223 my ($op, $other) = @_;
2008 223 ▶ die "col(): '$op' compares a column with a value, not with another column; "
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($other) and $other->isa(__PACKAGE__) 12 211 223
Condition66%2/3
builtin::blessed($other) and $other->isa(__PACKAGE__)
!ll&&!rl&&r
211012
MC/DC50%1/2
builtin::blessed($other) and $other->isa(__PACKAGE__)
builtin::blessed($other) $other->isa(__PACKAGE__)
Truth table66%2/3
A and B
A= builtin::blessed($other)B= $other->isa(__PACKAGE__)
ABresult
0X0
100
111
2009 . "use a sub, e.g. sub { \$_->{x} $op \$_->{y} }\n"
2010 if blessed($other) && $other->isa(__PACKAGE__);
2011 }
2012  
2013 # the distinct names in two {cols} lists, first appearance first
2014 44 ▶ sub _cols_union {
Subroutine _cols_union: called CC=2 SCAR=7.0
2015 44 my %seen;
2016 44 ▶ return [ grep { !$seen{$_}++ } map { @{ $_ || [] } } @_ ];
Condition50%1/2
$_ || []
l!l
760
MC/DC0%0/1
$_ || []
$_
Truth table50%1/2
A
A= $_
Aresult
11
00
2017 }
2018  
2019 my %NUM = (
2020 659 ▶ '>' => sub { $_[0] > $_[1] }, '<' => sub { $_[0] < $_[1] },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
2021 249 ▶ '>=' => sub { $_[0] >= $_[1] }, '<=' => sub { $_[0] <= $_[1] },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
2022 154 ▶ '==' => sub { $_[0] == $_[1] }, '!=' => sub { $_[0] != $_[1] },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
2023 508 );
2024 my %STR = (
2025 141 ▶ 'gt' => sub { $_[0] gt $_[1] }, 'lt' => sub { $_[0] lt $_[1] },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
2026 71 ▶ 'ge' => sub { $_[0] ge $_[1] }, 'le' => sub { $_[0] le $_[1] },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
2027 275 ▶ 'eq' => sub { $_[0] eq $_[1] }, 'ne' => sub { $_[0] ne $_[1] },
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
2028 508 );
2029  
2030 # Besides the closure, a comparison carries a {plan}: the same test written
2031 # as plain data, which filter() (XS) compiles and runs in C, so a whole
2032 # frame can be tested without building a row hash or entering perl once per
2033 # row. The plan is [ KIND, OP, column, literal, swap ] for a comparison and
2034 # [ KIND, left, right ] / [ KIND, operand ] for & | !. KIND and OP are the
2035 # small integers LikeR.xs knows (FLTP_*/FLTC_*); the operator ids below are
2036 # positional, so the two tables must keep this order.
2037 #
2038 # A plan is only built for what C can reproduce exactly: the literal must be
2039 # a defined non-reference (and, for a numeric test, numeric), which rules
2040 # out overloaded objects and the warnings a non-numeric operand raises.
2041 # Everything else -- ->match/->nomatch, an object operand, any expression
2042 # with such a part in it -- carries no plan and takes the closure path, so
2043 # the two paths never disagree about a row.
2044 508 my $P_NUM = 0; my $P_STR = 1; my $P_AND = 2; my $P_OR = 3; my $P_NOT = 4;
2045 508 my %NUM_ID = ('>' => 0, '<' => 1, '>=' => 2, '<=' => 3, '==' => 4, '!=' => 5);
2046 508 my %STR_ID = ('gt' => 0, 'lt' => 1, 'ge' => 2, 'le' => 3, 'eq' => 4, 'ne' => 5);
2047  
2048 # numeric comparison: undef OR non-numeric cells never match
2049 176 ▶ sub _num {
Subroutine _num: called CC=8 SCAR=20.8
2050 176 my ($self, $op, $other, $swap) = @_;
2051 176 my $name = $self->{name};
2052 176 ▶ die "col(): the '$op' comparison must start from a bare column, e.g. col('x') $op ...\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 176 176
2053 unless defined $name;
2054 176 _literal($op, $other);
2055 170 my $f = $NUM{$op};
2056 my $code = $swap
2057 174 ▶ ? sub { my $c = $_[0]{$name}; (defined($c) && looks_like_number($c)) ? ($f->($other, $c) ? 1 : 0) : 0 }
Subroutine __ANON__: called CC=4 SCAR=13.9
Branch: 2 branches
BranchTrueFalseTotal
defined $c && &looks_like_number($c) ? : 131 43 174
&$f($other, $c) ? : 72 59 131
Condition100%3/3
defined $c and &looks_like_number($c)
!ll&&!rl&&r
1528131
MC/DC100%2/2
defined $c and &looks_like_number($c)
defined $c &looks_like_number($c)
Truth table100%3/3
A and B
A= defined $cB= &looks_like_number($c)
ABresult
0X0
100
111
2058 170 ▶ : sub { my $c = $_[0]{$name}; (defined($c) && looks_like_number($c)) ? ($f->($c, $other) ? 1 : 0) : 0 };
Subroutine __ANON__: called CC=4 SCAR=13.9
Branch: 3 branches
BranchTrueFalseTotal
$swap ? : 8 162 170
defined $c && &looks_like_number($c) ? : 1248 260 1508
&$f($c, $other) ? : 575 673 1248
Condition100%3/3
defined $c and &looks_like_number($c)
!ll&&!rl&&r
911691248
MC/DC100%2/2
defined $c and &looks_like_number($c)
defined $c &looks_like_number($c)
Truth table100%3/3
A and B
A= defined $cB= &looks_like_number($c)
ABresult
0X0
100
111
2059 my $plan = (defined($other) && !ref($other) && looks_like_number($other))
2060 170 ▶ ? [ $P_NUM, $NUM_ID{$op}, $name, $other, ($swap ? 1 : 0) ] : undef;
Branch: 2 branches
BranchTrueFalseTotal
defined $other && !ref($other) && &looks_like_number($other) ? : 167 3 170
$swap ? : 8 159 167
Condition100%6/6
defined $other and not ref $other and &looks_like_number($other)
!ll&&!rl&&r
21167
defined $other and not ref $other
!ll&&!rl&&r
11168
MC/DC100%3/3
defined $other and not ref $other and &looks_like_number($other)
defined $other not ref $other &looks_like_number($other)
Truth table100%4/4
A and not(B) and C
A= defined $otherB= not ref $otherC= &looks_like_number($other)
ABCresult
0XX0
10X0
1100
1111
2061 170 ▶ return bless { code => $code, cols => [ $name ], ($plan ? (plan => $plan) : ()) }, __PACKAGE__;
Branch: 1 branch
BranchTrueFalseTotal
$plan ? : 167 3 170
2062 }
2063  
2064 # string comparison: undef cells never match
2065 47 ▶ sub _str {
Subroutine _str: called CC=7 SCAR=19.7
2066 47 my ($self, $op, $other, $swap) = @_;
2067 47 my $name = $self->{name};
2068 47 ▶ die "col(): the '$op' comparison must start from a bare column, e.g. col('x') $op ...\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 47 47
2069 unless defined $name;
2070 47 _literal($op, $other);
2071 41 my $f = $STR{$op};
2072 my $code = $swap
2073 77 ▶ ? sub { my $c = $_[0]{$name}; defined($c) ? ($f->($other, $c) ? 1 : 0) : 0 }
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 2 branches
BranchTrueFalseTotal
defined $c ? : 70 7 77
&$f($other, $c) ? : 49 21 70
2074 41 ▶ : sub { my $c = $_[0]{$name}; defined($c) ? ($f->($c, $other) ? 1 : 0) : 0 };
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 3 branches
BranchTrueFalseTotal
$swap ? : 1 40 41
defined $c ? : 684 59 743
&$f($c, $other) ? : 285 399 684
2075 my $plan = (defined($other) && !ref($other))
2076 41 ▶ ? [ $P_STR, $STR_ID{$op}, $name, $other, ($swap ? 1 : 0) ] : undef;
Branch: 2 branches
BranchTrueFalseTotal
defined $other && !ref($other) ? : 41 0 41
$swap ? : 1 40 41
Condition33%1/3
defined $other and not ref $other
!ll&&!rl&&r
0041
MC/DC0%0/2
defined $other and not ref $other
defined $other not ref $other
Truth table33%1/3
A and not(B)
A= defined $otherB= not ref $other
ABresult
0X0
100
111
2077 41 ▶ return bless { code => $code, cols => [ $name ], ($plan ? (plan => $plan) : ()) }, __PACKAGE__;
Branch: 1 branch
BranchTrueFalseTotal
$plan ? : 41 0 41
2078 }
2079  
2080 34 ▶ sub _logic {
Subroutine _logic: called CC=10 SCAR=23.1
2081 34 my ($self, $op, $other) = @_;
2082 34 my $lc = $self->{code};
2083 34 ▶ die "col(): the left operand of '$op' is not a comparison (build it like (col('x') > 0))\n"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $lc eq "CODE" 1 33 34
2084 unless ref $lc eq 'CODE';
2085 33 ▶ my $rc = (blessed($other) && $other->isa(__PACKAGE__)) ? $other->{code} : undef;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($other) && $other->isa(__PACKAGE__) ? : 33 0 33
Condition33%1/3
builtin::blessed($other) and $other->isa(__PACKAGE__)
!ll&&!rl&&r
0033
MC/DC0%0/2
builtin::blessed($other) and $other->isa(__PACKAGE__)
builtin::blessed($other) $other->isa(__PACKAGE__)
Truth table33%1/3
A and B
A= builtin::blessed($other)B= $other->isa(__PACKAGE__)
ABresult
0X0
100
111
2086 33 ▶ die "col(): the right operand of '$op' must be a col() comparison too\n"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rc eq "CODE" 1 32 33
2087 unless ref $rc eq 'CODE';
2088 my $code = $op eq '&'
2089 270 ▶ ? sub { ($lc->($_[0]) && $rc->($_[0])) ? 1 : 0 }
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
&$lc($_[0]) && &$rc($_[0]) ? : 82 188 270
Condition100%3/3
&$lc($_[0]) and &$rc($_[0])
!ll&&!rl&&r
1622682
MC/DC100%2/2
&$lc($_[0]) and &$rc($_[0])
&$lc($_[0]) &$rc($_[0])
Truth table100%3/3
A and B
A= &$lc($_[0])B= &$rc($_[0])
ABresult
0X0
100
111
2090 32 ▶ : sub { ($lc->($_[0]) || $rc->($_[0])) ? 1 : 0 };
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 2 branches
BranchTrueFalseTotal
$op eq '&' ? : 18 14 32
&$lc($_[0]) || &$rc($_[0]) ? : 61 117 178
Condition100%3/3
&$lc($_[0]) or &$rc($_[0])
l!l&&r!l&&!r
4417117
MC/DC100%2/2
&$lc($_[0]) or &$rc($_[0])
&$lc($_[0]) &$rc($_[0])
Truth table100%3/3
A or B
A= &$lc($_[0])B= &$rc($_[0])
ABresult
1X1
011
000
2091 my $plan = ($self->{plan} && $other->{plan})
2092 32 ▶ ? [ ($op eq '&' ? $P_AND : $P_OR), $self->{plan}, $other->{plan} ] : undef;
Branch: 2 branches
BranchTrueFalseTotal
$self->{'plan'} && $other->{'plan'} ? : 26 6 32
$op eq '&' ? : 13 13 26
Condition100%3/3
$self->{"plan"} and $other->{"plan"}
!ll&&!rl&&r
5126
MC/DC100%2/2
$self->{"plan"} and $other->{"plan"}
$self->{"plan"} $other->{"plan"}
Truth table100%3/3
A and B
A= $self->{"plan"}B= $other->{"plan"}
ABresult
0X0
100
111
2093 32 ▶ return bless { code => $code, cols => _cols_union($self->{cols}, $other->{cols}),
Branch: 1 branch
BranchTrueFalseTotal
$plan ? : 26 6 32
2094 ($plan ? (plan => $plan) : ()) }, __PACKAGE__;
2095 }
2096  
2097 13 ▶ sub _not {
Subroutine _not: called CC=4 SCAR=13.9
2098 13 my ($self) = @_;
2099 13 my $c = $self->{code};
2100 13 ▶ die "col(): the operand of '!' is not a comparison (build it like !(col('x') > 0))\n"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $c eq "CODE" 1 12 13
2101 unless ref $c eq 'CODE';
2102 12 ▶ my $plan = $self->{plan} ? [ $P_NOT, $self->{plan} ] : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'plan'} ? : 8 4 12
2103 12 ▶ return bless { code => sub { $c->($_[0]) ? 0 : 1 }, cols => _cols_union($self->{cols}),
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 2 branches
BranchTrueFalseTotal
$plan ? : 8 4 12
&$c($_[0]) ? : 107 86 193
2104 ($plan ? (plan => $plan) : ()) }, __PACKAGE__;
2105 }
2106  
2107 # regex predicates. Perl cannot overload =~, so col('x') =~ /re/ can never
2108 # be intercepted; these methods give the same deferred, composable predicate
2109 # instead. The pattern is a qr// or a string (compiled with qr//); an undef
2110 # cell never matches (mirroring the string comparisons).
2111 # filter($df, col('id')->match(qr/^5iz/));
2112 # filter($df, col('id')->nomatch('^5iz')); # string pattern ok
2113 # filter($df, col('id')->match(qr/^5iz/) & (col('res') < 2.5));
2114 33 ▶ sub _match {
Subroutine _match: called CC=4 SCAR=13.9
2115 33 my ($self, $re, $want, $how) = @_;
2116 die "col(): ->$how must start from a bare column, e.g. col('x')->$how(qr/.../)\n"
2117 33 ▶ unless defined $self->{name};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"name"} 1 32 33
2118 32 ▶ die "col(): ->$how needs a pattern (a qr// or a string)\n" unless defined $re;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $re 2 30 32
2119 # an empty pattern (qr//, or the string '') matches every defined cell;
2120 # see _rx_for_match() for what perl before 5.18 makes of one
2121 30 ▶ my $qr = Stats::LikeR::_rx_for_match(ref $re eq 'Regexp' ? $re : qr/$re/);
Branch: 1 branch
BranchTrueFalseTotal
ref $re eq 'Regexp' ? : 21 9 30
2122 30 my $name = $self->{name};
2123 123 ▶ my $code = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
2124 123 my $c = $_[0]{$name};
2125 123 ▶ return 0 unless defined $c;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $c 22 101 123
2126 101 ▶ return ( ($c =~ $qr) ? 1 : 0 ) == $want ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
($c =~ /$qr/ ? 1 : 0) == $want ? : 61 40 101
$c =~ /$qr/ ? : 74 27 101
2127 30 };
2128 30 return bless { code => $code, cols => [ $name ] }, __PACKAGE__;
2129 }
2130 25 ▶ sub match { _match($_[0], $_[1], 1, 'match') }
Subroutine match: called CC=1 SCAR=0.0
2131 8 ▶ sub nomatch { _match($_[0], $_[1], 0, 'nomatch') }
Subroutine nomatch: called CC=1 SCAR=0.0
2132 }
2133  
2134 # concat(@frames) / rbind(@frames) -- row-bind data frames (pandas concat
2135 # axis=0, R rbind). rbind is a true synonym (same subroutine).
2136 #
2137 # Every frame must be the same shape (AoA/AoH/HoA/HoH); a mix dies with a hint
2138 # to convert first (aoh2hoa, hoa2aoh, hoh2hoa, aoh2hoh). undef frames and
2139 # empty frames are skipped, and shape is taken from the first non-empty frame;
2140 # passing nothing usable dies. A NEW top-level frame of that shape is returned;
2141 # the original frames are never modified.
2142 #
2143 # AoA outer arrays concatenated in order (row arrayrefs reused by ref).
2144 # Ragged rows are kept as-is; a short row reads undef past its end.
2145 # AoH rows concatenated in order (row hashrefs reused by ref). The result is
2146 # the union of columns; a column absent from a given row reads undef,
2147 # matching this library's "missing key == undef" convention (dropna,
2148 # view, summary).
2149 # HoA union of columns (sorted for a deterministic layout). Each column is
2150 # the per-frame arrays joined in frame order; a frame lacking a column,
2151 # or a ragged short column, is padded with undef so every column ends up
2152 # the same length (= total rows).
2153 # HoH outer hashes merged in frame order (inner row hashrefs reused by ref).
2154 # Because a Perl hash cannot hold duplicate keys, a repeated row name is
2155 # made unique R-style (name, name.1, name.2, ...) and a single warning is
2156 # emitted noting that row names collided.
2157 508 ▶sub concat {
Subroutine concat: called CC=33 SCAR=35.0
Pod documented
2158 27 my @frames = grep { defined } @_;
2159 27 ▶ _usage_error('concat', 'needs at least one data frame') unless @frames;
Branch: 1 branch
BranchTrueFalseTotal
unless @frames 4 23 27
2160  
2161 23 for my $f (@frames) {
2162 44 ▶ _usage_error('concat', 'every frame must be an ARRAY or HASH ref')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $f eq "ARRAY" or ref $f eq "HASH" 5 39 44
Condition100%3/3
ref $f eq "ARRAY" or ref $f eq "HASH"
l!l&&r!l&&!r
23165
MC/DC100%2/2
ref $f eq "ARRAY" or ref $f eq "HASH"
ref $f eq "ARRAY" ref $f eq "HASH"
Truth table100%3/3
A or B
A= ref $f eq "ARRAY"B= ref $f eq "HASH"
ABresult
1X1
011
000
2163 unless ref $f eq 'ARRAY' || ref $f eq 'HASH';
2164 }
2165 # An empty frame has no shape, so it is dropped here rather than skipped in
2166 # each loop below, which dereferenced a [] among HoAs as a hash and died.
2167 18 ▶ my @nonempty = grep { ref $_ eq 'ARRAY' ? scalar(@$_) : scalar(%$_) } @frames;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 22 16 38
2168 18 ▶ unless (@nonempty) { # all frames empty
Branch: 1 branch
BranchTrueFalseTotal
unless (@nonempty) 2 16 18
2169 2 ▶ return ref $frames[0] eq 'ARRAY' ? [] : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $frames[0] eq 'ARRAY' ? : 1 1 2
2170 }
2171 16 @frames = @nonempty;
2172 # reference shape = first frame; all the others must agree
2173 16 my $ref_shape = _df_shape($frames[0], 'concat');
2174 16 for my $f (@frames) {
2175 29 my $s = _df_shape($f, 'concat');
2176 29 ▶ die "concat: cannot mix a $s frame with a $ref_shape frame; "
Branch: 1 branch
BranchTrueFalseTotal
if $s ne $ref_shape 2 27 29
2177 . "convert them to one shape first (aoh2hoa, hoa2aoh, hoh2hoa, aoh2hoh)\n"
2178 if $s ne $ref_shape;
2179 }
2180  
2181 14 ▶ if ($ref_shape eq 'AoA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref_shape eq "AoA") 3 11 14
2182 3 my @out;
2183 3 for my $f (@frames) {
2184 6 for my $row (@$f) {
2185 8 ▶ die "concat: AoA row is not an ARRAY ref\n" unless ref $row eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "ARRAY" 0 8 8
2186 8 push @out, $row;
2187 }
2188 }
2189 3 return \@out;
2190 }
2191 11 ▶ if ($ref_shape eq 'AoH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref_shape eq "AoH") 4 7 11
2192 4 my @out;
2193 4 for my $f (@frames) {
2194 8 for my $row (@$f) {
2195 8 ▶ die "concat: AoH row is not a HASH ref\n" unless ref $row eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $row eq "HASH" 0 8 8
2196 8 push @out, $row;
2197 }
2198 }
2199 4 return \@out;
2200 }
2201 7 ▶ if ($ref_shape eq 'HoA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref_shape eq "HoA") 5 2 7
2202 5 my (@cols, %seen); # union of columns, sorted
2203 5 for my $f (@frames) { $seen{$_} = 1 for keys %$f }
2204 5 @cols = sort keys %seen;
2205 5 my %out = map { $_ => [] } @cols;
2206 5 for my $f (@frames) {
2207 7 my $n = 0;
2208 7 for my $c (keys %$f) {
2209 11 ▶ $n = @{ $f->{$c} } if ref $f->{$c} eq 'ARRAY' && @{ $f->{$c} } > $n;
Branch: 1 branch
BranchTrueFalseTotal
if ref $f->{$c} eq "ARRAY" and @{$f->{$c};} > $n 8 3 11
Condition66%2/3
ref $f->{$c} eq "ARRAY" and @{$f->{$c};} > $n
!ll&&!rl&&r
038
MC/DC50%1/2
ref $f->{$c} eq "ARRAY" and @{$f->{$c};} > $n
ref $f->{$c} eq "ARRAY" @{$f->{$c};} > $n
Truth table66%2/3
A and B
A= ref $f->{$c} eq "ARRAY"B= @{$f->{$c};} > $n
ABresult
0X0
100
111
2210 }
2211 7 for my $c (@cols) {
2212 13 ▶ if (ref $f->{$c} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $f->{$c} eq 'ARRAY') { } 11 2 13
2213 11 push @{ $out{$c} }, @{ $f->{$c} };
2214 1 push @{ $out{$c} }, (undef) x ($n - @{ $f->{$c} })
2215 11 ▶ if @{ $f->{$c} } < $n; # ragged short column
Branch: 1 branch
BranchTrueFalseTotal
if @{$f->{$c};} < $n 1 10 11
2216 } else {
2217 2 push @{ $out{$c} }, (undef) x $n; # column absent in this frame
2218 }
2219 }
2220 }
2221 5 return \%out;
2222 }
2223 # HoH
2224 2 my (%out, $collided);
2225 2 for my $f (@frames) {
2226 4 for my $rk (sort keys %$f) {
2227 die "concat: HoH row '$rk' is not a HASH ref\n"
2228 5 ▶ unless ref $f->{$rk} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $f->{$rk} eq "HASH" 0 5 5
2229 5 my $label = $rk;
2230 5 my $j = 0;
2231 5 ▶ while (exists $out{$label}) { $collided = 1; $label = $rk . '.' . (++$j) }
Branch: 1 branch
BranchTrueFalseTotal
if (exists $out{$label}) 1 5 6
2232 5 $out{$label} = $f->{$rk}; # reuse the row ref
2233 }
2234 }
2235 2 ▶ warn "concat: duplicate HoH row name(s) made unique with a .N suffix\n"
Branch: 1 branch
BranchTrueFalseTotal
if $collided 1 1 2
2236 if $collided;
2237 2 return \%out;
2238 }
2239 508 ▶{ no warnings 'once'; *rbind = \&concat; } # true synonym
Subroutine BEGIN: called CC=1 SCAR=0.0
2240 #
2241 # dropna($df, cols => \@cols, how => 'any'|'all') # NA mode
2242 # dropna($df, rows => \@rows) # literal deletion
2243 #
2244 # $df may be:
2245 # AoH [ { A=>.., B=>.. }, ... ] rows are 0-based indices
2246 # HoA { A=>[..], B=>[..] } rows are 0-based indices
2247 # HoH { r1=>{ A=>.. }, r2=>{ .. } } rows are the outer keys
2248 #
2249 # cols mode (NA): inspect the named columns and drop the rows that are undef
2250 # in them. how => 'any' (default) drops a row when any named column is undef;
2251 # how => 'all' drops it only when every named column is undef. Columns that
2252 # are not named are untouched but stay aligned (their cell at a dropped index
2253 # goes too). A missing key counts as undef.
2254 #
2255 # rows mode: delete exactly the listed rows (indices for AoH/HoA, keys for HoH);
2256 # no NA check. Indices/keys that aren't present are ignored.
2257 #
2258 # Returns a NEW top-level data frame; the original is never modified. For HoA
2259 # the column arrays are rebuilt (cell values copied); for AoH/HoH the surviving
2260 # row references are reused, not deep-copied (dropna never mutates a row).
2261 #
2262 57 ▶sub dropna {
Subroutine dropna: called CC=39 SCAR=36.6
Pod documented
2263 57 my $df = shift;
2264 57 ▶ _usage_error('dropna', 'first argument is undefined') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 2 55 57
2265 55 ▶ _usage_error('dropna', 'first argument must be a data frame (HoA/HoH hashref or AoH arrayref)')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $df 4 51 55
2266 unless ref $df;
2267 51 ▶ _usage_error('dropna', 'arguments after the data frame must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 1 50 51
2268 if @_ % 2;
2269 50 my %arg = @_;
2270  
2271 50 my %known = ( cols => 1, rows => 1, how => 1 );
2272 50 my @bad = sort grep { !$known{$_} } keys %arg;
2273 50 ▶ _usage_error('dropna', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 3 47 50
2274  
2275 47 my $have_cols = exists $arg{cols};
2276 47 my $have_rows = exists $arg{rows};
2277 47 ▶ _usage_error('dropna', "pass exactly one of 'cols' or 'rows'")
Branch: 1 branch
BranchTrueFalseTotal
unless $have_cols xor $have_rows 7 40 47
Condition100%4/4
$have_cols xor $have_rows
l&&rl&&!r!l&&r!l&&!r
33194
MC/DC100%2/2
$have_cols xor $have_rows
$have_cols $have_rows
Truth table100%4/4
A xor B
A= $have_colsB= $have_rows
ABresult
110
101
011
000
2278 unless $have_cols xor $have_rows;
2279  
2280 40 ▶ my $sel = $have_cols ? $arg{cols} : $arg{rows};
Branch: 1 branch
BranchTrueFalseTotal
$have_cols ? : 31 9 40
2281 40 ▶ _usage_error('dropna', "'" . ($have_cols ? 'cols' : 'rows') . "' must be an arrayref")
Branch: 2 branches
BranchTrueFalseTotal
unless ref $sel eq "ARRAY" 2 38 40
$have_cols ? : 2 0 2
2282 unless ref $sel eq 'ARRAY';
2283  
2284 38 ▶ my $how = defined $arg{how} ? lc $arg{how} : 'any';
Branch: 1 branch
BranchTrueFalseTotal
defined $arg{'how'} ? : 9 29 38
2285 38 ▶ _usage_error('dropna', "'how' must be 'any' or 'all'")
Branch: 1 branch
BranchTrueFalseTotal
unless $how eq "any" or $how eq "all" 2 36 38
Condition100%3/3
$how eq "any" or $how eq "all"
l!l&&r!l&&!r
3242
MC/DC100%2/2
$how eq "any" or $how eq "all"
$how eq "any" $how eq "all"
Truth table100%3/3
A or B
A= $how eq "any"B= $how eq "all"
ABresult
1X1
011
000
2286 unless $how eq 'any' or $how eq 'all';
2287  
2288 36 my $r = ref $df;
2289  
2290 #AoH
2291 36 ▶ if ($r eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r eq "ARRAY") 12 24 36
2292 12 ▶ if ($have_rows) { # literal index deletion
Branch: 1 branch
BranchTrueFalseTotal
if ($have_rows) 2 10 12
2293 2 my %drop = map { $_ => 1 } @$sel;
2294 2 return [ map { $df->[$_] } grep { !$drop{$_} } 0 .. $#$df ];
2295 }
2296 10 my @cols = @$sel;
2297 10 ▶ return [ @$df ] unless @cols; # nothing to check -> keep all
Branch: 1 branch
BranchTrueFalseTotal
unless @cols 1 9 10
2298 9 ▶ return [] unless @$df; # empty frame -> empty result
Branch: 1 branch
BranchTrueFalseTotal
unless @$df 2 7 9
2299 7 my %seen = map { $_ => 1 } @{ _aoh_key_union($df) };
2300 7 for my $c (@cols) {
2301 11 ▶ die "dropna: column '$c' not found\n" unless $seen{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$c} 1 10 11
2302 }
2303 # the rows kept, in XS; a row that is not a hash counts as all NA
2304 6 ▶ return _dropna_xs($df, 1, [ @cols ], $how eq 'all' ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$how eq 'all' ? : 2 4 6
2305 }
2306  
2307 #HoA vs HoH
2308 24 ▶ if ($r eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r eq "HASH") 24 0 24
2309 24 my ($saw_arr, $saw_hash) = (0, 0);
2310 24 for my $v (values %$df) {
2311 42 ▶ next unless ref $v;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $v 3 39 42
2312 39 ▶ $saw_arr++ if ref $v eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $v eq "ARRAY" 26 13 39
2313 39 ▶ $saw_hash++ if ref $v eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $v eq "HASH" 13 26 39
2314 }
2315 24 ▶ die "dropna: hashref mixes array and hash values (ambiguous HoA/HoH)\n"
Branch: 1 branch
BranchTrueFalseTotal
if $saw_arr and $saw_hash 1 23 24
Condition100%3/3
$saw_arr and $saw_hash
!ll&&!rl&&r
6171
MC/DC100%2/2
$saw_arr and $saw_hash
$saw_arr $saw_hash
Truth table100%3/3
A and B
A= $saw_arrB= $saw_hash
ABresult
0X0
100
111
2316 if $saw_arr and $saw_hash;
2317  
2318 #HoH
2319 23 ▶ if ($saw_hash) {
Branch: 1 branch
BranchTrueFalseTotal
if ($saw_hash) 5 18 23
2320 5 ▶ if ($have_rows) { # delete row keys
Branch: 1 branch
BranchTrueFalseTotal
if ($have_rows) 2 3 5
2321 2 my %drop = map { $_ => 1 } @$sel;
2322 2 return { map { $_ => $df->{$_} } grep { !$drop{$_} } keys %$df };
2323 }
2324 3 my @cols = @$sel;
2325 3 ▶ return { %$df } unless @cols;
Branch: 1 branch
BranchTrueFalseTotal
unless @cols 1 2 3
2326 2 ▶ return _dropna_xs($df, 2, [ @cols ], $how eq 'all' ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$how eq 'all' ? : 0 2 2
2327 }
2328  
2329 #HoA (also the empty-hash fallthrough)
2330 18 my $n = 0;
2331 18 for my $v (values %$df) {
2332 28 ▶ $n = @$v if ref $v eq 'ARRAY' and @$v > $n;
Branch: 1 branch
BranchTrueFalseTotal
if ref $v eq "ARRAY" and @$v > $n 17 11 28
Condition100%3/3
ref $v eq "ARRAY" and @$v > $n
!ll&&!rl&&r
3817
MC/DC100%2/2
ref $v eq "ARRAY" and @$v > $n
ref $v eq "ARRAY" @$v > $n
Truth table100%3/3
A and B
A= ref $v eq "ARRAY"B= @$v > $n
ABresult
0X0
100
111
2333 }
2334 18 ▶ if ($have_rows) { # delete indices
Branch: 1 branch
BranchTrueFalseTotal
if ($have_rows) 5 13 18
2335 5 my %drop = map { $_ => 1 } @$sel;
2336 5 my @keep = grep { !$drop{$_} } 0 .. $n - 1;
2337 5 return { map { $_ => [ @{ $df->{$_} }[@keep] ] } keys %$df };
2338 }
2339 13 my @cols = @$sel;
2340 13 ▶ return { map { $_ => [ @{ $df->{$_} } ] } keys %$df } unless @cols;
Branch: 1 branch
BranchTrueFalseTotal
unless @cols 2 11 13
2341 11 for my $c (@cols) {
2342 14 ▶ die "dropna: column '$c' not found\n" unless exists $df->{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $df->{$c} 2 12 14
2343 }
2344 9 ▶ return _dropna_xs($df, 4, [ @cols ], $how eq 'all' ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$how eq 'all' ? : 2 7 9
2345 }
2346  
2347 0 _usage_error('dropna', 'data frame must be an arrayref (AoH) or hashref (HoA/HoH)');
2348 }
2349  
2350 # drop_duplicates($df, subset => $col | \@cols, keep => 'first' | 'last' | 0)
2351 #
2352 # Remove duplicate rows, loosely modeled on pandas' DataFrame.drop_duplicates.
2353 # Works on the three positional/columnar shapes -- AoA, AoH, HoA -- but NOT
2354 # HoH (its rows are labeled, so "drop_duplicates" has no natural meaning; call
2355 # hoh2aoh/hoh2hoa first). Two rows are duplicates when their cells are equal
2356 # in every subset column; comparison is by stringified value with a distinct
2357 # undef (NA), exactly the key semantics merge() uses, so 1 and "1.0" differ.
2358 #
2359 # subset scalar or arrayref of the columns that define a row's identity;
2360 # default every column. For AoA these are 0-based integer positions
2361 # (default 0 .. widest-row-1); for AoH/HoA they are column names
2362 # (AoH default: the sorted union of row keys; HoA: the sorted keys).
2363 # keep which occurrence to keep: 'first' (default) keeps the earliest,
2364 # 'last' the latest, 0 (or 'none') drops every row that has a dup.
2365 #
2366 # Row order is preserved (first-seen positions for the survivors). Returns a
2367 # NEW top-level frame of the same family; the original is never modified. What
2368 # survives is shared, not deep-copied: AoA/AoH reuse the surviving row refs,
2369 # HoA builds new column arrays over the same cell SVs. Assigning through a
2370 # survivor therefore reaches the input's cell.
2371 84 ▶sub drop_duplicates {
Subroutine drop_duplicates: called CC=30 SCAR=34.1
Pod documented
2372 84 my $df = _untied(shift);
2373 84 ▶ _usage_error('drop_duplicates', 'undefined data in first position') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 2 82 84
2374 82 ▶ _usage_error('drop_duplicates', 'arguments after the data frame must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 0 82 82
2375 if @_ % 2;
2376 82 my %arg = @_;
2377 82 my %known = ( subset => 1, keep => 1 );
2378 82 my @bad = sort grep { !$known{$_} } keys %arg;
2379 82 ▶ _usage_error('drop_duplicates', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 81 82
2380  
2381 81 my $shape = _df_shape($df, 'drop_duplicates');
2382 78 ▶ _usage_error('drop_duplicates', 'an HoH data frame is not supported (convert to AoH/HoA/AoA first)')
Branch: 1 branch
BranchTrueFalseTotal
if $shape eq "HoH" 1 77 78
2383 if $shape eq 'HoH';
2384  
2385 # keep -> code: 1 = first, -1 = last, 0 = drop every duplicate
2386 77 ▶ my $keep = exists $arg{keep} ? $arg{keep} : 'first';
Branch: 1 branch
BranchTrueFalseTotal
exists $arg{'keep'} ? : 37 40 77
2387 77 ▶ _usage_error('drop_duplicates', "'keep' is undefined (use 'first', 'last', or 0)")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $keep 0 77 77
2388 unless defined $keep;
2389 77 my $kc;
2390 77 ▶ if ($keep eq 'first') { $kc = 1 }
Branch: 3 branches
BranchTrueFalseTotal
if ($keep eq 'first') { } 50 27 77
elsif ($keep eq 'last') { } 13 14 27
elsif ($keep eq 'none' or $keep eq '' or &looks_like_number($keep) and $keep == 0) { } 12 2 14
2391 13 elsif ($keep eq 'last') { $kc = -1 }
2392 12 ▶ elsif ($keep eq 'none' || $keep eq '' || (looks_like_number($keep) && $keep == 0)) { $kc = 0 }
Condition77%7/9
$keep eq "none" or $keep eq "" or &looks_like_number($keep) and $keep == 0
l!l&&r!l&&!r
1112
$keep eq "none" or $keep eq ""
l!l&&r!l&&!r
1013
&looks_like_number($keep) and $keep == 0
!ll&&!rl&&r
2011
MC/DC50%2/4
$keep eq "none" or $keep eq "" or &looks_like_number($keep) and $keep == 0
$keep eq "none" $keep eq "" &looks_like_number($keep) $keep == 0
Truth table60%3/5
A or B or C and D
A= $keep eq "none"B= $keep eq ""C= &looks_like_number($keep)D= $keep == 0
ABCDresult
1XXX1
01XX1
00111
000X0
00100
2393 2 else { _usage_error('drop_duplicates', "'keep' must be 'first', 'last', or 0 (got '$keep')") }
2394  
2395 # subset -> ordered column list
2396 75 my @sub;
2397 75 ▶ if (exists $arg{subset} && defined $arg{subset}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $arg{"subset"} and defined $arg{"subset"}) 17 58 75
Condition66%2/3
exists $arg{"subset"} and defined $arg{"subset"}
!ll&&!rl&&r
58017
MC/DC50%1/2
exists $arg{"subset"} and defined $arg{"subset"}
exists $arg{"subset"} defined $arg{"subset"}
Truth table66%2/3
A and B
A= exists $arg{"subset"}B= defined $arg{"subset"}
ABresult
0X0
100
111
2398 17 my $s = $arg{subset};
2399 17 ▶ if (ref $s eq 'ARRAY') { @sub = @$s }
Branch: 2 branches
BranchTrueFalseTotal
if (ref $s eq 'ARRAY') { } 3 14 17
elsif (not ref $s) { } 14 0 14
2400 14 elsif (!ref $s) { @sub = ($s) }
2401 0 else { _usage_error('drop_duplicates', "'subset' must be a column or an arrayref of columns") }
2402 17 ▶ _usage_error('drop_duplicates', "'subset' is empty") unless @sub;
Branch: 1 branch
BranchTrueFalseTotal
unless @sub 1 16 17
2403 16 my %seen;
2404 16 for my $c (@sub) {
2405 18 ▶ _usage_error('drop_duplicates', "undefined column in 'subset'") unless defined $c;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $c 0 18 18
2406 18 ▶ _usage_error('drop_duplicates', "duplicate column '$c' in 'subset'") if $seen{$c}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$c}++ 1 17 18
2407 }
2408 }
2409  
2410 73 ▶ if ($shape eq 'AoA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "AoA") 26 47 73
2411 26 ▶ if (@sub) { _aoa_int_cols('drop_duplicates', $df, @sub) }
Branch: 1 branch
BranchTrueFalseTotal
if (@sub) { } 6 20 26
2412 20 else { @sub = (0 .. _aoa_width($df) - 1) }
2413 24 return _drop_dups_core($df, 3, [ @sub ], $kc);
2414 }
2415 47 ▶ if ($shape eq 'AoH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "AoH") 25 22 47
2416 # same union _present_keys builds, but scanned in C: on a large AoH the
2417 # pure-Perl walk over every key of every row cost more than the dedup
2418 25 my %present = map { $_ => 1 } @{ _aoh_key_union($df) };
2419 25 ▶ if (@sub) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sub) { } 3 22 25
2420 3 for my $c (@sub) {
2421 3 ▶ die "drop_duplicates: column '$c' not found\n" unless $present{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $present{$c} 1 2 3
2422 }
2423 } else {
2424 22 @sub = sort keys %present;
2425 }
2426 24 return _drop_dups_core($df, 1, [ @sub ], $kc);
2427 }
2428 # HoA
2429 22 ▶ if (@sub) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sub) { } 6 16 22
2430 6 for my $c (@sub) {
2431 6 ▶ die "drop_duplicates: column '$c' not found\n" unless exists $df->{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $df->{$c} 1 5 6
2432 }
2433 } else {
2434 16 @sub = sort keys %$df;
2435 }
2436 21 return _drop_dups_core($df, 4, [ @sub ], $kc);
2437 }
2438 # Count rows across Stats::LikeR frame forms: AoH, AoA, HoA, HoH.
2439  
2440 # Count columns across Stats::LikeR frame forms: AoH, AoA, HoA, HoH
2441 # (plain vector => 1 column). Uses die, not croak. reftype => blessed frames ok.
2442 56 ▶sub ncol {
Subroutine ncol: called CC=36 SCAR=35.9
Pod documented
2443 56 my ($data) = @_;
2444 56 my $type = reftype $data;
2445 56 ▶ _usage_error('ncol', 'expected an ARRAY or HASH ref (got '
Branch: 2 branches
BranchTrueFalseTotal
unless defined $type and $type eq "ARRAY" || $type eq "HASH" 10 46 56
defined $data ? : 7 3 10
Condition100%8/8
defined $type and $type eq "ARRAY" || $type eq "HASH"
!ll&&!rl&&r
7346
$type eq "ARRAY" or $type eq "HASH"
l!l&&r!l&&!r
18283
ref $data or "non-ref scalar"
l!l
34
MC/DC100%3/3
defined $type and $type eq "ARRAY" || $type eq "HASH"
defined $type $type eq "ARRAY" $type eq "HASH"
MC/DC100%1/1
ref $data or "non-ref scalar"
ref $data
Truth table100%4/4
A and B or C
A= defined $typeB= $type eq "ARRAY"C= $type eq "HASH"
ABCresult
0XX0
1000
11X1
1011
Truth table100%2/2
A
A= ref $data
Aresult
11
00
2446 . (defined $data ? (ref($data) || 'non-ref scalar') : 'undef') . ')')
2447 unless defined $type && ($type eq 'ARRAY' || $type eq 'HASH');
2448  
2449 46 ▶ if ($type eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "ARRAY") 18 28 46
2450 18 ▶ return 0 unless @$data; # empty frame
Branch: 1 branch
BranchTrueFalseTotal
unless @$data 1 17 18
2451 17 my $r0 = reftype $data->[0]; # element 0 decides the form
2452  
2453 # AoH: columns = keys per row; every row a hash ref of equal key count
2454 17 ▶ if (defined $r0 && $r0 eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $r0 and $r0 eq "HASH") 7 10 17
Condition100%3/3
defined $r0 and $r0 eq "HASH"
!ll&&!rl&&r
287
MC/DC100%2/2
defined $r0 and $r0 eq "HASH"
defined $r0 $r0 eq "HASH"
Truth table100%3/3
A and B
A= defined $r0B= $r0 eq "HASH"
ABresult
0X0
100
111
2455 7 my $ncol = scalar keys %{ $data->[0] };
2456 7 for my $i (1 .. $#$data) {
2457 6 my $row = $data->[$i];
2458 6 ▶ die "ncol: AoH row $i is not a hash ref\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined builtin::reftype($row) and builtin::reftype($row) eq "HASH" 1 5 6
Condition66%2/3
defined builtin::reftype($row) and builtin::reftype($row) eq "HASH"
!ll&&!rl&&r
015
MC/DC50%1/2
defined builtin::reftype($row) and builtin::reftype($row) eq "HASH"
defined builtin::reftype($row) builtin::reftype($row) eq "HASH"
Truth table66%2/3
A and B
A= defined builtin::reftype($row)B= builtin::reftype($row) eq "HASH"
ABresult
0X0
100
111
2459 unless defined(reftype $row) && reftype($row) eq 'HASH';
2460 5 my $k = scalar keys %$row;
2461 5 ▶ die "ncol: ragged AoH — row $i has $k columns, but row 0 has $ncol\n"
Branch: 1 branch
BranchTrueFalseTotal
if $k != $ncol 1 4 5
2462 if $k != $ncol;
2463 }
2464 5 return $ncol;
2465 }
2466  
2467 # AoA: columns = row length; every row an array ref of equal length
2468 10 ▶ if (defined $r0 && $r0 eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $r0 and $r0 eq "ARRAY") 7 3 10
Condition100%3/3
defined $r0 and $r0 eq "ARRAY"
!ll&&!rl&&r
217
MC/DC100%2/2
defined $r0 and $r0 eq "ARRAY"
defined $r0 $r0 eq "ARRAY"
Truth table100%3/3
A and B
A= defined $r0B= $r0 eq "ARRAY"
ABresult
0X0
100
111
2469 7 my $ncol = scalar @{ $data->[0] };
2470 7 for my $i (1 .. $#$data) {
2471 5 my $row = $data->[$i];
2472 5 ▶ die "ncol: AoA row $i is not an array ref\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined builtin::reftype($row) and builtin::reftype($row) eq "ARRAY" 1 4 5
Condition66%2/3
defined builtin::reftype($row) and builtin::reftype($row) eq "ARRAY"
!ll&&!rl&&r
014
MC/DC50%1/2
defined builtin::reftype($row) and builtin::reftype($row) eq "ARRAY"
defined builtin::reftype($row) builtin::reftype($row) eq "ARRAY"
Truth table66%2/3
A and B
A= defined builtin::reftype($row)B= builtin::reftype($row) eq "ARRAY"
ABresult
0X0
100
111
2473 unless defined(reftype $row) && reftype($row) eq 'ARRAY';
2474 4 my $len = scalar @$row;
2475 4 ▶ die "ncol: ragged AoA — row $i has $len columns, but row 0 has $ncol\n"
Branch: 1 branch
BranchTrueFalseTotal
if $len != $ncol 1 3 4
2476 if $len != $ncol;
2477 }
2478 5 return $ncol;
2479 }
2480  
2481 3 ▶ return 1 unless defined $r0; # plain 1-D vector: one column
Branch: 1 branch
BranchTrueFalseTotal
unless defined $r0 2 1 3
2482  
2483 1 die "ncol: array element 0 is a $r0 ref; expected HASH (AoH), ARRAY (AoA), or plain scalars (vector)\n";
2484 }
2485  
2486 # HASH: HoA (keys are columns) or HoH (keys are rows)
2487 28 ▶ return 0 unless %$data;
Branch: 1 branch
BranchTrueFalseTotal
unless %$data 1 27 28
2488  
2489 27 my $probe; # first defined value decides the form
2490 27 foreach my $k (keys %$data) {
2491 30 ▶ next unless defined $data->{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data->{$k} 4 26 30
2492 26 $probe = $data->{$k};
2493 26 last;
2494 }
2495 27 my $vtype = reftype $probe;
2496  
2497 # HoA: keys ARE the columns. Validate values are array refs so a malformed
2498 # frame dies deterministically rather than depending on which key `probe` hit.
2499 27 ▶ if (defined $vtype && $vtype eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $vtype and $vtype eq "ARRAY") 20 7 27
Condition100%3/3
defined $vtype and $vtype eq "ARRAY"
!ll&&!rl&&r
2520
MC/DC100%2/2
defined $vtype and $vtype eq "ARRAY"
defined $vtype $vtype eq "ARRAY"
Truth table100%3/3
A and B
A= defined $vtypeB= $vtype eq "ARRAY"
ABresult
0X0
100
111
2500 20 foreach my $col (keys %$data) {
2501 die "ncol: HoA column '$col' is not an array ref\n"
2502 25 ▶ unless defined(reftype $data->{$col}) && reftype($data->{$col}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless defined builtin::reftype($data->{$col}) and builtin::reftype($data->{$col}) eq "ARRAY" 1 24 25
Condition66%2/3
defined builtin::reftype($data->{$col}) and builtin::reftype($data->{$col}) eq "ARRAY"
!ll&&!rl&&r
1024
MC/DC50%1/2
defined builtin::reftype($data->{$col}) and builtin::reftype($data->{$col}) eq "ARRAY"
defined builtin::reftype($data->{$col}) builtin::reftype($data->{$col}) eq "ARRAY"
Truth table66%2/3
A and B
A= defined builtin::reftype($data->{$col})B= builtin::reftype($data->{$col}) eq "ARRAY"
ABresult
0X0
100
111
2503 }
2504 19 return scalar keys %$data;
2505 }
2506  
2507 # HoH: keys are rows; columns = keys of a row hash, consistent across rows
2508 7 ▶ if (defined $vtype && $vtype eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $vtype and $vtype eq "HASH") 5 2 7
Condition66%2/3
defined $vtype and $vtype eq "HASH"
!ll&&!rl&&r
205
MC/DC50%1/2
defined $vtype and $vtype eq "HASH"
defined $vtype $vtype eq "HASH"
Truth table66%2/3
A and B
A= defined $vtypeB= $vtype eq "HASH"
ABresult
0X0
100
111
2509 5 my ($ncol, $ref_row);
2510 5 foreach my $row_key (keys %$data) {
2511 8 my $row = $data->{$row_key};
2512 8 ▶ die "ncol: HoH row '$row_key' is not a hash ref\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined builtin::reftype($row) and builtin::reftype($row) eq "HASH" 1 7 8
Condition66%2/3
defined builtin::reftype($row) and builtin::reftype($row) eq "HASH"
!ll&&!rl&&r
107
MC/DC50%1/2
defined builtin::reftype($row) and builtin::reftype($row) eq "HASH"
defined builtin::reftype($row) builtin::reftype($row) eq "HASH"
Truth table66%2/3
A and B
A= defined builtin::reftype($row)B= builtin::reftype($row) eq "HASH"
ABresult
0X0
100
111
2513 unless defined(reftype $row) && reftype($row) eq 'HASH';
2514 7 my $k = scalar keys %$row;
2515 7 ▶ if (not defined $ncol) { $ncol = $k; $ref_row = $row_key }
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $ncol) { } 4 3 7
elsif ($k != $ncol) { } 1 2 3
2516 elsif ($k != $ncol) {
2517 1 die "ncol: ragged HoH — row '$row_key' has $k columns, but '$ref_row' has $ncol\n";
2518 }
2519 }
2520 3 return $ncol;
2521 }
2522  
2523 2 die "ncol: HASH values are neither ARRAY refs (HoA) nor HASH refs (HoH)\n";
2524 }
2525  
2526 31 ▶sub nrow {
Subroutine nrow: called CC=17 SCAR=28.4
Pod documented
2527 31 my ($data) = @_;
2528 31 my $type = reftype $data;
2529 31 ▶ _usage_error('nrow', 'expected an ARRAY or HASH ref (got '
Branch: 2 branches
BranchTrueFalseTotal
unless defined $type 7 24 31
defined $data ? : 5 2 7
Condition50%1/2
ref $data or "non-ref scalar"
l!l
05
MC/DC0%0/1
ref $data or "non-ref scalar"
ref $data
Truth table50%1/2
A
A= ref $data
Aresult
11
00
2530 . (defined $data ? (ref($data) || 'non-ref scalar') : 'undef') . ')')
2531 unless defined $type;
2532  
2533 # AoH / AoA (and a plain vector): one top-level element per row.
2534 24 ▶ return scalar @$data if $type eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "ARRAY" 8 16 24
2535  
2536 # HASH: HoA (keys are columns) or HoH (keys are rows).
2537 16 ▶ return 0 unless %$data; # empty frame, either form
Branch: 1 branch
BranchTrueFalseTotal
unless %$data 1 12 13
2538  
2539 12 my $probe; # first defined value decides the form
2540 12 foreach my $k (keys %$data) {
2541 13 ▶ next unless defined $data->{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data->{$k} 2 11 13
2542 11 $probe = $data->{$k};
2543 11 last;
2544 }
2545 12 my $vtype = reftype $probe;
2546  
2547 12 ▶ return scalar keys %$data # HoH: one key per row
Branch: 1 branch
BranchTrueFalseTotal
if defined $vtype and $vtype eq "HASH" 4 8 12
Condition100%3/3
defined $vtype and $vtype eq "HASH"
!ll&&!rl&&r
264
MC/DC100%2/2
defined $vtype and $vtype eq "HASH"
defined $vtype $vtype eq "HASH"
Truth table100%3/3
A and B
A= defined $vtypeB= $vtype eq "HASH"
ABresult
0X0
100
111
2548 if defined $vtype && $vtype eq 'HASH';
2549  
2550 8 ▶ if (defined $vtype && $vtype eq 'ARRAY') { # HoA: rows = common column length
Branch: 1 branch
BranchTrueFalseTotal
if (defined $vtype and $vtype eq "ARRAY") 6 2 8
Condition66%2/3
defined $vtype and $vtype eq "ARRAY"
!ll&&!rl&&r
206
MC/DC50%1/2
defined $vtype and $vtype eq "ARRAY"
defined $vtype $vtype eq "ARRAY"
Truth table66%2/3
A and B
A= defined $vtypeB= $vtype eq "ARRAY"
ABresult
0X0
100
111
2551 6 my ($n, $ref_col);
2552 6 foreach my $col (keys %$data) { # verify columns agree, so a ragged
2553 11 my $vec = $data->{$col}; # frame can't return a silently-wrong
2554 11 ▶ die "nrow: HoA column '$col' is not an array ref" # (and, given hash
Branch: 1 branch
BranchTrueFalseTotal
unless defined builtin::reftype($vec) and builtin::reftype($vec) eq "ARRAY" 1 10 11
Condition66%2/3
defined builtin::reftype($vec) and builtin::reftype($vec) eq "ARRAY"
!ll&&!rl&&r
1010
MC/DC50%1/2
defined builtin::reftype($vec) and builtin::reftype($vec) eq "ARRAY"
defined builtin::reftype($vec) builtin::reftype($vec) eq "ARRAY"
Truth table66%2/3
A and B
A= defined builtin::reftype($vec)B= builtin::reftype($vec) eq "ARRAY"
ABresult
0X0
100
111
2555 unless defined(reftype $vec) && reftype($vec) eq 'ARRAY'; # ordering,
2556 10 my $len = scalar @$vec; # nondeterministic) count
2557 10 ▶ if (not defined $n) { $n = $len; $ref_col = $col }
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $n) { } 6 4 10
elsif ($len != $n) { } 1 3 4
2558 elsif ($len != $n) {
2559 1 die "nrow: ragged HoA — column '$col' has $len rows, but '$ref_col' has $n";
2560 }
2561 }
2562 4 return $n;
2563 }
2564 2 die 'nrow: HASH values are neither ARRAY refs (HoA) nor HASH refs (HoH)';
2565 }
2566 35 ▶sub qcut {
Subroutine qcut: called CC=33 SCAR=35.0
Pod documented
2567 35 my ($data, $q, %opt) = @_;
2568  
2569 35 ▶ _usage_error('qcut', 'first argument must be an ARRAY reference')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "ARRAY" 5 30 35
2570 unless ref $data eq 'ARRAY';
2571  
2572 # probability vector: q+1 evenly spaced points, or an explicit list
2573 30 my $probs;
2574 30 ▶ if (ref $q eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $q eq 'ARRAY') { } 2 28 30
2575 2 $probs = [ sort { $a <=> $b } @$q ];
2576 } else {
2577 28 ▶ _usage_error('qcut', 'number of quantiles must be a positive integer')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $q and $q =~ /\A[1-9][0-9]*\z/ 3 25 28
Condition66%2/3
defined $q and $q =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
0325
MC/DC50%1/2
defined $q and $q =~ /\A[1-9][0-9]*\z/
defined $q $q =~ /\A[1-9][0-9]*\z/
Truth table66%2/3
A and B
A= defined $qB= $q =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
2578 unless defined $q && $q =~ /\A[1-9][0-9]*\z/;
2579 25 $probs = [ map { $_ / $q } 0 .. $q ];
2580 }
2581  
2582 27 ▶ my $drop = (($opt{duplicates} // 'raise') eq 'drop') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
($opt{'duplicates'} // 'raise') eq 'drop' ? : 1 26 27
Condition100%2/2
$opt{"duplicates"} // "raise"
l!l
126
MC/DC100%1/1
$opt{"duplicates"} // "raise"
$opt{"duplicates"}
Truth table100%2/2
A
A= $opt{"duplicates"}
Aresult
11
00
2583 27 my $labels = $opt{labels};
2584  
2585 # codes are opt-in (labels imply them); edges are on unless codes asked for
2586 27 ▶ my $want_codes = ($opt{codes} || defined $labels) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'codes'} || defined $labels ? : 15 12 27
Condition100%3/3
$opt{"codes"} or defined $labels
l!l&&r!l&&!r
13212
MC/DC100%2/2
$opt{"codes"} or defined $labels
$opt{"codes"} defined $labels
Truth table100%3/3
A or B
A= $opt{"codes"}B= defined $labels
ABresult
1X1
011
000
2587 my $want_edges = exists $opt{edges}
2588 27 ▶ ? ($opt{edges} ? 1 : 0)
Branch: 3 branches
BranchTrueFalseTotal
exists $opt{'edges'} ? : 9 18 27
$opt{'edges'} ? : 9 0 9
$want_codes ? : 6 12 18
2589 : ($want_codes ? 0 : 1);
2590 27 ▶ _usage_error('qcut', 'nothing to return (set edges => 1 or codes => 1)')
Branch: 1 branch
BranchTrueFalseTotal
unless $want_edges or $want_codes 0 27 27
Condition66%2/3
$want_edges or $want_codes
l!l&&r!l&&!r
2160
MC/DC0%0/2
$want_edges or $want_codes
$want_edges $want_codes
Truth table66%2/3
A or B
A= $want_edgesB= $want_codes
ABresult
1X1
011
000
2591 unless $want_edges || $want_codes;
2592  
2593 # does the column contain any NA? undef and NaN both are, as NaN is to
2594 # pandas: up to 0.3413 a NaN was binned as a number, and every edge it
2595 # touched came back NaN (qcut([1, 2, 3, 4, NaN], 4) gave 1 2 3 NaN NaN).
2596 508 ▶ my $is_na = sub { my $x = shift; no warnings 'numeric'; return !defined($x) || $x != $x };
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=2 SCAR=6.9
Condition100%3/3
!defined($x) || $x != $x
l!l&&r!l&&!r
3503481305
MC/DC100%2/2
!defined($x) || $x != $x
!defined($x) $x != $x
Truth table100%3/3
not(A) || B
A= !defined($x)B= $x != $x
ABresult
1X1
011
000
2597 27 my $has_na = 0;
2598 27 ▶ for my $x (@$data) { if ($is_na->($x)) { $has_na = 1; last } }
Branch: 1 branch
BranchTrueFalseTotal
if (&$is_na($x)) 17 376 393
2599  
2600 27 my ($codes, $edges, @pos);
2601 27 ▶ if ($want_codes && $has_na) {
Branch: 2 branches
BranchTrueFalseTotal
if ($want_codes and $has_na) { } 9 18 27
elsif ($has_na) { } 8 10 18
Condition100%3/3
$want_codes and $has_na
!ll&&!rl&&r
1269
MC/DC100%2/2
$want_codes and $has_na
$want_codes $has_na
Truth table100%3/3
A and B
A= $want_codesB= $has_na
ABresult
0X0
100
111
2602 # strip NA, remember positions, scatter codes back afterwards
2603 9 my @vals;
2604 9 for my $i (0 .. $#$data) {
2605 810 my $x = $data->[$i];
2606 810 ▶ next if $is_na->($x);
Branch: 1 branch
BranchTrueFalseTotal
if &$is_na($x) 341 469 810
2607 469 push @vals, $x + 0;
2608 469 push @pos, $i;
2609 }
2610 9 ▶ die "qcut: no non-missing values\n" unless @vals;
Branch: 1 branch
BranchTrueFalseTotal
unless @vals 0 9 9
2611 9 ($codes, $edges) = _qcut_core(\@vals, $probs, $drop, 1);
2612 } elsif ($has_na) {
2613 # edges only: drop NA so cutpoints ignore them, positions don't matter
2614 8 my @vals = grep { !$is_na->($_) } @$data;
2615 8 ▶ die "qcut: no non-missing values\n" unless @vals;
Branch: 1 branch
BranchTrueFalseTotal
unless @vals 0 8 8
2616 8 ($codes, $edges) = _qcut_core(\@vals, $probs, $drop, 0);
2617 } else {
2618 # no NA: hand the original arrayref straight to XS (no copy)
2619 10 ($codes, $edges) = _qcut_core($data, $probs, $drop, $want_codes);
2620 }
2621  
2622 # edges-only: return the flat list
2623 26 ▶ return @$edges unless $want_codes;
Branch: 1 branch
BranchTrueFalseTotal
unless $want_codes 11 15 26
2624  
2625 # turn integer codes into requested labels, or keep the XS arrayref as-is
2626 15 my $out;
2627 15 ▶ if (defined $labels && ref $labels eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $labels and ref $labels eq 'ARRAY') { } 1 14 15
elsif (defined $labels and $labels eq 'interval') { } 1 13 14
Condition100%3/3
defined $labels and ref $labels eq "ARRAY"
!ll&&!rl&&r
1311
MC/DC100%2/2
defined $labels and ref $labels eq "ARRAY"
defined $labels ref $labels eq "ARRAY"
Truth table100%3/3
A and B
A= defined $labelsB= ref $labels eq "ARRAY"
ABresult
0X0
100
111
2628 1 my $nbin = scalar(@$edges) - 1;
2629 1 ▶ die "qcut: got $nbin bins but " . scalar(@$labels) . " labels\n"
Branch: 1 branch
BranchTrueFalseTotal
unless @$labels == $nbin 0 1 1
2630 unless @$labels == $nbin;
2631 1 $out = [ map { $labels->[$_] } @$codes ];
2632 ▶ } elsif (defined $labels && $labels eq 'interval') {
Condition66%2/3
defined $labels and $labels eq "interval"
!ll&&!rl&&r
1301
MC/DC50%1/2
defined $labels and $labels eq "interval"
defined $labels $labels eq "interval"
Truth table66%2/3
A and B
A= defined $labelsB= $labels eq "interval"
ABresult
0X0
100
111
2633 1 my @iv;
2634 1 for my $b (0 .. $#$edges - 1) {
2635 4 my $l = $edges->[$b];
2636 4 my $r = $edges->[$b + 1];
2637 4 ▶ $iv[$b] = $b == 0 ? "[$l, $r]" : "($l, $r]";
Branch: 1 branch
BranchTrueFalseTotal
$b == 0 ? : 1 3 4
2638 }
2639 1 $out = [ map { $iv[$_] } @$codes ];
2640 } else {
2641 13 $out = $codes; # reuse XS result; no copy
2642 }
2643  
2644 # scatter NA positions back in (codes path only)
2645 15 ▶ if ($has_na) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_na) 9 6 15
2646 9 my @r = (undef) x scalar(@$data);
2647 9 @r[@pos] = @$out;
2648 9 $out = \@r;
2649 }
2650  
2651 15 ▶ return $want_edges ? ($out, $edges) : $out;
Branch: 1 branch
BranchTrueFalseTotal
$want_edges ? : 9 6 15
2652 }
2653  
2654 # summary($data, %opts) -- R-style five-number-plus-mean summary.
2655 #
2656 # Accepts every shape view() does and computes one statistics row per numeric
2657 # "variable": a flat vector (one row); an AoA (one row per inner array, labelled
2658 # by Index); a HoA (one row per key); and -- like view() -- an AoH or HoH (one
2659 # row per column, gathered across the rows). Non-numeric and undefined cells are
2660 # ignored (they never count toward '# values'); an all-non-numeric variable
2661 # shows 0 values and 'na' statistics. Output, colour, and the display options
2662 # are rendered exactly like view() via the shared _render_grid().
2663 44 ▶sub summary {
Subroutine summary: called CC=37 SCAR=36.6
Pod documented
2664 44 my $current_sub = (split(/::/,(caller(0))[3]))[-1];
2665 # options view() understands, plus the row-cap synonyms
2666 44 my %opt_key = map { $_ => 1 } qw(
2667 nrows nrow n rows
2668 na color colors max_width ellipsis gap width to return_only
2669 );
2670 44 my ($data, %args);
2671 44 ▶ if (@_ && ref $_[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ and ref $_[0]) { } 33 11 44
Condition66%2/3
@_ and ref $_[0]
!ll&&!rl&&r
01133
MC/DC50%1/2
@_ and ref $_[0]
@_ ref $_[0]
Truth table66%2/3
A and B
A= @_B= ref $_[0]
ABresult
0X0
100
111
2672 # summary(\@arr, ...) / summary(\%h, ...)
2673 33 $data = shift;
2674 33 ▶ _usage_error($current_sub, 'arguments after the data must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 1 32 33
2675 if @_ % 2;
2676 32 %args = @_;
2677 } else {
2678 # summary(@vector) / summary(@vector, nrows => N): peel recognised
2679 # trailing key/value option pairs off the flat list; the rest is data.
2680 11 ▶ while (@_ >= 2 && defined $_[-2] && !ref($_[-2]) && $opt_key{ $_[-2] }) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ >= 2 and defined $_[-2] and not ref $_[-2] and $opt_key{$_[-2]}) 22 11 33
Condition77%7/9
@_ >= 2 and defined $_[-2] and not ref $_[-2] and $opt_key{$_[-2]}
!ll&&!rl&&r
2922
@_ >= 2 and defined $_[-2] and not ref $_[-2]
!ll&&!rl&&r
2031
@_ >= 2 and defined $_[-2]
!ll&&!rl&&r
2031
MC/DC50%2/4
@_ >= 2 and defined $_[-2] and not ref $_[-2] and $opt_key{$_[-2]}
@_ >= 2 defined $_[-2] not ref $_[-2] $opt_key{$_[-2]}
Truth table60%3/5
A and B and not(C) and D
A= @_ >= 2B= defined $_[-2]C= not ref $_[-2]D= $opt_key{$_[-2]}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2681 22 my $val = pop @_;
2682 22 my $key = pop @_;
2683 22 $args{$key} = $val;
2684 }
2685 11 my @list = @_;
2686 11 $data = \@list;
2687 }
2688 43 my @bad = sort grep { !$opt_key{$_} } keys %args;
2689 43 ▶ _usage_error($current_sub, "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 3 40 43
2690 # row cap: nrows / nrow / n / rows are synonyms (default 10)
2691 my $nrows = exists $args{nrows} ? $args{nrows} : exists $args{nrow} ? $args{nrow}
2692 : exists $args{n} ? $args{n} : exists $args{rows} ? $args{rows}
2693 40 ▶ : 10;
Branch: 4 branches
BranchTrueFalseTotal
exists $args{'nrows'} ? : 6 34 40
exists $args{'nrow'} ? : 1 33 34
exists $args{'n'} ? : 1 32 33
exists $args{'rows'} ? : 0 32 32
2694 40 ▶ _usage_error($current_sub, "'nrows' must be a non-negative integer")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $nrows and $nrows =~ /^\d+$/ 0 40 40
Condition33%1/3
defined $nrows and $nrows =~ /^\d+$/
!ll&&!rl&&r
0040
MC/DC0%0/2
defined $nrows and $nrows =~ /^\d+$/
defined $nrows $nrows =~ /^\d+$/
Truth table33%1/3
A and B
A= defined $nrowsB= $nrows =~ /^\d+$/
ABresult
0X0
100
111
2695 unless defined $nrows && $nrows =~ /^\d+$/;
2696  
2697 40 my $rt = ref $data;
2698 40 ▶ _usage_error($current_sub, "data must either be a hash or an array, not \"$rt\"")
Branch: 1 branch
BranchTrueFalseTotal
unless $rt eq "ARRAY" or $rt eq "HASH" 2 38 40
Condition100%3/3
$rt eq "ARRAY" or $rt eq "HASH"
l!l&&r!l&&!r
3082
MC/DC100%2/2
$rt eq "ARRAY" or $rt eq "HASH"
$rt eq "ARRAY" $rt eq "HASH"
Truth table100%3/3
A or B
A= $rt eq "ARRAY"B= $rt eq "HASH"
ABresult
1X1
011
000
2699 unless $rt eq 'ARRAY' or $rt eq 'HASH';
2700  
2701 # resolve the data shape into series: a label, and where its numbers come
2702 # from, as _numeric_cells's (src, kind, key)
2703 38 my (@labels, @srcs, $lab_header);
2704 38 ▶ if ($rt eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($rt eq 'ARRAY') { } 30 8 38
2705 30 my $first;
2706 30 ▶ for my $e (@$data) { if (defined $e) { $first = $e; last } }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $e) 30 0 30
2707 30 my $ft = ref $first;
2708 30 ▶ if ($ft eq 'HASH') { # AoH: one series per column
Branch: 2 branches
BranchTrueFalseTotal
if ($ft eq 'HASH') { } 1 29 30
elsif ($ft eq 'ARRAY') { } 3 26 29
2709 1 $lab_header = 'Column';
2710 1 for my $col (sort @{ _aoh_key_union($data) }) {
2711 2 push @labels, $col;
2712 2 push @srcs, [ $data, 1, $col ];
2713 }
2714 } elsif ($ft eq 'ARRAY') { # AoA: one series per inner array
2715 3 $lab_header = 'Index';
2716 3 for my $i (0 .. $#$data) {
2717 6 push @labels, $i;
2718 6 ▶ push @srcs, (ref $data->[$i] eq 'ARRAY' ? [ $data->[$i], 3, undef ] : undef);
Branch: 1 branch
BranchTrueFalseTotal
ref $data->[$i] eq 'ARRAY' ? : 6 0 6
2719 }
2720 } else { # flat vector: a single series
2721 26 $lab_header = '';
2722 26 push @labels, '';
2723 26 push @srcs, [ $data, 3, undef ];
2724 }
2725 } else { # HASH
2726 8 my @keys = keys %$data;
2727 8 my $sample;
2728 8 ▶ for my $k (@keys) { $sample = $data->{$k}; last if defined $sample }
Branch: 1 branch
BranchTrueFalseTotal
if defined $sample 8 0 8
2729 8 my $vt = ref $sample;
2730 8 ▶ if ($vt eq 'ARRAY') { # HoA: one series per key
Branch: 2 branches
BranchTrueFalseTotal
if ($vt eq 'ARRAY') { } 5 3 8
elsif ($vt eq 'HASH') { } 3 0 3
2731 5 $lab_header = 'Key';
2732 5 for my $k (sort { lc $a cmp lc $b } @keys) {
2733 14 push @labels, $k;
2734 14 ▶ push @srcs, (ref $data->{$k} eq 'ARRAY' ? [ $data->{$k}, 3, undef ] : undef);
Branch: 1 branch
BranchTrueFalseTotal
ref $data->{$k} eq 'ARRAY' ? : 14 0 14
2735 }
2736 } elsif ($vt eq 'HASH') { # HoH: one series per column (inner key)
2737 3 $lab_header = 'Column';
2738 3 for my $col (sort @{ _aoh_key_union([ values %$data ]) }) {
2739 6 push @labels, $col;
2740 6 push @srcs, [ $data, 2, $col ];
2741 }
2742 } else { # flat hash: its values as one series
2743 0 $lab_header = '';
2744 0 push @labels, '';
2745 0 push @srcs, [ $data, 4, undef ];
2746 }
2747 }
2748  
2749 # cap the number of series shown (keep the true total for the "... more" note)
2750 38 my $total = scalar @labels;
2751 38 ▶ if ($nrows < $total) { $#labels = $nrows - 1; $#srcs = $nrows - 1; }
Branch: 1 branch
BranchTrueFalseTotal
if ($nrows < $total) 2 36 38
2752  
2753 # compute the statistics grid, one series at a time and only for the series
2754 # shown. Up to 0.3424 every series was copied whole, all of them at once,
2755 # and then filtered in perl; _numeric_cells (LikeR.xs) hands back only the
2756 # numbers, as copies.
2757 38 my @colnames = ('# values', 'Min.', '1st Qu.', 'Median', 'Mean', '3rd Qu.', 'Max.');
2758 38 my @raw;
2759 38 for my $src (@srcs) {
2760 49 ▶ my $numeric = $src ? _numeric_cells(@$src) : [];
Branch: 1 branch
BranchTrueFalseTotal
$src ? : 49 0 49
2761 49 ▶ if (!@$numeric) { push @raw, [ 0, (undef) x 6 ]; next } # empty -> na stats
Branch: 1 branch
BranchTrueFalseTotal
unless (@$numeric) 3 46 49
2762 46 my $q = quantile($numeric, probs => [0.25, 0.75]);
2763 # format as %.4g strings; they still look numeric, so _render_grid
2764 # right-aligns and colours them as numbers.
2765 push @raw, [
2766 scalar @$numeric,
2767 sprintf('%.4g', min($numeric)), sprintf('%.4g', $q->{'25%'}),
2768 sprintf('%.4g', median($numeric)), sprintf('%.4g', mean($numeric)),
2769 46 sprintf('%.4g', $q->{'75%'}), sprintf('%.4g', max($numeric)),
2770 ];
2771 }
2772  
2773 # The display options go on as they were given; _render_grid() checks them.
2774 return _render_grid('summary', $total, \@colnames, \@labels, \@raw, $lab_header,
2775 38 ▶ map { exists $args{$_} ? ($_ => $args{$_}) : () }
Branch: 1 branch
BranchTrueFalseTotal
exists $args{$_} ? : 76 266 342
2776 qw(na max_width ellipsis gap width to return_only color colors));
2777 }
2778  
2779 # .xlsx support (pure Perl, no CPAN deps)
2780 # An .xlsx file is a ZIP archive of XML parts. IO::Uncompress::Unzip is a core
2781 # module, so we can pull the parts out and parse the (very regular) XML with
2782 # regexes, then feed rows to read_table's callback exactly like _parse_csv_file
2783 # does. A workbook with more than one worksheet is read into a hash keyed by
2784 # sheet name (see read_table). Limitations: dates/times come back as their raw
2785 # serial numbers (no style-based formatting); shared-string rich-text runs are
2786 # concatenated.
2787  
2788 # The decompressed bytes of a named archive member as a SCALAR REFERENCE, or
2789 # undef if the member is absent.
2790 #
2791 # The reference is the point. Returning the string itself costs a full copy of
2792 # it -- perl cannot hand back the pad slot of a lexical, so `return $content'
2793 # copies, and on the 36 MB worksheet part of a 21,845 x 50 workbook that was
2794 # 34 MB of peak RSS for nothing: 82.4 MB against 48.5 MB for the reference, and
2795 # 81 MB still resident afterwards against 13 MB, the difference being heap the
2796 # allocator never gave back. Every caller dereferences; `$$ws' on an argument
2797 # list pushes the SV itself, so the part reaches the XS parser without a copy
2798 # either.
2799 #
2800 # _unzip_member_fast() handles the archives Excel, LibreOffice and openpyxl
2801 # actually write; the loop below is the fallback for everything else, and is
2802 # what every member went through up to 0.316.
2803 #
2804 # The read appends onto the end of $content rather than going through a second
2805 # scalar: IO::Uncompress::Base::read() turns its truncating substr() into a
2806 # no-op when the offset is already the buffer's length, so the string is
2807 # extended in place instead of being copied by a concatenation. On the 36 MB
2808 # worksheet part of a 21,845 x 50 workbook that is 0.171 s against 0.243 s for
2809 # `$content .= $buf`, over three runs each in a fresh process, and it leaves
2810 # behind none of the ~25 MB of realloc slack the concatenation did.
2811 # Do NOT reach for BlockSize => 1<<20 instead: measured at 0.262 s on the same
2812 # part against 0.174 s for the default. (The 2.08 s this comment used to quote
2813 # does not reproduce here, but its conclusion does.)
2814 1767 ▶sub _unzip_member {
Subroutine _unzip_member: called CC=4 SCAR=13.9
2815 1767 my ($file, $member) = @_;
2816 1767 my ($handled, $ref) = _unzip_member_fast($file, $member);
2817 1767 ▶ return $ref if $handled;
Branch: 1 branch
BranchTrueFalseTotal
if $handled 1511 256 1767
2818 256 require IO::Uncompress::Unzip;
2819 256 ▶ my $z = IO::Uncompress::Unzip->new($file, Name => $member)
Branch: 1 branch
BranchTrueFalseTotal
my $z = "IO::Uncompress::Unzip"->new($file, "Name", $member) or return undef 232 24 256
2820 or return undef;
2821 232 my $content = '';
2822 232 my ($off, $n) = (0, 0);
2823 232 ▶ while (($n = $z->read($content, 1 << 20, $off)) > 0) { $off += $n }
Branch: 1 branch
BranchTrueFalseTotal
if (($n = $z->read($content, 1048576, $off)) > 0) 231 232 463
2824 232 $z->close;
2825 232 return \$content;
2826 }
2827  
2828 # The same member, read straight out of the archive with Compress::Raw::Zlib
2829 # instead of through IO::Uncompress::Unzip.
2830 #
2831 # Returns a two-element list: (1, \$bytes) for a member it read, (1, undef) for
2832 # an archive it understood that does not hold the member, and (0, undef) for
2833 # anything it declines -- at which point _unzip_member falls back and the old
2834 # path decides. Declining is never an error: this reads the central directory
2835 # and one deflate stream and nothing else, and hands everything beyond that to
2836 # the module that has been ported to all of it.
2837 #
2838 # Why bother: with the worksheet parser in XS since 0.316, decompression is what
2839 # a read of an .xlsx now spends its time on -- 0.239 s of the 0.413 s a
2840 # 21,845 x 50 workbook takes, against 0.015 s to parse its 117,870 shared
2841 # strings. IO::Uncompress::Unzip needs 0.174 s for the 36 MB worksheet part
2842 # where inflating it directly needs 0.052 s, plus 0.004 s to read the 5.5 MB of
2843 # compressed bytes.
2844 #
2845 # Most of that gap is one thing. Unzip.pm's ckParams() sets `crc32 => 1'
2846 # unconditionally ("unzip always needs crc32"), so every byte is run through
2847 # Compress::Raw::Zlib::crc32() -- 0.076 s on this part, more than the inflate
2848 # itself -- and then the comparison against the stored CRC happens only under
2849 # `Strict', which defaults to 0. The check is paid for and not made. This path
2850 # does not compute it either, which is the same answer for the same money;
2851 # asking Inflate for -CRC32 => 1 costs the identical 0.076 s (it is the same
2852 # per-chunk call), so turning it on here would want `Strict'-like behaviour --
2853 # a croak on mismatch -- to be worth anything, and that is a change in what
2854 # read_table does with a damaged file rather than a speed decision.
2855 #
2856 # Bufsize 1<<16: 0.052 s against 0.063 s at the 4 KB default on that part, and
2857 # flat from there (1<<18 through 1<<22 all measure 0.052 s).
2858 #
2859 # Layout constants are ECMA-376's container, i.e. PKWARE's APPNOTE.TXT 6.3.10:
2860 # section 4.3.16 for the end-of-central-directory record, 4.3.12 for a central
2861 # directory entry, 4.3.7 for a local file header.
2862 1793 ▶sub _unzip_member_fast {
Subroutine _unzip_member_fast: called CC=46 SCAR=43.1
2863 1793 my ($file, $member) = @_;
2864 1793 require Compress::Raw::Zlib;
2865 1793 my $fh;
2866 1793 ▶ open $fh, '<', $file or return (0, undef);
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<", $file or return 0, undef 1791 2 1793
2867 1791 binmode $fh;
2868 1791 my $size = -s $fh;
2869 1791 ▶ return (0, undef) unless defined $size && $size >= 22;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $size and $size >= 22 2 1789 1791
Condition66%2/3
defined $size and $size >= 22
!ll&&!rl&&r
021789
MC/DC50%1/2
defined $size and $size >= 22
defined $size $size >= 22
Truth table66%2/3
A and B
A= defined $sizeB= $size >= 22
ABresult
0X0
100
111
2870  
2871 # The EOCD is 22 bytes plus a comment of up to 65535, so it begins no
2872 # earlier than 65557 from the end. Its signature can also occur inside the
2873 # comment (or inside compressed data, for an archive with no comment), so
2874 # a candidate counts only when the record it starts ends exactly at the end
2875 # of the file.
2876 1789 ▶ my $want = $size < 65557 ? $size : 65557;
Branch: 1 branch
BranchTrueFalseTotal
$size < 65557 ? : 1769 20 1789
2877 1789 ▶ seek $fh, $size - $want, 0 or return (0, undef);
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $size - $want, 0 or return 0, undef 1789 0 1789
2878 1789 my $tail = '';
2879 1789 ▶ return (0, undef) unless read($fh, $tail, $want) == $want;
Branch: 1 branch
BranchTrueFalseTotal
unless read($fh, $tail, $want) == $want 0 1789 1789
2880 1789 my ($ncd, $cdsz, $cdoff);
2881 1789 my $at = length($tail) - 22;
2882 1789 ▶ while ($at >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($at >= 0) 1791 0 1791
2883 1791 $at = rindex($tail, "PK\5\6", $at);
2884 1791 ▶ last if $at < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $at < 0 4 1787 1791
2885 1787 my ($d1, $d2, $nd, $nt, $sz, $off, $cmt)
2886 = unpack('x' . ($at + 4) . ' v v v v V V v', $tail);
2887 1787 ▶ if ($at + 22 + $cmt == length $tail) {
Branch: 1 branch
BranchTrueFalseTotal
if ($at + 22 + $cmt == length $tail) 1785 2 1787
2888 # a split archive has its directory somewhere this cannot reach
2889 1785 ▶ return (0, undef) if $d1 || $d2 || $nd != $nt;
Branch: 1 branch
BranchTrueFalseTotal
if $d1 or $d2 or $nd != $nt 0 1785 1785
Condition33%2/6
$d1 or $d2 or $nd != $nt
l!l&&r!l&&!r
001785
$d1 or $d2
l!l&&r!l&&!r
001785
MC/DC0%0/3
$d1 or $d2 or $nd != $nt
$d1 $d2 $nd != $nt
Truth table25%1/4
A or B or C
A= $d1B= $d2C= $nd != $nt
ABCresult
1XX1
01X1
0011
0000
2890 # the zip64 sentinels: the real values are in a record this does
2891 # not read, so hand the whole archive back
2892 1785 ▶ return (0, undef)
Branch: 1 branch
BranchTrueFalseTotal
if $nt == 65535 or $sz == 4294967295 or $off == 4294967295 2 1783 1785
Condition50%3/6
$nt == 65535 or $sz == 4294967295 or $off == 4294967295
l!l&&r!l&&!r
021783
$nt == 65535 or $sz == 4294967295
l!l&&r!l&&!r
001785
MC/DC33%1/3
$nt == 65535 or $sz == 4294967295 or $off == 4294967295
$nt == 65535 $sz == 4294967295 $off == 4294967295
Truth table50%2/4
A or B or C
A= $nt == 65535B= $sz == 4294967295C= $off == 4294967295
ABCresult
1XX1
01X1
0011
0000
2893 if $nt == 0xFFFF || $sz == 0xFFFFFFFF || $off == 0xFFFFFFFF;
2894 1783 ($ncd, $cdsz, $cdoff) = ($nt, $sz, $off);
2895 1783 last;
2896 }
2897 2 $at--;
2898 }
2899 1787 ▶ return (0, undef) unless defined $cdoff;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cdoff 4 1783 1787
2900 1783 ▶ return (0, undef) if $cdoff + $cdsz > $size;
Branch: 1 branch
BranchTrueFalseTotal
if $cdoff + $cdsz > $size 0 1783 1783
2901 1783 ▶ seek $fh, $cdoff, 0 or return (0, undef);
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $cdoff, 0 or return 0, undef 1783 0 1783
2902 1783 my $cd = '';
2903 1783 ▶ return (0, undef) unless read($fh, $cd, $cdsz) == $cdsz;
Branch: 1 branch
BranchTrueFalseTotal
unless read($fh, $cd, $cdsz) == $cdsz 0 1783 1783
2904  
2905 # Walk the directory to the member. Entries are in the order the local
2906 # headers are, so stopping at the first match is what Unzip.pm's own
2907 # sequential scan would have found.
2908 1783 my ($gp, $method, $csz, $usz, $lho);
2909 1783 my $p = 0;
2910 1783 ▶ for (my $i = 0; $i < $ncd; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $ncd) 7063 293 7356
2911 7063 ▶ return (0, undef) if $p + 46 > $cdsz;
Branch: 1 branch
BranchTrueFalseTotal
if $p + 46 > $cdsz 0 7063 7063
2912 7063 ▶ return (0, undef) unless substr($cd, $p, 4) eq "PK\1\2";
Branch: 1 branch
BranchTrueFalseTotal
unless substr($cd, $p, 4) eq "PK\1\2" 253 6810 7063
2913 6810 my ($g, $m, $cs, $us, $nl, $el, $cl, $lo)
2914 = unpack('x' . ($p + 8) . ' v v x8 V V v v v x8 V', $cd);
2915 6810 ▶ return (0, undef) if $p + 46 + $nl + $el + $cl > $cdsz;
Branch: 1 branch
BranchTrueFalseTotal
if $p + 46 + $nl + $el + $cl > $cdsz 0 6810 6810
2916 6810 ▶ if (substr($cd, $p + 46, $nl) eq $member) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($cd, $p + 46, $nl) eq $member) 1237 5573 6810
2917 1237 ($gp, $method, $csz, $usz, $lho) = ($g, $m, $cs, $us, $lo);
2918 1237 last;
2919 }
2920 5573 $p += 46 + $nl + $el + $cl;
2921 }
2922 1530 ▶ return (1, undef) unless defined $lho; # the archive has no such member
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lho 293 1237 1530
2923  
2924 # bit 0 is encryption and bit 6 strong encryption; bit 3 only moves the
2925 # sizes into a trailing descriptor, and the directory's copies (which is
2926 # what is read here) are authoritative either way.
2927 1237 ▶ return (0, undef) if $gp & 0x41;
Branch: 1 branch
BranchTrueFalseTotal
if $gp & 65 0 1237 1237
2928 1237 ▶ return (0, undef) if $method != 0 && $method != 8; # 0 stored, 8 deflate
Branch: 1 branch
BranchTrueFalseTotal
if $method != 0 and $method != 8 0 1237 1237
Condition66%2/3
$method != 0 and $method != 8
!ll&&!rl&&r
7444930
MC/DC0%0/2
$method != 0 and $method != 8
$method != 0 $method != 8
Truth table66%2/3
A and B
A= $method != 0B= $method != 8
ABresult
0X0
100
111
2929 1237 ▶ return (0, undef) if $csz == 0xFFFFFFFF || $usz == 0xFFFFFFFF
Branch: 1 branch
BranchTrueFalseTotal
if $csz == 4294967295 or $usz == 4294967295 or $lho == 4294967295 0 1237 1237
Condition33%2/6
$csz == 4294967295 or $usz == 4294967295 or $lho == 4294967295
l!l&&r!l&&!r
001237
$csz == 4294967295 or $usz == 4294967295
l!l&&r!l&&!r
001237
MC/DC0%0/3
$csz == 4294967295 or $usz == 4294967295 or $lho == 4294967295
$csz == 4294967295 $usz == 4294967295 $lho == 4294967295
Truth table25%1/4
A or B or C
A= $csz == 4294967295B= $usz == 4294967295C= $lho == 4294967295
ABCresult
1XX1
01X1
0011
0000
2930 || $lho == 0xFFFFFFFF; # zip64 again
2931 1237 ▶ return (0, undef) if $lho + 30 > $size;
Branch: 1 branch
BranchTrueFalseTotal
if $lho + 30 > $size 0 1237 1237
2932  
2933 # The local header repeats the name and carries its own extra field, which
2934 # need not be the directory's: only its two lengths are read here, to step
2935 # over them to the data.
2936 1237 ▶ seek $fh, $lho, 0 or return (0, undef);
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $lho, 0 or return 0, undef 1237 0 1237
2937 1237 my $lh = '';
2938 1237 ▶ return (0, undef) unless read($fh, $lh, 30) == 30;
Branch: 1 branch
BranchTrueFalseTotal
unless read($fh, $lh, 30) == 30 0 1237 1237
2939 1237 ▶ return (0, undef) unless substr($lh, 0, 4) eq "PK\3\4";
Branch: 1 branch
BranchTrueFalseTotal
unless substr($lh, 0, 4) eq "PK\3\4" 0 1237 1237
2940 1237 my ($lnl, $lel) = unpack('x26 v v', $lh);
2941 1237 my $data = $lho + 30 + $lnl + $lel;
2942 1237 ▶ return (0, undef) if $data + $csz > $size;
Branch: 1 branch
BranchTrueFalseTotal
if $data + $csz > $size 0 1237 1237
2943 1237 ▶ seek $fh, $data, 0 or return (0, undef);
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $data, 0 or return 0, undef 1237 0 1237
2944 1237 my $comp = '';
2945 1237 ▶ return (0, undef) unless read($fh, $comp, $csz) == $csz;
Branch: 1 branch
BranchTrueFalseTotal
unless read($fh, $comp, $csz) == $csz 0 1237 1237
2946 1237 ▶ close $fh or return (0, undef);
Branch: 1 branch
BranchTrueFalseTotal
close $fh or return 0, undef 1237 0 1237
2947  
2948 1237 ▶ if ($method == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method == 0) 744 493 1237
2949 744 ▶ return (0, undef) unless length($comp) == $usz;
Branch: 1 branch
BranchTrueFalseTotal
unless length $comp == $usz 0 744 744
2950 744 return (1, \$comp);
2951 }
2952 493 my ($inf, $st) = Compress::Raw::Zlib::Inflate->new(
2953 -WindowBits => -Compress::Raw::Zlib::MAX_WBITS(),
2954 -Bufsize => 1 << 16);
2955 493 ▶ return (0, undef) unless $inf;
Branch: 1 branch
BranchTrueFalseTotal
unless $inf 0 493 493
2956 493 my $out = '';
2957 # inflate() eats $comp as it goes, so the two are never both whole
2958 493 $st = $inf->inflate($comp, $out);
2959 493 ▶ return (0, undef) unless $st == Compress::Raw::Zlib::Z_STREAM_END()
Branch: 1 branch
BranchTrueFalseTotal
unless $st == Compress::Raw::Zlib::Z_STREAM_END() or $st == Compress::Raw::Zlib::Z_OK() 0 493 493
Condition33%1/3
$st == Compress::Raw::Zlib::Z_STREAM_END() or $st == Compress::Raw::Zlib::Z_OK()
l!l&&r!l&&!r
49300
MC/DC0%0/2
$st == Compress::Raw::Zlib::Z_STREAM_END() or $st == Compress::Raw::Zlib::Z_OK()
$st == Compress::Raw::Zlib::Z_STREAM_END() $st == Compress::Raw::Zlib::Z_OK()
Truth table33%1/3
A or B
A= $st == Compress::Raw::Zlib::Z_STREAM_END()B= $st == Compress::Raw::Zlib::Z_OK()
ABresult
1X1
011
000
2960 || $st == Compress::Raw::Zlib::Z_OK();
2961 493 ▶ return (0, undef) unless length($out) == $usz;
Branch: 1 branch
BranchTrueFalseTotal
unless length $out == $usz 0 493 493
2962 493 return (1, \$out);
2963 }
2964  
2965 # Decode the five predefined XML entities plus numeric character references,
2966 # the latter as UTF-8 bytes so the result stays byte-consistent with the part it
2967 # came out of (a relationship's Target names an archive member, which is bytes;
2968 # a sheet name is decoded to characters afterwards, by _xlsx_text()). The
2969 # decoding is
2970 # xlsx_xml_uncat() in LikeR.xs, the one the cells go through: up to 0.320 this
2971 # was five substitutions in a row, and a reference the first one produced was
2972 # decoded again by a later one, so "&#38;lt;" came back as "<".
2973 1075 ▶sub _xml_unescape {
Subroutine _xml_unescape: called CC=3 SCAR=11.0
2974 1075 my ($s) = @_;
2975 1075 ▶ return $s unless defined $s && index($s, '&') >= 0;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s and index($s, "&") != -1 1067 8 1075
Condition100%3/3
defined $s and index($s, "&") != -1
!ll&&!rl&&r
110668
MC/DC100%2/2
defined $s and index($s, "&") != -1
defined $s index($s, "&") != -1
Truth table100%3/3
A and B
A= defined $sB= index($s, "&") != -1
ABresult
0X0
100
111
2976 8 return _xml_unescape_xs($s);
2977 }
2978  
2979 # XML text from a workbook part, as characters: the bytes are UTF-8, as an
2980 # .xlsx's XML is, and a string with no non-ASCII character is the same either
2981 # way. Text that is not valid UTF-8 is returned as the bytes it holds, which is
2982 # what utf8::decode() does with it, and what the cells do (xlsx_text_is_utf8()
2983 # in LikeR.xs). Applied to a sheet name here; the cells are decoded in XS.
2984 504 ▶sub _xlsx_text {
Subroutine _xlsx_text: called CC=2 SCAR=7.1
2985 504 my ($s) = @_;
2986 504 ▶ utf8::decode($s) if defined $s;
Branch: 1 branch
BranchTrueFalseTotal
if defined $s 504 0 504
2987 504 return $s;
2988 }
2989  
2990 # A caller's name or token as the characters read_table compares an .xlsx's
2991 # text with, which is what the file's names and cells come back as. A string
2992 # perl holds as characters is returned as it is. One it holds as bytes is
2993 # decoded when the bytes are valid UTF-8 and have a non-ASCII byte, so that a
2994 # name typed in a script without `use utf8`, which is what an .xlsx read
2995 # required of it up to 0.3425, still matches; any other byte string is returned
2996 # as it is, and its bytes are then Latin-1 characters, as perl reads them.
2997 158 ▶sub _as_chars {
Subroutine _as_chars: called CC=3 SCAR=11.0
2998 158 my ($s) = @_;
2999 158 ▶ return $s if !defined $s || utf8::is_utf8($s);
Branch: 1 branch
BranchTrueFalseTotal
if not defined $s or utf8::is_utf8($s) 18 140 158
Condition66%2/3
not defined $s or utf8::is_utf8($s)
l!l&&r!l&&!r
018140
MC/DC50%1/2
not defined $s or utf8::is_utf8($s)
not defined $s utf8::is_utf8($s)
Truth table66%2/3
not(A) or B
A= not defined $sB= utf8::is_utf8($s)
ABresult
1X1
011
000
3000 140 utf8::decode($s);
3001 140 return $s;
3002 }
3003  
3004 # The start tags of every element called $local in $xml, under any namespace
3005 # prefix, as their attribute runs. Comments are taken out first, so that a
3006 # commented-out <sheet> or <Relationship> is not read as one, and a tag is
3007 # matched quote by quote, so that a '>' inside an attribute value -- which XML
3008 # allows unescaped -- does not end it.
3009 #
3010 # Both this and _xml_attr() compile their pattern once per name and keep it.
3011 # Interpolated into the match, it was recompiled on every call (the callers
3012 # alternate names), and perl 5.32's regcomp leaks the inversion lists it builds
3013 # for \s and \w on each compile: 0.3214 failed 14 leak subtests on a 5.32.1
3014 # smoker that no perl in the local matrix could reproduce. The keys are the
3015 # literal names the xlsx reader passes, so the caches stay a few entries long,
3016 # and the qr// is evaluated only on a miss, never inside a warmed leak check
3017 # (5.10.0's pp_qr() leaks an SV each time one is).
3018 508 my (%xml_tag_re, %xml_attr_re);
3019 855 ▶sub _xml_start_tags {
Subroutine _xml_start_tags: called CC=4 SCAR=13.9
3020 855 my ($xml, $local) = @_;
3021 855 ▶ $xml =~ s/<!--.*?-->//gs if index($xml, '<!--') >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($xml, "<!--") != -1 2 853 855
3022 855 ▶ my $re = $xml_tag_re{$local}
Condition100%2/2
$xml_tag_re{$local} ||= qr/<(?:[\w.-]+:)?\Q$local\E\b((?:[^>"']|"[^"]*"|'[^']*')*)>/
l!l
80946
MC/DC100%1/1
$xml_tag_re{$local} ||= qr/<(?:[\w.-]+:)?\Q$local\E\b((?:[^>"']|"[^"]*"|'[^']*')*)>/
$xml_tag_re{$local}
Truth table100%2/2
A
A= $xml_tag_re{$local}
Aresult
11
00
3023 ||= qr{<(?:[\w.-]+:)?\Q$local\E\b((?:[^>"']|"[^"]*"|'[^']*')*)>};
3024 855 my @tags;
3025 855 ▶ while ($xml =~ /$re/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($xml =~ /$re/g) 1073 855 1928
3026 1073 (my $at = $1) =~ s{/\z}{}; # the "/" of a self-closing tag
3027 1073 push @tags, $at;
3028 }
3029 855 return @tags;
3030 }
3031  
3032 # The value of the attribute whose name matches $name (a pattern, so that the
3033 # r:id of a <sheet> can be found under whatever prefix its writer bound) in an
3034 # attribute run from _xml_start_tags, or undef. XML lets a value be quoted with
3035 # '"' or with "'", and up to 0.3213 only the first was read: a workbook written
3036 # with single quotes lost every sheet name, and its sheets were then read by
3037 # file position rather than through their relationships.
3038 2713 ▶sub _xml_attr {
Subroutine _xml_attr: called CC=4 SCAR=13.9
3039 2713 my ($attrs, $name) = @_;
3040 2713 ▶ my $re = $xml_attr_re{$name}
Condition100%2/2
$xml_attr_re{$name} ||= qr/(?:\A|\s)$name\s*=\s*(?:"([^"]*)"|'([^']*)')/
l!l
2598115
MC/DC100%1/1
$xml_attr_re{$name} ||= qr/(?:\A|\s)$name\s*=\s*(?:"([^"]*)"|'([^']*)')/
$xml_attr_re{$name}
Truth table100%2/2
A
A= $xml_attr_re{$name}
Aresult
11
00
3041 ||= qr/(?:\A|\s)$name\s*=\s*(?:"([^"]*)"|'([^']*)')/;
3042 2713 ▶ return undef unless $attrs =~ $re;
Branch: 1 branch
BranchTrueFalseTotal
unless $attrs =~ /$re/ 2 2711 2713
3043 2711 ▶ return defined $1 ? $1 : $2;
Branch: 1 branch
BranchTrueFalseTotal
defined $1 ? : 2701 10 2711
3044 }
3045  
3046 # A relationship's Target as the name of the archive member it points at. A
3047 # target is a URI reference resolved against the part that holds the
3048 # relationship (ECMA-376 Part 2, Open Packaging Conventions), so it is relative
3049 # to xl/, where workbook.xml lives, unless it starts with "/", which makes it
3050 # relative to the package root; "." and ".." segments are resolved. A
3051 # target that already starts with "xl/" is taken as rooted, which is how this
3052 # has always read one.
3053 572 ▶sub _xlsx_part_path {
Subroutine _xlsx_part_path: called CC=7 SCAR=19.5
3054 572 my ($tg) = @_;
3055 572 ▶ my $path = $tg =~ s{\A/+}{} ? $tg : $tg =~ m{\Axl/} ? $tg : "xl/$tg";
Branch: 2 branches
BranchTrueFalseTotal
$tg =~ s[\A/+][] ? : 2 570 572
$tg =~ m[\Axl/] ? : 1 569 570
3056 572 my @seg;
3057 572 for my $s (split m{/}, $path) {
3058 1669 ▶ next if $s eq '' || $s eq '.';
Branch: 1 branch
BranchTrueFalseTotal
if $s eq "" or $s eq "." 4 1665 1669
Condition100%3/3
$s eq "" or $s eq "."
l!l&&r!l&&!r
131665
MC/DC100%2/2
$s eq "" or $s eq "."
$s eq "" $s eq "."
Truth table100%3/3
A or B
A= $s eq ""B= $s eq "."
ABresult
1X1
011
000
3059 1665 ▶ if ($s eq '..') { pop @seg; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($s eq "..") 2 1663 1665
3060 1663 push @seg, $s;
3061 }
3062 572 return join '/', @seg;
3063 }
3064  
3065 # The relationships of xl/workbook.xml, from xl/_rels/workbook.xml.rels:
3066 # { target => { $id => $member, ... }, sst => $member or undef }. 'sst' is the
3067 # shared-string part, found by its relationship Type -- the transitional
3068 # .../officeDocument/2006/relationships/sharedStrings or the strict
3069 # .../officeDocument/relationships/sharedStrings, both ending in
3070 # "/sharedStrings" -- rather than by its usual name: the name is the writer's
3071 # choice, and up to 0.3213 a workbook that stored the part as
3072 # xl/SharedStrings.xml read every string cell as empty.
3073 429 ▶sub _xlsx_rels {
Subroutine _xlsx_rels: called CC=8 SCAR=21.6
3074 429 my ($file) = @_;
3075 429 my (%target, $sst);
3076 429 my $rels = _unzip_member($file, 'xl/_rels/workbook.xml.rels');
3077 429 ▶ if (defined $rels) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rels) 429 0 429
3078 429 for my $at (_xml_start_tags($$rels, 'Relationship')) {
3079 567 my $tg = _xml_attr($at, 'Target');
3080 567 ▶ next unless defined $tg;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tg 0 567 567
3081 567 $tg = _xlsx_part_path(_xml_unescape($tg));
3082 567 my $id = _xml_attr($at, 'Id');
3083 567 my $type = _xml_attr($at, 'Type');
3084 567 ▶ $target{$id} = $tg if defined $id;
Branch: 1 branch
BranchTrueFalseTotal
if defined $id 567 0 567
3085 567 ▶ $sst = $tg if !defined $sst && defined $type && $type =~ m{/sharedStrings\z};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $sst and defined $type and $type =~ m[/sharedStrings\z] 57 510 567
Condition50%3/6
not defined $sst and defined $type and $type =~ m[/sharedStrings\z]
!ll&&!rl&&r
051057
not defined $sst and defined $type
!ll&&!rl&&r
00567
MC/DC33%1/3
not defined $sst and defined $type and $type =~ m[/sharedStrings\z]
not defined $sst defined $type $type =~ m[/sharedStrings\z]
Truth table50%2/4
not(A) and B and C
A= not defined $sstB= defined $typeC= $type =~ m[/sharedStrings\z]
ABCresult
0XX0
10X0
1100
1111
3086 }
3087 }
3088 429 return { target => \%target, sst => $sst };
3089 }
3090  
3091 # Shared strings (optional part): each <si> may hold several <t> runs, which
3092 # are concatenated. Returns an arrayref indexed by shared-string id. The parse
3093 # is xlsx_sst_parse() in LikeR.xs; the two nested regexes it replaces cost
3094 # 0.205 s on an 8 MB table of 117,870 strings. $rels, from _xlsx_rels(), says
3095 # where the part is; a workbook whose relationships do not name one is tried at
3096 # xl/sharedStrings.xml, the name Excel gives it, as it always was.
3097 419 ▶sub _xlsx_shared_strings {
Subroutine _xlsx_shared_strings: called CC=4 SCAR=13.9
3098 419 my ($file, $rels) = @_;
3099 419 ▶ $rels ||= _xlsx_rels($file);
Condition66%2/3
$rels ||= _xlsx_rels($file)
l!l&&r!l&&!r
41720
MC/DC0%0/2
$rels ||= _xlsx_rels($file)
$rels _xlsx_rels($file)
Truth table66%2/3
A ||= B
A= $relsB= _xlsx_rels($file)
ABresult
1X1
011
000
3100 419 ▶ my $ss = _unzip_member($file, $rels->{sst} // 'xl/sharedStrings.xml');
Condition100%2/2
$rels->{"sst"} // "xl/sharedStrings.xml"
l!l
56363
MC/DC100%1/1
$rels->{"sst"} // "xl/sharedStrings.xml"
$rels->{"sst"}
Truth table100%2/2
A
A= $rels->{"sst"}
Aresult
11
00
3101 419 ▶ return defined $ss ? _xlsx_sst_xs($$ss) : [];
Branch: 1 branch
BranchTrueFalseTotal
defined $ss ? : 105 314 419
3102 }
3103  
3104 # The workbook's worksheets, in document order, as a list of
3105 # { name => $sheet_name, path => 'xl/worksheets/sheetN.xml' } hashrefs. The path
3106 # is resolved through workbook.xml.rels ($rels, from _xlsx_rels(), read here
3107 # when it is not given); a sheet with no resolvable relationship (or a workbook
3108 # with no metadata at all) falls back to a positional sheetN.xml.
3109 #
3110 # An element may carry a namespace prefix -- <x:sheet>, as the Open XML SDK
3111 # writes them -- and the relationship id is matched by its local name, since
3112 # the prefix bound to the relationships namespace is the writer's choice. See
3113 # xlsx_ns_prefix() in LikeR.xs for the worksheet side of the same thing.
3114 426 ▶sub _xlsx_sheets {
Subroutine _xlsx_sheets: called CC=9 SCAR=22.7
3115 426 my ($file, $rels) = @_;
3116 426 ▶ $rels ||= _xlsx_rels($file);
Condition66%2/3
$rels ||= _xlsx_rels($file)
l!l&&r!l&&!r
42240
MC/DC0%0/2
$rels ||= _xlsx_rels($file)
$rels _xlsx_rels($file)
Truth table66%2/3
A ||= B
A= $relsB= _xlsx_rels($file)
ABresult
1X1
011
000
3117 426 my $target = $rels->{target};
3118 426 my @sheets;
3119 426 ▶ if (defined(my $wb = _unzip_member($file, 'xl/workbook.xml'))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $wb = _unzip_member($file, "xl/workbook.xml"))) 426 0 426
3120 426 for my $at (_xml_start_tags($$wb, 'sheet')) {
3121 506 my $name = _xml_attr($at, 'name');
3122 506 my $rid = _xml_attr($at, '[\w.-]+:id');
3123 push @sheets, {
3124 name => defined $name ? _xlsx_text(_xml_unescape($name)) : undef,
3125 506 ▶ path => defined $rid ? $target->{$rid} : undef,
Branch: 2 branches
BranchTrueFalseTotal
defined $name ? : 504 2 506
defined $rid ? : 506 0 506
3126 };
3127 }
3128 }
3129 426 ▶ @sheets = ({ name => undef, path => undef }) unless @sheets; # no metadata
Branch: 1 branch
BranchTrueFalseTotal
unless @sheets 0 426 426
3130 # any sheet still lacking a path falls back to its positional worksheet file
3131 $sheets[$_]{path} //= 'xl/worksheets/sheet' . ($_ + 1) . '.xml'
3132 426 ▶ for 0 .. $#sheets;
Condition50%1/2
$sheets[$_]{"path"} //= 'xl/worksheets/sheet' . ($_ + 1) . '.xml'
l!l
5060
MC/DC0%0/1
$sheets[$_]{"path"} //= 'xl/worksheets/sheet' . ($_ + 1) . '.xml'
$sheets[$_]{"path"}
Truth table50%1/2
A
A= $sheets[$_]{"path"}
Aresult
11
00
3133 426 return \@sheets;
3134 }
3135  
3136 # Resolve a 'sheet' argument (undef -> first; a name; or a 1-based index) to one
3137 # of the hashrefs from _xlsx_sheets, dying with a clear message on a bad request.
3138 #
3139 # A name is tried first. A workbook read whole comes back keyed by sheet name,
3140 # and up to 0.3213 any all-digit 'sheet' was an index, so of sheets "2024" and
3141 # "2023" neither key could be asked for again ("sheet index 2023 is out of
3142 # range"), and with sheets "2" and "1", sheet => '1' quietly returned "2". The
3143 # name is compared as characters (see _as_chars), which is how it is read since
3144 # 0.3426; up to 0.3425 it was bytes.
3145 376 ▶sub _xlsx_choose_sheet {
Subroutine _xlsx_choose_sheet: called CC=8 SCAR=20.9
3146 376 my ($file, $sheets, $sheet) = @_;
3147 376 ▶ return $sheets->[0] unless defined $sheet;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sheet 343 33 376
3148 33 my $want = _as_chars($sheet);
3149 33 ▶ my ($chosen) = grep { defined $_->{name} && $_->{name} eq $want } @$sheets;
Condition66%2/3
defined $_->{'name'} && $_->{'name'} eq $want
!ll&&!rl&&r
03426
MC/DC50%1/2
defined $_->{'name'} && $_->{'name'} eq $want
defined $_->{'name'} $_->{'name'} eq $want
Truth table66%2/3
A && B
A= defined $_->{'name'}B= $_->{'name'} eq $want
ABresult
0X0
100
111
3150 33 ▶ return $chosen if $chosen;
Branch: 1 branch
BranchTrueFalseTotal
if $chosen 26 7 33
3151 7 ▶ if ($want =~ /\A[0-9]+\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($want =~ /\A[0-9]+\z/) 4 3 7
3152 4 ▶ die "read_table: sheet index $want is out of range (1..${\ scalar @$sheets}), "
Branch: 1 branch
BranchTrueFalseTotal
if $want < 1 or $want > @$sheets 2 2 4
Condition66%2/3
$want < 1 or $want > @$sheets
l!l&&r!l&&!r
022
MC/DC50%1/2
$want < 1 or $want > @$sheets
$want < 1 $want > @$sheets
Truth table66%2/3
A or B
A= $want < 1B= $want > @$sheets
ABresult
1X1
011
000
3153 . "and no sheet is named '$want', in $file\n"
3154 if $want < 1 || $want > @$sheets;
3155 2 return $sheets->[$want - 1];
3156 }
3157 die "read_table: sheet '$want' not found in $file (have: "
3158 3 ▶ . join(', ', map { defined $_->{name} ? "'$_->{name}'" : '?' } @$sheets)
Branch: 1 branch
BranchTrueFalseTotal
defined $_->{'name'} ? : 6 0 6
3159 . ")\n";
3160 }
3161  
3162 # Parse one worksheet, invoking $callback->(\@fields) once per non-empty row
3163 # (header row included) with all rows padded to the same width -- the same
3164 # contract _parse_csv_file offers read_table's callback, and the same $plan
3165 # fast path: once read_table has filled the plan in, the rows are assembled in
3166 # XS and the callback is not called again. $sst is the shared strings arrayref
3167 # from _xlsx_shared_strings.
3168 #
3169 # The part is decompressed here and parsed by xlsx_ws_scan() in LikeR.xs, which
3170 # is also where the reason it is not done in perl any more is written down.
3171 468 ▶sub _parse_xlsx_sheet {
Subroutine _parse_xlsx_sheet: called CC=2 SCAR=7.0
3172 468 my ($file, $sst, $path, $callback, $plan) = @_;
3173 468 my $ws = _unzip_member($file, $path);
3174 468 ▶ die "read_table: could not read worksheet '$path' in $file\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ws 0 468 468
3175 unless defined $ws;
3176 468 _parse_xlsx_sheet_xs($$ws, $sst, $callback, $plan);
3177 399 return;
3178 }
3179  
3180 # True when a sep regex is pandas' whitespace-delimited spelling. pandas reads
3181 # sep=r"\s+" as delim_whitespace, not as a plain re.split(): leading and
3182 # trailing whitespace on a line make no empty field (pandas 3.0.4,
3183 # tests/io/parser/common/test_common_basic.py, test_ignore_leading_whitespace
3184 # and test_whitespace_regex_separator). R's read.table(sep = "") and Perl's own
3185 # split ' ' treat whitespace the same way. Only the pattern text counts, so
3186 # qr/\s+/x qualifies and qr/[ \t]+/ does not.
3187 829 ▶sub _sep_re_is_ws {
Subroutine _sep_re_is_ws: called CC=2 SCAR=7.0
3188 829 my ($re) = @_;
3189 829 my ($pat) = re::regexp_pattern($re);
3190 829 ▶ return defined $pat && $pat eq '\s+';
Condition66%2/3
defined $pat && $pat eq '\\s+'
!ll&&!rl&&r
0659170
MC/DC50%1/2
defined $pat && $pat eq '\\s+'
defined $pat $pat eq '\\s+'
Truth table66%2/3
A && B
A= defined $patB= $pat eq '\\s+'
ABresult
0X0
100
111
3191 }
3192  
3193 # Compressed input for read_table
3194 #
3195 # A gzip or bzip2 file is recognised by its first bytes, not its name, the way
3196 # R's file() recognises one for read.table: do_url() in src/main/connections.c
3197 # calls comp_type_from_memory() on the first bytes of a file opened "r" or
3198 # "rt" (R-devel 4.7.0, r-source commit b3c233dd). pandas' compression='infer'
3199 # goes by the extension instead; sniffing reads every file pandas would, and a
3200 # compressed one that has lost its suffix too.
3201 #
3202 # The magic numbers are that function's:
3203 # gzip 1f 8b, RFC 1952 section 2.3.1's ID1 and ID2. A method other than
3204 # deflate after them is reported by zlib as corrupt data, as R's
3205 # gzio.h check_header() refuses it.
3206 # bzip2 "BZh" and a block size of '1'..'9', then the 48-bit magic of either
3207 # the first block (0x314159265359, BCD pi) or the end-of-stream
3208 # marker (0x177245385090, BCD sqrt(pi)), which is all an empty stream
3209 # holds -- bzip2 1.0.8 compress.c, BZ_HDR_h/BZ_HDR_0 and the
3210 # bsPutUChar() runs. R added the last six bytes in PR#18768, after a
3211 # text file that began "BZh" was taken for bzip2.
3212 # Neither is how text begins: 0x1f is a control character, 0x8b is not ASCII
3213 # and cannot start a UTF-8 sequence, and the bzip2 test runs to ten bytes.
3214 #
3215 # The same function also recognises four formats this module cannot inflate,
3216 # and they are sniffed only so that read_table can say so: up to 0.3213 an
3217 # .xz file was parsed as text and reported as "Alignment error on x.csv.xz data
3218 # row 2", which sent the reader looking for a ragged row. Their magic numbers
3219 # are comp_type_from_memory()'s as well:
3220 # xz fd "7zXZ" (the .xz container)
3221 # lzma ff "LZMA", or 5d 00 00 80 00 (the two legacy LZMA headers)
3222 # zstd 28 b5 2f fd (RFC 8878 section 3.1.1's Magic_Number)
3223 # lzop 89 "LZO"
3224 # Each begins with a byte that no text file does, or, for the 5d header, holds
3225 # NUL bytes, which no text file does either.
3226 8402 ▶sub _sniff_compression {
Subroutine _sniff_compression: called CC=9 SCAR=22.0
3227 8402 my ($file) = @_;
3228 8402 ▶ open my $fh, '<', $file or return ''; # read_table's own open reports it
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or return "" 8402 0 8402
3229 8402 binmode $fh;
3230 8402 my $got = read $fh, my $head, 10;
3231 8402 close $fh;
3232 8402 ▶ return '' unless $got;
Branch: 1 branch
BranchTrueFalseTotal
unless $got 2 8400 8402
3233 8400 ▶ return 'gzip' if $head =~ /\A\x1f\x8b/;
Branch: 1 branch
BranchTrueFalseTotal
if $head =~ /\A\x1f\x8b/ 685 7715 8400
3234 7715 ▶ return 'bzip2'
Branch: 1 branch
BranchTrueFalseTotal
if $head =~ /\ABZh[1-9](?:\x31\x41\x59\x26\x53\x59|\x17\x72\x45\x38\x50\x90)/ 508 7207 7715
3235 if $head =~ /\ABZh[1-9](?:\x31\x41\x59\x26\x53\x59|\x17\x72\x45\x38\x50\x90)/;
3236 7207 ▶ return 'xz' if $head =~ /\A\xFD7zXZ/;
Branch: 1 branch
BranchTrueFalseTotal
if $head =~ /\A\xFD7zXZ/ 1 7206 7207
3237 7206 ▶ return 'lzma' if $head =~ /\A(?:\xFFLZMA|\x5D\x00\x00\x80\x00)/;
Branch: 1 branch
BranchTrueFalseTotal
if $head =~ /\A(?:\xFFLZMA|\x5D\x00\x00\x80\x00)/ 2 7204 7206
3238 7204 ▶ return 'zstd' if $head =~ /\A\x28\xB5\x2F\xFD/;
Branch: 1 branch
BranchTrueFalseTotal
if $head =~ /\A\x28\xB5\x2F\xFD/ 1 7203 7204
3239 7203 ▶ return 'lzop' if $head =~ /\A\x89LZO/;
Branch: 1 branch
BranchTrueFalseTotal
if $head =~ /\A\x89LZO/ 1 7202 7203
3240 7202 return '';
3241 }
3242  
3243 # True when $file's lines end in a bare CR, as classic Mac OS wrote them.
3244 # R's scan() and pandas' C tokenizer both take a lone CR as a line end (R
3245 # 4.6.1 tests/reg-tests-1a.R, PR#2469; pandas 3.0.4
3246 # tests/io/parser/test_textreader.py, test_cr_delimited); _parse_csv_file()
3247 # reads LF and CRLF only, and handed such a file back as one long header.
3248 #
3249 # The file is taken for one only when what is read of it holds a CR and no LF
3250 # outside a quoted field, so an LF or CRLF file with a stray CR in its first
3251 # line still reads as it always has. A line break inside quotes is part of a
3252 # cell, not a line end: up to 0.33 any LF counted, so a CR file with one quoted
3253 # cell holding an LF was split on LF, and 'a,b\r1,"x\ny"\r2,z\r' came back as
3254 # the one row a, b1, "x\ny2", z where R 4.6.1's read.csv() and pandas 3.0.4's
3255 # read_csv() both read a, b over (1, "x\ny") and (2, z). Quotes are counted
3256 # as _parse_csv_file() counts them -- every '"' opens or closes one, a doubled
3257 # '""' doing both -- unless $quote is false (quote => ''). A CR that ends the
3258 # block may be the first half of a CRLF, so the block is extended past it. 64
3259 # KB is one read; reading stops at 1 MB, which bounds the cost for a file with
3260 # no line end in its first megabyte, and reads that one as LF, as it was read
3261 # before.
3262 8397 ▶sub _eol_is_cr {
Subroutine _eol_is_cr: called CC=18 SCAR=29.0
3263 8397 my ($file, $codec, $quote) = @_;
3264 # not on a compressed handle: it is opened :raw already, and a bare binmode
3265 # is :raw, which can pop the via layer that is doing the decompressing
3266 8397 ▶ my $fh = $codec ? _open_decompressed($file, $codec) : _open_read($file);
Branch: 1 branch
BranchTrueFalseTotal
$codec ? : 1193 7204 8397
3267 8396 ▶ binmode $fh unless $codec;
Branch: 1 branch
BranchTrueFalseTotal
unless $codec 7204 1192 8396
3268 8396 my $buf = '';
3269 8396 my $eof = 0;
3270 8396 my $in_q = 0; # the scan is inside a quoted field
3271 8396 my $cr = 0; # a CR outside quotes has been seen
3272 8396 my $lf = 0; # an LF outside quotes has been seen
3273 8396 ▶ my $class = $quote ? qr/["\r\n]/ : qr/[\r\n]/;
Branch: 1 branch
BranchTrueFalseTotal
$quote ? : 8218 178 8396
3274 8396 pos($buf) = 0;
3275 8396 ▶ while (length $buf < 1 << 20) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $buf < 1048576) 8440 0 8440
3276 8440 ▶ my $at = pos($buf) // 0; # where the scan resumes in the grown block
Condition50%1/2
pos $buf // 0
l!l
84400
MC/DC0%0/1
pos $buf // 0
pos $buf
Truth table50%1/2
A
A= pos $buf
Aresult
11
00
3277 8440 my $got = read $fh, $buf, 1 << 16, length $buf;
3278 7378 ▶ if (!$got) { $eof = 1; last }
Branch: 1 branch
BranchTrueFalseTotal
unless ($got) 46 7332 7378
3279 7332 pos($buf) = $at;
3280 7332 ▶ while ($buf =~ /$class/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($buf =~ /$class/g) 16658 54 16712
3281 16658 my $c = substr($buf, pos($buf) - 1, 1);
3282 16658 ▶ if ($c eq '"') { $in_q = !$in_q }
Branch: 3 branches
BranchTrueFalseTotal
if ($c eq '"') { } 9079 7579 16658
elsif ($in_q) { } 65 7514 7579
elsif ($c eq "\n") { } 7278 236 7514
3283 65 elsif ($in_q) { next }
3284 7278 elsif ($c eq "\n") { $lf = 1; last }
3285 236 else { $cr = 1 }
3286 }
3287 7332 ▶ last if $lf;
Branch: 1 branch
BranchTrueFalseTotal
if $lf 7278 54 7332
3288 54 ▶ last if $cr && substr($buf, -1) ne "\r";
Branch: 1 branch
BranchTrueFalseTotal
if $cr and substr($buf, -1) ne "\r" 10 44 54
Condition100%3/3
$cr and substr($buf, -1) ne "\r"
!ll&&!rl&&r
53910
MC/DC100%2/2
$cr and substr($buf, -1) ne "\r"
$cr substr($buf, -1) ne "\r"
Truth table100%3/3
A and B
A= $crB= substr($buf, -1) ne "\r"
ABresult
0X0
100
111
3289 44 pos($buf) = length $buf;
3290 }
3291 7334 _close($fh);
3292 7334 ▶ return 0 if $lf || !$cr;
Branch: 1 branch
BranchTrueFalseTotal
if $lf or not $cr 7286 48 7334
Condition100%3/3
$lf or not $cr
l!l&&r!l&&!r
7278848
MC/DC100%2/2
$lf or not $cr
$lf not $cr
Truth table100%3/3
A or not(B)
A= $lfB= not $cr
ABresult
1X1
011
000
3293 48 ▶ return 1 if $eof || substr($buf, -1) ne "\r";
Branch: 1 branch
BranchTrueFalseTotal
if $eof or substr($buf, -1) ne "\r" 48 0 48
Condition66%2/3
$eof or substr($buf, -1) ne "\r"
l!l&&r!l&&!r
38100
MC/DC0%0/2
$eof or substr($buf, -1) ne "\r"
$eof substr($buf, -1) ne "\r"
Truth table66%2/3
A or B
A= $eofB= substr($buf, -1) ne "\r"
ABresult
1X1
011
000
3294 0 return 0; # 1 MB ending in a CR whose partner was not read: as before
3295 }
3296  
3297 # An input handle on the decompressed text of $file, streamed through the
3298 # PerlIO::via layer below, so a multi-gigabyte .tsv.gz is inflated a buffer
3299 # at a time as the parser reads it rather than into memory first. Both halves
3300 # are core: PerlIO::via since 5.8, Compress::Raw::Zlib since 5.9.4 and
3301 # Compress::Raw::Bzip2 since 5.10.1, the oldest perl this supports. The bzip2
3302 # one is still loaded only when a bzip2 file is read, and its absence reported
3303 # as what it is: some vendors' perls ship core modules as separate packages.
3304 1439 ▶sub _open_decompressed {
Subroutine _open_decompressed: called CC=4 SCAR=13.9
3305 1439 my ($file, $codec) = @_;
3306 1439 require PerlIO::via;
3307 1439 my $layer;
3308 1439 ▶ if ($codec eq 'gzip') {
Branch: 1 branch
BranchTrueFalseTotal
if ($codec eq 'gzip') { } 868 571 1439
3309 868 require Compress::Raw::Zlib;
3310 868 $layer = 'Stats::LikeR::_Gunzip';
3311 } else {
3312 571 ▶ eval { require Compress::Raw::Bzip2; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Compress::Raw::Bzip2; 1 } } or die qq[read_table: "$file" is bzip2-compressed, and reading it ] . "needs Compress::Raw::Bzip2, which is not installed\n" 570 1 571
3313 or die "read_table: \"$file\" is bzip2-compressed, and reading it "
3314 . "needs Compress::Raw::Bzip2, which is not installed\n";
3315 570 $layer = 'Stats::LikeR::_Bunzip2';
3316 }
3317 # PUSHED is given no file name, so it reads this one while the open runs.
3318 1438 local $Stats::LikeR::_Decompress::name = $file;
3319 1438 my $fh;
3320 1438 ▶ open $fh, "<:raw:via($layer)", $file
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<:raw:via($layer)", $file or _io_die("Can't open '${file}' for reading: '$!'") 1438 0 1438
3321 or _io_die("Can't open '$file' for reading: '$!'");
3322 1438 return $fh;
3323 }
3324  
3325 # A copy of $s as the bytes read_table compares it with. Every field comes
3326 # back from the file as the bytes it holds -- UTF-8 ones for an .xlsx and for
3327 # any CSV written as UTF-8 -- and a literal sep or comment marker already meets
3328 # them that way, since the parser takes its bytes from SvPV. A name or token
3329 # the caller holds as characters (under `use utf8`, or decoded from anywhere)
3330 # is encoded the same way here before it is compared with a field. Up to
3331 # 0.3213 na_strings => "\x{2014}", sheet => "Donn\x{e9}es" and a filter or
3332 # row_names key of the same kind never matched what the file plainly held. A
3333 # string perl holds as bytes is returned as it is.
3334 #
3335 # The encoded copy is made by stringifying, because the argument may be a copy
3336 # of a shared hash key (a filter's or colClasses' key), and on perl 5.32
3337 # utf8::encode() of a plain copy of one leaves it looking up as the key it came
3338 # from (see the keep_cols spellings in read_table).
3339 1859 ▶sub _as_bytes {
Subroutine _as_bytes: called CC=3 SCAR=11.0
3340 1859 my ($s) = @_;
3341 1859 ▶ return $s unless defined $s && utf8::is_utf8($s);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s and utf8::is_utf8($s) 1841 18 1859
Condition66%2/3
defined $s and utf8::is_utf8($s)
!ll&&!rl&&r
0184118
MC/DC50%1/2
defined $s and utf8::is_utf8($s)
defined $s utf8::is_utf8($s)
Truth table66%2/3
A and B
A= defined $sB= utf8::is_utf8($s)
ABresult
0X0
100
111
3342 18 $s = "$s";
3343 18 utf8::encode($s);
3344 18 return $s;
3345 }
3346  
3347 # warn() of a message that may hold characters past Latin-1, as read_table's
3348 # can since 0.3426 returns an .xlsx's names as characters. From perl 5.18 on,
3349 # warn() of such a string warns "Wide character in warn", which this file's
3350 # FATAL warnings turn into a die; the message is encoded to the UTF-8 perl
3351 # would have printed instead.
3352 510 ▶sub _warn_text {
Subroutine _warn_text: called CC=2 SCAR=6.9
3353 510 my $m = join '', @_;
3354 510 ▶ utf8::encode($m) if utf8::is_utf8($m);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($m) 2 508 510
3355 510 warn $m;
3356 }
3357  
3358 8937 ▶sub read_table {
Subroutine read_table: called CC=161 SCAR=50.9
Pod documented
3359 8937 my $file = shift;
3360 # without a name, -f would die on the fatal "uninitialized" warning instead
3361 8937 ▶ _usage_error('read_table', 'file name missing') unless defined $file;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file 2 8935 8937
3362 8935 ▶ die "read_table: \"$file\" is not a file\n" unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 4 8931 8935
3363 8931 ▶ die "read_table: \"$file\" is not readable\n" unless -r $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $file 0 8931 8931
3364  
3365 8931 my %input_args = @_;
3366 8931 ▶ if (exists $input_args{delim}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $input_args{"delim"}) 7 8924 8931
3367 # FIX: sep + delim together used to silently prefer delim
3368 _usage_error('read_table', "pass either 'sep' or 'delim', not both")
3369 7 ▶ if exists $input_args{sep};
Branch: 1 branch
BranchTrueFalseTotal
if exists $input_args{"sep"} 3 4 7
3370 4 $input_args{sep} = delete $input_args{delim};
3371 }
3372 # One option, three names: 'na_strings' is R's na.strings, 'na_values' is
3373 # pandas', and 'undef_val' is what write_table calls the same token on the
3374 # way out, so a round trip can be written with one spelling on both halves.
3375 # Only one may be given, for the same reason 'sep' and 'delim' may not both
3376 # be. The names are checked in a fixed order so the message is
3377 # deterministic. The dotted 'na.strings' and 'undef.val' are refused as
3378 # unknown arguments.
3379 {
3380 8928 my @given = grep { exists $input_args{$_} }
3381 qw(na_strings na_values undef_val);
3382 _usage_error('read_table', "pass only one of 'na_strings', 'na_values' or "
3383 8928 ▶ . "'undef_val'; got " . join(', ', map { "'$_'" } @given))
Branch: 1 branch
BranchTrueFalseTotal
if @given > 1 7 8921 8928
3384 if @given > 1;
3385 8921 ▶ $input_args{'na_strings'} = delete $input_args{ $given[0] } if @given;
Branch: 1 branch
BranchTrueFalseTotal
if @given 301 8620 8921
3386 }
3387  
3388 # An Excel workbook by its name: .xlsx, and the macro-enabled .xlsm and the
3389 # two template forms .xltx and .xltm, which hold their sheets in the same
3390 # parts (ECMA-376 differs only in the main part's content type). Up to
3391 # 0.3213 only .xlsx was recognised, and an .xlsm was read as text and
3392 # reported as an alignment error in a ragged row.
3393 8921 my $is_xlsx = $file =~ /\.xl(?:sx|sm|tx|tm)\z/i;
3394 # What a name or token the caller passes is turned into before it is
3395 # compared with a field: the bytes a delimited file holds, but the
3396 # characters an .xlsx's names and cells are (see _as_bytes, _as_chars)
3397 8921 ▶ my $as_field = $is_xlsx ? \&_as_chars : \&_as_bytes;
Branch: 1 branch
BranchTrueFalseTotal
$is_xlsx ? : 519 8402 8921
3398 8921 ▶ my $codec = $is_xlsx ? '' : _sniff_compression($file);
Branch: 1 branch
BranchTrueFalseTotal
$is_xlsx ? : 519 8402 8921
3399 8921 ▶ die "read_table: \"$file\" is $codec-compressed, which read_table cannot "
Branch: 1 branch
BranchTrueFalseTotal
if $codec =~ /\A(?:xz|lzma|zstd|lzop)\z/ 5 8916 8921
3400 . "decompress; decompress it first, or recompress it with gzip or bzip2\n"
3401 if $codec =~ /\A(?:xz|lzma|zstd|lzop)\z/;
3402 # quote => '' makes '"' text, so it opens no quoted field for the line-end
3403 # scan either; the value itself is checked further down
3404 my $cr_eol = $is_xlsx ? 0 : _eol_is_cr($file, $codec,
3405 8916 ▶ !(defined $input_args{quote} && !ref $input_args{quote} && $input_args{quote} eq '')); # lines end in a bare CR
Branch: 1 branch
BranchTrueFalseTotal
$is_xlsx ? : 519 8397 8916
Condition100%6/6
defined $input_args{'quote'} && !ref($input_args{'quote'}) && $input_args{'quote'} eq ''
!ll&&!rl&&r
82154178
defined $input_args{"quote"} and not ref $input_args{"quote"}
!ll&&!rl&&r
82141182
MC/DC100%3/3
defined $input_args{'quote'} && !ref($input_args{'quote'}) && $input_args{'quote'} eq ''
defined $input_args{"quote"} not ref $input_args{"quote"} $input_args{'quote'} eq ''
Truth table100%4/4
A and not(B) && C
A= defined $input_args{"quote"}B= not ref $input_args{"quote"}C= $input_args{'quote'} eq ''
ABCresult
0XX0
10X0
1100
1111
3406 7853 ▶ my $eol = $cr_eol ? "\r" : "\n";
Branch: 1 branch
BranchTrueFalseTotal
$cr_eol ? : 48 7805 7853
3407 # The extension only picks the default sep, and a compressed file's is
3408 # that of the text inside it: x.tsv.gz is tab-separated.
3409 7853 ▶ (my $sep_name = $file) =~ s/\.(?:gz|bgz|bz2)\z//i if $codec;
Branch: 1 branch
BranchTrueFalseTotal
if $codec 130 7723 7853
3410 7853 ▶ $sep_name = $file unless $codec;
Branch: 1 branch
BranchTrueFalseTotal
unless $codec 7723 130 7853
3411 # A VCF (VCF 4.2/4.3 spec, section 1: "##" meta-information lines, then
3412 # one "#CHROM POS ID REF ALT QUAL FILTER INFO [FORMAT sample...]" header
3413 # line, then tab-separated data) is read with its own defaults: sep is a
3414 # tab, the comment marker is "##" so that only the meta lines are
3415 # comments, and the "#" in front of CHROM comes off (see $finalize_header).
3416 7853 my $is_vcf = $sep_name =~ /\.vcf\z/i;
3417 7853 ▶ my $default_sep = $is_vcf || $sep_name =~ /\.tsv\z/i ? "\t" : ',';
Branch: 1 branch
BranchTrueFalseTotal
$is_vcf || $sep_name =~ /\.tsv\z/i ? : 897 6956 7853
Condition100%3/3
$is_vcf or $sep_name =~ /\.tsv\z/i
l!l&&r!l&&!r
2466516956
MC/DC100%2/2
$is_vcf or $sep_name =~ /\.tsv\z/i
$is_vcf $sep_name =~ /\.tsv\z/i
Truth table100%3/3
A or B
A= $is_vcfB= $sep_name =~ /\.tsv\z/i
ABresult
1X1
011
000
3418 7853 ▶ my %args = (
Branch: 1 branch
BranchTrueFalseTotal
$is_vcf ? : 246 7607 7853
3419 sep => $default_sep, comment => $is_vcf ? '##' : '#', %input_args,
3420 );
3421  
3422 7853 my %allowed_args = map { $_ => 1 } (
3423 'comment', 'output_type', 'filter', 'row_names', 'sep',
3424 'auto_row_names', 'sheet', 'na_strings', 'header', 'col_names', 'quote',
3425 'explode', 'colClasses', 'drop_cols', 'keep_cols',
3426 # private, undocumented: the multi-sheet expansion passes an already
3427 # parsed worksheet list / shared-string table to each per-sheet recursion
3428 # so a big sharedStrings.xml is not re-decompressed once per worksheet.
3429 '_xlsx_sheets', '_sst', '_sheet_ix',
3430 # private, for t/read_table.filter.t: keep every row in the perl
3431 # closure, which is the reference the parser's filter path is held to
3432 '_closure',
3433 );
3434 7853 my @undef_args = sort grep { !$allowed_args{$_} } keys %args;
3435 7853 ▶ _usage_error('read_table', "unknown argument(s): @undef_args") if @undef_args;
Branch: 1 branch
BranchTrueFalseTotal
if @undef_args 5 7848 7853
3436 # explode => 1, the default for a VCF read with its header: every sample
3437 # column is split on ':' into one column per FORMAT key, and the table is
3438 # a hoh keyed by CHROM:POS:REF:ALT (see _vcf_explode). Without a header
3439 # there is no FORMAT column to split by, so header => 0 reads it plain.
3440 7848 ▶ if (exists $args{explode}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"explode"}) 171 7677 7848
3441 171 ▶ _usage_error('read_table', "'explode' applies only to a VCF (.vcf, .vcf.gz or "
Branch: 1 branch
BranchTrueFalseTotal
unless $is_vcf 1 170 171
3442 . ".vcf.bgz), and \"$file\" is not named as one")
3443 unless $is_vcf;
3444 _usage_error('read_table', "'explode' must be 0 or 1")
3445 unless defined $args{explode} && !ref $args{explode}
3446 170 ▶ && $args{explode} =~ /\A[01]?\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"explode"} and not ref $args{"explode"} and $args{"explode"} =~ /\A[01]?\z/ 2 168 170
Condition83%5/6
defined $args{"explode"} and not ref $args{"explode"} and $args{"explode"} =~ /\A[01]?\z/
!ll&&!rl&&r
11168
defined $args{"explode"} and not ref $args{"explode"}
!ll&&!rl&&r
10169
MC/DC66%2/3
defined $args{"explode"} and not ref $args{"explode"} and $args{"explode"} =~ /\A[01]?\z/
defined $args{"explode"} not ref $args{"explode"} $args{"explode"} =~ /\A[01]?\z/
Truth table75%3/4
A and not(B) and C
A= defined $args{"explode"}B= not ref $args{"explode"}C= $args{"explode"} =~ /\A[01]?\z/
ABCresult
0XX0
10X0
1100
1111
3447 }
3448 my $explode = $is_vcf && ($args{explode} // 1)
3449 7845 ▶ && !(exists $args{header} && defined $args{header} && !$args{header});
Condition85%12/14
$is_vcf && ($args{'explode'} // 1) && !(exists $args{'header'} && defined $args{'header'} && !$args{'header'})
!ll&&!rl&&r
7762578
$is_vcf and $args{"explode"} // 1
!ll&&!rl&&r
760116183
$args{"explode"} // 1
l!l
16876
exists $args{'header'} && defined $args{'header'} && !$args{'header'}
!ll&&!rl&&r
7805
exists $args{"header"} and defined $args{"header"}
!ll&&!rl&&r
7805
MC/DC20%1/5
$is_vcf && ($args{'explode'} // 1) && !(exists $args{'header'} && defined $args{'header'} && !$args{'header'})
$is_vcf $args{"explode"} exists $args{"header"} defined $args{"header"} !$args{'header'}
Truth table33%2/6
A and B && not(C and D && not(E))
A= $is_vcfB= $args{"explode"}C= exists $args{"header"}D= defined $args{"header"}E= !$args{'header'}
ABCDEresult
0XXXX0
10XXX0
111110
110XX1
1110X1
111101
3450 # keep_cols and drop_cols: the columns kept, and the columns left out, by
3451 # name. Each is a column name, a qr//, or a list of either, tried against
3452 # each column's name once the header is fixed (see $finalize_header); undef
3453 # is no selection at all. A plain string is a whole name, compared with eq,
3454 # and a qr// is a pattern. A column is stored when keep_cols, if given,
3455 # names or matches it and drop_cols does not. It is what keeps a wide
3456 # file's unwanted columns from ever being stored, so the entries are checked
3457 # here, before the file is opened.
3458 7845 my %sel; # keep / drop => { names => [...], name => {...}, rx => [...] }; absent when not given
3459 7845 for my $opt ('keep_cols', 'drop_cols') {
3460 15681 ▶ next unless defined $args{$opt};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{$opt} 13528 2153 15681
3461 2153 ▶ my @ent = ref $args{$opt} eq 'ARRAY' ? @{ $args{$opt} } : ($args{$opt});
Branch: 1 branch
BranchTrueFalseTotal
ref $args{$opt} eq 'ARRAY' ? : 1102 1051 2153
3462 _usage_error('read_table', "'$opt' must be a column name, a qr// regex, or an "
3463 . "ARRAY reference of them")
3464 2153 ▶ if !@ent || grep { !defined($_) || (ref($_) && ref($_) ne 'Regexp') } @ent;
Branch: 1 branch
BranchTrueFalseTotal
if not @ent or grep {not defined $_ or ref $_ and ref $_ ne "Regexp";} @ent 20 2133 2153
Condition100%9/9
not @ent or grep {not defined $_ or ref $_ and ref $_ ne "Regexp";} @ent
l!l&&r!l&&!r
4162133
!defined($_) || ref $_ && ref $_ ne 'Regexp'
l!l&&r!l&&!r
5114429
ref $_ and ref $_ ne "Regexp"
!ll&&!rl&&r
3340108911
MC/DC100%2/2
not @ent or grep {not defined $_ or ref $_ and ref $_ ne "Regexp";} @ent
not @ent grep {not defined $_ or ref $_ and ref $_ ne "Regexp";} @ent
MC/DC100%3/3
!defined($_) || ref $_ && ref $_ ne 'Regexp'
!defined($_) ref $_ ref $_ ne "Regexp"
Truth table100%3/3
not(A) or B
A= not @entB= grep {not defined $_ or ref $_ and ref $_ ne "Regexp";} @ent
ABresult
1X1
011
000
Truth table100%4/4
not(A) || B and C
A= !defined($_)B= ref $_C= ref $_ ne "Regexp"
ABCresult
1XX1
0111
00X0
0100
3465 # The names, once each and in the order given, which is the order a
3466 # name that is no column is reported in. {name} is what a header name
3467 # is looked up in: a hash key is compared as the characters it spells,
3468 # so a name held as characters and the same name held as Latin-1 bytes
3469 # are one key.
3470 2133 my (@names, %name);
3471 2133 for my $n (grep { !ref $_ } @ent) {
3472 3336 ▶ push @names, $n unless $name{$n}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $name{$n}++ 3304 32 3336
3473 }
3474 $sel{ $opt eq 'keep_cols' ? 'keep' : 'drop' } = {
3475 names => \@names, name => \%name,
3476 # qr// is every column, on every perl: see _rx_for_match()
3477 2133 ▶ rx => [ map { _rx_for_match($_) } grep { ref $_ } @ent ],
Branch: 1 branch
BranchTrueFalseTotal
$opt eq 'keep_cols' ? : 941 1192 2133
3478 };
3479 }
3480 # An exploded VCF is built from the file's own columns by position (FORMAT
3481 # and each sample), so there is no column to choose until it has been
3482 # exploded, by which time it has been stored.
3483 7825 for my $opt (grep { defined $args{$_} } 'keep_cols', 'drop_cols') {
3484 2132 ▶ _usage_error('read_table', "'$opt' cannot be used with an exploded VCF; pass "
Branch: 1 branch
BranchTrueFalseTotal
if $explode 6 2126 2132
3485 . "explode => 0 to read the file's own columns")
3486 if $explode;
3487 }
3488 7819 ▶ my $otype = $args{'output_type'} // ($explode ? 'hoh' : 'aoh');
Branch: 1 branch
BranchTrueFalseTotal
$explode ? : 22 1659 1681
Condition100%2/2
$args{"output_type"} // ($explode ? "hoh" : "aoh")
l!l
61381681
MC/DC100%1/1
$args{"output_type"} // ($explode ? "hoh" : "aoh")
$args{"output_type"}
Truth table100%2/2
A
A= $args{"output_type"}
Aresult
11
00
3489 7819 ▶ _usage_error('read_table', "output_type \"$otype\" isn't allowed (aoa, aoh, hoa, hoh)")
Branch: 1 branch
BranchTrueFalseTotal
unless $otype =~ /^(?:aoa|aoh|hoa|hoh)$/ 4 7815 7819
3490 unless $otype =~ m/^(?:aoa|aoh|hoa|hoh)$/;
3491 # Only a hoh is keyed by a column. An aoa is positional, and an aoh or hoa
3492 # keeps every column as data, so a row_names column would only be a column
3493 # like any other. Up to 0.3213 an aoh or hoa checked the name against the
3494 # header and then ignored it, which read as though it had done something.
3495 _usage_error('read_table', "'row_names' has no meaning for output_type \"$otype\"; "
3496 . "the row names column is read as an ordinary column")
3497 7815 ▶ if $otype ne 'hoh' && defined $args{'row_names'};
Branch: 1 branch
BranchTrueFalseTotal
if $otype ne "hoh" and defined $args{"row_names"} 18 7797 7815
Condition100%3/3
$otype ne "hoh" and defined $args{"row_names"}
!ll&&!rl&&r
1011678618
MC/DC100%2/2
$otype ne "hoh" and defined $args{"row_names"}
$otype ne "hoh" defined $args{"row_names"}
Truth table100%3/3
A and B
A= $otype ne "hoh"B= defined $args{"row_names"}
ABresult
0X0
100
111
3498 # compared with the header's bytes, both here and in _vcf_explode()
3499 7797 ▶ $args{'row_names'} = $as_field->($args{'row_names'}) if defined $args{'row_names'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"row_names"} 396 7401 7797
3500 # 'sheet' picks a worksheet, which only an .xlsx has; it was ignored on
3501 # any other file up to 0.3213, as 'explode' is refused on a non-VCF.
3502 _usage_error('read_table', "'sheet' applies only to an .xlsx, and \"$file\" is not "
3503 . "named as one")
3504 7797 ▶ if defined $args{sheet} && !$is_xlsx;
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"sheet"} and not $is_xlsx 1 7796 7797
Condition100%3/3
defined $args{"sheet"} and not $is_xlsx
!ll&&!rl&&r
7763331
MC/DC100%2/2
defined $args{"sheet"} and not $is_xlsx
defined $args{"sheet"} not $is_xlsx
Truth table100%3/3
A and not(B)
A= defined $args{"sheet"}B= not $is_xlsx
ABresult
0X0
100
111
3505 # A qr// separator is found by perl's regex engine; any other sep is
3506 # a literal string, as it has always been. A regex is not looked at for an
3507 # .xlsx, where a literal sep is not either.
3508 7796 ▶ if (ref $args{sep} && ref $args{sep} ne 'Regexp') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args{"sep"} and ref $args{"sep"} ne "Regexp") 2 7794 7796
Condition100%3/3
ref $args{"sep"} and ref $args{"sep"} ne "Regexp"
!ll&&!rl&&r
69728222
MC/DC100%2/2
ref $args{"sep"} and ref $args{"sep"} ne "Regexp"
ref $args{"sep"} ref $args{"sep"} ne "Regexp"
Truth table100%3/3
A and B
A= ref $args{"sep"}B= ref $args{"sep"} ne "Regexp"
ABresult
0X0
100
111
3509 _usage_error('read_table', "'sep' must be a string or a qr// regex, not a "
3510 2 . ref($args{sep}) . " reference");
3511 }
3512 7794 ▶ my $sep_re = (ref $args{sep} && !$is_xlsx) ? $args{sep} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $args{'sep'} && !$is_xlsx ? : 821 6973 7794
Condition100%3/3
ref $args{"sep"} and not $is_xlsx
!ll&&!rl&&r
69721821
MC/DC100%2/2
ref $args{"sep"} and not $is_xlsx
ref $args{"sep"} not $is_xlsx
Truth table100%3/3
A and not(B)
A= ref $args{"sep"}B= not $is_xlsx
ABresult
0X0
100
111
3513 # Refused before the file is read, so that qr/\s*/ fails the same way
3514 # whatever the file holds. A pattern that matches nothing but an empty
3515 # string -- a bare lookahead, say -- passes this, and is refused where it
3516 # first matches one anywhere but at the start of a line.
3517 7794 ▶ _usage_error('read_table', "the sep regex $sep_re matches an empty string; it must "
Branch: 1 branch
BranchTrueFalseTotal
if $sep_re and "" =~ /\A(?:$sep_re)\z/ 1 7793 7794
Condition100%3/3
$sep_re and "" =~ /\A(?:$sep_re)\z/
!ll&&!rl&&r
69738201
MC/DC100%2/2
$sep_re and "" =~ /\A(?:$sep_re)\z/
$sep_re "" =~ /\A(?:$sep_re)\z/
Truth table100%3/3
A and B
A= $sep_reB= "" =~ /\A(?:$sep_re)\z/
ABresult
0X0
100
111
3518 . "match at least one character")
3519 if $sep_re && '' =~ /\A(?:$sep_re)\z/;
3520 # header => 0 is R's header = FALSE and pandas' header=None: the first line
3521 # is data, and the columns are named by 'col_names' or, as R names them,
3522 # V1, V2, ... 'col_names' with a header renames its columns, as in R.
3523 # '' is allowed as well as 0, since that is what perl's own false is:
3524 # header => ($n > 0) must not be refused when it is false.
3525 7793 my $want_header = 1;
3526 7793 ▶ if (exists $args{header}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"header"}) 295 7498 7793
3527 _usage_error('read_table', "'header' must be 0 or 1")
3528 unless defined $args{header} && !ref $args{header}
3529 295 ▶ && $args{header} =~ /\A[01]?\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"header"} and not ref $args{"header"} and $args{"header"} =~ /\A[01]?\z/ 4 291 295
Condition100%6/6
defined $args{"header"} and not ref $args{"header"} and $args{"header"} =~ /\A[01]?\z/
!ll&&!rl&&r
22291
defined $args{"header"} and not ref $args{"header"}
!ll&&!rl&&r
11293
MC/DC100%3/3
defined $args{"header"} and not ref $args{"header"} and $args{"header"} =~ /\A[01]?\z/
defined $args{"header"} not ref $args{"header"} $args{"header"} =~ /\A[01]?\z/
Truth table100%4/4
A and not(B) and C
A= defined $args{"header"}B= not ref $args{"header"}C= $args{"header"} =~ /\A[01]?\z/
ABCresult
0XX0
10X0
1100
1111
3530 291 ▶ $want_header = $args{header} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$args{'header'} ? : 1 290 291
3531 }
3532 7789 my $col_names = $args{'col_names'};
3533 7789 ▶ if (defined $col_names) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $col_names) 110 7679 7789
3534 110 ▶ _usage_error('read_table', "'col_names' must be an ARRAY reference of names")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $col_names eq "ARRAY" and @$col_names 3 107 110
Condition100%3/3
ref $col_names eq "ARRAY" and @$col_names
!ll&&!rl&&r
21107
MC/DC100%2/2
ref $col_names eq "ARRAY" and @$col_names
ref $col_names eq "ARRAY" @$col_names
Truth table100%3/3
A and B
A= ref $col_names eq "ARRAY"B= @$col_names
ABresult
0X0
100
111
3535 unless ref $col_names eq 'ARRAY' && @$col_names;
3536 107 for my $n (@$col_names) {
3537 556 ▶ _usage_error('read_table', "'col_names' may only hold defined, plain strings")
Branch: 1 branch
BranchTrueFalseTotal
if not defined $n or ref $n 2 554 556
Condition100%3/3
not defined $n or ref $n
l!l&&r!l&&!r
11554
MC/DC100%2/2
not defined $n or ref $n
not defined $n ref $n
Truth table100%3/3
not(A) or B
A= not defined $nB= ref $n
ABresult
1X1
011
000
3538 if !defined $n || ref $n;
3539 }
3540 }
3541 # quote => '' is R's quote = "" and pandas' quoting=QUOTE_NONE: '"' is
3542 # ordinary text. Only '"' can quote, so it is the only other value; R's
3543 # read.table would also take "'", which neither parser here knows.
3544 7784 my $quote = 1;
3545 7784 ▶ if (exists $args{quote}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"quote"}) 185 7599 7784
3546 _usage_error('read_table', "'quote' must be '\"' (the default) or '' (no quoting)")
3547 unless defined $args{quote} && !ref $args{quote}
3548 185 ▶ && ($args{quote} eq '' || $args{quote} eq '"');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"quote"} and not ref $args{"quote"} and $args{"quote"} eq "" || $args{"quote"} eq "\"" 4 181 185
Condition100%9/9
defined $args{"quote"} and not ref $args{"quote"} and $args{"quote"} eq "" || $args{"quote"} eq "\""
!ll&&!rl&&r
22181
defined $args{"quote"} and not ref $args{"quote"}
!ll&&!rl&&r
11183
$args{"quote"} eq "" or $args{"quote"} eq "\""
l!l&&r!l&&!r
17922
MC/DC100%4/4
defined $args{"quote"} and not ref $args{"quote"} and $args{"quote"} eq "" || $args{"quote"} eq "\""
defined $args{"quote"} not ref $args{"quote"} $args{"quote"} eq "" $args{"quote"} eq "\""
Truth table100%5/5
A and not(B) and C or D
A= defined $args{"quote"}B= not ref $args{"quote"}C= $args{"quote"} eq ""D= $args{"quote"} eq "\""
ABCDresult
0XXX0
10XX0
11000
111X1
11011
3549 181 ▶ $quote = $args{quote} eq '"' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$args{'quote'} eq '"' ? : 2 179 181
3550 }
3551  
3552 # The file is read plain, as an aoa, with every option but the output
3553 # type and row_names, so 'filter' sees the file's own columns (FORMAT and
3554 # each sample's unsplit text), and is then exploded into the shape asked
3555 # for. Each raw row is released as it is exploded.
3556 7780 ▶ if ($explode) {
Branch: 1 branch
BranchTrueFalseTotal
if ($explode) 70 7710 7780
3557 70 my %raw_args = (%input_args, explode => 0, 'output_type' => 'aoa');
3558 70 delete $raw_args{'row_names'};
3559 70 my $raw = read_table($file, %raw_args);
3560 5 ▶ my %na = map { _as_bytes($_) => 1 } !defined $args{'na_strings'} ? ()
Branch: 2 branches
BranchTrueFalseTotal
!defined($args{'na_strings'}) ? : 64 5 69
ref $args{'na_strings'} ? : 0 5 5
3561 0 : ref $args{'na_strings'} ? @{ $args{'na_strings'} }
3562 69 : ($args{'na_strings'});
3563 # _vcf_explode() in LikeR.xs; its comment says what the columns are
3564 69 my %mode = (aoh => 0, hoa => 1, hoh => 2, aoa => 3);
3565 # A sample's values have no column of their own to give a class to, so
3566 # they follow the one spelling that speaks for every column:
3567 # colClasses => 'character' keeps them text, and anything else stores
3568 # an integer's text as its number, as the file's own columns are.
3569 my $all_text = defined $args{colClasses} && !ref $args{colClasses}
3570 69 ▶ && $args{colClasses} eq 'character';
Condition66%4/6
defined $args{'colClasses'} && !ref($args{'colClasses'}) && $args{'colClasses'} eq 'character'
!ll&&!rl&&r
6801
defined $args{"colClasses"} and not ref $args{"colClasses"}
!ll&&!rl&&r
6801
MC/DC33%1/3
defined $args{'colClasses'} && !ref($args{'colClasses'}) && $args{'colClasses'} eq 'character'
defined $args{"colClasses"} not ref $args{"colClasses"} $args{'colClasses'} eq 'character'
Truth table50%2/4
A and not(B) && C
A= defined $args{"colClasses"}B= not ref $args{"colClasses"}C= $args{'colClasses'} eq 'character'
ABCresult
0XX0
10X0
1100
1111
3571 69 ▶ return _vcf_explode($raw, $mode{$otype}, $args{'row_names'}, $file,
Branch: 2 branches
BranchTrueFalseTotal
%na ? : 5 64 69
$all_text ? : 1 68 69
3572 %na ? \%na : undef, $all_text ? 0 : 1);
3573 }
3574  
3575 # A multi-worksheet .xlsx with no explicit 'sheet' is returned as a hash
3576 # keyed by worksheet name, each value being that sheet parsed with the same
3577 # options (recursing one sheet at a time keeps every table's state, and any
3578 # hoh row_names default, independent). A single-worksheet workbook, or an
3579 # explicit 'sheet', still returns that one table directly.
3580 # Resolve the worksheet list once and reuse it below (it decompresses and
3581 # parses workbook.xml + its rels, so recomputing it in the main xlsx branch
3582 # would double that work for every single-sheet / explicit-sheet read).
3583 7710 my ($xlsx_sheets, $xlsx_rels);
3584 7710 ▶ if ($is_xlsx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_xlsx) 519 7191 7710
3585 # Reuse a caller-supplied worksheet list (from the multi-sheet expansion
3586 # below) rather than re-parsing workbook.xml + its rels for every sheet.
3587 519 ▶ if ($args{_xlsx_sheets}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'_xlsx_sheets'}) { } 97 422 519
3588 97 $xlsx_sheets = $args{_xlsx_sheets};
3589 } else {
3590 422 $xlsx_rels = _xlsx_rels($file);
3591 422 $xlsx_sheets = _xlsx_sheets($file, $xlsx_rels);
3592 }
3593 519 ▶ if (!defined $args{sheet} && !defined $args{_sheet_ix}
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $args{"sheet"} || defined $args{"_sheet_ix"} and @$xlsx_sheets > 1) 46 473 519
Condition100%6/6
not defined $args{"sheet"} || defined $args{"_sheet_ix"} and @$xlsx_sheets > 1
!ll&&!rl&&r
13034346
defined $args{'sheet'} || defined $args{'_sheet_ix'}
l!l&&r!l&&!r
3397389
MC/DC100%3/3
not defined $args{"sheet"} || defined $args{"_sheet_ix"} and @$xlsx_sheets > 1
defined $args{'sheet'} defined $args{'_sheet_ix'} @$xlsx_sheets > 1
Truth table100%4/4
not(A || B) and C
A= defined $args{'sheet'}B= defined $args{'_sheet_ix'}C= @$xlsx_sheets > 1
ABCresult
1XX0
01X0
0000
0011
3594 && @$xlsx_sheets > 1) {
3595 # Decompress + parse the shared-string table once for the whole
3596 # workbook and hand it to each per-sheet read, instead of every
3597 # recursion re-reading (a potentially large) sharedStrings.xml.
3598 46 my $sst = _xlsx_shared_strings($file, $xlsx_rels);
3599 # A sheet with no name is keyed "SheetN", N its position -- or the
3600 # next N no other sheet is named, since up to 0.3213 an unnamed
3601 # first sheet and a sheet called "Sheet1" were both keyed "Sheet1",
3602 # and one of the two tables was silently lost.
3603 46 ▶ my %taken = map { defined $_->{name} ? ($_->{name} => 1) : () }
Branch: 1 branch
BranchTrueFalseTotal
defined $_->{'name'} ? : 97 2 99
3604 @$xlsx_sheets;
3605 46 my %book;
3606 46 for my $i (0 .. $#$xlsx_sheets) {
3607 97 my $name = $xlsx_sheets->[$i]{name};
3608 97 ▶ if (!defined $name) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $name) 2 95 97
3609 2 my $n = $i + 1;
3610 2 ▶ $n++ while $taken{"Sheet$n"};
Branch: 1 branch
BranchTrueFalseTotal
$taken{"Sheet$n"} and do { ++$n } 1 2 3
3611 2 $name = "Sheet$n";
3612 2 $taken{$name} = 1;
3613 }
3614 # by position, privately: 'sheet' takes a name before a
3615 # number, so sheets named "2" and "1" would swap places
3616 97 $book{$name} = read_table($file, %input_args,
3617 _sheet_ix => $i,
3618 _xlsx_sheets => $xlsx_sheets,
3619 _sst => $sst);
3620 }
3621 32 return \%book;
3622 }
3623 }
3624  
3625 # R's write.table(col.names=TRUE) default omits the header label for the
3626 # row-names column, so a header comes out one field short of every data
3627 # row. With 'auto_row_names' set, mirror read.table's rule: when (and only
3628 # when) the header is exactly one field short, treat the first data field
3629 # as an (otherwise unlabelled) row-names column. Any truthy value enables
3630 # it; a non-1 string is used as the synthesized column name.
3631 7664 ▶ my $want_auto_rn = $args{'auto_row_names'} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$args{'auto_row_names'} ? : 562 7102 7664
3632 7664 my $auto_rn_added = 0; # the row-names column was put in front of @header
3633 my $auto_rn_name =
3634 ($want_auto_rn && "$args{'auto_row_names'}" ne '1')
3635 7664 ▶ ? $args{'auto_row_names'} : 'row_name';
Branch: 1 branch
BranchTrueFalseTotal
$want_auto_rn && "$args{'auto_row_names'}" ne '1' ? : 20 7644 7664
Condition100%3/3
$want_auto_rn and qq[$args{"auto_row_names"}] ne 1
!ll&&!rl&&r
710254220
MC/DC100%2/2
$want_auto_rn and qq[$args{"auto_row_names"}] ne 1
$want_auto_rn qq[$args{"auto_row_names"}] ne 1
Truth table100%3/3
A and B
A= $want_auto_rnB= qq[$args{"auto_row_names"}] ne 1
ABresult
0X0
100
111
3636  
3637 7664 my $filter = $args{filter};
3638 7664 ▶ if (defined $filter && ref($filter) eq 'CODE') {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $filter and ref $filter eq 'CODE') { } 52 7612 7664
elsif (defined $filter and ref $filter ne 'HASH') { } 2 14777 14779
Condition100%3/3
defined $filter and ref $filter eq "CODE"
!ll&&!rl&&r
716744552
MC/DC100%2/2
defined $filter and ref $filter eq "CODE"
defined $filter ref $filter eq "CODE"
Truth table100%3/3
A and B
A= defined $filterB= ref $filter eq "CODE"
ABresult
0X0
100
111
3639 52 $filter = { 0 => $filter };
3640 ▶ } elsif (defined $filter && ref($filter) ne 'HASH') {
Condition100%3/3
defined $filter and ref $filter ne "HASH"
!ll&&!rl&&r
71674432
MC/DC100%2/2
defined $filter and ref $filter ne "HASH"
defined $filter ref $filter ne "HASH"
Truth table100%3/3
A and B
A= defined $filterB= ref $filter ne "HASH"
ABresult
0X0
100
111
3641 2 _usage_error('read_table', "'filter' must be a CODE or HASH reference");
3642 }
3643 # The parser calls the subs itself (see $plan below), and it takes a code
3644 # reference only. Asked up front, so a bad one is not first noticed on
3645 # whichever row reaches it.
3646 7662 ▶ for my $k (sort keys %{ $filter || {} }) {
Condition100%2/2
$filter || {}
l!l
4957167
MC/DC100%1/1
$filter || {}
$filter
Truth table100%2/2
A
A= $filter
Aresult
11
00
3647 _usage_error('read_table', "filter '$k' must be a CODE reference")
3648 566 ▶ unless (reftype($filter->{$k}) // '') eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($filter->{$k}) // "") eq "CODE" 1 565 566
Condition100%2/2
builtin::reftype($filter->{$k}) // ""
l!l
5651
MC/DC100%1/1
builtin::reftype($filter->{$k}) // ""
builtin::reftype($filter->{$k})
Truth table100%2/2
A
A= builtin::reftype($filter->{$k})
Aresult
11
00
3649 }
3650  
3651 # colClasses, R's: a column declared numeric or integer is stored as an NV or
3652 # an IV rather than as its text. On a 300,000 x 5 CSV with three of its five
3653 # columns declared, a hoa took 74 MB instead of 116 MB on perl 5.44.0, about
3654 # 47 bytes less for each of the 900,000 cells converted. R's spellings:
3655 # one class for every column, a list by position (recycled when short, as R
3656 # recycles it), or a hash by name, where a name that is no column is warned
3657 # about, in R's words, and otherwise ignored. 'character' keeps a column as
3658 # the text the file holds. undef (R's NA), and any column with no class at
3659 # all, is code 3: a cell whose text is an integer exactly as perl would print
3660 # it ("42", "-7", not "007" or "4.0") is stored as that IV, 24 bytes where the
3661 # text took 72, and every other cell as its text; S_text_is_iv() in LikeR.xs
3662 # has the rule and what it measured. Each name is checked here, before the
3663 # file is opened; which field gets which class waits for the header.
3664 # %cls_code: 0 = character (its text), 1 = numeric (an NV), 2 = integer (an
3665 # IV), 3 = no class given
3666 7661 my %cls_code = (numeric => 1, double => 1, real => 1, integer => 2, character => 0);
3667 7661 my $cls_arg = $args{colClasses};
3668 1018 ▶ my $cls_of = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
3669 1018 my ($c) = @_;
3670 1018 ▶ return 3 unless defined $c;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $c 51 967 1018
3671 _usage_error('read_table', "colClasses '$c' is not one read_table reads: it takes "
3672 . "'numeric' (or 'double' or 'real'), 'integer', 'character' or undef")
3673 967 ▶ unless exists $cls_code{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $cls_code{$c} 3 964 967
3674 964 return $cls_code{$c};
3675 7661 };
3676 7661 ▶ if (defined $cls_arg) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cls_arg) 282 7379 7661
3677 282 my $r = ref $cls_arg;
3678 282 ▶ _usage_error('read_table', "'colClasses' must be a string, an ARRAY reference or a "
Branch: 1 branch
BranchTrueFalseTotal
if $r and $r ne "ARRAY" and $r ne "HASH" 1 281 282
Condition100%6/6
$r and $r ne "ARRAY" and $r ne "HASH"
!ll&&!rl&&r
1411401
$r and $r ne "ARRAY"
!ll&&!rl&&r
8655141
MC/DC100%3/3
$r and $r ne "ARRAY" and $r ne "HASH"
$r $r ne "ARRAY" $r ne "HASH"
Truth table100%4/4
A and B and C
A= $rB= $r ne "ARRAY"C= $r ne "HASH"
ABCresult
0XX0
10X0
1100
1111
3679 . "HASH reference") if $r && $r ne 'ARRAY' && $r ne 'HASH';
3680 281 ▶ $cls_of->($_) for $r eq 'ARRAY' ? @$cls_arg : $r eq 'HASH' ? values %$cls_arg : $cls_arg;
Branch: 2 branches
BranchTrueFalseTotal
$r eq 'ARRAY' ? : 55 226 281
$r eq 'HASH' ? : 140 86 226
3681 278 ▶ _usage_error('read_table', "'colClasses' is an empty list") if $r eq 'ARRAY' && !@$cls_arg;
Branch: 1 branch
BranchTrueFalseTotal
if $r eq "ARRAY" and not @$cls_arg 1 277 278
Condition100%3/3
$r eq "ARRAY" and not @$cls_arg
!ll&&!rl&&r
224531
MC/DC100%2/2
$r eq "ARRAY" and not @$cls_arg
$r eq "ARRAY" not @$cls_arg
Truth table100%3/3
A and not(B)
A= $r eq "ARRAY"B= not @$cls_arg
ABresult
0X0
100
111
3682 }
3683 7656 my @cls; # per field of @header, once it is fixed: a %cls_code value
3684  
3685 # na_strings / na_values / undef_val -- field texts that mean "missing", mapped
3686 # to undef exactly as an empty field already is. Every spelling has been folded
3687 # into 'na_strings' above, so only that one is read from here on.
3688 #
3689 # Off by default. R's read.table defaults to na.strings = "NA" and pandas
3690 # recognises a whole list, but this module has always handed a literal "NA"
3691 # back as real data, and t/read_table.t pins that, so turning it on for
3692 # everyone is a maintainer's call rather than a bug fix. What was a bug is that
3693 # there was no way to ask for it at all: write_table renders undef with
3694 # 'undef_val' (documented under write_table as not round-tripping back to
3695 # undef), so read_table could not read back what its own sibling had written.
3696 #
3697 # The match is on the exact field text, case-sensitively and without trimming
3698 # whitespace, so " NA" is not "NA"; list both spellings if a file has both.
3699 my %na_string;
3700 {
3701 7656 my $ns = $args{'na_strings'};
3702 7656 ▶ my @ns = !defined($ns) ? ()
Branch: 3 branches
BranchTrueFalseTotal
!defined($ns) ? : 7364 292 7656
ref $ns eq 'ARRAY' ? : 63 229 292
ref $ns ? : 3 226 229
3703 : ref($ns) eq 'ARRAY' ? @$ns
3704 : ref($ns) ? _usage_error('read_table', "'na_strings' must be a "
3705 . 'string or an ARRAY reference, not a '
3706 . ref($ns) . ' reference')
3707 : ($ns);
3708 7653 for my $s (@ns) {
3709 494 ▶ _usage_error('read_table', "'na_strings' may not contain an undefined value")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 1 493 494
3710 unless defined $s;
3711 493 $na_string{ $as_field->($s) } = 1;
3712 }
3713 }
3714 7652 ▶ my $has_na = %na_string ? 1 : 0; # skip the hash lookup in the common case
Branch: 1 branch
BranchTrueFalseTotal
%na_string ? : 283 7369 7652
3715  
3716 # @field_wins: per field, TRUE when it is the last to carry its name and
3717 # the name is not excluded, which is when %line_hash holds its value
3718 # @excl: per field, TRUE when 'drop_cols' leaves its column out; empty when
3719 # nothing is excluded. @kept_flds: the indices of the other fields
3720 7652 my (@data, %data, @header, @uniq_header, @hoa_cols, @field_wins,
3721 %mapped_filters, @sorted_filter_flds, %seen_rownames, @excl, @kept_flds);
3722 7652 my ($data_row, $header_seen, $header_done, $provisional_hdr) = (0, 0, 0, 0);
3723 # hoh: rows whose name an earlier row already had, and the first of them as
3724 # [name, data row]. Counted and warned about once, after the parse.
3725 7652 my ($n_dup_rn, $first_dup_rn) = (0, undef);
3726 # The alignment message's parts, set by $finalize_header: what a ragged
3727 # row's field count is compared with, and a note for a width of one whose
3728 # line held no separator (undef when there is none). The parser's
3729 # S_fast_row() gets both through the plan.
3730 7652 my ($width_txt, $sep_note);
3731  
3732 # Once the header is fixed there is nothing left for the row closure below to
3733 # decide, so the parser is given a plan and builds the rest of the table
3734 # itself. That closure, called once per row, used to be about four fifths of
3735 # read_table's wall clock -- on a 300,000 x 5 CSV, 0.42 s of 0.53 s -- doing in
3736 # perl what C can do from the fields it has already cut.
3737 #
3738 # A 'filter' goes this way too: its subs are handed over in the plan and the
3739 # parser calls them, with the same $_, %_ and arguments the closure below
3740 # gives them (S_filter_row() in LikeR.xs). Up to 0.3212 a filter kept every row
3741 # in the closure, and a filtered read of a 300,000 x 5 CSV took 0.58 s to
3742 # 1.07 s against 0.08 s to 0.18 s unfiltered. The closure still applies them to
3743 # any data row it handles itself, before the plan is installed. 'hoh' went
3744 # through the closure too until 0.319, which on a 300,000 x 5 CSV cost 0.91 s;
3745 # it now takes 0.20 s. An .xlsx goes through a different parser (_parse_xlsx_sheet_xs)
3746 # but the same plan: both hand a finished row to the same S_fast_row().
3747 # A qr// sep goes this way too: _parse_csv_file() matches it with perl's regex
3748 # engine, from C, so only how a separator is found changes.
3749 #
3750 # See csv_plan in LikeR.xs for what each key means. install_plan() runs exactly
3751 # once, from wherever $header_done is first set, and writes 'out' last because
3752 # that is the key the parser tests for.
3753 7652 ▶ my $plan = $args{_closure} ? undef : {};
Branch: 1 branch
BranchTrueFalseTotal
$args{'_closure'} ? : 1132 6520 7652
3754 7368 ▶ my $install_plan = sub {
Subroutine __ANON__: called CC=12 SCAR=24.8
3755 7368 ▶ return if !$plan || %$plan;
Branch: 1 branch
BranchTrueFalseTotal
if not $plan or %$plan 1003 6365 7368
Condition66%2/3
not $plan or %$plan
l!l&&r!l&&!r
100306365
MC/DC50%1/2
not $plan or %$plan
not $plan %$plan
Truth table66%2/3
not(A) or B
A= not $planB= %$plan
ABresult
1X1
011
000
3756 # A repeated column name resolves to its LAST field, which is what
3757 # "later values win" means when %line_hash is built below.
3758 6365 my %last;
3759 6365 $last{ $header[$_] } = $_ for 0 .. $#header;
3760 6365 $plan->{keys} = \@uniq_header;
3761 6365 $plan->{idx} = [ map { $last{$_} } @uniq_header ];
3762 6365 $plan->{ncol} = scalar @header;
3763 6365 $plan->{file} = $file;
3764 6365 $plan->{width} = $width_txt;
3765 6365 $plan->{sep_note} = $sep_note;
3766 6365 ▶ $plan->{na} = $has_na ? \%na_string : undef;
Branch: 1 branch
BranchTrueFalseTotal
$has_na ? : 233 6132 6365
3767 6365 ▶ if (@cls) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cls) 6351 14 6365
3768 6351 $plan->{cls} = [ @cls ];
3769 6351 $plan->{hdr} = [ @header ];
3770 }
3771 # 'drop_cols': @uniq_header already lacks the names, so no key reads an
3772 # excluded field; this tells the parser not to make its cells
3773 6365 ▶ $plan->{skip} = [ @excl ] if @excl;
Branch: 1 branch
BranchTrueFalseTotal
if @excl 894 5471 6365
3774 # in the order the closure below runs them
3775 6365 for my $fld (@sorted_filter_flds) {
3776 399 for my $sub (@{ $mapped_filters{$fld} }) {
3777 421 push @{ $plan->{flt_fld} }, $fld;
3778 421 push @{ $plan->{flt_sub} }, $sub;
3779 }
3780 }
3781 # a reference, not a copy: the parser reads it when it picks the plan
3782 # up, by which time $on_line may have emitted a data row of its own.
3783 6365 $plan->{row} = \$data_row;
3784 6365 ▶ if ($otype eq 'aoh') {
Branch: 3 branches
BranchTrueFalseTotal
if ($otype eq 'aoh') { } 2206 4159 6365
elsif ($otype eq 'aoa') { } 2776 1383 4159
elsif ($otype eq 'hoa') { } 699 684 1383
3785 2206 $plan->{mode} = 0;
3786 2206 $plan->{out} = \@data;
3787 } elsif ($otype eq 'aoa') {
3788 2776 $plan->{mode} = 3;
3789 2776 $plan->{out} = \@data;
3790 } elsif ($otype eq 'hoa') {
3791 699 $plan->{mode} = 1;
3792 699 $plan->{out} = [ @hoa_cols ];
3793 } else {
3794 # $finalize_header has already checked that row_names is a column
3795 684 my ($rn) = grep { $uniq_header[$_] eq $args{'row_names'} }
3796 0 .. $#uniq_header;
3797 684 $plan->{mode} = 2;
3798 684 $plan->{rn} = $rn;
3799 684 $plan->{out} = \%data;
3800 }
3801 7652 };
3802  
3803 # Everything that depends on the (possibly augmented) @header lives here so
3804 # it can run either right after the header line (strict mode) or deferred
3805 # to the first data row (auto_row_names mode, once the width is known).
3806 7636 ▶ my $finalize_header = sub {
Subroutine __ANON__: called CC=76 SCAR=43.3
3807 # A VCF header line is "#CHROM\tPOS...": under the default "##" marker it
3808 # is not a comment, so it arrives with its "#" on. Read with
3809 # comment => '#' instead, the marker is already off and this is a no-op.
3810 # Its first column, not $header[0], since auto_row_names may have put a
3811 # row-names column in front of it.
3812 7636 ▶ $header[$auto_rn_added] =~ s/\A#//
Branch: 1 branch
BranchTrueFalseTotal
if $is_vcf and $want_header and defined $header[$auto_rn_added] 156 7480 7636
Condition83%5/6
$is_vcf and $want_header and defined $header[$auto_rn_added]
!ll&&!rl&&r
74800156
$is_vcf and $want_header
!ll&&!rl&&r
747010156
MC/DC66%2/3
$is_vcf and $want_header and defined $header[$auto_rn_added]
$is_vcf $want_header defined $header[$auto_rn_added]
Truth table75%3/4
A and B and C
A= $is_vcfB= $want_headerC= defined $header[$auto_rn_added]
ABCresult
0XX0
10X0
1100
1111
3813 if $is_vcf && $want_header && defined $header[$auto_rn_added];
3814 # R's read.table: 'col.names' replaces a header's names, and a header
3815 # of another length is warned about ("header and 'col.names' are of
3816 # different lengths") and then the names are used all the same.
3817 7636 ▶ if ($col_names && $want_header) {
Branch: 1 branch
BranchTrueFalseTotal
if ($col_names and $want_header) 67 7569 7636
Condition100%3/3
$col_names and $want_header
!ll&&!rl&&r
75343567
MC/DC100%2/2
$col_names and $want_header
$col_names $want_header
Truth table100%3/3
A and B
A= $col_namesB= $want_header
ABresult
0X0
100
111
3818 67 my $n = @header - $auto_rn_added;
3819 67 ▶ warn "read_table: header and 'col_names' are of different lengths "
Branch: 1 branch
BranchTrueFalseTotal
if $n != @$col_names 1 66 67
3820 . "($n and " . scalar(@$col_names) . ") in $file\n"
3821 if $n != @$col_names;
3822 67 splice @header, $auto_rn_added, $n, @$col_names;
3823 }
3824 7636 ▶ if (@header && $header[0] eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if (@header and $header[0] eq "") 80 7556 7636
Condition66%2/3
@header and $header[0] eq ""
!ll&&!rl&&r
0755680
MC/DC50%1/2
@header and $header[0] eq ""
@header $header[0] eq ""
Truth table66%2/3
A and B
A= @headerB= $header[0] eq ""
ABresult
0X0
100
111
3825 80 $header[0] = 'row_name';
3826 }
3827 7636 my %seen_h;
3828 7636 @uniq_header = grep { !$seen_h{$_}++ } @header;
3829 # 'keep_cols' and 'drop_cols', against the names as they now stand:
3830 # after 'col_names', the VCF "#" and the row_name default, so a name or
3831 # pattern is written for the name the table would have had. A name is
3832 # the bytes the file holds, and is tried as those and, when they are
3833 # UTF-8, as the characters they spell, so that a pattern compiled under
3834 # `use utf8` and one compiled without it both match "Größe", and so do
3835 # a column name written under it and one written without. Each name is
3836 # tried once, and every field carrying an excluded name goes. An .xlsx's
3837 # names are already characters, and are tried as those and as the bytes
3838 # they encode to, for the same two kinds of caller.
3839 7636 @excl = ();
3840 7636 @kept_flds = (0 .. $#header);
3841 7636 ▶ if (%sel) {
Branch: 1 branch
BranchTrueFalseTotal
if (%sel) 2035 5601 7636
3842 # A hoh is keyed by its row_names column, which is never a cell of
3843 # a row, so keep_cols keeps it whether or not it names it: what
3844 # keep_cols chooses is the cells. drop_cols naming it is refused
3845 # below. Its default, the first column, is set further down.
3846 my $rn = $otype ne 'hoh' ? undef
3847 2035 ▶ : defined $args{'row_names'} ? $args{'row_names'}
Branch: 2 branches
BranchTrueFalseTotal
$otype ne 'hoh' ? : 1529 506 2035
defined $args{'row_names'} ? : 346 160 506
3848 : $header[0];
3849 2035 my %named; # keep / drop => { name => 1 }: the entries that are a column
3850 # the file, and the worksheet when a workbook is read one sheet at a time
3851 2035 my $in = $file;
3852 2035 ▶ if (defined $args{_sheet_ix}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"_sheet_ix"}) 46 1989 2035
3853 46 my $sn = $xlsx_sheets->[ $args{_sheet_ix} ]{name};
3854 46 ▶ $in .= defined $sn ? " (sheet \"$sn\")" : ' (sheet ' . ($args{_sheet_ix} + 1) . ')';
Branch: 1 branch
BranchTrueFalseTotal
defined $sn ? : 46 0 46
3855 }
3856 14331 ▶ my $hit = sub { # does $sel{$k} name or match this header name?
Subroutine __ANON__: called CC=7 SCAR=19.5
3857 14331 my ($k, $name, $chars, $wide) = @_;
3858 14331 my $s = $sel{$k};
3859 14331 my $found = 0;
3860 14331 ▶ for my $as ($wide ? ($name, $chars) : ($name)) {
Branch: 1 branch
BranchTrueFalseTotal
$wide ? : 372 13959 14331
3861 14703 ▶ next unless $s->{name}{$as};
Branch: 1 branch
BranchTrueFalseTotal
unless $s->{"name"}{$as} 11690 3013 14703
3862 3013 $named{$k}{$as} = 1;
3863 3013 $found = 1;
3864 }
3865 return $found
3866 14331 ▶ || grep { $name =~ $_ || ($wide && $chars =~ $_) } @{ $s->{rx} };
Condition100%9/9
$found || grep({$name =~ /$_/ or $wide and $chars =~ /$_/;} @{$$s{'rx'};})
l!l&&r!l&&!r
299726738661
$name =~ /$_/ || $wide && $chars =~ /$_/
l!l&&r!l&&!r
2660244579
$wide and $chars =~ /$_/
!ll&&!rl&&r
45403924
MC/DC100%2/2
$found || grep({$name =~ /$_/ or $wide and $chars =~ /$_/;} @{$$s{'rx'};})
$found grep({$name =~ /$_/ or $wide and $chars =~ /$_/;} @{$$s{'rx'};})
MC/DC100%3/3
$name =~ /$_/ || $wide && $chars =~ /$_/
$name =~ /$_/ $wide $chars =~ /$_/
Truth table100%3/3
A || B
A= $foundB= grep({$name =~ /$_/ or $wide and $chars =~ /$_/;} @{$$s{'rx'};})
ABresult
1X1
011
000
Truth table100%4/4
A || B and C
A= $name =~ /$_/B= $wideC= $chars =~ /$_/
ABCresult
1XX1
0111
00X0
0100
3867 2035 };
3868 2035 my %out;
3869 2035 for my $name (@uniq_header) {
3870 # the two spellings a name is tried as: for a delimited file
3871 # the bytes it holds and the characters they spell; for an
3872 # .xlsx the characters it holds and the bytes they encode to
3873 #
3874 # The copy is "$name", not $name: an .xlsx's name is a copy of a
3875 # shared hash key, and on perl 5.32 utf8::encode() of such a copy
3876 # leaves it looking up as the key it was copied from, so its
3877 # bytes found the characters' entry and the name was never
3878 # marked found (a stringified copy owns its buffer).
3879 13954 my $chars = "$name";
3880 13954 my $wide;
3881 13954 ▶ if ($is_xlsx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_xlsx) { } 714 13240 13954
3882 714 utf8::encode($chars);
3883 714 $wide = $chars ne $name;
3884 } else {
3885 13240 ▶ $wide = utf8::decode($chars) && $chars ne $name;
Condition100%3/3
utf8::decode($chars) && $chars ne $name
!ll&&!rl&&r
2412908308
MC/DC100%2/2
utf8::decode($chars) && $chars ne $name
utf8::decode($chars) $chars ne $name
Truth table100%3/3
A && B
A= utf8::decode($chars)B= $chars ne $name
ABresult
0X0
100
111
3886 }
3887 # both are tried, whatever the first says, so that each one's
3888 # names are marked as found
3889 13954 ▶ my $kept = !$sel{keep} || $hit->('keep', $name, $chars, $wide)
Condition100%9/9
!$sel{'keep'} || &$hit('keep', $name, $chars, $wide) || defined $rn && $name eq $rn
l!l&&r!l&&!r
9745344175
not $sel{"keep"} or &$hit("keep", $name, $chars, $wide)
l!l&&r!l&&!r
724824974209
defined $rn and $name eq $rn
!ll&&!rl&&r
330387234
MC/DC100%4/4
!$sel{'keep'} || &$hit('keep', $name, $chars, $wide) || defined $rn && $name eq $rn
not $sel{"keep"} &$hit("keep", $name, $chars, $wide) defined $rn $name eq $rn
Truth table100%5/5
not(A) or B || C and D
A= not $sel{"keep"}B= &$hit("keep", $name, $chars, $wide)C= defined $rnD= $name eq $rn
ABCDresult
1XXX1
01XX1
00111
000X0
00100
3890 || (defined $rn && $name eq $rn);
3891 13954 ▶ my $dropped = $sel{drop} && $hit->('drop', $name, $chars, $wide);
Condition100%3/3
$sel{'drop'} && &$hit('drop', $name, $chars, $wide)
!ll&&!rl&&r
632944523173
MC/DC100%2/2
$sel{'drop'} && &$hit('drop', $name, $chars, $wide)
$sel{'drop'} &$hit('drop', $name, $chars, $wide)
Truth table100%3/3
A && B
A= $sel{'drop'}B= &$hit('drop', $name, $chars, $wide)
ABresult
0X0
100
111
3892 13954 ▶ $out{$name} = 1 if !$kept || $dropped;
Branch: 1 branch
BranchTrueFalseTotal
if not $kept or $dropped 7329 6625 13954
Condition100%3/3
not $kept or $dropped
l!l&&r!l&&!r
417531546625
MC/DC100%2/2
not $kept or $dropped
not $kept $dropped
Truth table100%3/3
not(A) or B
A= not $keptB= $dropped
ABresult
1X1
011
000
3893 }
3894 # A name that is no column is most often a misspelled one, and the
3895 # column it meant is then stored after all, or not stored, so it is
3896 # said -- as R's read.table() says "not all columns named in
3897 # 'colClasses' exist" of colClasses = c(nope = "NULL"), its way of
3898 # skipping a column by name (R 4.6.1 src/library/utils/R/readtable.R).
3899 # A pattern that matches nothing stays silent: it never claimed a
3900 # column was there. Said before the die below, so that a read
3901 # refused for keeping no column says which name was no column; and
3902 # of a workbook read sheet by sheet, with the sheet, since the name
3903 # may be a column of another one.
3904 #
3905 # A workbook read sheet by sheet is refused instead: the caller
3906 # chose columns for every sheet at once, and a sheet without one of
3907 # them would come back whole, or cut down to other columns, under
3908 # a warning that is easy to miss among the sheets that were right.
3909 # Both options' names are said in the one error.
3910 2035 my @absent_msg;
3911 2035 for my $k ('keep', 'drop') {
3912 4070 ▶ next unless $sel{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless $sel{$k} 1970 2100 4070
3913 2100 my @absent = grep { !$named{$k}{$_} } @{ $sel{$k}{names} };
3914 push @absent_msg, "read_table: not all columns named in '${k}_cols' exist in $in: "
3915 2100 ▶ . join(', ', map { "'" . $as_field->($_) . "'" } @absent) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if @absent 228 1872 2100
3916 if @absent;
3917 }
3918 2035 ▶ if (@absent_msg && defined $args{_sheet_ix}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@absent_msg and defined $args{"_sheet_ix"}) 14 2021 2035
Condition100%3/3
@absent_msg and defined $args{"_sheet_ix"}
!ll&&!rl&&r
181720414
MC/DC100%2/2
@absent_msg and defined $args{"_sheet_ix"}
@absent_msg defined $args{"_sheet_ix"}
Truth table100%3/3
A and B
A= @absent_msgB= defined $args{"_sheet_ix"}
ABresult
0X0
100
111
3919 14 die join('', @absent_msg) . "read_table: pass 'sheet' to read one worksheet, "
3920 . "or a qr// regex, which may match no column of a sheet\n";
3921 }
3922 2021 _warn_text($_) for @absent_msg;
3923 2021 ▶ if (%out) {
Branch: 1 branch
BranchTrueFalseTotal
if (%out) 1927 94 2021
3924 1927 ▶ @excl = map { $out{$_} ? 1 : 0 } @header;
Branch: 1 branch
BranchTrueFalseTotal
$out{$_} ? : 7355 6065 13420
3925 1927 @kept_flds = grep { !$excl[$_] } 0 .. $#header;
3926 1927 @uniq_header = grep { !$out{$_} } @uniq_header;
3927 die "read_table: " . (!$sel{keep} ? "'drop_cols' leaves out every column"
3928 1927 ▶ : !$sel{drop} ? "'keep_cols' keeps no column"
Branch: 3 branches
BranchTrueFalseTotal
unless @kept_flds 216 1711 1927
!$sel{'keep'} ? : 168 48 216
!$sel{'drop'} ? : 36 12 48
3929 : "'keep_cols' and 'drop_cols' leave no column")
3930 . " of $in\n"
3931 unless @kept_flds;
3932 }
3933 }
3934 # Name each repeated column, with how many fields carry it and which
3935 # ones (1-based, as a spreadsheet or `cut -f` counts them). A bare
3936 # list of the names is not enough to find them: a merged banner row
3937 # repeats the *empty* name, which prints as nothing at all, and a name
3938 # repeated three times reads the same as one repeated twice.
3939 7406 my %at;
3940 7406 push @{ $at{ $header[$_] } }, $_ + 1 for 0 .. $#header;
3941 # 12 positions is what fits on one terminal line beside the name and
3942 # the count; a merged banner row can repeat the empty name across
3943 # every field of the sheet (66 of them in the file this was written
3944 # for), and the count still says how many there are in total.
3945 my @dup_cols = map {
3946 111 my @f = @{ $at{$_} };
3947 111 ▶ my $more = @f > 12 ? ', ...' : '';
Branch: 1 branch
BranchTrueFalseTotal
@f > 12 ? : 1 110 111
3948 111 ▶ splice @f, 12 if @f > 12;
Branch: 1 branch
BranchTrueFalseTotal
if @f > 12 1 110 111
3949 111 "'$_' x $seen_h{$_} (fields " . join(', ', @f) . "$more)"
3950 7406 } grep { $seen_h{$_} > 1 } @uniq_header;
3951 # an aoa keeps every field, so a repeated name loses nothing there
3952 7406 ▶ _warn_text("read_table: duplicate column name(s) in $file (later values win): "
Branch: 1 branch
BranchTrueFalseTotal
if @dup_cols and $otype ne "aoa" 73 7333 7406
Condition100%3/3
@dup_cols and $otype ne "aoa"
!ll&&!rl&&r
72963773
MC/DC100%2/2
@dup_cols and $otype ne "aoa"
@dup_cols $otype ne "aoa"
Truth table100%3/3
A and B
A= @dup_colsB= $otype ne "aoa"
ABresult
0X0
100
111
3953 . join('; ', @dup_cols) . "\n")
3954 if @dup_cols && $otype ne 'aoa';
3955 # An aoa's first row is the header -- the shape write_table reads an
3956 # AoA as -- in file order and with any repeated name kept.
3957 7406 ▶ @data = ([ @header[@kept_flds] ]) if $otype eq 'aoa';
Branch: 1 branch
BranchTrueFalseTotal
if $otype eq "aoa" 3030 4376 7406
3958 7406 ▶ if ($otype eq 'hoh' && !defined $args{'row_names'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($otype eq "hoh" and not defined $args{"row_names"}) 549 6857 7406
Condition100%3/3
$otype eq "hoh" and not defined $args{"row_names"}
!ll&&!rl&&r
6469388549
MC/DC100%2/2
$otype eq "hoh" and not defined $args{"row_names"}
$otype eq "hoh" not defined $args{"row_names"}
Truth table100%3/3
A and not(B)
A= $otype eq "hoh"B= not defined $args{"row_names"}
ABresult
0X0
100
111
3959 549 $args{'row_names'} = $header[0];
3960 }
3961 7406 ▶ if (defined $args{'row_names'}
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"row_names"} and not grep({$_ eq $args{"row_names"};} @header)) 3 7403 7406
Condition100%3/3
defined $args{"row_names"} and not grep({$_ eq $args{"row_names"};} @header)
!ll&&!rl&&r
64699343
MC/DC100%2/2
defined $args{"row_names"} and not grep({$_ eq $args{"row_names"};} @header)
defined $args{"row_names"} not grep({$_ eq $args{"row_names"};} @header)
Truth table100%3/3
A and not(B)
A= defined $args{"row_names"}B= not grep({$_ eq $args{"row_names"};} @header)
ABresult
0X0
100
111
3962 5477 && !grep { $_ eq $args{'row_names'} } @header) {
3963 3 die "\"$args{'row_names'}\" isn't in the header of $file\n";
3964 }
3965 # A hoh is keyed by this column, so it cannot be left out; said here
3966 # rather than picking another column to key the rows by.
3967 die "read_table: 'drop_cols' leaves out \"$args{'row_names'}\", the row_names "
3968 . "column of $file\n"
3969 if defined $args{'row_names'} && @excl
3970 7403 ▶ && !grep { $_ eq $args{'row_names'} } @uniq_header;
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"row_names"} and @excl and not grep({$_ eq $args{"row_names"};} @uniq_header) 10 7393 7403
Condition100%6/6
defined $args{"row_names"} and @excl and not grep({$_ eq $args{"row_names"};} @uniq_header)
!ll&&!rl&&r
696343010
defined $args{"row_names"} and @excl
!ll&&!rl&&r
6469494440
MC/DC100%3/3
defined $args{"row_names"} and @excl and not grep({$_ eq $args{"row_names"};} @uniq_header)
defined $args{"row_names"} @excl not grep({$_ eq $args{"row_names"};} @uniq_header)
Truth table100%4/4
A and B and not(C)
A= defined $args{"row_names"}B= @exclC= not grep({$_ eq $args{"row_names"};} @uniq_header)
ABCresult
0XX0
10X0
1100
1111
3971 # A repeated name resolves to its last field, which is the one
3972 # %line_hash keeps, so only that field's filter writes $_ back into it.
3973 7393 my %last_field;
3974 7393 $last_field{ $header[$_] } = $_ for 0 .. $#header;
3975 # An excluded field is not in %line_hash, so a filter keyed on it is
3976 # given the field's own value, as one whose name a later field repeats
3977 # is, and nothing it writes to $_ reaches %line_hash.
3978 7393 ▶ @field_wins = map { $last_field{ $header[$_] } == $_ && !$excl[$_] } 0 .. $#header;
Condition100%3/3
$last_field{$header[$_]} == $_ && !$excl[$_]
!ll&&!rl&&r
173646927530
MC/DC100%2/2
$last_field{$header[$_]} == $_ && !$excl[$_]
$last_field{$header[$_]} == $_ !$excl[$_]
Truth table100%3/3
A && not(B)
A= $last_field{$header[$_]} == $_B= !$excl[$_]
ABresult
0X0
100
111
3979 7393 ▶ if ($filter) {
Branch: 1 branch
BranchTrueFalseTotal
if ($filter) 494 6899 7393
3980 # Each key is resolved to a field before any filter runs: '0' to
3981 # the whole row; a column's name to the last field carrying it;
3982 # and any other number to that field, counting from 1. A name
3983 # comes before a number, so a column named "2021" can be filtered
3984 # on -- up to 0.3213 that key was a field number and died as out
3985 # of range. A field named by two keys (1 and its name, say) runs
3986 # both, in key order; one used to replace the other, and which
3987 # depended on hash order, so the rows kept changed between runs.
3988 494 %mapped_filters = ();
3989 494 for my $k (sort keys %$filter) {
3990 565 my $fld;
3991 565 ▶ if ($k eq '0') {
Branch: 1 branch
BranchTrueFalseTotal
if ($k eq '0') { } 239 326 565
3992 239 $fld = 0;
3993 } else {
3994 326 my $kb = $as_field->($k);
3995 326 my $idx = $last_field{$kb};
3996 326 ▶ if (!defined $idx && length( $args{comment} // '' )) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $idx and length($args{"comment"} // "")) 103 223 326
Condition60%3/5
not defined $idx and length($args{"comment"} // "")
!ll&&!rl&&r
2230103
$args{"comment"} // ""
l!l
1030
MC/DC50%1/2
not defined $idx and length($args{"comment"} // "")
not defined $idx $args{"comment"}
Truth table66%2/3
not(A) and B
A= not defined $idxB= $args{"comment"}
ABresult
0X0
100
111
3997 # A commented-out header has its marker (and any
3998 # following whitespace) stripped from the first
3999 # column, so a key written as it appears in the file
4000 # (e.g. "# PDB") won't match the clean name ("PDB").
4001 # Normalize the key the same way and retry.
4002 103 (my $nk = $kb) =~ s/^\s*\Q$args{comment}\E\s*//;
4003 103 $idx = $last_field{$nk};
4004 }
4005 326 ▶ if (defined $idx) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $idx) { } 224 102 326
elsif ($k =~ /\A[0-9]+\z/) { } 82 20 102
4006 224 $fld = $idx + 1;
4007 } elsif ($k =~ /\A[0-9]+\z/) {
4008 82 ▶ die "read_table: numeric filter key $k exceeds the "
Branch: 1 branch
BranchTrueFalseTotal
if $k > @header 2 80 82
4009 . scalar(@header) . " columns of $file, and no column "
4010 . "is named '$k'\n"
4011 if $k > @header;
4012 80 $fld = $k + 0;
4013 } else {
4014 die "read_table: Filter column '$k' not found in the "
4015 . "header of $file; header is: "
4016 20 . join( ', ', map { "'$_'" } @header ) . "\n";
4017 }
4018 }
4019 543 push @{ $mapped_filters{$fld} }, $filter->{$k};
4020 }
4021 472 @sorted_filter_flds = sort { $a <=> $b } keys %mapped_filters;
4022 }
4023 7371 ▶ if (defined $cls_arg) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cls_arg) { } 277 7094 7371
4024 277 my $r = ref $cls_arg;
4025 277 ▶ if ($r eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if ($r eq 'HASH') { } 138 139 277
elsif ($r eq 'ARRAY') { } 53 86 139
4026 138 my %by = map { $as_field->($_) => $cls_of->( $cls_arg->{$_} ) } keys %$cls_arg;
4027 138 ▶ @cls = map { $by{$_} // 3 } @header;
Condition100%2/2
$by{$_} // 3
l!l
206491
MC/DC100%1/1
$by{$_} // 3
$by{$_}
Truth table100%2/2
A
A= $by{$_}
Aresult
11
00
4028 138 my %have = map { $_ => 1 } @header;
4029 warn "read_table: not all columns named in 'colClasses' exist\n"
4030 138 ▶ if grep { !$have{$_} } keys %by;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not $have{$_};} keys %by 9 129 138
4031 } elsif ($r eq 'ARRAY') {
4032 53 ▶ die "read_table: 'colClasses' has " . scalar(@$cls_arg) . " entries "
Branch: 1 branch
BranchTrueFalseTotal
if @$cls_arg > @header 1 52 53
4033 . "for the " . scalar(@header) . " columns of $file\n"
4034 if @$cls_arg > @header;
4035 52 @cls = map { $cls_of->( $cls_arg->[ $_ % @$cls_arg ] ) } 0 .. $#header;
4036 } else {
4037 86 @cls = ( $cls_of->($cls_arg) ) x @header;
4038 }
4039 } else {
4040 7094 @cls = (3) x @header;
4041 }
4042 # all 'character': nothing to convert, and the parser is told nothing
4043 7370 ▶ @cls = () unless grep { $_ } @cls;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_;} @cls 19 7351 7370
4044 # The column arrays are made once and held, so neither the fast path
4045 # nor the row loop below has to fetch them out of %data (and
4046 # autovivify them) once per column per row.
4047 7370 ▶ @hoa_cols = map { $data{$_} ||= [] } @uniq_header if $otype eq 'hoa';
Branch: 1 branch
BranchTrueFalseTotal
if $otype eq "hoa" 910 6460 7370
Condition50%1/2
$data{$_} ||= []
l!l
04023
MC/DC0%0/1
$data{$_} ||= []
$data{$_}
Truth table50%1/2
A
A= $data{$_}
Aresult
11
00
4048 # What the alignment message compares a ragged row with. With
4049 # header => 0 there is no header to count, and up to 0.3217 the message
4050 # said "N headers" all the same, which read as though header => 0 had
4051 # been ignored; it now says where the width came from.
4052 7370 my $w = @header;
4053 7370 ▶ $width_txt = $want_header ? "$w headers"
Branch: 2 branches
BranchTrueFalseTotal
$want_header ? : 7081 289 7370
$col_names ? : 35 254 289
4054 : $col_names ? "$w 'col_names'"
4055 : "$w in data row 1";
4056 # A width of one, read from the file, means that the line that set it
4057 # held no separator, and a later row with more fields did: the shape of
4058 # a file read with the wrong sep. A ';'-separated .csv read with the
4059 # default ',' fails on the first row with a comma in its text. Not for
4060 # an .xlsx, whose cells are not split, nor where 'col_names' set the
4061 # width.
4062 7370 $sep_note = undef;
4063 7370 ▶ if ($w == 1 && !$is_xlsx && !$col_names) {
Branch: 1 branch
BranchTrueFalseTotal
if ($w == 1 and not $is_xlsx and not $col_names) 289 7081 7370
Condition100%6/6
$w == 1 and not $is_xlsx and not $col_names
!ll&&!rl&&r
70792289
$w == 1 and not $is_xlsx
!ll&&!rl&&r
698495291
MC/DC100%3/3
$w == 1 and not $is_xlsx and not $col_names
$w == 1 not $is_xlsx not $col_names
Truth table100%4/4
A and not(B) and not(C)
A= $w == 1B= not $is_xlsxC= not $col_names
ABCresult
0XX0
10X0
1100
1111
4064 289 ▶ my $where = $want_header ? 'the header' : 'data row 1';
Branch: 1 branch
BranchTrueFalseTotal
$want_header ? : 258 31 289
4065 289 ▶ if ($sep_re) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sep_re) { } 72 217 289
4066 72 $sep_note = "$where has no match for the sep regex $sep_re, so "
4067 . "it may not be what separates this file's fields";
4068 } else {
4069 217 ▶ my $s = $args{sep} eq "\t" ? '\t' : $args{sep};
Branch: 1 branch
BranchTrueFalseTotal
$args{'sep'} eq "\t" ? : 30 187 217
4070 $sep_note = exists $input_args{sep}
4071 217 ▶ ? "$where has no '$s' in it, so '$s' may not be what "
Branch: 1 branch
BranchTrueFalseTotal
exists $input_args{'sep'} ? : 57 160 217
4072 . "separates this file's fields"
4073 : "$where has no '$s' in it, and '$s' is only the default "
4074 . "sep for this file's name: pass 'sep' if its fields are "
4075 . "separated by something else";
4076 }
4077 289 $sep_note = _as_bytes($sep_note);
4078 }
4079 7652 };
4080  
4081 # _parse_csv_file() treats a line whose comment marker is followed by
4082 # whitespace (e.g. "# PDB\tscore") as a comment and drops it, so a header
4083 # written that way never reaches the callback and the first data row would
4084 # be mistaken for the header. Recover it: read the first physical line, and
4085 # if it is marker + whitespace and splits into >=2 fields, hold it as a
4086 # CANDIDATE header. It is confirmed (in the callback) only if its field
4087 # count matches the first line the parser delivers and that line looks
4088 # like data rather than a header (see $is_data below); otherwise it was an
4089 # ordinary leading comment and is discarded. A marker hugging its text ("#id,val") is
4090 # delivered by the parser and held as a candidate in the same way by the
4091 # callback, so it never reaches this branch.
4092 7652 ▶ if ($want_header && !$is_xlsx && length( $args{comment} // '' )
Branch: 1 branch
BranchTrueFalseTotal
if ($want_header and not $is_xlsx and length($args{"comment"} // "") and length($args{"sep"} // "")) 6890 762 7652
Condition69%9/13
$want_header and not $is_xlsx and length($args{"comment"} // "") and length($args{"sep"} // "")
!ll&&!rl&&r
76206890
$want_header and not $is_xlsx and length($args{"comment"} // "")
!ll&&!rl&&r
76206890
$want_header and not $is_xlsx
!ll&&!rl&&r
2904726890
$args{"comment"} // ""
l!l
68900
$args{"sep"} // ""
l!l
68900
MC/DC50%2/4
$want_header and not $is_xlsx and length($args{"comment"} // "") and length($args{"sep"} // "")
$want_header not $is_xlsx $args{"comment"} $args{"sep"}
Truth table60%3/5
A and not(B) and C and D
A= $want_headerB= not $is_xlsxC= $args{"comment"}D= $args{"sep"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
4093 && length( $args{sep} // '' )) {
4094 # $/ is the caller's, and under a `local $/;` this read the whole
4095 # file; _parse_csv_file() splits on "\n" (or "\r", see _eol_is_cr)
4096 # whatever $/ is, and so does this. A UTF-8 byte-order mark is dropped
4097 # here as the parser drops it.
4098 6890 ▶ my $fh = $codec ? _open_decompressed($file, $codec)
Branch: 1 branch
BranchTrueFalseTotal
$codec ? : 120 6770 6890
4099 : _open_read($file);
4100 6890 ▶ binmode $fh unless $codec; # the parser's bytes; see _eol_is_cr for the codec case
Branch: 1 branch
BranchTrueFalseTotal
unless $codec 6770 120 6890
4101 6890 my $first = do { local $/ = $eol; <$fh> };
4102 6890 _close($fh);
4103 6890 ▶ $first =~ s/\A\xEF\xBB\xBF// if defined $first;
Branch: 1 branch
BranchTrueFalseTotal
if defined $first 6887 3 6890
4104 6890 ▶ if (defined $first && $first =~ /^\Q$args{comment}\E\s/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $first and $first =~ /^\Q$args{"comment"}\E\s/) 112 6778 6890
Condition100%3/3
defined $first and $first =~ /^\Q$args{"comment"}\E\s/
!ll&&!rl&&r
36775112
MC/DC100%2/2
defined $first and $first =~ /^\Q$args{"comment"}\E\s/
defined $first $first =~ /^\Q$args{"comment"}\E\s/
Truth table100%3/3
A and B
A= defined $firstB= $first =~ /^\Q$args{"comment"}\E\s/
ABresult
0X0
100
111
4105 112 ▶ if ($cr_eol) { $first =~ s/\r\z// } else { $first =~ s/\r?\n\z// }
Branch: 1 branch
BranchTrueFalseTotal
if ($cr_eol) { } 2 110 112
4106 # The marker and the blanks after it come off before the cut, so
4107 # that neither can become a field: a tab after "#" in a
4108 # tab-separated file made an empty first column of "#\tid\tval",
4109 # whose three names then failed to match two-field data rows.
4110 112 (my $body = $first) =~ s/^\Q$args{comment}\E\s*//;
4111 # The rest is cut by _parse_csv_file() itself, through an in-memory
4112 # handle, so it is split by exactly the rules the data will be:
4113 # up to 0.3213 a perl split() ignored quoting, and # "x,y",z came
4114 # out as three names. Both mismatches promoted the first data row
4115 # to the header without a word. Quoting is left off for a comment
4116 # with an odd number of '"', which no one-line row of quoted
4117 # fields has, so that prose like 5'10" is not taken for a quoted
4118 # field running to the end of the file; and a sep regex that
4119 # croaks on this line leaves it as no candidate at all, since the
4120 # parser drops it as a comment and would never have seen it.
4121 112 my @cols;
4122 112 ▶ if (length $body) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 112 0 112
4123 112 ▶ my $q = $quote && !(($body =~ tr/"//) % 2);
Condition66%2/3
$quote && !($body =~ tr/"// % 2)
!ll&&!rl&&r
01111
MC/DC50%1/2
$quote && !($body =~ tr/"// % 2)
$quote !($body =~ tr/"// % 2)
Truth table66%2/3
A && not(B)
A= $quoteB= !($body =~ tr/"// % 2)
ABresult
0X0
100
111
4124 112 my $rows = eval {
4125 112 ▶ open my $mfh, '<', \$body
Branch: 1 branch
BranchTrueFalseTotal
open my $mfh, "<", \$body or die "read_table: could not read the commented-out header\n" 112 0 112
4126 or die "read_table: could not read the commented-out header\n";
4127 112 ▶ _parse_csv_file($file, $sep_re ? '' : $args{sep}, '', undef,
Branch: 2 branches
BranchTrueFalseTotal
$sep_re ? : 9 103 112
$sep_re && _sep_re_is_ws($sep_re) ? : 7 105 112
Condition100%3/3
$sep_re and _sep_re_is_ws($sep_re)
!ll&&!rl&&r
10327
MC/DC100%2/2
$sep_re and _sep_re_is_ws($sep_re)
$sep_re _sep_re_is_ws($sep_re)
Truth table100%3/3
A and B
A= $sep_reB= _sep_re_is_ws($sep_re)
ABresult
0X0
100
111
4128 undef, $q, 0, $sep_re,
4129 $sep_re && _sep_re_is_ws($sep_re) ? 1 : 0, $mfh, 0);
4130 };
4131 112 ▶ @cols = @{ $rows->[0] } if $rows && @$rows;
Branch: 1 branch
BranchTrueFalseTotal
if $rows and @$rows 112 0 112
Condition33%1/3
$rows and @$rows
!ll&&!rl&&r
00112
MC/DC0%0/2
$rows and @$rows
$rows @$rows
Truth table33%1/3
A and B
A= $rowsB= @$rows
ABresult
0X0
100
111
4132 }
4133 112 ▶ if (@cols >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@cols >= 2) 83 29 112
4134 83 @header = @cols;
4135 83 $header_seen = 1;
4136 83 $provisional_hdr = 1; # confirm against the first data row
4137 }
4138 }
4139 }
4140  
4141 # $quote_note is the parser's account of a quoted field that ran this row
4142 # across lines (S_quote_note() in LikeR.xs), undef for a one-line row; it
4143 # only ever goes into the alignment message. $first_quoted is true when the
4144 # row's first field was written in '"' (S_emit_row()), so that a comment
4145 # marker at its start is text, never a commented-out header's.
4146 33101 ▶ my $on_line = sub {
Subroutine __ANON__: called CC=84 SCAR=44.6
4147 33101 my ($line_ref, $quote_note, $first_quoted) = @_;
4148  
4149 # quote => '' on a file whose first line has every field in '"' keeps
4150 # the quote marks in every name or value: R's write.csv() writes
4151 # exactly that header, and it is read as intended only with the
4152 # default quote. 'quote' means nothing to an .xlsx, so it is not checked.
4153 33101 ▶ if (!$header_seen && !$quote && !$is_xlsx && @$line_ref
Branch: 1 branch
BranchTrueFalseTotal
if (not $header_seen || $quote || $is_xlsx and @$line_ref and not grep({not defined $_ && /\A".*"\z/s;} @$line_ref)) 82 33019 33101
Condition91%11/12
not $header_seen || $quote || $is_xlsx and @$line_ref and not grep({not defined $_ && /\A".*"\z/s;} @$line_ref)
!ll&&!rl&&r
329239682
not $header_seen || $quote || $is_xlsx and @$line_ref
!ll&&!rl&&r
329230178
$header_seen || $quote || $is_xlsx
l!l&&r!l&&!r
329221178
$header_seen or $quote
l!l&&r!l&&!r
255487374179
MC/DC80%4/5
not $header_seen || $quote || $is_xlsx and @$line_ref and not grep({not defined $_ && /\A".*"\z/s;} @$line_ref)
$header_seen $quote $is_xlsx @$line_ref not grep({not defined $_ && /\A".*"\z/s;} @$line_ref)
Truth table83%5/6
not(A or B || C) and D and not(E)
A= $header_seenB= $quoteC= $is_xlsxD= @$line_refE= not grep({not defined $_ && /\A".*"\z/s;} @$line_ref)
ABCDEresult
1XXXX0
01XXX0
001XX0
0000X0
000100
000111
4154 1020 ▶ && !grep { !defined || !/\A".*"\z/s } @$line_ref) {
Condition66%2/3
defined $_ && /\A".*"\z/s
!ll&&!rl&&r
0417603
MC/DC50%1/2
defined $_ && /\A".*"\z/s
defined $_ /\A".*"\z/s
Truth table66%2/3
A && B
A= defined $_B= /\A".*"\z/s
ABresult
0X0
100
111
4155 82 warn "read_table: every field on the first line of $file is "
4156 . "wrapped in '\"', and quote => '' keeps the quote marks as "
4157 . "part of the text; leave 'quote' out to read them as quoting\n";
4158 }
4159  
4160 33101 ▶ if (!$header_seen && !$want_header) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($header_seen or $want_header) 289 32812 33101
Condition100%3/3
$header_seen or $want_header
l!l&&r!l&&!r
255487264289
MC/DC100%2/2
$header_seen or $want_header
$header_seen $want_header
Truth table100%3/3
A or B
A= $header_seenB= $want_header
ABresult
1X1
011
000
4161 # header => 0: this line is the first data row, so it only sets the
4162 # width; the names come from 'col_names' or are V1, V2, ... It falls
4163 # through to be finalized and read as data below.
4164 289 ▶ @header = $col_names ? @$col_names : map { "V$_" } 1 .. @$line_ref;
Branch: 1 branch
BranchTrueFalseTotal
$col_names ? : 35 254 289
4165 289 $header_seen = 1;
4166 }
4167 # A line whose marker hugs its text ("#id,val") is not dropped by the
4168 # parser, since it may be a commented-out header. It is held as a
4169 # CANDIDATE, as the "# id,val" form read above is, and a later one
4170 # replaces it, so in a run of them it is the last -- the one next to
4171 # the data -- that is tried. Up to 0.3213 the first was taken for the
4172 # header on the spot, so a VCF's 140 "##" meta lines became one
4173 # column called "fileformat=VCFv4.2" and the "#CHROM" line an
4174 # alignment error. Only while no real header has been taken: after
4175 # that, such a line is data, as it has always been.
4176 # Not in an .xlsx, where 'comment' has never applied: a first cell
4177 # such as "#id" or "# of items" is a cell, and treating it as a
4178 # commented-out header lost "#a1"-style data rows wholesale up to 0.3213.
4179 # Nor in a quoted first field: R's read.table() reads a comment
4180 # character inside quotes as text, and up to 0.3213 "#a",b came back
4181 # as a column named a -- or, where the next row was text as well, not
4182 # at all, that row being taken for the header in its place.
4183 33101 ▶ if ((!$header_seen || $provisional_hdr) && !$is_xlsx && !$first_quoted
Branch: 1 branch
BranchTrueFalseTotal
if (!$header_seen || $provisional_hdr and not $is_xlsx and not $first_quoted and length($args{"comment"} // "") and @$line_ref and defined $line_ref->[0] and index($line_ref->[0], $args{"comment"}) == 0) 1178 31923 33101
Condition82%19/23
!$header_seen || $provisional_hdr and not $is_xlsx and not $first_quoted and length($args{"comment"} // "") and @$line_ref and defined $line_ref->[0] and index($line_ref->[0], $args{"comment"}) == 0
!ll&&!rl&&r
2560463191178
!$header_seen || $provisional_hdr and not $is_xlsx and not $first_quoted and length($args{"comment"} // "") and @$line_ref and defined $line_ref->[0]
!ll&&!rl&&r
2560407497
!$header_seen || $provisional_hdr and not $is_xlsx and not $first_quoted and length($args{"comment"} // "") and @$line_ref
!ll&&!rl&&r
2560407497
!$header_seen || $provisional_hdr and not $is_xlsx and not $first_quoted and length($args{"comment"} // "")
!ll&&!rl&&r
2560407497
!$header_seen || $provisional_hdr and not $is_xlsx and not $first_quoted
!ll&&!rl&&r
250405647497
!$header_seen || $provisional_hdr and not $is_xlsx
!ll&&!rl&&r
245784628061
not $header_seen or $provisional_hdr
l!l&&r!l&&!r
7264125924578
$args{"comment"} // ""
l!l
74970
MC/DC62%5/8
!$header_seen || $provisional_hdr and not $is_xlsx and not $first_quoted and length($args{"comment"} // "") and @$line_ref and defined $line_ref->[0] and index($line_ref->[0], $args{"comment"}) == 0
not $header_seen $provisional_hdr not $is_xlsx not $first_quoted $args{"comment"} @$line_ref defined $line_ref->[0] index($line_ref->[0], $args{"comment"}) == 0
Truth table53%8/15
not(A) or B and not(C) and not(D) and E and F and G and H
A= not $header_seenB= $provisional_hdrC= not $is_xlsxD= not $first_quotedE= $args{"comment"}F= @$line_refG= defined $line_ref->[0]H= index($line_ref->[0], $args{"comment"}) == 0
ABCDEFGHresult
00XXXXXX0
1X0XXXXX0
010XXXXX0
1X10XXXX0
0110XXXX0
1X110XXX0
01110XXX0
1X1110XX0
011110XX0
1X11110X0
0111110X0
1X1111100
011111100
1X1111111
011111111
4184 && length( $args{comment} // '' )
4185 && @$line_ref && defined $line_ref->[0]
4186 && index($line_ref->[0], $args{comment}) == 0) {
4187 1178 @header = @$line_ref;
4188 1178 $header[0] =~ s/^\Q$args{comment}\E\s*//;
4189 1178 $header_seen = 1;
4190 1178 $provisional_hdr = 1; # confirm against the first data row
4191 1178 return;
4192 }
4193  
4194 31923 ▶ if (!$header_seen) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($header_seen) 7068 24855 31923
4195 # HEADER CAPTURE (copy made only here; runs once). A commented
4196 # line never gets here: it was taken as a candidate just above.
4197 7068 @header = @$line_ref;
4198 7068 $header_seen = 1;
4199 7068 ▶ unless ($want_auto_rn) { # strict: finalize immediately
Branch: 1 branch
BranchTrueFalseTotal
unless ($want_auto_rn) 6521 547 7068
4200 6521 $finalize_header->();
4201 6257 $header_done = 1;
4202 6257 $install_plan->();
4203 }
4204 6804 return;
4205 }
4206  
4207 24855 ▶ if (!$header_done) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($header_done) 1115 23740 24855
4208 # Confirm or reject a provisionally-captured commented-out header:
4209 # it is a real header only if its field count matches the first
4210 # data row. If not, the candidate was an ordinary leading comment;
4211 # discard it and treat THIS delivered line as the header instead.
4212 1115 ▶ if ($provisional_hdr) {
Branch: 1 branch
BranchTrueFalseTotal
if ($provisional_hdr) 277 838 1115
4213 277 $provisional_hdr = 0;
4214 # Under auto_row_names a header one field short of the data is
4215 # the shape being looked for, not a mismatch; refusing it here
4216 # made the first data row the header (0.320 and before).
4217 277 ▶ my $one_short = $want_auto_rn && @$line_ref == @header + 1;
Condition100%3/3
$want_auto_rn && @$line_ref == @header + 1
!ll&&!rl&&r
263212
MC/DC100%2/2
$want_auto_rn && @$line_ref == @header + 1
$want_auto_rn @$line_ref == @header + 1
Truth table100%3/3
A && B
A= $want_auto_rnB= @$line_ref == @header + 1
ABresult
0X0
100
111
4218 # The same width is not enough on its own. "# written by foo,
4219 # v2" before "id,val" has two fields too, and up to 0.3213 that
4220 # comment became the header and "id,val" the first data row,
4221 # without a word. A row the same width is taken for data only
4222 # when one of its fields is a number or an na_strings token, or
4223 # every field is empty, which no header is; otherwise it is the
4224 # file's own header, as R and pandas read it, and the comment
4225 # is a comment.
4226 2066 ▶ my $is_data = (!grep { defined && length } @$line_ref)
Condition66%2/3
defined $_ && length $_
!ll&&!rl&&r
022064
MC/DC50%1/2
defined $_ && length $_
defined $_ length $_
Truth table66%2/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
4227 || grep {
4228 277 ▶ defined && length
Condition100%3/3
!grep({defined $_ and length $_;} @$line_ref) || grep({defined $_ and length $_ and &looks_like_number($_) || $has_na && $na_string{$_};} @$line_ref)
l!l&&r!l&&!r
1104172
MC/DC100%2/2
!grep({defined $_ and length $_;} @$line_ref) || grep({defined $_ and length $_ and &looks_like_number($_) || $has_na && $na_string{$_};} @$line_ref)
!grep({defined $_ and length $_;} @$line_ref) grep({defined $_ and length $_ and &looks_like_number($_) || $has_na && $na_string{$_};} @$line_ref)
Truth table100%3/3
not(A) || B
A= !grep({defined $_ and length $_;} @$line_ref)B= grep({defined $_ and length $_ and &looks_like_number($_) || $has_na && $na_string{$_};} @$line_ref)
ABresult
1X1
011
000
4229 2064 ▶ && (looks_like_number($_) || ($has_na && $na_string{$_}))
Condition75%9/12
defined $_ && length $_ && (&looks_like_number($_) || $has_na && $na_string{$_})
!ll&&!rl&&r
01863201
defined $_ and length $_
!ll&&!rl&&r
002064
&looks_like_number($_) or $has_na and $na_string{$_}
l!l&&r!l&&!r
19831863
$has_na and $na_string{$_}
!ll&&!rl&&r
1799643
MC/DC60%3/5
defined $_ && length $_ && (&looks_like_number($_) || $has_na && $na_string{$_})
defined $_ length $_ &looks_like_number($_) $has_na $na_string{$_}
Truth table66%4/6
A and B && C or D and E
A= defined $_B= length $_C= &looks_like_number($_)D= $has_naE= $na_string{$_}
ABCDEresult
0XXXX0
10XXX0
1100X0
110100
111XX1
110111
4230 } @$line_ref;
4231 277 ▶ if (!$one_short && (@$line_ref != @header || !$is_data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $one_short and @$line_ref != @header || !$is_data) 172 105 277
Condition100%6/6
not $one_short and @$line_ref != @header || !$is_data
!ll&&!rl&&r
1293172
@$line_ref != @header or not $is_data
l!l&&r!l&&!r
1581493
MC/DC100%3/3
not $one_short and @$line_ref != @header || !$is_data
not $one_short @$line_ref != @header not $is_data
Truth table100%4/4
not(A) and B or not(C)
A= not $one_shortB= @$line_ref != @headerC= not $is_data
ABCresult
0XX0
1000
11X1
1011
4232 # not commented: a commented line is a candidate above
4233 172 @header = @$line_ref;
4234 172 ▶ unless ($want_auto_rn) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($want_auto_rn) 170 2 172
4235 170 $finalize_header->();
4236 169 $header_done = 1;
4237 169 $install_plan->();
4238 }
4239 171 return; # this line WAS the header, not data
4240 }
4241 # widths match and the row is data: accept the commented
4242 # header, and let the auto_row_names / finalize logic below
4243 # run on THIS data row.
4244 }
4245  
4246 # First data row in auto_row_names mode: now the data width is
4247 # known, so decide whether the file carries an unlabelled leading
4248 # row-names column (header exactly one field short).
4249 943 ▶ if ($want_auto_rn && @$line_ref == @header + 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($want_auto_rn and @$line_ref == @header + 1) 115 828 943
Condition100%3/3
$want_auto_rn and @$line_ref == @header + 1
!ll&&!rl&&r
381447115
MC/DC100%2/2
$want_auto_rn and @$line_ref == @header + 1
$want_auto_rn @$line_ref == @header + 1
Truth table100%3/3
A and B
A= $want_auto_rnB= @$line_ref == @header + 1
ABresult
0X0
100
111
4250 115 unshift @header, $auto_rn_name;
4251 115 $auto_rn_added = 1;
4252 }
4253 943 $finalize_header->();
4254 942 $header_done = 1;
4255 942 $install_plan->();
4256 # fall through and process THIS line as data
4257 }
4258  
4259 # --- DATA PROCESSING (operate on $line_ref directly; no row copy)
4260 24682 $data_row++;
4261 24682 ▶ if (@$line_ref != @header) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$line_ref != @header) 42 24640 24682
4262 # FIX: alignment errors now say WHICH row is ragged. The words
4263 # are S_fast_row()'s in LikeR.xs, and must stay the same.
4264 42 ▶ die sprintf "Alignment error on %s data row %d (%d fields vs %s)%s%s.\n",
Branch: 2 branches
BranchTrueFalseTotal
defined $quote_note ? : 7 35 42
defined $sep_note && @$line_ref > @header ? : 9 33 42
Condition66%2/3
defined $sep_note and @$line_ref > @header
!ll&&!rl&&r
3309
MC/DC50%1/2
defined $sep_note and @$line_ref > @header
defined $sep_note @$line_ref > @header
Truth table66%2/3
A and B
A= defined $sep_noteB= @$line_ref > @header
ABresult
0X0
100
111
4265 $file, $data_row, scalar @$line_ref, $width_txt,
4266 defined $quote_note ? "; $quote_note" : '',
4267 defined $sep_note && @$line_ref > @header ? "; $sep_note" : '';
4268 }
4269 24640 my %line_hash;
4270 24640 for my $i (@kept_flds) { # every field, unless 'drop_cols' left some out
4271 373090 my $v = $line_ref->[$i];
4272 $line_hash{ $header[$i] }
4273 = ( !defined($v) || $v eq ''
4274 373090 ▶ || ( $has_na && $na_string{$v} ) ) ? undef : $v;
Branch: 1 branch
BranchTrueFalseTotal
!defined($v) || $v eq '' || $has_na && $na_string{$v} ? : 40266 332824 373090
Condition88%8/9
not defined $v or $v eq "" or $has_na and $na_string{$v}
l!l&&r!l&&!r
318938373332824
not defined $v or $v eq ""
l!l&&r!l&&!r
031893341197
$has_na and $na_string{$v}
!ll&&!rl&&r
106243222008373
MC/DC75%3/4
not defined $v or $v eq "" or $has_na and $na_string{$v}
not defined $v $v eq "" $has_na $na_string{$v}
Truth table80%4/5
not(A) or B or C and D
A= not defined $vB= $v eq ""C= $has_naD= $na_string{$v}
ABCDresult
1XXX1
01XX1
00111
000X0
00100
4275 }
4276 # APPLY FILTERS
4277 24640 ▶ if (@sorted_filter_flds) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sorted_filter_flds) 328 24312 24640
4278 328 local *_ = \%line_hash;
4279 328 foreach my $fld (@sorted_filter_flds) {
4280 400 for my $sub (@{ $mapped_filters{$fld} }) {
4281 # The field's value as %line_hash holds it, which is what
4282 # an earlier filter may have changed -- except for a field
4283 # whose name a later field repeats, whose own value is not
4284 # in %line_hash at all; that one is read from the row by
4285 # the rule %line_hash is built by.
4286 local $_ = $fld == 0 ? $line_ref
4287 : $field_wins[ $fld - 1 ] ? $line_hash{ $header[ $fld - 1 ] }
4288 404 ▶ : do {
Branch: 2 branches
BranchTrueFalseTotal
$fld == 0 ? : 79 325 404
$field_wins[$fld - 1] ? : 196 129 325
4289 129 my $v = $line_ref->[ $fld - 1 ];
4290 ( !defined($v) || $v eq ''
4291 129 ▶ || ( $has_na && $na_string{$v} ) ) ? undef : $v
Branch: 1 branch
BranchTrueFalseTotal
!defined($v) || $v eq '' || $has_na && $na_string{$v} ? : 18 111 129
Condition55%5/9
not defined $v or $v eq "" or $has_na and $na_string{$v}
l!l&&r!l&&!r
180111
not defined $v or $v eq ""
l!l&&r!l&&!r
018111
$has_na and $na_string{$v}
!ll&&!rl&&r
11100
MC/DC25%1/4
not defined $v or $v eq "" or $has_na and $na_string{$v}
not defined $v $v eq "" $has_na $na_string{$v}
Truth table40%2/5
not(A) or B or C and D
A= not defined $vB= $v eq ""C= $has_naD= $na_string{$v}
ABCDresult
1XXX1
01XX1
00111
000X0
00100
4292 };
4293 404 ▶ return if !$sub->( $line_ref, \%line_hash );
Branch: 1 branch
BranchTrueFalseTotal
unless &$sub($line_ref, \%line_hash) 86 317 403
4294 317 ▶ next if $fld == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $fld == 0 74 243 317
4295 # write back any mutation made to $_
4296 243 $line_ref->[ $fld - 1 ] = $_;
4297 # na_strings applies to a written-back value too, so the
4298 # empty-string rule and the NA rule stay the same rule.
4299 # A field whose name a later field repeats is not the one
4300 # %line_hash holds, so it does not overwrite it.
4301 $line_hash{ $header[ $fld - 1 ] }
4302 = ( !defined($_) || $_ eq ''
4303 243 ▶ || ( $has_na && $na_string{$_} ) ) ? undef : $_
Branch: 2 branches
BranchTrueFalseTotal
if $field_wins[$fld - 1] 150 93 243
!defined($_) || $_ eq '' || $has_na && $na_string{$_} ? : 13 137 150
Condition77%7/9
not defined $_ or $_ eq "" or $has_na and $na_string{$_}
l!l&&r!l&&!r
130137
not defined $_ or $_ eq ""
l!l&&r!l&&!r
94137
$has_na and $na_string{$_}
!ll&&!rl&&r
111260
MC/DC0%0/4
not defined $_ or $_ eq "" or $has_na and $na_string{$_}
not defined $_ $_ eq "" $has_na $na_string{$_}
Truth table0%0/5
not(A) or B or C and D
A= not defined $_B= $_ eq ""C= $has_naD= $na_string{$_}
ABCDresult
1XXX1
01XX1
00111
000X0
00100
4304 if $field_wins[ $fld - 1 ];
4305 }
4306 }
4307 }
4308 # colClasses, after the filters and on %line_hash itself, as the parser does it
4309 # (S_filter_row() in LikeR.xs); a key a filter deleted stays deleted. An aoa's
4310 # fields are converted as they are copied, below.
4311 24553 ▶ if (@cls && $otype ne 'aoa') {
Branch: 1 branch
BranchTrueFalseTotal
if (@cls and $otype ne "aoa") 18544 6009 24553
Condition100%3/3
@cls and $otype ne "aoa"
!ll&&!rl&&r
15599418544
MC/DC100%2/2
@cls and $otype ne "aoa"
@cls $otype ne "aoa"
Truth table100%3/3
A and B
A= @clsB= $otype ne "aoa"
ABresult
0X0
100
111
4312 18544 ▶ for my $f (grep { $cls[$_] && $field_wins[$_] } 0 .. $#header) {
Condition100%3/3
$cls[$_] && $field_wins[$_]
!ll&&!rl&&r
38379375280665
MC/DC100%2/2
$cls[$_] && $field_wins[$_]
$cls[$_] $field_wins[$_]
Truth table100%3/3
A && B
A= $cls[$_]B= $field_wins[$_]
ABresult
0X0
100
111
4313 280647 my $name = $header[$f];
4314 $line_hash{$name} = _cell_class($line_hash{$name}, $cls[$f],
4315 $file, $data_row, $name, $f + 1)
4316 280647 ▶ if exists $line_hash{$name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $line_hash{$name} 280647 0 280647
4317 }
4318 }
4319 # Populate requested data structure
4320 24514 ▶ if ($otype eq 'aoh') {
Branch: 4 branches
BranchTrueFalseTotal
if ($otype eq 'aoh') { } 6376 18138 24514
elsif ($otype eq 'aoa') { } 5997 12141 18138
elsif ($otype eq 'hoa') { } 6043 6098 12141
elsif ($otype eq 'hoh') { } 6098 0 6098
4321 6376 push @data, \%line_hash;
4322 } elsif ($otype eq 'aoa') {
4323 # from the fields rather than %line_hash, so a repeated name keeps
4324 # every one of its fields, as the fast path's mode 3 does
4325 push @data, [ map {
4326 91912 my $v = $line_ref->[$_];
4327 91912 ▶ $v = undef if !defined($v) || $v eq '' || ( $has_na && $na_string{$v} );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $v or $v eq "" or $has_na and $na_string{$v} 10045 81867 91912
Condition100%9/9
not defined $v or $v eq "" or $has_na and $na_string{$v}
l!l&&r!l&&!r
7955209081867
not defined $v or $v eq ""
l!l&&r!l&&!r
2795383957
$has_na and $na_string{$v}
!ll&&!rl&&r
1772800952090
MC/DC100%4/4
not defined $v or $v eq "" or $has_na and $na_string{$v}
not defined $v $v eq "" $has_na $na_string{$v}
Truth table100%5/5
not(A) or B or C and D
A= not defined $vB= $v eq ""C= $has_naD= $na_string{$v}
ABCDresult
1XXX1
01XX1
00111
000X0
00100
4328 91912 ▶ ( defined $v && @cls && $cls[$_] )
Branch: 1 branch
BranchTrueFalseTotal
defined $v && @cls && $cls[$_] ? : 81832 10080 91912
Condition100%6/6
defined $v and @cls and $cls[$_]
!ll&&!rl&&r
100592181832
defined $v and @cls
!ll&&!rl&&r
100451481853
MC/DC100%3/3
defined $v and @cls and $cls[$_]
defined $v @cls $cls[$_]
Truth table100%4/4
A and B and C
A= defined $vB= @clsC= $cls[$_]
ABCresult
0XX0
10X0
1100
1111
4329 ? _cell_class($v, $cls[$_], $file, $data_row, $header[$_], $_ + 1)
4330 : $v
4331 5997 } grep { !$excl[$_] } 0 .. $#$line_ref ]; # a field past the header is one a filter added
4332 } elsif ($otype eq 'hoa') {
4333 6043 my $c = 0;
4334 6043 push @{ $hoa_cols[ $c++ ] }, $line_hash{$_} for @uniq_header;
4335 } elsif ($otype eq 'hoh') {
4336 6098 my $row_name = $line_hash{ $args{'row_names'} };
4337 die sprintf "read_table: undefined row name (column '%s') in %s data row %d\n",
4338 6098 ▶ $args{'row_names'}, $file, $data_row
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row_name 8 6090 6098
4339 unless defined $row_name;
4340 6090 ▶ if ($seen_rownames{$row_name}++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen_rownames{$row_name}++) 5 6085 6090
4341 5 $n_dup_rn++;
4342 5 ▶ $first_dup_rn ||= [ $row_name, $data_row ];
Condition100%2/2
$first_dup_rn ||= [$row_name, $data_row]
l!l
23
MC/DC100%1/1
$first_dup_rn ||= [$row_name, $data_row]
$first_dup_rn
Truth table100%2/2
A
A= $first_dup_rn
Aresult
11
00
4343 }
4344 # made up front, so that a file whose only column is the row name
4345 # still has its rows -- as empty hashes, the way R's read.table
4346 # gives it a data frame of n rows and 0 columns -- rather than none
4347 6090 ▶ my $row = $data{$row_name} ||= {};
Condition100%2/2
$data{$row_name} ||= {}
l!l
56085
MC/DC100%1/1
$data{$row_name} ||= {}
$data{$row_name}
Truth table100%2/2
A
A= $data{$row_name}
Aresult
11
00
4348 6090 foreach my $col (@uniq_header) {
4349 94350 ▶ next if $col eq $args{'row_names'};
Branch: 1 branch
BranchTrueFalseTotal
if $col eq $args{"row_names"} 6090 88260 94350
4350 88260 $row->{$col} = $line_hash{$col};
4351 }
4352 }
4353 7652 };
4354 7652 ▶ if ($is_xlsx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_xlsx) { } 473 7179 7652
4355 # the sheet first, so a bad 'sheet' is refused before the whole
4356 # shared-string table has been inflated and parsed for nothing
4357 my $chosen = defined $args{_sheet_ix} ? $xlsx_sheets->[ $args{_sheet_ix} ]
4358 473 ▶ : _xlsx_choose_sheet($file, $xlsx_sheets, $args{sheet});
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'_sheet_ix'} ? : 97 376 473
4359 468 ▶ my $sst = $args{_sst} // _xlsx_shared_strings($file, $xlsx_rels);
Condition66%2/3
$args{"_sst"} // _xlsx_shared_strings($file, $xlsx_rels)
l!l&&r!l&&!r
973710
MC/DC0%0/2
$args{"_sst"} // _xlsx_shared_strings($file, $xlsx_rels)
$args{"_sst"} _xlsx_shared_strings($file, $xlsx_rels)
Truth table66%2/3
A // B
A= $args{"_sst"}B= _xlsx_shared_strings($file, $xlsx_rels)
ABresult
1X1
011
000
4360 468 _parse_xlsx_sheet($file, $sst, $chosen->{path}, $on_line, $plan);
4361 } else {
4362 7179 ▶ my $fh = $codec ? _open_decompressed($file, $codec) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$codec ? : 126 7053 7179
4363 _parse_csv_file($file, $sep_re ? '' : $args{sep} // '',
4364 7179 ▶ $args{comment} // '', $on_line, $plan, $quote,
Branch: 3 branches
BranchTrueFalseTotal
$sep_re ? : 820 6359 7179
$want_header ? : 6890 289 7179
$sep_re && _sep_re_is_ws($sep_re) ? : 163 7016 7179
Condition71%5/7
$args{"sep"} // ""
l!l
63590
$args{"comment"} // ""
l!l
71790
$sep_re and _sep_re_is_ws($sep_re)
!ll&&!rl&&r
6359657163
MC/DC0%0/1
$args{"sep"} // ""
$args{"sep"}
MC/DC0%0/1
$args{"comment"} // ""
$args{"comment"}
MC/DC100%2/2
$sep_re and _sep_re_is_ws($sep_re)
$sep_re _sep_re_is_ws($sep_re)
Truth table50%1/2
A
A= $args{"sep"}
Aresult
11
00
Truth table50%1/2
A
A= $args{"comment"}
Aresult
11
00
Truth table100%3/3
A and B
A= $sep_reB= _sep_re_is_ws($sep_re)
ABresult
0X0
100
111
4365 $want_header ? 0 : 1, $sep_re,
4366 $sep_re && _sep_re_is_ws($sep_re) ? 1 : 0, $fh, $cr_eol);
4367 6693 ▶ _close($fh) if $fh;
Branch: 1 branch
BranchTrueFalseTotal
if $fh 120 6573 6693
4368 }
4369 # A hoh's repeated row names, from this closure and from the fast path
4370 # (S_plan_report() in LikeR.xs) together. One warning for the file: up to
4371 # 0.3213 there was one per repeated row, 40,820 of them for a 300,000-row
4372 # file. A single repeat keeps the words it has always had.
4373 7092 ▶ if ($plan && $plan->{dup_n}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plan and $plan->{"dup_n"}) 222 6870 7092
Condition100%3/3
$plan and $plan->{"dup_n"}
!ll&&!rl&&r
9075963222
MC/DC100%2/2
$plan and $plan->{"dup_n"}
$plan $plan->{"dup_n"}
Truth table100%3/3
A and B
A= $planB= $plan->{"dup_n"}
ABresult
0X0
100
111
4374 222 $n_dup_rn += $plan->{dup_n};
4375 222 ▶ $first_dup_rn ||= [ $plan->{dup_first}, $plan->{dup_row} ];
Condition50%1/2
$first_dup_rn ||= [$plan->{"dup_first"}, $plan->{"dup_row"}]
l!l
0222
MC/DC0%0/1
$first_dup_rn ||= [$plan->{"dup_first"}, $plan->{"dup_row"}]
$first_dup_rn
Truth table50%1/2
A
A= $first_dup_rn
Aresult
11
00
4376 }
4377 7092 ▶ if ($n_dup_rn == 1) {
Branch: 2 branches
BranchTrueFalseTotal
if ($n_dup_rn == 1) { } 9 7083 7092
elsif ($n_dup_rn) { } 216 6867 7083
4378 9 _warn_text("read_table: duplicate row name '$first_dup_rn->[0]' in $file "
4379 . "(later values win)\n");
4380 } elsif ($n_dup_rn) {
4381 216 _warn_text("read_table: $n_dup_rn rows of $file repeat an earlier row's name "
4382 . "(later values win); the first is '$first_dup_rn->[0]', on data "
4383 . "row $first_dup_rn->[1]\n");
4384 }
4385 # header-only files never hit a data row. A provisional (commented-out)
4386 # header was never confirmed against a data row, but with no data to
4387 # contradict it we accept it; either way still validate.
4388 7092 ▶ $finalize_header->() if $header_seen && !$header_done;
Branch: 1 branch
BranchTrueFalseTotal
if $header_seen and not $header_done 2 7090 7092
Condition100%3/3
$header_seen and not $header_done
!ll&&!rl&&r
970812
MC/DC100%2/2
$header_seen and not $header_done
$header_seen not $header_done
Truth table100%3/3
A and not(B)
A= $header_seenB= not $header_done
ABresult
0X0
100
111
4389 # A hoa's column arrays are now made when the header is finalized rather
4390 # than by the first push into them, so a file with a header and no data
4391 # rows would come back as one empty array per column. It has always come
4392 # back as {}, the way an aoh comes back as [], so keep it that way.
4393 7092 ▶ %data = () if $otype eq 'hoa' && @hoa_cols && !@{ $hoa_cols[0] };
Branch: 1 branch
BranchTrueFalseTotal
if $otype eq "hoa" and @hoa_cols and not @{$hoa_cols[0];} 9 7083 7092
Condition83%5/6
$otype eq "hoa" and @hoa_cols and not @{$hoa_cols[0];}
!ll&&!rl&&r
62098749
$otype eq "hoa" and @hoa_cols
!ll&&!rl&&r
62090883
MC/DC66%2/3
$otype eq "hoa" and @hoa_cols and not @{$hoa_cols[0];}
$otype eq "hoa" @hoa_cols not @{$hoa_cols[0];}
Truth table75%3/4
A and B and not(C)
A= $otype eq "hoa"B= @hoa_colsC= not @{$hoa_cols[0];}
ABCresult
0XX0
10X0
1100
1111
4394 7092 ▶ if ($otype eq 'aoh' || $otype eq 'aoa') {
Branch: 1 branch
BranchTrueFalseTotal
if ($otype eq 'aoh' or $otype eq 'aoa') { } 5364 1728 7092
Condition100%3/3
$otype eq "aoh" or $otype eq "aoa"
l!l&&r!l&&!r
239029741728
MC/DC100%2/2
$otype eq "aoh" or $otype eq "aoa"
$otype eq "aoh" $otype eq "aoa"
Truth table100%3/3
A or B
A= $otype eq "aoh"B= $otype eq "aoa"
ABresult
1X1
011
000
4395 5364 return \@data;
4396 } else { # hoa or hoh
4397 1728 return \%data;
4398 }
4399 }
4400 # view() and _render_grid(), the renderer it shares with summary(), are in
4401 # LikeR.xs, under "view() and summary(): the table renderer".
4402  
4403 # TukeyHSD($fit, %opts) -- Tukey Honest Significant Differences.
4404 #
4405 # Mirrors R's stats::TukeyHSD for the fitted objects produced by this
4406 # module's aov(), lm() and glm(). Base R only defines TukeyHSD.aov; this
4407 # extends the same all-pairwise studentized-range comparison to lm and glm
4408 # outputs as well.
4409 #
4410 # The fitted objects here do not retain the model frame, so unlike R the
4411 # response values and per-level replication counts are recomputed from the
4412 # data. Therefore the caller supplies the data frame and the response name:
4413 #
4414 # my $fit = aov({ weight => \@w, group => \@g }, 'weight ~ group');
4415 # my $hsd = TukeyHSD($fit, data => $df, formula => 'weight ~ group');
4416 # # or: TukeyHSD($fit, data => $df, response => 'weight');
4417 #
4418 # Options:
4419 # data (required) the AoH / HoA / HoH used to fit the model
4420 # response response column name; or give formula => 'y ~ ...'
4421 # formula alternative to response: LHS is parsed for the response
4422 # which factor name or arrayref of names (default: all factors)
4423 # conf_level confidence level, default 0.95 (the dotted conf.level is
4424 # refused as an unknown option)
4425 # ordered if true, order each factor's levels by increasing mean
4426 #
4427 # Returns a hashref: one entry per factor mapping to an arrayref of
4428 # comparison hashes { comparison, diff, lwr, upr, 'p adj' } in R's
4429 # lower-triangle order, plus the attributes 'conf_level' and 'ordered'.
4430 #
4431 # Scope: main-effect factors (those present in $fit->{xlevels}); a grouping
4432 # variable must be categorical (string levels) to be treated as a factor,
4433 # exactly as R requires factor(). MSE is the residual mean square (for glm
4434 # this is deviance/df_residual: exact for the gaussian family, a Wald-type
4435 # scale otherwise). Per-level means are observed marginal means, which
4436 # match R's model.tables means for one-way (and balanced) designs.
4437 30 ▶sub TukeyHSD {
Subroutine TukeyHSD: called CC=53 SCAR=43.3
Pod undocumented
4438 30 ▶ _usage_error('TukeyHSD', 'first argument must be a fitted-model hashref (from aov/lm/glm)')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $_[0] eq "HASH" 3 27 30
4439 unless ref($_[0]) eq 'HASH';
4440 # checked before %opt is filled, which an odd list would make perl's own
4441 # "Odd number of elements" die under FATAL warnings
4442 27 ▶ _usage_error('TukeyHSD', 'arguments after the fit must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
unless @_ % 2 1 26 27
4443 unless @_ % 2;
4444 26 my ($fit, %opt) = @_;
4445 26 my %known = map { $_ => 1 } qw(conf_level data formula ordered response which);
4446 26 my @bad = sort grep { !$known{$_} } keys %opt;
4447 26 ▶ _usage_error('TukeyHSD', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 0 26 26
4448  
4449 26 ▶ my $conf = exists $opt{conf_level} ? $opt{conf_level} : 0.95;
Branch: 1 branch
BranchTrueFalseTotal
exists $opt{'conf_level'} ? : 3 23 26
4450 26 ▶ _usage_error('TukeyHSD', 'conf_level must be between 0 and 1')
Branch: 1 branch
BranchTrueFalseTotal
unless $conf > 0 and $conf < 1 0 26 26
Condition33%1/3
$conf > 0 and $conf < 1
!ll&&!rl&&r
0026
MC/DC0%0/2
$conf > 0 and $conf < 1
$conf > 0 $conf < 1
Truth table33%1/3
A and B
A= $conf > 0B= $conf < 1
ABresult
0X0
100
111
4451 unless $conf > 0 && $conf < 1;
4452 26 ▶ my $ordered = $opt{ordered} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'ordered'} ? : 8 18 26
4453  
4454 my $data = $opt{data}
4455 26 ▶ or _usage_error('TukeyHSD', "'data' (the data frame used to fit the model) is required");
Branch: 1 branch
BranchTrueFalseTotal
my $data = $opt{"data"} or _usage_error("TukeyHSD", "'data' (the data frame used to fit the model) is required") 25 1 26
4456  
4457 # residual mean square (MSE) and residual d.f., per model type
4458 25 my ($mse, $df);
4459 25 ▶ if (ref($fit->{Residuals}) eq 'HASH') { # aov
Branch: 3 branches
BranchTrueFalseTotal
if (ref $fit->{'Residuals'} eq 'HASH') { } 23 2 25
elsif (exists $fit->{'rss'} and exists $fit->{'df_residual'}) { } 1 1 2
elsif (exists $fit->{'deviance'} and exists $fit->{'df_residual'}) { } 1 0 1
4460 23 $df = $fit->{Residuals}{Df};
4461 23 $mse = $fit->{Residuals}{'Mean Sq'};
4462 ▶ } elsif (exists($fit->{rss}) && exists($fit->{'df_residual'})) { # lm
Condition66%2/3
exists $fit->{"rss"} and exists $fit->{"df_residual"}
!ll&&!rl&&r
101
MC/DC50%1/2
exists $fit->{"rss"} and exists $fit->{"df_residual"}
exists $fit->{"rss"} exists $fit->{"df_residual"}
Truth table66%2/3
A and B
A= exists $fit->{"rss"}B= exists $fit->{"df_residual"}
ABresult
0X0
100
111
4463 1 $df = $fit->{'df_residual'};
4464 1 ▶ $mse = ($df > 0) ? $fit->{rss} / $df : undef;
Branch: 1 branch
BranchTrueFalseTotal
$df > 0 ? : 1 0 1
4465 ▶ } elsif (exists($fit->{deviance}) && exists($fit->{'df_residual'})) { # glm
Condition33%1/3
exists $fit->{"deviance"} and exists $fit->{"df_residual"}
!ll&&!rl&&r
001
MC/DC0%0/2
exists $fit->{"deviance"} and exists $fit->{"df_residual"}
exists $fit->{"deviance"} exists $fit->{"df_residual"}
Truth table33%1/3
A and B
A= exists $fit->{"deviance"}B= exists $fit->{"df_residual"}
ABresult
0X0
100
111
4466 1 $df = $fit->{'df_residual'};
4467 1 ▶ $mse = ($df > 0) ? $fit->{deviance} / $df : undef;
Branch: 1 branch
BranchTrueFalseTotal
$df > 0 ? : 1 0 1
4468 } else {
4469 0 die 'TukeyHSD: could not find residual MSE/df in the fit (expected aov/lm/glm output)';
4470 }
4471 25 ▶ die 'TukeyHSD: residual degrees of freedom must be >= 2 (got '
Branch: 2 branches
BranchTrueFalseTotal
unless defined $df and $df >= 2 0 25 25
defined $df ? : 0 0 0
Condition33%1/3
defined $df and $df >= 2
!ll&&!rl&&r
0025
MC/DC0%0/2
defined $df and $df >= 2
defined $df $df >= 2
Truth table33%1/3
A and B
A= defined $dfB= $df >= 2
ABresult
0X0
100
111
4472 . (defined($df) ? $df : 'undef') . ')'
4473 unless defined($df) && $df >= 2;
4474 25 ▶ die 'TukeyHSD: could not determine a positive residual mean square'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mse and $mse > 0 0 25 25
Condition33%1/3
defined $mse and $mse > 0
!ll&&!rl&&r
0025
MC/DC0%0/2
defined $mse and $mse > 0
defined $mse $mse > 0
Truth table33%1/3
A and B
A= defined $mseB= $mse > 0
ABresult
0X0
100
111
4475 unless defined($mse) && $mse > 0;
4476  
4477 # WIDE one-way layout
4478 # data = { level => [observations], ... } with no response/formula: each
4479 # key is a group and its arrayref holds that group's values -- the same
4480 # shape aov() auto-stacks when the formula is omitted. Simpler than R's
4481 # long format: no stacked response column, no separate factor column.
4482 25 ▶ if ( !defined($opt{response}) && !defined($opt{formula})
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $opt{"response"} || defined $opt{"formula"} and ref $data eq "HASH" and keys %$data >= 2 and not grep({ref $_ ne "ARRAY";} values %$data) and not grep({not grep({defined $_ and &looks_like_number($_);} @$_);} values %$data)) 2 23 25
Condition80%12/15
not defined $opt{"response"} || defined $opt{"formula"} and ref $data eq "HASH" and keys %$data >= 2 and not grep({ref $_ ne "ARRAY";} values %$data) and not grep({not grep({defined $_ and &looks_like_number($_);} @$_);} values %$data)
!ll&&!rl&&r
2212
not defined $opt{"response"} || defined $opt{"formula"} and ref $data eq "HASH" and keys %$data >= 2 and not grep({ref $_ ne "ARRAY";} values %$data)
!ll&&!rl&&r
2203
not defined $opt{"response"} || defined $opt{"formula"} and ref $data eq "HASH" and keys %$data >= 2
!ll&&!rl&&r
2203
not defined $opt{"response"} || defined $opt{"formula"} and ref $data eq "HASH"
!ll&&!rl&&r
2203
defined $opt{'response'} || defined $opt{'formula'}
l!l&&r!l&&!r
1663
MC/DC50%3/6
not defined $opt{"response"} || defined $opt{"formula"} and ref $data eq "HASH" and keys %$data >= 2 and not grep({ref $_ ne "ARRAY";} values %$data) and not grep({not grep({defined $_ and &looks_like_number($_);} @$_);} values %$data)
defined $opt{'response'} defined $opt{'formula'} ref $data eq "HASH" keys %$data >= 2 not grep({ref $_ ne "ARRAY";} values %$data) not grep({not grep({defined $_ and &looks_like_number($_);} @$_);} values %$data)
Truth table57%4/7
not(A || B) and C and D and not(E) and not(F)
A= defined $opt{'response'}B= defined $opt{'formula'}C= ref $data eq "HASH"D= keys %$data >= 2E= not grep({ref $_ ne "ARRAY";} values %$data)F= not grep({not grep({defined $_ and &looks_like_number($_);} @$_);} values %$data)
ABCDEFresult
1XXXXX0
01XXXX0
000XXX0
0010XX0
00110X0
0011100
0011111
4483 && ref($data) eq 'HASH' && keys(%$data) >= 2
4484 8 && (!grep { ref($_) ne 'ARRAY' } values %$data)
4485 8 ▶ && (!grep { !grep { defined && looks_like_number($_) } @$_ } values %$data)) {
Condition66%2/3
defined $_ && &looks_like_number($_)
!ll&&!rl&&r
03090
MC/DC50%1/2
defined $_ && &looks_like_number($_)
defined $_ &looks_like_number($_)
Truth table66%2/3
A && B
A= defined $_B= &looks_like_number($_)
ABresult
0X0
100
111
4486 2 ▶ my $label = (defined $opt{which} && !ref $opt{which}) ? $opt{which} : 'group';
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'which'} && !ref($opt{'which'}) ? : 1 1 2
Condition66%2/3
defined $opt{"which"} and not ref $opt{"which"}
!ll&&!rl&&r
101
MC/DC50%1/2
defined $opt{"which"} and not ref $opt{"which"}
defined $opt{"which"} not ref $opt{"which"}
Truth table66%2/3
A and not(B)
A= defined $opt{"which"}B= not ref $opt{"which"}
ABresult
0X0
100
111
4487 2 my (%sum, %cnt);
4488 2 for my $lev (keys %$data) {
4489 6 for my $yv (@{ $data->{$lev} }) {
4490 60 ▶ next unless defined($yv) && looks_like_number($yv);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $yv and &looks_like_number($yv) 0 60 60
Condition33%1/3
defined $yv and &looks_like_number($yv)
!ll&&!rl&&r
0060
MC/DC0%0/2
defined $yv and &looks_like_number($yv)
defined $yv &looks_like_number($yv)
Truth table33%1/3
A and B
A= defined $yvB= &looks_like_number($yv)
ABresult
0X0
100
111
4491 60 $sum{$lev} += $yv;
4492 60 $cnt{$lev}++;
4493 }
4494 }
4495 2 my @levels = grep { $cnt{$_} } sort keys %$data; # R orders levels alphabetically
4496 2 ▶ die 'TukeyHSD: need at least 2 non-empty groups' unless @levels >= 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @levels >= 2 0 2 2
4497 2 my @means = map { $sum{$_} / $cnt{$_} } @levels;
4498 2 my @n = map { $cnt{$_} } @levels;
4499 return {
4500 2 $label => _tukey_compare(\@levels, \@means, \@n, $mse, $df, $conf, $ordered),
4501 'conf_level' => $conf,
4502 ordered => $ordered,
4503 };
4504 }
4505  
4506 # --- LONG layout (R-style): a response column + one or more factor columns
4507 23 my $resp = $opt{response};
4508 23 ▶ if (!defined($resp) && defined $opt{formula}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $resp and defined $opt{"formula"}) 6 17 23
Condition100%3/3
not defined $resp and defined $opt{"formula"}
!ll&&!rl&&r
1616
MC/DC100%2/2
not defined $resp and defined $opt{"formula"}
not defined $resp defined $opt{"formula"}
Truth table100%3/3
not(A) and B
A= not defined $respB= defined $opt{"formula"}
ABresult
0X0
100
111
4509 6 ($resp) = $opt{formula} =~ /\A\s*([^~]+?)\s*~/;
4510 }
4511 23 ▶ _usage_error('TukeyHSD', "need the response variable; pass response => 'name' or formula => 'y ~ ...'")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $resp and length $resp 1 22 23
Condition66%2/3
defined $resp and length $resp
!ll&&!rl&&r
1022
MC/DC50%1/2
defined $resp and length $resp
defined $resp length $resp
Truth table66%2/3
A and B
A= defined $respB= length $resp
ABresult
0X0
100
111
4512 unless defined($resp) && length $resp;
4513  
4514 # factors present in the model (idx 0 of each xlevels entry = reference)
4515 22 my $xl = $fit->{xlevels};
4516 22 ▶ die 'TukeyHSD: no factors in the fitted model (nothing to compare)'
Branch: 1 branch
BranchTrueFalseTotal
unless ref $xl eq "HASH" and keys %$xl 0 22 22
Condition33%1/3
ref $xl eq "HASH" and keys %$xl
!ll&&!rl&&r
0022
MC/DC0%0/2
ref $xl eq "HASH" and keys %$xl
ref $xl eq "HASH" keys %$xl
Truth table33%1/3
A and B
A= ref $xl eq "HASH"B= keys %$xl
ABresult
0X0
100
111
4517 unless ref($xl) eq 'HASH' && keys %$xl;
4518  
4519 my @which = defined($opt{which})
4520 22 ▶ ? (ref($opt{which}) eq 'ARRAY' ? @{ $opt{which} } : ($opt{which}))
Branch: 2 branches
BranchTrueFalseTotal
defined $opt{'which'} ? : 2 20 22
ref $opt{'which'} eq 'ARRAY' ? : 1 1 2
4521 : (sort keys %$xl);
4522  
4523 22 my @factors;
4524 22 for my $f (@which) {
4525 35 ▶ if (exists $xl->{$f}) { push @factors, $f }
Branch: 1 branch
BranchTrueFalseTotal
if (exists $xl->{$f}) { } 34 1 35
4526 1 else { warn "TukeyHSD: '$f' is not a factor in the model and will be dropped\n" }
4527 }
4528 22 ▶ _usage_error('TukeyHSD', "'which' specified no factors") unless @factors;
Branch: 1 branch
BranchTrueFalseTotal
unless @factors 0 22 22
4529  
4530 22 my $y = _tukey_col($data, $resp);
4531  
4532 22 my %out;
4533 22 for my $f (@factors) {
4534 34 my $g = _tukey_col($data, $f);
4535 34 ▶ die "TukeyHSD: response '$resp' and factor '$f' differ in length"
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @$y == scalar @$g 0 34 34
4536 unless scalar(@$y) == scalar(@$g);
4537  
4538 34 my (%sum, %cnt);
4539 34 for my $i (0 .. $#$g) {
4540 1589 my $gv = $g->[$i];
4541 1589 my $yv = $y->[$i];
4542 1589 ▶ next unless defined($gv) && defined($yv) && looks_like_number($yv);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $gv and defined $yv and &looks_like_number($yv) 0 1589 1589
Condition33%2/6
defined $gv and defined $yv and &looks_like_number($yv)
!ll&&!rl&&r
001589
defined $gv and defined $yv
!ll&&!rl&&r
001589
MC/DC0%0/3
defined $gv and defined $yv and &looks_like_number($yv)
defined $gv defined $yv &looks_like_number($yv)
Truth table25%1/4
A and B and C
A= defined $gvB= defined $yvC= &looks_like_number($yv)
ABCresult
0XX0
10X0
1100
1111
4543 1589 $sum{$gv} += $yv;
4544 1589 $cnt{$gv}++;
4545 }
4546  
4547 # canonical level order from xlevels, then any extra observed levels
4548 34 my @levels = @{ $xl->{$f} };
4549 34 my %seen = map { $_ => 1 } @levels;
4550 34 push @levels, sort grep { !$seen{$_} } keys %cnt;
4551 34 @levels = grep { $cnt{$_} } @levels; # only levels that carry data
4552  
4553 34 ▶ die "TukeyHSD: factor '$f' needs at least 2 non-empty levels"
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @levels >= 2 0 34 34
4554 unless scalar(@levels) >= 2;
4555  
4556 34 my @means = map { $sum{$_} / $cnt{$_} } @levels;
4557 34 my @n = map { $cnt{$_} } @levels;
4558  
4559 34 $out{$f} = _tukey_compare(\@levels, \@means, \@n, $mse, $df, $conf, $ordered);
4560 }
4561  
4562 22 $out{'conf_level'} = $conf; # attributes, R-style
4563 22 $out{ordered} = $ordered;
4564 22 return \%out;
4565 }
4566  
4567 # _tukey_compare(\@levels, \@means, \@n, $mse, $df, $conf, $ordered)
4568 # Shared HSD math for one factor: builds the pairwise-comparison rows in R's
4569 # lower-triangle, column-major order. Used by both the wide and long paths.
4570 36 ▶sub _tukey_compare {
Subroutine _tukey_compare: called CC=6 SCAR=18.0
4571 36 my ($levels, $means, $n, $mse, $df, $conf, $ordered) = @_;
4572 36 my @levels = @$levels;
4573 36 my @means = @$means;
4574 36 my @n = @$n;
4575 36 ▶ if ($ordered) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ordered) 14 22 36
4576 14 my @ord = sort { $means[$a] <=> $means[$b] } 0 .. $#means;
4577 14 @levels = @levels[@ord];
4578 14 @means = @means[@ord];
4579 14 @n = @n[@ord];
4580 }
4581 36 my $k = scalar @means;
4582 36 my $crit = Stats::LikeR::qtukey($conf, $k, $df); # nranges = 1
4583 36 my @rows;
4584 36 for my $j (0 .. $k - 1) { # column-major lower triangle
4585 99 for my $i ($j + 1 .. $k - 1) {
4586 96 my $diff = $means[$i] - $means[$j];
4587 96 my $se = sqrt( ($mse / 2) * (1 / $n[$i] + 1 / $n[$j]) );
4588 96 my $width = $crit * $se;
4589 96 ▶ my $est = ($se > 0)
Branch: 2 branches
BranchTrueFalseTotal
$se > 0 ? : 96 0 96
$diff >= 0 ? : 0 0 0
4590 ? $diff / $se
4591 : ($diff >= 0 ? 9**9**9 : -(9**9**9));
4592 96 my $padj = Stats::LikeR::ptukey(abs($est), $k, $df, 'lower_tail' => 0);
4593 96 push @rows, {
4594 comparison => "$levels[$i]-$levels[$j]",
4595 diff => $diff,
4596 lwr => $diff - $width,
4597 upr => $diff + $width,
4598 'p adj' => $padj,
4599 };
4600 }
4601 }
4602 36 return \@rows;
4603 }
4604  
4605 # melt / pivot_table / fillna / ffill / bfill
4606 #
4607 # Each checks its arguments here and hands the frame to an XSUB in LikeR.xs
4608 # (_melt_xs, _pivot_split, _impute_xs), which up to 0.3424 were perl loops;
4609 # pivot_table still reduces each bucket here, through the reducers agg() uses.
4610 #
4611 # NA is undef throughout, exactly as dropna() treats it (a missing hash key
4612 # counts as NA). Every function returns a NEW top-level frame and never
4613 # mutates its input. Shape is classified by _df_shape (the agg()/view()
4614 # detector); 'output_type' defaults to the input family, like agg().
4615  
4616 # _frame_cols($df, $shape, \@need, \@rows) -> (\%col, $R, \@rows)
4617 #
4618 # Extract the named columns once, aligned to row positions 0 .. R-1, using
4619 # the same per-shape access agg() uses. For HoA the column arrays are
4620 # aliased (read-only callers), not rebuilt; every other shape materialises
4621 # a fresh per-column slice. HoH rows are visited in string-sorted key
4622 # order so a positional axis exists. \@rows is those rows in that order,
4623 # undef for HoA, which needs none; passing back the one an earlier call
4624 # returned skips finding them again -- for HoH, a sort of every key -- so a
4625 # caller can fetch one column at a time. Not exported.
4626 20 ▶sub _frame_cols {
Subroutine _frame_cols: called CC=12 SCAR=27.1
4627 20 my ($df, $shape, $need, $rows) = @_;
4628 20 my %col;
4629 20 ▶ if ($shape eq 'HoA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "HoA") 16 4 20
4630 16 my $R = 0;
4631 16 ▶ for my $v (values %$df) { $R = @$v if ref $v eq 'ARRAY' && @$v > $R }
Branch: 1 branch
BranchTrueFalseTotal
if ref $v eq "ARRAY" and @$v > $R 17 20 37
Condition66%2/3
ref $v eq "ARRAY" and @$v > $R
!ll&&!rl&&r
02017
MC/DC50%1/2
ref $v eq "ARRAY" and @$v > $R
ref $v eq "ARRAY" @$v > $R
Truth table66%2/3
A and B
A= ref $v eq "ARRAY"B= @$v > $R
ABresult
0X0
100
111
4632 16 ▶ for my $c (@$need) { $col{$c} = ref $df->{$c} eq 'ARRAY' ? $df->{$c} : [] }
Branch: 1 branch
BranchTrueFalseTotal
ref $df->{$c} eq 'ARRAY' ? : 15 0 15
4633 16 return (\%col, $R, undef);
4634 }
4635 0 $rows ||= $shape eq 'HoH' ? [ map { $df->{$_} } sort keys %$df ]
4636 4 ▶ : [ grep { defined } @$df ];
Branch: 1 branch
BranchTrueFalseTotal
$shape eq 'HoH' ? : 0 4 4
Condition33%1/3
$rows ||= $shape eq "HoH" ? [map({$df->{$_};} sort(keys %$df))] : [grep({defined $_;} @$df)]
l!l&&r!l&&!r
040
MC/DC0%0/2
$rows ||= $shape eq "HoH" ? [map({$df->{$_};} sort(keys %$df))] : [grep({defined $_;} @$df)]
$rows $shape eq "HoH" ? [map({$df->{$_};} sort(keys %$df))] : [grep({defined $_;} @$df)]
Truth table33%1/3
A ||= B
A= $rowsB= $shape eq "HoH" ? [map({$df->{$_};} sort(keys %$df))] : [grep({defined $_;} @$df)]
ABresult
1X1
011
000
4637 4 ▶ if ($shape eq 'AoA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq 'AoA') { } 0 4 4
4638 0 for my $c (@$need) { $col{$c} = [ map { $_->[$c] } @$rows ] }
4639 } else { # AoH, HoH
4640 4 for my $c (@$need) { $col{$c} = [ map { $_->{$c} } @$rows ] }
4641 }
4642 4 return (\%col, scalar @$rows, $rows);
4643 }
4644  
4645 # melt($df, id_vars => $col|\@cols, value_vars => $col|\@cols,
4646 # var_name => 'variable', value_name => 'value', 'output_type' => aoa|aoh|hoa|hoh)
4647 #
4648 # Wide -> long, like pandas DataFrame.melt. Each cell of the value_vars
4649 # columns becomes its own output row: the id_vars are copied across, the
4650 # var_name column holds the source column identifier and the value_name
4651 # column holds the cell. Column identifiers are names for AoH/HoA/HoH and
4652 # 0-based integer positions for AoA.
4653 #
4654 # id_vars scalar or arrayref; default none.
4655 # value_vars scalar or arrayref; default every column not in id_vars
4656 # (column universe and order come from colnames()).
4657 # var_name name of the variable column; default 'variable'.
4658 # value_name name of the value column; default 'value'.
4659 # 'output_type' aoa|aoh|hoa|hoh; default the input family. For aoa output
4660 # the columns are positional (id_vars.., variable, value) so
4661 # var_name/value_name are not used. For hoh output the row
4662 # labels are reset to 0 .. N-1 (like pandas' RangeIndex).
4663 #
4664 # Row order is column-major, matching pandas: all rows for value_vars[0],
4665 # then all rows for value_vars[1], and so on, preserving input row order
4666 # within each block. The original frame is never modified.
4667 25 ▶sub melt {
Subroutine melt: called CC=19 SCAR=29.4
Pod documented
4668 25 my $df = shift;
4669 25 ▶ _usage_error('melt', 'undefined data in first position') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 2 23 25
4670 23 my $shape = _df_shape($df, 'melt');
4671 21 ▶ _usage_error('melt', 'arguments after the data frame must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 2 19 21
4672 if @_ % 2;
4673 19 my %arg = @_;
4674 19 my %known = ( id_vars => 1, value_vars => 1, var_name => 1,
4675 value_name => 1, 'output_type' => 1 );
4676 19 my @bad = sort grep { !$known{$_} } keys %arg;
4677 19 ▶ _usage_error('melt', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 18 19
4678  
4679 my @id = !defined $arg{id_vars} ? ()
4680 1 : ref $arg{id_vars} eq 'ARRAY' ? @{ $arg{id_vars} }
4681 18 ▶ : ( $arg{id_vars} );
Branch: 2 branches
BranchTrueFalseTotal
!defined($arg{'id_vars'}) ? : 1 17 18
ref $arg{'id_vars'} eq 'ARRAY' ? : 1 16 17
4682 # A name repeated in id_vars is one output column, so it is kept once:
4683 # pushed twice per row, it made that column of a hoa twice as long as the rest.
4684 18 { my %s; @id = grep { !$s{$_}++ } @id }
4685 18 ▶ my $var_name = defined $arg{var_name} ? $arg{var_name} : 'variable';
Branch: 1 branch
BranchTrueFalseTotal
defined $arg{'var_name'} ? : 3 15 18
4686 18 ▶ my $value_name = defined $arg{value_name} ? $arg{value_name} : 'value';
Branch: 1 branch
BranchTrueFalseTotal
defined $arg{'value_name'} ? : 2 16 18
4687 18 ▶ my $otype = defined $arg{'output_type'} ? lc $arg{'output_type'} : lc $shape;
Branch: 1 branch
BranchTrueFalseTotal
defined $arg{'output_type'} ? : 4 14 18
4688 18 my %ok_otype = ( aoa => 1, aoh => 1, hoa => 1, hoh => 1 );
4689 _usage_error('melt', "output_type '$otype' isn't allowed (aoa, aoh, hoa, hoh)")
4690 18 ▶ unless $ok_otype{$otype};
Branch: 1 branch
BranchTrueFalseTotal
unless $ok_otype{$otype} 1 17 18
4691  
4692 17 my @universe = colnames($df);
4693 17 my %uni = map { $_ => 1 } @universe;
4694 17 my %is_id = map { $_ => 1 } @id;
4695 21 ▶ my @val = !defined $arg{value_vars} ? ( grep { !$is_id{$_} } @universe )
Branch: 1 branch
BranchTrueFalseTotal
ref $arg{'value_vars'} eq 'ARRAY' ? : 3 4 7
4696 3 : ref $arg{value_vars} eq 'ARRAY' ? @{ $arg{value_vars} }
4697 17 ▶ : ( $arg{value_vars} );
Branch: 1 branch
BranchTrueFalseTotal
!defined($arg{'value_vars'}) ? : 10 7 17
4698 17 for my $c (@id, @val) {
4699 38 ▶ die "melt: column '$c' not found\n" unless $uni{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $uni{$c} 1 37 38
4700 }
4701 # name hygiene: the emitted variable/value columns must not collide
4702 16 ▶ _usage_error('melt', 'var_name and value_name must differ')
Branch: 1 branch
BranchTrueFalseTotal
if $var_name eq $value_name 1 15 16
4703 if $var_name eq $value_name;
4704 15 ▶ if ($otype ne 'aoa') {
Branch: 1 branch
BranchTrueFalseTotal
if ($otype ne "aoa") 12 3 15
4705 12 for my $c (@id) {
4706 13 ▶ die "melt: var_name '$var_name' collides with an id_vars column\n"
Branch: 1 branch
BranchTrueFalseTotal
if $c eq $var_name 1 12 13
4707 if $c eq $var_name;
4708 12 ▶ die "melt: value_name '$value_name' collides with an id_vars column\n"
Branch: 1 branch
BranchTrueFalseTotal
if $c eq $value_name 0 12 12
4709 if $c eq $value_name;
4710 }
4711 }
4712  
4713 # Column-major, straight into the requested shape, in XS. Up to 0.3424
4714 # this was perl, which copied every id and value column out of the frame
4715 # before it emitted a row, and on a 200,000-row AoH melted over three
4716 # value columns took 0.54 s and 324 MB above the frame; see Changes.
4717 14 my %shape_code = ( AoH => 1, HoH => 2, AoA => 3, HoA => 4 ); # _melt_xs's `shape`
4718 14 my %otype_code = ( aoa => 0, aoh => 1, hoa => 2, hoh => 3 ); # and its `otype`
4719 14 return _melt_xs($df, $shape_code{$shape}, [ @id ], [ @val ], $otype_code{$otype},
4720 $var_name, $value_name);
4721 }
4722  
4723 # pivot_table($df, index => $col|\@cols, columns => $col|\@cols,
4724 # values => $col|\@cols, aggfunc => 'mean', fill_value => undef,
4725 # skipna => 1, sort => 1, sep => '.', 'output_type' => ...)
4726 #
4727 # Long -> wide with aggregation, like pandas DataFrame.pivot_table. Rows are
4728 # the distinct `index` tuples; the distinct `columns` tuples spread into new
4729 # output columns; each cell is `aggfunc` applied to the `values` that fall in
4730 # that (index, columns) bucket. This is the combine half of agg() with the
4731 # group value spread across columns instead of down rows, and it reuses the
4732 # same aggregator vocabulary.
4733 #
4734 # index scalar/arrayref of columns that become output rows; default
4735 # none (a single aggregated row).
4736 # columns scalar/arrayref whose distinct value tuples become output
4737 # columns. REQUIRED. A row whose `columns` tuple has any NA
4738 # is skipped (no column can be named from it).
4739 # values scalar/arrayref of columns to aggregate; default every column
4740 # not used by index/columns.
4741 # aggfunc one aggregator name, an arrayref of names, or a coderef;
4742 # default 'mean'. Named: mean median sum sd var min max count
4743 # n nunique first last mode (the agg() set). A coderef is
4744 # called as $code->(\@cells) with every cell (NA included).
4745 # fill_value substituted for any NA result cell (missing bucket, or an
4746 # aggregate that came back undef); default leaves undef.
4747 # skipna 0|1, default 1; forwarded to the numeric reducers as in agg.
4748 # sort 0|1, default 1; sort output rows and columns by their key
4749 # (numeric if every key looks numeric, else string).
4750 # sep separator for generated column names; default '.'.
4751 # 'output_type' aoa|aoh|hoa|hoh; default input family. For hoh the row
4752 # label is the index tuple joined with '.', uniquified with .N.
4753 #
4754 # Generated column names join, with `sep` and in this order, only the pieces
4755 # that vary: the aggregator name (only when >1 aggregator), the value column
4756 # (only when >1 value), and always the `columns` tuple. With a single value
4757 # and single aggregator the name is exactly the `columns` tuple, matching
4758 # pandas' flat output. A duplicate generated name is an error (raise `sep`).
4759 # The original frame is never modified.
4760 38 ▶sub pivot_table {
Subroutine pivot_table: called CC=46 SCAR=38.5
Pod documented
4761 38 my $df = shift;
4762 38 ▶ _usage_error('pivot_table', 'undefined data in first position') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 2 36 38
4763 36 my $shape = _df_shape($df, 'pivot_table');
4764 34 ▶ _usage_error('pivot_table', 'arguments after the data frame must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 1 33 34
4765 if @_ % 2;
4766 33 my %arg = @_;
4767 33 my %known = ( index => 1, columns => 1, values => 1, aggfunc => 1,
4768 fill_value => 1, skipna => 1, sort => 1, sep => 1,
4769 'output_type' => 1 );
4770 33 my @bad = sort grep { !$known{$_} } keys %arg;
4771 33 ▶ _usage_error('pivot_table', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 32 33
4772 32 ▶ _usage_error('pivot_table', "'columns' is required") unless defined $arg{columns};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $arg{"columns"} 2 30 32
4773  
4774 my @index = !defined $arg{index} ? ()
4775 3 : ref $arg{index} eq 'ARRAY' ? @{ $arg{index} }
4776 30 ▶ : ( $arg{index} );
Branch: 2 branches
BranchTrueFalseTotal
!defined($arg{'index'}) ? : 8 22 30
ref $arg{'index'} eq 'ARRAY' ? : 3 19 22
4777 30 ▶ my @columns = ref $arg{columns} eq 'ARRAY' ? @{ $arg{columns} } : ( $arg{columns} );
Branch: 1 branch
BranchTrueFalseTotal
ref $arg{'columns'} eq 'ARRAY' ? : 4 26 30
4778 30 ▶ _usage_error('pivot_table', "'columns' must name at least one column") unless @columns;
Branch: 1 branch
BranchTrueFalseTotal
unless @columns 0 30 30
4779  
4780 30 ▶ my $sep = defined $arg{sep} ? $arg{sep} : '.';
Branch: 1 branch
BranchTrueFalseTotal
defined $arg{'sep'} ? : 3 27 30
4781 30 ▶ my $skipna = exists $arg{skipna} ? ($arg{skipna} ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $arg{'skipna'} ? : 1 29 30
$arg{'skipna'} ? : 0 1 1
4782 30 ▶ my $dosort = exists $arg{sort} ? ($arg{sort} ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $arg{'sort'} ? : 1 29 30
$arg{'sort'} ? : 0 1 1
4783 30 my $has_fill = exists $arg{fill_value};
4784 30 my $fill = $arg{fill_value};
4785 30 ▶ my $otype = defined $arg{'output_type'} ? lc $arg{'output_type'} : lc $shape;
Branch: 1 branch
BranchTrueFalseTotal
defined $arg{'output_type'} ? : 10 20 30
4786 30 my %ok_otype = ( aoa => 1, aoh => 1, hoa => 1, hoh => 1 );
4787 _usage_error('pivot_table', "output_type '$otype' isn't allowed (aoa, aoh, hoa, hoh)")
4788 30 ▶ unless $ok_otype{$otype};
Branch: 1 branch
BranchTrueFalseTotal
unless $ok_otype{$otype} 1 29 30
4789  
4790 29 ▶ my $af = exists $arg{aggfunc} ? $arg{aggfunc} : 'mean';
Branch: 1 branch
BranchTrueFalseTotal
exists $arg{'aggfunc'} ? : 24 5 29
4791 29 ▶ my @funcs = ref $af eq 'ARRAY' ? @$af : ( $af );
Branch: 1 branch
BranchTrueFalseTotal
ref $af eq 'ARRAY' ? : 3 26 29
4792 29 ▶ _usage_error('pivot_table', 'empty aggfunc list') unless @funcs;
Branch: 1 branch
BranchTrueFalseTotal
unless @funcs 1 28 29
4793 28 my %known_agg = map { $_ => 1 }
4794 qw(mean median sum sd var min max count n nunique first last mode);
4795 28 for my $f (@funcs) {
4796 30 ▶ next if ref $f eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $f eq "CODE" 1 29 30
4797 29 ▶ _usage_error('pivot_table', "unknown aggfunc '$f'") unless $known_agg{$f};
Branch: 1 branch
BranchTrueFalseTotal
unless $known_agg{$f} 1 28 29
4798 }
4799  
4800 27 my @universe = colnames($df);
4801 27 my %uni = map { $_ => 1 } @universe;
4802 27 my %reserved = map { $_ => 1 } @index, @columns;
4803 4 ▶ my @values = !defined $arg{values} ? ( grep { !$reserved{$_} } @universe )
Branch: 1 branch
BranchTrueFalseTotal
ref $arg{'values'} eq 'ARRAY' ? : 1 24 25
4804 1 : ref $arg{values} eq 'ARRAY' ? @{ $arg{values} }
4805 27 ▶ : ( $arg{values} );
Branch: 1 branch
BranchTrueFalseTotal
!defined($arg{'values'}) ? : 2 25 27
4806 27 ▶ die "pivot_table: no value columns to aggregate\n" unless @values;
Branch: 1 branch
BranchTrueFalseTotal
unless @values 0 27 27
4807 27 for my $c (@index, @columns, @values) {
4808 83 ▶ die "pivot_table: column '$c' not found\n" unless $uni{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $uni{$c} 1 82 83
4809 }
4810  
4811 # split, in XS: every row's index tuple, columns tuple and value cells,
4812 # each tuple numbered in first-seen order. Up to 0.3424 this was a perl
4813 # loop that copied every column it needed first, joined two key strings for
4814 # each row, and pushed every value cell into a three-level hash.
4815 26 my $has_code = grep { ref $_ eq 'CODE' } @funcs;
4816 my $how = $has_code ? 0 # cells incl. undef, copied
4817 26 ▶ : ( grep { $_ eq 'mode' || $_ eq 'nunique' } @funcs ) ? 1 # defined cells, copied
Branch: 2 branches
BranchTrueFalseTotal
$has_code ? : 1 25 26
grep({$_ eq 'mode' or $_ eq 'nunique';} @funcs) ? : 0 25 25
Condition33%1/3
$_ eq 'mode' || $_ eq 'nunique'
l!l&&r!l&&!r
0027
MC/DC0%0/2
$_ eq 'mode' || $_ eq 'nunique'
$_ eq 'mode' $_ eq 'nunique'
Truth table33%1/3
A || B
A= $_ eq 'mode'B= $_ eq 'nunique'
ABresult
1X1
011
000
4818 : 2; # defined cells, shared
4819 my ($src, $code) = $shape eq 'AoA' ? ( $df, 3 )
4820 : $shape eq 'AoH' ? ( $df, 1 )
4821 : $shape eq 'HoA' ? ( $df, 4 )
4822 0 ▶ : ( [ @{$df}{ sort keys %$df } ], 1 ); # HoH: its rows, key order
Branch: 3 branches
BranchTrueFalseTotal
$shape eq 'AoA' ? : 0 26 26
$shape eq 'AoH' ? : 26 0 26
$shape eq 'HoA' ? : 0 0 0
4823 26 my ($rrepr, $crepr, $buckets) = @{ _pivot_split($src, $code, [ @index ],
4824 [ @columns ], [ @values ], [ ($how) x @values ]) };
4825 26 my @rorder = 0 .. $#$rrepr;
4826 26 my @corder = 0 .. $#$crepr;
4827 26 ▶ if ($dosort) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dosort) 25 1 26
4828 25 ▶ @rorder = @{ _group_order($rrepr) } if @index;
Branch: 1 branch
BranchTrueFalseTotal
if @index 22 3 25
4829 25 @corder = @{ _group_order($crepr) };
4830 }
4831  
4832 # output column plan: aggfunc-major, then value, then columns tuple
4833 26 my $multi_f = @funcs > 1;
4834 26 my $multi_v = @values > 1;
4835 26 my @colplan; # [ col id, value index, func, outname ]
4836 26 for my $f (@funcs) {
4837 28 ▶ my $fl = ref $f eq 'CODE' ? 'fn' : $f;
Branch: 1 branch
BranchTrueFalseTotal
ref $f eq 'CODE' ? : 1 27 28
4838 28 for my $vi (0 .. $#values) {
4839 29 for my $ck (@corder) {
4840 48 ▶ my $cstr = join $sep, map { defined $_ ? $_ : '' } @{ $crepr->[$ck] };
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 56 0 56
4841 48 my @pieces;
4842 48 ▶ push @pieces, $fl if $multi_f;
Branch: 1 branch
BranchTrueFalseTotal
if $multi_f 6 42 48
4843 48 ▶ push @pieces, $values[$vi] if $multi_v;
Branch: 1 branch
BranchTrueFalseTotal
if $multi_v 4 44 48
4844 48 push @pieces, $cstr;
4845 48 push @colplan, [ $ck, $vi, $f, join($sep, @pieces) ];
4846 }
4847 }
4848 }
4849 26 my @out_names = ( @index, map { $_->[3] } @colplan );
4850 {
4851 26 my (%seen, @dup);
4852 26 ▶ for my $n (@out_names) { push @dup, $n if $seen{$n}++ == 1 }
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$n}++ == 1 1 72 73
4853 26 ▶ die "pivot_table: generated duplicate column name(s): @dup; "
Branch: 1 branch
BranchTrueFalseTotal
if @dup 1 25 26
4854 . "pass a different 'sep' or rename inputs\n" if @dup;
4855 }
4856  
4857 # combine, in XS: each row's cells reduced and laid straight out in the
4858 # requested shape. Up to 0.3424 this was perl, one reducer call per cell.
4859 25 my %otype_code = ( aoa => 0, aoh => 1, hoa => 2, hoh => 3 ); # _pivot_combine's `otype`
4860 return _pivot_combine($rrepr, \@rorder, $buckets, scalar @$crepr,
4861 46 ▶ [ map { [ @{$_}[0 .. 2] ] } @colplan ], $how, $skipna, $has_fill ? 1 : 0, $fill,
Branch: 1 branch
BranchTrueFalseTotal
$has_fill ? : 2 23 25
4862 25 $otype_code{$otype}, \@out_names, scalar @index);
4863 }
4864  
4865 # fillna($df, value => $scalar | { col => val, ... }, cols => \@cols)
4866 #
4867 # Replace NA (undef) cells with a constant, like pandas DataFrame.fillna with
4868 # a scalar or a dict. `value` is REQUIRED and is either a single scalar (fill
4869 # every NA in the frame, or only within `cols` when given) or a hashref mapping
4870 # column => fill value (only those columns are touched; a dict key that names
4871 # no existing column is ignored, matching pandas, and `cols` is then forbidden).
4872 # For a scalar `value`, an explicit `cols` that names a missing column dies,
4873 # like dropna(). Column identifiers are names for AoH/HoA/HoH and 0-based
4874 # integer positions for AoA.
4875 #
4876 # A targeted column's missing hash key counts as NA and is materialised on
4877 # fill (as in dropna's NA view). AoA rows are not extended past their own
4878 # length. A structurally-undef (non-ref) row is passed through unchanged, not
4879 # fabricated into a data row, matching ffill()/bfill(). For propagation instead
4880 # of a constant use ffill()/bfill(). Returns
4881 # a NEW frame (rows/columns rebuilt as needed); the original is never modified.
4882 22 ▶sub fillna {
Subroutine fillna: called CC=13 SCAR=25.7
Pod documented
4883 22 my $df = shift;
4884 22 ▶ _usage_error('fillna', 'undefined data in first position') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 2 20 22
4885 20 my $shape = _df_shape($df, 'fillna');
4886 18 ▶ _usage_error('fillna', 'arguments after the data frame must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 1 17 18
4887 if @_ % 2;
4888 17 my %arg = @_;
4889 17 my %known = ( value => 1, cols => 1 );
4890 17 my @bad = sort grep { !$known{$_} } keys %arg;
4891 17 ▶ _usage_error('fillna', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 16 17
4892 16 ▶ _usage_error('fillna', "a 'value' is required") unless exists $arg{value};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $arg{"value"} 2 14 16
4893  
4894 14 my $value = $arg{value};
4895 14 my $per_col = ref $value eq 'HASH';
4896 _usage_error('fillna', "'cols' cannot be combined with a per-column 'value' hashref")
4897 14 ▶ if $per_col && exists $arg{cols};
Branch: 1 branch
BranchTrueFalseTotal
if $per_col and exists $arg{"cols"} 1 13 14
Condition100%3/3
$per_col and exists $arg{"cols"}
!ll&&!rl&&r
1211
MC/DC100%2/2
$per_col and exists $arg{"cols"}
$per_col exists $arg{"cols"}
Truth table100%3/3
A and B
A= $per_colB= exists $arg{"cols"}
ABresult
0X0
100
111
4898  
4899 13 my @universe = colnames($df);
4900 13 my %uni = map { $_ => 1 } @universe;
4901  
4902 13 my (%fillmap, $scalar_fill, @targets);
4903 13 ▶ if ($per_col) {
Branch: 1 branch
BranchTrueFalseTotal
if ($per_col) { } 1 12 13
4904 1 %fillmap = %$value;
4905 1 @targets = grep { $uni{$_} } keys %fillmap; # ignore unknown dict keys
4906 } else {
4907 12 $scalar_fill = $value;
4908 12 ▶ if (exists $arg{cols}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $arg{'cols'}) { } 3 9 12
4909 _usage_error('fillna', "'cols' must be an arrayref")
4910 3 ▶ unless ref $arg{cols} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $arg{"cols"} eq "ARRAY" 0 3 3
4911 3 for my $c (@{ $arg{cols} }) {
4912 3 ▶ die "fillna: column '$c' not found\n" unless $uni{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $uni{$c} 1 2 3
4913 }
4914 2 @targets = @{ $arg{cols} };
4915 } else {
4916 9 @targets = @universe;
4917 }
4918 }
4919 # the copy and the fill, in XS (_impute_xs), which up to 0.3424 was perl
4920 # that called a closure for every cell of every target column
4921 12 my %shape_code = ( AoH => 1, HoH => 2, AoA => 3, HoA => 4 ); # _impute_xs's `shape`
4922 return _impute_xs($df, $shape_code{$shape}, [ @targets ], 0,
4923 12 ▶ [ map { $per_col ? $fillmap{$_} : $scalar_fill } @targets ],
Branch: 1 branch
BranchTrueFalseTotal
$per_col ? : 1 19 20
4924 (undef) x 6);
4925 }
4926  
4927 # _impute_prop($df, $name, $dir, %opts) -- shared core of ffill/bfill.
4928 #
4929 # Propagate defined values along the row axis within each targeted column.
4930 # Row order is positional for AoA/AoH/HoA and string-sorted key order for HoH
4931 # (the only deterministic order a HoH has). Options: cols => \@cols (default
4932 # every column; an unknown column dies), limit => positive int (max fills per
4933 # gap). Fills within each column's existing length only (ragged HoA columns
4934 # are not extended); AoA rows are not extended past their own length. Returns
4935 # a NEW frame; the original is never modified. Not exported.
4936 29 ▶sub _impute_prop {
Subroutine _impute_prop: called CC=12 SCAR=24.9
4937 29 my $df = shift;
4938 29 my $name = shift;
4939 29 my $dir = shift;
4940 29 ▶ _usage_error($name, 'undefined data in first position') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 3 26 29
4941 26 my $shape = _df_shape($df, $name);
4942 22 ▶ _usage_error($name, 'arguments after the data frame must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 1 21 22
4943 if @_ % 2;
4944 21 my %arg = @_;
4945 21 my %known = ( cols => 1, limit => 1 );
4946 21 my @bad = sort grep { !$known{$_} } keys %arg;
4947 21 ▶ _usage_error($name, "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 2 19 21
4948  
4949 19 my $limit = $arg{limit};
4950 19 ▶ _usage_error($name, "'limit' must be a positive integer")
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit and !&looks_like_number($limit) || $limit < 1 || $limit != int $limit 3 16 19
Condition88%8/9
defined $limit and !&looks_like_number($limit) || $limit < 1 || $limit != int $limit
!ll&&!rl&&r
1063
not &looks_like_number($limit) or $limit < 1 or $limit != int $limit
l!l&&r!l&&!r
216
not &looks_like_number($limit) or $limit < 1
l!l&&r!l&&!r
027
MC/DC75%3/4
defined $limit and !&looks_like_number($limit) || $limit < 1 || $limit != int $limit
defined $limit not &looks_like_number($limit) $limit < 1 $limit != int $limit
Truth table80%4/5
A and not(B) or C or D
A= defined $limitB= not &looks_like_number($limit)C= $limit < 1D= $limit != int $limit
ABCDresult
0XXX0
10000
11XX1
101X1
10011
4951 if defined $limit
4952 && ( !looks_like_number($limit) || $limit < 1 || $limit != int $limit );
4953  
4954 16 my @universe = colnames($df);
4955 16 my %uni = map { $_ => 1 } @universe;
4956 16 my @targets;
4957 16 ▶ if (exists $arg{cols}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $arg{'cols'}) { } 8 8 16
4958 8 ▶ _usage_error($name, "'cols' must be an arrayref") unless ref $arg{cols} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $arg{"cols"} eq "ARRAY" 0 8 8
4959 8 for my $c (@{ $arg{cols} }) {
4960 8 ▶ die "$name: column '$c' not found\n" unless $uni{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $uni{$c} 1 7 8
4961 }
4962 7 @targets = @{ $arg{cols} };
4963 } else {
4964 8 @targets = @universe;
4965 }
4966 # the copy and the fill, in XS (_impute_xs); up to 0.3424 perl, which
4967 # copied each target column out of the rows, filled it and wrote it back
4968 15 my %shape_code = ( AoH => 1, HoH => 2, AoA => 3, HoA => 4 ); # _impute_xs's `shape`
4969 15 return _impute_xs($df, $shape_code{$shape}, [ @targets ], $dir, undef, $limit,
4970 (undef) x 5);
4971 }
4972  
4973 # ffill($df, cols => \@cols, limit => $n) -- forward-fill NA (last valid obs).
4974 # bfill($df, cols => \@cols, limit => $n) -- back-fill NA (next valid obs).
4975 # See _impute_prop for the row-axis and shape semantics.
4976 20 ▶sub ffill { _impute_prop( shift, 'ffill', 1, @_ ) }
Subroutine ffill: called CC=1 SCAR=0.0
Pod documented
4977 9 ▶sub bfill { _impute_prop( shift, 'bfill', -1, @_ ) }
Subroutine bfill: called CC=1 SCAR=0.0
Pod documented
4978  
4979 # The interpolate() numeric kernels now live in XS (see ip_fill_column and the
4980 # _interp_column_xs XSUB in LikeR.xs); it is called once per target column below.
4981  
4982 # interpolate($df, method => 'linear', cols => \@cols, x => ...,
4983 # order => $k, limit => $n,
4984 # limit_direction => 'forward'|'backward'|'both',
4985 # limit_area => 'inside'|'outside')
4986 #
4987 # Fill NA (undef) cells along the row axis, like pandas DataFrame.interpolate.
4988 # It is the numeric sibling of ffill/bfill. Row order and the four shapes match
4989 # ffill/bfill (positional for AoA/AoH/HoA, sorted-key order for HoH), and it
4990 # returns a NEW frame; the original is never modified.
4991 #
4992 # method the interpolant. All of pandas' methods are supported:
4993 # linear (default), index, values, time -- straight line; the
4994 # first three use `x`, 'linear' uses equal spacing.
4995 # slinear, nearest, zero -- piecewise, interior only.
4996 # pad/ffill, bfill/backfill -- hold the last/next value.
4997 # quadratic, cubic -- interp1d B-splines.
4998 # cubicspline, pchip, akima, spline -- SciPy-named splines.
4999 # polynomial, spline (need `order`) -- degree-k spline.
5000 # barycentric, krogh -- global polynomial.
5001 # order required for method 'polynomial' / 'spline' (degree 1, 2 or 3).
5002 # x abscissae: an arrayref (one per row) or a column name/index whose
5003 # numeric values are the coordinates (default: equal spacing 0,1,2..).
5004 # Must be strictly increasing. Used by every method except 'linear'.
5005 # limit_direction 'forward' (default), 'backward', or 'both'.
5006 # limit_area 'inside' fills only interior gaps, 'outside' only leading/
5007 # trailing gaps, undef (default) fills both.
5008 # limit max cells filled per undef run.
5009 # cols columns to interpolate; default every column.
5010 #
5011 # The pipeline follows pandas exactly: fill every gap with the method, then
5012 # blank the cells limit/direction/area forbid. Only 'linear' and the hold/
5013 # global methods reach leading/trailing gaps (the interp1d and akima methods
5014 # are interior-only, matching SciPy). Only numeric cells anchor a fill; a
5015 # defined non-numeric cell is preserved (and, for the piecewise-local methods,
5016 # blocks interpolation across it). Interpolated cells are floats. Fills within
5017 # each column's existing length only; a non-ref row is passed through untouched.
5018 5234 ▶sub interpolate {
Subroutine interpolate: called CC=43 SCAR=38.2
Pod documented
5019 5234 my $df = shift;
5020 5234 ▶ _usage_error('interpolate', 'undefined data in first position') unless defined $df;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $df 2 5232 5234
5021 5232 my $shape = _df_shape($df, 'interpolate');
5022 5230 ▶ _usage_error('interpolate', 'arguments after the data frame must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 1 5229 5230
5023 if @_ % 2;
5024 5229 my %arg = @_;
5025 5229 my %known = ( cols => 1, limit => 1, limit_direction => 1,
5026 limit_area => 1, method => 1, order => 1, x => 1 );
5027 5229 my @bad = sort grep { !$known{$_} } keys %arg;
5028 5229 ▶ _usage_error('interpolate', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 5228 5229
5029  
5030 5228 my %known_method = map { $_ => 1 } qw(
5031 linear index values time slinear nearest zero pad ffill bfill backfill
5032 quadratic cubic cubicspline pchip akima barycentric krogh polynomial spline );
5033 5228 ▶ my $method = defined $arg{method} ? lc $arg{method} : 'linear';
Branch: 1 branch
BranchTrueFalseTotal
defined $arg{'method'} ? : 5196 32 5228
5034 5228 ▶ _usage_error('interpolate', "unknown method '$method'") unless $known_method{$method};
Branch: 1 branch
BranchTrueFalseTotal
unless $known_method{$method} 2 5226 5228
5035  
5036 5226 my $order = $arg{order};
5037 5226 ▶ if ($method eq 'polynomial' || $method eq 'spline') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "polynomial" or $method eq "spline") 83 5143 5226
Condition100%3/3
$method eq "polynomial" or $method eq "spline"
l!l&&r!l&&!r
7855143
MC/DC100%2/2
$method eq "polynomial" or $method eq "spline"
$method eq "polynomial" $method eq "spline"
Truth table100%3/3
A or B
A= $method eq "polynomial"B= $method eq "spline"
ABresult
1X1
011
000
5038 83 ▶ _usage_error('interpolate', "method '$method' requires an integer 'order' >= 1")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $order and &looks_like_number($order) and $order >= 1 and $order == int $order 2 81 83
Condition66%6/9
defined $order and &looks_like_number($order) and $order >= 1 and $order == int $order
!ll&&!rl&&r
2081
defined $order and &looks_like_number($order) and $order >= 1
!ll&&!rl&&r
2081
defined $order and &looks_like_number($order)
!ll&&!rl&&r
2081
MC/DC25%1/4
defined $order and &looks_like_number($order) and $order >= 1 and $order == int $order
defined $order &looks_like_number($order) $order >= 1 $order == int $order
Truth table40%2/5
A and B and C and D
A= defined $orderB= &looks_like_number($order)C= $order >= 1D= $order == int $order
ABCDresult
0XXX0
10XX0
110X0
11100
11111
5039 unless defined $order && looks_like_number($order)
5040 && $order >= 1 && $order == int $order;
5041 }
5042  
5043 5224 my $limit = $arg{limit};
5044 5224 ▶ _usage_error('interpolate', "'limit' must be a positive integer")
Branch: 1 branch
BranchTrueFalseTotal
if defined $limit and !&looks_like_number($limit) || $limit < 1 || $limit != int $limit 2 5222 5224
Condition88%8/9
defined $limit and !&looks_like_number($limit) || $limit < 1 || $limit != int $limit
!ll&&!rl&&r
218930332
not &looks_like_number($limit) or $limit < 1 or $limit != int $limit
l!l&&r!l&&!r
113033
not &looks_like_number($limit) or $limit < 1
l!l&&r!l&&!r
013034
MC/DC75%3/4
defined $limit and !&looks_like_number($limit) || $limit < 1 || $limit != int $limit
defined $limit not &looks_like_number($limit) $limit < 1 $limit != int $limit
Truth table80%4/5
A and not(B) or C or D
A= defined $limitB= not &looks_like_number($limit)C= $limit < 1D= $limit != int $limit
ABCDresult
0XXX0
10000
11XX1
101X1
10011
5045 if defined $limit
5046 && ( !looks_like_number($limit) || $limit < 1 || $limit != int $limit );
5047  
5048 5222 ▶ my $dir = defined $arg{limit_direction} ? lc $arg{limit_direction} : 'forward';
Branch: 1 branch
BranchTrueFalseTotal
defined $arg{'limit_direction'} ? : 4217 1005 5222
5049 5222 my %okdir = ( forward => 1, backward => 1, both => 1 );
5050 _usage_error('interpolate', "'limit_direction' must be 'forward', 'backward', or 'both'")
5051 5222 ▶ unless $okdir{$dir};
Branch: 1 branch
BranchTrueFalseTotal
unless $okdir{$dir} 1 5221 5222
5052 # the directional-hold methods pin their own direction
5053 5221 ▶ $dir = 'forward' if $method eq 'pad' || $method eq 'ffill';
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "pad" or $method eq "ffill" 325 4896 5221
Condition100%3/3
$method eq "pad" or $method eq "ffill"
l!l&&r!l&&!r
32414896
MC/DC100%2/2
$method eq "pad" or $method eq "ffill"
$method eq "pad" $method eq "ffill"
Truth table100%3/3
A or B
A= $method eq "pad"B= $method eq "ffill"
ABresult
1X1
011
000
5054 5221 ▶ $dir = 'backward' if $method eq 'bfill' || $method eq 'backfill';
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "bfill" or $method eq "backfill" 325 4896 5221
Condition66%2/3
$method eq "bfill" or $method eq "backfill"
l!l&&r!l&&!r
32504896
MC/DC50%1/2
$method eq "bfill" or $method eq "backfill"
$method eq "bfill" $method eq "backfill"
Truth table66%2/3
A or B
A= $method eq "bfill"B= $method eq "backfill"
ABresult
1X1
011
000
5055  
5056 5221 my $area;
5057 5221 ▶ if (defined $arg{limit_area}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $arg{"limit_area"}) 3317 1904 5221
5058 3317 $area = lc $arg{limit_area};
5059 3317 ▶ _usage_error('interpolate', "'limit_area' must be 'inside' or 'outside'")
Branch: 1 branch
BranchTrueFalseTotal
unless $area eq "inside" or $area eq "outside" 1 3316 3317
Condition100%3/3
$area eq "inside" or $area eq "outside"
l!l&&r!l&&!r
180215141
MC/DC100%2/2
$area eq "inside" or $area eq "outside"
$area eq "inside" $area eq "outside"
Truth table100%3/3
A or B
A= $area eq "inside"B= $area eq "outside"
ABresult
1X1
011
000
5060 unless $area eq 'inside' || $area eq 'outside';
5061 }
5062  
5063 5220 my @universe = colnames($df);
5064 5220 my %uni = map { $_ => 1 } @universe;
5065 5220 my @targets;
5066 5220 ▶ if (exists $arg{cols}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $arg{'cols'}) { } 7 5213 5220
5067 7 ▶ _usage_error('interpolate', "'cols' must be an arrayref") unless ref $arg{cols} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $arg{"cols"} eq "ARRAY" 1 6 7
5068 6 for my $c (@{ $arg{cols} }) {
5069 7 ▶ die "interpolate: column '$c' not found\n" unless $uni{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $uni{$c} 1 6 7
5070 }
5071 5 @targets = @{ $arg{cols} };
5072 } else {
5073 5213 @targets = @universe;
5074 }
5075  
5076 # x coordinate: arrayref, or a column key whose values are the coordinates
5077 5218 my ($x_is_col, $x_col);
5078 5218 ▶ if (defined $arg{x} && ref $arg{x} ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $arg{"x"} and ref $arg{"x"} ne "ARRAY") 2 5216 5218
Condition100%3/3
defined $arg{"x"} and ref $arg{"x"} ne "ARRAY"
!ll&&!rl&&r
521062
MC/DC100%2/2
defined $arg{"x"} and ref $arg{"x"} ne "ARRAY"
defined $arg{"x"} ref $arg{"x"} ne "ARRAY"
Truth table100%3/3
A and B
A= defined $arg{"x"}B= ref $arg{"x"} ne "ARRAY"
ABresult
0X0
100
111
5079 2 $x_is_col = 1;
5080 2 $x_col = $arg{x};
5081 2 ▶ die "interpolate: x column '$x_col' not found\n" unless $uni{$x_col};
Branch: 1 branch
BranchTrueFalseTotal
unless $uni{$x_col} 0 2 2
5082 }
5083 # validated coordinates of length $len; $xcolseq is the x column pulled in
5084 # the same row order (only consulted when x is a column key).
5085 5218 ▶ my $mkcoords = sub {
Subroutine __ANON__: called CC=12 SCAR=25.1
5086 5218 my ($len, $xcolseq) = @_;
5087 5218 my @x;
5088 5218 ▶ if ($x_is_col) {
Branch: 2 branches
BranchTrueFalseTotal
if ($x_is_col) { } 2 5216 5218
elsif (ref $arg{'x'} eq 'ARRAY') { } 6 5210 5216
5089 0 ▶ die "interpolate: x column '$x_col' length (${\ scalar @$xcolseq}) != column length ($len)\n"
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @$xcolseq == $len 0 2 2
5090 unless scalar @$xcolseq == $len;
5091 2 @x = @$xcolseq;
5092 }
5093 elsif (ref $arg{x} eq 'ARRAY') {
5094 1 die "interpolate: 'x' arrayref length (${\ scalar @{$arg{x}}}) != column length ($len)\n"
5095 6 ▶ unless scalar @{ $arg{x} } == $len;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @{$arg{"x"};} == $len 1 5 6
5096 5 @x = @{ $arg{x} };
5097 5210 } else { @x = (0 .. $len - 1); }
5098 5217 for my $v (@x) {
5099 882486 ▶ die "interpolate: 'x' coordinates must all be defined and numeric\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and &looks_like_number($v) 0 882486 882486
Condition33%1/3
defined $v and &looks_like_number($v)
!ll&&!rl&&r
00882486
MC/DC0%0/2
defined $v and &looks_like_number($v)
defined $v &looks_like_number($v)
Truth table33%1/3
A and B
A= defined $vB= &looks_like_number($v)
ABresult
0X0
100
111
5100 unless defined $v && looks_like_number($v);
5101 # pandas raises NotImplementedError for a NaN in the index ("Interpolation
5102 # with NaNs in the index has not been implemented"); a NaN here would
5103 # slip past the increasing test below, since every comparison with it is false
5104 882486 ▶ die "interpolate: 'x' coordinates must not be NaN\n" if $v != $v;
Branch: 1 branch
BranchTrueFalseTotal
if $v != $v 4 882482 882486
5105 }
5106 5213 ▶ if (defined $arg{x}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $arg{"x"}) 3 5210 5213
5107 3 for my $i (1 .. $#x) {
5108 7 ▶ die "interpolate: 'x' coordinates must be strictly increasing\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $x[$i] > $x[$i - 1] 1 6 7
5109 unless $x[$i] > $x[$i - 1];
5110 }
5111 }
5112 5212 return \@x;
5113 5218 };
5114 # The numeric fill (every method, the dense solve, the preserve mask) is
5115 # _interp_column_xs's. A HoA's columns go to it whole; the rows of the
5116 # other shapes are copied and their target columns filled by _impute_xs,
5117 # which up to 0.3424 was perl that copied each column out of the rows and
5118 # wrote it back.
5119 5218 ▶ if ($shape eq 'HoA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($shape eq "HoA") 5208 10 5218
5120 5208 my %out;
5121 5208 for my $c (keys %$df) {
5122 5210 ▶ $out{$c} = ref $df->{$c} eq 'ARRAY' ? [ @{ $df->{$c} } ] : [];
Branch: 1 branch
BranchTrueFalseTotal
ref $df->{$c} eq 'ARRAY' ? : 5210 0 5210
5123 }
5124 5208 for my $c (@targets) {
5125 5208 my $arr = $out{$c};
5126 my $xcolseq = $x_is_col
5127 5208 ▶ ? [ @{ ref $df->{$x_col} eq 'ARRAY' ? $df->{$x_col} : [] } ]
Branch: 2 branches
BranchTrueFalseTotal
$x_is_col ? : 2 5206 5208
ref $df->{$x_col} eq 'ARRAY' ? : 2 0 2
5128 : undef;
5129 5208 my $coords = $mkcoords->(scalar @$arr, $xcolseq);
5130 5202 _interp_column_xs($arr, $coords, $method, $order, $dir, $limit, $area);
5131 }
5132 5198 return \%out;
5133 }
5134 # AoH, HoH, AoA: one coordinate per row, in the order the rows are filled
5135 10 ▶ my $rows = $shape eq 'HoH' ? [ map { $df->{$_} } sort keys %$df ] : $df;
Branch: 1 branch
BranchTrueFalseTotal
$shape eq 'HoH' ? : 1 9 10
5136 my $xcolseq = !$x_is_col ? undef
5137 0 ▶ : $shape eq 'AoA' ? [ map { ref $_ eq 'ARRAY' ? $_->[$x_col] : undef } @$rows ]
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 0 0 0
5138 0 ▶ : [ map { ref $_ eq 'HASH' ? $_->{$x_col} : undef } @$rows ];
Branch: 3 branches
BranchTrueFalseTotal
!$x_is_col ? : 10 0 10
$shape eq 'AoA' ? : 0 0 0
ref $_ eq 'HASH' ? : 0 0 0
5139 10 my $coords = $mkcoords->(scalar @$rows, $xcolseq);
5140 10 my %shape_code = ( AoH => 1, HoH => 2, AoA => 3 ); # _impute_xs's `shape`
5141 10 return _impute_xs($df, $shape_code{$shape}, [ @targets ], 2, undef, $limit,
5142 $coords, $method, $order, $dir, $area);
5143 }
5144  
5145 # _tukey_col($data, $col) -- pull one column's cells, in row order, from any
5146 # of the three data-frame shapes (AoH arrayref, HoA/HoH hashref).
5147 56 ▶sub _tukey_col {
Subroutine _tukey_col: called CC=6 SCAR=18.2
5148 56 my ($data, $col) = @_;
5149 56 ▶ die 'TukeyHSD: data must be a reference (AoH / HoA / HoH)' unless ref $data;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data 0 56 56
5150 56 my $r = ref $data;
5151 56 ▶ if ($r eq 'ARRAY') { # AoH
Branch: 2 branches
BranchTrueFalseTotal
if ($r eq 'ARRAY') { } 12 44 56
elsif ($r eq 'HASH') { } 44 0 44
5152 12 return [ map { $_->{$col} } @$data ];
5153 } elsif ($r eq 'HASH') {
5154 44 my ($first) = values %$data;
5155 44 ▶ if (ref($first) eq 'ARRAY') { # HoA
Branch: 1 branch
BranchTrueFalseTotal
if (ref $first eq 'ARRAY') { } 32 12 44
5156 die "TukeyHSD: column '$col' not found in data"
5157 32 ▶ unless exists $data->{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $data->{$col} 0 32 32
5158 32 return [ @{ $data->{$col} } ];
5159 } else { # HoH (row-name keyed)
5160 12 return [ map { $data->{$_}{$col} } sort keys %$data ];
5161 }
5162 }
5163 0 die 'TukeyHSD: unsupported data shape';
5164 }
5165  
5166 # table_one: a stratified descriptive "Table 1". A variable whose type is not
5167 # given is continuous when every defined cell looks like a number and one is
5168 # defined, and otherwise categorical (_t1_col in LikeR.xs decides).
5169  
5170 # p-value + test label for a continuous variable across >=2 groups.
5171 # @$byg is one arrayref of (numeric, defined) values per group. Returns
5172 # (undef, undef) when the test cannot run, as _t1_cat_p() does: t_test() dies
5173 # on a group of one and on data that are constant, and up to 0.3217 that took
5174 # the whole table down for the sake of one row.
5175 15 ▶sub _t1_cont_p {
Subroutine _t1_cont_p: called CC=9 SCAR=22.0
5176 15 my ($byg, $nonpar) = @_;
5177 15 my @g = grep { @$_ >= 1 } @$byg;
5178 15 ▶ return (undef, undef) if @g < 2;
Branch: 1 branch
BranchTrueFalseTotal
if @g < 2 0 15 15
5179 15 my @r = eval {
5180 15 ▶ if (@g == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@g == 2) 11 4 15
5181 11 ▶ my $r = $nonpar ? wilcox_test($g[0], $g[1]) : t_test($g[0], $g[1]);
Branch: 1 branch
BranchTrueFalseTotal
$nonpar ? : 3 8 11
5182 7 ▶ return ($r->{'p_value'}, $nonpar ? 'wilcoxon' : 't-test');
Branch: 1 branch
BranchTrueFalseTotal
$nonpar ? : 3 4 7
5183 }
5184 # >2 groups: Kruskal-Wallis (nonparametric) or one-way ANOVA
5185 4 my %by; @by{ map { "g$_" } 0 .. $#g } = @g;
5186 4 ▶ return (kruskal_test(\%by)->{'p_value'}, 'kruskal-wallis') if $nonpar;
Branch: 1 branch
BranchTrueFalseTotal
if $nonpar 1 3 4
5187 # oneway_test(var_equal => 1) is the F test aov() computes for one
5188 # factor -- R's oneway.test(var.equal = TRUE) -- from each group's sum
5189 # and sum of squares, where aov() builds and rotates a design: on 1e5
5190 # rows in three groups, 8 ms against aov()'s 54. It refuses a group of
5191 # one observation, which aov() takes, so that case still goes to aov().
5192 return (oneway_test(\@g, var_equal => 1)->{Group}{'Pr(>F)'}, 'anova')
5193 3 ▶ unless grep { @$_ < 2 } @g;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {@$_ < 2;} @g 1 2 3
5194 2 my (@x, @lab);
5195 2 for my $i (0 .. $#g) { push @x, @{ $g[$i] }; push @lab, ("g$i") x scalar @{ $g[$i] } }
5196 2 my $aov = aov({ value => \@x, grp => \@lab }, 'value ~ grp');
5197 2 return ($aov->{grp}{'Pr(>F)'}, 'anova');
5198 };
5199 15 ▶ return $@ ? (undef, undef) : @r;
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 4 11 15
5200 }
5201  
5202 # p-value + test label for a categorical variable: chi-squared on the
5203 # level-by-group contingency table. Returns undef if the test cannot run.
5204 5 ▶sub _t1_cat_p {
Subroutine _t1_cat_p: called CC=5 SCAR=17.8
5205 5 my ($table) = @_;
5206 # A variable with a single level gives a 1 x k table, which chisq_test
5207 # (like R) collapses to a goodness-of-fit test on the group sizes -- a
5208 # different question from the one this column asks. There is no
5209 # association to test, so report none.
5210 5 ▶ return (undef, undef) if @$table < 2 || @{ $table->[0] } < 2;
Branch: 1 branch
BranchTrueFalseTotal
if @$table < 2 or @{$table->[0];} < 2 0 5 5
Condition33%1/3
@$table < 2 or @{$table->[0];} < 2
l!l&&r!l&&!r
005
MC/DC0%0/2
@$table < 2 or @{$table->[0];} < 2
@$table < 2 @{$table->[0];} < 2
Truth table33%1/3
A or B
A= @$table < 2B= @{$table->[0];} < 2
ABresult
1X1
011
000
5211 # small expected counts are worth knowing about at the call site, but
5212 # table_one summarises dozens of variables at once and the warning would
5213 # say nothing about which one
5214 5 my $r = eval {
5215 5 ▶ local $SIG{__WARN__} = sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
5216 5 ▶ warn @_ unless $_[0] =~ /Chi-squared approximation may be incorrect/;
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0] =~ /Chi-squared approximation may be incorrect/ 0 5 5
5217 5 };
5218 5 chisq_test($table);
5219 };
5220 5 ▶ return (undef, undef) if $@ || !$r;
Branch: 1 branch
BranchTrueFalseTotal
if $@ or not $r 0 5 5
Condition33%1/3
$@ or not $r
l!l&&r!l&&!r
005
MC/DC0%0/2
$@ or not $r
$@ not $r
Truth table33%1/3
A or not(B)
A= $@B= not $r
ABresult
1X1
011
000
5221 5 return ($r->{'p_value'}, 'chi-squared');
5222 }
5223  
5224 29 ▶sub table_one {
Subroutine table_one: called CC=53 SCAR=40.0
Pod documented
5225 29 my ($df, %opt) = @_;
5226 29 my %known = map { $_ => 1 } qw(by vars types nonparametric digits pct_digits);
5227 29 my @bad = sort grep { !$known{$_} } keys %opt;
5228 29 ▶ _usage_error('table_one', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 2 27 29
5229  
5230 27 my $by = $opt{by};
5231 27 ▶ my $digits = defined $opt{digits} ? $opt{digits} : 2;
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'digits'} ? : 1 26 27
5232 27 ▶ my $pdig = defined $opt{pct_digits} ? $opt{pct_digits} : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'pct_digits'} ? : 0 27 27
5233 27 ▶ my $nonpar = $opt{nonparametric} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'nonparametric'} ? : 2 25 27
5234 27 ▶ my %types = $opt{types} ? %{ $opt{types} } : ();
Branch: 1 branch
BranchTrueFalseTotal
$opt{'types'} ? : 5 22 27
5235 # anything but 'continuous' took the categorical branch, so a misspelling
5236 # or types => { age => 'numeric' } made a row of every distinct age
5237 27 for my $v (sort keys %types) {
5238 5 my $t = $types{$v};
5239 5 ▶ _usage_error('table_one', "the type of '$v' must be 'continuous' or 'categorical', not '"
Branch: 2 branches
BranchTrueFalseTotal
unless defined $t and $t eq "continuous" || $t eq "categorical" 2 3 5
defined $t ? : 1 1 2
Condition83%5/6
defined $t and $t eq "continuous" || $t eq "categorical"
!ll&&!rl&&r
113
$t eq "continuous" or $t eq "categorical"
l!l&&r!l&&!r
031
MC/DC66%2/3
defined $t and $t eq "continuous" || $t eq "categorical"
defined $t $t eq "continuous" $t eq "categorical"
Truth table75%3/4
A and B or C
A= defined $tB= $t eq "continuous"C= $t eq "categorical"
ABCresult
0XX0
1000
11X1
1011
5240 . (defined $t ? $t : 'undef') . "'")
5241 unless defined $t && ($t eq 'continuous' || $t eq 'categorical');
5242 }
5243  
5244 25 my $shape = _df_shape($df, 'table_one');
5245 22 my @allcols = colnames($df);
5246 22 my %colset = map { $_ => 1 } @allcols;
5247 22 ▶ die "table_one: 'by' column '$by' not found\n" if defined $by && !$colset{$by};
Branch: 1 branch
BranchTrueFalseTotal
if defined $by and not $colset{$by} 1 21 22
Condition100%3/3
defined $by and not $colset{$by}
!ll&&!rl&&r
3181
MC/DC100%2/2
defined $by and not $colset{$by}
defined $by not $colset{$by}
Truth table100%3/3
A and not(B)
A= defined $byB= not $colset{$by}
ABresult
0X0
100
111
5248 3 my @vars = $opt{vars} ? @{ $opt{vars} }
5249 21 ▶ : grep { !defined $by || $_ ne $by } @allcols;
Branch: 1 branch
BranchTrueFalseTotal
$opt{'vars'} ? : 3 18 21
Condition100%3/3
!defined($by) || $_ ne $by
l!l&&r!l&&!r
42416
MC/DC100%2/2
!defined($by) || $_ ne $by
!defined($by) $_ ne $by
Truth table100%3/3
not(A) || B
A= !defined($by)B= $_ ne $by
ABresult
1X1
011
000
5250 21 ▶ for my $v (@vars) { die "table_one: column '$v' not found\n" unless $colset{$v} }
Branch: 1 branch
BranchTrueFalseTotal
unless $colset{$v} 1 30 31
5251  
5252 # Each column is fetched as it is summarised rather than all at once: an
5253 # AoA, AoH or HoH frame's columns are copies, and holding every one of them
5254 # for the whole call was most of the memory this used.
5255 20 ▶ my ($bc, $R, $rows) = _frame_cols($df, $shape, defined $by ? [$by] : []);
Branch: 1 branch
BranchTrueFalseTotal
defined $by ? : 18 2 20
5256  
5257 # $gidx[$r] is row $r's group, an index into @groups. The labels are read
5258 # over 0 .. $R-1, as every column below is, so that a `by` column shorter
5259 # than the frame reads as 'NA' past its end; mapping over the column itself
5260 # left those rows with no group, and the warning that raised was fatal.
5261 20 my (@groups, @gidx, @gsize);
5262 20 ▶ if (defined $by) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $by) { } 18 2 20
5263 18 my $bycol = $bc->{$by};
5264 18 my %size; # label => rows in that group
5265 18 for my $r (0 .. $R - 1) {
5266 128 my $g = $bycol->[$r];
5267 128 ▶ $size{ defined $g ? $g : 'NA' }++;
Branch: 1 branch
BranchTrueFalseTotal
defined $g ? : 127 1 128
5268 }
5269 18 @groups = sort keys %size;
5270 18 @gsize = @size{@groups};
5271 # Each group is a key of every output row, beside these: a group named
5272 # 'test' was overwritten by the label 't-test', and one named 'Overall'
5273 # overwrote the column summarising every row.
5274 18 my %fixed = map { $_ => 1 } qw(variable level type p_value test Overall);
5275 18 my @clash = grep { $fixed{$_} } @groups;
5276 18 ▶ die "table_one: the '$by' column has a group named '"
Branch: 1 branch
BranchTrueFalseTotal
if @clash 6 12 18
5277 . join("', '", @clash) . "', which is also the name of an output column\n"
5278 if @clash;
5279 12 my %gpos; @gpos{@groups} = 0 .. $#groups;
5280 12 ▶ @gidx = map { my $g = $bycol->[$_]; $gpos{ defined $g ? $g : 'NA' } } 0 .. $R - 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $g ? : 91 1 92
5281 } else {
5282 2 @groups = ('Overall');
5283 2 @gsize = ($R);
5284 2 @gidx = (0) x $R;
5285 }
5286  
5287 # Each variable's pass over the rows is _t1_col (LikeR.xs): a continuous
5288 # one's numbers by group, a categorical one's level counts by group. Up to
5289 # 0.3424 that pass was perl, over a copy of the column.
5290 14 ▶ my ($t1_kind, $t1_src) = $shape eq 'HoA' ? ( 4, undef )
Branch: 2 branches
BranchTrueFalseTotal
$shape eq 'HoA' ? : 10 4 14
$shape eq 'AoA' ? : 0 4 4
5291 : $shape eq 'AoA' ? ( 3, $rows )
5292 : ( 1, $rows ); # _t1_col's `kind`
5293 14 my @out;
5294 14 for my $v (@vars) {
5295 24 ▶ my $src = $shape eq 'HoA' ? ( ref $df->{$v} eq 'ARRAY' ? $df->{$v} : undef ) : $t1_src;
Branch: 2 branches
BranchTrueFalseTotal
$shape eq 'HoA' ? : 16 8 24
ref $df->{$v} eq 'ARRAY' ? : 16 0 16
5296 24 my ($type, $per, $allv) = @{ _t1_col($src, $t1_kind, $v, \@gidx, scalar @groups, $R, $types{$v}) };
5297  
5298 24 ▶ if ($type eq 'continuous') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq 'continuous') { } 16 8 24
5299 16 my %row = (variable => $v, level => '', type => 'continuous');
5300 # The numbers keep their row order, and with it mean()'s and sd()'s
5301 # last bit; each is `0 + $cell`, made once.
5302 16 my @byg = @$per;
5303 16 for my $gi (0 .. $#groups) {
5304 35 my $gv = $byg[$gi];
5305 35 ▶ $row{ $groups[$gi] } = @$gv
Branch: 2 branches
BranchTrueFalseTotal
@$gv ? : 35 0 35
@$gv > 1 ? : 29 6 35
5306 ? sprintf('%.*f (%.*f)', $digits, mean($gv), $digits, @$gv > 1 ? sd($gv) : 0)
5307 : '';
5308 }
5309 16 ▶ $row{Overall} = @$allv
Branch: 2 branches
BranchTrueFalseTotal
@$allv ? : 16 0 16
@$allv > 1 ? : 16 0 16
5310 ? sprintf('%.*f (%.*f)', $digits, mean($allv), $digits, @$allv > 1 ? sd($allv) : 0)
5311 : '';
5312 16 ▶ if (defined $by && @groups >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $by and @groups >= 2) 15 1 16
Condition66%2/3
defined $by and @groups >= 2
!ll&&!rl&&r
1015
MC/DC50%1/2
defined $by and @groups >= 2
defined $by @groups >= 2
Truth table66%2/3
A and B
A= defined $byB= @groups >= 2
ABresult
0X0
100
111
5313 15 ($row{'p_value'}, $row{test}) = _t1_cont_p(\@byg, $nonpar);
5314 }
5315 16 push @out, \%row;
5316 }
5317 else {
5318 # Every (group, level) pair is counted in one pass; the Overall
5319 # count of a level is the sum over the groups, since every row is
5320 # in exactly one. A column shorter than the frame counts its rows
5321 # past the end as NA.
5322 8 my @gcnt = @$per; # $gcnt[$gi]{$level} = rows in that group
5323 8 my %allcnt;
5324 8 for my $c (@gcnt) { $allcnt{$_} += $c->{$_} for keys %$c }
5325 8 my @levels = keys %allcnt;
5326 # Numeric codes in numeric order -- a string sort put stage 10
5327 # between 1 and 2 -- with NA last. A NaN level has no numeric
5328 # order, and <=> returning undef is fatal here, so it keeps the
5329 # string sort.
5330 8 my @known = grep { $_ ne 'NA' } @levels;
5331 8 ▶ if (@known && !grep { !looks_like_number($_) || $_ != $_ } @known) {
Branch: 1 branch
BranchTrueFalseTotal
if (@known and not grep({not &looks_like_number($_) or $_ != $_;} @known)) { } 2 6 8
Condition66%4/6
@known and not grep({not &looks_like_number($_) or $_ != $_;} @known)
!ll&&!rl&&r
062
!&looks_like_number($_) || $_ != $_
l!l&&r!l&&!r
13015
MC/DC50%1/2
@known and not grep({not &looks_like_number($_) or $_ != $_;} @known)
@known not grep({not &looks_like_number($_) or $_ != $_;} @known)
MC/DC50%1/2
!&looks_like_number($_) || $_ != $_
!&looks_like_number($_) $_ != $_
Truth table66%2/3
A and not(B)
A= @knownB= not grep({not &looks_like_number($_) or $_ != $_;} @known)
ABresult
0X0
100
111
Truth table66%2/3
not(A) || B
A= !&looks_like_number($_)B= $_ != $_
ABresult
1X1
011
000
5332 2 ▶ @levels = ( (sort { $a <=> $b || $a cmp $b } @known),
Branch: 1 branch
BranchTrueFalseTotal
@known < @levels ? : 1 1 2
Condition33%1/3
$a <=> $b || $a cmp $b
l!l&&r!l&&!r
3000
MC/DC0%0/2
$a <=> $b || $a cmp $b
$a <=> $b $a cmp $b
Truth table33%1/3
A || B
A= $a <=> $bB= $a cmp $b
ABresult
1X1
011
000
5333 (@known < @levels ? 'NA' : ()) );
5334 } else {
5335 6 @levels = sort @levels;
5336 }
5337 8 my %hdr = (variable => $v, level => '', type => 'categorical');
5338 8 ▶ if (defined $by && @groups >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $by and @groups >= 2) 5 3 8
Condition66%2/3
defined $by and @groups >= 2
!ll&&!rl&&r
305
MC/DC50%1/2
defined $by and @groups >= 2
defined $by @groups >= 2
Truth table66%2/3
A and B
A= defined $byB= @groups >= 2
ABresult
0X0
100
111
5339 5 my @table;
5340 5 for my $lv (@levels) {
5341 23 ▶ push @table, [ map { $gcnt[$_]{$lv} || 0 } 0 .. $#groups ];
Condition100%2/2
$gcnt[$_]{$lv} || 0
l!l
3115
MC/DC100%1/1
$gcnt[$_]{$lv} || 0
$gcnt[$_]{$lv}
Truth table100%2/2
A
A= $gcnt[$_]{$lv}
Aresult
11
00
5342 }
5343 5 ($hdr{'p_value'}, $hdr{test}) = _t1_cat_p(\@table);
5344 }
5345 8 push @out, \%hdr;
5346 8 for my $lv (@levels) {
5347 31 my %row = (variable => $v, level => $lv, type => 'categorical');
5348 31 for my $gi (0 .. $#groups) {
5349 54 ▶ my $cnt = $gcnt[$gi]{$lv} || 0;
Condition100%2/2
$gcnt[$gi]{$lv} || 0
l!l
3915
MC/DC100%1/1
$gcnt[$gi]{$lv} || 0
$gcnt[$gi]{$lv}
Truth table100%2/2
A
A= $gcnt[$gi]{$lv}
Aresult
11
00
5350 54 my $tot = $gsize[$gi];
5351 54 ▶ $row{ $groups[$gi] } = $tot ? sprintf('%d (%.*f%%)', $cnt, $pdig, 100 * $cnt / $tot) : '0';
Branch: 1 branch
BranchTrueFalseTotal
$tot ? : 54 0 54
5352 }
5353 31 ▶ my $cntall = $allcnt{$lv} || 0;
Condition50%1/2
$allcnt{$lv} || 0
l!l
310
MC/DC0%0/1
$allcnt{$lv} || 0
$allcnt{$lv}
Truth table50%1/2
A
A= $allcnt{$lv}
Aresult
11
00
5354 31 ▶ $row{Overall} = $R ? sprintf('%d (%.*f%%)', $cntall, $pdig, 100 * $cntall / $R) : '0';
Branch: 1 branch
BranchTrueFalseTotal
$R ? : 31 0 31
5355 31 push @out, \%row;
5356 }
5357 }
5358 }
5359 14 return \@out;
5360 }
5361  
5362 # Effect sizes (Perl level; compose the XS primitives mean/var/aov). All
5363 # validated numerically against R. Added to @EXPORT_OK (== @EXPORT).
5364  
5365 # _num_pair(\@x, \@y, $who) -> (\@xn, \@yn): defined, numeric values only.
5366 142 ▶sub _num_pair {
Subroutine _num_pair: called CC=7 SCAR=19.5
5367 142 my ($x, $y, $who) = @_;
5368 142 ▶ _usage_error($who, 'first two arguments must be array references')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $x eq "ARRAY" and ref $y eq "ARRAY" 7 135 142
Condition100%3/3
ref $x eq "ARRAY" and ref $y eq "ARRAY"
!ll&&!rl&&r
61135
MC/DC100%2/2
ref $x eq "ARRAY" and ref $y eq "ARRAY"
ref $x eq "ARRAY" ref $y eq "ARRAY"
Truth table100%3/3
A and B
A= ref $x eq "ARRAY"B= ref $y eq "ARRAY"
ABresult
0X0
100
111
5369 unless ref $x eq 'ARRAY' && ref $y eq 'ARRAY';
5370 135 ▶ my @xn = grep { defined && looks_like_number($_) } @$x;
Condition100%3/3
defined $_ && &looks_like_number($_)
!ll&&!rl&&r
58111416325893
MC/DC100%2/2
defined $_ && &looks_like_number($_)
defined $_ &looks_like_number($_)
Truth table100%3/3
A && B
A= defined $_B= &looks_like_number($_)
ABresult
0X0
100
111
5371 135 ▶ my @yn = grep { defined && looks_like_number($_) } @$y;
Condition100%3/3
defined $_ && &looks_like_number($_)
!ll&&!rl&&r
59081416317117
MC/DC100%2/2
defined $_ && &looks_like_number($_)
defined $_ &looks_like_number($_)
Truth table100%3/3
A && B
A= defined $_B= &looks_like_number($_)
ABresult
0X0
100
111
5372 135 ▶ die "$who: each group needs at least two numeric observations\n"
Branch: 1 branch
BranchTrueFalseTotal
if @xn < 2 or @yn < 2 4 131 135
Condition100%3/3
@xn < 2 or @yn < 2
l!l&&r!l&&!r
31131
MC/DC100%2/2
@xn < 2 or @yn < 2
@xn < 2 @yn < 2
Truth table100%3/3
A or B
A= @xn < 2B= @yn < 2
ABresult
1X1
011
000
5373 if @xn < 2 || @yn < 2;
5374 131 return (\@xn, \@yn);
5375 }
5376  
5377 # cohen_d(\@x, \@y, conf_level => 0.95, ci_method => 'nct')
5378 #
5379 # Cohen's d for two independent samples using the pooled standard deviation,
5380 # with the Hedges' g small-sample bias correction.
5381 #
5382 # The interval is effectsize 1.0.3's cohens_d() interval by default
5383 # (R/cohens_d.R): t = d / sqrt(1/n1 + 1/n2) on n1 + n2 - 2 df, the limits of
5384 # its noncentrality parameter (_nct_ncp_ci(), in the XS), each scaled back by
5385 # sqrt(1/n1 + 1/n2). Up to 0.3217 it was d +- z * se, which effectsize's own
5386 # test of mtcars wt ~ am puts at 1.048 to 2.737 for its 1.030 to 2.732; that
5387 # interval is still there as ci_method => 'normal'. se is Hedges and Olkin's
5388 # large-sample standard error, which effsize 0.8.1's cohen.d() also reports
5389 # (as sqrt of var); the 'nct' interval does not use it.
5390 #
5391 # J is the approximation 1 - 3/(4 df - 1) that effsize 0.8.1 uses, written
5392 # with df = n1 + n2 - 2. effectsize 1.0.3 uses the exact gamma ratio; the two
5393 # differ by 4e-5 relative at df = 30 and by 3e-6 at df = 100.
5394 110 ▶sub cohen_d {
Subroutine cohen_d: called CC=13 SCAR=25.6
Pod documented
5395 110 my ($x, $y, @rest) = @_;
5396 110 ▶ _usage_error('cohen_d', 'arguments after the two groups must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @rest % 2 1 109 110
5397 if @rest % 2;
5398 109 _opt_names_defined('cohen_d', @rest);
5399 109 my %opt = @rest;
5400 109 ▶ my @bad = sort grep { $_ ne 'conf_level' && $_ ne 'ci_method' } keys %opt;
Condition100%3/3
$_ ne 'conf_level' && $_ ne 'ci_method'
!ll&&!rl&&r
98471
MC/DC100%2/2
$_ ne 'conf_level' && $_ ne 'ci_method'
$_ ne 'conf_level' $_ ne 'ci_method'
Truth table100%3/3
A && B
A= $_ ne 'conf_level'B= $_ ne 'ci_method'
ABresult
0X0
100
111
5401 109 ▶ _usage_error('cohen_d', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 108 109
5402 108 ▶ my $cl = defined $opt{conf_level} ? $opt{conf_level} : 0.95;
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'conf_level'} ? : 98 10 108
5403 108 ▶ _usage_error('cohen_d', 'conf_level must be between 0 and 1')
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($cl) and $cl > 0 and $cl < 1 5 103 108
Condition100%6/6
&looks_like_number($cl) and $cl > 0 and $cl < 1
!ll&&!rl&&r
32103
&looks_like_number($cl) and $cl > 0
!ll&&!rl&&r
12105
MC/DC100%3/3
&looks_like_number($cl) and $cl > 0 and $cl < 1
&looks_like_number($cl) $cl > 0 $cl < 1
Truth table100%4/4
A and B and C
A= &looks_like_number($cl)B= $cl > 0C= $cl < 1
ABCresult
0XX0
10X0
1100
1111
5404 unless looks_like_number($cl) && $cl > 0 && $cl < 1;
5405 103 ▶ my $method = defined $opt{ci_method} ? $opt{ci_method} : 'nct';
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'ci_method'} ? : 47 56 103
5406 103 ▶ _usage_error('cohen_d', "ci_method must be 'nct' or 'normal'")
Branch: 1 branch
BranchTrueFalseTotal
unless $method eq "nct" or $method eq "normal" 1 102 103
Condition100%3/3
$method eq "nct" or $method eq "normal"
l!l&&r!l&&!r
56461
MC/DC100%2/2
$method eq "nct" or $method eq "normal"
$method eq "nct" $method eq "normal"
Truth table100%3/3
A or B
A= $method eq "nct"B= $method eq "normal"
ABresult
1X1
011
000
5407 unless $method eq 'nct' || $method eq 'normal';
5408 102 my ($xn, $yn) = _num_pair($x, $y, 'cohen_d');
5409 97 my ($n1, $n2) = (scalar @$xn, scalar @$yn);
5410 97 my ($m1, $m2) = (mean($xn), mean($yn));
5411 97 my ($v1, $v2) = (var($xn), var($yn));
5412 97 my $sp = sqrt((($n1 - 1) * $v1 + ($n2 - 1) * $v2) / ($n1 + $n2 - 2));
5413 97 ▶ die "cohen_d: pooled standard deviation is zero\n" if $sp == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $sp == 0 1 96 97
5414 96 my $d = ($m1 - $m2) / $sp;
5415 96 my $J = 1 - 3 / (4 * ($n1 + $n2) - 9); # Hedges' correction factor
5416 96 my $se = sqrt(($n1 + $n2) / ($n1 * $n2) + $d * $d / (2 * ($n1 + $n2)));
5417 96 my @ci;
5418 96 ▶ if ($method eq 'nct') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq 'nct') { } 50 46 96
5419 50 my $hn = sqrt(1 / $n1 + 1 / $n2);
5420 50 @ci = map { $_ * $hn } _nct_ncp_ci($d / $hn, $n1 + $n2 - 2, $cl);
5421 } else {
5422 46 my $z = qnorm((1 + $cl) / 2);
5423 46 @ci = ($d - $z * $se, $d + $z * $se);
5424 }
5425 return {
5426 96 estimate => $d,
5427 hedges_g => $d * $J,
5428 pooled_sd => $sp,
5429 se => $se,
5430 'conf_int' => \@ci,
5431 'conf_level' => $cl,
5432 ci_method => $method,
5433 n1 => $n1,
5434 n2 => $n2,
5435 };
5436 }
5437  
5438 # smd(\@x, \@y)
5439 #
5440 # Standardized mean difference for two continuous groups using the simple
5441 # (unweighted) average of the group variances in the denominator -- the
5442 # convention used for covariate-balance "Table 1" diagnostics. It is
5443 # tableone 0.13.2's StdDiff() (R/modules-smd.R) for one pair of groups, signed
5444 # where StdDiff() returns abs().
5445 #
5446 # A zero denominator is answered as StdDiff() answers it. A column that is
5447 # one constant in both groups is 0, which StdDiff() substitutes for 0/0 and
5448 # smd 0.8.0's tests also expect; a column constant within each group but not
5449 # between them is +-Inf, StdDiff()'s mean difference over sqrt(0). Up to
5450 # 0.3217 both died with "pooled standard deviation is zero", which took a
5451 # balance table down over one constant covariate.
5452 40 ▶sub smd {
Subroutine smd: called CC=4 SCAR=13.9
Pod documented
5453 40 my ($x, $y) = @_;
5454 40 my ($xn, $yn) = _num_pair($x, $y, 'smd');
5455 34 my $diff = mean($xn) - mean($yn);
5456 34 my $denom = sqrt((var($xn) + var($yn)) / 2);
5457 34 ▶ if ($denom == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($denom == 0) 10 24 34
5458 10 ▶ return 0 if $diff == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $diff == 0 8 2 10
5459 2 ▶ return $diff > 0 ? 9**9**9 : -9**9**9;
Branch: 1 branch
BranchTrueFalseTotal
$diff > 0 ? : 1 1 2
5460 }
5461 24 return $diff / $denom;
5462 }
5463  
5464 # _xtab(\@a, \@b) -> (\@table, \@rowlevels, \@collevels): contingency table
5465 # from two parallel categorical vectors (rows = levels of a, cols = levels of b).
5466 1 ▶sub _xtab {
Subroutine _xtab: called CC=6 SCAR=18.4
5467 1 my ($a, $b) = @_;
5468 1 ▶ die "cramers_v: the two vectors must have the same length\n"
Branch: 1 branch
BranchTrueFalseTotal
unless @$a == @$b 0 1 1
5469 unless @$a == @$b;
5470 1 my (%rseen, %cseen, %cell);
5471 1 for my $i (0 .. $#$a) {
5472 12 ▶ next unless defined $a->[$i] && defined $b->[$i];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $a->[$i] and defined $b->[$i] 0 12 12
Condition33%1/3
defined $a->[$i] and defined $b->[$i]
!ll&&!rl&&r
0012
MC/DC0%0/2
defined $a->[$i] and defined $b->[$i]
defined $a->[$i] defined $b->[$i]
Truth table33%1/3
A and B
A= defined $a->[$i]B= defined $b->[$i]
ABresult
0X0
100
111
5473 12 my ($r, $c) = ("$a->[$i]", "$b->[$i]");
5474 12 $rseen{$r}++; $cseen{$c}++; $cell{$r}{$c}++;
5475 }
5476 1 my @rl = sort keys %rseen;
5477 1 my @cl = sort keys %cseen;
5478 1 ▶ my @tab = map { my $r = $_; [ map { $cell{$r}{$_} // 0 } @cl ] } @rl;
Condition50%1/2
$cell{$r}{$_} // 0
l!l
60
MC/DC0%0/1
$cell{$r}{$_} // 0
$cell{$r}{$_}
Truth table50%1/2
A
A= $cell{$r}{$_}
Aresult
11
00
5479 1 return (\@tab, \@rl, \@cl);
5480 }
5481  
5482 # cramers_v(\@table) or cramers_v(\@x, \@y)
5483 #
5484 # Cramer's V for an r x c contingency table (uncorrected Pearson chi-square),
5485 # with the Bergsma (2013) bias-corrected variant. Accepts either a table
5486 # (array of array refs of counts) or two parallel categorical vectors.
5487 8 ▶sub cramers_v {
Subroutine cramers_v: called CC=22 SCAR=31.5
Pod documented
5488 8 my @args = @_;
5489 8 my $tab;
5490 8 ▶ if (ref $args[0] eq 'ARRAY' && ref $args[0][0] eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $args[0] eq 'ARRAY' and ref $args[0][0] eq 'ARRAY') { } 3 5 8
elsif (ref $args[0] eq 'ARRAY' and ref $args[1] eq 'ARRAY') { } 1 4 5
Condition100%3/3
ref $args[0] eq "ARRAY" and ref $args[0][0] eq "ARRAY"
!ll&&!rl&&r
413
MC/DC100%2/2
ref $args[0] eq "ARRAY" and ref $args[0][0] eq "ARRAY"
ref $args[0] eq "ARRAY" ref $args[0][0] eq "ARRAY"
Truth table100%3/3
A and B
A= ref $args[0] eq "ARRAY"B= ref $args[0][0] eq "ARRAY"
ABresult
0X0
100
111
5491 3 $tab = $args[0];
5492 ▶ } elsif (ref $args[0] eq 'ARRAY' && ref $args[1] eq 'ARRAY') {
Condition66%2/3
ref $args[0] eq "ARRAY" and ref $args[1] eq "ARRAY"
!ll&&!rl&&r
401
MC/DC50%1/2
ref $args[0] eq "ARRAY" and ref $args[1] eq "ARRAY"
ref $args[0] eq "ARRAY" ref $args[1] eq "ARRAY"
Truth table66%2/3
A and B
A= ref $args[0] eq "ARRAY"B= ref $args[1] eq "ARRAY"
ABresult
0X0
100
111
5493 1 ($tab) = _xtab($args[0], $args[1]);
5494 } else {
5495 4 _usage_error('cramers_v', 'expected a count table or two parallel vectors');
5496 }
5497 4 my $r = scalar @$tab;
5498 4 ▶ die "cramers_v: table needs at least two rows and columns\n" if $r < 2;
Branch: 1 branch
BranchTrueFalseTotal
if $r < 2 1 3 4
5499 3 my $c = scalar @{ $tab->[0] };
5500 3 ▶ die "cramers_v: table needs at least two rows and columns\n" if $c < 2;
Branch: 1 branch
BranchTrueFalseTotal
if $c < 2 0 3 3
5501 3 my (@rsum, @csum, $N);
5502 3 for my $i (0 .. $r - 1) {
5503 7 ▶ die "cramers_v: ragged table\n" unless @{ $tab->[$i] } == $c;
Branch: 1 branch
BranchTrueFalseTotal
unless @{$tab->[$i];} == $c 0 7 7
5504 7 for my $j (0 .. $c - 1) {
5505 16 my $v = $tab->[$i][$j];
5506 16 ▶ die "cramers_v: counts must be non-negative numbers\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and &looks_like_number($v) and $v >= 0 0 16 16
Condition33%2/6
defined $v and &looks_like_number($v) and $v >= 0
!ll&&!rl&&r
0016
defined $v and &looks_like_number($v)
!ll&&!rl&&r
0016
MC/DC0%0/3
defined $v and &looks_like_number($v) and $v >= 0
defined $v &looks_like_number($v) $v >= 0
Truth table25%1/4
A and B and C
A= defined $vB= &looks_like_number($v)C= $v >= 0
ABCresult
0XX0
10X0
1100
1111
5507 unless defined $v && looks_like_number($v) && $v >= 0;
5508 16 $rsum[$i] += $v; $csum[$j] += $v; $N += $v;
5509 }
5510 }
5511 3 ▶ die "cramers_v: table total is zero\n" unless $N;
Branch: 1 branch
BranchTrueFalseTotal
unless $N 0 3 3
5512 # the bias correction divides by N - 1: up to 0.3217 a total of 1 died on
5513 # perl's own "Illegal division by zero", naming a line of this file
5514 3 ▶ die "cramers_v: the table total must be more than 1\n" unless $N > 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $N > 1 1 2 3
5515 2 my $chi = 0;
5516 2 for my $i (0 .. $r - 1) {
5517 5 for my $j (0 .. $c - 1) {
5518 12 my $e = $rsum[$i] * $csum[$j] / $N;
5519 12 ▶ next unless $e > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $e > 0 0 12 12
5520 12 my $diff = $tab->[$i][$j] - $e;
5521 12 $chi += $diff * $diff / $e;
5522 }
5523 }
5524 2 ▶ my $mindim = ($r < $c ? $r : $c) - 1;
Branch: 1 branch
BranchTrueFalseTotal
$r < $c ? : 1 1 2
5525 2 my $v = sqrt($chi / ($N * $mindim));
5526 # Bergsma bias-corrected V
5527 2 my $phi2 = $chi / $N;
5528 2 my $phi2c = $phi2 - ($c - 1) * ($r - 1) / ($N - 1);
5529 2 ▶ $phi2c = 0 if $phi2c < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $phi2c < 0 1 1 2
5530 2 my $rc = $r - ($r - 1) ** 2 / ($N - 1);
5531 2 my $cc = $c - ($c - 1) ** 2 / ($N - 1);
5532 2 ▶ my $mc = ($rc < $cc ? $rc : $cc) - 1;
Branch: 1 branch
BranchTrueFalseTotal
$rc < $cc ? : 1 1 2
5533 2 ▶ my $vc = $mc > 0 ? sqrt($phi2c / $mc) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$mc > 0 ? : 2 0 2
5534 return {
5535 2 estimate => $v,
5536 bias_corrected => $vc,
5537 chisq => $chi,
5538 df => ($r - 1) * ($c - 1),
5539 n => $N,
5540 };
5541 }
5542  
5543 # eta_squared($aov_result) or eta_squared(\@values, \@groups)
5544 #
5545 # Eta-squared, partial eta-squared and omega-squared for a one-way design,
5546 # from the ANOVA sums of squares. Accepts an aov() result hash (single factor)
5547 # or raw values + group labels.
5548 #
5549 # The raw form fits Group as a factor whatever its labels look like, through
5550 # oneway_test() or aov()'s stacked form; see below for which. Up to 0.3217 it
5551 # passed aov() a formula, which fits a column whose values all look like
5552 # numbers as one slope: groups coded 1, 2, 3 were a linear trend with 1 df,
5553 # and the airquality Ozone ~ Month example gave eta_sq 0.0271 for R's 0.2352.
5554 32 ▶sub eta_squared {
Subroutine eta_squared: called CC=17 SCAR=28.3
Pod documented
5555 32 my @args = @_;
5556 32 my $aov_res;
5557 32 ▶ if (ref $args[0] eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $args[0] eq 'HASH') { } 11 21 32
elsif (ref $args[0] eq 'ARRAY' and ref $args[1] eq 'ARRAY') { } 16 5 21
5558 11 $aov_res = $args[0];
5559 ▶ } elsif (ref $args[0] eq 'ARRAY' && ref $args[1] eq 'ARRAY') {
Condition66%2/3
ref $args[0] eq "ARRAY" and ref $args[1] eq "ARRAY"
!ll&&!rl&&r
5016
MC/DC50%1/2
ref $args[0] eq "ARRAY" and ref $args[1] eq "ARRAY"
ref $args[0] eq "ARRAY" ref $args[1] eq "ARRAY"
Truth table66%2/3
A and B
A= ref $args[0] eq "ARRAY"B= ref $args[1] eq "ARRAY"
ABresult
0X0
100
111
5560 16 my ($v, $g) = @args;
5561 16 ▶ die "eta_squared: values and groups must have the same length\n"
Branch: 1 branch
BranchTrueFalseTotal
unless @$v == @$g 1 15 16
5562 unless @$v == @$g;
5563 15 my %by; # group label => its values; aov() drops an undef value itself
5564 15 my $plain = 1; # 0 = some value is undef or not a number
5565 15 for my $i (0 .. $#$v) {
5566 739 ▶ next unless defined $g->[$i];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $g->[$i] 1 738 739
5567 738 my $x = $v->[$i];
5568 738 ▶ $plain = 0 unless defined $x && looks_like_number($x);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $x and &looks_like_number($x) 76 662 738
Condition100%3/3
defined $x and &looks_like_number($x)
!ll&&!rl&&r
751662
MC/DC100%2/2
defined $x and &looks_like_number($x)
defined $x &looks_like_number($x)
Truth table100%3/3
A and B
A= defined $xB= &looks_like_number($x)
ABresult
0X0
100
111
5569 738 push @{ $by{ $g->[$i] } }, $x;
5570 }
5571 # oneway_test(var_equal => 1) gives the table aov()'s stacked form does,
5572 # from each group's sum and sum of squares rather than a design matrix:
5573 # on 1e6 values in 5 groups, 0.10 s and 47 MB against 0.73 s and 326 MB.
5574 # It refuses what aov() takes -- one group, a group of one value, and an
5575 # undef or non-numeric value, which aov() drops -- so those go to aov().
5576 15 my $small = grep { @$_ < 2 } values %by; # groups of fewer than two values
5577 15 ▶ $aov_res = $plain && keys %by >= 2 && !$small
Branch: 1 branch
BranchTrueFalseTotal
$plain && keys %by >= 2 && !$small ? : 9 6 15
Condition100%6/6
$plain and keys %by >= 2 and not $small
!ll&&!rl&&r
519
$plain and keys %by >= 2
!ll&&!rl&&r
4110
MC/DC100%3/3
$plain and keys %by >= 2 and not $small
$plain keys %by >= 2 not $small
Truth table100%4/4
A and B and not(C)
A= $plainB= keys %by >= 2C= not $small
ABCresult
0XX0
10X0
1100
1111
5578 ? oneway_test(\%by, var_equal => 1)
5579 : aov(\%by);
5580 } else {
5581 5 _usage_error('eta_squared', 'expected an aov() result or (\@values, \@groups)');
5582 }
5583 my $resid = $aov_res->{Residuals}
5584 26 ▶ or die "eta_squared: not an ANOVA result (no Residuals term)\n";
Branch: 1 branch
BranchTrueFalseTotal
my $resid = $aov_res->{"Residuals"} or die "eta_squared: not an ANOVA result (no Residuals term)\n" 25 1 26
5585 25 my $ss_resid = $resid->{'Sum Sq'};
5586 25 my $ms_resid = $resid->{'Mean Sq'};
5587 # SS_total below is SS_effect + SS_resid, which is the total only when there
5588 # is one effect term. Up to 0.3217 a two-factor result was answered for
5589 # whichever term sorted first, with partial eta-squared reported as eta_sq.
5590 25 my @terms = grep { $_ ne 'Residuals' && ref $aov_res->{$_} eq 'HASH'
5591 140 ▶ && exists $aov_res->{$_}{'Sum Sq'} } sort keys %$aov_res;
Condition100%6/6
$_ ne 'Residuals' && ref $aov_res->{$_} eq 'HASH' && exists $aov_res->{$_}{'Sum Sq'}
!ll&&!rl&&r
417326
$_ ne "Residuals" and ref $aov_res->{$_} eq "HASH"
!ll&&!rl&&r
251699
MC/DC100%3/3
$_ ne 'Residuals' && ref $aov_res->{$_} eq 'HASH' && exists $aov_res->{$_}{'Sum Sq'}
$_ ne "Residuals" ref $aov_res->{$_} eq "HASH" exists $aov_res->{$_}{'Sum Sq'}
Truth table100%4/4
A and B && C
A= $_ ne "Residuals"B= ref $aov_res->{$_} eq "HASH"C= exists $aov_res->{$_}{'Sum Sq'}
ABCresult
0XX0
10X0
1100
1111
5592 25 ▶ die "eta_squared: could not find an effect term\n" unless @terms;
Branch: 1 branch
BranchTrueFalseTotal
unless @terms 0 25 25
5593 25 ▶ die 'eta_squared: the aov() result has ' . @terms . " effect terms (@terms); "
Branch: 1 branch
BranchTrueFalseTotal
if @terms > 1 1 24 25
5594 . "eta_squared() measures a one-way design, which has one\n" if @terms > 1;
5595 24 my $term = $terms[0];
5596 24 my $ss_eff = $aov_res->{$term}{'Sum Sq'};
5597 24 my $df_eff = $aov_res->{$term}{'Df'};
5598 24 my $ss_tot = $ss_eff + $ss_resid;
5599 return {
5600 24 term => $term,
5601 eta_sq => $ss_eff / $ss_tot,
5602 partial_eta_sq => $ss_eff / ($ss_eff + $ss_resid),
5603 omega_sq => ($ss_eff - $df_eff * $ms_resid) / ($ss_tot + $ms_resid),
5604 };
5605 }
5606  
5607 # Regression diagnostics (Perl level). Validated numerically against R.
5608 #
5609 # _lgamma/_igamc/_pchisq_upper used to be pure-Perl ports of the XS igamc()
5610 # living here. They are now XS (see LikeR.xs), so there is one implementation
5611 # instead of two that could disagree; _lgamma went away entirely because only
5612 # _igamc ever called it. _qnorm went the same way in 0.303: it was Acklam's
5613 # rational approximation, good to about 1e-9, and cohen_d's normal interval
5614 # is now built from the XS qnorm() that every other confidence limit in the
5615 # distribution uses.
5616  
5617 # _quantile7(\@sorted_ascending, $p): R's default (type 7) sample quantile,
5618 # in R 4.6.1 quantile.default()'s own arithmetic -- the 1-based index, and
5619 # (1 - h) * x[lo] + h * x[hi] rather than x[lo] + h * (x[hi] - x[lo]) -- so that
5620 # a break hosmer_lemeshow() compares a prediction against is R's to the bit.
5621 493 ▶sub _quantile7 {
Subroutine _quantile7: called CC=3 SCAR=11.0
5622 493 my ($s, $p) = @_;
5623 493 my $index = 1 + (@$s - 1) * $p;
5624 493 my $lo = int $index; # floor: $index >= 1
5625 493 my $qs = $s->[$lo - 1];
5626 493 ▶ return $qs unless $index > $lo && $s->[$lo] != $qs;
Branch: 1 branch
BranchTrueFalseTotal
unless $index > $lo and $s->[$lo] != $qs 147 346 493
Condition100%3/3
$index > $lo and $s->[$lo] != $qs
!ll&&!rl&&r
4998346
MC/DC100%2/2
$index > $lo and $s->[$lo] != $qs
$index > $lo $s->[$lo] != $qs
Truth table100%3/3
A and B
A= $index > $loB= $s->[$lo] != $qs
ABresult
0X0
100
111
5627 346 my $h = $index - $lo;
5628 346 return (1 - $h) * $qs + $h * $s->[$lo];
5629 }
5630  
5631 # _chol(\@A) -> \@L: the lower Cholesky factor of a symmetric positive definite
5632 # matrix given as an array of rows, or undef when it is not positive definite.
5633 186 ▶sub _chol {
Subroutine _chol: called CC=6 SCAR=17.9
5634 186 my ($A) = @_;
5635 186 my $n = @$A;
5636 186 my @L = map { [ (0) x $n ] } 1 .. $n;
5637 186 for my $j (0 .. $n - 1) {
5638 414 my $s = $A->[$j][$j];
5639 414 $s -= $L[$j][$_] ** 2 for 0 .. $j - 1;
5640 414 ▶ return undef unless $s > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $s > 0 0 414 414
5641 414 my $d = sqrt $s;
5642 414 $L[$j][$j] = $d;
5643 414 for my $i ($j + 1 .. $n - 1) {
5644 319 my $t = $A->[$i][$j];
5645 319 $t -= $L[$i][$_] * $L[$j][$_] for 0 .. $j - 1;
5646 319 $L[$i][$j] = $t / $d;
5647 }
5648 }
5649 186 return \@L;
5650 }
5651  
5652 # _chol_det(\@A): the determinant of a symmetric positive definite matrix.
5653 20 ▶sub _chol_det {
Subroutine _chol_det: called CC=3 SCAR=11.1
5654 20 ▶ my $L = _chol($_[0]) or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $L = _chol($_[0]) or return 0 20 0 20
5655 20 my $det = 1;
5656 20 $det *= $L->[$_][$_] ** 2 for 0 .. $#$L;
5657 20 return $det;
5658 }
5659  
5660 # vif($data, $formula_or_predictors [, type => 'terms' | 'predictor'])
5661 #
5662 # Variance inflation factors, ported from car 3.1-5's vif.default()
5663 # (R/vif.R), which vif.lm() hands its default type = "terms" to (type =
5664 # "predictor" is vif.lm()'s own, ported below as _vif_predictor()):
5665 #
5666 # R <- cov2cor(vcov(mod))[-1, -1] # less the intercept
5667 # GVIF_term = det(R[subs, subs]) * det(R[-subs, -subs]) / det(R)
5668 #
5669 # with subs the columns of one term, its result a plain VIF per term when
5670 # every term has 1 df and a GVIF, Df and GVIF^(1/(2*Df)) table when one has
5671 # more. The design is the one lm() builds from the formula, read by the XS
5672 # _vif_design(); only its columns' correlation matters, so R here is the
5673 # correlation of the design columns rather than of the coefficients. The two
5674 # give the same determinant ratio: by Jacobi's identity, det((C^-1)_SS) =
5675 # det(C_-S-S) / det(C), and the diagonal scaling of cov2cor() cancels. So
5676 #
5677 # GVIF_term = det(C[S, S]) * det(Cinv[S, S]), C = cor(X), Cinv = C^-1
5678 #
5679 # which for a 1-df term is Cinv's diagonal, the classical 1 / (1 - R^2_j).
5680 # Without an intercept car uses the uncentred vcov, and C here is the
5681 # uncentred cross-product matrix scaled to a unit diagonal, by the same
5682 # identity.
5683 #
5684 # Through 0.3217 vif() split the formula's right-hand side on '+' and
5685 # regressed each piece on the others, so only additive numeric terms worked:
5686 # y ~ x1*x2 + x3, y ~ x1 + x2 - x3 and y ~ . all died, the first two with
5687 # lm()'s "0 degrees of freedom" and the last with "need at least two
5688 # predictors"; a factor was never handled; and a response's missing values
5689 # did not take its rows out, where car's model has none of them.
5690 208 ▶sub vif {
Subroutine vif: called CC=30 SCAR=34.0
Pod documented
5691 208 my ($data, $spec, @opt) = @_;
5692 208 ▶ _usage_error('vif', 'first argument must be a data reference') unless ref $data;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data 4 204 208
5693 204 ▶ _usage_error('vif', 'options after the formula must be name => value pairs') if @opt % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @opt % 2 1 203 204
5694 203 _opt_names_defined('vif', @opt);
5695 203 my %opt = @opt;
5696 203 my $type = delete $opt{type};
5697 203 ▶ _usage_error('vif', "unknown option '" . (sort keys %opt)[0] . "'") if %opt;
Branch: 1 branch
BranchTrueFalseTotal
if %opt 1 202 203
5698 # match.arg(type): the full name or any unambiguous start of it
5699 202 ▶ $type = 'terms' unless defined $type;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type 179 23 202
5700 {
5701 202 ▶ my @hit = ref $type || $type eq '' ? () : grep { index($_, $type) == 0 } qw(terms predictor);
Branch: 1 branch
BranchTrueFalseTotal
ref $type || $type eq '' ? : 1 201 202
Condition66%2/3
ref $type or $type eq ""
l!l&&r!l&&!r
01201
MC/DC50%1/2
ref $type or $type eq ""
ref $type $type eq ""
Truth table66%2/3
A or B
A= ref $typeB= $type eq ""
ABresult
1X1
011
000
5702 202 ▶ _usage_error('vif', "type must be 'terms' or 'predictor'") unless @hit == 1;
Branch: 1 branch
BranchTrueFalseTotal
unless @hit == 1 2 200 202
5703 200 $type = $hit[0];
5704 }
5705 200 my $formula;
5706 200 ▶ if (ref $spec eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $spec eq 'ARRAY') { } 9 191 200
elsif (defined $spec and not ref $spec and $spec =~ /~/) { } 188 3 191
5707 9 $formula = '~ ' . join(' + ', @$spec);
5708 ▶ } elsif (defined $spec && !ref $spec && $spec =~ /~/) {
Condition100%6/6
defined $spec and not ref $spec and $spec =~ /~/
!ll&&!rl&&r
21188
defined $spec and not ref $spec
!ll&&!rl&&r
11189
MC/DC100%3/3
defined $spec and not ref $spec and $spec =~ /~/
defined $spec not ref $spec $spec =~ /~/
Truth table100%4/4
A and not(B) and C
A= defined $specB= not ref $specC= $spec =~ /~/
ABCresult
0XX0
10X0
1100
1111
5709 188 $formula = $spec;
5710 } else {
5711 3 _usage_error('vif', 'expected a formula string or an array ref of predictors');
5712 }
5713 # the XS croaks from this line, so its messages would name a line of this
5714 # file; vif()'s own messages carry no location, and neither do these
5715 197 my $ds = eval { _vif_design($data, $formula) };
5716 197 ▶ if (!$ds) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ds) 5 192 197
5717 5 (my $e = $@) =~ s/ at \S+ line \d+\.\n\z/\n/;
5718 5 die $e;
5719 }
5720 2 die 'vif: there are aliased coefficients in the model (' . join(', ', @{ $ds->{aliased} }) . ")\n"
5721 192 ▶ if @{ $ds->{aliased} };
Branch: 1 branch
BranchTrueFalseTotal
if @{$ds->{"aliased"};} 2 190 192
5722 190 ▶ return _vif_predictor($ds, $formula, $data) if $type eq 'predictor';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "predictor" 19 171 190
5723 # car counts the formula's terms; a factor with one level has no column
5724 # here, and lm() leaves it out of the fit, so it is not one of them
5725 171 my @terms = grep { $ds->{order}[$_] } 0 .. $#{ $ds->{term_labels} };
5726 171 ▶ die "vif: model contains fewer than 2 terms\n" if @terms < 2;
Branch: 1 branch
BranchTrueFalseTotal
if @terms < 2 5 166 171
5727 166 ▶ warn "vif: No intercept: vifs may not be sensible.\n" unless $ds->{intercept};
Branch: 1 branch
BranchTrueFalseTotal
unless $ds->{"intercept"} 2 164 166
5728 warn "vif: there are higher-order terms (interactions) in this model\n"
5729 . "consider setting type = 'predictor'; see ?vif\n"
5730 166 ▶ if grep { $ds->{order}[$_] > 1 } @terms;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$ds->{"order"}[$_] > 1;} @terms 6 160 166
5731 166 my $q = @{ $ds->{names} };
5732 166 my $x = $ds->{cross};
5733 166 my @sd = map { sqrt $x->[$_ * $q + $_] } 0 .. $q - 1;
5734 166 my @C;
5735 166 for my $i (0 .. $q - 1) {
5736 374 $C[$i][$_] = $x->[$i * $q + $_] / ($sd[$i] * $sd[$_]) for 0 .. $q - 1;
5737 }
5738 166 ▶ my $L = _chol(\@C) or die "vif: there are aliased coefficients in the model\n";
Branch: 1 branch
BranchTrueFalseTotal
my $L = _chol(\@C) or die "vif: there are aliased coefficients in the model\n" 166 0 166
5739 # Cinv = L'^-1 L^-1, from M = L^-1
5740 166 my @M = map { [ (0) x $q ] } 1 .. $q;
5741 166 for my $j (0 .. $q - 1) {
5742 374 $M[$j][$j] = 1 / $L->[$j][$j];
5743 374 for my $i ($j + 1 .. $q - 1) {
5744 299 my $s = 0;
5745 299 $s += $L->[$i][$_] * $M[$_][$j] for $j .. $i - 1;
5746 299 $M[$i][$j] = -$s / $L->[$i][$i];
5747 }
5748 }
5749 166 my @Cinv;
5750 166 for my $i (0 .. $q - 1) {
5751 374 for my $j ($i .. $q - 1) {
5752 673 my $s = 0;
5753 673 $s += $M[$_][$i] * $M[$_][$j] for $j .. $q - 1;
5754 673 $Cinv[$i][$j] = $Cinv[$j][$i] = $s;
5755 }
5756 }
5757 166 my (%gvif, %df);
5758 166 for my $t (@terms) {
5759 364 my @S = grep { $ds->{assign}[$_] == $t + 1 } 0 .. $q - 1;
5760 364 my $label = $ds->{term_labels}[$t];
5761 364 $df{$label} = @S;
5762 $gvif{$label} = @S == 1
5763 ? $Cinv[ $S[0] ][ $S[0] ]
5764 20 : _chol_det([ map { my $i = $_; [ @{ $C[$i] }[@S] ] } @S ])
5765 364 ▶ * _chol_det([ map { my $i = $_; [ @{ $Cinv[$i] }[@S] ] } @S ]);
Branch: 1 branch
BranchTrueFalseTotal
@S == 1 ? : 354 10 364
5766 }
5767 166 ▶ return \%gvif unless grep { $_ > 1 } values %df;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ > 1;} values %df 161 5 166
5768 5 return { map { $_ => {
5769 GVIF => $gvif{$_},
5770 Df => $df{$_},
5771 19 'GVIF^(1/(2*Df))' => $gvif{$_} ** (1 / (2 * $df{$_})),
5772 } } keys %gvif };
5773 }
5774  
5775 # _det_lu(\@A): the determinant of a square matrix, by Gaussian elimination with
5776 # partial pivoting as LAPACK's dgetrf does for R's det(); the empty matrix has
5777 # determinant 1. _chol_det() would do for a positive definite matrix, but
5778 # _vif_predictor() also asks for submatrices that need not be.
5779 107 ▶sub _det_lu {
Subroutine _det_lu: called CC=8 SCAR=20.8
5780 107 my @a = map { [ @$_ ] } @{ $_[0] };
5781 107 my $n = @a;
5782 107 my $det = 1;
5783 107 for my $k (0 .. $n - 1) {
5784 223 my $p = $k;
5785 223 ▶ for my $i ($k + 1 .. $n - 1) { $p = $i if abs $a[$i][$k] > abs $a[$p][$k] }
Branch: 1 branch
BranchTrueFalseTotal
if abs $a[$i][$k] > abs $a[$p][$k] 13 201 214
5786 223 ▶ return 0 if $a[$p][$k] == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $a[$p][$k] == 0 0 223 223
5787 223 ▶ if ($p != $k) { @a[$p, $k] = @a[$k, $p]; $det = -$det }
Branch: 1 branch
BranchTrueFalseTotal
if ($p != $k) 9 214 223
5788 223 $det *= $a[$k][$k];
5789 223 for my $i ($k + 1 .. $n - 1) {
5790 214 my $f = $a[$i][$k] / $a[$k][$k];
5791 214 $a[$i][$_] -= $f * $a[$k][$_] for $k + 1 .. $n - 1;
5792 }
5793 }
5794 107 return $det;
5795 }
5796  
5797 # _formula_vars($text, $data): R's all.vars() of a formula's text, the names
5798 # of the variables in order of first appearance. A name followed by '(' is a
5799 # function and a token that begins with a digit a number, so log(x + 1) and
5800 # I(a - b) give x and a, b; '.' gives every column of $data but the row-name
5801 # columns, in the sorted order lm() expands it in.
5802 74 ▶sub _formula_vars {
Subroutine _formula_vars: called CC=13 SCAR=38.5
5803 74 my ($text, $data) = @_;
5804 74 my (@v, %seen);
5805 74 $text =~ s/\s+//g;
5806 74 $text =~ s/%in%/+/g;
5807 74 ▶ while ($text =~ /([^-+*\/:^()%,]+)(\()?/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ m[([^-+*/:^()%,]+)(\()?]g) 120 74 194
5808 120 my ($tok, $call) = ($1, $2);
5809 120 ▶ next if $call || $tok =~ /^[0-9]/;
Branch: 1 branch
BranchTrueFalseTotal
if $call or $tok =~ /^[0-9]/ 0 120 120
Condition33%1/3
$call or $tok =~ /^[0-9]/
l!l&&r!l&&!r
00120
MC/DC0%0/2
$call or $tok =~ /^[0-9]/
$call $tok =~ /^[0-9]/
Truth table33%1/3
A or B
A= $callB= $tok =~ /^[0-9]/
ABresult
1X1
011
000
5810 120 my @names = $tok;
5811 120 ▶ if ($tok eq '.') {
Branch: 1 branch
BranchTrueFalseTotal
if ($tok eq ".") 0 120 120
5812 0 ▶ my $first = ref $data eq 'ARRAY' ? $data->[0] : $data;
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'ARRAY' ? : 0 0 0
5813 0 ▶ my @ks = ref $first eq 'HASH' ? keys %$first : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $first eq 'HASH' ? : 0 0 0
5814 # a hash of rows (HoH) names its columns by its first row's keys
5815 0 ▶ if (ref $data eq 'HASH' && @ks && !grep { ref $first->{$_} eq 'ARRAY' } @ks) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "HASH" and @ks and not grep({ref $first->{$_} eq "ARRAY";} @ks)) 0 0 0
Condition0%0/6
ref $data eq "HASH" and @ks and not grep({ref $first->{$_} eq "ARRAY";} @ks)
!ll&&!rl&&r
000
ref $data eq "HASH" and @ks
!ll&&!rl&&r
000
MC/DC0%0/3
ref $data eq "HASH" and @ks and not grep({ref $first->{$_} eq "ARRAY";} @ks)
ref $data eq "HASH" @ks not grep({ref $first->{$_} eq "ARRAY";} @ks)
Truth table0%0/4
A and B and not(C)
A= ref $data eq "HASH"B= @ksC= not grep({ref $first->{$_} eq "ARRAY";} @ks)
ABCresult
0XX0
10X0
1100
1111
5816 0 my ($row) = map { $data->{$_} } sort keys %$data;
5817 0 ▶ @ks = ref $row eq 'HASH' ? keys %$row : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $row eq 'HASH' ? : 0 0 0
5818 }
5819 0 @names = grep { $_ !~ /\A(?:row_names|_row|rownames|\.rownames)\z/ } sort @ks;
5820 }
5821 120 ▶ for my $n (@names) { push @v, $n unless $seen{$n}++ }
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$n}++ 118 2 120
5822 }
5823 74 return @v;
5824 }
5825  
5826 # _vif_predictor($ds, $formula, $data): vif(type = "predictor"), ported from
5827 # car 3.1-5's vif.lm() (R/vif.R). For each predictor, the GVIF of the columns
5828 # of the terms it appears in, with the terms of every predictor it does not
5829 # interact with held out:
5830 #
5831 # related the variables of the terms the predictor is in
5832 # columns the design's columns, less those of every term that has a
5833 # variable the predictor is not related to
5834 # GVIF det(R[columns, columns]) * det(R[-columns, -columns]) / det(R)
5835 #
5836 # with R the correlation of the design's columns, less the intercept's. So a
5837 # predictor with no interaction gets the GVIF of its own term among all the
5838 # others, and interacting predictors share one value. Df is the number of
5839 # columns, and the result a table with "Interacts With" and "Other
5840 # Predictors" beside GVIF, Df and GVIF^(1/(2*Df)) -- or, as car's, a plain
5841 # predictor => GVIF hash when every Df is 1.
5842 #
5843 # What car does and this follows, though odd: "Interacts With" lists the
5844 # related variables after the first, which is the predictor only when its first
5845 # term starts with it (a predictor b met only in a:b is listed as interacting
5846 # with b, not with a); a variable in the formula that no term has (`- qsec`) is a
5847 # predictor of Df 0 whose GVIF^(1/(2*Df)) is Inf; and an empty set of columns
5848 # has determinant 1.
5849 #
5850 # car's refusals, which this keeps: a model with no intercept, where vif.lm()
5851 # stops at "object 'assign.X' not found" (it defines that only with one), and a
5852 # model matrix with a single column, where cor() stops at "supply both 'x' and
5853 # 'y' or a matrix-like 'x'". An aliased column, which car carries on past
5854 # into NaN, is refused as type = "terms" refuses it, in vif().
5855 19 ▶sub _vif_predictor {
Subroutine _vif_predictor: called CC=19 SCAR=29.5
5856 19 my ($ds, $formula, $data) = @_;
5857 die "vif: type = 'predictor' needs a model with an intercept; car::vif() stops at "
5858 19 ▶ . "\"object 'assign.X' not found\" without one\n" unless $ds->{intercept};
Branch: 1 branch
BranchTrueFalseTotal
unless $ds->{"intercept"} 1 18 19
5859 18 my $q = @{ $ds->{names} };
5860 18 ▶ die "vif: type = 'predictor' needs a design with at least two columns besides the intercept; "
Branch: 1 branch
BranchTrueFalseTotal
if $q < 2 1 17 18
5861 . "car::vif() stops at \"supply both 'x' and 'y' or a matrix-like 'x'\"\n" if $q < 2;
5862 17 my $x = $ds->{cross};
5863 17 my @sd = map { sqrt $x->[$_ * $q + $_] } 0 .. $q - 1;
5864 17 my @R;
5865 17 for my $i (0 .. $q - 1) {
5866 63 $R[$i][$_] = $x->[$i * $q + $_] / ($sd[$i] * $sd[$_]) for 0 .. $q - 1;
5867 }
5868 17 my $det_r = _det_lu(\@R);
5869 17 my @label = @{ $ds->{term_labels} };
5870 17 my @term_vars = map { [ _formula_vars($_, $data) ] } @label;
5871 17 (my $rhs = $formula) =~ s/\A[^~]*~//;
5872 17 my @predictors = _formula_vars($rhs, $data);
5873 17 my @all_cols = 0 .. $q - 1;
5874 17 my (%row, $table);
5875 17 for my $pred (@predictors) {
5876 48 my @which = grep { my $v = $term_vars[$_]; scalar grep { $_ eq $pred } @$v } 0 .. $#label;
5877 48 my (%seen, @related);
5878 48 ▶ for my $part (split /:/, join ':', @label[@which]) { push @related, $part unless $seen{$part}++ }
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$part}++ 73 23 96
5879 48 my %rel = map { $_ => 1 } @related;
5880 48 my @unrelated = grep { !$rel{$_} } @predictors;
5881 48 my ($gvif, @columns);
5882 48 ▶ if (@unrelated) {
Branch: 1 branch
BranchTrueFalseTotal
if (@unrelated) { } 45 3 48
5883 45 my %un = map { $_ => 1 } @unrelated;
5884 72 my %drop = map { $_ + 1 => 1 }
5885 45 grep { my $v = $term_vars[$_]; scalar grep { $un{$_} } @$v } 0 .. $#label;
5886 45 @columns = grep { !$drop{ $ds->{assign}[$_] } } @all_cols;
5887 45 my %in = map { $_ => 1 } @columns;
5888 45 my @out = grep { !$in{$_} } @all_cols;
5889 # R[-columns, -columns] with no columns is empty, not everything
5890 45 ▶ @out = () unless @columns;
Branch: 1 branch
BranchTrueFalseTotal
unless @columns 1 44 45
5891 87 $gvif = _det_lu([ map { my $i = $_; [ @{ $R[$i] }[@columns] ] } @columns ])
5892 45 * _det_lu([ map { my $i = $_; [ @{ $R[$i] }[@out] ] } @out ]);
5893 45 ▶ $gvif = $det_r == 0 ? 9**9**9 / 9**9**9 : $gvif / $det_r;
Branch: 1 branch
BranchTrueFalseTotal
$det_r == 0 ? : 0 45 45
5894 } else {
5895 3 @columns = @all_cols;
5896 3 $gvif = 1;
5897 }
5898 48 my $p = @columns;
5899 48 ▶ my $root = $p == 0 ? ($gvif > 1 ? 9**9**9 : $gvif == 1 ? 1 : 0) : $gvif ** (1 / (2 * $p));
Branch: 3 branches
BranchTrueFalseTotal
$p == 0 ? : 1 47 48
$gvif > 1 ? : 1 0 1
$gvif == 1 ? : 0 0 0
5900 48 my @rest = @related[1 .. $#related];
5901 48 ▶ $row{$pred} = {
Branch: 2 branches
BranchTrueFalseTotal
@rest ? : 25 23 48
@unrelated ? : 45 3 48
5902 GVIF => $gvif,
5903 Df => $p,
5904 'GVIF^(1/(2*Df))' => $root,
5905 'Interacts With' => @rest ? join(', ', @rest) : '-- ',
5906 'Other Predictors' => @unrelated ? join(', ', @unrelated) : '-- ',
5907 };
5908 48 ▶ $table = 1 if $p != 1;
Branch: 1 branch
BranchTrueFalseTotal
if $p != 1 25 23 48
5909 }
5910 17 ▶ warn 'vif: ' . ($table ? 'GVIFs' : 'VIFs') . " computed for predictors\n";
Branch: 1 branch
BranchTrueFalseTotal
$table ? : 13 4 17
5911 17 ▶ return $table ? \%row : { map { $_ => $row{$_}{GVIF} } keys %row };
Branch: 1 branch
BranchTrueFalseTotal
$table ? : 13 4 17
5912 }
5913  
5914 # hosmer_lemeshow(\@observed, \@predicted, g => 10)
5915 #
5916 # Hosmer-Lemeshow goodness-of-fit test for a logistic model, ported from
5917 # ResourceSelection 0.3-6's hoslem.test() (R/hoslem.test.R):
5918 #
5919 # qq <- unique(quantile(yhat, probs = seq(0, 1, 1/g)))
5920 # cutyhat <- cut(yhat, breaks = qq, include.lowest = TRUE)
5921 # chisq <- sum((observed - expected)^2/expected)
5922 # G <- length(unique(cutyhat)); df = G - 2
5923 #
5924 # Up to 0.3217 the breaks were not made unique, so a prediction tied at the
5925 # lowest break -- every prediction from a model with only categorical
5926 # predictors -- was a group of its own rather than part of the first one; and
5927 # df was g - 2 where 0.3-6 has G - 2, the number of groups that hold a row.
5928 #
5929 # Two departures from 0.3-6, both where it has no usable answer:
5930 # * an empty bin, which cut() makes when two breaks fall in the gap between
5931 # the same two sorted predictions, is left out rather than added as 0/0,
5932 # which made R's statistic NaN; a bin whose expected count is 0 and whose
5933 # observed count is also 0 adds 0 for the same reason.
5934 # * the last break is the largest prediction. seq(0, 1, 1/g) ends at
5935 # 1 - 2^-53 rather than 1 for some g (49 is the first), and the last
5936 # quantile then falls below the largest prediction, which cut() leaves out of
5937 # every bin: at g = 49 the package's own example bins 499 of 500 rows and,
5938 # counting the NA as a group, reports df 48.
5939 62 ▶sub hosmer_lemeshow {
Subroutine hosmer_lemeshow: called CC=29 SCAR=33.7
Pod documented
5940 62 my ($obs, $pred, @opt) = @_;
5941 62 ▶ _usage_error('hosmer_lemeshow', 'observed and predicted must be array references')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $obs eq "ARRAY" and ref $pred eq "ARRAY" 6 56 62
Condition100%3/3
ref $obs eq "ARRAY" and ref $pred eq "ARRAY"
!ll&&!rl&&r
4256
MC/DC100%2/2
ref $obs eq "ARRAY" and ref $pred eq "ARRAY"
ref $obs eq "ARRAY" ref $pred eq "ARRAY"
Truth table100%3/3
A and B
A= ref $obs eq "ARRAY"B= ref $pred eq "ARRAY"
ABresult
0X0
100
111
5942 unless ref $obs eq 'ARRAY' && ref $pred eq 'ARRAY';
5943 # checked before the hash is built, which an odd list makes die with perl's
5944 # own "Odd number of elements" instead
5945 56 ▶ _usage_error('hosmer_lemeshow', 'options after the two arrays must be name => value pairs')
Branch: 1 branch
BranchTrueFalseTotal
if @opt % 2 1 55 56
5946 if @opt % 2;
5947 55 my %opt = @opt;
5948 55 ▶ die "hosmer_lemeshow: observed and predicted must have the same length\n"
Branch: 1 branch
BranchTrueFalseTotal
unless @$obs == @$pred 2 53 55
5949 unless @$obs == @$pred;
5950 53 ▶ my $g = defined $opt{g} ? $opt{g} : 10;
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'g'} ? : 52 1 53
5951 53 ▶ _usage_error('hosmer_lemeshow', 'g must be an integer of at least 3')
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($g) and $g == int $g and $g >= 3 5 48 53
Condition100%6/6
&looks_like_number($g) and $g == int $g and $g >= 3
!ll&&!rl&&r
2348
&looks_like_number($g) and $g == int $g
!ll&&!rl&&r
1151
MC/DC100%3/3
&looks_like_number($g) and $g == int $g and $g >= 3
&looks_like_number($g) $g == int $g $g >= 3
Truth table100%4/4
A and B and C
A= &looks_like_number($g)B= $g == int $gC= $g >= 3
ABCresult
0XX0
10X0
1100
1111
5952 unless looks_like_number($g) && $g == int $g && $g >= 3;
5953  
5954 48 my (@y, @p);
5955 48 for my $i (0 .. $#$obs) {
5956 9954 ▶ next unless defined $obs->[$i] && defined $pred->[$i]
Branch: 1 branch
BranchTrueFalseTotal
unless defined $obs->[$i] and defined $pred->[$i] and &looks_like_number($obs->[$i]) and &looks_like_number($pred->[$i]) 4 9950 9954
Condition100%9/9
defined $obs->[$i] and defined $pred->[$i] and &looks_like_number($obs->[$i]) and &looks_like_number($pred->[$i])
!ll&&!rl&&r
319950
defined $obs->[$i] and defined $pred->[$i] and &looks_like_number($obs->[$i])
!ll&&!rl&&r
219951
defined $obs->[$i] and defined $pred->[$i]
!ll&&!rl&&r
119952
MC/DC100%4/4
defined $obs->[$i] and defined $pred->[$i] and &looks_like_number($obs->[$i]) and &looks_like_number($pred->[$i])
defined $obs->[$i] defined $pred->[$i] &looks_like_number($obs->[$i]) &looks_like_number($pred->[$i])
Truth table100%5/5
A and B and C and D
A= defined $obs->[$i]B= defined $pred->[$i]C= &looks_like_number($obs->[$i])D= &looks_like_number($pred->[$i])
ABCDresult
0XXX0
10XX0
110X0
11100
11111
5957 && looks_like_number($obs->[$i]) && looks_like_number($pred->[$i]);
5958 9950 push @y, $obs->[$i] + 0;
5959 9950 push @p, $pred->[$i] + 0;
5960 }
5961 48 my $n = scalar @y;
5962 48 ▶ die "hosmer_lemeshow: not enough complete observations for g=$g groups\n" if $n < $g;
Branch: 1 branch
BranchTrueFalseTotal
if $n < $g 1 47 48
5963  
5964 47 my @sorted = sort { $a <=> $b } @p;
5965 # seq(0, 1, 1/g) is (0:g) * (1/g) in R, not (0:g) / g; the two differ in
5966 # the last bit for some k, and with it which side of a tie a break lands on.
5967 47 my $step = 1 / $g;
5968 780 my @br = sort { $a <=> $b }
5969 47 ( map( { _quantile7(\@sorted, $_ * $step) } 0 .. $g - 1 ), $sorted[-1] );
5970 47 my @qq = ($br[0]);
5971 47 ▶ for my $b (@br[1 .. $#br]) { push @qq, $b if $b != $qq[-1] }
Branch: 1 branch
BranchTrueFalseTotal
if $b != $qq[-1] 408 85 493
5972 47 ▶ die "hosmer_lemeshow: every prediction is $qq[0], so there is only one group\n"
Branch: 1 branch
BranchTrueFalseTotal
if @qq < 2 1 46 47
5973 if @qq < 2;
5974  
5975 46 my $nbin = $#qq;
5976 46 my (@O1, @O0, @E1, @E0, @ng);
5977 46 $O1[$_] = $O0[$_] = $E1[$_] = $E0[$_] = $ng[$_] = 0 for 0 .. $nbin - 1;
5978 46 for my $i (0 .. $n - 1) {
5979 # cut(..., include.lowest = TRUE): bin 0 is [qq0, qq1], bin k is
5980 # (qq_k, qq_k+1]. A binary search for the first break >= the
5981 # prediction, as R's .bincode() does.
5982 9926 my ($lo, $hi) = (0, $nbin);
5983 9926 ▶ while ($hi - $lo > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hi - $lo > 1) 34827 9926 44753
5984 34827 my $mid = ($lo + $hi) >> 1;
5985 34827 ▶ if ($p[$i] > $qq[$mid]) { $lo = $mid } else { $hi = $mid }
Branch: 1 branch
BranchTrueFalseTotal
if ($p[$i] > $qq[$mid]) { } 18716 16111 34827
5986 }
5987 9926 $O1[$lo] += $y[$i];
5988 9926 $O0[$lo] += 1 - $y[$i];
5989 9926 $E1[$lo] += $p[$i];
5990 9926 $E0[$lo] += 1 - $p[$i];
5991 9926 $ng[$lo]++;
5992 }
5993  
5994 46 my ($chi, $used) = (0, 0);
5995 46 my @groups;
5996 46 for my $j (0 .. $nbin - 1) {
5997 408 ▶ next unless $ng[$j];
Branch: 1 branch
BranchTrueFalseTotal
unless $ng[$j] 1 407 408
5998 407 $used++;
5999 407 for my $oe ([ $O1[$j], $E1[$j] ], [ $O0[$j], $E0[$j] ]) {
6000 814 my ($o, $e) = @$oe;
6001 814 ▶ $chi += $e ? ($o - $e) ** 2 / $e : $o ? 9**9**9 : 0;
Branch: 2 branches
BranchTrueFalseTotal
$e ? : 810 4 814
$o ? : 1 3 4
6002 }
6003 407 push @groups, { n => $ng[$j], observed => $O1[$j], expected => $E1[$j] };
6004 }
6005 46 ▶ die "hosmer_lemeshow: the predictions allow only one group\n" if $used < 2;
Branch: 1 branch
BranchTrueFalseTotal
if $used < 2 3 43 46
6006 43 ▶ warn "hosmer_lemeshow: the data allowed $used of the $g groups requested\n"
Branch: 1 branch
BranchTrueFalseTotal
if $used < $g 21 22 43
6007 if $used < $g;
6008 43 my $df = $used - 2;
6009 return {
6010 43 statistic => $chi,
6011 parameter => $df,
6012 # not _pchisq_upper(), which is NaN at an infinite statistic and 1 at
6013 # df 0, where R's 1 - pchisq(chisq, 0) is 0 for any chisq > 0
6014 'p_value' => pchisq($chi, $df, lower => 0),
6015 groups => $used,
6016 table => \@groups,
6017 };
6018 }
6019  
6020 # _qgamma($p, $shape, $scale): quantile of the gamma distribution, found by
6021 # inverting the regularized lower incomplete gamma P(shape, x) = p (bisection).
6022 #
6023 # The bisection compares against _pgamma_lower, which is the XS igam() and
6024 # computes the lower tail directly. It used to form that tail as
6025 # `1 - _igamc($shape, $x)`, and subtracting from 1 is precisely the
6026 # cancellation igam() was added to avoid: below a lower tail of about
6027 # NV_EPSILON the difference can only be a multiple of NV_EPSILON, so every
6028 # candidate the bisection tried compared equal and the search converged on
6029 # noise. age_standardize() reaches this with p = alpha/2, so it is the lower
6030 # confidence limit at a high conf_level that was affected -- conf_level =>
6031 # 0.9999 asks for the 5e-5 quantile, and 1 - _igamc could not resolve one.
6032 24 ▶sub _qgamma {
Subroutine _qgamma: called CC=12 SCAR=26.4
6033 24 my ($p, $shape, $scale) = @_;
6034 24 ▶ $scale = 1 unless defined $scale;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $scale 0 24 24
6035 24 ▶ return 0 if $p <= 0 || $shape <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $p <= 0 or $shape <= 0 0 24 24
Condition33%1/3
$p <= 0 or $shape <= 0
l!l&&r!l&&!r
0024
MC/DC0%0/2
$p <= 0 or $shape <= 0
$p <= 0 $shape <= 0
Truth table33%1/3
A or B
A= $p <= 0B= $shape <= 0
ABresult
1X1
011
000
6036 24 ▶ return 9**9**9 if $p >= 1;
Branch: 1 branch
BranchTrueFalseTotal
if $p >= 1 0 24 24
6037 24 my ($lo, $hi) = (0, 1);
6038 24 ▶ $hi *= 2 while _pgamma_lower($shape, $hi) < $p && $hi < 1e15;
Branch: 1 branch
BranchTrueFalseTotal
_pgamma_lower($shape, $hi) < $p and $hi < "1e+15" and do { $hi *= 2 } 180 24 204
Condition66%2/3
_pgamma_lower($shape, $hi) < $p and $hi < "1e+15"
!ll&&!rl&&r
240180
MC/DC50%1/2
_pgamma_lower($shape, $hi) < $p and $hi < "1e+15"
_pgamma_lower($shape, $hi) < $p $hi < "1e+15"
Truth table66%2/3
A and B
A= _pgamma_lower($shape, $hi) < $pB= $hi < "1e+15"
ABresult
0X0
100
111
6039 24 for (1 .. 300) {
6040 984 my $mid = ($lo + $hi) / 2;
6041 984 ▶ last if $mid <= $lo || $mid >= $hi; # adjacent NVs: nothing left
Branch: 1 branch
BranchTrueFalseTotal
if $mid <= $lo or $mid >= $hi 0 984 984
Condition33%1/3
$mid <= $lo or $mid >= $hi
l!l&&r!l&&!r
00984
MC/DC0%0/2
$mid <= $lo or $mid >= $hi
$mid <= $lo $mid >= $hi
Truth table33%1/3
A or B
A= $mid <= $loB= $mid >= $hi
ABresult
1X1
011
000
6042 984 ▶ if (_pgamma_lower($shape, $mid) < $p) { $lo = $mid } else { $hi = $mid }
Branch: 1 branch
BranchTrueFalseTotal
if (_pgamma_lower($shape, $mid) < $p) { } 478 506 984
6043 984 ▶ last if ($hi - $lo) <= 1e-12 * ($hi + 1e-300);
Branch: 1 branch
BranchTrueFalseTotal
if $hi - $lo <= "1e-12" * ($hi + "1e-300") 24 960 984
6044 }
6045 24 return $scale * ($lo + $hi) / 2;
6046 }
6047  
6048 # age_standardize(\@count, \@pop, \@stdpop, conf_level => 0.95, per => 1)
6049 # or age_standardize(count => \@c, pop => \@n, stdpop => \@w, ...)
6050 # (supply rate => \@r instead of count if you have stratum-specific rates)
6051 #
6052 # Directly standardized rate: reweights stratum-specific rates to a standard
6053 # population. The confidence interval uses the Fay-Feuer gamma method (as in
6054 # R's epitools::ageadjust.direct), which is accurate even for rare events.
6055 # `per` scales every reported rate (e.g. per => 100_000). Validated against R.
6056 20 ▶sub age_standardize {
Subroutine age_standardize: called CC=29 SCAR=35.0
Pod documented
6057 20 my @a = @_;
6058 20 my (%opt, $count, $pop, $stdpop, $rate);
6059 20 my $positional = ref $a[0] eq 'ARRAY'; # else every argument is named
6060 20 ▶ ($count, $pop, $stdpop) = splice(@a, 0, 3) if $positional;
Branch: 1 branch
BranchTrueFalseTotal
if $positional 14 6 20
6061 20 ▶ _usage_error('age_standardize', 'arguments must be name => value pairs, after any '
Branch: 1 branch
BranchTrueFalseTotal
if @a % 2 3 17 20
6062 . 'positional count, pop and stdpop') if @a % 2;
6063 17 _opt_names_defined('age_standardize', @a);
6064 17 %opt = @a;
6065 17 ▶ ($count, $pop, $stdpop, $rate) = @opt{qw(count pop stdpop rate)} unless $positional;
Branch: 1 branch
BranchTrueFalseTotal
unless $positional 4 13 17
6066 17 my %known = map { $_ => 1 } qw(count pop stdpop rate per conf_level);
6067 17 my @bad = sort grep { !$known{$_} } keys %opt;
6068 17 ▶ _usage_error('age_standardize', "unknown argument(s): @bad") if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 16 17
6069 16 ▶ $rate ||= $opt{rate};
Condition66%2/3
$rate ||= $opt{"rate"}
l!l&&r!l&&!r
1015
MC/DC50%1/2
$rate ||= $opt{"rate"}
$rate $opt{"rate"}
Truth table66%2/3
A ||= B
A= $rateB= $opt{"rate"}
ABresult
1X1
011
000
6070 16 ▶ my $cl = defined $opt{conf_level} ? $opt{conf_level} : 0.95;
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'conf_level'} ? : 9 7 16
6071 16 ▶ my $per = defined $opt{per} ? $opt{per} : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'per'} ? : 1 15 16
6072 16 ▶ _usage_error('age_standardize', 'conf_level must be between 0 and 1') unless $cl > 0 && $cl < 1;
Branch: 1 branch
BranchTrueFalseTotal
unless $cl > 0 and $cl < 1 1 15 16
Condition66%2/3
$cl > 0 and $cl < 1
!ll&&!rl&&r
0115
MC/DC50%1/2
$cl > 0 and $cl < 1
$cl > 0 $cl < 1
Truth table66%2/3
A and B
A= $cl > 0B= $cl < 1
ABresult
0X0
100
111
6073 15 ▶ _usage_error('age_standardize', "'pop' and 'stdpop' array refs are required")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pop eq "ARRAY" and ref $stdpop eq "ARRAY" 1 14 15
Condition66%2/3
ref $pop eq "ARRAY" and ref $stdpop eq "ARRAY"
!ll&&!rl&&r
1014
MC/DC50%1/2
ref $pop eq "ARRAY" and ref $stdpop eq "ARRAY"
ref $pop eq "ARRAY" ref $stdpop eq "ARRAY"
Truth table66%2/3
A and B
A= ref $pop eq "ARRAY"B= ref $stdpop eq "ARRAY"
ABresult
0X0
100
111
6074 unless ref $pop eq 'ARRAY' && ref $stdpop eq 'ARRAY';
6075 14 ▶ _usage_error('age_standardize', "supply either 'count' or 'rate'")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $count eq "ARRAY" or ref $rate eq "ARRAY" 1 13 14
Condition100%3/3
ref $count eq "ARRAY" or ref $rate eq "ARRAY"
l!l&&r!l&&!r
1211
MC/DC100%2/2
ref $count eq "ARRAY" or ref $rate eq "ARRAY"
ref $count eq "ARRAY" ref $rate eq "ARRAY"
Truth table100%3/3
A or B
A= ref $count eq "ARRAY"B= ref $rate eq "ARRAY"
ABresult
1X1
011
000
6076 unless ref $count eq 'ARRAY' || ref $rate eq 'ARRAY';
6077  
6078 13 my $k = scalar @$pop;
6079 13 ▶ die "age_standardize: pop and stdpop must have the same length\n" unless @$stdpop == $k;
Branch: 1 branch
BranchTrueFalseTotal
unless @$stdpop == $k 1 12 13
6080 12 ▶ if (ref $count eq 'ARRAY') { die "age_standardize: count and pop length mismatch\n" unless @$count == $k; }
Branch: 2 branches
BranchTrueFalseTotal
if (ref $count eq 'ARRAY') { } 11 1 12
unless @$count == $k 0 11 11
6081 1 ▶ else { die "age_standardize: rate and pop length mismatch\n" unless @$rate == $k; }
Branch: 1 branch
BranchTrueFalseTotal
unless @$rate == $k 0 1 1
6082  
6083 12 ▶ my @cnt = ref $count eq 'ARRAY' ? @$count : map { $rate->[$_] * $pop->[$_] } 0 .. $k - 1;
Branch: 1 branch
BranchTrueFalseTotal
ref $count eq 'ARRAY' ? : 11 1 12
6084 12 my ($sum_c, $sum_n, $sum_w) = (0, 0, 0);
6085 12 $sum_c += $cnt[$_], $sum_n += $pop->[$_], $sum_w += $stdpop->[$_] for 0 .. $k - 1;
6086 12 ▶ die "age_standardize: total population and standard population must be positive\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $sum_n > 0 and $sum_w > 0 0 12 12
Condition33%1/3
$sum_n > 0 and $sum_w > 0
!ll&&!rl&&r
0012
MC/DC0%0/2
$sum_n > 0 and $sum_w > 0
$sum_n > 0 $sum_w > 0
Truth table33%1/3
A and B
A= $sum_n > 0B= $sum_w > 0
ABresult
0X0
100
111
6087 unless $sum_n > 0 && $sum_w > 0;
6088  
6089 12 my ($dsr, $var, $wmax) = (0, 0, 0);
6090 12 for my $i (0 .. $k - 1) {
6091 48 ▶ die "age_standardize: stratum $i has non-positive population\n" if $pop->[$i] <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $pop->[$i] <= 0 0 48 48
6092 48 my $r = $cnt[$i] / $pop->[$i];
6093 48 my $wt = $stdpop->[$i] / $sum_w; # normalized weight
6094 48 $dsr += $wt * $r;
6095 48 $var += $wt * $wt * $cnt[$i] / ($pop->[$i] ** 2);
6096 48 my $w_over_n = $wt / $pop->[$i];
6097 48 ▶ $wmax = $w_over_n if $w_over_n > $wmax;
Branch: 1 branch
BranchTrueFalseTotal
if $w_over_n > $wmax 12 36 48
6098 }
6099 12 my $crude = $sum_c / $sum_n;
6100  
6101 12 my $alpha = 1 - $cl;
6102 12 my ($lci, $uci);
6103 12 ▶ if ($dsr > 0 && $var > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dsr > 0 and $var > 0) { } 12 0 12
Condition33%1/3
$dsr > 0 and $var > 0
!ll&&!rl&&r
0012
MC/DC0%0/2
$dsr > 0 and $var > 0
$dsr > 0 $var > 0
Truth table33%1/3
A and B
A= $dsr > 0B= $var > 0
ABresult
0X0
100
111
6104 12 $lci = _qgamma($alpha / 2, ($dsr ** 2) / $var, $var / $dsr);
6105 12 $uci = _qgamma(1 - $alpha / 2, (($dsr + $wmax) ** 2) / ($var + $wmax ** 2),
6106 ($var + $wmax ** 2) / ($dsr + $wmax));
6107 } else {
6108 0 $lci = 0;
6109 0 ▶ $uci = ($dsr == 0) ? _qgamma(1 - $alpha / 2, 1, $wmax > 0 ? $wmax : 0) : $dsr;
Branch: 2 branches
BranchTrueFalseTotal
$dsr == 0 ? : 0 0 0
$wmax > 0 ? : 0 0 0
6110 }
6111  
6112 return {
6113 12 crude_rate => $crude * $per,
6114 adj_rate => $dsr * $per,
6115 'conf_int' => [ $lci * $per, $uci * $per ],
6116 se => sqrt($var) * $per,
6117 'conf_level' => $cl,
6118 per => $per,
6119 };
6120 }
6121  
6122  
6123 # anova($fit0, $fit1, ..., test => 'Chisq' | 'LRT' | 'F', dispersion => $phi)
6124 #
6125 # Nested-model comparison on fits that already exist -- R's anova(m0, m1) --
6126 # for lm() and glm() results, and MASS's likelihood-ratio table for
6127 # negative-binomial fits whose theta was estimated. The XS anova() compares
6128 # models it fits itself from a data set and formulas; this is the same
6129 # question asked of fits the caller already has, which is what a first-stage
6130 # F on excluded instruments or a joint test of a block of terms needs. Any
6131 # call whose first argument is not a fitted model goes to the XS function
6132 # unchanged.
6133 #
6134 # The arithmetic is R's: anova.lmlist() for lm, anova.glmlist() and
6135 # stat.anova() for glm, anova.negbin() for glm.nb. Rows come back in the
6136 # order given (MASS's negbin table is sorted by residual df, as it sorts it),
6137 # each a hash; every row after the first carries the comparison with the row
6138 # before it.
6139 {
6140 508 my $xs_anova = \&anova;
6141 # The XS anova() is prototyped ($@), which would put anova(@fits) in
6142 # scalar context and hand it the number of fits; the replacement has no
6143 # prototype, which changes nothing for the XS call forms.
6144 508 ▶ no warnings qw(redefine prototype);
Subroutine BEGIN: called CC=1 SCAR=0.0
6145 253 ▶ *anova = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
6146 253 ▶ return _anova_fits(@_) if @_ && _is_fit($_[0]);
Branch: 1 branch
BranchTrueFalseTotal
if @_ and _is_fit($_[0]) 21 232 253
Condition100%3/3
@_ and _is_fit($_[0])
!ll&&!rl&&r
123121
MC/DC100%2/2
@_ and _is_fit($_[0])
@_ _is_fit($_[0])
Truth table100%3/3
A and B
A= @_B= _is_fit($_[0])
ABresult
0X0
100
111
6147 232 goto &$xs_anova;
6148 508 };
6149 }
6150  
6151 317 ▶sub _is_fit {
Subroutine _is_fit: called CC=6 SCAR=18.7
6152 317 my $f = shift;
6153 return ref $f eq 'HASH' && exists $f->{coefficients} && exists $f->{'df_residual'}
6154 317 ▶ && !ref $f->{'df_residual'} && (exists $f->{rss} || exists $f->{deviance});
Condition73%11/15
ref $f eq 'HASH' && exists $f->{'coefficients'} && exists $f->{'df_residual'} && !ref($f->{'df_residual'}) && (exists $f->{'rss'} || exists $f->{'deviance'})
!ll&&!rl&&r
243074
ref $f eq "HASH" and exists $f->{"coefficients"} and exists $f->{"df_residual"} and not ref $f->{"df_residual"}
!ll&&!rl&&r
243074
ref $f eq "HASH" and exists $f->{"coefficients"} and exists $f->{"df_residual"}
!ll&&!rl&&r
243074
ref $f eq "HASH" and exists $f->{"coefficients"}
!ll&&!rl&&r
1822574
exists $f->{"rss"} or exists $f->{"deviance"}
l!l&&r!l&&!r
30440
MC/DC33%2/6
ref $f eq 'HASH' && exists $f->{'coefficients'} && exists $f->{'df_residual'} && !ref($f->{'df_residual'}) && (exists $f->{'rss'} || exists $f->{'deviance'})
ref $f eq "HASH" exists $f->{"coefficients"} exists $f->{"df_residual"} not ref $f->{"df_residual"} exists $f->{"rss"} exists $f->{"deviance"}
Truth table57%4/7
A and B and C and not(D) && E or F
A= ref $f eq "HASH"B= exists $f->{"coefficients"}C= exists $f->{"df_residual"}D= not ref $f->{"df_residual"}E= exists $f->{"rss"}F= exists $f->{"deviance"}
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
1111000
11111X1
1111011
6155 }
6156  
6157 21 ▶sub _anova_fits {
Subroutine _anova_fits: called CC=52 SCAR=40.7
6158 21 my @m;
6159 21 ▶ push @m, shift while @_ && _is_fit($_[0]);
Branch: 1 branch
BranchTrueFalseTotal
@_ and _is_fit($_[0]) and do { push @m, shift() } 53 21 74
Condition100%3/3
@_ and _is_fit($_[0])
!ll&&!rl&&r
91253
MC/DC100%2/2
@_ and _is_fit($_[0])
@_ _is_fit($_[0])
Truth table100%3/3
A and B
A= @_B= _is_fit($_[0])
ABresult
0X0
100
111
6160 21 ▶ _usage_error('anova', 'options after the models must be name => value pairs') if @_ % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 0 21 21
6161 21 my %opt = @_;
6162 21 for (sort keys %opt) {
6163 12 ▶ _usage_error('anova', "unknown argument '$_'") unless /^(?:test|dispersion)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless /^(?:test|dispersion)$/ 1 11 12
6164 }
6165 20 ▶ _usage_error('anova', 'give at least two fitted models to compare') if @m < 2;
Branch: 1 branch
BranchTrueFalseTotal
if @m < 2 1 19 20
6166 19 my $is_glm = exists $m[0]{family};
6167 19 for (@m) {
6168 die "anova: cannot compare lm() and glm() fits in one table\n"
6169 50 ▶ if (exists $_->{family}) != $is_glm;
Branch: 1 branch
BranchTrueFalseTotal
if exists $_->{"family"} != $is_glm 1 49 50
6170 die "anova: models are not all of the same family\n"
6171 49 ▶ if $is_glm && $_->{family} ne $m[0]{family};
Branch: 1 branch
BranchTrueFalseTotal
if $is_glm and $_->{"family"} ne $m[0]{"family"} 1 48 49
Condition100%3/3
$is_glm and $_->{"family"} ne $m[0]{"family"}
!ll&&!rl&&r
23251
MC/DC100%2/2
$is_glm and $_->{"family"} ne $m[0]{"family"}
$is_glm $_->{"family"} ne $m[0]{"family"}
Truth table100%3/3
A and B
A= $is_glmB= $_->{"family"} ne $m[0]{"family"}
ABresult
0X0
100
111
6172 }
6173 # anova.lmlist / anova.glmlist: "models were not all fitted to the same
6174 # size of dataset"
6175 17 ▶ my @n = map { $is_glm ? $_->{nobs} : $_->{'df_residual'} + $_->{rank} } @m;
Branch: 1 branch
BranchTrueFalseTotal
$is_glm ? : 23 23 46
6176 17 for (@n) {
6177 46 ▶ die "anova: models were not all fitted to the same size of dataset\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ and $_ == $n[0] 1 45 46
Condition66%2/3
defined $_ and $_ == $n[0]
!ll&&!rl&&r
0145
MC/DC50%1/2
defined $_ and $_ == $n[0]
defined $_ $_ == $n[0]
Truth table66%2/3
A and B
A= defined $_B= $_ == $n[0]
ABresult
0X0
100
111
6178 unless defined $_ && $_ == $n[0];
6179 }
6180 16 ▶ my $fam = $is_glm ? $m[0]{family} : 'lm';
Branch: 1 branch
BranchTrueFalseTotal
$is_glm ? : 10 6 16
6181 16 ▶ $fam = 'negbin' if $fam eq 'negative.binomial' || $fam eq 'nb';
Branch: 1 branch
BranchTrueFalseTotal
if $fam eq "negative.binomial" or $fam eq "nb" 0 16 16
Condition33%1/3
$fam eq "negative.binomial" or $fam eq "nb"
l!l&&r!l&&!r
0016
MC/DC0%0/2
$fam eq "negative.binomial" or $fam eq "nb"
$fam eq "negative.binomial" $fam eq "nb"
Truth table33%1/3
A or B
A= $fam eq "negative.binomial"B= $fam eq "nb"
ABresult
1X1
011
000
6182 16 ▶ if ($fam eq 'negbin' && !grep { !exists $_->{'SE_theta'} } @m) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fam eq "negbin" and not grep({not exists $_->{"SE_theta"};} @m)) 3 13 16
Condition66%2/3
$fam eq "negbin" and not grep({not exists $_->{"SE_theta"};} @m)
!ll&&!rl&&r
1303
MC/DC50%1/2
$fam eq "negbin" and not grep({not exists $_->{"SE_theta"};} @m)
$fam eq "negbin" not grep({not exists $_->{"SE_theta"};} @m)
Truth table66%2/3
A and not(B)
A= $fam eq "negbin"B= not grep({not exists $_->{"SE_theta"};} @m)
ABresult
0X0
100
111
6183 # MASS anova.negbin(): theta was estimated in every model, so the
6184 # models differ in theta too and only the likelihood-ratio test is
6185 # valid. MASS sorts by residual df, largest first.
6186 die "anova: negbin models are compared by the likelihood-ratio test only\n"
6187 3 ▶ if defined $opt{test} && $opt{test} !~ /^(?:Chisq|LRT)$/;
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{"test"} and not $opt{"test"} =~ /^(?:Chisq|LRT)$/ 1 2 3
Condition66%2/3
defined $opt{"test"} and not $opt{"test"} =~ /^(?:Chisq|LRT)$/
!ll&&!rl&&r
201
MC/DC50%1/2
defined $opt{"test"} and not $opt{"test"} =~ /^(?:Chisq|LRT)$/
defined $opt{"test"} not $opt{"test"} =~ /^(?:Chisq|LRT)$/
Truth table66%2/3
A and not(B)
A= defined $opt{"test"}B= not $opt{"test"} =~ /^(?:Chisq|LRT)$/
ABresult
0X0
100
111
6188 2 my @o = sort { $b->{'df_residual'} <=> $a->{'df_residual'} } @m;
6189 2 my @rows;
6190 2 for my $i (0 .. $#o) {
6191 my %r = (theta => $o[$i]{theta}, 'Resid. df' => $o[$i]{'df_residual'},
6192 4 '2 x log-lik.' => $o[$i]{twologlik});
6193 4 ▶ if ($i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i) 2 2 4
6194 2 my $df = $o[$i - 1]{'df_residual'} - $o[$i]{'df_residual'};
6195 2 my $lr = $o[$i]{twologlik} - $o[$i - 1]{twologlik};
6196 2 $r{df} = $df;
6197 2 $r{'LR stat.'} = $lr;
6198 # MASS: 1 - pchisq(x2, df); the upper tail directly here
6199 2 $r{'Pr(Chi)'} = pchisq($lr, $df, lower => 0);
6200 }
6201 4 push @rows, \%r;
6202 }
6203 2 return \@rows;
6204 }
6205 13 my @resdf = map { $_->{'df_residual'} } @m;
6206 13 ▶ my @resdev = map { $is_glm ? $_->{deviance} : $_->{rss} } @m;
Branch: 1 branch
BranchTrueFalseTotal
$is_glm ? : 15 23 38
6207 13 my ($big) = sort { $resdf[$a] <=> $resdf[$b] } 0 .. $#m; # order(resdf)[1]
6208 13 my ($test, $scale, $df_scale);
6209 13 ▶ if (!$is_glm) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $is_glm) { } 6 7 13
6210 # anova.lmlist: an F test on the largest model's residual mean square
6211 6 ▶ $test = defined $opt{test} ? $opt{test} : 'F';
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'test'} ? : 5 1 6
6212 6 ▶ $scale = defined $opt{dispersion} ? $opt{dispersion} : $resdev[$big] / $resdf[$big];
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'dispersion'} ? : 0 6 6
6213 6 $df_scale = $resdf[$big];
6214 } else {
6215 # anova.glmlist: family$dispersion is 1 for binomial and poisson and
6216 # NA for gaussian; a negbin at a fixed theta has its variance fully
6217 # specified, and is treated like poisson (see glm's dispersion).
6218 7 my $known = $fam ne 'gaussian';
6219 7 ▶ $test = defined $opt{test} ? $opt{test} : ($known ? 'Chisq' : 'F');
Branch: 2 branches
BranchTrueFalseTotal
defined $opt{'test'} ? : 5 2 7
$known ? : 1 1 2
6220 7 ▶ $scale = defined $opt{dispersion} ? $opt{dispersion} : $m[$big]{dispersion};
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'dispersion'} ? : 0 7 7
6221 7 ▶ $df_scale = (defined $opt{dispersion} ? $opt{dispersion} == 1 : $known)
Branch: 2 branches
BranchTrueFalseTotal
(defined $opt{'dispersion'} ? $opt{'dispersion'} == 1 : $known) ? : 5 2 7
defined $opt{'dispersion'} ? : 0 7 7
6222 ? 9**9**9 : $resdf[$big];
6223 7 ▶ if ($test eq 'F' && $df_scale == 9**9**9) {
Branch: 1 branch
BranchTrueFalseTotal
if ($test eq "F" and $df_scale == "Inf") 1 6 7
Condition100%3/3
$test eq "F" and $df_scale == "Inf"
!ll&&!rl&&r
511
MC/DC100%2/2
$test eq "F" and $df_scale == "Inf"
$test eq "F" $df_scale == "Inf"
Truth table100%3/3
A and B
A= $test eq "F"B= $df_scale == "Inf"
ABresult
0X0
100
111
6224 1 ▶ warn(($fam eq 'binomial' || $fam eq 'poisson')
Branch: 1 branch
BranchTrueFalseTotal
$fam eq 'binomial' || $fam eq 'poisson' ? : 1 0 1
Condition33%1/3
$fam eq "binomial" or $fam eq "poisson"
l!l&&r!l&&!r
010
MC/DC0%0/2
$fam eq "binomial" or $fam eq "poisson"
$fam eq "binomial" $fam eq "poisson"
Truth table33%1/3
A or B
A= $fam eq "binomial"B= $fam eq "poisson"
ABresult
1X1
011
000
6225 ? "anova: using F test with a '$fam' family is inappropriate\n"
6226 : "anova: using F test with a fixed dispersion is inappropriate\n");
6227 }
6228 }
6229 13 ▶ _usage_error('anova', "test must be 'F', 'Chisq' or 'LRT'") unless $test =~ /^(?:F|Chisq|LRT)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $test =~ /^(?:F|Chisq|LRT)$/ 1 12 13
6230 12 my @rows;
6231 12 for my $i (0 .. $#m) {
6232 36 ▶ my %r = $is_glm ? ('Resid. Df' => $resdf[$i], 'Resid. Dev' => $resdev[$i])
Branch: 1 branch
BranchTrueFalseTotal
$is_glm ? : 13 23 36
6233 : ('Res_Df' => $resdf[$i], 'RSS' => $resdev[$i]);
6234 36 ▶ if ($i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i) 24 12 36
6235 24 my $df = $resdf[$i - 1] - $resdf[$i];
6236 24 my $dv = $resdev[$i - 1] - $resdev[$i];
6237 24 $r{Df} = $df;
6238 24 ▶ $r{ $is_glm ? 'Deviance' : 'Sum of Sq' } = $dv;
Branch: 1 branch
BranchTrueFalseTotal
$is_glm ? : 7 17 24
6239 # stat.anova(): a zero or negative statistic has no p-value (NA)
6240 24 ▶ if ($test eq 'F') {
Branch: 1 branch
BranchTrueFalseTotal
if ($test eq 'F') { } 17 7 24
6241 17 ▶ my $F = ($df != 0) ? ($dv / $df) / $scale : undef;
Branch: 1 branch
BranchTrueFalseTotal
$df != 0 ? : 17 0 17
6242 17 ▶ $F = undef if defined $F && $F < 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $F and $F < 0 0 17 17
Condition33%1/3
defined $F and $F < 0
!ll&&!rl&&r
0170
MC/DC0%0/2
defined $F and $F < 0
defined $F $F < 0
Truth table33%1/3
A and B
A= defined $FB= $F < 0
ABresult
0X0
100
111
6243 17 $r{F} = $F;
6244 17 ▶ $r{'Pr(>F)'} = defined $F
Branch: 2 branches
BranchTrueFalseTotal
defined $F ? : 17 0 17
$df_scale == 9**9**9 ? : 1 16 17
6245 ? ($df_scale == 9**9**9 ? pchisq($F * abs($df), abs($df), lower => 0)
6246 : pf($F, abs($df), $df_scale, lower => 0))
6247 : undef;
6248 } else {
6249 7 ▶ my $v = ($df != 0) ? ($dv / $scale) * ($df <=> 0) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$df != 0 ? : 7 0 7
6250 7 ▶ $v = undef if defined $v && $v < 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $v and $v < 0 0 7 7
Condition33%1/3
defined $v and $v < 0
!ll&&!rl&&r
070
MC/DC0%0/2
defined $v and $v < 0
defined $v $v < 0
Truth table33%1/3
A and B
A= defined $vB= $v < 0
ABresult
0X0
100
111
6251 7 ▶ $r{'Pr(>Chi)'} = defined $v ? pchisq($v, abs($df), lower => 0) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 7 0 7
6252 }
6253 }
6254 36 push @rows, \%r;
6255 }
6256 12 return \@rows;
6257 }
6258  
6259 # The PerlIO::via layers _open_decompressed() reads a compressed file through.
6260 # PerlIO::via calls FILL whenever the parser's sv_gets() has used up the
6261 # buffer, and FILL returns the next piece of decompressed text, or undef at
6262 # the end.
6263 #
6264 # A file may hold several compressed members one after another, and every one
6265 # of them is read: `cat a.gz b.gz' is a valid gzip file (RFC 1952 section 2.2)
6266 # holding both, bgzip -- the BGZF format of tabix and every .vcf.gz -- writes
6267 # nothing else, and pbzip2 does the same with bzip2 streams. Stopping at the
6268 # first would drop all but the first 64 KB of a bgzip file without a word. NUL
6269 # bytes between or after members are skipped, as Python's gzip module skips
6270 # them (Lib/gzip.py, _GzipReader._read_eof(): "Gzip files can be padded with
6271 # zeroes and still have archives"); anything else there is an error, as it is
6272 # in Python, rather than being passed on as text, as R's gzio.h does
6273 # ("transparent" mode).
6274 #
6275 # Each member's own check is made: zlib compares a gzip member's CRC-32 and
6276 # length against its trailer, bzip2 its block and stream CRCs, and a mismatch
6277 # comes back as corrupt data.
6278 package Stats::LikeR::_Decompress;
6279  
6280 508 our $name; # the file being opened; see _open_decompressed()
6281  
6282 # 1<<16, as a read of both the compressed bytes and the text made per call.
6283 # read_table of a 2,000,000 x 5 CSV (110 MB, 47 MB gzipped) took 1.50 s from
6284 # the .gz against 0.82 s from the plain file, three runs each; 1<<12 took
6285 # 1.66 s, 1<<14 1.60 s, and 1<<18 and 1<<20 both 1.45 s. `zcat' alone takes
6286 # 0.69 s, so the layer adds almost nothing to the inflate itself, and the last
6287 # 3% is not worth four times the buffer. The .bz2 took 4.47 s, against 3.69 s
6288 # for `bzip2 -dc' alone.
6289 508 my $BUFSIZE = 1 << 16;
6290  
6291 1438 ▶sub PUSHED {
Subroutine PUSHED: called CC=1 SCAR=0.0
6292 1438 my ($class) = @_;
6293 1438 return bless { name => $name, in => '', eof => 0, z => undef,
6294 members => 0 }, $class;
6295 }
6296  
6297 4866 ▶sub FILL {
Subroutine FILL: called CC=14 SCAR=26.4
6298 4866 my ($self, $fh) = @_;
6299 4866 my $magic = $self->MAGIC;
6300 4866 for (;;) {
6301 8246 ▶ if (!$self->{z}) { # at the start of a member, or past the last
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"z"}) 5771 2475 8246
6302 5771 ▶ $self->{in} =~ s/\A\0+// if $self->{members};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"members"} 2895 2876 5771
6303 5771 ▶ if (length $self->{in} < length($magic) && !$self->{eof}) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"in"} < length $magic and not $self->{"eof"}) 1671 4100 5771
Condition100%3/3
length $self->{"in"} < length $magic and not $self->{"eof"}
!ll&&!rl&&r
38662341671
MC/DC100%2/2
length $self->{"in"} < length $magic and not $self->{"eof"}
length $self->{"in"} < length $magic not $self->{"eof"}
Truth table100%3/3
A and not(B)
A= length $self->{"in"} < length $magicB= not $self->{"eof"}
ABresult
0X0
100
111
6304 1671 $self->_more($fh);
6305 1671 next;
6306 }
6307 4100 ▶ return undef if !length $self->{in} && $self->{members};
Branch: 1 branch
BranchTrueFalseTotal
if not length $self->{"in"} and $self->{"members"} 231 3869 4100
Condition66%2/3
not length $self->{"in"} and $self->{"members"}
!ll&&!rl&&r
38690231
MC/DC50%1/2
not length $self->{"in"} and $self->{"members"}
not length $self->{"in"} $self->{"members"}
Truth table66%2/3
not(A) and B
A= not length $self->{"in"}B= $self->{"members"}
ABresult
0X0
100
111
6308 die "read_table: \"$self->{name}\" has data after its last "
6309 . $self->CODEC . " member that is not " . $self->CODEC . "\n"
6310 3869 ▶ unless substr($self->{in}, 0, length $magic) eq $magic;
Branch: 1 branch
BranchTrueFalseTotal
unless substr($self->{"in"}, 0, length $magic) eq $magic 4 3865 3869
6311 3865 $self->{z} = $self->NEW;
6312 }
6313 6340 my $before = length $self->{in};
6314 6340 my $out = '';
6315 6340 my ($status, $ended) = $self->INFLATE($out);
6316 6340 ▶ die "read_table: \"$self->{name}\" is not valid " . $self->CODEC
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ended 3 6337 6340
6317 . " data ($status)\n" unless defined $ended;
6318 6337 ▶ if ($ended) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ended) 2760 3577 6337
6319 2760 $self->{z} = undef;
6320 2760 $self->{members}++;
6321 }
6322 6337 ▶ return $out if length $out;
Branch: 1 branch
BranchTrueFalseTotal
if length $out 3572 2765 6337
6323 2765 ▶ next if $ended || length $self->{in} != $before;
Branch: 1 branch
BranchTrueFalseTotal
if $ended or length $self->{"in"} != $before 586 2179 2765
Condition100%3/3
$ended or length $self->{"in"} != $before
l!l&&r!l&&!r
275592179
MC/DC100%2/2
$ended or length $self->{"in"} != $before
$ended length $self->{"in"} != $before
Truth table100%3/3
A or B
A= $endedB= length $self->{"in"} != $before
ABresult
1X1
011
000
6324 # no progress: the member wants more input than has been read
6325 die "read_table: \"$self->{name}\" ends in the middle of its "
6326 2179 ▶ . $self->CODEC . " data; it is truncated\n" if $self->{eof};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"eof"} 1056 1123 2179
6327 1123 $self->_more($fh);
6328 }
6329 }
6330  
6331 2794 ▶sub _more {
Subroutine _more: called CC=3 SCAR=11.0
6332 2794 my ($self, $fh) = @_;
6333 2794 my $n = read $fh, $self->{in}, $BUFSIZE, length $self->{in};
6334 2794 ▶ die "read_table: could not read \"$self->{name}\": $!\n" unless defined $n;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n 0 2794 2794
6335 2794 ▶ $self->{eof} = 1 unless $n;
Branch: 1 branch
BranchTrueFalseTotal
unless $n 1289 1505 2794
6336 2794 return;
6337 }
6338  
6339 package Stats::LikeR::_Gunzip;
6340 508 our @ISA = ('Stats::LikeR::_Decompress');
6341  
6342 591 ▶sub CODEC { 'gzip' }
Subroutine CODEC: called CC=1 SCAR=0.0
6343 3713 ▶sub MAGIC { "\x1f\x8b" }
Subroutine MAGIC: called CC=1 SCAR=0.0
6344  
6345 2893 ▶sub NEW {
Subroutine NEW: called CC=2 SCAR=7.1
6346 # WANT_GZIP: a gzip wrapper, header and trailer, around each deflate
6347 # stream. LimitOutput caps what one call makes at about Bufsize, so one
6348 # 64 KB read of a highly compressible member cannot inflate into hundreds
6349 # of megabytes at once.
6350 2893 my ($z, $err) = Compress::Raw::Zlib::Inflate->new(
6351 -WindowBits => Compress::Raw::Zlib::WANT_GZIP(),
6352 -Bufsize => $BUFSIZE,
6353 -ConsumeInput => 1,
6354 -LimitOutput => 1);
6355 2893 ▶ die "read_table: could not start inflating: $err\n" unless $z;
Branch: 1 branch
BranchTrueFalseTotal
unless $z 0 2893 2893
6356 2893 return $z;
6357 }
6358  
6359 # (status, 1) at the end of a member, (status, 0) to go on, (status, undef) on
6360 # corrupt data. Z_BUF_ERROR is "no progress possible", which with LimitOutput
6361 # and ConsumeInput is how the stream asks for more input, not an error.
6362 4211 ▶sub INFLATE {
Subroutine INFLATE: called CC=4 SCAR=13.9
6363 4211 my ($self) = @_;
6364 4211 my $status = $self->{z}->inflate($self->{in}, $_[1]);
6365 4211 ▶ return ($status, 1) if $status == Compress::Raw::Zlib::Z_STREAM_END();
Branch: 1 branch
BranchTrueFalseTotal
if $status == Compress::Raw::Zlib::Z_STREAM_END() 2283 1928 4211
6366 1928 ▶ return ($status, 0) if $status == Compress::Raw::Zlib::Z_OK()
Branch: 1 branch
BranchTrueFalseTotal
if $status == Compress::Raw::Zlib::Z_OK() or $status == Compress::Raw::Zlib::Z_BUF_ERROR() 1925 3 1928
Condition100%3/3
$status == Compress::Raw::Zlib::Z_OK() or $status == Compress::Raw::Zlib::Z_BUF_ERROR()
l!l&&r!l&&!r
60413213
MC/DC100%2/2
$status == Compress::Raw::Zlib::Z_OK() or $status == Compress::Raw::Zlib::Z_BUF_ERROR()
$status == Compress::Raw::Zlib::Z_OK() $status == Compress::Raw::Zlib::Z_BUF_ERROR()
Truth table100%3/3
A or B
A= $status == Compress::Raw::Zlib::Z_OK()B= $status == Compress::Raw::Zlib::Z_BUF_ERROR()
ABresult
1X1
011
000
6367 || $status == Compress::Raw::Zlib::Z_BUF_ERROR();
6368 3 return ("$status", undef);
6369 }
6370  
6371 package Stats::LikeR::_Bunzip2;
6372 508 our @ISA = ('Stats::LikeR::_Decompress');
6373  
6374 476 ▶sub CODEC { 'bzip2' }
Subroutine CODEC: called CC=1 SCAR=0.0
6375 1153 ▶sub MAGIC { 'BZh' }
Subroutine MAGIC: called CC=1 SCAR=0.0
6376  
6377 972 ▶sub NEW {
Subroutine NEW: called CC=2 SCAR=7.1
6378 # appendOutput 0, consumeInput 1, small 0, verbosity 0, limitOutput 1:
6379 # the same streaming contract as _Gunzip's.
6380 972 my ($z, $err) = Compress::Raw::Bunzip2->new(0, 1, 0, 0, 1);
6381 972 ▶ die "read_table: could not start bunzipping: $err\n" unless $z;
Branch: 1 branch
BranchTrueFalseTotal
unless $z 0 972 972
6382 972 return $z;
6383 }
6384  
6385 2129 ▶sub INFLATE {
Subroutine INFLATE: called CC=3 SCAR=11.3
6386 2129 my ($self) = @_;
6387 2129 my $status = $self->{z}->bzinflate($self->{in}, $_[1]);
6388 2129 ▶ return ($status, 1) if $status == Compress::Raw::Bzip2::BZ_STREAM_END();
Branch: 1 branch
BranchTrueFalseTotal
if $status == Compress::Raw::Bzip2::BZ_STREAM_END() 477 1652 2129
6389 1652 ▶ return ($status, 0) if $status == Compress::Raw::Bzip2::BZ_OK();
Branch: 1 branch
BranchTrueFalseTotal
if $status == Compress::Raw::Bzip2::BZ_OK() 1652 0 1652
6390 0 return ("$status", undef);
6391 }
6392  
6393 # The PerlIO::via layers write_table writes a .gz or .bz2 file through. The XS
6394 # opens the file binary, as for a plain file, and pushes
6395 # :raw:via(<class>):perlio onto it; the rows bring their own row ends (CR LF
6396 # where perl is a CRLF shop, WT_EOL in LikeR.xs), so the compressed file holds
6397 # the bytes a plain one would. They reach WRITE 8 KB at a time from the :perlio
6398 # buffer above rather than a field or a character at a time.
6399 #
6400 # The end of the stream -- zlib's final block and the gzip trailer, bzip2's
6401 # end-of-stream marker -- cannot be written from FLUSH or CLOSE. The :perlio
6402 # buffer above calls FLUSH after every 8 KB it hands down, so FLUSH does not
6403 # mean "done", and PerlIO::via calls CLOSE only once the layer below has been
6404 # closed (PerlIOVia_close() runs PerlIOBase_close() first; perl 5.10.1 and
6405 # 5.42.0 ext/PerlIO-via/via.xs). So once the last row is written, the XS pops
6406 # the :perlio layer and then this one, and POPPED finishes the stream while
6407 # the file is still open.
6408 #
6409 # A write that croaks partway closes the handle without the pops, and then
6410 # CLOSE runs before POPPED: the stream is left unfinished, on purpose, so that
6411 # the file is a truncated .gz that read_table refuses rather than a complete
6412 # one holding half the table.
6413 #
6414 # A failure goes back the PerlIO way, as -1 from PUSHED or WRITE; the XS turns
6415 # it into a croak naming the file. PUSHED leaves its reason in $error.
6416 package Stats::LikeR::_Compress;
6417  
6418 508 our $error;
6419  
6420 58 ▶sub PUSHED {
Subroutine PUSHED: called CC=3 SCAR=14.2
6421 58 my ($class) = @_;
6422 58 my $z = eval { $class->NEW };
6423 58 ▶ if (!$z) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($z) 0 58 58
6424 0 ▶ $error = $@ || 'could not start compressing';
Condition0%0/2
$@ || 'could not start compressing'
l!l
00
MC/DC0%0/1
$@ || 'could not start compressing'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
6425 0 $error =~ s/\n\z//;
6426 0 return -1;
6427 }
6428 58 return bless { z => $z, closed => 0 }, $class;
6429 }
6430  
6431 1356 ▶sub WRITE {
Subroutine WRITE: called CC=4 SCAR=13.9
6432 1356 my ($self, $buf, $fh) = @_;
6433 1356 my $out = '';
6434 1356 ▶ return -1 unless $self->DEFLATE($buf, $out);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->DEFLATE($buf, $out) 0 1356 1356
6435 1356 ▶ return -1 if length $out && !print {$fh} $out;
Branch: 1 branch
BranchTrueFalseTotal
if length $out and not print({$fh;} $out) 3 1353 1356
Condition100%3/3
length $out and not print({$fh;} $out)
!ll&&!rl&&r
1286673
MC/DC100%2/2
length $out and not print({$fh;} $out)
length $out not print({$fh;} $out)
Truth table100%3/3
A and not(B)
A= length $outB= not print({$fh;} $out)
ABresult
0X0
100
111
6436 1353 return length $buf;
6437 }
6438  
6439 1468 ▶sub FLUSH { 0 }
Subroutine FLUSH: called CC=1 SCAR=0.0
6440  
6441 4 ▶sub CLOSE {
Subroutine CLOSE: called CC=1 SCAR=0.0
6442 4 $_[0]{closed} = 1;
6443 4 return 0;
6444 }
6445  
6446 58 ▶sub POPPED {
Subroutine POPPED: called CC=5 SCAR=16.7
6447 58 my ($self, $fh) = @_;
6448 58 ▶ return if $self->{closed} || !$self->{z};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} or not $self->{"z"} 4 54 58
Condition66%2/3
$self->{"closed"} or not $self->{"z"}
l!l&&r!l&&!r
4054
MC/DC50%1/2
$self->{"closed"} or not $self->{"z"}
$self->{"closed"} not $self->{"z"}
Truth table66%2/3
A or not(B)
A= $self->{"closed"}B= not $self->{"z"}
ABresult
1X1
011
000
6449 54 my $out = '';
6450 # a failure here shows up as the error flag or the close of the layer
6451 # below, which is what the XS checks next
6452 54 ▶ print {$fh} $out if $self->FINISH($out) && length $out;
Branch: 1 branch
BranchTrueFalseTotal
if $self->FINISH($out) and length $out 54 0 54
Condition33%1/3
$self->FINISH($out) and length $out
!ll&&!rl&&r
0054
MC/DC0%0/2
$self->FINISH($out) and length $out
$self->FINISH($out) length $out
Truth table33%1/3
A and B
A= $self->FINISH($out)B= length $out
ABresult
0X0
100
111
6453 54 $self->{z} = undef;
6454 54 return;
6455 }
6456  
6457 package Stats::LikeR::_Gzip;
6458 508 our @ISA = ('Stats::LikeR::_Compress');
6459  
6460 # Level 6 is Z_DEFAULT_COMPRESSION, the level of gzip(1) and of R's
6461 # gzfile(compression = 6). zlib's gzip wrapper writes a header with no name
6462 # and an mtime of 0, so the same table always makes the same bytes.
6463 31 ▶sub NEW {
Subroutine NEW: called CC=2 SCAR=7.0
6464 31 require Compress::Raw::Zlib;
6465 31 my ($z, $err) = Compress::Raw::Zlib::Deflate->new(
6466 -WindowBits => Compress::Raw::Zlib::WANT_GZIP(),
6467 -Level => Compress::Raw::Zlib::Z_DEFAULT_COMPRESSION());
6468 31 ▶ die "could not start gzip compression: $err\n" unless $z;
Branch: 1 branch
BranchTrueFalseTotal
unless $z 0 31 31
6469 31 return $z;
6470 }
6471  
6472 680 ▶sub DEFLATE {
Subroutine DEFLATE: called CC=1 SCAR=0.0
6473 680 $_[0]{z}->deflate($_[1], $_[2]) == Compress::Raw::Zlib::Z_OK();
6474 }
6475  
6476 29 ▶sub FINISH {
Subroutine FINISH: called CC=1 SCAR=0.0
6477 29 $_[0]{z}->flush($_[1]) == Compress::Raw::Zlib::Z_OK();
6478 }
6479  
6480 package Stats::LikeR::_Bzip2;
6481 508 our @ISA = ('Stats::LikeR::_Compress');
6482  
6483 # appendOutput 1, blockSize100k 9, workfactor 0 (the default, 30), verbosity
6484 # 0. 9 is bzip2(1)'s default and R's bzfile(compression = 9). Output is
6485 # appended because DEFLATE may make it in two calls; WRITE and POPPED each pass
6486 # an empty buffer.
6487 27 ▶sub NEW {
Subroutine NEW: called CC=2 SCAR=7.0
6488 27 require Compress::Raw::Bzip2;
6489 27 my ($z, $err) = Compress::Raw::Bzip2->new(1, 9, 0, 0);
6490 27 ▶ die "could not start bzip2 compression: $err\n" unless $z;
Branch: 1 branch
BranchTrueFalseTotal
unless $z 0 27 27
6491 27 return $z;
6492 }
6493  
6494 # bzip2 writes nothing until it has a whole 900 KB block, so a write that
6495 # croaked before then would leave an empty file, and an empty file reads as an
6496 # empty table rather than a broken one. The first WRITE therefore ends its
6497 # block at once, which puts the stream header and that block on disk, and a
6498 # file that is never finished is then a truncated bzip2 file, as a gzip one
6499 # already is from its first write. It costs one short block at the start.
6500 676 ▶sub DEFLATE {
Subroutine DEFLATE: called CC=3 SCAR=11.0
6501 676 my ($self) = @_;
6502 676 ▶ return 0 unless $self->{z}->bzdeflate($_[1], $_[2])
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"z"}->bzdeflate($_[1], $_[2]) == Compress::Raw::Bzip2::BZ_RUN_OK() 0 676 676
6503 == Compress::Raw::Bzip2::BZ_RUN_OK();
6504 676 ▶ return 1 if $self->{started}++;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"started"}++ 649 27 676
6505 27 return $self->{z}->bzflush($_[2]) == Compress::Raw::Bzip2::BZ_RUN_OK();
6506 }
6507  
6508 25 ▶sub FINISH {
Subroutine FINISH: called CC=1 SCAR=0.0
6509 25 $_[0]{z}->bzclose($_[1]) == Compress::Raw::Bzip2::BZ_STREAM_END();
6510 }
6511  
6512 package Stats::LikeR;
6513  
6514 508 1;
6515  
6516 __END__
↑ Summary LikeR.xs »