blib/lib/Cn/Bioinf.pm

filter: Statementstmt 78.6% 2630 / 3346 Branchbran 71.0% 1517 / 2134 Conditioncond 67.4% 1099 / 1630 MC/DCmcdc 51.3% 449 / 875 Subroutinesub 86.4% 185 / 214 Podpod 100% 40 / 40 totaltotal 71.8% 5920 / 8239 CC 1835 SCAR 56.6
CC
1835
Cov
74%
pgs_score
3561.7
gwas
834.6
msa_quality_table
758.1
CRAP 286.4
↑ Summary Bioinf.xs »
1 package Cn::Bioinf;
2 # ABSTRACT: FASTA I/O in XS, BLAST hit ranking, and alignment plots and tables
3 #
4 # Taken from ~/Scripts/bioinf.pm (as it stood on 2026-08-19): fasta2hash,
5 # get_best_alignment_hit, hash2fasta_file, msa_quality_table, msa_phylo_plot and
6 # clustal_view_residues (now view_alignment, since 2026-11-16, which also shows
7 # the alignment in the terminal and draws it as an SVG). fasta2hash and
8 # hash2fasta_file are now XS (Bioinf.xs).
9 # msa_phylo_plot is now plot_msa and plot_phylo, and no longer takes a BLAST
10 # report and a proteome database: each is given the sequences, aligns them with
11 # Clustal Omega and draws the result itself, with share/msa_plot.py (from
12 # ~/Scripts/HitList/scripts/x.my.align.py) in place of that script and of the
13 # R/ggtree tree. msa_quality_table's table is drawn by that script too, where
14 # bioinf.pm had Matplotlib::Simple's colored_table draw it. clustalo, blastp and
15 # that Python all come from Alien::Bioinf, never from PATH. Alien::Bioinf is only
16 # recommended, not required, since it cannot be installed everywhere (NCBI
17 # builds BLAST+ for few platforms) and fasta2hash, hash2fasta_file and
18 # get_best_alignment_hit do not need it; the functions that do load it through
19 # _alien, which says what is missing.
20 #
21 # concordance is ~/Scripts/old/x.low_ram_local_concordance.pl (as it stood on
22 # 2026-10-19) made a function of two VCFs: its 45 kinds of comparison and its
23 # metrics are counted in Bioinf.xs, whose comments above CONC_NAME and CONC_TP
24 # say where it departs from that script; its XLSX, JSON and ACMG59 output are
25 # not made.
26 40 require 5.012;
27 40 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 40 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 40 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
30 40 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 40 ▶use Sys::Hostname 'hostname';
Subroutine BEGIN: called CC=1 SCAR=0.0
32 40 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
33 40 ▶use XSLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
34 40 our $VERSION = '0.031';
35 40 our @EXPORT_OK = qw(
36 admixture assembly_stats back_transcribe blood_type complement concordance fasta2hash fasta_index
37 fasta_region find_orfs fst gc_content get_best_alignment_hit gwas hardy_weinberg hash2fasta_file hirisplex_genotypes
38 isoelectric_point kmer_count ld ld_prune molecular_weight motif_search msa_quality_table parent pca pdb_search
39 pgs_score plot_msa plot_phylo protein_charge relatedness reverse_complement sex_check subseq trait_predict transcribe translate
40 translate_six_frames view_alignment
41 );
42 # Nothing is in @EXPORT: a caller names what it wants, or asks for ":all".
43 40 our %EXPORT_TAGS = (all => \@EXPORT_OK);
44 40 XSLoader::load('Cn::Bioinf', $VERSION);
45 # The calling script's full path, for _creator. It is looked up at load time,
46 # as FindBin always does, but FindBin croaks when $0 is not a file on disk
47 # (after $0 is assigned to, or under an embedder), and that must not stop this
48 # module loading, so $0 made absolute stands in then. Up to 2026-10-17 this was
49 # the script's file name alone, which _creator joined to the working directory,
50 # so a script run from another directory was recorded at a path that wasn't it.
51 40 ▶my $Script = eval { require FindBin; File::Spec->catfile($FindBin::RealBin, $FindBin::RealScript) } // File::Spec->rel2abs($0);
Condition66%2/3
eval { do { require FindBin; "File::Spec"->catfile($FindBin::RealBin, $FindBin::RealScript) } } // "File::Spec"->rel2abs($0)
l!l&&r!l&&!r
3910
MC/DC0%0/2
eval { do { require FindBin; "File::Spec"->catfile($FindBin::RealBin, $FindBin::RealScript) } } // "File::Spec"->rel2abs($0)
eval { do { require FindBin; "File::Spec"->catfile($FindBin::RealBin, $FindBin::RealScript) } } "File::Spec"->rel2abs($0)
Truth table66%2/3
A // B
A= eval { do { require FindBin; "File::Spec"->catfile($FindBin::RealBin, $FindBin::RealScript) } }B= "File::Spec"->rel2abs($0)
ABresult
1X1
011
000
52  
53 # ---- private helpers
54  
55 # The name => value pairs in @$list as a hash ref. Dies unless they hold every
56 # @$required key and nothing outside @$required and @$optional. Its messages
57 # are prefixed with $sub, the public function whose arguments they are, not
58 # with "_args".
59 1086 ▶sub _args {
Subroutine _args: called CC=7 SCAR=19.5
60 1086 my ($list, $sub, $required, $optional) = @_;
61 1086 ▶ croak "$sub: takes name => value pairs, not a hash ref" if @{ $list } == 1 && ref $list->[0] eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if @{$list;} == 1 and ref $list->[0] eq "HASH" 14 1072 1086
Condition100%3/3
@{$list;} == 1 and ref $list->[0] eq "HASH"
!ll&&!rl&&r
10621014
MC/DC100%2/2
@{$list;} == 1 and ref $list->[0] eq "HASH"
@{$list;} == 1 ref $list->[0] eq "HASH"
Truth table100%3/3
A and B
A= @{$list;} == 1B= ref $list->[0] eq "HASH"
ABresult
0X0
100
111
62 1072 ▶ croak "$sub: takes name => value pairs, and was given an odd number of arguments" if @{ $list } % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @{$list;} % 2 13 1059 1072
63 # an undef name would only warn, as a hash key, and then be reported as ""
64 1059 my ($nameless) = grep { !defined $list->[2 * $_] } 0 .. @{ $list } / 2 - 1;
65 1059 ▶ croak "$sub: takes name => value pairs, and the name of pair " . ($nameless + 1) . ' is undef' if defined $nameless;
Branch: 1 branch
BranchTrueFalseTotal
if defined $nameless 3 1056 1059
66 1056 my $args = { @{ $list } };
67 1056 my @missing = grep { !defined $args->{$_} } @{ $required };
68 1056 ▶ croak "$sub: needs " . join(', ', map { "\"$_\"" } @missing) if @missing;
Branch: 1 branch
BranchTrueFalseTotal
if @missing 13 1043 1056
69 1043 my %ok = map { $_ => 1 } @{ $required }, @{ $optional };
70 1043 my @bad = sort grep { !$ok{$_} } keys %{ $args };
71 1043 ▶ croak "$sub: doesn't know " . join(', ', map { "\"$_\"" } @bad) . '; it takes ' . join(', ', sort keys %ok) if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 20 1023 1043
72 1023 $args;
73 }
74  
75 # $v as a message names it: "a HASH ref", "an ARRAY ref", "undef", or the
76 # string quoted.
77 262 ▶sub _what {
Subroutine _what: called CC=4 SCAR=13.9
78 262 my ($v) = @_;
79 262 ▶ return 'undef' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 29 233 262
80 233 ▶ ref $v ?(ref($v) =~ /\A[AEIOU]/ ? 'an ' : 'a ') . ref($v) . ' ref' : "\"$v\"";
Branch: 2 branches
BranchTrueFalseTotal
ref $v ? : 74 159 233
ref($v) =~ /\A[AEIOU]/ ? : 57 17 74
81 }
82  
83 # Dies unless each of @keys of $args that was given is a $type ('ARRAY' or
84 # 'HASH') ref, naming $sub, the public function whose arguments they are. Up to
85 # 2026-10-17 a wrong one died with perl's own "Not an ARRAY reference", naming
86 # no function, and often only once clustalo had run.
87 140 ▶sub _refs {
Subroutine _refs: called CC=5 SCAR=16.1
88 140 my ($sub, $args, $type, @keys) = @_;
89 140 foreach my $k (@keys) {
90 219 ▶ next if !defined $args->{$k} || ref $args->{$k} eq $type;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $args->{$k} or ref $args->{$k} eq $type 212 7 219
Condition100%3/3
not defined $args->{$k} or ref $args->{$k} eq $type
l!l&&r!l&&!r
20847
MC/DC100%2/2
not defined $args->{$k} or ref $args->{$k} eq $type
not defined $args->{$k} ref $args->{$k} eq $type
Truth table100%3/3
not(A) or B
A= not defined $args->{$k}B= ref $args->{$k} eq $type
ABresult
1X1
011
000
91 7 ▶ croak "$sub: \"$k\" must be " . ($type eq 'ARRAY' ? 'an array' : 'a hash') . ' ref, not ' . _what($args->{$k});
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'ARRAY' ? : 5 2 7
92 }
93 }
94  
95 # Dies unless each of @keys of $args that was given is a file name: a string
96 # that is not empty, naming $sub, the public function whose arguments they are.
97 # Up to 2026-11-10 a reference was used as its text, so that
98 # plot_msa(filename => []) wrote an image named "ARRAY(0x5ea732db32c8)".
99 100 ▶sub _file_names {
Subroutine _file_names: called CC=5 SCAR=16.1
100 100 my ($sub, $args, @keys) = @_;
101 100 foreach my $k (@keys) {
102 224 ▶ next unless defined $args->{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args->{$k} 132 92 224
103 92 ▶ croak "$sub: \"$k\" must be a file name, not " . _what($args->{$k}) if ref $args->{$k} || $args->{$k} eq '';
Branch: 1 branch
BranchTrueFalseTotal
if ref $args->{$k} or $args->{$k} eq "" 7 85 92
Condition100%3/3
ref $args->{$k} or $args->{$k} eq ""
l!l&&r!l&&!r
6185
MC/DC100%2/2
ref $args->{$k} or $args->{$k} eq ""
ref $args->{$k} $args->{$k} eq ""
Truth table100%3/3
A or B
A= ref $args->{$k}B= $args->{$k} eq ""
ABresult
1X1
011
000
104 }
105 }
106  
107 # Dies unless "threads" of $sub's $args, clustalo's --threads, is a whole
108 # number, 1 or more, or was not given. Up to 2026-11-10 anything else reached
109 # clustalo, which refused it under _run's name once the sequences were written.
110 77 ▶sub _threads {
Subroutine _threads: called CC=4 SCAR=14.9
111 77 my ($sub, $args) = @_;
112 croak "$sub: \"threads\" must be a whole number, 1 or more, not " . _what($args->{threads})
113 77 ▶ if defined $args->{threads} && (ref $args->{threads} || $args->{threads} !~ /\A[1-9][0-9]*\z/);
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"threads"} and ref $args->{"threads"} || !($args->{"threads"} =~ /\A[1-9][0-9]*\z/) 4 73 77
Condition50%3/6
defined $args->{"threads"} and ref $args->{"threads"} || !($args->{"threads"} =~ /\A[1-9][0-9]*\z/)
!ll&&!rl&&r
7304
ref $args->{"threads"} or not $args->{"threads"} =~ /\A[1-9][0-9]*\z/
l!l&&r!l&&!r
040
MC/DC33%1/3
defined $args->{"threads"} and ref $args->{"threads"} || !($args->{"threads"} =~ /\A[1-9][0-9]*\z/)
defined $args->{"threads"} ref $args->{"threads"} not $args->{"threads"} =~ /\A[1-9][0-9]*\z/
Truth table50%2/4
A and B or not(C)
A= defined $args->{"threads"}B= ref $args->{"threads"}C= not $args->{"threads"} =~ /\A[1-9][0-9]*\z/
ABCresult
0XX0
1000
11X1
1011
114 }
115  
116 # The error that Bioinf.xs's croak() ends with when it is raised in this file,
117 # which is where every XSUB is called from; compiled once, since perl 5.32
118 # leaks a pattern that is compiled at run time.
119 40 my $Located_here = qr/ at \Q${\ __FILE__}\E line [0-9]+\.\n\z/;
120  
121 # What $code, a call of one of Bioinf.xs's XSUBs, returns, in list context. An
122 # error that Bioinf.xs raised is raised again at the caller's line, as croak
123 # raises this file's own: C's croak() gives the line of this file that called
124 # the XSUB, which up to 2026-11-10 was all a caller was told. Any other error,
125 # such as one a VCF's reader croaked with, has its place already and is passed
126 # on as it is. $@ is not localized, since before perl 5.14 leaving that scope
127 # by die restored it, and lost the error.
128 777 ▶sub _located {
Subroutine _located: called CC=4 SCAR=13.9
129 777 my ($code) = @_;
130 777 my @r;
131 777 ▶ return @r if eval { @r = $code->(); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { @r = &$code(); 1 } } 685 92 777
132 92 my $error = $@;
133 92 ▶ die $error if ref $error || $error !~ s/$Located_here//;
Branch: 1 branch
BranchTrueFalseTotal
if ref $error or not $error =~ s/$Located_here// 2 90 92
Condition66%2/3
ref $error or not $error =~ s/$Located_here//
l!l&&r!l&&!r
0290
MC/DC50%1/2
ref $error or not $error =~ s/$Located_here//
ref $error not $error =~ s/$Located_here//
Truth table66%2/3
A or not(B)
A= ref $errorB= not $error =~ s/$Located_here//
ABresult
1X1
011
000
134 90 croak $error;
135 }
136  
137 # $s as characters. A string perl holds as characters is taken as it is; one it
138 # holds as bytes is taken to be UTF-8 if it decodes as such, which is how the
139 # command line used to pass it to Python, and Latin-1 otherwise.
140 596 ▶sub _chars {
Subroutine _chars: called CC=2 SCAR=7.1
141 596 my $s = "$_[0]";
142 596 ▶ utf8::decode($s) unless utf8::is_utf8($s);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($s) 596 0 596
143 596 $s;
144 }
145  
146 # $s, read as _chars reads it, as UTF-8 bytes, which is what msa_plot.py reads
147 # a FASTA or newick file as.
148 0 ▶sub _utf8 {
Subroutine _utf8: not called CC=1 SCAR=6.9
149 0 my $s = _chars($_[0]);
150 0 utf8::encode($s);
151 0 $s;
152 }
153  
154 # The start of the "Creator" written into an image's metadata, after the one
155 # Matplotlib::Simple 0.319 writes: which script, run where, called which sub of
156 # which version of this module (and of Alien::Bioinf, whose tools and Python
157 # draw every image), by whom, on which computer (its hostname and OS), with
158 # which perl and where it is. Like Matplotlib::Simple's, the Creator is the image's
159 # whole provenance, on one line, and the only metadata written: msa_plot.py
160 # appends the Python, matplotlib and Biopython versions as it runs, since only
161 # it knows them, and then each clause it is given with "--p" (what the image
162 # was made from, with digests, and the commands that made it). Matplotlib::Simple has to py_str() its
163 # Creator, which it pastes into a Python literal; this one reaches Python as a
164 # JSON string through _python's --argfile, so backslashes and quotes in a path
165 # need no escaping here.
166 #
167 # With $own, the file is written by this module itself (view_alignment's SVG
168 # and LaTeX), so Alien::Bioinf is neither needed nor named; the clause that
169 # says how an alignment was made names it when clustalo was run.
170 15 ▶sub _creator {
Subroutine _creator: called CC=3 SCAR=11.0
171 15 my ($sub, $own) = @_;
172 15 ▶ _alien($sub) unless $own;
Branch: 1 branch
BranchTrueFalseTotal
unless $own 1 14 15
173 15 ▶ "$Script called using \"$sub\" in " . __FILE__ . " version $VERSION" . ($own ? '' : " with Alien::Bioinf $Alien::Bioinf::VERSION")
Branch: 1 branch
BranchTrueFalseTotal
$own ? : 14 1 15
174 . ' by user ' . _user() . ' on host ' . hostname() . " ($^O) with Perl " . sprintf('%vd', $^V) . " ($^X)";
175 }
176  
177 # The name of the user running this. getpwuid is unimplemented on MSWin32,
178 # where it dies, and getlogin is undef without a controlling terminal (under
179 # cron, or a batch scheduler), so the environment is the last resort.
180 15 ▶sub _user {
Subroutine _user: called CC=8 SCAR=28.4
181 15 my $user = eval { (getpwuid $<)[0] };
182 15 ▶ $user = getlogin() unless defined $user && length $user;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $user and length $user 0 15 15
Condition33%1/3
defined $user and length $user
!ll&&!rl&&r
0015
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
183 15 ▶ $user = $ENV{USERNAME} // $ENV{USER} unless defined $user && length $user;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $user and length $user 0 15 15
Condition16%1/6
defined $user and length $user
!ll&&!rl&&r
0015
$ENV{"USERNAME"} // $ENV{"USER"}
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $user and length $user
defined $user length $user
MC/DC0%0/2
$ENV{"USERNAME"} // $ENV{"USER"}
$ENV{"USERNAME"} $ENV{"USER"}
Truth table33%1/3
A and B
A= defined $userB= length $user
ABresult
0X0
100
111
Truth table0%0/3
A // B
A= $ENV{"USERNAME"}B= $ENV{"USER"}
ABresult
1X1
011
000
184 15 ▶ defined $user && length $user ? $user : 'unknown';
Branch: 1 branch
BranchTrueFalseTotal
defined $user && length $user ? : 15 0 15
Condition33%1/3
defined $user and length $user
!ll&&!rl&&r
0015
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
185 }
186  
187 # The data in the JSON file $file, which $sub was given; dies naming $sub, as
188 # the file is that caller's argument. Up to 2026-11-02 a file that was not JSON
189 # died with JSON::MaybeXS's message, naming no function, and an empty one with
190 # a "Usage:" message, since <$fh> passed decode_json an empty list.
191 24 ▶sub _json_file {
Subroutine _json_file: called CC=5 SCAR=16.2
192 24 my ($sub, $file) = @_;
193 24 require JSON::MaybeXS;
194 24 ▶ open my $fh, '<:raw', $file or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $file or croak("${sub}: can't read ${file}: $!") 24 0 24
195 24 ▶ my $text = do { local $/; <$fh> } // ''; # undef for an empty file
Condition50%1/2
do { local $/; readline $fh } // ""
l!l
240
MC/DC0%0/1
do { local $/; readline $fh } // ""
do { local $/; readline $fh }
Truth table50%1/2
A
A= do { local $/; readline $fh }
Aresult
11
00
196 24 ▶ close $fh or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't read ${file}: $!") 24 0 24
197 24 my $data = eval { JSON::MaybeXS::decode_json($text) };
198 24 ▶ unless (defined $data) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 3 21 24
199 3 (my $why = $@) =~ s/ at .+ line \d+\.\n\z//; # the location is the module's, which says nothing of the file
200 3 croak "$sub: $file isn't JSON: $why";
201 }
202 21 $data;
203 }
204  
205 # @cmd run with list-form system, which needs no shell. $? is -1 when the
206 # program never started; otherwise its low 7 bits are the signal that killed
207 # it, and must be read before the shift, which leaves only the exit code.
208 2 ▶sub _run {
Subroutine _run: called CC=4 SCAR=14.2
209 2 my @cmd = @_;
210 2 ▶ system(@cmd) == 0 and return;
Branch: 1 branch
BranchTrueFalseTotal
system(@cmd) == 0 and return 0 2 2
211 2 ▶ my $why = $? == -1 ? "it didn't start: $!" : $? & 127 ? 'killed by signal ' . ($? & 127) : 'exit ' . ($? >> 8);
Branch: 2 branches
BranchTrueFalseTotal
$? == -1 ? : 0 2 2
$? & 127 ? : 1 1 2
212 2 croak "_run: \"@cmd\" failed: $why";
213 }
214  
215 # Alien::Bioinf, loaded for $sub, or a message saying that $sub needs it.
216 2 ▶sub _alien {
Subroutine _alien: called CC=2 SCAR=6.9
217 2 my ($sub) = @_;
218 2 ▶ eval { require Alien::Bioinf; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Alien::Bioinf; 1 } } or croak("_alien: $sub needs Alien::Bioinf, for Clustal Omega, BLAST+ and the plotting Python, and it can't be loaded: $@") 1 1 2
219 or croak "_alien: $sub needs Alien::Bioinf, for Clustal Omega, BLAST+ and the plotting Python, and it can't be loaded: $@";
220 1 'Alien::Bioinf';
221 }
222  
223 # share/msa_plot.py run with @args under Alien::Bioinf's Python, for $sub. The
224 # arguments go in a JSON file rather than on the command line: perl's
225 # system(LIST) on Windows does not escape a '"' inside an argument, and the
226 # Creator and the JSON options are full of them. Each argument is read as
227 # _chars reads it; encode_json alone would read UTF-8 bytes as Latin-1. -I
228 # keeps PYTHONPATH, PYTHONHOME and the user's own site-packages out, so that
229 # nothing but Alien::Bioinf's venv is imported.
230 0 ▶sub _python {
Subroutine _python: not called CC=3 SCAR=24.8
231 0 my ($sub, @args) = @_;
232 0 require JSON::MaybeXS;
233 0 my @chars = map { _chars($_) } @args;
234 0 my $argfile = _tmp('.json');
235 0 ▶ open my $fh, '>:raw', $argfile or croak "_python: can't write $argfile: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $argfile or croak("_python: can't write ${argfile}: $!") 0 0 0
236 0 print {$fh} JSON::MaybeXS::encode_json(\@chars);
237 0 ▶ close $fh or croak "_python: can't write $argfile: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("_python: can't write ${argfile}: $!") 0 0 0
238 0 _run(_alien($sub)->python, '-I', _script(), '--argfile', $argfile);
239 }
240  
241 # $data, whose strings the caller has made characters with _chars, as JSON
242 # text: characters, not UTF-8 bytes, since it is one argument that _python
243 # encodes along with the rest. It is held as UTF-8, so that _python takes it as
244 # it is: decoding it whole, as up to 2026-10-17, turned a byte string inside it
245 # to mojibake whenever another string in it held characters.
246 0 ▶sub _json_text {
Subroutine _json_text: not called CC=1 SCAR=6.9
247 0 my ($data) = @_;
248 0 require JSON::MaybeXS;
249 0 my $text = JSON::MaybeXS->new(utf8 => 0, canonical => 1)->encode($data);
250 0 utf8::upgrade($text);
251 0 $text;
252 }
253  
254 # "wrote $file" to STDOUT, as LikeR's write_table prints it: $file in black
255 # (30) on $bg (an ANSI background, 43 = yellow or 46 = cyan) and then reset
256 # (0), written out rather than loaded from Term::ANSIColor; the reset comes
257 # before the newline so the colour doesn't run on into the next line. The
258 # colour is left out when STDOUT is not a terminal, where the escapes would
259 # only be noise in a log or a test harness.
260 21 ▶sub _wrote {
Subroutine _wrote: called CC=3 SCAR=11.7
261 21 my ($file, $bg, $verb) = @_;
262 21 ▶ $verb //= 'wrote'; # or 'will write', for an image whose script has not run yet
Condition50%1/2
$verb //= "wrote"
l!l
021
MC/DC0%0/1
$verb //= "wrote"
$verb
Truth table50%1/2
A
A= $verb
Aresult
11
00
263 21 ▶ print STDOUT -t STDOUT ? "$verb \e[30;${bg}m$file\e[0m\n" : "$verb $file\n";
Branch: 1 branch
BranchTrueFalseTotal
-t STDOUT ? : 0 21 21
264 }
265  
266 # A new temporary file's name, with $suffix. It is removed when perl exits
267 # unless $keep is true.
268 2 ▶sub _tmp {
Subroutine _tmp: called CC=3 SCAR=11.3
269 2 my ($suffix, $keep) = @_;
270 2 require File::Temp;
271 2 ▶ my ($fh, $name) = File::Temp::tempfile(SUFFIX => $suffix, UNLINK => $keep ? 0 : 1, TMPDIR => 1);
Branch: 1 branch
BranchTrueFalseTotal
$keep ? : 0 2 2
272 2 ▶ close $fh or croak "_tmp: can't close $name: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("_tmp: can't close ${name}: $!") 2 0 2
273 2 $name;
274 }
275  
276 # "fh" and "execute" of $sub's $args, resolved and checked before anything
277 # runs, as Matplotlib::Simple's plt takes them: "fh" is a File::Temp that the
278 # Python drawing the image is appended to, so that one script, run once, can
279 # draw several images (and those of Matplotlib::Simple, which takes the same
280 # File::Temp); "execute" says whether to run that script now.
281 23 ▶sub _drawing {
Subroutine _drawing: called CC=8 SCAR=21.1
282 23 my ($sub, $args) = @_;
283 23 my %r = (fh => $args->{fh});
284 23 ▶ $r{execute} = $args->{execute} // 1; # 1 = run the script now; 0 = only write it
Condition100%2/2
$args->{"execute"} // 1
l!l
617
MC/DC100%1/1
$args->{"execute"} // 1
$args->{"execute"}
Truth table100%2/2
A
A= $args->{"execute"}
Aresult
11
00
285 croak "$sub: \"execute\" must be 0 or 1, not " . _what($r{execute})
286 23 ▶ unless !ref $r{execute} && ($r{execute} eq '0' || $r{execute} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"execute"} and $r{"execute"} eq 0 || $r{"execute"} eq 1 6 17 23
Condition83%5/6
not ref $r{"execute"} and $r{"execute"} eq 0 || $r{"execute"} eq 1
!ll&&!rl&&r
2417
$r{"execute"} eq 0 or $r{"execute"} eq 1
l!l&&r!l&&!r
0174
MC/DC66%2/3
not ref $r{"execute"} and $r{"execute"} eq 0 || $r{"execute"} eq 1
not ref $r{"execute"} $r{"execute"} eq 0 $r{"execute"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"execute"}B= $r{"execute"} eq 0C= $r{"execute"} eq 1
ABCresult
0XX0
1000
11X1
1011
287 17 ▶ if (defined $r{fh}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $r{"fh"}) 4 13 17
288 4 require Scalar::Util;
289 croak "$sub: \"fh\" must be a File::Temp object, as for Matplotlib::Simple, not " . _what($r{fh})
290 4 ▶ unless Scalar::Util::blessed($r{fh}) && $r{fh}->isa('File::Temp');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($r{"fh"}) and $r{"fh"}->isa("File::Temp") 4 0 4
Condition33%1/3
builtin::blessed($r{"fh"}) and $r{"fh"}->isa("File::Temp")
!ll&&!rl&&r
400
MC/DC0%0/2
builtin::blessed($r{"fh"}) and $r{"fh"}->isa("File::Temp")
builtin::blessed($r{"fh"}) $r{"fh"}->isa("File::Temp")
Truth table33%1/3
A and B
A= builtin::blessed($r{"fh"})B= $r{"fh"}->isa("File::Temp")
ABresult
0X0
100
111
291 }
292 13 \%r;
293 }
294  
295 # share/msa_plot.py run with @args for $sub, as Python appended to the script
296 # that $drawing (from _drawing) names, or to a new temporary one; the script is
297 # run under Alien::Bioinf's Python if $drawing->{execute}. Returns the script's
298 # file name. A new script is kept after perl exits only when it is not run
299 # here, since only then is it of use afterwards.
300 #
301 # The script is the whole of what it needs, so that it can be run later, after
302 # perl has removed its temporary files: each file passed with --f, --tree or
303 # --table is carried in it, and written out again, to a temporary directory,
304 # as the script runs. Nothing perl was given is pasted into the Python source:
305 # the arguments, the files and msa_plot.py's path are one JSON object, base64
306 # encoded, as Matplotlib::Simple's write_data passes data, since a Windows
307 # path's "\b" is a backspace in a Python literal and an apostrophe would close
308 # it. msa_plot.py is run by runpy in a namespace of its own, so that its
309 # globals meet neither those of another image in the script nor those of
310 # Matplotlib::Simple's code. -I keeps PYTHONPATH, PYTHONHOME and the user's own
311 # site-packages out, as for _python.
312 0 ▶sub _draw {
Subroutine _draw: not called CC=15 SCAR=54.8
313 0 my ($sub, $drawing, @args) = @_;
314 0 require JSON::MaybeXS;
315 0 require MIME::Base64;
316 0 my %file = map { $_ => 1 } qw(--f --tree --table); # the options whose value is a file msa_plot.py reads
317 0 my @json;
318 0 ▶ for (my $i = 0; $i < @args; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @args) 0 0 0
319 0 push @json, _chars($args[$i]);
320 0 ▶ next unless $file{ $args[$i] } && $i < $#args;
Branch: 1 branch
BranchTrueFalseTotal
unless $file{$args[$i]} and $i < $#args 0 0 0
Condition0%0/3
$file{$args[$i]} and $i < $#args
!ll&&!rl&&r
000
MC/DC0%0/2
$file{$args[$i]} and $i < $#args
$file{$args[$i]} $i < $#args
Truth table0%0/3
A and B
A= $file{$args[$i]}B= $i < $#args
ABresult
0X0
100
111
321 0 my $in = $args[++$i];
322 0 ▶ open my $fh, '<:raw', $in or croak "_draw: can't read $in: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $in or croak("_draw: can't read ${in}: $!") 0 0 0
323 0 my $bytes = do { local $/; <$fh> };
324 0 ▶ close $fh or croak "_draw: can't read $in: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("_draw: can't read ${in}: $!") 0 0 0
325 # named by its place, so that no two collide, and with its own suffix
326 0 ▶ push @json, { name => 'input' . scalar(@json) . ($in =~ /(\.[A-Za-z]+)\z/ ? $1 : ''), b64 => MIME::Base64::encode_base64($bytes // '', '') };
Branch: 1 branch
BranchTrueFalseTotal
$in =~ /(\.[A-Za-z]+)\z/ ? : 0 0 0
Condition0%0/2
$bytes // ""
l!l
00
MC/DC0%0/1
$bytes // ""
$bytes
Truth table0%0/2
A
A= $bytes
Aresult
11
00
327 }
328 0 my $b64 = MIME::Base64::encode_base64(JSON::MaybeXS::encode_json({ script => _chars(_script()), args => \@json }), '');
329 0 my $py = <<"PYTHON";
330 # $sub, from Cn::Bioinf $VERSION: msa_plot.py run on the arguments below
331 import base64, json, os, runpy, sys, tempfile
332 cn_bioinf = json.loads(base64.b64decode('$b64').decode('utf-8'))
333 with tempfile.TemporaryDirectory() as cn_bioinf_dir:
334 cn_bioinf_argv = []
335 for cn_bioinf_arg in cn_bioinf['args']:
336 if isinstance(cn_bioinf_arg, dict):
337 cn_bioinf_path = os.path.join(cn_bioinf_dir, cn_bioinf_arg['name'])
338 with open(cn_bioinf_path, 'wb') as cn_bioinf_fh:
339 cn_bioinf_fh.write(base64.b64decode(cn_bioinf_arg['b64']))
340 cn_bioinf_arg = cn_bioinf_path
341 cn_bioinf_argv.append(cn_bioinf_arg)
342 sys.argv = [cn_bioinf['script']] + cn_bioinf_argv
343 runpy.run_path(cn_bioinf['script'], run_name='__main__')
344 PYTHON
345 0 my $script;
346 0 ▶ if (defined $drawing->{fh}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $drawing->{'fh'}) { } 0 0 0
347 0 my $fh = $drawing->{fh};
348 0 $script = $fh->filename;
349 0 ▶ print {$fh} $py or croak "$sub: can't write to \"fh\", $script: $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $py or croak(qq[${sub}: can't write to "fh", ${script}: $!]) 0 0 0
350 0 ▶ $fh->flush or croak "$sub: can't write to \"fh\", $script: $!";
Branch: 1 branch
BranchTrueFalseTotal
$fh->flush or croak(qq[${sub}: can't write to "fh", ${script}: $!]) 0 0 0
351 } else {
352 0 $script = _tmp('.py', !$drawing->{execute});
353 0 ▶ open my $fh, '>:raw', $script or croak "$sub: can't write $script: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $script or croak("${sub}: can't write ${script}: $!") 0 0 0
354 0 ▶ print {$fh} $py or croak "$sub: can't write $script: $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $py or croak("${sub}: can't write ${script}: $!") 0 0 0
355 0 ▶ close $fh or croak "$sub: can't write $script: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't write ${script}: $!") 0 0 0
356 }
357 0 ▶ _run(_alien($sub)->python, '-I', $script) if $drawing->{execute};
Branch: 1 branch
BranchTrueFalseTotal
if $drawing->{"execute"} 0 0 0
358 0 $script;
359 }
360  
361 0 ▶sub _script {
Subroutine _script: not called CC=1 SCAR=6.9
362 0 require File::ShareDir;
363 0 File::ShareDir::dist_file('Cn-Bioinf', 'msa_plot.py');
364 }
365  
366 # The FASTA file's records and their deflines in file order.
367 2 ▶sub _fasta_ordered {
Subroutine _fasta_ordered: called CC=4 SCAR=14.0
368 2 my ($file) = @_;
369 2 my @order;
370 2 my $fh = _open_fasta($file);
371 2 ▶ my ($h) = _located(sub { _read_fasta($fh, undef, $file, \@order) });
Subroutine __ANON__: called CC=1 SCAR=0.0
372 # a truncated or corrupt .gz shows only in gzip's exit status, as in
373 # fasta2hash; the whole file was read, so no SIGPIPE is expected
374 2 ▶ unless (close $fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close $fh) 1 1 2
375 1 ▶ my $why = $! ? "$!" : $? & 127 ? 'gzip was killed by signal ' . ($? & 127) : 'gzip exited ' . ($? >> 8);
Branch: 2 branches
BranchTrueFalseTotal
$! ? : 0 1 1
$? & 127 ? : 0 1 1
376 1 croak "_fasta_ordered: couldn't read all of $file: $why";
377 }
378 1 ($h, \@order);
379 }
380  
381 64 ▶sub _open_fasta {
Subroutine _open_fasta: called CC=8 SCAR=21.8
382 64 my ($file) = @_;
383 64 ▶ croak "_open_fasta: undef isn't a readable file" unless defined $file;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file 1 63 64
384 63 ▶ croak "_open_fasta: \"$file\" doesn't exist or isn't a readable file" unless -f $file && -r _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file and -r _ 1 62 63
Condition66%2/3
-f $file and -r _
!ll&&!rl&&r
1062
MC/DC50%1/2
-f $file and -r _
-f $file -r _
Truth table66%2/3
A and B
A= -f $fileB= -r _
ABresult
0X0
100
111
385 62 my $fh;
386 62 ▶ if ($file =~ /\.gz\z/i) { # any case, as _weight_rows takes it
Branch: 1 branch
BranchTrueFalseTotal
if ($file =~ /\.gz\z/i) { } 9 53 62
387 # in an eval, since a perl without list-form piped open (MSWin32 before
388 # 5.22) dies in open itself, with no function name in the message
389 # "--", or gzip would read a name that starts with "-" as its options
390 9 ▶ eval { open $fh, '-|', 'gzip', '-dc', '--', $file } or croak "_open_fasta: can't run gzip on $file: " . ($@ || $!);
Branch: 1 branch
BranchTrueFalseTotal
eval { do { open $fh, "-|", "gzip", "-dc", "--", $file } } or croak("_open_fasta: can't run gzip on ${file}: " . ($@ || $!)) 9 0 9
Condition0%0/3
$@ || $!
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ || $!
$@ $!
Truth table0%0/3
A || B
A= $@B= $!
ABresult
1X1
011
000
391 } else {
392 53 ▶ open $fh, '<:raw', $file or croak "_open_fasta: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<:raw", $file or croak("_open_fasta: can't read ${file}: $!") 53 0 53
393 }
394 62 $fh;
395 }
396  
397 6 ▶sub _first_letter {
Subroutine _first_letter: called CC=2 SCAR=8.1
398 6 my ($string) = @_;
399 6 ▶ return $1 if $string =~ /^([A-Za-z])/;
Branch: 1 branch
BranchTrueFalseTotal
if $string =~ /^([A-Za-z])/ 6 0 6
400 0 croak "_first_letter: \"$string\" doesn't start with a letter, so it has no first letter";
401 }
402  
403 # Narrow but unambiguous labels, e.g. "$\it{C.al.}$", for [genus, species,
404 # strain] triples ('' for no strain). One letter of the species cannot tell
405 # C.albicans from C.auris, so this takes the shortest species prefix that
406 # separates every entry; the strain is always kept, since it is all that
407 # separates the three C.neoformans.
408 2 ▶sub _abbreviated_labels {
Subroutine _abbreviated_labels: called CC=6 SCAR=19.1
409 2 my ($names) = @_;
410 2 my $max = 0;
411 2 foreach my $n (@{ $names }) {
412 3 ▶ $max = length $n->[1] if length $n->[1] > $max;
Branch: 1 branch
BranchTrueFalseTotal
if length $n->[1] > $max 2 1 3
413 }
414 2 foreach my $n (1 .. $max) {
415 my @labels = map {
416 3 ▶ '$\it{' . ucfirst(_first_letter($_->[0])) . '.' . lc(substr($_->[1], 0, $n)) . '.}$' . ($_->[2] ne '' ? " $_->[2]" : '')
Branch: 1 branch
BranchTrueFalseTotal
$_->[2] ne '' ? : 0 3 3
417 2 } @{ $names };
418 2 my %seen;
419 2 ▶ return \@labels unless grep { $seen{$_}++ } @labels;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$seen{$_}++;} @labels 2 0 2
420 }
421 0 croak "_abbreviated_labels: can't tell " . join(', ', map { join '.', @{ $_ } } @{ $names }) . ' apart, even with the full species name and strain';
422 }
423  
424 # ---- FASTA
425  
426 62 ▶sub fasta2hash {
Subroutine fasta2hash: called CC=9 SCAR=22.2
Pod documented
427 62 my ($file, $key) = @_;
428 62 my $fh = _open_fasta($file);
429 60 ▶ my ($r) = _located(sub { _read_fasta($fh, $key, $file) });
Subroutine __ANON__: called CC=1 SCAR=0.0
430 # A gzip that fails part-way, on a truncated or corrupt .gz, has merely
431 # stopped writing, so its exit status is the only sign of it. That is
432 # checked unless $key was found, when reading may have stopped early and
433 # the closed pipe have killed gzip with a SIGPIPE.
434 56 ▶ unless (close $fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close $fh) 2 54 56
435 2 ▶ my $why = $! ? "$!" : $? & 127 ? 'gzip was killed by signal ' . ($? & 127) : 'gzip exited ' . ($? >> 8);
Branch: 2 branches
BranchTrueFalseTotal
$! ? : 0 2 2
$? & 127 ? : 0 2 2
436 2 ▶ croak "fasta2hash: couldn't read all of $file: $why" unless defined $key && defined $r;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key and defined $r 2 0 2
Condition66%2/3
defined $key and defined $r
!ll&&!rl&&r
110
MC/DC0%0/2
defined $key and defined $r
defined $key defined $r
Truth table66%2/3
A and B
A= defined $keyB= defined $r
ABresult
0X0
100
111
437 }
438 54 ▶ if (defined $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key) 15 39 54
439 15 ▶ return $r if defined $r;
Branch: 1 branch
BranchTrueFalseTotal
if defined $r 12 3 15
440 3 croak "fasta2hash: couldn't find \"$key\" in $file";
441 }
442 39 ▶ croak "fasta2hash: couldn't find any sequences in $file" unless %{ $r };
Branch: 1 branch
BranchTrueFalseTotal
unless %{$r;} 1 38 39
443 38 $r;
444 }
445  
446 28 ▶sub hash2fasta_file {
Subroutine hash2fasta_file: called CC=10 SCAR=23.1
Pod documented
447 28 my ($hash, $filename, $order, $width) = @_;
448 28 ▶ croak "hash2fasta_file: 1st argument must be a hash ref" unless ref $hash eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $hash eq "HASH" 1 27 28
449 27 ▶ croak "hash2fasta_file: 2nd argument must be a file name" unless defined $filename && ref $filename eq '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $filename and ref $filename eq "" 0 27 27
Condition33%1/3
defined $filename and ref $filename eq ""
!ll&&!rl&&r
0027
MC/DC0%0/2
defined $filename and ref $filename eq ""
defined $filename ref $filename eq ""
Truth table33%1/3
A and B
A= defined $filenameB= ref $filename eq ""
ABresult
0X0
100
111
450 27 ▶ croak "hash2fasta_file: 3rd argument must be an array ref or undef" if defined $order && ref $order ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if defined $order and ref $order ne "ARRAY" 1 26 27
Condition100%3/3
defined $order and ref $order ne "ARRAY"
!ll&&!rl&&r
16101
MC/DC100%2/2
defined $order and ref $order ne "ARRAY"
defined $order ref $order ne "ARRAY"
Truth table100%3/3
A and B
A= defined $orderB= ref $order ne "ARRAY"
ABresult
0X0
100
111
451 # checked here because the XS takes it as a UV, where -1 would wrap round
452 26 ▶ croak "hash2fasta_file: 4th argument must be a whole number, 0 or more, or undef, not \"$width\"" if defined $width && $width !~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
if defined $width and not $width =~ /\A[0-9]+\z/ 3 23 26
Condition100%3/3
defined $width and not $width =~ /\A[0-9]+\z/
!ll&&!rl&&r
1943
MC/DC100%2/2
defined $width and not $width =~ /\A[0-9]+\z/
defined $width not $width =~ /\A[0-9]+\z/
Truth table100%3/3
A and not(B)
A= defined $widthB= not $width =~ /\A[0-9]+\z/
ABresult
0X0
100
111
453 23 ▶ _fasta_file('hash2fasta_file', $hash, $filename, $order // [sort keys %{ $hash }], $width // 80);
Condition100%4/4
$order // [sort(keys %{$hash;})]
l!l
1013
$width // 80
l!l
419
MC/DC100%1/1
$order // [sort(keys %{$hash;})]
$order
MC/DC100%1/1
$width // 80
$width
Truth table100%2/2
A
A= $order
Aresult
11
00
Truth table100%2/2
A
A= $width
Aresult
11
00
454 13 _wrote($filename, 46); # cyan
455 13 $filename;
456 }
457  
458 # hash2fasta_file without its checks, its defaults or its "wrote" line, for
459 # the FASTA files the module writes for itself, mostly temporary ones that a
460 # caller never asked for; $sub is the caller, to name in an error.
461 24 ▶sub _fasta_file {
Subroutine _fasta_file: called CC=3 SCAR=11.2
462 24 my ($sub, $hash, $filename, $order, $width) = @_;
463 24 ▶ open my $fh, '>:raw', $filename or croak "$sub: can't write $filename: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $filename or croak("${sub}: can't write ${filename}: $!") 24 0 24
464 24 ▶ _located(sub { _write_fasta($fh, $hash, $order, $width) });
Subroutine __ANON__: called CC=1 SCAR=0.0
465 14 ▶ close $fh or croak "$sub: can't write $filename: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't write ${filename}: $!") 14 0 14
466 14 $filename;
467 }
468  
469 # ---- sequences
470 #
471 # complement to motif_search work on a sequence held as a perl string, and
472 # fasta_index and fasta_region on a FASTA file. Each says which function of
473 # which library it follows, and t/seq.t, t/protein.t and t/faidx.t take their
474 # expected values from that library's own tests.
475  
476 # Dies, naming $sub, unless $seq is a sequence: a string, which may be empty.
477 538 ▶sub _sequence {
Subroutine _sequence: called CC=3 SCAR=11.0
478 538 my ($sub, $seq) = @_;
479 538 ▶ croak "$sub: the sequence must be a string, not " . _what($seq) if !defined $seq || ref $seq;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $seq or ref $seq 28 510 538
Condition100%3/3
not defined $seq or ref $seq
l!l&&r!l&&!r
1414510
MC/DC100%2/2
not defined $seq or ref $seq
not defined $seq ref $seq
Truth table100%3/3
not(A) or B
A= not defined $seqB= ref $seq
ABresult
1X1
011
000
480 }
481  
482 # "type" of $sub's $args, which says what kind of sequence it was given, as the
483 # one of @$allowed ('DNA', 'RNA', 'protein') that it names in any case; DNA
484 # when it was not given.
485 168 ▶sub _seq_type {
Subroutine _seq_type: called CC=4 SCAR=13.9
486 168 my ($sub, $args, $allowed) = @_;
487 168 ▶ my $type = $args->{type} // 'DNA';
Condition100%2/2
$args->{"type"} // "DNA"
l!l
68100
MC/DC100%1/1
$args->{"type"} // "DNA"
$args->{"type"}
Truth table100%2/2
A
A= $args->{"type"}
Aresult
11
00
488 168 ▶ my ($found) = ref $type ? () : grep { lc $_ eq lc $type } @{ $allowed };
Branch: 1 branch
BranchTrueFalseTotal
ref $type ? : 1 167 168
489 168 ▶ return $found if defined $found;
Branch: 1 branch
BranchTrueFalseTotal
if defined $found 164 4 168
490 4 my @q = map { "\"$_\"" } @{ $allowed };
491 4 croak "$sub: \"type\" must be " . join(', ', @q[0 .. $#q - 1]) . " or $q[-1], not " . _what($type);
492 }
493  
494 # "strand" of $sub's $args as 'both', '+' or '-'; $default when it was not
495 # given.
496 58 ▶sub _strand {
Subroutine _strand: called CC=4 SCAR=14.0
497 58 my ($sub, $args, $default) = @_;
498 58 ▶ my $strand = $args->{strand} // $default;
Condition66%2/3
$args->{"strand"} // $default
l!l&&r!l&&!r
23350
MC/DC0%0/2
$args->{"strand"} // $default
$args->{"strand"} $default
Truth table66%2/3
A // B
A= $args->{"strand"}B= $default
ABresult
1X1
011
000
499 58 ▶ croak "$sub: \"strand\" must be \"+\", \"-\" or \"both\", not " . _what($strand)
Branch: 1 branch
BranchTrueFalseTotal
if ref $strand or not $strand =~ /\A(?:\+|-|both)\z/ 2 56 58
Condition66%2/3
ref $strand or not $strand =~ /\A(?:\+|-|both)\z/
l!l&&r!l&&!r
0256
MC/DC50%1/2
ref $strand or not $strand =~ /\A(?:\+|-|both)\z/
ref $strand not $strand =~ /\A(?:\+|-|both)\z/
Truth table66%2/3
A or not(B)
A= ref $strandB= not $strand =~ /\A(?:\+|-|both)\z/
ABresult
1X1
011
000
500 if ref $strand || $strand !~ /\A(?:\+|-|both)\z/;
501 56 $strand;
502 }
503  
504 # $seq with every nucleotide replaced by the one it pairs with, for $sub, which
505 # was given @opt. The pairs are Biopython 1.87's ambiguous_dna_complement and
506 # ambiguous_rna_complement (Bio/Data/IUPACData.py), in both cases, and U is
507 # read as T, as its Seq.complement() and Seq.complement_rna() read it. N and X
508 # pair with themselves, and so does every character that is not a nucleotide,
509 # a gap included.
510 113 ▶sub _complement {
Subroutine _complement: called CC=2 SCAR=6.9
511 113 my ($sub, $seq, @opt) = @_;
512 113 _sequence($sub, $seq);
513 109 my $type = _seq_type($sub, _args(\@opt, $sub, [], ['type']), ['DNA', 'RNA']);
514 101 my $c = "$seq";
515 101 ▶ if ($type eq 'RNA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq 'RNA') { } 35 66 101
516 35 $c =~ tr/ACGTUMRWSYKVHDBacgtumrwsykvhdb/UGCAAKYWSRMBDHVugcaakywsrmbdhv/;
517 } else {
518 66 $c =~ tr/ACGTUMRWSYKVHDBacgtumrwsykvhdb/TGCAAKYWSRMBDHVtgcaakywsrmbdhv/;
519 }
520 101 $c;
521 }
522  
523 43 ▶sub complement { _complement('complement', @_) }
Subroutine complement: called CC=1 SCAR=0.0
Pod documented
524  
525 44 ▶sub reverse_complement { scalar reverse _complement('reverse_complement', @_) }
Subroutine reverse_complement: called CC=1 SCAR=0.0
Pod documented
526  
527 21 ▶sub transcribe {
Subroutine transcribe: called CC=2 SCAR=6.9
Pod documented
528 21 my ($seq, @rest) = @_;
529 21 ▶ croak 'transcribe: takes one argument, the sequence' if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 20 21
530 20 _sequence('transcribe', $seq);
531 18 (my $rna = "$seq") =~ tr/Tt/Uu/;
532 18 $rna;
533 }
534  
535 19 ▶sub back_transcribe {
Subroutine back_transcribe: called CC=2 SCAR=6.9
Pod documented
536 19 my ($seq, @rest) = @_;
537 19 ▶ croak 'back_transcribe: takes one argument, the sequence' if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 18 19
538 18 _sequence('back_transcribe', $seq);
539 16 (my $dna = "$seq") =~ tr/Uu/Tt/;
540 16 $dna;
541 }
542  
543 # NCBI's genetic codes, from share/genetic_codes.tsv, which
544 # share/make_genetic_codes.pl writes and whose header comment says where each
545 # column comes from. %Code is id => { id, names, aas, start_mask, stop_mask,
546 # both } and %Code_id is each lower-cased name => id; both are empty until the
547 # file has been read. The three 64-letter strings are what Bioinf.xs's
548 # _translate() takes, a letter for each codon from TTT to GGG:
549 #
550 # - aas: the codon's amino acid, or * for a stop.
551 # - start_mask: M for a codon that can start a protein, and A for any other.
552 # - stop_mask: * for a codon that can end one, and A for any other.
553 #
554 # "Translating" a codon with a mask says whether it is a start or a stop by the
555 # rules that translate it, so that an ambiguous codon is a start only when
556 # every codon it stands for is one. "both" lists, as [codon, amino acid], the
557 # codons that aas gives an amino acid and stop_mask a stop: the organism reads
558 # them either way.
559 40 my (%Code, %Code_id);
560  
561 # The 64 codons in the order of those strings.
562 40 my @Codon = map { my $x = $_; map { my $y = $_; map { "$x$y$_" } qw(T C A G) } qw(T C A G) } qw(T C A G);
563  
564 # start_mask for ATG alone, which is codon 35: A is base 2 and G base 3 of
565 # T, C, A, G, so 16 * 2 + 4 * 0 + 3.
566 40 my $Atg_mask = ('A' x 35) . 'M' . ('A' x 28);
567  
568 # Reads the genetic codes into %Code and %Code_id, once, for $sub.
569 148 ▶sub _genetic_codes {
Subroutine _genetic_codes: called CC=16 SCAR=29.6
570 148 my ($sub) = @_;
571 148 ▶ return if %Code;
Branch: 1 branch
BranchTrueFalseTotal
if %Code 145 3 148
572 3 my $file = _share_file($sub, 'genetic_codes.tsv');
573 3 ▶ open my $fh, '<', $file or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or croak("${sub}: can't read ${file}: $!") 3 0 3
574 3 my (%code, %id);
575 3 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 87 3 90
576 87 $line =~ s/\r?\n\z//;
577 87 ▶ next if $line eq '' || $line =~ /\A#/;
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" or $line =~ /\A#/ 6 81 87
Condition66%2/3
$line eq "" or $line =~ /\A#/
l!l&&r!l&&!r
0681
MC/DC50%1/2
$line eq "" or $line =~ /\A#/
$line eq "" $line =~ /\A#/
Truth table66%2/3
A or B
A= $line eq ""B= $line =~ /\A#/
ABresult
1X1
011
000
578 81 my ($id, $names, $aas, $starts) = split /\t/, $line, -1;
579 81 ▶ croak "$sub: line $. of $file isn't a genetic code: it needs a number, names, 64 amino acids and 64 start and stop marks"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $starts and $id =~ /\A[1-9][0-9]*\z/ and length $names and $aas =~ /\A[A-Z*]{64}\z/ and $starts =~ /\A[M*-]{64}\z/ 0 81 81
Condition33%4/12
defined $starts and $id =~ /\A[1-9][0-9]*\z/ and length $names and $aas =~ /\A[A-Z*]{64}\z/ and $starts =~ /\A[M*-]{64}\z/
!ll&&!rl&&r
0081
defined $starts and $id =~ /\A[1-9][0-9]*\z/ and length $names and $aas =~ /\A[A-Z*]{64}\z/
!ll&&!rl&&r
0081
defined $starts and $id =~ /\A[1-9][0-9]*\z/ and length $names
!ll&&!rl&&r
0081
defined $starts and $id =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
0081
MC/DC0%0/5
defined $starts and $id =~ /\A[1-9][0-9]*\z/ and length $names and $aas =~ /\A[A-Z*]{64}\z/ and $starts =~ /\A[M*-]{64}\z/
defined $starts $id =~ /\A[1-9][0-9]*\z/ length $names $aas =~ /\A[A-Z*]{64}\z/ $starts =~ /\A[M*-]{64}\z/
Truth table16%1/6
A and B and C and D and E
A= defined $startsB= $id =~ /\A[1-9][0-9]*\z/C= length $namesD= $aas =~ /\A[A-Z*]{64}\z/E= $starts =~ /\A[M*-]{64}\z/
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
580 unless defined $starts && $id =~ /\A[1-9][0-9]*\z/ && length $names && $aas =~ /\A[A-Z*]{64}\z/ && $starts =~ /\A[M*-]{64}\z/;
581 81 (my $start_mask = $starts) =~ tr/M*-/MAA/;
582 81 (my $stop_mask = $starts) =~ tr/M*-/A*A/;
583 81 ▶ my @both = map { [$Codon[$_], substr $aas, $_, 1] } grep { substr($starts, $_, 1) eq '*' && substr($aas, $_, 1) ne '*' } 0 .. 63;
Condition100%3/3
substr($starts, $_, 1) eq '*' && substr($aas, $_, 1) ne '*'
!ll&&!rl&&r
501015618
MC/DC100%2/2
substr($starts, $_, 1) eq '*' && substr($aas, $_, 1) ne '*'
substr($starts, $_, 1) eq '*' substr($aas, $_, 1) ne '*'
Truth table100%3/3
A && B
A= substr($starts, $_, 1) eq '*'B= substr($aas, $_, 1) ne '*'
ABresult
0X0
100
111
584 81 $code{$id} = { id => 0 + $id, names => [split /; /, $names], aas => $aas, start_mask => $start_mask, stop_mask => $stop_mask, both => \@both };
585 # A code is known by each of its names, and by each part of a name that
586 # lists several organisms, which is how Biopython's CodonTable.py
587 # registers them: "Bacterial, Archaeal and Plant Plastid" is also
588 # "Bacterial", "Archaeal" and "Plant Plastid".
589 81 ▶ $id{lc $_} //= 0 + $id for $names, map { $_, split /, | and / } split /; /, $names;
Condition100%2/2
$id{lc $_} //= 0 + $id
l!l
177165
MC/DC100%1/1
$id{lc $_} //= 0 + $id
$id{lc $_}
Truth table100%2/2
A
A= $id{lc $_}
Aresult
11
00
590 }
591 3 ▶ close $fh or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't read ${file}: $!") 3 0 3
592 3 ▶ croak "$sub: $file has no genetic codes" unless %code;
Branch: 1 branch
BranchTrueFalseTotal
unless %code 0 3 3
593 3 %Code = %code;
594 3 %Code_id = %id;
595 }
596  
597 # The genetic code that $table, "table" of $sub's arguments, names: one of
598 # %Code's values.
599 148 ▶sub _genetic_code {
Subroutine _genetic_code: called CC=5 SCAR=16.1
600 148 my ($sub, $table) = @_;
601 148 _genetic_codes($sub);
602 148 ▶ my $id = ref $table ? undef : $table =~ /\A[0-9]+\z/ ? 0 + $table : $Code_id{lc $table};
Branch: 2 branches
BranchTrueFalseTotal
ref $table ? : 3 145 148
$table =~ /\A[0-9]+\z/ ? : 132 13 145
603 croak "$sub: \"table\" must be the number or the name of an NCBI genetic code, not " . _what($table)
604 148 ▶ . '; the numbers are ' . join(', ', sort { $a <=> $b } keys %Code) unless defined $id && $Code{$id};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and $Code{$id} 9 139 148
Condition100%3/3
defined $id and $Code{$id}
!ll&&!rl&&r
63139
MC/DC100%2/2
defined $id and $Code{$id}
defined $id $Code{$id}
Truth table100%3/3
A and B
A= defined $idB= $Code{$id}
ABresult
0X0
100
111
605 139 $Code{$id};
606 }
607  
608 # Warns, for $sub, when $code has codons that are read as an amino acid or as
609 # a stop, since they are translated as the amino acid; with $to_stop it dies
610 # instead, as the protein's end could not be told. Biopython 1.87's
611 # _translate_str() (Bio/Seq.py) does both.
612 139 ▶sub _both_ways {
Subroutine _both_ways: called CC=4 SCAR=13.9
613 139 my ($sub, $code, $to_stop) = @_;
614 139 ▶ my @both = @{ $code->{both} } or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@both) = @{$code->{"both"};} or return 2 137 139
615 2 my $reads = "genetic code $code->{id} reads " . join(' and ', map { "$_->[0] as $_->[1] or as a stop" } @both);
616 2 ▶ croak "$sub: \"to_stop\" can't be used with \"table\" $code->{id}: $reads" if $to_stop;
Branch: 1 branch
BranchTrueFalseTotal
if $to_stop 1 1 2
617 1 ▶ carp "$sub: $reads, and " . (@both > 1 ? 'they are' : 'it is') . ' translated as the amino acid';
Branch: 1 branch
BranchTrueFalseTotal
@both > 1 ? : 1 0 1
618 }
619  
620 # $v, the option $k of $sub, as a single byte for Bioinf.xs, which takes the
621 # first byte of the string it is handed; dies unless it is one character below
622 # 256. undef is passed through.
623 253 ▶sub _one_char {
Subroutine _one_char: called CC=4 SCAR=13.9
624 253 my ($sub, $k, $v) = @_;
625 253 ▶ return $v unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 110 143 253
626 143 ▶ croak "$sub: \"$k\" must be one character, below 256, not " . _what($v) if ref $v || $v !~ /\A[\x00-\xff]\z/s;
Branch: 1 branch
BranchTrueFalseTotal
if ref $v or not $v =~ /\A[\x00-\xff]\z/s 6 137 143
Condition100%3/3
ref $v or not $v =~ /\A[\x00-\xff]\z/s
l!l&&r!l&&!r
15137
MC/DC100%2/2
ref $v or not $v =~ /\A[\x00-\xff]\z/s
ref $v not $v =~ /\A[\x00-\xff]\z/s
Truth table100%3/3
A or not(B)
A= ref $vB= not $v =~ /\A[\x00-\xff]\z/s
ABresult
1X1
011
000
627 137 utf8::downgrade($v); # a character from 128 to 255 can be held as two bytes
628 137 $v;
629 }
630  
631 127 ▶sub translate {
Subroutine translate: called CC=12 SCAR=24.8
Pod documented
632 127 my ($seq, @opt) = @_;
633 127 my $sub = 'translate';
634 127 _sequence($sub, $seq);
635 125 my $args = _args(\@opt, $sub, [], [qw(cds gap stop_symbol table to_stop)]);
636 122 my %r; # the options, each resolved once
637 122 ▶ $r{table} = $args->{table} // 1; # an NCBI genetic code's number or name
Condition100%2/2
$args->{"table"} // 1
l!l
5666
MC/DC100%1/1
$args->{"table"} // 1
$args->{"table"}
Truth table100%2/2
A
A= $args->{"table"}
Aresult
11
00
638 122 ▶ $r{to_stop} = $args->{to_stop} ? 1 : 0; # 1 = the protein ends before the first stop
Branch: 1 branch
BranchTrueFalseTotal
$args->{'to_stop'} ? : 12 110 122
639 122 ▶ $r{cds} = $args->{cds} ? 1 : 0; # 1 = $seq is a whole coding sequence, start codon to stop codon
Branch: 1 branch
BranchTrueFalseTotal
$args->{'cds'} ? : 8 114 122
640 122 ▶ $r{stop_symbol} = _one_char($sub, 'stop_symbol', $args->{stop_symbol} // '*'); # the letter written for a stop
Condition100%2/2
$args->{"stop_symbol"} // "*"
l!l
7115
MC/DC100%1/1
$args->{"stop_symbol"} // "*"
$args->{"stop_symbol"}
Truth table100%2/2
A
A= $args->{"stop_symbol"}
Aresult
11
00
641 119 $r{gap} = _one_char($sub, 'gap', $args->{gap}); # the gap character; undef = a gap is not a codon
642 117 my $code = _genetic_code($sub, $r{table});
643 114 _both_ways($sub, $code, $r{to_stop});
644 113 my $len = length $seq;
645 113 ▶ if ($r{cds}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"cds"}) 8 105 113
646 # Biopython's checks, in its order
647 8 ▶ my ($first) = _located(sub { _translate(substr($seq, 0, 3), $code->{start_mask}, '*', 0, undef) });
Subroutine __ANON__: called CC=1 SCAR=0.0
648 8 ▶ croak "$sub: with \"cds\", the first codon, \"" . substr($seq, 0, 3) . "\", must be a start codon of genetic code $code->{id}"
Branch: 1 branch
BranchTrueFalseTotal
unless $first eq "M" 1 7 8
649 unless $first eq 'M';
650 7 ▶ croak "$sub: with \"cds\", the sequence's length, $len, must be a multiple of three" if $len % 3;
Branch: 1 branch
BranchTrueFalseTotal
if $len % 3 1 6 7
651 6 ▶ my ($last) = _located(sub { _translate(substr($seq, -3), $code->{stop_mask}, '*', 0, undef) });
Subroutine __ANON__: called CC=1 SCAR=0.0
652 6 ▶ croak "$sub: with \"cds\", the last codon, \"" . substr($seq, -3) . "\", must be a stop codon of genetic code $code->{id}"
Branch: 1 branch
BranchTrueFalseTotal
unless $last eq "*" 1 5 6
653 unless $last eq '*';
654 # every codon but the last, up to the first stop, which there must not be
655 5 ▶ my ($p) = _located(sub { _translate(substr($seq, 0, $len - 3), $code->{aas}, '*', 1, $r{gap}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
656 5 ▶ croak "$sub: with \"cds\", only the last codon may be a stop, and codon " . (length($p) + 1) . ', "'
Branch: 1 branch
BranchTrueFalseTotal
if length $p < $len / 3 - 1 1 4 5
657 . substr($seq, 3 * length $p, 3) . '", is one' if length($p) < $len / 3 - 1;
658 4 substr($p, 0, 1) = 'M'; # whatever the start codon stands for inside a protein
659 4 return $p;
660 }
661 105 ▶ carp "$sub: the sequence's length, $len, is not a multiple of three, so its last " . ($len % 3 == 1 ? 'letter is' : '2 letters are')
Branch: 2 branches
BranchTrueFalseTotal
if $len % 3 2 103 105
$len % 3 == 1 ? : 0 2 2
662 . ' not translated' if $len % 3;
663 105 ▶ my ($p) = _located(sub { _translate($seq, $code->{aas}, $r{stop_symbol}, $r{to_stop}, $r{gap}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
664 94 $p;
665 }
666  
667 17 ▶sub translate_six_frames {
Subroutine translate_six_frames: called CC=7 SCAR=19.5
Pod documented
668 17 my ($seq, @opt) = @_;
669 17 my $sub = 'translate_six_frames';
670 17 _sequence($sub, $seq);
671 15 my $args = _args(\@opt, $sub, [], [qw(stop_symbol table)]);
672 12 my %r; # the options, each resolved once
673 12 ▶ $r{table} = $args->{table} // 1; # an NCBI genetic code's number or name
Condition100%2/2
$args->{"table"} // 1
l!l
48
MC/DC100%1/1
$args->{"table"} // 1
$args->{"table"}
Truth table100%2/2
A
A= $args->{"table"}
Aresult
11
00
674 12 ▶ $r{stop_symbol} = _one_char($sub, 'stop_symbol', $args->{stop_symbol} // '*'); # the letter written for a stop
Condition100%2/2
$args->{"stop_symbol"} // "*"
l!l
210
MC/DC100%1/1
$args->{"stop_symbol"} // "*"
$args->{"stop_symbol"}
Truth table100%2/2
A
A= $args->{"stop_symbol"}
Aresult
11
00
675 11 my $code = _genetic_code($sub, $r{table});
676 8 _both_ways($sub, $code, 0);
677 8 my %frame;
678 8 foreach my $strand (1, -1) {
679 15 ▶ my $nuc = $strand > 0 ? $seq : scalar reverse _complement($sub, $seq);
Branch: 1 branch
BranchTrueFalseTotal
$strand > 0 ? : 8 7 15
680 15 foreach my $f (0 .. 2) {
681 # a frame that starts beyond the sequence's end has no codons
682 ($frame{$strand * ($f + 1)}) = $f < length $nuc
683 43 ▶ ? _located(sub { _translate(substr($nuc, $f), $code->{aas}, $r{stop_symbol}, 0, undef) }) : '';
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$f < length $nuc ? : 35 8 43
684 }
685 }
686 7 \%frame;
687 }
688  
689 32 ▶sub find_orfs {
Subroutine find_orfs: called CC=27 SCAR=33.0
Pod documented
690 32 my ($seq, @opt) = @_;
691 32 my $sub = 'find_orfs';
692 32 _sequence($sub, $seq);
693 30 my $args = _args(\@opt, $sub, [], [qw(min_length start strand table)]);
694 27 my %r; # the options, each resolved once
695 27 ▶ $r{table} = $args->{table} // 1; # an NCBI genetic code's number or name
Condition100%2/2
$args->{"table"} // 1
l!l
720
MC/DC100%1/1
$args->{"table"} // 1
$args->{"table"}
Truth table100%2/2
A
A= $args->{"table"}
Aresult
11
00
696 # The fewest amino acids an open reading frame may have. 10 is the default
697 # of EMBOSS 6.6.0's getorf, whose -minsize is 30 nucleotides.
698 27 ▶ $r{min_length} = $args->{min_length} // 10;
Condition100%2/2
$args->{"min_length"} // 10
l!l
1512
MC/DC100%1/1
$args->{"min_length"} // 10
$args->{"min_length"}
Truth table100%2/2
A
A= $args->{"min_length"}
Aresult
11
00
699 croak "$sub: \"min_length\" must be a whole number, 1 or more, not " . _what($r{min_length})
700 27 ▶ if ref $r{min_length} || $r{min_length} !~ /\A[1-9][0-9]*\z/;
Branch: 1 branch
BranchTrueFalseTotal
if ref $r{"min_length"} or not $r{"min_length"} =~ /\A[1-9][0-9]*\z/ 5 22 27
Condition100%3/3
ref $r{"min_length"} or not $r{"min_length"} =~ /\A[1-9][0-9]*\z/
l!l&&r!l&&!r
1422
MC/DC100%2/2
ref $r{"min_length"} or not $r{"min_length"} =~ /\A[1-9][0-9]*\z/
ref $r{"min_length"} not $r{"min_length"} =~ /\A[1-9][0-9]*\z/
Truth table100%3/3
A or not(B)
A= ref $r{"min_length"}B= not $r{"min_length"} =~ /\A[1-9][0-9]*\z/
ABresult
1X1
011
000
701 # Where a reading frame opens: 'any' = at the codon after a stop, or the
702 # first of the sequence; 'ATG' = at the first ATG after that; 'code' = at
703 # the first of the genetic code's start codons after that.
704 22 ▶ $r{start} = $args->{start} // 'any';
Condition100%2/2
$args->{"start"} // "any"
l!l
913
MC/DC100%1/1
$args->{"start"} // "any"
$args->{"start"}
Truth table100%2/2
A
A= $args->{"start"}
Aresult
11
00
705 croak "$sub: \"start\" must be \"any\", \"ATG\" or \"code\", not " . _what($r{start})
706 22 ▶ if ref $r{start} || $r{start} !~ /\A(?:any|ATG|code)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if ref $r{"start"} or not $r{"start"} =~ /\A(?:any|ATG|code)\z/ 1 21 22
Condition66%2/3
ref $r{"start"} or not $r{"start"} =~ /\A(?:any|ATG|code)\z/
l!l&&r!l&&!r
0121
MC/DC50%1/2
ref $r{"start"} or not $r{"start"} =~ /\A(?:any|ATG|code)\z/
ref $r{"start"} not $r{"start"} =~ /\A(?:any|ATG|code)\z/
Truth table66%2/3
A or not(B)
A= ref $r{"start"}B= not $r{"start"} =~ /\A(?:any|ATG|code)\z/
ABresult
1X1
011
000
707 21 $r{strand} = _strand($sub, $args, 'both'); # '+', '-' or 'both'
708 20 my $code = _genetic_code($sub, $r{table});
709 17 _both_ways($sub, $code, 0);
710 17 ▶ my $mask = $r{start} eq 'any' ? undef : $r{start} eq 'ATG' ? $Atg_mask : $code->{start_mask};
Branch: 2 branches
BranchTrueFalseTotal
$r{'start'} eq 'any' ? : 9 8 17
$r{'start'} eq 'ATG' ? : 6 2 8
711 17 my $len = length $seq;
712 17 my @orf;
713 17 ▶ foreach my $strand ($r{strand} eq 'both' ? (1, -1) : $r{strand} eq '+' ? 1 : -1) {
Branch: 2 branches
BranchTrueFalseTotal
$r{'strand'} eq 'both' ? : 10 7 17
$r{'strand'} eq '+' ? : 6 1 7
714 26 ▶ my $nuc = $strand > 0 ? $seq : scalar reverse _complement($sub, $seq);
Branch: 1 branch
BranchTrueFalseTotal
$strand > 0 ? : 16 10 26
715 26 foreach my $f (0 .. 2) {
716 76 ▶ next unless $f < $len;
Branch: 1 branch
BranchTrueFalseTotal
unless $f < $len 8 68 76
717 68 my $frame = substr $nuc, $f;
718 # the frame's codons as amino acids, and as M where one is a start
719 68 ▶ my ($protein) = _located(sub { _translate($frame, $code->{aas}, '*', 0, undef) });
Subroutine __ANON__: called CC=1 SCAR=0.0
720 67 ▶ my ($starts) = defined $mask ? _located(sub { _translate($frame, $mask, '*', 0, undef) }) : undef;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
defined $mask ? : 33 34 67
721 67 my $codons = length $protein;
722 # $from and $stop count codons: the frame is open over $from .. $stop - 1
723 67 ▶ for (my $from = 0; $from < $codons;) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from < $codons) 3788 67 3855
724 3788 my $stop = index $protein, '*', $from;
725 3788 ▶ $stop = $codons if $stop < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $stop < 0 55 3733 3788
726 3788 my $next = $stop + 1;
727 3788 ▶ $from = index $starts, 'M', $from if defined $starts;
Branch: 1 branch
BranchTrueFalseTotal
if defined $starts 1897 1891 3788
728 3788 ▶ if ($from >= 0 && $stop - $from >= $r{min_length}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from >= 0 and $stop - $from >= $r{"min_length"}) 139 3649 3788
Condition100%3/3
$from >= 0 and $stop - $from >= $r{"min_length"}
!ll&&!rl&&r
463603139
MC/DC100%2/2
$from >= 0 and $stop - $from >= $r{"min_length"}
$from >= 0 $stop - $from >= $r{"min_length"}
Truth table100%3/3
A and B
A= $from >= 0B= $stop - $from >= $r{"min_length"}
ABresult
0X0
100
111
729 139 my $p = substr $protein, $from, $stop - $from;
730 # a start codon stands for M at a protein's start, whatever
731 # it stands for inside one, as getorf's -methionine has it
732 139 ▶ substr($p, 0, 1) = 'M' if defined $starts;
Branch: 1 branch
BranchTrueFalseTotal
if defined $starts 57 82 139
733 # the first and last base, counted from 0 on this strand
734 139 my ($x, $y) = ($f + 3 * $from, $f + 3 * $stop - 1);
735 139 ▶ push @orf, {
Branch: 2 branches
BranchTrueFalseTotal
$strand > 0 ? : 66 73 139
$strand > 0 ? : 66 73 139
736 start => $strand > 0 ? $x + 1 : $len - $y, end => $strand > 0 ? $y + 1 : $len - $x,
737 strand => $strand, frame => $strand * ($f + 1), length => $stop - $from, protein => $p,
738 };
739 }
740 3788 $from = $next;
741 }
742 }
743 }
744 16 ▶ [sort { $a->{start} <=> $b->{start} || $a->{end} <=> $b->{end} || $b->{strand} <=> $a->{strand} } @orf];
Condition50%3/6
$Cn::Bioinf::a->{'start'} <=> $Cn::Bioinf::b->{'start'} || $Cn::Bioinf::a->{'end'} <=> $Cn::Bioinf::b->{'end'} || $Cn::Bioinf::b->{'strand'} <=> $Cn::Bioinf::a->{'strand'}
l!l&&r!l&&!r
39400
$Cn::Bioinf::a->{"start"} <=> $Cn::Bioinf::b->{"start"} or $Cn::Bioinf::a->{"end"} <=> $Cn::Bioinf::b->{"end"}
l!l&&r!l&&!r
39310
MC/DC0%0/3
$Cn::Bioinf::a->{'start'} <=> $Cn::Bioinf::b->{'start'} || $Cn::Bioinf::a->{'end'} <=> $Cn::Bioinf::b->{'end'} || $Cn::Bioinf::b->{'strand'} <=> $Cn::Bioinf::a->{'strand'}
$Cn::Bioinf::a->{"start"} <=> $Cn::Bioinf::b->{"start"} $Cn::Bioinf::a->{"end"} <=> $Cn::Bioinf::b->{"end"} $Cn::Bioinf::b->{'strand'} <=> $Cn::Bioinf::a->{'strand'}
Truth table50%2/4
A or B || C
A= $Cn::Bioinf::a->{"start"} <=> $Cn::Bioinf::b->{"start"}B= $Cn::Bioinf::a->{"end"} <=> $Cn::Bioinf::b->{"end"}C= $Cn::Bioinf::b->{'strand'} <=> $Cn::Bioinf::a->{'strand'}
ABCresult
1XX1
01X1
0011
0000
745 }
746  
747 35 ▶sub gc_content {
Subroutine gc_content: called CC=7 SCAR=19.5
Pod documented
748 35 my ($seq, @opt) = @_;
749 35 my $sub = 'gc_content';
750 35 _sequence($sub, $seq);
751 33 my $args = _args(\@opt, $sub, [], ['ambiguous']);
752 # What a letter other than A, C, G, T, U, S and W counts for: 'remove' =
753 # nothing, and it is left out of the length too; 'ignore' = nothing, but it
754 # is part of the length; 'weighted' = the share of the bases it stands for
755 # that are G or C.
756 30 ▶ my $ambiguous = $args->{ambiguous} // 'remove';
Condition100%2/2
$args->{"ambiguous"} // "remove"
l!l
282
MC/DC100%1/1
$args->{"ambiguous"} // "remove"
$args->{"ambiguous"}
Truth table100%2/2
A
A= $args->{"ambiguous"}
Aresult
11
00
757 30 ▶ croak "$sub: \"ambiguous\" must be \"remove\", \"ignore\" or \"weighted\", not " . _what($ambiguous)
Branch: 1 branch
BranchTrueFalseTotal
if ref $ambiguous or not $ambiguous =~ /\A(?:remove|ignore|weighted)\z/ 1 29 30
Condition66%2/3
ref $ambiguous or not $ambiguous =~ /\A(?:remove|ignore|weighted)\z/
l!l&&r!l&&!r
0129
MC/DC50%1/2
ref $ambiguous or not $ambiguous =~ /\A(?:remove|ignore|weighted)\z/
ref $ambiguous not $ambiguous =~ /\A(?:remove|ignore|weighted)\z/
Truth table66%2/3
A or not(B)
A= ref $ambiguousB= not $ambiguous =~ /\A(?:remove|ignore|weighted)\z/
ABresult
1X1
011
000
758 if ref $ambiguous || $ambiguous !~ /\A(?:remove|ignore|weighted)\z/;
759 29 my $gc = ($seq =~ tr/CGScgs//);
760 29 ▶ my $len = $ambiguous eq 'remove' ? $gc + ($seq =~ tr/ATWUatwu//) : length $seq;
Branch: 1 branch
BranchTrueFalseTotal
$ambiguous eq 'remove' ? : 11 18 29
761 29 ▶ if ($ambiguous eq 'weighted') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ambiguous eq "weighted") 9 20 29
762 # Biopython 1.87's _gc_values (Bio/SeqUtils/__init__.py), added in the
763 # order its gc_fraction() adds them, B D H K M N R V X Y, so that the
764 # sum rounds as its sum does
765 9 $gc += ($seq =~ tr/Bb//) * (2 / 3); # C, G or T
766 9 $gc += ($seq =~ tr/Dd//) * (1 / 3); # A, G or T
767 9 $gc += ($seq =~ tr/Hh//) * (1 / 3); # A, C or T
768 9 $gc += ($seq =~ tr/Kk//) * 0.5; # G or T
769 9 $gc += ($seq =~ tr/Mm//) * 0.5; # A or C
770 9 $gc += ($seq =~ tr/Nn//) * 0.5; # any base
771 9 $gc += ($seq =~ tr/Rr//) * 0.5; # A or G
772 9 $gc += ($seq =~ tr/Vv//) * (2 / 3); # A, C or G
773 9 $gc += ($seq =~ tr/Xx//) * 0.5; # any base
774 9 $gc += ($seq =~ tr/Yy//) * 0.5; # C or T
775 }
776 29 ▶ $len ? $gc / $len : 0;
Branch: 1 branch
BranchTrueFalseTotal
$len ? : 26 3 29
777 }
778  
779 10 ▶sub assembly_stats {
Subroutine assembly_stats: called CC=19 SCAR=29.4
Pod documented
780 10 my ($seqs, @rest) = @_;
781 10 my $sub = 'assembly_stats';
782 10 ▶ croak "$sub: takes one argument, the sequences" if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 9 10
783 9 ▶ croak "$sub: the sequences must be a hash ref, as fasta2hash returns, or an array ref, not " . _what($seqs)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $seqs eq "HASH" or ref $seqs eq "ARRAY" 3 6 9
Condition100%3/3
ref $seqs eq "HASH" or ref $seqs eq "ARRAY"
l!l&&r!l&&!r
243
MC/DC100%2/2
ref $seqs eq "HASH" or ref $seqs eq "ARRAY"
ref $seqs eq "HASH" ref $seqs eq "ARRAY"
Truth table100%3/3
A or B
A= ref $seqs eq "HASH"B= ref $seqs eq "ARRAY"
ABresult
1X1
011
000
784 unless ref $seqs eq 'HASH' || ref $seqs eq 'ARRAY';
785 6 my (@len, %nx, %lx);
786 6 my ($total, $n_count, $gaps) = (0, 0, 0);
787 6 ▶ foreach my $s (ref $seqs eq 'HASH' ? values %{ $seqs } : @{ $seqs }) {
Branch: 1 branch
BranchTrueFalseTotal
ref $seqs eq 'HASH' ? : 2 4 6
788 15 ▶ croak "$sub: every sequence must be a string, and one is " . _what($s) if !defined $s || ref $s;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $s or ref $s 2 13 15
Condition100%3/3
not defined $s or ref $s
l!l&&r!l&&!r
1113
MC/DC100%2/2
not defined $s or ref $s
not defined $s ref $s
Truth table100%3/3
not(A) or B
A= not defined $sB= ref $s
ABresult
1X1
011
000
789 13 push @len, length $s;
790 13 $total += length $s;
791 13 $n_count += ($s =~ tr/Nn//);
792 13 ▶ $gaps++ while $s =~ /[Nn]+/g;
Branch: 1 branch
BranchTrueFalseTotal
$s =~ /[Nn]+/g and do { ++$gaps } 4 13 17
793 }
794 4 @len = sort { $b <=> $a } @len;
795 # Nx is the length of the sequence at which the lengths, added from the
796 # longest down, first reach x% of their total, and Lx is how many
797 # sequences that took. The comparison is in whole numbers, 10 * the sum
798 # against the total * x / 10, where assembly-stats divides in floating point.
799 4 my ($sum, $tenth) = (0, 1); # $tenth = the x / 10 that has not been reached yet
800 # with a total of 0, 10 * 0 >= 0 * x would reach every tenth at the first
801 # sequence, and give an Lx of 1 where the rule below says 0
802 4 ▶ foreach my $i ($total ? (0 .. $#len) : ()) {
Branch: 1 branch
BranchTrueFalseTotal
$total ? : 2 2 4
803 10 $sum += $len[$i];
804 10 ▶ while ($tenth <= 10 && 10 * $sum >= $total * $tenth) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tenth <= 10 and 10 * $sum >= $total * $tenth) 20 10 30
Condition100%3/3
$tenth <= 10 and 10 * $sum >= $total * $tenth
!ll&&!rl&&r
2820
MC/DC100%2/2
$tenth <= 10 and 10 * $sum >= $total * $tenth
$tenth <= 10 10 * $sum >= $total * $tenth
Truth table100%3/3
A and B
A= $tenth <= 10B= 10 * $sum >= $total * $tenth
ABresult
0X0
100
111
805 20 $nx{10 * $tenth} = $len[$i];
806 20 $lx{10 * $tenth} = $i + 1;
807 20 $tenth++;
808 }
809 }
810 # no sequences, or none with any length: every Nx and Lx is 0
811 4 ▶ $nx{10 * $_} //= 0, $lx{10 * $_} //= 0 for 1 .. 10;
Condition100%4/4
$nx{10 * $_} //= 0
l!l
2020
$lx{10 * $_} //= 0
l!l
2020
MC/DC100%1/1
$nx{10 * $_} //= 0
$nx{10 * $_}
MC/DC100%1/1
$lx{10 * $_} //= 0
$lx{10 * $_}
Truth table100%2/2
A
A= $nx{10 * $_}
Aresult
11
00
Truth table100%2/2
A
A= $lx{10 * $_}
Aresult
11
00
812 {
813 number => scalar @len, total_length => $total, mean_length => @len ? $total / @len : 0,
814 longest => @len ? $len[0] : 0, shortest => @len ? $len[-1] : 0,
815 4 ▶ n_count => $n_count, gaps => $gaps, n50 => $nx{50}, l50 => $lx{50}, nx => \%nx, lx => \%lx,
Branch: 3 branches
BranchTrueFalseTotal
@len ? : 3 1 4
@len ? : 3 1 4
@len ? : 3 1 4
816 };
817 }
818  
819 38 ▶sub kmer_count {
Subroutine kmer_count: called CC=15 SCAR=27.1
Pod documented
820 38 my ($seq, $k, @opt) = @_;
821 38 my $sub = 'kmer_count';
822 38 _sequence($sub, $seq);
823 # 2147483647 is the longest key a perl hash takes, I32_MAX
824 36 ▶ croak "$sub: k must be a whole number from 1 to 2147483647, not " . _what($k)
Branch: 1 branch
BranchTrueFalseTotal
if not defined $k or ref $k or not $k =~ /\A[1-9][0-9]{0,9}\z/ or $k > 2147483647 8 28 36
Condition100%9/9
not defined $k or ref $k or not $k =~ /\A[1-9][0-9]{0,9}\z/ or $k > 2147483647
l!l&&r!l&&!r
7128
not defined $k or ref $k or not $k =~ /\A[1-9][0-9]{0,9}\z/
l!l&&r!l&&!r
2529
not defined $k or ref $k
l!l&&r!l&&!r
1134
MC/DC100%4/4
not defined $k or ref $k or not $k =~ /\A[1-9][0-9]{0,9}\z/ or $k > 2147483647
not defined $k ref $k not $k =~ /\A[1-9][0-9]{0,9}\z/ $k > 2147483647
Truth table100%5/5
not(A) or B or not(C) or D
A= not defined $kB= ref $kC= not $k =~ /\A[1-9][0-9]{0,9}\z/D= $k > 2147483647
ABCDresult
1XXX1
01XX1
001X1
00011
00000
825 if !defined $k || ref $k || $k !~ /\A[1-9][0-9]{0,9}\z/ || $k > 2147483647;
826 28 my $args = _args(\@opt, $sub, [], [qw(overlap relative)]);
827 25 my %r; # the options, each resolved once
828 25 ▶ $r{overlap} = ($args->{overlap} // 1) ? 1 : 0; # 1 = every k-mer; 0 = one every k letters, which do not overlap
Branch: 1 branch
BranchTrueFalseTotal
$args->{'overlap'} // 1 ? : 18 7 25
Condition100%2/2
$args->{"overlap"} // 1
l!l
817
MC/DC100%1/1
$args->{"overlap"} // 1
$args->{"overlap"}
Truth table100%2/2
A
A= $args->{"overlap"}
Aresult
11
00
829 25 ▶ $r{relative} = $args->{relative} ? 1 : 0; # 1 = each count as a share of them all
Branch: 1 branch
BranchTrueFalseTotal
$args->{'relative'} ? : 10 15 25
830 25 ▶ my $step = $r{overlap} ? 1 : 0 + $k;
Branch: 1 branch
BranchTrueFalseTotal
$r{'overlap'} ? : 18 7 25
831 25 my $count;
832 # Bioinf.xs counts bytes. A string that perl holds as characters is handed
833 # over as bytes where it can be, and counted here where it cannot, which
834 # is when it has a character above 255.
835 25 my $bytes = $seq;
836 25 ▶ if (!utf8::is_utf8($bytes) || utf8::downgrade($bytes, 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not utf8::is_utf8($bytes) or utf8::downgrade($bytes, 1)) { } 24 1 25
Condition100%3/3
not utf8::is_utf8($bytes) or utf8::downgrade($bytes, 1)
l!l&&r!l&&!r
2131
MC/DC100%2/2
not utf8::is_utf8($bytes) or utf8::downgrade($bytes, 1)
not utf8::is_utf8($bytes) utf8::downgrade($bytes, 1)
Truth table100%3/3
not(A) or B
A= not utf8::is_utf8($bytes)B= utf8::downgrade($bytes, 1)
ABresult
1X1
011
000
837 24 ▶ ($count) = _located(sub { _kmer_count($bytes, 0 + $k, $step) });
Subroutine __ANON__: called CC=1 SCAR=0.0
838 } else {
839 1 $count = {};
840 1 ▶ for (my $i = 0; $i + $k <= length $seq; $i += $step) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i + $k <= length $seq) 3 1 4
841 3 $count->{ substr $seq, $i, $k }++;
842 }
843 }
844 25 ▶ if ($r{relative}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"relative"}) 10 15 25
845 10 my $all = 0;
846 10 $all += $_ for values %{ $count };
847 10 $_ /= $all for values %{ $count };
848 }
849 25 $count;
850 }
851  
852 # The weight of each nucleotide, as its monophosphate, and of each amino acid,
853 # in daltons: "average" with every element at its standard atomic weight and
854 # "monoisotopic" with each at its commonest isotope. They are Biopython 1.87's
855 # unambiguous_dna_weights, unambiguous_rna_weights and protein_weights, and
856 # the monoisotopic_ table of each (Bio/Data/IUPACData.py), which that file
857 # introduces with "Mass data taken from PubChem". O is pyrrolysine and U
858 # selenocysteine. "water" is what one bond between two residues gives up, from
859 # molecular_weight() of Bio/SeqUtils/__init__.py.
860 40 my %Weight = (
861 average => {
862 DNA => { A => 331.2218, C => 307.1971, G => 347.2212, T => 322.2085 },
863 RNA => { A => 347.2212, C => 323.1965, G => 363.2206, U => 324.1813 },
864 protein => {
865 A => 89.0932, C => 121.1582, D => 133.1027, E => 147.1293, F => 165.1891, G => 75.0666, H => 155.1546,
866 I => 131.1729, K => 146.1876, L => 131.1729, M => 149.2113, N => 132.1179, O => 255.3134, P => 115.1305,
867 Q => 146.1445, R => 174.201, S => 105.0926, T => 119.1192, U => 168.0532, V => 117.1463, W => 204.2252,
868 Y => 181.1885,
869 },
870 water => 18.0153,
871 },
872 monoisotopic => {
873 DNA => { A => 331.06817, C => 307.056936, G => 347.063084, T => 322.056602 },
874 RNA => { A => 347.063084, C => 323.051851, G => 363.057999, U => 324.035867 },
875 protein => {
876 A => 89.047678, C => 121.019749, D => 133.037508, E => 147.053158, F => 165.078979, G => 75.032028,
877 H => 155.069477, I => 131.094629, K => 146.105528, L => 131.094629, M => 149.051049, N => 132.053492,
878 O => 255.158292, P => 115.063329, Q => 146.069142, R => 174.111676, S => 105.042593, T => 119.058243,
879 U => 168.964203, V => 117.078979, W => 204.089878, Y => 181.073893,
880 },
881 water => 18.010565,
882 },
883 );
884  
885 # A pattern for each capital letter, compiled once: perl 5.32 leaks a pattern
886 # that is compiled at run time, and molecular_weight would compile one for
887 # each letter on every call.
888 40 my %Letter_re = map { $_ => qr/$_/ } 'A' .. 'Z';
889  
890 32 ▶sub molecular_weight {
Subroutine molecular_weight: called CC=15 SCAR=27.1
Pod documented
891 32 my ($seq, @opt) = @_;
892 32 my $sub = 'molecular_weight';
893 32 _sequence($sub, $seq);
894 30 my $args = _args(\@opt, $sub, [], [qw(circular double_stranded monoisotopic type)]);
895 27 my %r; # the options, each resolved once
896 27 $r{type} = _seq_type($sub, $args, ['DNA', 'RNA', 'protein']);
897 26 ▶ $r{circular} = $args->{circular} ? 1 : 0; # 1 = the molecule has no ends
Branch: 1 branch
BranchTrueFalseTotal
$args->{'circular'} ? : 4 22 26
898 26 ▶ $r{double_stranded} = $args->{double_stranded} ? 1 : 0; # 1 = with the strand that pairs with it
Branch: 1 branch
BranchTrueFalseTotal
$args->{'double_stranded'} ? : 5 21 26
899 26 ▶ $r{monoisotopic} = $args->{monoisotopic} ? 1 : 0; # 1 = every atom its commonest isotope
Branch: 1 branch
BranchTrueFalseTotal
$args->{'monoisotopic'} ? : 5 21 26
900 26 ▶ croak "$sub: a protein has one strand, so \"double_stranded\" can't be used with it" if $r{double_stranded} && $r{type} eq 'protein';
Branch: 1 branch
BranchTrueFalseTotal
if $r{"double_stranded"} and $r{"type"} eq "protein" 1 25 26
Condition100%3/3
$r{"double_stranded"} and $r{"type"} eq "protein"
!ll&&!rl&&r
2141
MC/DC100%2/2
$r{"double_stranded"} and $r{"type"} eq "protein"
$r{"double_stranded"} $r{"type"} eq "protein"
Truth table100%3/3
A and B
A= $r{"double_stranded"}B= $r{"type"} eq "protein"
ABresult
0X0
100
111
901 25 ▶ my $table = $Weight{ $r{monoisotopic} ? 'monoisotopic' : 'average' };
Branch: 1 branch
BranchTrueFalseTotal
$r{'monoisotopic'} ? : 5 20 25
902 25 my $weight = $table->{ $r{type} };
903 # whitespace is dropped and case ignored, as Biopython does
904 25 (my $left = uc $seq) =~ s/\s+//g;
905 25 my $len = length $left;
906 25 ▶ croak "$sub: the sequence is empty" unless $len;
Branch: 1 branch
BranchTrueFalseTotal
unless $len 1 24 25
907 # Each letter is counted by taking it out, so that what is left when every
908 # letter of the table has gone is what the table has no weight for.
909 24 my %n;
910 24 ▶ $n{$_} = ($left =~ s/$Letter_re{$_}//g) || 0 for sort keys %{ $weight };
Condition100%2/2
$left =~ s/$Letter_re{$_}//g || 0
l!l
16098
MC/DC100%1/1
$left =~ s/$Letter_re{$_}//g || 0
$left =~ s/$Letter_re{$_}//g
Truth table100%2/2
A
A= $left =~ s/$Letter_re{$_}//g
Aresult
11
00
911 24 ▶ croak "$sub: \"" . substr($left, 0, 1) . "\" has no weight as a letter of $r{type}; only " . join('', sort keys %{ $weight }) . ' do'
Branch: 1 branch
BranchTrueFalseTotal
if length $left 3 21 24
912 if length $left;
913 # a chain of $len residues has $len - 1 bonds, and a ring has $len
914 21 my $bonds = ($len - 1 + $r{circular}) * $table->{water};
915 21 my $total = -$bonds;
916 21 $total += $n{$_} * $weight->{$_} for sort keys %{ $weight };
917 21 ▶ if ($r{double_stranded}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"double_stranded"}) 4 17 21
918 # the other strand has as many of a letter's partner as this has of it
919 4 ▶ my %pair = $r{type} eq 'DNA' ? (A => 'T', C => 'G', G => 'C', T => 'A') : (A => 'U', C => 'G', G => 'C', U => 'A');
Branch: 1 branch
BranchTrueFalseTotal
$r{'type'} eq 'DNA' ? : 3 1 4
920 4 $total -= $bonds;
921 4 $total += $n{$_} * $weight->{ $pair{$_} } for sort keys %{ $weight };
922 }
923 21 $total;
924 }
925  
926 # The pK of each group of a protein that takes or gives up a proton, for its
927 # charge at a pH. They are positive_pKs, negative_pKs, pKnterminal and
928 # pKcterminal of Biopython 1.87's Bio/SeqUtils/IsoelectricPoint.py, which
929 # takes them from Bjellqvist et al., Electrophoresis 14:1023-1031 (1993) and
930 # 15:529-539 (1994): the values ExPASy's Compute pI/Mw uses. "N" and "C" are
931 # the two ends of the chain, whose pK depends on the residue that is there:
932 # %Pk_n_end and %Pk_c_end give it for the residues that change it.
933 40 my @Pk_positive = (['N', 7.5], ['K', 10.0], ['R', 12.0], ['H', 5.98]);
934 40 my @Pk_negative = (['C_end', 3.55], ['D', 4.05], ['E', 4.45], ['C', 9.0], ['Y', 10.0]);
935 40 my %Pk_n_end = (A => 7.59, M => 7.0, S => 6.93, P => 8.36, T => 6.82, V => 7.44, E => 7.7);
936 40 my %Pk_c_end = (D => 4.55, E => 4.75);
937  
938 # How many of each charged group the protein $seq has, with the pK of each of
939 # its ends, for _charge(): [[count, pK], ...] for the groups that carry a
940 # positive charge when they hold a proton, and the same for those that carry a
941 # negative one when they have lost it. Dies, for $sub, when $seq is empty.
942 45 ▶sub _charged_groups {
Subroutine _charged_groups: called CC=6 SCAR=17.9
943 45 my ($sub, $seq) = @_;
944 45 _sequence($sub, $seq);
945 41 ▶ croak "$sub: the sequence is empty" unless length $seq;
Branch: 1 branch
BranchTrueFalseTotal
unless length $seq 2 39 41
946 39 my %n = (
947 N => 1, C_end => 1, # one of each end
948 K => ($seq =~ tr/Kk//), R => ($seq =~ tr/Rr//), H => ($seq =~ tr/Hh//),
949 D => ($seq =~ tr/Dd//), E => ($seq =~ tr/Ee//), C => ($seq =~ tr/Cc//), Y => ($seq =~ tr/Yy//),
950 );
951 39 my ($first, $last) = (uc substr($seq, 0, 1), uc substr($seq, -1));
952 39 ▶ my @positive = map { [$n{ $_->[0] }, $_->[0] eq 'N' && exists $Pk_n_end{$first} ? $Pk_n_end{$first} : $_->[1]] } @Pk_positive;
Branch: 1 branch
BranchTrueFalseTotal
$_->[0] eq 'N' && exists $Pk_n_end{$first} ? : 28 128 156
Condition100%3/3
$_->[0] eq "N" and exists $Pk_n_end{$first}
!ll&&!rl&&r
1171128
MC/DC100%2/2
$_->[0] eq "N" and exists $Pk_n_end{$first}
$_->[0] eq "N" exists $Pk_n_end{$first}
Truth table100%3/3
A and B
A= $_->[0] eq "N"B= exists $Pk_n_end{$first}
ABresult
0X0
100
111
953 39 ▶ my @negative = map { [$n{ $_->[0] }, $_->[0] eq 'C_end' && exists $Pk_c_end{$last} ? $Pk_c_end{$last} : $_->[1]] } @Pk_negative;
Branch: 1 branch
BranchTrueFalseTotal
$_->[0] eq 'C_end' && exists $Pk_c_end{$last} ? : 6 189 195
Condition100%3/3
$_->[0] eq "C_end" and exists $Pk_c_end{$last}
!ll&&!rl&&r
156336
MC/DC100%2/2
$_->[0] eq "C_end" and exists $Pk_c_end{$last}
$_->[0] eq "C_end" exists $Pk_c_end{$last}
Truth table100%3/3
A and B
A= $_->[0] eq "C_end"B= exists $Pk_c_end{$last}
ABresult
0X0
100
111
954 39 (\@positive, \@negative);
955 }
956  
957 # The charge at $ph of a protein with _charged_groups()'s $positive and
958 # $negative: by the Henderson-Hasselbalch equation, a group of pK p holds its
959 # proton for 1 / (1 + 10 ** (pH - p)) of the time. The sums are made in
960 # Biopython's order, so that they round as its charge_at_pH() does.
961 225 ▶sub _charge {
Subroutine _charge: called CC=3 SCAR=11.0
962 225 my ($positive, $negative, $ph) = @_;
963 225 my ($plus, $minus) = (0, 0);
964 225 $plus += $_->[0] * (1 / (10 ** ($ph - $_->[1]) + 1)) for @{ $positive };
965 225 $minus += $_->[0] * (1 / (10 ** ($_->[1] - $ph) + 1)) for @{ $negative };
966 225 $plus - $minus;
967 }
968  
969 31 ▶sub protein_charge {
Subroutine protein_charge: called CC=7 SCAR=19.5
Pod documented
970 31 my ($seq, $ph, @rest) = @_;
971 31 my $sub = 'protein_charge';
972 31 ▶ croak "$sub: takes two arguments, the sequence and the pH" if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 30 31
973 30 my ($positive, $negative) = _charged_groups($sub, $seq);
974 27 require Scalar::Util;
975 27 ▶ croak "$sub: the pH must be a number, not " . _what($ph)
Branch: 1 branch
BranchTrueFalseTotal
if not defined $ph or ref $ph or not &Scalar::Util::looks_like_number($ph) or $ph != $ph or $ph - $ph != 0 6 21 27
Condition91%11/12
not defined $ph or ref $ph or not &Scalar::Util::looks_like_number($ph) or $ph != $ph or $ph - $ph != 0
l!l&&r!l&&!r
4221
not defined $ph or ref $ph or not &Scalar::Util::looks_like_number($ph) or $ph != $ph
l!l&&r!l&&!r
4023
not defined $ph or ref $ph or not &Scalar::Util::looks_like_number($ph)
l!l&&r!l&&!r
2223
not defined $ph or ref $ph
l!l&&r!l&&!r
1125
MC/DC80%4/5
not defined $ph or ref $ph or not &Scalar::Util::looks_like_number($ph) or $ph != $ph or $ph - $ph != 0
not defined $ph ref $ph not &Scalar::Util::looks_like_number($ph) $ph != $ph $ph - $ph != 0
Truth table83%5/6
not(A) or B or not(C) or D or E
A= not defined $phB= ref $phC= not &Scalar::Util::looks_like_number($ph)D= $ph != $phE= $ph - $ph != 0
ABCDEresult
1XXXX1
01XXX1
001XX1
0001X1
000011
000000
976 if !defined $ph || ref $ph || !Scalar::Util::looks_like_number($ph) || $ph != $ph || $ph - $ph != 0;
977 21 _charge($positive, $negative, $ph);
978 }
979  
980 16 ▶sub isoelectric_point {
Subroutine isoelectric_point: called CC=4 SCAR=13.9
Pod documented
981 16 my ($seq, @rest) = @_;
982 16 my $sub = 'isoelectric_point';
983 16 ▶ croak "$sub: takes one argument, the sequence" if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 15 16
984 15 my ($positive, $negative) = _charged_groups($sub, $seq);
985 # Bisection, as IsoelectricPoint.pi() of Biopython 1.87 does it, from its
986 # own starting interval: 4.05 is below the pI of a protein that is all
987 # aspartate and 12 above that of one that is all arginine, and 7.775 is
988 # its first guess. It stops when the interval is 0.0001 wide or less,
989 # which is that function's limit, so the answer is good to 4 decimal
990 # places.
991 12 my ($ph, $low, $high) = (7.775, 4.05, 12);
992 12 ▶ while ($high - $low > 0.0001) {
Branch: 1 branch
BranchTrueFalseTotal
if ($high - $low > "0.0001") 204 12 216
993 204 ▶ if (_charge($positive, $negative, $ph) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (_charge($positive, $negative, $ph) > 0) { } 108 96 204
994 108 $low = $ph;
995 } else {
996 96 $high = $ph;
997 }
998 204 $ph = ($low + $high) / 2;
999 }
1000 12 $ph;
1001 }
1002  
1003 19 ▶sub subseq {
Subroutine subseq: called CC=9 SCAR=22.0
Pod documented
1004 19 my ($seq, $start, $end, @rest) = @_;
1005 19 my $sub = 'subseq';
1006 19 ▶ croak "$sub: takes the sequence, where to start and where to end" if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 18 19
1007 18 _sequence($sub, $seq);
1008 16 my $len = length $seq;
1009 16 ▶ $end //= $len;
Condition66%2/3
$end //= $len
l!l&&r!l&&!r
1510
MC/DC0%0/2
$end //= $len
$end $len
Truth table66%2/3
A //= B
A= $endB= $len
ABresult
1X1
011
000
1010 16 foreach my $p (['start', $start], ['end', $end]) {
1011 27 ▶ croak "$sub: the $p->[0] must be a whole number, 1 or more, not " . _what($p->[1])
Branch: 1 branch
BranchTrueFalseTotal
if not defined $p->[1] or ref $p->[1] or not $p->[1] =~ /\A[1-9][0-9]*\z/ 7 20 27
Condition100%6/6
not defined $p->[1] or ref $p->[1] or not $p->[1] =~ /\A[1-9][0-9]*\z/
l!l&&r!l&&!r
2520
not defined $p->[1] or ref $p->[1]
l!l&&r!l&&!r
1125
MC/DC100%3/3
not defined $p->[1] or ref $p->[1] or not $p->[1] =~ /\A[1-9][0-9]*\z/
not defined $p->[1] ref $p->[1] not $p->[1] =~ /\A[1-9][0-9]*\z/
Truth table100%4/4
not(A) or B or not(C)
A= not defined $p->[1]B= ref $p->[1]C= not $p->[1] =~ /\A[1-9][0-9]*\z/
ABCresult
1XX1
01X1
0011
0000
1012 if !defined $p->[1] || ref $p->[1] || $p->[1] !~ /\A[1-9][0-9]*\z/;
1013 }
1014 9 ▶ croak "$sub: the start, $start, is after the end, $end" if $start > $end;
Branch: 1 branch
BranchTrueFalseTotal
if $start > $end 1 8 9
1015 8 ▶ croak "$sub: the end, $end, is beyond the sequence's length, $len" if $end > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $end > $len 1 7 8
1016 7 substr $seq, $start - 1, $end - $start + 1;
1017 }
1018  
1019 # ---- FASTA index
1020 #
1021 # The index is samtools's .fai: a line for each sequence, of its name, its
1022 # length, the byte in the file where it starts, how many bases each of its
1023 # lines holds, and how many bytes each takes with its line ending. What is and
1024 # is not a sequence that can be indexed is decided as fai_build_core() of
1025 # htslib 1.25's faidx.c decides it, by Bioinf.xs's fai_scan() (since
1026 # 2026-11-18, and by a readline loop here until then), and t/faidx.t checks
1027 # the result against that library's own expected index.
1028  
1029 # The index of the FASTA $file, read from the file itself, for $sub: the text
1030 # of its .fai, with the sequences in the file's order.
1031 21 ▶sub _fai_scan {
Subroutine _fai_scan: called CC=11 SCAR=24.3
1032 21 my ($sub, $file) = @_;
1033 21 ▶ open my $fh, '<:raw', $file or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $file or croak("${sub}: can't read ${file}: $!") 21 0 21
1034 # $error is undef or one of fai_scan()'s, which Bioinf.xs lists at
1035 # fai_state; $line and $name are the line and the sequence it is in, and
1036 # $why is the system's reason for a read error
1037 21 ▶ my ($index, $dups, $error, $line, $name, $why) = _located(sub { _fai_build($fh) });
Subroutine __ANON__: called CC=1 SCAR=0.0
1038 21 carp "$sub: $file has more than one sequence named \"$_\", and the first is the one indexed" foreach @{ $dups };
1039 21 ▶ if (!defined $error) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $error) 9 12 21
1040 9 ▶ close $fh or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't read ${file}: $!") 9 0 9
1041 9 return $index;
1042 }
1043 12 ▶ croak "$sub: can't read $file: $why" if $error eq 'read';
Branch: 1 branch
BranchTrueFalseTotal
if $error eq "read" 0 12 12
1044 12 ▶ croak "$sub: the last sequence of $file has a defline and nothing more" if $error eq 'no_sequence';
Branch: 1 branch
BranchTrueFalseTotal
if $error eq "no_sequence" 4 8 12
1045 8 ▶ croak "$sub: $file has no sequences" if $error eq 'none';
Branch: 1 branch
BranchTrueFalseTotal
if $error eq "none" 2 6 8
1046 6 ▶ croak "$sub: line $line of $file comes before any defline" if $error eq 'before_defline';
Branch: 1 branch
BranchTrueFalseTotal
if $error eq "before_defline" 2 4 6
1047 4 ▶ croak "$sub: line $line of $file follows a shorter line of \"$name\", and only a sequence's last line can be shorter than its others"
Branch: 1 branch
BranchTrueFalseTotal
if $error eq "after_short" 2 2 4
1048 if $error eq 'after_short';
1049 2 ▶ croak "$sub: line $line of $file is longer than the lines before it of \"$name\", and only a sequence's last line can differ"
Branch: 1 branch
BranchTrueFalseTotal
if $error eq "longer" 2 0 2
1050 if $error eq 'longer';
1051 0 croak "_fai_scan: Bioinf.xs's fai_scan() gave \"$error\", which it has no message for"; # cannot happen
1052 }
1053  
1054 # The entries of a FASTA index, read a line at a time from $fh, which is the
1055 # .fai $what of $sub, for the names in %$want alone: a hash ref of name =>
1056 # [name, length, offset, line bases, line width], each the first line of its
1057 # name. Every line is checked, wanted or not, so that a file that isn't an
1058 # index dies whatever was asked of it.
1059 3297 ▶sub _fai_entries {
Subroutine _fai_entries: called CC=7 SCAR=19.5
1060 3297 my ($sub, $fh, $what, $want) = @_;
1061 3297 my %entry;
1062 3297 my $any = 0; # 1 = the index has had a line
1063 3297 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 19745 3296 23041
1064 19745 $line =~ s/\r?\n\z//;
1065 19745 my @f = split /\t/, $line, -1;
1066 # a FASTQ's index has a sixth column, where its qualities start
1067 croak "$sub: line $. of $what isn't a line of a FASTA index: it needs a name, a length, an offset, a line's bases and a line's width"
1068 19745 ▶ unless @f == 5 && !grep { !/\A[0-9]+\z/ } @f[1 .. 4];
Branch: 1 branch
BranchTrueFalseTotal
unless @f == 5 and not grep({not /\A[0-9]+\z/;} @f[1..4]) 1 19744 19745
Condition66%2/3
@f == 5 and not grep({not /\A[0-9]+\z/;} @f[1..4])
!ll&&!rl&&r
1019744
MC/DC50%1/2
@f == 5 and not grep({not /\A[0-9]+\z/;} @f[1..4])
@f == 5 not grep({not /\A[0-9]+\z/;} @f[1..4])
Truth table66%2/3
A and not(B)
A= @f == 5B= not grep({not /\A[0-9]+\z/;} @f[1..4])
ABresult
0X0
100
111
1069 19744 $any = 1;
1070 19744 ▶ $entry{ $f[0] } //= [$f[0], map { 0 + $_ } @f[1 .. 4]] if $want->{ $f[0] };
Branch: 1 branch
BranchTrueFalseTotal
if $$want{$f[0]} 3305 16439 19744
Condition50%1/2
$entry{$f[0]} //= [$f[0], map({0 + $_;} @f[1..4])]
l!l
03305
MC/DC0%0/1
$entry{$f[0]} //= [$f[0], map({0 + $_;} @f[1..4])]
$entry{$f[0]}
Truth table50%1/2
A
A= $entry{$f[0]}
Aresult
11
00
1071 }
1072 3296 ▶ croak "$sub: $what has no sequences" unless $any;
Branch: 1 branch
BranchTrueFalseTotal
unless $any 1 3295 3296
1073 3295 \%entry;
1074 }
1075  
1076 # Dies, for $sub, unless $file is a FASTA that can be indexed: a file that is
1077 # there, and not gzip's, since a byte of it cannot be sought.
1078 3324 ▶sub _fai_file {
Subroutine _fai_file: called CC=7 SCAR=19.5
1079 3324 my ($sub, $file) = @_;
1080 3324 ▶ croak "$sub: the FASTA must be a file name, not " . _what($file) if !defined $file || ref $file || $file eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $file or ref $file or $file eq "" 6 3318 3324
Condition100%6/6
not defined $file or ref $file or $file eq ""
l!l&&r!l&&!r
423318
not defined $file or ref $file
l!l&&r!l&&!r
223320
MC/DC100%3/3
not defined $file or ref $file or $file eq ""
not defined $file ref $file $file eq ""
Truth table100%4/4
not(A) or B or C
A= not defined $fileB= ref $fileC= $file eq ""
ABCresult
1XX1
01X1
0011
0000
1081 3318 ▶ croak "$sub: \"$file\" doesn't exist or isn't a readable file" unless -f $file && -r _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file and -r _ 1 3317 3318
Condition66%2/3
-f $file and -r _
!ll&&!rl&&r
103317
MC/DC50%1/2
-f $file and -r _
-f $file -r _
Truth table66%2/3
A and B
A= -f $fileB= -r _
ABresult
0X0
100
111
1082 3317 ▶ croak "$sub: $file is compressed, and a place in it can't be sought; decompress it first" if $file =~ /\.(?:gz|bz2|xz|zst)\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /\.(?:gz|bz2|xz|zst)\z/i 2 3315 3317
1083 }
1084  
1085 14 ▶sub fasta_index {
Subroutine fasta_index: called CC=5 SCAR=16.3
Pod documented
1086 14 my ($file, @rest) = @_;
1087 14 my $sub = 'fasta_index';
1088 14 ▶ croak "$sub: takes one argument, the FASTA file" if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 13 14
1089 13 _fai_file($sub, $file);
1090 9 my $index = _fai_scan($sub, $file);
1091 3 my $fai = "$file.fai";
1092 3 ▶ open my $fh, '>:raw', $fai or croak "$sub: can't write $fai: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $fai or croak("${sub}: can't write ${fai}: $!") 3 0 3
1093 3 ▶ print {$fh} $index or croak "$sub: can't write $fai: $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $index or croak("${sub}: can't write ${fai}: $!") 3 0 3
1094 3 ▶ close $fh or croak "$sub: can't write $fai: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't write ${fai}: $!") 3 0 3
1095 3 _wrote($fai, 46); # cyan
1096 3 $fai;
1097 }
1098  
1099 3311 ▶sub fasta_region {
Subroutine fasta_region: called CC=40 SCAR=37.2
Pod documented
1100 3311 my ($file, @regions) = @_;
1101 3311 my $sub = 'fasta_region';
1102 3311 _fai_file($sub, $file);
1103 3306 ▶ croak "$sub: needs at least one region, such as \"chr1:100-200\"" unless @regions;
Branch: 1 branch
BranchTrueFalseTotal
unless @regions 1 3305 3306
1104 3305 foreach my $r (@regions) {
1105 3331 ▶ croak "$sub: a region must be a string, such as \"chr1:100-200\", not " . _what($r) if !defined $r || ref $r;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $r or ref $r 2 3329 3331
Condition100%3/3
not defined $r or ref $r
l!l&&r!l&&!r
113329
MC/DC100%2/2
not defined $r or ref $r
not defined $r ref $r
Truth table100%3/3
not(A) or B
A= not defined $rB= ref $r
ABresult
1X1
011
000
1106 }
1107 # Only the entries of the index that a region could name are kept: the
1108 # region whole, and the name before the colon of one that could be a range
1109 # (by the pattern below). Until 2026-11-18 every entry was, as an array of
1110 # five: for two regions of a FASTA of 1,000,000 contigs (perl 5.44.0), the
1111 # peak RSS was 458 MB with its .fai and 468 MB without, and is now 13 MB
1112 # and 194 MB, most of the last being fai_scan()'s hash of every name, which
1113 # it keeps to warn of a name used twice.
1114 3303 my %asked; # each name a region could be of => 1
1115 3303 foreach my $r (@regions) {
1116 3328 $asked{$r} = 1;
1117 3328 ▶ $asked{$1} = 1 if $r =~ /\A(.*):[0-9,]*(?:-[0-9,]*)?\z/s;
Branch: 1 branch
BranchTrueFalseTotal
if $r =~ /\A(.*):[0-9,]*(?:-[0-9,]*)?\z/s 3306 22 3328
1118 }
1119 3303 my $fai = "$file.fai";
1120 3303 my ($by, $ifh);
1121 3303 ▶ if (-f $fai) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $fai) { } 3291 12 3303
1122 3291 ▶ open $ifh, '<', $fai or croak "$sub: can't read $fai: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $ifh, "<", $fai or croak("${sub}: can't read ${fai}: $!") 3291 0 3291
1123 3291 $by = _fai_entries($sub, $ifh, $fai, \%asked);
1124 3289 ▶ close $ifh or croak "$sub: can't read $fai: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $ifh or croak("${sub}: can't read ${fai}: $!") 3289 0 3289
1125 # as htslib warns; -M is the age in days, so the older file has the larger
1126 3289 ▶ carp "$sub: $fai is older than $file, and may no longer describe it" if -M $fai > -M $file;
Branch: 1 branch
BranchTrueFalseTotal
if -M $fai > -M $file 1 3288 3289
1127 } else {
1128 12 my $index = _fai_scan($sub, $file);
1129 6 ▶ open $ifh, '<', \$index or croak "$sub: can't read the index of $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $ifh, "<", \$index or croak("${sub}: can't read the index of ${file}: $!") 6 0 6
1130 6 $by = _fai_entries($sub, $ifh, "the index of $file", \%asked);
1131 6 ▶ close $ifh or croak "$sub: can't read the index of $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $ifh or croak("${sub}: can't read the index of ${file}: $!") 6 0 6
1132 }
1133 3295 ▶ open my $fh, '<:raw', $file or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $file or croak("${sub}: can't read ${file}: $!") 3295 0 3295
1134 3295 my %seq;
1135 3295 foreach my $region (@regions) {
1136 3320 ▶ next if exists $seq{$region};
Branch: 1 branch
BranchTrueFalseTotal
if exists $seq{$region} 1 3319 3320
1137 # A region that is a sequence's whole name is that sequence, even when
1138 # it could be read as a name and a range, which is how htslib's
1139 # hts_parse_region() reads "HLA-A*01:01:01:01".
1140 3319 my ($entry, $start, $end) = ($by->{$region});
1141 # "name:start-end", "name:start", "name:start-" and "name:-end", with
1142 # commas allowed in the numbers
1143 3319 ▶ if (!$entry && $region =~ /\A(.*):([0-9,]*)(?:-([0-9,]*))?\z/s && $by->{$1}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $entry and $region =~ /\A(.*):([0-9,]*)(?:-([0-9,]*))?\z/s and $by->{$1}) 3303 16 3319
Condition100%6/6
not $entry and $region =~ /\A(.*):([0-9,]*)(?:-([0-9,]*))?\z/s and $by->{$1}
!ll&&!rl&&r
1513303
not $entry and $region =~ /\A(.*):([0-9,]*)(?:-([0-9,]*))?\z/s
!ll&&!rl&&r
1413304
MC/DC100%3/3
not $entry and $region =~ /\A(.*):([0-9,]*)(?:-([0-9,]*))?\z/s and $by->{$1}
not $entry $region =~ /\A(.*):([0-9,]*)(?:-([0-9,]*))?\z/s $by->{$1}
Truth table100%4/4
not(A) and B and C
A= not $entryB= $region =~ /\A(.*):([0-9,]*)(?:-([0-9,]*))?\z/sC= $by->{$1}
ABCresult
0XX0
10X0
1100
1111
1144 3303 ▶ my ($name, $from, $to) = ($1, $2, $3 // '');
Condition100%2/2
$3 // ""
l!l
33012
MC/DC100%1/1
$3 // ""
$3
Truth table100%2/2
A
A= $3
Aresult
11
00
1145 3303 tr/,//d for $from, $to;
1146 3303 ▶ ($entry, $start, $end) = ($by->{$name}, $from, $to) if length "$from$to";
Branch: 1 branch
BranchTrueFalseTotal
if length "$from$to" 3303 0 3303
1147 }
1148 3319 ▶ croak "$sub: $file has no sequence named \"$region\"" . ($region =~ /:/ ? ', nor is it a range of one' : '') unless $entry;
Branch: 2 branches
BranchTrueFalseTotal
unless $entry 2 3317 3319
$region =~ /:/ ? : 1 1 2
1149 3317 my (undef, $len, $offset, $bases, $width) = @{ $entry };
1150 3317 ▶ $start = 1 unless defined $start && length $start;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $start and length $start 15 3302 3317
Condition100%3/3
defined $start and length $start
!ll&&!rl&&r
1413302
MC/DC100%2/2
defined $start and length $start
defined $start length $start
Truth table100%3/3
A and B
A= defined $startB= length $start
ABresult
0X0
100
111
1151 3317 ▶ my $to_end = !(defined $end && length $end); # 1 = no end was given, so it runs to the sequence's
Condition100%3/3
defined $end && length $end
!ll&&!rl&&r
1443299
MC/DC100%2/2
defined $end && length $end
defined $end length $end
Truth table100%3/3
A && B
A= defined $endB= length $end
ABresult
0X0
100
111
1152 3317 ▶ croak "$sub: the region \"$region\" starts at 0, and positions are counted from 1" if $start < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $start < 1 1 3316 3317
1153 3316 ▶ croak "$sub: the region \"$region\" ends before it starts" if !$to_end && $end < $start;
Branch: 1 branch
BranchTrueFalseTotal
if not $to_end and $end < $start 1 3315 3316
Condition100%3/3
not $to_end and $end < $start
!ll&&!rl&&r
1832971
MC/DC100%2/2
not $to_end and $end < $start
not $to_end $end < $start
Truth table100%3/3
not(A) and B
A= not $to_endB= $end < $start
ABresult
0X0
100
111
1154 # a range that runs past the sequence's end is cut short there, as
1155 # samtools faidx cuts it; one that starts past it is empty
1156 3315 ▶ $end = $len if $to_end || $end > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $to_end or $end > $len 21 3294 3315
Condition100%3/3
$to_end or $end > $len
l!l&&r!l&&!r
1833294
MC/DC100%2/2
$to_end or $end > $len
$to_end $end > $len
Truth table100%3/3
A or B
A= $to_endB= $end > $len
ABresult
1X1
011
000
1157 3315 my $want = $end - $start + 1;
1158 3315 ▶ if ($want <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($want <= 0) 2 3313 3315
1159 2 $seq{$region} = '';
1160 2 next;
1161 }
1162 3313 ▶ croak "$sub: $fai gives \"$entry->[0]\" lines of no bases" unless $bases > 0 && $width >= $bases;
Branch: 1 branch
BranchTrueFalseTotal
unless $bases > 0 and $width >= $bases 0 3313 3313
Condition33%1/3
$bases > 0 and $width >= $bases
!ll&&!rl&&r
003313
MC/DC0%0/2
$bases > 0 and $width >= $bases
$bases > 0 $width >= $bases
Truth table33%1/3
A and B
A= $bases > 0B= $width >= $bases
ABresult
0X0
100
111
1163 3313 my $skip = $start - 1; # bases before the first one wanted
1164 3313 my $in_line = $skip % $bases; # those of them on its own line
1165 3313 my $from = $offset + ($skip - $in_line) / $bases * $width + $in_line;
1166 # the bases wanted and the line endings between them
1167 3313 my $bytes = $want + int(($in_line + $want - 1) / $bases) * ($width - $bases);
1168 3313 ▶ seek $fh, $from, 0 or croak "$sub: can't seek to byte $from of $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $from, 0 or croak("${sub}: can't seek to byte $from of ${file}: $!") 3313 0 3313
1169 3313 my $buffer = '';
1170 3313 my $got = read $fh, $buffer, $bytes;
1171 3313 ▶ croak "$sub: can't read $file: $!" unless defined $got;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $got 0 3313 3313
1172 3313 $buffer =~ tr/\x21-\x7e//cd;
1173 3313 ▶ croak "$sub: the index gives \"$entry->[0]\" " . ($skip + $want) . " bases, and $file has fewer where it says they are"
Branch: 2 branches
BranchTrueFalseTotal
unless length $buffer == $want 1 3312 3313
-f $fai ? : 1 0 1
1174 . (-f $fai ? "; $fai doesn't describe this file" : '') unless length($buffer) == $want;
1175 3312 $seq{$region} = $buffer;
1176 }
1177 3290 ▶ close $fh or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't read ${file}: $!") 3290 0 3290
1178 3290 \%seq;
1179 }
1180  
1181 # ---- motifs
1182  
1183 # What each letter of a motif matches, as the inside of a character class: the
1184 # bases an IUPAC nucleotide letter stands for (Biopython 1.87's
1185 # ambiguous_dna_values, Bio/Data/IUPACData.py, with U beside T so that a motif
1186 # written either way finds DNA and RNA alike), and the amino acids that B, Z
1187 # and J stand for (its extended_protein_values). X of a protein motif is any
1188 # one character, as it is when Bio::Tools::SeqPattern of BioPerl expands it.
1189 my %Motif_class = (
1190 nucleotide => {
1191 A => 'A', C => 'C', G => 'G', T => 'TU', U => 'TU', M => 'AC', R => 'AG', W => 'ATU', S => 'CG', Y => 'CTU',
1192 K => 'GTU', V => 'ACG', H => 'ACTU', D => 'AGTU', B => 'CGTU', N => 'ACGTU',
1193 },
1194 40 protein => { (map { $_ => $_ } split //, 'ACDEFGHIKLMNOPQRSTUVWY'), B => 'DN', Z => 'EQ', J => 'IL' },
1195 );
1196  
1197 # The compiled pattern of each motif that motif_search has been given: by
1198 # "type" and then the motif for a string of letters, and under "pattern" by its
1199 # own text for a qr//.
1200 40 my %Motif_re;
1201  
1202 43 ▶sub motif_search {
Subroutine motif_search: called CC=27 SCAR=33.0
Pod documented
1203 43 my ($seq, $motif, @opt) = @_;
1204 43 my $sub = 'motif_search';
1205 43 _sequence($sub, $seq);
1206 41 my $args = _args(\@opt, $sub, [], [qw(strand type)]);
1207 38 my %r; # the options, each resolved once
1208 38 $r{type} = _seq_type($sub, $args, ['DNA', 'RNA', 'protein']);
1209 37 $r{strand} = _strand($sub, $args, '+'); # '+', '-' or 'both'
1210 36 ▶ croak "$sub: a protein has one strand, so \"strand\" can only be \"+\" with it" if $r{type} eq 'protein' && $r{strand} ne '+';
Branch: 1 branch
BranchTrueFalseTotal
if $r{"type"} eq "protein" and $r{"strand"} ne "+" 1 35 36
Condition100%3/3
$r{"type"} eq "protein" and $r{"strand"} ne "+"
!ll&&!rl&&r
3231
MC/DC100%2/2
$r{"type"} eq "protein" and $r{"strand"} ne "+"
$r{"type"} eq "protein" $r{"strand"} ne "+"
Truth table100%3/3
A and B
A= $r{"type"} eq "protein"B= $r{"strand"} ne "+"
ABresult
0X0
100
111
1211 # The motif as a pattern that matches without moving on, so that the next
1212 # search starts one letter along and hits that overlap are all found. It
1213 # is compiled once for each motif and kept in %Motif_re, since perl 5.32
1214 # leaks a pattern that is compiled at run time, and is used alone in the
1215 # match below.
1216 35 my $re;
1217 35 ▶ if (re::is_regexp($motif)) {
Branch: 2 branches
BranchTrueFalseTotal
if (&re::is_regexp($motif)) { } 4 31 35
elsif (defined $motif and not ref $motif and $Motif_re{$r{'type'}}{$motif}) { } 12 19 31
1218 4 ▶ $re = $Motif_re{pattern}{"$motif"} //= qr/(?=($motif))/;
Condition50%1/2
$Motif_re{"pattern"}{"$motif"} //= qr/(?=($motif))/
l!l
04
MC/DC0%0/1
$Motif_re{"pattern"}{"$motif"} //= qr/(?=($motif))/
$Motif_re{"pattern"}{"$motif"}
Truth table50%1/2
A
A= $Motif_re{"pattern"}{"$motif"}
Aresult
11
00
1219 ▶ } elsif (defined $motif && !ref $motif && $Motif_re{ $r{type} }{$motif}) {
Condition100%6/6
defined $motif and not ref $motif and $Motif_re{$r{"type"}}{$motif}
!ll&&!rl&&r
21712
defined $motif and not ref $motif
!ll&&!rl&&r
1129
MC/DC100%3/3
defined $motif and not ref $motif and $Motif_re{$r{"type"}}{$motif}
defined $motif not ref $motif $Motif_re{$r{"type"}}{$motif}
Truth table100%4/4
A and not(B) and C
A= defined $motifB= not ref $motifC= $Motif_re{$r{"type"}}{$motif}
ABCresult
0XX0
10X0
1100
1111
1220 12 $re = $Motif_re{ $r{type} }{$motif};
1221 } else {
1222 19 ▶ croak "$sub: the motif must be a string of IUPAC letters or a qr// pattern, not " . _what($motif)
Branch: 1 branch
BranchTrueFalseTotal
if not defined $motif or ref $motif or $motif eq "" 3 16 19
Condition100%6/6
not defined $motif or ref $motif or $motif eq ""
l!l&&r!l&&!r
2116
not defined $motif or ref $motif
l!l&&r!l&&!r
1117
MC/DC100%3/3
not defined $motif or ref $motif or $motif eq ""
not defined $motif ref $motif $motif eq ""
Truth table100%4/4
not(A) or B or C
A= not defined $motifB= ref $motifC= $motif eq ""
ABCresult
1XX1
01X1
0011
0000
1223 if !defined $motif || ref $motif || $motif eq '';
1224 16 ▶ my $class = $Motif_class{ $r{type} eq 'protein' ? 'protein' : 'nucleotide' };
Branch: 1 branch
BranchTrueFalseTotal
$r{'type'} eq 'protein' ? : 3 13 16
1225 16 my $pattern = '';
1226 16 foreach my $letter (split //, uc $motif) {
1227 70 ▶ if ($r{type} eq 'protein' && $letter eq 'X') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"type"} eq "protein" and $letter eq "X") 1 69 70
Condition100%3/3
$r{"type"} eq "protein" and $letter eq "X"
!ll&&!rl&&r
6271
MC/DC100%2/2
$r{"type"} eq "protein" and $letter eq "X"
$r{"type"} eq "protein" $letter eq "X"
Truth table100%3/3
A and B
A= $r{"type"} eq "protein"B= $letter eq "X"
ABresult
0X0
100
111
1228 1 $pattern .= '.';
1229 1 next;
1230 }
1231 croak "$sub: \"$letter\" of the motif \"$motif\" isn't a letter of $r{type}; a pattern is given as qr//"
1232 69 ▶ unless exists $class->{$letter};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $class->{$letter} 3 66 69
1233 66 ▶ $pattern .= length $class->{$letter} > 1 ? "[$class->{$letter}]" : $class->{$letter};
Branch: 1 branch
BranchTrueFalseTotal
length $class->{$letter} > 1 ? : 23 43 66
1234 }
1235 13 $re = $Motif_re{ $r{type} }{$motif} = qr/(?=($pattern))/is;
1236 }
1237 29 my $len = length $seq;
1238 29 my @hit;
1239 29 ▶ foreach my $strand ($r{strand} eq 'both' ? (1, -1) : $r{strand} eq '+' ? 1 : -1) {
Branch: 2 branches
BranchTrueFalseTotal
$r{'strand'} eq 'both' ? : 4 25 29
$r{'strand'} eq '+' ? : 20 5 25
1240 33 ▶ my $text = $strand > 0 ? "$seq" : scalar reverse _complement($sub, $seq, type => $r{type});
Branch: 1 branch
BranchTrueFalseTotal
$strand > 0 ? : 24 9 33
1241 33 ▶ while ($text =~ /$re/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /$re/g) 191 33 224
1242 191 ▶ next unless $+[1] > $-[1]; # a pattern that can match nothing does, everywhere
Branch: 1 branch
BranchTrueFalseTotal
unless $+[1] > $-[1] 5 186 191
1243 186 ▶ push @hit, {
Branch: 2 branches
BranchTrueFalseTotal
$strand > 0 ? : 120 66 186
$strand > 0 ? : 120 66 186
1244 start => $strand > 0 ? $-[1] + 1 : $len - $+[1] + 1, end => $strand > 0 ? $+[1] : $len - $-[1],
1245 strand => $strand, match => $1,
1246 };
1247 }
1248 }
1249 29 ▶ [sort { $a->{start} <=> $b->{start} || $a->{end} <=> $b->{end} || $b->{strand} <=> $a->{strand} } @hit];
Condition66%4/6
$Cn::Bioinf::a->{'start'} <=> $Cn::Bioinf::b->{'start'} || $Cn::Bioinf::a->{'end'} <=> $Cn::Bioinf::b->{'end'} || $Cn::Bioinf::b->{'strand'} <=> $Cn::Bioinf::a->{'strand'}
l!l&&r!l&&!r
313140
$Cn::Bioinf::a->{"start"} <=> $Cn::Bioinf::b->{"start"} or $Cn::Bioinf::a->{"end"} <=> $Cn::Bioinf::b->{"end"}
l!l&&r!l&&!r
313014
MC/DC0%0/3
$Cn::Bioinf::a->{'start'} <=> $Cn::Bioinf::b->{'start'} || $Cn::Bioinf::a->{'end'} <=> $Cn::Bioinf::b->{'end'} || $Cn::Bioinf::b->{'strand'} <=> $Cn::Bioinf::a->{'strand'}
$Cn::Bioinf::a->{"start"} <=> $Cn::Bioinf::b->{"start"} $Cn::Bioinf::a->{"end"} <=> $Cn::Bioinf::b->{"end"} $Cn::Bioinf::b->{'strand'} <=> $Cn::Bioinf::a->{'strand'}
Truth table50%2/4
A or B || C
A= $Cn::Bioinf::a->{"start"} <=> $Cn::Bioinf::b->{"start"}B= $Cn::Bioinf::a->{"end"} <=> $Cn::Bioinf::b->{"end"}C= $Cn::Bioinf::b->{'strand'} <=> $Cn::Bioinf::a->{'strand'}
ABCresult
1XX1
01X1
0011
0000
1250 }
1251  
1252 # ---- BLAST
1253  
1254 25 ▶sub get_best_alignment_hit {
Subroutine get_best_alignment_hit: called CC=44 SCAR=38.4
Pod documented
1255 25 my ($json_file, $sort_criterion) = @_;
1256 25 ▶ $sort_criterion //= 'evalue';
Condition100%2/2
$sort_criterion //= "evalue"
l!l
817
MC/DC100%1/1
$sort_criterion //= "evalue"
$sort_criterion
Truth table100%2/2
A
A= $sort_criterion
Aresult
11
00
1257 # For each query in one BLAST JSON file (-outfmt 15), that query's hits as
1258 # an array sorted best-first on $sort_criterion, one element per hit: the
1259 # hit's single best hsp plus the fields that say which subject it is.
1260 #
1261 # The hits are an array, not a hash on the hit title, because two hits can
1262 # share a title (one protein deposited under two accessions): in
1263 # identify.target/potato/new/f.sambunicum.json 76 hits carry 44 distinct
1264 # titles, and a hash kept 44.
1265 25 ▶ croak "get_best_alignment_hit: undef isn't a readable file" unless defined $json_file;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $json_file 1 24 25
1266 24 ▶ croak "get_best_alignment_hit: \"$json_file\" doesn't exist or isn't a readable file" unless -f $json_file && -r _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $json_file and -r _ 1 23 24
Condition66%2/3
-f $json_file and -r _
!ll&&!rl&&r
1023
MC/DC50%1/2
-f $json_file and -r _
-f $json_file -r _
Truth table66%2/3
A and B
A= -f $json_fileB= -r _
ABresult
0X0
100
111
1267 # Which way is better for each numeric hsp field: -1 = smaller, 1 = larger.
1268 # The other hsp keys (hseq, qseq, midline, num, *_from/*_to) are content
1269 # or position, not quality.
1270 23 my %better = (align_len => 1, bit_score => 1, evalue => -1, gaps => -1, identity => 1, positive => 1, score => 1);
1271 23 ▶ my $direction = $better{$sort_criterion}
Condition100%2/2
$better{$sort_criterion} // croak(qq[get_best_alignment_hit: "$sort_criterion" isn't a sortable hsp field; use one of ] . join(", ", sort(keys %better)))
l!l
221
MC/DC100%1/1
$better{$sort_criterion} // croak(qq[get_best_alignment_hit: "$sort_criterion" isn't a sortable hsp field; use one of ] . join(", ", sort(keys %better)))
$better{$sort_criterion}
Truth table100%2/2
A
A= $better{$sort_criterion}
Aresult
11
00
1272 // croak "get_best_alignment_hit: \"$sort_criterion\" isn't a sortable hsp field; use one of " . join(', ', sort keys %better);
1273 22 my $blast = _json_file('get_best_alignment_hit', $json_file);
1274 croak "get_best_alignment_hit: $json_file isn't a BLAST report in JSON (-outfmt 15): it has no \"BlastOutput2\" array"
1275 20 ▶ unless ref $blast eq 'HASH' && ref $blast->{BlastOutput2} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $blast eq "HASH" and ref $blast->{"BlastOutput2"} eq "ARRAY" 2 18 20
Condition100%3/3
ref $blast eq "HASH" and ref $blast->{"BlastOutput2"} eq "ARRAY"
!ll&&!rl&&r
1118
MC/DC100%2/2
ref $blast eq "HASH" and ref $blast->{"BlastOutput2"} eq "ARRAY"
ref $blast eq "HASH" ref $blast->{"BlastOutput2"} eq "ARRAY"
Truth table100%3/3
A and B
A= ref $blast eq "HASH"B= ref $blast->{"BlastOutput2"} eq "ARRAY"
ABresult
0X0
100
111
1276 18 my %alignments;
1277 18 foreach my $i (0 .. $#{ $blast->{BlastOutput2} }) {
1278 19 my $report = $blast->{BlastOutput2}[$i];
1279 my $search = ref $report eq 'HASH' && ref $report->{report} eq 'HASH' && ref $report->{report}{results} eq 'HASH'
1280 19 ▶ ? $report->{report}{results}{search} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $report eq 'HASH' && ref $report->{'report'} eq 'HASH' && ref $report->{'report'}{'results'} eq 'HASH' ? : 18 1 19
Condition66%4/6
ref $report eq "HASH" and ref $report->{"report"} eq "HASH" and ref $report->{"report"}{"results"} eq "HASH"
!ll&&!rl&&r
1018
ref $report eq "HASH" and ref $report->{"report"} eq "HASH"
!ll&&!rl&&r
1018
MC/DC33%1/3
ref $report eq "HASH" and ref $report->{"report"} eq "HASH" and ref $report->{"report"}{"results"} eq "HASH"
ref $report eq "HASH" ref $report->{"report"} eq "HASH" ref $report->{"report"}{"results"} eq "HASH"
Truth table50%2/4
A and B and C
A= ref $report eq "HASH"B= ref $report->{"report"} eq "HASH"C= ref $report->{"report"}{"results"} eq "HASH"
ABCresult
0XX0
10X0
1100
1111
1281 19 ▶ croak "get_best_alignment_hit: report " . ($i + 1) . " of $json_file has no report.results.search" unless ref $search eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $search eq "HASH" 1 18 19
1282 # BLAST titles a query by its defline, and a query with none by its
1283 # query_id alone.
1284 18 ▶ my $query = $search->{query_title} // $search->{query_id};
Condition100%3/3
$search->{"query_title"} // $search->{"query_id"}
l!l&&r!l&&!r
1611
MC/DC100%2/2
$search->{"query_title"} // $search->{"query_id"}
$search->{"query_title"} $search->{"query_id"}
Truth table100%3/3
A // B
A= $search->{"query_title"}B= $search->{"query_id"}
ABresult
1X1
011
000
1285 18 ▶ croak "get_best_alignment_hit: report " . ($i + 1) . " of $json_file names no query: it has no query_title or query_id" unless defined $query;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $query 1 17 18
1286 # Each hit's shape is checked before it is read. Up to 2026-11-10 "hits"
1287 # as an object died with perl's "Not an ARRAY reference", naming no
1288 # function, and an hsp with no bit_score, which BLAST always writes,
1289 # warned "uninitialized" each time it broke a tie; it now ties.
1290 17 ▶ my $listed = $search->{hits} // [];
Condition50%1/2
$search->{"hits"} // []
l!l
170
MC/DC0%0/1
$search->{"hits"} // []
$search->{"hits"}
Truth table50%1/2
A
A= $search->{"hits"}
Aresult
11
00
1291 17 ▶ croak "get_best_alignment_hit: report " . ($i + 1) . " of $json_file has \"hits\" that isn't an array, but " . _what($listed)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $listed eq "ARRAY" 1 16 17
1292 unless ref $listed eq 'ARRAY';
1293 16 my @hits;
1294 16 foreach my $h (0 .. $#{ $listed }) {
1295 46 my $hit = $listed->[$h];
1296 croak "get_best_alignment_hit: hit " . ($h + 1) . " of report " . ($i + 1) . " of $json_file isn't a hit, which is an object whose \"description\" and \"hsps\" are arrays of objects"
1297 unless ref $hit eq 'HASH' && ref($hit->{description} // []) eq 'ARRAY' && ref($hit->{hsps} // []) eq 'ARRAY'
1298 46 ▶ && !grep { ref $_ ne 'HASH' } @{ $hit->{description} // [] }, @{ $hit->{hsps} // [] };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $hit eq "HASH" and ref($hit->{"description"} // []) eq "ARRAY" and ref($hit->{"hsps"} // []) eq "ARRAY" and not grep({ref $_ ne "HASH";} @{$hit->{"description"} // [];}, @{$hit->{"hsps"} // [];}) 2 44 46
Condition76%13/17
ref $hit eq "HASH" and ref($hit->{"description"} // []) eq "ARRAY" and ref($hit->{"hsps"} // []) eq "ARRAY" and not grep({ref $_ ne "HASH";} @{$hit->{"description"} // [];}, @{$hit->{"hsps"} // [];})
!ll&&!rl&&r
2044
ref $hit eq "HASH" and ref($hit->{"description"} // []) eq "ARRAY" and ref($hit->{"hsps"} // []) eq "ARRAY"
!ll&&!rl&&r
1144
ref $hit eq "HASH" and ref($hit->{"description"} // []) eq "ARRAY"
!ll&&!rl&&r
1045
$hit->{"description"} // []
l!l
432
$hit->{"hsps"} // []
l!l
450
$hit->{"description"} // []
l!l
431
$hit->{"hsps"} // []
l!l
440
MC/DC25%1/4
ref $hit eq "HASH" and ref($hit->{"description"} // []) eq "ARRAY" and ref($hit->{"hsps"} // []) eq "ARRAY" and not grep({ref $_ ne "HASH";} @{$hit->{"description"} // [];}, @{$hit->{"hsps"} // [];})
ref $hit eq "HASH" $hit->{"description"} $hit->{"hsps"} not grep({ref $_ ne "HASH";} @{$hit->{"description"} // [];}, @{$hit->{"hsps"} // [];})
Truth table40%2/5
A and B and C and not(D)
A= ref $hit eq "HASH"B= $hit->{"description"}C= $hit->{"hsps"}D= not grep({ref $_ ne "HASH";} @{$hit->{"description"} // [];}, @{$hit->{"hsps"} // [];})
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1299 44 ▶ my $first = ($hit->{description} // [])->[0] // {}; # the description the hit is named by; empty when it has none
Condition100%4/4
+($hit->{"description"} // [])->[0] // {}
l!l
431
$hit->{"description"} // []
l!l
431
MC/DC100%1/1
+($hit->{"description"} // [])->[0] // {}
$hit->{"description"}
Truth table100%2/2
A
A= $hit->{"description"}
Aresult
11
00
1300 44 my $best; # undef until an hsp is seen; a hit with no hsps has nothing to record
1301 44 ▶ foreach my $hsp (@{ $hit->{hsps} // [] }) {
Condition50%1/2
$hit->{"hsps"} // []
l!l
440
MC/DC0%0/1
$hit->{"hsps"} // []
$hit->{"hsps"}
Truth table50%1/2
A
A= $hit->{"hsps"}
Aresult
11
00
1302 croak "get_best_alignment_hit: an hsp of " . _what($first->{title}) . " in $json_file has no \"$sort_criterion\" to sort on"
1303 61 ▶ unless defined $hsp->{$sort_criterion};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hsp->{$sort_criterion} 0 61 61
1304 61 ▶ unless (defined $best) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $best) 44 17 61
1305 44 $best = $hsp;
1306 44 next;
1307 }
1308 17 my $cmp = $direction * ($hsp->{$sort_criterion} <=> $best->{$sort_criterion});
1309 # BLAST rounds any strong e-value to 0, so ties are the rule; the bit score breaks them
1310 17 ▶ $cmp = ($hsp->{bit_score} // 0) <=> ($best->{bit_score} // 0) if $cmp == 0 && $sort_criterion ne 'bit_score';
Branch: 1 branch
BranchTrueFalseTotal
if $cmp == 0 and $sort_criterion ne "bit_score" 2 15 17
Condition85%6/7
$cmp == 0 and $sort_criterion ne "bit_score"
!ll&&!rl&&r
1502
$hsp->{"bit_score"} // 0
l!l
11
$best->{"bit_score"} // 0
l!l
11
MC/DC50%1/2
$cmp == 0 and $sort_criterion ne "bit_score"
$cmp == 0 $sort_criterion ne "bit_score"
MC/DC100%1/1
$hsp->{"bit_score"} // 0
$hsp->{"bit_score"}
MC/DC100%1/1
$best->{"bit_score"} // 0
$best->{"bit_score"}
Truth table66%2/3
A and B
A= $cmp == 0B= $sort_criterion ne "bit_score"
ABresult
0X0
100
111
Truth table100%2/2
A
A= $hsp->{"bit_score"}
Aresult
11
00
Truth table100%2/2
A
A= $best->{"bit_score"}
Aresult
11
00
1311 17 ▶ $best = $hsp if $cmp > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cmp > 0 3 14 17
1312 }
1313 44 ▶ next unless defined $best;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $best 0 44 44
1314 # A shallow copy (an hsp holds only numbers and strings), so these
1315 # fields are not written into $blast. The hit's own "num" is not
1316 # merged, as it would shadow the hsp's; its "len" is the subject's
1317 # full length, so it arrives as "hit_len" beside the hsp's "align_len".
1318 # A hit has one description for each identical sequence in a
1319 # non-redundant database such as nr; it is named by the first, as
1320 # BLAST lists it, and every one is in "descriptions". Up to
1321 # 2026-10-17 a hit with more than one died.
1322 44 push @hits, { %{ $best },
1323 accession => $first->{accession},
1324 44 ▶ descriptions => [map { +{ %{ $_ } } } @{ $hit->{description} // [] }],
Condition100%2/2
$hit->{"description"} // []
l!l
431
MC/DC100%1/1
$hit->{"description"} // []
$hit->{"description"}
Truth table100%2/2
A
A= $hit->{"description"}
Aresult
11
00
1325 hit_len => $hit->{len},
1326 id => $first->{id},
1327 title => $first->{title},
1328 44 };
1329 }
1330 # Indices are sorted so the last tiebreak can be BLAST's own order; the
1331 # array runs best-first, hence $b before $a.
1332 my @order = sort {
1333 14 ($direction * ($hits[$b]{$sort_criterion} <=> $hits[$a]{$sort_criterion}))
1334 65 ▶ || (($hits[$b]{bit_score} // 0) <=> ($hits[$a]{bit_score} // 0))
Condition70%7/10
$direction * ($hits[$b]{$sort_criterion} <=> $hits[$a]{$sort_criterion}) || ($hits[$b]{'bit_score'} // 0) <=> ($hits[$a]{'bit_score'} // 0) || $a <=> $b
l!l&&r!l&&!r
49160
$direction * ($hits[$b]{$sort_criterion} <=> $hits[$a]{$sort_criterion}) or ($hits[$b]{"bit_score"} // 0) <=> ($hits[$a]{"bit_score"} // 0)
l!l&&r!l&&!r
40916
$hits[$b]{"bit_score"} // 0
l!l
250
$hits[$a]{"bit_score"} // 0
l!l
250
MC/DC0%0/3
$direction * ($hits[$b]{$sort_criterion} <=> $hits[$a]{$sort_criterion}) || ($hits[$b]{'bit_score'} // 0) <=> ($hits[$a]{'bit_score'} // 0) || $a <=> $b
$direction * ($hits[$b]{$sort_criterion} <=> $hits[$a]{$sort_criterion}) $hits[$b]{"bit_score"} $a <=> $b
MC/DC0%0/1
$hits[$a]{"bit_score"} // 0
$hits[$a]{"bit_score"}
Truth table50%2/4
A or B || C
A= $direction * ($hits[$b]{$sort_criterion} <=> $hits[$a]{$sort_criterion})B= $hits[$b]{"bit_score"}C= $a <=> $b
ABCresult
1XX1
01X1
0011
0000
Truth table50%1/2
A
A= $hits[$a]{"bit_score"}
Aresult
11
00
1335 || ($a <=> $b)
1336 } 0 .. $#hits;
1337 # Two queries of one title would leave only the second's hits, so that
1338 # is refused rather than lost silently.
1339 14 ▶ croak "get_best_alignment_hit: two queries in $json_file are both titled \"$query\"" if exists $alignments{$query};
Branch: 1 branch
BranchTrueFalseTotal
if exists $alignments{$query} 1 13 14
1340 13 $alignments{$query} = [ @hits[@order] ];
1341 }
1342 12 \%alignments;
1343 }
1344  
1345 # ---- polygenic scores
1346  
1347 # The rows of $frame, given to $sub as $what, as an array ref of hash refs, in
1348 # whichever of Stats::LikeR's four shapes it comes: an array of hashes
1349 # (read_table's default), a hash of hashes (its default for a VCF), a hash of
1350 # arrays, or an array of arrays whose first row is the header. A row of an AoH or
1351 # HoH is the frame's own hash, and is only read; one of a HoA or AoA is made
1352 # here. With $labelled, also returns how a message names each row: "row 3",
1353 # counting data rows from 1, or 'row "key"' for a hash of hashes, whose rows are
1354 # then in key order so that the first bad one is always the same one.
1355 53 ▶sub _frame_rows {
Subroutine _frame_rows: called CC=25 SCAR=32.2
1356 53 my ($sub, $what, $frame, $labelled) = @_;
1357 53 my $shapes = 'an array of hashes or of arrays, or a hash of hashes or of arrays, as Stats::LikeR\'s read_table returns';
1358 53 my (@rows, @labels);
1359 53 ▶ if (ref $frame eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $frame eq 'ARRAY') { } 44 9 53
elsif (ref $frame eq 'HASH') { } 9 0 9
1360 44 ▶ croak "$sub: \"$what\" has no rows" unless @{ $frame };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$frame;} 1 43 44
1361 43 ▶ if (ref $frame->[0] eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $frame->[0] eq 'HASH') { } 37 6 43
elsif (ref $frame->[0] eq 'ARRAY') { } 5 1 6
1362 37 @rows = @{ $frame };
1363 } elsif (ref $frame->[0] eq 'ARRAY') {
1364 5 my ($head, @data) = @{ $frame };
1365 5 ▶ croak "$sub: \"$what\" has a header and no rows" unless @data;
Branch: 1 branch
BranchTrueFalseTotal
unless @data 1 4 5
1366 4 foreach my $i (0 .. $#data) {
1367 4 ▶ croak "$sub: row " . ($i + 1) . " of \"$what\" must be an array ref, as its header is, not " . _what($data[$i])
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data[$i] eq "ARRAY" 1 3 4
1368 unless ref $data[$i] eq 'ARRAY';
1369 2 croak "$sub: row " . ($i + 1) . " of \"$what\" has " . scalar(@{ $data[$i] }) . ' fields, and its header ' . scalar(@{ $head })
1370 3 ▶ unless @{ $data[$i] } == @{ $head };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$data[$i];} == @{$head;} 2 1 3
1371 1 my %row;
1372 1 @row{ @{ $head } } = @{ $data[$i] };
1373 1 push @rows, \%row;
1374 }
1375 } else {
1376 1 croak "$sub: \"$what\" must be $shapes, not an array whose first row is " . _what($frame->[0]);
1377 }
1378 38 ▶ @labels = map { "row $_" } 1 .. @rows if $labelled;
Branch: 1 branch
BranchTrueFalseTotal
if $labelled 28 10 38
1379 } elsif (ref $frame eq 'HASH') {
1380 9 my ($key, $first) = each %{ $frame };
1381 9 keys %{ $frame }; # resets the iterator that each left part-way
1382 9 ▶ croak "$sub: \"$what\" has no rows" unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 1 8 9
1383 8 ▶ if (ref $first eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $first eq 'HASH') { } 4 4 8
elsif (ref $first eq 'ARRAY') { } 3 1 4
1384 4 ▶ if ($labelled) {
Branch: 1 branch
BranchTrueFalseTotal
if ($labelled) { } 1 3 4
1385 1 my @keys = sort keys %{ $frame };
1386 1 @rows = @{ $frame }{@keys};
1387 1 @labels = map { "row \"$_\"" } @keys;
1388 } else {
1389 3 @rows = values %{ $frame };
1390 }
1391 } elsif (ref $first eq 'ARRAY') {
1392 # sorted, so that the column a length is compared with, and named
1393 # when it differs, is not the hash's order
1394 3 my @cols = sort keys %{ $frame };
1395 3 foreach my $c (@cols) {
1396 croak "$sub: column \"$c\" of \"$what\" must be an array ref, as \"$key\" is, not " . _what($frame->{$c})
1397 10 ▶ unless ref $frame->{$c} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $frame->{$c} eq "ARRAY" 1 9 10
1398 9 my $n = @{ $frame->{$c} };
1399 1 croak "$sub: column \"$c\" of \"$what\" has $n value" . ($n == 1 ? '' : 's') . ", and \"$cols[0]\" " . scalar(@{ $frame->{ $cols[0] } })
1400 9 ▶ unless $n == @{ $frame->{ $cols[0] } };
Branch: 2 branches
BranchTrueFalseTotal
unless $n == @{$$frame{$cols[0]};} 1 8 9
$n == 1 ? : 1 0 1
1401 }
1402 1 foreach my $i (0 .. $#{ $first }) {
1403 2 push @rows, { map { $_ => $frame->{$_}[$i] } @cols };
1404 }
1405 1 ▶ croak "$sub: \"$what\" has no rows" unless @rows;
Branch: 1 branch
BranchTrueFalseTotal
unless @rows 0 1 1
1406 1 ▶ @labels = map { "row $_" } 1 .. @rows if $labelled;
Branch: 1 branch
BranchTrueFalseTotal
if $labelled 1 0 1
1407 } else {
1408 1 croak "$sub: \"$what\" must be $shapes, not a hash whose \"$key\" is " . _what($first);
1409 }
1410 } else {
1411 0 croak "$sub: \"$what\" must be $shapes, not " . _what($frame);
1412 }
1413 43 foreach my $i (0 .. $#rows) {
1414 64 ▶ croak "$sub: row " . ($i + 1) . " of \"$what\" must be a hash ref, not " . _what($rows[$i]) unless ref $rows[$i] eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rows[$i] eq "HASH" 1 63 64
1415 }
1416 42 ▶ $labelled ? (\@rows, \@labels) : \@rows;
Branch: 1 branch
BranchTrueFalseTotal
$labelled ? : 29 13 42
1417 }
1418  
1419 # A chromosome's name as a VCF, PLINK 2 and a scoring file are compared on: in
1420 # upper case, without UCSC's "chr" prefix (GRCh37's own names, and the PGS
1421 # Catalog's, have none), with PLINK's numeric codes for the sex and
1422 # mitochondrial chromosomes and UCSC's "M" named as Ensembl names them, and with
1423 # X's pseudo-autosomal regions, which PLINK 2 names PAR1 and PAR2 (or XY, its
1424 # 25) once --split-par has split them off, taken as X.
1425 40 my %Chrom_alias = (23 => 'X', 24 => 'Y', 25 => 'X', 26 => 'MT', M => 'MT', PAR1 => 'X', PAR2 => 'X', XY => 'X');
1426 10 ▶sub _chrom {
Subroutine _chrom: called CC=2 SCAR=7.6
1427 10 my $c = uc $_[0];
1428 10 $c =~ s/\ACHR//;
1429 10 ▶ $Chrom_alias{$c} // $c;
Condition33%1/3
$Chrom_alias{$c} // $c
l!l&&r!l&&!r
0100
MC/DC0%0/2
$Chrom_alias{$c} // $c
$Chrom_alias{$c} $c
Truth table33%1/3
A // B
A= $Chrom_alias{$c}B= $c
ABresult
1X1
011
000
1430 }
1431  
1432 # A decimal number, as an effect_weight must be. Infinity and NaN, which
1433 # looks_like_number would take, are left out, as either would make every score
1434 # the same non-number.
1435 40 my $Number = qr/\A[-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][-+]?[0-9]+)?\z/;
1436  
1437 # The rows of the option $what ("weights" for pgs_score, "model" for
1438 # trait_predict) one at a time, each a hash ref with how a message names it,
1439 # and the column names: from a data frame (see _frame_rows), or read from a
1440 # tab-separated file a line at a time, so that a score of millions of variants
1441 # is never held whole. An empty field of a file is '', where read_table gives
1442 # undef; every check below treats the two alike.
1443 49 ▶sub _weight_rows {
Subroutine _weight_rows: called CC=13 SCAR=25.7
1444 49 my ($sub, $weights, $what) = @_;
1445 49 ▶ $what //= 'weights';
Condition100%2/2
$what //= "weights"
l!l
2227
MC/DC100%1/1
$what //= "weights"
$what
Truth table100%2/2
A
A= $what
Aresult
11
00
1446 49 ▶ if (ref $weights) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $weights) 38 11 49
1447 38 my ($rows, $labels) = _frame_rows($sub, $what, $weights, 1);
1448 29 my $i = 0;
1449 29 ▶ return (sub { $i < @{ $rows } ? ($rows->[$i], $labels->[$i++]) : () }, [keys %{ $rows->[0] }]);
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$i < @{$rows;} ? : 34 14 48
1450 }
1451 11 ▶ croak "$sub: \"$what\" file \"$weights\" doesn't exist or isn't readable" unless -f $weights && -r _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $weights and -r _ 2 9 11
Condition66%2/3
-f $weights and -r _
!ll&&!rl&&r
209
MC/DC50%1/2
-f $weights and -r _
-f $weights -r _
Truth table66%2/3
A and B
A= -f $weightsB= -r _
ABresult
0X0
100
111
1452 9 my $fh;
1453 9 ▶ if ($weights =~ /\.gz\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weights =~ /\.gz\z/i) { } 2 7 9
1454 2 require IO::Uncompress::Gunzip;
1455 2 ▶ $fh = IO::Uncompress::Gunzip->new($weights, MultiStream => 1)
Branch: 1 branch
BranchTrueFalseTotal
$fh = "IO::Uncompress::Gunzip"->new($weights, "MultiStream", 1) or croak("${sub}: can't read ${weights}: $IO::Uncompress::Gunzip::GunzipError") 2 0 2
1456 or croak "$sub: can't read $weights: $IO::Uncompress::Gunzip::GunzipError";
1457 } else {
1458 7 ▶ open $fh, '<:raw', $weights or croak "$sub: can't read $weights: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<:raw", $weights or croak("${sub}: can't read ${weights}: $!") 7 0 7
1459 }
1460 9 my $n = 0; # rows read so far
1461 # IO::Uncompress::Gunzip ends a truncated or corrupt stream as if it were
1462 # the end of the file, and says so only in its error(), which reading a
1463 # .gz to the end therefore checks
1464 8 ▶ my $whole = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1465 8 ▶ return unless ref $fh ne 'GLOB' && $fh->error;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $fh ne "GLOB" and $fh->error 7 1 8
Condition100%3/3
ref $fh ne "GLOB" and $fh->error
!ll&&!rl&&r
611
MC/DC100%2/2
ref $fh ne "GLOB" and $fh->error
ref $fh ne "GLOB" $fh->error
Truth table100%3/3
A and B
A= ref $fh ne "GLOB"B= $fh->error
ABresult
0X0
100
111
1466 1 ▶ croak "$sub: \"$what\" file $weights ends early or is corrupt, " . ($n ? "after row $n" : 'before its first row') . ': ' . $fh->error;
Branch: 1 branch
BranchTrueFalseTotal
$n ? : 1 0 1
1467 9 };
1468 9 my $head;
1469 9 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 55 1 56
1470 55 $line =~ s/\r?\n\z//;
1471 55 ▶ next if $line eq '' || $line =~ /\A#/;
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" or $line =~ /\A#/ 47 8 55
Condition66%2/3
$line eq "" or $line =~ /\A#/
l!l&&r!l&&!r
0478
MC/DC50%1/2
$line eq "" or $line =~ /\A#/
$line eq "" $line =~ /\A#/
Truth table66%2/3
A or B
A= $line eq ""B= $line =~ /\A#/
ABresult
1X1
011
000
1472 8 $head = $line;
1473 8 last;
1474 }
1475 9 ▶ $whole->() unless defined $head;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $head 1 8 9
1476 9 ▶ croak "$sub: \"$what\" file $weights has no header line" unless defined $head;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $head 1 8 9
1477 8 my @cols = split /\t/, $head, -1;
1478 29757 ▶ my $next = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1479 29757 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 29750 7 29757
1480 29750 $line =~ s/\r?\n\z//;
1481 29750 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 29750 29750
1482 29750 my %row;
1483 29750 @row{@cols} = split /\t/, $line, -1;
1484 29750 return (\%row, 'row ' . ++$n);
1485 }
1486 7 $whole->();
1487 6 return;
1488 8 };
1489 8 ($next, \@cols);
1490 }
1491  
1492 # The data frame $frame written to $file as a VCF of GT alone, for PLINK 2 to
1493 # read. Its rows are sorted by chromosome and position, as PLINK 2 needs them
1494 # to be, under the names _chrom gives the chromosomes, so that "chr1" and "1"
1495 # are one chromosome. A row with no CHROM, POS, REF or ALT is left out, and so
1496 # matches nothing, and a missing or empty GT is written "./.". Returns how many
1497 # rows were written.
1498 5 ▶sub _frame_vcf {
Subroutine _frame_vcf: called CC=21 SCAR=53.7
1499 5 my ($sub, $frame, $file, $match) = @_;
1500 5 my $rows = _frame_rows($sub, 'vcf', $frame);
1501 # read_table names each sample's genotype column "<sample>.GT" when it splits
1502 # the sample columns by FORMAT, as it does by default for a VCF
1503 3 ▶ my @samples = sort map { /\A(.+)\.GT\z/s ? $1 : () } keys %{ $rows->[0] };
Branch: 1 branch
BranchTrueFalseTotal
/\A(.+)\.GT\z/s ? : 2 13 15
1504 3 ▶ croak "$sub: \"vcf\" has no <sample>.GT column; read the VCF with read_table's default of explode => 1" unless @samples;
Branch: 1 branch
BranchTrueFalseTotal
unless @samples 1 2 3
1505 2 ▶ my @absent = grep { !exists $rows->[0]{$_} } qw(CHROM POS REF ALT), $match eq 'id' ? 'ID' : ();
Branch: 1 branch
BranchTrueFalseTotal
$match eq 'id' ? : 1 1 2
1506 2 ▶ croak "$sub: \"vcf\" has no " . join(', ', map { "\"$_\"" } @absent) . ' column' . (@absent > 1 ? 's' : '') if @absent;
Branch: 2 branches
BranchTrueFalseTotal
if @absent 2 0 2
@absent > 1 ? : 0 2 2
1507 0 ▶ my @keep = sort { $a->[0] cmp $b->[0] || $a->[1] <=> $b->[1] }
Condition0%0/3
$Cn::Bioinf::a->[0] cmp $Cn::Bioinf::b->[0] || $Cn::Bioinf::a->[1] <=> $Cn::Bioinf::b->[1]
l!l&&r!l&&!r
000
MC/DC0%0/2
$Cn::Bioinf::a->[0] cmp $Cn::Bioinf::b->[0] || $Cn::Bioinf::a->[1] <=> $Cn::Bioinf::b->[1]
$Cn::Bioinf::a->[0] cmp $Cn::Bioinf::b->[0] $Cn::Bioinf::a->[1] <=> $Cn::Bioinf::b->[1]
Truth table0%0/3
A || B
A= $Cn::Bioinf::a->[0] cmp $Cn::Bioinf::b->[0]B= $Cn::Bioinf::a->[1] <=> $Cn::Bioinf::b->[1]
ABresult
1X1
011
000
1508 0 map { [_chrom($_->{CHROM}), $_->{POS}, $_] }
1509 grep { defined $_->{CHROM} && length $_->{CHROM} && defined $_->{POS} && $_->{POS} =~ /\A[1-9][0-9]*\z/
1510 0 ▶ && defined $_->{REF} && length $_->{REF} && defined $_->{ALT} && length $_->{ALT} } @{ $rows };
Condition0%0/21
defined $_->{'CHROM'} && length $_->{'CHROM'} && defined $_->{'POS'} && $_->{'POS'} =~ /\A[1-9][0-9]*\z/ && defined $_->{'REF'} && length $_->{'REF'} && defined $_->{'ALT'} && length $_->{'ALT'}
!ll&&!rl&&r
000
defined $_->{"CHROM"} and length $_->{"CHROM"} and defined $_->{"POS"} and $_->{"POS"} =~ /\A[1-9][0-9]*\z/ and defined $_->{"REF"} and length $_->{"REF"} and defined $_->{"ALT"}
!ll&&!rl&&r
000
defined $_->{"CHROM"} and length $_->{"CHROM"} and defined $_->{"POS"} and $_->{"POS"} =~ /\A[1-9][0-9]*\z/ and defined $_->{"REF"} and length $_->{"REF"}
!ll&&!rl&&r
000
defined $_->{"CHROM"} and length $_->{"CHROM"} and defined $_->{"POS"} and $_->{"POS"} =~ /\A[1-9][0-9]*\z/ and defined $_->{"REF"}
!ll&&!rl&&r
000
defined $_->{"CHROM"} and length $_->{"CHROM"} and defined $_->{"POS"} and $_->{"POS"} =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
000
defined $_->{"CHROM"} and length $_->{"CHROM"} and defined $_->{"POS"}
!ll&&!rl&&r
000
defined $_->{"CHROM"} and length $_->{"CHROM"}
!ll&&!rl&&r
000
MC/DC0%0/8
defined $_->{'CHROM'} && length $_->{'CHROM'} && defined $_->{'POS'} && $_->{'POS'} =~ /\A[1-9][0-9]*\z/ && defined $_->{'REF'} && length $_->{'REF'} && defined $_->{'ALT'} && length $_->{'ALT'}
defined $_->{"CHROM"} length $_->{"CHROM"} defined $_->{"POS"} $_->{"POS"} =~ /\A[1-9][0-9]*\z/ defined $_->{"REF"} length $_->{"REF"} defined $_->{"ALT"} length $_->{'ALT'}
Truth table0%0/9
A and B and C and D and E and F and G && H
A= defined $_->{"CHROM"}B= length $_->{"CHROM"}C= defined $_->{"POS"}D= $_->{"POS"} =~ /\A[1-9][0-9]*\z/E= defined $_->{"REF"}F= length $_->{"REF"}G= defined $_->{"ALT"}H= length $_->{'ALT'}
ABCDEFGHresult
0XXXXXXX0
10XXXXXX0
110XXXXX0
1110XXXX0
11110XXX0
111110XX0
1111110X0
111111100
111111111
1511 0 ▶ open my $fh, '>:raw', $file or croak "_frame_vcf: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $file or croak("_frame_vcf: can't write ${file}: $!") 0 0 0
1512 0 print {$fh} "##fileformat=VCFv4.2\n##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">\n",
1513 join("\t", '#CHROM', qw(POS ID REF ALT QUAL FILTER INFO FORMAT), @samples), "\n";
1514 0 foreach my $k (@keep) {
1515 0 my $r = $k->[2];
1516 0 ▶ my $id = defined $r->{ID} && length $r->{ID} ? $r->{ID} : '.';
Branch: 1 branch
BranchTrueFalseTotal
defined $r->{'ID'} && length $r->{'ID'} ? : 0 0 0
Condition0%0/3
defined $r->{"ID"} and length $r->{"ID"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $r->{"ID"} and length $r->{"ID"}
defined $r->{"ID"} length $r->{"ID"}
Truth table0%0/3
A and B
A= defined $r->{"ID"}B= length $r->{"ID"}
ABresult
0X0
100
111
1517 0 print {$fh} join("\t", $k->[0], $k->[1], $id, $r->{REF}, $r->{ALT}, '.', '.', '.', 'GT',
1518 0 ▶ map { my $gt = $r->{"$_.GT"}; defined $gt && length $gt ? $gt : './.' } @samples), "\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $gt && length $gt ? : 0 0 0
Condition0%0/3
defined $gt and length $gt
!ll&&!rl&&r
000
MC/DC0%0/2
defined $gt and length $gt
defined $gt length $gt
Truth table0%0/3
A and B
A= defined $gtB= length $gt
ABresult
0X0
100
111
1519 }
1520 0 ▶ close $fh or croak "_frame_vcf: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("_frame_vcf: can't write ${file}: $!") 0 0 0
1521 0 scalar @keep;
1522 }
1523  
1524 # plink2 run with @args for $sub, its output in $dir/plink2.out rather than on
1525 # the caller's terminal; a failure dies with the lines of it that say why.
1526 1 ▶sub _plink2 {
Subroutine _plink2: called CC=12 SCAR=29.4
1527 1 my ($sub, $plink2, $dir, @args) = @_;
1528 1 my $log = File::Spec->catfile($dir, 'plink2.out');
1529 1 ▶ open my $out, '>&', \*STDOUT or croak "_plink2: can't save STDOUT: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $out, ">&", \*STDOUT or croak("_plink2: can't save STDOUT: $!") 1 0 1
1530 1 ▶ open my $err, '>&', \*STDERR or croak "_plink2: can't save STDERR: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $err, ">&", \*STDERR or croak("_plink2: can't save STDERR: $!") 1 0 1
1531 # Puts the caller's STDOUT and STDERR back, so that a failure to redirect
1532 # them does not leave the rest of the caller's output in the log.
1533 1 ▶ my $restore = sub {
Subroutine __ANON__: called CC=3 SCAR=12.0
1534 1 ▶ open STDOUT, '>&', $out or croak "_plink2: can't restore STDOUT: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, ">&", $out or croak("_plink2: can't restore STDOUT: $!") 1 0 1
1535 1 ▶ open STDERR, '>&', $err or croak "_plink2: can't restore STDERR: $!";
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, ">&", $err or croak("_plink2: can't restore STDERR: $!") 1 0 1
1536 1 };
1537 1 ▶ unless (open STDOUT, '>', $log) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open STDOUT, ">", $log) 0 1 1
1538 0 my $why = "$!";
1539 0 $restore->();
1540 0 croak "_plink2: can't write $log: $why";
1541 }
1542 1 ▶ unless (open STDERR, '>&', \*STDOUT) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open STDERR, ">&", \*STDOUT) 0 1 1
1543 0 my $why = "$!";
1544 0 $restore->();
1545 0 croak "_plink2: can't send STDERR to $log: $why";
1546 }
1547 1 my $rc = system($plink2, @args);
1548 # taken before $restore's opens can set $! to their own errors
1549 1 my ($status, $errno) = ($?, "$!");
1550 1 $restore->();
1551 1 ▶ return if $rc == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $rc == 0 0 1 1
1552 1 ▶ my $why = $status == -1 ? "it didn't start: $errno" : $status & 127 ? 'killed by signal ' . ($status & 127) : 'exit ' . ($status >> 8);
Branch: 2 branches
BranchTrueFalseTotal
$status == -1 ? : 1 0 1
$status & 127 ? : 0 0 0
1553 # what PLINK 2 says from its "Error:" on, or else its last line; it
1554 # rewrites its progress lines with a CR
1555 1 my @said;
1556 1 ▶ if (open my $fh, '<', $log) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, "<", $log) 1 0 1
1557 # less the "End time:" it ends every run with, which says nothing of why
1558 1 ▶ @said = grep { /\S/ && !/\AEnd time: / } map { (my $l = $_) =~ s/\s+\z//; $l } map { split /\r/ } <$fh>;
Condition33%1/3
/\S/ && !/\AEnd time: /
!ll&&!rl&&r
001
MC/DC0%0/2
/\S/ && !/\AEnd time: /
/\S/ !/\AEnd time: /
Truth table33%1/3
A && not(B)
A= /\S/B= !/\AEnd time: /
ABresult
0X0
100
111
1559 }
1560 1 my ($first) = grep { $said[$_] =~ /\AError/ } 0 .. $#said;
1561 1 ▶ my $said = join ' ', defined $first ? @said[$first .. $#said] : @said ? $said[-1] : 'nothing';
Branch: 2 branches
BranchTrueFalseTotal
defined $first ? : 0 1 1
@said ? : 1 0 1
1562 1 croak "$sub: \"$plink2 @args\" failed ($why): $said";
1563 }
1564  
1565 # Dies unless "memory" and "threads" of $sub's $args are numbers PLINK 2
1566 # takes, or were not given. Returns plink2's arguments for them, after the
1567 # --allow-extra-chr that every run here passes, so that a contig PLINK 2 has no
1568 # code for (chrUn_..., say) is read rather than refused.
1569 53 ▶sub _plink2_resources {
Subroutine _plink2_resources: called CC=9 SCAR=22.4
1570 53 my ($sub, $args) = @_;
1571 53 foreach my $k (qw(memory threads)) {
1572 # undef = PLINK 2's own default: half the machine's memory, every CPU
1573 croak "$sub: \"$k\" must be a whole number, 1 or more, not " . _what($args->{$k})
1574 105 ▶ if defined $args->{$k} && (ref $args->{$k} || $args->{$k} !~ /\A[1-9][0-9]*\z/);
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{$k} and ref $args->{$k} || !($args->{$k} =~ /\A[1-9][0-9]*\z/) 4 101 105
Condition83%5/6
defined $args->{$k} and ref $args->{$k} || !($args->{$k} =~ /\A[1-9][0-9]*\z/)
!ll&&!rl&&r
9924
ref $args->{$k} or not $args->{$k} =~ /\A[1-9][0-9]*\z/
l!l&&r!l&&!r
042
MC/DC66%2/3
defined $args->{$k} and ref $args->{$k} || !($args->{$k} =~ /\A[1-9][0-9]*\z/)
defined $args->{$k} ref $args->{$k} not $args->{$k} =~ /\A[1-9][0-9]*\z/
Truth table75%3/4
A and B or not(C)
A= defined $args->{$k}B= ref $args->{$k}C= not $args->{$k} =~ /\A[1-9][0-9]*\z/
ABCresult
0XX0
1000
11X1
1011
1575 }
1576 49 my ($memory, $threads) = @{ $args }{qw(memory threads)};
1577 # PLINK 2 v2.0.0-a.7.13LM refuses less: "Invalid --memory argument '256' (minimum 640)"
1578 49 ▶ croak "$sub: \"memory\" must be 640 or more (MiB), the least PLINK 2 takes, not $memory" if defined $memory && $memory < 640;
Branch: 1 branch
BranchTrueFalseTotal
if defined $memory and $memory < 640 2 47 49
Condition66%2/3
defined $memory and $memory < 640
!ll&&!rl&&r
4702
MC/DC50%1/2
defined $memory and $memory < 640
defined $memory $memory < 640
Truth table66%2/3
A and B
A= defined $memoryB= $memory < 640
ABresult
0X0
100
111
1579 47 ▶ ('--allow-extra-chr', (defined $memory ? ('--memory', $memory) : ()), (defined $threads ? ('--threads', $threads) : ()));
Branch: 2 branches
BranchTrueFalseTotal
defined $memory ? : 0 47 47
defined $threads ? : 0 47 47
1580 }
1581  
1582 # plink2's arguments that read "vcf" of $sub, a file, which dies unless it is
1583 # one PLINK 2 reads by its name; or () for a data frame, which the caller
1584 # writes to a VCF with _frame_vcf once its other arguments have been checked.
1585 47 ▶sub _plink2_input {
Subroutine _plink2_input: called CC=11 SCAR=25.6
1586 47 my ($sub, $vcf) = @_;
1587 47 ▶ if (!ref $vcf) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $vcf) 5 42 47
1588 5 ▶ croak "$sub: \"vcf\" file \"$vcf\" doesn't exist or isn't readable" unless -f $vcf && -r _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $vcf and -r _ 2 3 5
Condition66%2/3
-f $vcf and -r _
!ll&&!rl&&r
203
MC/DC50%1/2
-f $vcf and -r _
-f $vcf -r _
Truth table66%2/3
A and B
A= -f $vcfB= -r _
ABresult
0X0
100
111
1589 3 ▶ if ($vcf =~ /\A(.*)\.pgen\z/is) {
Branch: 1 branch
BranchTrueFalseTotal
if ($vcf =~ /\A(.*)\.pgen\z/is) 1 2 3
1590 1 my $prefix = $1;
1591 1 ▶ croak "$sub: \"vcf\" $vcf has no $prefix.pvar (or .pvar.zst) beside it" unless grep { -f "$prefix.$_" } qw(pvar pvar.zst);
Branch: 1 branch
BranchTrueFalseTotal
unless grep {-f "$prefix.$_";} "pvar", "pvar.zst" 1 0 1
1592 0 ▶ croak "$sub: \"vcf\" $vcf has no $prefix.psam beside it" unless -f "$prefix.psam";
Branch: 1 branch
BranchTrueFalseTotal
unless -f "$prefix.psam" 0 0 0
1593 0 return ('--pfile', $prefix);
1594 }
1595 2 ▶ return ('--bcf', $vcf) if $vcf =~ /\.bcf\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $vcf =~ /\.bcf\z/i 0 2 2
1596 2 ▶ return ('--vcf', $vcf) if $vcf =~ /\.vcf(?:\.b?gz)?\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $vcf =~ /\.vcf(?:\.b?gz)?\z/i 0 2 2
1597 2 croak "$sub: \"vcf\" file $vcf must end in .vcf, .vcf.gz, .vcf.bgz, .bcf or .pgen, as PLINK 2 reads it by its name";
1598 }
1599 42 ▶ croak "$sub: \"vcf\" must be a VCF, BCF or PLINK 2 .pgen file, or a data frame, not " . _what($vcf)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $vcf eq "ARRAY" or ref $vcf eq "HASH" 2 40 42
Condition66%2/3
ref $vcf eq "ARRAY" or ref $vcf eq "HASH"
l!l&&r!l&&!r
0402
MC/DC50%1/2
ref $vcf eq "ARRAY" or ref $vcf eq "HASH"
ref $vcf eq "ARRAY" ref $vcf eq "HASH"
Truth table66%2/3
A or B
A= ref $vcf eq "ARRAY"B= ref $vcf eq "HASH"
ABresult
1X1
011
000
1600 unless ref $vcf eq 'ARRAY' || ref $vcf eq 'HASH';
1601 40 ();
1602 }
1603  
1604 # Alien::Bioinf's plink2, for $sub, or a death that says why there is none.
1605 0 ▶sub _plink2_program {
Subroutine _plink2_program: not called CC=2 SCAR=17.9
1606 0 my ($sub) = @_;
1607 0 my $plink2 = eval { _alien($sub)->plink2 };
1608 0 ▶ return $plink2 if defined $plink2;
Branch: 1 branch
BranchTrueFalseTotal
if defined $plink2 0 0 0
1609 0 (my $why = $@) =~ s/ at \S+ line \d+\.?\n?\z//;
1610 0 croak "$sub: needs PLINK 2, which Alien::Bioinf installs, and hasn't here: $why";
1611 }
1612  
1613 # The IIDs of the .psam $file, in its order, for $sub, which returns its
1614 # $what (such as "scores") keyed by IID. PLINK 2 tells samples apart by FID and
1615 # IID together, so two samples that share an IID, in different families, die
1616 # here, rather than having their results added into one.
1617 0 ▶sub _psam_iids {
Subroutine _psam_iids: not called CC=8 SCAR=42.8
1618 0 my ($sub, $file, $what) = @_;
1619 0 ▶ open my $psam, '<', $file or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $psam, "<", $file or croak("${sub}: can't read ${file}: $!") 0 0 0
1620 0 my ($iid, $fid); # the columns of the IID and of the FID, which a .psam need not have
1621 0 my %family; # IID => its FID, or '' with no FID column
1622 0 my @samples;
1623 0 ▶ while (my $line = <$psam>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $psam)) 0 0 0
1624 0 chomp $line;
1625 0 my @f = split /\t/, $line;
1626 0 ▶ if ($line =~ /\A#/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\A#/) 0 0 0
1627 0 ($iid) = grep { $f[$_] =~ /\A#?IID\z/ } 0 .. $#f;
1628 0 ($fid) = grep { $f[$_] =~ /\A#?FID\z/ } 0 .. $#f;
1629 0 next;
1630 }
1631 0 ▶ my $id = $f[$iid // 0];
Condition0%0/2
$iid // 0
l!l
00
MC/DC0%0/1
$iid // 0
$iid
Truth table0%0/2
A
A= $iid
Aresult
11
00
1632 0 ▶ my $family = defined $fid ? $f[$fid] : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $fid ? : 0 0 0
1633 croak "$sub: \"vcf\" has two samples whose IID is \"$id\"" . (defined $fid ? ", in families \"$family{$id}\" and \"$family\"" : '')
1634 0 ▶ . "; the $what are returned by IID, so each sample's must be unique" if exists $family{$id};
Branch: 2 branches
BranchTrueFalseTotal
if exists $family{$id} 0 0 0
defined $fid ? : 0 0 0
1635 0 $family{$id} = $family;
1636 0 push @samples, $id;
1637 }
1638 0 close $psam;
1639 0 @samples;
1640 }
1641  
1642 39 ▶sub pgs_score {
Subroutine pgs_score: called CC=107 SCAR=81.8
Pod documented
1643 39 my $sub = 'pgs_score';
1644 39 my $args = _args(\@_, $sub, [qw(vcf weights)], [qw(build match memory threads)]);
1645 36 my %r;
1646 36 ▶ $r{match} = $args->{match} // 'position'; # 'position' = CHROM and POS against chr_name and chr_position; 'id' = ID against rsID
Condition100%2/2
$args->{"match"} // "position"
l!l
333
MC/DC100%1/1
$args->{"match"} // "position"
$args->{"match"}
Truth table100%2/2
A
A= $args->{"match"}
Aresult
11
00
1647 croak "$sub: \"match\" must be \"position\" or \"id\", not " . _what($r{match})
1648 36 ▶ unless !ref $r{match} && ($r{match} eq 'position' || $r{match} eq 'id');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"match"} and $r{"match"} eq "position" || $r{"match"} eq "id" 1 35 36
Condition83%5/6
not ref $r{"match"} and $r{"match"} eq "position" || $r{"match"} eq "id"
!ll&&!rl&&r
0135
$r{"match"} eq "position" or $r{"match"} eq "id"
l!l&&r!l&&!r
3321
MC/DC66%2/3
not ref $r{"match"} and $r{"match"} eq "position" || $r{"match"} eq "id"
not ref $r{"match"} $r{"match"} eq "position" $r{"match"} eq "id"
Truth table75%3/4
not(A) and B or C
A= not ref $r{"match"}B= $r{"match"} eq "position"C= $r{"match"} eq "id"
ABCresult
0XX0
1000
11X1
1011
1649 35 $r{build} = $args->{build}; # undef = the sex chromosomes are left out; hg19, b37, hg38 or b38 = PLINK 2 reads them, with X's pseudo-autosomal regions placed for that build
1650 croak "$sub: \"build\" must be hg19, b37, hg38 or b38, not " . _what($r{build})
1651 35 ▶ if defined $r{build} && (ref $r{build} || $r{build} !~ /\A(?:hg19|b37|hg38|b38)\z/);
Branch: 1 branch
BranchTrueFalseTotal
if defined $r{"build"} and ref $r{"build"} || !($r{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/) 1 34 35
Condition50%3/6
defined $r{"build"} and ref $r{"build"} || !($r{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/)
!ll&&!rl&&r
3401
ref $r{"build"} or not $r{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/
l!l&&r!l&&!r
010
MC/DC33%1/3
defined $r{"build"} and ref $r{"build"} || !($r{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/)
defined $r{"build"} ref $r{"build"} not $r{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/
Truth table50%2/4
A and B or not(C)
A= defined $r{"build"}B= ref $r{"build"}C= not $r{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/
ABCresult
0XX0
1000
11X1
1011
1652 34 my @common = _plink2_resources($sub, $args);
1653 31 my $vcf = $args->{vcf};
1654 31 my @input = _plink2_input($sub, $vcf); # plink2's arguments that read the genotypes; set below for a data frame
1655  
1656 27 my ($next, $cols) = _weight_rows($sub, $args->{weights});
1657 19 my %have = map { $_ => 1 } @{ $cols };
1658 # A harmonized (hmPOS) scoring file has its variants on the build its name
1659 # gives in the hm_ columns, and on the author's build in chr_name,
1660 # chr_position and rsID, so the hm_ columns are the ones read when present.
1661 my @key_cols = $r{match} eq 'id' ? ($have{hm_rsID} ? 'hm_rsID' : 'rsID')
1662 19 ▶ : $have{hm_pos} ? qw(hm_chr hm_pos) : qw(chr_name chr_position);
Branch: 3 branches
BranchTrueFalseTotal
$r{'match'} eq 'id' ? : 2 17 19
$have{'hm_rsID'} ? : 0 2 2
$have{'hm_pos'} ? : 1 16 17
1663 19 ▶ my $chr_col = $have{hm_chr} ? 'hm_chr' : $have{chr_name} ? 'chr_name' : undef;
Branch: 2 branches
BranchTrueFalseTotal
$have{'hm_chr'} ? : 1 18 19
$have{'chr_name'} ? : 17 1 18
1664 19 my @absent = grep { !$have{$_} } @key_cols, 'effect_allele', 'effect_weight';
1665 19 ▶ croak "$sub: \"weights\" has no " . join(', ', map { "\"$_\"" } @absent) . ' column' . (@absent > 1 ? 's' : '')
Branch: 2 branches
BranchTrueFalseTotal
if @absent 2 17 19
@absent > 1 ? : 1 1 2
1666 . ', which a PGS Catalog scoring file has' if @absent;
1667 # Only an additive weight is a weight times the dosage. These columns of the
1668 # PGS Catalog's format 2.0 mark a variant that is scored some other way, which
1669 # this function would get wrong, so a variant marked so is refused.
1670 17 my @flags = grep { $have{$_} } qw(is_haplotype is_diplotype is_interaction is_dominant is_recessive);
1671 17 my @dosage_weights = grep { $have{$_} } qw(dosage_0_weight dosage_1_weight dosage_2_weight);
1672 # removed as pgs_score returns, or, after an error, as the program ends;
1673 # File::Temp's newdir, which would do both, is newer than 5.10.0's File::Temp
1674 17 require File::Temp;
1675 17 my $dir = File::Temp::tempdir(CLEANUP => 1);
1676 17 my $regions = File::Spec->catfile($dir, 'regions.txt');
1677 17 ▶ open my $rfh, '>', $regions or croak "$sub: can't write $regions: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $rfh, ">", $regions or croak("${sub}: can't write ${regions}: $!") 17 0 17
1678 # Each row of weights is kept as a line "effect\tother\tweight\n" of $rows,
1679 # the alleles in upper case and the weight as written, and where its line
1680 # starts is packed into $row_at as a C double, exact to 2^53 on every perl.
1681 # Until 2026-11-18 each row was a perl string of its own, of 82 bytes on
1682 # perl 5.44.0, and these take 8 and the line. With @use an array, the bit vector $taken and
1683 # %at freed early (all below), a score of 1,000,000 variants against a VCF
1684 # of all of them peaked at 325 MB rather than 629 MB (perl 5.44.0, on
1685 # 2026-11-18), and scored the same.
1686 17 my ($rows, $row_at, $n_rows) = ('', '', 0);
1687 0 ▶ my $row = sub { # row $_[0] of weights as (effect, other, weight)
Subroutine __ANON__: not called CC=1 SCAR=6.9
1688 0 my $from = unpack 'd', substr $row_at, 8 * $_[0], 8;
1689 0 split /\t/, substr($rows, $from, index($rows, "\n", $from) - $from), -1;
1690 17 };
1691 17 my %at; # key (CHROM:POS or rsID) => the rows of weights at it, joined by commas
1692 my %chroms; # chromosome, as _chrom names it => 1, for each of the rows' chromosomes
1693 17 ▶ while (my ($w, $label) = $next->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$next()) 18 7 25
1694 18 foreach my $c (@flags) {
1695 croak "$sub: $label of \"weights\" has $c \"$w->{$c}\", and only additive weights can be scored"
1696 2 ▶ if defined $w->{$c} && $w->{$c} =~ /\A(?:true|1)\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if defined $w->{$c} and $w->{$c} =~ /\A(?:true|1)\z/i 2 0 2
Condition33%1/3
defined $w->{$c} and $w->{$c} =~ /\A(?:true|1)\z/i
!ll&&!rl&&r
002
MC/DC0%0/2
defined $w->{$c} and $w->{$c} =~ /\A(?:true|1)\z/i
defined $w->{$c} $w->{$c} =~ /\A(?:true|1)\z/i
Truth table33%1/3
A and B
A= defined $w->{$c}B= $w->{$c} =~ /\A(?:true|1)\z/i
ABresult
0X0
100
111
1697 }
1698 16 foreach my $c (@dosage_weights) {
1699 croak "$sub: $label of \"weights\" has a $c, and only additive weights can be scored"
1700 1 ▶ if defined $w->{$c} && length $w->{$c};
Branch: 1 branch
BranchTrueFalseTotal
if defined $w->{$c} and length $w->{$c} 1 0 1
Condition33%1/3
defined $w->{$c} and length $w->{$c}
!ll&&!rl&&r
001
MC/DC0%0/2
defined $w->{$c} and length $w->{$c}
defined $w->{$c} length $w->{$c}
Truth table33%1/3
A and B
A= defined $w->{$c}B= length $w->{$c}
ABresult
0X0
100
111
1701 }
1702 15 my ($e, $o, $weight) = @{ $w }{qw(effect_allele other_allele effect_weight)};
1703 15 ▶ croak "$sub: $label of \"weights\" has no effect_allele" unless defined $e && length $e;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $e and length $e 1 14 15
Condition66%2/3
defined $e and length $e
!ll&&!rl&&r
0114
MC/DC50%1/2
defined $e and length $e
defined $e length $e
Truth table66%2/3
A and B
A= defined $eB= length $e
ABresult
0X0
100
111
1704 14 ▶ croak "$sub: $label of \"weights\" has effect_weight " . _what($weight) . ', which isn\'t a number'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $weight and not ref $weight and $weight =~ /$Number/ 4 10 14
Condition83%5/6
defined $weight and not ref $weight and $weight =~ /$Number/
!ll&&!rl&&r
1310
defined $weight and not ref $weight
!ll&&!rl&&r
1013
MC/DC66%2/3
defined $weight and not ref $weight and $weight =~ /$Number/
defined $weight not ref $weight $weight =~ /$Number/
Truth table75%3/4
A and not(B) and C
A= defined $weightB= not ref $weightC= $weight =~ /$Number/
ABCresult
0XX0
10X0
1100
1111
1705 unless defined $weight && !ref $weight && $weight =~ $Number;
1706 10 my $i = $n_rows++;
1707 10 $row_at .= pack 'd', length $rows;
1708 10 ▶ $rows .= join("\t", uc $e, defined $o && length $o ? uc $o : '', $weight) . "\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $o && length $o ? : 9 1 10
Condition66%2/3
defined $o and length $o
!ll&&!rl&&r
109
MC/DC50%1/2
defined $o and length $o
defined $o length $o
Truth table66%2/3
A and B
A= defined $oB= length $o
ABresult
0X0
100
111
1709 10 ▶ my $chr = defined $chr_col && defined $w->{$chr_col} && length $w->{$chr_col} ? _chrom($w->{$chr_col}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $chr_col && defined $w->{$chr_col} && length $w->{$chr_col} ? : 10 0 10
Condition33%2/6
defined $chr_col and defined $w->{$chr_col} and length $w->{$chr_col}
!ll&&!rl&&r
0010
defined $chr_col and defined $w->{$chr_col}
!ll&&!rl&&r
0010
MC/DC0%0/3
defined $chr_col and defined $w->{$chr_col} and length $w->{$chr_col}
defined $chr_col defined $w->{$chr_col} length $w->{$chr_col}
Truth table25%1/4
A and B and C
A= defined $chr_colB= defined $w->{$chr_col}C= length $w->{$chr_col}
ABCresult
0XX0
10X0
1100
1111
1710 10 my $key;
1711 10 ▶ if ($r{match} eq 'id') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{'match'} eq 'id') { } 1 9 10
1712 1 $key = $w->{ $key_cols[0] };
1713 } else {
1714 9 my $pos = $w->{ $key_cols[1] };
1715 # A harmonized file leaves hm_chr and hm_pos empty for a variant it
1716 # could not place, and that variant is then not found, rather than an error.
1717 9 ▶ if (defined $chr && defined $pos && length $pos) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $chr and defined $pos and length $pos) 9 0 9
Condition33%2/6
defined $chr and defined $pos and length $pos
!ll&&!rl&&r
009
defined $chr and defined $pos
!ll&&!rl&&r
009
MC/DC0%0/3
defined $chr and defined $pos and length $pos
defined $chr defined $pos length $pos
Truth table25%1/4
A and B and C
A= defined $chrB= defined $posC= length $pos
ABCresult
0XX0
10X0
1100
1111
1718 9 ▶ croak "$sub: $label of \"weights\" has $key_cols[1] \"$pos\", which isn't a position"
Branch: 1 branch
BranchTrueFalseTotal
unless $pos =~ /\A[1-9][0-9]*\z/ 2 7 9
1719 unless $pos =~ /\A[1-9][0-9]*\z/;
1720 7 $key = "$chr:$pos";
1721 # X's positions are given under PAR1 and PAR2 too, which --split-par
1722 # may have moved them to
1723 7 ▶ print {$rfh} map { "$_\t$pos\t$pos\n" } $chr, $chr eq 'X' ? qw(PAR1 PAR2) : ();
Branch: 1 branch
BranchTrueFalseTotal
$chr eq 'X' ? : 1 6 7
1724 }
1725 }
1726 8 ▶ $chroms{$chr} = 1 if defined $chr;
Branch: 1 branch
BranchTrueFalseTotal
if defined $chr 8 0 8
1727 8 ▶ $at{$key} = defined $at{$key} ? "$at{$key},$i" : $i if defined $key && length $key;
Branch: 2 branches
BranchTrueFalseTotal
if defined $key and length $key 8 0 8
defined $at{$key} ? : 0 8 8
Condition33%1/3
defined $key and length $key
!ll&&!rl&&r
008
MC/DC0%0/2
defined $key and length $key
defined $key length $key
Truth table33%1/3
A and B
A= defined $keyB= length $key
ABresult
0X0
100
111
1728 }
1729 7 ▶ close $rfh or croak "$sub: can't write $regions: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $rfh or croak("${sub}: can't write ${regions}: $!") 7 0 7
1730 7 ▶ croak "$sub: \"weights\" has no rows" unless $n_rows;
Branch: 1 branch
BranchTrueFalseTotal
unless $n_rows 1 6 7
1731 6 my @sex = grep { $chroms{$_} } qw(X Y);
1732 croak "$sub: \"weights\" has variants on " . join(' and ', @sex) . ', which PLINK 2 reads only when "build" says where X\'s'
1733 6 ▶ . ' pseudo-autosomal regions are: hg19 (b37) or hg38 (b38)' if @sex && !defined $r{build};
Branch: 1 branch
BranchTrueFalseTotal
if @sex and not defined $r{"build"} 1 5 6
Condition66%2/3
@sex and not defined $r{"build"}
!ll&&!rl&&r
501
MC/DC50%1/2
@sex and not defined $r{"build"}
@sex not defined $r{"build"}
Truth table66%2/3
A and not(B)
A= @sexB= not defined $r{"build"}
ABresult
0X0
100
111
1734 5 ▶ _frame_vcf($sub, $vcf, File::Spec->catfile($dir, 'frame.vcf'), $r{match}) if ref $vcf;
Branch: 1 branch
BranchTrueFalseTotal
if ref $vcf 5 0 5
1735 0 ▶ @input = ('--vcf', File::Spec->catfile($dir, 'frame.vcf')) if ref $vcf;
Branch: 1 branch
BranchTrueFalseTotal
if ref $vcf 0 0 0
1736  
1737 0 my $plink2 = _plink2_program($sub);
1738 0 ▶ push @input, '--vcf-half-call', 'missing' unless $input[0] eq '--pfile';
Branch: 1 branch
BranchTrueFalseTotal
unless $input[0] eq "--pfile" 0 0 0
1739 # The samples, each of unknown sex, written by PLINK 2 without reading the
1740 # sex chromosomes, which it would refuse to without each one's sex.
1741 0 my $samples = File::Spec->catfile($dir, 'samples');
1742 0 my @psam = ('--not-chr', 'X,Y,XY', '--make-just-psam', '--out', $samples);
1743 0 ▶ unless (eval { _plink2($sub, $plink2, $dir, @input, @common, @psam); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { _plink2($sub, $plink2, $dir, @input, @common, @psam); 1 } }) 0 0 0
1744 # PLINK 2 refuses a single-sample VCF with no 0/0 among its first 1,000
1745 # called genotypes, as one that lists only the sites where the sample
1746 # carries an ALT allele; scored, every other variant is missing.
1747 # die, not croak, which would give _plink2's message a second "at ... line"
1748 0 ▶ die $@ unless $@ =~ /contain at least one ALT allele/;
Branch: 1 branch
BranchTrueFalseTotal
unless $@ =~ /contain at least one ALT allele/ 0 0 0
1749 0 carp "$sub: \"vcf\" lists only the sites where its sample carries an ALT allele, so every variant where it matches"
1750 . ' the reference is missing, and its score is not comparable with one from a VCF of every site';
1751 0 push @input, '--vcf-allow-no-nonvar';
1752 0 _plink2($sub, $plink2, $dir, @input, @common, @psam);
1753 }
1754 0 my @import = (@input, @common);
1755 # Only the chromosomes the score uses are read, or, where it gives none
1756 # (matching by ID alone), all but the sex chromosomes, unless "build" says
1757 # where X's pseudo-autosomal regions are. PLINK 2 needs that, and each
1758 # sample's sex, before it reads X at all; the sex is given as unknown, which
1759 # counts a haploid call on X as homozygous.
1760 0 ▶ if (%chroms) {
Branch: 2 branches
BranchTrueFalseTotal
if (%chroms) { } 0 0 0
elsif (not defined $r{'build'}) { } 0 0 0
1761 0 ▶ push @import, '--chr', join ',', sort(keys %chroms), $chroms{X} ? qw(PAR1 PAR2) : ();
Branch: 1 branch
BranchTrueFalseTotal
$chroms{'X'} ? : 0 0 0
1762 } elsif (!defined $r{build}) {
1763 0 push @import, '--not-chr', 'X,Y,XY';
1764 }
1765 0 ▶ push @import, '--psam', "$samples.psam", '--split-par', $r{build} if defined $r{build} && $input[0] ne '--pfile';
Branch: 1 branch
BranchTrueFalseTotal
if defined $r{"build"} and $input[0] ne "--pfile" 0 0 0
Condition0%0/3
defined $r{"build"} and $input[0] ne "--pfile"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $r{"build"} and $input[0] ne "--pfile"
defined $r{"build"} $input[0] ne "--pfile"
Truth table0%0/3
A and B
A= defined $r{"build"}B= $input[0] ne "--pfile"
ABresult
0X0
100
111
1766 0 ▶ push @import, '--extract', 'bed1', $regions if $r{match} eq 'position';
Branch: 1 branch
BranchTrueFalseTotal
if $r{"match"} eq "position" 0 0 0
1767 0 my $g = File::Spec->catfile($dir, 'g');
1768 # PLINK 2 exits 13 when none of the score's positions is in the VCF, and 7
1769 # when none of its chromosomes is (a VCF, filtered by --chr as it is
1770 # imported; a --pfile is filtered later, and exits 13). Either is a result
1771 # here: every variant is missing.
1772 0 ▶ my $none = eval { _plink2($sub, $plink2, $dir, @import, '--make-pgen', '--out', $g); 0 }
Branch: 1 branch
BranchTrueFalseTotal
$@ =~ /\((?:exit 13\): Error: No variants remaining|exit 7\): Error: All \d+ variant\(s\) in --vcf file excluded by --chr)/ ? : 0 0 0
Condition0%0/2
eval { do { _plink2($sub, $plink2, $dir, @import, "--make-pgen", "--out", $g); 0 } } // ($@ =~ /\((?:exit 13\): Error: No variants remaining|exit 7\): Error: All \d+ variant\(s\) in --vcf file excluded by --chr)/ ? 1 : die($@))
l!l
00
MC/DC0%0/1
eval { do { _plink2($sub, $plink2, $dir, @import, "--make-pgen", "--out", $g); 0 } } // ($@ =~ /\((?:exit 13\): Error: No variants remaining|exit 7\): Error: All \d+ variant\(s\) in --vcf file excluded by --chr)/ ? 1 : die($@))
eval { do { _plink2($sub, $plink2, $dir, @import, "--make-pgen", "--out", $g); 0 } }
Truth table0%0/2
A
A= eval { do { _plink2($sub, $plink2, $dir, @import, "--make-pgen", "--out", $g); 0 } }
Aresult
11
00
1773 // ($@ =~ /\((?:exit 13\): Error: No variants remaining|exit 7\): Error: All \d+ variant\(s\) in --vcf file excluded by --chr)/ ? 1 : die $@);
1774  
1775 0 my @samples = _psam_iids($sub, "$samples.psam", 'scores'); # in PLINK 2's order
1776  
1777 # The .pvar a record at a time, matched against the rows of weights, and
1778 # written again with each record's ID made v1, v2, ..., which --score finds
1779 # it by, since a VCF's own IDs are often "." and need not be unique.
1780 0 my $found = ''; # bit $i set: row $i of weights is at a position (or ID) of the VCF
1781 0 my @use; # row $i => "record number\tA1 as the record writes it\tits CHROM:POS:REF:ALT\t1, or 0 when the record lacks the effect allele", for the record whose alleles agree with it; an array, whose slot is 8 bytes a row, where a hash gave each a key and an entry too
1782 0 my ($in, $out);
1783 0 ▶ unless ($none) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($none) 0 0 0
1784 0 ▶ open $in, '<', "$g.pvar" or croak "$sub: can't read $g.pvar: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $in, "<", "$g.pvar" or croak("${sub}: can't read $g.pvar: $!") 0 0 0
1785 0 ▶ open $out, '>', "$g.ids.pvar" or croak "$sub: can't write $g.ids.pvar: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $out, ">", "$g.ids.pvar" or croak("${sub}: can't write $g.ids.pvar: $!") 0 0 0
1786 }
1787 0 my ($n, %col) = (0);
1788 0 ▶ while (!$none && defined(my $line = <$in>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $none and defined(my $line = readline $in)) 0 0 0
Condition0%0/3
not $none and defined(my $line = readline $in)
!ll&&!rl&&r
000
MC/DC0%0/2
not $none and defined(my $line = readline $in)
not $none defined(my $line = readline $in)
Truth table0%0/3
not(A) and B
A= not $noneB= defined(my $line = readline $in)
ABresult
0X0
100
111
1789 0 ▶ if ($line =~ /\A##/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\A##/) 0 0 0
1790 0 print {$out} $line;
1791 0 next;
1792 }
1793 0 chomp $line;
1794 0 my @f = split /\t/, $line, -1;
1795 0 ▶ if ($line =~ /\A#CHROM/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\A#CHROM/) 0 0 0
1796 0 %col = map { $f[$_] => $_ } 0 .. $#f;
1797 0 print {$out} "$line\n";
1798 0 next;
1799 }
1800 0 $n++;
1801 0 my ($chrom, $pos, $id, $ref, $alt) = @f[ @col{'#CHROM', 'POS', 'ID', 'REF', 'ALT'} ];
1802 0 $f[ $col{ID} ] = "v$n";
1803 0 print {$out} join("\t", @f), "\n";
1804 0 ▶ my @keys = $r{match} eq 'id' ? grep { length && $_ ne '.' } split(/;/, $id) : (_chrom($chrom) . ":$pos");
Branch: 1 branch
BranchTrueFalseTotal
$r{'match'} eq 'id' ? : 0 0 0
Condition0%0/3
length $_ && $_ ne '.'
!ll&&!rl&&r
000
MC/DC0%0/2
length $_ && $_ ne '.'
length $_ $_ ne '.'
Truth table0%0/3
A && B
A= length $_B= $_ ne '.'
ABresult
0X0
100
111
1805 0 ▶ my @here = map { split /,/, $at{$_} // '' } @keys;
Condition0%0/2
$at{$_} // ""
l!l
00
MC/DC0%0/1
$at{$_} // ""
$at{$_}
Truth table0%0/2
A
A= $at{$_}
Aresult
11
00
1806 0 ▶ next unless @here;
Branch: 1 branch
BranchTrueFalseTotal
unless @here 0 0 0
1807 # An ALT of "." is a site with no alternate allele, which a VCF of every
1808 # site writes where the sample matches the reference.
1809 0 ▶ my @alleles = ($ref, $alt eq '.' ? () : split /,/, $alt);
Branch: 1 branch
BranchTrueFalseTotal
$alt eq '.' ? : 0 0 0
1810 0 my %named; # allele in upper case => as the record writes it
1811 0 ▶ $named{ uc $_ } //= $_ foreach @alleles;
Condition0%0/3
$named{uc $_} //= $_
l!l&&r!l&&!r
000
MC/DC0%0/2
$named{uc $_} //= $_
$named{uc $_} $_
Truth table0%0/3
A //= B
A= $named{uc $_}B= $_
ABresult
1X1
011
000
1812 0 my $sort = join ':', $chrom, $pos, $ref, $alt;
1813 0 foreach my $i (@here) {
1814 0 vec($found, $i, 1) = 1;
1815 0 my ($e, $o) = $row->($i);
1816 # The alleles agree when both of the variant's are the record's, or,
1817 # for a record with no ALT, when either is its REF.
1818 next unless @alleles == 1
1819 ? $e eq uc $ref || (length $o && $o eq uc $ref)
1820 0 ▶ : defined $named{$e} && (!length $o || defined $named{$o});
Branch: 2 branches
BranchTrueFalseTotal
unless @alleles == 1 ? $e eq uc $ref || length $o && $o eq uc $ref : defined $named{$e} && (!length($o) || defined $named{$o}) 0 0 0
@alleles == 1 ? : 0 0 0
Condition0%0/12
$e eq uc $ref or length $o and $o eq uc $ref
l!l&&r!l&&!r
000
length $o and $o eq uc $ref
!ll&&!rl&&r
000
defined $named{$e} and !length($o) || defined $named{$o}
!ll&&!rl&&r
000
not length $o or defined $named{$o}
l!l&&r!l&&!r
000
MC/DC0%0/3
$e eq uc $ref or length $o and $o eq uc $ref
$e eq uc $ref length $o $o eq uc $ref
MC/DC0%0/3
defined $named{$e} and !length($o) || defined $named{$o}
defined $named{$e} not length $o defined $named{$o}
Truth table0%0/4
A or B and C
A= $e eq uc $refB= length $oC= $o eq uc $ref
ABCresult
1XX1
0111
00X0
0100
Truth table0%0/4
A and not(B) or C
A= defined $named{$e}B= not length $oC= defined $named{$o}
ABCresult
0XX0
1000
11X1
1011
1821 # Of two records that agree, as a multi-allelic site split in two
1822 # can give, the one whose "CHROM:POS:REF:ALT" sorts first as a
1823 # string is used, so that the order of the file does not decide it.
1824 # That is not genomic order ("1:100" sorts before "1:99"), and need
1825 # not be: the choice only has to be the same every time.
1826 0 ▶ next if defined $use[$i] && (split /\t/, $use[$i])[2] le $sort;
Branch: 1 branch
BranchTrueFalseTotal
if defined $use[$i] and (split(/\t/, $use[$i], 0))[2] le $sort 0 0 0
Condition0%0/3
defined $use[$i] and (split(/\t/, $use[$i], 0))[2] le $sort
!ll&&!rl&&r
000
MC/DC0%0/2
defined $use[$i] and (split(/\t/, $use[$i], 0))[2] le $sort
defined $use[$i] (split(/\t/, $use[$i], 0))[2] le $sort
Truth table0%0/3
A and B
A= defined $use[$i]B= (split(/\t/, $use[$i], 0))[2] le $sort
ABresult
0X0
100
111
1827 # An effect allele the record lacks (its REF being the other allele)
1828 # has no copies; it is given as the REF with a weight of 0, which
1829 # counts the sample's alleles there and adds nothing.
1830 0 ▶ $use[$i] = join "\t", $n, $named{$e} // $ref, $sort, defined $named{$e} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $named{$e} ? : 0 0 0
Condition0%0/3
$named{$e} // $ref
l!l&&r!l&&!r
000
MC/DC0%0/2
$named{$e} // $ref
$named{$e} $ref
Truth table0%0/3
A // B
A= $named{$e}B= $ref
ABresult
1X1
011
000
1831 }
1832 }
1833 0 ▶ unless ($none) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($none) 0 0 0
1834 0 close $in;
1835 0 ▶ close $out or croak "$sub: can't write $g.ids.pvar: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $out or croak("${sub}: can't write $g.ids.pvar: $!") 0 0 0
1836 }
1837 0 undef %at; # no longer needed, and the largest of these, with a key and an entry for every row
1838  
1839 0 my %score = map { $_ => { alleles => 0, mismatched => 0, missing => 0, score => 0, variants => 0 } } @samples;
1840 0 my $agree = grep { defined } @use;
1841 0 my $disagree = unpack('%32b*', $found) - $agree;
1842 # --score takes one line for each record, so a record that two rows of
1843 # weights fall on is scored in a second pass, and so on.
1844 # Pass $p's score file and list of records are written as the rows are
1845 # read, rather than gathered first, so that a score of millions of variants
1846 # is not held twice.
1847 # A record is in pass 0 when it is the first row's to take it, and in pass
1848 # $again{record} when it is a later one's; nearly every record is taken by
1849 # one row alone, so a bit for each is all that most need.
1850 0 my $taken = ''; # bit $rec set: a row has taken record $rec
1851 0 my %again; # record => how many rows have taken it, less 1, for a record taken by more than one
1852 my @pass; # pass => [its file's prefix, score file handle, ID list handle]
1853 0 foreach my $i (grep { defined $use[$_] } 0 .. $#use) {
1854 0 my ($rec, $a1, undef, $has) = split /\t/, $use[$i];
1855 0 my $p = 0;
1856 0 ▶ if (vec $taken, $rec, 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (vec $taken, $rec, 1) { } 0 0 0
1857 0 $p = ++$again{$rec};
1858 } else {
1859 0 vec($taken, $rec, 1) = 1;
1860 }
1861 0 ▶ unless ($pass[$p]) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pass[$p]) 0 0 0
1862 0 my $file = File::Spec->catfile($dir, "score$p");
1863 0 ▶ open my $fh, '>', "$file.txt" or croak "$sub: can't write $file.txt: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", "$file.txt" or croak("${sub}: can't write $file.txt: $!") 0 0 0
1864 0 ▶ open my $ids, '>', "$file.ids" or croak "$sub: can't write $file.ids: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $ids, ">", "$file.ids" or croak("${sub}: can't write $file.ids: $!") 0 0 0
1865 0 print {$fh} "ID\tA1\tWEIGHT\n";
1866 0 $pass[$p] = [$file, $fh, $ids];
1867 }
1868 0 ▶ print { $pass[$p][1] } "v$rec\t$a1\t", ($has ? ($row->($i))[2] : 0), "\n";
Branch: 1 branch
BranchTrueFalseTotal
$has ? : 0 0 0
1869 0 print { $pass[$p][2] } "v$rec\n";
1870 }
1871 0 undef $taken;
1872 0 undef %again;
1873 0 undef @use;
1874 0 foreach my $pass (@pass) {
1875 0 my ($file, $fh, $ids) = @{ $pass };
1876 0 ▶ close $fh or croak "$sub: can't write $file.txt: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't write $file.txt: $!") 0 0 0
1877 0 ▶ close $ids or croak "$sub: can't write $file.ids: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $ids or croak("${sub}: can't write $file.ids: $!") 0 0 0
1878 0 _plink2($sub, $plink2, $dir, '--pgen', "$g.pgen", '--pvar', "$g.ids.pvar", '--psam', "$g.psam", @common,
1879 '--extract', "$file.ids", '--score', "$file.txt", 1, 2, 3, 'header', 'no-mean-imputation', 'cols=+scoresums',
1880 '--missing', 'sample-only', '--out', $file);
1881 # .smiss's OBS_CT is how many genotypes there were to see, and
1882 # MISSING_CT how many of those were missing, so a sample's variants are
1883 # the one less the other.
1884 0 foreach my $part (['sscore', ALLELE_CT => ['alleles', 1], SCORE1_SUM => ['score', 1]],
1885 ['smiss', OBS_CT => ['variants', 1], MISSING_CT => ['variants', -1]]) {
1886 0 my ($ext, %field) = @{ $part };
1887 0 ▶ open my $res, '<', "$file.$ext" or croak "$sub: can't read $file.$ext: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $res, "<", "$file.$ext" or croak("${sub}: can't read $file.${ext}: $!") 0 0 0
1888 0 chomp(my $head = <$res>);
1889 0 my @h = split /\t/, $head;
1890 0 my %at_col = map { $h[$_] => $_ } 0 .. $#h;
1891 0 ▶ my $id_col = $at_col{'#IID'} // $at_col{IID};
Condition0%0/3
$at_col{"#IID"} // $at_col{"IID"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$at_col{"#IID"} // $at_col{"IID"}
$at_col{"#IID"} $at_col{"IID"}
Truth table0%0/3
A // B
A= $at_col{"#IID"}B= $at_col{"IID"}
ABresult
1X1
011
000
1892 0 ▶ while (my $line = <$res>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $res)) 0 0 0
1893 0 chomp $line;
1894 0 my @f = split /\t/, $line;
1895 0 $score{ $f[$id_col] }{ $field{$_}[0] } += $field{$_}[1] * $f[ $at_col{$_} ] foreach keys %field;
1896 }
1897 0 close $res;
1898 }
1899 }
1900 0 foreach my $s (values %score) {
1901 0 $s->{missing} = $n_rows - $s->{variants};
1902 0 $s->{mismatched} = $disagree;
1903 0 ▶ $s->{average} = $s->{alleles} ? $s->{score} / $s->{alleles} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$s->{'alleles'} ? : 0 0 0
1904 }
1905 # On 2026-10-17, PGS000138 (whose header says genome_build=NR) against a
1906 # GRCh37 genome had 12,015 of its 22,274 variants at their positions, and
1907 # the alleles agreed at all 12,015; with every position moved on one base,
1908 # as a stand-in for the wrong build, they agreed at 9 of the 58 found.
1909 # Disagreement at more than half the variants found is the second case.
1910 0 ▶ if (!$agree) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $agree) { } 0 0 0
elsif ($disagree > $agree) { } 0 0 0
1911 carp "$sub: none of the $n_rows" . ' variants of "weights" was found in "vcf" with its alleles; check that the two'
1912 0 ▶ . ($r{match} eq 'id' ? ' use the same rsIDs' : ' are on the same genome build and name chromosomes alike');
Branch: 1 branch
BranchTrueFalseTotal
$r{'match'} eq 'id' ? : 0 0 0
1913 } elsif ($disagree > $agree) {
1914 carp "$sub: the alleles disagree at $disagree of the " . ($agree + $disagree) . ' variants of "weights" found in "vcf"; check that'
1915 0 ▶ . ' the two are on the same ' . ($r{match} eq 'id' ? 'strand' : 'genome build');
Branch: 1 branch
BranchTrueFalseTotal
$r{'match'} eq 'id' ? : 0 0 0
1916 }
1917 0 require File::Path;
1918 0 File::Path::rmtree($dir);
1919 0 \%score;
1920 }
1921  
1922 # ---- population genetics, by PLINK 2 (since 2026-11-17)
1923  
1924 # The genotypes of "vcf" of $sub, given as plink2's arguments @$input (from
1925 # _plink2_input) and @$common (from _plink2_resources), made a PLINK 2 fileset
1926 # in $dir of the autosomes' biallelic variants alone, with each variant's ID
1927 # made v1, v2, ... in the fileset's order, which every command's output then
1928 # names it by: a VCF's own IDs are often "." and need not be unique, and
1929 # --indep-pairwise refuses IDs that are not. The sex chromosomes are left out,
1930 # since PLINK 2 reads them only once told each sample's sex and where X's
1931 # pseudo-autosomal regions are. Returns plink2's arguments that read the
1932 # fileset, the variants in its order, for _popgen_variant to look up, and the
1933 # samples' IIDs in its order, $what being what $sub returns by IID.
1934 #
1935 # The variants are a hash ref, whose "count" is how many there are. With
1936 # $keep, each one's CHROM, POS, ID, REF and ALT are also written, a line of
1937 # them for each, to $dir/variants.tsv ("file"), and where each line starts in
1938 # it is packed into "offsets" as a C double, exact to 2^53 bytes on every
1939 # perl. Until 2026-11-18 they were held as a perl string each, 98 bytes a
1940 # variant (measured on perl 5.44.0), which for the 70 million or so of a
1941 # whole-genome cohort is about 7 GB; the offsets take 8 bytes a variant, and
1942 # pca, which reports only the count, keeps nothing.
1943 0 ▶sub _popgen_genotypes {
Subroutine _popgen_genotypes: not called CC=17 SCAR=57.2
1944 0 my ($sub, $vcf, $input, $common, $plink2, $dir, $what, $keep) = @_;
1945 0 my @input = @{ $input };
1946 0 ▶ if (ref $vcf) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $vcf) 0 0 0
1947 0 my $file = File::Spec->catfile($dir, 'frame.vcf');
1948 0 _frame_vcf($sub, $vcf, $file, 'position');
1949 0 @input = ('--vcf', $file);
1950 }
1951 0 ▶ push @input, '--vcf-half-call', 'missing' unless $input[0] eq '--pfile';
Branch: 1 branch
BranchTrueFalseTotal
unless $input[0] eq "--pfile" 0 0 0
1952 0 my $g = File::Spec->catfile($dir, 'g');
1953 # PLINK 2 exits 7 when a VCF has nothing on the autosomes (it filters by
1954 # --autosome as it reads), and 13 when a fileset has none left
1955 0 ▶ unless (eval { _plink2($sub, $plink2, $dir, @input, @{ $common }, '--autosome', '--min-alleles', 2, '--max-alleles', 2, '--make-pgen', '--out', $g); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { _plink2($sub, $plink2, $dir, @input, @{$common;}, "--autosome", "--min-alleles", 2, "--max-alleles", 2, "--make-pgen", "--out", $g); 1 } }) 0 0 0
1956 # die, not croak, which would give _plink2's message a second "at ... line"
1957 0 ▶ die $@ unless $@ =~ /\((?:exit 13\): Error: No variants remaining|exit 7\): Error: All \d+ variant\(s\) in --[bv]cf file excluded)/;
Branch: 1 branch
BranchTrueFalseTotal
unless $@ =~ /\((?:exit 13\): Error: No variants remaining|exit 7\): Error: All \d+ variant\(s\) in --[bv]cf file excluded)/ 0 0 0
1958 0 croak "$sub: \"vcf\" has no biallelic variant on the autosomes (1 to 22), which are all that $sub reads";
1959 }
1960 0 my %variants = (count => 0, file => File::Spec->catfile($dir, 'variants.tsv'), offsets => '');
1961 0 my $at = 0; # bytes written to variants.tsv
1962 0 my ($list, %col);
1963 0 ▶ if ($keep) {
Branch: 1 branch
BranchTrueFalseTotal
if ($keep) 0 0 0
1964 0 ▶ open $list, '>:raw', $variants{file} or croak "$sub: can't write $variants{file}: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $list, ">:raw", $variants{"file"} or croak(qq[${sub}: can't write $variants{"file"}: $!]) 0 0 0
1965 }
1966 0 ▶ open my $in, '<', "$g.pvar" or croak "$sub: can't read $g.pvar: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $in, "<", "$g.pvar" or croak("${sub}: can't read $g.pvar: $!") 0 0 0
1967 0 ▶ open my $out, '>', "$g.ids.pvar" or croak "$sub: can't write $g.ids.pvar: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $out, ">", "$g.ids.pvar" or croak("${sub}: can't write $g.ids.pvar: $!") 0 0 0
1968 0 ▶ while (my $line = <$in>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $in)) 0 0 0
1969 0 ▶ if ($line =~ /\A##/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\A##/) 0 0 0
1970 0 print {$out} $line;
1971 0 next;
1972 }
1973 0 chomp $line;
1974 0 my @f = split /\t/, $line, -1;
1975 0 ▶ if ($line =~ /\A#CHROM/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\A#CHROM/) 0 0 0
1976 0 %col = map { $f[$_] => $_ } 0 .. $#f;
1977 0 print {$out} "$line\n";
1978 0 next;
1979 }
1980 0 ▶ if ($keep) {
Branch: 1 branch
BranchTrueFalseTotal
if ($keep) 0 0 0
1981 0 my $v = join("\t", @f[ @col{'#CHROM', 'POS', 'ID', 'REF', 'ALT'} ]) . "\n";
1982 0 ▶ print {$list} $v or croak "$sub: can't write $variants{file}: $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$list;} $v or croak(qq[${sub}: can't write $variants{"file"}: $!]) 0 0 0
1983 0 $variants{offsets} .= pack 'd', $at;
1984 0 $at += length $v;
1985 }
1986 0 $f[ $col{ID} ] = 'v' . ++$variants{count};
1987 0 print {$out} join("\t", @f), "\n";
1988 }
1989 0 close $in;
1990 0 ▶ close $out or croak "$sub: can't write $g.ids.pvar: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $out or croak("${sub}: can't write $g.ids.pvar: $!") 0 0 0
1991 0 ▶ if ($keep) {
Branch: 1 branch
BranchTrueFalseTotal
if ($keep) { } 0 0 0
1992 0 ▶ close $list or croak "$sub: can't write $variants{file}: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $list or croak(qq[${sub}: can't write $variants{"file"}: $!]) 0 0 0
1993 } else {
1994 0 delete @variants{qw(file offsets)};
1995 }
1996 0 my @samples = _psam_iids($sub, "$g.psam", $what);
1997 0 (['--pgen', "$g.pgen", '--pvar', "$g.ids.pvar", '--psam', "$g.psam", @{ $common }], \%variants, \@samples);
1998 }
1999  
2000 # The variant that PLINK 2's output names $id ("v<n>", as _popgen_genotypes
2001 # named it) as a hash ref of chrom, pos, id, ref and alt, read from the file
2002 # of $variants (which _popgen_genotypes kept). Its handle is kept open in
2003 # $variants, with "next" the variant it will read next, so that variants
2004 # asked for in order, as every output but --r2's lists them, are read on
2005 # without a seek.
2006 0 ▶sub _popgen_variant {
Subroutine _popgen_variant: not called CC=10 SCAR=47.0
2007 0 my ($variants, $id) = @_;
2008 croak "_popgen_variant: PLINK 2 named a variant \"$id\", which it was not given"
2009 0 ▶ unless defined $id && $id =~ /\Av([1-9][0-9]*)\z/ && $1 <= $variants->{count};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and $id =~ /\Av([1-9][0-9]*)\z/ and $1 <= $variants->{"count"} 0 0 0
Condition0%0/6
defined $id and $id =~ /\Av([1-9][0-9]*)\z/ and $1 <= $variants->{"count"}
!ll&&!rl&&r
000
defined $id and $id =~ /\Av([1-9][0-9]*)\z/
!ll&&!rl&&r
000
MC/DC0%0/3
defined $id and $id =~ /\Av([1-9][0-9]*)\z/ and $1 <= $variants->{"count"}
defined $id $id =~ /\Av([1-9][0-9]*)\z/ $1 <= $variants->{"count"}
Truth table0%0/4
A and B and C
A= defined $idB= $id =~ /\Av([1-9][0-9]*)\z/C= $1 <= $variants->{"count"}
ABCresult
0XX0
10X0
1100
1111
2010 0 my $n = $1 - 1;
2011 0 my $file = $variants->{file};
2012 0 ▶ unless ($variants->{fh}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($variants->{"fh"}) 0 0 0
2013 0 ▶ open $variants->{fh}, '<:raw', $file or croak "_popgen_variant: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $variants->{"fh"}, "<:raw", $file or croak("_popgen_variant: can't read ${file}: $!") 0 0 0
2014 0 $variants->{next} = 0;
2015 }
2016 0 my $fh = $variants->{fh};
2017 0 ▶ if ($variants->{next} != $n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($variants->{"next"} != $n) 0 0 0
2018 0 my $offset = unpack 'd', substr $variants->{offsets}, 8 * $n, 8;
2019 0 ▶ seek $fh, $offset, 0 or croak "_popgen_variant: can't seek to byte $offset of $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $offset, 0 or croak("_popgen_variant: can't seek to byte $offset of ${file}: $!") 0 0 0
2020 }
2021 0 my $line = <$fh>;
2022 0 ▶ croak "_popgen_variant: $file ends before variant " . ($n + 1) unless defined $line && chomp $line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line and chomp $line 0 0 0
Condition0%0/3
defined $line and chomp $line
!ll&&!rl&&r
000
MC/DC0%0/2
defined $line and chomp $line
defined $line chomp $line
Truth table0%0/3
A and B
A= defined $lineB= chomp $line
ABresult
0X0
100
111
2023 0 $variants->{next} = $n + 1;
2024 0 my %v;
2025 0 @v{qw(chrom pos id ref alt)} = split /\t/, $line, -1;
2026 0 $v{pos} += 0;
2027 0 \%v;
2028 }
2029  
2030 # Each line of PLINK 2's tab-separated output $file, for $sub, given to $code
2031 # as a hash ref keyed by its header's columns (the header's "#" dropped), with
2032 # PLINK 2's "NA" and "nan" made undef.
2033 40 my $Plink2_na = qr/\A(?:NA|-?nan)\z/i;
2034 0 ▶sub _plink2_rows {
Subroutine _plink2_rows: not called CC=5 SCAR=34.0
2035 0 my ($sub, $file, $code) = @_;
2036 0 ▶ open my $fh, '<', $file or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or croak("${sub}: can't read ${file}: $!") 0 0 0
2037 0 my $head = <$fh>;
2038 0 ▶ croak "$sub: PLINK 2 wrote $file with no header" unless defined $head;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $head 0 0 0
2039 0 chomp $head;
2040 0 $head =~ s/\A#//;
2041 0 my @cols = split /\t/, $head;
2042 0 ▶ while (my $line = <$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 0 0 0
2043 0 chomp $line;
2044 0 my %row;
2045 0 ▶ @row{@cols} = map { $_ =~ $Plink2_na ? undef : $_ } split /\t/, $line, -1;
Branch: 1 branch
BranchTrueFalseTotal
$_ =~ /$Plink2_na/ ? : 0 0 0
2046 0 $code->(\%row);
2047 }
2048 0 close $fh;
2049 }
2050  
2051 # $x as a number, or undef for undef, so that a JSON encoder writes it as one.
2052 0 ▶sub _number { defined $_[0] ? 0 + $_[0] : undef }
Subroutine _number: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 0 0 0
2053  
2054 # The temporary directory $dir removed, as a function of this section returns,
2055 # once the handle _popgen_variant keeps in $variants is closed: Windows will
2056 # not remove a file that is open.
2057 0 ▶sub _popgen_cleanup {
Subroutine _popgen_cleanup: not called CC=3 SCAR=24.8
2058 0 my ($dir, $variants) = @_;
2059 0 ▶ if (my $fh = delete $variants->{fh}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $fh = delete $variants->{"fh"}) 0 0 0
2060 0 ▶ close $fh or croak "_popgen_cleanup: can't read $variants->{file}: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak(qq[_popgen_cleanup: can't read $variants->{"file"}: $!]) 0 0 0
2061 }
2062 0 require File::Path;
2063 0 File::Path::rmtree($dir);
2064 }
2065  
2066 # Dies unless $sub's option $key, $v, is 0 or 1.
2067 8 ▶sub _flag {
Subroutine _flag: called CC=4 SCAR=14.2
2068 8 my ($sub, $key, $v) = @_;
2069 8 ▶ croak "$sub: \"$key\" must be 0 or 1, not " . _what($v) unless !ref $v && ($v eq '0' || $v eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $v and $v eq 0 || $v eq 1 3 5 8
Condition66%4/6
not ref $v and $v eq 0 || $v eq 1
!ll&&!rl&&r
035
$v eq 0 or $v eq 1
l!l&&r!l&&!r
503
MC/DC33%1/3
not ref $v and $v eq 0 || $v eq 1
not ref $v $v eq 0 $v eq 1
Truth table50%2/4
not(A) and B or C
A= not ref $vB= $v eq 0C= $v eq 1
ABCresult
0XX0
1000
11X1
1011
2070 }
2071  
2072 # The setup every function of this section shares: "vcf" of $sub checked, PLINK
2073 # 2 found, a temporary directory made, and the genotypes read into it by
2074 # _popgen_genotypes, which keeps each variant's columns when $keep is 1 and
2075 # only their count when it is 0. Returns that directory, the plink2 program,
2076 # and what _popgen_genotypes returns.
2077 5 ▶sub _popgen_setup {
Subroutine _popgen_setup: called CC=1 SCAR=1.7
2078 5 my ($sub, $args, $what, $keep) = @_;
2079 5 my @common = _plink2_resources($sub, $args);
2080 3 my @input = _plink2_input($sub, $args->{vcf});
2081 0 my $plink2 = _plink2_program($sub);
2082 # removed as $sub returns, or, after an error, as the program ends, as
2083 # pgs_score's is
2084 0 require File::Temp;
2085 0 my $dir = File::Temp::tempdir(CLEANUP => 1);
2086 0 ($dir, $plink2, _popgen_genotypes($sub, $args->{vcf}, \@input, \@common, $plink2, $dir, $what, $keep));
2087 }
2088  
2089 9 ▶sub pca {
Subroutine pca: called CC=5 SCAR=23.4
Pod documented
2090 9 my $sub = 'pca';
2091 9 my $args = _args(\@_, $sub, ['vcf'], [qw(memory n threads)]);
2092 7 my %r;
2093 7 ▶ $r{n} = $args->{n} // 10; # how many principal components; 10 is PLINK 2's own default
Condition100%2/2
$args->{"n"} // 10
l!l
25
MC/DC100%1/1
$args->{"n"} // 10
$args->{"n"}
Truth table100%2/2
A
A= $args->{"n"}
Aresult
11
00
2094 7 ▶ croak "$sub: \"n\" must be a whole number, 1 or more, not " . _what($r{n}) unless !ref $r{n} && $r{n} =~ /\A[1-9][0-9]*\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"n"} and $r{"n"} =~ /\A[1-9][0-9]*\z/ 2 5 7
Condition66%2/3
not ref $r{"n"} and $r{"n"} =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
025
MC/DC50%1/2
not ref $r{"n"} and $r{"n"} =~ /\A[1-9][0-9]*\z/
not ref $r{"n"} $r{"n"} =~ /\A[1-9][0-9]*\z/
Truth table66%2/3
not(A) and B
A= not ref $r{"n"}B= $r{"n"} =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
2095 5 my ($dir, $plink2, $files, $variants, $samples) = _popgen_setup($sub, $args, 'principal components', 0);
2096 0 my $out = File::Spec->catfile($dir, 'pca');
2097 0 _plink2($sub, $plink2, $dir, @{ $files }, '--pca', $r{n}, '--out', $out);
2098 0 ▶ open my $fh, '<', "$out.eigenval" or croak "$sub: can't read $out.eigenval: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", "$out.eigenval" or croak("${sub}: can't read $out.eigenval: $!") 0 0 0
2099 0 chomp(my @eigenvalues = <$fh>);
2100 0 close $fh;
2101 0 @eigenvalues = map { 0 + $_ } @eigenvalues;
2102 0 my %pcs;
2103 0 ▶ _plink2_rows($sub, "$out.eigenvec", sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2104 0 my ($row) = @_;
2105 0 $pcs{ $row->{IID} } = [ map { _number($row->{"PC$_"}) } 1 .. @eigenvalues ];
2106 0 });
2107 0 _popgen_cleanup($dir, $variants);
2108 0 { eigenvalues => \@eigenvalues, samples => \%pcs, variants => 0 + $variants->{count} };
2109 }
2110  
2111 8 ▶sub fst {
Subroutine fst: called CC=23 SCAR=49.9
Pod documented
2112 8 my $sub = 'fst';
2113 8 my $args = _args(\@_, $sub, [qw(vcf populations)], [qw(memory method per_variant threads)]);
2114 7 my %r;
2115 7 ▶ $r{method} = $args->{method} // 'hudson'; # 'hudson' = Bhatia et al. (2013), PLINK 2's default; 'wc' = Weir and Cockerham (1984)
Condition100%2/2
$args->{"method"} // "hudson"
l!l
16
MC/DC100%1/1
$args->{"method"} // "hudson"
$args->{"method"}
Truth table100%2/2
A
A= $args->{"method"}
Aresult
11
00
2116 croak "$sub: \"method\" must be \"hudson\" or \"wc\", not " . _what($r{method})
2117 7 ▶ unless !ref $r{method} && ($r{method} eq 'hudson' || $r{method} eq 'wc');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"method"} and $r{"method"} eq "hudson" || $r{"method"} eq "wc" 1 6 7
Condition66%4/6
not ref $r{"method"} and $r{"method"} eq "hudson" || $r{"method"} eq "wc"
!ll&&!rl&&r
016
$r{"method"} eq "hudson" or $r{"method"} eq "wc"
l!l&&r!l&&!r
601
MC/DC33%1/3
not ref $r{"method"} and $r{"method"} eq "hudson" || $r{"method"} eq "wc"
not ref $r{"method"} $r{"method"} eq "hudson" $r{"method"} eq "wc"
Truth table50%2/4
not(A) and B or C
A= not ref $r{"method"}B= $r{"method"} eq "hudson"C= $r{"method"} eq "wc"
ABCresult
0XX0
1000
11X1
1011
2118 6 ▶ $r{per_variant} = $args->{per_variant} // 0; # 1 = each variant's Fst too, for each pair of populations; 0 = each pair's alone
Condition100%2/2
$args->{"per_variant"} // 0
l!l
15
MC/DC100%1/1
$args->{"per_variant"} // 0
$args->{"per_variant"}
Truth table100%2/2
A
A= $args->{"per_variant"}
Aresult
11
00
2119 6 _flag($sub, 'per_variant', $r{per_variant});
2120 5 my $pops = $args->{populations};
2121 5 ▶ croak "$sub: \"populations\" must be a hash ref of sample => population, not " . _what($pops) unless ref $pops eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pops eq "HASH" 1 4 5
2122 4 foreach my $s (sort keys %{ $pops }) {
2123 6 my $p = $pops->{$s};
2124 6 ▶ croak "$sub: \"populations\" gives \"$s\" the population " . _what($p) . ', where a population is a name'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $p and not ref $p and length $p 2 4 6
Condition83%5/6
defined $p and not ref $p and length $p
!ll&&!rl&&r
114
defined $p and not ref $p
!ll&&!rl&&r
105
MC/DC66%2/3
defined $p and not ref $p and length $p
defined $p not ref $p length $p
Truth table75%3/4
A and not(B) and C
A= defined $pB= not ref $pC= length $p
ABCresult
0XX0
10X0
1100
1111
2125 unless defined $p && !ref $p && length $p;
2126 }
2127 2 my %named = map { $_ => 1 } values %{ $pops };
2128 2 ▶ croak "$sub: \"populations\" names " . (%named ? 'one population' : 'no population') . ', and Fst is between two or more' if keys %named < 2;
Branch: 2 branches
BranchTrueFalseTotal
if keys %named < 2 2 0 2
%named ? : 1 1 2
2129 0 my ($dir, $plink2, $files, $variants, $samples) = _popgen_setup($sub, $args, 'populations', $r{per_variant});
2130 # Each population is named in PLINK 2's file by a code, P1, P2, ..., in the
2131 # order of the names, since PLINK 2 would take a name that is a number as a
2132 # quantitative value, and one with a space as two fields.
2133 0 my @names = sort keys %named;
2134 0 my %code = map { $names[$_] => 'P' . ($_ + 1) } 0 .. $#names;
2135 0 my %name = reverse %code;
2136 0 my %size; # population => its samples in the VCF
2137 0 my $pheno = File::Spec->catfile($dir, 'populations.tsv');
2138 0 ▶ open my $fh, '>', $pheno or croak "$sub: can't write $pheno: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $pheno or croak("${sub}: can't write ${pheno}: $!") 0 0 0
2139 0 print {$fh} "#IID\tPOP\n";
2140 0 foreach my $s (@{ $samples }) {
2141 0 my $p = $pops->{$s};
2142 0 ▶ $size{$p}++ if defined $p;
Branch: 1 branch
BranchTrueFalseTotal
if defined $p 0 0 0
2143 # NONE is PLINK 2's missing category (--missing-catname); it refuses NA there
2144 0 ▶ print {$fh} "$s\t", defined $p ? $code{$p} : 'NONE', "\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $p ? : 0 0 0
2145 }
2146 0 ▶ close $fh or croak "$sub: can't write $pheno: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't write ${pheno}: $!") 0 0 0
2147 0 ▶ croak "$sub: " . (%size ? 'only "' . join('', keys %size) . '", one' : 'none') . ' of the ' . @names
Branch: 2 branches
BranchTrueFalseTotal
if keys %size < 2 0 0 0
%size ? : 0 0 0
2148 . ' populations of "populations" has a sample in "vcf", and Fst is between two or more' if keys %size < 2;
2149 0 my $out = File::Spec->catfile($dir, 'fst');
2150 0 ▶ _plink2($sub, $plink2, $dir, @{ $files }, '--pheno', $pheno, '--fst', 'POP', "method=$r{method}",
Branch: 1 branch
BranchTrueFalseTotal
$r{'per_variant'} ? : 0 0 0
2151 0 $r{per_variant} ? 'report-variants' : (), '--out', $out);
2152 0 ▶ my $column = $r{method} eq 'hudson' ? 'HUDSON_FST' : 'WC_FST';
Branch: 1 branch
BranchTrueFalseTotal
$r{'method'} eq 'hudson' ? : 0 0 0
2153 0 my (%fst, %per);
2154 0 ▶ _plink2_rows($sub, "$out.fst.summary", sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2155 0 my ($row) = @_;
2156 0 my ($x, $y) = @{ $row }{qw(POP1 POP2)};
2157 0 my ($p, $q) = @name{$x, $y};
2158 0 $fst{$p}{$q} = $fst{$q}{$p} = _number($row->{$column});
2159 0 ▶ return unless $r{per_variant};
Branch: 1 branch
BranchTrueFalseTotal
unless $r{"per_variant"} 0 0 0
2160 0 my @each;
2161 0 ▶ _plink2_rows($sub, "$out.$x.$y.fst.var", sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
2162 0 my ($v) = @_;
2163 0 my $variant = _popgen_variant($variants, $v->{ID});
2164 0 $variant->{fst} = _number($v->{$column});
2165 0 push @each, $variant;
2166 0 });
2167 0 $per{$p}{$q} = $per{$q}{$p} = \@each;
2168 0 });
2169 0 _popgen_cleanup($dir, $variants);
2170 0 ▶ { method => $r{method}, populations => \%size, fst => \%fst, variants => $r{per_variant} ? \%per : undef };
Branch: 1 branch
BranchTrueFalseTotal
$r{'per_variant'} ? : 0 0 0
2171 }
2172  
2173 1 ▶sub hardy_weinberg {
Subroutine hardy_weinberg: called CC=3 SCAR=20.8
Pod documented
2174 1 my $sub = 'hardy_weinberg';
2175 1 my $args = _args(\@_, $sub, ['vcf'], [qw(memory midp threads)]);
2176 1 my %r;
2177 1 ▶ $r{midp} = $args->{midp} // 0; # 1 = the mid-p (Graffelman and Moreno 2013); 0 = the exact test's own p (Wigginton et al. 2005), PLINK 2's default
Condition50%1/2
$args->{"midp"} // 0
l!l
10
MC/DC0%0/1
$args->{"midp"} // 0
$args->{"midp"}
Truth table50%1/2
A
A= $args->{"midp"}
Aresult
11
00
2178 1 _flag($sub, 'midp', $r{midp});
2179 0 my ($dir, $plink2, $files, $variants) = _popgen_setup($sub, $args, 'genotype counts', 1);
2180 0 my $out = File::Spec->catfile($dir, 'hardy');
2181 0 ▶ _plink2($sub, $plink2, $dir, @{ $files }, '--hardy', $r{midp} ? 'midp' : (), '--out', $out);
Branch: 1 branch
BranchTrueFalseTotal
$r{'midp'} ? : 0 0 0
2182 0 my @out;
2183 0 ▶ _plink2_rows($sub, "$out.hardy", sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
2184 0 my ($row) = @_;
2185 0 my $v = _popgen_variant($variants, $row->{ID});
2186 # PLINK 2 counts by A1, which may be either allele
2187 0 ▶ my $a1_ref = uc $row->{A1} eq uc $v->{ref} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
uc $row->{'A1'} eq uc $v->{'ref'} ? : 0 0 0
2188 0 ▶ @{ $v }{qw(hom_ref het hom_alt)} = map { 0 + $_ } @{ $row }{ $a1_ref ? qw(HOM_A1_CT HET_A1_CT TWO_AX_CT) : qw(TWO_AX_CT HET_A1_CT HOM_A1_CT) };
Branch: 1 branch
BranchTrueFalseTotal
$a1_ref ? : 0 0 0
2189 0 $v->{observed_het} = _number($row->{'O(HET_A1)'});
2190 0 $v->{expected_het} = _number($row->{'E(HET_A1)'});
2191 0 ▶ $v->{p} = _number($row->{ $r{midp} ? 'MIDP' : 'P' });
Branch: 1 branch
BranchTrueFalseTotal
$r{'midp'} ? : 0 0 0
2192 0 push @out, $v;
2193 0 });
2194 0 _popgen_cleanup($dir, $variants);
2195 0 \@out;
2196 }
2197  
2198 4 ▶sub ld {
Subroutine ld: called CC=17 SCAR=39.4
Pod documented
2199 4 my $sub = 'ld';
2200 4 my $args = _args(\@_, $sub, ['vcf'], [qw(memory min_r2 phased threads window window_kb)]);
2201 4 my %r;
2202 4 ▶ $r{window_kb} = $args->{window_kb} // 1000; # the farthest apart, in kb, the two variants of a pair are; 1000 is PLINK 2's default
Condition100%2/2
$args->{"window_kb"} // 1000
l!l
13
MC/DC100%1/1
$args->{"window_kb"} // 1000
$args->{"window_kb"}
Truth table100%2/2
A
A= $args->{"window_kb"}
Aresult
11
00
2203 croak "$sub: \"window_kb\" must be a number above 0, not " . _what($r{window_kb})
2204 4 ▶ unless !ref $r{window_kb} && $r{window_kb} =~ $Number && $r{window_kb} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"window_kb"} and $r{"window_kb"} =~ /$Number/ and $r{"window_kb"} > 0 1 3 4
Condition50%3/6
not ref $r{"window_kb"} and $r{"window_kb"} =~ /$Number/ and $r{"window_kb"} > 0
!ll&&!rl&&r
013
not ref $r{"window_kb"} and $r{"window_kb"} =~ /$Number/
!ll&&!rl&&r
004
MC/DC33%1/3
not ref $r{"window_kb"} and $r{"window_kb"} =~ /$Number/ and $r{"window_kb"} > 0
not ref $r{"window_kb"} $r{"window_kb"} =~ /$Number/ $r{"window_kb"} > 0
Truth table50%2/4
not(A) and B and C
A= not ref $r{"window_kb"}B= $r{"window_kb"} =~ /$Number/C= $r{"window_kb"} > 0
ABCresult
0XX0
10X0
1100
1111
2205 3 $r{window} = $args->{window}; # undef = no limit, PLINK 2's default; n = the two variants of a pair are at most n variants apart (1 = adjacent)
2206 croak "$sub: \"window\" must be a whole number, 1 or more, not " . _what($r{window})
2207 3 ▶ if defined $r{window} && (ref $r{window} || $r{window} !~ /\A[1-9][0-9]*\z/);
Branch: 1 branch
BranchTrueFalseTotal
if defined $r{"window"} and ref $r{"window"} || !($r{"window"} =~ /\A[1-9][0-9]*\z/) 1 2 3
Condition50%3/6
defined $r{"window"} and ref $r{"window"} || !($r{"window"} =~ /\A[1-9][0-9]*\z/)
!ll&&!rl&&r
201
ref $r{"window"} or not $r{"window"} =~ /\A[1-9][0-9]*\z/
l!l&&r!l&&!r
010
MC/DC33%1/3
defined $r{"window"} and ref $r{"window"} || !($r{"window"} =~ /\A[1-9][0-9]*\z/)
defined $r{"window"} ref $r{"window"} not $r{"window"} =~ /\A[1-9][0-9]*\z/
Truth table50%2/4
A and B or not(C)
A= defined $r{"window"}B= ref $r{"window"}C= not $r{"window"} =~ /\A[1-9][0-9]*\z/
ABCresult
0XX0
1000
11X1
1011
2208 2 ▶ $r{min_r2} = $args->{min_r2} // 0.2; # the least r² of a pair reported; 0.2 is PLINK 2's default, and 0 reports every pair
Condition100%2/2
$args->{"min_r2"} // "0.2"
l!l
11
MC/DC100%1/1
$args->{"min_r2"} // "0.2"
$args->{"min_r2"}
Truth table100%2/2
A
A= $args->{"min_r2"}
Aresult
11
00
2209 croak "$sub: \"min_r2\" must be a number from 0 to 1, not " . _what($r{min_r2})
2210 2 ▶ unless !ref $r{min_r2} && $r{min_r2} =~ $Number && $r{min_r2} >= 0 && $r{min_r2} <= 1;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"min_r2"} and $r{"min_r2"} =~ /$Number/ and $r{"min_r2"} >= 0 and $r{"min_r2"} <= 1 1 1 2
Condition44%4/9
not ref $r{"min_r2"} and $r{"min_r2"} =~ /$Number/ and $r{"min_r2"} >= 0 and $r{"min_r2"} <= 1
!ll&&!rl&&r
011
not ref $r{"min_r2"} and $r{"min_r2"} =~ /$Number/ and $r{"min_r2"} >= 0
!ll&&!rl&&r
002
not ref $r{"min_r2"} and $r{"min_r2"} =~ /$Number/
!ll&&!rl&&r
002
MC/DC25%1/4
not ref $r{"min_r2"} and $r{"min_r2"} =~ /$Number/ and $r{"min_r2"} >= 0 and $r{"min_r2"} <= 1
not ref $r{"min_r2"} $r{"min_r2"} =~ /$Number/ $r{"min_r2"} >= 0 $r{"min_r2"} <= 1
Truth table40%2/5
not(A) and B and C and D
A= not ref $r{"min_r2"}B= $r{"min_r2"} =~ /$Number/C= $r{"min_r2"} >= 0D= $r{"min_r2"} <= 1
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2211 1 ▶ $r{phased} = $args->{phased} // 0; # 0 = r² of the genotypes' allele counts (--r2-unphased); 1 = r² of the haplotypes, and D' (--r2-phased)
Condition50%1/2
$args->{"phased"} // 0
l!l
10
MC/DC0%0/1
$args->{"phased"} // 0
$args->{"phased"}
Truth table50%1/2
A
A= $args->{"phased"}
Aresult
11
00
2212 1 _flag($sub, 'phased', $r{phased});
2213 0 my ($dir, $plink2, $files, $variants) = _popgen_setup($sub, $args, 'pairs', 1);
2214 0 my $out = File::Spec->catfile($dir, 'ld');
2215 # PLINK 2's --ld-window counts the second variant: 2 is adjacent pairs alone
2216 0 ▶ _plink2($sub, $plink2, $dir, @{ $files }, $r{phased} ? ('--r2-phased', 'cols=+dprime') : '--r2-unphased',
Branch: 2 branches
BranchTrueFalseTotal
$r{'phased'} ? : 0 0 0
defined $r{'window'} ? : 0 0 0
2217 0 '--ld-window-kb', $r{window_kb}, '--ld-window-r2', $r{min_r2}, (defined $r{window} ? ('--ld-window', $r{window} + 1) : ()), '--out', $out);
2218 0 ▶ my $column = $r{phased} ? 'PHASED_R2' : 'UNPHASED_R2';
Branch: 1 branch
BranchTrueFalseTotal
$r{'phased'} ? : 0 0 0
2219 0 my @pairs;
2220 0 ▶ _plink2_rows($sub, "$out.vcor", sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2221 0 my ($row) = @_;
2222 push @pairs, { a => _popgen_variant($variants, $row->{ID_A}), b => _popgen_variant($variants, $row->{ID_B}),
2223 0 ▶ r2 => _number($row->{$column}), dprime => $r{phased} ? _number($row->{DPRIME}) : undef };
Branch: 1 branch
BranchTrueFalseTotal
$r{'phased'} ? : 0 0 0
2224 0 });
2225 0 _popgen_cleanup($dir, $variants);
2226 0 \@pairs;
2227 }
2228  
2229 7 ▶sub ld_prune {
Subroutine ld_prune: called CC=27 SCAR=42.1
Pod documented
2230 7 my $sub = 'ld_prune';
2231 7 my $args = _args(\@_, $sub, ['vcf'], [qw(memory r2 step threads window window_kb)]);
2232 7 my %r;
2233 croak "$sub: the window is given either in variants, as \"window\", or in kb, as \"window_kb\", not both"
2234 7 ▶ if defined $args->{window} && defined $args->{window_kb};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"window"} and defined $args->{"window_kb"} 1 6 7
Condition100%3/3
defined $args->{"window"} and defined $args->{"window_kb"}
!ll&&!rl&&r
511
MC/DC100%2/2
defined $args->{"window"} and defined $args->{"window_kb"}
defined $args->{"window"} defined $args->{"window_kb"}
Truth table100%3/3
A and B
A= defined $args->{"window"}B= defined $args->{"window_kb"}
ABresult
0X0
100
111
2235 6 $r{window_kb} = $args->{window_kb}; # undef = the window is counted in variants, by "window"; n = n kb
2236 croak "$sub: \"window_kb\" must be a whole number, 1 or more, not " . _what($r{window_kb})
2237 6 ▶ if defined $r{window_kb} && (ref $r{window_kb} || $r{window_kb} !~ /\A[1-9][0-9]*\z/);
Branch: 1 branch
BranchTrueFalseTotal
if defined $r{"window_kb"} and ref $r{"window_kb"} || !($r{"window_kb"} =~ /\A[1-9][0-9]*\z/) 1 5 6
Condition83%5/6
defined $r{"window_kb"} and ref $r{"window_kb"} || !($r{"window_kb"} =~ /\A[1-9][0-9]*\z/)
!ll&&!rl&&r
411
ref $r{"window_kb"} or not $r{"window_kb"} =~ /\A[1-9][0-9]*\z/
l!l&&r!l&&!r
011
MC/DC66%2/3
defined $r{"window_kb"} and ref $r{"window_kb"} || !($r{"window_kb"} =~ /\A[1-9][0-9]*\z/)
defined $r{"window_kb"} ref $r{"window_kb"} not $r{"window_kb"} =~ /\A[1-9][0-9]*\z/
Truth table75%3/4
A and B or not(C)
A= defined $r{"window_kb"}B= ref $r{"window_kb"}C= not $r{"window_kb"} =~ /\A[1-9][0-9]*\z/
ABCresult
0XX0
1000
11X1
1011
2238 # 50, 5 and 0.5 are the example the PLINK 1.9 manual gives for --indep-pairwise
2239 5 ▶ $r{window} = defined $r{window_kb} ? undef : $args->{window} // 50; # the variants in each window; undef with "window_kb"
Branch: 1 branch
BranchTrueFalseTotal
defined $r{'window_kb'} ? : 1 4 5
Condition100%2/2
$args->{"window"} // 50
l!l
13
MC/DC100%1/1
$args->{"window"} // 50
$args->{"window"}
Truth table100%2/2
A
A= $args->{"window"}
Aresult
11
00
2240 croak "$sub: \"window\" must be a whole number, 2 or more, not " . _what($r{window})
2241 5 ▶ if defined $r{window} && (ref $r{window} || $r{window} !~ /\A[1-9][0-9]*\z/ || $r{window} < 2);
Branch: 1 branch
BranchTrueFalseTotal
if defined $r{"window"} and ref $r{"window"} || !($r{"window"} =~ /\A[1-9][0-9]*\z/) || $r{"window"} < 2 1 4 5
Condition66%6/9
defined $r{"window"} and ref $r{"window"} || !($r{"window"} =~ /\A[1-9][0-9]*\z/) || $r{"window"} < 2
!ll&&!rl&&r
131
ref $r{"window"} or not $r{"window"} =~ /\A[1-9][0-9]*\z/ or $r{"window"} < 2
l!l&&r!l&&!r
013
ref $r{"window"} or not $r{"window"} =~ /\A[1-9][0-9]*\z/
l!l&&r!l&&!r
004
MC/DC50%2/4
defined $r{"window"} and ref $r{"window"} || !($r{"window"} =~ /\A[1-9][0-9]*\z/) || $r{"window"} < 2
defined $r{"window"} ref $r{"window"} not $r{"window"} =~ /\A[1-9][0-9]*\z/ $r{"window"} < 2
Truth table60%3/5
A and B or not(C) or D
A= defined $r{"window"}B= ref $r{"window"}C= not $r{"window"} =~ /\A[1-9][0-9]*\z/D= $r{"window"} < 2
ABCDresult
0XXX0
10000
11XX1
101X1
10011
2242 4 ▶ $r{step} = $args->{step} // (defined $r{window_kb} ? 1 : 5); # the variants the window moves on by; PLINK 2 takes only 1 with a window in kb
Branch: 1 branch
BranchTrueFalseTotal
defined $r{'window_kb'} ? : 0 2 2
Condition100%2/2
$args->{"step"} // (defined $r{"window_kb"} ? 1 : 5)
l!l
22
MC/DC100%1/1
$args->{"step"} // (defined $r{"window_kb"} ? 1 : 5)
$args->{"step"}
Truth table100%2/2
A
A= $args->{"step"}
Aresult
11
00
2243 4 ▶ croak "$sub: \"step\" must be a whole number, 1 or more, not " . _what($r{step}) unless !ref $r{step} && $r{step} =~ /\A[1-9][0-9]*\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"step"} and $r{"step"} =~ /\A[1-9][0-9]*\z/ 1 3 4
Condition66%2/3
not ref $r{"step"} and $r{"step"} =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
013
MC/DC50%1/2
not ref $r{"step"} and $r{"step"} =~ /\A[1-9][0-9]*\z/
not ref $r{"step"} $r{"step"} =~ /\A[1-9][0-9]*\z/
Truth table66%2/3
not(A) and B
A= not ref $r{"step"}B= $r{"step"} =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
2244 3 ▶ croak "$sub: \"step\" must be 1 with \"window_kb\", as PLINK 2 has it, not $r{step}" if defined $r{window_kb} && $r{step} != 1;
Branch: 1 branch
BranchTrueFalseTotal
if defined $r{"window_kb"} and $r{"step"} != 1 1 2 3
Condition66%2/3
defined $r{"window_kb"} and $r{"step"} != 1
!ll&&!rl&&r
201
MC/DC50%1/2
defined $r{"window_kb"} and $r{"step"} != 1
defined $r{"window_kb"} $r{"step"} != 1
Truth table66%2/3
A and B
A= defined $r{"window_kb"}B= $r{"step"} != 1
ABresult
0X0
100
111
2245 2 ▶ $r{r2} = $args->{r2} // 0.5; # of two variants whose r² is above this, one is pruned
Condition50%1/2
$args->{"r2"} // "0.5"
l!l
20
MC/DC0%0/1
$args->{"r2"} // "0.5"
$args->{"r2"}
Truth table50%1/2
A
A= $args->{"r2"}
Aresult
11
00
2246 croak "$sub: \"r2\" must be a number above 0 and below 1, not " . _what($r{r2})
2247 2 ▶ unless !ref $r{r2} && $r{r2} =~ $Number && $r{r2} > 0 && $r{r2} < 1;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"r2"} and $r{"r2"} =~ /$Number/ and $r{"r2"} > 0 and $r{"r2"} < 1 2 0 2
Condition55%5/9
not ref $r{"r2"} and $r{"r2"} =~ /$Number/ and $r{"r2"} > 0 and $r{"r2"} < 1
!ll&&!rl&&r
110
not ref $r{"r2"} and $r{"r2"} =~ /$Number/ and $r{"r2"} > 0
!ll&&!rl&&r
011
not ref $r{"r2"} and $r{"r2"} =~ /$Number/
!ll&&!rl&&r
002
MC/DC0%0/4
not ref $r{"r2"} and $r{"r2"} =~ /$Number/ and $r{"r2"} > 0 and $r{"r2"} < 1
not ref $r{"r2"} $r{"r2"} =~ /$Number/ $r{"r2"} > 0 $r{"r2"} < 1
Truth table40%2/5
not(A) and B and C and D
A= not ref $r{"r2"}B= $r{"r2"} =~ /$Number/C= $r{"r2"} > 0D= $r{"r2"} < 1
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2248 0 my ($dir, $plink2, $files, $variants) = _popgen_setup($sub, $args, 'variants', 1);
2249 0 my $out = File::Spec->catfile($dir, 'prune');
2250 0 ▶ _plink2($sub, $plink2, $dir, @{ $files }, '--indep-pairwise', defined $r{window_kb} ? "$r{window_kb}kb" : $r{window}, $r{step}, $r{r2}, '--out', $out);
Branch: 1 branch
BranchTrueFalseTotal
defined $r{'window_kb'} ? : 0 0 0
2251 0 my %list;
2252 0 foreach my $k (qw(in out)) {
2253 0 ▶ open my $fh, '<', "$out.prune.$k" or croak "$sub: can't read $out.prune.$k: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", "$out.prune.$k" or croak("${sub}: can't read $out.prune.${k}: $!") 0 0 0
2254 0 chomp(my @ids = <$fh>);
2255 0 close $fh;
2256 # in the VCF's order, which PLINK 2's lists already are, and need not be
2257 0 ▶ $list{$k} = [ map { _popgen_variant($variants, "v$_") } sort { $a <=> $b } map { /\Av([0-9]+)\z/ ? $1 : -1 } @ids ];
Branch: 1 branch
BranchTrueFalseTotal
/\Av([0-9]+)\z/ ? : 0 0 0
2258 }
2259 0 _popgen_cleanup($dir, $variants);
2260 0 { keep => $list{in}, remove => $list{out} };
2261 }
2262  
2263 # The rows of "phenotypes" of $sub as an array of hash refs: a data frame, or a
2264 # tab-separated file whose first line is its header, which may begin with "#",
2265 # as PLINK 2's own phenotype files' does; the "#" is dropped.
2266 13 ▶sub _phenotype_rows {
Subroutine _phenotype_rows: called CC=10 SCAR=24.2
2267 13 my ($sub, $phenotypes) = @_;
2268 13 ▶ return _frame_rows($sub, 'phenotypes', $phenotypes) if ref $phenotypes;
Branch: 1 branch
BranchTrueFalseTotal
if ref $phenotypes 10 3 13
2269 3 ▶ croak "$sub: \"phenotypes\" file \"$phenotypes\" doesn't exist or isn't readable" unless -f $phenotypes && -r _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $phenotypes and -r _ 1 2 3
Condition66%2/3
-f $phenotypes and -r _
!ll&&!rl&&r
102
MC/DC50%1/2
-f $phenotypes and -r _
-f $phenotypes -r _
Truth table66%2/3
A and B
A= -f $phenotypesB= -r _
ABresult
0X0
100
111
2270 2 ▶ open my $fh, '<', $phenotypes or croak "$sub: can't read $phenotypes: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $phenotypes or croak("${sub}: can't read ${phenotypes}: $!") 2 0 2
2271 2 my (@cols, @rows);
2272 2 ▶ while (my $line = <$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 3 1 4
2273 3 $line =~ s/\r?\n\z//;
2274 3 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 3 3
2275 3 ▶ unless (@cols) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@cols) 2 1 3
2276 2 $line =~ s/\A#//;
2277 2 @cols = split /\t/, $line, -1;
2278 2 next;
2279 }
2280 1 my @f = split /\t/, $line, -1;
2281 1 ▶ croak "$sub: line $. of \"phenotypes\" file $phenotypes has " . @f . ' fields, and its header ' . @cols unless @f == @cols;
Branch: 1 branch
BranchTrueFalseTotal
unless @f == @cols 1 0 1
2282 0 my %row;
2283 0 @row{@cols} = @f;
2284 0 push @rows, \%row;
2285 }
2286 1 close $fh;
2287 1 ▶ croak "$sub: \"phenotypes\" file $phenotypes has no rows" unless @rows;
Branch: 1 branch
BranchTrueFalseTotal
unless @rows 1 0 1
2288 0 \@rows;
2289 }
2290  
2291 # A value of a phenotype or covariate that is missing: undef, empty, or NA.
2292 37 ▶sub _missing_value { !defined $_[0] || $_[0] eq '' || $_[0] eq 'NA' ? 1 : 0 }
Subroutine _missing_value: called CC=4 SCAR=13.9
Branch: 1 branch
BranchTrueFalseTotal
!defined($_[0]) || $_[0] eq '' || $_[0] eq 'NA' ? : 3 34 37
Condition83%5/6
not defined $_[0] or $_[0] eq "" or $_[0] eq "NA"
l!l&&r!l&&!r
2134
not defined $_[0] or $_[0] eq ""
l!l&&r!l&&!r
0235
MC/DC66%2/3
not defined $_[0] or $_[0] eq "" or $_[0] eq "NA"
not defined $_[0] $_[0] eq "" $_[0] eq "NA"
Truth table75%3/4
not(A) or B or C
A= not defined $_[0]B= $_[0] eq ""C= $_[0] eq "NA"
ABCresult
1XX1
01X1
0011
0000
2293  
2294 21 ▶sub gwas {
Subroutine gwas: called CC=66 SCAR=67.3
Pod documented
2295 21 my $sub = 'gwas';
2296 21 my $args = _args(\@_, $sub, [qw(vcf phenotypes phenotype)], [qw(covariates memory model threads)]);
2297 20 my %r;
2298 20 $r{phenotype} = $args->{phenotype};
2299 croak "$sub: \"phenotype\" must be the name of a column of \"phenotypes\", not " . _what($r{phenotype})
2300 20 ▶ if ref $r{phenotype} || $r{phenotype} eq '';
Branch: 1 branch
BranchTrueFalseTotal
if ref $r{"phenotype"} or $r{"phenotype"} eq "" 1 19 20
Condition66%2/3
ref $r{"phenotype"} or $r{"phenotype"} eq ""
l!l&&r!l&&!r
1019
MC/DC50%1/2
ref $r{"phenotype"} or $r{"phenotype"} eq ""
ref $r{"phenotype"} $r{"phenotype"} eq ""
Truth table66%2/3
A or B
A= ref $r{"phenotype"}B= $r{"phenotype"} eq ""
ABresult
1X1
011
000
2301 19 ▶ $r{covariates} = $args->{covariates} // []; # the columns of "phenotypes" the test adjusts for; [] = none
Condition100%2/2
$args->{"covariates"} // []
l!l
613
MC/DC100%1/1
$args->{"covariates"} // []
$args->{"covariates"}
Truth table100%2/2
A
A= $args->{"covariates"}
Aresult
11
00
2302 croak "$sub: \"covariates\" must be an array ref of names of columns of \"phenotypes\", not " . _what($r{covariates})
2303 19 ▶ unless ref $r{covariates} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $r{"covariates"} eq "ARRAY" 1 18 19
2304 18 my %seen = ($r{phenotype} => 'phenotype');
2305 18 foreach my $c (@{ $r{covariates} }) {
2306 6 ▶ croak "$sub: \"covariates\" must name columns of \"phenotypes\", and one is " . _what($c) if !defined $c || ref $c || $c eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $c or ref $c or $c eq "" 1 5 6
Condition66%4/6
not defined $c or ref $c or $c eq ""
l!l&&r!l&&!r
105
not defined $c or ref $c
l!l&&r!l&&!r
105
MC/DC33%1/3
not defined $c or ref $c or $c eq ""
not defined $c ref $c $c eq ""
Truth table50%2/4
not(A) or B or C
A= not defined $cB= ref $cC= $c eq ""
ABCresult
1XX1
01X1
0011
0000
2307 5 ▶ croak "$sub: \"covariates\" names \"$c\", which is already " . ($seen{$c} eq 'phenotype' ? 'the phenotype' : 'a covariate') if $seen{$c};
Branch: 2 branches
BranchTrueFalseTotal
if $seen{$c} 2 3 5
$seen{$c} eq 'phenotype' ? : 1 1 2
2308 3 $seen{$c} = 'covariate';
2309 }
2310 15 $r{model} = $args->{model}; # undef = decided by the phenotype's values; 'linear' = linear regression; 'logistic' = logistic (Firth's where it fails to converge)
2311 croak "$sub: \"model\" must be \"linear\" or \"logistic\", not " . _what($r{model})
2312 15 ▶ if defined $r{model} && (ref $r{model} || ($r{model} ne 'linear' && $r{model} ne 'logistic'));
Branch: 1 branch
BranchTrueFalseTotal
if defined $r{"model"} and ref $r{"model"} || $r{"model"} ne "linear" && $r{"model"} ne "logistic" 1 14 15
Condition77%7/9
defined $r{"model"} and ref $r{"model"} || $r{"model"} ne "linear" && $r{"model"} ne "logistic"
!ll&&!rl&&r
1311
ref $r{"model"} or $r{"model"} ne "linear" and $r{"model"} ne "logistic"
l!l&&r!l&&!r
011
$r{"model"} ne "linear" and $r{"model"} ne "logistic"
!ll&&!rl&&r
011
MC/DC50%2/4
defined $r{"model"} and ref $r{"model"} || $r{"model"} ne "linear" && $r{"model"} ne "logistic"
defined $r{"model"} ref $r{"model"} $r{"model"} ne "linear" $r{"model"} ne "logistic"
Truth table60%3/5
A and B or C and D
A= defined $r{"model"}B= ref $r{"model"}C= $r{"model"} ne "linear"D= $r{"model"} ne "logistic"
ABCDresult
0XXX0
100X0
10100
11XX1
10111
2313 14 _plink2_resources($sub, $args);
2314 13 _plink2_input($sub, $args->{vcf});
2315 13 my $rows = _phenotype_rows($sub, $args->{phenotypes});
2316 10 my ($id_col) = grep { exists $rows->[0]{$_} } 'IID', '#IID';
2317 10 ▶ croak "$sub: \"phenotypes\" has no \"IID\" column, which names each row's sample" unless defined $id_col;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id_col 1 9 10
2318 9 my @cols = ($r{phenotype}, @{ $r{covariates} });
2319 9 my @absent = grep { !exists $rows->[0]{$_} } @cols;
2320 9 ▶ croak "$sub: \"phenotypes\" has no " . join(', ', map { "\"$_\"" } @absent) . ' column' . (@absent > 1 ? 's' : '') if @absent;
Branch: 2 branches
BranchTrueFalseTotal
if @absent 1 8 9
@absent > 1 ? : 1 0 1
2321 8 my %value; # column => sample => its value, missing ones left out
2322 8 foreach my $row (@{ $rows }) {
2323 19 my $id = $row->{$id_col};
2324 19 ▶ croak "$sub: \"phenotypes\" has a row whose IID is " . _what($id) if ref $id || _missing_value($id);
Branch: 1 branch
BranchTrueFalseTotal
if ref $id or _missing_value($id) 1 18 19
Condition66%2/3
ref $id or _missing_value($id)
l!l&&r!l&&!r
0118
MC/DC50%1/2
ref $id or _missing_value($id)
ref $id _missing_value($id)
Truth table66%2/3
A or B
A= ref $idB= _missing_value($id)
ABresult
1X1
011
000
2325 18 ▶ croak "$sub: \"phenotypes\" has two rows for \"$id\"" if exists $value{''}{$id};
Branch: 1 branch
BranchTrueFalseTotal
if exists $value{""}{$id} 1 17 18
2326 17 $value{''}{$id} = 1; # '' is no column's name: it holds the samples seen
2327 17 foreach my $c (@cols) {
2328 19 my $v = $row->{$c};
2329 19 ▶ croak "$sub: column \"$c\" of \"phenotypes\" has " . _what($v) . " for \"$id\"" if ref $v;
Branch: 1 branch
BranchTrueFalseTotal
if ref $v 1 18 19
2330 18 ▶ $value{$c}{$id} = $v unless _missing_value($v);
Branch: 1 branch
BranchTrueFalseTotal
unless _missing_value($v) 16 2 18
2331 }
2332 }
2333 5 my %numeric; # column => 1 when every value of it is a number, else 0, when it is a categorical covariate
2334 5 foreach my $c (@cols) {
2335 6 my ($word) = grep { $value{$c}{$_} !~ $Number } sort keys %{ $value{$c} };
2336 6 ▶ $numeric{$c} = defined $word ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $word ? : 2 4 6
2337 6 ▶ croak "$sub: phenotype \"$c\" has \"$value{$c}{$word}\" for \"$word\", which isn't a number" if !$numeric{$c} && $c eq $r{phenotype};
Branch: 1 branch
BranchTrueFalseTotal
if not $numeric{$c} and $c eq $r{"phenotype"} 1 5 6
Condition100%3/3
not $numeric{$c} and $c eq $r{"phenotype"}
!ll&&!rl&&r
411
MC/DC100%2/2
not $numeric{$c} and $c eq $r{"phenotype"}
not $numeric{$c} $c eq $r{"phenotype"}
Truth table100%3/3
not(A) and B
A= not $numeric{$c}B= $c eq $r{"phenotype"}
ABresult
0X0
100
111
2338 croak "$sub: column \"$c\" of \"phenotypes\" has \"$value{$c}{$word}\" for \"$word\", and a covariate's values have no whitespace"
2339 5 ▶ if !$numeric{$c} && $value{$c}{$word} =~ /\s/;
Branch: 1 branch
BranchTrueFalseTotal
if not $numeric{$c} and $value{$c}{$word} =~ /\s/ 1 4 5
Condition66%2/3
not $numeric{$c} and $value{$c}{$word} =~ /\s/
!ll&&!rl&&r
401
MC/DC50%1/2
not $numeric{$c} and $value{$c}{$word} =~ /\s/
not $numeric{$c} $value{$c}{$word} =~ /\s/
Truth table66%2/3
not(A) and B
A= not $numeric{$c}B= $value{$c}{$word} =~ /\s/
ABresult
0X0
100
111
2340 }
2341 3 my %level = map { (0 + $_) => 1 } values %{ $value{ $r{phenotype} } };
2342 3 my @levels = sort { $a <=> $b } keys %level;
2343 3 ▶ croak "$sub: phenotype \"$r{phenotype}\" has " . (@levels ? "only the value $levels[0]" : 'no values') . ', and a test needs two or more' if @levels < 2;
Branch: 2 branches
BranchTrueFalseTotal
if @levels < 2 2 1 3
@levels ? : 1 1 2
2344 1 ▶ my $case_control = @levels == 2 && ($levels[0] == 1 && $levels[1] == 2 || $levels[0] == 0 && $levels[1] == 1) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
@levels == 2 && ($levels[0] == 1 && $levels[1] == 2 || $levels[0] == 0 && $levels[1] == 1) ? : 0 1 1
Condition8%1/12
@levels == 2 and $levels[0] == 1 && $levels[1] == 2 || $levels[0] == 0 && $levels[1] == 1
!ll&&!rl&&r
100
$levels[0] == 1 and $levels[1] == 2 or $levels[0] == 0 and $levels[1] == 1
l!l&&r!l&&!r
000
$levels[0] == 1 and $levels[1] == 2
!ll&&!rl&&r
000
$levels[0] == 0 and $levels[1] == 1
!ll&&!rl&&r
000
MC/DC0%0/5
@levels == 2 and $levels[0] == 1 && $levels[1] == 2 || $levels[0] == 0 && $levels[1] == 1
@levels == 2 $levels[0] == 1 $levels[1] == 2 $levels[0] == 0 $levels[1] == 1
Truth table12%1/8
A and B and C or D and E
A= @levels == 2B= $levels[0] == 1C= $levels[1] == 2D= $levels[0] == 0E= $levels[1] == 1
ABCDEresult
0XXXX0
10X0X0
10X100
1100X0
110100
111XX1
10X111
110111
2345 1 ▶ $r{model} //= $case_control ? 'logistic' : 'linear';
Branch: 1 branch
BranchTrueFalseTotal
$case_control ? : 0 0 0
Condition50%1/2
$r{"model"} //= $case_control ? "logistic" : "linear"
l!l
10
MC/DC0%0/1
$r{"model"} //= $case_control ? "logistic" : "linear"
$r{"model"}
Truth table50%1/2
A
A= $r{"model"}
Aresult
11
00
2346 croak "$sub: \"model\" is logistic, and phenotype \"$r{phenotype}\" has the values " . join(', ', @levels[0 .. ($#levels < 3 ? $#levels : 3)])
2347 1 ▶ . (@levels > 4 ? ', ...' : '') . ', where a case-control phenotype has two: 1 and 2, or 0 and 1' if $r{model} eq 'logistic' && !$case_control;
Branch: 3 branches
BranchTrueFalseTotal
if $r{"model"} eq "logistic" and not $case_control 1 0 1
$#levels < 3 ? : 1 0 1
@levels > 4 ? : 0 1 1
Condition33%1/3
$r{"model"} eq "logistic" and not $case_control
!ll&&!rl&&r
001
MC/DC0%0/2
$r{"model"} eq "logistic" and not $case_control
$r{"model"} eq "logistic" not $case_control
Truth table33%1/3
A and not(B)
A= $r{"model"} eq "logistic"B= not $case_control
ABresult
0X0
100
111
2348 0 my ($dir, $plink2, $files, $variants, $samples) = _popgen_setup($sub, $args, 'phenotypes', 1);
2349 0 my $with = grep { exists $value{ $r{phenotype} }{$_} } @{ $samples };
2350 0 ▶ croak "$sub: none of the " . @{ $samples } . " samples of \"vcf\" has a value of \"$r{phenotype}\" in \"phenotypes\"; check that its IIDs are the VCF's sample names"
Branch: 1 branch
BranchTrueFalseTotal
unless $with 0 0 0
2351 unless $with;
2352 # PLINK 2 takes a column whose values are all 0, 1 and 2 for case-control,
2353 # 0 being missing, whatever is meant, so such a quantitative phenotype or
2354 # covariate is moved up by 3, which changes no test of a variant: a linear
2355 # regression's slopes, and their standard errors, do not depend on where its
2356 # phenotype's or covariates' zeroes are.
2357 my %shift = map {
2358 0 my $c = $_;
2359 0 ▶ ($c => $numeric{$c} && !($c eq $r{phenotype} && $r{model} eq 'logistic') && !(grep { $_ != 0 && $_ != 1 && $_ != 2 } values %{ $value{$c} }) ? 3 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$numeric{$c} && !($c eq $r{'phenotype'} && $r{'model'} eq 'logistic') && !grep({$_ != 0 and $_ != 1 and $_ != 2;} values %{$value{$c};}) ? : 0 0 0
Condition0%0/15
$numeric{$c} and not $c eq $r{"phenotype"} && $r{"model"} eq "logistic" and not grep({$_ != 0 and $_ != 1 and $_ != 2;} values %{$value{$c};})
!ll&&!rl&&r
000
$numeric{$c} and not $c eq $r{"phenotype"} && $r{"model"} eq "logistic"
!ll&&!rl&&r
000
$c eq $r{'phenotype'} && $r{'model'} eq 'logistic'
!ll&&!rl&&r
000
$_ != 0 && $_ != 1 && $_ != 2
!ll&&!rl&&r
000
$_ != 0 and $_ != 1
!ll&&!rl&&r
000
MC/DC0%0/4
$numeric{$c} and not $c eq $r{"phenotype"} && $r{"model"} eq "logistic" and not grep({$_ != 0 and $_ != 1 and $_ != 2;} values %{$value{$c};})
$numeric{$c} $c eq $r{'phenotype'} $r{'model'} eq 'logistic' not grep({$_ != 0 and $_ != 1 and $_ != 2;} values %{$value{$c};})
MC/DC0%0/3
$_ != 0 && $_ != 1 && $_ != 2
$_ != 0 $_ != 1 $_ != 2
Truth table0%0/6
A and not(B && C) and not(D)
A= $numeric{$c}B= $c eq $r{'phenotype'}C= $r{'model'} eq 'logistic'D= not grep({$_ != 0 and $_ != 1 and $_ != 2;} values %{$value{$c};})
ABCDresult
0XXX0
111X0
10X00
11000
10X11
11011
Truth table0%0/4
A and B && C
A= $_ != 0B= $_ != 1C= $_ != 2
ABCresult
0XX0
10X0
1100
1111
2360 } @cols;
2361 # A categorical covariate's values are written as codes, C1, C2, ..., in the
2362 # order of the values, since PLINK 2 refuses one that begins with a number.
2363 my %category = map {
2364 0 my $c = $_;
2365 0 my @v = sort keys %{ { map { $_ => 1 } values %{ $value{$c} } } };
2366 0 ($c => { map { $v[$_] => 'C' . ($_ + 1) } 0 .. $#v });
2367 0 } grep { !$numeric{$_} } @{ $r{covariates} };
2368 0 my $pheno = File::Spec->catfile($dir, 'phenotypes.tsv');
2369 0 ▶ open my $fh, '>', $pheno or croak "$sub: can't write $pheno: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $pheno or croak("${sub}: can't write ${pheno}: $!") 0 0 0
2370 # The columns are named Y and X1, X2, ..., since a column's own name could
2371 # hold a space, or be one PLINK 2 reserves.
2372 0 my @names = ('Y', map { "X$_" } 1 .. @{ $r{covariates} });
2373 0 print {$fh} join("\t", '#IID', @names), "\n";
2374 0 foreach my $s (@{ $samples }) {
2375 0 print {$fh} join("\t", $s, map {
2376 0 my $c = $_;
2377 0 my $v = $value{$c}{$s};
2378 # NONE is PLINK 2's missing category, which it refuses NA for
2379 !defined $v ? ($numeric{$c} ? 'NA' : 'NONE')
2380 : $category{$c} ? $category{$c}{$v}
2381 : $c eq $r{phenotype} && $r{model} eq 'logistic' ? ($v == $levels[0] ? 1 : 2)
2382 0 ▶ : $shift{$c} ? $v + $shift{$c}
Branch: 6 branches
BranchTrueFalseTotal
!defined($v) ? : 0 0 0
$numeric{$c} ? : 0 0 0
$category{$c} ? : 0 0 0
$c eq $r{'phenotype'} && $r{'model'} eq 'logistic' ? : 0 0 0
$v == $levels[0] ? : 0 0 0
$shift{$c} ? : 0 0 0
Condition0%0/3
$c eq $r{"phenotype"} and $r{"model"} eq "logistic"
!ll&&!rl&&r
000
MC/DC0%0/2
$c eq $r{"phenotype"} and $r{"model"} eq "logistic"
$c eq $r{"phenotype"} $r{"model"} eq "logistic"
Truth table0%0/3
A and B
A= $c eq $r{"phenotype"}B= $r{"model"} eq "logistic"
ABresult
0X0
100
111
2383 : $v;
2384 } @cols), "\n";
2385 }
2386 0 ▶ close $fh or croak "$sub: can't write $pheno: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't write ${pheno}: $!") 0 0 0
2387 0 my @covar = map { $names[$_] } 1 .. $#names;
2388 0 my $out = File::Spec->catfile($dir, 'gwas');
2389 # omit-ref makes A1, the allele whose copies are counted, the ALT, where
2390 # PLINK 2 would otherwise count the minor allele's.
2391 0 ▶ _plink2($sub, $plink2, $dir, @{ $files }, '--pheno', $pheno, '--pheno-name', 'Y', '--no-input-missing-phenotype',
Branch: 2 branches
BranchTrueFalseTotal
@covar ? : 0 0 0
grep({$numeric{$_};} @{$r{'covariates'};}) ? : 0 0 0
2392 (@covar ? ('--covar', $pheno, '--covar-name', join(',', @covar)) : ()),
2393 # so that a covariate of large values, such as a year, does not make the
2394 # regression's matrix too ill-conditioned for PLINK 2 to solve
2395 0 ▶ ((grep { $numeric{$_} } @{ $r{covariates} }) ? '--covar-variance-standardize' : ()),
Branch: 1 branch
BranchTrueFalseTotal
@covar ? : 0 0 0
2396 '--glm', 'omit-ref', 'hide-covar', (@covar ? () : 'allow-no-covars'), 'cols=a1freq,firth,test,nobs,beta,se,tz,p,err', '--out', $out);
2397 0 ▶ my ($result) = grep { -f } map { "$out.Y.glm.$_" } $r{model} eq 'linear' ? 'linear' : qw(logistic.hybrid logistic logistic.firth);
Branch: 1 branch
BranchTrueFalseTotal
$r{'model'} eq 'linear' ? : 0 0 0
2398 0 ▶ croak "$sub: PLINK 2 wrote no results of its regression to $out.Y.glm.*" unless defined $result;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $result 0 0 0
2399 0 my @out;
2400 0 ▶ _plink2_rows($sub, $result, sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
2401 0 my ($row) = @_;
2402 0 my $v = _popgen_variant($variants, $row->{ID});
2403 0 ▶ croak "$sub: PLINK 2 counted the copies of $row->{A1} at $v->{chrom}:$v->{pos}, which isn't its ALT, $v->{alt}" unless uc $row->{A1} eq uc $v->{alt};
Branch: 1 branch
BranchTrueFalseTotal
unless uc $row->{"A1"} eq uc $v->{"alt"} 0 0 0
2404 0 $v->{alt_freq} = _number($row->{A1_FREQ});
2405 0 $v->{n} = _number($row->{OBS_CT});
2406 0 ▶ @{ $v }{qw(beta se stat p)} = map { _number($_) } @{ $row }{ 'BETA', 'SE', $r{model} eq 'linear' ? 'T_STAT' : 'Z_STAT', 'P' };
Branch: 1 branch
BranchTrueFalseTotal
$r{'model'} eq 'linear' ? : 0 0 0
2407 0 ▶ $v->{firth} = ($row->{'FIRTH?'} // 'N') eq 'Y' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
($row->{'FIRTH?'} // 'N') eq 'Y' ? : 0 0 0
Condition0%0/2
$row->{"FIRTH?"} // "N"
l!l
00
MC/DC0%0/1
$row->{"FIRTH?"} // "N"
$row->{"FIRTH?"}
Truth table0%0/2
A
A= $row->{"FIRTH?"}
Aresult
11
00
2408 0 ▶ $v->{error} = defined $row->{ERRCODE} && $row->{ERRCODE} ne '.' ? $row->{ERRCODE} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $row->{'ERRCODE'} && $row->{'ERRCODE'} ne '.' ? : 0 0 0
Condition0%0/3
defined $row->{"ERRCODE"} and $row->{"ERRCODE"} ne "."
!ll&&!rl&&r
000
MC/DC0%0/2
defined $row->{"ERRCODE"} and $row->{"ERRCODE"} ne "."
defined $row->{"ERRCODE"} $row->{"ERRCODE"} ne "."
Truth table0%0/3
A and B
A= defined $row->{"ERRCODE"}B= $row->{"ERRCODE"} ne "."
ABresult
0X0
100
111
2409 0 push @out, $v;
2410 0 });
2411 0 _popgen_cleanup($dir, $variants);
2412 0 { model => $r{model}, samples => $with, variants => \@out };
2413 }
2414  
2415 # ---- admixture proportions, in Bioinf.xs (since 2026-11-17)
2416  
2417 26 ▶sub admixture {
Subroutine admixture: called CC=36 SCAR=36.4
Pod documented
2418 26 my $sub = 'admixture';
2419 26 my $args = _args(\@_, $sub, [qw(vcf k)], [qw(max_iterations min_depth seed starts tolerance)]);
2420 23 my %r;
2421 23 $r{k} = $args->{k}; # the ancestral populations
2422 23 ▶ croak "$sub: \"k\" must be a whole number, 2 or more, not " . _what($r{k}) unless !ref $r{k} && $r{k} =~ /\A[1-9][0-9]*\z/ && $r{k} >= 2;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"k"} and $r{"k"} =~ /\A[1-9][0-9]*\z/ and $r{"k"} >= 2 2 21 23
Condition83%5/6
not ref $r{"k"} and $r{"k"} =~ /\A[1-9][0-9]*\z/ and $r{"k"} >= 2
!ll&&!rl&&r
1121
not ref $r{"k"} and $r{"k"} =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
0122
MC/DC66%2/3
not ref $r{"k"} and $r{"k"} =~ /\A[1-9][0-9]*\z/ and $r{"k"} >= 2
not ref $r{"k"} $r{"k"} =~ /\A[1-9][0-9]*\z/ $r{"k"} >= 2
Truth table75%3/4
not(A) and B and C
A= not ref $r{"k"}B= $r{"k"} =~ /\A[1-9][0-9]*\z/C= $r{"k"} >= 2
ABCresult
0XX0
10X0
1100
1111
2423 # On t/data/popgen.vcf at K 3, ADMIXTURE 1.3.0 found the lesser of two
2424 # maxima from 2 of the 6 seeds tried (t/admixture.t), so a single start
2425 # finds the greater with a chance of about 2 in 3; ten fail together about
2426 # once in 60,000 such fits, if the starts' chances are alike.
2427 21 ▶ $r{starts} = $args->{starts} // 10; # the random starts fitted, of which the one of the highest likelihood is kept
Condition100%2/2
$args->{"starts"} // 10
l!l
1110
MC/DC100%1/1
$args->{"starts"} // 10
$args->{"starts"}
Truth table100%2/2
A
A= $args->{"starts"}
Aresult
11
00
2428 21 ▶ croak "$sub: \"starts\" must be a whole number, 1 or more, not " . _what($r{starts}) unless !ref $r{starts} && $r{starts} =~ /\A[1-9][0-9]*\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"starts"} and $r{"starts"} =~ /\A[1-9][0-9]*\z/ 1 20 21
Condition66%2/3
not ref $r{"starts"} and $r{"starts"} =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
0120
MC/DC50%1/2
not ref $r{"starts"} and $r{"starts"} =~ /\A[1-9][0-9]*\z/
not ref $r{"starts"} $r{"starts"} =~ /\A[1-9][0-9]*\z/
Truth table66%2/3
not(A) and B
A= not ref $r{"starts"}B= $r{"starts"} =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
2429 20 ▶ $r{seed} = $args->{seed} // 1; # start s (counting from 0) is drawn from seed + s
Condition100%2/2
$args->{"seed"} // 1
l!l
416
MC/DC100%1/1
$args->{"seed"} // 1
$args->{"seed"}
Truth table100%2/2
A
A= $args->{"seed"}
Aresult
11
00
2430 croak "$sub: \"seed\" must be a whole number, 0 or more, not " . _what($r{seed})
2431 20 ▶ unless !ref $r{seed} && $r{seed} =~ /\A[0-9]+\z/ && $r{seed} <= ~0 - $r{starts};
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"seed"} and $r{"seed"} =~ /\A[0-9]+\z/ and $r{"seed"} <= '18446744073709551615' - $r{"starts"} 1 19 20
Condition66%4/6
not ref $r{"seed"} and $r{"seed"} =~ /\A[0-9]+\z/ and $r{"seed"} <= '18446744073709551615' - $r{"starts"}
!ll&&!rl&&r
1019
not ref $r{"seed"} and $r{"seed"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
0119
MC/DC33%1/3
not ref $r{"seed"} and $r{"seed"} =~ /\A[0-9]+\z/ and $r{"seed"} <= '18446744073709551615' - $r{"starts"}
not ref $r{"seed"} $r{"seed"} =~ /\A[0-9]+\z/ $r{"seed"} <= '18446744073709551615' - $r{"starts"}
Truth table50%2/4
not(A) and B and C
A= not ref $r{"seed"}B= $r{"seed"} =~ /\A[0-9]+\z/C= $r{"seed"} <= '18446744073709551615' - $r{"starts"}
ABCresult
0XX0
10X0
1100
1111
2432 # The fit stops when an iteration raises the log-likelihood by less than
2433 # this, as ADMIXTURE 1.3.0's -C does, whose default is 1e-4. That is too
2434 # loose for these EM steps, which creep where the likelihood is flat. On
2435 # t/data/popgen.vcf at K 3 (2026-11-17), against ADMIXTURE's fit at
2436 # -C=1e-12: 1e-4 stopped the best of ten starts 1.1e-3 below its maximum,
2437 # with q 8e-4 from its. The 10 starts of seeds 1 and 3 to 12 that reached
2438 # the greater maximum came, at worst, within 1.4e-4 of its q at 1e-8, 1.9e-5
2439 # at 1e-10 and 1.75e-5 at 1e-12, the last being ADMIXTURE's own
2440 # convergence, for 2,550, 3,030 and 3,172 iterations in all.
2441 19 ▶ $r{tolerance} = $args->{tolerance} // 1e-10;
Condition100%2/2
$args->{"tolerance"} // "1e-10"
l!l
712
MC/DC100%1/1
$args->{"tolerance"} // "1e-10"
$args->{"tolerance"}
Truth table100%2/2
A
A= $args->{"tolerance"}
Aresult
11
00
2442 croak "$sub: \"tolerance\" must be a number above 0, not " . _what($r{tolerance})
2443 19 ▶ unless !ref $r{tolerance} && $r{tolerance} =~ $Number && $r{tolerance} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"tolerance"} and $r{"tolerance"} =~ /$Number/ and $r{"tolerance"} > 0 1 18 19
Condition50%3/6
not ref $r{"tolerance"} and $r{"tolerance"} =~ /$Number/ and $r{"tolerance"} > 0
!ll&&!rl&&r
0118
not ref $r{"tolerance"} and $r{"tolerance"} =~ /$Number/
!ll&&!rl&&r
0019
MC/DC33%1/3
not ref $r{"tolerance"} and $r{"tolerance"} =~ /$Number/ and $r{"tolerance"} > 0
not ref $r{"tolerance"} $r{"tolerance"} =~ /$Number/ $r{"tolerance"} > 0
Truth table50%2/4
not(A) and B and C
A= not ref $r{"tolerance"}B= $r{"tolerance"} =~ /$Number/C= $r{"tolerance"} > 0
ABCresult
0XX0
10X0
1100
1111
2444 18 ▶ $r{max_iterations} = $args->{max_iterations} // 10_000; # SQUAREM cycles, of three EM steps each, after which a start that has not converged stops
Condition100%2/2
$args->{"max_iterations"} // 10000
l!l
513
MC/DC100%1/1
$args->{"max_iterations"} // 10000
$args->{"max_iterations"}
Truth table100%2/2
A
A= $args->{"max_iterations"}
Aresult
11
00
2445 croak "$sub: \"max_iterations\" must be a whole number, 1 or more, not " . _what($r{max_iterations})
2446 18 ▶ unless !ref $r{max_iterations} && $r{max_iterations} =~ /\A[1-9][0-9]*\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"max_iterations"} and $r{"max_iterations"} =~ /\A[1-9][0-9]*\z/ 1 17 18
Condition66%2/3
not ref $r{"max_iterations"} and $r{"max_iterations"} =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
0117
MC/DC50%1/2
not ref $r{"max_iterations"} and $r{"max_iterations"} =~ /\A[1-9][0-9]*\z/
not ref $r{"max_iterations"} $r{"max_iterations"} =~ /\A[1-9][0-9]*\z/
Truth table66%2/3
not(A) and B
A= not ref $r{"max_iterations"}B= $r{"max_iterations"} =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
2447 17 ▶ $r{min_depth} = $args->{min_depth} // 0; # 0 = every genotype counts, whatever its DP; n = a genotype of DP below n is missing
Condition100%2/2
$args->{"min_depth"} // 0
l!l
116
MC/DC100%1/1
$args->{"min_depth"} // 0
$args->{"min_depth"}
Truth table100%2/2
A
A= $args->{"min_depth"}
Aresult
11
00
2448 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
2449 17 ▶ unless !ref $r{min_depth} && $r{min_depth} =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/ 1 16 17
Condition66%2/3
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
0116
MC/DC50%1/2
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
not ref $r{"min_depth"} $r{"min_depth"} =~ /\A[0-9]+\z/
Truth table66%2/3
not(A) and B
A= not ref $r{"min_depth"}B= $r{"min_depth"} =~ /\A[0-9]+\z/
ABresult
0X0
100
111
2450 16 my $vcf = $args->{vcf};
2451 16 my ($next, $close) = _vcf_open($sub, 'vcf', $vcf);
2452 13 ▶ my ($g, $variants, $names, $called) = _located(sub { _admixture_genotypes($next, $vcf, $r{min_depth}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2453 13 $close->();
2454 13 my $n = @{ $names };
2455 13 ▶ croak "$sub: \"vcf\" $vcf has no biallelic variant on the autosomes (1 to 22), which are all that $sub reads" unless @{ $variants };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$variants;} 1 12 13
2456 croak "$sub: \"vcf\" $vcf has $n sample" . ($n == 1 ? '' : 's') . ", and \"k\" is $r{k}; a sample's ancestry is a share of the k populations, which needs more samples than k"
2457 12 ▶ unless $n > $r{k};
Branch: 2 branches
BranchTrueFalseTotal
unless $n > $r{"k"} 1 11 12
$n == 1 ? : 0 1 1
2458 11 my ($best, @ll); # the best start's [q, p, log-likelihood, iterations, converged]; each start's log-likelihood
2459 11 foreach my $s (0 .. $r{starts} - 1) {
2460 21 ▶ my @fit = _located(sub { _admixture_fit($g, $n, $r{k}, $r{seed} + $s, $r{max_iterations}, $r{tolerance}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2461 21 push @ll, $fit[2];
2462 # the first of equal ones, so that the order of the starts decides a tie
2463 21 ▶ $best = \@fit if !$best || $fit[2] > $best->[2];
Branch: 1 branch
BranchTrueFalseTotal
if not $best or $fit[2] > $best->[2] 13 8 21
Condition100%3/3
not $best or $fit[2] > $best->[2]
l!l&&r!l&&!r
1128
MC/DC100%2/2
not $best or $fit[2] > $best->[2]
not $best $fit[2] > $best->[2]
Truth table100%3/3
not(A) or B
A= not $bestB= $fit[2] > $best->[2]
ABresult
1X1
011
000
2464 }
2465 11 my ($q, $p, $ll, $iterations, $converged) = @{ $best };
2466 11 ▶ carp "$sub: the best of the $r{starts} start" . ($r{starts} == 1 ? '' : 's') . " stopped after $iterations iterations without converging"
Branch: 2 branches
BranchTrueFalseTotal
unless $converged 4 7 11
$r{'starts'} == 1 ? : 3 1 4
2467 . ' (its log-likelihood still rising by ' . _two_digit_exponent("$r{tolerance}") . ' or more); give a larger "max_iterations"' unless $converged;
2468 11 my @none = grep { !$called->[$_] } 0 .. $n - 1;
2469 carp "$sub: " . scalar(@none) . ' sample' . (@none == 1 ? ' has' : 's have') . ' no called genotype, and so an even share of each population: '
2470 11 ▶ . join(', ', map { "\"$names->[$_]\"" } @none[0 .. ($#none < 4 ? $#none : 4)]) . (@none > 5 ? ', ...' : '') if @none;
Branch: 4 branches
BranchTrueFalseTotal
if @none 1 10 11
@none == 1 ? : 1 0 1
$#none < 4 ? : 1 0 1
@none > 5 ? : 0 1 1
2471 # The populations' order is the fit's own, which differs from start to
2472 # start, so they are put in an order that does not: by their share of the
2473 # samples, the largest first.
2474 11 my @share = (0) x $r{k};
2475 11 foreach my $row (@{ $q }) {
2476 603 $share[$_] += $row->[$_] foreach 0 .. $r{k} - 1;
2477 }
2478 11 ▶ my @order = sort { $share[$b] <=> $share[$a] || $a <=> $b } 0 .. $r{k} - 1;
Condition33%1/3
$share[$b] <=> $share[$a] || $a <=> $b
l!l&&r!l&&!r
3000
MC/DC0%0/2
$share[$b] <=> $share[$a] || $a <=> $b
$share[$b] <=> $share[$a] $a <=> $b
Truth table33%1/3
A || B
A= $share[$b] <=> $share[$a]B= $a <=> $b
ABresult
1X1
011
000
2479 11 my %samples = map { $names->[$_] => [ @{ $q->[$_] }[@order] ] } 0 .. $n - 1;
2480 my @variants = map {
2481 2682 my %v;
2482 2682 @v{qw(chrom pos id ref alt)} = split /\t/, $variants->[$_];
2483 2682 $v{pos} += 0;
2484 2682 $v{freq} = [ @{ $p->[$_] }[@order] ];
2485 2682 \%v;
2486 11 } 0 .. $#{ $variants };
2487 11 { k => 0 + $r{k}, loglik => $ll, iterations => $iterations, converged => $converged, starts => \@ll,
2488 samples => \%samples, variants => \@variants };
2489 }
2490  
2491 # ---- VCF genotypes: sex and parentage
2492  
2493 # The bytes sex_check and parent read at a time, from a file or through
2494 # IO::Uncompress, for Bioinf.xs to count. On 2026-10-18 sex_check read
2495 # a whole genome, genome.vcf.gz (155 MB, 3.5 million records), in 4.84 s with
2496 # blocks of 16 KiB, 64 KiB or 256 KiB, and 4.90 s and 4.86 s with 1 MiB and 4
2497 # MiB (best of three, peak RSS 47 MB each), so 64 KiB, as for FASTA. The time
2498 # is gzip's: the same file uncompressed (928 MB) took 0.26 s and 11 MB, and
2499 # zcat alone 3.7 s; as .vcf.bz2 it took 19.4 s, and bzip2 -dc alone 18.5 s.
2500 # IO::Uncompress::Gunzip's readline, which is perl, took 14.3 s just to read
2501 # the lines, and the read loop alone in 1 MiB blocks 5.7 s.
2502 40 my $Vcf_block = 1 << 16;
2503  
2504 # Dies unless the VCF $file, given to $sub as its option $key, is a readable
2505 # file with a VCF's name. Returns how it is compressed: 'gz', 'bz2', or '' for
2506 # not at all. Its messages are prefixed with $sub, whose argument the file is.
2507 986 ▶sub _vcf_check {
Subroutine _vcf_check: called CC=8 SCAR=20.8
2508 986 my ($sub, $key, $file) = @_;
2509 986 ▶ croak "$sub: \"$key\" must be a file name, not " . _what($file) if ref $file || !defined $file;
Branch: 1 branch
BranchTrueFalseTotal
if ref $file or not defined $file 8 978 986
Condition100%3/3
ref $file or not defined $file
l!l&&r!l&&!r
71978
MC/DC100%2/2
ref $file or not defined $file
ref $file not defined $file
Truth table100%3/3
A or not(B)
A= ref $fileB= not defined $file
ABresult
1X1
011
000
2510 978 ▶ croak "$sub: \"$key\" file \"$file\" doesn't exist or isn't readable" unless -f $file && -r _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file and -r _ 11 967 978
Condition66%2/3
-f $file and -r _
!ll&&!rl&&r
110967
MC/DC50%1/2
-f $file and -r _
-f $file -r _
Truth table66%2/3
A and B
A= -f $fileB= -r _
ABresult
0X0
100
111
2511 967 ▶ return 'gz' if $file =~ /\.vcf\.b?gz\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /\.vcf\.b?gz\z/i 17 950 967
2512 950 ▶ return 'bz2' if $file =~ /\.vcf\.bz2\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /\.vcf\.bz2\z/i 9 941 950
2513 941 ▶ return '' if $file =~ /\.vcf\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /\.vcf\z/i 933 8 941
2514 8 croak "$sub: \"$key\" file $file must end in .vcf, .vcf.gz, .vcf.bgz or .vcf.bz2";
2515 }
2516  
2517 # The VCF $file, given to $sub as its option $key, opened: returns a sub that
2518 # gives the next block of it and then undef, and a sub that closes it. Its
2519 # messages are prefixed with $sub, whose argument the file is.
2520 681 ▶sub _vcf_open {
Subroutine _vcf_open: called CC=8 SCAR=21.0
2521 681 my ($sub, $key, $file) = @_;
2522 681 my $packed = _vcf_check($sub, $key, $file);
2523 670 my ($fh, $error); # $error: what says why a read failed
2524 # Transparent => 0, or IO::Uncompress would pass a file that isn't compressed
2525 # through as it is, and the error would be that it isn't a VCF. For a file too
2526 # short to hold a header, new() gives undef and leaves the error empty in
2527 # IO::Uncompress::Gunzip 2.223 (perl 5.44.0), though 2.020 (perl 5.10.1) says
2528 # "Header Error: Minimum header size is 10 bytes".
2529 670 ▶ if ($packed eq 'gz') {
Branch: 2 branches
BranchTrueFalseTotal
if ($packed eq 'gz') { } 13 657 670
elsif ($packed eq 'bz2') { } 7 650 657
2530 13 require IO::Uncompress::Gunzip;
2531 13 ▶ $fh = IO::Uncompress::Gunzip->new($file, MultiStream => 1, Transparent => 0)
Branch: 1 branch
BranchTrueFalseTotal
$fh = "IO::Uncompress::Gunzip"->new($file, "MultiStream", 1, "Transparent", 0) or croak("${sub}: can't read ${file}: " . ($IO::Uncompress::Gunzip::GunzipError || "it isn't gzip-compressed")) 10 3 13
Condition50%1/2
$IO::Uncompress::Gunzip::GunzipError || q[it isn't gzip-compressed]
l!l
03
MC/DC0%0/1
$IO::Uncompress::Gunzip::GunzipError || q[it isn't gzip-compressed]
$IO::Uncompress::Gunzip::GunzipError
Truth table50%1/2
A
A= $IO::Uncompress::Gunzip::GunzipError
Aresult
11
00
2532 or croak "$sub: can't read $file: " . ($IO::Uncompress::Gunzip::GunzipError || 'it isn\'t gzip-compressed');
2533 10 ▶ $error = sub { $IO::Uncompress::Gunzip::GunzipError };
Subroutine __ANON__: called CC=1 SCAR=0.0
2534 } elsif ($packed eq 'bz2') {
2535 7 require IO::Uncompress::Bunzip2;
2536 7 ▶ $fh = IO::Uncompress::Bunzip2->new($file, MultiStream => 1, Transparent => 0)
Branch: 1 branch
BranchTrueFalseTotal
$fh = "IO::Uncompress::Bunzip2"->new($file, "MultiStream", 1, "Transparent", 0) or croak("${sub}: can't read ${file}: " . ($IO::Uncompress::Bunzip2::Bunzip2Error || "it isn't bzip2-compressed")) 6 1 7
Condition50%1/2
$IO::Uncompress::Bunzip2::Bunzip2Error || q[it isn't bzip2-compressed]
l!l
01
MC/DC0%0/1
$IO::Uncompress::Bunzip2::Bunzip2Error || q[it isn't bzip2-compressed]
$IO::Uncompress::Bunzip2::Bunzip2Error
Truth table50%1/2
A
A= $IO::Uncompress::Bunzip2::Bunzip2Error
Aresult
11
00
2537 or croak "$sub: can't read $file: " . ($IO::Uncompress::Bunzip2::Bunzip2Error || 'it isn\'t bzip2-compressed');
2538 6 ▶ $error = sub { $IO::Uncompress::Bunzip2::Bunzip2Error };
Subroutine __ANON__: called CC=1 SCAR=0.0
2539 } else {
2540 650 ▶ open $fh, '<:raw', $file or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<:raw", $file or croak("${sub}: can't read ${file}: $!") 650 0 650
2541 0 ▶ $error = sub { "$!" };
Subroutine __ANON__: not called CC=1 SCAR=1.2
2542 }
2543 1287 ▶ my $next = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
2544 1287 my $block;
2545 1287 my $n = read $fh, $block, $Vcf_block;
2546 # IO::Uncompress's read gives a negative number on an error, perl's undef
2547 1287 ▶ croak "$sub: can't read $file: " . $error->() if !defined $n || $n < 0;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $n or $n < 0 2 1285 1287
Condition66%2/3
not defined $n or $n < 0
l!l&&r!l&&!r
021285
MC/DC50%1/2
not defined $n or $n < 0
not defined $n $n < 0
Truth table66%2/3
not(A) or B
A= not defined $nB= $n < 0
ABresult
1X1
011
000
2548 1285 ▶ $n ? $block : undef;
Branch: 1 branch
BranchTrueFalseTotal
$n ? : 860 425 1285
2549 666 };
2550 666 ▶ my $close = sub { close $fh or croak "$sub: can't read $file: " . $error->() };
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't read ${file}: " . &$error()) 570 0 570
2551 666 ($next, $close);
2552 }
2553  
2554 # The header of the VCF $file, given to $sub as its option $key, read as far as
2555 # its first line that does not start with "##": a hash ref whose "contig" is an
2556 # array ref of the ##contig lines' [ID, length, assembly], in the header's
2557 # order, and whose "reference" is the first ##reference line's value, or
2558 # undef. An ID loses its "chr" prefix, in any case, as Bioinf.xs's
2559 # conc_chrom() drops it from CHROM; a length or an assembly that the line
2560 # lacks is undef. Whatever is wrong with the file beyond its ## lines is left
2561 # for Bioinf.xs to find, as it reads it.
2562 167 ▶sub _vcf_meta {
Subroutine _vcf_meta: called CC=10 SCAR=23.1
2563 167 my ($sub, $key, $file) = @_;
2564 167 my ($next, $close) = _vcf_open($sub, $key, $file);
2565 166 my %meta = (contig => [], reference => undef);
2566 166 my $carry = ''; # the start of a line that the last block ended inside
2567 166 my $done = 0; # 1 = a line not starting with "##" has been read
2568 166 ▶ while (!$done && defined(my $block = $next->())) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $done and defined(my $block = &$next())) 168 166 334
Condition100%3/3
not $done and defined(my $block = &$next())
!ll&&!rl&&r
1651168
MC/DC100%2/2
not $done and defined(my $block = &$next())
not $done defined(my $block = &$next())
Truth table100%3/3
not(A) and B
A= not $doneB= defined(my $block = &$next())
ABresult
0X0
100
111
2569 168 $carry .= $block;
2570 168 my $end = rindex $carry, "\n";
2571 168 ▶ next if $end < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $end < 0 0 168 168
2572 168 foreach my $line (split /\n/, substr($carry, 0, $end)) {
2573 4471 $line =~ s/\r\z//;
2574 4471 ▶ if (substr($line, 0, 2) ne '##') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($line, 0, 2) ne "##") 165 4306 4471
2575 165 $done = 1;
2576 165 last;
2577 }
2578 4306 ▶ if ($line =~ /\A##contig=<(.*)>\z/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($line =~ /\A##contig=<(.*)>\z/) { } 4099 207 4306
elsif ($line =~ /\A##reference=(.+)\z/) { } 2 205 207
2579 4099 my $attr = $1;
2580 4099 my ($id) = $attr =~ /(?:\A|,)ID=([^,]+)/;
2581 4099 ▶ next unless defined $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id 0 4099 4099
2582 4099 $id =~ s/\Achr(?=.)//i;
2583 4099 my ($length) = $attr =~ /(?:\A|,)length=([0-9]+)/;
2584 4099 my ($assembly) = $attr =~ /(?:\A|,)assembly="?([^,"]+)/;
2585 4099 push @{ $meta{contig} }, [$id, $length, $assembly];
2586 } elsif ($line =~ /\A##reference=(.+)\z/) {
2587 2 ▶ $meta{reference} //= $1;
Condition33%1/3
$meta{"reference"} //= $1
l!l&&r!l&&!r
020
MC/DC0%0/2
$meta{"reference"} //= $1
$meta{"reference"} $1
Truth table33%1/3
A //= B
A= $meta{"reference"}B= $1
ABresult
1X1
011
000
2588 }
2589 }
2590 168 $carry = substr($carry, $end + 1);
2591 }
2592 166 $close->();
2593 166 \%meta;
2594 }
2595  
2596 # Dies unless the VCFs $test and $truth, given to $sub, can be on one genome
2597 # build: every contig that both headers give a length for must have the same
2598 # length in each. A chromosome's length differs from one build to the next, and
2599 # so does a site's POS, so that two builds share few sites, and only by chance.
2600 # A header with no lengths cannot be checked, and is not. Contigs are matched by
2601 # name less "chr", as sites are, so hg19 and b37 (chr1 and 1, both 249,250,621
2602 # bases by the headers of an hg19 exome's VCF and of 1000 Genomes' hs37d5 BCF,
2603 # read 2026-10-20) pass.
2604 66 ▶sub _same_build {
Subroutine _same_build: called CC=18 SCAR=29.1
2605 66 my ($sub, $test, $truth) = @_;
2606 66 my %meta = (test => _vcf_meta($sub, 'test', $test), truth => _vcf_meta($sub, 'truth', $truth));
2607 65 my %truth_length; # contig => its length in the truth, for those that have one
2608 65 foreach my $c (@{ $meta{truth}{contig} }) {
2609 4015 ▶ $truth_length{ $c->[0] } //= $c->[1] if defined $c->[1];
Branch: 1 branch
BranchTrueFalseTotal
if defined $c->[1] 4015 0 4015
Condition33%1/3
$truth_length{$c->[0]} //= $c->[1]
l!l&&r!l&&!r
040150
MC/DC0%0/2
$truth_length{$c->[0]} //= $c->[1]
$truth_length{$c->[0]} $c->[1]
Truth table33%1/3
A //= B
A= $truth_length{$c->[0]}B= $c->[1]
ABresult
1X1
011
000
2610 }
2611 65 my ($shared, @differ) = (0); # @differ: [contig, test length, truth length], in the test's order
2612 65 my %seen;
2613 65 foreach my $c (@{ $meta{test}{contig} }) {
2614 14 my ($id, $length) = @{ $c };
2615 14 ▶ next if !defined $length || !defined $truth_length{$id} || $seen{$id}++;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $length && defined $truth_length{$id} or $seen{$id}++ 2 12 14
Condition83%5/6
not defined $length && defined $truth_length{$id} or $seen{$id}++
l!l&&r!l&&!r
2012
defined $length && defined $truth_length{$id}
!ll&&!rl&&r
1112
MC/DC66%2/3
not defined $length && defined $truth_length{$id} or $seen{$id}++
defined $length defined $truth_length{$id} $seen{$id}++
Truth table75%3/4
not(A && B) or C
A= defined $lengthB= defined $truth_length{$id}C= $seen{$id}++
ABCresult
0XX1
10X1
1111
1100
2616 12 $shared++;
2617 12 ▶ push @differ, [$id, $length, $truth_length{$id}] if $length != $truth_length{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $length != $truth_length{$id} 8 4 12
2618 }
2619 65 ▶ return unless @differ;
Branch: 1 branch
BranchTrueFalseTotal
unless @differ 61 4 65
2620 # what each header says its build is: the assembly of a ##contig line that
2621 # differs, or else its ##reference
2622 4 my %says;
2623 4 foreach my $key (qw(test truth)) {
2624 8 ▶ my ($asm) = map { $_->[2] } grep { defined $_->[2] && defined $_->[1] && $_->[0] eq $differ[0][0] } @{ $meta{$key}{contig} };
Condition83%5/6
defined $_->[2] && defined $_->[1] && $_->[0] eq $differ[0][0]
!ll&&!rl&&r
401422
defined $_->[2] and defined $_->[1]
!ll&&!rl&&r
401404
MC/DC66%2/3
defined $_->[2] && defined $_->[1] && $_->[0] eq $differ[0][0]
defined $_->[2] defined $_->[1] $_->[0] eq $differ[0][0]
Truth table75%3/4
A and B && C
A= defined $_->[2]B= defined $_->[1]C= $_->[0] eq $differ[0][0]
ABCresult
0XX0
10X0
1100
1111
2625 8 ▶ $says{$key} = $asm // $meta{$key}{reference};
Condition100%3/3
$asm // $meta{$key}{"reference"}
l!l&&r!l&&!r
224
MC/DC100%2/2
$asm // $meta{$key}{"reference"}
$asm $meta{$key}{"reference"}
Truth table100%3/3
A // B
A= $asmB= $meta{$key}{"reference"}
ABresult
1X1
011
000
2626 }
2627 4 my $listed = 3; # contigs named in the message; the rest are counted
2628 4 ▶ my @named = map { "$_->[0] as $_->[1] bases long in the test and $_->[2] in the truth" } @differ[0 .. ($#differ < $listed - 1 ? $#differ : $listed - 1)];
Branch: 1 branch
BranchTrueFalseTotal
$#differ < $listed - 1 ? : 3 1 4
2629 croak "$sub: \"test\" $test and \"truth\" $truth are on different genome builds: their ##contig lines give " . join(', ', @named)
2630 . (@differ > $listed ? ', and ' . (@differ - $listed) . ' more' : '') . ' (' . scalar(@differ) . " of the $shared contigs that both give a length for differ)"
2631 4 ▶ . (defined $says{test} && defined $says{truth} ? "; the test's header says \"$says{test}\" and the truth's \"$says{truth}\"" : '')
Branch: 2 branches
BranchTrueFalseTotal
@differ > $listed ? : 1 3 4
defined $says{'test'} && defined $says{'truth'} ? : 2 2 4
Condition66%2/3
defined $says{"test"} and defined $says{"truth"}
!ll&&!rl&&r
202
MC/DC50%1/2
defined $says{"test"} and defined $says{"truth"}
defined $says{"test"} defined $says{"truth"}
Truth table66%2/3
A and B
A= defined $says{"test"}B= defined $says{"truth"}
ABresult
0X0
100
111
2632 . ', so a POS in one is not the same place in the other. Lift one over to the other\'s build first';
2633 }
2634  
2635 # sex_check's report on $vcf: what was counted and the rule, then a table of
2636 # the samples in $order, the VCF's, each with its sex and the counts it was told
2637 # from. Columns are as wide as their widest entry, numbers right-aligned.
2638 21 ▶sub _sex_report {
Subroutine _sex_report: called CC=7 SCAR=19.5
2639 21 my ($vcf, $r, $tally, $order) = @_;
2640 21 my @head = ('sample', 'sex', 'het/hom-ALT', 'X het', 'X hom-ALT', 'X haploid', 'X missing', 'Y called');
2641 my @rows = map {
2642 74 my $s = $tally->{$_};
2643 [$_, $s->{sex} // 'unknown', defined $s->{het_ratio} ? sprintf('%.3f', $s->{het_ratio}) : '-',
2644 74 ▶ @{ $s }{qw(x_het x_hom_alt x_haploid x_missing y_called)}]
Branch: 1 branch
BranchTrueFalseTotal
defined $s->{'het_ratio'} ? : 53 21 74
Condition100%2/2
$s->{"sex"} // "unknown"
l!l
5321
MC/DC100%1/1
$s->{"sex"} // "unknown"
$s->{"sex"}
Truth table100%2/2
A
A= $s->{"sex"}
Aresult
11
00
2645 21 } @{ $order };
2646 21 my @w = map { length $head[$_] } 0 .. $#head;
2647 21 foreach my $row (@rows) {
2648 74 foreach my $i (0 .. $#head) {
2649 592 ▶ $w[$i] = length $row->[$i] if length $row->[$i] > $w[$i];
Branch: 1 branch
BranchTrueFalseTotal
if length $row->[$i] > $w[$i] 38 554 592
2650 }
2651 }
2652 21 ▶ my $line = sub { join(' ', map { $_ < 2 ? sprintf('%-*s', $w[$_], $_[$_]) : sprintf('%*s', $w[$_], $_[$_]) } 0 .. $#head) . "\n" };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_ < 2 ? : 190 570 760
2653 21 my @unknown = grep { !defined $tally->{$_}{sex} } @{ $order };
2654 "sex_check: $vcf\n"
2655 . "male when het/hom-ALT, over SNVs on X outside its pseudo-autosomal regions, is below $r->{cutoff}; genotypes of DP below $r->{min_depth} not counted\n"
2656 21 ▶ . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows)
Branch: 1 branch
BranchTrueFalseTotal
@unknown ? : 20 1 21
2657 . (@unknown ? scalar(@unknown) . ' of ' . scalar(@rows) . " unknown: no het or hom-ALT call on X\n" : '');
2658 }
2659  
2660 # peddy 0.4.3's (sex_check() in peddy/peddy.py): male below a het to hom-ALT
2661 # ratio of 0.6 on non-PAR X. sex_check's default "cutoff", and what relatedness
2662 # tells sex by.
2663 40 my $Sex_cutoff = 0.6;
2664  
2665 # The het_ratio and sex of one sample's counts, $s, from Bioinf.xs's
2666 # sex_count(), set in $s: male when the ratio is below $cutoff. peddy divides
2667 # by a hom-ALT count of 0 as if it were 1, and so calls a sample with no calls
2668 # on X male; here it is undef, as is its sex.
2669 297 ▶sub _sex_of {
Subroutine _sex_of: called CC=5 SCAR=16.1
2670 297 my ($s, $cutoff) = @_;
2671 297 my $calls = $s->{x_het} + $s->{x_hom_alt};
2672 297 ▶ $s->{het_ratio} = $calls ? $s->{x_het} / ($s->{x_hom_alt} || 1) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$calls ? : 148 149 297
Condition100%2/2
$s->{'x_hom_alt'} || 1
l!l
1435
MC/DC100%1/1
$s->{'x_hom_alt'} || 1
$s->{'x_hom_alt'}
Truth table100%2/2
A
A= $s->{'x_hom_alt'}
Aresult
11
00
2673 297 ▶ $s->{sex} = !$calls ? undef : $s->{het_ratio} < $cutoff ? 'male' : 'female';
Branch: 2 branches
BranchTrueFalseTotal
!$calls ? : 149 148 297
$s->{'het_ratio'} < $cutoff ? : 95 53 148
2674 }
2675  
2676 72 ▶sub sex_check {
Subroutine sex_check: called CC=25 SCAR=32.2
Pod documented
2677 72 my $sub = 'sex_check';
2678 # sex_check($file) and sex_check($file, %options) take the file first; an
2679 # odd count whose first is an option's name is left for _args to refuse
2680 72 ▶ unshift @_, 'vcf' if @_ % 2 && defined $_[0] && !ref $_[0] && $_[0] !~ /\A(?:vcf|cutoff|min_depth|report)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 and defined $_[0] and not ref $_[0] and not $_[0] =~ /\A(?:vcf|cutoff|min_depth|report)\z/ 6 66 72
Condition100%9/9
@_ % 2 and defined $_[0] and not ref $_[0] and not $_[0] =~ /\A(?:vcf|cutoff|min_depth|report)\z/
!ll&&!rl&&r
6516
@_ % 2 and defined $_[0] and not ref $_[0]
!ll&&!rl&&r
6417
@_ % 2 and defined $_[0]
!ll&&!rl&&r
6318
MC/DC100%4/4
@_ % 2 and defined $_[0] and not ref $_[0] and not $_[0] =~ /\A(?:vcf|cutoff|min_depth|report)\z/
@_ % 2 defined $_[0] not ref $_[0] not $_[0] =~ /\A(?:vcf|cutoff|min_depth|report)\z/
Truth table100%5/5
A and B and not(C) and not(D)
A= @_ % 2B= defined $_[0]C= not ref $_[0]D= not $_[0] =~ /\A(?:vcf|cutoff|min_depth|report)\z/
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2681 72 ▶ croak "$sub: \"$_[0]\" is the file, so the options after it must be name => value pairs, and are an odd number"
Branch: 1 branch
BranchTrueFalseTotal
if @_ and defined $_[0] and not ref $_[0] and $_[0] ne "vcf" and -f $_[0] 1 71 72
Condition100%12/12
@_ and defined $_[0] and not ref $_[0] and $_[0] ne "vcf" and -f $_[0]
!ll&&!rl&&r
7011
@_ and defined $_[0] and not ref $_[0] and $_[0] ne "vcf"
!ll&&!rl&&r
4662
@_ and defined $_[0] and not ref $_[0]
!ll&&!rl&&r
3168
@_ and defined $_[0]
!ll&&!rl&&r
1269
MC/DC100%5/5
@_ and defined $_[0] and not ref $_[0] and $_[0] ne "vcf" and -f $_[0]
@_ defined $_[0] not ref $_[0] $_[0] ne "vcf" -f $_[0]
Truth table100%6/6
A and B and not(C) and D and E
A= @_B= defined $_[0]C= not ref $_[0]D= $_[0] ne "vcf"E= -f $_[0]
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
2682 if @_ && defined $_[0] && !ref $_[0] && $_[0] ne 'vcf' && -f $_[0];
2683 71 my $args = _args(\@_, $sub, ['vcf'], [qw(cutoff min_depth report)]);
2684 65 my %r;
2685 # peddy 0.4.3's defaults (sex_check() in peddy/peddy.py): male below a het
2686 # to hom-ALT ratio of 0.6 on non-PAR X, and genotypes of depth 7 or more
2687 65 ▶ $r{cutoff} = $args->{cutoff} // $Sex_cutoff;
Condition66%2/3
$args->{"cutoff"} // $Sex_cutoff
l!l&&r!l&&!r
6590
MC/DC0%0/2
$args->{"cutoff"} // $Sex_cutoff
$args->{"cutoff"} $Sex_cutoff
Truth table66%2/3
A // B
A= $args->{"cutoff"}B= $Sex_cutoff
ABresult
1X1
011
000
2688 croak "$sub: \"cutoff\" must be a number above 0, not " . _what($r{cutoff})
2689 65 ▶ unless !ref $r{cutoff} && $r{cutoff} =~ $Number && $r{cutoff} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"cutoff"} and $r{"cutoff"} =~ /$Number/ and $r{"cutoff"} > 0 3 62 65
Condition100%6/6
not ref $r{"cutoff"} and $r{"cutoff"} =~ /$Number/ and $r{"cutoff"} > 0
!ll&&!rl&&r
2162
not ref $r{"cutoff"} and $r{"cutoff"} =~ /$Number/
!ll&&!rl&&r
1163
MC/DC100%3/3
not ref $r{"cutoff"} and $r{"cutoff"} =~ /$Number/ and $r{"cutoff"} > 0
not ref $r{"cutoff"} $r{"cutoff"} =~ /$Number/ $r{"cutoff"} > 0
Truth table100%4/4
not(A) and B and C
A= not ref $r{"cutoff"}B= $r{"cutoff"} =~ /$Number/C= $r{"cutoff"} > 0
ABCresult
0XX0
10X0
1100
1111
2690 62 ▶ $r{min_depth} = $args->{min_depth} // 7; # 0 = count every genotype, whatever its DP
Condition100%2/2
$args->{"min_depth"} // 7
l!l
953
MC/DC100%1/1
$args->{"min_depth"} // 7
$args->{"min_depth"}
Truth table100%2/2
A
A= $args->{"min_depth"}
Aresult
11
00
2691 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
2692 62 ▶ unless !ref $r{min_depth} && $r{min_depth} =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/ 2 60 62
Condition66%2/3
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
0260
MC/DC50%1/2
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
not ref $r{"min_depth"} $r{"min_depth"} =~ /\A[0-9]+\z/
Truth table66%2/3
not(A) and B
A= not ref $r{"min_depth"}B= $r{"min_depth"} =~ /\A[0-9]+\z/
ABresult
0X0
100
111
2693 60 ▶ $r{report} = $args->{report} // 1; # 1 = print a table of the samples to STDOUT; 0 = only return them
Condition100%2/2
$args->{"report"} // 1
l!l
1149
MC/DC100%1/1
$args->{"report"} // 1
$args->{"report"}
Truth table100%2/2
A
A= $args->{"report"}
Aresult
11
00
2694 60 ▶ croak "$sub: \"report\" must be 0 or 1, not " . _what($r{report}) unless !ref $r{report} && ($r{report} eq '0' || $r{report} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1 2 58 60
Condition83%5/6
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
!ll&&!rl&&r
0258
$r{"report"} eq 0 or $r{"report"} eq 1
l!l&&r!l&&!r
9492
MC/DC66%2/3
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
not ref $r{"report"} $r{"report"} eq 0 $r{"report"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"report"}B= $r{"report"} eq 0C= $r{"report"} eq 1
ABCresult
0XX0
1000
11X1
1011
2695 58 my $vcf = $args->{vcf};
2696 58 my ($next, $close) = _vcf_open($sub, 'vcf', $vcf);
2697 50 ▶ my ($tally, $x_sites, $order) = _located(sub { _sex_tally($next, $vcf, $r{min_depth}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2698 30 $close->();
2699 30 _sex_of($_, $r{cutoff}) foreach values %{ $tally };
2700 30 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 21 9 30
2701 21 ▶ print STDOUT _sex_report($vcf, \%r, $tally, $order) or croak "$sub: can't print the report: $!";
Branch: 1 branch
BranchTrueFalseTotal
print STDOUT _sex_report($vcf, \%r, $tally, $order) or croak("${sub}: can't print the report: $!") 21 0 21
2702 }
2703 30 ▶ carp "$sub: \"vcf\" $vcf has no SNV on X outside its pseudo-autosomal regions, so no sex can be told" unless $x_sites;
Branch: 1 branch
BranchTrueFalseTotal
unless $x_sites 2 28 30
2704 30 $tally;
2705 }
2706  
2707 # KING's bounds on the kinship coefficient, from its manual
2708 # (www.kingrelatedness.com/manual.shtml, read 2026-10-18): above 0.354 the same
2709 # person or identical twins, and then first-, second- and third-degree
2710 # relatives down to 0.177, 0.0884 and 0.0442, below which a pair is unrelated.
2711 # They are 2^-1.5, 2^-2.5, 2^-3.5 and 2^-4.5, the geometric means of the
2712 # kinships of neighbouring degrees (1/2, 1/4, 1/8, 1/16, 1/32), and the
2713 # rounded values are used, as KING prints them.
2714 40 my @King = ([0.354, 'the same person or identical twins'], [0.177, 'first-degree relatives'],
2715 [0.0884, 'second-degree relatives'], [0.0442, 'third-degree relatives']);
2716  
2717 # The fewest sites parent will decide from. At the IBS0 rate of the unrelated
2718 # pair measured (0.081, in the README), 1,000 sites hold 81 IBS0 sites on
2719 # average, with a binomial standard deviation of 8.6, so that falling below
2720 # the 12 of the default max_ibs0 is 8 standard deviations away. An exome
2721 # gives about 150,000 and a genome 3 million, so only a small panel, or
2722 # files that hardly overlap, comes near it.
2723 40 my $Parent_sites = 1000;
2724  
2725 # Whether two people's own VCFs were probably not sequenced over the same
2726 # regions, which parent and relatedness warn of: of the sites compared, $sites,
2727 # one file has $more that the other lacks and the other $fewer that it lacks,
2728 # $more being the larger. Three things must hold.
2729 #
2730 # $more is over twice $fewer. Two VCFs of one pipeline have about as many each:
2731 # on 2026-10-18 the three pairs of one family's exomes had ratios of 1.13 at
2732 # most, where an exome of another capture kit had 3.0 to 13 against them, and a
2733 # genome against an exome 58, which is why 2.
2734 #
2735 # $more exceeds $fewer by $Region_excess sites, so that it is not chance. Were a
2736 # site in one file alone as likely to be in either, the chance of a ratio over
2737 # 2 with a difference of 50 or more is greatest at 99 against 49, where it is
2738 # 4.8e-5 (the exact binomial tail on both sides, computed 2026-11-10); a
2739 # difference of 30 would allow 1.8e-3.
2740 #
2741 # And by $Region_share of the sites compared, so that it could matter. Each of
2742 # those sites is taken as hom-REF in the file that lacks it, and at worst is an
2743 # opposite homozygote that was never sequenced, which adds that share to the
2744 # IBS0 rate. 0.009 is the smallest margin measured between a parent and
2745 # child's rate and max_ibs0's default: 0.012 less the 0.0030 of the comment in
2746 # parent. Fewer cannot carry such a pair over it.
2747 #
2748 # Up to 2026-11-10 the ratio was the whole test, so that two VCFs of 3,000
2749 # sites that differed by 3 sites against 1 were warned of.
2750 40 my $Region_excess = 50;
2751 40 my $Region_share = 0.009;
2752 78 ▶sub _regions_differ {
Subroutine _regions_differ: called CC=4 SCAR=13.9
2753 78 my ($more, $fewer, $sites) = @_;
2754 78 ▶ $more > 2 * $fewer && $more - $fewer >= $Region_excess && $more - $fewer >= $Region_share * $sites ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$more > 2 * $fewer && $more - $fewer >= $Region_excess && $more - $fewer >= $Region_share * $sites ? : 6 72 78
Condition100%6/6
$more > 2 * $fewer and $more - $fewer >= $Region_excess and $more - $fewer >= $Region_share * $sites
!ll&&!rl&&r
7026
$more > 2 * $fewer and $more - $fewer >= $Region_excess
!ll&&!rl&&r
6648
MC/DC100%3/3
$more > 2 * $fewer and $more - $fewer >= $Region_excess and $more - $fewer >= $Region_share * $sites
$more > 2 * $fewer $more - $fewer >= $Region_excess $more - $fewer >= $Region_share * $sites
Truth table100%4/4
A and B and C
A= $more > 2 * $fewerB= $more - $fewer >= $Region_excessC= $more - $fewer >= $Region_share * $sites
ABCresult
0XX0
10X0
1100
1111
2755 }
2756  
2757 # The KING-robust between-family kinship (Manichaikul et al. 2010,
2758 # Bioinformatics 26:2867) of two samples with $het_a and $het_b het calls at the
2759 # sites compared, $het_het sites where both are het and $ibs0 opposite
2760 # homozygotes, in the form PLINK 2's --make-king-table gives it (t/parent.t's
2761 # header says how the two were found to agree); undef when either has no het
2762 # call.
2763 500 ▶sub _king {
Subroutine _king: called CC=3 SCAR=11.0
2764 500 my ($het_a, $het_b, $het_het, $ibs0) = @_;
2765 500 ▶ my $min_het = $het_a < $het_b ? $het_a : $het_b;
Branch: 1 branch
BranchTrueFalseTotal
$het_a < $het_b ? : 271 229 500
2766 500 ▶ return undef unless $min_het;
Branch: 1 branch
BranchTrueFalseTotal
unless $min_het 4 496 500
2767 496 0.5 - ($het_a + $het_b - 2 * $het_het + 4 * $ibs0) / (4 * $min_het);
2768 }
2769  
2770 # The relationship that a $kinship and an IBS0 rate say, by KING's ranges, with
2771 # an IBS0 rate below $max_ibs0 telling parent and child from full siblings.
2772 453 ▶sub _relationship {
Subroutine _relationship: called CC=6 SCAR=17.9
2773 453 my ($kinship, $ibs0_rate, $max_ibs0) = @_;
2774 453 my $band = (grep { $kinship > $King[$_][0] } 0 .. $#King)[0];
2775 453 ▶ !defined $band ? 'unrelated' : $band == 0 ? 'duplicate'
Branch: 5 branches
BranchTrueFalseTotal
!defined($band) ? : 126 327 453
$band == 0 ? : 19 308 327
$band == 1 ? : 245 63 308
$ibs0_rate < $max_ibs0 ? : 199 46 245
$band == 2 ? : 59 4 63
2776 : $band == 1 ? ($ibs0_rate < $max_ibs0 ? 'parent-child' : 'full siblings')
2777 : $band == 2 ? 'second-degree' : 'third-degree';
2778 }
2779  
2780 # parent's report, given its sample or file names, the resolved options, and
2781 # its result.
2782 26 ▶sub _parent_report {
Subroutine _parent_report: called CC=12 SCAR=24.8
2783 26 my ($child, $parent, $vcf, $r, $s) = @_;
2784 26 my $kin = sprintf '%.4f', $s->{kinship};
2785 26 my $rate = sprintf '%.4f', $s->{ibs0_rate};
2786 26 my $band = (grep { $s->{kinship} > $King[$_][0] } 0 .. $#King)[0];
2787 26 ▶ my $kin_says = !defined $band ? "kinship $kin is below 0.0442, as for unrelated people"
Branch: 2 branches
BranchTrueFalseTotal
!defined($band) ? : 4 22 26
$band == 0 ? : 2 20 22
2788 : $band == 0 ? "kinship $kin is above 0.354, as for $King[0][1]"
2789 : "kinship $kin is from $King[$band][0] to $King[$band - 1][0], as for $King[$band][1]";
2790 26 ▶ my $ibs0_says = "the IBS0 rate, $rate, is " . ($s->{ibs0_rate} < $r->{max_ibs0} ? 'below' : 'not below') . " $r->{max_ibs0}";
Branch: 1 branch
BranchTrueFalseTotal
$s->{'ibs0_rate'} < $r->{'max_ibs0'} ? : 16 10 26
2791 26 ▶ my $verdict = $s->{parent} ? "parent and child (1): $ibs0_says, and $kin_says"
Branch: 1 branch
BranchTrueFalseTotal
$s->{'parent'} ? : 14 12 26
2792 : "not parent and child (0): $kin_says, and $ibs0_says";
2793 26 ▶ $verdict .= ', so full siblings' if $s->{relationship} eq 'full siblings';
Branch: 1 branch
BranchTrueFalseTotal
if $s->{"relationship"} eq "full siblings" 4 22 26
2794 26 my @rows = (["sites compared", $s->{sites}, "autosomal biallelic SNVs where either carries the ALT, DP $r->{min_depth} or more"]);
2795 push @rows, ([' in both VCFs', $s->{in_both}, ''], [" in the child's alone", $s->{child_only}, 'the parent taken as hom-REF'],
2796 26 ▶ [" in the parent's alone", $s->{parent_only}, 'the child taken as hom-REF']) unless defined $vcf;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $vcf 7 19 26
2797 push @rows, (['IBS0', $s->{ibs0}, 'opposite homozygotes'],
2798 [' child hom-ALT', $s->{child_alt_parent_ref}, 'and the parent hom-REF'], [' child hom-REF', $s->{child_ref_parent_alt}, 'and the parent hom-ALT'],
2799 ['IBS1', $s->{ibs1}, 'one allele shared'], ['IBS2', $s->{ibs2}, 'both alleles shared'],
2800 ['het in both', $s->{het_het}, ''], ['het', $s->{child_het}, "the child's, and $s->{parent_het} the parent's"],
2801 26 ['hom-ALT', $s->{child_hom_alt}, "the child's, and $s->{parent_hom_alt} the parent's"],
2802 ['kinship', $kin, 'KING-robust, between-family']);
2803 26 my ($w0, $w1) = (0, 0);
2804 26 foreach my $row (@rows) {
2805 281 ▶ $w0 = length $row->[0] if length $row->[0] > $w0;
Branch: 1 branch
BranchTrueFalseTotal
if length $row->[0] > $w0 59 222 281
2806 281 ▶ $w1 = length $row->[1] if length $row->[1] > $w1;
Branch: 1 branch
BranchTrueFalseTotal
if length $row->[1] > $w1 52 229 281
2807 }
2808 "parent: child " . (defined $vcf ? "$child, parent $parent, in $vcf" : "$child, parent $parent") . "\n"
2809 . "$verdict\n"
2810 26 ▶ . join('', map { my $l = sprintf '%-*s %*s', $w0, $_->[0], $w1, $_->[1]; $l .= " $_->[2]" if length $_->[2]; "$l\n" } @rows);
Branch: 2 branches
BranchTrueFalseTotal
defined $vcf ? : 19 7 26
if length $_->[2] 248 33 281
2811 }
2812  
2813 99 ▶sub parent {
Subroutine parent: called CC=34 SCAR=35.4
Pod documented
2814 99 my $sub = 'parent';
2815 99 my $args = _args(\@_, $sub, [qw(child parent)], [qw(vcf min_depth max_ibs0 report)]);
2816 96 my %r;
2817 # Measured on three exomes of one family on 2026-10-18 (README.md): with
2818 # every genotype counted the two parent-child pairs had IBS0 rates of 0.254
2819 # and 0.215, from off-target calls of DP 1 to 3, and with DP 10 or more
2820 # 0.0030 and 0.0020, against 0.081 for the unrelated pair; DP 7 gave 0.0053
2821 # and 0.0037, half the margin below max_ibs0, for 8% more sites.
2822 96 ▶ $r{min_depth} = $args->{min_depth} // 10; # 0 = count every genotype, whatever its DP
Condition100%2/2
$args->{"min_depth"} // 10
l!l
492
MC/DC100%1/1
$args->{"min_depth"} // 10
$args->{"min_depth"}
Truth table100%2/2
A
A= $args->{"min_depth"}
Aresult
11
00
2823 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
2824 96 ▶ unless !ref $r{min_depth} && $r{min_depth} =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/ 1 95 96
Condition66%2/3
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
0195
MC/DC50%1/2
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
not ref $r{"min_depth"} $r{"min_depth"} =~ /\A[0-9]+\z/
Truth table66%2/3
not(A) and B
A= not ref $r{"min_depth"}B= $r{"min_depth"} =~ /\A[0-9]+\z/
ABresult
0X0
100
111
2825 # peddy 0.4.3's (ped_check() in peddy/peddy.py: predicted_parents is
2826 # ibs0 / n < 0.012), where it sits between the measured parent-child rates
2827 # above and the 0.02 or so expected of full siblings, who share no allele
2828 # by descent at a quarter of sites and so have a quarter of the unrelated
2829 # pair's 0.081
2830 95 ▶ $r{max_ibs0} = $args->{max_ibs0} // 0.012;
Condition100%2/2
$args->{"max_ibs0"} // "0.012"
l!l
491
MC/DC100%1/1
$args->{"max_ibs0"} // "0.012"
$args->{"max_ibs0"}
Truth table100%2/2
A
A= $args->{"max_ibs0"}
Aresult
11
00
2831 croak "$sub: \"max_ibs0\" must be a number above 0, not " . _what($r{max_ibs0})
2832 95 ▶ unless !ref $r{max_ibs0} && $r{max_ibs0} =~ $Number && $r{max_ibs0} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"max_ibs0"} and $r{"max_ibs0"} =~ /$Number/ and $r{"max_ibs0"} > 0 2 93 95
Condition83%5/6
not ref $r{"max_ibs0"} and $r{"max_ibs0"} =~ /$Number/ and $r{"max_ibs0"} > 0
!ll&&!rl&&r
1193
not ref $r{"max_ibs0"} and $r{"max_ibs0"} =~ /$Number/
!ll&&!rl&&r
0194
MC/DC66%2/3
not ref $r{"max_ibs0"} and $r{"max_ibs0"} =~ /$Number/ and $r{"max_ibs0"} > 0
not ref $r{"max_ibs0"} $r{"max_ibs0"} =~ /$Number/ $r{"max_ibs0"} > 0
Truth table75%3/4
not(A) and B and C
A= not ref $r{"max_ibs0"}B= $r{"max_ibs0"} =~ /$Number/C= $r{"max_ibs0"} > 0
ABCresult
0XX0
10X0
1100
1111
2833 93 ▶ $r{report} = $args->{report} // 1; # 1 = print the report to STDOUT; 0 = only return
Condition100%2/2
$args->{"report"} // 1
l!l
4944
MC/DC100%1/1
$args->{"report"} // 1
$args->{"report"}
Truth table100%2/2
A
A= $args->{"report"}
Aresult
11
00
2834 93 ▶ croak "$sub: \"report\" must be 0 or 1, not " . _what($r{report}) unless !ref $r{report} && ($r{report} eq '0' || $r{report} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1 1 92 93
Condition83%5/6
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
!ll&&!rl&&r
0192
$r{"report"} eq 0 or $r{"report"} eq 1
l!l&&r!l&&!r
48441
MC/DC66%2/3
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
not ref $r{"report"} $r{"report"} eq 0 $r{"report"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"report"}B= $r{"report"} eq 0C= $r{"report"} eq 1
ABCresult
0XX0
1000
11X1
1011
2835 92 my ($child, $parent, $vcf) = @{ $args }{qw(child parent vcf)}; # $vcf: undef = child and parent are each a VCF of its own
2836 92 my @t; # sites by the child's ALT count and then the parent's, 0 to 2, flattened; then the informative sites in both files, the child's alone, the parent's alone
2837 92 ▶ if (defined $vcf) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $vcf) { } 61 31 92
2838 61 foreach my $key (qw(child parent)) {
2839 120 ▶ croak "$sub: \"$key\" must be a sample name of \"vcf\", not " . _what($args->{$key}) if ref $args->{$key} || !length $args->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if ref $args->{$key} or not length $args->{$key} 2 118 120
Condition100%3/3
ref $args->{$key} or not length $args->{$key}
l!l&&r!l&&!r
11118
MC/DC100%2/2
ref $args->{$key} or not length $args->{$key}
ref $args->{$key} not length $args->{$key}
Truth table100%3/3
A or not(B)
A= ref $args->{$key}B= not length $args->{$key}
ABresult
1X1
011
000
2840 }
2841 59 ▶ croak "$sub: \"child\" and \"parent\" are both \"$child\"" if $child eq $parent;
Branch: 1 branch
BranchTrueFalseTotal
if $child eq $parent 1 58 59
2842 58 my ($next, $close) = _vcf_open($sub, 'vcf', $vcf);
2843 58 ▶ @t = _located(sub { _parent_one($next, $vcf, $r{min_depth}, $child, $parent) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2844 56 $close->();
2845 } else {
2846 31 ▶ croak "$sub: \"child\" and \"parent\" are both \"$child\"" if !ref $child && !ref $parent && $child eq $parent;
Branch: 1 branch
BranchTrueFalseTotal
if not ref $child || ref $parent and $child eq $parent 1 30 31
Condition50%3/6
not ref $child || ref $parent and $child eq $parent
!ll&&!rl&&r
0301
ref $child || ref $parent
l!l&&r!l&&!r
0031
MC/DC33%1/3
not ref $child || ref $parent and $child eq $parent
ref $child ref $parent $child eq $parent
Truth table50%2/4
not(A || B) and C
A= ref $childB= ref $parentC= $child eq $parent
ABCresult
1XX0
01X0
0000
0011
2847 30 my ($child_next, $child_close) = _vcf_open($sub, 'child', $child);
2848 30 my ($parent_next, $parent_close) = _vcf_open($sub, 'parent', $parent);
2849 27 ▶ @t = _located(sub { _parent_own($child_next, $child, $parent_next, $parent, $r{min_depth}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2850 19 $child_close->();
2851 19 $parent_close->();
2852 }
2853 75 my %s;
2854 75 @s{qw(in_both child_only parent_only)} = @t[9 .. 11];
2855 75 $s{sites} = $s{in_both} + $s{child_only} + $s{parent_only};
2856 75 @s{qw(child_ref_parent_alt child_alt_parent_ref)} = @t[2, 6];
2857 75 $s{ibs0} = $t[2] + $t[6];
2858 75 $s{ibs1} = $t[1] + $t[3] + $t[5] + $t[7];
2859 75 $s{ibs2} = $t[4] + $t[8];
2860 75 $s{het_het} = $t[4];
2861 75 $s{child_het} = $t[3] + $t[4] + $t[5];
2862 75 $s{parent_het} = $t[1] + $t[4] + $t[7];
2863 75 $s{child_hom_alt} = $t[6] + $t[7] + $t[8];
2864 75 $s{parent_hom_alt} = $t[2] + $t[5] + $t[8];
2865 75 ▶ my $what = defined $vcf ? "\"$child\" and \"$parent\" of $vcf" : "$child and $parent";
Branch: 1 branch
BranchTrueFalseTotal
defined $vcf ? : 56 19 75
2866 # Without a hom-REF call, IBS0 cannot be seen, and an unrelated pair would
2867 # look like parent and child. A VCF merged from VCFs that list only their own
2868 # sample's variant sites is like that, as bcftools merge writes it without
2869 # -0: each sample is "./." wherever it had no variant. It is checked before
2870 # the number of sites, which such a VCF often has too few of as well, since
2871 # this says what to do about it.
2872 croak "$sub: neither of $what has a hom-REF call where the other carries the ALT, so no opposite homozygote can be seen;"
2873 . ' a VCF merged from VCFs that list only their own variants is like that, so give each sample\'s own VCF as "child" and "parent"'
2874 75 ▶ if $s{sites} && !($t[1] + $t[2] + $t[3] + $t[6]);
Branch: 1 branch
BranchTrueFalseTotal
if $s{"sites"} and not $t[1] + $t[2] + $t[3] + $t[6] 1 74 75
Condition66%2/3
$s{"sites"} and not $t[1] + $t[2] + $t[3] + $t[6]
!ll&&!rl&&r
0741
MC/DC50%1/2
$s{"sites"} and not $t[1] + $t[2] + $t[3] + $t[6]
$s{"sites"} not $t[1] + $t[2] + $t[3] + $t[6]
Truth table66%2/3
A and not(B)
A= $s{"sites"}B= not $t[1] + $t[2] + $t[3] + $t[6]
ABresult
0X0
100
111
2875 croak "$sub: $what have only $s{sites} autosomal biallelic SNVs of DP $r{min_depth} or more where either carries the ALT,"
2876 . " and $Parent_sites are needed" . (defined $vcf ? '' : '; if the files share few sites, check that they are of the same genome build')
2877 74 ▶ if $s{sites} < $Parent_sites;
Branch: 2 branches
BranchTrueFalseTotal
if $s{"sites"} < $Parent_sites 3 71 74
defined $vcf ? : 2 1 3
2878 71 $s{kinship} = _king(@s{qw(child_het parent_het het_het ibs0)});
2879 71 ▶ croak "$sub: " . ($s{child_het} ? 'the parent' : 'the child') . " of $what has no het call at the sites compared, so no kinship can be taken" unless defined $s{kinship};
Branch: 2 branches
BranchTrueFalseTotal
unless defined $s{"kinship"} 1 70 71
$s{'child_het'} ? : 0 1 1
2880 70 $s{ibs0_rate} = $s{ibs0} / $s{sites};
2881 70 $s{relationship} = _relationship($s{kinship}, $s{ibs0_rate}, $r{max_ibs0});
2882 70 ▶ $s{parent} = $s{relationship} eq 'parent-child' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$s{'relationship'} eq 'parent-child' ? : 36 34 70
2883 70 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 26 44 70
2884 26 ▶ print STDOUT _parent_report($child, $parent, $vcf, \%r, \%s) or croak "$sub: can't print the report: $!";
Branch: 1 branch
BranchTrueFalseTotal
print STDOUT _parent_report($child, $parent, $vcf, \%r, \%s) or croak("${sub}: can't print the report: $!") 26 0 26
2885 }
2886 # _regions_differ's comment says what is tested, and why
2887 70 ▶ my ($more, $fewer) = $s{child_only} > $s{parent_only} ? ('child', 'parent') : ('parent', 'child');
Branch: 1 branch
BranchTrueFalseTotal
$s{'child_only'} > $s{'parent_only'} ? : 7 63 70
2888 70 my ($n_more, $n_fewer) = @s{"${more}_only", "${fewer}_only"};
2889 carp "$sub: the ${more}'s VCF has $n_more sites that the ${fewer}'s lacks, and the ${fewer}'s only $n_fewer that the ${more}'s lacks,"
2890 . ' so the two were probably not sequenced over the same regions (an exome and a genome, or two capture kits);'
2891 . ' a site that one lacks is taken as hom-REF in it, so IBS0 and the kinship are not to be trusted'
2892 70 ▶ if !defined $vcf && _regions_differ($n_more, $n_fewer, $s{sites});
Branch: 1 branch
BranchTrueFalseTotal
if not defined $vcf and _regions_differ($n_more, $n_fewer, $s{"sites"}) 3 67 70
Condition100%3/3
not defined $vcf and _regions_differ($n_more, $n_fewer, $s{"sites"})
!ll&&!rl&&r
52153
MC/DC100%2/2
not defined $vcf and _regions_differ($n_more, $n_fewer, $s{"sites"})
not defined $vcf _regions_differ($n_more, $n_fewer, $s{"sites"})
Truth table100%3/3
not(A) and B
A= not defined $vcfB= _regions_differ($n_more, $n_fewer, $s{"sites"})
ABresult
0X0
100
111
2893 70 ▶ wantarray ? ($s{parent}, \%s) : $s{parent};
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 55 15 70
2894 }
2895  
2896 # The words for a male and a female relative, in relatedness's categories:
2897 # the parent, the child, the sibling.
2898 40 my %Kin_word = (male => [qw(father son brother)], female => [qw(mother daughter sister)]);
2899  
2900 # relatedness's report, given its files, the resolved options, the samples in
2901 # order, each one's sex counts, and $each_pair, which gives each pair in order
2902 # to a sub. Columns are as wide as their widest entry, numbers right-aligned.
2903 # The pairs' rows are made twice, once for the widths and once for the lines,
2904 # rather than held: 1,000 samples have 499,500.
2905 4 ▶sub _relatedness_report {
Subroutine _relatedness_report: called CC=2 SCAR=6.9
2906 4 my ($files, $r, $names, $tally, $each_pair) = @_;
2907 # the lines of the rows that $rows gives to a sub, under @head, with the
2908 # columns in %$right right-aligned
2909 8 ▶ my $table = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2910 8 my ($right, $rows, @head) = @_;
2911 8 my @w = map { length } @head;
2912 76 ▶ $rows->(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2913 76 foreach my $i (0 .. $#_) {
2914 398 ▶ $w[$i] = length $_[$i] if length $_[$i] > $w[$i];
Branch: 1 branch
BranchTrueFalseTotal
if length $_[$i] > $w[$i] 15 383 398
2915 }
2916 8 });
2917 8 my $text = '';
2918 84 ▶ my $line = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2919 84 ▶ (my $l = join ' ', map { $right->{$_} ? sprintf('%*s', $w[$_], $_[$_]) : sprintf('%-*s', $w[$_], $_[$_]) } 0 .. $#_) =~ s/ +\z//;
Branch: 1 branch
BranchTrueFalseTotal
$right->{$_} ? : 200 236 436
2920 84 $text .= "$l\n";
2921 8 };
2922 8 $line->(@head);
2923 8 $rows->($line);
2924 8 $text;
2925 4 };
2926 4 my $several = @{ $files } > 1;
2927 8 ▶ my $samples = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
2928 8 my ($row) = @_;
2929 8 foreach my $x (@{ $names }) {
2930 44 my $s = $tally->{$x};
2931 44 ▶ $row->($x, $s->{sex} // 'unknown', defined $s->{het_ratio} ? sprintf('%.3f', $s->{het_ratio}) : '-', $several ? $s->{file} : ());
Branch: 2 branches
BranchTrueFalseTotal
defined $s->{'het_ratio'} ? : 8 36 44
$several ? : 16 28 44
Condition100%2/2
$s->{"sex"} // "unknown"
l!l
836
MC/DC100%1/1
$s->{"sex"} // "unknown"
$s->{"sex"}
Truth table100%2/2
A
A= $s->{"sex"}
Aresult
11
00
2932 }
2933 4 };
2934 8 ▶ my $pairs = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2935 8 my ($row) = @_;
2936 108 ▶ $each_pair->(sub {
Subroutine __ANON__: called CC=5 SCAR=16.5
2937 108 my ($x, $y, $s) = @_;
2938 $row->($x, $y, $s->{sites}, defined $s->{ibs0_rate} ? sprintf('%.4f', $s->{ibs0_rate}) : '-', defined $s->{kinship} ? sprintf('%.4f', $s->{kinship}) : '-',
2939 108 ▶ defined $s->{undecided} ? "undecided: $s->{undecided}" : $s->{category} . (defined $s->{parent} ? " ($s->{parent} the parent)" : ''));
Branch: 4 branches
BranchTrueFalseTotal
defined $s->{'ibs0_rate'} ? : 108 0 108
defined $s->{'kinship'} ? : 108 0 108
defined $s->{'undecided'} ? : 42 66 108
defined $s->{'parent'} ? : 26 40 66
2940 8 });
2941 4 };
2942 4 ▶ 'relatedness: ' . join(', ', @{ $files }) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
$several ? : 2 2 4
2943 . "KING-robust kinship over autosomal biallelic SNVs where either carries the ALT, genotypes of DP below $r->{min_depth} not counted;"
2944 . " first-degree from 0.177 to 0.354, and of those, parent and child when the IBS0 rate is below $r->{max_ibs0};"
2945 . " male when het/hom-ALT on X outside its pseudo-autosomal regions is below $Sex_cutoff\n"
2946 . $table->({ 2 => 1 }, $samples, 'sample', 'sex', 'X het/hom-ALT', $several ? 'VCF' : ())
2947 . $table->({ 2 => 1, 3 => 1, 4 => 1 }, $pairs, 'sample', 'sample', 'sites', 'IBS0 rate', 'kinship', 'relationship');
2948 }
2949  
2950 72 ▶sub relatedness {
Subroutine relatedness: called CC=44 SCAR=37.9
Pod documented
2951 72 my $sub = 'relatedness';
2952 # relatedness($file, ...) takes the VCFs first, unnamed, up to the first word:
2953 # a VCF's name has a dot, as its suffix must, and an option's name, or a
2954 # misspelling of one, has none
2955 72 my @vcf;
2956 72 ▶ push @vcf, shift @_ while @_ && defined $_[0] && !ref $_[0] && $_[0] !~ /\A\w+\z/;
Branch: 1 branch
BranchTrueFalseTotal
@_ and defined $_[0] and not ref $_[0] and not $_[0] =~ /\A\w+\z/ and do { push @vcf, shift @_ } 110 72 182
Condition88%8/9
@_ and defined $_[0] and not ref $_[0] and not $_[0] =~ /\A\w+\z/
!ll&&!rl&&r
1755110
@_ and defined $_[0] and not ref $_[0]
!ll&&!rl&&r
161165
@_ and defined $_[0]
!ll&&!rl&&r
160166
MC/DC75%3/4
@_ and defined $_[0] and not ref $_[0] and not $_[0] =~ /\A\w+\z/
@_ defined $_[0] not ref $_[0] not $_[0] =~ /\A\w+\z/
Truth table80%4/5
A and B and not(C) and not(D)
A= @_B= defined $_[0]C= not ref $_[0]D= not $_[0] =~ /\A\w+\z/
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2957 72 my $args = _args(\@_, $sub, [], [qw(vcf min_depth max_ibs0 report)]);
2958 69 ▶ if (defined $args->{vcf}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"vcf"}) 8 61 69
2959 8 ▶ croak "$sub: the VCFs are given either first, unnamed, or as \"vcf\", not both" if @vcf;
Branch: 1 branch
BranchTrueFalseTotal
if @vcf 1 7 8
2960 7 ▶ @vcf = ref $args->{vcf} eq 'ARRAY' ? @{ $args->{vcf} } : $args->{vcf};
Branch: 1 branch
BranchTrueFalseTotal
ref $args->{'vcf'} eq 'ARRAY' ? : 5 2 7
2961 }
2962 68 ▶ croak "$sub: needs a VCF of several samples, or several VCFs of one, as relatedness(\$file) or relatedness(\$file, \$file2)" unless @vcf;
Branch: 1 branch
BranchTrueFalseTotal
unless @vcf 3 65 68
2963 65 my %r;
2964 65 ▶ $r{min_depth} = $args->{min_depth} // 10; # 0 = count every genotype, whatever its DP; 10 is parent's, for parent's reasons
Condition100%2/2
$args->{"min_depth"} // 10
l!l
362
MC/DC100%1/1
$args->{"min_depth"} // 10
$args->{"min_depth"}
Truth table100%2/2
A
A= $args->{"min_depth"}
Aresult
11
00
2965 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
2966 65 ▶ unless !ref $r{min_depth} && $r{min_depth} =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/ 2 63 65
Condition66%2/3
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
0263
MC/DC50%1/2
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
not ref $r{"min_depth"} $r{"min_depth"} =~ /\A[0-9]+\z/
Truth table66%2/3
not(A) and B
A= not ref $r{"min_depth"}B= $r{"min_depth"} =~ /\A[0-9]+\z/
ABresult
0X0
100
111
2967 63 ▶ $r{max_ibs0} = $args->{max_ibs0} // 0.012; # parent's, and peddy 0.4.3's
Condition100%2/2
$args->{"max_ibs0"} // "0.012"
l!l
459
MC/DC100%1/1
$args->{"max_ibs0"} // "0.012"
$args->{"max_ibs0"}
Truth table100%2/2
A
A= $args->{"max_ibs0"}
Aresult
11
00
2968 croak "$sub: \"max_ibs0\" must be a number above 0, not " . _what($r{max_ibs0})
2969 63 ▶ unless !ref $r{max_ibs0} && $r{max_ibs0} =~ $Number && $r{max_ibs0} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"max_ibs0"} and $r{"max_ibs0"} =~ /$Number/ and $r{"max_ibs0"} > 0 3 60 63
Condition100%6/6
not ref $r{"max_ibs0"} and $r{"max_ibs0"} =~ /$Number/ and $r{"max_ibs0"} > 0
!ll&&!rl&&r
2160
not ref $r{"max_ibs0"} and $r{"max_ibs0"} =~ /$Number/
!ll&&!rl&&r
1161
MC/DC100%3/3
not ref $r{"max_ibs0"} and $r{"max_ibs0"} =~ /$Number/ and $r{"max_ibs0"} > 0
not ref $r{"max_ibs0"} $r{"max_ibs0"} =~ /$Number/ $r{"max_ibs0"} > 0
Truth table100%4/4
not(A) and B and C
A= not ref $r{"max_ibs0"}B= $r{"max_ibs0"} =~ /$Number/C= $r{"max_ibs0"} > 0
ABCresult
0XX0
10X0
1100
1111
2970 60 ▶ $r{report} = $args->{report} // 1; # 1 = print the report to STDOUT; 0 = only return
Condition100%2/2
$args->{"report"} // 1
l!l
4218
MC/DC100%1/1
$args->{"report"} // 1
$args->{"report"}
Truth table100%2/2
A
A= $args->{"report"}
Aresult
11
00
2971 60 ▶ croak "$sub: \"report\" must be 0 or 1, not " . _what($r{report}) unless !ref $r{report} && ($r{report} eq '0' || $r{report} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1 1 59 60
Condition83%5/6
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
!ll&&!rl&&r
0159
$r{"report"} eq 0 or $r{"report"} eq 1
l!l&&r!l&&!r
41181
MC/DC66%2/3
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
not ref $r{"report"} $r{"report"} eq 0 $r{"report"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"report"}B= $r{"report"} eq 0C= $r{"report"} eq 1
ABCresult
0XX0
1000
11X1
1011
2972 # every file checked before any is read, which can take minutes
2973 59 my %given;
2974 59 foreach my $file (@vcf) {
2975 112 _vcf_check($sub, 'vcf', $file);
2976 106 ▶ croak "$sub: \"$file\" is given twice" if $given{$file}++;
Branch: 1 branch
BranchTrueFalseTotal
if $given{$file}++ 1 105 106
2977 }
2978 52 my ($names, $counts, $tally); # the samples in order; REL_T counts a pair, as Bioinf.xs describes them, packed as UVs; each sample's sex counts
2979 52 ▶ if (@vcf == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@vcf == 1) { } 28 24 52
2980 28 my ($next, $close) = _vcf_open($sub, 'vcf', $vcf[0]);
2981 28 ▶ ($names, $counts, $tally) = _located(sub { _relatedness_one($next, $vcf[0], $r{min_depth}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2982 25 $close->();
2983 } else {
2984 # each opened as Bioinf.xs comes to it, and closed at its end, so that only
2985 # one is open at a time
2986 my @next = map {
2987 24 my $file = $_;
2988 70 my ($next, $close);
2989 140 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2990 140 ▶ ($next, $close) = _vcf_open($sub, 'vcf', $file) unless $next;
Branch: 1 branch
BranchTrueFalseTotal
unless $next 70 70 140
2991 140 my $block = $next->();
2992 140 ▶ $close->() unless defined $block;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $block 63 77 140
2993 140 $block;
2994 70 };
2995 } @vcf;
2996 24 ▶ ($names, $counts, $tally) = _located(sub { _relatedness_own(\@next, \@vcf, $r{min_depth}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2997 }
2998 41 foreach my $i (0 .. $#{ $names }) {
2999 187 my $s = $tally->{ $names->[$i] };
3000 187 _sex_of($s, $Sex_cutoff);
3001 187 ▶ $s->{file} = @vcf == 1 ? $vcf[0] : $vcf[$i];
Branch: 1 branch
BranchTrueFalseTotal
@vcf == 1 ? : 137 50 187
3002 }
3003 41 my %out = map { $_ => {} } @{ $names };
3004 # each pair, in the samples' order, given to $code as (first, second, its
3005 # hash); walked when needed rather than held as a list, which for 1,000
3006 # samples would be 499,500 arrays, each with a copy of both names
3007 131 ▶ my $each_pair = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
3008 131 my ($code) = @_;
3009 131 foreach my $i (0 .. $#{ $names } - 1) {
3010 474 my $x = $names->[$i];
3011 474 $code->($x, $_, $out{$x}{$_}) foreach @{ $names }[$i + 1 .. $#{ $names }];
3012 }
3013 41 };
3014 41 my $pair = 11 * length pack 'J', 0; # bytes of a pair's counts in $counts
3015 41 my $k = 0; # where the pair's counts start in $counts
3016 41 foreach my $i (0 .. $#{ $names } - 1) {
3017 146 foreach my $j ($i + 1 .. $#{ $names }) {
3018 429 my ($x, $y) = @{ $names }[$i, $j];
3019 # t[3 * x's ALT count + y's], as parent's, and then the sites in both VCFs,
3020 # in x's alone and in y's alone
3021 429 my @t = (0, unpack "x$k J11", $counts);
3022 429 my @in = splice @t, 9;
3023 429 $k += $pair;
3024 # Flat, but for het and only: on 1,000 samples (2026-10-19) the pairs took
3025 # 560 MB with no field a hash, and 1,110 MB with four, which were these two
3026 # and each sample's hom-ALT count and share of ibs0.
3027 429 my %s;
3028 429 $s{sites} = 0;
3029 429 $s{sites} += $_ foreach @t;
3030 429 ▶ @in = ($s{sites}, 0, 0) if @vcf == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @vcf == 1 369 60 429
3031 429 $s{in_both} = $in[0];
3032 429 $s{only} = { $x => $in[1], $y => $in[2] };
3033 429 $s{ibs0} = $t[2] + $t[6];
3034 429 $s{ibs1} = $t[1] + $t[3] + $t[5] + $t[7];
3035 429 $s{ibs2} = $t[4] + $t[8];
3036 429 $s{het_het} = $t[4];
3037 429 $s{het} = { $x => $t[3] + $t[4] + $t[5], $y => $t[1] + $t[4] + $t[7] };
3038 429 $s{kinship} = _king($s{het}{$x}, $s{het}{$y}, $s{het_het}, $s{ibs0});
3039 429 ▶ $s{ibs0_rate} = $s{sites} ? $s{ibs0} / $s{sites} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$s{'sites'} ? : 429 0 429
3040 # parent's reasons for dying, in parent's order
3041 $s{undecided} = $s{sites} && !($t[1] + $t[2] + $t[3] + $t[6])
3042 ? 'neither has a hom-REF call where the other carries the ALT, so no opposite homozygote can be seen, as in a VCF merged from VCFs that list only their own variants; give each sample\'s own VCF instead'
3043 : $s{sites} < $Parent_sites ? "$s{sites} sites compared, and $Parent_sites are needed"
3044 429 ▶ : !defined $s{kinship} ? ($s{het}{$x} ? $y : $x) . ' has no het call at the sites compared'
Branch: 4 branches
BranchTrueFalseTotal
$s{'sites'} && !($t[1] + $t[2] + $t[3] + $t[6]) ? : 42 387 429
$s{'sites'} < $Parent_sites ? : 3 384 387
!defined($s{'kinship'}) ? : 1 383 384
$s{'het'}{$x} ? : 0 1 1
Condition66%2/3
$s{"sites"} and not $t[1] + $t[2] + $t[3] + $t[6]
!ll&&!rl&&r
038742
MC/DC50%1/2
$s{"sites"} and not $t[1] + $t[2] + $t[3] + $t[6]
$s{"sites"} not $t[1] + $t[2] + $t[3] + $t[6]
Truth table66%2/3
A and not(B)
A= $s{"sites"}B= not $t[1] + $t[2] + $t[3] + $t[6]
ABresult
0X0
100
111
3045 : undef;
3046 429 ▶ $s{relationship} = defined $s{undecided} ? undef : _relationship($s{kinship}, $s{ibs0_rate}, $r{max_ibs0});
Branch: 1 branch
BranchTrueFalseTotal
defined $s{'undecided'} ? : 46 383 429
3047 429 $s{parent} = $s{category} = undef; # below, once every pair is known
3048 429 $out{$x}{$y} = $out{$y}{$x} = \%s;
3049 }
3050 }
3051 41 undef $counts;
3052 # Which of a parent and child is the parent, where a third sample says, since
3053 # two people's genotypes cannot: x is y's parent when x has another child who
3054 # is y's full sibling, or when y has another parent who is unrelated to x, the
3055 # two being y's parents. Two of y's parent-child partners who are
3056 # second-degree relatives are y's parent and y's child, and say nothing about
3057 # which. "Third-degree" is not taken as unrelated: in the CEPH 1463 pedigree
3058 # (peddy's ceph1463.peddy.vcf.gz), the grandfather NA12889 and grandson
3059 # NA12893 had a kinship of 0.0839, below KING's 0.0884, and would have made
3060 # NA12893's father NA12877 his son too.
3061 41 my %pc; # sample => its parent-child partners
3062 429 ▶ $each_pair->(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
3063 429 my ($x, $y, $s) = @_;
3064 429 ▶ return unless ($s->{relationship} // '') eq 'parent-child';
Branch: 1 branch
BranchTrueFalseTotal
unless ($s->{"relationship"} // "") eq "parent-child" 266 163 429
Condition100%2/2
$s->{"relationship"} // ""
l!l
38346
MC/DC100%1/1
$s->{"relationship"} // ""
$s->{"relationship"}
Truth table100%2/2
A
A= $s->{"relationship"}
Aresult
11
00
3065 163 push @{ $pc{$x} }, $y;
3066 163 push @{ $pc{$y} }, $x;
3067 41 });
3068 326 ▶ my $is_parent = sub { # 1 or 0, and never a list, which would spill into the caller's next variable
Subroutine __ANON__: called CC=7 SCAR=19.5
3069 326 my ($x, $y) = @_;
3070 850 ▶ (grep { $_ ne $y && ($out{$y}{$_}{relationship} // '') eq 'full siblings' } @{ $pc{$x} })
Condition80%4/5
$_ ne $y && ($out{$y}{$_}{'relationship'} // '') eq 'full siblings'
!ll&&!rl&&r
326392132
$out{$y}{$_}{"relationship"} // ""
l!l
5240
MC/DC50%1/2
$_ ne $y && ($out{$y}{$_}{'relationship'} // '') eq 'full siblings'
$_ ne $y $out{$y}{$_}{"relationship"}
Truth table66%2/3
A && B
A= $_ ne $yB= $out{$y}{$_}{"relationship"}
ABresult
0X0
100
111
3071 326 ▶ || (grep { $_ ne $x && ($out{$x}{$_}{relationship} // '') eq 'unrelated' } @{ $pc{$y} }) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
grep({$_ ne $y and ($out{$y}{$_}{'relationship'} // '') eq 'full siblings';} @{$pc{$x};}) || grep({$_ ne $x and ($out{$x}{$_}{'relationship'} // '') eq 'unrelated';} @{$pc{$y};}) ? : 157 169 326
Condition87%7/8
grep {$_ ne $y and ($out{$y}{$_}{"relationship"} // "") eq "full siblings";} @{$pc{$x};} or grep {$_ ne $x and ($out{$x}{$_}{"relationship"} // "") eq "unrelated";} @{$pc{$y};}
l!l&&r!l&&!r
10453169
$_ ne $x && ($out{$x}{$_}{'relationship'} // '') eq 'unrelated'
!ll&&!rl&&r
22231668
$out{$x}{$_}{"relationship"} // ""
l!l
3840
MC/DC100%2/2
grep {$_ ne $y and ($out{$y}{$_}{"relationship"} // "") eq "full siblings";} @{$pc{$x};} or grep {$_ ne $x and ($out{$x}{$_}{"relationship"} // "") eq "unrelated";} @{$pc{$y};}
grep {$_ ne $y and ($out{$y}{$_}{"relationship"} // "") eq "full siblings";} @{$pc{$x};} grep {$_ ne $x and ($out{$x}{$_}{"relationship"} // "") eq "unrelated";} @{$pc{$y};}
MC/DC50%1/2
$_ ne $x && ($out{$x}{$_}{'relationship'} // '') eq 'unrelated'
$_ ne $x $out{$x}{$_}{"relationship"}
Truth table100%3/3
A or B
A= grep {$_ ne $y and ($out{$y}{$_}{"relationship"} // "") eq "full siblings";} @{$pc{$x};}B= grep {$_ ne $x and ($out{$x}{$_}{"relationship"} // "") eq "unrelated";} @{$pc{$y};}
ABresult
1X1
011
000
Truth table66%2/3
A && B
A= $_ ne $xB= $out{$x}{$_}{"relationship"}
ABresult
0X0
100
111
3072 41 };
3073 429 ▶ $each_pair->(sub {
Subroutine __ANON__: called CC=19 SCAR=29.5
3074 429 my ($x, $y, $s) = @_;
3075 429 my ($rel, $sx, $sy) = ($s->{relationship}, $tally->{$x}{sex}, $tally->{$y}{sex});
3076 429 ▶ return unless defined $rel;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rel 46 383 429
3077 383 ▶ if ($rel eq 'parent-child') {
Branch: 2 branches
BranchTrueFalseTotal
if ($rel eq 'parent-child') { } 163 220 383
elsif ($rel eq 'full siblings') { } 39 181 220
3078 163 my ($x_is, $y_is) = ($is_parent->($x, $y), $is_parent->($y, $x));
3079 163 ▶ $s->{parent} = $x_is && !$y_is ? $x : $y_is && !$x_is ? $y : undef; # undef when neither is said, or both
Branch: 2 branches
BranchTrueFalseTotal
$x_is && !$y_is ? : 145 18 163
$y_is && !$x_is ? : 12 6 18
Condition66%4/6
$x_is and not $y_is
!ll&&!rl&&r
180145
$y_is and not $x_is
!ll&&!rl&&r
6012
MC/DC50%1/2
$x_is and not $y_is
$x_is not $y_is
MC/DC50%1/2
$y_is and not $x_is
$y_is not $x_is
Truth table66%2/3
A and not(B)
A= $x_isB= not $y_is
ABresult
0X0
100
111
Truth table66%2/3
A and not(B)
A= $y_isB= not $x_is
ABresult
0X0
100
111
3080 163 ▶ if (defined $s->{parent}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $s->{'parent'}) { } 157 6 163
3081 157 ▶ my ($ps, $cs) = $s->{parent} eq $x ? ($sx, $sy) : ($sy, $sx);
Branch: 1 branch
BranchTrueFalseTotal
$s->{'parent'} eq $x ? : 145 12 157
3082 157 ▶ $s->{category} = ($ps ? $Kin_word{$ps}[0] : 'parent') . '-' . ($cs ? $Kin_word{$cs}[1] : 'child');
Branch: 2 branches
BranchTrueFalseTotal
$ps ? : 50 107 157
$cs ? : 66 91 157
3083 } else { # two men are father and son, whichever is which
3084 6 ▶ $s->{category} = $sx && $sy && $sx eq $sy ? "$Kin_word{$sx}[0]-$Kin_word{$sx}[1]" : 'parent-child';
Branch: 1 branch
BranchTrueFalseTotal
$sx && $sy && $sx eq $sy ? : 1 5 6
Condition100%6/6
$sx and $sy and $sx eq $sy
!ll&&!rl&&r
411
$sx and $sy
!ll&&!rl&&r
132
MC/DC100%3/3
$sx and $sy and $sx eq $sy
$sx $sy $sx eq $sy
Truth table100%4/4
A and B and C
A= $sxB= $syC= $sx eq $sy
ABCresult
0XX0
10X0
1100
1111
3085 }
3086 } elsif ($rel eq 'full siblings') {
3087 39 ▶ $s->{category} = !$sx || !$sy ? 'full siblings' : $sx ne $sy ? 'brother-sister' : $sx eq 'male' ? 'brothers' : 'sisters';
Branch: 3 branches
BranchTrueFalseTotal
!($sx && $sy) ? : 30 9 39
$sx ne $sy ? : 5 4 9
$sx eq 'male' ? : 2 2 4
Condition100%3/3
$sx && $sy
!ll&&!rl&&r
12189
MC/DC100%2/2
$sx && $sy
$sx $sy
Truth table100%3/3
A && B
A= $sxB= $sy
ABresult
0X0
100
111
3088 } else {
3089 181 $s->{category} = $rel;
3090 }
3091 41 });
3092 41 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 4 37 41
3093 4 ▶ print STDOUT _relatedness_report(\@vcf, \%r, $names, $tally, $each_pair) or croak "$sub: can't print the report: $!";
Branch: 1 branch
BranchTrueFalseTotal
print STDOUT _relatedness_report(\@vcf, \%r, $names, $tally, $each_pair) or croak("${sub}: can't print the report: $!") 4 0 4
3094 }
3095 41 my ($undecided, $first) = (0); # the pairs undecided, and the first of them as [first, second, why]
3096 41 my @regions; # as parent warns, and for its reasons: the pairs whose VCFs differ in their regions
3097 429 ▶ $each_pair->(sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
3098 429 my ($x, $y, $s) = @_;
3099 429 ▶ if (defined $s->{undecided}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $s->{"undecided"}) 46 383 429
3100 46 ▶ $first //= [$x, $y, $s->{undecided}];
Condition100%2/2
$first //= [$x, $y, $s->{"undecided"}]
l!l
406
MC/DC100%1/1
$first //= [$x, $y, $s->{"undecided"}]
$first
Truth table100%2/2
A
A= $first
Aresult
11
00
3101 46 $undecided++;
3102 }
3103 429 ▶ my ($more, $fewer) = $s->{only}{$x} > $s->{only}{$y} ? ($x, $y) : ($y, $x);
Branch: 1 branch
BranchTrueFalseTotal
$s->{'only'}{$x} > $s->{'only'}{$y} ? : 32 397 429
3104 push @regions, "$tally->{$more}{file} against $tally->{$fewer}{file} ($s->{only}{$more} to $s->{only}{$fewer})"
3105 429 ▶ if @vcf > 1 && _regions_differ($s->{only}{$more}, $s->{only}{$fewer}, $s->{sites});
Branch: 1 branch
BranchTrueFalseTotal
if @vcf > 1 and _regions_differ($s->{"only"}{$more}, $s->{"only"}{$fewer}, $s->{"sites"}) 3 426 429
Condition100%3/3
@vcf > 1 and _regions_differ($s->{"only"}{$more}, $s->{"only"}{$fewer}, $s->{"sites"})
!ll&&!rl&&r
369573
MC/DC100%2/2
@vcf > 1 and _regions_differ($s->{"only"}{$more}, $s->{"only"}{$fewer}, $s->{"sites"})
@vcf > 1 _regions_differ($s->{"only"}{$more}, $s->{"only"}{$fewer}, $s->{"sites"})
Truth table100%3/3
A and B
A= @vcf > 1B= _regions_differ($s->{"only"}{$more}, $s->{"only"}{$fewer}, $s->{"sites"})
ABresult
0X0
100
111
3106 41 });
3107 41 my $n_pairs = @{ $names } * (@{ $names } - 1) / 2;
3108 41 ▶ carp "$sub: $undecided of $n_pairs pairs are undecided, and their relationship undef, such as $first->[0] and $first->[1]: $first->[2]" if $undecided;
Branch: 1 branch
BranchTrueFalseTotal
if $undecided 6 35 41
3109 41 ▶ carp "$sub: the VCFs of " . scalar(@regions) . ' pair' . (@regions == 1 ? ' were' : 's were') . ' probably not sequenced over the same regions (an exome and a genome, or two capture kits),'
Branch: 4 branches
BranchTrueFalseTotal
if @regions 2 39 41
@regions == 1 ? : 1 1 2
$#regions < 2 ? : 2 0 2
@regions > 3 ? : 0 2 2
3110 . ' since one has more than twice as many sites that the other lacks as the other has that it lacks: '
3111 . join(', ', @regions[0 .. ($#regions < 2 ? $#regions : 2)]) . (@regions > 3 ? ', and ' . (@regions - 3) . ' more' : '')
3112 . '; a site that one lacks is taken as hom-REF in it, so their IBS0 and kinship are not to be trusted'
3113 if @regions;
3114 41 ▶ wantarray ? (\%out, $tally) : \%out;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 8 33 41
3115 }
3116  
3117 # ---- genotype concordance
3118  
3119 # concordance's report, given its files, the resolved options, its result,
3120 # and the test's samples in its file's order. Columns are
3121 # as wide as their widest entry, numbers right-aligned.
3122 2 ▶sub _concordance_report {
Subroutine _concordance_report: called CC=14 SCAR=26.5
3123 2 my ($test, $truth, $r, $out, $test_names) = @_;
3124 2 my @pairs = map { $out->{$_} } grep { exists $out->{$_} } @{ $test_names }; # not a slice, which grep would autovivify into $out
3125 2 my $renamed = grep { $_->{test_sample} ne $_->{truth_sample} } @pairs; # the truth's sample is shown only when one is named otherwise
3126 2 ▶ my @head = ('sample', $renamed ? 'truth sample' : (), 'sites', 'in truth', 'concordant', 'discordant', 'gained', 'lost',
Branch: 1 branch
BranchTrueFalseTotal
$renamed ? : 1 1 2
3127 'concordance', 'precision', 'recall', 'specificity');
3128 2 ▶ my $ratio = sub { defined $_[0] ? sprintf('%.4f', $_[0]) : '-' };
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 12 0 12
3129 my @rows = map {
3130 2 my ($c, $m) = @{ $_ }{qw(counts metrics)};
3131 3 my ($agree, $differ) = (0, 0);
3132 3 foreach my $kind (keys %{ $c }) {
3133 135 ▶ $agree += $c->{$kind} if $kind =~ /\Aconcordant_/;
Branch: 1 branch
BranchTrueFalseTotal
if $kind =~ /\Aconcordant_/ 33 102 135
3134 135 ▶ $differ += $c->{$kind} if $kind =~ /\Adiscordant_/;
Branch: 1 branch
BranchTrueFalseTotal
if $kind =~ /\Adiscordant_/ 96 39 135
3135 }
3136 3 [$_->{test_sample}, $renamed ? $_->{truth_sample} : (), $_->{sites}, $_->{in_truth}, $agree, $differ, @{ $c }{qw(gained_site lost_site)},
3137 3 ▶ map { $ratio->($m->{$_}) } qw(genotype_concordance precision_genotype recall_genotype specificity_genotype)]
Branch: 1 branch
BranchTrueFalseTotal
$renamed ? : 1 2 3
3138 } @pairs;
3139 2 my @w = map { length } @head;
3140 2 foreach my $row (@rows) {
3141 3 foreach my $i (0 .. $#head) {
3142 34 ▶ $w[$i] = length $row->[$i] if length $row->[$i] > $w[$i];
Branch: 1 branch
BranchTrueFalseTotal
if length $row->[$i] > $w[$i] 0 34 34
3143 }
3144 }
3145 2 ▶ my $text_cols = $renamed ? 2 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$renamed ? : 1 1 2
3146 2 ▶ my $line = sub { join(' ', map { $_ < $text_cols ? sprintf('%-*s', $w[$_], $_[$_]) : sprintf('%*s', $w[$_], $_[$_]) } 0 .. $#head) . "\n" };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_ < $text_cols ? : 7 50 57
3147 2 my @alone = grep { !exists $out->{$_} } @{ $test_names };
3148 "concordance: test $test against truth $truth\n"
3149 . 'each test site compared with the truth\'s of the same CHROM, POS, REF and ALT, a site the truth lacks being a no-call there'
3150 . ($r->{min_depth} ? ", and a genotype of DP below $r->{min_depth} a no-call" : '')
3151 . "; precision, recall and specificity are of genotypes\n"
3152 3 ▶ . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows)
Branch: 1 branch
BranchTrueFalseTotal
@alone ? : 1 1 2
3153 2 ▶ . (@alone ? scalar(@alone) . ' of the test\'s ' . scalar(@{ $test_names }) . ' samples are not in the truth: '
Branch: 3 branches
BranchTrueFalseTotal
$r->{'min_depth'} ? : 0 2 2
$#alone < 4 ? : 1 0 1
@alone > 5 ? : 0 1 1
3154 . join(', ', @alone[0 .. ($#alone < 4 ? $#alone : 4)]) . (@alone > 5 ? ', and ' . (@alone - 5) . ' more' : '') . "\n" : '');
3155 }
3156  
3157 83 ▶sub concordance {
Subroutine concordance: called CC=17 SCAR=28.3
Pod documented
3158 83 my $sub = 'concordance';
3159 83 my $args = _args(\@_, $sub, [qw(test truth)], [qw(discordances min_depth report)]);
3160 77 my %r;
3161 # x.low_ram_local_concordance.pl, which this is taken from, had no depth filter
3162 77 ▶ $r{min_depth} = $args->{min_depth} // 0; # 0 = every genotype compared, whatever its DP; otherwise a genotype of DP below it is a no-call
Condition100%2/2
$args->{"min_depth"} // 0
l!l
572
MC/DC100%1/1
$args->{"min_depth"} // 0
$args->{"min_depth"}
Truth table100%2/2
A
A= $args->{"min_depth"}
Aresult
11
00
3163 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
3164 77 ▶ unless !ref $r{min_depth} && $r{min_depth} =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/ 3 74 77
Condition100%3/3
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
1274
MC/DC100%2/2
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
not ref $r{"min_depth"} $r{"min_depth"} =~ /\A[0-9]+\z/
Truth table100%3/3
not(A) and B
A= not ref $r{"min_depth"}B= $r{"min_depth"} =~ /\A[0-9]+\z/
ABresult
0X0
100
111
3165 74 ▶ $r{discordances} = $args->{discordances} // 1; # 1 = list each discordant, gained and lost site; 0 = only count them, and "discordances" is undef
Condition100%2/2
$args->{"discordances"} // 1
l!l
470
MC/DC100%1/1
$args->{"discordances"} // 1
$args->{"discordances"}
Truth table100%2/2
A
A= $args->{"discordances"}
Aresult
11
00
3166 croak "$sub: \"discordances\" must be 0 or 1, not " . _what($r{discordances})
3167 74 ▶ unless !ref $r{discordances} && ($r{discordances} eq '0' || $r{discordances} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"discordances"} and $r{"discordances"} eq 0 || $r{"discordances"} eq 1 2 72 74
Condition83%5/6
not ref $r{"discordances"} and $r{"discordances"} eq 0 || $r{"discordances"} eq 1
!ll&&!rl&&r
0272
$r{"discordances"} eq 0 or $r{"discordances"} eq 1
l!l&&r!l&&!r
2702
MC/DC66%2/3
not ref $r{"discordances"} and $r{"discordances"} eq 0 || $r{"discordances"} eq 1
not ref $r{"discordances"} $r{"discordances"} eq 0 $r{"discordances"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"discordances"}B= $r{"discordances"} eq 0C= $r{"discordances"} eq 1
ABCresult
0XX0
1000
11X1
1011
3168 72 ▶ $r{report} = $args->{report} // 1; # 1 = print a table of the samples to STDOUT; 0 = only return them
Condition100%2/2
$args->{"report"} // 1
l!l
657
MC/DC100%1/1
$args->{"report"} // 1
$args->{"report"}
Truth table100%2/2
A
A= $args->{"report"}
Aresult
11
00
3169 72 ▶ croak "$sub: \"report\" must be 0 or 1, not " . _what($r{report}) unless !ref $r{report} && ($r{report} eq '0' || $r{report} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1 1 71 72
Condition83%5/6
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
!ll&&!rl&&r
0171
$r{"report"} eq 0 or $r{"report"} eq 1
l!l&&r!l&&!r
6471
MC/DC66%2/3
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
not ref $r{"report"} $r{"report"} eq 0 $r{"report"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"report"}B= $r{"report"} eq 0C= $r{"report"} eq 1
ABCresult
0XX0
1000
11X1
1011
3170 71 my ($test, $truth) = @{ $args }{qw(test truth)};
3171 # both checked before either is read, which can take minutes
3172 71 _vcf_check($sub, 'test', $test);
3173 69 _vcf_check($sub, 'truth', $truth);
3174 66 _same_build($sub, $test, $truth); # reads only the headers
3175 # the truth's samples first, so that the test's reading keeps the calls of
3176 # only those samples it will compare
3177 61 my ($next, $close) = _vcf_open($sub, 'truth', $truth);
3178 61 ▶ my ($truth_names) = _located(sub { _vcf_samples($next, $truth) });
Subroutine __ANON__: called CC=1 SCAR=0.0
3179 59 $close->();
3180 59 my ($test_next, $test_close) = _vcf_open($sub, 'test', $test);
3181 59 my ($truth_next, $truth_close) = _vcf_open($sub, 'truth', $truth);
3182 59 ▶ my ($out, $test_names) = _located(sub { _concordance($test_next, $test, $truth_next, $truth, $truth_names, $r{min_depth}, $r{discordances}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
3183 38 $test_close->();
3184 38 $truth_close->();
3185 38 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 2 36 38
3186 2 ▶ print STDOUT _concordance_report($test, $truth, \%r, $out, $test_names) or croak "$sub: can't print the report: $!";
Branch: 1 branch
BranchTrueFalseTotal
print STDOUT _concordance_report($test, $truth, \%r, $out, $test_names) or croak("${sub}: can't print the report: $!") 2 0 2
3187 }
3188 38 my ($any) = values %{ $out }; # every pair has the same sites
3189 38 ▶ carp "$sub: \"test\" $test has no records, so nothing was compared" unless $any->{sites};
Branch: 1 branch
BranchTrueFalseTotal
unless $any->{"sites"} 1 37 38
3190 carp "$sub: none of the $any->{sites} sites of \"test\" $test is in \"truth\" $truth, so every call of the test is gained or a no-call;"
3191 . ' check that the two are of the same genome build'
3192 38 ▶ if $any->{sites} && !$any->{in_truth};
Branch: 1 branch
BranchTrueFalseTotal
if $any->{"sites"} and not $any->{"in_truth"} 6 32 38
Condition100%3/3
$any->{"sites"} and not $any->{"in_truth"}
!ll&&!rl&&r
1316
MC/DC100%2/2
$any->{"sites"} and not $any->{"in_truth"}
$any->{"sites"} not $any->{"in_truth"}
Truth table100%3/3
A and not(B)
A= $any->{"sites"}B= not $any->{"in_truth"}
ABresult
0X0
100
111
3193 38 $out;
3194 }
3195  
3196 # ---- trait prediction
3197  
3198 # GRCh37's and GRCh38's lengths for four of the chromosomes the HIrisPlex-S
3199 # panel sits on, which _hirisplex_build tells one build from the other by.
3200 # From Ensembl's /info/assembly/homo_sapiens, rest.ensembl.org for GRCh38 and
3201 # grch37.rest.ensembl.org for GRCh37, read 2026-10-20. hg19 and b37 differ
3202 # only in what they call their chromosomes, and hg38 and b38 likewise, so a
3203 # length separates the two pairs but not the two within a pair, which the
3204 # panel's positions do not depend on.
3205 40 my %Build_length = (
3206 b37 => { 1 => 249250621, 15 => 102531392, 16 => 90354753, 20 => 63025520 },
3207 b38 => { 1 => 248956422, 15 => 101991189, 16 => 90338345, 20 => 64444167 },
3208 );
3209  
3210 # The HIrisPlex-S marker panel, share/hirisplex_s_panel.tsv, read once into an
3211 # array ref of hash refs in the panel's own order. share/make_hirisplex_panel.pl
3212 # writes that file and its header comment says where every column comes from.
3213 40 my $Panel; # undef until the file has been read
3214  
3215 # The data file $name (a marker panel, or the genetic codes), which this
3216 # distribution installs in its share directory, as a file that can be read;
3217 # dies, naming $sub, when it is nowhere.
3218 7 ▶sub _share_file {
Subroutine _share_file: called CC=9 SCAR=34.3
3219 7 my ($sub, $name) = @_;
3220 # Installed, the panel is in the distribution's share directory, which is
3221 # what File::ShareDir finds. Two fallbacks follow it: the same layout looked
3222 # for in @INC, which is where blib puts the file under "make test" and keeps
3223 # this working on a perl that has not got File::ShareDir, and the share
3224 # directory beside lib/, which is what lets a working copy be used before
3225 # the module is installed.
3226 7 my $file = eval { require File::ShareDir; File::ShareDir::dist_file('Cn-Bioinf', $name) };
3227 7 ▶ unless (defined $file && -f $file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $file and -f $file) 0 7 7
Condition33%1/3
defined $file and -f $file
!ll&&!rl&&r
007
MC/DC0%0/2
defined $file and -f $file
defined $file -f $file
Truth table33%1/3
A and B
A= defined $fileB= -f $file
ABresult
0X0
100
111
3228 0 my @try = map { File::Spec->catfile($_, 'auto', 'share', 'dist', 'Cn-Bioinf', $name) } grep { !ref } @INC;
3229 0 ▶ my (undef, $dir) = File::Spec->splitpath($INC{'Cn/Bioinf.pm'} // '');
Condition0%0/2
$INC{"Cn/Bioinf.pm"} // ""
l!l
00
MC/DC0%0/1
$INC{"Cn/Bioinf.pm"} // ""
$INC{"Cn/Bioinf.pm"}
Truth table0%0/2
A
A= $INC{"Cn/Bioinf.pm"}
Aresult
11
00
3230 0 ▶ push @try, File::Spec->catfile($dir, File::Spec->updir, File::Spec->updir, 'share', $name) if length $dir;
Branch: 1 branch
BranchTrueFalseTotal
if length $dir 0 0 0
3231 0 ▶ ($file) = grep { -f $_ && -r _ } @try;
Condition0%0/3
-f $_ && -r _
!ll&&!rl&&r
000
MC/DC0%0/2
-f $_ && -r _
-f $_ -r _
Truth table0%0/3
A && B
A= -f $_B= -r _
ABresult
0X0
100
111
3232 }
3233 7 ▶ croak "$sub: can't find $name, which this distribution installs in its share directory"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file and -f $file and -r _ 0 7 7
Condition33%2/6
defined $file and -f $file and -r _
!ll&&!rl&&r
007
defined $file and -f $file
!ll&&!rl&&r
007
MC/DC0%0/3
defined $file and -f $file and -r _
defined $file -f $file -r _
Truth table25%1/4
A and B and C
A= defined $fileB= -f $fileC= -r _
ABCresult
0XX0
10X0
1100
1111
3234 unless defined $file && -f $file && -r _;
3235 7 $file;
3236 }
3237  
3238 15 ▶sub _hirisplex_panel {
Subroutine _hirisplex_panel: called CC=19 SCAR=32.9
3239 15 my ($sub) = @_;
3240 15 ▶ return $Panel if $Panel;
Branch: 1 branch
BranchTrueFalseTotal
if $Panel 13 2 15
3241 2 my $file = _share_file($sub, 'hirisplex_s_panel.tsv');
3242 2 ▶ open my $fh, '<', $file or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or croak("${sub}: can't read ${file}: $!") 2 0 2
3243 2 my $head = <$fh>;
3244 2 ▶ croak "$sub: marker panel $file is empty" unless defined $head;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $head 0 2 2
3245 2 $head =~ s/\r?\n\z//;
3246 2 $head =~ s/\A#//;
3247 2 my @cols = split /\t/, $head, -1;
3248 2 my @panel;
3249 2 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 82 2 84
3250 82 $line =~ s/\r?\n\z//;
3251 82 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 82 82
3252 82 my %m;
3253 82 @m{@cols} = split /\t/, $line, -1;
3254 82 push @panel, \%m;
3255 }
3256 2 ▶ close $fh or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't read ${file}: $!") 2 0 2
3257 2 ▶ croak "$sub: marker panel $file has no markers" unless @panel;
Branch: 1 branch
BranchTrueFalseTotal
unless @panel 0 2 2
3258 2 foreach my $m (@panel) {
3259 82 foreach my $c (qw(rsid gene input_allele count_allele kind)) {
3260 410 ▶ croak "$sub: marker " . ($m->{rsid} // '?') . " of $file has no $c" unless defined $m->{$c} && length $m->{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $m->{$c} and length $m->{$c} 0 410 410
Condition20%1/5
defined $m->{$c} and length $m->{$c}
!ll&&!rl&&r
00410
$m->{"rsid"} // "?"
l!l
00
MC/DC0%0/2
defined $m->{$c} and length $m->{$c}
defined $m->{$c} length $m->{$c}
MC/DC0%0/1
$m->{"rsid"} // "?"
$m->{"rsid"}
Truth table33%1/3
A and B
A= defined $m->{$c}B= length $m->{$c}
ABresult
0X0
100
111
Truth table0%0/2
A
A= $m->{"rsid"}
Aresult
11
00
3261 }
3262 # Every marker of this panel is autosomal, and the reader counts a
3263 # diploid call only, so a sex chromosome here would be counted wrongly
3264 # rather than refused.
3265 82 foreach my $b (qw(b37 b38)) {
3266 164 my ($c, $p) = @{ $m }{"${b}_chrom", "${b}_pos"};
3267 164 ▶ next unless defined $c && length $c;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $c and length $c 0 164 164
Condition33%1/3
defined $c and length $c
!ll&&!rl&&r
00164
MC/DC0%0/2
defined $c and length $c
defined $c length $c
Truth table33%1/3
A and B
A= defined $cB= length $c
ABresult
0X0
100
111
3268 164 ▶ croak "$sub: marker $m->{rsid} of $file is on $b chromosome \"$c\", and the panel is autosomal"
Branch: 1 branch
BranchTrueFalseTotal
unless $c =~ /\A(?:[1-9]|1[0-9]|2[0-2])\z/ 0 164 164
3269 unless $c =~ /\A(?:[1-9]|1[0-9]|2[0-2])\z/;
3270 164 ▶ croak "$sub: marker $m->{rsid} of $file has $b position " . _what($p) . ", which isn't a position"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $p and $p =~ /\A[1-9][0-9]*\z/ 0 164 164
Condition33%1/3
defined $p and $p =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
00164
MC/DC0%0/2
defined $p and $p =~ /\A[1-9][0-9]*\z/
defined $p $p =~ /\A[1-9][0-9]*\z/
Truth table33%1/3
A and B
A= defined $pB= $p =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
3271 unless defined $p && $p =~ /\A[1-9][0-9]*\z/;
3272 }
3273 }
3274 2 $Panel = \@panel;
3275 }
3276  
3277 # Which build's coordinates the panel is matched on, read from the ##contig
3278 # lines of the VCF $file, given to $sub as "vcf": "b37" or "b38". A header
3279 # that gives no length for any of the chromosomes above, or lengths that are
3280 # neither build's, cannot be told apart and dies asking for "build".
3281 35 ▶sub _hirisplex_build {
Subroutine _hirisplex_build: called CC=6 SCAR=18.0
3282 35 my ($sub, $file) = @_;
3283 35 my $meta = _vcf_meta($sub, 'vcf', $file);
3284 35 my %length; # contig => the first length its header gives
3285 35 foreach my $c (@{ $meta->{contig} }) {
3286 70 ▶ $length{ $c->[0] } //= $c->[1] if defined $c->[1];
Branch: 1 branch
BranchTrueFalseTotal
if defined $c->[1] 70 0 70
Condition33%1/3
$length{$c->[0]} //= $c->[1]
l!l&&r!l&&!r
0700
MC/DC0%0/2
$length{$c->[0]} //= $c->[1]
$length{$c->[0]} $c->[1]
Truth table33%1/3
A //= B
A= $length{$c->[0]}B= $c->[1]
ABresult
1X1
011
000
3287 }
3288 35 my @named = grep { defined $length{$_} } sort { $a <=> $b } keys %{ $Build_length{b37} };
3289 croak "$sub: \"vcf\" $file has no ##contig line giving a length for chromosome "
3290 35 ▶ . join(', ', sort { $a <=> $b } keys %{ $Build_length{b37} }) . ', so its genome build can\'t be told from its header;'
Branch: 1 branch
BranchTrueFalseTotal
unless @named 2 33 35
3291 . ' give "build" as hg19, b37, hg38 or b38' unless @named;
3292 33 my @fits = grep { my $b = $_; !grep { $length{$_} != $Build_length{$b}{$_} } @named } sort keys %Build_length;
3293 croak "$sub: \"vcf\" $file gives chromosome lengths that are neither GRCh37's nor GRCh38's ("
3294 33 ▶ . join(', ', map { "$_ is $length{$_}" } @named) . '), so its genome build can\'t be told from its header;'
Branch: 1 branch
BranchTrueFalseTotal
unless @fits == 1 1 32 33
3295 . ' give "build" as hg19, b37, hg38 or b38' unless @fits == 1;
3296 32 $fits[0];
3297 }
3298  
3299 # Whether each prediction can be made at all from $d, one genotype for each
3300 # marker of $panel and undef where the sample had no call. The webtool refuses
3301 # some outright, whatever the genotypes say, because the loss in AUC is too
3302 # great; from the HIrisPlex-S user manual (version 2.0, 2018,
3303 # https://hirisplex.erasmusmc.nl/pdf/hirisplex.erasmusmc.nl.pdf, read
3304 # 2026-10-20), page 2: "Inputs missing the HERC2 SNP (rs12913832 = NA) will
3305 # not provide an eye colour prediction result, as the loss in AUC is too
3306 # great. Inputs missing all 11 MC1R SNPs will not provide a hair colour
3307 # prediction result. Inputs missing a combination of HERC2-SLC45A2-IRF4 will
3308 # not produce and eye or hair prediction result." The manual gives no such
3309 # rule for skin, and says only that missing any marker "is not advised", so
3310 # skin is refused here only when nothing at all was called.
3311 28 ▶sub _hirisplex_possible {
Subroutine _hirisplex_possible: called CC=8 SCAR=20.8
3312 28 my ($panel, $d) = @_;
3313 28 my %called; # rs number => 1 for each marker the sample has a genotype at
3314 28 my ($mc1r, $any) = (0, 0);
3315 28 foreach my $k (0 .. $#{ $panel }) {
3316 1148 ▶ next unless defined $d->[$k];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $d->[$k] 451 697 1148
3317 697 $called{ $panel->[$k]{rsid} } = 1;
3318 697 ▶ $mc1r++ if $panel->[$k]{gene} eq 'MC1R';
Branch: 1 branch
BranchTrueFalseTotal
if $panel->[$k]{"gene"} eq "MC1R" 191 506 697
3319 697 $any++;
3320 }
3321 # HERC2 rs12913832, SLC45A2 rs16891982 and IRF4 rs12203592: eye needs the
3322 # first, so it needs one of the three already, and hair needs one of them
3323 28 my $three = grep { $called{$_} } qw(rs12913832 rs16891982 rs12203592);
3324 {
3325 28 ▶ eye => $called{rs12913832} ? 1 : 0,
Branch: 3 branches
BranchTrueFalseTotal
$called{'rs12913832'} ? : 15 13 28
$mc1r && $three ? : 20 8 28
$any ? : 27 1 28
Condition100%3/3
$mc1r and $three
!ll&&!rl&&r
1720
MC/DC100%2/2
$mc1r and $three
$mc1r $three
Truth table100%3/3
A and B
A= $mc1rB= $three
ABresult
0X0
100
111
3326 hair => $mc1r && $three ? 1 : 0,
3327 skin => $any ? 1 : 0,
3328 };
3329 }
3330  
3331 # The genotypes of $out written to $file as the CSV the HIrisPlex-S webtool
3332 # takes: a sampleid column and one for each marker, headed
3333 # "<rs number>_<input allele>" as the webtool's own template heads it, holding
3334 # the count of that allele or NA. The samples are written in $order, the VCF's.
3335 1 ▶sub _hirisplex_csv {
Subroutine _hirisplex_csv: called CC=10 SCAR=25.1
3336 1 my ($sub, $file, $panel, $out, $order) = @_;
3337 1 my @head = map { "$_->{rsid}_$_->{input_allele}" } @{ $panel };
3338 # The webtool reads the file as plain CSV, so a sample whose name holds a
3339 # comma, a quote or a newline would move or split its row rather than
3340 # being quoted into it.
3341 1 my @bad = grep { /[",\r\n]/ } @{ $order };
3342 0 ▶ croak "$sub: can't write $file: sample" . (@bad > 1 ? 's ' : ' ') . join(', ', map { "\"$_\"" } @bad)
Branch: 3 branches
BranchTrueFalseTotal
if @bad 0 1 1
@bad > 1 ? : 0 0 0
@bad > 1 ? : 0 0 0
3343 . (@bad > 1 ? ' have' : ' has') . ' a comma, a quote or a newline in the name, which a CSV column can\'t hold' if @bad;
3344 1 ▶ open my $fh, '>', $file or croak "$sub: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $file or croak("${sub}: can't write ${file}: $!") 1 0 1
3345 1 ▶ print {$fh} join(',', 'sampleid', @head), "\n" or croak "$sub: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} join(",", "sampleid", @head), "\n" or croak("${sub}: can't write ${file}: $!") 1 0 1
3346 1 foreach my $s (@{ $order }) {
3347 4 my $g = $out->{$s}{genotype};
3348 4 ▶ print {$fh} join(',', $s, map { defined $g->{$_} ? $g->{$_} : 'NA' } @head), "\n" or croak "$sub: can't write $file: $!";
Branch: 2 branches
BranchTrueFalseTotal
print {$fh;} join(",", $s, map({defined $g->{$_} ? $g->{$_} : "NA";} @head)), "\n" or croak("${sub}: can't write ${file}: $!") 4 0 4
defined $g->{$_} ? : 136 28 164
3349 }
3350 1 ▶ close $fh or croak "$sub: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't write ${file}: $!") 1 0 1
3351 }
3352  
3353 # hirisplex_genotypes's report on $vcf: what was read and how, then a table of
3354 # the samples in $order, the VCF's, each with how many markers were called and
3355 # which predictions its genotypes allow.
3356 0 ▶sub _hirisplex_report {
Subroutine _hirisplex_report: not called CC=8 SCAR=42.8
3357 0 my ($vcf, $r, $panel, $out, $order, $absent) = @_;
3358 0 my @head = ('sample', 'called', 'missing', 'eye', 'hair', 'skin');
3359 my @rows = map {
3360 0 my $s = $out->{$_};
3361 0 ▶ [$_, $s->{called}, scalar @{ $s->{missing} }, map { $s->{$_} ? 'yes' : 'no' } qw(eye hair skin)]
Branch: 1 branch
BranchTrueFalseTotal
$s->{$_} ? : 0 0 0
3362 0 } @{ $order };
3363 0 my @w = map { length $head[$_] } 0 .. $#head;
3364 0 foreach my $row (@rows) {
3365 0 foreach my $i (0 .. $#head) {
3366 0 ▶ $w[$i] = length $row->[$i] if length $row->[$i] > $w[$i];
Branch: 1 branch
BranchTrueFalseTotal
if length $row->[$i] > $w[$i] 0 0 0
3367 }
3368 }
3369 0 ▶ my $line = sub { join(' ', map { $_ == 0 ? sprintf('%-*s', $w[$_], $_[$_]) : sprintf('%*s', $w[$_], $_[$_]) } 0 .. $#head) . "\n" };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
$_ == 0 ? : 0 0 0
3370 "hirisplex_genotypes: $vcf\n"
3371 0 ▶ . scalar(@{ $panel }) . ' HIrisPlex-S markers, matched by '
Branch: 2 branches
BranchTrueFalseTotal
$r->{'match'} eq 'id' ? : 0 0 0
@{$absent;} ? : 0 0 0
3372 . ($r->{match} eq 'id' ? 'rs number' : "position on $r->{build}")
3373 . "; genotypes of DP below $r->{min_depth} not counted\n"
3374 0 ▶ . (@{ $absent } ? scalar(@{ $absent }) . ' marker' . (@{ $absent } > 1 ? 's' : '') . ' not in the file at all: '
Branch: 1 branch
BranchTrueFalseTotal
@{$absent;} > 1 ? : 0 0 0
3375 0 . join(', ', @{ $absent }) . "\n" : '')
3376 0 . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows)
3377 . "\"eye\", \"hair\" and \"skin\" are whether the HIrisPlex-S manual's rules allow that prediction from these markers\n";
3378 }
3379  
3380 25 ▶sub hirisplex_genotypes {
Subroutine hirisplex_genotypes: called CC=47 SCAR=40.4
Pod documented
3381 25 my $sub = 'hirisplex_genotypes';
3382 # hirisplex_genotypes($file) and hirisplex_genotypes($file, %options) take
3383 # the file first, as sex_check does; an odd count whose first is an
3384 # option's name is left for _args to refuse
3385 25 ▶ unshift @_, 'vcf' if @_ % 2 && defined $_[0] && !ref $_[0] && $_[0] !~ /\A(?:vcf|build|file|match|min_depth|report)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 and defined $_[0] and not ref $_[0] and not $_[0] =~ /\A(?:vcf|build|file|match|min_depth|report)\z/ 1 24 25
Condition66%6/9
@_ % 2 and defined $_[0] and not ref $_[0] and not $_[0] =~ /\A(?:vcf|build|file|match|min_depth|report)\z/
!ll&&!rl&&r
2401
@_ % 2 and defined $_[0] and not ref $_[0]
!ll&&!rl&&r
2401
@_ % 2 and defined $_[0]
!ll&&!rl&&r
2401
MC/DC25%1/4
@_ % 2 and defined $_[0] and not ref $_[0] and not $_[0] =~ /\A(?:vcf|build|file|match|min_depth|report)\z/
@_ % 2 defined $_[0] not ref $_[0] not $_[0] =~ /\A(?:vcf|build|file|match|min_depth|report)\z/
Truth table40%2/5
A and B and not(C) and not(D)
A= @_ % 2B= defined $_[0]C= not ref $_[0]D= not $_[0] =~ /\A(?:vcf|build|file|match|min_depth|report)\z/
ABCDresult
0XXX0
10XX0
110X0
11100
11111
3386 25 ▶ croak "$sub: \"$_[0]\" is the file, so the options after it must be name => value pairs, and are an odd number"
Branch: 1 branch
BranchTrueFalseTotal
if @_ and defined $_[0] and not ref $_[0] and $_[0] ne "vcf" and -f $_[0] 0 25 25
Condition58%7/12
@_ and defined $_[0] and not ref $_[0] and $_[0] ne "vcf" and -f $_[0]
!ll&&!rl&&r
2500
@_ and defined $_[0] and not ref $_[0] and $_[0] ne "vcf"
!ll&&!rl&&r
1240
@_ and defined $_[0] and not ref $_[0]
!ll&&!rl&&r
1024
@_ and defined $_[0]
!ll&&!rl&&r
0124
MC/DC0%0/5
@_ and defined $_[0] and not ref $_[0] and $_[0] ne "vcf" and -f $_[0]
@_ defined $_[0] not ref $_[0] $_[0] ne "vcf" -f $_[0]
Truth table33%2/6
A and B and not(C) and D and E
A= @_B= defined $_[0]C= not ref $_[0]D= $_[0] ne "vcf"E= -f $_[0]
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
3387 if @_ && defined $_[0] && !ref $_[0] && $_[0] ne 'vcf' && -f $_[0];
3388 25 my $args = _args(\@_, $sub, ['vcf'], [qw(build file match min_depth report)]);
3389 23 my %r;
3390 23 ▶ $r{match} = $args->{match} // 'position'; # 'position' = CHROM and POS against the panel's coordinates; 'id' = the ID column against its rs numbers
Condition100%2/2
$args->{"match"} // "position"
l!l
419
MC/DC100%1/1
$args->{"match"} // "position"
$args->{"match"}
Truth table100%2/2
A
A= $args->{"match"}
Aresult
11
00
3391 croak "$sub: \"match\" must be \"position\" or \"id\", not " . _what($r{match})
3392 23 ▶ unless !ref $r{match} && ($r{match} eq 'position' || $r{match} eq 'id');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"match"} and $r{"match"} eq "position" || $r{"match"} eq "id" 1 22 23
Condition83%5/6
not ref $r{"match"} and $r{"match"} eq "position" || $r{"match"} eq "id"
!ll&&!rl&&r
0122
$r{"match"} eq "position" or $r{"match"} eq "id"
l!l&&r!l&&!r
1931
MC/DC66%2/3
not ref $r{"match"} and $r{"match"} eq "position" || $r{"match"} eq "id"
not ref $r{"match"} $r{"match"} eq "position" $r{"match"} eq "id"
Truth table75%3/4
not(A) and B or C
A= not ref $r{"match"}B= $r{"match"} eq "position"C= $r{"match"} eq "id"
ABCresult
0XX0
1000
11X1
1011
3393 22 ▶ $r{min_depth} = $args->{min_depth} // 7; # 0 = count every genotype, whatever its DP; 7 is sex_check's, for sex_check's reasons
Condition100%2/2
$args->{"min_depth"} // 7
l!l
1012
MC/DC100%1/1
$args->{"min_depth"} // 7
$args->{"min_depth"}
Truth table100%2/2
A
A= $args->{"min_depth"}
Aresult
11
00
3394 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
3395 22 ▶ unless !ref $r{min_depth} && $r{min_depth} =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/ 2 20 22
Condition66%2/3
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
0220
MC/DC50%1/2
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
not ref $r{"min_depth"} $r{"min_depth"} =~ /\A[0-9]+\z/
Truth table66%2/3
not(A) and B
A= not ref $r{"min_depth"}B= $r{"min_depth"} =~ /\A[0-9]+\z/
ABresult
0X0
100
111
3396 20 ▶ $r{report} = $args->{report} // 1; # 1 = print a table of the samples to STDOUT; 0 = only return them
Condition100%2/2
$args->{"report"} // 1
l!l
164
MC/DC100%1/1
$args->{"report"} // 1
$args->{"report"}
Truth table100%2/2
A
A= $args->{"report"}
Aresult
11
00
3397 20 ▶ croak "$sub: \"report\" must be 0 or 1, not " . _what($r{report}) unless !ref $r{report} && ($r{report} eq '0' || $r{report} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1 1 19 20
Condition83%5/6
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
!ll&&!rl&&r
0119
$r{"report"} eq 0 or $r{"report"} eq 1
l!l&&r!l&&!r
1541
MC/DC66%2/3
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
not ref $r{"report"} $r{"report"} eq 0 $r{"report"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"report"}B= $r{"report"} eq 0C= $r{"report"} eq 1
ABCresult
0XX0
1000
11X1
1011
3398 19 $r{file} = $args->{file}; # undef = no CSV is written
3399 19 ▶ croak "$sub: \"file\" must be a file name, not " . _what($r{file}) if defined $r{file} && ref $r{file};
Branch: 1 branch
BranchTrueFalseTotal
if defined $r{"file"} and ref $r{"file"} 1 18 19
Condition100%3/3
defined $r{"file"} and ref $r{"file"}
!ll&&!rl&&r
1711
MC/DC100%2/2
defined $r{"file"} and ref $r{"file"}
defined $r{"file"} ref $r{"file"}
Truth table100%3/3
A and B
A= defined $r{"file"}B= ref $r{"file"}
ABresult
0X0
100
111
3400 croak "$sub: \"build\" must be hg19, b37, hg38 or b38, not " . _what($args->{build})
3401 18 ▶ if defined $args->{build} && (ref $args->{build} || $args->{build} !~ /\A(?:hg19|b37|hg38|b38)\z/);
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"build"} and ref $args->{"build"} || !($args->{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/) 1 17 18
Condition83%5/6
defined $args->{"build"} and ref $args->{"build"} || !($args->{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/)
!ll&&!rl&&r
1071
ref $args->{"build"} or not $args->{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/
l!l&&r!l&&!r
017
MC/DC66%2/3
defined $args->{"build"} and ref $args->{"build"} || !($args->{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/)
defined $args->{"build"} ref $args->{"build"} not $args->{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/
Truth table75%3/4
A and B or not(C)
A= defined $args->{"build"}B= ref $args->{"build"}C= not $args->{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/
ABCresult
0XX0
1000
11X1
1011
3402 17 my $vcf = $args->{vcf};
3403 17 _vcf_check($sub, 'vcf', $vcf);
3404 15 my $panel = _hirisplex_panel($sub);
3405 # which of the panel's two sets of coordinates the markers are looked for
3406 # at; undef when matching by rs number, which needs neither
3407 $r{build} = $r{match} eq 'id' ? undef
3408 15 ▶ : defined $args->{build} ? ($args->{build} =~ /\A(?:hg19|b37)\z/ ? 'b37' : 'b38')
Branch: 3 branches
BranchTrueFalseTotal
$r{'match'} eq 'id' ? : 3 12 15
defined $args->{'build'} ? : 7 5 12
$args->{'build'} =~ /\A(?:hg19|b37)\z/ ? : 7 0 7
3409 : _hirisplex_build($sub, $vcf);
3410  
3411 # What the reader searches for: one entry for each marker, and for matching
3412 # by rs number a second under the number that marker's has been merged
3413 # into, since a VCF annotated from either dbSNP release should match.
3414 13 my @entries;
3415 13 foreach my $k (0 .. $#{ $panel }) {
3416 533 my $m = $panel->[$k];
3417 533 ▶ my $insertion = $m->{kind} eq 'insertion' ? 1 : 0; # 1 = count the ALT longer than REF, 0 = count count_allele
Branch: 1 branch
BranchTrueFalseTotal
$m->{'kind'} eq 'insertion' ? : 13 520 533
3418 533 ▶ if ($r{match} eq 'id') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{'match'} eq 'id') { } 123 410 533
3419 123 my %seen;
3420 123 ▶ foreach my $id (grep { defined $_ && length $_ && !$seen{$_}++ } $m->{rsid}, $m->{current_rsid}) {
Condition50%3/6
defined $_ && length $_ && !$seen{$_}++
!ll&&!rl&&r
0120126
defined $_ and length $_
!ll&&!rl&&r
00246
MC/DC33%1/3
defined $_ && length $_ && !$seen{$_}++
defined $_ length $_ !$seen{$_}++
Truth table50%2/4
A and B && not(C)
A= defined $_B= length $_C= !$seen{$_}++
ABCresult
0XX0
10X0
1100
1111
3421 126 push @entries, [0, 0, $m->{count_allele}, $insertion, $id, $k];
3422 }
3423 } else {
3424 410 my ($c, $p) = @{ $m }{"$r{build}_chrom", "$r{build}_pos"};
3425 # a marker the panel could not place on this build is searched for
3426 # nowhere, and comes back as one the file did not hold
3427 410 ▶ next unless defined $c && length $c;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $c and length $c 0 410 410
Condition33%1/3
defined $c and length $c
!ll&&!rl&&r
00410
MC/DC0%0/2
defined $c and length $c
defined $c length $c
Truth table33%1/3
A and B
A= defined $cB= length $c
ABresult
0X0
100
111
3428 410 push @entries, [$c, $p, $m->{count_allele}, $insertion, $m->{rsid}, $k];
3429 }
3430 }
3431 13 ▶ croak "$sub: no marker of the panel has a " . ($r{build} // 'known') . ' position' unless @entries;
Branch: 1 branch
BranchTrueFalseTotal
unless @entries 0 13 13
Condition0%0/2
$r{"build"} // "known"
l!l
00
MC/DC0%0/1
$r{"build"} // "known"
$r{"build"}
Truth table0%0/2
A
A= $r{"build"}
Aresult
11
00
3432  
3433 13 my ($next, $close) = _vcf_open($sub, 'vcf', $vcf);
3434 13 ▶ my ($dose, $names, $seen) = _located(sub { _hirisplex_dosage($next, $vcf, $r{min_depth}, \@entries, scalar @{ $panel }, $r{match} eq 'id' ? 1 : 0) });
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$r{'match'} eq 'id' ? : 3 10 13
3435 13 $close->();
3436  
3437 13 my @column = map { "$_->{rsid}_$_->{input_allele}" } @{ $panel };
3438 13 my @absent = map { $panel->[$_]{rsid} } grep { !$seen->[$_] } 0 .. $#{ $panel };
3439 13 my %out;
3440 13 foreach my $s (keys %{ $dose }) {
3441 28 my $d = $dose->{$s};
3442 28 my (%genotype, @missing);
3443 28 foreach my $k (0 .. $#{ $panel }) {
3444 1148 $genotype{ $column[$k] } = $d->[$k];
3445 1148 ▶ push @missing, $panel->[$k]{rsid} unless defined $d->[$k];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $d->[$k] 451 697 1148
3446 }
3447 28 my $can = _hirisplex_possible($panel, $d);
3448 $out{$s} = {
3449 genotype => \%genotype,
3450 missing => \@missing,
3451 28 markers => scalar @{ $panel },
3452 28 called => scalar(@{ $panel }) - scalar(@missing),
3453 28 %{ $can },
3454 };
3455 }
3456 13 ▶ _hirisplex_csv($sub, $r{file}, $panel, \%out, $names) if defined $r{file};
Branch: 1 branch
BranchTrueFalseTotal
if defined $r{"file"} 1 12 13
3457 13 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 0 13 13
3458 0 ▶ print STDOUT _hirisplex_report($vcf, \%r, $panel, \%out, $names, \@absent) or croak "$sub: can't print the report: $!";
Branch: 1 branch
BranchTrueFalseTotal
print STDOUT _hirisplex_report($vcf, \%r, $panel, \%out, $names, \@absent) or croak("${sub}: can't print the report: $!") 0 0 0
3459 }
3460 1 ▶ carp "$sub: \"vcf\" $vcf holds none of the " . scalar(@{ $panel }) . ' HIrisPlex-S markers'
Branch: 1 branch
BranchTrueFalseTotal
$r{'match'} eq 'id' ? : 1 0 1
3461 . ($r{match} eq 'id' ? '; it was matched by rs number, and a VCF whose ID column is "." matches nothing that way'
3462 : ", matched by position on $r{build}; check that it is the build the file is on")
3463 13 ▶ if @absent == @{ $panel };
Branch: 1 branch
BranchTrueFalseTotal
if @absent == @{$panel;} 1 12 13
3464 13 \%out;
3465 }
3466  
3467 # The marker that carries a category's intercept, in place of an rs number, in
3468 # a "model" table. A marker can't be called this, so nothing is ambiguous.
3469 40 my $Intercept = '(intercept)';
3470  
3471 # The rows of "model" read into trait => category => { marker => beta }, with
3472 # the intercept under $Intercept, and the traits and their categories in the
3473 # order the table first names them, which is the order the report prints.
3474 22 ▶sub _trait_model {
Subroutine _trait_model: called CC=15 SCAR=27.3
3475 22 my ($sub, $model) = @_;
3476 22 my ($next, $cols) = _weight_rows($sub, $model, 'model');
3477 18 my %have = map { $_ => 1 } @{ $cols };
3478 18 my @absent = grep { !$have{$_} } qw(trait category marker beta);
3479 18 ▶ croak "$sub: \"model\" has no " . join(', ', map { "\"$_\"" } @absent) . ' column' . (@absent > 1 ? 's' : '')
Branch: 2 branches
BranchTrueFalseTotal
if @absent 1 17 18
@absent > 1 ? : 1 0 1
3480 . '; a model table has trait, category, marker and beta' if @absent;
3481 17 my (%beta, @traits, %category);
3482 17 ▶ while (my ($row, $label) = $next->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$next()) 29766 13 29779
3483 29766 my ($t, $c, $m, $b) = @{ $row }{qw(trait category marker beta)};
3484 29766 foreach my $f (['trait', $t], ['category', $c], ['marker', $m]) {
3485 89298 ▶ croak "$sub: $label of \"model\" has no $f->[0]" unless defined $f->[1] && length $f->[1];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $f->[1] and length $f->[1] 1 89297 89298
Condition66%2/3
defined $f->[1] and length $f->[1]
!ll&&!rl&&r
0189297
MC/DC50%1/2
defined $f->[1] and length $f->[1]
defined $f->[1] length $f->[1]
Truth table66%2/3
A and B
A= defined $f->[1]B= length $f->[1]
ABresult
0X0
100
111
3486 }
3487 29765 ▶ croak "$sub: $label of \"model\" has beta " . _what($b) . ", which isn't a number"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $b and not ref $b and $b =~ /$Number/ 1 29764 29765
Condition50%3/6
defined $b and not ref $b and $b =~ /$Number/
!ll&&!rl&&r
0129764
defined $b and not ref $b
!ll&&!rl&&r
0029765
MC/DC33%1/3
defined $b and not ref $b and $b =~ /$Number/
defined $b not ref $b $b =~ /$Number/
Truth table50%2/4
A and not(B) and C
A= defined $bB= not ref $bC= $b =~ /$Number/
ABCresult
0XX0
10X0
1100
1111
3488 unless defined $b && !ref $b && $b =~ $Number;
3489 29764 ▶ push @traits, $t unless $beta{$t};
Branch: 1 branch
BranchTrueFalseTotal
unless $beta{$t} 18 29746 29764
3490 29764 ▶ push @{ $category{$t} }, $c unless $beta{$t} && $beta{$t}{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $beta{$t} and $beta{$t}{$c} 33 29731 29764
Condition100%3/3
$beta{$t} and $beta{$t}{$c}
!ll&&!rl&&r
181529731
MC/DC100%2/2
$beta{$t} and $beta{$t}{$c}
$beta{$t} $beta{$t}{$c}
Truth table100%3/3
A and B
A= $beta{$t}B= $beta{$t}{$c}
ABresult
0X0
100
111
3491 croak "$sub: $label of \"model\" gives $t category \"$c\" a second beta for $m"
3492 29764 ▶ if exists $beta{$t}{$c}{$m};
Branch: 1 branch
BranchTrueFalseTotal
if exists $beta{$t}{$c}{$m} 1 29763 29764
3493 29763 $beta{$t}{$c}{$m} = $b;
3494 }
3495 13 ▶ croak "$sub: \"model\" has no rows" unless @traits;
Branch: 1 branch
BranchTrueFalseTotal
unless @traits 0 13 13
3496 13 (\%beta, \@traits, \%category);
3497 }
3498  
3499 # exp() of each of @$eta, divided by their sum: the probabilities a multinomial
3500 # logistic regression gives its categories. The largest is taken out first, so
3501 # that a linear predictor big enough to overflow exp() (about 710 on an IEEE
3502 # double, and larger on a long-double or quadmath perl) gives 1 and the rest 0
3503 # rather than inf/inf, which is NaN.
3504 22 ▶sub _softmax {
Subroutine _softmax: called CC=4 SCAR=13.9
3505 22 my ($eta) = @_;
3506 22 my $max = $eta->[0];
3507 22 ▶ foreach my $e (@{ $eta }) { $max = $e if $e > $max }
Branch: 1 branch
BranchTrueFalseTotal
if $e > $max 13 35 48
3508 22 my @exp = map { exp($_ - $max) } @{ $eta };
3509 22 my $sum = 0;
3510 22 $sum += $_ foreach @exp;
3511 22 [map { $_ / $sum } @exp];
3512 }
3513  
3514 # trait_predict's report on $out: a table of each sample's probabilities, one
3515 # block for each trait, the categories in the model's order.
3516 0 ▶sub _trait_report {
Subroutine _trait_report: not called CC=10 SCAR=47.0
3517 0 my ($r, $out, $order, $traits, $category) = @_;
3518 0 ▶ my $text = "trait_predict: " . scalar(@{ $order }) . ' sample' . (@{ $order } > 1 ? 's' : '')
Branch: 1 branch
BranchTrueFalseTotal
@{$order;} > 1 ? : 0 0 0
3519 0 ▶ . ', ' . scalar(@{ $traits }) . ' trait' . (@{ $traits } > 1 ? 's' : '')
Branch: 2 branches
BranchTrueFalseTotal
@{$traits;} > 1 ? : 0 0 0
$r->{'force'} ? : 0 0 0
3520 . "; a marker the sample has no genotype for counts as 0 copies"
3521 0 . ($r->{force} ? ', and a prediction the HIrisPlex-S rules refuse is made anyway ("force")' : '') . "\n";
3522 0 foreach my $t (@{ $traits }) {
3523 0 my @head = ('sample', 'call', @{ $category->{$t} }, 'called');
3524 my @rows = map {
3525 0 my $p = $out->{$_}{$t};
3526 0 ▶ [$_, $p->{call} // '-', (map { defined $p->{p}{$_} ? sprintf('%.3f', $p->{p}{$_}) : '-' } @{ $category->{$t} }),
Branch: 1 branch
BranchTrueFalseTotal
defined $p->{'p'}{$_} ? : 0 0 0
Condition0%0/2
$p->{"call"} // "-"
l!l
00
MC/DC0%0/1
$p->{"call"} // "-"
$p->{"call"}
Truth table0%0/2
A
A= $p->{"call"}
Aresult
11
00
3527 "$p->{called}/$p->{markers}"]
3528 0 } @{ $order };
3529 0 my @w = map { length $head[$_] } 0 .. $#head;
3530 0 foreach my $row (@rows) {
3531 0 foreach my $i (0 .. $#head) {
3532 0 ▶ $w[$i] = length $row->[$i] if length $row->[$i] > $w[$i];
Branch: 1 branch
BranchTrueFalseTotal
if length $row->[$i] > $w[$i] 0 0 0
3533 }
3534 }
3535 0 ▶ my $line = sub { join(' ', map { $_ == 0 ? sprintf('%-*s', $w[$_], $_[$_]) : sprintf('%*s', $w[$_], $_[$_]) } 0 .. $#head) . "\n" };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
$_ == 0 ? : 0 0 0
3536 0 $text .= "\n$t\n" . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows);
3537 0 my @refused = grep { defined $out->{$_}{$t}{refused} } @{ $order };
3538 0 $text .= join '', map { " $_: no $t prediction: $out->{$_}{$t}{refused}\n" } @refused;
3539 }
3540 0 $text;
3541 }
3542  
3543 26 ▶sub trait_predict {
Subroutine trait_predict: called CC=40 SCAR=37.1
Pod documented
3544 26 my $sub = 'trait_predict';
3545 26 my $args = _args(\@_, $sub, [qw(genotypes model)], [qw(force report)]);
3546 25 my %r;
3547 25 ▶ $r{force} = $args->{force} // 0; # 0 = a trait the genotypes say can't be predicted isn't; 1 = predict it anyway
Condition100%2/2
$args->{"force"} // 0
l!l
223
MC/DC100%1/1
$args->{"force"} // 0
$args->{"force"}
Truth table100%2/2
A
A= $args->{"force"}
Aresult
11
00
3548 25 ▶ croak "$sub: \"force\" must be 0 or 1, not " . _what($r{force}) unless !ref $r{force} && ($r{force} eq '0' || $r{force} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"force"} and $r{"force"} eq 0 || $r{"force"} eq 1 1 24 25
Condition83%5/6
not ref $r{"force"} and $r{"force"} eq 0 || $r{"force"} eq 1
!ll&&!rl&&r
0124
$r{"force"} eq 0 or $r{"force"} eq 1
l!l&&r!l&&!r
2311
MC/DC66%2/3
not ref $r{"force"} and $r{"force"} eq 0 || $r{"force"} eq 1
not ref $r{"force"} $r{"force"} eq 0 $r{"force"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"force"}B= $r{"force"} eq 0C= $r{"force"} eq 1
ABCresult
0XX0
1000
11X1
1011
3549 24 ▶ $r{report} = $args->{report} // 1; # 1 = print a table of the samples to STDOUT; 0 = only return them
Condition100%2/2
$args->{"report"} // 1
l!l
1212
MC/DC100%1/1
$args->{"report"} // 1
$args->{"report"}
Truth table100%2/2
A
A= $args->{"report"}
Aresult
11
00
3550 24 ▶ croak "$sub: \"report\" must be 0 or 1, not " . _what($r{report}) unless !ref $r{report} && ($r{report} eq '0' || $r{report} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1 0 24 24
Condition50%3/6
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
!ll&&!rl&&r
0024
$r{"report"} eq 0 or $r{"report"} eq 1
l!l&&r!l&&!r
12120
MC/DC0%0/3
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
not ref $r{"report"} $r{"report"} eq 0 $r{"report"} eq 1
Truth table50%2/4
not(A) and B or C
A= not ref $r{"report"}B= $r{"report"} eq 0C= $r{"report"} eq 1
ABCresult
0XX0
1000
11X1
1011
3551 24 my $g = $args->{genotypes};
3552 24 ▶ croak "$sub: \"genotypes\" must be a hash ref of sample => genotypes, as hirisplex_genotypes returns, not " . _what($g)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $g eq "HASH" 1 23 24
3553 unless ref $g eq 'HASH';
3554 23 ▶ croak "$sub: \"genotypes\" has no samples" unless keys %{ $g };
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$g;} 1 22 23
3555 22 my ($beta, $traits, $category) = _trait_model($sub, $args->{model});
3556  
3557 # Which markers each trait's categories use between them: the same for every
3558 # sample, so it is worked out once rather than once per sample.
3559 13 my %uses;
3560 13 foreach my $t (@{ $traits }) {
3561 16 foreach my $c (@{ $category->{$t} }) {
3562 31 $uses{$t}{$_} = 1 foreach grep { $_ ne $Intercept } keys %{ $beta->{$t}{$c} };
3563 }
3564 }
3565 13 my %used = map { %{ $uses{$_} } } keys %uses; # every trait's markers, whose dosages are checked
3566  
3567 13 my %out;
3568 13 foreach my $s (sort keys %{ $g }) {
3569 19 my $rec = $g->{$s};
3570 19 ▶ croak "$sub: \"genotypes\" sample \"$s\" must be a hash ref, not " . _what($rec) unless ref $rec eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rec eq "HASH" 1 18 19
3571 # Either what hirisplex_genotypes returns, whose genotypes are under
3572 # "genotype" and which also says which predictions its markers allow,
3573 # or a plain hash of marker => dosage.
3574 18 ▶ my $dose = ref $rec->{genotype} eq 'HASH' ? $rec->{genotype} : $rec;
Branch: 1 branch
BranchTrueFalseTotal
ref $rec->{'genotype'} eq 'HASH' ? : 9 9 18
3575 # A dosage may be fractional, as imputation gives, but anything else
3576 # would be multiplied in as 0 copies and counted as called.
3577 18 foreach my $m (sort keys %used) {
3578 20033 my $d = $dose->{$m};
3579 20033 ▶ croak "$sub: \"genotypes\" sample \"$s\" has $m " . _what($d) . ", which isn't a dosage from 0 to 2; a missing genotype is undef"
Branch: 1 branch
BranchTrueFalseTotal
unless not defined $d or not ref $d and $d =~ /$Number/ and $d >= 0 and $d <= 2 4 20029 20033
Condition100%12/12
not defined $d or not ref $d and $d =~ /$Number/ and $d >= 0 and $d <= 2
l!l&&r!l&&!r
20004254
not ref $d and $d =~ /$Number/ and $d >= 0 and $d <= 2
!ll&&!rl&&r
3125
not ref $d and $d =~ /$Number/ and $d >= 0
!ll&&!rl&&r
2126
not ref $d and $d =~ /$Number/
!ll&&!rl&&r
1127
MC/DC100%5/5
not defined $d or not ref $d and $d =~ /$Number/ and $d >= 0 and $d <= 2
not defined $d not ref $d $d =~ /$Number/ $d >= 0 $d <= 2
Truth table100%6/6
not(A) or not(B) and C and D and E
A= not defined $dB= not ref $dC= $d =~ /$Number/D= $d >= 0E= $d <= 2
ABCDEresult
1XXXX1
011111
00XXX0
010XX0
0110X0
011100
3580 unless !defined $d || (!ref $d && $d =~ $Number && $d >= 0 && $d <= 2);
3581 }
3582 14 foreach my $t (@{ $traits }) {
3583 23 my (@eta, @missing);
3584 23 my $called = 0;
3585 23 my $marker = $uses{$t};
3586 23 foreach my $m (sort keys %{ $marker }) {
3587 20029 ▶ if (defined $dose->{$m}) { $called++ } else { push @missing, $m }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $dose->{$m}) { } 25 20004 20029
3588 }
3589 23 foreach my $c (@{ $category->{$t} }) {
3590 51 ▶ my $eta = $beta->{$t}{$c}{$Intercept} // 0;
Condition100%2/2
$beta->{$t}{$c}{$Intercept} // 0
l!l
501
MC/DC100%1/1
$beta->{$t}{$c}{$Intercept} // 0
$beta->{$t}{$c}{$Intercept}
Truth table100%2/2
A
A= $beta->{$t}{$c}{$Intercept}
Aresult
11
00
3591 51 foreach my $m (keys %{ $beta->{$t}{$c} }) {
3592 20088 ▶ next if $m eq $Intercept;
Branch: 1 branch
BranchTrueFalseTotal
if $m eq $Intercept 50 20038 20088
3593 # A marker with no genotype drops out of the sum, which is
3594 # the same as counting it 0 copies of the counted allele.
3595 20038 ▶ $eta += $beta->{$t}{$c}{$m} * $dose->{$m} if defined $dose->{$m};
Branch: 1 branch
BranchTrueFalseTotal
if defined $dose->{$m} 32 20006 20038
3596 }
3597 51 push @eta, $eta;
3598 }
3599 # hirisplex_genotypes sets eye, hair and skin to 0 where the
3600 # HIrisPlex-S manual refuses the prediction outright; a model whose
3601 # trait it says nothing about is predicted whatever it holds.
3602 23 ▶ my $refused = !$r{force} && defined $rec->{$t} && !ref $rec->{$t} && $rec->{$t} eq '0'
Branch: 1 branch
BranchTrueFalseTotal
!$r{'force'} && defined $rec->{$t} && !ref($rec->{$t}) && $rec->{$t} eq '0' ? : 1 22 23
Condition88%8/9
not $r{"force"} and defined $rec->{$t} and not ref $rec->{$t} and $rec->{$t} eq 0
!ll&&!rl&&r
1931
not $r{"force"} and defined $rec->{$t} and not ref $rec->{$t}
!ll&&!rl&&r
1904
not $r{"force"} and defined $rec->{$t}
!ll&&!rl&&r
8114
MC/DC75%3/4
not $r{"force"} and defined $rec->{$t} and not ref $rec->{$t} and $rec->{$t} eq 0
not $r{"force"} defined $rec->{$t} not ref $rec->{$t} $rec->{$t} eq 0
Truth table80%4/5
not(A) and B and not(C) and D
A= not $r{"force"}B= defined $rec->{$t}C= not ref $rec->{$t}D= $rec->{$t} eq 0
ABCDresult
0XXX0
10XX0
110X0
11100
11111
3603 ? 'the markers it needs are missing, and the HIrisPlex-S rules refuse it' : undef;
3604 23 ▶ my $p = $refused ? {} : do {
Branch: 1 branch
BranchTrueFalseTotal
$refused ? : 1 22 23
3605 22 my $soft = _softmax(\@eta);
3606 22 my %p;
3607 22 @p{ @{ $category->{$t} } } = @{ $soft };
3608 22 \%p;
3609 };
3610 23 ▶ my ($call) = $refused ? () : sort { $p->{$b} <=> $p->{$a} || $a cmp $b } keys %{ $p };
Branch: 1 branch
BranchTrueFalseTotal
$refused ? : 1 22 23
Condition66%2/3
$p->{$b} <=> $p->{$a} || $a cmp $b
l!l&&r!l&&!r
3110
MC/DC0%0/2
$p->{$b} <=> $p->{$a} || $a cmp $b
$p->{$b} <=> $p->{$a} $a cmp $b
Truth table66%2/3
A || B
A= $p->{$b} <=> $p->{$a}B= $a cmp $b
ABresult
1X1
011
000
3611 $out{$s}{$t} = {
3612 p => $p,
3613 call => $call,
3614 23 markers => scalar keys %{ $marker },
3615 called => $called,
3616 missing => \@missing,
3617 refused => $refused,
3618 };
3619 }
3620 }
3621 8 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 0 8 8
3622 0 ▶ print STDOUT _trait_report(\%r, \%out, [sort keys %out], $traits, $category) or croak "$sub: can't print the report: $!";
Branch: 1 branch
BranchTrueFalseTotal
print STDOUT _trait_report(\%r, \%out, [sort(keys %out)], $traits, $category) or croak("${sub}: can't print the report: $!") 0 0 0
3623 }
3624 8 \%out;
3625 }
3626  
3627 # ---- blood type
3628  
3629 # The panel blood_type reads, share/blood_type_panel.tsv, once it has been
3630 # read: a hash ref of
3631 #
3632 # markers every marker, a hash ref a row, in the file's order, which is
3633 # the order Bioinf.xs returns their genotypes in
3634 # abo role => the marker's place in "markers", for the three of ABO:
3635 # "functional" (rs8176719, where the insertion counted is a
3636 # working A or B gene and its lack is O), "B" and "O2"
3637 # sites the places in "markers" of RHD's sites
3638 # gene the row of the RHD gene, whose span a deletion has to cover
3639 #
3640 # share/make_blood_type_panel.pl writes the file, and its header comment says
3641 # where every row comes from and what was measured. The counted allele of
3642 # every marker is an ALT on both builds, never the reference's own, which is
3643 # what lets a marker with no record be read as no copies of it.
3644 40 my $Blood_panel; # undef until the file has been read
3645  
3646 33 ▶sub _blood_panel {
Subroutine _blood_panel: called CC=27 SCAR=36.4
3647 33 my ($sub) = @_;
3648 33 ▶ return $Blood_panel if $Blood_panel;
Branch: 1 branch
BranchTrueFalseTotal
if $Blood_panel 31 2 33
3649 2 my $file = _share_file($sub, 'blood_type_panel.tsv');
3650 2 ▶ open my $fh, '<', $file or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or croak("${sub}: can't read ${file}: $!") 2 0 2
3651 2 my $head = <$fh>;
3652 2 ▶ croak "$sub: marker panel $file is empty" unless defined $head;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $head 0 2 2
3653 2 $head =~ s/\r?\n\z//;
3654 2 $head =~ s/\A#//;
3655 2 my @cols = split /\t/, $head, -1;
3656 2 my %panel = (markers => [], abo => {}, sites => [], gene => undef);
3657 2 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 38 2 40
3658 38 $line =~ s/\r?\n\z//;
3659 38 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 38 38
3660 38 my %m;
3661 38 @m{@cols} = split /\t/, $line, -1;
3662 38 foreach my $c (qw(name system role kind)) {
3663 152 ▶ croak "$sub: row " . ($m{name} // '?') . " of $file has no $c" unless defined $m{$c} && length $m{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $m{$c} and length $m{$c} 0 152 152
Condition20%1/5
defined $m{$c} and length $m{$c}
!ll&&!rl&&r
00152
$m{"name"} // "?"
l!l
00
MC/DC0%0/2
defined $m{$c} and length $m{$c}
defined $m{$c} length $m{$c}
MC/DC0%0/1
$m{"name"} // "?"
$m{"name"}
Truth table33%1/3
A and B
A= defined $m{$c}B= length $m{$c}
ABresult
0X0
100
111
Truth table0%0/2
A
A= $m{"name"}
Aresult
11
00
3664 }
3665 38 foreach my $b (qw(b37 b38)) {
3666 # vcf_chrom()'s numbering, which the panel's two chromosomes, 1 and 9, are already in
3667 croak "$sub: row $m{name} of $file is on $b chromosome " . _what($m{"${b}_chrom"}) . ', which isn\'t an autosome'
3668 76 ▶ unless defined $m{"${b}_chrom"} && $m{"${b}_chrom"} =~ /\A(?:[1-9]|1[0-9]|2[0-2])\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $m{"${b}_chrom"} and $m{"${b}_chrom"} =~ /\A(?:[1-9]|1[0-9]|2[0-2])\z/ 0 76 76
Condition33%1/3
defined $m{"${b}_chrom"} and $m{"${b}_chrom"} =~ /\A(?:[1-9]|1[0-9]|2[0-2])\z/
!ll&&!rl&&r
0076
MC/DC0%0/2
defined $m{"${b}_chrom"} and $m{"${b}_chrom"} =~ /\A(?:[1-9]|1[0-9]|2[0-2])\z/
defined $m{"${b}_chrom"} $m{"${b}_chrom"} =~ /\A(?:[1-9]|1[0-9]|2[0-2])\z/
Truth table33%1/3
A and B
A= defined $m{"${b}_chrom"}B= $m{"${b}_chrom"} =~ /\A(?:[1-9]|1[0-9]|2[0-2])\z/
ABresult
0X0
100
111
3669 76 ▶ foreach my $c ("${b}_pos", $m{kind} eq 'region' ? "${b}_end" : ()) {
Branch: 1 branch
BranchTrueFalseTotal
$m{'kind'} eq 'region' ? : 4 72 76
3670 croak "$sub: row $m{name} of $file has $c " . _what($m{$c}) . ', which isn\'t a position'
3671 80 ▶ unless defined $m{$c} && $m{$c} =~ /\A[1-9][0-9]*\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $m{$c} and $m{$c} =~ /\A[1-9][0-9]*\z/ 0 80 80
Condition33%1/3
defined $m{$c} and $m{$c} =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
0080
MC/DC0%0/2
defined $m{$c} and $m{$c} =~ /\A[1-9][0-9]*\z/
defined $m{$c} $m{$c} =~ /\A[1-9][0-9]*\z/
Truth table33%1/3
A and B
A= defined $m{$c}B= $m{$c} =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
3672 }
3673 }
3674 38 ▶ if ($m{kind} eq 'region') {
Branch: 1 branch
BranchTrueFalseTotal
if ($m{"kind"} eq "region") 2 36 38
3675 2 ▶ croak "$sub: $file has more than one gene" if $panel{gene};
Branch: 1 branch
BranchTrueFalseTotal
if $panel{"gene"} 0 2 2
3676 2 $panel{gene} = \%m;
3677 2 next;
3678 }
3679 croak "$sub: marker $m{name} of $file counts " . _what($m{count_allele}) . ', which isn\'t one base'
3680 36 ▶ unless defined $m{count_allele} && $m{count_allele} =~ /\A[ACGT]\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $m{"count_allele"} and $m{"count_allele"} =~ /\A[ACGT]\z/ 0 36 36
Condition33%1/3
defined $m{"count_allele"} and $m{"count_allele"} =~ /\A[ACGT]\z/
!ll&&!rl&&r
0036
MC/DC0%0/2
defined $m{"count_allele"} and $m{"count_allele"} =~ /\A[ACGT]\z/
defined $m{"count_allele"} $m{"count_allele"} =~ /\A[ACGT]\z/
Truth table33%1/3
A and B
A= defined $m{"count_allele"}B= $m{"count_allele"} =~ /\A[ACGT]\z/
ABresult
0X0
100
111
3681 36 push @{ $panel{markers} }, \%m;
3682 36 ▶ if ($m{system} eq 'ABO') {
Branch: 1 branch
BranchTrueFalseTotal
if ($m{'system'} eq 'ABO') { } 6 30 36
3683 6 $panel{abo}{ $m{role} } = $#{ $panel{markers} };
3684 } else {
3685 30 push @{ $panel{sites} }, $#{ $panel{markers} };
3686 }
3687 }
3688 2 ▶ close $fh or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't read ${file}: $!") 2 0 2
3689 2 ▶ croak "$sub: marker panel $file has no RHD gene" unless $panel{gene};
Branch: 1 branch
BranchTrueFalseTotal
unless $panel{"gene"} 0 2 2
3690 2 ▶ croak "$sub: marker panel $file has no site of RHD" unless @{ $panel{sites} };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$panel{"sites"};} 0 2 2
3691 2 foreach my $role (qw(functional B O2)) {
3692 6 ▶ croak "$sub: marker panel $file has no ABO marker of role \"$role\"" unless defined $panel{abo}{$role};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $panel{"abo"}{$role} 0 6 6
3693 }
3694 2 $Blood_panel = \%panel;
3695 }
3696  
3697 # The ABO genotype and phenotype that $n says, a hash ref of how many copies
3698 # (0 to 2, or undef for no genotype) a sample has of each of the three ABO
3699 # markers' counted alleles, by role: (genotype, phenotype, undef), or (undef,
3700 # undef, the role whose genotype was needed and is missing).
3701 #
3702 # A chromosome without rs8176719's insertion is O whatever else it carries. One
3703 # with it is B when it carries rs8176746's T, O when it carries rs41302905's T
3704 # (the O2 allele, an O with no deletion), and otherwise A. The genotypes are
3705 # not phased, so a B or O2 allele is taken to be on a chromosome that has the
3706 # insertion, as long as there is one to put it on. That is nearly always
3707 # right: of 1000 Genomes phase 3's 5,008 haplotypes (b37 BCF, read
3708 # 2026-11-10), 721 carried the insertion with the B allele, 1,001 the
3709 # insertion without it, 44 the B allele without the insertion and 3,242
3710 # neither, so somebody heterozygous at both is B and O rather than A and an O
3711 # that carries B's base with a probability of 721 * 3242 / (721 * 3242 + 1001
3712 # * 44), which is 0.981.
3713 140 ▶sub _abo_type {
Subroutine _abo_type: called CC=11 SCAR=24.0
3714 140 my ($n) = @_;
3715 140 ▶ return (undef, undef, 'functional') unless defined $n->{functional};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n->{"functional"} 37 103 140
3716 103 my $working = $n->{functional}; # chromosomes with a working gene, A or B, unless they are O2
3717 103 my ($b, $o2) = (0, 0);
3718 103 ▶ if ($working) {
Branch: 1 branch
BranchTrueFalseTotal
if ($working) 87 16 103
3719 87 foreach my $role (qw(B O2)) {
3720 166 ▶ return (undef, undef, $role) unless defined $n->{$role};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n->{$role} 8 158 166
3721 }
3722 79 ▶ $b = $n->{B} < $working ? $n->{B} : $working;
Branch: 1 branch
BranchTrueFalseTotal
$n->{'B'} < $working ? : 47 32 79
3723 79 ▶ $o2 = $n->{O2} < $working - $b ? $n->{O2} : $working - $b;
Branch: 1 branch
BranchTrueFalseTotal
$n->{'O2'} < $working - $b ? : 33 46 79
3724 }
3725 95 my %count = (A => $working - $b - $o2, B => $b, O => 2 - $working + $o2);
3726 95 my $genotype = join '', map { $_ x $count{$_} } qw(A B O);
3727 95 ▶ my $phenotype = $count{A} && $count{B} ? 'AB' : $count{A} ? 'A' : $count{B} ? 'B' : 'O';
Branch: 3 branches
BranchTrueFalseTotal
$count{'A'} && $count{'B'} ? : 7 88 95
$count{'A'} ? : 26 62 88
$count{'B'} ? : 39 23 62
Condition100%3/3
$count{"A"} and $count{"B"}
!ll&&!rl&&r
62267
MC/DC100%2/2
$count{"A"} and $count{"B"}
$count{"A"} $count{"B"}
Truth table100%3/3
A and B
A= $count{"A"}B= $count{"B"}
ABresult
0X0
100
111
3728 95 ($genotype, $phenotype, undef);
3729 }
3730  
3731 # blood_type's report on $vcf: what was read and how, a table of the samples in
3732 # $order, the VCF's, then what was taken as homozygous REF because the file has
3733 # no record of it, and why any sample has no type.
3734 3 ▶sub _blood_report {
Subroutine _blood_report: called CC=14 SCAR=26.4
3735 3 my ($vcf, $r, $panel, $out, $order, $assumed) = @_;
3736 3 my $sites = scalar @{ $panel->{sites} };
3737 3 my @head = ('sample', 'type', 'ABO', 'ABO genotype', 'RhD', 'RhD genotype', 'RHD sites');
3738 my @rows = map {
3739 18 my $s = $out->{$_};
3740 [$_, $s->{type} // '-', $s->{abo}{phenotype} // '-', $s->{abo}{genotype} // '-',
3741 18 ▶ $s->{rhesus}{phenotype} // '-', $s->{rhesus}{genotype} // '-', "$s->{rhesus}{carried}/$sites"]
Condition100%10/10
$s->{"type"} // "-"
l!l
126
$s->{"abo"}{"phenotype"} // "-"
l!l
144
$s->{"abo"}{"genotype"} // "-"
l!l
144
$s->{"rhesus"}{"phenotype"} // "-"
l!l
162
$s->{"rhesus"}{"genotype"} // "-"
l!l
162
MC/DC100%1/1
$s->{"type"} // "-"
$s->{"type"}
MC/DC100%1/1
$s->{"abo"}{"phenotype"} // "-"
$s->{"abo"}{"phenotype"}
MC/DC100%1/1
$s->{"abo"}{"genotype"} // "-"
$s->{"abo"}{"genotype"}
MC/DC100%1/1
$s->{"rhesus"}{"phenotype"} // "-"
$s->{"rhesus"}{"phenotype"}
MC/DC100%1/1
$s->{"rhesus"}{"genotype"} // "-"
$s->{"rhesus"}{"genotype"}
Truth table100%2/2
A
A= $s->{"type"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"abo"}{"phenotype"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"abo"}{"genotype"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"rhesus"}{"phenotype"}
Aresult
11
00
Truth table100%2/2
A
A= $s->{"rhesus"}{"genotype"}
Aresult
11
00
3742 3 } @{ $order };
3743 3 my @w = map { length $head[$_] } 0 .. $#head;
3744 3 foreach my $row (@rows) {
3745 18 foreach my $i (0 .. $#head) {
3746 126 ▶ $w[$i] = length $row->[$i] if length $row->[$i] > $w[$i];
Branch: 1 branch
BranchTrueFalseTotal
if length $row->[$i] > $w[$i] 3 123 126
3747 }
3748 }
3749 3 ▶ my $line = sub { join(' ', map { $_ < $#head ? sprintf('%-*s', $w[$_], $_[$_]) : sprintf('%*s', $w[$_], $_[$_]) } 0 .. $#head) . "\n" };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_ < $#head ? : 126 21 147
3750 3 my @why; # one line for each system of each sample that has no type
3751 3 foreach my $name (@{ $order }) {
3752 18 foreach my $system (qw(abo rhesus)) {
3753 36 my $why = $out->{$name}{$system}{why};
3754 36 ▶ push @why, "$name has no " . ($system eq 'abo' ? 'ABO' : 'RhD') . " type: $why\n" if defined $why;
Branch: 2 branches
BranchTrueFalseTotal
if defined $why 6 30 36
$system eq 'abo' ? : 4 2 6
3755 }
3756 }
3757 "blood_type: $vcf\n"
3758 . "ABO from rs8176719 (O's deletion), rs8176746 (B) and rs41302905 (O2); RhD from $sites sites of RHD, or a record of the gene's deletion;"
3759 . " matched by position on $r->{build}; genotypes of DP below $r->{min_depth} not counted\n"
3760 18 ▶ . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows)
Branch: 1 branch
BranchTrueFalseTotal
@{$assumed;} ? : 2 1 3
3761 . "\"RHD sites\" is how many of the sites the sample has an ALT allele at; one is enough for RhD positive\n"
3762 3 . (@{ $assumed } ? 'not in the file, and taken as homozygous for the reference allele: ' . join(', ', @{ $assumed }) . "\n" : '')
3763 . join('', @why);
3764 }
3765  
3766 46 ▶sub blood_type {
Subroutine blood_type: called CC=53 SCAR=39.7
Pod documented
3767 46 my $sub = 'blood_type';
3768 # blood_type($file) and blood_type($file, %options) take the file first,
3769 # as sex_check does; an odd count whose first is an option's name is left
3770 # for _args to refuse
3771 46 ▶ unshift @_, 'vcf' if @_ % 2 && defined $_[0] && !ref $_[0] && $_[0] !~ /\A(?:vcf|assume_ref|build|min_depth|report)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 and defined $_[0] and not ref $_[0] and not $_[0] =~ /\A(?:vcf|assume_ref|build|min_depth|report)\z/ 2 44 46
Condition77%7/9
@_ % 2 and defined $_[0] and not ref $_[0] and not $_[0] =~ /\A(?:vcf|assume_ref|build|min_depth|report)\z/
!ll&&!rl&&r
4402
@_ % 2 and defined $_[0] and not ref $_[0]
!ll&&!rl&&r
4312
@_ % 2 and defined $_[0]
!ll&&!rl&&r
4303
MC/DC50%2/4
@_ % 2 and defined $_[0] and not ref $_[0] and not $_[0] =~ /\A(?:vcf|assume_ref|build|min_depth|report)\z/
@_ % 2 defined $_[0] not ref $_[0] not $_[0] =~ /\A(?:vcf|assume_ref|build|min_depth|report)\z/
Truth table60%3/5
A and B and not(C) and not(D)
A= @_ % 2B= defined $_[0]C= not ref $_[0]D= not $_[0] =~ /\A(?:vcf|assume_ref|build|min_depth|report)\z/
ABCDresult
0XXX0
10XX0
110X0
11100
11111
3772 46 ▶ croak "$sub: \"$_[0]\" is the file, so the options after it must be name => value pairs, and are an odd number"
Branch: 1 branch
BranchTrueFalseTotal
if @_ and defined $_[0] and not ref $_[0] and $_[0] ne "vcf" and -f $_[0] 1 45 46
Condition83%10/12
@_ and defined $_[0] and not ref $_[0] and $_[0] ne "vcf" and -f $_[0]
!ll&&!rl&&r
4501
@_ and defined $_[0] and not ref $_[0] and $_[0] ne "vcf"
!ll&&!rl&&r
2431
@_ and defined $_[0] and not ref $_[0]
!ll&&!rl&&r
1144
@_ and defined $_[0]
!ll&&!rl&&r
1045
MC/DC60%3/5
@_ and defined $_[0] and not ref $_[0] and $_[0] ne "vcf" and -f $_[0]
@_ defined $_[0] not ref $_[0] $_[0] ne "vcf" -f $_[0]
Truth table66%4/6
A and B and not(C) and D and E
A= @_B= defined $_[0]C= not ref $_[0]D= $_[0] ne "vcf"E= -f $_[0]
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
3773 if @_ && defined $_[0] && !ref $_[0] && $_[0] ne 'vcf' && -f $_[0];
3774 45 my $args = _args(\@_, $sub, ['vcf'], [qw(assume_ref build min_depth report)]);
3775 42 my %r;
3776 # 1 = a marker the file has no record of is homozygous for the reference
3777 # allele, as a VCF that lists only its sample's variants means it;
3778 # 0 = it has no genotype, as in a file of every site, or of an array's
3779 42 ▶ $r{assume_ref} = $args->{assume_ref} // 1;
Condition100%2/2
$args->{"assume_ref"} // 1
l!l
339
MC/DC100%1/1
$args->{"assume_ref"} // 1
$args->{"assume_ref"}
Truth table100%2/2
A
A= $args->{"assume_ref"}
Aresult
11
00
3780 croak "$sub: \"assume_ref\" must be 0 or 1, not " . _what($r{assume_ref})
3781 42 ▶ unless !ref $r{assume_ref} && ($r{assume_ref} eq '0' || $r{assume_ref} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"assume_ref"} and $r{"assume_ref"} eq 0 || $r{"assume_ref"} eq 1 2 40 42
Condition100%6/6
not ref $r{"assume_ref"} and $r{"assume_ref"} eq 0 || $r{"assume_ref"} eq 1
!ll&&!rl&&r
1140
$r{"assume_ref"} eq 0 or $r{"assume_ref"} eq 1
l!l&&r!l&&!r
1391
MC/DC100%3/3
not ref $r{"assume_ref"} and $r{"assume_ref"} eq 0 || $r{"assume_ref"} eq 1
not ref $r{"assume_ref"} $r{"assume_ref"} eq 0 $r{"assume_ref"} eq 1
Truth table100%4/4
not(A) and B or C
A= not ref $r{"assume_ref"}B= $r{"assume_ref"} eq 0C= $r{"assume_ref"} eq 1
ABCresult
0XX0
1000
11X1
1011
3782 40 ▶ $r{min_depth} = $args->{min_depth} // 7; # 0 = count every genotype, whatever its DP; 7 is sex_check's, and what the panel's sites were chosen at
Condition100%2/2
$args->{"min_depth"} // 7
l!l
535
MC/DC100%1/1
$args->{"min_depth"} // 7
$args->{"min_depth"}
Truth table100%2/2
A
A= $args->{"min_depth"}
Aresult
11
00
3783 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
3784 40 ▶ unless !ref $r{min_depth} && $r{min_depth} =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/ 2 38 40
Condition66%2/3
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
0238
MC/DC50%1/2
not ref $r{"min_depth"} and $r{"min_depth"} =~ /\A[0-9]+\z/
not ref $r{"min_depth"} $r{"min_depth"} =~ /\A[0-9]+\z/
Truth table66%2/3
not(A) and B
A= not ref $r{"min_depth"}B= $r{"min_depth"} =~ /\A[0-9]+\z/
ABresult
0X0
100
111
3785 38 ▶ $r{report} = $args->{report} // 1; # 1 = print a table of the samples to STDOUT; 0 = only return them
Condition100%2/2
$args->{"report"} // 1
l!l
317
MC/DC100%1/1
$args->{"report"} // 1
$args->{"report"}
Truth table100%2/2
A
A= $args->{"report"}
Aresult
11
00
3786 38 ▶ croak "$sub: \"report\" must be 0 or 1, not " . _what($r{report}) unless !ref $r{report} && ($r{report} eq '0' || $r{report} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1 1 37 38
Condition83%5/6
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
!ll&&!rl&&r
0137
$r{"report"} eq 0 or $r{"report"} eq 1
l!l&&r!l&&!r
3071
MC/DC66%2/3
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
not ref $r{"report"} $r{"report"} eq 0 $r{"report"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"report"}B= $r{"report"} eq 0C= $r{"report"} eq 1
ABCresult
0XX0
1000
11X1
1011
3787 croak "$sub: \"build\" must be hg19, b37, hg38 or b38, not " . _what($args->{build})
3788 37 ▶ if defined $args->{build} && (ref $args->{build} || $args->{build} !~ /\A(?:hg19|b37|hg38|b38)\z/);
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"build"} and ref $args->{"build"} || !($args->{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/) 1 36 37
Condition83%5/6
defined $args->{"build"} and ref $args->{"build"} || !($args->{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/)
!ll&&!rl&&r
3331
ref $args->{"build"} or not $args->{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/
l!l&&r!l&&!r
013
MC/DC66%2/3
defined $args->{"build"} and ref $args->{"build"} || !($args->{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/)
defined $args->{"build"} ref $args->{"build"} not $args->{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/
Truth table75%3/4
A and B or not(C)
A= defined $args->{"build"}B= ref $args->{"build"}C= not $args->{"build"} =~ /\A(?:hg19|b37|hg38|b38)\z/
ABCresult
0XX0
1000
11X1
1011
3789 36 my $vcf = $args->{vcf};
3790 36 _vcf_check($sub, 'vcf', $vcf);
3791 33 my $panel = _blood_panel($sub);
3792 # which of the panel's two sets of coordinates the markers are looked for at
3793 33 ▶ $r{build} = defined $args->{build} ? ($args->{build} =~ /\A(?:hg19|b37)\z/ ? 'b37' : 'b38') : _hirisplex_build($sub, $vcf);
Branch: 2 branches
BranchTrueFalseTotal
defined $args->{'build'} ? : 3 30 33
$args->{'build'} =~ /\A(?:hg19|b37)\z/ ? : 1 2 3
3794  
3795 32 my @marker = @{ $panel->{markers} };
3796 my @entries = map {
3797 32 my $m = $marker[$_];
3798 576 ▶ [$m->{"$r{build}_chrom"}, $m->{"$r{build}_pos"}, $m->{count_allele}, $m->{kind} eq 'insertion' ? 1 : 0, $m->{name}, $_]
Branch: 1 branch
BranchTrueFalseTotal
$m->{'kind'} eq 'insertion' ? : 32 544 576
3799 } 0 .. $#marker;
3800 32 my $gene = $panel->{gene};
3801 32 my ($next, $close) = _vcf_open($sub, 'vcf', $vcf);
3802 32 ▶ my ($dose, $names, $seen, $deleted, $read, $longer) = _located(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3803 32 _blood_type_tally($next, $vcf, $r{min_depth}, \@entries, scalar @marker, @{ $gene }{"$r{build}_chrom", "$r{build}_pos", "$r{build}_end"})
3804 32 });
3805 31 $close->();
3806  
3807 # Each marker the file has no record of: whether it is read as homozygous
3808 # REF, and if not, why not. The file must have been able to hold the
3809 # record: one with nothing on the marker's chromosome was not sequenced or
3810 # not called there, and one with no allele longer than a base on it holds
3811 # SNVs only, and cannot hold ABO's insertion.
3812 31 my (@as_ref, @unknown); # one per marker: 1 = unlisted and read as REF; why an unlisted marker has no genotype, or undef
3813 31 foreach my $k (0 .. $#marker) {
3814 558 ▶ next if $seen->[$k];
Branch: 1 branch
BranchTrueFalseTotal
if $seen->[$k] 144 414 558
3815 414 my $m = $marker[$k];
3816 414 my $chrom = $m->{"$r{build}_chrom"};
3817 414 my $bit = 1 << $chrom;
3818 $unknown[$k] = !$r{assume_ref} ? "the file has no record of $m->{name}, and \"assume_ref\" is 0"
3819 : !($read & $bit) ? "the file has no record on chromosome $chrom"
3820 414 ▶ : $m->{kind} eq 'insertion' && !($longer & $bit)
Branch: 3 branches
BranchTrueFalseTotal
!$r{'assume_ref'} ? : 17 397 414
!($read & $bit) ? : 69 328 397
$m->{'kind'} eq 'insertion' && !($longer & $bit) ? : 1 327 328
Condition100%3/3
$m->{"kind"} eq "insertion" and not $longer & $bit
!ll&&!rl&&r
32521
MC/DC100%2/2
$m->{"kind"} eq "insertion" and not $longer & $bit
$m->{"kind"} eq "insertion" not $longer & $bit
Truth table100%3/3
A and not(B)
A= $m->{"kind"} eq "insertion"B= not $longer & $bit
ABresult
0X0
100
111
3821 ? "the file has no record of $m->{name}, an insertion, and no allele longer than one base on chromosome $chrom, so it holds SNVs only and could not show it"
3822 : undef;
3823 414 ▶ $as_ref[$k] = defined $unknown[$k] ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $unknown[$k] ? : 87 327 414
3824 }
3825 31 my @abo_role = sort { $panel->{abo}{$a} <=> $panel->{abo}{$b} } keys %{ $panel->{abo} };
3826 31 my @sites = @{ $panel->{sites} };
3827 31 my $listed = grep { $seen->[$_] } @sites;
3828 # why a sample with a genotype at none of the sites has no RhD type: the
3829 # file's reason when it has a record of none of them, and otherwise the
3830 # sample's calls at those it has
3831 my ($site_unknown) = $listed ? ("no genotype at any of the $listed RHD sites the file has a record of: the calls are missing, are not diploid, or have a DP below $r{min_depth}")
3832 31 ▶ : grep { defined } map { $unknown[$_] } @sites;
Branch: 1 branch
BranchTrueFalseTotal
$listed ? : 12 19 31
3833  
3834 31 my %out;
3835 31 foreach my $i (0 .. $#{ $names }) {
3836 140 my $name = $names->[$i];
3837 140 my $d = $dose->{$name};
3838 140 my (%n, %copies, @assumed);
3839 140 foreach my $role (@abo_role) {
3840 420 my $k = $panel->{abo}{$role};
3841 420 ▶ $n{$role} = $as_ref[$k] ? 0 : $d->[$k];
Branch: 1 branch
BranchTrueFalseTotal
$as_ref[$k] ? : 17 403 420
3842 420 $copies{ $marker[$k]{name} } = $n{$role};
3843 420 ▶ push @assumed, $marker[$k]{name} if $as_ref[$k];
Branch: 1 branch
BranchTrueFalseTotal
if $as_ref[$k] 17 403 420
3844 }
3845 140 my ($genotype, $phenotype, $lacking) = _abo_type(\%n);
3846 140 my $abo_why;
3847 140 ▶ if (defined $lacking) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lacking) 45 95 140
3848 45 my $k = $panel->{abo}{$lacking};
3849 45 ▶ $abo_why = $unknown[$k] // "no genotype at $marker[$k]{name}: the call is missing, is not diploid, or has a DP below $r{min_depth}";
Condition100%2/2
$unknown[$k] // qq[no genotype at $marker[$k]{"name"}: the call is missing, is not diploid, or has a DP below $r{"min_depth"}]
l!l
1926
MC/DC100%1/1
$unknown[$k] // qq[no genotype at $marker[$k]{"name"}: the call is missing, is not diploid, or has a DP below $r{"min_depth"}]
$unknown[$k]
Truth table100%2/2
A
A= $unknown[$k]
Aresult
11
00
3850 }
3851 140 my $carried = grep { $d->[$_] } @sites;
3852 # The sites this sample has a genotype at: a call the file has, or a
3853 # site it has no record of that is read as REF. No ALT is RhD negative
3854 # only where there is one; a site's no-call, or a call below
3855 # min_depth, is undef, and up to 2026-11-16 was counted as REF.
3856 140 ▶ my $typed = grep { $as_ref[$_] || defined $d->[$_] } @sites;
Condition100%3/3
$as_ref[$_] || defined $d->[$_]
l!l&&r!l&&!r
3701505225
MC/DC100%2/2
$as_ref[$_] || defined $d->[$_]
$as_ref[$_] defined $d->[$_]
Truth table100%3/3
A || B
A= $as_ref[$_]B= defined $d->[$_]
ABresult
1X1
011
000
3857 140 my $lost = $deleted->[$i]; # copies of a deletion covering RHD: 0 to 2, or undef when the file has no record of one that calls this sample
3858 # 'deletion' = from a record of the gene's deletion; 'sites' = from the
3859 # RHD sites; undef = no type
3860 140 my ($rh_genotype, $rh_phenotype, $basis, $rh_why);
3861 140 ▶ if (defined $lost) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $lost) { } 9 131 140
elsif ($carried) { } 69 62 131
elsif ($typed) { } 47 15 62
3862 9 ▶ ($rh_genotype, $rh_phenotype, $basis) = (('DD', 'Dd', 'dd')[$lost], $lost == 2 ? 'negative' : 'positive', 'deletion');
Branch: 1 branch
BranchTrueFalseTotal
$lost == 2 ? : 3 6 9
3863 } elsif ($carried) {
3864 # the second copy cannot be told from SNVs; see the README
3865 69 ($rh_genotype, $rh_phenotype, $basis) = ('D.', 'positive', 'sites');
3866 } elsif ($typed) {
3867 47 ($rh_genotype, $rh_phenotype, $basis) = ('dd', 'negative', 'sites');
3868 } else {
3869 15 $rh_why = $site_unknown;
3870 }
3871 140 ▶ $out{$name} = {
Branch: 2 branches
BranchTrueFalseTotal
defined $phenotype && defined $rh_phenotype ? : 82 58 140
$rh_phenotype eq 'positive' ? : 55 27 82
Condition100%3/3
defined $phenotype and defined $rh_phenotype
!ll&&!rl&&r
451382
MC/DC100%2/2
defined $phenotype and defined $rh_phenotype
defined $phenotype defined $rh_phenotype
Truth table100%3/3
A and B
A= defined $phenotypeB= defined $rh_phenotype
ABresult
0X0
100
111
3872 type => defined $phenotype && defined $rh_phenotype ? $phenotype . ($rh_phenotype eq 'positive' ? '+' : '-') : undef,
3873 abo => {
3874 genotype => $genotype,
3875 phenotype => $phenotype,
3876 markers => \%copies,
3877 assumed_ref => \@assumed,
3878 why => $abo_why,
3879 },
3880 rhesus => {
3881 genotype => $rh_genotype,
3882 phenotype => $rh_phenotype,
3883 basis => $basis,
3884 sites => scalar @sites,
3885 listed => 0 + $listed,
3886 carried => 0 + $carried,
3887 deleted => $lost,
3888 why => $rh_why,
3889 },
3890 };
3891 }
3892 31 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 3 28 31
3893 3 my @assumed = map { $marker[$_]{name} } grep { $as_ref[$_] } map { $panel->{abo}{$_} } @abo_role;
3894 3 my $ref_sites = grep { $as_ref[$_] } @sites;
3895 3 ▶ push @assumed, "$ref_sites of the " . scalar(@sites) . ' RHD sites' if $ref_sites;
Branch: 1 branch
BranchTrueFalseTotal
if $ref_sites 2 1 3
3896 3 ▶ print STDOUT _blood_report($vcf, \%r, $panel, \%out, $names, \@assumed) or croak "$sub: can't print the report: $!";
Branch: 1 branch
BranchTrueFalseTotal
print STDOUT _blood_report($vcf, \%r, $panel, \%out, $names, \@assumed) or croak("${sub}: can't print the report: $!") 3 0 3
3897 }
3898 31 my %chroms = map { $_->{"$r{build}_chrom"} => 1 } @marker;
3899 1 carp "$sub: \"vcf\" $vcf has no record on chromosome " . join(' or ', sort { $a <=> $b } keys %chroms)
3900 . ", matched by position on $r{build}, so no blood type can be told; check that it is the build the file is on"
3901 31 ▶ unless grep { $read & (1 << $_) } keys %chroms;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$read & 1 << $_;} keys %chroms 1 30 31
3902 31 \%out;
3903 }
3904  
3905 # ---- PDB structures
3906 #
3907 # pdb_search asks two RCSB APIs, as their documentation at
3908 # https://search.rcsb.org/ and https://data.rcsb.org/ described them on
3909 # 2026-10-21: the search API finds the polymer entities whose sequence
3910 # matches, by MMseqs2, and the data API's GraphQL says what each one's
3911 # structure is.
3912  
3913 40 my $Rcsb_search = 'https://search.rcsb.org/rcsbsearch/v2/query';
3914 40 my $Rcsb_data = 'https://data.rcsb.org/graphql';
3915 # The search API's own limit on "rows", which it refuses past with "numeric
3916 # instance is greater than the required maximum (maximum: 10000" (2026-10-21).
3917 40 my $Rcsb_rows = 10000;
3918 # How many entities each GraphQL request asks about. 500 came back in one
3919 # request in 2.45 s, 1.6 MB of JSON, on 2026-10-21, so 200 leaves headroom
3920 # for entities with more annotations than those had.
3921 40 my $Rcsb_batch = 200;
3922 40 my $Rcsb_entities = <<'GRAPHQL';
3923 query ($ids: [String!]!) { polymer_entities(entity_ids: $ids) {
3924 rcsb_id
3925 entity_poly { rcsb_entity_polymer_type pdbx_strand_id }
3926 rcsb_polymer_entity { pdbx_description }
3927 rcsb_entity_source_organism { scientific_name ncbi_taxonomy_id }
3928 rcsb_polymer_entity_container_identifiers { reference_sequence_identifiers { database_name database_accession } }
3929 rcsb_polymer_entity_annotation { type annotation_id name }
3930 entry {
3931 struct { title }
3932 rcsb_entry_info { experimental_method resolution_combined polymer_composition structure_determination_methodology }
3933 rcsb_accession_info { deposit_date initial_release_date }
3934 rcsb_ma_qa_metric_global { ma_qa_metric_global { type value } }
3935 assemblies { rcsb_struct_symmetry { kind oligomeric_state stoichiometry symbol } }
3936 nonpolymer_entities { nonpolymer_comp { chem_comp { id name } } }
3937 }
3938 } }
3939 GRAPHQL
3940  
3941 # $body POSTed to $url as JSON, for $sub, and the JSON it answers with,
3942 # decoded; undef when it answers 204, which is how the search API says that
3943 # nothing matched. A failure dies with RCSB's own "message" where it sent one.
3944 # The tests replace this sub, so that they run with no network.
3945 7 ▶sub _rcsb_post {
Subroutine _rcsb_post: called CC=8 SCAR=20.8
3946 7 my ($sub, $url, $body, $timeout) = @_;
3947 7 require HTTP::Tiny;
3948 7 require JSON::MaybeXS;
3949 # verify_SSL is given, since it is the default only from HTTP::Tiny 0.083
3950 7 my $http = HTTP::Tiny->new(agent => "Cn-Bioinf/$VERSION ", timeout => $timeout, verify_SSL => 1);
3951 7 my ($ssl, $why) = $http->can_ssl;
3952 7 ▶ unless ($ssl) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ssl) 1 6 7
3953 1 $why =~ s/\s+\z//;
3954 1 croak "$sub: can't reach RCSB, which needs HTTPS: $why";
3955 }
3956 6 my $res = $http->post($url, {
3957 headers => { 'Content-Type' => 'application/json', Accept => 'application/json' },
3958 content => JSON::MaybeXS::encode_json($body),
3959 });
3960 6 ▶ return undef if $res->{status} == 204;
Branch: 1 branch
BranchTrueFalseTotal
if $res->{"status"} == 204 1 5 6
3961 5 my $json = eval { JSON::MaybeXS::decode_json($res->{content}) };
3962 5 ▶ unless ($res->{success}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->{"success"}) 3 2 5
3963 # 599 is HTTP::Tiny's own status, for a request that got no answer at
3964 # all, and its content says why
3965 my $msg = $res->{status} == 599 ? $res->{content}
3966 3 ▶ : ref $json eq 'HASH' && defined $json->{message} ? $json->{message} : $res->{reason};
Branch: 2 branches
BranchTrueFalseTotal
$res->{'status'} == 599 ? : 1 2 3
ref $json eq 'HASH' && defined $json->{'message'} ? : 1 1 2
Condition66%2/3
ref $json eq "HASH" and defined $json->{"message"}
!ll&&!rl&&r
101
MC/DC50%1/2
ref $json eq "HASH" and defined $json->{"message"}
ref $json eq "HASH" defined $json->{"message"}
Truth table66%2/3
A and B
A= ref $json eq "HASH"B= defined $json->{"message"}
ABresult
0X0
100
111
3967 3 $msg =~ s/\s+\z//;
3968 3 croak "$sub: $url answered $res->{status}: $msg";
3969 }
3970 2 ▶ croak "$sub: $url answered with something that isn't JSON: " . substr($res->{content}, 0, 200) unless ref $json;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $json 1 1 2
3971 1 $json;
3972 }
3973  
3974 # The alignment of one search hit, from the "match_context" RCSB gave it,
3975 # under the names get_best_alignment_hit gives a BLAST hsp. RCSB's
3976 # sequence_identity is truncated to 3 places, so the identity is counted from
3977 # the aligned sequences instead, which is how BLAST counts it.
3978 45 ▶sub _pdb_alignment {
Subroutine _pdb_alignment: called CC=12 SCAR=25.2
3979 45 my ($m) = @_;
3980 45 ▶ my ($q, $h) = map { $_ // '' } @{ $m }{qw(query_aligned_seq subject_aligned_seq)};
Condition50%1/2
$_ // ""
l!l
900
MC/DC0%0/1
$_ // ""
$_
Truth table50%1/2
A
A= $_
Aresult
11
00
3981 45 my ($identity, $gaps) = (0, 0);
3982 45 foreach my $i (0 .. length($q) - 1) {
3983 6417 my ($x, $y) = (substr($q, $i, 1), substr($h, $i, 1));
3984 6417 ▶ if ($x eq '-' || $y eq '-') { $gaps++ } elsif ($x eq $y) { $identity++ }
Branch: 2 branches
BranchTrueFalseTotal
if ($x eq '-' or $y eq '-') { } 81 6336 6417
elsif ($x eq $y) { } 5409 927 6336
Condition100%3/3
$x eq "-" or $y eq "-"
l!l&&r!l&&!r
63186336
MC/DC100%2/2
$x eq "-" or $y eq "-"
$x eq "-" $y eq "-"
Truth table100%3/3
A or B
A= $x eq "-"B= $y eq "-"
ABresult
1X1
011
000
3985 }
3986 return {
3987 evalue => $m->{evalue},
3988 bit_score => $m->{bitscore},
3989 align_len => $m->{alignment_length},
3990 identity => $identity,
3991 # undef where RCSB gives no length to divide by, rather than dying of it
3992 pident => ($m->{alignment_length} // 0) > 0 ? 100 * $identity / $m->{alignment_length} : undef,
3993 mismatches => $m->{mismatches},
3994 gaps => $gaps,
3995 gap_opens => $m->{gaps_opened},
3996 query_from => $m->{query_beg},
3997 query_to => $m->{query_end},
3998 query_len => $m->{query_length},
3999 query_cover => defined $m->{query_beg} && defined $m->{query_end} && ($m->{query_length} // 0) > 0
4000 ? 100 * ($m->{query_end} - $m->{query_beg} + 1) / $m->{query_length} : undef,
4001 hit_from => $m->{subject_beg},
4002 hit_to => $m->{subject_end},
4003 hit_len => $m->{subject_length},
4004 45 ▶ qseq => $q,
Branch: 2 branches
BranchTrueFalseTotal
($m->{'alignment_length'} // 0) > 0 ? : 44 1 45
defined $m->{'query_beg'} && defined $m->{'query_end'} && ($m->{'query_length'} // 0) > 0 ? : 44 1 45
Condition60%6/10
$m->{"alignment_length"} // 0
l!l
450
defined $m->{"query_beg"} and defined $m->{"query_end"} and ($m->{"query_length"} // 0) > 0
!ll&&!rl&&r
0144
defined $m->{"query_beg"} and defined $m->{"query_end"}
!ll&&!rl&&r
0045
$m->{"query_length"} // 0
l!l
441
MC/DC0%0/1
$m->{"alignment_length"} // 0
$m->{"alignment_length"}
MC/DC33%1/3
defined $m->{"query_beg"} and defined $m->{"query_end"} and ($m->{"query_length"} // 0) > 0
defined $m->{"query_beg"} defined $m->{"query_end"} $m->{"query_length"}
Truth table50%1/2
A
A= $m->{"alignment_length"}
Aresult
11
00
Truth table50%2/4
A and B and C
A= defined $m->{"query_beg"}B= defined $m->{"query_end"}C= $m->{"query_length"}
ABCresult
0XX0
10X0
1100
1111
4005 hseq => $h,
4006 };
4007 }
4008  
4009 # What the data API said of one polymer entity, $e, which is undef when it
4010 # said nothing, as the fields pdb_search returns: every key is there either
4011 # way, undef or an empty array when RCSB has no value.
4012 40 ▶sub _pdb_structure {
Subroutine _pdb_structure: called CC=32 SCAR=35.0
4013 40 my ($e) = @_;
4014 40 ▶ $e //= {};
Condition100%2/2
$e //= {}
l!l
391
MC/DC100%1/1
$e //= {}
$e
Truth table100%2/2
A
A= $e
Aresult
11
00
4015 40 ▶ my $entry = $e->{entry} // {};
Condition100%2/2
$e->{"entry"} // {}
l!l
391
MC/DC100%1/1
$e->{"entry"} // {}
$e->{"entry"}
Truth table100%2/2
A
A= $e->{"entry"}
Aresult
11
00
4016 40 ▶ my $info = $entry->{rcsb_entry_info} // {};
Condition100%2/2
$entry->{"rcsb_entry_info"} // {}
l!l
391
MC/DC100%1/1
$entry->{"rcsb_entry_info"} // {}
$entry->{"rcsb_entry_info"}
Truth table100%2/2
A
A= $entry->{"rcsb_entry_info"}
Aresult
11
00
4017 40 ▶ my $dates = $entry->{rcsb_accession_info} // {};
Condition100%2/2
$entry->{"rcsb_accession_info"} // {}
l!l
391
MC/DC100%1/1
$entry->{"rcsb_accession_info"} // {}
$entry->{"rcsb_accession_info"}
Truth table100%2/2
A
A= $entry->{"rcsb_accession_info"}
Aresult
11
00
4018 # The global symmetry of the first assembly, which is the one the
4019 # depositors gave first, and the one RCSB's own page shows.
4020 54 ▶ my ($sym) = grep { ($_->{kind} // '') eq 'Global Symmetry' }
Condition50%1/2
$_->{"kind"} // ""
l!l
540
MC/DC0%0/1
$_->{"kind"} // ""
$_->{"kind"}
Truth table50%1/2
A
A= $_->{"kind"}
Aresult
11
00
4021 40 ▶ map { @{ $_->{rcsb_struct_symmetry} // [] } } grep { ref $_ eq 'HASH' } @{ $entry->{assemblies} // [] }[0];
Condition75%3/4
$_->{"rcsb_struct_symmetry"} // []
l!l
390
$entry->{"assemblies"} // []
l!l
391
MC/DC0%0/1
$_->{"rcsb_struct_symmetry"} // []
$_->{"rcsb_struct_symmetry"}
MC/DC100%1/1
$entry->{"assemblies"} // []
$entry->{"assemblies"}
Truth table50%1/2
A
A= $_->{"rcsb_struct_symmetry"}
Aresult
11
00
Truth table100%2/2
A
A= $entry->{"assemblies"}
Aresult
11
00
4022 40 ▶ $sym //= {};
Condition100%2/2
$sym //= {}
l!l
391
MC/DC100%1/1
$sym //= {}
$sym
Truth table100%2/2
A
A= $sym
Aresult
11
00
4023 8 ▶ my ($plddt) = map { $_->{value} } grep { ($_->{type} // '') eq 'pLDDT' }
Condition50%1/2
$_->{"type"} // ""
l!l
80
MC/DC0%0/1
$_->{"type"} // ""
$_->{"type"}
Truth table50%1/2
A
A= $_->{"type"}
Aresult
11
00
4024 40 ▶ map { @{ $_->{ma_qa_metric_global} // [] } } @{ $entry->{rcsb_ma_qa_metric_global} // [] };
Condition75%3/4
$_->{"ma_qa_metric_global"} // []
l!l
80
$entry->{"rcsb_ma_qa_metric_global"} // []
l!l
832
MC/DC0%0/1
$_->{"ma_qa_metric_global"} // []
$_->{"ma_qa_metric_global"}
MC/DC100%1/1
$entry->{"rcsb_ma_qa_metric_global"} // []
$entry->{"rcsb_ma_qa_metric_global"}
Truth table50%1/2
A
A= $_->{"ma_qa_metric_global"}
Aresult
11
00
Truth table100%2/2
A
A= $entry->{"rcsb_ma_qa_metric_global"}
Aresult
11
00
4025 40 ▶ my @annotation = @{ $e->{rcsb_polymer_entity_annotation} // [] };
Condition100%2/2
$e->{"rcsb_polymer_entity_annotation"} // []
l!l
391
MC/DC100%1/1
$e->{"rcsb_polymer_entity_annotation"} // []
$e->{"rcsb_polymer_entity_annotation"}
Truth table100%2/2
A
A= $e->{"rcsb_polymer_entity_annotation"}
Aresult
11
00
4026 40 my (%seen, @ligands);
4027 40 ▶ foreach my $c (map { $_->{nonpolymer_comp}{chem_comp} // () } @{ $entry->{nonpolymer_entities} // [] }) {
Condition60%3/5
$_->{"nonpolymer_comp"}{"chem_comp"} // ()
l!l&&r!l&&!r
6200
$entry->{"nonpolymer_entities"} // []
l!l
319
MC/DC0%0/2
$_->{"nonpolymer_comp"}{"chem_comp"} // ()
$_->{"nonpolymer_comp"}{"chem_comp"} ()
MC/DC100%1/1
$entry->{"nonpolymer_entities"} // []
$entry->{"nonpolymer_entities"}
Truth table33%1/3
A // B
A= $_->{"nonpolymer_comp"}{"chem_comp"}B= ()
ABresult
1X1
011
000
Truth table100%2/2
A
A= $entry->{"nonpolymer_entities"}
Aresult
11
00
4028 62 ▶ push @ligands, { id => $c->{id}, name => $c->{name} } unless $seen{ $c->{id} }++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$c->{"id"}}++ 62 0 62
4029 }
4030 40 ▶ my $chains = ($e->{entity_poly} // {})->{pdbx_strand_id};
Condition100%2/2
$e->{"entity_poly"} // {}
l!l
391
MC/DC100%1/1
$e->{"entity_poly"} // {}
$e->{"entity_poly"}
Truth table100%2/2
A
A= $e->{"entity_poly"}
Aresult
11
00
4031 return {
4032 title => ($entry->{struct} // {})->{title},
4033 description => ($e->{rcsb_polymer_entity} // {})->{pdbx_description},
4034 method => $info->{experimental_method},
4035 methodology => $info->{structure_determination_methodology},
4036 resolution => ($info->{resolution_combined} // [])->[0],
4037 plddt => $plddt,
4038 polymer_type => ($e->{entity_poly} // {})->{rcsb_entity_polymer_type},
4039 polymer_composition => $info->{polymer_composition},
4040 oligomeric_state => $sym->{oligomeric_state},
4041 39 ▶ stoichiometry => $sym->{stoichiometry} ? join('', @{ $sym->{stoichiometry} }) : undef,
Branch: 1 branch
BranchTrueFalseTotal
defined $chains ? : 39 1 40
4042 symmetry => $sym->{symbol},
4043 chains => [defined $chains ? split(/,/, $chains) : ()],
4044 39 ▶ organisms => [map { +{ name => $_->{scientific_name}, taxonomy_id => $_->{ncbi_taxonomy_id} } } @{ $e->{rcsb_entity_source_organism} // [] }],
Condition100%2/2
$e->{"rcsb_entity_source_organism"} // []
l!l
391
MC/DC100%1/1
$e->{"rcsb_entity_source_organism"} // []
$e->{"rcsb_entity_source_organism"}
Truth table100%2/2
A
A= $e->{"rcsb_entity_source_organism"}
Aresult
11
00
4045 39 ▶ uniprot => [map { $_->{database_accession} } grep { ($_->{database_name} // '') eq 'UniProt' }
Condition50%1/2
$_->{"database_name"} // ""
l!l
390
MC/DC0%0/1
$_->{"database_name"} // ""
$_->{"database_name"}
Truth table50%1/2
A
A= $_->{"database_name"}
Aresult
11
00
4046 40 ▶ @{ ($e->{rcsb_polymer_entity_container_identifiers} // {})->{reference_sequence_identifiers} // [] }],
Condition100%4/4
+($e->{"rcsb_polymer_entity_container_identifiers"} // {})->{"reference_sequence_identifiers"} // []
l!l
391
$e->{"rcsb_polymer_entity_container_identifiers"} // {}
l!l
391
MC/DC100%1/1
+($e->{"rcsb_polymer_entity_container_identifiers"} // {})->{"reference_sequence_identifiers"} // []
$e->{"rcsb_polymer_entity_container_identifiers"}
Truth table100%2/2
A
A= $e->{"rcsb_polymer_entity_container_identifiers"}
Aresult
11
00
4047 24 ▶ pfam => [map { +{ id => $_->{annotation_id}, name => $_->{name} } } grep { ($_->{type} // '') eq 'Pfam' } @annotation],
Condition50%1/2
$_->{"type"} // ""
l!l
10070
MC/DC0%0/1
$_->{"type"} // ""
$_->{"type"}
Truth table50%1/2
A
A= $_->{"type"}
Aresult
11
00
4048 226 ▶ interpro => [map { +{ id => $_->{annotation_id}, name => $_->{name} } } grep { ($_->{type} // '') eq 'InterPro' } @annotation],
Branch: 2 branches
BranchTrueFalseTotal
defined $dates->{'deposit_date'} ? : 39 1 40
defined $dates->{'initial_release_date'} ? : 39 1 40
Condition50%1/2
$_->{"type"} // ""
l!l
10070
MC/DC0%0/1
$_->{"type"} // ""
$_->{"type"}
Truth table50%1/2
A
A= $_->{"type"}
Aresult
11
00
4049 ligands => \@ligands,
4050 deposited => defined $dates->{deposit_date} ? substr($dates->{deposit_date}, 0, 10) : undef,
4051 40 ▶ released => defined $dates->{initial_release_date} ? substr($dates->{initial_release_date}, 0, 10) : undef,
Branch: 1 branch
BranchTrueFalseTotal
$sym->{'stoichiometry'} ? : 39 1 40
Condition100%8/8
$entry->{"struct"} // {}
l!l
391
$e->{"rcsb_polymer_entity"} // {}
l!l
391
$info->{"resolution_combined"} // []
l!l
319
$e->{"entity_poly"} // {}
l!l
391
MC/DC100%1/1
$entry->{"struct"} // {}
$entry->{"struct"}
MC/DC100%1/1
$e->{"rcsb_polymer_entity"} // {}
$e->{"rcsb_polymer_entity"}
MC/DC100%1/1
$info->{"resolution_combined"} // []
$info->{"resolution_combined"}
MC/DC100%1/1
$e->{"entity_poly"} // {}
$e->{"entity_poly"}
Truth table100%2/2
A
A= $entry->{"struct"}
Aresult
11
00
Truth table100%2/2
A
A= $e->{"rcsb_polymer_entity"}
Aresult
11
00
Truth table100%2/2
A
A= $info->{"resolution_combined"}
Aresult
11
00
Truth table100%2/2
A
A= $e->{"entity_poly"}
Aresult
11
00
4052 };
4053 }
4054  
4055 # How a hit's structure was determined, as the report shows it: RCSB's
4056 # experimental method, which a computed model has none of. Its values, and
4057 # those of the methodology, are the enums of rcsb_entry_info in
4058 # https://data.rcsb.org/rest/v1/schema/entry (checked 2026-10-21).
4059 25 ▶sub _pdb_method {
Subroutine _pdb_method: called CC=4 SCAR=14.3
4060 25 my ($h) = @_;
4061 25 ▶ return $h->{method} if defined $h->{method};
Branch: 1 branch
BranchTrueFalseTotal
if defined $h->{"method"} 20 5 25
4062 5 ▶ ($h->{methodology} // '') eq 'computational' ? 'model' : '-';
Branch: 1 branch
BranchTrueFalseTotal
($h->{'methodology'} // '') eq 'computational' ? : 5 0 5
Condition50%1/2
$h->{"methodology"} // ""
l!l
50
MC/DC0%0/1
$h->{"methodology"} // ""
$h->{"methodology"}
Truth table50%1/2
A
A= $h->{"methodology"}
Aresult
11
00
4063 }
4064  
4065 # $text, a number as perl wrote it, with an exponent of two digits where two
4066 # are enough, as C99's printf writes one. The C runtime under Strawberry Perl
4067 # 5.24.4 writes three, so pdb_search's report read "1.6e-089" there (CPAN
4068 # Testers report 620bc624-ddea-11f1-b231-87fe50e89311, 2026-11-11) and
4069 # "1.6e-89" everywhere else, and admixture's warning gave its default tolerance
4070 # as "1e-010" there in 0.03-TRIAL (report 363318e0-e362-11f1-808f-855b4a25bcf6,
4071 # 2026-11-18). An exponent that needs three digits keeps them.
4072 45 ▶sub _two_digit_exponent {
Subroutine _two_digit_exponent: called CC=1 SCAR=0.0
4073 45 my ($text) = @_;
4074 45 $text =~ s/([eE][-+])0(\d\d)\z/$1$2/;
4075 45 $text;
4076 }
4077  
4078 # pdb_search's report on @$hits, $total of which RCSB found: one line a hit,
4079 # best first.
4080 6 ▶sub _pdb_report {
Subroutine _pdb_report: called CC=15 SCAR=27.3
4081 6 my ($r, $hits, $total) = @_;
4082 5 ▶ my $text = "pdb_search: " . ($total == 0 ? 'no hits' : scalar(@{ $hits }) . " of $total hit" . ($total > 1 ? 's' : ''))
Branch: 3 branches
BranchTrueFalseTotal
$total > 1 ? : 5 0 5
$r->{'computed'} ? : 0 6 6
$r->{'identity'} > 0 ? : 0 6 6
4083 . " in RCSB's " . ($r->{computed} ? 'PDB and computed models' : 'PDB')
4084 . " for a $r->{len}-residue $r->{type} sequence, at an E-value below " . _two_digit_exponent("$r->{evalue}")
4085 6 ▶ . ($r->{identity} > 0 ? " and $r->{identity}% identity or more" : '') . "\n";
Branch: 1 branch
BranchTrueFalseTotal
$total == 0 ? : 1 5 6
4086 6 ▶ return $text unless @{ $hits };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$hits;} 1 5 6
4087 5 my @head = ('id', 'method', 'resolution', 'identity', 'cover', 'evalue', 'bits', 'oligomer', 'description');
4088 my @rows = map {
4089 [$_->{id}, _pdb_method($_),
4090 defined $_->{resolution} ? sprintf('%.2f A', $_->{resolution}) : defined $_->{plddt} ? "pLDDT $_->{plddt}" : '-',
4091 defined $_->{pident} ? sprintf('%.1f%%', $_->{pident}) : '-', defined $_->{query_cover} ? sprintf('%.0f%%', $_->{query_cover}) : '-',
4092 _two_digit_exponent(sprintf('%.2g', $_->{evalue})), $_->{bit_score},
4093 25 ▶ $_->{oligomeric_state} // '-', $_->{description} // '-']
Branch: 4 branches
BranchTrueFalseTotal
defined $_->{'resolution'} ? : 20 5 25
defined $_->{'plddt'} ? : 5 0 5
defined $_->{'pident'} ? : 24 1 25
defined $_->{'query_cover'} ? : 24 1 25
Condition50%2/4
$_->{"oligomeric_state"} // "-"
l!l
250
$_->{"description"} // "-"
l!l
250
MC/DC0%0/1
$_->{"oligomeric_state"} // "-"
$_->{"oligomeric_state"}
MC/DC0%0/1
$_->{"description"} // "-"
$_->{"description"}
Truth table50%1/2
A
A= $_->{"oligomeric_state"}
Aresult
11
00
Truth table50%1/2
A
A= $_->{"description"}
Aresult
11
00
4094 5 } @{ $hits };
4095 5 my @w = map { length $head[$_] } 0 .. $#head;
4096 5 foreach my $row (@rows) {
4097 25 foreach my $i (0 .. $#head) {
4098 225 ▶ $w[$i] = length $row->[$i] if length $row->[$i] > $w[$i];
Branch: 1 branch
BranchTrueFalseTotal
if length $row->[$i] > $w[$i] 33 192 225
4099 }
4100 }
4101 # left-aligned text, right-aligned numbers; the last column is not padded
4102 5 my %left = map { $_ => 1 } 0, 1, 7, 8;
4103 5 ▶ my $line = sub { join(' ', map { $_ == $#head ? $_[$_] : $left{$_} ? sprintf('%-*s', $w[$_], $_[$_]) : sprintf('%*s', $w[$_], $_[$_]) } 0 .. $#head) . "\n" };
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 2 branches
BranchTrueFalseTotal
$_ == $#head ? : 30 240 270
$left{$_} ? : 90 150 240
4104 5 $text . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows);
4105 }
4106  
4107 32 ▶sub pdb_search {
Subroutine pdb_search: called CC=72 SCAR=44.9
Pod documented
4108 32 my $sub = 'pdb_search';
4109 32 my $args = _args(\@_, $sub, [qw(seq)], [qw(computed evalue identity max_hits report timeout type)]);
4110 30 my %r;
4111 # The cutoffs are made numbers with 0 +, since JSON::XS writes a string as
4112 # a string, and RCSB refuses a string where its schema wants a number.
4113 30 ▶ $r{evalue} = $args->{evalue} // 0.1; # hits at this E-value or above are left out; BLAST's default of 10 would let in hits expected 10 times by chance
Condition100%2/2
$args->{"evalue"} // "0.1"
l!l
426
MC/DC100%1/1
$args->{"evalue"} // "0.1"
$args->{"evalue"}
Truth table100%2/2
A
A= $args->{"evalue"}
Aresult
11
00
4114 croak "$sub: \"evalue\" must be a number above 0, not " . _what($r{evalue})
4115 30 ▶ unless !ref $r{evalue} && $r{evalue} =~ $Number && $r{evalue} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"evalue"} and $r{"evalue"} =~ /$Number/ and $r{"evalue"} > 0 2 28 30
Condition83%5/6
not ref $r{"evalue"} and $r{"evalue"} =~ /$Number/ and $r{"evalue"} > 0
!ll&&!rl&&r
1128
not ref $r{"evalue"} and $r{"evalue"} =~ /$Number/
!ll&&!rl&&r
0129
MC/DC66%2/3
not ref $r{"evalue"} and $r{"evalue"} =~ /$Number/ and $r{"evalue"} > 0
not ref $r{"evalue"} $r{"evalue"} =~ /$Number/ $r{"evalue"} > 0
Truth table75%3/4
not(A) and B and C
A= not ref $r{"evalue"}B= $r{"evalue"} =~ /$Number/C= $r{"evalue"} > 0
ABCresult
0XX0
10X0
1100
1111
4116 28 $r{evalue} = 0 + $r{evalue};
4117 28 ▶ $r{identity} = $args->{identity} // 0; # percent; hits with less identity than this are left out
Condition100%2/2
$args->{"identity"} // 0
l!l
325
MC/DC100%1/1
$args->{"identity"} // 0
$args->{"identity"}
Truth table100%2/2
A
A= $args->{"identity"}
Aresult
11
00
4118 croak "$sub: \"identity\" must be a percentage, from 0 to 100, not " . _what($r{identity})
4119 28 ▶ unless !ref $r{identity} && $r{identity} =~ $Number && $r{identity} >= 0 && $r{identity} <= 100;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"identity"} and $r{"identity"} =~ /$Number/ and $r{"identity"} >= 0 and $r{"identity"} <= 100 2 26 28
Condition66%6/9
not ref $r{"identity"} and $r{"identity"} =~ /$Number/ and $r{"identity"} >= 0 and $r{"identity"} <= 100
!ll&&!rl&&r
1126
not ref $r{"identity"} and $r{"identity"} =~ /$Number/ and $r{"identity"} >= 0
!ll&&!rl&&r
0127
not ref $r{"identity"} and $r{"identity"} =~ /$Number/
!ll&&!rl&&r
0028
MC/DC50%2/4
not ref $r{"identity"} and $r{"identity"} =~ /$Number/ and $r{"identity"} >= 0 and $r{"identity"} <= 100
not ref $r{"identity"} $r{"identity"} =~ /$Number/ $r{"identity"} >= 0 $r{"identity"} <= 100
Truth table60%3/5
not(A) and B and C and D
A= not ref $r{"identity"}B= $r{"identity"} =~ /$Number/C= $r{"identity"} >= 0D= $r{"identity"} <= 100
ABCDresult
0XXX0
10XX0
110X0
11100
11111
4120 26 $r{identity} = 0 + $r{identity};
4121 26 ▶ $r{max_hits} = $args->{max_hits} // 100; # the most hits returned, best first
Condition100%2/2
$args->{"max_hits"} // 100
l!l
422
MC/DC100%1/1
$args->{"max_hits"} // 100
$args->{"max_hits"}
Truth table100%2/2
A
A= $args->{"max_hits"}
Aresult
11
00
4122 croak "$sub: \"max_hits\" must be a whole number from 1 to $Rcsb_rows, RCSB's limit, not " . _what($r{max_hits})
4123 26 ▶ unless !ref $r{max_hits} && $r{max_hits} =~ /\A[0-9]+\z/ && $r{max_hits} >= 1 && $r{max_hits} <= $Rcsb_rows;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"max_hits"} and $r{"max_hits"} =~ /\A[0-9]+\z/ and $r{"max_hits"} >= 1 and $r{"max_hits"} <= $Rcsb_rows 3 23 26
Condition88%8/9
not ref $r{"max_hits"} and $r{"max_hits"} =~ /\A[0-9]+\z/ and $r{"max_hits"} >= 1 and $r{"max_hits"} <= $Rcsb_rows
!ll&&!rl&&r
2123
not ref $r{"max_hits"} and $r{"max_hits"} =~ /\A[0-9]+\z/ and $r{"max_hits"} >= 1
!ll&&!rl&&r
1124
not ref $r{"max_hits"} and $r{"max_hits"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
0125
MC/DC75%3/4
not ref $r{"max_hits"} and $r{"max_hits"} =~ /\A[0-9]+\z/ and $r{"max_hits"} >= 1 and $r{"max_hits"} <= $Rcsb_rows
not ref $r{"max_hits"} $r{"max_hits"} =~ /\A[0-9]+\z/ $r{"max_hits"} >= 1 $r{"max_hits"} <= $Rcsb_rows
Truth table80%4/5
not(A) and B and C and D
A= not ref $r{"max_hits"}B= $r{"max_hits"} =~ /\A[0-9]+\z/C= $r{"max_hits"} >= 1D= $r{"max_hits"} <= $Rcsb_rows
ABCDresult
0XXX0
10XX0
110X0
11100
11111
4124 23 $r{max_hits} = 0 + $r{max_hits};
4125 23 ▶ $r{computed} = $args->{computed} // 0; # 0 = experimental structures only; 1 = also computed models (AlphaFold DB, ModelArchive)
Condition100%2/2
$args->{"computed"} // 0
l!l
221
MC/DC100%1/1
$args->{"computed"} // 0
$args->{"computed"}
Truth table100%2/2
A
A= $args->{"computed"}
Aresult
11
00
4126 23 ▶ croak "$sub: \"computed\" must be 0 or 1, not " . _what($r{computed}) unless !ref $r{computed} && ($r{computed} eq '0' || $r{computed} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"computed"} and $r{"computed"} eq 0 || $r{"computed"} eq 1 1 22 23
Condition83%5/6
not ref $r{"computed"} and $r{"computed"} eq 0 || $r{"computed"} eq 1
!ll&&!rl&&r
0122
$r{"computed"} eq 0 or $r{"computed"} eq 1
l!l&&r!l&&!r
2111
MC/DC66%2/3
not ref $r{"computed"} and $r{"computed"} eq 0 || $r{"computed"} eq 1
not ref $r{"computed"} $r{"computed"} eq 0 $r{"computed"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"computed"}B= $r{"computed"} eq 0C= $r{"computed"} eq 1
ABCresult
0XX0
1000
11X1
1011
4127 22 ▶ $r{type} = $args->{type} // 'protein'; # protein, dna or rna: which of RCSB's sequence databases to search
Condition100%2/2
$args->{"type"} // "protein"
l!l
121
MC/DC100%1/1
$args->{"type"} // "protein"
$args->{"type"}
Truth table100%2/2
A
A= $args->{"type"}
Aresult
11
00
4128 22 ▶ croak "$sub: \"type\" must be protein, dna or rna, not " . _what($r{type}) unless !ref $r{type} && $r{type} =~ /\A(?:protein|dna|rna)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"type"} and $r{"type"} =~ /\A(?:protein|dna|rna)\z/ 1 21 22
Condition66%2/3
not ref $r{"type"} and $r{"type"} =~ /\A(?:protein|dna|rna)\z/
!ll&&!rl&&r
0121
MC/DC50%1/2
not ref $r{"type"} and $r{"type"} =~ /\A(?:protein|dna|rna)\z/
not ref $r{"type"} $r{"type"} =~ /\A(?:protein|dna|rna)\z/
Truth table66%2/3
not(A) and B
A= not ref $r{"type"}B= $r{"type"} =~ /\A(?:protein|dna|rna)\z/
ABresult
0X0
100
111
4129 21 ▶ $r{report} = $args->{report} // 1; # 1 = print a table of the hits to STDOUT; 0 = only return them
Condition100%2/2
$args->{"report"} // 1
l!l
516
MC/DC100%1/1
$args->{"report"} // 1
$args->{"report"}
Truth table100%2/2
A
A= $args->{"report"}
Aresult
11
00
4130 21 ▶ croak "$sub: \"report\" must be 0 or 1, not " . _what($r{report}) unless !ref $r{report} && ($r{report} eq '0' || $r{report} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1 1 20 21
Condition83%5/6
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
!ll&&!rl&&r
0120
$r{"report"} eq 0 or $r{"report"} eq 1
l!l&&r!l&&!r
4161
MC/DC66%2/3
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
not ref $r{"report"} $r{"report"} eq 0 $r{"report"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"report"}B= $r{"report"} eq 0C= $r{"report"} eq 1
ABCresult
0XX0
1000
11X1
1011
4131 20 ▶ $r{timeout} = $args->{timeout} // 60; # seconds for each request, HTTP::Tiny's own default
Condition100%2/2
$args->{"timeout"} // 60
l!l
218
MC/DC100%1/1
$args->{"timeout"} // 60
$args->{"timeout"}
Truth table100%2/2
A
A= $args->{"timeout"}
Aresult
11
00
4132 croak "$sub: \"timeout\" must be a number of seconds above 0, not " . _what($r{timeout})
4133 20 ▶ unless !ref $r{timeout} && $r{timeout} =~ $Number && $r{timeout} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"timeout"} and $r{"timeout"} =~ /$Number/ and $r{"timeout"} > 0 1 19 20
Condition50%3/6
not ref $r{"timeout"} and $r{"timeout"} =~ /$Number/ and $r{"timeout"} > 0
!ll&&!rl&&r
0119
not ref $r{"timeout"} and $r{"timeout"} =~ /$Number/
!ll&&!rl&&r
0020
MC/DC33%1/3
not ref $r{"timeout"} and $r{"timeout"} =~ /$Number/ and $r{"timeout"} > 0
not ref $r{"timeout"} $r{"timeout"} =~ /$Number/ $r{"timeout"} > 0
Truth table50%2/4
not(A) and B and C
A= not ref $r{"timeout"}B= $r{"timeout"} =~ /$Number/C= $r{"timeout"} > 0
ABCresult
0XX0
10X0
1100
1111
4134  
4135 19 my $seq = $args->{seq};
4136 19 ▶ croak "$sub: \"seq\" must be a sequence, as a string, not " . _what($seq) if ref $seq;
Branch: 1 branch
BranchTrueFalseTotal
if ref $seq 1 18 19
4137 # A sequence copied out of a FASTA file keeps its line breaks, and one
4138 # translated from DNA can end in a stop; RCSB refuses both, and lower case.
4139 18 $seq =~ s/\s+//g;
4140 18 $seq = uc $seq;
4141 18 $seq =~ s/\*\z//;
4142 18 ▶ croak "$sub: \"seq\" has no residues" unless length $seq;
Branch: 1 branch
BranchTrueFalseTotal
unless length $seq 1 17 18
4143 17 ▶ croak "$sub: \"seq\" has \"$1\" at residue " . ($-[0] + 1) . ', which isn\'t a residue letter' if $seq =~ /([^A-Z])/;
Branch: 1 branch
BranchTrueFalseTotal
if $seq =~ /([^A-Z])/ 2 15 17
4144 15 $r{len} = length $seq;
4145  
4146 my $found = _rcsb_post($sub, $Rcsb_search, {
4147 query => { type => 'terminal', service => 'sequence', parameters => {
4148 evalue_cutoff => $r{evalue}, identity_cutoff => $r{identity} / 100, sequence_type => $r{type}, value => $seq,
4149 } },
4150 request_options => {
4151 results_verbosity => 'verbose', # which gives each hit's alignment
4152 results_content_type => [$r{computed} ? ('experimental', 'computational') : 'experimental'],
4153 scoring_strategy => 'sequence',
4154 paginate => { start => 0, rows => $r{max_hits} },
4155 },
4156 return_type => 'polymer_entity',
4157 15 ▶ }, $r{timeout});
Branch: 1 branch
BranchTrueFalseTotal
$r{'computed'} ? : 1 14 15
4158 14 ▶ if ($found) {
Branch: 1 branch
BranchTrueFalseTotal
if ($found) 13 1 14
4159 13 my $not = "$sub: $Rcsb_search answered with JSON that isn't a search result: ";
4160 13 ▶ croak $not . 'it is not an object' unless ref $found eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $found eq "HASH" 1 12 13
4161 12 ▶ croak $not . 'it has no result_set array' unless ref $found->{result_set} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $found->{"result_set"} eq "ARRAY" 1 11 12
4162 11 ▶ croak $not . 'it has no total_count' unless defined $found->{total_count} && !ref $found->{total_count};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $found->{"total_count"} and not ref $found->{"total_count"} 1 10 11
Condition66%2/3
defined $found->{"total_count"} and not ref $found->{"total_count"}
!ll&&!rl&&r
1010
MC/DC50%1/2
defined $found->{"total_count"} and not ref $found->{"total_count"}
defined $found->{"total_count"} not ref $found->{"total_count"}
Truth table66%2/3
A and not(B)
A= defined $found->{"total_count"}B= not ref $found->{"total_count"}
ABresult
0X0
100
111
4163 10 ▶ ref $_ eq 'HASH' && defined $_->{identifier} or croak $not . 'a hit in its result_set has no identifier' foreach @{ $found->{result_set} };
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq "HASH" and defined $_->{"identifier"} or croak($not . 'a hit in its result_set has no identifier') 45 1 46
Condition66%2/3
ref $_ eq "HASH" and defined $_->{"identifier"}
!ll&&!rl&&r
1045
MC/DC50%1/2
ref $_ eq "HASH" and defined $_->{"identifier"}
ref $_ eq "HASH" defined $_->{"identifier"}
Truth table66%2/3
A and B
A= ref $_ eq "HASH"B= defined $_->{"identifier"}
ABresult
0X0
100
111
4164 }
4165 10 ▶ my $total = $found ? $found->{total_count} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$found ? : 9 1 10
4166 10 my @hits;
4167 10 ▶ foreach my $res (@{ $found ? $found->{result_set} : [] }) {
Branch: 1 branch
BranchTrueFalseTotal
$found ? : 9 1 10
4168 45 my $best; # undef until a match is seen
4169 45 ▶ foreach my $m (map { @{ $_->{match_context} // [] } } map { @{ $_->{nodes} // [] } } @{ $res->{services} // [] }) {
Condition50%3/6
$_->{"match_context"} // []
l!l
450
$_->{"nodes"} // []
l!l
450
$res->{"services"} // []
l!l
450
MC/DC0%0/1
$_->{"match_context"} // []
$_->{"match_context"}
MC/DC0%0/1
$_->{"nodes"} // []
$_->{"nodes"}
MC/DC0%0/1
$res->{"services"} // []
$res->{"services"}
Truth table50%1/2
A
A= $_->{"match_context"}
Aresult
11
00
Truth table50%1/2
A
A= $_->{"nodes"}
Aresult
11
00
Truth table50%1/2
A
A= $res->{"services"}
Aresult
11
00
4170 # none of the 1382 hits for human haemoglobin alpha had more than
4171 # one match on 2026-10-21, but the format allows it
4172 45 ▶ $best = $m if !defined $best || $m->{bitscore} > $best->{bitscore};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $best or $m->{"bitscore"} > $best->{"bitscore"} 45 0 45
Condition33%1/3
not defined $best or $m->{"bitscore"} > $best->{"bitscore"}
l!l&&r!l&&!r
4500
MC/DC0%0/2
not defined $best or $m->{"bitscore"} > $best->{"bitscore"}
not defined $best $m->{"bitscore"} > $best->{"bitscore"}
Truth table33%1/3
not(A) or B
A= not defined $bestB= $m->{"bitscore"} > $best->{"bitscore"}
ABresult
1X1
011
000
4173 }
4174 45 ▶ croak "$sub: RCSB gave no alignment for $res->{identifier}" unless defined $best;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $best 0 45 45
4175 # An identifier is entry_entity: 1BZ1_1, or AF_AFP69905F1_1 for a computed model
4176 45 ▶ my ($entry, $entity) = $res->{identifier} =~ /\A(.+)_([^_]+)\z/
Branch: 1 branch
BranchTrueFalseTotal
() = $res->{"identifier"} =~ /\A(.+)_([^_]+)\z/ or croak(qq[${sub}: RCSB returned "$res->{"identifier"}", which isn't an entry_entity identifier]) 45 0 45
4177 or croak "$sub: RCSB returned \"$res->{identifier}\", which isn't an entry_entity identifier";
4178 push @hits, { id => $res->{identifier}, entry => $entry, entity => $entity,
4179 45 url => "https://www.rcsb.org/structure/$entry", %{ _pdb_alignment($best) } };
4180 }
4181  
4182 10 my %entity;
4183 10 ▶ for (my $i = 0; $i < @hits; $i += $Rcsb_batch) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @hits) 9 9 18
4184 9 ▶ my @ids = map { $_->{id} } @hits[$i .. ($i + $Rcsb_batch > @hits ? $#hits : $i + $Rcsb_batch - 1)];
Branch: 1 branch
BranchTrueFalseTotal
$i + $Rcsb_batch > @hits ? : 9 0 9
4185 9 my $data = _rcsb_post($sub, $Rcsb_data, { query => $Rcsb_entities, variables => { ids => \@ids } }, $r{timeout});
4186 9 ▶ my $list = ref $data eq 'HASH' && ref $data->{data} eq 'HASH' ? $data->{data}{polymer_entities} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' && ref $data->{'data'} eq 'HASH' ? : 8 1 9
Condition66%2/3
ref $data eq "HASH" and ref $data->{"data"} eq "HASH"
!ll&&!rl&&r
018
MC/DC50%1/2
ref $data eq "HASH" and ref $data->{"data"} eq "HASH"
ref $data eq "HASH" ref $data->{"data"} eq "HASH"
Truth table66%2/3
A and B
A= ref $data eq "HASH"B= ref $data->{"data"} eq "HASH"
ABresult
0X0
100
111
4187 9 ▶ unless (ref $list eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $list eq "ARRAY") 1 8 9
4188 1 ▶ my @why = map { $_->{message} // () } @{ ref $data eq 'HASH' && ref $data->{errors} eq 'ARRAY' ? $data->{errors} : [] };
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' && ref $data->{'errors'} eq 'ARRAY' ? : 1 0 1
Condition33%2/6
$_->{"message"} // ()
l!l&&r!l&&!r
100
ref $data eq "HASH" and ref $data->{"errors"} eq "ARRAY"
!ll&&!rl&&r
001
MC/DC0%0/2
$_->{"message"} // ()
$_->{"message"} ()
MC/DC0%0/2
ref $data eq "HASH" and ref $data->{"errors"} eq "ARRAY"
ref $data eq "HASH" ref $data->{"errors"} eq "ARRAY"
Truth table33%1/3
A // B
A= $_->{"message"}B= ()
ABresult
1X1
011
000
Truth table33%1/3
A and B
A= ref $data eq "HASH"B= ref $data->{"errors"} eq "ARRAY"
ABresult
0X0
100
111
4189 1 ▶ croak "$sub: $Rcsb_data said nothing of $ids[0]" . (@ids > 1 ? ' and the rest' : '') . (@why ? ': ' . join('; ', @why) : '');
Branch: 2 branches
BranchTrueFalseTotal
@ids > 1 ? : 1 0 1
@why ? : 1 0 1
4190 }
4191 8 $entity{ $_->{rcsb_id} } = $_ foreach grep { ref $_ eq 'HASH' } @{ $list };
4192 }
4193 9 foreach my $h (@hits) {
4194 # the search index can be ahead of the data API for a new release
4195 40 ▶ carp "$sub: $Rcsb_data had nothing on $h->{id}, so its structure fields are empty" unless $entity{ $h->{id} };
Branch: 1 branch
BranchTrueFalseTotal
unless $entity{$h->{"id"}} 1 39 40
4196 40 %{ $h } = (%{ $h }, %{ _pdb_structure($entity{ $h->{id} }) });
4197 }
4198 # Best first, as get_best_alignment_hit sorts on "evalue": RCSB rounds a
4199 # strong E-value to 0, so the bit score breaks ties, and then RCSB's order.
4200 9 ▶ my @order = sort { $hits[$a]{evalue} <=> $hits[$b]{evalue} || $hits[$b]{bit_score} <=> $hits[$a]{bit_score} || $a <=> $b } 0 .. $#hits;
Condition66%4/6
$hits[$a]{'evalue'} <=> $hits[$b]{'evalue'} || $hits[$b]{'bit_score'} <=> $hits[$a]{'bit_score'} || $a <=> $b
l!l&&r!l&&!r
40240
$hits[$a]{"evalue"} <=> $hits[$b]{"evalue"} or $hits[$b]{"bit_score"} <=> $hits[$a]{"bit_score"}
l!l&&r!l&&!r
40024
MC/DC0%0/3
$hits[$a]{'evalue'} <=> $hits[$b]{'evalue'} || $hits[$b]{'bit_score'} <=> $hits[$a]{'bit_score'} || $a <=> $b
$hits[$a]{"evalue"} <=> $hits[$b]{"evalue"} $hits[$b]{"bit_score"} <=> $hits[$a]{"bit_score"} $a <=> $b
Truth table50%2/4
A or B || C
A= $hits[$a]{"evalue"} <=> $hits[$b]{"evalue"}B= $hits[$b]{"bit_score"} <=> $hits[$a]{"bit_score"}C= $a <=> $b
ABCresult
1XX1
01X1
0011
0000
4201 9 @hits = @hits[@order];
4202 9 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 6 3 9
4203 6 my $text = _pdb_report(\%r, \@hits, $total);
4204 # RCSB's text is characters, and can hold some above 255 (a Greek
4205 # letter in a title), which print would warn of as a "Wide character",
4206 # fatally in a caller under FATAL warnings, unless STDOUT encodes.
4207 6 ▶ utf8::encode($text) unless grep { /\A(?:utf8|encoding)/ } PerlIO::get_layers(*STDOUT);
Branch: 1 branch
BranchTrueFalseTotal
unless grep {/\A(?:utf8|encoding)/;} &PerlIO::get_layers(\*STDOUT) 6 0 6
4208 6 ▶ print STDOUT $text or croak "$sub: can't print the report: $!";
Branch: 1 branch
BranchTrueFalseTotal
print STDOUT $text or croak("${sub}: can't print the report: $!") 6 0 6
4209 }
4210 9 ▶ wantarray ? (\@hits, $total) : \@hits;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 9 0 9
4211 }
4212  
4213 # ---- alignment plots and tables
4214  
4215 # Dies unless $n, given to $sub as $what, is a 1-based residue number. Without
4216 # this, 0 and the negative numbers index @col from its end in plot_msa and
4217 # view_alignment, and silently mean the last residues.
4218 31 ▶sub _residue_number {
Subroutine _residue_number: called CC=4 SCAR=14.3
4219 31 my ($sub, $what, $n) = @_;
4220 31 ▶ croak "$sub: $what must be a residue number, 1 or more, not " . (defined $n ? "\"$n\"" : 'undef')
Branch: 2 branches
BranchTrueFalseTotal
unless defined $n and $n =~ /\A[1-9][0-9]*\z/ 7 24 31
defined $n ? : 7 0 7
Condition66%2/3
defined $n and $n =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
0724
MC/DC50%1/2
defined $n and $n =~ /\A[1-9][0-9]*\z/
defined $n $n =~ /\A[1-9][0-9]*\z/
Truth table66%2/3
A and B
A= defined $nB= $n =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
4221 unless defined $n && $n =~ /\A[1-9][0-9]*\z/;
4222 }
4223  
4224 # "fasta" -- a FASTA file name or a hash ref of name => sequence -- written to a
4225 # temporary FASTA file with its gaps stripped, so that an input that is already
4226 # aligned is aligned afresh. clustalo's --dealign does the same, but prints a
4227 # "FORCED DEBUG" warning about them first; blastp would take a gap for a residue.
4228 # Returns that file and the sequence names in input order (sorted for a hash).
4229 # With $numbered, each sequence is written under its number in that order, "s1",
4230 # "s2" and so on, rather than its name, for clustalo: it cuts a name at its
4231 # first space in the guide tree and writes "(),:" in one unquoted, which drew 4
4232 # sequences as 5 tips up to 2026-10-17. _unnumber_fasta and _unnumber_newick put
4233 # the names back. Dies naming $sub, whose "fasta" it is, for a sequence that is
4234 # not a string or that has no residues once its gaps are gone, which clustalo
4235 # and blastp would otherwise be given.
4236 7 ▶sub _ungapped_fasta {
Subroutine _ungapped_fasta: called CC=8 SCAR=21.0
4237 7 my ($sub, $fasta, $numbered) = @_;
4238 7 my ($seqs, @names);
4239 7 ▶ if (ref $fasta eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $fasta eq 'HASH') { } 6 1 7
elsif (ref $fasta eq '') { } 0 1 1
4240 6 $seqs = $fasta;
4241 6 @names = sort keys %{ $seqs };
4242 } elsif (ref $fasta eq '') {
4243 0 my $order;
4244 0 ($seqs, $order) = _fasta_ordered($fasta);
4245 0 @names = @{ $order };
4246 } else {
4247 1 croak "$sub: \"fasta\" must be a FASTA file name or a hash ref of name => sequence, not " . _what($fasta);
4248 }
4249 6 ▶ my @written = $numbered ? map { "s$_" } 1 .. @names : @names;
Branch: 1 branch
BranchTrueFalseTotal
$numbered ? : 5 1 6
4250 6 my %ungapped;
4251 6 foreach my $i (0 .. $#names) {
4252 12 my $s = $seqs->{ $names[$i] };
4253 12 ▶ croak "$sub: \"fasta\" sequence \"$names[$i]\" must be a string of residues, not " . _what($s) unless defined $s && !ref $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s and not ref $s 2 10 12
Condition100%3/3
defined $s and not ref $s
!ll&&!rl&&r
1110
MC/DC100%2/2
defined $s and not ref $s
defined $s not ref $s
Truth table100%3/3
A and not(B)
A= defined $sB= not ref $s
ABresult
0X0
100
111
4254 10 $s =~ tr/-.//d;
4255 10 ▶ croak "$sub: \"fasta\" sequence \"$names[$i]\" has no residues" if $s eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $s eq "" 3 7 10
4256 7 $ungapped{ $written[$i] } = $s;
4257 }
4258 1 (_fasta_file('_ungapped_fasta', \%ungapped, _tmp('.fa'), \@written, 80), \@names);
4259 }
4260  
4261 # The name that clustalo's "s<n>" in $file stands for, from @$names, the list
4262 # _ungapped_fasta numbered.
4263 0 ▶sub _unnumber {
Subroutine _unnumber: not called CC=3 SCAR=24.8
4264 0 my ($id, $names, $file) = @_;
4265 0 croak "_unnumber: clustalo wrote \"$id\" in $file, which isn't one of the s1 to s" . scalar(@{ $names }) . ' it was given'
4266 0 ▶ unless $id =~ /\As([1-9][0-9]*)\z/ && $1 <= @{ $names };
Branch: 1 branch
BranchTrueFalseTotal
unless $id =~ /\As([1-9][0-9]*)\z/ and $1 <= @{$names;} 0 0 0
Condition0%0/3
$id =~ /\As([1-9][0-9]*)\z/ and $1 <= @{$names;}
!ll&&!rl&&r
000
MC/DC0%0/2
$id =~ /\As([1-9][0-9]*)\z/ and $1 <= @{$names;}
$id =~ /\As([1-9][0-9]*)\z/ $1 <= @{$names;}
Truth table0%0/3
A and B
A= $id =~ /\As([1-9][0-9]*)\z/B= $1 <= @{$names;}
ABresult
0X0
100
111
4267 0 $names->[$1 - 1];
4268 }
4269  
4270 # The alignment clustalo wrote to $file under _ungapped_fasta's numbers,
4271 # rewritten in place under the names in @$names, as UTF-8, in clustalo's order
4272 # and 60-column lines. Returns the aligned sequences as a hash ref keyed by
4273 # those names as perl was given them, which a name's UTF-8 may not equal.
4274 0 ▶sub _unnumber_fasta {
Subroutine _unnumber_fasta: not called CC=2 SCAR=17.9
4275 0 my ($file, $names) = @_;
4276 0 my ($numbered, $ids) = _fasta_ordered($file);
4277 0 my (%aln, %utf8);
4278 0 foreach my $id (@{ $ids }) {
4279 0 my $name = _unnumber($id, $names, $file);
4280 0 $aln{$name} = $utf8{ _utf8($name) } = $numbered->{$id};
4281 }
4282 0 _fasta_file('_unnumber_fasta', \%utf8, $file, [map { _utf8(_unnumber($_, $names, $file)) } @{ $ids }], 60);
4283 0 \%aln;
4284 }
4285  
4286 # The guide tree clustalo wrote to $file under _ungapped_fasta's numbers,
4287 # rewritten in place under the names in @$names, as UTF-8. A name holding
4288 # whitespace or any of "()[]':;," is quoted as newick quotes one: in single
4289 # quotes, each of its own doubled.
4290 0 ▶sub _unnumber_newick {
Subroutine _unnumber_newick: not called CC=6 SCAR=37.4
4291 0 my ($file, $names) = @_;
4292 0 ▶ open my $fh, '<:raw', $file or croak "_unnumber_newick: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $file or croak("_unnumber_newick: can't read ${file}: $!") 0 0 0
4293 0 my $tree = do { local $/; <$fh> };
4294 0 ▶ close $fh or croak "_unnumber_newick: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("_unnumber_newick: can't read ${file}: $!") 0 0 0
4295 0 $tree =~ s{(?<=[(,\s])(s[0-9]+)(?=\s*[:,);])}{
4296 0 my $name = _utf8(_unnumber($1, $names, $file));
4297 0 ▶ $name =~ /[\s()\[\]':;,]/ ? "'" . join("''", split /'/, $name, -1) . "'" : $name;
Branch: 1 branch
BranchTrueFalseTotal
$name =~ /[\s()\[\]':;,]/ ? : 0 0 0
4298 }ge;
4299 0 ▶ open $fh, '>:raw', $file or croak "_unnumber_newick: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open $fh, ">:raw", $file or croak("_unnumber_newick: can't write ${file}: $!") 0 0 0
4300 0 print {$fh} $tree;
4301 0 ▶ close $fh or croak "_unnumber_newick: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("_unnumber_newick: can't write ${file}: $!") 0 0 0
4302 }
4303  
4304 # Aligns "fasta" with clustalo for $sub. The alignment goes to "msa_file" and
4305 # the guide tree to "tree_file" when those are given, and to temporary files
4306 # otherwise; the tree is not asked for at all unless it is kept or $want_tree.
4307 # Returns the hash ref of files to report (the alignment always, the tree only
4308 # when it was named), the tree's file, the sequence names in input order
4309 # (sorted for a hash), an array ref of the clustalo command as it was run, with
4310 # the ungapped FASTA it read as its "--in", and the aligned sequences as a hash
4311 # ref keyed by those names; or nothing, after a warning, for fewer than 2
4312 # sequences. clustalo is given the sequences numbered, and the alignment and
4313 # tree it writes get their names back.
4314 6 ▶sub _align {
Subroutine _align: called CC=11 SCAR=38.2
4315 6 my ($args, $sub, $want_tree) = @_;
4316 6 my ($in, $names) = _ungapped_fasta($sub, $args->{fasta}, 1);
4317 1 ▶ if (@{ $names } < 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$names;} < 2) 0 1 1
4318 0 ▶ carp "$sub: clustalo needs at least 2 sequences, and there " . (@{ $names } ? 'is only 1' : 'are none');
Branch: 1 branch
BranchTrueFalseTotal
@{$names;} ? : 0 0 0
4319 0 return;
4320 }
4321 1 ▶ my %r = ('msa_file' => $args->{'msa_file'} // _tmp('.aln.fa'));
Condition33%1/3
$args->{"msa_file"} // _tmp(".aln.fa")
l!l&&r!l&&!r
010
MC/DC0%0/2
$args->{"msa_file"} // _tmp(".aln.fa")
$args->{"msa_file"} _tmp(".aln.fa")
Truth table33%1/3
A // B
A= $args->{"msa_file"}B= _tmp(".aln.fa")
ABresult
1X1
011
000
4322 1 ▶ my $tree = $args->{'tree_file'} // ($want_tree ? _tmp('.newick') : undef);
Branch: 1 branch
BranchTrueFalseTotal
$want_tree ? : 0 1 1
Condition33%1/3
$args->{"tree_file"} // ($want_tree ? _tmp(".newick") : undef)
l!l&&r!l&&!r
001
MC/DC0%0/2
$args->{"tree_file"} // ($want_tree ? _tmp(".newick") : undef)
$args->{"tree_file"} ($want_tree ? _tmp(".newick") : undef)
Truth table33%1/3
A // B
A= $args->{"tree_file"}B= ($want_tree ? _tmp(".newick") : undef)
ABresult
1X1
011
000
4323 1 ▶ $r{'tree_file'} = $tree if defined $args->{'tree_file'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"tree_file"} 0 1 1
4324 my @cmd = (_alien($sub)->clustalo, '--in', $in, '--out', $r{'msa_file'}, '--outfmt=fa', '--force',
4325 0 ▶ '--threads', $args->{threads} // 1, (defined $tree ? "--guidetree-out=$tree" : ()), @{ $args->{'clustal_args'} // [] });
Branch: 1 branch
BranchTrueFalseTotal
defined $tree ? : 0 0 0
Condition0%0/4
$args->{"threads"} // 1
l!l
00
$args->{"clustal_args"} // []
l!l
00
MC/DC0%0/1
$args->{"threads"} // 1
$args->{"threads"}
MC/DC0%0/1
$args->{"clustal_args"} // []
$args->{"clustal_args"}
Truth table0%0/2
A
A= $args->{"threads"}
Aresult
11
00
Truth table0%0/2
A
A= $args->{"clustal_args"}
Aresult
11
00
4326 0 _run(@cmd);
4327 0 my $aln = _unnumber_fasta($r{'msa_file'}, $names);
4328 0 ▶ _unnumber_newick($tree, $names) if defined $tree;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tree 0 0 0
4329 0 (\%r, $tree, $names, \@cmd, $aln);
4330 }
4331  
4332 27 ▶sub plot_msa {
Subroutine plot_msa: called CC=29 SCAR=56.5
Pod documented
4333 27 my $sub = 'plot_msa';
4334 27 my $args = _args(\@_, $sub, [qw(fasta filename)], [qw(active_site_aa clustal_args execute fh labels msa_file order query threads title
4335 tooltips tree_file xlabel ylabel)]);
4336 27 _refs($sub, $args, 'ARRAY', qw(clustal_args order));
4337 25 _refs($sub, $args, 'HASH', 'labels');
4338 24 _file_names($sub, $args, qw(filename msa_file tree_file));
4339 20 _threads($sub, $args);
4340 18 my $drawing = _drawing($sub, $args);
4341 13 ▶ my $tooltips = $args->{'tooltips'} // 0; # 1 = a tooltip naming each residue, in an SVG; 0 = none
Condition100%2/2
$args->{"tooltips"} // 0
l!l
211
MC/DC100%1/1
$args->{"tooltips"} // 0
$args->{"tooltips"}
Truth table100%2/2
A
A= $args->{"tooltips"}
Aresult
11
00
4342 13 ▶ croak "$sub: \"tooltips\" must be 0 or 1, not " . _what($tooltips) unless !ref $tooltips && ($tooltips eq '0' || $tooltips eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $tooltips and $tooltips eq 0 || $tooltips eq 1 1 12 13
Condition83%5/6
not ref $tooltips and $tooltips eq 0 || $tooltips eq 1
!ll&&!rl&&r
0112
$tooltips eq 0 or $tooltips eq 1
l!l&&r!l&&!r
1111
MC/DC66%2/3
not ref $tooltips and $tooltips eq 0 || $tooltips eq 1
not ref $tooltips $tooltips eq 0 $tooltips eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $tooltipsB= $tooltips eq 0C= $tooltips eq 1
ABCresult
0XX0
1000
11X1
1011
4343 croak "$sub: \"tooltips\" needs an SVG \"filename\", the only format that carries them, not \"$args->{filename}\""
4344 12 ▶ if $tooltips && $args->{filename} !~ /\.svg\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $tooltips and not $args->{"filename"} =~ /\.svg\z/i 1 11 12
Condition66%2/3
$tooltips and not $args->{"filename"} =~ /\.svg\z/i
!ll&&!rl&&r
1101
MC/DC50%1/2
$tooltips and not $args->{"filename"} =~ /\.svg\z/i
$tooltips not $args->{"filename"} =~ /\.svg\z/i
Truth table66%2/3
A and not(B)
A= $tooltipsB= not $args->{"filename"} =~ /\.svg\z/i
ABresult
0X0
100
111
4345 11 my $sites = $args->{'active_site_aa'};
4346 11 ▶ if (defined $sites) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sites) 5 6 11
4347 5 ▶ croak "$sub: \"active_site_aa\" must be a hash ref of label => residue number" unless ref $sites eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $sites eq "HASH" 1 4 5
4348 4 ▶ croak "$sub: needs \"query\" to place \"active_site_aa\"" unless defined $args->{query};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args->{"query"} 0 4 4
4349 4 _residue_number($sub, "active site $_", $sites->{$_}) foreach sort keys %{ $sites };
4350 }
4351 6 ▶ my ($r, undef, $names, $cmd, $aln) = _align($args, $sub, 0) or return {};
Branch: 1 branch
BranchTrueFalseTotal
my($r, undef, $names, $cmd, $aln) = _align($args, $sub, 0) or return {} 0 0 0
4352 0 ▶ my @order = @{ $args->{order} // $names };
Condition0%0/3
$args->{"order"} // $names
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{"order"} // $names
$args->{"order"} $names
Truth table0%0/3
A // B
A= $args->{"order"}B= $names
ABresult
1X1
011
000
4353 0 my @unknown = grep { !defined $aln->{$_} } @order;
4354 0 ▶ croak "$sub: \"order\" names sequences that aren't in the alignment: @unknown" if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 0 0 0
4355 0 ▶ my $labels = $args->{labels} // {};
Condition0%0/2
$args->{"labels"} // {}
l!l
00
MC/DC0%0/1
$args->{"labels"} // {}
$args->{"labels"}
Truth table0%0/2
A
A= $args->{"labels"}
Aresult
11
00
4356 # Each name as msa_plot.py is to show it, in UTF-8, which is what it reads.
4357 # Up to 2026-10-17 the name was written as perl held it, Latin-1 or UTF-8,
4358 # and Python died on the Latin-1.
4359 0 ▶ my %shown_as = map { $_ => _utf8($labels->{$_} // $_) } @order;
Condition0%0/3
$labels->{$_} // $_
l!l&&r!l&&!r
000
MC/DC0%0/2
$labels->{$_} // $_
$labels->{$_} $_
Truth table0%0/3
A // B
A= $labels->{$_}B= $_
ABresult
1X1
011
000
4360 # Two sequences shown under one label would be one row of the image, fed
4361 # two deflines.
4362 0 my %by_label;
4363 0 push @{ $by_label{ $shown_as{$_} } }, $_ foreach @order;
4364 0 foreach my $label (sort keys %by_label) {
4365 0 croak "$sub: " . join(', ', map { "\"$_\"" } @{ $by_label{$label} }) . " would all be drawn as \"$label\""
4366 0 ▶ if @{ $by_label{$label} } > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @{$by_label{$label};} > 1 0 0 0
4367 }
4368 0 my @segments;
4369 0 ▶ if (defined $sites) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sites) 0 0 0
4370 0 ▶ my $q = $aln->{ $args->{query} } // croak "$sub: the query \"$args->{query}\" isn't in the alignment";
Condition0%0/2
$$aln{$args->{"query"}} // croak(qq[${sub}: the query "$args->{"query"}" isn't in the alignment])
l!l
00
MC/DC0%0/1
$$aln{$args->{"query"}} // croak(qq[${sub}: the query "$args->{"query"}" isn't in the alignment])
$$aln{$args->{"query"}}
Truth table0%0/2
A
A= $$aln{$args->{"query"}}
Aresult
11
00
4371 # 1-based residue number => 0-based alignment column
4372 0 my (@col, %sites);
4373 0 ▶ while ($q =~ /[^-]/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($q =~ /[^-]/g) 0 0 0
4374 0 push @col, pos($q) - 1;
4375 }
4376 0 foreach my $label (sort keys %{ $sites }) {
4377 0 my $n = $sites->{$label};
4378 0 ▶ $sites{$label} = $col[$n - 1] // croak "$sub: active site $label ($n) is past the end of \"$args->{query}\", which has " . scalar(@col) . ' residues';
Condition0%0/2
$col[$n - 1] // croak(qq[${sub}: active site $label ($n) is past the end of "$args->{"query"}", which has ] . scalar(@col) . ' residues')
l!l
00
MC/DC0%0/1
$col[$n - 1] // croak(qq[${sub}: active site $label ($n) is past the end of "$args->{"query"}", which has ] . scalar(@col) . ' residues')
$col[$n - 1]
Truth table0%0/2
A
A= $col[$n - 1]
Aresult
11
00
4379 }
4380 0 @segments = ('--s', _json_text({ map { _chars($_) => 0 + $sites{$_} } keys %sites }));
4381 }
4382 0 my %shown = map { $shown_as{$_} => $aln->{$_} } @order;
4383 0 my $fa = _fasta_file($sub, \%shown, _tmp('.fa'), [@shown_as{@order}], 0);
4384 $r->{'python_file'} = _draw($sub, $drawing, '--f', $fa, '--o', $args->{filename}, '--c', _creator($sub), '--quiet',
4385 0 ▶ '--p', _json_text([map { _chars($_) } _align_provenance($args, $sub, $cmd, $names, $r->{'msa_file'}), _kept($args, qw(msa_file tree_file))]),
Branch: 4 branches
BranchTrueFalseTotal
defined $args->{'title'} ? : 0 0 0
defined $args->{'xlabel'} ? : 0 0 0
defined $args->{'ylabel'} ? : 0 0 0
$tooltips ? : 0 0 0
4386 (defined $args->{title} ? ('--t', $args->{title}) : ()),
4387 (defined $args->{xlabel} ? ('--x', $args->{xlabel}) : ()),
4388 (defined $args->{ylabel} ? ('--y', $args->{ylabel}) : ()), @segments,
4389 # the tooltips name each sequence as perl was given it, not by its label, which may be mathtext
4390 0 ($tooltips ? ('--tips', _json_text([map { _chars($_) } @order])) : ()));
4391 0 ▶ _wrote($args->{filename}, 43, $drawing->{execute} ? 'wrote' : 'will write'); # yellow
Branch: 1 branch
BranchTrueFalseTotal
$drawing->{'execute'} ? : 0 0 0
4392 0 $r->{filename} = $args->{filename};
4393 0 $r;
4394 }
4395  
4396 # "path (SHA-256 hex)" of an existing file, for the provenance of an image.
4397 6 ▶sub _file_id {
Subroutine _file_id: called CC=1 SCAR=0.0
4398 6 my ($file) = @_;
4399 6 require Digest::SHA;
4400 6 require File::Spec;
4401 6 File::Spec->rel2abs($file) . ' (SHA-256 ' . Digest::SHA->new(256)->addfile($file, 'b')->hexdigest . ')';
4402 }
4403  
4404 # "fasta" as an image's Creator names it: a file by its path and digest, a hash
4405 # ref by its size, since its contents were never on disk until
4406 # _ungapped_fasta wrote them.
4407 14 ▶sub _fasta_id {
Subroutine _fasta_id: called CC=2 SCAR=6.9
4408 14 my ($fasta, $n) = @_;
4409 14 ▶ ref $fasta ? "a hash ref of $n sequences" : 'the FASTA file ' . _file_id($fasta) . " of $n sequences";
Branch: 1 branch
BranchTrueFalseTotal
ref $fasta ? : 9 5 14
4410 }
4411  
4412 # The files named in @keys of $args that were written and kept beside an
4413 # image, as a clause of its Creator, or nothing when none was.
4414 0 ▶sub _kept {
Subroutine _kept: not called CC=4 SCAR=30.0
4415 0 my ($args, @keys) = @_;
4416 0 require File::Spec;
4417 0 ▶ my @kept = map { defined $args->{$_} && !ref $args->{$_} ? "$_ " . File::Spec->rel2abs($args->{$_}) : () } @keys;
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{$_} && !ref($args->{$_}) ? : 0 0 0
Condition0%0/3
defined $args->{$_} and not ref $args->{$_}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $args->{$_} and not ref $args->{$_}
defined $args->{$_} not ref $args->{$_}
Truth table0%0/3
A and not(B)
A= defined $args->{$_}B= not ref $args->{$_}
ABresult
0X0
100
111
4418 0 ▶ @kept ? 'kept with it: ' . join(', ', @kept) : ();
Branch: 1 branch
BranchTrueFalseTotal
@kept ? : 0 0 0
4419 }
4420  
4421 # A command as it could be pasted into a POSIX shell, for an image's Creator:
4422 # an argument that holds anything but the characters listed, or nothing at all,
4423 # goes between apostrophes, and an apostrophe inside it is written '\''.
4424 1 ▶sub _cmd_text {
Subroutine _cmd_text: called CC=3 SCAR=11.0
4425 join ' ', map {
4426 1 (my $s = $_) =~ s/'/'\\''/g;
4427 5 ▶ $s eq '' || $s =~ /[^\w\/.,:=+-]/ ? "'$s'" : $s;
Branch: 1 branch
BranchTrueFalseTotal
$s eq '' || $s =~ m[[^\w/.,:=+-]] ? : 2 3 5
Condition100%3/3
$s eq "" or $s =~ m[[^\w/.,:=+-]]
l!l&&r!l&&!r
113
MC/DC100%2/2
$s eq "" or $s =~ m[[^\w/.,:=+-]]
$s eq "" $s =~ m[[^\w/.,:=+-]]
Truth table100%3/3
A or B
A= $s eq ""B= $s =~ m[[^\w/.,:=+-]]
ABresult
1X1
011
000
4428 } @_;
4429 }
4430  
4431 # How _align made an alignment, as one clause of an image's Creator: what
4432 # Clustal Omega read, which version ran, what it wrote and the command. $cmd,
4433 # $names and $msa are what _align returned.
4434 0 ▶sub _align_provenance {
Subroutine _align_provenance: not called CC=1 SCAR=6.9
4435 0 my ($args, $sub, $cmd, $names, $msa) = @_;
4436 0 my $alien = _alien($sub);
4437 # $cmd->[2] is clustalo's "--in", the ungapped copy _ungapped_fasta wrote
4438 0 'from ' . _fasta_id($args->{fasta}, scalar @{ $names }) . ', written with its gaps stripped and the sequences numbered s1 to s'
4439 0 . scalar(@{ $names }) . ' to ' . _file_id($cmd->[2]) . ', which Clustal Omega ' . $alien->versions->{clustalo}
4440 . " from Alien::Bioinf $Alien::Bioinf::VERSION aligned into " . _file_id($msa) . ' (with the names put back), run as: '
4441 0 . _cmd_text(@{ $cmd });
4442 }
4443  
4444 9 ▶sub plot_phylo {
Subroutine plot_phylo: called CC=13 SCAR=48.2
Pod documented
4445 9 my $sub = 'plot_phylo';
4446 9 my $args = _args(\@_, $sub, [], [qw(clustal_args execute fasta fh labels msa_file output_file threads title tree_file)]);
4447 9 _refs($sub, $args, 'ARRAY', 'clustal_args');
4448 8 _refs($sub, $args, 'HASH', 'labels');
4449 7 _file_names($sub, $args, qw(msa_file output_file tree_file));
4450 6 _threads($sub, $args);
4451 5 my $drawing = _drawing($sub, $args);
4452 0 ▶ $args->{output_file} //= 'phylo.svg';
Condition0%0/2
$args->{"output_file"} //= "phylo.svg"
l!l
00
MC/DC0%0/1
$args->{"output_file"} //= "phylo.svg"
$args->{"output_file"}
Truth table0%0/2
A
A= $args->{"output_file"}
Aresult
11
00
4453 0 my ($r, $tree, $names, $cmd);
4454 0 ▶ if (defined $args->{fasta}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{'fasta'}) { } 0 0 0
4455 0 ▶ ($r, $tree, $names, $cmd) = _align($args, $sub, 1) or return {};
Branch: 1 branch
BranchTrueFalseTotal
() = _align($args, $sub, 1) or return {} 0 0 0
4456 } else {
4457 # no alignment to make, so "tree_file" is the tree to draw, not where to keep one
4458 0 ▶ $tree = $args->{'tree_file'} // croak "$sub: needs \"fasta\" to align, or \"tree_file\" to draw";
Condition0%0/2
$args->{"tree_file"} // croak(qq[${sub}: needs "fasta" to align, or "tree_file" to draw])
l!l
00
MC/DC0%0/1
$args->{"tree_file"} // croak(qq[${sub}: needs "fasta" to align, or "tree_file" to draw])
$args->{"tree_file"}
Truth table0%0/2
A
A= $args->{"tree_file"}
Aresult
11
00
4459 0 my @moot = grep { defined $args->{$_} } qw(clustal_args msa_file threads);
4460 0 ▶ croak "$sub: was given " . join(', ', map { "\"$_\"" } @moot) . ' but no "fasta" to align' if @moot;
Branch: 1 branch
BranchTrueFalseTotal
if @moot 0 0 0
4461 0 ▶ croak "$sub: \"$tree\" doesn't exist or isn't a readable file" unless -f $tree && -r _;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $tree and -r _ 0 0 0
Condition0%0/3
-f $tree and -r _
!ll&&!rl&&r
000
MC/DC0%0/2
-f $tree and -r _
-f $tree -r _
Truth table0%0/3
A and B
A= -f $treeB= -r _
ABresult
0X0
100
111
4462 0 $r = { 'tree_file' => $tree };
4463 }
4464 0 ▶ my $labels = $args->{labels} // {};
Condition0%0/2
$args->{"labels"} // {}
l!l
00
MC/DC0%0/1
$args->{"labels"} // {}
$args->{"labels"}
Truth table0%0/2
A
A= $args->{"labels"}
Aresult
11
00
4465 my @prov = defined $cmd
4466 0 ▶ ? (_align_provenance($args, $sub, $cmd, $names, $r->{'msa_file'}), 'drawing the guide tree it wrote, ' . _file_id($tree),
Branch: 1 branch
BranchTrueFalseTotal
defined $cmd ? : 0 0 0
4467 _kept($args, qw(msa_file tree_file)))
4468 : ('from the newick file ' . _file_id($tree));
4469 # the tips are named in UTF-8 by _unnumber_newick, which msa_plot.py decodes
4470 $r->{'python_file'} = _draw($sub, $drawing, '--tree', $tree, '--o', $args->{'output_file'}, '--c', _creator($sub), '--quiet',
4471 0 ▶ '--p', _json_text([map { _chars($_) } @prov]),
Branch: 2 branches
BranchTrueFalseTotal
defined $args->{'title'} ? : 0 0 0
%{$labels;} ? : 0 0 0
4472 (defined $args->{title} ? ('--t', $args->{title}) : ()),
4473 0 (%{ $labels } ? ('--l', _json_text({ map { _chars($_) => _chars($labels->{$_}) } keys %{ $labels } })) : ()));
4474 0 $r->{'output_file'} = $args->{'output_file'};
4475 0 ▶ _wrote($args->{output_file}, 43, $drawing->{execute} ? 'wrote' : 'will write'); # yellow
Branch: 1 branch
BranchTrueFalseTotal
$drawing->{'execute'} ? : 0 0 0
4476 0 $r;
4477 }
4478  
4479 18 ▶sub msa_quality_table {
Subroutine msa_quality_table: called CC=89 SCAR=66.3
Pod documented
4480 18 my $sub = 'msa_quality_table';
4481 18 my $args = _args(\@_, $sub, ['filename'], [qw(alignment_json cb_label cb_max cb_min cblogscale default_undefined fasta
4482 logscale_add metric msa_file normalize order show_numbers title unaligned_fa)]);
4483 18 _refs($sub, $args, 'ARRAY', 'order');
4484 17 _file_names($sub, $args, qw(filename msa_file));
4485 # Each is added to, divided by or compared with a score. Up to 2026-11-10
4486 # one that was not a number only warned "isn't numeric", and was drawn as 0.
4487 16 foreach my $k (qw(cb_max cb_min default_undefined logscale_add normalize)) {
4488 croak "$sub: \"$k\" must be a number, not " . _what($args->{$k})
4489 70 ▶ if defined $args->{$k} && (ref $args->{$k} || $args->{$k} !~ $Number);
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{$k} and ref $args->{$k} || !($args->{$k} =~ /$Number/) 5 65 70
Condition100%6/6
defined $args->{$k} and ref $args->{$k} || !($args->{$k} =~ /$Number/)
!ll&&!rl&&r
6415
ref $args->{$k} or not $args->{$k} =~ /$Number/
l!l&&r!l&&!r
141
MC/DC100%3/3
defined $args->{$k} and ref $args->{$k} || !($args->{$k} =~ /$Number/)
defined $args->{$k} ref $args->{$k} not $args->{$k} =~ /$Number/
Truth table100%4/4
A and B or not(C)
A= defined $args->{$k}B= ref $args->{$k}C= not $args->{$k} =~ /$Number/
ABCresult
0XX0
1000
11X1
1011
4490 }
4491 11 my %metric = map { $_ => 1 } qw(num bit_score score evalue identity positive align_len);
4492 11 ▶ my $metric = $args->{metric} // 'score';
Condition50%1/2
$args->{"metric"} // "score"
l!l
110
MC/DC0%0/1
$args->{"metric"} // "score"
$args->{"metric"}
Truth table50%1/2
A
A= $args->{"metric"}
Aresult
11
00
4493 11 ▶ croak "$sub: \"$metric\" isn't one of the metrics: " . join(', ', sort keys %metric) unless $metric{$metric};
Branch: 1 branch
BranchTrueFalseTotal
unless $metric{$metric} 0 11 11
4494 # "unaligned_fa" is the old name for "fasta"
4495 11 ▶ croak "$sub: was given both \"fasta\" and \"unaligned_fa\", which are the same thing" if defined $args->{fasta} && defined $args->{'unaligned_fa'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"fasta"} and defined $args->{"unaligned_fa"} 0 11 11
Condition66%2/3
defined $args->{"fasta"} and defined $args->{"unaligned_fa"}
!ll&&!rl&&r
1010
MC/DC0%0/2
defined $args->{"fasta"} and defined $args->{"unaligned_fa"}
defined $args->{"fasta"} defined $args->{"unaligned_fa"}
Truth table66%2/3
A and B
A= defined $args->{"fasta"}B= defined $args->{"unaligned_fa"}
ABresult
0X0
100
111
4496 11 ▶ my $fasta = $args->{fasta} // $args->{'unaligned_fa'};
Condition66%2/3
$args->{"fasta"} // $args->{"unaligned_fa"}
l!l&&r!l&&!r
1010
MC/DC50%1/2
$args->{"fasta"} // $args->{"unaligned_fa"}
$args->{"fasta"} $args->{"unaligned_fa"}
Truth table66%2/3
A // B
A= $args->{"fasta"}B= $args->{"unaligned_fa"}
ABresult
1X1
011
000
4497 # All-against-all blastp of the sequences: given as the parsed report, read
4498 # from "alignment_json", or -- when that file does not exist yet, or none is
4499 # named -- made by running blastp on "fasta", and kept in "alignment_json"
4500 # for next time if that is named.
4501 11 my $aj = $args->{'alignment_json'};
4502 11 ▶ croak "$sub: \"alignment_json\" must be a file name or a hash ref, not " . _what($aj) if ref $aj && ref $aj ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $aj and ref $aj ne "HASH" 1 10 11
Condition100%3/3
ref $aj and ref $aj ne "HASH"
!ll&&!rl&&r
371
MC/DC100%2/2
ref $aj and ref $aj ne "HASH"
ref $aj ref $aj ne "HASH"
Truth table100%3/3
A and B
A= ref $ajB= ref $aj ne "HASH"
ABresult
0X0
100
111
4503 10 my ($blast, $prov);
4504 10 ▶ if (ref $aj eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $aj eq 'HASH') { } 7 3 10
elsif (defined $aj and -f $aj) { } 2 1 3
4505 7 $blast = $aj;
4506 7 $prov = 'from a BLAST report given as a hash ref';
4507 ▶ } elsif (defined $aj && -f $aj) {
Condition66%2/3
defined $aj and -f $aj
!ll&&!rl&&r
102
MC/DC50%1/2
defined $aj and -f $aj
defined $aj -f $aj
Truth table66%2/3
A and B
A= defined $ajB= -f $aj
ABresult
0X0
100
111
4508 2 $blast = _json_file($sub, $aj);
4509 1 $prov = 'from the BLAST report ' . _file_id($aj);
4510 } else {
4511 1 ▶ croak "$sub: needs \"fasta\" to align, or an existing \"alignment_json\"" . (defined $aj ? " ($aj doesn't exist yet)" : '')
Branch: 2 branches
BranchTrueFalseTotal
unless defined $fasta 0 1 1
defined $aj ? : 0 0 0
4512 unless defined $fasta;
4513 1 my ($in, $names) = _ungapped_fasta($sub, $fasta);
4514 0 ▶ $aj //= _tmp('.json');
Condition0%0/3
$aj //= _tmp(".json")
l!l&&r!l&&!r
000
MC/DC0%0/2
$aj //= _tmp(".json")
$aj _tmp(".json")
Truth table0%0/3
A //= B
A= $ajB= _tmp(".json")
ABresult
1X1
011
000
4515 0 my $alien = _alien($sub);
4516 0 my @cmd = ($alien->blast('blastp'), '-query', $in, '-subject', $in, '-out', $aj, '-outfmt', 15);
4517 0 _run(@cmd);
4518 0 $blast = _json_file($sub, $aj);
4519 0 $prov = 'from ' . _fasta_id($fasta, scalar @{ $names }) . ', written with its gaps stripped to ' . _file_id($in)
4520 0 . ', which blastp ' . $alien->versions->{blast} . " from Alien::Bioinf $Alien::Bioinf::VERSION compared all against all into "
4521 . _file_id($aj) . ', run as: ' . _cmd_text(@cmd);
4522 0 $prov = join '; ', $prov, _kept($args, 'alignment_json');
4523 }
4524 croak "$sub: \"alignment_json\" isn't a BLAST report in JSON (-outfmt 15): it has no \"BlastOutput2\" array"
4525 8 ▶ unless ref $blast eq 'HASH' && ref $blast->{BlastOutput2} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $blast eq "HASH" and ref $blast->{"BlastOutput2"} eq "ARRAY" 1 7 8
Condition66%2/3
ref $blast eq "HASH" and ref $blast->{"BlastOutput2"} eq "ARRAY"
!ll&&!rl&&r
107
MC/DC50%1/2
ref $blast eq "HASH" and ref $blast->{"BlastOutput2"} eq "ARRAY"
ref $blast eq "HASH" ref $blast->{"BlastOutput2"} eq "ARRAY"
Truth table66%2/3
A and B
A= ref $blast eq "HASH"B= ref $blast->{"BlastOutput2"} eq "ARRAY"
ABresult
0X0
100
111
4526 # The report's shape is checked as it is read. Up to 2026-11-10 a report
4527 # that was not an object, or "hits" that was not an array, died with perl's
4528 # "Can't use string as a HASH ref" or "Not an ARRAY reference", naming no
4529 # function. A report with no bl2seq, as a search of a database has, holds no
4530 # pair, and is left for the message below.
4531 7 my (%data, $max);
4532 7 my %known; # every query the report names, whether or not it has a hit
4533 7 foreach my $i (0 .. $#{ $blast->{BlastOutput2} }) {
4534 11 my $query = $blast->{BlastOutput2}[$i];
4535 11 my $where = 'report ' . ($i + 1) . ' of "alignment_json"';
4536 11 ▶ my $results = ref $query eq 'HASH' && ref $query->{report} eq 'HASH' ? $query->{report}{results} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $query eq 'HASH' && ref $query->{'report'} eq 'HASH' ? : 10 1 11
Condition66%2/3
ref $query eq "HASH" and ref $query->{"report"} eq "HASH"
!ll&&!rl&&r
1010
MC/DC50%1/2
ref $query eq "HASH" and ref $query->{"report"} eq "HASH"
ref $query eq "HASH" ref $query->{"report"} eq "HASH"
Truth table66%2/3
A and B
A= ref $query eq "HASH"B= ref $query->{"report"} eq "HASH"
ABresult
0X0
100
111
4537 11 ▶ croak "$sub: $where has no report.results" unless ref $results eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $results eq "HASH" 1 10 11
4538 10 ▶ my $lists = $results->{bl2seq} // [];
Condition50%1/2
$results->{"bl2seq"} // []
l!l
100
MC/DC0%0/1
$results->{"bl2seq"} // []
$results->{"bl2seq"}
Truth table50%1/2
A
A= $results->{"bl2seq"}
Aresult
11
00
4539 10 ▶ croak "$sub: $where has a \"bl2seq\" that isn't an array, but " . _what($lists) unless ref $lists eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $lists eq "ARRAY" 1 9 10
4540 9 foreach my $hit_list (@{ $lists }) {
4541 croak "$sub: $where has a comparison that isn't one, which is an object with a \"query_title\" and a \"hits\" array"
4542 unless ref $hit_list eq 'HASH' && defined $hit_list->{query_title} && !ref $hit_list->{query_title}
4543 9 ▶ && ref($hit_list->{hits} // []) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $hit_list eq "HASH" and defined $hit_list->{"query_title"} and not ref $hit_list->{"query_title"} and ref($hit_list->{"hits"} // []) eq "ARRAY" 1 8 9
Condition45%5/11
ref $hit_list eq "HASH" and defined $hit_list->{"query_title"} and not ref $hit_list->{"query_title"} and ref($hit_list->{"hits"} // []) eq "ARRAY"
!ll&&!rl&&r
018
ref $hit_list eq "HASH" and defined $hit_list->{"query_title"} and not ref $hit_list->{"query_title"}
!ll&&!rl&&r
009
ref $hit_list eq "HASH" and defined $hit_list->{"query_title"}
!ll&&!rl&&r
009
$hit_list->{"hits"} // []
l!l
90
MC/DC0%0/4
ref $hit_list eq "HASH" and defined $hit_list->{"query_title"} and not ref $hit_list->{"query_title"} and ref($hit_list->{"hits"} // []) eq "ARRAY"
ref $hit_list eq "HASH" defined $hit_list->{"query_title"} not ref $hit_list->{"query_title"} $hit_list->{"hits"}
Truth table20%1/5
A and B and not(C) and D
A= ref $hit_list eq "HASH"B= defined $hit_list->{"query_title"}C= not ref $hit_list->{"query_title"}D= $hit_list->{"hits"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
4544 8 $known{ $hit_list->{query_title} } = 1;
4545 8 ▶ foreach my $hit (@{ $hit_list->{hits} // [] }) {
Condition50%1/2
$hit_list->{"hits"} // []
l!l
80
MC/DC0%0/1
$hit_list->{"hits"} // []
$hit_list->{"hits"}
Truth table50%1/2
A
A= $hit_list->{"hits"}
Aresult
11
00
4546 croak "$sub: $where has a hit of \"$hit_list->{query_title}\" that isn't one, which is an object whose \"description\" and \"hsps\" are arrays of objects"
4547 unless ref $hit eq 'HASH' && ref($hit->{description} // []) eq 'ARRAY' && ref($hit->{hsps} // []) eq 'ARRAY'
4548 13 ▶ && !grep { ref $_ ne 'HASH' } @{ $hit->{description} // [] }, @{ $hit->{hsps} // [] };
Branch: 1 branch
BranchTrueFalseTotal
unless ref $hit eq "HASH" and ref($hit->{"description"} // []) eq "ARRAY" and ref($hit->{"hsps"} // []) eq "ARRAY" and not grep({ref $_ ne "HASH";} @{$hit->{"description"} // [];}, @{$hit->{"hsps"} // [];}) 1 12 13
Condition58%10/17
ref $hit eq "HASH" and ref($hit->{"description"} // []) eq "ARRAY" and ref($hit->{"hsps"} // []) eq "ARRAY" and not grep({ref $_ ne "HASH";} @{$hit->{"description"} // [];}, @{$hit->{"hsps"} // [];})
!ll&&!rl&&r
1012
ref $hit eq "HASH" and ref($hit->{"description"} // []) eq "ARRAY" and ref($hit->{"hsps"} // []) eq "ARRAY"
!ll&&!rl&&r
1012
ref $hit eq "HASH" and ref($hit->{"description"} // []) eq "ARRAY"
!ll&&!rl&&r
1012
$hit->{"description"} // []
l!l
120
$hit->{"hsps"} // []
l!l
120
$hit->{"description"} // []
l!l
120
$hit->{"hsps"} // []
l!l
120
MC/DC25%1/4
ref $hit eq "HASH" and ref($hit->{"description"} // []) eq "ARRAY" and ref($hit->{"hsps"} // []) eq "ARRAY" and not grep({ref $_ ne "HASH";} @{$hit->{"description"} // [];}, @{$hit->{"hsps"} // [];})
ref $hit eq "HASH" $hit->{"description"} $hit->{"hsps"} not grep({ref $_ ne "HASH";} @{$hit->{"description"} // [];}, @{$hit->{"hsps"} // [];})
Truth table40%2/5
A and B and C and not(D)
A= ref $hit eq "HASH"B= $hit->{"description"}C= $hit->{"hsps"}D= not grep({ref $_ ne "HASH";} @{$hit->{"description"} // [];}, @{$hit->{"hsps"} // [];})
ABCDresult
0XXX0
10XX0
110X0
11100
11111
4549 12 ▶ my ($first, $hsp) = (($hit->{description} // [])->[0], ($hit->{hsps} // [])->[0]);
Condition50%2/4
$hit->{"description"} // []
l!l
120
$hit->{"hsps"} // []
l!l
120
MC/DC0%0/1
$hit->{"description"} // []
$hit->{"description"}
MC/DC0%0/1
$hit->{"hsps"} // []
$hit->{"hsps"}
Truth table50%1/2
A
A= $hit->{"description"}
Aresult
11
00
Truth table50%1/2
A
A= $hit->{"hsps"}
Aresult
11
00
4550 12 ▶ next unless defined $first && defined $first->{title} && defined $hsp;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $first and defined $first->{"title"} and defined $hsp 0 12 12
Condition33%2/6
defined $first and defined $first->{"title"} and defined $hsp
!ll&&!rl&&r
0012
defined $first and defined $first->{"title"}
!ll&&!rl&&r
0012
MC/DC0%0/3
defined $first and defined $first->{"title"} and defined $hsp
defined $first defined $first->{"title"} defined $hsp
Truth table25%1/4
A and B and C
A= defined $firstB= defined $first->{"title"}C= defined $hsp
ABCresult
0XX0
10X0
1100
1111
4551 12 ▶ my $value = $hsp->{$metric} // next;
Condition50%1/2
$hsp->{$metric} // (next)
l!l
120
MC/DC0%0/1
$hsp->{$metric} // (next)
$hsp->{$metric}
Truth table50%1/2
A
A= $hsp->{$metric}
Aresult
11
00
4552 12 $data{ $hit_list->{query_title} }{ $first->{title} } = $value;
4553 12 ▶ $max = $value if !defined $max || $value > $max;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $max or $value > $max 3 9 12
Condition66%2/3
not defined $max or $value > $max
l!l&&r!l&&!r
309
MC/DC50%1/2
not defined $max or $value > $max
not defined $max $value > $max
Truth table66%2/3
not(A) or B
A= not defined $maxB= $value > $max
ABresult
1X1
011
000
4554 }
4555 }
4556 }
4557 3 ▶ croak "$sub: no \"$metric\" values in the BLAST report" unless defined $max;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $max 0 3 3
4558 # Up to 2026-11-10 a name in "order" that the report lacks, a misspelt one
4559 # say, was drawn as a row and a column of grey cells, as a sequence that
4560 # has no hit is.
4561 3 ▶ my @unknown = grep { !$known{$_} } @{ $args->{order} // [] };
Condition100%2/2
$args->{"order"} // []
l!l
21
MC/DC100%1/1
$args->{"order"} // []
$args->{"order"}
Truth table100%2/2
A
A= $args->{"order"}
Aresult
11
00
4562 3 ▶ croak "$sub: \"order\" names sequences that aren't in the BLAST report: @unknown" if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 2 3
4563 2 ▶ my @order = @{ $args->{order} // [sort { lc $a cmp lc $b } keys %data] };
Condition100%2/2
$args->{"order"} // [(sort {lc $a cmp lc $b;} keys %data)]
l!l
11
MC/DC100%1/1
$args->{"order"} // [(sort {lc $a cmp lc $b;} keys %data)]
$args->{"order"}
Truth table100%2/2
A
A= $args->{"order"}
Aresult
11
00
4564 2 my (@row_labels, @names);
4565 2 foreach my $key (@order) {
4566 3 ▶ my ($genus, $species) = $key =~ /^([^.]+)\.(.+)/ or croak "$sub: can't get a genus and species from \"$key\"";
Branch: 1 branch
BranchTrueFalseTotal
() = $key =~ /^([^.]+)\.(.+)/ or croak(qq[${sub}: can't get a genus and species from "$key"]) 3 0 3
4567 3 my ($sp, @strain) = split /\./, $species; # C.neoformans.B.3501A
4568 3 push @names, [$genus, $sp, "@strain"];
4569 3 ▶ push @row_labels, '$\it{' . ucfirst(_first_letter($genus)) . ". $sp}\$" . (@strain ? " @strain" : '');
Branch: 1 branch
BranchTrueFalseTotal
@strain ? : 0 3 3
4570 }
4571 2 my @col_labels = @{ _abbreviated_labels(\@names) };
4572 2 ▶ my $add = $args->{'logscale_add'} // 0;
Condition50%1/2
$args->{"logscale_add"} // 0
l!l
02
MC/DC0%0/1
$args->{"logscale_add"} // 0
$args->{"logscale_add"}
Truth table50%1/2
A
A= $args->{"logscale_add"}
Aresult
11
00
4573 2 ▶ my $norm = ($args->{normalize} // 0) > 0;
Condition100%2/2
$args->{"normalize"} // 0
l!l
11
MC/DC100%1/1
$args->{"normalize"} // 0
$args->{"normalize"}
Truth table100%2/2
A
A= $args->{"normalize"}
Aresult
11
00
4574 # Normalized, every value is divided by the largest, with "logscale_add"
4575 # added to both so that the largest is still 1. That needs a largest above
4576 # 0, which "evalue" does not have when BLAST has rounded every e-value to 0.
4577 2 ▶ croak "$sub: can't normalize \"$metric\", since its largest value" . ($add ? ' plus "logscale_add"' : '') . ' is ' . ($max + $add) . ', not above 0'
Branch: 2 branches
BranchTrueFalseTotal
if $norm and $max + $add <= 0 1 1 2
$add ? : 0 1 1
Condition66%2/3
$norm and $max + $add <= 0
!ll&&!rl&&r
101
MC/DC50%1/2
$norm and $max + $add <= 0
$norm $max + $add <= 0
Truth table66%2/3
A and B
A= $normB= $max + $add <= 0
ABresult
0X0
100
111
4578 if $norm && $max + $add <= 0;
4579 1 my $log = $args->{cblogscale};
4580 1 my (@cells, $lo, $hi, $lo_positive);
4581 1 foreach my $i (0 .. $#order) {
4582 1 foreach my $j (0 .. $#order) {
4583 # a pair with no hit stays out of the table, rather than claiming a
4584 # score of 0, and is drawn grey
4585 1 ▶ my $value = $data{ $order[$i] }{ $order[$j] } // $args->{default_undefined};
Condition33%1/3
$data{$order[$i]}{$order[$j]} // $args->{"default_undefined"}
l!l&&r!l&&!r
001
MC/DC0%0/2
$data{$order[$i]}{$order[$j]} // $args->{"default_undefined"}
$data{$order[$i]}{$order[$j]} $args->{"default_undefined"}
Truth table33%1/3
A // B
A= $data{$order[$i]}{$order[$j]}B= $args->{"default_undefined"}
ABresult
1X1
011
000
4586 1 ▶ if (defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) 0 1 1
4587 0 $value += $add;
4588 0 ▶ $value /= $max + $add if $norm;
Branch: 1 branch
BranchTrueFalseTotal
if $norm 0 0 0
4589 0 ▶ $lo = $value if !defined $lo || $value < $lo;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $lo or $value < $lo 0 0 0
Condition0%0/3
not defined $lo or $value < $lo
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $lo or $value < $lo
not defined $lo $value < $lo
Truth table0%0/3
not(A) or B
A= not defined $loB= $value < $lo
ABresult
1X1
011
000
4590 0 ▶ $hi = $value if !defined $hi || $value > $hi;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $hi or $value > $hi 0 0 0
Condition0%0/3
not defined $hi or $value > $hi
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $hi or $value > $hi
not defined $hi $value > $hi
Truth table0%0/3
not(A) or B
A= not defined $hiB= $value > $hi
ABresult
1X1
011
000
4591 0 ▶ $lo_positive = $value if $value > 0 && (!defined $lo_positive || $value < $lo_positive);
Branch: 1 branch
BranchTrueFalseTotal
if $value > 0 and !defined($lo_positive) || $value < $lo_positive 0 0 0
Condition0%0/6
$value > 0 and !defined($lo_positive) || $value < $lo_positive
!ll&&!rl&&r
000
not defined $lo_positive or $value < $lo_positive
l!l&&r!l&&!r
000
MC/DC0%0/3
$value > 0 and !defined($lo_positive) || $value < $lo_positive
$value > 0 not defined $lo_positive $value < $lo_positive
Truth table0%0/4
A and not(B) or C
A= $value > 0B= not defined $lo_positiveC= $value < $lo_positive
ABCresult
0XX0
1000
11X1
1011
4592 }
4593 1 $cells[$i][$j] = $value;
4594 }
4595 }
4596 1 ▶ croak "$sub: no pair of the sequences in \"order\" has a \"$metric\" value, or a \"default_undefined\", to draw" unless defined $hi;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hi 1 0 1
4597 # A normalized scale runs from 0 to 1, but a log scale can't start at 0 or
4598 # below, so it starts at the smallest value above 0 instead, as it does
4599 # when not normalized.
4600 0 ▶ @{ $args }{qw(cb_min cb_max)} = ($log ? undef : 0, 1) if $norm;
Branch: 2 branches
BranchTrueFalseTotal
if $norm 0 0 0
$log ? : 0 0 0
4601 0 ▶ $lo = $args->{cb_min} // ($log ? $lo_positive : $lo);
Branch: 1 branch
BranchTrueFalseTotal
$log ? : 0 0 0
Condition0%0/3
$args->{"cb_min"} // ($log ? $lo_positive : $lo)
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{"cb_min"} // ($log ? $lo_positive : $lo)
$args->{"cb_min"} ($log ? $lo_positive : $lo)
Truth table0%0/3
A // B
A= $args->{"cb_min"}B= ($log ? $lo_positive : $lo)
ABresult
1X1
011
000
4602 0 ▶ $hi = $args->{cb_max} // $hi;
Condition0%0/3
$args->{"cb_max"} // $hi
l!l&&r!l&&!r
000
MC/DC0%0/2
$args->{"cb_max"} // $hi
$args->{"cb_max"} $hi
Truth table0%0/3
A // B
A= $args->{"cb_max"}B= $hi
ABresult
1X1
011
000
4603 0 ▶ croak "$sub: \"cblogscale\" needs a value above 0 to start the scale at, or a \"cb_min\" above 0" if $log && (!defined $lo || $lo <= 0);
Branch: 1 branch
BranchTrueFalseTotal
if $log and !defined($lo) || $lo <= 0 0 0 0
Condition0%0/6
$log and !defined($lo) || $lo <= 0
!ll&&!rl&&r
000
not defined $lo or $lo <= 0
l!l&&r!l&&!r
000
MC/DC0%0/3
$log and !defined($lo) || $lo <= 0
$log not defined $lo $lo <= 0
Truth table0%0/4
A and not(B) or C
A= $logB= not defined $loC= $lo <= 0
ABCresult
0XX0
1000
11X1
1011
4604 0 require JSON::MaybeXS;
4605 0 my $table = _tmp('.json');
4606 0 ▶ open my $fh, '>:raw', $table or croak "$sub: can't write $table: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $table or croak("${sub}: can't write ${table}: $!") 0 0 0
4607 # The strings go through _chars, since encode_json reads a byte string as
4608 # Latin-1: up to 2026-10-17 a UTF-8 title "caf\xc3\xa9" was drawn as
4609 # "caf\xc3\x83\xc2\xa9".
4610 0 print {$fh} JSON::MaybeXS::encode_json({
4611 0 ▶ cells => \@cells, cols => [map { _chars($_) } @col_labels], rows => [map { _chars($_) } @row_labels], vmin => $lo + 0, vmax => $hi + 0,
Branch: 3 branches
BranchTrueFalseTotal
$log ? : 0 0 0
$args->{'show_numbers'} ? : 0 0 0
defined $args->{'cb_label'} ? : 0 0 0
Condition0%0/2
$args->{"title"} // ""
l!l
00
MC/DC0%0/1
$args->{"title"} // ""
$args->{"title"}
Truth table0%0/2
A
A= $args->{"title"}
Aresult
11
00
4612 log => $log ? JSON::MaybeXS::true() : JSON::MaybeXS::false(),
4613 numbers => $args->{'show_numbers'} ? JSON::MaybeXS::true() : JSON::MaybeXS::false(),
4614 0 title => _chars($args->{title} // ''), cblabel => (defined $args->{cb_label} ? _chars($args->{cb_label}) : undef),
4615 });
4616 0 ▶ close $fh or croak "$sub: can't write $table: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't write ${table}: $!") 0 0 0
4617 0 _python($sub, '--table', $table, '--o', $args->{filename}, '--c', _creator($sub), '--p', _json_text([map { _chars($_) } "showing each pair's \"$metric\"", $prov]));
4618 0 $args->{filename};
4619 }
4620  
4621 # $text with every character that LaTeX treats specially written so that it
4622 # prints as itself. "\^" would be a circumflex accent, not a caret, and "\~" a
4623 # tilde accent, so those two (and the backslash) are spelled as text commands.
4624 124 ▶sub _latex_text {
Subroutine _latex_text: called CC=2 SCAR=6.9
4625 124 my ($text) = @_;
4626 # |, < and > are commands, as the others are, because under the default
4627 # OT1 fonts they print as an em dash and an inverted ! and ?
4628 124 my %special = ('\\' => '\\textbackslash{}', '^' => '\\textasciicircum{}', '~' => '\\textasciitilde{}',
4629 '|' => '\\textbar{}', '<' => '\\textless{}', '>' => '\\textgreater{}');
4630 124 ▶ $text =~ s/([\\^~#\$%&_{}|<>])/$special{$1} \/\/ "\\$1"/ge;
Condition100%2/2
$special{$1} // "\\$1"
l!l
614
MC/DC100%1/1
$special{$1} // "\\$1"
$special{$1}
Truth table100%2/2
A
A= $special{$1}
Aresult
11
00
4631 124 $text;
4632 }
4633  
4634 # xcolor's 19 base colors as [r, g, b], each 0 to 1, for the terminal and the
4635 # SVG, which have no xcolor to look a name up in. Taken from xcolor.sty v3.01
4636 # (2023/11/15, TeX Live's tex/latex/xcolor), its three \definecolorset lines
4637 # for the base colors (lines 1435 to 1456): red to violet are given in rgb
4638 # first, cyan to olive in cmyk and black to white in gray, and the rgb of each
4639 # is the one written in its rgb place.
4640 40 my %Xcolor = (
4641 red => [1, 0, 0], green => [0, 1, 0], blue => [0, 0, 1],
4642 brown => [.75, .5, .25], lime => [.75, 1, 0], orange => [1, .5, 0],
4643 pink => [1, .75, .75], purple => [.75, 0, .25], teal => [0, .5, .5],
4644 violet => [.5, 0, .5], cyan => [0, 1, 1], magenta => [1, 0, 1],
4645 yellow => [1, 1, 0], olive => [.5, .5, 0], black => [0, 0, 0],
4646 darkgray => [.25, .25, .25], gray => [.5, .5, .5], lightgray => [.75, .75, .75],
4647 white => [1, 1, 1],
4648 );
4649  
4650 # The color view_alignment's "color" gives every residue: plot_msa's, as
4651 # share/msa_plot.py's AA and NT tables hold them, which are CIAlign's
4652 # color-blind-safe "CBS" palette (getAAColours('CBS') and getNtColours('CBS');
4653 # Tumescheit, Firth & Brown, PeerJ 2022, MIT license), so that the text, the
4654 # SVG and plot_msa's image color a residue alike. The gap and "*", which
4655 # msa_plot.py draws white, are left out here, and so stay uncolored.
4656 # t/checks.t reads msa_plot.py's tables and checks that these are the same.
4657 my %Residue_color = (
4658 aa => {
4659 D => '#a22c49', E => '#a22c49', C => '#c9c433', M => '#c9c433', K => '#0038a2', R => '#0038a2',
4660 S => '#e57700', T => '#e57700', F => '#589aab', Y => '#589aab', N => '#50d3cb', Q => '#50d3cb',
4661 G => '#eae2ea', L => '#56ae6c', V => '#56ae6c', I => '#56ae6c', A => '#888988', W => '#89236a',
4662 H => '#e669ca', P => '#ffc4a9', X => '#000000', B => '#936e23', Z => '#936e23', J => '#936e23',
4663 U => '#936e23', O => '#936e23',
4664 },
4665 nt => {
4666 A => '#56ae6c', G => '#c9c433', T => '#a22c49', C => '#0038a2', N => '#6979d3', U => '#a22c49',
4667 40 map { $_ => '#6979d3' } split //, 'RYSWKMBDHVX',
4668 },
4669 );
4670  
4671 # %Residue_color itself, for t/checks.t to compare with msa_plot.py's tables.
4672 2 ▶sub _residue_colors { \%Residue_color }
Subroutine _residue_colors: called CC=1 SCAR=0.0
4673  
4674 # The palette of %Residue_color for these sequences: 'nt' when every character
4675 # of every one, upper-cased, is a nucleotide code or a gap, as msa_plot.py
4676 # decides it after CIAlign's seqType(), and 'aa' otherwise. A "." counts as a
4677 # gap here, which msa_plot.py has no use for, since it reads only "-".
4678 5 ▶sub _palette_for {
Subroutine _palette_for: called CC=6 SCAR=17.9
4679 5 my ($seqs) = @_;
4680 5 my $nt = $Residue_color{nt};
4681 5 foreach my $s (values %{ $seqs }) {
4682 6 foreach my $c (split //, uc $s) {
4683 20 ▶ return 'aa' unless $c eq '-' || $c eq '.' || defined $nt->{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $c eq "-" or $c eq "." or defined $nt->{$c} 4 16 20
Condition83%5/6
$c eq "-" or $c eq "." or defined $nt->{$c}
l!l&&r!l&&!r
5114
$c eq "-" or $c eq "."
l!l&&r!l&&!r
5015
MC/DC66%2/3
$c eq "-" or $c eq "." or defined $nt->{$c}
$c eq "-" $c eq "." defined $nt->{$c}
Truth table75%3/4
A or B or C
A= $c eq "-"B= $c eq "."C= defined $nt->{$c}
ABCresult
1XX1
01X1
0011
0000
4684 }
4685 }
4686 1 'nt';
4687 }
4688  
4689 # The text color, as 0 to 255 r, g, b, that reads best on the background $r,
4690 # $g, $b: white or black, whichever has the higher contrast ratio against it
4691 # by WCAG 2.2's definitions of relative luminance and contrast ratio (W3C
4692 # Recommendation, 2023-10-05, "Glossary"): each channel taken from sRGB to
4693 # linear, L = 0.2126 R + 0.7152 G + 0.0722 B, and the ratio of the lighter L
4694 # + 0.05 to the darker. The two ratios are equal at L = 0.1791; of
4695 # %Residue_color, #936e23 (L = 0.1748, white) and #6979d3 (L = 0.2138, black)
4696 # are the nearest it (measured 2026-11-16), far enough that no NV width can
4697 # tip them.
4698 35 ▶sub _text_on {
Subroutine _text_on: called CC=3 SCAR=11.0
4699 35 ▶ my @lin = map { my $s = $_ / 255; $s <= 0.04045 ? $s / 12.92 : (($s + 0.055) / 1.055) ** 2.4 } @_;
Branch: 1 branch
BranchTrueFalseTotal
$s <= 0.04045 ? : 14 91 105
4700 35 my $l = 0.2126 * $lin[0] + 0.7152 * $lin[1] + 0.0722 * $lin[2];
4701 35 ▶ 1.05 / ($l + 0.05) > ($l + 0.05) / 0.05 ? (255, 255, 255) : (0, 0, 0);
Branch: 1 branch
BranchTrueFalseTotal
1.05 / ($l + 0.05) > ($l + 0.05) / 0.05 ? : 6 29 35
4702 }
4703  
4704 # A color of "color_residues", an xcolor base name or [r, g, b], as the 0 to
4705 # 255 integers of the terminal's and the SVG's rgb.
4706 21 ▶sub _rgb255 {
Subroutine _rgb255: called CC=2 SCAR=6.9
4707 21 my ($c) = @_;
4708 21 ▶ map { int(255 * $_ + 0.5) } @{ ref $c ? $c : $Xcolor{$c} };
Branch: 1 branch
BranchTrueFalseTotal
ref $c ? : 8 13 21
4709 }
4710  
4711 # $name as the terminal and the SVG show it: a tab, carriage return or newline
4712 # as \t, \r or \n, as Stats::LikeR's view writes them, and any other control
4713 # character as \x{..}, so that one name stays on one line and the SVG stays
4714 # XML, which allows none of them.
4715 127 ▶sub _shown_name {
Subroutine _shown_name: called CC=2 SCAR=7.0
4716 127 my ($name) = @_;
4717 127 my %esc = ("\t" => '\\t', "\r" => '\\r', "\n" => '\\n');
4718 127 ▶ $name =~ s/([\x00-\x1f\x7f])/$esc{$1} \/\/ sprintf('\\x{%02x}', ord $1)/ge;
Condition50%1/2
$esc{$1} // sprintf("\\x{%02x}", ord $1)
l!l
10
MC/DC0%0/1
$esc{$1} // sprintf("\\x{%02x}", ord $1)
$esc{$1}
Truth table50%1/2
A
A= $esc{$1}
Aresult
11
00
4719 127 $name;
4720 }
4721  
4722 # $text as the text of an XML element: &, < and > written as entities. Quotes
4723 # need none outside an attribute, and are left as they are, as matplotlib
4724 # leaves them in the Creator, so that the provenance reads the same in both.
4725 131 ▶sub _xml {
Subroutine _xml: called CC=1 SCAR=0.0
4726 131 my ($text) = @_;
4727 131 my %ent = ('&' => '&amp;', '<' => '&lt;', '>' => '&gt;');
4728 131 $text =~ s/([&<>])/$ent{$1}/g;
4729 131 $text;
4730 }
4731  
4732 # The alignment of view_alignment as LaTeX tables, the original output of
4733 # bioinf.pm's clustal_view_residues: each block's rows of name, residues and
4734 # residues so far, a table of "split" blocks each.
4735 7 ▶sub _alignment_tex {
Subroutine _alignment_tex: called CC=24 SCAR=32.4
4736 7 my ($sub, $r, $blocks, $creator) = @_;
4737 7 my @table;
4738 7 foreach my $block (@{ $blocks }) {
4739 13 foreach my $row (@{ $block->{rows} }) {
4740 26 my $name = _latex_text($row->{name});
4741 26 ▶ if ($row->{track}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($row->{"track"}) 4 22 26
4742 4 push @table, ["\\textit{$name} track", '\texttt{' . join('', @{ $row->{chars} }) . '}', $row->{count}];
4743 4 next;
4744 }
4745 # a residue is written so that LaTeX prints it, as a name is
4746 22 my @seq = map { _latex_text($_) } @{ $row->{chars} };
4747 22 foreach my $i (0 .. $#seq) {
4748 95 ▶ if (my $bg = $row->{bg}[$i]) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $bg = $row->{"bg"}[$i]) 9 86 95
4749 # a box of its color, the \strut making every box in the row
4750 # one height, under the residue in white or black; the {} ends
4751 # the command's name, which would otherwise run on into "M"
4752 9 my $x = $seq[$i];
4753 9 ▶ $x = "\\textcolor{white}{$x}" if (_text_on(@{ $bg }))[0];
Branch: 1 branch
BranchTrueFalseTotal
if (_text_on(@{$bg;}))[0] 0 9 9
4754 9 ▶ $x = "\\textbf{$x}" if $row->{strong}[$i];
Branch: 1 branch
BranchTrueFalseTotal
if $row->{"strong"}[$i] 2 7 9
4755 9 $seq[$i] = '\colorbox[RGB]{' . join(',', @{ $bg }) . "}{\\strut{}$x}";
4756 9 next;
4757 }
4758 86 ▶ my $c = $row->{colors}[$i] // next;
Condition100%2/2
$row->{"colors"}[$i] // (next)
l!l
1274
MC/DC100%1/1
$row->{"colors"}[$i] // (next)
$row->{"colors"}[$i]
Truth table100%2/2
A
A= $row->{"colors"}[$i]
Aresult
11
00
4759 0 ▶ $seq[$i] = ref $c ? '{\color[rgb]{' . join(',', @{ $c }) . "}$seq[$i]}" : "\\textcolor{$c}{$seq[$i]}";
Branch: 1 branch
BranchTrueFalseTotal
ref $c ? : 0 12 12
4760 }
4761 22 push @table, ["\\textit{$name}", '\texttt{' . join('', @seq) . '}', $row->{count}];
4762 }
4763 13 push @table, ['\hline'];
4764 }
4765 7 my $per_table = $r->{split} * (1 + @{ $blocks->[0]{rows} }); # a block's rows, and its \hline
4766 7 my $file = $r->{'output_file'};
4767 7 ▶ open my $tex, '>', $file or croak "$sub: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $tex, ">", $file or croak("${sub}: can't write ${file}: $!") 7 0 7
4768 # a newline in a path would end the comment, and make the rest LaTeX
4769 7 (my $comment = $creator) =~ tr/\r\n/ /;
4770 7 ▶ print {$tex} "% $comment\n" or croak "$sub: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$tex;} "% $comment\n" or croak("${sub}: can't write ${file}: $!") 7 0 7
4771 7 my $n_tables = int((@table + $per_table - 1) / $per_table);
4772 7 foreach my $t (0 .. $n_tables - 1) {
4773 10 my $end = ($t + 1) * $per_table - 1;
4774 10 ▶ $end = $#table if $end > $#table;
Branch: 1 branch
BranchTrueFalseTotal
if $end > $#table 6 4 10
4775 # with "color", no margin round a residue's box, so that the boxes meet;
4776 # the table's group keeps the setting from the rest of the document
4777 10 ▶ print {$tex} "\\begin{table}[htp]$r->{'table_text_size'}\n", ($r->{color} ? "\\setlength{\\fboxsep}{0pt}\n" : ''),
Branch: 3 branches
BranchTrueFalseTotal
$r->{'color'} ? : 1 9 10
$r->{'title'} ne '' ? : 3 7 10
$t > 0 ? : 2 1 3
4778 10 ($r->{title} ne '' ? '\textbf{' . _latex_text($r->{title}) . '}' . ($t > 0 ? ' (continued)' : '') . "\\par\n" : ''),
4779 "\\begin{tabular}{|c|l|c|} \\hline\n",
4780 '\textbf{Track} & \textbf{Sequence} & \textbf{Length}\\\\ \hline', "\n";
4781 10 ▶ print {$tex} join(' & ', @{ $_ }), ($_->[-1] eq '\hline' ? "\n" : "\n\\\\\n") foreach @table[$t * $per_table .. $end];
Branch: 1 branch
BranchTrueFalseTotal
$_->[-1] eq '\\hline' ? : 13 26 39
4782 10 ▶ print {$tex} "\\end{tabular}\n\\caption{$r->{caption}", ($t > 0 && $r->{caption} ne '' ? ' (continued)' : ''), "}\n";
Branch: 1 branch
BranchTrueFalseTotal
$t > 0 && $r->{'caption'} ne '' ? : 0 10 10
Condition66%2/3
$t > 0 and $r->{"caption"} ne ""
!ll&&!rl&&r
730
MC/DC0%0/2
$t > 0 and $r->{"caption"} ne ""
$t > 0 $r->{"caption"} ne ""
Truth table66%2/3
A and B
A= $t > 0B= $r->{"caption"} ne ""
ABresult
0X0
100
111
4783 0 ▶ print {$tex} "\\label{tab:$r->{label}", ($n_tables > 1 ? $t : ''), "}\n" if defined $r->{label};
Branch: 2 branches
BranchTrueFalseTotal
if defined $r->{"label"} 0 10 10
$n_tables > 1 ? : 0 0 0
4784 10 print {$tex} "\\end{table} \\FloatBarrier\n";
4785 }
4786 7 ▶ close $tex or croak "$sub: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $tex or croak("${sub}: can't write ${file}: $!") 7 0 7
4787 }
4788  
4789 # The width of the name column and of the residue count column, in
4790 # characters, which the terminal and the SVG lay their rows out by.
4791 29 ▶sub _alignment_widths {
Subroutine _alignment_widths: called CC=5 SCAR=16.1
4792 29 my ($blocks) = @_;
4793 29 my ($name_w, $count_w) = (0, 0);
4794 29 foreach my $row (map { @{ $_->{rows} } } @{ $blocks }) {
4795 106 my $w = length _chars($row->{label});
4796 106 ▶ $name_w = $w if $w > $name_w;
Branch: 1 branch
BranchTrueFalseTotal
if $w > $name_w 39 67 106
4797 106 ▶ $count_w = length $row->{count} if !$row->{track} && length $row->{count} > $count_w;
Branch: 1 branch
BranchTrueFalseTotal
if not $row->{"track"} and length $row->{"count"} > $count_w 30 76 106
Condition100%3/3
not $row->{"track"} and length $row->{"count"} > $count_w
!ll&&!rl&&r
205630
MC/DC100%2/2
not $row->{"track"} and length $row->{"count"} > $count_w
not $row->{"track"} length $row->{"count"} > $count_w
Truth table100%3/3
not(A) and B
A= not $row->{"track"}B= length $row->{"count"} > $count_w
ABresult
0X0
100
111
4798 }
4799 29 ($name_w, $count_w);
4800 }
4801  
4802 # The header of a block, as the terminal shows it: its first alignment column
4803 # over its first residue, and its last over its last when there is room for
4804 # both with a space between.
4805 34 ▶sub _block_header {
Subroutine _block_header: called CC=2 SCAR=6.9
4806 34 my ($block) = @_;
4807 34 my ($first, $last) = ($block->{start} + 1, $block->{start} + $block->{width});
4808 34 my $room = $block->{width} - length($first) - length($last);
4809 34 ▶ $first . ($room >= 1 ? ' ' x $room . $last : '');
Branch: 1 branch
BranchTrueFalseTotal
$room >= 1 ? : 19 15 34
4810 }
4811  
4812 # The alignment of view_alignment as text: a banner, then each block's header
4813 # and rows of name, residues and residues so far, the banner again last, as
4814 # Stats::LikeR's view ends with it. With $color, a residue with a background
4815 # (view_alignment's "color") is on it, as a 24-bit ANSI background
4816 # (48;2;r;g;b), in the text color _text_on picks (38;2;r;g;b), and also bold
4817 # (1) and underlined (4) when it is one of "color_residues"; any other colored
4818 # residue is in its color, as a foreground; and each is followed by a reset
4819 # (0). Characters, not bytes.
4820 22 ▶sub _alignment_text {
Subroutine _alignment_text: called CC=11 SCAR=24.0
4821 22 my ($blocks, $banner, $color) = @_;
4822 22 my ($name_w, $count_w) = _alignment_widths($blocks);
4823 22 my $seq_w = $blocks->[0]{width}; # the first block is the widest
4824 22 my @lines = ($banner);
4825 22 foreach my $b (0 .. $#{ $blocks }) {
4826 34 my $block = $blocks->[$b];
4827 34 ▶ push @lines, '' if $b > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $b > 0 12 22 34
4828 34 push @lines, ' ' x ($name_w + 2) . _block_header($block);
4829 34 foreach my $row (@{ $block->{rows} }) {
4830 80 my $seq = '';
4831 80 foreach my $i (0 .. $#{ $row->{chars} }) {
4832 272 my $c = _chars($row->{chars}[$i]);
4833 272 my $bg = $row->{bg}[$i];
4834 272 ▶ if ($color && defined $bg) {
Branch: 2 branches
BranchTrueFalseTotal
if ($color and defined $bg) { } 2 270 272
elsif ($color and defined $row->{'colors'}[$i]) { } 1 269 270
Condition100%3/3
$color and defined $bg
!ll&&!rl&&r
26822
MC/DC100%2/2
$color and defined $bg
$color defined $bg
Truth table100%3/3
A and B
A= $colorB= defined $bg
ABresult
0X0
100
111
4835 2 ▶ $seq .= "\e[" . ($row->{strong}[$i] ? '1;4;' : '') . '38;2;' . join(';', _text_on(@{ $bg })) . ';48;2;' . join(';', @{ $bg }) . "m$c\e[0m";
Branch: 1 branch
BranchTrueFalseTotal
$row->{'strong'}[$i] ? : 1 1 2
4836 ▶ } elsif ($color && defined $row->{colors}[$i]) {
Condition100%3/3
$color and defined $row->{"colors"}[$i]
!ll&&!rl&&r
26811
MC/DC100%2/2
$color and defined $row->{"colors"}[$i]
$color defined $row->{"colors"}[$i]
Truth table100%3/3
A and B
A= $colorB= defined $row->{"colors"}[$i]
ABresult
0X0
100
111
4837 1 $seq .= "\e[38;2;" . join(';', _rgb255($row->{colors}[$i])) . "m$c\e[0m";
4838 } else {
4839 269 $seq .= $c;
4840 }
4841 }
4842 80 my $name = _chars($row->{label});
4843 80 my $line = $name . ' ' x ($name_w - length($name) + 2) . $seq;
4844 80 ▶ $line .= ' ' x ($seq_w - @{ $row->{chars} } + 2 + $count_w - length $row->{count}) . $row->{count} unless $row->{track};
Branch: 1 branch
BranchTrueFalseTotal
unless $row->{"track"} 64 16 80
4845 80 push @lines, $line;
4846 }
4847 }
4848 22 join('', map { "$_\n" } @lines, $banner);
4849 }
4850  
4851 # The alignment of view_alignment as an SVG, laid out as _alignment_text lays
4852 # it out, with its provenance $creator in the <metadata> that Matplotlib::Simple
4853 # 0.33's svg_creator_metadata writes it in, after matplotlib 3.11.2's
4854 # backend_svg._write_metadata: <dc:creator><cc:Agent><dc:title>, the one place
4855 # a figure from any of its engines keeps it, and the only metadata written.
4856 # Each residue is a <tspan> of its own, centered on its column by its own x,
4857 # so that the columns of every row, and the backgrounds under them, line up
4858 # whatever font the viewer has. Up to 2026-11-16 a row was one <text> whose
4859 # textLength was fixed instead, which librsvg 2.58 (Eye of GNOME's renderer)
4860 # ignores: it drew DejaVu Sans Mono's own 7.224 px advance, so the letters ran
4861 # further right of their backgrounds at every column; and it reads only the
4862 # first of a list of x on one <text>, so that is no way out either. A
4863 # colored residue has a tooltip, an empty <rect> over it with a <title>, as
4864 # msa_plot.py puts one on each cell. With "color", each run of residues of one
4865 # background is one <rect> under the row, and a residue whose text is to be
4866 # white, or which is one of "color_residues" (bold and underlined, as in the
4867 # terminal), is a <tspan>. A $title other than '' is a bold line above the
4868 # first block, and the image is widened to hold it if need be.
4869 7 ▶sub _alignment_svg {
Subroutine _alignment_svg: called CC=28 SCAR=33.3
4870 7 my ($sub, $file, $blocks, $creator, $title) = @_;
4871 # 12 px text, and 7.2 px a character: 0.6 em is the advance of DejaVu Sans
4872 # Mono, Liberation Mono and Courier New alike, so the names and the counts,
4873 # which are not stretched, end where the layout puts them in any of them.
4874 # 16 px a line leaves 4 px between the descenders of one row and the
4875 # capitals of the next; 8 px is the margin all round.
4876 7 my ($fs, $cw, $lh, $pad) = (12, 7.2, 16, 8);
4877 # The title is 14 px bold, 8.4 px a character by the same 0.6 em, on a
4878 # baseline 15 px into a band of 20 px, which leaves its descenders 1 px
4879 # clear of the band and the band 4 px clear of the first header's capitals.
4880 7 my ($title_fs, $title_cw, $title_h, $title_base) = (14, 8.4, 20, 15);
4881 7 ▶ $title //= '';
Condition50%1/2
$title //= ""
l!l
70
MC/DC0%0/1
$title //= ""
$title
Truth table50%1/2
A
A= $title
Aresult
11
00
4882 7 ▶ my $top = $pad + ($title eq '' ? 0 : $title_h); # where the first block's line starts
Branch: 1 branch
BranchTrueFalseTotal
$title eq '' ? : 5 2 7
4883 7 my ($name_w, $count_w) = _alignment_widths($blocks);
4884 # Every length is written with %.10g, so that 8 + 9 * 7.2 is written 72.8
4885 # and not 72.80000000000001, and a column past the millionth is still
4886 # placed to the hundredth of a pixel.
4887 7 my $x0 = sprintf '%.10g', $pad + ($name_w + 2) * $cw; # where the residues start
4888 7 my $x_count = $x0 + ($blocks->[0]{width} + 2 + $count_w) * $cw; # where the counts end
4889 7 my $lines = 0;
4890 7 $lines += 1 + @{ $_->{rows} } foreach @{ $blocks }; # a header and the rows of each block
4891 7 $lines += @{ $blocks } - 1; # a blank line between blocks
4892 7 my $right = $x_count; # where the widest thing drawn ends
4893 7 my $title_end = $pad + length(_chars($title)) * $title_cw;
4894 7 ▶ $right = $title_end if $title_end > $right;
Branch: 1 branch
BranchTrueFalseTotal
if $title_end > $right 1 6 7
4895 7 my ($width, $height) = map { sprintf '%.10g', $_ } $right + $pad, $top + $pad + $lines * $lh;
4896 7 my ($before, $after) = (
4897 "\n <metadata>\n"
4898 . ' <rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">' . "\n"
4899 . " <cc:Work>\n <dc:creator>\n <cc:Agent>\n <dc:title>",
4900 "</dc:title>\n </cc:Agent>\n </dc:creator>\n </cc:Work>\n </rdf:RDF>\n </metadata>"
4901 );
4902 7 my $svg = qq{<?xml version="1.0" encoding="utf-8" standalone="no"?>\n}
4903 . qq{<svg xmlns="http://www.w3.org/2000/svg" width="$width" height="$height" viewBox="0 0 $width $height" version="1.1">}
4904 . $before . _xml(_chars($creator)) . $after . "\n"
4905 . qq{ <rect width="100%" height="100%" fill="#ffffff"/>\n}
4906 . qq{ <g font-family="DejaVu Sans Mono, Liberation Mono, Courier New, monospace" font-size="$fs" fill="#000000">\n};
4907 7 ▶ $svg .= sprintf(qq{ <text x="$pad" y="%d" font-size="$title_fs" font-weight="bold">%s</text>\n}, $pad + $title_base, _xml(_chars($title)))
Branch: 1 branch
BranchTrueFalseTotal
if $title ne "" 2 5 7
4908 if $title ne '';
4909 7 my $line = 0;
4910 7 foreach my $b (0 .. $#{ $blocks }) {
4911 9 my $block = $blocks->[$b];
4912 9 ▶ $line++ if $b > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $b > 0 2 7 9
4913 9 my $y = $top + ++$line * $lh - 4; # the baseline, 4 px above the line's foot
4914 9 my ($first, $last) = ($block->{start} + 1, $block->{start} + $block->{width});
4915 9 $svg .= qq{ <text x="$x0" y="$y" fill="#666666">$first</text>\n};
4916 $svg .= sprintf(qq{ <text x="%.10g" y="$y" fill="#666666" text-anchor="end">$last</text>\n}, $x0 + $block->{width} * $cw)
4917 9 ▶ if $block->{width} - length($first) - length($last) >= 1;
Branch: 1 branch
BranchTrueFalseTotal
if $block->{"width"} - length($first) - length($last) >= 1 6 3 9
4918 9 foreach my $row (@{ $block->{rows} }) {
4919 26 $y = $top + ++$line * $lh - 4;
4920 26 ▶ $svg .= qq{ <text x="$pad" y="$y"} . ($row->{track} ? ' fill="#666666"' : '') . '>' . _xml(_chars($row->{label})) . "</text>\n";
Branch: 1 branch
BranchTrueFalseTotal
$row->{'track'} ? : 4 22 26
4921 # the backgrounds, drawn before the text so as to be under it
4922 26 my $n = @{ $row->{chars} };
4923 26 ▶ for (my $i = 0; $i < $n; ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $n) 78 26 104
4924 78 my $bg = $row->{bg}[$i];
4925 78 ▶ unless (defined $bg) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $bg) 58 20 78
4926 58 $i++;
4927 58 next;
4928 }
4929 20 my $key = join ',', @{ $bg };
4930 20 my $end = $i + 1; # one past the last of the run
4931 20 ▶ $end++ while $end < $n && defined $row->{bg}[$end] && join(',', @{ $row->{bg}[$end] }) eq $key;
Branch: 1 branch
BranchTrueFalseTotal
$end < $n and defined $row->{"bg"}[$end] and join(",", @{$row->{"bg"}[$end];}) eq $key and do { ++$end } 4 20 24
Condition100%6/6
$end < $n and defined $row->{"bg"}[$end] and join(",", @{$row->{"bg"}[$end];}) eq $key
!ll&&!rl&&r
10104
$end < $n and defined $row->{"bg"}[$end]
!ll&&!rl&&r
6414
MC/DC100%3/3
$end < $n and defined $row->{"bg"}[$end] and join(",", @{$row->{"bg"}[$end];}) eq $key
$end < $n defined $row->{"bg"}[$end] join(",", @{$row->{"bg"}[$end];}) eq $key
Truth table100%4/4
A and B and C
A= $end < $nB= defined $row->{"bg"}[$end]C= join(",", @{$row->{"bg"}[$end];}) eq $key
ABCresult
0XX0
10X0
1100
1111
4932 20 $svg .= sprintf(qq{ <rect x="%.10g" y="%.10g" width="%.10g" height="$lh" fill="rgb($key)"/>\n}, $x0 + $i * $cw, $y + 4 - $lh, ($end - $i) * $cw);
4933 20 $i = $end;
4934 }
4935 26 my (@tips, $seq);
4936 26 foreach my $i (0 .. $#{ $row->{chars} }) {
4937 82 my $c = _xml(_chars($row->{chars}[$i]));
4938 82 my $color = $row->{colors}[$i];
4939 82 my $attr = '';
4940 82 ▶ if (my $bg = $row->{bg}[$i]) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $bg = $row->{'bg'}[$i]) { } 24 58 82
elsif (defined $color) { } 12 46 58
4941 24 my @fg = _text_on(@{ $bg });
4942 24 ▶ $attr = ($fg[0] ? ' fill="rgb(255,255,255)"' : '') . ($row->{strong}[$i] ? ' font-weight="bold" text-decoration="underline"' : '');
Branch: 2 branches
BranchTrueFalseTotal
$fg[0] ? : 5 19 24
$row->{'strong'}[$i] ? : 2 22 24
4943 } elsif (defined $color) {
4944 12 $attr = ' fill="rgb(' . join(',', _rgb255($color)) . ')"';
4945 }
4946 # centered on its own column, whatever the font's advance
4947 82 $seq .= sprintf qq{<tspan x="%.10g"$attr>%s</tspan>}, $x0 + ($i + 0.5) * $cw, $c;
4948 82 ▶ next unless defined $color;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $color 68 14 82
4949 push @tips, sprintf(qq{ <rect x="%.10g" y="%.10g" width="$cw" height="$lh" fill="none" pointer-events="all"><title>%s</title></rect>\n},
4950 14 ▶ $x0 + $i * $cw, $y + 4 - $lh, _xml(_chars($row->{tips}[$i]))) if defined $row->{tips}[$i];
Branch: 1 branch
BranchTrueFalseTotal
if defined $row->{"tips"}[$i] 14 0 14
4951 }
4952 # $seq is an argument, not part of the format, which a residue "%" would break
4953 $svg .= sprintf(qq{ <text y="$y" text-anchor="middle" xml:space="preserve"%s>%s</text>\n},
4954 26 ▶ $row->{track} ? ' fill="#666666"' : '', $seq);
Branch: 1 branch
BranchTrueFalseTotal
$row->{'track'} ? : 4 22 26
4955 26 $svg .= join '', @tips;
4956 26 ▶ $svg .= sprintf(qq{ <text x="%.10g" y="$y" text-anchor="end">$row->{count}</text>\n}, $x_count) unless $row->{track};
Branch: 1 branch
BranchTrueFalseTotal
unless $row->{"track"} 22 4 26
4957 }
4958 }
4959 7 $svg .= " </g>\n</svg>\n";
4960 7 utf8::encode($svg);
4961 7 ▶ open my $fh, '>:raw', $file or croak "$sub: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:raw", $file or croak("${sub}: can't write ${file}: $!") 7 0 7
4962 7 ▶ print {$fh} $svg or croak "$sub: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} $svg or croak("${sub}: can't write ${file}: $!") 7 0 7
4963 7 ▶ close $fh or croak "$sub: can't write $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't write ${file}: $!") 7 0 7
4964 }
4965  
4966 53 ▶sub view_alignment {
Subroutine view_alignment: called CC=107 SCAR=47.9
Pod documented
4967 53 my $sub = 'view_alignment';
4968 # The alignment comes first, as the data does in Stats::LikeR's view: a hash
4969 # ref of name => sequence, or a FASTA file name; or else it is "msa_file",
4970 # among the name => value pairs. It is the odd one out, so an odd number of
4971 # arguments means it was given first.
4972 53 my @list = @_;
4973 53 ▶ my $data = @list % 2 ? shift @list : undef;
Branch: 1 branch
BranchTrueFalseTotal
@list % 2 ? : 34 19 53
4974 # msa_file: a FASTA file, aligned (such as plot_msa's) or not;
4975 # output_file: a .svg or a .tex to write; color_residues: {protein =>
4976 # {1-based residue number => color}}, the color an xcolor base name or an
4977 # [r, g, b] ref; color: 1 = every residue on its color from plot_msa's
4978 # palette, 0 = only those of color_residues; order: proteins top to bottom;
4979 # row_width: columns per block (100); track: a protein whose colored residue
4980 # numbers get a row of their own; threads and clustal_args: for clustalo, if
4981 # the sequences have to be aligned; to: the filehandle to print to;
4982 # return_only: 1 = print nothing; title: a line above the alignment in
4983 # "output_file", .svg or .tex; caption, label, split (blocks per table, 4)
4984 # and table_text_size: for a .tex only.
4985 53 my $args = _args(\@list, $sub, [], [qw(caption clustal_args color color_residues label msa_file order output_file return_only
4986 row_width split table_text_size threads title to track)]);
4987 53 _refs($sub, $args, 'ARRAY', qw(clustal_args order));
4988 52 _file_names($sub, $args, qw(msa_file output_file));
4989 51 _threads($sub, $args);
4990 50 ▶ if (defined $data) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $data) { } 34 16 50
4991 34 ▶ croak "$sub: was given the alignment both first and as \"msa_file\"" if defined $args->{'msa_file'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"msa_file"} 1 33 34
4992 33 ▶ croak "$sub: the alignment must be a hash ref of name => sequence or a FASTA file name, not " . _what($data)
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" or not ref $data and $data ne "" 2 31 33
Condition100%6/6
ref $data eq "HASH" or not ref $data and $data ne ""
l!l&&r!l&&!r
3012
not ref $data and $data ne ""
!ll&&!rl&&r
111
MC/DC100%3/3
ref $data eq "HASH" or not ref $data and $data ne ""
ref $data eq "HASH" not ref $data $data ne ""
Truth table100%4/4
A or not(B) and C
A= ref $data eq "HASH"B= not ref $dataC= $data ne ""
ABCresult
1XX1
0111
00X0
0100
4993 unless ref $data eq 'HASH' || (!ref $data && $data ne '');
4994 } else {
4995 16 ▶ $data = $args->{'msa_file'} // croak "$sub: needs an alignment, first or as \"msa_file\"";
Condition100%2/2
$args->{"msa_file"} // croak(qq[${sub}: needs an alignment, first or as "msa_file"])
l!l
151
MC/DC100%1/1
$args->{"msa_file"} // croak(qq[${sub}: needs an alignment, first or as "msa_file"])
$args->{"msa_file"}
Truth table100%2/2
A
A= $args->{"msa_file"}
Aresult
11
00
4996 }
4997 46 my %r;
4998 46 ▶ $r{'row_width'} = $args->{'row_width'} // 100;
Condition100%2/2
$args->{"row_width"} // 100
l!l
1729
MC/DC100%1/1
$args->{"row_width"} // 100
$args->{"row_width"}
Truth table100%2/2
A
A= $args->{"row_width"}
Aresult
11
00
4999 46 ▶ $r{split} = $args->{split} // 4;
Condition100%2/2
$args->{"split"} // 4
l!l
640
MC/DC100%1/1
$args->{"split"} // 4
$args->{"split"}
Truth table100%2/2
A
A= $args->{"split"}
Aresult
11
00
5000 # 0 would never end the loop over blocks, and divide by 0 in the tables
5001 46 foreach my $k ('row_width', 'split') {
5002 89 ▶ croak "$sub: \"$k\" must be a whole number, 1 or more, not " . _what($args->{$k}) if defined $args->{$k} && (ref $args->{$k} || $args->{$k} !~ /\A[1-9][0-9]*\z/);
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{$k} and ref $args->{$k} || !($args->{$k} =~ /\A[1-9][0-9]*\z/) 6 83 89
Condition83%5/6
defined $args->{$k} and ref $args->{$k} || !($args->{$k} =~ /\A[1-9][0-9]*\z/)
!ll&&!rl&&r
66176
ref $args->{$k} or not $args->{$k} =~ /\A[1-9][0-9]*\z/
l!l&&r!l&&!r
0617
MC/DC66%2/3
defined $args->{$k} and ref $args->{$k} || !($args->{$k} =~ /\A[1-9][0-9]*\z/)
defined $args->{$k} ref $args->{$k} not $args->{$k} =~ /\A[1-9][0-9]*\z/
Truth table75%3/4
A and B or not(C)
A= defined $args->{$k}B= ref $args->{$k}C= not $args->{$k} =~ /\A[1-9][0-9]*\z/
ABCresult
0XX0
1000
11X1
1011
5003 }
5004 40 ▶ $r{color} = $args->{color} // 0; # 1 = every residue on its palette color; 0 = only "color_residues" colored
Condition100%2/2
$args->{"color"} // 0
l!l
634
MC/DC100%1/1
$args->{"color"} // 0
$args->{"color"}
Truth table100%2/2
A
A= $args->{"color"}
Aresult
11
00
5005 40 ▶ croak "$sub: \"color\" must be 0 or 1, not " . _what($r{color}) unless !ref $r{color} && ($r{color} eq '0' || $r{color} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"color"} and $r{"color"} eq 0 || $r{"color"} eq 1 1 39 40
Condition83%5/6
not ref $r{"color"} and $r{"color"} eq 0 || $r{"color"} eq 1
!ll&&!rl&&r
0139
$r{"color"} eq 0 or $r{"color"} eq 1
l!l&&r!l&&!r
3451
MC/DC66%2/3
not ref $r{"color"} and $r{"color"} eq 0 || $r{"color"} eq 1
not ref $r{"color"} $r{"color"} eq 0 $r{"color"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"color"}B= $r{"color"} eq 0C= $r{"color"} eq 1
ABCresult
0XX0
1000
11X1
1011
5006 39 ▶ $r{'return_only'} = $args->{'return_only'} // 0; # 1 = return the text and print nothing; 0 = print it too
Condition100%2/2
$args->{"return_only"} // 0
l!l
1623
MC/DC100%1/1
$args->{"return_only"} // 0
$args->{"return_only"}
Truth table100%2/2
A
A= $args->{"return_only"}
Aresult
11
00
5007 croak "$sub: \"return_only\" must be 0 or 1, not " . _what($r{'return_only'})
5008 39 ▶ unless !ref $r{'return_only'} && ($r{'return_only'} eq '0' || $r{'return_only'} eq '1');
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $r{"return_only"} and $r{"return_only"} eq 0 || $r{"return_only"} eq 1 1 38 39
Condition83%5/6
not ref $r{"return_only"} and $r{"return_only"} eq 0 || $r{"return_only"} eq 1
!ll&&!rl&&r
0138
$r{"return_only"} eq 0 or $r{"return_only"} eq 1
l!l&&r!l&&!r
24141
MC/DC66%2/3
not ref $r{"return_only"} and $r{"return_only"} eq 0 || $r{"return_only"} eq 1
not ref $r{"return_only"} $r{"return_only"} eq 0 $r{"return_only"} eq 1
Truth table75%3/4
not(A) and B or C
A= not ref $r{"return_only"}B= $r{"return_only"} eq 0C= $r{"return_only"} eq 1
ABCresult
0XX0
1000
11X1
1011
5009 38 require Symbol;
5010 38 require Scalar::Util;
5011 # the selected handle, which is STDOUT unless the program changed it
5012 $r{to} = Scalar::Util::openhandle($args->{to} // Symbol::qualify_to_ref(select()))
5013 38 ▶ // croak "$sub: \"to\" must be an open filehandle, not " . _what($args->{to});
Condition80%4/5
&Scalar::Util::openhandle(scalar($args->{"to"} // &Symbol::qualify_to_ref(select))) // croak(qq[${sub}: "to" must be an open filehandle, not ] . _what($args->{"to"}))
l!l
371
$args->{"to"} // &Symbol::qualify_to_ref(select)
l!l&&r!l&&!r
2360
MC/DC100%1/1
&Scalar::Util::openhandle(scalar($args->{"to"} // &Symbol::qualify_to_ref(select))) // croak(qq[${sub}: "to" must be an open filehandle, not ] . _what($args->{"to"}))
&Scalar::Util::openhandle(scalar($args->{"to"} // &Symbol::qualify_to_ref(select)))
MC/DC0%0/2
$args->{"to"} // &Symbol::qualify_to_ref(select)
$args->{"to"} &Symbol::qualify_to_ref(select)
Truth table100%2/2
A
A= &Scalar::Util::openhandle(scalar($args->{"to"} // &Symbol::qualify_to_ref(select)))
Aresult
11
00
Truth table66%2/3
A // B
A= $args->{"to"}B= &Symbol::qualify_to_ref(select)
ABresult
1X1
011
000
5014 37 $r{'output_file'} = $args->{'output_file'};
5015 37 ▶ $r{format} = !defined $r{'output_file'} ? '' : $r{'output_file'} =~ /\.svg\z/i ? 'svg' : $r{'output_file'} =~ /\.tex\z/i ? 'tex'
Branch: 3 branches
BranchTrueFalseTotal
!defined($r{'output_file'}) ? : 15 22 37
$r{'output_file'} =~ /\.svg\z/i ? : 10 12 22
$r{'output_file'} =~ /\.tex\z/i ? : 11 1 12
5016 : croak "$sub: \"output_file\" must end in .svg or .tex, which say what to write, not \"$r{'output_file'}\""; # '' = no file
5017 36 my @tex_only = grep { defined $args->{$_} } qw(caption label split table_text_size);
5018 36 ▶ croak "$sub: " . join(', ', map { "\"$_\"" } @tex_only) . ' only shape a LaTeX "output_file" (.tex)' if @tex_only && $r{format} ne 'tex';
Branch: 1 branch
BranchTrueFalseTotal
if @tex_only and $r{"format"} ne "tex" 2 34 36
Condition100%3/3
@tex_only and $r{"format"} ne "tex"
!ll&&!rl&&r
3222
MC/DC100%2/2
@tex_only and $r{"format"} ne "tex"
@tex_only $r{"format"} ne "tex"
Truth table100%3/3
A and B
A= @tex_onlyB= $r{"format"} ne "tex"
ABresult
0X0
100
111
5019 34 ▶ $r{title} = $args->{title} // ''; # '' = no title line
Condition100%2/2
$args->{"title"} // ""
l!l
628
MC/DC100%1/1
$args->{"title"} // ""
$args->{"title"}
Truth table100%2/2
A
A= $args->{"title"}
Aresult
11
00
5020 34 ▶ croak "$sub: \"title\" is drawn only in an \"output_file\" (.svg or .tex), and none was given" if defined $args->{title} && $r{format} eq '';
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"title"} and $r{"format"} eq "" 1 33 34
Condition100%3/3
defined $args->{"title"} and $r{"format"} eq ""
!ll&&!rl&&r
2851
MC/DC100%2/2
defined $args->{"title"} and $r{"format"} eq ""
defined $args->{"title"} $r{"format"} eq ""
Truth table100%3/3
A and B
A= defined $args->{"title"}B= $r{"format"} eq ""
ABresult
0X0
100
111
5021 33 ▶ croak "$sub: \"title\" must be a string, not " . _what($r{title}) if ref $r{title};
Branch: 1 branch
BranchTrueFalseTotal
if ref $r{"title"} 1 32 33
5022 # a newline would end the SVG's line of text, and a blank line the LaTeX's \textbf
5023 32 ▶ croak "$sub: \"title\" holds a control character, " . sprintf('\\x{%02x}', ord $1) if $r{title} =~ /([\x00-\x1f\x7f])/;
Branch: 1 branch
BranchTrueFalseTotal
if $r{"title"} =~ /([\x00-\x1f\x7f])/ 1 31 32
5024 31 ▶ $r{caption} = $args->{caption} // '';
Condition50%1/2
$args->{"caption"} // ""
l!l
031
MC/DC0%0/1
$args->{"caption"} // ""
$args->{"caption"}
Truth table50%1/2
A
A= $args->{"caption"}
Aresult
11
00
5025 31 $r{label} = $args->{label};
5026 31 ▶ $r{'table_text_size'} = $args->{'table_text_size'} // '\footnotesize';
Condition50%1/2
$args->{"table_text_size"} // "\\footnotesize"
l!l
031
MC/DC0%0/1
$args->{"table_text_size"} // "\\footnotesize"
$args->{"table_text_size"}
Truth table50%1/2
A
A= $args->{"table_text_size"}
Aresult
11
00
5027 31 ▶ my $color = $args->{'color_residues'} // {};
Condition100%2/2
$args->{"color_residues"} // {}
l!l
1714
MC/DC100%1/1
$args->{"color_residues"} // {}
$args->{"color_residues"}
Truth table100%2/2
A
A= $args->{"color_residues"}
Aresult
11
00
5028 31 ▶ croak "$sub: \"color_residues\" must be a hash ref" unless ref $color eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $color eq "HASH" 0 31 31
5029 31 foreach my $protein (sort keys %{ $color }) {
5030 croak "$sub: \"color_residues\" must map $protein to a hash ref of residue number => color, not " . _what($color->{$protein})
5031 17 ▶ unless ref $color->{$protein} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $color->{$protein} eq "HASH" 1 16 17
5032 # checked before they are sorted as numbers, which would warn of one that is not
5033 16 _residue_number($sub, "a residue of $protein in \"color_residues\"", $_) foreach sort keys %{ $color->{$protein} };
5034 13 foreach my $n (sort { $a <=> $b } keys %{ $color->{$protein} }) {
5035 23 my $c = $color->{$protein}{$n};
5036 # xcolor's own names beyond its base 19 (dvipsnames and the rest)
5037 # have no rgb here, for the terminal or the SVG
5038 croak "$sub: the color of $protein residue $n must be one of xcolor's base colors (" . join(', ', sort keys %Xcolor)
5039 . ') or [r, g, b], each 0 to 1, not ' . _what($c)
5040 8 ▶ unless ref $c ? ref $c eq 'ARRAY' && @{ $c } == 3 && !grep { !defined $_ || ref $_ || !/\A(?:[0-9]+\.?[0-9]*|\.[0-9]+)\z/ || $_ > 1 } @{ $c }
Condition66%6/9
!defined($_) || ref $_ || !/\A(?:[0-9]+\.?[0-9]*|\.[0-9]+)\z/ || $_ > 1
l!l&&r!l&&!r
1122
not defined $_ or ref $_ or not /\A(?:[0-9]+\.?[0-9]*|\.[0-9]+)\z/
l!l&&r!l&&!r
0123
not defined $_ or ref $_
l!l&&r!l&&!r
0024
MC/DC50%2/4
!defined($_) || ref $_ || !/\A(?:[0-9]+\.?[0-9]*|\.[0-9]+)\z/ || $_ > 1
not defined $_ ref $_ not /\A(?:[0-9]+\.?[0-9]*|\.[0-9]+)\z/ $_ > 1
Truth table60%3/5
not(A) or B or not(C) || D
A= not defined $_B= ref $_C= not /\A(?:[0-9]+\.?[0-9]*|\.[0-9]+)\z/D= $_ > 1
ABCDresult
1XXX1
01XX1
001X1
00011
00000
5041 23 ▶ : defined $Xcolor{$c};
Branch: 2 branches
BranchTrueFalseTotal
unless ref $c ? ref $c eq "ARRAY" && @{$c;} == 3 && !grep({not defined $_ or ref $_ or not /\A(?:[0-9]+\.?[0-9]*|\.[0-9]+)\z/ or $_ > 1;} @{$c;}) : defined $Xcolor{$c} 3 20 23
ref $c ? : 8 15 23
Condition50%3/6
ref $c eq "ARRAY" and @{$c;} == 3 and not grep({not defined $_ or ref $_ or not /\A(?:[0-9]+\.?[0-9]*|\.[0-9]+)\z/ or $_ > 1;} @{$c;})
!ll&&!rl&&r
026
ref $c eq "ARRAY" and @{$c;} == 3
!ll&&!rl&&r
008
MC/DC33%1/3
ref $c eq "ARRAY" and @{$c;} == 3 and not grep({not defined $_ or ref $_ or not /\A(?:[0-9]+\.?[0-9]*|\.[0-9]+)\z/ or $_ > 1;} @{$c;})
ref $c eq "ARRAY" @{$c;} == 3 not grep({not defined $_ or ref $_ or not /\A(?:[0-9]+\.?[0-9]*|\.[0-9]+)\z/ or $_ > 1;} @{$c;})
Truth table50%2/4
A and B and not(C)
A= ref $c eq "ARRAY"B= @{$c;} == 3C= not grep({not defined $_ or ref $_ or not /\A(?:[0-9]+\.?[0-9]*|\.[0-9]+)\z/ or $_ > 1;} @{$c;})
ABCresult
0XX0
10X0
1100
1111
5042 }
5043 }
5044 24 my ($fasta, $seqs);
5045 24 ▶ if (ref $data) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data) { } 18 6 24
5046 18 ($fasta, $seqs) = ($data, $data);
5047 } else {
5048 6 ▶ croak "$sub: the FASTA file $data doesn't exist" unless -e $data;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $data 0 6 6
5049 6 ($fasta, $seqs) = ($data, fasta2hash($data));
5050 }
5051 24 ▶ croak "$sub: has no sequences to show in " . (ref $data ? 'the hash ref' : $data) unless %{ $seqs };
Branch: 2 branches
BranchTrueFalseTotal
unless %{$seqs;} 1 23 24
ref $data ? : 1 0 1
5052 23 foreach my $name (sort keys %{ $seqs }) {
5053 43 my $s = $seqs->{$name};
5054 43 ▶ croak "$sub: sequence \"$name\" must be a string of residues, not " . _what($s) unless defined $s && !ref $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s and not ref $s 1 42 43
Condition66%2/3
defined $s and not ref $s
!ll&&!rl&&r
0142
MC/DC50%1/2
defined $s and not ref $s
defined $s not ref $s
Truth table66%2/3
A and not(B)
A= defined $sB= not ref $s
ABresult
0X0
100
111
5055 # one would break a row in two, or make the SVG XML no longer
5056 42 ▶ croak "$sub: sequence \"$name\" holds a control character, " . sprintf('\\x{%02x}', ord $1) if $s =~ /([\x00-\x1f\x7f])/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /([\x00-\x1f\x7f])/ 1 41 42
5057 }
5058 21 my %len = map { length $_ => 1 } values %{ $seqs };
5059 21 my ($cmd, $names);
5060 21 ▶ if (keys %len > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %len > 1) 0 21 21
5061 # Sequences of different lengths can't be an alignment, so align them,
5062 # into a temporary file: the input is never written.
5063 0 my %clustal = map { $_ => $args->{$_} } grep { defined $args->{$_} } qw(clustal_args threads);
5064 0 (undef, undef, $names, $cmd, $seqs) = _align({ %clustal, fasta => $fasta }, $sub, 0);
5065 0 %len = map { length $_ => 1 } values %{ $seqs };
5066 }
5067 21 my ($aln_len) = keys %len;
5068 21 ▶ croak "$sub: has no residues to show in " . (ref $data ? 'the hash ref' : $data) unless $aln_len;
Branch: 2 branches
BranchTrueFalseTotal
unless $aln_len 1 20 21
ref $data ? : 1 0 1
5069 20 my $track = $args->{track};
5070 20 ▶ croak "$sub: tracker \"$track\" isn't in the alignment" if defined $track && !defined $seqs->{$track};
Branch: 1 branch
BranchTrueFalseTotal
if defined $track and not defined $seqs->{$track} 0 20 20
Condition66%2/3
defined $track and not defined $seqs->{$track}
!ll&&!rl&&r
1190
MC/DC0%0/2
defined $track and not defined $seqs->{$track}
defined $track not defined $seqs->{$track}
Truth table66%2/3
A and not(B)
A= defined $trackB= not defined $seqs->{$track}
ABresult
0X0
100
111
5071 20 my @undef = grep { !defined $seqs->{$_} } sort keys %{ $color };
5072 20 ▶ croak "$sub: \"color_residues\" names proteins that aren't in the alignment: @undef" if @undef;
Branch: 1 branch
BranchTrueFalseTotal
if @undef 0 20 20
5073 20 ▶ my @proteins = @{ $args->{order} // [sort { lc $a cmp lc $b } keys %{ $seqs }] };
Condition100%2/2
$args->{"order"} // [(sort {lc $a cmp lc $b;} keys %{$seqs;})]
l!l
218
MC/DC100%1/1
$args->{"order"} // [(sort {lc $a cmp lc $b;} keys %{$seqs;})]
$args->{"order"}
Truth table100%2/2
A
A= $args->{"order"}
Aresult
11
00
5074 20 my @bad = grep { !defined $seqs->{$_} } @proteins;
5075 20 ▶ croak "$sub: \"order\" names proteins that aren't in the alignment: @bad" if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 0 20 20
5076 20 my $width = $r{'row_width'};
5077 # Alignment column => color, and for the tracked protein column => its
5078 # residue number. A colored column is colored in every protein.
5079 20 my (%col_color, %col_number);
5080 20 foreach my $protein (sort keys %{ $color }) {
5081 10 my @col;
5082 10 ▶ while ($seqs->{$protein} =~ /[A-Za-z]/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seqs->{$protein} =~ /[A-Za-z]/g) 56 10 66
5083 56 push @col, pos($seqs->{$protein}) - 1;
5084 }
5085 10 foreach my $n (sort { $a <=> $b } keys %{ $color->{$protein} }) {
5086 20 ▶ my $col = $col[$n - 1] // croak "$sub: $protein has no residue $n";
Condition50%1/2
$col[$n - 1] // croak("${sub}: $protein has no residue $n")
l!l
200
MC/DC0%0/1
$col[$n - 1] // croak("${sub}: $protein has no residue $n")
$col[$n - 1]
Truth table50%1/2
A
A= $col[$n - 1]
Aresult
11
00
5087 20 $col_color{$col} = $color->{$protein}{$n};
5088 20 ▶ $col_number{$col} = $n if defined $track && $protein eq $track;
Branch: 1 branch
BranchTrueFalseTotal
if defined $track and $protein eq $track 18 2 20
Condition66%2/3
defined $track and $protein eq $track
!ll&&!rl&&r
2018
MC/DC50%1/2
defined $track and $protein eq $track
defined $track $protein eq $track
Truth table66%2/3
A and B
A= defined $trackB= $protein eq $track
ABresult
0X0
100
111
5089 }
5090 }
5091 # Each block of "row_width" columns: its first column (0-based), its width,
5092 # and its rows, each of which has its name, the label it is shown under,
5093 # whether it is the track row (1) or a sequence (0), its characters, each
5094 # one's color of "color_residues" or undef, each one's tooltip or undef, each
5095 # one's background as 0 to 255 r, g, b or undef (with "color" only), each
5096 # one's emphasis (1 = one of "color_residues" on a background, which is
5097 # shown bold and underlined; undef = none), and the residues so far. With
5098 # "color", one of "color_residues" has its own color as its background.
5099 20 ▶ my $palette = $r{color} ? _palette_for($seqs) : undef; # 'aa' or 'nt'; undef = no "color"
Branch: 1 branch
BranchTrueFalseTotal
$r{'color'} ? : 5 15 20
5100 20 ▶ my %bg = $r{color} ? map { $_ => [map { hex } $Residue_color{$palette}{$_} =~ /([0-9a-f]{2})/gi] } keys %{ $Residue_color{$palette} } : ();
Branch: 1 branch
BranchTrueFalseTotal
$r{'color'} ? : 5 15 20
5101 20 my (@blocks, %count);
5102 20 ▶ for (my $start = 0; $start < $aln_len; $start += $width) {
Branch: 1 branch
BranchTrueFalseTotal
if ($start < $aln_len) 32 20 52
5103 32 ▶ my $w = $aln_len - $start < $width ? $aln_len - $start : $width;
Branch: 1 branch
BranchTrueFalseTotal
$aln_len - $start < $width ? : 16 16 32
5104 32 my @rows;
5105 32 foreach my $protein (@proteins) {
5106 62 my @seq = split //, substr($seqs->{$protein}, $start, $w);
5107 62 my (@colors, @tips, @bg, @strong);
5108 62 foreach my $i (0 .. $#seq) {
5109 214 ▶ my $before = $count{$protein} // 0;
Condition100%2/2
$count{$protein} // 0
l!l
17638
MC/DC100%1/1
$count{$protein} // 0
$count{$protein}
Truth table100%2/2
A
A= $count{$protein}
Aresult
11
00
5110 214 ▶ $count{$protein} = $before + 1 if $seq[$i] =~ /[A-Za-z]/;
Branch: 1 branch
BranchTrueFalseTotal
if $seq[$i] =~ /[A-Za-z]/ 184 30 214
5111 214 ▶ $bg[$i] = $bg{ uc $seq[$i] } if $r{color};
Branch: 1 branch
BranchTrueFalseTotal
if $r{"color"} 48 166 214
5112 214 ▶ my $c = $col_color{ $start + $i } // next;
Condition100%2/2
$col_color{$start + $i} // (next)
l!l
44170
MC/DC100%1/1
$col_color{$start + $i} // (next)
$col_color{$start + $i}
Truth table100%2/2
A
A= $col_color{$start + $i}
Aresult
11
00
5113 44 $colors[$i] = $c;
5114 44 ▶ ($bg[$i], $strong[$i]) = ([_rgb255($c)], 1) if $r{color};
Branch: 1 branch
BranchTrueFalseTotal
if $r{"color"} 8 36 44
5115 44 ▶ $tips[$i] = _shown_name($protein) . ': ' . ($seq[$i] =~ /[A-Za-z]/ ? "$seq[$i]$count{$protein}" : 'a gap')
Branch: 1 branch
BranchTrueFalseTotal
$seq[$i] =~ /[A-Za-z]/ ? : 34 10 44
5116 . ', alignment column ' . ($start + $i + 1);
5117 }
5118 62 ▶ $count{$protein} //= 0;
Condition50%1/2
$count{$protein} //= 0
l!l
620
MC/DC0%0/1
$count{$protein} //= 0
$count{$protein}
Truth table50%1/2
A
A= $count{$protein}
Aresult
11
00
5119 push @rows, { name => $protein, label => _shown_name($protein), track => 0, chars => \@seq, colors => \@colors,
5120 62 tips => \@tips, bg => \@bg, strong => \@strong, count => $count{$protein} };
5121 62 ▶ next unless defined $track && $protein eq $track;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $track and $protein eq $track 46 16 62
Condition100%3/3
defined $track and $protein eq $track
!ll&&!rl&&r
232316
MC/DC100%2/2
defined $track and $protein eq $track
defined $track $protein eq $track
Truth table100%3/3
A and B
A= defined $trackB= $protein eq $track
ABresult
0X0
100
111
5122 # Each residue number written from its own column rightwards, one
5123 # digit per column so the row stays aligned, and moved right past
5124 # the end of the previous number rather than overwriting it. One
5125 # that would then run past the end of the block is moved left to end
5126 # there, and is left out only if that would overwrite the number
5127 # before it.
5128 16 my @row = ('-') x $w;
5129 16 my $free = 0; # first column not yet taken by a number
5130 16 ▶ foreach my $col (sort { $a <=> $b } grep { $_ >= $start && $_ < $start + $w } keys %col_number) {
Condition100%3/3
$_ >= $start && $_ < $start + $w
!ll&&!rl&&r
11718
MC/DC100%2/2
$_ >= $start && $_ < $start + $w
$_ >= $start $_ < $start + $w
Truth table100%3/3
A && B
A= $_ >= $startB= $_ < $start + $w
ABresult
0X0
100
111
5131 18 ▶ my $at = $col - $start < $free ? $free : $col - $start;
Branch: 1 branch
BranchTrueFalseTotal
$col - $start < $free ? : 1 17 18
5132 18 my @digits = split //, $col_number{$col};
5133 18 ▶ $at = $w - @digits if $at + @digits > $w;
Branch: 1 branch
BranchTrueFalseTotal
if $at + @digits > $w 2 16 18
5134 18 ▶ next if $at < $free;
Branch: 1 branch
BranchTrueFalseTotal
if $at < $free 1 17 18
5135 17 @row[$at .. $at + $#digits] = @digits;
5136 17 $free = $at + @digits + 1;
5137 }
5138 push @rows, { name => $protein, label => _shown_name($protein) . ' track', track => 1, chars => \@row, colors => [], tips => [],
5139 16 bg => [], strong => [], count => $count{$protein} };
5140 }
5141 32 push @blocks, { start => $start, width => $w, rows => \@rows };
5142 }
5143 20 my $n_seqs = keys %{ $seqs };
5144 20 ▶ my $banner = "# alignment: $n_seqs sequence" . ($n_seqs == 1 ? '' : 's') . " x $aln_len column" . ($aln_len == 1 ? '' : 's')
Branch: 4 branches
BranchTrueFalseTotal
$n_seqs == 1 ? : 2 18 20
$aln_len == 1 ? : 0 20 20
defined $cmd ? : 0 20 20
@proteins == $n_seqs ? : 18 2 20
5145 . (defined $cmd ? ', aligned by Clustal Omega' : '') . (@proteins == $n_seqs ? '' : ' (showing ' . scalar(@proteins) . ')');
5146 20 ▶ if ($r{format} ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"format"} ne "") 14 6 20
5147 14 ▶ my $from = defined $cmd ? _align_provenance({ fasta => $fasta }, $sub, $cmd, $names, $cmd->[4])
Branch: 1 branch
BranchTrueFalseTotal
defined $cmd ? : 0 14 14
5148 : 'from ' . _fasta_id($fasta, $n_seqs);
5149 my $creator = _creator($sub, 1) . ', written as ' . ($r{format} eq 'svg' ? 'SVG' : 'LaTeX') . ' by ' . __FILE__ . " itself; $from"
5150 . '; showing ' . scalar(@proteins) . " of $n_seqs sequences in blocks of $width columns"
5151 . (defined $track ? ', tracking ' . _shown_name($track) : '') . ', coloring ' . scalar(keys %col_color) . ' column'
5152 . (keys %col_color == 1 ? '' : 's')
5153 14 ▶ . ($r{color} ? ', every residue on its color from CIAlign\'s CBS ' . ($palette eq 'nt' ? 'nucleotide' : 'amino acid') . ' palette, as plot_msa colors it' : '');
Branch: 5 branches
BranchTrueFalseTotal
$r{'format'} eq 'svg' ? : 7 7 14
defined $track ? : 5 9 14
keys %col_color == 1 ? : 2 12 14
$r{'color'} ? : 4 10 14
$palette eq 'nt' ? : 1 3 4
5154 14 ▶ if ($r{format} eq 'svg') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{'format'} eq 'svg') { } 7 7 14
5155 7 _alignment_svg($sub, $r{'output_file'}, \@blocks, $creator, $r{title});
5156 } else {
5157 7 _alignment_tex($sub, \%r, \@blocks, $creator);
5158 }
5159 }
5160 20 my $text = _alignment_text(\@blocks, $banner, 0);
5161 20 utf8::encode($text);
5162 20 ▶ return $text if $r{'return_only'};
Branch: 1 branch
BranchTrueFalseTotal
if $r{"return_only"} 14 6 20
5163 6 my $shown = $text;
5164 6 ▶ if (-t $r{to}) {
Branch: 1 branch
BranchTrueFalseTotal
if (-t $r{"to"}) 0 6 6
5165 0 $shown = _alignment_text(\@blocks, $banner, 1);
5166 0 utf8::encode($shown);
5167 }
5168 6 ▶ print { $r{to} } $shown or croak "$sub: can't print to \"to\": $!";
Branch: 1 branch
BranchTrueFalseTotal
print {$r{"to"};} $shown or croak(qq[${sub}: can't print to "to": $!]) 6 0 6
5169 6 ▶ _wrote($r{'output_file'}, 46) if $r{format} ne ''; # cyan
Branch: 1 branch
BranchTrueFalseTotal
if $r{"format"} ne "" 5 1 6
5170 6 $text;
5171 }
5172  
5173 40 1;
5174  
5175 __END__
↑ Summary Bioinf.xs »