blib/lib/Cn/Bioinf.pm

filter: Statementstmt 82.3% 2162 / 2625 Branchbran 73.3% 1229 / 1676 Conditioncond 67.6% 895 / 1324 MC/DCmcdc 51.0% 365 / 715 Subroutinesub 88.4% 153 / 173 Podpod 100% 33 / 33 totaltotal 73.8% 4837 / 6546 CC 1469 SCAR 60.7
CC
1469
Cov
76%
pgs_score
4550.0
msa_quality_table
758.1
plot_msa
285.2
CRAP 433.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. fasta2hash and hash2fasta_file are now XS (Bioinf.xs).
7 # msa_phylo_plot is now plot_msa and plot_phylo, and no longer takes a BLAST
8 # report and a proteome database: each is given the sequences, aligns them with
9 # Clustal Omega and draws the result itself, with share/msa_plot.py (from
10 # ~/Scripts/HitList/scripts/x.my.align.py) in place of that script and of the
11 # R/ggtree tree. msa_quality_table's table is drawn by that script too, where
12 # bioinf.pm had Matplotlib::Simple's colored_table draw it. clustalo, blastp and
13 # that Python all come from Alien::Bioinf, never from PATH. Alien::Bioinf is only
14 # recommended, not required, since it cannot be installed everywhere (NCBI
15 # builds BLAST+ for few platforms) and fasta2hash, hash2fasta_file and
16 # get_best_alignment_hit do not need it; the functions that do load it through
17 # _alien, which says what is missing.
18 #
19 # concordance is ~/Scripts/old/x.low_ram_local_concordance.pl (as it stood on
20 # 2026-10-19) made a function of two VCFs: its 45 kinds of comparison and its
21 # metrics are counted in Bioinf.xs, whose comments above CONC_NAME and CONC_TP
22 # say where it departs from that script; its XLSX, JSON and ACMG59 output are
23 # not made.
24 36 require 5.012;
25 36 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 36 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 36 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
28 36 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 36 ▶use Sys::Hostname 'hostname';
Subroutine BEGIN: called CC=1 SCAR=0.0
30 36 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
31 36 ▶use XSLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 36 our $VERSION = '0.02';
33 36 our @EXPORT_OK = qw(
34 assembly_stats back_transcribe blood_type clustal_view_residues complement concordance fasta2hash fasta_index
35 fasta_region find_orfs gc_content get_best_alignment_hit hash2fasta_file hirisplex_genotypes isoelectric_point
36 kmer_count molecular_weight motif_search msa_quality_table parent pdb_search pgs_score plot_msa plot_phylo
37 protein_charge relatedness reverse_complement sex_check subseq trait_predict transcribe translate
38 translate_six_frames
39 );
40 36 our @EXPORT = @EXPORT_OK;
41 36 our %EXPORT_TAGS = (all => \@EXPORT_OK);
42 36 XSLoader::load('Cn::Bioinf', $VERSION);
43 # The calling script's full path, for _creator. It is looked up at load time,
44 # as FindBin always does, but FindBin croaks when $0 is not a file on disk
45 # (after $0 is assigned to, or under an embedder), and that must not stop this
46 # module loading, so $0 made absolute stands in then. Up to 2026-10-17 this was
47 # the script's file name alone, which _creator joined to the working directory,
48 # so a script run from another directory was recorded at a path that wasn't it.
49 36 ▶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
3510
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
50  
51 # ---- private helpers
52  
53 # The name => value pairs in @$list as a hash ref. Dies unless they hold every
54 # @$required key and nothing outside @$required and @$optional. Its messages
55 # are prefixed with $sub, the public function whose arguments they are, not
56 # with "_args".
57 968 ▶sub _args {
Subroutine _args: called CC=7 SCAR=19.5
58 968 my ($list, $sub, $required, $optional) = @_;
59 968 ▶ 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 954 968
Condition100%3/3
@{$list;} == 1 and ref $list->[0] eq "HASH"
!ll&&!rl&&r
9441014
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
60 954 ▶ 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 941 954
61 # an undef name would only warn, as a hash key, and then be reported as ""
62 941 my ($nameless) = grep { !defined $list->[2 * $_] } 0 .. @{ $list } / 2 - 1;
63 941 ▶ 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 938 941
64 938 my $args = { @{ $list } };
65 938 my @missing = grep { !defined $args->{$_} } @{ $required };
66 938 ▶ croak "$sub: needs " . join(', ', map { "\"$_\"" } @missing) if @missing;
Branch: 1 branch
BranchTrueFalseTotal
if @missing 8 930 938
67 930 my %ok = map { $_ => 1 } @{ $required }, @{ $optional };
68 930 my @bad = sort grep { !$ok{$_} } keys %{ $args };
69 930 ▶ croak "$sub: doesn't know " . join(', ', map { "\"$_\"" } @bad) . '; it takes ' . join(', ', sort keys %ok) if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 18 912 930
70 912 $args;
71 }
72  
73 # $v as a message names it: "a HASH ref", "an ARRAY ref", "undef", or the
74 # string quoted.
75 212 ▶sub _what {
Subroutine _what: called CC=4 SCAR=13.9
76 212 my ($v) = @_;
77 212 ▶ return 'undef' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 27 185 212
78 185 ▶ ref $v ?(ref($v) =~ /\A[AEIOU]/ ? 'an ' : 'a ') . ref($v) . ' ref' : "\"$v\"";
Branch: 2 branches
BranchTrueFalseTotal
ref $v ? : 63 122 185
ref($v) =~ /\A[AEIOU]/ ? : 47 16 63
79 }
80  
81 # Dies unless each of @keys of $args that was given is a $type ('ARRAY' or
82 # 'HASH') ref, naming $sub, the public function whose arguments they are. Up to
83 # 2026-10-17 a wrong one died with perl's own "Not an ARRAY reference", naming
84 # no function, and often only once clustalo had run.
85 105 ▶sub _refs {
Subroutine _refs: called CC=5 SCAR=16.1
86 105 my ($sub, $args, $type, @keys) = @_;
87 105 foreach my $k (@keys) {
88 149 ▶ 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 142 7 149
Condition100%3/3
not defined $args->{$k} or ref $args->{$k} eq $type
l!l&&r!l&&!r
13937
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
89 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
90 }
91 }
92  
93 # Dies unless each of @keys of $args that was given is a file name: a string
94 # that is not empty, naming $sub, the public function whose arguments they are.
95 # Up to 2026-11-10 a reference was used as its text, so that
96 # plot_msa(filename => []) wrote an image named "ARRAY(0x5ea732db32c8)".
97 65 ▶sub _file_names {
Subroutine _file_names: called CC=5 SCAR=16.1
98 65 my ($sub, $args, @keys) = @_;
99 65 foreach my $k (@keys) {
100 154 ▶ next unless defined $args->{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args->{$k} 76 78 154
101 78 ▶ 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 71 78
Condition100%3/3
ref $args->{$k} or $args->{$k} eq ""
l!l&&r!l&&!r
6171
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
102 }
103 }
104  
105 # Dies unless "threads" of $sub's $args, clustalo's --threads, is a whole
106 # number, 1 or more, or was not given. Up to 2026-11-10 anything else reached
107 # clustalo, which refused it under _run's name once the sequences were written.
108 42 ▶sub _threads {
Subroutine _threads: called CC=4 SCAR=14.9
109 42 my ($sub, $args) = @_;
110 croak "$sub: \"threads\" must be a whole number, 1 or more, not " . _what($args->{threads})
111 42 ▶ 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 38 42
Condition50%3/6
defined $args->{"threads"} and ref $args->{"threads"} || !($args->{"threads"} =~ /\A[1-9][0-9]*\z/)
!ll&&!rl&&r
3804
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
112 }
113  
114 # The error that Bioinf.xs's croak() ends with when it is raised in this file,
115 # which is where every XSUB is called from; compiled once, since perl 5.32
116 # leaks a pattern that is compiled at run time.
117 36 my $Located_here = qr/ at \Q${\ __FILE__}\E line [0-9]+\.\n\z/;
118  
119 # What $code, a call of one of Bioinf.xs's XSUBs, returns, in list context. An
120 # error that Bioinf.xs raised is raised again at the caller's line, as croak
121 # raises this file's own: C's croak() gives the line of this file that called
122 # the XSUB, which up to 2026-11-10 was all a caller was told. Any other error,
123 # such as one a VCF's reader croaked with, has its place already and is passed
124 # on as it is. $@ is not localized, since before perl 5.14 leaving that scope
125 # by die restored it, and lost the error.
126 720 ▶sub _located {
Subroutine _located: called CC=4 SCAR=13.9
127 720 my ($code) = @_;
128 720 my @r;
129 720 ▶ return @r if eval { @r = $code->(); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { @r = &$code(); 1 } } 628 92 720
130 92 my $error = $@;
131 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
132 90 croak $error;
133 }
134  
135 # $s as characters. A string perl holds as characters is taken as it is; one it
136 # holds as bytes is taken to be UTF-8 if it decodes as such, which is how the
137 # command line used to pass it to Python, and Latin-1 otherwise.
138 0 ▶sub _chars {
Subroutine _chars: not called CC=2 SCAR=17.9
139 0 my $s = "$_[0]";
140 0 ▶ utf8::decode($s) unless utf8::is_utf8($s);
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::is_utf8($s) 0 0 0
141 0 $s;
142 }
143  
144 # $s, read as _chars reads it, as UTF-8 bytes, which is what msa_plot.py reads
145 # a FASTA or newick file as.
146 0 ▶sub _utf8 {
Subroutine _utf8: not called CC=1 SCAR=6.9
147 0 my $s = _chars($_[0]);
148 0 utf8::encode($s);
149 0 $s;
150 }
151  
152 # The start of the "Creator" written into an image's metadata, after the one
153 # Matplotlib::Simple 0.319 writes: which script, run where, called which sub of
154 # which version of this module (and of Alien::Bioinf, whose tools and Python
155 # draw every image), by whom, on which computer (its hostname and OS), with
156 # which perl and where it is. Like Matplotlib::Simple's, the Creator is the image's
157 # whole provenance, on one line, and the only metadata written: msa_plot.py
158 # appends the Python, matplotlib and Biopython versions as it runs, since only
159 # it knows them, and then each clause it is given with "--p" (what the image
160 # was made from, with digests, and the commands that made it). Matplotlib::Simple has to py_str() its
161 # Creator, which it pastes into a Python literal; this one reaches Python as a
162 # JSON string through _python's --argfile, so backslashes and quotes in a path
163 # need no escaping here.
164 1 ▶sub _creator {
Subroutine _creator: called CC=1 SCAR=0.0
165 1 my ($sub) = @_;
166 1 _alien($sub);
167 1 "$Script called using \"$sub\" in " . __FILE__ . " version $VERSION with Alien::Bioinf $Alien::Bioinf::VERSION"
168 . ' by user ' . _user() . ' on host ' . hostname() . " ($^O) with Perl " . sprintf('%vd', $^V) . " ($^X)";
169 }
170  
171 # The name of the user running this. getpwuid is unimplemented on MSWin32,
172 # where it dies, and getlogin is undef without a controlling terminal (under
173 # cron, or a batch scheduler), so the environment is the last resort.
174 1 ▶sub _user {
Subroutine _user: called CC=8 SCAR=28.4
175 1 my $user = eval { (getpwuid $<)[0] };
176 1 ▶ $user = getlogin() unless defined $user && length $user;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $user and length $user 0 1 1
Condition33%1/3
defined $user and length $user
!ll&&!rl&&r
001
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
177 1 ▶ $user = $ENV{USERNAME} // $ENV{USER} unless defined $user && length $user;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $user and length $user 0 1 1
Condition16%1/6
defined $user and length $user
!ll&&!rl&&r
001
$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
178 1 ▶ defined $user && length $user ? $user : 'unknown';
Branch: 1 branch
BranchTrueFalseTotal
defined $user && length $user ? : 1 0 1
Condition33%1/3
defined $user and length $user
!ll&&!rl&&r
001
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
179 }
180  
181 # The data in the JSON file $file, which $sub was given; dies naming $sub, as
182 # the file is that caller's argument. Up to 2026-11-02 a file that was not JSON
183 # died with JSON::MaybeXS's message, naming no function, and an empty one with
184 # a "Usage:" message, since <$fh> passed decode_json an empty list.
185 24 ▶sub _json_file {
Subroutine _json_file: called CC=5 SCAR=16.2
186 24 my ($sub, $file) = @_;
187 24 require JSON::MaybeXS;
188 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
189 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
190 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
191 24 my $data = eval { JSON::MaybeXS::decode_json($text) };
192 24 ▶ unless (defined $data) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 3 21 24
193 3 (my $why = $@) =~ s/ at .+ line \d+\.\n\z//; # the location is the module's, which says nothing of the file
194 3 croak "$sub: $file isn't JSON: $why";
195 }
196 21 $data;
197 }
198  
199 # @cmd run with list-form system, which needs no shell. $? is -1 when the
200 # program never started; otherwise its low 7 bits are the signal that killed
201 # it, and must be read before the shift, which leaves only the exit code.
202 2 ▶sub _run {
Subroutine _run: called CC=4 SCAR=14.2
203 2 my @cmd = @_;
204 2 ▶ system(@cmd) == 0 and return;
Branch: 1 branch
BranchTrueFalseTotal
system(@cmd) == 0 and return 0 2 2
205 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
206 2 croak "_run: \"@cmd\" failed: $why";
207 }
208  
209 # Alien::Bioinf, loaded for $sub, or a message saying that $sub needs it.
210 2 ▶sub _alien {
Subroutine _alien: called CC=2 SCAR=6.9
211 2 my ($sub) = @_;
212 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
213 or croak "_alien: $sub needs Alien::Bioinf, for Clustal Omega, BLAST+ and the plotting Python, and it can't be loaded: $@";
214 1 'Alien::Bioinf';
215 }
216  
217 # share/msa_plot.py run with @args under Alien::Bioinf's Python, for $sub. The
218 # arguments go in a JSON file rather than on the command line: perl's
219 # system(LIST) on Windows does not escape a '"' inside an argument, and the
220 # Creator and the JSON options are full of them. Each argument is read as
221 # _chars reads it; encode_json alone would read UTF-8 bytes as Latin-1. -I
222 # keeps PYTHONPATH, PYTHONHOME and the user's own site-packages out, so that
223 # nothing but Alien::Bioinf's venv is imported.
224 0 ▶sub _python {
Subroutine _python: not called CC=3 SCAR=24.8
225 0 my ($sub, @args) = @_;
226 0 require JSON::MaybeXS;
227 0 my @chars = map { _chars($_) } @args;
228 0 my $argfile = _tmp('.json');
229 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
230 0 print {$fh} JSON::MaybeXS::encode_json(\@chars);
231 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
232 0 _run(_alien($sub)->python, '-I', _script(), '--argfile', $argfile);
233 }
234  
235 # $data, whose strings the caller has made characters with _chars, as JSON
236 # text: characters, not UTF-8 bytes, since it is one argument that _python
237 # encodes along with the rest. It is held as UTF-8, so that _python takes it as
238 # it is: decoding it whole, as up to 2026-10-17, turned a byte string inside it
239 # to mojibake whenever another string in it held characters.
240 0 ▶sub _json_text {
Subroutine _json_text: not called CC=1 SCAR=6.9
241 0 my ($data) = @_;
242 0 require JSON::MaybeXS;
243 0 my $text = JSON::MaybeXS->new(utf8 => 0, canonical => 1)->encode($data);
244 0 utf8::upgrade($text);
245 0 $text;
246 }
247  
248 # "wrote $file" to STDOUT, as LikeR's write_table prints it: $file in black
249 # (30) on $bg (an ANSI background, 43 = yellow or 46 = cyan) and then reset
250 # (0), written out rather than loaded from Term::ANSIColor; the reset comes
251 # before the newline so the colour doesn't run on into the next line. The
252 # colour is left out when STDOUT is not a terminal, where the escapes would
253 # only be noise in a log or a test harness.
254 19 ▶sub _wrote {
Subroutine _wrote: called CC=3 SCAR=11.7
255 19 my ($file, $bg, $verb) = @_;
256 19 ▶ $verb //= 'wrote'; # or 'will write', for an image whose script has not run yet
Condition50%1/2
$verb //= "wrote"
l!l
019
MC/DC0%0/1
$verb //= "wrote"
$verb
Truth table50%1/2
A
A= $verb
Aresult
11
00
257 19 ▶ print STDOUT -t STDOUT ? "$verb \e[30;${bg}m$file\e[0m\n" : "$verb $file\n";
Branch: 1 branch
BranchTrueFalseTotal
-t STDOUT ? : 0 19 19
258 }
259  
260 # A new temporary file's name, with $suffix. It is removed when perl exits
261 # unless $keep is true.
262 2 ▶sub _tmp {
Subroutine _tmp: called CC=3 SCAR=11.3
263 2 my ($suffix, $keep) = @_;
264 2 require File::Temp;
265 2 ▶ my ($fh, $name) = File::Temp::tempfile(SUFFIX => $suffix, UNLINK => $keep ? 0 : 1, TMPDIR => 1);
Branch: 1 branch
BranchTrueFalseTotal
$keep ? : 0 2 2
266 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
267 2 $name;
268 }
269  
270 # "fh" and "execute" of $sub's $args, resolved and checked before anything
271 # runs, as Matplotlib::Simple's plt takes them: "fh" is a File::Temp that the
272 # Python drawing the image is appended to, so that one script, run once, can
273 # draw several images (and those of Matplotlib::Simple, which takes the same
274 # File::Temp); "execute" says whether to run that script now.
275 23 ▶sub _drawing {
Subroutine _drawing: called CC=8 SCAR=21.1
276 23 my ($sub, $args) = @_;
277 23 my %r = (fh => $args->{fh});
278 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
279 croak "$sub: \"execute\" must be 0 or 1, not " . _what($r{execute})
280 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
281 17 ▶ if (defined $r{fh}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $r{"fh"}) 4 13 17
282 4 require Scalar::Util;
283 croak "$sub: \"fh\" must be a File::Temp object, as for Matplotlib::Simple, not " . _what($r{fh})
284 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
285 }
286 13 \%r;
287 }
288  
289 # share/msa_plot.py run with @args for $sub, as Python appended to the script
290 # that $drawing (from _drawing) names, or to a new temporary one; the script is
291 # run under Alien::Bioinf's Python if $drawing->{execute}. Returns the script's
292 # file name. A new script is kept after perl exits only when it is not run
293 # here, since only then is it of use afterwards.
294 #
295 # The script is the whole of what it needs, so that it can be run later, after
296 # perl has removed its temporary files: each file passed with --f, --tree or
297 # --table is carried in it, and written out again, to a temporary directory,
298 # as the script runs. Nothing perl was given is pasted into the Python source:
299 # the arguments, the files and msa_plot.py's path are one JSON object, base64
300 # encoded, as Matplotlib::Simple's write_data passes data, since a Windows
301 # path's "\b" is a backspace in a Python literal and an apostrophe would close
302 # it. msa_plot.py is run by runpy in a namespace of its own, so that its
303 # globals meet neither those of another image in the script nor those of
304 # Matplotlib::Simple's code. -I keeps PYTHONPATH, PYTHONHOME and the user's own
305 # site-packages out, as for _python.
306 0 ▶sub _draw {
Subroutine _draw: not called CC=15 SCAR=54.8
307 0 my ($sub, $drawing, @args) = @_;
308 0 require JSON::MaybeXS;
309 0 require MIME::Base64;
310 0 my %file = map { $_ => 1 } qw(--f --tree --table); # the options whose value is a file msa_plot.py reads
311 0 my @json;
312 0 ▶ for (my $i = 0; $i < @args; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @args) 0 0 0
313 0 push @json, _chars($args[$i]);
314 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
315 0 my $in = $args[++$i];
316 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
317 0 my $bytes = do { local $/; <$fh> };
318 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
319 # named by its place, so that no two collide, and with its own suffix
320 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
321 }
322 0 my $b64 = MIME::Base64::encode_base64(JSON::MaybeXS::encode_json({ script => _chars(_script()), args => \@json }), '');
323 0 my $py = <<"PYTHON";
324 # $sub, from Cn::Bioinf $VERSION: msa_plot.py run on the arguments below
325 import base64, json, os, runpy, sys, tempfile
326 cn_bioinf = json.loads(base64.b64decode('$b64').decode('utf-8'))
327 with tempfile.TemporaryDirectory() as cn_bioinf_dir:
328 cn_bioinf_argv = []
329 for cn_bioinf_arg in cn_bioinf['args']:
330 if isinstance(cn_bioinf_arg, dict):
331 cn_bioinf_path = os.path.join(cn_bioinf_dir, cn_bioinf_arg['name'])
332 with open(cn_bioinf_path, 'wb') as cn_bioinf_fh:
333 cn_bioinf_fh.write(base64.b64decode(cn_bioinf_arg['b64']))
334 cn_bioinf_arg = cn_bioinf_path
335 cn_bioinf_argv.append(cn_bioinf_arg)
336 sys.argv = [cn_bioinf['script']] + cn_bioinf_argv
337 runpy.run_path(cn_bioinf['script'], run_name='__main__')
338 PYTHON
339 0 my $script;
340 0 ▶ if (defined $drawing->{fh}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $drawing->{'fh'}) { } 0 0 0
341 0 my $fh = $drawing->{fh};
342 0 $script = $fh->filename;
343 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
344 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
345 } else {
346 0 $script = _tmp('.py', !$drawing->{execute});
347 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
348 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
349 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
350 }
351 0 ▶ _run(_alien($sub)->python, '-I', $script) if $drawing->{execute};
Branch: 1 branch
BranchTrueFalseTotal
if $drawing->{"execute"} 0 0 0
352 0 $script;
353 }
354  
355 0 ▶sub _script {
Subroutine _script: not called CC=1 SCAR=6.9
356 0 require File::ShareDir;
357 0 File::ShareDir::dist_file('Cn-Bioinf', 'msa_plot.py');
358 }
359  
360 # The FASTA file's records and their deflines in file order.
361 0 ▶sub _fasta_ordered {
Subroutine _fasta_ordered: not called CC=1 SCAR=6.9
362 0 my ($file) = @_;
363 0 my @order;
364 0 my $fh = _open_fasta($file);
365 0 ▶ my ($h) = _located(sub { _read_fasta($fh, undef, $file, \@order) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
366 0 close $fh;
367 0 ($h, \@order);
368 }
369  
370 63 ▶sub _open_fasta {
Subroutine _open_fasta: called CC=8 SCAR=21.8
371 63 my ($file) = @_;
372 63 ▶ croak "_open_fasta: undef isn't a readable file" unless defined $file;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file 1 62 63
373 62 ▶ 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 61 62
Condition66%2/3
-f $file and -r _
!ll&&!rl&&r
1061
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
374 61 my $fh;
375 61 ▶ if ($file =~ /\.gz\z/i) { # any case, as _weight_rows takes it
Branch: 1 branch
BranchTrueFalseTotal
if ($file =~ /\.gz\z/i) { } 7 54 61
376 # in an eval, since a perl without list-form piped open (MSWin32 before
377 # 5.22) dies in open itself, with no function name in the message
378 # "--", or gzip would read a name that starts with "-" as its options
379 7 ▶ 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}: " . ($@ || $!)) 7 0 7
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
380 } else {
381 54 ▶ 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}: $!") 54 0 54
382 }
383 61 $fh;
384 }
385  
386 6 ▶sub _first_letter {
Subroutine _first_letter: called CC=2 SCAR=8.1
387 6 my ($string) = @_;
388 6 ▶ return $1 if $string =~ /^([A-Za-z])/;
Branch: 1 branch
BranchTrueFalseTotal
if $string =~ /^([A-Za-z])/ 6 0 6
389 0 croak "_first_letter: \"$string\" doesn't start with a letter, so it has no first letter";
390 }
391  
392 # Narrow but unambiguous labels, e.g. "$\it{C.al.}$", for [genus, species,
393 # strain] triples ('' for no strain). One letter of the species cannot tell
394 # C.albicans from C.auris, so this takes the shortest species prefix that
395 # separates every entry; the strain is always kept, since it is all that
396 # separates the three C.neoformans.
397 2 ▶sub _abbreviated_labels {
Subroutine _abbreviated_labels: called CC=6 SCAR=19.1
398 2 my ($names) = @_;
399 2 my $max = 0;
400 2 foreach my $n (@{ $names }) {
401 3 ▶ $max = length $n->[1] if length $n->[1] > $max;
Branch: 1 branch
BranchTrueFalseTotal
if length $n->[1] > $max 2 1 3
402 }
403 2 foreach my $n (1 .. $max) {
404 my @labels = map {
405 3 ▶ '$\it{' . ucfirst(_first_letter($_->[0])) . '.' . lc(substr($_->[1], 0, $n)) . '.}$' . ($_->[2] ne '' ? " $_->[2]" : '')
Branch: 1 branch
BranchTrueFalseTotal
$_->[2] ne '' ? : 0 3 3
406 2 } @{ $names };
407 2 my %seen;
408 2 ▶ return \@labels unless grep { $seen{$_}++ } @labels;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$seen{$_}++;} @labels 2 0 2
409 }
410 0 croak "_abbreviated_labels: can't tell " . join(', ', map { join '.', @{ $_ } } @{ $names }) . ' apart, even with the full species name and strain';
411 }
412  
413 # ---- FASTA
414  
415 63 ▶sub fasta2hash {
Subroutine fasta2hash: called CC=9 SCAR=22.2
Pod documented
416 63 my ($file, $key) = @_;
417 63 my $fh = _open_fasta($file);
418 61 ▶ my ($r) = _located(sub { _read_fasta($fh, $key, $file) });
Subroutine __ANON__: called CC=1 SCAR=0.0
419 # A gzip that fails part-way, on a truncated or corrupt .gz, has merely
420 # stopped writing, so its exit status is the only sign of it. That is
421 # checked unless $key was found, when reading may have stopped early and
422 # the closed pipe have killed gzip with a SIGPIPE.
423 57 ▶ unless (close $fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close $fh) 2 55 57
424 2 ▶ my $why = $! ? "$!" : $? & 127 ? 'gzip was killed by signal ' . ($? & 127) : 'gzip exited ' . ($? >> 8);
Branch: 2 branches
BranchTrueFalseTotal
$! ? : 0 2 2
$? & 127 ? : 0 2 2
425 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
426 }
427 55 ▶ if (defined $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key) 15 40 55
428 15 ▶ return $r if defined $r;
Branch: 1 branch
BranchTrueFalseTotal
if defined $r 12 3 15
429 3 croak "fasta2hash: couldn't find \"$key\" in $file";
430 }
431 40 ▶ croak "fasta2hash: couldn't find any sequences in $file" unless %{ $r };
Branch: 1 branch
BranchTrueFalseTotal
unless %{$r;} 1 39 40
432 39 $r;
433 }
434  
435 27 ▶sub hash2fasta_file {
Subroutine hash2fasta_file: called CC=10 SCAR=23.1
Pod documented
436 27 my ($hash, $filename, $order, $width) = @_;
437 27 ▶ 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 26 27
438 26 ▶ 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 26 26
Condition33%1/3
defined $filename and ref $filename eq ""
!ll&&!rl&&r
0026
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
439 26 ▶ 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 25 26
Condition100%3/3
defined $order and ref $order ne "ARRAY"
!ll&&!rl&&r
15101
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
440 # checked here because the XS takes it as a UV, where -1 would wrap round
441 25 ▶ 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 22 25
Condition100%3/3
defined $width and not $width =~ /\A[0-9]+\z/
!ll&&!rl&&r
1843
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
442 22 ▶ _fasta_file('hash2fasta_file', $hash, $filename, $order // [sort keys %{ $hash }], $width // 80);
Condition100%4/4
$order // [sort(keys %{$hash;})]
l!l
1012
$width // 80
l!l
418
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
443 12 _wrote($filename, 46); # cyan
444 12 $filename;
445 }
446  
447 # hash2fasta_file without its checks, its defaults or its "wrote" line, for
448 # the FASTA files the module writes for itself, mostly temporary ones that a
449 # caller never asked for; $sub is the caller, to name in an error.
450 23 ▶sub _fasta_file {
Subroutine _fasta_file: called CC=3 SCAR=11.2
451 23 my ($sub, $hash, $filename, $order, $width) = @_;
452 23 ▶ 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}: $!") 23 0 23
453 23 ▶ _located(sub { _write_fasta($fh, $hash, $order, $width) });
Subroutine __ANON__: called CC=1 SCAR=0.0
454 13 ▶ close $fh or croak "$sub: can't write $filename: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't write ${filename}: $!") 13 0 13
455 13 $filename;
456 }
457  
458 # ---- sequences
459 #
460 # complement to motif_search work on a sequence held as a perl string, and
461 # fasta_index and fasta_region on a FASTA file. Each says which function of
462 # which library it follows, and t/seq.t, t/protein.t and t/faidx.t take their
463 # expected values from that library's own tests.
464  
465 # Dies, naming $sub, unless $seq is a sequence: a string, which may be empty.
466 538 ▶sub _sequence {
Subroutine _sequence: called CC=3 SCAR=11.0
467 538 my ($sub, $seq) = @_;
468 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
469 }
470  
471 # "type" of $sub's $args, which says what kind of sequence it was given, as the
472 # one of @$allowed ('DNA', 'RNA', 'protein') that it names in any case; DNA
473 # when it was not given.
474 168 ▶sub _seq_type {
Subroutine _seq_type: called CC=4 SCAR=13.9
475 168 my ($sub, $args, $allowed) = @_;
476 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
477 168 ▶ my ($found) = ref $type ? () : grep { lc $_ eq lc $type } @{ $allowed };
Branch: 1 branch
BranchTrueFalseTotal
ref $type ? : 1 167 168
478 168 ▶ return $found if defined $found;
Branch: 1 branch
BranchTrueFalseTotal
if defined $found 164 4 168
479 4 my @q = map { "\"$_\"" } @{ $allowed };
480 4 croak "$sub: \"type\" must be " . join(', ', @q[0 .. $#q - 1]) . " or $q[-1], not " . _what($type);
481 }
482  
483 # "strand" of $sub's $args as 'both', '+' or '-'; $default when it was not
484 # given.
485 58 ▶sub _strand {
Subroutine _strand: called CC=4 SCAR=14.0
486 58 my ($sub, $args, $default) = @_;
487 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
488 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
489 if ref $strand || $strand !~ /\A(?:\+|-|both)\z/;
490 56 $strand;
491 }
492  
493 # $seq with every nucleotide replaced by the one it pairs with, for $sub, which
494 # was given @opt. The pairs are Biopython 1.87's ambiguous_dna_complement and
495 # ambiguous_rna_complement (Bio/Data/IUPACData.py), in both cases, and U is
496 # read as T, as its Seq.complement() and Seq.complement_rna() read it. N and X
497 # pair with themselves, and so does every character that is not a nucleotide,
498 # a gap included.
499 113 ▶sub _complement {
Subroutine _complement: called CC=2 SCAR=6.9
500 113 my ($sub, $seq, @opt) = @_;
501 113 _sequence($sub, $seq);
502 109 my $type = _seq_type($sub, _args(\@opt, $sub, [], ['type']), ['DNA', 'RNA']);
503 101 my $c = "$seq";
504 101 ▶ if ($type eq 'RNA') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq 'RNA') { } 35 66 101
505 35 $c =~ tr/ACGTUMRWSYKVHDBacgtumrwsykvhdb/UGCAAKYWSRMBDHVugcaakywsrmbdhv/;
506 } else {
507 66 $c =~ tr/ACGTUMRWSYKVHDBacgtumrwsykvhdb/TGCAAKYWSRMBDHVtgcaakywsrmbdhv/;
508 }
509 101 $c;
510 }
511  
512 43 ▶sub complement { _complement('complement', @_) }
Subroutine complement: called CC=1 SCAR=0.0
Pod documented
513  
514 44 ▶sub reverse_complement { scalar reverse _complement('reverse_complement', @_) }
Subroutine reverse_complement: called CC=1 SCAR=0.0
Pod documented
515  
516 21 ▶sub transcribe {
Subroutine transcribe: called CC=2 SCAR=6.9
Pod documented
517 21 my ($seq, @rest) = @_;
518 21 ▶ croak 'transcribe: takes one argument, the sequence' if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 20 21
519 20 _sequence('transcribe', $seq);
520 18 (my $rna = "$seq") =~ tr/Tt/Uu/;
521 18 $rna;
522 }
523  
524 19 ▶sub back_transcribe {
Subroutine back_transcribe: called CC=2 SCAR=6.9
Pod documented
525 19 my ($seq, @rest) = @_;
526 19 ▶ croak 'back_transcribe: takes one argument, the sequence' if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 18 19
527 18 _sequence('back_transcribe', $seq);
528 16 (my $dna = "$seq") =~ tr/Uu/Tt/;
529 16 $dna;
530 }
531  
532 # NCBI's genetic codes, from share/genetic_codes.tsv, which
533 # share/make_genetic_codes.pl writes and whose header comment says where each
534 # column comes from. %Code is id => { id, names, aas, start_mask, stop_mask,
535 # both } and %Code_id is each lower-cased name => id; both are empty until the
536 # file has been read. The three 64-letter strings are what Bioinf.xs's
537 # _translate() takes, a letter for each codon from TTT to GGG:
538 #
539 # - aas: the codon's amino acid, or * for a stop.
540 # - start_mask: M for a codon that can start a protein, and A for any other.
541 # - stop_mask: * for a codon that can end one, and A for any other.
542 #
543 # "Translating" a codon with a mask says whether it is a start or a stop by the
544 # rules that translate it, so that an ambiguous codon is a start only when
545 # every codon it stands for is one. "both" lists, as [codon, amino acid], the
546 # codons that aas gives an amino acid and stop_mask a stop: the organism reads
547 # them either way.
548 36 my (%Code, %Code_id);
549  
550 # The 64 codons in the order of those strings.
551 36 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);
552  
553 # start_mask for ATG alone, which is codon 35: A is base 2 and G base 3 of
554 # T, C, A, G, so 16 * 2 + 4 * 0 + 3.
555 36 my $Atg_mask = ('A' x 35) . 'M' . ('A' x 28);
556  
557 # Reads the genetic codes into %Code and %Code_id, once, for $sub.
558 148 ▶sub _genetic_codes {
Subroutine _genetic_codes: called CC=16 SCAR=29.6
559 148 my ($sub) = @_;
560 148 ▶ return if %Code;
Branch: 1 branch
BranchTrueFalseTotal
if %Code 145 3 148
561 3 my $file = _share_file($sub, 'genetic_codes.tsv');
562 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
563 3 my (%code, %id);
564 3 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 87 3 90
565 87 $line =~ s/\r?\n\z//;
566 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
567 81 my ($id, $names, $aas, $starts) = split /\t/, $line, -1;
568 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
569 unless defined $starts && $id =~ /\A[1-9][0-9]*\z/ && length $names && $aas =~ /\A[A-Z*]{64}\z/ && $starts =~ /\A[M*-]{64}\z/;
570 81 (my $start_mask = $starts) =~ tr/M*-/MAA/;
571 81 (my $stop_mask = $starts) =~ tr/M*-/A*A/;
572 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
573 81 $code{$id} = { id => 0 + $id, names => [split /; /, $names], aas => $aas, start_mask => $start_mask, stop_mask => $stop_mask, both => \@both };
574 # A code is known by each of its names, and by each part of a name that
575 # lists several organisms, which is how Biopython's CodonTable.py
576 # registers them: "Bacterial, Archaeal and Plant Plastid" is also
577 # "Bacterial", "Archaeal" and "Plant Plastid".
578 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
579 }
580 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
581 3 ▶ croak "$sub: $file has no genetic codes" unless %code;
Branch: 1 branch
BranchTrueFalseTotal
unless %code 0 3 3
582 3 %Code = %code;
583 3 %Code_id = %id;
584 }
585  
586 # The genetic code that $table, "table" of $sub's arguments, names: one of
587 # %Code's values.
588 148 ▶sub _genetic_code {
Subroutine _genetic_code: called CC=5 SCAR=16.1
589 148 my ($sub, $table) = @_;
590 148 _genetic_codes($sub);
591 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
592 croak "$sub: \"table\" must be the number or the name of an NCBI genetic code, not " . _what($table)
593 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
594 139 $Code{$id};
595 }
596  
597 # Warns, for $sub, when $code has codons that are read as an amino acid or as
598 # a stop, since they are translated as the amino acid; with $to_stop it dies
599 # instead, as the protein's end could not be told. Biopython 1.87's
600 # _translate_str() (Bio/Seq.py) does both.
601 139 ▶sub _both_ways {
Subroutine _both_ways: called CC=4 SCAR=13.9
602 139 my ($sub, $code, $to_stop) = @_;
603 139 ▶ my @both = @{ $code->{both} } or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@both) = @{$code->{"both"};} or return 2 137 139
604 2 my $reads = "genetic code $code->{id} reads " . join(' and ', map { "$_->[0] as $_->[1] or as a stop" } @both);
605 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
606 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
607 }
608  
609 # $v, the option $k of $sub, as a single byte for Bioinf.xs, which takes the
610 # first byte of the string it is handed; dies unless it is one character below
611 # 256. undef is passed through.
612 253 ▶sub _one_char {
Subroutine _one_char: called CC=4 SCAR=13.9
613 253 my ($sub, $k, $v) = @_;
614 253 ▶ return $v unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 110 143 253
615 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
616 137 utf8::downgrade($v); # a character from 128 to 255 can be held as two bytes
617 137 $v;
618 }
619  
620 127 ▶sub translate {
Subroutine translate: called CC=12 SCAR=24.8
Pod documented
621 127 my ($seq, @opt) = @_;
622 127 my $sub = 'translate';
623 127 _sequence($sub, $seq);
624 125 my $args = _args(\@opt, $sub, [], [qw(cds gap stop_symbol table to_stop)]);
625 122 my %r; # the options, each resolved once
626 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
627 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
628 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
629 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
630 119 $r{gap} = _one_char($sub, 'gap', $args->{gap}); # the gap character; undef = a gap is not a codon
631 117 my $code = _genetic_code($sub, $r{table});
632 114 _both_ways($sub, $code, $r{to_stop});
633 113 my $len = length $seq;
634 113 ▶ if ($r{cds}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"cds"}) 8 105 113
635 # Biopython's checks, in its order
636 8 ▶ my ($first) = _located(sub { _translate(substr($seq, 0, 3), $code->{start_mask}, '*', 0, undef) });
Subroutine __ANON__: called CC=1 SCAR=0.0
637 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
638 unless $first eq 'M';
639 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
640 6 ▶ my ($last) = _located(sub { _translate(substr($seq, -3), $code->{stop_mask}, '*', 0, undef) });
Subroutine __ANON__: called CC=1 SCAR=0.0
641 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
642 unless $last eq '*';
643 # every codon but the last, up to the first stop, which there must not be
644 5 ▶ my ($p) = _located(sub { _translate(substr($seq, 0, $len - 3), $code->{aas}, '*', 1, $r{gap}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
645 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
646 . substr($seq, 3 * length $p, 3) . '", is one' if length($p) < $len / 3 - 1;
647 4 substr($p, 0, 1) = 'M'; # whatever the start codon stands for inside a protein
648 4 return $p;
649 }
650 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
651 . ' not translated' if $len % 3;
652 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
653 94 $p;
654 }
655  
656 17 ▶sub translate_six_frames {
Subroutine translate_six_frames: called CC=7 SCAR=19.5
Pod documented
657 17 my ($seq, @opt) = @_;
658 17 my $sub = 'translate_six_frames';
659 17 _sequence($sub, $seq);
660 15 my $args = _args(\@opt, $sub, [], [qw(stop_symbol table)]);
661 12 my %r; # the options, each resolved once
662 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
663 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
664 11 my $code = _genetic_code($sub, $r{table});
665 8 _both_ways($sub, $code, 0);
666 8 my %frame;
667 8 foreach my $strand (1, -1) {
668 15 ▶ my $nuc = $strand > 0 ? $seq : scalar reverse _complement($sub, $seq);
Branch: 1 branch
BranchTrueFalseTotal
$strand > 0 ? : 8 7 15
669 15 foreach my $f (0 .. 2) {
670 # a frame that starts beyond the sequence's end has no codons
671 ($frame{$strand * ($f + 1)}) = $f < length $nuc
672 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
673 }
674 }
675 7 \%frame;
676 }
677  
678 32 ▶sub find_orfs {
Subroutine find_orfs: called CC=27 SCAR=33.0
Pod documented
679 32 my ($seq, @opt) = @_;
680 32 my $sub = 'find_orfs';
681 32 _sequence($sub, $seq);
682 30 my $args = _args(\@opt, $sub, [], [qw(min_length start strand table)]);
683 27 my %r; # the options, each resolved once
684 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
685 # The fewest amino acids an open reading frame may have. 10 is the default
686 # of EMBOSS 6.6.0's getorf, whose -minsize is 30 nucleotides.
687 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
688 croak "$sub: \"min_length\" must be a whole number, 1 or more, not " . _what($r{min_length})
689 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
690 # Where a reading frame opens: 'any' = at the codon after a stop, or the
691 # first of the sequence; 'ATG' = at the first ATG after that; 'code' = at
692 # the first of the genetic code's start codons after that.
693 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
694 croak "$sub: \"start\" must be \"any\", \"ATG\" or \"code\", not " . _what($r{start})
695 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
696 21 $r{strand} = _strand($sub, $args, 'both'); # '+', '-' or 'both'
697 20 my $code = _genetic_code($sub, $r{table});
698 17 _both_ways($sub, $code, 0);
699 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
700 17 my $len = length $seq;
701 17 my @orf;
702 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
703 26 ▶ my $nuc = $strand > 0 ? $seq : scalar reverse _complement($sub, $seq);
Branch: 1 branch
BranchTrueFalseTotal
$strand > 0 ? : 16 10 26
704 26 foreach my $f (0 .. 2) {
705 76 ▶ next unless $f < $len;
Branch: 1 branch
BranchTrueFalseTotal
unless $f < $len 8 68 76
706 68 my $frame = substr $nuc, $f;
707 # the frame's codons as amino acids, and as M where one is a start
708 68 ▶ my ($protein) = _located(sub { _translate($frame, $code->{aas}, '*', 0, undef) });
Subroutine __ANON__: called CC=1 SCAR=0.0
709 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
710 67 my $codons = length $protein;
711 # $from and $stop count codons: the frame is open over $from .. $stop - 1
712 67 ▶ for (my $from = 0; $from < $codons;) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from < $codons) 3788 67 3855
713 3788 my $stop = index $protein, '*', $from;
714 3788 ▶ $stop = $codons if $stop < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $stop < 0 55 3733 3788
715 3788 my $next = $stop + 1;
716 3788 ▶ $from = index $starts, 'M', $from if defined $starts;
Branch: 1 branch
BranchTrueFalseTotal
if defined $starts 1897 1891 3788
717 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
718 139 my $p = substr $protein, $from, $stop - $from;
719 # a start codon stands for M at a protein's start, whatever
720 # it stands for inside one, as getorf's -methionine has it
721 139 ▶ substr($p, 0, 1) = 'M' if defined $starts;
Branch: 1 branch
BranchTrueFalseTotal
if defined $starts 57 82 139
722 # the first and last base, counted from 0 on this strand
723 139 my ($x, $y) = ($f + 3 * $from, $f + 3 * $stop - 1);
724 139 ▶ push @orf, {
Branch: 2 branches
BranchTrueFalseTotal
$strand > 0 ? : 66 73 139
$strand > 0 ? : 66 73 139
725 start => $strand > 0 ? $x + 1 : $len - $y, end => $strand > 0 ? $y + 1 : $len - $x,
726 strand => $strand, frame => $strand * ($f + 1), length => $stop - $from, protein => $p,
727 };
728 }
729 3788 $from = $next;
730 }
731 }
732 }
733 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
734 }
735  
736 35 ▶sub gc_content {
Subroutine gc_content: called CC=7 SCAR=19.5
Pod documented
737 35 my ($seq, @opt) = @_;
738 35 my $sub = 'gc_content';
739 35 _sequence($sub, $seq);
740 33 my $args = _args(\@opt, $sub, [], ['ambiguous']);
741 # What a letter other than A, C, G, T, U, S and W counts for: 'remove' =
742 # nothing, and it is left out of the length too; 'ignore' = nothing, but it
743 # is part of the length; 'weighted' = the share of the bases it stands for
744 # that are G or C.
745 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
746 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
747 if ref $ambiguous || $ambiguous !~ /\A(?:remove|ignore|weighted)\z/;
748 29 my $gc = ($seq =~ tr/CGScgs//);
749 29 ▶ my $len = $ambiguous eq 'remove' ? $gc + ($seq =~ tr/ATWUatwu//) : length $seq;
Branch: 1 branch
BranchTrueFalseTotal
$ambiguous eq 'remove' ? : 11 18 29
750 29 ▶ if ($ambiguous eq 'weighted') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ambiguous eq "weighted") 9 20 29
751 # Biopython 1.87's _gc_values (Bio/SeqUtils/__init__.py), added in the
752 # order its gc_fraction() adds them, B D H K M N R V X Y, so that the
753 # sum rounds as its sum does
754 9 $gc += ($seq =~ tr/Bb//) * (2 / 3); # C, G or T
755 9 $gc += ($seq =~ tr/Dd//) * (1 / 3); # A, G or T
756 9 $gc += ($seq =~ tr/Hh//) * (1 / 3); # A, C or T
757 9 $gc += ($seq =~ tr/Kk//) * 0.5; # G or T
758 9 $gc += ($seq =~ tr/Mm//) * 0.5; # A or C
759 9 $gc += ($seq =~ tr/Nn//) * 0.5; # any base
760 9 $gc += ($seq =~ tr/Rr//) * 0.5; # A or G
761 9 $gc += ($seq =~ tr/Vv//) * (2 / 3); # A, C or G
762 9 $gc += ($seq =~ tr/Xx//) * 0.5; # any base
763 9 $gc += ($seq =~ tr/Yy//) * 0.5; # C or T
764 }
765 29 ▶ $len ? $gc / $len : 0;
Branch: 1 branch
BranchTrueFalseTotal
$len ? : 26 3 29
766 }
767  
768 9 ▶sub assembly_stats {
Subroutine assembly_stats: called CC=18 SCAR=28.9
Pod documented
769 9 my ($seqs, @rest) = @_;
770 9 my $sub = 'assembly_stats';
771 9 ▶ croak "$sub: takes one argument, the sequences" if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 8 9
772 8 ▶ 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 5 8
Condition100%3/3
ref $seqs eq "HASH" or ref $seqs eq "ARRAY"
l!l&&r!l&&!r
233
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
773 unless ref $seqs eq 'HASH' || ref $seqs eq 'ARRAY';
774 5 my (@len, %nx, %lx);
775 5 my ($total, $n_count, $gaps) = (0, 0, 0);
776 5 ▶ foreach my $s (ref $seqs eq 'HASH' ? values %{ $seqs } : @{ $seqs }) {
Branch: 1 branch
BranchTrueFalseTotal
ref $seqs eq 'HASH' ? : 2 3 5
777 13 ▶ 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 11 13
Condition100%3/3
not defined $s or ref $s
l!l&&r!l&&!r
1111
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
778 11 push @len, length $s;
779 11 $total += length $s;
780 11 $n_count += ($s =~ tr/Nn//);
781 11 ▶ $gaps++ while $s =~ /[Nn]+/g;
Branch: 1 branch
BranchTrueFalseTotal
$s =~ /[Nn]+/g and do { ++$gaps } 4 11 15
782 }
783 3 @len = sort { $b <=> $a } @len;
784 # Nx is the length of the sequence at which the lengths, added from the
785 # longest down, first reach x% of their total, and Lx is how many
786 # sequences that took. The comparison is in whole numbers, 10 * the sum
787 # against the total * x / 10, where assembly-stats divides in floating point.
788 3 my ($sum, $tenth) = (0, 1); # $tenth = the x / 10 that has not been reached yet
789 3 foreach my $i (0 .. $#len) {
790 10 $sum += $len[$i];
791 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
792 20 $nx{10 * $tenth} = $len[$i];
793 20 $lx{10 * $tenth} = $i + 1;
794 20 $tenth++;
795 }
796 }
797 # no sequences, or none with any length: every Nx and Lx is 0
798 3 ▶ $nx{10 * $_} //= 0, $lx{10 * $_} //= 0 for 1 .. 10;
Condition100%4/4
$nx{10 * $_} //= 0
l!l
2010
$lx{10 * $_} //= 0
l!l
2010
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
799 {
800 number => scalar @len, total_length => $total, mean_length => @len ? $total / @len : 0,
801 longest => @len ? $len[0] : 0, shortest => @len ? $len[-1] : 0,
802 3 ▶ n_count => $n_count, gaps => $gaps, n50 => $nx{50}, l50 => $lx{50}, nx => \%nx, lx => \%lx,
Branch: 3 branches
BranchTrueFalseTotal
@len ? : 2 1 3
@len ? : 2 1 3
@len ? : 2 1 3
803 };
804 }
805  
806 38 ▶sub kmer_count {
Subroutine kmer_count: called CC=15 SCAR=27.1
Pod documented
807 38 my ($seq, $k, @opt) = @_;
808 38 my $sub = 'kmer_count';
809 38 _sequence($sub, $seq);
810 # 2147483647 is the longest key a perl hash takes, I32_MAX
811 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
812 if !defined $k || ref $k || $k !~ /\A[1-9][0-9]{0,9}\z/ || $k > 2147483647;
813 28 my $args = _args(\@opt, $sub, [], [qw(overlap relative)]);
814 25 my %r; # the options, each resolved once
815 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
816 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
817 25 ▶ my $step = $r{overlap} ? 1 : 0 + $k;
Branch: 1 branch
BranchTrueFalseTotal
$r{'overlap'} ? : 18 7 25
818 25 my $count;
819 # Bioinf.xs counts bytes. A string that perl holds as characters is handed
820 # over as bytes where it can be, and counted here where it cannot, which
821 # is when it has a character above 255.
822 25 my $bytes = $seq;
823 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
824 24 ▶ ($count) = _located(sub { _kmer_count($bytes, 0 + $k, $step) });
Subroutine __ANON__: called CC=1 SCAR=0.0
825 } else {
826 1 $count = {};
827 1 ▶ for (my $i = 0; $i + $k <= length $seq; $i += $step) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i + $k <= length $seq) 3 1 4
828 3 $count->{ substr $seq, $i, $k }++;
829 }
830 }
831 25 ▶ if ($r{relative}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"relative"}) 10 15 25
832 10 my $all = 0;
833 10 $all += $_ for values %{ $count };
834 10 $_ /= $all for values %{ $count };
835 }
836 25 $count;
837 }
838  
839 # The weight of each nucleotide, as its monophosphate, and of each amino acid,
840 # in daltons: "average" with every element at its standard atomic weight and
841 # "monoisotopic" with each at its commonest isotope. They are Biopython 1.87's
842 # unambiguous_dna_weights, unambiguous_rna_weights and protein_weights, and
843 # the monoisotopic_ table of each (Bio/Data/IUPACData.py), which that file
844 # introduces with "Mass data taken from PubChem". O is pyrrolysine and U
845 # selenocysteine. "water" is what one bond between two residues gives up, from
846 # molecular_weight() of Bio/SeqUtils/__init__.py.
847 36 my %Weight = (
848 average => {
849 DNA => { A => 331.2218, C => 307.1971, G => 347.2212, T => 322.2085 },
850 RNA => { A => 347.2212, C => 323.1965, G => 363.2206, U => 324.1813 },
851 protein => {
852 A => 89.0932, C => 121.1582, D => 133.1027, E => 147.1293, F => 165.1891, G => 75.0666, H => 155.1546,
853 I => 131.1729, K => 146.1876, L => 131.1729, M => 149.2113, N => 132.1179, O => 255.3134, P => 115.1305,
854 Q => 146.1445, R => 174.201, S => 105.0926, T => 119.1192, U => 168.0532, V => 117.1463, W => 204.2252,
855 Y => 181.1885,
856 },
857 water => 18.0153,
858 },
859 monoisotopic => {
860 DNA => { A => 331.06817, C => 307.056936, G => 347.063084, T => 322.056602 },
861 RNA => { A => 347.063084, C => 323.051851, G => 363.057999, U => 324.035867 },
862 protein => {
863 A => 89.047678, C => 121.019749, D => 133.037508, E => 147.053158, F => 165.078979, G => 75.032028,
864 H => 155.069477, I => 131.094629, K => 146.105528, L => 131.094629, M => 149.051049, N => 132.053492,
865 O => 255.158292, P => 115.063329, Q => 146.069142, R => 174.111676, S => 105.042593, T => 119.058243,
866 U => 168.964203, V => 117.078979, W => 204.089878, Y => 181.073893,
867 },
868 water => 18.010565,
869 },
870 );
871  
872 # A pattern for each capital letter, compiled once: perl 5.32 leaks a pattern
873 # that is compiled at run time, and molecular_weight would compile one for
874 # each letter on every call.
875 36 my %Letter_re = map { $_ => qr/$_/ } 'A' .. 'Z';
876  
877 32 ▶sub molecular_weight {
Subroutine molecular_weight: called CC=15 SCAR=27.1
Pod documented
878 32 my ($seq, @opt) = @_;
879 32 my $sub = 'molecular_weight';
880 32 _sequence($sub, $seq);
881 30 my $args = _args(\@opt, $sub, [], [qw(circular double_stranded monoisotopic type)]);
882 27 my %r; # the options, each resolved once
883 27 $r{type} = _seq_type($sub, $args, ['DNA', 'RNA', 'protein']);
884 26 ▶ $r{circular} = $args->{circular} ? 1 : 0; # 1 = the molecule has no ends
Branch: 1 branch
BranchTrueFalseTotal
$args->{'circular'} ? : 4 22 26
885 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
886 26 ▶ $r{monoisotopic} = $args->{monoisotopic} ? 1 : 0; # 1 = every atom its commonest isotope
Branch: 1 branch
BranchTrueFalseTotal
$args->{'monoisotopic'} ? : 5 21 26
887 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
888 25 ▶ my $table = $Weight{ $r{monoisotopic} ? 'monoisotopic' : 'average' };
Branch: 1 branch
BranchTrueFalseTotal
$r{'monoisotopic'} ? : 5 20 25
889 25 my $weight = $table->{ $r{type} };
890 # whitespace is dropped and case ignored, as Biopython does
891 25 (my $left = uc $seq) =~ s/\s+//g;
892 25 my $len = length $left;
893 25 ▶ croak "$sub: the sequence is empty" unless $len;
Branch: 1 branch
BranchTrueFalseTotal
unless $len 1 24 25
894 # Each letter is counted by taking it out, so that what is left when every
895 # letter of the table has gone is what the table has no weight for.
896 24 my %n;
897 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
898 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
899 if length $left;
900 # a chain of $len residues has $len - 1 bonds, and a ring has $len
901 21 my $bonds = ($len - 1 + $r{circular}) * $table->{water};
902 21 my $total = -$bonds;
903 21 $total += $n{$_} * $weight->{$_} for sort keys %{ $weight };
904 21 ▶ if ($r{double_stranded}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"double_stranded"}) 4 17 21
905 # the other strand has as many of a letter's partner as this has of it
906 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
907 4 $total -= $bonds;
908 4 $total += $n{$_} * $weight->{ $pair{$_} } for sort keys %{ $weight };
909 }
910 21 $total;
911 }
912  
913 # The pK of each group of a protein that takes or gives up a proton, for its
914 # charge at a pH. They are positive_pKs, negative_pKs, pKnterminal and
915 # pKcterminal of Biopython 1.87's Bio/SeqUtils/IsoelectricPoint.py, which
916 # takes them from Bjellqvist et al., Electrophoresis 14:1023-1031 (1993) and
917 # 15:529-539 (1994): the values ExPASy's Compute pI/Mw uses. "N" and "C" are
918 # the two ends of the chain, whose pK depends on the residue that is there:
919 # %Pk_n_end and %Pk_c_end give it for the residues that change it.
920 36 my @Pk_positive = (['N', 7.5], ['K', 10.0], ['R', 12.0], ['H', 5.98]);
921 36 my @Pk_negative = (['C_end', 3.55], ['D', 4.05], ['E', 4.45], ['C', 9.0], ['Y', 10.0]);
922 36 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);
923 36 my %Pk_c_end = (D => 4.55, E => 4.75);
924  
925 # How many of each charged group the protein $seq has, with the pK of each of
926 # its ends, for _charge(): [[count, pK], ...] for the groups that carry a
927 # positive charge when they hold a proton, and the same for those that carry a
928 # negative one when they have lost it. Dies, for $sub, when $seq is empty.
929 45 ▶sub _charged_groups {
Subroutine _charged_groups: called CC=6 SCAR=17.9
930 45 my ($sub, $seq) = @_;
931 45 _sequence($sub, $seq);
932 41 ▶ croak "$sub: the sequence is empty" unless length $seq;
Branch: 1 branch
BranchTrueFalseTotal
unless length $seq 2 39 41
933 39 my %n = (
934 N => 1, C_end => 1, # one of each end
935 K => ($seq =~ tr/Kk//), R => ($seq =~ tr/Rr//), H => ($seq =~ tr/Hh//),
936 D => ($seq =~ tr/Dd//), E => ($seq =~ tr/Ee//), C => ($seq =~ tr/Cc//), Y => ($seq =~ tr/Yy//),
937 );
938 39 my ($first, $last) = (uc substr($seq, 0, 1), uc substr($seq, -1));
939 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
940 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
941 39 (\@positive, \@negative);
942 }
943  
944 # The charge at $ph of a protein with _charged_groups()'s $positive and
945 # $negative: by the Henderson-Hasselbalch equation, a group of pK p holds its
946 # proton for 1 / (1 + 10 ** (pH - p)) of the time. The sums are made in
947 # Biopython's order, so that they round as its charge_at_pH() does.
948 225 ▶sub _charge {
Subroutine _charge: called CC=3 SCAR=11.0
949 225 my ($positive, $negative, $ph) = @_;
950 225 my ($plus, $minus) = (0, 0);
951 225 $plus += $_->[0] * (1 / (10 ** ($ph - $_->[1]) + 1)) for @{ $positive };
952 225 $minus += $_->[0] * (1 / (10 ** ($_->[1] - $ph) + 1)) for @{ $negative };
953 225 $plus - $minus;
954 }
955  
956 31 ▶sub protein_charge {
Subroutine protein_charge: called CC=7 SCAR=19.5
Pod documented
957 31 my ($seq, $ph, @rest) = @_;
958 31 my $sub = 'protein_charge';
959 31 ▶ croak "$sub: takes two arguments, the sequence and the pH" if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 30 31
960 30 my ($positive, $negative) = _charged_groups($sub, $seq);
961 27 require Scalar::Util;
962 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
963 if !defined $ph || ref $ph || !Scalar::Util::looks_like_number($ph) || $ph != $ph || $ph - $ph != 0;
964 21 _charge($positive, $negative, $ph);
965 }
966  
967 16 ▶sub isoelectric_point {
Subroutine isoelectric_point: called CC=4 SCAR=13.9
Pod documented
968 16 my ($seq, @rest) = @_;
969 16 my $sub = 'isoelectric_point';
970 16 ▶ croak "$sub: takes one argument, the sequence" if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 15 16
971 15 my ($positive, $negative) = _charged_groups($sub, $seq);
972 # Bisection, as IsoelectricPoint.pi() of Biopython 1.87 does it, from its
973 # own starting interval: 4.05 is below the pI of a protein that is all
974 # aspartate and 12 above that of one that is all arginine, and 7.775 is
975 # its first guess. It stops when the interval is 0.0001 wide or less,
976 # which is that function's limit, so the answer is good to 4 decimal
977 # places.
978 12 my ($ph, $low, $high) = (7.775, 4.05, 12);
979 12 ▶ while ($high - $low > 0.0001) {
Branch: 1 branch
BranchTrueFalseTotal
if ($high - $low > "0.0001") 204 12 216
980 204 ▶ if (_charge($positive, $negative, $ph) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (_charge($positive, $negative, $ph) > 0) { } 108 96 204
981 108 $low = $ph;
982 } else {
983 96 $high = $ph;
984 }
985 204 $ph = ($low + $high) / 2;
986 }
987 12 $ph;
988 }
989  
990 19 ▶sub subseq {
Subroutine subseq: called CC=9 SCAR=22.0
Pod documented
991 19 my ($seq, $start, $end, @rest) = @_;
992 19 my $sub = 'subseq';
993 19 ▶ croak "$sub: takes the sequence, where to start and where to end" if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 18 19
994 18 _sequence($sub, $seq);
995 16 my $len = length $seq;
996 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
997 16 foreach my $p (['start', $start], ['end', $end]) {
998 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
999 if !defined $p->[1] || ref $p->[1] || $p->[1] !~ /\A[1-9][0-9]*\z/;
1000 }
1001 9 ▶ croak "$sub: the start, $start, is after the end, $end" if $start > $end;
Branch: 1 branch
BranchTrueFalseTotal
if $start > $end 1 8 9
1002 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
1003 7 substr $seq, $start - 1, $end - $start + 1;
1004 }
1005  
1006 # ---- FASTA index
1007 #
1008 # The index is samtools's .fai: a line for each sequence, of its name, its
1009 # length, the byte in the file where it starts, how many bases each of its
1010 # lines holds, and how many bytes each takes with its line ending. What is and
1011 # is not a sequence that can be indexed is decided as fai_build_core() of
1012 # htslib 1.25's faidx.c decides it, and t/faidx.t checks the result against
1013 # that library's own expected index.
1014  
1015 # The index of the FASTA $file, read from the file itself, for $sub: an array
1016 # ref of [name, length, offset, line bases, line width] in the file's order.
1017 18 ▶sub _fai_scan {
Subroutine _fai_scan: called CC=19 SCAR=29.4
1018 18 my ($sub, $file) = @_;
1019 18 ▶ 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}: $!") 18 0 18
1020 18 my (@index, %seen);
1021 18 my ($name, $len, $offset, $bases, $width); # the sequence being read
1022 18 my $inside = 0; # 1 = its lines are being read; 0 = they have ended, and only a blank line or a defline may follow
1023 18 my $any = 0; # 1 = it has had a line, without which htslib does not count it as a sequence
1024 18 my $pos = 0; # bytes read
1025 25 ▶ my $add = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1026 25 ▶ if ($seen{$name}++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen{$name}++) { } 2 23 25
1027 2 carp "$sub: $file has more than one sequence named \"$name\", and the first is the one indexed";
1028 } else {
1029 23 push @index, [$name, $len, $offset, $bases, $width];
1030 }
1031 18 };
1032 18 local $/ = "\n";
1033 18 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 93 10 103
1034 93 $pos += length $line;
1035 93 ▶ if (substr($line, 0, 1) eq '>') {
Branch: 3 branches
BranchTrueFalseTotal
if (substr($line, 0, 1) eq '>') { } 33 60 93
elsif ($inside and $line eq "\n") { } 2 58 60
elsif (not $inside) { } 10 48 58
1036 33 ▶ $add->() if $any;
Branch: 1 branch
BranchTrueFalseTotal
if $any 19 14 33
1037 33 ▶ croak "$sub: the last sequence of $file has a defline and nothing more" unless $line =~ /\n\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\n\z/ 2 31 33
1038 # the name is the defline's first word, after any space that follows the ">"
1039 31 ($name) = $line =~ /\A>[^\S\n]*(\S*)/;
1040 31 ($len, $offset, $bases, $width, $inside, $any) = (0, $pos, 0, 0, 1, 0);
1041 ▶ } elsif ($inside && $line eq "\n") {
Condition100%3/3
$inside and $line eq "\n"
!ll&&!rl&&r
10482
MC/DC100%2/2
$inside and $line eq "\n"
$inside $line eq "\n"
Truth table100%3/3
A and B
A= $insideB= $line eq "\n"
ABresult
0X0
100
111
1042 2 $inside = 0;
1043 } elsif (!$inside) {
1044 10 ▶ next if $line eq "\n" || $line eq "\r\n";
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "\n" or $line eq "\r\n" 6 4 10
Condition100%3/3
$line eq "\n" or $line eq "\r\n"
l!l&&r!l&&!r
424
MC/DC100%2/2
$line eq "\n" or $line eq "\r\n"
$line eq "\n" $line eq "\r\n"
Truth table100%3/3
A or B
A= $line eq "\n"B= $line eq "\r\n"
ABresult
1X1
011
000
1045 4 ▶ croak "$sub: line $. of $file " . (defined $name
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 2 2 4
1046 ? "follows a shorter line of \"$name\", and only a sequence's last line can be shorter than its others"
1047 : "comes before any defline");
1048 } else {
1049 # htslib counts the line feed even of a last line that has none
1050 48 ▶ my $ll = length($line) + ($line =~ /\n\z/ ? 0 : 1);
Branch: 1 branch
BranchTrueFalseTotal
$line =~ /\n\z/ ? : 47 1 48
1051 48 my $cl = ($line =~ tr/\x21-\x7e//); # what C's isgraph() takes: the bases
1052 48 $any = 1;
1053 48 $len += $cl;
1054 48 ▶ if ($width == 0) {
Branch: 3 branches
BranchTrueFalseTotal
if ($width == 0) { } 29 19 48
elsif ($ll < $width) { } 10 9 19
elsif ($ll > $width) { } 2 7 9
1055 29 ($width, $bases) = ($ll, $cl);
1056 } elsif ($ll < $width) {
1057 10 $inside = 0;
1058 } elsif ($ll > $width) {
1059 2 croak "$sub: line $. of $file is longer than the lines before it of \"$name\", and only a sequence's last line can differ";
1060 }
1061 }
1062 }
1063 10 ▶ close $fh or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't read ${file}: $!") 10 0 10
1064 10 ▶ croak "$sub: " . (defined $name ? "the last sequence of $file has a defline and nothing more" : "$file has no sequences") unless $any;
Branch: 2 branches
BranchTrueFalseTotal
unless $any 4 6 10
defined $name ? : 2 2 4
1065 6 $add->();
1066 6 \@index;
1067 }
1068  
1069 # The index in the .fai file $fai, for $sub, as _fai_scan() returns one.
1070 3291 ▶sub _fai_read {
Subroutine _fai_read: called CC=7 SCAR=19.6
1071 3291 my ($sub, $fai) = @_;
1072 3291 ▶ open my $fh, '<', $fai or croak "$sub: can't read $fai: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $fai or croak("${sub}: can't read ${fai}: $!") 3291 0 3291
1073 3291 my @index;
1074 3291 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 19730 3290 23020
1075 19730 $line =~ s/\r?\n\z//;
1076 19730 my @f = split /\t/, $line, -1;
1077 # a FASTQ's index has a sixth column, where its qualities start
1078 croak "$sub: line $. of $fai 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"
1079 19730 ▶ 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 19729 19730
Condition66%2/3
@f == 5 and not grep({not /\A[0-9]+\z/;} @f[1..4])
!ll&&!rl&&r
1019729
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
1080 19729 push @index, [$f[0], map { 0 + $_ } @f[1 .. 4]];
1081 }
1082 3290 ▶ close $fh or croak "$sub: can't read $fai: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't read ${fai}: $!") 3290 0 3290
1083 3290 ▶ croak "$sub: $fai has no sequences" unless @index;
Branch: 1 branch
BranchTrueFalseTotal
unless @index 1 3289 3290
1084 3289 \@index;
1085 }
1086  
1087 # Dies, for $sub, unless $file is a FASTA that can be indexed: a file that is
1088 # there, and not gzip's, since a byte of it cannot be sought.
1089 3321 ▶sub _fai_file {
Subroutine _fai_file: called CC=7 SCAR=19.5
1090 3321 my ($sub, $file) = @_;
1091 3321 ▶ 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 3315 3321
Condition100%6/6
not defined $file or ref $file or $file eq ""
l!l&&r!l&&!r
423315
not defined $file or ref $file
l!l&&r!l&&!r
223317
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
1092 3315 ▶ 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 3314 3315
Condition66%2/3
-f $file and -r _
!ll&&!rl&&r
103314
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
1093 3314 ▶ 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 3312 3314
1094 }
1095  
1096 13 ▶sub fasta_index {
Subroutine fasta_index: called CC=6 SCAR=18.1
Pod documented
1097 13 my ($file, @rest) = @_;
1098 13 my $sub = 'fasta_index';
1099 13 ▶ croak "$sub: takes one argument, the FASTA file" if @rest;
Branch: 1 branch
BranchTrueFalseTotal
if @rest 1 12 13
1100 12 _fai_file($sub, $file);
1101 8 my $index = _fai_scan($sub, $file);
1102 2 my $fai = "$file.fai";
1103 2 ▶ 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}: $!") 2 0 2
1104 2 ▶ print {$fh} join("\t", @{ $_ }), "\n" or croak "$sub: can't write $fai: $!" for @{ $index };
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} join("\t", @{$_;}), "\n" or croak("${sub}: can't write ${fai}: $!") 7 0 7
1105 2 ▶ close $fh or croak "$sub: can't write $fai: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't write ${fai}: $!") 2 0 2
1106 2 _wrote($fai, 46); # cyan
1107 2 $fai;
1108 }
1109  
1110 3309 ▶sub fasta_region {
Subroutine fasta_region: called CC=36 SCAR=36.1
Pod documented
1111 3309 my ($file, @regions) = @_;
1112 3309 my $sub = 'fasta_region';
1113 3309 _fai_file($sub, $file);
1114 3304 ▶ croak "$sub: needs at least one region, such as \"chr1:100-200\"" unless @regions;
Branch: 1 branch
BranchTrueFalseTotal
unless @regions 1 3303 3304
1115 3303 foreach my $r (@regions) {
1116 3327 ▶ 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 3325 3327
Condition100%3/3
not defined $r or ref $r
l!l&&r!l&&!r
113325
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
1117 }
1118 3301 my $fai = "$file.fai";
1119 3301 my $index;
1120 3301 ▶ if (-f $fai) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $fai) { } 3291 10 3301
1121 3291 $index = _fai_read($sub, $fai);
1122 # as htslib warns; -M is the age in days, so the older file has the larger
1123 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
1124 } else {
1125 10 $index = _fai_scan($sub, $file);
1126 }
1127 3293 my %by;
1128 3293 ▶ $by{ $_->[0] } //= $_ for @{ $index };
Condition33%1/3
$by{$_->[0]} //= $_
l!l&&r!l&&!r
0197410
MC/DC0%0/2
$by{$_->[0]} //= $_
$by{$_->[0]} $_
Truth table33%1/3
A //= B
A= $by{$_->[0]}B= $_
ABresult
1X1
011
000
1129 3293 ▶ 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}: $!") 3293 0 3293
1130 3293 my %seq;
1131 3293 foreach my $region (@regions) {
1132 3316 ▶ next if exists $seq{$region};
Branch: 1 branch
BranchTrueFalseTotal
if exists $seq{$region} 1 3315 3316
1133 # A region that is a sequence's whole name is that sequence, even when
1134 # it could be read as a name and a range, which is how htslib's
1135 # hts_parse_region() reads "HLA-A*01:01:01:01".
1136 3315 my ($entry, $start, $end) = ($by{$region});
1137 # "name:start-end", "name:start", "name:start-" and "name:-end", with
1138 # commas allowed in the numbers
1139 3315 ▶ 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}) 3301 14 3315
Condition100%6/6
not $entry and $region =~ /\A(.*):([0-9,]*)(?:-([0-9,]*))?\z/s and $by{$1}
!ll&&!rl&&r
1313301
not $entry and $region =~ /\A(.*):([0-9,]*)(?:-([0-9,]*))?\z/s
!ll&&!rl&&r
1213302
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
1140 3301 ▶ my ($name, $from, $to) = ($1, $2, $3 // '');
Condition100%2/2
$3 // ""
l!l
32992
MC/DC100%1/1
$3 // ""
$3
Truth table100%2/2
A
A= $3
Aresult
11
00
1141 3301 tr/,//d for $from, $to;
1142 3301 ▶ ($entry, $start, $end) = ($by{$name}, $from, $to) if length "$from$to";
Branch: 1 branch
BranchTrueFalseTotal
if length "$from$to" 3301 0 3301
1143 }
1144 3315 ▶ 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 3313 3315
$region =~ /:/ ? : 1 1 2
1145 3313 my (undef, $len, $offset, $bases, $width) = @{ $entry };
1146 3313 ▶ $start = 1 unless defined $start && length $start;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $start and length $start 13 3300 3313
Condition100%3/3
defined $start and length $start
!ll&&!rl&&r
1213300
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
1147 3313 ▶ 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
1233298
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
1148 3313 ▶ 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 3312 3313
1149 3312 ▶ 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 3311 3312
Condition100%3/3
not $to_end and $end < $start
!ll&&!rl&&r
1532961
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
1150 # a range that runs past the sequence's end is cut short there, as
1151 # samtools faidx cuts it; one that starts past it is empty
1152 3311 ▶ $end = $len if $to_end || $end > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $to_end or $end > $len 18 3293 3311
Condition100%3/3
$to_end or $end > $len
l!l&&r!l&&!r
1533293
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
1153 3311 my $want = $end - $start + 1;
1154 3311 ▶ if ($want <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($want <= 0) 2 3309 3311
1155 2 $seq{$region} = '';
1156 2 next;
1157 }
1158 3309 ▶ 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 3309 3309
Condition33%1/3
$bases > 0 and $width >= $bases
!ll&&!rl&&r
003309
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
1159 3309 my $skip = $start - 1; # bases before the first one wanted
1160 3309 my $in_line = $skip % $bases; # those of them on its own line
1161 3309 my $from = $offset + ($skip - $in_line) / $bases * $width + $in_line;
1162 # the bases wanted and the line endings between them
1163 3309 my $bytes = $want + int(($in_line + $want - 1) / $bases) * ($width - $bases);
1164 3309 ▶ 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}: $!") 3309 0 3309
1165 3309 my $buffer = '';
1166 3309 my $got = read $fh, $buffer, $bytes;
1167 3309 ▶ croak "$sub: can't read $file: $!" unless defined $got;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $got 0 3309 3309
1168 3309 $buffer =~ tr/\x21-\x7e//cd;
1169 3309 ▶ 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 3308 3309
-f $fai ? : 1 0 1
1170 . (-f $fai ? "; $fai doesn't describe this file" : '') unless length($buffer) == $want;
1171 3308 $seq{$region} = $buffer;
1172 }
1173 3288 ▶ close $fh or croak "$sub: can't read $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croak("${sub}: can't read ${file}: $!") 3288 0 3288
1174 3288 \%seq;
1175 }
1176  
1177 # ---- motifs
1178  
1179 # What each letter of a motif matches, as the inside of a character class: the
1180 # bases an IUPAC nucleotide letter stands for (Biopython 1.87's
1181 # ambiguous_dna_values, Bio/Data/IUPACData.py, with U beside T so that a motif
1182 # written either way finds DNA and RNA alike), and the amino acids that B, Z
1183 # and J stand for (its extended_protein_values). X of a protein motif is any
1184 # one character, as it is when Bio::Tools::SeqPattern of BioPerl expands it.
1185 my %Motif_class = (
1186 nucleotide => {
1187 A => 'A', C => 'C', G => 'G', T => 'TU', U => 'TU', M => 'AC', R => 'AG', W => 'ATU', S => 'CG', Y => 'CTU',
1188 K => 'GTU', V => 'ACG', H => 'ACTU', D => 'AGTU', B => 'CGTU', N => 'ACGTU',
1189 },
1190 36 protein => { (map { $_ => $_ } split //, 'ACDEFGHIKLMNOPQRSTUVWY'), B => 'DN', Z => 'EQ', J => 'IL' },
1191 );
1192  
1193 # The compiled pattern of each motif that motif_search has been given: by
1194 # "type" and then the motif for a string of letters, and under "pattern" by its
1195 # own text for a qr//.
1196 36 my %Motif_re;
1197  
1198 43 ▶sub motif_search {
Subroutine motif_search: called CC=27 SCAR=33.0
Pod documented
1199 43 my ($seq, $motif, @opt) = @_;
1200 43 my $sub = 'motif_search';
1201 43 _sequence($sub, $seq);
1202 41 my $args = _args(\@opt, $sub, [], [qw(strand type)]);
1203 38 my %r; # the options, each resolved once
1204 38 $r{type} = _seq_type($sub, $args, ['DNA', 'RNA', 'protein']);
1205 37 $r{strand} = _strand($sub, $args, '+'); # '+', '-' or 'both'
1206 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
1207 # The motif as a pattern that matches without moving on, so that the next
1208 # search starts one letter along and hits that overlap are all found. It
1209 # is compiled once for each motif and kept in %Motif_re, since perl 5.32
1210 # leaks a pattern that is compiled at run time, and is used alone in the
1211 # match below.
1212 35 my $re;
1213 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
1214 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
1215 ▶ } 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
1216 12 $re = $Motif_re{ $r{type} }{$motif};
1217 } else {
1218 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
1219 if !defined $motif || ref $motif || $motif eq '';
1220 16 ▶ my $class = $Motif_class{ $r{type} eq 'protein' ? 'protein' : 'nucleotide' };
Branch: 1 branch
BranchTrueFalseTotal
$r{'type'} eq 'protein' ? : 3 13 16
1221 16 my $pattern = '';
1222 16 foreach my $letter (split //, uc $motif) {
1223 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
1224 1 $pattern .= '.';
1225 1 next;
1226 }
1227 croak "$sub: \"$letter\" of the motif \"$motif\" isn't a letter of $r{type}; a pattern is given as qr//"
1228 69 ▶ unless exists $class->{$letter};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $class->{$letter} 3 66 69
1229 66 ▶ $pattern .= length $class->{$letter} > 1 ? "[$class->{$letter}]" : $class->{$letter};
Branch: 1 branch
BranchTrueFalseTotal
length $class->{$letter} > 1 ? : 23 43 66
1230 }
1231 13 $re = $Motif_re{ $r{type} }{$motif} = qr/(?=($pattern))/is;
1232 }
1233 29 my $len = length $seq;
1234 29 my @hit;
1235 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
1236 33 ▶ my $text = $strand > 0 ? "$seq" : scalar reverse _complement($sub, $seq, type => $r{type});
Branch: 1 branch
BranchTrueFalseTotal
$strand > 0 ? : 24 9 33
1237 33 ▶ while ($text =~ /$re/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /$re/g) 191 33 224
1238 191 ▶ next unless $+[1] > $-[1]; # a pattern that can match nothing does, everywhere
Branch: 1 branch
BranchTrueFalseTotal
unless $+[1] > $-[1] 5 186 191
1239 186 ▶ push @hit, {
Branch: 2 branches
BranchTrueFalseTotal
$strand > 0 ? : 120 66 186
$strand > 0 ? : 120 66 186
1240 start => $strand > 0 ? $-[1] + 1 : $len - $+[1] + 1, end => $strand > 0 ? $+[1] : $len - $-[1],
1241 strand => $strand, match => $1,
1242 };
1243 }
1244 }
1245 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
1246 }
1247  
1248 # ---- BLAST
1249  
1250 25 ▶sub get_best_alignment_hit {
Subroutine get_best_alignment_hit: called CC=44 SCAR=38.4
Pod documented
1251 25 my ($json_file, $sort_criterion) = @_;
1252 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
1253 # For each query in one BLAST JSON file (-outfmt 15), that query's hits as
1254 # an array sorted best-first on $sort_criterion, one element per hit: the
1255 # hit's single best hsp plus the fields that say which subject it is.
1256 #
1257 # The hits are an array, not a hash on the hit title, because two hits can
1258 # share a title (one protein deposited under two accessions): in
1259 # identify.target/potato/new/f.sambunicum.json 76 hits carry 44 distinct
1260 # titles, and a hash kept 44.
1261 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
1262 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
1263 # Which way is better for each numeric hsp field: -1 = smaller, 1 = larger.
1264 # The other hsp keys (hseq, qseq, midline, num, *_from/*_to) are content
1265 # or position, not quality.
1266 23 my %better = (align_len => 1, bit_score => 1, evalue => -1, gaps => -1, identity => 1, positive => 1, score => 1);
1267 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
1268 // croak "get_best_alignment_hit: \"$sort_criterion\" isn't a sortable hsp field; use one of " . join(', ', sort keys %better);
1269 22 my $blast = _json_file('get_best_alignment_hit', $json_file);
1270 croak "get_best_alignment_hit: $json_file isn't a BLAST report in JSON (-outfmt 15): it has no \"BlastOutput2\" array"
1271 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
1272 18 my %alignments;
1273 18 foreach my $i (0 .. $#{ $blast->{BlastOutput2} }) {
1274 19 my $report = $blast->{BlastOutput2}[$i];
1275 my $search = ref $report eq 'HASH' && ref $report->{report} eq 'HASH' && ref $report->{report}{results} eq 'HASH'
1276 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
1277 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
1278 # BLAST titles a query by its defline, and a query with none by its
1279 # query_id alone.
1280 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
1281 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
1282 # Each hit's shape is checked before it is read. Up to 2026-11-10 "hits"
1283 # as an object died with perl's "Not an ARRAY reference", naming no
1284 # function, and an hsp with no bit_score, which BLAST always writes,
1285 # warned "uninitialized" each time it broke a tie; it now ties.
1286 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
1287 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
1288 unless ref $listed eq 'ARRAY';
1289 16 my @hits;
1290 16 foreach my $h (0 .. $#{ $listed }) {
1291 46 my $hit = $listed->[$h];
1292 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"
1293 unless ref $hit eq 'HASH' && ref($hit->{description} // []) eq 'ARRAY' && ref($hit->{hsps} // []) eq 'ARRAY'
1294 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
1295 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
1296 44 my $best; # undef until an hsp is seen; a hit with no hsps has nothing to record
1297 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
1298 croak "get_best_alignment_hit: an hsp of " . _what($first->{title}) . " in $json_file has no \"$sort_criterion\" to sort on"
1299 61 ▶ unless defined $hsp->{$sort_criterion};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hsp->{$sort_criterion} 0 61 61
1300 61 ▶ unless (defined $best) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $best) 44 17 61
1301 44 $best = $hsp;
1302 44 next;
1303 }
1304 17 my $cmp = $direction * ($hsp->{$sort_criterion} <=> $best->{$sort_criterion});
1305 # BLAST rounds any strong e-value to 0, so ties are the rule; the bit score breaks them
1306 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
1307 17 ▶ $best = $hsp if $cmp > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $cmp > 0 3 14 17
1308 }
1309 44 ▶ next unless defined $best;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $best 0 44 44
1310 # A shallow copy (an hsp holds only numbers and strings), so these
1311 # fields are not written into $blast. The hit's own "num" is not
1312 # merged, as it would shadow the hsp's; its "len" is the subject's
1313 # full length, so it arrives as "hit_len" beside the hsp's "align_len".
1314 # A hit has one description for each identical sequence in a
1315 # non-redundant database such as nr; it is named by the first, as
1316 # BLAST lists it, and every one is in "descriptions". Up to
1317 # 2026-10-17 a hit with more than one died.
1318 44 push @hits, { %{ $best },
1319 accession => $first->{accession},
1320 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
1321 hit_len => $hit->{len},
1322 id => $first->{id},
1323 title => $first->{title},
1324 44 };
1325 }
1326 # Indices are sorted so the last tiebreak can be BLAST's own order; the
1327 # array runs best-first, hence $b before $a.
1328 my @order = sort {
1329 14 ($direction * ($hits[$b]{$sort_criterion} <=> $hits[$a]{$sort_criterion}))
1330 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
1331 || ($a <=> $b)
1332 } 0 .. $#hits;
1333 # Two queries of one title would leave only the second's hits, so that
1334 # is refused rather than lost silently.
1335 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
1336 13 $alignments{$query} = [ @hits[@order] ];
1337 }
1338 12 \%alignments;
1339 }
1340  
1341 # ---- polygenic scores
1342  
1343 # The rows of $frame, given to $sub as $what, as an array ref of hash refs, in
1344 # whichever of Stats::LikeR's four shapes it comes: an array of hashes
1345 # (read_table's default), a hash of hashes (its default for a VCF), a hash of
1346 # arrays, or an array of arrays whose first row is the header. A row of an AoH or
1347 # HoH is the frame's own hash, and is only read; one of a HoA or AoA is made
1348 # here. With $labelled, also returns how a message names each row: "row 3",
1349 # counting data rows from 1, or 'row "key"' for a hash of hashes, whose rows are
1350 # then in key order so that the first bad one is always the same one.
1351 38 ▶sub _frame_rows {
Subroutine _frame_rows: called CC=22 SCAR=33.3
1352 38 my ($sub, $what, $frame, $labelled) = @_;
1353 38 my $shapes = 'an array of hashes or of arrays, or a hash of hashes or of arrays, as Stats::LikeR\'s read_table returns';
1354 38 my (@rows, @labels);
1355 38 ▶ if (ref $frame eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $frame eq 'ARRAY') { } 31 7 38
elsif (ref $frame eq 'HASH') { } 7 0 7
1356 31 ▶ croak "$sub: \"$what\" has no rows" unless @{ $frame };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$frame;} 1 30 31
1357 30 ▶ if (ref $frame->[0] eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $frame->[0] eq 'HASH') { } 27 3 30
elsif (ref $frame->[0] eq 'ARRAY') { } 2 1 3
1358 27 @rows = @{ $frame };
1359 } elsif (ref $frame->[0] eq 'ARRAY') {
1360 2 my ($head, @data) = @{ $frame };
1361 2 ▶ croak "$sub: \"$what\" has a header and no rows" unless @data;
Branch: 1 branch
BranchTrueFalseTotal
unless @data 1 1 2
1362 1 foreach my $i (0 .. $#data) {
1363 1 ▶ 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 0 1
1364 unless ref $data[$i] eq 'ARRAY';
1365 0 my %row;
1366 0 @row{ @{ $head } } = @{ $data[$i] };
1367 0 push @rows, \%row;
1368 }
1369 } else {
1370 1 croak "$sub: \"$what\" must be $shapes, not an array whose first row is " . _what($frame->[0]);
1371 }
1372 27 ▶ @labels = map { "row $_" } 1 .. @rows if $labelled;
Branch: 1 branch
BranchTrueFalseTotal
if $labelled 27 0 27
1373 } elsif (ref $frame eq 'HASH') {
1374 7 my ($key, $first) = each %{ $frame };
1375 7 keys %{ $frame }; # resets the iterator that each left part-way
1376 7 ▶ croak "$sub: \"$what\" has no rows" unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 1 6 7
1377 6 ▶ if (ref $first eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $first eq 'HASH') { } 4 2 6
elsif (ref $first eq 'ARRAY') { } 1 1 2
1378 4 ▶ if ($labelled) {
Branch: 1 branch
BranchTrueFalseTotal
if ($labelled) { } 1 3 4
1379 1 my @keys = sort keys %{ $frame };
1380 1 @rows = @{ $frame }{@keys};
1381 1 @labels = map { "row \"$_\"" } @keys;
1382 } else {
1383 3 @rows = values %{ $frame };
1384 }
1385 } elsif (ref $first eq 'ARRAY') {
1386 1 my @cols = keys %{ $frame };
1387 1 foreach my $c (@cols) {
1388 croak "$sub: column \"$c\" of \"$what\" must be an array ref, as \"$key\" is, not " . _what($frame->{$c})
1389 2 ▶ unless ref $frame->{$c} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $frame->{$c} eq "ARRAY" 1 1 2
1390 }
1391 0 foreach my $i (0 .. $#{ $first }) {
1392 0 push @rows, { map { $_ => $frame->{$_}[$i] } @cols };
1393 }
1394 0 ▶ croak "$sub: \"$what\" has no rows" unless @rows;
Branch: 1 branch
BranchTrueFalseTotal
unless @rows 0 0 0
1395 0 ▶ @labels = map { "row $_" } 1 .. @rows if $labelled;
Branch: 1 branch
BranchTrueFalseTotal
if $labelled 0 0 0
1396 } else {
1397 1 croak "$sub: \"$what\" must be $shapes, not a hash whose \"$key\" is " . _what($first);
1398 }
1399 } else {
1400 0 croak "$sub: \"$what\" must be $shapes, not " . _what($frame);
1401 }
1402 31 foreach my $i (0 .. $#rows) {
1403 39 ▶ 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 38 39
1404 }
1405 30 ▶ $labelled ? (\@rows, \@labels) : \@rows;
Branch: 1 branch
BranchTrueFalseTotal
$labelled ? : 27 3 30
1406 }
1407  
1408 # A chromosome's name as a VCF, PLINK 2 and a scoring file are compared on: in
1409 # upper case, without UCSC's "chr" prefix (GRCh37's own names, and the PGS
1410 # Catalog's, have none), with PLINK's numeric codes for the sex and
1411 # mitochondrial chromosomes and UCSC's "M" named as Ensembl names them, and with
1412 # X's pseudo-autosomal regions, which PLINK 2 names PAR1 and PAR2 (or XY, its
1413 # 25) once --split-par has split them off, taken as X.
1414 36 my %Chrom_alias = (23 => 'X', 24 => 'Y', 25 => 'X', 26 => 'MT', M => 'MT', PAR1 => 'X', PAR2 => 'X', XY => 'X');
1415 10 ▶sub _chrom {
Subroutine _chrom: called CC=2 SCAR=7.6
1416 10 my $c = uc $_[0];
1417 10 $c =~ s/\ACHR//;
1418 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
1419 }
1420  
1421 # A decimal number, as an effect_weight must be. Infinity and NaN, which
1422 # looks_like_number would take, are left out, as either would make every score
1423 # the same non-number.
1424 36 my $Number = qr/\A[-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][-+]?[0-9]+)?\z/;
1425  
1426 # The rows of the option $what ("weights" for pgs_score, "model" for
1427 # trait_predict) one at a time, each a hash ref with how a message names it,
1428 # and the column names: from a data frame (see _frame_rows), or read from a
1429 # tab-separated file a line at a time, so that a score of millions of variants
1430 # is never held whole. An empty field of a file is '', where read_table gives
1431 # undef; every check below treats the two alike.
1432 42 ▶sub _weight_rows {
Subroutine _weight_rows: called CC=12 SCAR=25.2
1433 42 my ($sub, $weights, $what) = @_;
1434 42 ▶ $what //= 'weights';
Condition100%2/2
$what //= "weights"
l!l
1527
MC/DC100%1/1
$what //= "weights"
$what
Truth table100%2/2
A
A= $what
Aresult
11
00
1435 42 ▶ if (ref $weights) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $weights) 33 9 42
1436 33 my ($rows, $labels) = _frame_rows($sub, $what, $weights, 1);
1437 27 my $i = 0;
1438 27 ▶ 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;} ? : 31 12 43
1439 }
1440 9 ▶ 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 7 9
Condition66%2/3
-f $weights and -r _
!ll&&!rl&&r
207
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
1441 7 my $fh;
1442 7 ▶ if ($weights =~ /\.gz\z/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weights =~ /\.gz\z/i) { } 0 7 7
1443 0 require IO::Uncompress::Gunzip;
1444 0 ▶ $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") 0 0 0
1445 or croak "$sub: can't read $weights: $IO::Uncompress::Gunzip::GunzipError";
1446 } else {
1447 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
1448 }
1449 7 my $head;
1450 7 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 53 1 54
1451 53 $line =~ s/\r?\n\z//;
1452 53 ▶ next if $line eq '' || $line =~ /\A#/;
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" or $line =~ /\A#/ 47 6 53
Condition66%2/3
$line eq "" or $line =~ /\A#/
l!l&&r!l&&!r
0476
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
1453 6 $head = $line;
1454 6 last;
1455 }
1456 7 ▶ croak "$sub: \"$what\" file $weights has no header line" unless defined $head;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $head 1 6 7
1457 6 my @cols = split /\t/, $head, -1;
1458 6 my $n = 0;
1459 36 ▶ my $next = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1460 36 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 31 5 36
1461 31 $line =~ s/\r?\n\z//;
1462 31 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 31 31
1463 31 my %row;
1464 31 @row{@cols} = split /\t/, $line, -1;
1465 31 return (\%row, 'row ' . ++$n);
1466 }
1467 5 return;
1468 6 };
1469 6 ($next, \@cols);
1470 }
1471  
1472 # The data frame $frame written to $file as a VCF of GT alone, for PLINK 2 to
1473 # read. Its rows are sorted by chromosome and position, as PLINK 2 needs them
1474 # to be, under the names _chrom gives the chromosomes, so that "chr1" and "1"
1475 # are one chromosome. A row with no CHROM, POS, REF or ALT is left out, and so
1476 # matches nothing, and a missing or empty GT is written "./.". Returns how many
1477 # rows were written.
1478 5 ▶sub _frame_vcf {
Subroutine _frame_vcf: called CC=21 SCAR=53.7
1479 5 my ($sub, $frame, $file, $match) = @_;
1480 5 my $rows = _frame_rows($sub, 'vcf', $frame);
1481 # read_table names each sample's genotype column "<sample>.GT" when it splits
1482 # the sample columns by FORMAT, as it does by default for a VCF
1483 3 ▶ my @samples = sort map { /\A(.+)\.GT\z/s ? $1 : () } keys %{ $rows->[0] };
Branch: 1 branch
BranchTrueFalseTotal
/\A(.+)\.GT\z/s ? : 2 13 15
1484 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
1485 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
1486 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
1487 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
1488 0 map { [_chrom($_->{CHROM}), $_->{POS}, $_] }
1489 grep { defined $_->{CHROM} && length $_->{CHROM} && defined $_->{POS} && $_->{POS} =~ /\A[1-9][0-9]*\z/
1490 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
1491 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
1492 0 print {$fh} "##fileformat=VCFv4.2\n##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">\n",
1493 join("\t", '#CHROM', qw(POS ID REF ALT QUAL FILTER INFO FORMAT), @samples), "\n";
1494 0 foreach my $k (@keep) {
1495 0 my $r = $k->[2];
1496 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
1497 0 print {$fh} join("\t", $k->[0], $k->[1], $id, $r->{REF}, $r->{ALT}, '.', '.', '.', 'GT',
1498 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
1499 }
1500 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
1501 0 scalar @keep;
1502 }
1503  
1504 # plink2 run with @args for $sub, its output in $dir/plink2.out rather than on
1505 # the caller's terminal; a failure dies with the lines of it that say why.
1506 1 ▶sub _plink2 {
Subroutine _plink2: called CC=12 SCAR=29.4
1507 1 my ($sub, $plink2, $dir, @args) = @_;
1508 1 my $log = File::Spec->catfile($dir, 'plink2.out');
1509 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
1510 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
1511 # Puts the caller's STDOUT and STDERR back, so that a failure to redirect
1512 # them does not leave the rest of the caller's output in the log.
1513 1 ▶ my $restore = sub {
Subroutine __ANON__: called CC=3 SCAR=12.0
1514 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
1515 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
1516 1 };
1517 1 ▶ unless (open STDOUT, '>', $log) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open STDOUT, ">", $log) 0 1 1
1518 0 my $why = "$!";
1519 0 $restore->();
1520 0 croak "_plink2: can't write $log: $why";
1521 }
1522 1 ▶ unless (open STDERR, '>&', \*STDOUT) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open STDERR, ">&", \*STDOUT) 0 1 1
1523 0 my $why = "$!";
1524 0 $restore->();
1525 0 croak "_plink2: can't send STDERR to $log: $why";
1526 }
1527 1 my $rc = system($plink2, @args);
1528 # taken before $restore's opens can set $! to their own errors
1529 1 my ($status, $errno) = ($?, "$!");
1530 1 $restore->();
1531 1 ▶ return if $rc == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $rc == 0 0 1 1
1532 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
1533 # what PLINK 2 says from its "Error:" on, or else its last line; it
1534 # rewrites its progress lines with a CR
1535 1 my @said;
1536 1 ▶ if (open my $fh, '<', $log) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, "<", $log) 1 0 1
1537 # less the "End time:" it ends every run with, which says nothing of why
1538 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
1539 }
1540 1 my ($first) = grep { $said[$_] =~ /\AError/ } 0 .. $#said;
1541 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
1542 1 croak "$sub: \"$plink2 @args\" failed ($why): $said";
1543 }
1544  
1545 39 ▶sub pgs_score {
Subroutine pgs_score: called CC=129 SCAR=84.2
Pod documented
1546 39 my $sub = 'pgs_score';
1547 39 my $args = _args(\@_, $sub, [qw(vcf weights)], [qw(build match memory threads)]);
1548 36 my %r;
1549 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
1550 croak "$sub: \"match\" must be \"position\" or \"id\", not " . _what($r{match})
1551 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
1552 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
1553 croak "$sub: \"build\" must be hg19, b37, hg38 or b38, not " . _what($r{build})
1554 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
1555 34 foreach my $k (qw(memory threads)) {
1556 # undef = PLINK 2's own default: half the machine's memory, every CPU
1557 croak "$sub: \"$k\" must be a whole number, 1 or more, not " . _what($args->{$k})
1558 67 ▶ 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/) 2 65 67
Condition83%5/6
defined $args->{$k} and ref $args->{$k} || !($args->{$k} =~ /\A[1-9][0-9]*\z/)
!ll&&!rl&&r
6412
ref $args->{$k} or not $args->{$k} =~ /\A[1-9][0-9]*\z/
l!l&&r!l&&!r
021
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
1559 65 $r{$k} = $args->{$k};
1560 }
1561 # PLINK 2 v2.0.0-a.7.13LM refuses less: "Invalid --memory argument '256' (minimum 640)"
1562 32 ▶ croak "$sub: \"memory\" must be 640 or more (MiB), the least PLINK 2 takes, not $r{memory}" if defined $r{memory} && $r{memory} < 640;
Branch: 1 branch
BranchTrueFalseTotal
if defined $r{"memory"} and $r{"memory"} < 640 1 31 32
Condition66%2/3
defined $r{"memory"} and $r{"memory"} < 640
!ll&&!rl&&r
3101
MC/DC50%1/2
defined $r{"memory"} and $r{"memory"} < 640
defined $r{"memory"} $r{"memory"} < 640
Truth table66%2/3
A and B
A= defined $r{"memory"}B= $r{"memory"} < 640
ABresult
0X0
100
111
1563 31 my $vcf = $args->{vcf};
1564 31 my @input; # plink2's arguments that read the genotypes; filled below
1565 31 ▶ if (!ref $vcf) {
Branch: 2 branches
BranchTrueFalseTotal
if (not ref $vcf) { } 3 28 31
elsif (ref $vcf ne 'ARRAY' and ref $vcf ne 'HASH') { } 1 27 28
1566 3 ▶ 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 _ 1 2 3
Condition66%2/3
-f $vcf and -r _
!ll&&!rl&&r
102
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
1567 2 ▶ if ($vcf =~ /\A(.*)\.pgen\z/is) {
Branch: 3 branches
BranchTrueFalseTotal
if ($vcf =~ /\A(.*)\.pgen\z/is) { } 1 1 2
elsif ($vcf =~ /\.bcf\z/i) { } 0 1 1
elsif ($vcf =~ /\.vcf(?:\.b?gz)?\z/i) { } 0 1 1
1568 1 my $prefix = $1;
1569 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
1570 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
1571 0 @input = ('--pfile', $prefix);
1572 } elsif ($vcf =~ /\.bcf\z/i) {
1573 0 @input = ('--bcf', $vcf);
1574 } elsif ($vcf =~ /\.vcf(?:\.b?gz)?\z/i) {
1575 0 @input = ('--vcf', $vcf);
1576 } else {
1577 1 croak "$sub: \"vcf\" file $vcf must end in .vcf, .vcf.gz, .vcf.bgz, .bcf or .pgen, as PLINK 2 reads it by its name";
1578 }
1579 ▶ } elsif (ref $vcf ne 'ARRAY' && ref $vcf ne 'HASH') {
Condition66%2/3
ref $vcf ne "ARRAY" and ref $vcf ne "HASH"
!ll&&!rl&&r
0271
MC/DC50%1/2
ref $vcf ne "ARRAY" and ref $vcf ne "HASH"
ref $vcf ne "ARRAY" ref $vcf ne "HASH"
Truth table66%2/3
A and B
A= ref $vcf ne "ARRAY"B= ref $vcf ne "HASH"
ABresult
0X0
100
111
1580 1 croak "$sub: \"vcf\" must be a VCF, BCF or PLINK 2 .pgen file, or a data frame, not " . _what($vcf);
1581 }
1582  
1583 27 my ($next, $cols) = _weight_rows($sub, $args->{weights});
1584 19 my %have = map { $_ => 1 } @{ $cols };
1585 # A harmonized (hmPOS) scoring file has its variants on the build its name
1586 # gives in the hm_ columns, and on the author's build in chr_name,
1587 # chr_position and rsID, so the hm_ columns are the ones read when present.
1588 my @key_cols = $r{match} eq 'id' ? ($have{hm_rsID} ? 'hm_rsID' : 'rsID')
1589 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
1590 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
1591 19 my @absent = grep { !$have{$_} } @key_cols, 'effect_allele', 'effect_weight';
1592 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
1593 . ', which a PGS Catalog scoring file has' if @absent;
1594 # Only an additive weight is a weight times the dosage. These columns of the
1595 # PGS Catalog's format 2.0 mark a variant that is scored some other way, which
1596 # this function would get wrong, so a variant marked so is refused.
1597 17 my @flags = grep { $have{$_} } qw(is_haplotype is_diplotype is_interaction is_dominant is_recessive);
1598 17 my @dosage_weights = grep { $have{$_} } qw(dosage_0_weight dosage_1_weight dosage_2_weight);
1599 # removed as pgs_score returns, or, after an error, as the program ends;
1600 # File::Temp's newdir, which would do both, is newer than 5.10.0's File::Temp
1601 17 require File::Temp;
1602 17 my $dir = File::Temp::tempdir(CLEANUP => 1);
1603 17 my $regions = File::Spec->catfile($dir, 'regions.txt');
1604 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
1605 # Each row of weights is kept as "effect\tother\tweight", the alleles in upper
1606 # case and the weight as written, which a few million rows can afford.
1607 17 my @variant;
1608 my %at; # key (CHROM:POS or rsID) => the rows of weights at it, joined by commas
1609 17 my %chroms; # chromosome, as _chrom names it => 1, for each of the rows' chromosomes
1610 17 ▶ while (my ($w, $label) = $next->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$next()) 18 7 25
1611 18 foreach my $c (@flags) {
1612 croak "$sub: $label of \"weights\" has $c \"$w->{$c}\", and only additive weights can be scored"
1613 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
1614 }
1615 16 foreach my $c (@dosage_weights) {
1616 croak "$sub: $label of \"weights\" has a $c, and only additive weights can be scored"
1617 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
1618 }
1619 15 my ($e, $o, $weight) = @{ $w }{qw(effect_allele other_allele effect_weight)};
1620 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
1621 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
1622 unless defined $weight && !ref $weight && $weight =~ $Number;
1623 10 my $i = @variant;
1624 10 ▶ push @variant, join "\t", uc $e, defined $o && length $o ? uc $o : '', $weight;
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
1625 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
1626 10 my $key;
1627 10 ▶ if ($r{match} eq 'id') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{'match'} eq 'id') { } 1 9 10
1628 1 $key = $w->{ $key_cols[0] };
1629 } else {
1630 9 my $pos = $w->{ $key_cols[1] };
1631 # A harmonized file leaves hm_chr and hm_pos empty for a variant it
1632 # could not place, and that variant is then not found, rather than an error.
1633 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
1634 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
1635 unless $pos =~ /\A[1-9][0-9]*\z/;
1636 7 $key = "$chr:$pos";
1637 # X's positions are given under PAR1 and PAR2 too, which --split-par
1638 # may have moved them to
1639 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
1640 }
1641 }
1642 8 ▶ $chroms{$chr} = 1 if defined $chr;
Branch: 1 branch
BranchTrueFalseTotal
if defined $chr 8 0 8
1643 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
1644 }
1645 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
1646 7 ▶ croak "$sub: \"weights\" has no rows" unless @variant;
Branch: 1 branch
BranchTrueFalseTotal
unless @variant 1 6 7
1647 6 my @sex = grep { $chroms{$_} } qw(X Y);
1648 croak "$sub: \"weights\" has variants on " . join(' and ', @sex) . ', which PLINK 2 reads only when "build" says where X\'s'
1649 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
1650 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
1651 0 ▶ @input = ('--vcf', File::Spec->catfile($dir, 'frame.vcf')) if ref $vcf;
Branch: 1 branch
BranchTrueFalseTotal
if ref $vcf 0 0 0
1652  
1653 0 my $plink2 = eval { _alien($sub)->plink2 };
1654 0 ▶ unless (defined $plink2) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $plink2) 0 0 0
1655 0 (my $why = $@) =~ s/ at \S+ line \d+\.?\n?\z//;
1656 0 croak "$sub: needs PLINK 2, which Alien::Bioinf installs, and hasn't here: $why";
1657 }
1658 0 ▶ my @common = ('--allow-extra-chr', (defined $r{memory} ? ('--memory', $r{memory}) : ()), (defined $r{threads} ? ('--threads', $r{threads}) : ()));
Branch: 2 branches
BranchTrueFalseTotal
defined $r{'memory'} ? : 0 0 0
defined $r{'threads'} ? : 0 0 0
1659 0 ▶ push @input, '--vcf-half-call', 'missing' unless $input[0] eq '--pfile';
Branch: 1 branch
BranchTrueFalseTotal
unless $input[0] eq "--pfile" 0 0 0
1660 # The samples, each of unknown sex, written by PLINK 2 without reading the
1661 # sex chromosomes, which it would refuse to without each one's sex.
1662 0 my $samples = File::Spec->catfile($dir, 'samples');
1663 0 my @psam = ('--not-chr', 'X,Y,XY', '--make-just-psam', '--out', $samples);
1664 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
1665 # PLINK 2 refuses a single-sample VCF with no 0/0 among its first 1,000
1666 # called genotypes, as one that lists only the sites where the sample
1667 # carries an ALT allele; scored, every other variant is missing.
1668 # die, not croak, which would give _plink2's message a second "at ... line"
1669 0 ▶ die $@ unless $@ =~ /contain at least one ALT allele/;
Branch: 1 branch
BranchTrueFalseTotal
unless $@ =~ /contain at least one ALT allele/ 0 0 0
1670 0 carp "$sub: \"vcf\" lists only the sites where its sample carries an ALT allele, so every variant where it matches"
1671 . ' the reference is missing, and its score is not comparable with one from a VCF of every site';
1672 0 push @input, '--vcf-allow-no-nonvar';
1673 0 _plink2($sub, $plink2, $dir, @input, @common, @psam);
1674 }
1675 0 my @import = (@input, @common);
1676 # Only the chromosomes the score uses are read, or, where it gives none
1677 # (matching by ID alone), all but the sex chromosomes, unless "build" says
1678 # where X's pseudo-autosomal regions are. PLINK 2 needs that, and each
1679 # sample's sex, before it reads X at all; the sex is given as unknown, which
1680 # counts a haploid call on X as homozygous.
1681 0 ▶ if (%chroms) {
Branch: 2 branches
BranchTrueFalseTotal
if (%chroms) { } 0 0 0
elsif (not defined $r{'build'}) { } 0 0 0
1682 0 ▶ push @import, '--chr', join ',', sort(keys %chroms), $chroms{X} ? qw(PAR1 PAR2) : ();
Branch: 1 branch
BranchTrueFalseTotal
$chroms{'X'} ? : 0 0 0
1683 } elsif (!defined $r{build}) {
1684 0 push @import, '--not-chr', 'X,Y,XY';
1685 }
1686 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
1687 0 ▶ push @import, '--extract', 'bed1', $regions if $r{match} eq 'position';
Branch: 1 branch
BranchTrueFalseTotal
if $r{"match"} eq "position" 0 0 0
1688 0 my $g = File::Spec->catfile($dir, 'g');
1689 # PLINK 2 exits 13 when none of the score's positions is in the VCF, and 7
1690 # when none of its chromosomes is (a VCF, filtered by --chr as it is
1691 # imported; a --pfile is filtered later, and exits 13). Either is a result
1692 # here: every variant is missing.
1693 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
1694 // ($@ =~ /\((?:exit 13\): Error: No variants remaining|exit 7\): Error: All \d+ variant\(s\) in --vcf file excluded by --chr)/ ? 1 : die $@);
1695  
1696 0 my @samples; # in PLINK 2's order
1697 0 ▶ open my $psam, '<', "$samples.psam" or croak "$sub: can't read $samples.psam: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $psam, "<", "$samples.psam" or croak("${sub}: can't read $samples.psam: $!") 0 0 0
1698 0 my $iid; # the column of the IID
1699 0 ▶ while (my $line = <$psam>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $psam)) 0 0 0
1700 0 chomp $line;
1701 0 my @f = split /\t/, $line;
1702 0 ▶ if ($line =~ /\A#/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\A#/) 0 0 0
1703 0 ($iid) = grep { $f[$_] =~ /\A#?IID\z/ } 0 .. $#f;
1704 0 next;
1705 }
1706 0 ▶ push @samples, $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
1707 }
1708 0 close $psam;
1709  
1710 # The .pvar a record at a time, matched against the rows of weights, and
1711 # written again with each record's ID made v1, v2, ..., which --score finds
1712 # it by, since a VCF's own IDs are often "." and need not be unique.
1713 0 my $found = ''; # bit $i set: row $i of weights is at a position (or ID) of the VCF
1714 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
1715 0 my ($in, $out);
1716 0 ▶ unless ($none) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($none) 0 0 0
1717 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
1718 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
1719 }
1720 0 my ($n, %col) = (0);
1721 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
1722 0 ▶ if ($line =~ /\A##/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\A##/) 0 0 0
1723 0 print {$out} $line;
1724 0 next;
1725 }
1726 0 chomp $line;
1727 0 my @f = split /\t/, $line, -1;
1728 0 ▶ if ($line =~ /\A#CHROM/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /\A#CHROM/) 0 0 0
1729 0 %col = map { $f[$_] => $_ } 0 .. $#f;
1730 0 print {$out} "$line\n";
1731 0 next;
1732 }
1733 0 $n++;
1734 0 my ($chrom, $pos, $id, $ref, $alt) = @f[ @col{'#CHROM', 'POS', 'ID', 'REF', 'ALT'} ];
1735 0 $f[ $col{ID} ] = "v$n";
1736 0 print {$out} join("\t", @f), "\n";
1737 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
1738 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
1739 0 ▶ next unless @here;
Branch: 1 branch
BranchTrueFalseTotal
unless @here 0 0 0
1740 # An ALT of "." is a site with no alternate allele, which a VCF of every
1741 # site writes where the sample matches the reference.
1742 0 ▶ my @alleles = ($ref, $alt eq '.' ? () : split /,/, $alt);
Branch: 1 branch
BranchTrueFalseTotal
$alt eq '.' ? : 0 0 0
1743 0 my %named; # allele in upper case => as the record writes it
1744 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
1745 0 my $sort = join ':', $chrom, $pos, $ref, $alt;
1746 0 foreach my $i (@here) {
1747 0 vec($found, $i, 1) = 1;
1748 0 my ($e, $o) = split /\t/, $variant[$i];
1749 # The alleles agree when both of the variant's are the record's, or,
1750 # for a record with no ALT, when either is its REF.
1751 next unless @alleles == 1
1752 ? $e eq uc $ref || (length $o && $o eq uc $ref)
1753 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
1754 # Of two records that agree, as a multi-allelic site split in two
1755 # can give, the first in CHROM:POS:REF:ALT order is used, so that the
1756 # order of the file does not decide it.
1757 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
1758 # An effect allele the record lacks (its REF being the other allele)
1759 # has no copies; it is given as the REF with a weight of 0, which
1760 # counts the sample's alleles there and adds nothing.
1761 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
1762 }
1763 }
1764 0 ▶ unless ($none) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($none) 0 0 0
1765 0 close $in;
1766 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
1767 }
1768  
1769 0 my %score = map { $_ => { alleles => 0, mismatched => 0, missing => 0, score => 0, variants => 0 } } @samples;
1770 0 my $agree = keys %use;
1771 0 my $disagree = unpack('%32b*', $found) - $agree;
1772 # --score takes one line for each record, so a record that two rows of
1773 # weights fall on is scored in a second pass, and so on.
1774 # Pass $p's score file and list of records are written as the rows are
1775 # read, rather than gathered first, so that a score of millions of variants
1776 # is not held twice.
1777 0 my %layer; # record => how many rows have taken it so far
1778 my @pass; # pass => [its file's prefix, score file handle, ID list handle]
1779 0 foreach my $i (sort { $a <=> $b } keys %use) {
1780 0 my ($rec, $a1, undef, $has) = split /\t/, $use{$i};
1781 0 my $p = $layer{$rec}++;
1782 0 ▶ unless ($pass[$p]) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pass[$p]) 0 0 0
1783 0 my $file = File::Spec->catfile($dir, "score$p");
1784 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
1785 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
1786 0 print {$fh} "ID\tA1\tWEIGHT\n";
1787 0 $pass[$p] = [$file, $fh, $ids];
1788 }
1789 0 ▶ print { $pass[$p][1] } "v$rec\t$a1\t", ($has ? (split /\t/, $variant[$i])[2] : 0), "\n";
Branch: 1 branch
BranchTrueFalseTotal
$has ? : 0 0 0
1790 0 print { $pass[$p][2] } "v$rec\n";
1791 }
1792 0 undef %layer;
1793 0 foreach my $pass (@pass) {
1794 0 my ($file, $fh, $ids) = @{ $pass };
1795 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
1796 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
1797 0 _plink2($sub, $plink2, $dir, '--pgen', "$g.pgen", '--pvar', "$g.ids.pvar", '--psam', "$g.psam", @common,
1798 '--extract', "$file.ids", '--score', "$file.txt", 1, 2, 3, 'header', 'no-mean-imputation', 'cols=+scoresums',
1799 '--missing', 'sample-only', '--out', $file);
1800 # .smiss's OBS_CT is how many genotypes there were to see, and
1801 # MISSING_CT how many of those were missing, so a sample's variants are
1802 # the one less the other.
1803 0 foreach my $part (['sscore', ALLELE_CT => ['alleles', 1], SCORE1_SUM => ['score', 1]],
1804 ['smiss', OBS_CT => ['variants', 1], MISSING_CT => ['variants', -1]]) {
1805 0 my ($ext, %field) = @{ $part };
1806 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
1807 0 chomp(my $head = <$res>);
1808 0 my @h = split /\t/, $head;
1809 0 my %at_col = map { $h[$_] => $_ } 0 .. $#h;
1810 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
1811 0 ▶ while (my $line = <$res>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $res)) 0 0 0
1812 0 chomp $line;
1813 0 my @f = split /\t/, $line;
1814 0 $score{ $f[$id_col] }{ $field{$_}[0] } += $field{$_}[1] * $f[ $at_col{$_} ] foreach keys %field;
1815 }
1816 0 close $res;
1817 }
1818 }
1819 0 foreach my $s (values %score) {
1820 0 $s->{missing} = @variant - $s->{variants};
1821 0 $s->{mismatched} = $disagree;
1822 0 ▶ $s->{average} = $s->{alleles} ? $s->{score} / $s->{alleles} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$s->{'alleles'} ? : 0 0 0
1823 }
1824 # On 2026-10-17, PGS000138 (whose header says genome_build=NR) against a
1825 # GRCh37 genome had 12,015 of its 22,274 variants at their positions, and
1826 # the alleles agreed at all 12,015; with every position moved on one base,
1827 # as a stand-in for the wrong build, they agreed at 9 of the 58 found.
1828 # Disagreement at more than half the variants found is the second case.
1829 0 ▶ if (!$agree) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $agree) { } 0 0 0
elsif ($disagree > $agree) { } 0 0 0
1830 carp "$sub: none of the " . scalar(@variant) . ' variants of "weights" was found in "vcf" with its alleles; check that the two'
1831 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
1832 } elsif ($disagree > $agree) {
1833 carp "$sub: the alleles disagree at $disagree of the " . ($agree + $disagree) . ' variants of "weights" found in "vcf"; check that'
1834 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
1835 }
1836 0 require File::Path;
1837 0 File::Path::rmtree($dir);
1838 0 \%score;
1839 }
1840  
1841 # ---- VCF genotypes: sex and parentage
1842  
1843 # The bytes sex_check and parent read at a time, from a file or through
1844 # IO::Uncompress, for Bioinf.xs to count. On 2026-10-18 sex_check read
1845 # a whole genome, genome.vcf.gz (155 MB, 3.5 million records), in 4.84 s with
1846 # blocks of 16 KiB, 64 KiB or 256 KiB, and 4.90 s and 4.86 s with 1 MiB and 4
1847 # MiB (best of three, peak RSS 47 MB each), so 64 KiB, as for FASTA. The time
1848 # is gzip's: the same file uncompressed (928 MB) took 0.26 s and 11 MB, and
1849 # zcat alone 3.7 s; as .vcf.bz2 it took 19.4 s, and bzip2 -dc alone 18.5 s.
1850 # IO::Uncompress::Gunzip's readline, which is perl, took 14.3 s just to read
1851 # the lines, and the read loop alone in 1 MiB blocks 5.7 s.
1852 36 my $Vcf_block = 1 << 16;
1853  
1854 # Dies unless the VCF $file, given to $sub as its option $key, is a readable
1855 # file with a VCF's name. Returns how it is compressed: 'gz', 'bz2', or '' for
1856 # not at all. Its messages are prefixed with $sub, whose argument the file is.
1857 970 ▶sub _vcf_check {
Subroutine _vcf_check: called CC=8 SCAR=20.8
1858 970 my ($sub, $key, $file) = @_;
1859 970 ▶ 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 7 963 970
Condition100%3/3
ref $file or not defined $file
l!l&&r!l&&!r
61963
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
1860 963 ▶ 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 _ 10 953 963
Condition66%2/3
-f $file and -r _
!ll&&!rl&&r
100953
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
1861 953 ▶ return 'gz' if $file =~ /\.vcf\.b?gz\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /\.vcf\.b?gz\z/i 16 937 953
1862 937 ▶ return 'bz2' if $file =~ /\.vcf\.bz2\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /\.vcf\.bz2\z/i 9 928 937
1863 928 ▶ return '' if $file =~ /\.vcf\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /\.vcf\z/i 921 7 928
1864 7 croak "$sub: \"$key\" file $file must end in .vcf, .vcf.gz, .vcf.bgz or .vcf.bz2";
1865 }
1866  
1867 # The VCF $file, given to $sub as its option $key, opened: returns a sub that
1868 # gives the next block of it and then undef, and a sub that closes it. Its
1869 # messages are prefixed with $sub, whose argument the file is.
1870 665 ▶sub _vcf_open {
Subroutine _vcf_open: called CC=8 SCAR=21.0
1871 665 my ($sub, $key, $file) = @_;
1872 665 my $packed = _vcf_check($sub, $key, $file);
1873 657 my ($fh, $error); # $error: what says why a read failed
1874 # Transparent => 0, or IO::Uncompress would pass a file that isn't compressed
1875 # through as it is, and the error would be that it isn't a VCF. For a file too
1876 # short to hold a header, new() gives undef and leaves the error empty in
1877 # IO::Uncompress::Gunzip 2.223 (perl 5.44.0), though 2.020 (perl 5.10.1) says
1878 # "Header Error: Minimum header size is 10 bytes".
1879 657 ▶ if ($packed eq 'gz') {
Branch: 2 branches
BranchTrueFalseTotal
if ($packed eq 'gz') { } 12 645 657
elsif ($packed eq 'bz2') { } 7 638 645
1880 12 require IO::Uncompress::Gunzip;
1881 12 ▶ $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")) 9 3 12
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
1882 or croak "$sub: can't read $file: " . ($IO::Uncompress::Gunzip::GunzipError || 'it isn\'t gzip-compressed');
1883 9 ▶ $error = sub { $IO::Uncompress::Gunzip::GunzipError };
Subroutine __ANON__: called CC=1 SCAR=0.0
1884 } elsif ($packed eq 'bz2') {
1885 7 require IO::Uncompress::Bunzip2;
1886 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
1887 or croak "$sub: can't read $file: " . ($IO::Uncompress::Bunzip2::Bunzip2Error || 'it isn\'t bzip2-compressed');
1888 6 ▶ $error = sub { $IO::Uncompress::Bunzip2::Bunzip2Error };
Subroutine __ANON__: called CC=1 SCAR=0.0
1889 } else {
1890 638 ▶ 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}: $!") 638 0 638
1891 0 ▶ $error = sub { "$!" };
Subroutine __ANON__: not called CC=1 SCAR=1.2
1892 }
1893 1250 ▶ my $next = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1894 1250 my $block;
1895 1250 my $n = read $fh, $block, $Vcf_block;
1896 # IO::Uncompress's read gives a negative number on an error, perl's undef
1897 1250 ▶ croak "$sub: can't read $file: " . $error->() if !defined $n || $n < 0;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $n or $n < 0 2 1248 1250
Condition66%2/3
not defined $n or $n < 0
l!l&&r!l&&!r
021248
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
1898 1248 ▶ $n ? $block : undef;
Branch: 1 branch
BranchTrueFalseTotal
$n ? : 836 412 1248
1899 653 };
1900 653 ▶ 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()) 557 0 557
1901 653 ($next, $close);
1902 }
1903  
1904 # The header of the VCF $file, given to $sub as its option $key, read as far as
1905 # its first line that does not start with "##": a hash ref whose "contig" is an
1906 # array ref of the ##contig lines' [ID, length, assembly], in the header's
1907 # order, and whose "reference" is the first ##reference line's value, or
1908 # undef. An ID loses its "chr" prefix, in any case, as Bioinf.xs's
1909 # conc_chrom() drops it from CHROM; a length or an assembly that the line
1910 # lacks is undef. Whatever is wrong with the file beyond its ## lines is left
1911 # for Bioinf.xs to find, as it reads it.
1912 167 ▶sub _vcf_meta {
Subroutine _vcf_meta: called CC=10 SCAR=23.1
1913 167 my ($sub, $key, $file) = @_;
1914 167 my ($next, $close) = _vcf_open($sub, $key, $file);
1915 166 my %meta = (contig => [], reference => undef);
1916 166 my $carry = ''; # the start of a line that the last block ended inside
1917 166 my $done = 0; # 1 = a line not starting with "##" has been read
1918 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
1919 168 $carry .= $block;
1920 168 my $end = rindex $carry, "\n";
1921 168 ▶ next if $end < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $end < 0 0 168 168
1922 168 foreach my $line (split /\n/, substr($carry, 0, $end)) {
1923 4471 $line =~ s/\r\z//;
1924 4471 ▶ if (substr($line, 0, 2) ne '##') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($line, 0, 2) ne "##") 165 4306 4471
1925 165 $done = 1;
1926 165 last;
1927 }
1928 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
1929 4099 my $attr = $1;
1930 4099 my ($id) = $attr =~ /(?:\A|,)ID=([^,]+)/;
1931 4099 ▶ next unless defined $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id 0 4099 4099
1932 4099 $id =~ s/\Achr(?=.)//i;
1933 4099 my ($length) = $attr =~ /(?:\A|,)length=([0-9]+)/;
1934 4099 my ($assembly) = $attr =~ /(?:\A|,)assembly="?([^,"]+)/;
1935 4099 push @{ $meta{contig} }, [$id, $length, $assembly];
1936 } elsif ($line =~ /\A##reference=(.+)\z/) {
1937 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
1938 }
1939 }
1940 168 $carry = substr($carry, $end + 1);
1941 }
1942 166 $close->();
1943 166 \%meta;
1944 }
1945  
1946 # Dies unless the VCFs $test and $truth, given to $sub, can be on one genome
1947 # build: every contig that both headers give a length for must have the same
1948 # length in each. A chromosome's length differs from one build to the next, and
1949 # so does a site's POS, so that two builds share few sites, and only by chance.
1950 # A header with no lengths cannot be checked, and is not. Contigs are matched by
1951 # name less "chr", as sites are, so hg19 and b37 (chr1 and 1, both 249,250,621
1952 # bases by the headers of an hg19 exome's VCF and of 1000 Genomes' hs37d5 BCF,
1953 # read 2026-10-20) pass.
1954 66 ▶sub _same_build {
Subroutine _same_build: called CC=18 SCAR=29.1
1955 66 my ($sub, $test, $truth) = @_;
1956 66 my %meta = (test => _vcf_meta($sub, 'test', $test), truth => _vcf_meta($sub, 'truth', $truth));
1957 65 my %truth_length; # contig => its length in the truth, for those that have one
1958 65 foreach my $c (@{ $meta{truth}{contig} }) {
1959 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
1960 }
1961 65 my ($shared, @differ) = (0); # @differ: [contig, test length, truth length], in the test's order
1962 65 my %seen;
1963 65 foreach my $c (@{ $meta{test}{contig} }) {
1964 14 my ($id, $length) = @{ $c };
1965 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
1966 12 $shared++;
1967 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
1968 }
1969 65 ▶ return unless @differ;
Branch: 1 branch
BranchTrueFalseTotal
unless @differ 61 4 65
1970 # what each header says its build is: the assembly of a ##contig line that
1971 # differs, or else its ##reference
1972 4 my %says;
1973 4 foreach my $key (qw(test truth)) {
1974 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
1975 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
1976 }
1977 4 my $listed = 3; # contigs named in the message; the rest are counted
1978 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
1979 croak "$sub: \"test\" $test and \"truth\" $truth are on different genome builds: their ##contig lines give " . join(', ', @named)
1980 . (@differ > $listed ? ', and ' . (@differ - $listed) . ' more' : '') . ' (' . scalar(@differ) . " of the $shared contigs that both give a length for differ)"
1981 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
1982 . ', so a POS in one is not the same place in the other. Lift one over to the other\'s build first';
1983 }
1984  
1985 # sex_check's report on $vcf: what was counted and the rule, then a table of
1986 # the samples in $order, the VCF's, each with its sex and the counts it was told
1987 # from. Columns are as wide as their widest entry, numbers right-aligned.
1988 21 ▶sub _sex_report {
Subroutine _sex_report: called CC=7 SCAR=19.5
1989 21 my ($vcf, $r, $tally, $order) = @_;
1990 21 my @head = ('sample', 'sex', 'het/hom-ALT', 'X het', 'X hom-ALT', 'X haploid', 'X missing', 'Y called');
1991 my @rows = map {
1992 74 my $s = $tally->{$_};
1993 [$_, $s->{sex} // 'unknown', defined $s->{het_ratio} ? sprintf('%.3f', $s->{het_ratio}) : '-',
1994 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
1995 21 } @{ $order };
1996 21 my @w = map { length $head[$_] } 0 .. $#head;
1997 21 foreach my $row (@rows) {
1998 74 foreach my $i (0 .. $#head) {
1999 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
2000 }
2001 }
2002 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
2003 21 my @unknown = grep { !defined $tally->{$_}{sex} } @{ $order };
2004 "sex_check: $vcf\n"
2005 . "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"
2006 21 ▶ . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows)
Branch: 1 branch
BranchTrueFalseTotal
@unknown ? : 20 1 21
2007 . (@unknown ? scalar(@unknown) . ' of ' . scalar(@rows) . " unknown: no het or hom-ALT call on X\n" : '');
2008 }
2009  
2010 # peddy 0.4.3's (sex_check() in peddy/peddy.py): male below a het to hom-ALT
2011 # ratio of 0.6 on non-PAR X. sex_check's default "cutoff", and what relatedness
2012 # tells sex by.
2013 36 my $Sex_cutoff = 0.6;
2014  
2015 # The het_ratio and sex of one sample's counts, $s, from Bioinf.xs's
2016 # sex_count(), set in $s: male when the ratio is below $cutoff. peddy divides
2017 # by a hom-ALT count of 0 as if it were 1, and so calls a sample with no calls
2018 # on X male; here it is undef, as is its sex.
2019 297 ▶sub _sex_of {
Subroutine _sex_of: called CC=5 SCAR=16.1
2020 297 my ($s, $cutoff) = @_;
2021 297 my $calls = $s->{x_het} + $s->{x_hom_alt};
2022 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
2023 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
2024 }
2025  
2026 72 ▶sub sex_check {
Subroutine sex_check: called CC=25 SCAR=32.2
Pod documented
2027 72 my $sub = 'sex_check';
2028 # sex_check($file) and sex_check($file, %options) take the file first; an
2029 # odd count whose first is an option's name is left for _args to refuse
2030 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
2031 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
2032 if @_ && defined $_[0] && !ref $_[0] && $_[0] ne 'vcf' && -f $_[0];
2033 71 my $args = _args(\@_, $sub, ['vcf'], [qw(cutoff min_depth report)]);
2034 65 my %r;
2035 # peddy 0.4.3's defaults (sex_check() in peddy/peddy.py): male below a het
2036 # to hom-ALT ratio of 0.6 on non-PAR X, and genotypes of depth 7 or more
2037 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
2038 croak "$sub: \"cutoff\" must be a number above 0, not " . _what($r{cutoff})
2039 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
2040 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
2041 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
2042 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
2043 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
2044 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
2045 58 my $vcf = $args->{vcf};
2046 58 my ($next, $close) = _vcf_open($sub, 'vcf', $vcf);
2047 50 ▶ my ($tally, $x_sites, $order) = _located(sub { _sex_tally($next, $vcf, $r{min_depth}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2048 30 $close->();
2049 30 _sex_of($_, $r{cutoff}) foreach values %{ $tally };
2050 30 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 21 9 30
2051 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
2052 }
2053 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
2054 30 $tally;
2055 }
2056  
2057 # KING's bounds on the kinship coefficient, from its manual
2058 # (www.kingrelatedness.com/manual.shtml, read 2026-10-18): above 0.354 the same
2059 # person or identical twins, and then first-, second- and third-degree
2060 # relatives down to 0.177, 0.0884 and 0.0442, below which a pair is unrelated.
2061 # They are 2^-1.5, 2^-2.5, 2^-3.5 and 2^-4.5, the geometric means of the
2062 # kinships of neighbouring degrees (1/2, 1/4, 1/8, 1/16, 1/32), and the
2063 # rounded values are used, as KING prints them.
2064 36 my @King = ([0.354, 'the same person or identical twins'], [0.177, 'first-degree relatives'],
2065 [0.0884, 'second-degree relatives'], [0.0442, 'third-degree relatives']);
2066  
2067 # The fewest sites parent will decide from. At the IBS0 rate of the unrelated
2068 # pair measured (0.081, in the README), 1,000 sites hold 81 IBS0 sites on
2069 # average, with a binomial standard deviation of 8.6, so that falling below
2070 # the 12 of the default max_ibs0 is 8 standard deviations away. An exome
2071 # gives about 150,000 and a genome 3 million, so only a small panel, or
2072 # files that hardly overlap, comes near it.
2073 36 my $Parent_sites = 1000;
2074  
2075 # Whether two people's own VCFs were probably not sequenced over the same
2076 # regions, which parent and relatedness warn of: of the sites compared, $sites,
2077 # one file has $more that the other lacks and the other $fewer that it lacks,
2078 # $more being the larger. Three things must hold.
2079 #
2080 # $more is over twice $fewer. Two VCFs of one pipeline have about as many each:
2081 # on 2026-10-18 the three pairs of one family's exomes had ratios of 1.13 at
2082 # most, where an exome of another capture kit had 3.0 to 13 against them, and a
2083 # genome against an exome 58, which is why 2.
2084 #
2085 # $more exceeds $fewer by $Region_excess sites, so that it is not chance. Were a
2086 # site in one file alone as likely to be in either, the chance of a ratio over
2087 # 2 with a difference of 50 or more is greatest at 99 against 49, where it is
2088 # 4.8e-5 (the exact binomial tail on both sides, computed 2026-11-10); a
2089 # difference of 30 would allow 1.8e-3.
2090 #
2091 # And by $Region_share of the sites compared, so that it could matter. Each of
2092 # those sites is taken as hom-REF in the file that lacks it, and at worst is an
2093 # opposite homozygote that was never sequenced, which adds that share to the
2094 # IBS0 rate. 0.009 is the smallest margin measured between a parent and
2095 # child's rate and max_ibs0's default: 0.012 less the 0.0030 of the comment in
2096 # parent. Fewer cannot carry such a pair over it.
2097 #
2098 # Up to 2026-11-10 the ratio was the whole test, so that two VCFs of 3,000
2099 # sites that differed by 3 sites against 1 were warned of.
2100 36 my $Region_excess = 50;
2101 36 my $Region_share = 0.009;
2102 78 ▶sub _regions_differ {
Subroutine _regions_differ: called CC=4 SCAR=13.9
2103 78 my ($more, $fewer, $sites) = @_;
2104 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
2105 }
2106  
2107 # The KING-robust between-family kinship (Manichaikul et al. 2010,
2108 # Bioinformatics 26:2867) of two samples with $het_a and $het_b het calls at the
2109 # sites compared, $het_het sites where both are het and $ibs0 opposite
2110 # homozygotes, in the form PLINK 2's --make-king-table gives it (t/parent.t's
2111 # header says how the two were found to agree); undef when either has no het
2112 # call.
2113 500 ▶sub _king {
Subroutine _king: called CC=3 SCAR=11.0
2114 500 my ($het_a, $het_b, $het_het, $ibs0) = @_;
2115 500 ▶ my $min_het = $het_a < $het_b ? $het_a : $het_b;
Branch: 1 branch
BranchTrueFalseTotal
$het_a < $het_b ? : 271 229 500
2116 500 ▶ return undef unless $min_het;
Branch: 1 branch
BranchTrueFalseTotal
unless $min_het 4 496 500
2117 496 0.5 - ($het_a + $het_b - 2 * $het_het + 4 * $ibs0) / (4 * $min_het);
2118 }
2119  
2120 # The relationship that a $kinship and an IBS0 rate say, by KING's ranges, with
2121 # an IBS0 rate below $max_ibs0 telling parent and child from full siblings.
2122 453 ▶sub _relationship {
Subroutine _relationship: called CC=6 SCAR=17.9
2123 453 my ($kinship, $ibs0_rate, $max_ibs0) = @_;
2124 453 my $band = (grep { $kinship > $King[$_][0] } 0 .. $#King)[0];
2125 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
2126 : $band == 1 ? ($ibs0_rate < $max_ibs0 ? 'parent-child' : 'full siblings')
2127 : $band == 2 ? 'second-degree' : 'third-degree';
2128 }
2129  
2130 # parent's report, given its sample or file names, the resolved options, and
2131 # its result.
2132 26 ▶sub _parent_report {
Subroutine _parent_report: called CC=12 SCAR=24.8
2133 26 my ($child, $parent, $vcf, $r, $s) = @_;
2134 26 my $kin = sprintf '%.4f', $s->{kinship};
2135 26 my $rate = sprintf '%.4f', $s->{ibs0_rate};
2136 26 my $band = (grep { $s->{kinship} > $King[$_][0] } 0 .. $#King)[0];
2137 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
2138 : $band == 0 ? "kinship $kin is above 0.354, as for $King[0][1]"
2139 : "kinship $kin is from $King[$band][0] to $King[$band - 1][0], as for $King[$band][1]";
2140 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
2141 26 ▶ my $verdict = $s->{parent} ? "parent and child (1): $ibs0_says, and $kin_says"
Branch: 1 branch
BranchTrueFalseTotal
$s->{'parent'} ? : 14 12 26
2142 : "not parent and child (0): $kin_says, and $ibs0_says";
2143 26 ▶ $verdict .= ', so full siblings' if $s->{relationship} eq 'full siblings';
Branch: 1 branch
BranchTrueFalseTotal
if $s->{"relationship"} eq "full siblings" 4 22 26
2144 26 my @rows = (["sites compared", $s->{sites}, "autosomal biallelic SNVs where either carries the ALT, DP $r->{min_depth} or more"]);
2145 push @rows, ([' in both VCFs', $s->{in_both}, ''], [" in the child's alone", $s->{child_only}, 'the parent taken as hom-REF'],
2146 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
2147 push @rows, (['IBS0', $s->{ibs0}, 'opposite homozygotes'],
2148 [' 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'],
2149 ['IBS1', $s->{ibs1}, 'one allele shared'], ['IBS2', $s->{ibs2}, 'both alleles shared'],
2150 ['het in both', $s->{het_het}, ''], ['het', $s->{child_het}, "the child's, and $s->{parent_het} the parent's"],
2151 26 ['hom-ALT', $s->{child_hom_alt}, "the child's, and $s->{parent_hom_alt} the parent's"],
2152 ['kinship', $kin, 'KING-robust, between-family']);
2153 26 my ($w0, $w1) = (0, 0);
2154 26 foreach my $row (@rows) {
2155 281 ▶ $w0 = length $row->[0] if length $row->[0] > $w0;
Branch: 1 branch
BranchTrueFalseTotal
if length $row->[0] > $w0 59 222 281
2156 281 ▶ $w1 = length $row->[1] if length $row->[1] > $w1;
Branch: 1 branch
BranchTrueFalseTotal
if length $row->[1] > $w1 52 229 281
2157 }
2158 "parent: child " . (defined $vcf ? "$child, parent $parent, in $vcf" : "$child, parent $parent") . "\n"
2159 . "$verdict\n"
2160 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
2161 }
2162  
2163 99 ▶sub parent {
Subroutine parent: called CC=34 SCAR=35.4
Pod documented
2164 99 my $sub = 'parent';
2165 99 my $args = _args(\@_, $sub, [qw(child parent)], [qw(vcf min_depth max_ibs0 report)]);
2166 96 my %r;
2167 # Measured on three exomes of one family on 2026-10-18 (README.md): with
2168 # every genotype counted the two parent-child pairs had IBS0 rates of 0.254
2169 # and 0.215, from off-target calls of DP 1 to 3, and with DP 10 or more
2170 # 0.0030 and 0.0020, against 0.081 for the unrelated pair; DP 7 gave 0.0053
2171 # and 0.0037, half the margin below max_ibs0, for 8% more sites.
2172 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
2173 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
2174 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
2175 # peddy 0.4.3's (ped_check() in peddy/peddy.py: predicted_parents is
2176 # ibs0 / n < 0.012), where it sits between the measured parent-child rates
2177 # above and the 0.02 or so expected of full siblings, who share no allele
2178 # by descent at a quarter of sites and so have a quarter of the unrelated
2179 # pair's 0.081
2180 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
2181 croak "$sub: \"max_ibs0\" must be a number above 0, not " . _what($r{max_ibs0})
2182 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
2183 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
2184 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
2185 92 my ($child, $parent, $vcf) = @{ $args }{qw(child parent vcf)}; # $vcf: undef = child and parent are each a VCF of its own
2186 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
2187 92 ▶ if (defined $vcf) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $vcf) { } 61 31 92
2188 61 foreach my $key (qw(child parent)) {
2189 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
2190 }
2191 59 ▶ croak "$sub: \"child\" and \"parent\" are both \"$child\"" if $child eq $parent;
Branch: 1 branch
BranchTrueFalseTotal
if $child eq $parent 1 58 59
2192 58 my ($next, $close) = _vcf_open($sub, 'vcf', $vcf);
2193 58 ▶ @t = _located(sub { _parent_one($next, $vcf, $r{min_depth}, $child, $parent) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2194 56 $close->();
2195 } else {
2196 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
2197 30 my ($child_next, $child_close) = _vcf_open($sub, 'child', $child);
2198 30 my ($parent_next, $parent_close) = _vcf_open($sub, 'parent', $parent);
2199 27 ▶ @t = _located(sub { _parent_own($child_next, $child, $parent_next, $parent, $r{min_depth}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2200 19 $child_close->();
2201 19 $parent_close->();
2202 }
2203 75 my %s;
2204 75 @s{qw(in_both child_only parent_only)} = @t[9 .. 11];
2205 75 $s{sites} = $s{in_both} + $s{child_only} + $s{parent_only};
2206 75 @s{qw(child_ref_parent_alt child_alt_parent_ref)} = @t[2, 6];
2207 75 $s{ibs0} = $t[2] + $t[6];
2208 75 $s{ibs1} = $t[1] + $t[3] + $t[5] + $t[7];
2209 75 $s{ibs2} = $t[4] + $t[8];
2210 75 $s{het_het} = $t[4];
2211 75 $s{child_het} = $t[3] + $t[4] + $t[5];
2212 75 $s{parent_het} = $t[1] + $t[4] + $t[7];
2213 75 $s{child_hom_alt} = $t[6] + $t[7] + $t[8];
2214 75 $s{parent_hom_alt} = $t[2] + $t[5] + $t[8];
2215 75 ▶ my $what = defined $vcf ? "\"$child\" and \"$parent\" of $vcf" : "$child and $parent";
Branch: 1 branch
BranchTrueFalseTotal
defined $vcf ? : 56 19 75
2216 # Without a hom-REF call, IBS0 cannot be seen, and an unrelated pair would
2217 # look like parent and child. A VCF merged from VCFs that list only their own
2218 # sample's variant sites is like that, as bcftools merge writes it without
2219 # -0: each sample is "./." wherever it had no variant. It is checked before
2220 # the number of sites, which such a VCF often has too few of as well, since
2221 # this says what to do about it.
2222 croak "$sub: neither of $what has a hom-REF call where the other carries the ALT, so no opposite homozygote can be seen;"
2223 . ' 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"'
2224 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
2225 croak "$sub: $what have only $s{sites} autosomal biallelic SNVs of DP $r{min_depth} or more where either carries the ALT,"
2226 . " and $Parent_sites are needed" . (defined $vcf ? '' : '; if the files share few sites, check that they are of the same genome build')
2227 74 ▶ if $s{sites} < $Parent_sites;
Branch: 2 branches
BranchTrueFalseTotal
if $s{"sites"} < $Parent_sites 3 71 74
defined $vcf ? : 2 1 3
2228 71 $s{kinship} = _king(@s{qw(child_het parent_het het_het ibs0)});
2229 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
2230 70 $s{ibs0_rate} = $s{ibs0} / $s{sites};
2231 70 $s{relationship} = _relationship($s{kinship}, $s{ibs0_rate}, $r{max_ibs0});
2232 70 ▶ $s{parent} = $s{relationship} eq 'parent-child' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$s{'relationship'} eq 'parent-child' ? : 36 34 70
2233 70 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 26 44 70
2234 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
2235 }
2236 # _regions_differ's comment says what is tested, and why
2237 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
2238 70 my ($n_more, $n_fewer) = @s{"${more}_only", "${fewer}_only"};
2239 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,"
2240 . ' so the two were probably not sequenced over the same regions (an exome and a genome, or two capture kits);'
2241 . ' a site that one lacks is taken as hom-REF in it, so IBS0 and the kinship are not to be trusted'
2242 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
2243 70 ▶ wantarray ? ($s{parent}, \%s) : $s{parent};
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 55 15 70
2244 }
2245  
2246 # The words for a male and a female relative, in relatedness's categories:
2247 # the parent, the child, the sibling.
2248 36 my %Kin_word = (male => [qw(father son brother)], female => [qw(mother daughter sister)]);
2249  
2250 # relatedness's report, given its files, the resolved options, the samples in
2251 # order, each one's sex counts, and $each_pair, which gives each pair in order
2252 # to a sub. Columns are as wide as their widest entry, numbers right-aligned.
2253 # The pairs' rows are made twice, once for the widths and once for the lines,
2254 # rather than held: 1,000 samples have 499,500.
2255 4 ▶sub _relatedness_report {
Subroutine _relatedness_report: called CC=2 SCAR=6.9
2256 4 my ($files, $r, $names, $tally, $each_pair) = @_;
2257 # the lines of the rows that $rows gives to a sub, under @head, with the
2258 # columns in %$right right-aligned
2259 8 ▶ my $table = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2260 8 my ($right, $rows, @head) = @_;
2261 8 my @w = map { length } @head;
2262 76 ▶ $rows->(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2263 76 foreach my $i (0 .. $#_) {
2264 398 ▶ $w[$i] = length $_[$i] if length $_[$i] > $w[$i];
Branch: 1 branch
BranchTrueFalseTotal
if length $_[$i] > $w[$i] 15 383 398
2265 }
2266 8 });
2267 8 my $text = '';
2268 84 ▶ my $line = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2269 84 ▶ (my $l = join ' ', map { $right->{$_} ? sprintf('%*s', $w[$_], $_[$_]) : sprintf('%-*s', $w[$_], $_[$_]) } 0 .. $#_) =~ s/ +\z//;
Branch: 1 branch
BranchTrueFalseTotal
$right->{$_} ? : 200 236 436
2270 84 $text .= "$l\n";
2271 8 };
2272 8 $line->(@head);
2273 8 $rows->($line);
2274 8 $text;
2275 4 };
2276 4 my $several = @{ $files } > 1;
2277 8 ▶ my $samples = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
2278 8 my ($row) = @_;
2279 8 foreach my $x (@{ $names }) {
2280 44 my $s = $tally->{$x};
2281 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
2282 }
2283 4 };
2284 8 ▶ my $pairs = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2285 8 my ($row) = @_;
2286 108 ▶ $each_pair->(sub {
Subroutine __ANON__: called CC=5 SCAR=16.5
2287 108 my ($x, $y, $s) = @_;
2288 $row->($x, $y, $s->{sites}, defined $s->{ibs0_rate} ? sprintf('%.4f', $s->{ibs0_rate}) : '-', defined $s->{kinship} ? sprintf('%.4f', $s->{kinship}) : '-',
2289 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
2290 8 });
2291 4 };
2292 4 ▶ 'relatedness: ' . join(', ', @{ $files }) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
$several ? : 2 2 4
2293 . "KING-robust kinship over autosomal biallelic SNVs where either carries the ALT, genotypes of DP below $r->{min_depth} not counted;"
2294 . " first-degree from 0.177 to 0.354, and of those, parent and child when the IBS0 rate is below $r->{max_ibs0};"
2295 . " male when het/hom-ALT on X outside its pseudo-autosomal regions is below $Sex_cutoff\n"
2296 . $table->({ 2 => 1 }, $samples, 'sample', 'sex', 'X het/hom-ALT', $several ? 'VCF' : ())
2297 . $table->({ 2 => 1, 3 => 1, 4 => 1 }, $pairs, 'sample', 'sample', 'sites', 'IBS0 rate', 'kinship', 'relationship');
2298 }
2299  
2300 72 ▶sub relatedness {
Subroutine relatedness: called CC=44 SCAR=37.9
Pod documented
2301 72 my $sub = 'relatedness';
2302 # relatedness($file, ...) takes the VCFs first, unnamed, up to the first word:
2303 # a VCF's name has a dot, as its suffix must, and an option's name, or a
2304 # misspelling of one, has none
2305 72 my @vcf;
2306 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
2307 72 my $args = _args(\@_, $sub, [], [qw(vcf min_depth max_ibs0 report)]);
2308 69 ▶ if (defined $args->{vcf}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{"vcf"}) 8 61 69
2309 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
2310 7 ▶ @vcf = ref $args->{vcf} eq 'ARRAY' ? @{ $args->{vcf} } : $args->{vcf};
Branch: 1 branch
BranchTrueFalseTotal
ref $args->{'vcf'} eq 'ARRAY' ? : 5 2 7
2311 }
2312 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
2313 65 my %r;
2314 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
2315 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
2316 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
2317 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
2318 croak "$sub: \"max_ibs0\" must be a number above 0, not " . _what($r{max_ibs0})
2319 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
2320 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
2321 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
2322 # every file checked before any is read, which can take minutes
2323 59 my %given;
2324 59 foreach my $file (@vcf) {
2325 112 _vcf_check($sub, 'vcf', $file);
2326 106 ▶ croak "$sub: \"$file\" is given twice" if $given{$file}++;
Branch: 1 branch
BranchTrueFalseTotal
if $given{$file}++ 1 105 106
2327 }
2328 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
2329 52 ▶ if (@vcf == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@vcf == 1) { } 28 24 52
2330 28 my ($next, $close) = _vcf_open($sub, 'vcf', $vcf[0]);
2331 28 ▶ ($names, $counts, $tally) = _located(sub { _relatedness_one($next, $vcf[0], $r{min_depth}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2332 25 $close->();
2333 } else {
2334 # each opened as Bioinf.xs comes to it, and closed at its end, so that only
2335 # one is open at a time
2336 my @next = map {
2337 24 my $file = $_;
2338 70 my ($next, $close);
2339 140 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2340 140 ▶ ($next, $close) = _vcf_open($sub, 'vcf', $file) unless $next;
Branch: 1 branch
BranchTrueFalseTotal
unless $next 70 70 140
2341 140 my $block = $next->();
2342 140 ▶ $close->() unless defined $block;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $block 63 77 140
2343 140 $block;
2344 70 };
2345 } @vcf;
2346 24 ▶ ($names, $counts, $tally) = _located(sub { _relatedness_own(\@next, \@vcf, $r{min_depth}) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2347 }
2348 41 foreach my $i (0 .. $#{ $names }) {
2349 187 my $s = $tally->{ $names->[$i] };
2350 187 _sex_of($s, $Sex_cutoff);
2351 187 ▶ $s->{file} = @vcf == 1 ? $vcf[0] : $vcf[$i];
Branch: 1 branch
BranchTrueFalseTotal
@vcf == 1 ? : 137 50 187
2352 }
2353 41 my %out = map { $_ => {} } @{ $names };
2354 # each pair, in the samples' order, given to $code as (first, second, its
2355 # hash); walked when needed rather than held as a list, which for 1,000
2356 # samples would be 499,500 arrays, each with a copy of both names
2357 131 ▶ my $each_pair = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2358 131 my ($code) = @_;
2359 131 foreach my $i (0 .. $#{ $names } - 1) {
2360 474 my $x = $names->[$i];
2361 474 $code->($x, $_, $out{$x}{$_}) foreach @{ $names }[$i + 1 .. $#{ $names }];
2362 }
2363 41 };
2364 41 my $pair = 11 * length pack 'J', 0; # bytes of a pair's counts in $counts
2365 41 my $k = 0; # where the pair's counts start in $counts
2366 41 foreach my $i (0 .. $#{ $names } - 1) {
2367 146 foreach my $j ($i + 1 .. $#{ $names }) {
2368 429 my ($x, $y) = @{ $names }[$i, $j];
2369 # t[3 * x's ALT count + y's], as parent's, and then the sites in both VCFs,
2370 # in x's alone and in y's alone
2371 429 my @t = (0, unpack "x$k J11", $counts);
2372 429 my @in = splice @t, 9;
2373 429 $k += $pair;
2374 # Flat, but for het and only: on 1,000 samples (2026-10-19) the pairs took
2375 # 560 MB with no field a hash, and 1,110 MB with four, which were these two
2376 # and each sample's hom-ALT count and share of ibs0.
2377 429 my %s;
2378 429 $s{sites} = 0;
2379 429 $s{sites} += $_ foreach @t;
2380 429 ▶ @in = ($s{sites}, 0, 0) if @vcf == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @vcf == 1 369 60 429
2381 429 $s{in_both} = $in[0];
2382 429 $s{only} = { $x => $in[1], $y => $in[2] };
2383 429 $s{ibs0} = $t[2] + $t[6];
2384 429 $s{ibs1} = $t[1] + $t[3] + $t[5] + $t[7];
2385 429 $s{ibs2} = $t[4] + $t[8];
2386 429 $s{het_het} = $t[4];
2387 429 $s{het} = { $x => $t[3] + $t[4] + $t[5], $y => $t[1] + $t[4] + $t[7] };
2388 429 $s{kinship} = _king($s{het}{$x}, $s{het}{$y}, $s{het_het}, $s{ibs0});
2389 429 ▶ $s{ibs0_rate} = $s{sites} ? $s{ibs0} / $s{sites} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$s{'sites'} ? : 429 0 429
2390 # parent's reasons for dying, in parent's order
2391 $s{undecided} = $s{sites} && !($t[1] + $t[2] + $t[3] + $t[6])
2392 ? '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'
2393 : $s{sites} < $Parent_sites ? "$s{sites} sites compared, and $Parent_sites are needed"
2394 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
2395 : undef;
2396 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
2397 429 $s{parent} = $s{category} = undef; # below, once every pair is known
2398 429 $out{$x}{$y} = $out{$y}{$x} = \%s;
2399 }
2400 }
2401 41 undef $counts;
2402 # Which of a parent and child is the parent, where a third sample says, since
2403 # two people's genotypes cannot: x is y's parent when x has another child who
2404 # is y's full sibling, or when y has another parent who is unrelated to x, the
2405 # two being y's parents. Two of y's parent-child partners who are
2406 # second-degree relatives are y's parent and y's child, and say nothing about
2407 # which. "Third-degree" is not taken as unrelated: in the CEPH 1463 pedigree
2408 # (peddy's ceph1463.peddy.vcf.gz), the grandfather NA12889 and grandson
2409 # NA12893 had a kinship of 0.0839, below KING's 0.0884, and would have made
2410 # NA12893's father NA12877 his son too.
2411 41 my %pc; # sample => its parent-child partners
2412 429 ▶ $each_pair->(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2413 429 my ($x, $y, $s) = @_;
2414 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
2415 163 push @{ $pc{$x} }, $y;
2416 163 push @{ $pc{$y} }, $x;
2417 41 });
2418 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
2419 326 my ($x, $y) = @_;
2420 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
2421 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
2422 41 };
2423 429 ▶ $each_pair->(sub {
Subroutine __ANON__: called CC=19 SCAR=29.5
2424 429 my ($x, $y, $s) = @_;
2425 429 my ($rel, $sx, $sy) = ($s->{relationship}, $tally->{$x}{sex}, $tally->{$y}{sex});
2426 429 ▶ return unless defined $rel;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rel 46 383 429
2427 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
2428 163 my ($x_is, $y_is) = ($is_parent->($x, $y), $is_parent->($y, $x));
2429 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
2430 163 ▶ if (defined $s->{parent}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $s->{'parent'}) { } 157 6 163
2431 157 ▶ my ($ps, $cs) = $s->{parent} eq $x ? ($sx, $sy) : ($sy, $sx);
Branch: 1 branch
BranchTrueFalseTotal
$s->{'parent'} eq $x ? : 145 12 157
2432 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
2433 } else { # two men are father and son, whichever is which
2434 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
2435 }
2436 } elsif ($rel eq 'full siblings') {
2437 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
2438 } else {
2439 181 $s->{category} = $rel;
2440 }
2441 41 });
2442 41 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 4 37 41
2443 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
2444 }
2445 41 my ($undecided, $first) = (0); # the pairs undecided, and the first of them as [first, second, why]
2446 41 my @regions; # as parent warns, and for its reasons: the pairs whose VCFs differ in their regions
2447 429 ▶ $each_pair->(sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
2448 429 my ($x, $y, $s) = @_;
2449 429 ▶ if (defined $s->{undecided}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $s->{"undecided"}) 46 383 429
2450 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
2451 46 $undecided++;
2452 }
2453 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
2454 push @regions, "$tally->{$more}{file} against $tally->{$fewer}{file} ($s->{only}{$more} to $s->{only}{$fewer})"
2455 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
2456 41 });
2457 41 my $n_pairs = @{ $names } * (@{ $names } - 1) / 2;
2458 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
2459 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
2460 . ' since one has more than twice as many sites that the other lacks as the other has that it lacks: '
2461 . join(', ', @regions[0 .. ($#regions < 2 ? $#regions : 2)]) . (@regions > 3 ? ', and ' . (@regions - 3) . ' more' : '')
2462 . '; a site that one lacks is taken as hom-REF in it, so their IBS0 and kinship are not to be trusted'
2463 if @regions;
2464 41 ▶ wantarray ? (\%out, $tally) : \%out;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 8 33 41
2465 }
2466  
2467 # ---- genotype concordance
2468  
2469 # concordance's report, given its files, the resolved options, its result,
2470 # and the test's samples in its file's order. Columns are
2471 # as wide as their widest entry, numbers right-aligned.
2472 2 ▶sub _concordance_report {
Subroutine _concordance_report: called CC=14 SCAR=26.5
2473 2 my ($test, $truth, $r, $out, $test_names) = @_;
2474 2 my @pairs = map { $out->{$_} } grep { exists $out->{$_} } @{ $test_names }; # not a slice, which grep would autovivify into $out
2475 2 my $renamed = grep { $_->{test_sample} ne $_->{truth_sample} } @pairs; # the truth's sample is shown only when one is named otherwise
2476 2 ▶ my @head = ('sample', $renamed ? 'truth sample' : (), 'sites', 'in truth', 'concordant', 'discordant', 'gained', 'lost',
Branch: 1 branch
BranchTrueFalseTotal
$renamed ? : 1 1 2
2477 'concordance', 'precision', 'recall', 'specificity');
2478 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
2479 my @rows = map {
2480 2 my ($c, $m) = @{ $_ }{qw(counts metrics)};
2481 3 my ($agree, $differ) = (0, 0);
2482 3 foreach my $kind (keys %{ $c }) {
2483 135 ▶ $agree += $c->{$kind} if $kind =~ /\Aconcordant_/;
Branch: 1 branch
BranchTrueFalseTotal
if $kind =~ /\Aconcordant_/ 33 102 135
2484 135 ▶ $differ += $c->{$kind} if $kind =~ /\Adiscordant_/;
Branch: 1 branch
BranchTrueFalseTotal
if $kind =~ /\Adiscordant_/ 96 39 135
2485 }
2486 3 [$_->{test_sample}, $renamed ? $_->{truth_sample} : (), $_->{sites}, $_->{in_truth}, $agree, $differ, @{ $c }{qw(gained_site lost_site)},
2487 3 ▶ map { $ratio->($m->{$_}) } qw(genotype_concordance precision_genotype recall_genotype specificity_genotype)]
Branch: 1 branch
BranchTrueFalseTotal
$renamed ? : 1 2 3
2488 } @pairs;
2489 2 my @w = map { length } @head;
2490 2 foreach my $row (@rows) {
2491 3 foreach my $i (0 .. $#head) {
2492 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
2493 }
2494 }
2495 2 ▶ my $text_cols = $renamed ? 2 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$renamed ? : 1 1 2
2496 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
2497 2 my @alone = grep { !exists $out->{$_} } @{ $test_names };
2498 "concordance: test $test against truth $truth\n"
2499 . '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'
2500 . ($r->{min_depth} ? ", and a genotype of DP below $r->{min_depth} a no-call" : '')
2501 . "; precision, recall and specificity are of genotypes\n"
2502 3 ▶ . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows)
Branch: 1 branch
BranchTrueFalseTotal
@alone ? : 1 1 2
2503 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
2504 . join(', ', @alone[0 .. ($#alone < 4 ? $#alone : 4)]) . (@alone > 5 ? ', and ' . (@alone - 5) . ' more' : '') . "\n" : '');
2505 }
2506  
2507 83 ▶sub concordance {
Subroutine concordance: called CC=17 SCAR=28.3
Pod documented
2508 83 my $sub = 'concordance';
2509 83 my $args = _args(\@_, $sub, [qw(test truth)], [qw(discordances min_depth report)]);
2510 77 my %r;
2511 # x.low_ram_local_concordance.pl, which this is taken from, had no depth filter
2512 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
2513 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
2514 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
2515 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
2516 croak "$sub: \"discordances\" must be 0 or 1, not " . _what($r{discordances})
2517 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
2518 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
2519 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
2520 71 my ($test, $truth) = @{ $args }{qw(test truth)};
2521 # both checked before either is read, which can take minutes
2522 71 _vcf_check($sub, 'test', $test);
2523 69 _vcf_check($sub, 'truth', $truth);
2524 66 _same_build($sub, $test, $truth); # reads only the headers
2525 # the truth's samples first, so that the test's reading keeps the calls of
2526 # only those samples it will compare
2527 61 my ($next, $close) = _vcf_open($sub, 'truth', $truth);
2528 61 ▶ my ($truth_names) = _located(sub { _vcf_samples($next, $truth) });
Subroutine __ANON__: called CC=1 SCAR=0.0
2529 59 $close->();
2530 59 my ($test_next, $test_close) = _vcf_open($sub, 'test', $test);
2531 59 my ($truth_next, $truth_close) = _vcf_open($sub, 'truth', $truth);
2532 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
2533 38 $test_close->();
2534 38 $truth_close->();
2535 38 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 2 36 38
2536 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
2537 }
2538 38 my ($any) = values %{ $out }; # every pair has the same sites
2539 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
2540 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;"
2541 . ' check that the two are of the same genome build'
2542 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
2543 38 $out;
2544 }
2545  
2546 # ---- trait prediction
2547  
2548 # GRCh37's and GRCh38's lengths for four of the chromosomes the HIrisPlex-S
2549 # panel sits on, which _hirisplex_build tells one build from the other by.
2550 # From Ensembl's /info/assembly/homo_sapiens, rest.ensembl.org for GRCh38 and
2551 # grch37.rest.ensembl.org for GRCh37, read 2026-10-20. hg19 and b37 differ
2552 # only in what they call their chromosomes, and hg38 and b38 likewise, so a
2553 # length separates the two pairs but not the two within a pair, which the
2554 # panel's positions do not depend on.
2555 36 my %Build_length = (
2556 b37 => { 1 => 249250621, 15 => 102531392, 16 => 90354753, 20 => 63025520 },
2557 b38 => { 1 => 248956422, 15 => 101991189, 16 => 90338345, 20 => 64444167 },
2558 );
2559  
2560 # The HIrisPlex-S marker panel, share/hirisplex_s_panel.tsv, read once into an
2561 # array ref of hash refs in the panel's own order. share/make_hirisplex_panel.pl
2562 # writes that file and its header comment says where every column comes from.
2563 36 my $Panel; # undef until the file has been read
2564  
2565 # The data file $name (a marker panel, or the genetic codes), which this
2566 # distribution installs in its share directory, as a file that can be read;
2567 # dies, naming $sub, when it is nowhere.
2568 7 ▶sub _share_file {
Subroutine _share_file: called CC=9 SCAR=34.3
2569 7 my ($sub, $name) = @_;
2570 # Installed, the panel is in the distribution's share directory, which is
2571 # what File::ShareDir finds. Two fallbacks follow it: the same layout looked
2572 # for in @INC, which is where blib puts the file under "make test" and keeps
2573 # this working on a perl that has not got File::ShareDir, and the share
2574 # directory beside lib/, which is what lets a working copy be used before
2575 # the module is installed.
2576 7 my $file = eval { require File::ShareDir; File::ShareDir::dist_file('Cn-Bioinf', $name) };
2577 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
2578 0 my @try = map { File::Spec->catfile($_, 'auto', 'share', 'dist', 'Cn-Bioinf', $name) } grep { !ref } @INC;
2579 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
2580 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
2581 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
2582 }
2583 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
2584 unless defined $file && -f $file && -r _;
2585 7 $file;
2586 }
2587  
2588 15 ▶sub _hirisplex_panel {
Subroutine _hirisplex_panel: called CC=19 SCAR=32.9
2589 15 my ($sub) = @_;
2590 15 ▶ return $Panel if $Panel;
Branch: 1 branch
BranchTrueFalseTotal
if $Panel 13 2 15
2591 2 my $file = _share_file($sub, 'hirisplex_s_panel.tsv');
2592 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
2593 2 my $head = <$fh>;
2594 2 ▶ croak "$sub: marker panel $file is empty" unless defined $head;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $head 0 2 2
2595 2 $head =~ s/\r?\n\z//;
2596 2 $head =~ s/\A#//;
2597 2 my @cols = split /\t/, $head, -1;
2598 2 my @panel;
2599 2 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 82 2 84
2600 82 $line =~ s/\r?\n\z//;
2601 82 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 82 82
2602 82 my %m;
2603 82 @m{@cols} = split /\t/, $line, -1;
2604 82 push @panel, \%m;
2605 }
2606 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
2607 2 ▶ croak "$sub: marker panel $file has no markers" unless @panel;
Branch: 1 branch
BranchTrueFalseTotal
unless @panel 0 2 2
2608 2 foreach my $m (@panel) {
2609 82 foreach my $c (qw(rsid gene input_allele count_allele kind)) {
2610 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
2611 }
2612 # Every marker of this panel is autosomal, and the reader counts a
2613 # diploid call only, so a sex chromosome here would be counted wrongly
2614 # rather than refused.
2615 82 foreach my $b (qw(b37 b38)) {
2616 164 my ($c, $p) = @{ $m }{"${b}_chrom", "${b}_pos"};
2617 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
2618 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
2619 unless $c =~ /\A(?:[1-9]|1[0-9]|2[0-2])\z/;
2620 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
2621 unless defined $p && $p =~ /\A[1-9][0-9]*\z/;
2622 }
2623 }
2624 2 $Panel = \@panel;
2625 }
2626  
2627 # Which build's coordinates the panel is matched on, read from the ##contig
2628 # lines of the VCF $file, given to $sub as "vcf": "b37" or "b38". A header
2629 # that gives no length for any of the chromosomes above, or lengths that are
2630 # neither build's, cannot be told apart and dies asking for "build".
2631 35 ▶sub _hirisplex_build {
Subroutine _hirisplex_build: called CC=6 SCAR=18.0
2632 35 my ($sub, $file) = @_;
2633 35 my $meta = _vcf_meta($sub, 'vcf', $file);
2634 35 my %length; # contig => the first length its header gives
2635 35 foreach my $c (@{ $meta->{contig} }) {
2636 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
2637 }
2638 35 my @named = grep { defined $length{$_} } sort { $a <=> $b } keys %{ $Build_length{b37} };
2639 croak "$sub: \"vcf\" $file has no ##contig line giving a length for chromosome "
2640 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
2641 . ' give "build" as hg19, b37, hg38 or b38' unless @named;
2642 33 my @fits = grep { my $b = $_; !grep { $length{$_} != $Build_length{$b}{$_} } @named } sort keys %Build_length;
2643 croak "$sub: \"vcf\" $file gives chromosome lengths that are neither GRCh37's nor GRCh38's ("
2644 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
2645 . ' give "build" as hg19, b37, hg38 or b38' unless @fits == 1;
2646 32 $fits[0];
2647 }
2648  
2649 # Whether each prediction can be made at all from $d, one genotype for each
2650 # marker of $panel and undef where the sample had no call. The webtool refuses
2651 # some outright, whatever the genotypes say, because the loss in AUC is too
2652 # great; from the HIrisPlex-S user manual (version 2.0, 2018,
2653 # https://hirisplex.erasmusmc.nl/pdf/hirisplex.erasmusmc.nl.pdf, read
2654 # 2026-10-20), page 2: "Inputs missing the HERC2 SNP (rs12913832 = NA) will
2655 # not provide an eye colour prediction result, as the loss in AUC is too
2656 # great. Inputs missing all 11 MC1R SNPs will not provide a hair colour
2657 # prediction result. Inputs missing a combination of HERC2-SLC45A2-IRF4 will
2658 # not produce and eye or hair prediction result." The manual gives no such
2659 # rule for skin, and says only that missing any marker "is not advised", so
2660 # skin is refused here only when nothing at all was called.
2661 28 ▶sub _hirisplex_possible {
Subroutine _hirisplex_possible: called CC=8 SCAR=20.8
2662 28 my ($panel, $d) = @_;
2663 28 my %called; # rs number => 1 for each marker the sample has a genotype at
2664 28 my ($mc1r, $any) = (0, 0);
2665 28 foreach my $k (0 .. $#{ $panel }) {
2666 1148 ▶ next unless defined $d->[$k];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $d->[$k] 451 697 1148
2667 697 $called{ $panel->[$k]{rsid} } = 1;
2668 697 ▶ $mc1r++ if $panel->[$k]{gene} eq 'MC1R';
Branch: 1 branch
BranchTrueFalseTotal
if $panel->[$k]{"gene"} eq "MC1R" 191 506 697
2669 697 $any++;
2670 }
2671 # HERC2 rs12913832, SLC45A2 rs16891982 and IRF4 rs12203592: eye needs the
2672 # first, so it needs one of the three already, and hair needs one of them
2673 28 my $three = grep { $called{$_} } qw(rs12913832 rs16891982 rs12203592);
2674 {
2675 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
2676 hair => $mc1r && $three ? 1 : 0,
2677 skin => $any ? 1 : 0,
2678 };
2679 }
2680  
2681 # The genotypes of $out written to $file as the CSV the HIrisPlex-S webtool
2682 # takes: a sampleid column and one for each marker, headed
2683 # "<rs number>_<input allele>" as the webtool's own template heads it, holding
2684 # the count of that allele or NA. The samples are written in $order, the VCF's.
2685 1 ▶sub _hirisplex_csv {
Subroutine _hirisplex_csv: called CC=10 SCAR=25.1
2686 1 my ($sub, $file, $panel, $out, $order) = @_;
2687 1 my @head = map { "$_->{rsid}_$_->{input_allele}" } @{ $panel };
2688 # The webtool reads the file as plain CSV, so a sample whose name holds a
2689 # comma, a quote or a newline would move or split its row rather than
2690 # being quoted into it.
2691 1 my @bad = grep { /[",\r\n]/ } @{ $order };
2692 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
2693 . (@bad > 1 ? ' have' : ' has') . ' a comma, a quote or a newline in the name, which a CSV column can\'t hold' if @bad;
2694 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
2695 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
2696 1 foreach my $s (@{ $order }) {
2697 4 my $g = $out->{$s}{genotype};
2698 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
2699 }
2700 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
2701 }
2702  
2703 # hirisplex_genotypes's report on $vcf: what was read and how, then a table of
2704 # the samples in $order, the VCF's, each with how many markers were called and
2705 # which predictions its genotypes allow.
2706 0 ▶sub _hirisplex_report {
Subroutine _hirisplex_report: not called CC=8 SCAR=42.8
2707 0 my ($vcf, $r, $panel, $out, $order, $absent) = @_;
2708 0 my @head = ('sample', 'called', 'missing', 'eye', 'hair', 'skin');
2709 my @rows = map {
2710 0 my $s = $out->{$_};
2711 0 ▶ [$_, $s->{called}, scalar @{ $s->{missing} }, map { $s->{$_} ? 'yes' : 'no' } qw(eye hair skin)]
Branch: 1 branch
BranchTrueFalseTotal
$s->{$_} ? : 0 0 0
2712 0 } @{ $order };
2713 0 my @w = map { length $head[$_] } 0 .. $#head;
2714 0 foreach my $row (@rows) {
2715 0 foreach my $i (0 .. $#head) {
2716 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
2717 }
2718 }
2719 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
2720 "hirisplex_genotypes: $vcf\n"
2721 0 ▶ . scalar(@{ $panel }) . ' HIrisPlex-S markers, matched by '
Branch: 2 branches
BranchTrueFalseTotal
$r->{'match'} eq 'id' ? : 0 0 0
@{$absent;} ? : 0 0 0
2722 . ($r->{match} eq 'id' ? 'rs number' : "position on $r->{build}")
2723 . "; genotypes of DP below $r->{min_depth} not counted\n"
2724 0 ▶ . (@{ $absent } ? scalar(@{ $absent }) . ' marker' . (@{ $absent } > 1 ? 's' : '') . ' not in the file at all: '
Branch: 1 branch
BranchTrueFalseTotal
@{$absent;} > 1 ? : 0 0 0
2725 0 . join(', ', @{ $absent }) . "\n" : '')
2726 0 . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows)
2727 . "\"eye\", \"hair\" and \"skin\" are whether the HIrisPlex-S manual's rules allow that prediction from these markers\n";
2728 }
2729  
2730 25 ▶sub hirisplex_genotypes {
Subroutine hirisplex_genotypes: called CC=47 SCAR=40.4
Pod documented
2731 25 my $sub = 'hirisplex_genotypes';
2732 # hirisplex_genotypes($file) and hirisplex_genotypes($file, %options) take
2733 # the file first, as sex_check does; an odd count whose first is an
2734 # option's name is left for _args to refuse
2735 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
2736 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
2737 if @_ && defined $_[0] && !ref $_[0] && $_[0] ne 'vcf' && -f $_[0];
2738 25 my $args = _args(\@_, $sub, ['vcf'], [qw(build file match min_depth report)]);
2739 23 my %r;
2740 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
2741 croak "$sub: \"match\" must be \"position\" or \"id\", not " . _what($r{match})
2742 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
2743 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
2744 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
2745 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
2746 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
2747 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
2748 19 $r{file} = $args->{file}; # undef = no CSV is written
2749 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
2750 croak "$sub: \"build\" must be hg19, b37, hg38 or b38, not " . _what($args->{build})
2751 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
2752 17 my $vcf = $args->{vcf};
2753 17 _vcf_check($sub, 'vcf', $vcf);
2754 15 my $panel = _hirisplex_panel($sub);
2755 # which of the panel's two sets of coordinates the markers are looked for
2756 # at; undef when matching by rs number, which needs neither
2757 $r{build} = $r{match} eq 'id' ? undef
2758 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
2759 : _hirisplex_build($sub, $vcf);
2760  
2761 # What the reader searches for: one entry for each marker, and for matching
2762 # by rs number a second under the number that marker's has been merged
2763 # into, since a VCF annotated from either dbSNP release should match.
2764 13 my @entries;
2765 13 foreach my $k (0 .. $#{ $panel }) {
2766 533 my $m = $panel->[$k];
2767 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
2768 533 ▶ if ($r{match} eq 'id') {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{'match'} eq 'id') { } 123 410 533
2769 123 my %seen;
2770 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
2771 126 push @entries, [0, 0, $m->{count_allele}, $insertion, $id, $k];
2772 }
2773 } else {
2774 410 my ($c, $p) = @{ $m }{"$r{build}_chrom", "$r{build}_pos"};
2775 # a marker the panel could not place on this build is searched for
2776 # nowhere, and comes back as one the file did not hold
2777 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
2778 410 push @entries, [$c, $p, $m->{count_allele}, $insertion, $m->{rsid}, $k];
2779 }
2780 }
2781 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
2782  
2783 13 my ($next, $close) = _vcf_open($sub, 'vcf', $vcf);
2784 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
2785 13 $close->();
2786  
2787 13 my @column = map { "$_->{rsid}_$_->{input_allele}" } @{ $panel };
2788 13 my @absent = map { $panel->[$_]{rsid} } grep { !$seen->[$_] } 0 .. $#{ $panel };
2789 13 my %out;
2790 13 foreach my $s (keys %{ $dose }) {
2791 28 my $d = $dose->{$s};
2792 28 my (%genotype, @missing);
2793 28 foreach my $k (0 .. $#{ $panel }) {
2794 1148 $genotype{ $column[$k] } = $d->[$k];
2795 1148 ▶ push @missing, $panel->[$k]{rsid} unless defined $d->[$k];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $d->[$k] 451 697 1148
2796 }
2797 28 my $can = _hirisplex_possible($panel, $d);
2798 $out{$s} = {
2799 genotype => \%genotype,
2800 missing => \@missing,
2801 28 markers => scalar @{ $panel },
2802 28 called => scalar(@{ $panel }) - scalar(@missing),
2803 28 %{ $can },
2804 };
2805 }
2806 13 ▶ _hirisplex_csv($sub, $r{file}, $panel, \%out, $names) if defined $r{file};
Branch: 1 branch
BranchTrueFalseTotal
if defined $r{"file"} 1 12 13
2807 13 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 0 13 13
2808 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
2809 }
2810 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
2811 . ($r{match} eq 'id' ? '; it was matched by rs number, and a VCF whose ID column is "." matches nothing that way'
2812 : ", matched by position on $r{build}; check that it is the build the file is on")
2813 13 ▶ if @absent == @{ $panel };
Branch: 1 branch
BranchTrueFalseTotal
if @absent == @{$panel;} 1 12 13
2814 13 \%out;
2815 }
2816  
2817 # The marker that carries a category's intercept, in place of an rs number, in
2818 # a "model" table. A marker can't be called this, so nothing is ambiguous.
2819 36 my $Intercept = '(intercept)';
2820  
2821 # The rows of "model" read into trait => category => { marker => beta }, with
2822 # the intercept under $Intercept, and the traits and their categories in the
2823 # order the table first names them, which is the order the report prints.
2824 15 ▶sub _trait_model {
Subroutine _trait_model: called CC=15 SCAR=27.3
2825 15 my ($sub, $model) = @_;
2826 15 my ($next, $cols) = _weight_rows($sub, $model, 'model');
2827 14 my %have = map { $_ => 1 } @{ $cols };
2828 14 my @absent = grep { !$have{$_} } qw(trait category marker beta);
2829 14 ▶ croak "$sub: \"model\" has no " . join(', ', map { "\"$_\"" } @absent) . ' column' . (@absent > 1 ? 's' : '')
Branch: 2 branches
BranchTrueFalseTotal
if @absent 1 13 14
@absent > 1 ? : 1 0 1
2830 . '; a model table has trait, category, marker and beta' if @absent;
2831 13 my (%beta, @traits, %category);
2832 13 ▶ while (my ($row, $label) = $next->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$next()) 44 10 54
2833 44 my ($t, $c, $m, $b) = @{ $row }{qw(trait category marker beta)};
2834 44 foreach my $f (['trait', $t], ['category', $c], ['marker', $m]) {
2835 132 ▶ 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 131 132
Condition66%2/3
defined $f->[1] and length $f->[1]
!ll&&!rl&&r
01131
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
2836 }
2837 43 ▶ 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 42 43
Condition50%3/6
defined $b and not ref $b and $b =~ /$Number/
!ll&&!rl&&r
0142
defined $b and not ref $b
!ll&&!rl&&r
0043
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
2838 unless defined $b && !ref $b && $b =~ $Number;
2839 42 ▶ push @traits, $t unless $beta{$t};
Branch: 1 branch
BranchTrueFalseTotal
unless $beta{$t} 14 28 42
2840 42 ▶ push @{ $category{$t} }, $c unless $beta{$t} && $beta{$t}{$c};
Branch: 1 branch
BranchTrueFalseTotal
unless $beta{$t} and $beta{$t}{$c} 29 13 42
Condition100%3/3
$beta{$t} and $beta{$t}{$c}
!ll&&!rl&&r
141513
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
2841 croak "$sub: $label of \"model\" gives $t category \"$c\" a second beta for $m"
2842 42 ▶ if exists $beta{$t}{$c}{$m};
Branch: 1 branch
BranchTrueFalseTotal
if exists $beta{$t}{$c}{$m} 1 41 42
2843 41 $beta{$t}{$c}{$m} = $b;
2844 }
2845 10 ▶ croak "$sub: \"model\" has no rows" unless @traits;
Branch: 1 branch
BranchTrueFalseTotal
unless @traits 0 10 10
2846 10 (\%beta, \@traits, \%category);
2847 }
2848  
2849 # exp() of each of @$eta, divided by their sum: the probabilities a multinomial
2850 # logistic regression gives its categories. The largest is taken out first, so
2851 # that a linear predictor big enough to overflow exp() (about 710 on an IEEE
2852 # double, and larger on a long-double or quadmath perl) gives 1 and the rest 0
2853 # rather than inf/inf, which is NaN.
2854 19 ▶sub _softmax {
Subroutine _softmax: called CC=4 SCAR=13.9
2855 19 my ($eta) = @_;
2856 19 my $max = $eta->[0];
2857 19 ▶ foreach my $e (@{ $eta }) { $max = $e if $e > $max }
Branch: 1 branch
BranchTrueFalseTotal
if $e > $max 13 32 45
2858 19 my @exp = map { exp($_ - $max) } @{ $eta };
2859 19 my $sum = 0;
2860 19 $sum += $_ foreach @exp;
2861 19 [map { $_ / $sum } @exp];
2862 }
2863  
2864 # trait_predict's report on $out: a table of each sample's probabilities, one
2865 # block for each trait, the categories in the model's order.
2866 0 ▶sub _trait_report {
Subroutine _trait_report: not called CC=10 SCAR=47.0
2867 0 my ($r, $out, $order, $traits, $category) = @_;
2868 0 ▶ my $text = "trait_predict: " . scalar(@{ $order }) . ' sample' . (@{ $order } > 1 ? 's' : '')
Branch: 1 branch
BranchTrueFalseTotal
@{$order;} > 1 ? : 0 0 0
2869 0 ▶ . ', ' . scalar(@{ $traits }) . ' trait' . (@{ $traits } > 1 ? 's' : '')
Branch: 2 branches
BranchTrueFalseTotal
@{$traits;} > 1 ? : 0 0 0
$r->{'force'} ? : 0 0 0
2870 . "; a marker the sample has no genotype for counts as 0 copies"
2871 0 . ($r->{force} ? ', and a prediction the HIrisPlex-S rules refuse is made anyway ("force")' : '') . "\n";
2872 0 foreach my $t (@{ $traits }) {
2873 0 my @head = ('sample', 'call', @{ $category->{$t} }, 'called');
2874 my @rows = map {
2875 0 my $p = $out->{$_}{$t};
2876 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
2877 "$p->{called}/$p->{markers}"]
2878 0 } @{ $order };
2879 0 my @w = map { length $head[$_] } 0 .. $#head;
2880 0 foreach my $row (@rows) {
2881 0 foreach my $i (0 .. $#head) {
2882 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
2883 }
2884 }
2885 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
2886 0 $text .= "\n$t\n" . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows);
2887 0 my @refused = grep { defined $out->{$_}{$t}{refused} } @{ $order };
2888 0 $text .= join '', map { " $_: no $t prediction: $out->{$_}{$t}{refused}\n" } @refused;
2889 }
2890 0 $text;
2891 }
2892  
2893 19 ▶sub trait_predict {
Subroutine trait_predict: called CC=40 SCAR=37.1
Pod documented
2894 19 my $sub = 'trait_predict';
2895 19 my $args = _args(\@_, $sub, [qw(genotypes model)], [qw(force report)]);
2896 18 my %r;
2897 18 ▶ $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
216
MC/DC100%1/1
$args->{"force"} // 0
$args->{"force"}
Truth table100%2/2
A
A= $args->{"force"}
Aresult
11
00
2898 18 ▶ 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 17 18
Condition83%5/6
not ref $r{"force"} and $r{"force"} eq 0 || $r{"force"} eq 1
!ll&&!rl&&r
0117
$r{"force"} eq 0 or $r{"force"} eq 1
l!l&&r!l&&!r
1611
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
2899 17 ▶ $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
512
MC/DC100%1/1
$args->{"report"} // 1
$args->{"report"}
Truth table100%2/2
A
A= $args->{"report"}
Aresult
11
00
2900 17 ▶ 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 17 17
Condition50%3/6
not ref $r{"report"} and $r{"report"} eq 0 || $r{"report"} eq 1
!ll&&!rl&&r
0017
$r{"report"} eq 0 or $r{"report"} eq 1
l!l&&r!l&&!r
5120
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
2901 17 my $g = $args->{genotypes};
2902 17 ▶ 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 16 17
2903 unless ref $g eq 'HASH';
2904 16 ▶ croak "$sub: \"genotypes\" has no samples" unless keys %{ $g };
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$g;} 1 15 16
2905 15 my ($beta, $traits, $category) = _trait_model($sub, $args->{model});
2906  
2907 # Which markers each trait's categories use between them: the same for every
2908 # sample, so it is worked out once rather than once per sample.
2909 10 my %uses;
2910 10 foreach my $t (@{ $traits }) {
2911 13 foreach my $c (@{ $category->{$t} }) {
2912 28 $uses{$t}{$_} = 1 foreach grep { $_ ne $Intercept } keys %{ $beta->{$t}{$c} };
2913 }
2914 }
2915 10 my %used = map { %{ $uses{$_} } } keys %uses; # every trait's markers, whose dosages are checked
2916  
2917 10 my %out;
2918 10 foreach my $s (sort keys %{ $g }) {
2919 16 my $rec = $g->{$s};
2920 16 ▶ 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 15 16
2921 # Either what hirisplex_genotypes returns, whose genotypes are under
2922 # "genotype" and which also says which predictions its markers allow,
2923 # or a plain hash of marker => dosage.
2924 15 ▶ my $dose = ref $rec->{genotype} eq 'HASH' ? $rec->{genotype} : $rec;
Branch: 1 branch
BranchTrueFalseTotal
ref $rec->{'genotype'} eq 'HASH' ? : 9 6 15
2925 # A dosage may be fractional, as imputation gives, but anything else
2926 # would be multiplied in as 0 copies and counted as called.
2927 15 foreach my $m (sort keys %used) {
2928 32 my $d = $dose->{$m};
2929 32 ▶ 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 28 32
Condition100%12/12
not defined $d or not ref $d and $d =~ /$Number/ and $d >= 0 and $d <= 2
l!l&&r!l&&!r
4244
not ref $d and $d =~ /$Number/ and $d >= 0 and $d <= 2
!ll&&!rl&&r
3124
not ref $d and $d =~ /$Number/ and $d >= 0
!ll&&!rl&&r
2125
not ref $d and $d =~ /$Number/
!ll&&!rl&&r
1126
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
2930 unless !defined $d || (!ref $d && $d =~ $Number && $d >= 0 && $d <= 2);
2931 }
2932 11 foreach my $t (@{ $traits }) {
2933 20 my (@eta, @missing);
2934 20 my $called = 0;
2935 20 my $marker = $uses{$t};
2936 20 foreach my $m (sort keys %{ $marker }) {
2937 28 ▶ if (defined $dose->{$m}) { $called++ } else { push @missing, $m }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $dose->{$m}) { } 24 4 28
2938 }
2939 20 foreach my $c (@{ $category->{$t} }) {
2940 48 ▶ my $eta = $beta->{$t}{$c}{$Intercept} // 0;
Condition100%2/2
$beta->{$t}{$c}{$Intercept} // 0
l!l
471
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
2941 48 foreach my $m (keys %{ $beta->{$t}{$c} }) {
2942 84 ▶ next if $m eq $Intercept;
Branch: 1 branch
BranchTrueFalseTotal
if $m eq $Intercept 47 37 84
2943 # A marker with no genotype drops out of the sum, which is
2944 # the same as counting it 0 copies of the counted allele.
2945 37 ▶ $eta += $beta->{$t}{$c}{$m} * $dose->{$m} if defined $dose->{$m};
Branch: 1 branch
BranchTrueFalseTotal
if defined $dose->{$m} 31 6 37
2946 }
2947 48 push @eta, $eta;
2948 }
2949 # hirisplex_genotypes sets eye, hair and skin to 0 where the
2950 # HIrisPlex-S manual refuses the prediction outright; a model whose
2951 # trait it says nothing about is predicted whatever it holds.
2952 20 ▶ 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 19 20
Condition88%8/9
not $r{"force"} and defined $rec->{$t} and not ref $rec->{$t} and $rec->{$t} eq 0
!ll&&!rl&&r
1631
not $r{"force"} and defined $rec->{$t} and not ref $rec->{$t}
!ll&&!rl&&r
1604
not $r{"force"} and defined $rec->{$t}
!ll&&!rl&&r
884
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
2953 ? 'the markers it needs are missing, and the HIrisPlex-S rules refuse it' : undef;
2954 20 ▶ my $p = $refused ? {} : do {
Branch: 1 branch
BranchTrueFalseTotal
$refused ? : 1 19 20
2955 19 my $soft = _softmax(\@eta);
2956 19 my %p;
2957 19 @p{ @{ $category->{$t} } } = @{ $soft };
2958 19 \%p;
2959 };
2960 20 ▶ my ($call) = $refused ? () : sort { $p->{$b} <=> $p->{$a} || $a cmp $b } keys %{ $p };
Branch: 1 branch
BranchTrueFalseTotal
$refused ? : 1 19 20
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
2961 $out{$s}{$t} = {
2962 p => $p,
2963 call => $call,
2964 20 markers => scalar keys %{ $marker },
2965 called => $called,
2966 missing => \@missing,
2967 refused => $refused,
2968 };
2969 }
2970 }
2971 5 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 0 5 5
2972 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
2973 }
2974 5 \%out;
2975 }
2976  
2977 # ---- blood type
2978  
2979 # The panel blood_type reads, share/blood_type_panel.tsv, once it has been
2980 # read: a hash ref of
2981 #
2982 # markers every marker, a hash ref a row, in the file's order, which is
2983 # the order Bioinf.xs returns their genotypes in
2984 # abo role => the marker's place in "markers", for the three of ABO:
2985 # "functional" (rs8176719, where the insertion counted is a
2986 # working A or B gene and its lack is O), "B" and "O2"
2987 # sites the places in "markers" of RHD's sites
2988 # gene the row of the RHD gene, whose span a deletion has to cover
2989 #
2990 # share/make_blood_type_panel.pl writes the file, and its header comment says
2991 # where every row comes from and what was measured. The counted allele of
2992 # every marker is an ALT on both builds, never the reference's own, which is
2993 # what lets a marker with no record be read as no copies of it.
2994 36 my $Blood_panel; # undef until the file has been read
2995  
2996 33 ▶sub _blood_panel {
Subroutine _blood_panel: called CC=27 SCAR=36.4
2997 33 my ($sub) = @_;
2998 33 ▶ return $Blood_panel if $Blood_panel;
Branch: 1 branch
BranchTrueFalseTotal
if $Blood_panel 31 2 33
2999 2 my $file = _share_file($sub, 'blood_type_panel.tsv');
3000 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
3001 2 my $head = <$fh>;
3002 2 ▶ croak "$sub: marker panel $file is empty" unless defined $head;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $head 0 2 2
3003 2 $head =~ s/\r?\n\z//;
3004 2 $head =~ s/\A#//;
3005 2 my @cols = split /\t/, $head, -1;
3006 2 my %panel = (markers => [], abo => {}, sites => [], gene => undef);
3007 2 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 38 2 40
3008 38 $line =~ s/\r?\n\z//;
3009 38 ▶ next if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 0 38 38
3010 38 my %m;
3011 38 @m{@cols} = split /\t/, $line, -1;
3012 38 foreach my $c (qw(name system role kind)) {
3013 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
3014 }
3015 38 foreach my $b (qw(b37 b38)) {
3016 # vcf_chrom()'s numbering, which the panel's two chromosomes, 1 and 9, are already in
3017 croak "$sub: row $m{name} of $file is on $b chromosome " . _what($m{"${b}_chrom"}) . ', which isn\'t an autosome'
3018 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
3019 76 ▶ foreach my $c ("${b}_pos", $m{kind} eq 'region' ? "${b}_end" : ()) {
Branch: 1 branch
BranchTrueFalseTotal
$m{'kind'} eq 'region' ? : 4 72 76
3020 croak "$sub: row $m{name} of $file has $c " . _what($m{$c}) . ', which isn\'t a position'
3021 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
3022 }
3023 }
3024 38 ▶ if ($m{kind} eq 'region') {
Branch: 1 branch
BranchTrueFalseTotal
if ($m{"kind"} eq "region") 2 36 38
3025 2 ▶ croak "$sub: $file has more than one gene" if $panel{gene};
Branch: 1 branch
BranchTrueFalseTotal
if $panel{"gene"} 0 2 2
3026 2 $panel{gene} = \%m;
3027 2 next;
3028 }
3029 croak "$sub: marker $m{name} of $file counts " . _what($m{count_allele}) . ', which isn\'t one base'
3030 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
3031 36 push @{ $panel{markers} }, \%m;
3032 36 ▶ if ($m{system} eq 'ABO') {
Branch: 1 branch
BranchTrueFalseTotal
if ($m{'system'} eq 'ABO') { } 6 30 36
3033 6 $panel{abo}{ $m{role} } = $#{ $panel{markers} };
3034 } else {
3035 30 push @{ $panel{sites} }, $#{ $panel{markers} };
3036 }
3037 }
3038 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
3039 2 ▶ croak "$sub: marker panel $file has no RHD gene" unless $panel{gene};
Branch: 1 branch
BranchTrueFalseTotal
unless $panel{"gene"} 0 2 2
3040 2 ▶ croak "$sub: marker panel $file has no site of RHD" unless @{ $panel{sites} };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$panel{"sites"};} 0 2 2
3041 2 foreach my $role (qw(functional B O2)) {
3042 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
3043 }
3044 2 $Blood_panel = \%panel;
3045 }
3046  
3047 # The ABO genotype and phenotype that $n says, a hash ref of how many copies
3048 # (0 to 2, or undef for no genotype) a sample has of each of the three ABO
3049 # markers' counted alleles, by role: (genotype, phenotype, undef), or (undef,
3050 # undef, the role whose genotype was needed and is missing).
3051 #
3052 # A chromosome without rs8176719's insertion is O whatever else it carries. One
3053 # with it is B when it carries rs8176746's T, O when it carries rs41302905's T
3054 # (the O2 allele, an O with no deletion), and otherwise A. The genotypes are
3055 # not phased, so a B or O2 allele is taken to be on a chromosome that has the
3056 # insertion, as long as there is one to put it on. That is nearly always
3057 # right: of 1000 Genomes phase 3's 5,008 haplotypes (b37 BCF, read
3058 # 2026-11-10), 721 carried the insertion with the B allele, 1,001 the
3059 # insertion without it, 44 the B allele without the insertion and 3,242
3060 # neither, so somebody heterozygous at both is B and O rather than A and an O
3061 # that carries B's base with a probability of 721 * 3242 / (721 * 3242 + 1001
3062 # * 44), which is 0.981.
3063 140 ▶sub _abo_type {
Subroutine _abo_type: called CC=11 SCAR=24.0
3064 140 my ($n) = @_;
3065 140 ▶ return (undef, undef, 'functional') unless defined $n->{functional};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n->{"functional"} 37 103 140
3066 103 my $working = $n->{functional}; # chromosomes with a working gene, A or B, unless they are O2
3067 103 my ($b, $o2) = (0, 0);
3068 103 ▶ if ($working) {
Branch: 1 branch
BranchTrueFalseTotal
if ($working) 87 16 103
3069 87 foreach my $role (qw(B O2)) {
3070 166 ▶ return (undef, undef, $role) unless defined $n->{$role};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n->{$role} 8 158 166
3071 }
3072 79 ▶ $b = $n->{B} < $working ? $n->{B} : $working;
Branch: 1 branch
BranchTrueFalseTotal
$n->{'B'} < $working ? : 47 32 79
3073 79 ▶ $o2 = $n->{O2} < $working - $b ? $n->{O2} : $working - $b;
Branch: 1 branch
BranchTrueFalseTotal
$n->{'O2'} < $working - $b ? : 33 46 79
3074 }
3075 95 my %count = (A => $working - $b - $o2, B => $b, O => 2 - $working + $o2);
3076 95 my $genotype = join '', map { $_ x $count{$_} } qw(A B O);
3077 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
3078 95 ($genotype, $phenotype, undef);
3079 }
3080  
3081 # blood_type's report on $vcf: what was read and how, a table of the samples in
3082 # $order, the VCF's, then what was taken as homozygous REF because the file has
3083 # no record of it, and why any sample has no type.
3084 3 ▶sub _blood_report {
Subroutine _blood_report: called CC=14 SCAR=26.4
3085 3 my ($vcf, $r, $panel, $out, $order, $assumed) = @_;
3086 3 my $sites = scalar @{ $panel->{sites} };
3087 3 my @head = ('sample', 'type', 'ABO', 'ABO genotype', 'RhD', 'RhD genotype', 'RHD sites');
3088 my @rows = map {
3089 18 my $s = $out->{$_};
3090 [$_, $s->{type} // '-', $s->{abo}{phenotype} // '-', $s->{abo}{genotype} // '-',
3091 18 ▶ $s->{rhesus}{phenotype} // '-', $s->{rhesus}{genotype} // '-', "$s->{rhesus}{carried}/$sites"]
Condition80%8/10
$s->{"type"} // "-"
l!l
144
$s->{"abo"}{"phenotype"} // "-"
l!l
144
$s->{"abo"}{"genotype"} // "-"
l!l
144
$s->{"rhesus"}{"phenotype"} // "-"
l!l
180
$s->{"rhesus"}{"genotype"} // "-"
l!l
180
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/DC0%0/1
$s->{"rhesus"}{"phenotype"} // "-"
$s->{"rhesus"}{"phenotype"}
MC/DC0%0/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 table50%1/2
A
A= $s->{"rhesus"}{"phenotype"}
Aresult
11
00
Truth table50%1/2
A
A= $s->{"rhesus"}{"genotype"}
Aresult
11
00
3092 3 } @{ $order };
3093 3 my @w = map { length $head[$_] } 0 .. $#head;
3094 3 foreach my $row (@rows) {
3095 18 foreach my $i (0 .. $#head) {
3096 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
3097 }
3098 }
3099 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
3100 3 my @why; # one line for each system of each sample that has no type
3101 3 foreach my $name (@{ $order }) {
3102 18 foreach my $system (qw(abo rhesus)) {
3103 36 my $why = $out->{$name}{$system}{why};
3104 36 ▶ push @why, "$name has no " . ($system eq 'abo' ? 'ABO' : 'RhD') . " type: $why\n" if defined $why;
Branch: 2 branches
BranchTrueFalseTotal
if defined $why 4 32 36
$system eq 'abo' ? : 4 0 4
3105 }
3106 }
3107 "blood_type: $vcf\n"
3108 . "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;"
3109 . " matched by position on $r->{build}; genotypes of DP below $r->{min_depth} not counted\n"
3110 18 ▶ . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows)
Branch: 1 branch
BranchTrueFalseTotal
@{$assumed;} ? : 2 1 3
3111 . "\"RHD sites\" is how many of the sites the sample has an ALT allele at; one is enough for RhD positive\n"
3112 3 . (@{ $assumed } ? 'not in the file, and taken as homozygous for the reference allele: ' . join(', ', @{ $assumed }) . "\n" : '')
3113 . join('', @why);
3114 }
3115  
3116 46 ▶sub blood_type {
Subroutine blood_type: called CC=52 SCAR=39.5
Pod documented
3117 46 my $sub = 'blood_type';
3118 # blood_type($file) and blood_type($file, %options) take the file first,
3119 # as sex_check does; an odd count whose first is an option's name is left
3120 # for _args to refuse
3121 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
3122 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
3123 if @_ && defined $_[0] && !ref $_[0] && $_[0] ne 'vcf' && -f $_[0];
3124 45 my $args = _args(\@_, $sub, ['vcf'], [qw(assume_ref build min_depth report)]);
3125 42 my %r;
3126 # 1 = a marker the file has no record of is homozygous for the reference
3127 # allele, as a VCF that lists only its sample's variants means it;
3128 # 0 = it has no genotype, as in a file of every site, or of an array's
3129 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
3130 croak "$sub: \"assume_ref\" must be 0 or 1, not " . _what($r{assume_ref})
3131 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
3132 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
3133 croak "$sub: \"min_depth\" must be a whole number, 0 or more, not " . _what($r{min_depth})
3134 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
3135 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
3136 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
3137 croak "$sub: \"build\" must be hg19, b37, hg38 or b38, not " . _what($args->{build})
3138 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
3139 36 my $vcf = $args->{vcf};
3140 36 _vcf_check($sub, 'vcf', $vcf);
3141 33 my $panel = _blood_panel($sub);
3142 # which of the panel's two sets of coordinates the markers are looked for at
3143 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
3144  
3145 32 my @marker = @{ $panel->{markers} };
3146 my @entries = map {
3147 32 my $m = $marker[$_];
3148 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
3149 } 0 .. $#marker;
3150 32 my $gene = $panel->{gene};
3151 32 my ($next, $close) = _vcf_open($sub, 'vcf', $vcf);
3152 32 ▶ my ($dose, $names, $seen, $deleted, $read, $longer) = _located(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3153 32 _blood_type_tally($next, $vcf, $r{min_depth}, \@entries, scalar @marker, @{ $gene }{"$r{build}_chrom", "$r{build}_pos", "$r{build}_end"})
3154 32 });
3155 31 $close->();
3156  
3157 # Each marker the file has no record of: whether it is read as homozygous
3158 # REF, and if not, why not. The file must have been able to hold the
3159 # record: one with nothing on the marker's chromosome was not sequenced or
3160 # not called there, and one with no allele longer than a base on it holds
3161 # SNVs only, and cannot hold ABO's insertion.
3162 31 my (@as_ref, @unknown); # one per marker: 1 = unlisted and read as REF; why an unlisted marker has no genotype, or undef
3163 31 foreach my $k (0 .. $#marker) {
3164 558 ▶ next if $seen->[$k];
Branch: 1 branch
BranchTrueFalseTotal
if $seen->[$k] 144 414 558
3165 414 my $m = $marker[$k];
3166 414 my $chrom = $m->{"$r{build}_chrom"};
3167 414 my $bit = 1 << $chrom;
3168 $unknown[$k] = !$r{assume_ref} ? "the file has no record of $m->{name}, and \"assume_ref\" is 0"
3169 : !($read & $bit) ? "the file has no record on chromosome $chrom"
3170 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
3171 ? "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"
3172 : undef;
3173 414 ▶ $as_ref[$k] = defined $unknown[$k] ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $unknown[$k] ? : 87 327 414
3174 }
3175 31 my @abo_role = sort { $panel->{abo}{$a} <=> $panel->{abo}{$b} } keys %{ $panel->{abo} };
3176 31 my @sites = @{ $panel->{sites} };
3177 31 my $listed = grep { $seen->[$_] } @sites;
3178 # why no RhD type can be told from the sites when a sample has an ALT at
3179 # none of them: undef when it can, which is when the file has a record of
3180 # one, or every one is read as REF
3181 31 ▶ my ($site_unknown) = $listed ? () : grep { defined } map { $unknown[$_] } @sites;
Branch: 1 branch
BranchTrueFalseTotal
$listed ? : 12 19 31
3182  
3183 31 my %out;
3184 31 foreach my $i (0 .. $#{ $names }) {
3185 140 my $name = $names->[$i];
3186 140 my $d = $dose->{$name};
3187 140 my (%n, %copies, @assumed);
3188 140 foreach my $role (@abo_role) {
3189 420 my $k = $panel->{abo}{$role};
3190 420 ▶ $n{$role} = $as_ref[$k] ? 0 : $d->[$k];
Branch: 1 branch
BranchTrueFalseTotal
$as_ref[$k] ? : 17 403 420
3191 420 $copies{ $marker[$k]{name} } = $n{$role};
3192 420 ▶ push @assumed, $marker[$k]{name} if $as_ref[$k];
Branch: 1 branch
BranchTrueFalseTotal
if $as_ref[$k] 17 403 420
3193 }
3194 140 my ($genotype, $phenotype, $lacking) = _abo_type(\%n);
3195 140 my $abo_why;
3196 140 ▶ if (defined $lacking) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lacking) 45 95 140
3197 45 my $k = $panel->{abo}{$lacking};
3198 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
3199 }
3200 140 my $carried = grep { $d->[$_] } @sites;
3201 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
3202 # 'deletion' = from a record of the gene's deletion; 'sites' = from the
3203 # RHD sites; undef = no type
3204 140 my ($rh_genotype, $rh_phenotype, $basis, $rh_why);
3205 140 ▶ if (defined $lost) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $lost) { } 9 131 140
elsif ($carried) { } 69 62 131
elsif (not defined $site_unknown) { } 59 3 62
3206 9 ▶ ($rh_genotype, $rh_phenotype, $basis) = (('DD', 'Dd', 'dd')[$lost], $lost == 2 ? 'negative' : 'positive', 'deletion');
Branch: 1 branch
BranchTrueFalseTotal
$lost == 2 ? : 3 6 9
3207 } elsif ($carried) {
3208 # the second copy cannot be told from SNVs; see the README
3209 69 ($rh_genotype, $rh_phenotype, $basis) = ('D.', 'positive', 'sites');
3210 } elsif (!defined $site_unknown) {
3211 59 ($rh_genotype, $rh_phenotype, $basis) = ('dd', 'negative', 'sites');
3212 } else {
3213 3 $rh_why = $site_unknown;
3214 }
3215 140 ▶ $out{$name} = {
Branch: 2 branches
BranchTrueFalseTotal
defined $phenotype && defined $rh_phenotype ? : 94 46 140
$rh_phenotype eq 'positive' ? : 55 39 94
Condition100%3/3
defined $phenotype and defined $rh_phenotype
!ll&&!rl&&r
45194
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
3216 type => defined $phenotype && defined $rh_phenotype ? $phenotype . ($rh_phenotype eq 'positive' ? '+' : '-') : undef,
3217 abo => {
3218 genotype => $genotype,
3219 phenotype => $phenotype,
3220 markers => \%copies,
3221 assumed_ref => \@assumed,
3222 why => $abo_why,
3223 },
3224 rhesus => {
3225 genotype => $rh_genotype,
3226 phenotype => $rh_phenotype,
3227 basis => $basis,
3228 sites => scalar @sites,
3229 listed => 0 + $listed,
3230 carried => 0 + $carried,
3231 deleted => $lost,
3232 why => $rh_why,
3233 },
3234 };
3235 }
3236 31 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 3 28 31
3237 3 my @assumed = map { $marker[$_]{name} } grep { $as_ref[$_] } map { $panel->{abo}{$_} } @abo_role;
3238 3 my $ref_sites = grep { $as_ref[$_] } @sites;
3239 3 ▶ push @assumed, "$ref_sites of the " . scalar(@sites) . ' RHD sites' if $ref_sites;
Branch: 1 branch
BranchTrueFalseTotal
if $ref_sites 2 1 3
3240 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
3241 }
3242 31 my %chroms = map { $_->{"$r{build}_chrom"} => 1 } @marker;
3243 1 carp "$sub: \"vcf\" $vcf has no record on chromosome " . join(' or ', sort { $a <=> $b } keys %chroms)
3244 . ", matched by position on $r{build}, so no blood type can be told; check that it is the build the file is on"
3245 31 ▶ unless grep { $read & (1 << $_) } keys %chroms;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$read & 1 << $_;} keys %chroms 1 30 31
3246 31 \%out;
3247 }
3248  
3249 # ---- PDB structures
3250 #
3251 # pdb_search asks two RCSB APIs, as their documentation at
3252 # https://search.rcsb.org/ and https://data.rcsb.org/ described them on
3253 # 2026-10-21: the search API finds the polymer entities whose sequence
3254 # matches, by MMseqs2, and the data API's GraphQL says what each one's
3255 # structure is.
3256  
3257 36 my $Rcsb_search = 'https://search.rcsb.org/rcsbsearch/v2/query';
3258 36 my $Rcsb_data = 'https://data.rcsb.org/graphql';
3259 # The search API's own limit on "rows", which it refuses past with "numeric
3260 # instance is greater than the required maximum (maximum: 10000" (2026-10-21).
3261 36 my $Rcsb_rows = 10000;
3262 # How many entities each GraphQL request asks about. 500 came back in one
3263 # request in 2.45 s, 1.6 MB of JSON, on 2026-10-21, so 200 leaves headroom
3264 # for entities with more annotations than those had.
3265 36 my $Rcsb_batch = 200;
3266 36 my $Rcsb_entities = <<'GRAPHQL';
3267 query ($ids: [String!]!) { polymer_entities(entity_ids: $ids) {
3268 rcsb_id
3269 entity_poly { rcsb_entity_polymer_type pdbx_strand_id }
3270 rcsb_polymer_entity { pdbx_description }
3271 rcsb_entity_source_organism { scientific_name ncbi_taxonomy_id }
3272 rcsb_polymer_entity_container_identifiers { reference_sequence_identifiers { database_name database_accession } }
3273 rcsb_polymer_entity_annotation { type annotation_id name }
3274 entry {
3275 struct { title }
3276 rcsb_entry_info { experimental_method resolution_combined polymer_composition structure_determination_methodology }
3277 rcsb_accession_info { deposit_date initial_release_date }
3278 rcsb_ma_qa_metric_global { ma_qa_metric_global { type value } }
3279 assemblies { rcsb_struct_symmetry { kind oligomeric_state stoichiometry symbol } }
3280 nonpolymer_entities { nonpolymer_comp { chem_comp { id name } } }
3281 }
3282 } }
3283 GRAPHQL
3284  
3285 # $body POSTed to $url as JSON, for $sub, and the JSON it answers with,
3286 # decoded; undef when it answers 204, which is how the search API says that
3287 # nothing matched. A failure dies with RCSB's own "message" where it sent one.
3288 # The tests replace this sub, so that they run with no network.
3289 7 ▶sub _rcsb_post {
Subroutine _rcsb_post: called CC=8 SCAR=20.8
3290 7 my ($sub, $url, $body, $timeout) = @_;
3291 7 require HTTP::Tiny;
3292 7 require JSON::MaybeXS;
3293 # verify_SSL is given, since it is the default only from HTTP::Tiny 0.083
3294 7 my $http = HTTP::Tiny->new(agent => "Cn-Bioinf/$VERSION ", timeout => $timeout, verify_SSL => 1);
3295 7 my ($ssl, $why) = $http->can_ssl;
3296 7 ▶ unless ($ssl) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ssl) 1 6 7
3297 1 $why =~ s/\s+\z//;
3298 1 croak "$sub: can't reach RCSB, which needs HTTPS: $why";
3299 }
3300 6 my $res = $http->post($url, {
3301 headers => { 'Content-Type' => 'application/json', Accept => 'application/json' },
3302 content => JSON::MaybeXS::encode_json($body),
3303 });
3304 6 ▶ return undef if $res->{status} == 204;
Branch: 1 branch
BranchTrueFalseTotal
if $res->{"status"} == 204 1 5 6
3305 5 my $json = eval { JSON::MaybeXS::decode_json($res->{content}) };
3306 5 ▶ unless ($res->{success}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->{"success"}) 3 2 5
3307 # 599 is HTTP::Tiny's own status, for a request that got no answer at
3308 # all, and its content says why
3309 my $msg = $res->{status} == 599 ? $res->{content}
3310 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
3311 3 $msg =~ s/\s+\z//;
3312 3 croak "$sub: $url answered $res->{status}: $msg";
3313 }
3314 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
3315 1 $json;
3316 }
3317  
3318 # The alignment of one search hit, from the "match_context" RCSB gave it,
3319 # under the names get_best_alignment_hit gives a BLAST hsp. RCSB's
3320 # sequence_identity is truncated to 3 places, so the identity is counted from
3321 # the aligned sequences instead, which is how BLAST counts it.
3322 45 ▶sub _pdb_alignment {
Subroutine _pdb_alignment: called CC=12 SCAR=25.2
3323 45 my ($m) = @_;
3324 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
3325 45 my ($identity, $gaps) = (0, 0);
3326 45 foreach my $i (0 .. length($q) - 1) {
3327 6417 my ($x, $y) = (substr($q, $i, 1), substr($h, $i, 1));
3328 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
3329 }
3330 return {
3331 evalue => $m->{evalue},
3332 bit_score => $m->{bitscore},
3333 align_len => $m->{alignment_length},
3334 identity => $identity,
3335 # undef where RCSB gives no length to divide by, rather than dying of it
3336 pident => ($m->{alignment_length} // 0) > 0 ? 100 * $identity / $m->{alignment_length} : undef,
3337 mismatches => $m->{mismatches},
3338 gaps => $gaps,
3339 gap_opens => $m->{gaps_opened},
3340 query_from => $m->{query_beg},
3341 query_to => $m->{query_end},
3342 query_len => $m->{query_length},
3343 query_cover => defined $m->{query_beg} && defined $m->{query_end} && ($m->{query_length} // 0) > 0
3344 ? 100 * ($m->{query_end} - $m->{query_beg} + 1) / $m->{query_length} : undef,
3345 hit_from => $m->{subject_beg},
3346 hit_to => $m->{subject_end},
3347 hit_len => $m->{subject_length},
3348 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
3349 hseq => $h,
3350 };
3351 }
3352  
3353 # What the data API said of one polymer entity, $e, which is undef when it
3354 # said nothing, as the fields pdb_search returns: every key is there either
3355 # way, undef or an empty array when RCSB has no value.
3356 40 ▶sub _pdb_structure {
Subroutine _pdb_structure: called CC=32 SCAR=35.0
3357 40 my ($e) = @_;
3358 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
3359 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
3360 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
3361 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
3362 # The global symmetry of the first assembly, which is the one the
3363 # depositors gave first, and the one RCSB's own page shows.
3364 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
3365 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
3366 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
3367 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
3368 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
3369 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
3370 40 my (%seen, @ligands);
3371 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
3372 62 ▶ push @ligands, { id => $c->{id}, name => $c->{name} } unless $seen{ $c->{id} }++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$c->{"id"}}++ 62 0 62
3373 }
3374 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
3375 return {
3376 title => ($entry->{struct} // {})->{title},
3377 description => ($e->{rcsb_polymer_entity} // {})->{pdbx_description},
3378 method => $info->{experimental_method},
3379 methodology => $info->{structure_determination_methodology},
3380 resolution => ($info->{resolution_combined} // [])->[0],
3381 plddt => $plddt,
3382 polymer_type => ($e->{entity_poly} // {})->{rcsb_entity_polymer_type},
3383 polymer_composition => $info->{polymer_composition},
3384 oligomeric_state => $sym->{oligomeric_state},
3385 39 ▶ stoichiometry => $sym->{stoichiometry} ? join('', @{ $sym->{stoichiometry} }) : undef,
Branch: 1 branch
BranchTrueFalseTotal
defined $chains ? : 39 1 40
3386 symmetry => $sym->{symbol},
3387 chains => [defined $chains ? split(/,/, $chains) : ()],
3388 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
3389 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
3390 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
3391 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
3392 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
3393 ligands => \@ligands,
3394 deposited => defined $dates->{deposit_date} ? substr($dates->{deposit_date}, 0, 10) : undef,
3395 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
3396 };
3397 }
3398  
3399 # How a hit's structure was determined, as the report shows it: RCSB's
3400 # experimental method, which a computed model has none of. Its values, and
3401 # those of the methodology, are the enums of rcsb_entry_info in
3402 # https://data.rcsb.org/rest/v1/schema/entry (checked 2026-10-21).
3403 25 ▶sub _pdb_method {
Subroutine _pdb_method: called CC=4 SCAR=14.3
3404 25 my ($h) = @_;
3405 25 ▶ return $h->{method} if defined $h->{method};
Branch: 1 branch
BranchTrueFalseTotal
if defined $h->{"method"} 20 5 25
3406 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
3407 }
3408  
3409 # $text, a number as perl wrote it, with an exponent of two digits where two
3410 # are enough, as C99's printf writes one. The C runtime under Strawberry Perl
3411 # 5.24.4 writes three, so pdb_search's report read "1.6e-089" there (CPAN
3412 # Testers report 620bc624-ddea-11f1-b231-87fe50e89311, 2026-11-11) and
3413 # "1.6e-89" everywhere else. An exponent that needs three digits keeps them.
3414 41 ▶sub _two_digit_exponent {
Subroutine _two_digit_exponent: called CC=1 SCAR=0.0
3415 41 my ($text) = @_;
3416 41 $text =~ s/([eE][-+])0(\d\d)\z/$1$2/;
3417 41 $text;
3418 }
3419  
3420 # pdb_search's report on @$hits, $total of which RCSB found: one line a hit,
3421 # best first.
3422 6 ▶sub _pdb_report {
Subroutine _pdb_report: called CC=15 SCAR=27.3
3423 6 my ($r, $hits, $total) = @_;
3424 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
3425 . " in RCSB's " . ($r->{computed} ? 'PDB and computed models' : 'PDB')
3426 . " for a $r->{len}-residue $r->{type} sequence, at an E-value below " . _two_digit_exponent("$r->{evalue}")
3427 6 ▶ . ($r->{identity} > 0 ? " and $r->{identity}% identity or more" : '') . "\n";
Branch: 1 branch
BranchTrueFalseTotal
$total == 0 ? : 1 5 6
3428 6 ▶ return $text unless @{ $hits };
Branch: 1 branch
BranchTrueFalseTotal
unless @{$hits;} 1 5 6
3429 5 my @head = ('id', 'method', 'resolution', 'identity', 'cover', 'evalue', 'bits', 'oligomer', 'description');
3430 my @rows = map {
3431 [$_->{id}, _pdb_method($_),
3432 defined $_->{resolution} ? sprintf('%.2f A', $_->{resolution}) : defined $_->{plddt} ? "pLDDT $_->{plddt}" : '-',
3433 defined $_->{pident} ? sprintf('%.1f%%', $_->{pident}) : '-', defined $_->{query_cover} ? sprintf('%.0f%%', $_->{query_cover}) : '-',
3434 _two_digit_exponent(sprintf('%.2g', $_->{evalue})), $_->{bit_score},
3435 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
3436 5 } @{ $hits };
3437 5 my @w = map { length $head[$_] } 0 .. $#head;
3438 5 foreach my $row (@rows) {
3439 25 foreach my $i (0 .. $#head) {
3440 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
3441 }
3442 }
3443 # left-aligned text, right-aligned numbers; the last column is not padded
3444 5 my %left = map { $_ => 1 } 0, 1, 7, 8;
3445 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
3446 5 $text . $line->(@head) . join('', map { $line->(@{ $_ }) } @rows);
3447 }
3448  
3449 32 ▶sub pdb_search {
Subroutine pdb_search: called CC=72 SCAR=44.9
Pod documented
3450 32 my $sub = 'pdb_search';
3451 32 my $args = _args(\@_, $sub, [qw(seq)], [qw(computed evalue identity max_hits report timeout type)]);
3452 30 my %r;
3453 # The cutoffs are made numbers with 0 +, since JSON::XS writes a string as
3454 # a string, and RCSB refuses a string where its schema wants a number.
3455 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
3456 croak "$sub: \"evalue\" must be a number above 0, not " . _what($r{evalue})
3457 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
3458 28 $r{evalue} = 0 + $r{evalue};
3459 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
3460 croak "$sub: \"identity\" must be a percentage, from 0 to 100, not " . _what($r{identity})
3461 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
3462 26 $r{identity} = 0 + $r{identity};
3463 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
3464 croak "$sub: \"max_hits\" must be a whole number from 1 to $Rcsb_rows, RCSB's limit, not " . _what($r{max_hits})
3465 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
3466 23 $r{max_hits} = 0 + $r{max_hits};
3467 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
3468 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
3469 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
3470 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
3471 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
3472 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
3473 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
3474 croak "$sub: \"timeout\" must be a number of seconds above 0, not " . _what($r{timeout})
3475 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
3476  
3477 19 my $seq = $args->{seq};
3478 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
3479 # A sequence copied out of a FASTA file keeps its line breaks, and one
3480 # translated from DNA can end in a stop; RCSB refuses both, and lower case.
3481 18 $seq =~ s/\s+//g;
3482 18 $seq = uc $seq;
3483 18 $seq =~ s/\*\z//;
3484 18 ▶ croak "$sub: \"seq\" has no residues" unless length $seq;
Branch: 1 branch
BranchTrueFalseTotal
unless length $seq 1 17 18
3485 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
3486 15 $r{len} = length $seq;
3487  
3488 my $found = _rcsb_post($sub, $Rcsb_search, {
3489 query => { type => 'terminal', service => 'sequence', parameters => {
3490 evalue_cutoff => $r{evalue}, identity_cutoff => $r{identity} / 100, sequence_type => $r{type}, value => $seq,
3491 } },
3492 request_options => {
3493 results_verbosity => 'verbose', # which gives each hit's alignment
3494 results_content_type => [$r{computed} ? ('experimental', 'computational') : 'experimental'],
3495 scoring_strategy => 'sequence',
3496 paginate => { start => 0, rows => $r{max_hits} },
3497 },
3498 return_type => 'polymer_entity',
3499 15 ▶ }, $r{timeout});
Branch: 1 branch
BranchTrueFalseTotal
$r{'computed'} ? : 1 14 15
3500 14 ▶ if ($found) {
Branch: 1 branch
BranchTrueFalseTotal
if ($found) 13 1 14
3501 13 my $not = "$sub: $Rcsb_search answered with JSON that isn't a search result: ";
3502 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
3503 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
3504 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
3505 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
3506 }
3507 10 ▶ my $total = $found ? $found->{total_count} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$found ? : 9 1 10
3508 10 my @hits;
3509 10 ▶ foreach my $res (@{ $found ? $found->{result_set} : [] }) {
Branch: 1 branch
BranchTrueFalseTotal
$found ? : 9 1 10
3510 45 my $best; # undef until a match is seen
3511 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
3512 # none of the 1382 hits for human haemoglobin alpha had more than
3513 # one match on 2026-10-21, but the format allows it
3514 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
3515 }
3516 45 ▶ croak "$sub: RCSB gave no alignment for $res->{identifier}" unless defined $best;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $best 0 45 45
3517 # An identifier is entry_entity: 1BZ1_1, or AF_AFP69905F1_1 for a computed model
3518 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
3519 or croak "$sub: RCSB returned \"$res->{identifier}\", which isn't an entry_entity identifier";
3520 push @hits, { id => $res->{identifier}, entry => $entry, entity => $entity,
3521 45 url => "https://www.rcsb.org/structure/$entry", %{ _pdb_alignment($best) } };
3522 }
3523  
3524 10 my %entity;
3525 10 ▶ for (my $i = 0; $i < @hits; $i += $Rcsb_batch) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @hits) 9 9 18
3526 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
3527 9 my $data = _rcsb_post($sub, $Rcsb_data, { query => $Rcsb_entities, variables => { ids => \@ids } }, $r{timeout});
3528 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
3529 9 ▶ unless (ref $list eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $list eq "ARRAY") 1 8 9
3530 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
3531 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
3532 }
3533 8 $entity{ $_->{rcsb_id} } = $_ foreach grep { ref $_ eq 'HASH' } @{ $list };
3534 }
3535 9 foreach my $h (@hits) {
3536 # the search index can be ahead of the data API for a new release
3537 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
3538 40 %{ $h } = (%{ $h }, %{ _pdb_structure($entity{ $h->{id} }) });
3539 }
3540 # Best first, as get_best_alignment_hit sorts on "evalue": RCSB rounds a
3541 # strong E-value to 0, so the bit score breaks ties, and then RCSB's order.
3542 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
3543 9 @hits = @hits[@order];
3544 9 ▶ if ($r{report}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r{"report"}) 6 3 9
3545 6 my $text = _pdb_report(\%r, \@hits, $total);
3546 # RCSB's text is characters, and can hold some above 255 (a Greek
3547 # letter in a title), which print would warn of as a "Wide character",
3548 # fatally in a caller under FATAL warnings, unless STDOUT encodes.
3549 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
3550 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
3551 }
3552 9 ▶ wantarray ? (\@hits, $total) : \@hits;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 9 0 9
3553 }
3554  
3555 # ---- alignment plots and tables
3556  
3557 # Dies unless $n, given to $sub as $what, is a 1-based residue number. Without
3558 # this, 0 and the negative numbers index @col from its end in plot_msa and
3559 # clustal_view_residues, and silently mean the last residues.
3560 14 ▶sub _residue_number {
Subroutine _residue_number: called CC=4 SCAR=14.3
3561 14 my ($sub, $what, $n) = @_;
3562 14 ▶ 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 7 14
defined $n ? : 7 0 7
Condition66%2/3
defined $n and $n =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
077
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
3563 unless defined $n && $n =~ /\A[1-9][0-9]*\z/;
3564 }
3565  
3566 # "fasta" -- a FASTA file name or a hash ref of name => sequence -- written to a
3567 # temporary FASTA file with its gaps stripped, so that an input that is already
3568 # aligned is aligned afresh. clustalo's --dealign does the same, but prints a
3569 # "FORCED DEBUG" warning about them first; blastp would take a gap for a residue.
3570 # Returns that file and the sequence names in input order (sorted for a hash).
3571 # With $numbered, each sequence is written under its number in that order, "s1",
3572 # "s2" and so on, rather than its name, for clustalo: it cuts a name at its
3573 # first space in the guide tree and writes "(),:" in one unquoted, which drew 4
3574 # sequences as 5 tips up to 2026-10-17. _unnumber_fasta and _unnumber_newick put
3575 # the names back. Dies naming $sub, whose "fasta" it is, for a sequence that is
3576 # not a string or that has no residues once its gaps are gone, which clustalo
3577 # and blastp would otherwise be given.
3578 7 ▶sub _ungapped_fasta {
Subroutine _ungapped_fasta: called CC=8 SCAR=21.0
3579 7 my ($sub, $fasta, $numbered) = @_;
3580 7 my ($seqs, @names);
3581 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
3582 6 $seqs = $fasta;
3583 6 @names = sort keys %{ $seqs };
3584 } elsif (ref $fasta eq '') {
3585 0 my $order;
3586 0 ($seqs, $order) = _fasta_ordered($fasta);
3587 0 @names = @{ $order };
3588 } else {
3589 1 croak "$sub: \"fasta\" must be a FASTA file name or a hash ref of name => sequence, not " . _what($fasta);
3590 }
3591 6 ▶ my @written = $numbered ? map { "s$_" } 1 .. @names : @names;
Branch: 1 branch
BranchTrueFalseTotal
$numbered ? : 5 1 6
3592 6 my %ungapped;
3593 6 foreach my $i (0 .. $#names) {
3594 12 my $s = $seqs->{ $names[$i] };
3595 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
3596 10 $s =~ tr/-.//d;
3597 10 ▶ croak "$sub: \"fasta\" sequence \"$names[$i]\" has no residues" if $s eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $s eq "" 3 7 10
3598 7 $ungapped{ $written[$i] } = $s;
3599 }
3600 1 (_fasta_file('_ungapped_fasta', \%ungapped, _tmp('.fa'), \@written, 80), \@names);
3601 }
3602  
3603 # The name that clustalo's "s<n>" in $file stands for, from @$names, the list
3604 # _ungapped_fasta numbered.
3605 0 ▶sub _unnumber {
Subroutine _unnumber: not called CC=3 SCAR=24.8
3606 0 my ($id, $names, $file) = @_;
3607 0 croak "_unnumber: clustalo wrote \"$id\" in $file, which isn't one of the s1 to s" . scalar(@{ $names }) . ' it was given'
3608 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
3609 0 $names->[$1 - 1];
3610 }
3611  
3612 # The alignment clustalo wrote to $file under _ungapped_fasta's numbers,
3613 # rewritten in place under the names in @$names, as UTF-8, in clustalo's order
3614 # and 60-column lines. Returns the aligned sequences as a hash ref keyed by
3615 # those names as perl was given them, which a name's UTF-8 may not equal.
3616 0 ▶sub _unnumber_fasta {
Subroutine _unnumber_fasta: not called CC=2 SCAR=17.9
3617 0 my ($file, $names) = @_;
3618 0 my ($numbered, $ids) = _fasta_ordered($file);
3619 0 my (%aln, %utf8);
3620 0 foreach my $id (@{ $ids }) {
3621 0 my $name = _unnumber($id, $names, $file);
3622 0 $aln{$name} = $utf8{ _utf8($name) } = $numbered->{$id};
3623 }
3624 0 _fasta_file('_unnumber_fasta', \%utf8, $file, [map { _utf8(_unnumber($_, $names, $file)) } @{ $ids }], 60);
3625 0 \%aln;
3626 }
3627  
3628 # The guide tree clustalo wrote to $file under _ungapped_fasta's numbers,
3629 # rewritten in place under the names in @$names, as UTF-8. A name holding
3630 # whitespace or any of "()[]':;," is quoted as newick quotes one: in single
3631 # quotes, each of its own doubled.
3632 0 ▶sub _unnumber_newick {
Subroutine _unnumber_newick: not called CC=6 SCAR=37.4
3633 0 my ($file, $names) = @_;
3634 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
3635 0 my $tree = do { local $/; <$fh> };
3636 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
3637 0 $tree =~ s{(?<=[(,\s])(s[0-9]+)(?=\s*[:,);])}{
3638 0 my $name = _utf8(_unnumber($1, $names, $file));
3639 0 ▶ $name =~ /[\s()\[\]':;,]/ ? "'" . join("''", split /'/, $name, -1) . "'" : $name;
Branch: 1 branch
BranchTrueFalseTotal
$name =~ /[\s()\[\]':;,]/ ? : 0 0 0
3640 }ge;
3641 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
3642 0 print {$fh} $tree;
3643 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
3644 }
3645  
3646 # Aligns "fasta" with clustalo for $sub. The alignment goes to "msa_file" and
3647 # the guide tree to "tree_file" when those are given, and to temporary files
3648 # otherwise; the tree is not asked for at all unless it is kept or $want_tree.
3649 # Returns the hash ref of files to report (the alignment always, the tree only
3650 # when it was named), the tree's file, the sequence names in input order
3651 # (sorted for a hash), an array ref of the clustalo command as it was run, with
3652 # the ungapped FASTA it read as its "--in", and the aligned sequences as a hash
3653 # ref keyed by those names; or nothing, after a warning, for fewer than 2
3654 # sequences. clustalo is given the sequences numbered, and the alignment and
3655 # tree it writes get their names back.
3656 6 ▶sub _align {
Subroutine _align: called CC=11 SCAR=38.2
3657 6 my ($args, $sub, $want_tree) = @_;
3658 6 my ($in, $names) = _ungapped_fasta($sub, $args->{fasta}, 1);
3659 1 ▶ if (@{ $names } < 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$names;} < 2) 0 1 1
3660 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
3661 0 return;
3662 }
3663 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
3664 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
3665 1 ▶ $r{'tree_file'} = $tree if defined $args->{'tree_file'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"tree_file"} 0 1 1
3666 my @cmd = (_alien($sub)->clustalo, '--in', $in, '--out', $r{'msa_file'}, '--outfmt=fa', '--force',
3667 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
3668 0 _run(@cmd);
3669 0 my $aln = _unnumber_fasta($r{'msa_file'}, $names);
3670 0 ▶ _unnumber_newick($tree, $names) if defined $tree;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tree 0 0 0
3671 0 (\%r, $tree, $names, \@cmd, $aln);
3672 }
3673  
3674 27 ▶sub plot_msa {
Subroutine plot_msa: called CC=29 SCAR=56.5
Pod documented
3675 27 my $sub = 'plot_msa';
3676 27 my $args = _args(\@_, $sub, [qw(fasta filename)], [qw(active_site_aa clustal_args execute fh labels msa_file order query threads title
3677 tooltips tree_file xlabel ylabel)]);
3678 27 _refs($sub, $args, 'ARRAY', qw(clustal_args order));
3679 25 _refs($sub, $args, 'HASH', 'labels');
3680 24 _file_names($sub, $args, qw(filename msa_file tree_file));
3681 20 _threads($sub, $args);
3682 18 my $drawing = _drawing($sub, $args);
3683 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
3684 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
3685 croak "$sub: \"tooltips\" needs an SVG \"filename\", the only format that carries them, not \"$args->{filename}\""
3686 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
3687 11 my $sites = $args->{'active_site_aa'};
3688 11 ▶ if (defined $sites) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sites) 5 6 11
3689 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
3690 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
3691 4 _residue_number($sub, "active site $_", $sites->{$_}) foreach sort keys %{ $sites };
3692 }
3693 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
3694 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
3695 0 my @unknown = grep { !defined $aln->{$_} } @order;
3696 0 ▶ croak "$sub: \"order\" names sequences that aren't in the alignment: @unknown" if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 0 0 0
3697 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
3698 # Each name as msa_plot.py is to show it, in UTF-8, which is what it reads.
3699 # Up to 2026-10-17 the name was written as perl held it, Latin-1 or UTF-8,
3700 # and Python died on the Latin-1.
3701 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
3702 # Two sequences shown under one label would be one row of the image, fed
3703 # two deflines.
3704 0 my %by_label;
3705 0 push @{ $by_label{ $shown_as{$_} } }, $_ foreach @order;
3706 0 foreach my $label (sort keys %by_label) {
3707 0 croak "$sub: " . join(', ', map { "\"$_\"" } @{ $by_label{$label} }) . " would all be drawn as \"$label\""
3708 0 ▶ if @{ $by_label{$label} } > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @{$by_label{$label};} > 1 0 0 0
3709 }
3710 0 my @segments;
3711 0 ▶ if (defined $sites) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sites) 0 0 0
3712 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
3713 # 1-based residue number => 0-based alignment column
3714 0 my (@col, %sites);
3715 0 ▶ while ($q =~ /[^-]/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($q =~ /[^-]/g) 0 0 0
3716 0 push @col, pos($q) - 1;
3717 }
3718 0 foreach my $label (sort keys %{ $sites }) {
3719 0 my $n = $sites->{$label};
3720 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
3721 }
3722 0 @segments = ('--s', _json_text({ map { _chars($_) => 0 + $sites{$_} } keys %sites }));
3723 }
3724 0 my %shown = map { $shown_as{$_} => $aln->{$_} } @order;
3725 0 my $fa = _fasta_file($sub, \%shown, _tmp('.fa'), [@shown_as{@order}], 0);
3726 $r->{'python_file'} = _draw($sub, $drawing, '--f', $fa, '--o', $args->{filename}, '--c', _creator($sub), '--quiet',
3727 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
3728 (defined $args->{title} ? ('--t', $args->{title}) : ()),
3729 (defined $args->{xlabel} ? ('--x', $args->{xlabel}) : ()),
3730 (defined $args->{ylabel} ? ('--y', $args->{ylabel}) : ()), @segments,
3731 # the tooltips name each sequence as perl was given it, not by its label, which may be mathtext
3732 0 ($tooltips ? ('--tips', _json_text([map { _chars($_) } @order])) : ()));
3733 0 ▶ _wrote($args->{filename}, 43, $drawing->{execute} ? 'wrote' : 'will write'); # yellow
Branch: 1 branch
BranchTrueFalseTotal
$drawing->{'execute'} ? : 0 0 0
3734 0 $r->{filename} = $args->{filename};
3735 0 $r;
3736 }
3737  
3738 # "path (SHA-256 hex)" of an existing file, for the provenance of an image.
3739 1 ▶sub _file_id {
Subroutine _file_id: called CC=1 SCAR=0.0
3740 1 my ($file) = @_;
3741 1 require Digest::SHA;
3742 1 require File::Spec;
3743 1 File::Spec->rel2abs($file) . ' (SHA-256 ' . Digest::SHA->new(256)->addfile($file, 'b')->hexdigest . ')';
3744 }
3745  
3746 # "fasta" as an image's Creator names it: a file by its path and digest, a hash
3747 # ref by its size, since its contents were never on disk until
3748 # _ungapped_fasta wrote them.
3749 0 ▶sub _fasta_id {
Subroutine _fasta_id: not called CC=2 SCAR=17.9
3750 0 my ($fasta, $n) = @_;
3751 0 ▶ ref $fasta ? "a hash ref of $n sequences" : 'the FASTA file ' . _file_id($fasta) . " of $n sequences";
Branch: 1 branch
BranchTrueFalseTotal
ref $fasta ? : 0 0 0
3752 }
3753  
3754 # The files named in @keys of $args that were written and kept beside an
3755 # image, as a clause of its Creator, or nothing when none was.
3756 0 ▶sub _kept {
Subroutine _kept: not called CC=4 SCAR=30.0
3757 0 my ($args, @keys) = @_;
3758 0 require File::Spec;
3759 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
3760 0 ▶ @kept ? 'kept with it: ' . join(', ', @kept) : ();
Branch: 1 branch
BranchTrueFalseTotal
@kept ? : 0 0 0
3761 }
3762  
3763 # A command as it could be pasted into a shell, for an image's Creator.
3764 0 ▶sub _cmd_text { join ' ', map { /[^\w\/.,:=+-]/ ? "'$_'" : $_ } @_ }
Subroutine _cmd_text: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
m[[^\w/.,:=+-]] ? : 0 0 0
3765  
3766 # How _align made an alignment, as one clause of an image's Creator: what
3767 # Clustal Omega read, which version ran, what it wrote and the command. $cmd,
3768 # $names and $msa are what _align returned.
3769 0 ▶sub _align_provenance {
Subroutine _align_provenance: not called CC=1 SCAR=6.9
3770 0 my ($args, $sub, $cmd, $names, $msa) = @_;
3771 0 my $alien = _alien($sub);
3772 # $cmd->[2] is clustalo's "--in", the ungapped copy _ungapped_fasta wrote
3773 0 'from ' . _fasta_id($args->{fasta}, scalar @{ $names }) . ', written with its gaps stripped and the sequences numbered s1 to s'
3774 0 . scalar(@{ $names }) . ' to ' . _file_id($cmd->[2]) . ', which Clustal Omega ' . $alien->versions->{clustalo}
3775 . " from Alien::Bioinf $Alien::Bioinf::VERSION aligned into " . _file_id($msa) . ' (with the names put back), run as: '
3776 0 . _cmd_text(@{ $cmd });
3777 }
3778  
3779 9 ▶sub plot_phylo {
Subroutine plot_phylo: called CC=13 SCAR=48.2
Pod documented
3780 9 my $sub = 'plot_phylo';
3781 9 my $args = _args(\@_, $sub, [], [qw(clustal_args execute fasta fh labels msa_file output_file threads title tree_file)]);
3782 9 _refs($sub, $args, 'ARRAY', 'clustal_args');
3783 8 _refs($sub, $args, 'HASH', 'labels');
3784 7 _file_names($sub, $args, qw(msa_file output_file tree_file));
3785 6 _threads($sub, $args);
3786 5 my $drawing = _drawing($sub, $args);
3787 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
3788 0 my ($r, $tree, $names, $cmd);
3789 0 ▶ if (defined $args->{fasta}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args->{'fasta'}) { } 0 0 0
3790 0 ▶ ($r, $tree, $names, $cmd) = _align($args, $sub, 1) or return {};
Branch: 1 branch
BranchTrueFalseTotal
() = _align($args, $sub, 1) or return {} 0 0 0
3791 } else {
3792 # no alignment to make, so "tree_file" is the tree to draw, not where to keep one
3793 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
3794 0 my @moot = grep { defined $args->{$_} } qw(clustal_args msa_file threads);
3795 0 ▶ croak "$sub: was given " . join(', ', map { "\"$_\"" } @moot) . ' but no "fasta" to align' if @moot;
Branch: 1 branch
BranchTrueFalseTotal
if @moot 0 0 0
3796 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
3797 0 $r = { 'tree_file' => $tree };
3798 }
3799 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
3800 my @prov = defined $cmd
3801 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
3802 _kept($args, qw(msa_file tree_file)))
3803 : ('from the newick file ' . _file_id($tree));
3804 # the tips are named in UTF-8 by _unnumber_newick, which msa_plot.py decodes
3805 $r->{'python_file'} = _draw($sub, $drawing, '--tree', $tree, '--o', $args->{'output_file'}, '--c', _creator($sub), '--quiet',
3806 0 ▶ '--p', _json_text([map { _chars($_) } @prov]),
Branch: 2 branches
BranchTrueFalseTotal
defined $args->{'title'} ? : 0 0 0
%{$labels;} ? : 0 0 0
3807 (defined $args->{title} ? ('--t', $args->{title}) : ()),
3808 0 (%{ $labels } ? ('--l', _json_text({ map { _chars($_) => _chars($labels->{$_}) } keys %{ $labels } })) : ()));
3809 0 $r->{'output_file'} = $args->{'output_file'};
3810 0 ▶ _wrote($args->{output_file}, 43, $drawing->{execute} ? 'wrote' : 'will write'); # yellow
Branch: 1 branch
BranchTrueFalseTotal
$drawing->{'execute'} ? : 0 0 0
3811 0 $r;
3812 }
3813  
3814 18 ▶sub msa_quality_table {
Subroutine msa_quality_table: called CC=89 SCAR=66.3
Pod documented
3815 18 my $sub = 'msa_quality_table';
3816 18 my $args = _args(\@_, $sub, ['filename'], [qw(alignment_json cb_label cb_max cb_min cblogscale default_undefined fasta
3817 logscale_add metric msa_file normalize order show_numbers title unaligned_fa)]);
3818 18 _refs($sub, $args, 'ARRAY', 'order');
3819 17 _file_names($sub, $args, qw(filename msa_file));
3820 # Each is added to, divided by or compared with a score. Up to 2026-11-10
3821 # one that was not a number only warned "isn't numeric", and was drawn as 0.
3822 16 foreach my $k (qw(cb_max cb_min default_undefined logscale_add normalize)) {
3823 croak "$sub: \"$k\" must be a number, not " . _what($args->{$k})
3824 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
3825 }
3826 11 my %metric = map { $_ => 1 } qw(num bit_score score evalue identity positive align_len);
3827 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
3828 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
3829 # "unaligned_fa" is the old name for "fasta"
3830 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
3831 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
3832 # All-against-all blastp of the sequences: given as the parsed report, read
3833 # from "alignment_json", or -- when that file does not exist yet, or none is
3834 # named -- made by running blastp on "fasta", and kept in "alignment_json"
3835 # for next time if that is named.
3836 11 my $aj = $args->{'alignment_json'};
3837 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
3838 10 my ($blast, $prov);
3839 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
3840 7 $blast = $aj;
3841 7 $prov = 'from a BLAST report given as a hash ref';
3842 ▶ } 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
3843 2 $blast = _json_file($sub, $aj);
3844 1 $prov = 'from the BLAST report ' . _file_id($aj);
3845 } else {
3846 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
3847 unless defined $fasta;
3848 1 my ($in, $names) = _ungapped_fasta($sub, $fasta);
3849 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
3850 0 my $alien = _alien($sub);
3851 0 my @cmd = ($alien->blast('blastp'), '-query', $in, '-subject', $in, '-out', $aj, '-outfmt', 15);
3852 0 _run(@cmd);
3853 0 $blast = _json_file($sub, $aj);
3854 0 $prov = 'from ' . _fasta_id($fasta, scalar @{ $names }) . ', written with its gaps stripped to ' . _file_id($in)
3855 0 . ', which blastp ' . $alien->versions->{blast} . " from Alien::Bioinf $Alien::Bioinf::VERSION compared all against all into "
3856 . _file_id($aj) . ', run as: ' . _cmd_text(@cmd);
3857 0 $prov = join '; ', $prov, _kept($args, 'alignment_json');
3858 }
3859 croak "$sub: \"alignment_json\" isn't a BLAST report in JSON (-outfmt 15): it has no \"BlastOutput2\" array"
3860 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
3861 # The report's shape is checked as it is read. Up to 2026-11-10 a report
3862 # that was not an object, or "hits" that was not an array, died with perl's
3863 # "Can't use string as a HASH ref" or "Not an ARRAY reference", naming no
3864 # function. A report with no bl2seq, as a search of a database has, holds no
3865 # pair, and is left for the message below.
3866 7 my (%data, $max);
3867 7 my %known; # every query the report names, whether or not it has a hit
3868 7 foreach my $i (0 .. $#{ $blast->{BlastOutput2} }) {
3869 11 my $query = $blast->{BlastOutput2}[$i];
3870 11 my $where = 'report ' . ($i + 1) . ' of "alignment_json"';
3871 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
3872 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
3873 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
3874 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
3875 9 foreach my $hit_list (@{ $lists }) {
3876 croak "$sub: $where has a comparison that isn't one, which is an object with a \"query_title\" and a \"hits\" array"
3877 unless ref $hit_list eq 'HASH' && defined $hit_list->{query_title} && !ref $hit_list->{query_title}
3878 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
3879 8 $known{ $hit_list->{query_title} } = 1;
3880 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
3881 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"
3882 unless ref $hit eq 'HASH' && ref($hit->{description} // []) eq 'ARRAY' && ref($hit->{hsps} // []) eq 'ARRAY'
3883 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
3884 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
3885 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
3886 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
3887 12 $data{ $hit_list->{query_title} }{ $first->{title} } = $value;
3888 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
3889 }
3890 }
3891 }
3892 3 ▶ croak "$sub: no \"$metric\" values in the BLAST report" unless defined $max;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $max 0 3 3
3893 # Up to 2026-11-10 a name in "order" that the report lacks, a misspelt one
3894 # say, was drawn as a row and a column of grey cells, as a sequence that
3895 # has no hit is.
3896 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
3897 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
3898 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
3899 2 my (@row_labels, @names);
3900 2 foreach my $key (@order) {
3901 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
3902 3 my ($sp, @strain) = split /\./, $species; # C.neoformans.B.3501A
3903 3 push @names, [$genus, $sp, "@strain"];
3904 3 ▶ push @row_labels, '$\it{' . ucfirst(_first_letter($genus)) . ". $sp}\$" . (@strain ? " @strain" : '');
Branch: 1 branch
BranchTrueFalseTotal
@strain ? : 0 3 3
3905 }
3906 2 my @col_labels = @{ _abbreviated_labels(\@names) };
3907 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
3908 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
3909 # Normalized, every value is divided by the largest, with "logscale_add"
3910 # added to both so that the largest is still 1. That needs a largest above
3911 # 0, which "evalue" does not have when BLAST has rounded every e-value to 0.
3912 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
3913 if $norm && $max + $add <= 0;
3914 1 my $log = $args->{cblogscale};
3915 1 my (@cells, $lo, $hi, $lo_positive);
3916 1 foreach my $i (0 .. $#order) {
3917 1 foreach my $j (0 .. $#order) {
3918 # a pair with no hit stays out of the table, rather than claiming a
3919 # score of 0, and is drawn grey
3920 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
3921 1 ▶ if (defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) 0 1 1
3922 0 $value += $add;
3923 0 ▶ $value /= $max + $add if $norm;
Branch: 1 branch
BranchTrueFalseTotal
if $norm 0 0 0
3924 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
3925 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
3926 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
3927 }
3928 1 $cells[$i][$j] = $value;
3929 }
3930 }
3931 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
3932 # A normalized scale runs from 0 to 1, but a log scale can't start at 0 or
3933 # below, so it starts at the smallest value above 0 instead, as it does
3934 # when not normalized.
3935 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
3936 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
3937 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
3938 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
3939 0 require JSON::MaybeXS;
3940 0 my $table = _tmp('.json');
3941 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
3942 # The strings go through _chars, since encode_json reads a byte string as
3943 # Latin-1: up to 2026-10-17 a UTF-8 title "caf\xc3\xa9" was drawn as
3944 # "caf\xc3\x83\xc2\xa9".
3945 0 print {$fh} JSON::MaybeXS::encode_json({
3946 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
3947 log => $log ? JSON::MaybeXS::true() : JSON::MaybeXS::false(),
3948 numbers => $args->{'show_numbers'} ? JSON::MaybeXS::true() : JSON::MaybeXS::false(),
3949 0 title => _chars($args->{title} // ''), cblabel => (defined $args->{cb_label} ? _chars($args->{cb_label}) : undef),
3950 });
3951 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
3952 0 _python($sub, '--table', $table, '--o', $args->{filename}, '--c', _creator($sub), '--p', _json_text([map { _chars($_) } "showing each pair's \"$metric\"", $prov]));
3953 0 $args->{filename};
3954 }
3955  
3956 # $text with every character that LaTeX treats specially written so that it
3957 # prints as itself. "\^" would be a circumflex accent, not a caret, and "\~" a
3958 # tilde accent, so those two (and the backslash) are spelled as text commands.
3959 89 ▶sub _latex_text {
Subroutine _latex_text: called CC=2 SCAR=6.9
3960 89 my ($text) = @_;
3961 # |, < and > are commands, as the others are, because under the default
3962 # OT1 fonts they print as an em dash and an inverted ! and ?
3963 89 my %special = ('\\' => '\\textbackslash{}', '^' => '\\textasciicircum{}', '~' => '\\textasciitilde{}',
3964 '|' => '\\textbar{}', '<' => '\\textless{}', '>' => '\\textgreater{}');
3965 89 ▶ $text =~ s/([\\^~#\$%&_{}|<>])/$special{$1} \/\/ "\\$1"/ge;
Condition100%2/2
$special{$1} // "\\$1"
l!l
65
MC/DC100%1/1
$special{$1} // "\\$1"
$special{$1}
Truth table100%2/2
A
A= $special{$1}
Aresult
11
00
3966 89 $text;
3967 }
3968  
3969 18 ▶sub clustal_view_residues {
Subroutine clustal_view_residues: called CC=56 SCAR=43.1
Pod documented
3970 18 my $sub = 'clustal_view_residues';
3971 # msa_file: a FASTA file, aligned (such as plot_msa's) or not; color_residues:
3972 # {protein => {1-based residue number => colour}}, the colour an xcolor
3973 # name or an [r, g, b] ref; order: proteins top to bottom; row_width:
3974 # columns per block (100); split: blocks per LaTeX table (4); track: a
3975 # protein whose coloured residue numbers get a row of their own; threads and
3976 # clustal_args: for clustalo, if msa_file has to be aligned.
3977 18 my $args = _args(\@_, $sub, ['msa_file', 'output_tex_file'], [qw(caption clustal_args color_residues label
3978 order row_width split table_text_size threads track)]);
3979 18 _refs($sub, $args, 'ARRAY', qw(clustal_args order));
3980 17 _file_names($sub, $args, qw(msa_file output_tex_file));
3981 16 _threads($sub, $args);
3982 15 ▶ my $color = $args->{'color_residues'} // {};
Condition100%2/2
$args->{"color_residues"} // {}
l!l
69
MC/DC100%1/1
$args->{"color_residues"} // {}
$args->{"color_residues"}
Truth table100%2/2
A
A= $args->{"color_residues"}
Aresult
11
00
3983 15 ▶ croak "$sub: \"color_residues\" must be a hash ref" unless ref $color eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $color eq "HASH" 0 15 15
3984 15 foreach my $protein (sort keys %{ $color }) {
3985 croak "$sub: \"color_residues\" must map $protein to a hash ref of residue number => colour, not " . _what($color->{$protein})
3986 6 ▶ unless ref $color->{$protein} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $color->{$protein} eq "HASH" 1 5 6
3987 }
3988 # 0 would never end the loop over blocks, and divide by 0 in the tables
3989 14 foreach my $k ('row_width', 'split') {
3990 25 ▶ croak "$sub: \"$k\" must be a whole number, 1 or more, not \"$args->{$k}\"" if defined $args->{$k} && $args->{$k} !~ /\A[1-9][0-9]*\z/;
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{$k} and not $args->{$k} =~ /\A[1-9][0-9]*\z/ 6 19 25
Condition100%3/3
defined $args->{$k} and not $args->{$k} =~ /\A[1-9][0-9]*\z/
!ll&&!rl&&r
1456
MC/DC100%2/2
defined $args->{$k} and not $args->{$k} =~ /\A[1-9][0-9]*\z/
defined $args->{$k} not $args->{$k} =~ /\A[1-9][0-9]*\z/
Truth table100%3/3
A and not(B)
A= defined $args->{$k}B= not $args->{$k} =~ /\A[1-9][0-9]*\z/
ABresult
0X0
100
111
3991 }
3992 8 ▶ croak "$sub: \"msa_file\" $args->{'msa_file'} doesn't exist" unless -e $args->{'msa_file'};
Branch: 1 branch
BranchTrueFalseTotal
unless -e $args->{"msa_file"} 0 8 8
3993 8 my $data = fasta2hash($args->{'msa_file'});
3994 8 ▶ croak "$sub: has no sequences to show in $args->{'msa_file'}" unless %{ $data };
Branch: 1 branch
BranchTrueFalseTotal
unless %{$data;} 0 8 8
3995 8 my %len = map { length $_ => 1 } values %{ $data };
3996 8 ▶ if (keys %len > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %len > 1) 0 8 8
3997 # Sequences of different lengths can't be an alignment, so align them,
3998 # into a temporary file: "msa_file" is the input, and is never written.
3999 0 my %clustal = map { $_ => $args->{$_} } grep { defined $args->{$_} } qw(clustal_args threads);
4000 0 (undef, undef, undef, undef, $data) = _align({ %clustal, fasta => $args->{'msa_file'} }, $sub, 0);
4001 0 %len = map { length $_ => 1 } values %{ $data };
4002 }
4003 8 my $track = $args->{track};
4004 8 ▶ croak "$sub: tracker \"$track\" isn't in the alignment" if defined $track && !defined $data->{$track};
Branch: 1 branch
BranchTrueFalseTotal
if defined $track and not defined $data->{$track} 0 8 8
Condition66%2/3
defined $track and not defined $data->{$track}
!ll&&!rl&&r
440
MC/DC0%0/2
defined $track and not defined $data->{$track}
defined $track not defined $data->{$track}
Truth table66%2/3
A and not(B)
A= defined $trackB= not defined $data->{$track}
ABresult
0X0
100
111
4005 8 my ($aln_len) = keys %len;
4006 8 my @undef = grep { !defined $data->{$_} } sort keys %{ $color };
4007 8 ▶ croak "$sub: \"color_residues\" names proteins that aren't in the alignment: @undef" if @undef;
Branch: 1 branch
BranchTrueFalseTotal
if @undef 0 8 8
4008 8 ▶ my @proteins = @{ $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
17
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
4009 8 my @bad = grep { !defined $data->{$_} } @proteins;
4010 8 ▶ croak "$sub: \"order\" names proteins that aren't in the alignment: @bad" if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 0 8 8
4011 8 ▶ my $width = $args->{'row_width'} // 100;
Condition100%2/2
$args->{"row_width"} // 100
l!l
44
MC/DC100%1/1
$args->{"row_width"} // 100
$args->{"row_width"}
Truth table100%2/2
A
A= $args->{"row_width"}
Aresult
11
00
4012 # Alignment column => colour, and for the tracked protein column => its
4013 # residue number. A coloured column is coloured in every protein.
4014 8 my (%col_color, %col_number);
4015 8 foreach my $protein (sort keys %{ $color }) {
4016 5 my @col;
4017 5 ▶ while ($data->{$protein} =~ /[A-Za-z]/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data->{$protein} =~ /[A-Za-z]/g) 44 5 49
4018 44 push @col, pos($data->{$protein}) - 1;
4019 }
4020 # checked before they are sorted as numbers, which would warn of one that is not
4021 5 _residue_number($sub, "a residue of $protein in \"color_residues\"", $_) foreach sort keys %{ $color->{$protein} };
4022 2 foreach my $n (sort { $a <=> $b } keys %{ $color->{$protein} }) {
4023 6 my $c = $color->{$protein}{$n};
4024 6 ▶ 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
60
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
4025 0 ▶ croak "$sub: the colour of $protein residue $n must be a name or 3 numbers" if ref $c && (ref $c ne 'ARRAY' || @{ $c } != 3);
Branch: 1 branch
BranchTrueFalseTotal
if ref $c and ref $c ne "ARRAY" || @{$c;} != 3 0 6 6
Condition16%1/6
ref $c and ref $c ne "ARRAY" || @{$c;} != 3
!ll&&!rl&&r
600
ref $c ne "ARRAY" or @{$c;} != 3
l!l&&r!l&&!r
000
MC/DC0%0/3
ref $c and ref $c ne "ARRAY" || @{$c;} != 3
ref $c ref $c ne "ARRAY" @{$c;} != 3
Truth table25%1/4
A and B or C
A= ref $cB= ref $c ne "ARRAY"C= @{$c;} != 3
ABCresult
0XX0
1000
11X1
1011
4026 6 $col_color{$col} = $c;
4027 6 ▶ $col_number{$col} = $n if defined $track && $protein eq $track;
Branch: 1 branch
BranchTrueFalseTotal
if defined $track and $protein eq $track 6 0 6
Condition33%1/3
defined $track and $protein eq $track
!ll&&!rl&&r
006
MC/DC0%0/2
defined $track and $protein eq $track
defined $track $protein eq $track
Truth table33%1/3
A and B
A= defined $trackB= $protein eq $track
ABresult
0X0
100
111
4028 }
4029 }
4030 5 my (@table, %count);
4031 5 ▶ for (my $start = 0; $start < $aln_len; $start += $width) {
Branch: 1 branch
BranchTrueFalseTotal
if ($start < $aln_len) 9 5 14
4032 9 ▶ my $w = $aln_len - $start < $width ? $aln_len - $start : $width;
Branch: 1 branch
BranchTrueFalseTotal
$aln_len - $start < $width ? : 4 5 9
4033 9 foreach my $protein (@proteins) {
4034 14 my @seq = split //, substr($data->{$protein}, $start, $w);
4035 14 $count{$protein} += grep { /[A-Za-z]/ } @seq;
4036 # a residue is written so that LaTeX prints it, as a name is
4037 14 $_ = _latex_text($_) foreach @seq;
4038 14 ▶ foreach my $col (grep { $_ >= $start && $_ < $start + $w } keys %col_color) {
Condition100%3/3
$_ >= $start && $_ < $start + $w
!ll&&!rl&&r
10212
MC/DC100%2/2
$_ >= $start && $_ < $start + $w
$_ >= $start $_ < $start + $w
Truth table100%3/3
A && B
A= $_ >= $startB= $_ < $start + $w
ABresult
0X0
100
111
4039 12 my ($c, $i) = ($col_color{$col}, $col - $start);
4040 0 ▶ $seq[$i] = ref $c ? '{\color[rgb]{' . join(',', @{ $c }) . "}$seq[$i]}" : "\\textcolor{$c}{$seq[$i]}";
Branch: 1 branch
BranchTrueFalseTotal
ref $c ? : 0 12 12
4041 }
4042 14 my $name = _latex_text($protein);
4043 14 push @table, ["\\textit{$name}", '\texttt{' . join('', @seq) . '}', $count{$protein}];
4044 14 ▶ next unless defined $track && $protein eq $track;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $track and $protein eq $track 10 4 14
Condition100%3/3
defined $track and $protein eq $track
!ll&&!rl&&r
374
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
4045 # Each residue number written from its own column rightwards, one
4046 # digit per column so the row stays aligned, and moved right past
4047 # the end of the previous number rather than overwriting it. One
4048 # that would then run past the end of the block is moved left to end
4049 # there, and is left out only if that would overwrite the number
4050 # before it.
4051 4 my @row = ('-') x $w;
4052 4 my $free = 0; # first column not yet taken by a number
4053 4 ▶ foreach my $col (sort { $a <=> $b } grep { $_ >= $start && $_ < $start + $w } keys %col_number) {
Condition100%3/3
$_ >= $start && $_ < $start + $w
!ll&&!rl&&r
516
MC/DC100%2/2
$_ >= $start && $_ < $start + $w
$_ >= $start $_ < $start + $w
Truth table100%3/3
A && B
A= $_ >= $startB= $_ < $start + $w
ABresult
0X0
100
111
4054 6 ▶ my $at = $col - $start < $free ? $free : $col - $start;
Branch: 1 branch
BranchTrueFalseTotal
$col - $start < $free ? : 1 5 6
4055 6 my @digits = split //, $col_number{$col};
4056 6 ▶ $at = $w - @digits if $at + @digits > $w;
Branch: 1 branch
BranchTrueFalseTotal
if $at + @digits > $w 2 4 6
4057 6 ▶ next if $at < $free;
Branch: 1 branch
BranchTrueFalseTotal
if $at < $free 1 5 6
4058 5 @row[$at .. $at + $#digits] = @digits;
4059 5 $free = $at + @digits + 1;
4060 }
4061 4 push @table, ["\\textit{$name} track", '\texttt{' . join('', @row) . '}', $count{$protein}];
4062 }
4063 9 push @table, ['\hline'];
4064 }
4065 # rows a block: its proteins, the track row if the tracked protein is shown, and \hline
4066 5 ▶ my $per_table = ($args->{split} // 4) * (1 + @proteins + ((defined $track && grep { $_ eq $track } @proteins) ? 1 : 0));
Branch: 1 branch
BranchTrueFalseTotal
defined $track && grep({$_ eq $track;} @proteins) ? : 2 3 5
Condition100%5/5
$args->{"split"} // 4
l!l
14
defined $track and grep {$_ eq $track;} @proteins
!ll&&!rl&&r
212
MC/DC100%1/1
$args->{"split"} // 4
$args->{"split"}
MC/DC100%2/2
defined $track and grep {$_ eq $track;} @proteins
defined $track grep {$_ eq $track;} @proteins
Truth table100%2/2
A
A= $args->{"split"}
Aresult
11
00
Truth table100%3/3
A and B
A= defined $trackB= grep {$_ eq $track;} @proteins
ABresult
0X0
100
111
4067 5 ▶ my $size = $args->{'table_text_size'} // '\footnotesize';
Condition50%1/2
$args->{"table_text_size"} // "\\footnotesize"
l!l
05
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
4068 5 ▶ my $caption = $args->{caption} // '';
Condition50%1/2
$args->{"caption"} // ""
l!l
05
MC/DC0%0/1
$args->{"caption"} // ""
$args->{"caption"}
Truth table50%1/2
A
A= $args->{"caption"}
Aresult
11
00
4069 5 ▶ open my $tex, '>', $args->{'output_tex_file'} or croak "$sub: can't write $args->{'output_tex_file'}: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $tex, ">", $args->{"output_tex_file"} or croak(qq[${sub}: can't write $args->{"output_tex_file"}: $!]) 5 0 5
4070 5 print {$tex} "%written by $0, calling $sub in " . __FILE__ . "\n";
4071 5 my $n_tables = int((@table + $per_table - 1) / $per_table);
4072 5 foreach my $t (0 .. $n_tables - 1) {
4073 6 my $end = ($t + 1) * $per_table - 1;
4074 6 ▶ $end = $#table if $end > $#table;
Branch: 1 branch
BranchTrueFalseTotal
if $end > $#table 5 1 6
4075 6 print {$tex} "\\begin{table}[htp]$size\n\\begin{tabular}{|c|l|c|} \\hline\n",
4076 '\textbf{Track} & \textbf{Sequence} & \textbf{Length}\\\\ \hline', "\n";
4077 6 ▶ print {$tex} join(' & ', @{ $_ }), ($_->[-1] eq '\hline' ? "\n" : "\n\\\\\n") foreach @table[$t * $per_table .. $end];
Branch: 1 branch
BranchTrueFalseTotal
$_->[-1] eq '\\hline' ? : 9 18 27
4078 6 ▶ print {$tex} "\\end{tabular}\n\\caption{$caption", ($t > 0 && $caption ne '' ? ' (continued)' : ''), "}\n";
Branch: 1 branch
BranchTrueFalseTotal
$t > 0 && $caption ne '' ? : 0 6 6
Condition66%2/3
$t > 0 and $caption ne ""
!ll&&!rl&&r
510
MC/DC0%0/2
$t > 0 and $caption ne ""
$t > 0 $caption ne ""
Truth table66%2/3
A and B
A= $t > 0B= $caption ne ""
ABresult
0X0
100
111
4079 0 ▶ print {$tex} "\\label{tab:$args->{label}", ($n_tables > 1 ? $t : ''), "}\n" if defined $args->{label};
Branch: 2 branches
BranchTrueFalseTotal
if defined $args->{"label"} 0 6 6
$n_tables > 1 ? : 0 0 0
4080 6 print {$tex} "\\end{table} \\FloatBarrier\n";
4081 }
4082 5 ▶ close $tex or croak "$sub: can't write $args->{'output_tex_file'}: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $tex or croak(qq[${sub}: can't write $args->{"output_tex_file"}: $!]) 5 0 5
4083 5 _wrote($args->{'output_tex_file'}, 46); # cyan
4084 5 $args->{'output_tex_file'};
4085 }
4086  
4087 36 1;
4088  
4089 __END__
↑ Summary Bioinf.xs »