Bioinf.xs

filter: Statementstmt 99.1% 1615 / 1629 Branchbran 84.9% 1328 / 1564 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 92.1% 2943 / 3193 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« blib/lib/Cn/Bioinf.pm ↑ Summary
1 /*FASTA reading and writing for Cn::Bioinf, (since 2026-11-18) the scan behind
2 fasta_index and fasta_region, the genotype counts behind its
3 sex_check, parent, relatedness, concordance, hirisplex_genotypes and
4 blood_type, (since 2026-11-11) the codon and k-mer loops behind translate,
5 translate_six_frames, find_orfs and kmer_count, and (since 2026-11-17) the
6 genotypes and the fit behind admixture.
7  
8 fasta2hash() and hash2fasta_file() used to be pure perl in ~/Scripts/bioinf.pm:
9 one readline, chomp and string append per line in, and one substr-sized SV per
10 80-column line out. Here a file is read in large blocks and every line of a
11 record is appended straight onto that record's SV, so no per-line SV is ever
12 made, and each finished sequence is shrunk to its length, which is the RAM a
13 proteome or genome actually needs rather than whatever the last buffer growth
14 left. On the file described at FASTA_BLOCK below, bioinf.pm read it in 3.83 s
15 with a peak RSS of 1,098 MB, and this in 0.80 s and 967 MB, 900 MB of which is
16 the sequences themselves; writing it back took 44.44 s and takes 0.97 s, and
17 the two files are byte-identical. Dropping the whitespace in sequences, which
18 began on 2026-10-17, costs about 15%: a made-up file of the same shape (938 MB,
19 400,000 records of 2,280 residues in 60-column lines, in the page cache) took
20 0.85 s to read before and 0.98 s after, best of five timed inside perl. The
21 perl side (lib/Cn/Bioinf.pm) opens and closes the files.
22  
23 Every croak() and warn() here starts with C99's __func__, so a message names
24 the C function that raised it (read_fasta, write_fasta, translate_codons,
25 kmer_tally, or one of the vcf_, sex_, parent_, rel_, conc_, hps_, bt_ and admix_ ones)
26 and stays right if one is renamed.*/
27 #define PERL_NO_GET_CONTEXT
28 #include "EXTERN.h"
29 #include "perl.h"
30 #include "XSUB.h"
31 #include <string.h>
32 #include <stdint.h>
33 /*`restrict` is spelled bare, which is C99 syntax.
34  
35 It is carried only by read_fasta()'s block buffer, which this file allocates
36 itself and reaches through nothing but that pointer and the ones derived from
37 it. Every other pointer here is perl's: an SV, AV or HV, or the PV inside one,
38 which the perl API may alias behind the code's back -- in write_fasta() a
39 defline and its sequence can be COW copies of the one buffer -- so the
40 qualifier would be a false promise. perl is built with -fno-strict-aliasing,
41 where `restrict` is the only disambiguation there is, but it earns nothing even
42 on the buffer: the loop over it stores only through memchr() and sv_catpvn(),
43 which are opaque calls the compiler must assume write anywhere. The generated
44 code for this file was byte-identical with and without it (gcc -O2 -std=gnu99,
45 2026-09-30), so the one annotation records the contract rather than buying
46 speed.
47  
48 Makefile.PL probes for a C99 flag but cannot always find one. MSVC accepts the
49 keyword only under /std:c11 or later and otherwise spells it __restrict, older
50 gcc spells it __restrict__, and a strict C89 compiler has no equivalent. Map it
51 where a spelling exists and define it away where none does -- the same block as
52 ~/Scripts/stats/LikeR.xs. It sits below every #include so that it cannot
53 rewrite a parameter named `restrict` inside a system header.*/
54 #if !defined(__cplusplus) && !defined(restrict)
55 # if defined(_MSC_VER)
56 # define restrict __restrict
57 # elif !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L
58 # if defined(__GNUC__)
59 # define restrict __restrict__
60 # else
61 # define restrict /*no spelling available; annotation only*/
62 # endif
63 # endif
64 #endif
65 /*PerlIO_read() request size. Reading a 928 MB FASTA of 400,000 records in
66 60-column lines, on this machine on 2026-09-29, took 0.84 s with 16 KiB blocks,
67 0.80 s with 64 KiB, 0.81 s with 256 KiB and 0.82 s with 1 MiB (best of three
68 each, file in the page cache), so nothing is gained past 64 KiB. Build with
69 DEFINE=-DFASTA_BLOCK=<bytes> to try another.*/
70 #ifndef FASTA_BLOCK
71 #define FASTA_BLOCK 65536
72 #endif
73  
74 /*Whether c is whitespace as Python has it, which is what Biopython strips: ' '
75 or one of '\t' (9), '\v' (11), '\f' (12) and '\r' (13), which is the range
76 9..13 less the '\n' (10) that ends every line, and so is never tested. perl's
77 isSPACE() is not used, since that took in '\v' only from 5.18.*/
78 #define FASTA_SPACE(c) ((c) == ' ' || (unsigned char)((c) - '\t') < 5)
79  
80 /*Whether p..e holds any FASTA_SPACE() byte, 8 bytes at a time.
81  
82 With a byte-at-a-time loop, the 938 MB file described at the top of this file
83 took 1.46 s to read rather than 0.85 s (best of five each, 2026-10-17): gcc
84 -O2 does not vectorise a loop of unknown length. This takes 8 bytes at once: a space is
85 a zero byte of w ^ 0x2020...20, found by Alan Mycroft's haszero(), and a byte
86 in 9..13 is found by hasbetween(w, 8, 14), both from Sean Eron Anderson's "Bit
87 Twiddling Hacks" (graphics.stanford.edu/~seander/bithacks.html, sections
88 ZeroInWord and HasBetweenInWord). Both are exact, and work byte by byte with no
89 carry between bytes, so the byte order does not matter.*/
90 47209 static bool any_space(const char *p, const char *e) {
91 47209 const uint64_t ones = UINT64_C(0x0101010101010101), low7 = ones * 0x7f, high = ones * 0x80;
92 368565 ▶ for (; e - p >= 8; p += 8) {
Branch: 1 branch
BranchTrueFalseTotal
for (; e - p >= 8; p += 8) { 321431 47134 368565
93 uint64_t w;
94 321431 memcpy(&w, p, 8);// not a cast to uint64_t *, since SPARC and some ARM fault on an unaligned load
95 321431 const uint64_t sp = w ^ (ones * ' ');
96 321491 ▶ if ((sp - ones) & ~sp & high) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if ((sp - ones) & ~sp & high) return 1; 15 321416 321431
97 321416 ▶ if ((ones * (127 + 14) - (w & low7)) & ~w & ((w & low7) + ones * (127 - 8)) & high) return TRUE;
Branch: 1 branch
BranchTrueFalseTotal
if ((ones * (127 + 14) - (w & low7)) & ~w & ((w & low7) + ones * (127 - 8)) & high) return TRUE; 60 321356 321416
98 }
99 235859 ▶ for (; p < e; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (; p < e; p++) { 188762 47097 235859
100 188762 ▶ if (FASTA_SPACE(*p)) return 1;
Branch: 2 branches
BranchTrueFalseTotal
if (FASTA_SPACE(*p)) return 1; 188754 8 188762
if (FASTA_SPACE(*p)) return 1; 29 188725 188754
101 }
102 47097 return 0;
103 }
104  
105 /*Drop the whitespace at the end of a defline, the '\r' of a CRLF file
106 included, as Biopython does. It is chopped when the line ends rather than as it
107 is read, because a block can end inside it. Only SvCUR moves: the bytes
108 dropped stay in the buffer with no NUL after SvCUR, so the SV is read by its
109 length (sv_eq, hv_*_ent, SVf) and never as a C string, as a warning in
110 read_fasta() once read it and printed them.*/
111 459 static void chop_space(SV *sv) {
112 459 STRLEN n = SvCUR(sv);
113 477 ▶ while (n && FASTA_SPACE(SvPVX(sv)[n - 1])) n--;
Branch: 3 branches
BranchTrueFalseTotal
while (n && FASTA_SPACE(SvPVX(sv)[n - 1])) n--; 476 1 477
while (n && FASTA_SPACE(SvPVX(sv)[n - 1])) n--; 6 470 476
while (n && FASTA_SPACE(SvPVX(sv)[n - 1])) n--; 12 458 470
114 459 SvCUR_set(sv, n);
115 459 }
116  
117 /*Append the residues in p..e to seq, leaving out the whitespace. Biopython
118 drops the spaces in a sequence line and the whitespace at its end; a tab inside
119 a line is dropped here too. A line with none, which is nearly every line, is
120 appended whole; otherwise each run between whitespace is one sv_catpvn().*/
121 47209 static void cat_residues(pTHX_ SV *seq, const char *p, const char *e) {
122 47209 ▶ if (!any_space(p, e)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!any_space(p, e)) { 47097 112 47209
123 47097 sv_catpvn(seq, p, (STRLEN)(e - p));
124 47097 return;
125 }
126 319 ▶ while (p < e) {
Branch: 1 branch
BranchTrueFalseTotal
while (p < e) { 207 112 319
127 207 const char *run = p;
128 133110 ▶ while (p < e && !FASTA_SPACE(*p)) p++;
Branch: 3 branches
BranchTrueFalseTotal
while (p < e && !FASTA_SPACE(*p)) p++; 133018 92 133110
while (p < e && !FASTA_SPACE(*p)) p++; 132993 25 133018
while (p < e && !FASTA_SPACE(*p)) p++; 132903 90 132993
129 207 ▶ if (p > run) sv_catpvn(seq, run, (STRLEN)(p - run));
Branch: 1 branch
BranchTrueFalseTotal
if (p > run) sv_catpvn(seq, run, (STRLEN)(p - run)); 205 2 207
130 322 ▶ while (p < e && FASTA_SPACE(*p)) p++;
Branch: 3 branches
BranchTrueFalseTotal
while (p < e && FASTA_SPACE(*p)) p++; 210 112 322
while (p < e && FASTA_SPACE(*p)) p++; 25 185 210
while (p < e && FASTA_SPACE(*p)) p++; 90 95 185
131 }
132 }
133  
134 /*Whether p..e holds nothing but whitespace.*/
135 5 static bool all_space(const char *p, const char *e) {
136 9 ▶ for (; p < e; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (; p < e; p++) { 6 3 9
137 6 ▶ if (!FASTA_SPACE(*p)) return FALSE;
Branch: 2 branches
BranchTrueFalseTotal
if (!FASTA_SPACE(*p)) return FALSE; 5 1 6
if (!FASTA_SPACE(*p)) return FALSE; 2 3 5
138 }
139 3 return TRUE;
140 }
141  
142 /*Every record of fh as a hash of defline => sequence, or with key given only
143 that record's sequence (undef if it is absent), reading no further than the
144 defline after it. name is the file's name, for messages. order, when not NULL,
145 gets each defline in file order.
146  
147 A repeated defline is warned about and its sequences concatenated, which is
148 what bioinf.pm did: it is the file that is wrong, and nothing here can say
149 which of the two records was meant. With key given, reading stops at the
150 defline after key's record, so the only repeat seen, and concatenated, is one
151 that follows it directly; a second record of key further on is never read,
152 and the one sequence returned is the first's alone. That is the price of
153 stopping early, and README.md says so. A repeat of any other defline is not
154 looked for either: finding it would mean keeping every defline read on the way
155 to key, a hash of 400,000 keys for one record of a proteome.
156  
157 A defline with a CR inside it, once the whitespace at its end is gone, dies:
158 it is what a file whose lines end in CR alone (classic Mac OS) has, since with
159 no LF the whole file is one line, and up to 2026-11-10 such a file came back as
160 one record named by all of it, with no sequence. Biopython, which opens a file
161 in Python's universal-newlines mode, reads one; here it is refused, by one
162 memchr() a defline, rather than every CR being tested for as the file is
163 read.*/
164 62 static SV *read_fasta(pTHX_ PerlIO *fh, SV *key, const char *name, AV *order) {
165 62 HV *out = (HV*)sv_2mortal((SV*)newHV());
166 62 SV *hdr = sv_2mortal(newSVpvs(""));
167 62 SV *seq = NULL;// record being filled; NULL before the first defline and while skipping
168 62 bool have_def = FALSE, in_hdr = FALSE, bol = TRUE, done = FALSE, fed = FALSE;// fed: the '\n' that ends an unterminated last line has been supplied
169 62 UV line = 0;// 1-based, as $. would count it
170 char *restrict buf;
171 62 Newx(buf, FASTA_BLOCK, char);
172 62 SAVEFREEPV(buf);// freed at the caller's LEAVE, croak or not
173 178 ▶ while (!done) {
Branch: 1 branch
BranchTrueFalseTotal
while (!done) { 171 7 178
174 171 SSize_t n = PerlIO_read(fh, buf, FASTA_BLOCK);
175 171 ▶ if (n < 0 || PerlIO_error(fh)) croak("%s: error reading %s: %s", __func__, name, Strerror(errno));
Branch: 2 branches
BranchTrueFalseTotal
if (n < 0 || PerlIO_error(fh)) croak("%s: error reading %s: %s", __func__, name, Strerror(errno)); 171 0 171
if (n < 0 || PerlIO_error(fh)) croak("%s: error reading %s: %s", __func__, name, Strerror(errno)); 0 171 171
176 171 ▶ if (n == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) { 58 113 171
177 58 ▶ if (bol || fed) break;
Branch: 2 branches
BranchTrueFalseTotal
if (bol || fed) break; 7 51 58
if (bol || fed) break; 7 0 7
178 7 buf[0] = '\n';
179 7 n = 1;
180 7 fed = 1;
181 }
182 120 const char *p = buf, *end = buf + n;
183 58092 ▶ while (p < end) {
Branch: 1 branch
BranchTrueFalseTotal
while (p < end) { 58041 51 58092
184 58041 ▶ if (bol) {
Branch: 1 branch
BranchTrueFalseTotal
if (bol) { 57524 517 58041
185 57524 line++;
186 57524 bol = FALSE;
187 57524 ▶ if (*p == '>') {
Branch: 1 branch
BranchTrueFalseTotal
if (*p == '>') { 459 57065 57524
188 459 in_hdr = 1;
189 459 SvCUR_set(hdr, 0);
190 459 p++;
191 459 continue;
192 }
193 }
194 57582 const char *nl = (const char*)memchr(p, '\n', (size_t)(end - p));
195 57582 ▶ const char *e = nl ? nl : end;
Branch: 1 branch
BranchTrueFalseTotal
const char *e = nl ? nl : end; 57524 58 57582
196 57582 ▶ if (in_hdr) sv_catpvn(hdr, p, (STRLEN)(e - p));
Branch: 1 branch
BranchTrueFalseTotal
if (in_hdr) sv_catpvn(hdr, p, (STRLEN)(e - p)); 464 57118 57582
197 57118 ▶ else if (seq) cat_residues(aTHX_ seq, p, e);
Branch: 1 branch
BranchTrueFalseTotal
else if (seq) cat_residues(aTHX_ seq, p, e); 47209 9909 57118
198 9909 ▶ else if (!have_def && !all_space(p, e))
Branch: 2 branches
BranchTrueFalseTotal
else if (!have_def && !all_space(p, e)) 5 9904 9909
else if (!have_def && !all_space(p, e)) 2 3 5
199 2 croak("%s: %s line %" UVuf " is sequence, but no defline (\">...\") has come before it", __func__, name, line);
200 57580 ▶ if (!nl) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!nl) break; 58 57522 57580
201 57522 p = nl + 1;
202 57522 bol = 1;
203 57522 ▶ if (!in_hdr) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!in_hdr) continue; 57063 459 57522
204 459 in_hdr = FALSE;
205 459 chop_space(hdr);
206 459 ▶ if (!SvCUR(hdr)) croak("%s: %s line %" UVuf " is a defline with no name", __func__, name, line);
Branch: 1 branch
BranchTrueFalseTotal
if (!SvCUR(hdr)) croak("%s: %s line %" UVuf " is a defline with no name", __func__, name, line); 1 458 459
207 458 ▶ if (memchr(SvPVX(hdr), '\r', SvCUR(hdr)))
Branch: 1 branch
BranchTrueFalseTotal
if (memchr(SvPVX(hdr), '\r', SvCUR(hdr))) 1 457 458
208 1 croak("%s: %s line %" UVuf " has a carriage return inside its defline, as a file whose lines end in CR alone (classic Mac OS) does; convert its line endings to LF first", __func__, name, line);
209 457 ▶ if (seq) SvPV_shrink_to_cur(seq);
Branch: 4 branches
BranchTrueFalseTotal
if (seq) SvPV_shrink_to_cur(seq); 386 71 457
if (seq) SvPV_shrink_to_cur(seq); 336 50 386
if (seq) SvPV_shrink_to_cur(seq); 0 336 336
if (seq) SvPV_shrink_to_cur(seq); 285 101 386
210 457 ▶ bool is_key = key && sv_eq(hdr, key);
Branch: 2 branches
BranchTrueFalseTotal
bool is_key = key && sv_eq(hdr, key); 37 420 457
bool is_key = key && sv_eq(hdr, key); 13 24 37
211 457 ▶ if (key && !is_key && hv_exists_ent(out, key, 0)) {
Branch: 3 branches
BranchTrueFalseTotal
if (key && !is_key && hv_exists_ent(out, key, 0)) { 37 420 457
if (key && !is_key && hv_exists_ent(out, key, 0)) { 24 13 37
if (key && !is_key && hv_exists_ent(out, key, 0)) { 7 17 24
212 7 done = 1;// the wanted record is complete
213 7 break;
214 }
215 450 have_def = 1;
216 450 ▶ if (key && !is_key) {
Branch: 2 branches
BranchTrueFalseTotal
if (key && !is_key) { 30 420 450
if (key && !is_key) { 17 13 30
217 17 seq = NULL;
218 17 continue;
219 }
220 433 ▶ if (hv_exists_ent(out, hdr, 0))
Branch: 1 branch
BranchTrueFalseTotal
if (hv_exists_ent(out, hdr, 0)) 4 429 433
221 4 warn("%s: \"%" SVf "\" appears more than once in %s (line %" UVuf "); its sequences will be concatenated", __func__, SVfARG(hdr), name, line);
222 429 ▶ else if (order) av_push(order, newSVsv(hdr));
Branch: 1 branch
BranchTrueFalseTotal
else if (order) av_push(order, newSVsv(hdr)); 2 427 429
223 433 seq = HeVAL(hv_fetch_ent(out, hdr, 1, 0));
224 433 ▶ if (!SvOK(seq)) sv_setpvs(seq, "");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(seq)) sv_setpvs(seq, ""); 429 4 433
225 }
226 }
227 58 ▶ if (seq) SvPV_shrink_to_cur(seq);
Branch: 4 branches
BranchTrueFalseTotal
if (seq) SvPV_shrink_to_cur(seq); 53 5 58
if (seq) SvPV_shrink_to_cur(seq); 14 39 53
if (seq) SvPV_shrink_to_cur(seq); 0 14 14
if (seq) SvPV_shrink_to_cur(seq); 8 45 53
228 58 ▶ if (!key) return newRV_inc((SV*)out);
Branch: 1 branch
BranchTrueFalseTotal
if (!key) return newRV_inc((SV*)out); 42 16 58
229 16 HE *he = hv_fetch_ent(out, key, 0, 0);
230 16 ▶ return he ? SvREFCNT_inc_simple_NN(HeVAL(he)) : newSV(0);// not a copy: out is mortal, so this becomes the only reference
Branch: 1 branch
BranchTrueFalseTotal
return he ? SvREFCNT_inc_simple_NN(HeVAL(he)) : newSV(0);// not a copy: out is mortal, so this becomes the only reference 12 4 16
231 }
232  
233 /*The bytes of sv for a FASTA file, as print to a :raw handle writes them: a
234 string perl holds as UTF-8 is written as the characters it holds, so that how
235 perl happened to store it cannot change the file. Up to 2026-10-17 it was
236 written as its UTF-8, and "caf\xe9" came out as one byte or two. scratch holds
237 that downgraded copy. A character above 255 has no byte, and gets NULL, for
238 the caller to die naming the string; print would write UTF-8 and warn.*/
239 60 static const char *fasta_bytes(pTHX_ SV *sv, SV *scratch, STRLEN *len) {
240 60 ▶ if (SvUTF8(sv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvUTF8(sv)) { 10 50 60
241 10 sv_setsv(scratch, sv);
242 10 ▶ if (!sv_utf8_downgrade(scratch, TRUE)) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!sv_utf8_downgrade(scratch, TRUE)) return NULL; 4 6 10
243 6 sv = scratch;
244 }
245 56 return SvPV_const(sv, *len);
246 }
247  
248 /*Each key of h named in order, as ">key" and then its sequence broken into
249 lines of width characters; width 0 puts each sequence on one line.
250  
251 A key that is empty or holds a line feed dies, since read_fasta() could not
252 read its record back: the one is a defline with no name, and the other ends
253 the defline at the line feed and makes the rest of the key sequence. So does a
254 sequence that is a reference, unless it is an object that overloads its own
255 text. Up to 2026-11-10 all three were written, the reference as
256 "ARRAY(0x5ea732db32c8)".*/
257 24 static void write_fasta(pTHX_ PerlIO *fh, HV *h, AV *order, STRLEN width) {
258 24 SV *kbuf = sv_newmortal(), *sbuf = sv_newmortal();// fasta_bytes()'s scratch copies, of the key and of its sequence
259 49 ▶ for (SSize_t i = 0; i <= av_len(order); i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (SSize_t i = 0; i <= av_len(order); i++) { 35 14 49
260 35 SV **k = av_fetch(order, i, 0);
261 35 ▶ if (!k || !SvOK(*k)) croak("%s: element %" IVdf " of the order is undefined", __func__, (IV)i);
Branch: 2 branches
BranchTrueFalseTotal
if (!k || !SvOK(*k)) croak("%s: element %" IVdf " of the order is undefined", __func__, (IV)i); 35 0 35
if (!k || !SvOK(*k)) croak("%s: element %" IVdf " of the order is undefined", __func__, (IV)i); 1 34 35
262 34 HE *he = hv_fetch_ent(h, *k, 0, 0);
263 STRLEN kl, sl;
264 // kp and sp not restrict: a defline and its sequence may share one COW buffer
265 34 const char *kp = fasta_bytes(aTHX_ *k, kbuf, &kl);
266 37 ▶ if (!kp) croak("%s: \"%s\" has a character above 255, so it has to be encoded (with Encode::encode('UTF-8', ...), say) before it is written", __func__, SvPV_nolen(*k));
Branch: 1 branch
BranchTrueFalseTotal
if (!kp) croak("%s: \"%s\" has a character above 255, so it has to be encoded (with Encode::encode('UTF-8', ...), say) before it is written", __func__, SvPV_nolen(*k)); 3 31 34
267 31 ▶ if (!kl) croak("%s: element %" IVdf " of the order is an empty name, which a defline can't be", __func__, (IV)i);
Branch: 1 branch
BranchTrueFalseTotal
if (!kl) croak("%s: element %" IVdf " of the order is an empty name, which a defline can't be", __func__, (IV)i); 1 30 31
268 30 ▶ if (memchr(kp, '\n', kl)) croak("%s: \"%s\" has a line feed in it, which would end the defline there", __func__, kp);
Branch: 1 branch
BranchTrueFalseTotal
if (memchr(kp, '\n', kl)) croak("%s: \"%s\" has a line feed in it, which would end the defline there", __func__, kp); 1 29 30
269 29 ▶ if (!he || !SvOK(HeVAL(he))) croak("%s: \"%s\" has no sequence in the hash", __func__, kp);
Branch: 2 branches
BranchTrueFalseTotal
if (!he || !SvOK(HeVAL(he))) croak("%s: \"%s\" has no sequence in the hash", __func__, kp); 27 2 29
if (!he || !SvOK(HeVAL(he))) croak("%s: \"%s\" has no sequence in the hash", __func__, kp); 0 27 27
270 27 ▶ if (SvROK(HeVAL(he)) && !SvAMAGIC(HeVAL(he))) croak("%s: the sequence of \"%s\" is a reference, not a string of residues", __func__, kp);
Branch: 4 branches
BranchTrueFalseTotal
if (SvROK(HeVAL(he)) && !SvAMAGIC(HeVAL(he))) croak("%s: the sequence of \"%s\" is a reference, not a string of residues", __func__, kp); 2 25 27
if (SvROK(HeVAL(he)) && !SvAMAGIC(HeVAL(he))) croak("%s: the sequence of \"%s\" is a reference, not a string of residues", __func__, kp); 2 0 2
if (SvROK(HeVAL(he)) && !SvAMAGIC(HeVAL(he))) croak("%s: the sequence of \"%s\" is a reference, not a string of residues", __func__, kp); 1 1 2
if (SvROK(HeVAL(he)) && !SvAMAGIC(HeVAL(he))) croak("%s: the sequence of \"%s\" is a reference, not a string of residues", __func__, kp); 0 1 1
271 26 const char *sp = fasta_bytes(aTHX_ HeVAL(he), sbuf, &sl);
272 26 ▶ if (!sp) croak("%s: the sequence of \"%s\" has a character above 255, so it has to be encoded before it is written", __func__, kp);
Branch: 1 branch
BranchTrueFalseTotal
if (!sp) croak("%s: the sequence of \"%s\" has a character above 255, so it has to be encoded before it is written", __func__, kp); 1 25 26
273 25 PerlIO_putc(fh, '>');
274 25 PerlIO_write(fh, kp, kl);
275 25 PerlIO_putc(fh, '\n');
276 25 ▶ STRLEN w = width ? width : sl;
Branch: 1 branch
BranchTrueFalseTotal
STRLEN w = width ? width : sl; 22 3 25
277 51 ▶ for (STRLEN o = 0; o < sl; o += w) {
Branch: 1 branch
BranchTrueFalseTotal
for (STRLEN o = 0; o < sl; o += w) { 26 25 51
278 26 PerlIO_write(fh, sp + o, sl - o < w ? sl - o : w);
279 26 PerlIO_putc(fh, '\n');
280 }
281 }
282 14 ▶ if (PerlIO_error(fh)) croak("%s: error writing FASTA: %s", __func__, Strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
if (PerlIO_error(fh)) croak("%s: error writing FASTA: %s", __func__, Strerror(errno)); 0 14 14
283 14 }
284  
285 /*Building a FASTA index, samtools's .fai, for fasta_index() and fasta_region()
286 (since 2026-11-18; until then a perl readline loop in lib/Cn/Bioinf.pm's
287 _fai_scan, whose rules these are, line for line).
288  
289 What is and is not a sequence that can be indexed is decided as fai_build_core()
290 of htslib 1.25's faidx.c decides it, and t/faidx.t checks the result against
291 that library's own expected index. A line is read in pieces, as the blocks
292 cut it, and only its length, the bytes of it that C's isgraph() takes, and its
293 first byte are kept; only a defline is copied, for its name. The index is
294 built as the .fai's own text, which fasta_index() writes as it is, rather than
295 as a perl array for each sequence. On a 305 MB file of 60 random sequences of
296 5 Mb in 60-column lines (2026-11-18, in the page cache, best of three), the
297 perl loop took 2.00 s and this 0.097 s, and the two indexes were identical.
298  
299 Nothing croaks here. A file that cannot be indexed sets error, and the line
300 and name it concerns, for the perl side to word the message, which names the
301 public function the file was given to; a read error is one too.*/
302  
303 /*Whether c is a base as fai_build_core() counts one: isgraph() in the C
304 locale, 0x21 '!' to 0x7e '~', 94 values in all.*/
305 #define FAI_GRAPH(c) ((unsigned char)((c) - 0x21) < 0x5e)
306  
307 /*How many bytes of p..e FAI_GRAPH() takes, 8 at a time.
308  
309 A word all of whose bytes are bases, which is nearly every word of a FASTA, is
310 counted whole: no byte below 0x21 is hasless(w, 0x21) and no byte above 0x7e
311 hasmore(w, 0x7e), from Sean Eron Anderson's "Bit Twiddling Hacks"
312 (graphics.stanford.edu/~seander/bithacks.html, sections HasLessInWord and
313 HasMoreInWord). Either may report a byte that is not there (a carry out of a
314 byte of 0xff reaches the next), but never misses one, so a word they flag is
315 merely counted a byte at a time. Counted a byte at a time throughout, the
316 file above took 0.22 s (gcc -O2 does not vectorize the loop).*/
317 4065 static uint64_t fai_graph(const char *p, const char *e) {
318 4065 const uint64_t ones = UINT64_C(0x0101010101010101), high = ones * 0x80;
319 4065 uint64_t n = 0;
320 32109 ▶ for (; e - p >= 8; p += 8) {
Branch: 1 branch
BranchTrueFalseTotal
for (; e - p >= 8; p += 8) { 28044 4065 32109
321 uint64_t w;
322 28044 memcpy(&w, p, 8);// not a cast to uint64_t *, since SPARC and some ARM fault on an unaligned load
323 28044 ▶ if (!(((w - ones * 0x21) & ~w & high) | (((w + ones) | w) & high))) {
Branch: 1 branch
BranchTrueFalseTotal
if (!(((w - ones * 0x21) & ~w & high) | (((w + ones) | w) & high))) { 28044 0 28044
324 28044 n += 8;
325 28044 continue;
326 }
327 0 ▶ for (unsigned short int k = 0; k < 8; k++) n += FAI_GRAPH(p[k]);
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int k = 0; k < 8; k++) n += FAI_GRAPH(p[k]); 0 0 0
328 }
329 20222 ▶ for (; p < e; p++) n += FAI_GRAPH(*p);
Branch: 1 branch
BranchTrueFalseTotal
for (; p < e; p++) n += FAI_GRAPH(*p); 16157 4065 20222
330 4065 return n;
331 }
332  
333 /*The state of one scan. Positions and lengths are uint64_t, not UV, since a
334 32-bit perl (5.44.0-i686 here) has a 32-bit UV and a genome can be more than
335 4 GiB; perl's own arithmetic, which the readline loop used, went on in an NV.*/
336 typedef struct {
337 SV *text;// the index so far, as .fai lines
338 HV *seen;// the names indexed so far
339 AV *dups;// each name met again after its first sequence, for the perl side to warn of
340 SV *def;// the defline being read, its '>' gone
341 SV *name;// the sequence being read: its defline's first word
342 uint64_t pos;// bytes of the file before the line being read
343 uint64_t line;// lines begun, counted from 1 as $. counts them
344 uint64_t len;// bases of the sequence being read
345 uint64_t offset;// where its first base is, in bytes
346 uint64_t bases;// bases in each of its lines, from the first
347 uint64_t width;// bytes in each of its lines, line ending included
348 uint64_t ll;// bytes of the line being read so far, its '\n' left out
349 uint64_t cl;// those of them FAI_GRAPH() takes
350 char first;// the first byte of the line being read
351 bool started;// a line has been begun and not yet ended
352 bool named;// a defline has been read, so name is set
353 bool inside;// TRUE = the sequence's lines are being read; FALSE = they have ended, and only a blank line or a defline may follow
354 bool any;// the sequence has had a line, without which htslib does not count it as a sequence
355 const char *error;// NULL, or why the file can't be indexed: "read", "no_sequence", "before_defline", "after_short", "longer" or "none"
356 int read_errno;// errno when error is "read"; int, as C declares errno
357 } fai_state;
358  
359 /*n as decimal digits onto sv. sv_catpvf()'s %" UVuf " cannot take a uint64_t
360 on a perl whose UV is 32 bits.*/
361 112 static void fai_cat_u64(pTHX_ SV *sv, uint64_t n) {
362 char digits[20];// UINT64_MAX has 20
363 112 unsigned short int k = 0;
364 do {
365 185 digits[k++] = (char)('0' + n % 10);
366 185 n /= 10;
367 185 ▶ } while (n);
Branch: 1 branch
BranchTrueFalseTotal
} while (n); 73 112 185
368 297 ▶ while (k) sv_catpvn(sv, &digits[--k], 1);
Branch: 1 branch
BranchTrueFalseTotal
while (k) sv_catpvn(sv, &digits[--k], 1); 185 112 297
369 112 }
370  
371 /*n as a perl number: a UV where one holds it, and an NV, exact to 2^53, where
372 it does not, as perl's own arithmetic would have it.*/
373 21 static SV *fai_number(pTHX_ uint64_t n) {
374 21 return n <= (uint64_t)UV_MAX ? newSVuv((UV)n) : newSVnv((NV)n);
375 }
376  
377 /*The sequence that has been read added to the index, or, when one of its name
378 is there already, to s->dups alone, since the first is the one indexed.*/
379 30 static void fai_add(pTHX_ fai_state *s) {
380 30 ▶ if (hv_exists_ent(s->seen, s->name, 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (hv_exists_ent(s->seen, s->name, 0)) { 2 28 30
381 2 av_push(s->dups, newSVsv(s->name));
382 2 return;
383 }
384 28 (void)hv_store_ent(s->seen, s->name, newSV(0), 0);
385 28 sv_catsv(s->text, s->name);
386 28 const uint64_t field[4] = { s->len, s->offset, s->bases, s->width };
387 140 ▶ for (unsigned short int k = 0; k < 4; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int k = 0; k < 4; k++) { 112 28 140
388 112 sv_catpvs(s->text, "\t");
389 112 fai_cat_u64(aTHX_ s->text, field[k]);
390 }
391 28 sv_catpvs(s->text, "\n");
392 }
393  
394 /*The line that has been read ended: by a '\n' when nl, and otherwise by the
395 end of the file.*/
396 4101 static void fai_line(pTHX_ fai_state *s, bool nl) {
397 4101 s->started = FALSE;
398 4101 ▶ s->pos += s->ll + (nl ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
s->pos += s->ll + (nl ? 1 : 0); 4098 3 4101
399 4101 ▶ if (s->first == '>') {
Branch: 1 branch
BranchTrueFalseTotal
if (s->first == '>') { 38 4063 4101
400 38 ▶ if (s->any) fai_add(aTHX_ s);
Branch: 1 branch
BranchTrueFalseTotal
if (s->any) fai_add(aTHX_ s); 21 17 38
401 38 ▶ if (!nl) {
Branch: 1 branch
BranchTrueFalseTotal
if (!nl) { 2 36 38
402 2 s->error = "no_sequence";
403 2 return;
404 }
405 /*the name is the defline's first word, after any space that follows the
406 '>'. FASTA_SPACE() is C's isspace() less the '\n' a defline cannot hold,
407 which is what fai_build_core() tests (state IN_NAME, in the htslib source
408 at ~/prog/htslib, 1.21-34-gb14fffb4, read on 2026-11-18); the perl loop's
409 \s left '\v' out of it before perl 5.18.*/
410 STRLEN dl;
411 36 const char *d = SvPV_const(s->def, dl), *de = d + dl;// not restrict: perl's buffer
412 42 ▶ while (d < de && FASTA_SPACE(*d)) d++;
Branch: 3 branches
BranchTrueFalseTotal
while (d < de && FASTA_SPACE(*d)) d++; 40 2 42
while (d < de && FASTA_SPACE(*d)) d++; 6 34 40
while (d < de && FASTA_SPACE(*d)) d++; 0 34 34
413 36 const char *w = d;
414 140193 ▶ while (w < de && !FASTA_SPACE(*w)) w++;
Branch: 3 branches
BranchTrueFalseTotal
while (w < de && !FASTA_SPACE(*w)) w++; 140167 26 140193
while (w < de && !FASTA_SPACE(*w)) w++; 140158 9 140167
while (w < de && !FASTA_SPACE(*w)) w++; 140157 1 140158
415 36 sv_setpvn(s->name, d, (STRLEN)(w - d));
416 36 s->named = TRUE;
417 36 s->len = s->bases = s->width = 0;
418 36 s->offset = s->pos;
419 36 s->inside = TRUE;
420 36 s->any = FALSE;
421 4063 ▶ } else if (s->inside && nl && s->ll == 0) {
Branch: 3 branches
BranchTrueFalseTotal
} else if (s->inside && nl && s->ll == 0) { 4053 10 4063
} else if (s->inside && nl && s->ll == 0) { 4052 1 4053
} else if (s->inside && nl && s->ll == 0) { 2 4050 4052
422 2 s->inside = FALSE;
423 4061 ▶ } else if (!s->inside) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (!s->inside) { 10 4051 4061
424 10 ▶ if (nl && (s->ll == 0 || (s->ll == 1 && s->first == '\r'))) return;// a blank line, LF or CRLF
Branch: 4 branches
BranchTrueFalseTotal
if (nl && (s->ll == 0 || (s->ll == 1 && s->first == '\r'))) return;// a blank line, LF or CRLF 10 0 10
if (nl && (s->ll == 0 || (s->ll == 1 && s->first == '\r'))) return;// a blank line, LF or CRLF 6 4 10
if (nl && (s->ll == 0 || (s->ll == 1 && s->first == '\r'))) return;// a blank line, LF or CRLF 2 4 6
if (nl && (s->ll == 0 || (s->ll == 1 && s->first == '\r'))) return;// a blank line, LF or CRLF 2 0 2
425 4 ▶ s->error = s->named ? "after_short" : "before_defline";
Branch: 1 branch
BranchTrueFalseTotal
s->error = s->named ? "after_short" : "before_defline"; 2 2 4
426 } else {
427 /*the line's bytes with its line feed, which htslib counts even for a
428 last line that has none*/
429 4051 const uint64_t width = s->ll + 1;
430 4051 s->any = TRUE;
431 4051 s->len += s->cl;
432 4051 ▶ if (s->width == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->width == 0) { 34 4017 4051
433 34 s->width = width;
434 34 s->bases = s->cl;
435 4017 ▶ } else if (width < s->width) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (width < s->width) { 10 4007 4017
436 10 s->inside = FALSE;
437 4007 ▶ } else if (width > s->width) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (width > s->width) { 2 4005 4007
438 2 s->error = "longer";
439 }
440 }
441 }
442  
443 /*The FASTA fh scanned into s, whose text, seen, dups, def and name the caller
444 makes. buf is FASTA_BLOCK bytes.*/
445 21 static void fai_scan(pTHX_ PerlIO *fh, fai_state *s, char *restrict buf) {
446 17 for (;;) {
447 38 const SSize_t n = PerlIO_read(fh, buf, FASTA_BLOCK);
448 38 ▶ if (n < 0 || PerlIO_error(fh)) {
Branch: 2 branches
BranchTrueFalseTotal
if (n < 0 || PerlIO_error(fh)) { 38 0 38
if (n < 0 || PerlIO_error(fh)) { 0 38 38
449 0 s->error = "read";
450 0 s->read_errno = errno;
451 0 return;
452 }
453 38 ▶ if (n == 0) break;
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) break; 15 23 38
454 23 const char *p = buf, *end = buf + n;
455 4153 ▶ while (p < end) {
Branch: 1 branch
BranchTrueFalseTotal
while (p < end) { 4143 10 4153
456 4143 ▶ if (!s->started) {
Branch: 1 branch
BranchTrueFalseTotal
if (!s->started) { 4101 42 4143
457 4101 s->started = TRUE;
458 4101 s->line++;
459 4101 s->ll = s->cl = 0;
460 4101 s->first = *p;
461 4101 ▶ if (*p == '>') {
Branch: 1 branch
BranchTrueFalseTotal
if (*p == '>') { 38 4063 4101
462 38 SvCUR_set(s->def, 0);
463 38 s->ll = 1;
464 38 p++;
465 38 continue;
466 }
467 }
468 4105 const char *nl = (const char*)memchr(p, '\n', (size_t)(end - p));
469 4105 ▶ const char *e = nl ? nl : end;
Branch: 1 branch
BranchTrueFalseTotal
const char *e = nl ? nl : end; 4098 7 4105
470 4105 ▶ if (s->first == '>') sv_catpvn(s->def, p, (STRLEN)(e - p));
Branch: 1 branch
BranchTrueFalseTotal
if (s->first == '>') sv_catpvn(s->def, p, (STRLEN)(e - p)); 40 4065 4105
471 4065 else s->cl += fai_graph(p, e);
472 4105 s->ll += (uint64_t)(e - p);
473 4105 ▶ if (!nl) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!nl) break; 7 4098 4105
474 4098 p = nl + 1;
475 4098 fai_line(aTHX_ s, TRUE);
476 4098 ▶ if (s->error) return;
Branch: 1 branch
BranchTrueFalseTotal
if (s->error) return; 6 4092 4098
477 }
478 }
479 15 ▶ if (s->started) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->started) { 3 12 15
480 3 fai_line(aTHX_ s, FALSE);
481 3 ▶ if (s->error) return;
Branch: 1 branch
BranchTrueFalseTotal
if (s->error) return; 2 1 3
482 }
483 13 ▶ if (!s->any) s->error = s->named ? "no_sequence" : "none";
Branch: 2 branches
BranchTrueFalseTotal
if (!s->any) s->error = s->named ? "no_sequence" : "none"; 4 9 13
if (!s->any) s->error = s->named ? "no_sequence" : "none"; 2 2 4
484 9 else fai_add(aTHX_ s);
485 }
486  
487 /*Reading a VCF, for sex_check(), parent(), relatedness(), concordance(),
488 hirisplex_genotypes(), blood_type() and admixture().
489  
490 The file is read by perl, which knows gzip and bzip2 through IO::Uncompress
491 (linking zlib and libbz2 here would be a build dependency on every platform),
492 and handed over a block at a time. vcf_read() cuts the blocks into lines and
493 gives each record to the reader's on_record, keeping nothing itself but the
494 one line a block can end inside; what each caller keeps is its own.*/
495  
496 typedef struct vcf_reader vcf_reader;
497 struct vcf_reader {
498 const char *name;// the file's, for messages
499 UV line;// 1-based, as $. would count it
500 UV min_depth;// a genotype whose DP is below this is not counted
501 size_t n;// samples; 0 until the #CHROM line
502 bool header;// the #CHROM line has been read
503 bool stop;// set by on_header to read no further, as concordance() does to learn the truth's samples
504 HV *samples;// sample => its 0-based column among the samples
505 AV *names;// the samples in file order
506 void (*on_header)(pTHX_ vcf_reader *r);// once the #CHROM line has been read
507 void (*on_record)(pTHX_ vcf_reader *r, const char *p, const char *e);// each record, its '\n' gone
508 };
509  
510 /*The end of the tab-separated field that starts at p, before e.*/
511 4622447 static const char *vcf_field_end(const char *p, const char *e) {
512 4622447 const char *t = (const char*)memchr(p, '\t', (size_t)(e - p));
513 4622447 ▶ return t ? t : e;
Branch: 1 branch
BranchTrueFalseTotal
return t ? t : e; 4276263 346184 4622447
514 }
515  
516 /*Sub-field k (0-based) of the colon-separated p..e, in *s..*f, or FALSE when
517 there are fewer.*/
518 1399587 static bool vcf_subfield(const char *p, const char *e, size_t k, const char **s, const char **f) {
519 2001802 ▶ for (; k; k--) {
Branch: 1 branch
BranchTrueFalseTotal
for (; k; k--) { 602420 1399382 2001802
520 602420 p = (const char*)memchr(p, ':', (size_t)(e - p));
521 602420 ▶ if (!p) return FALSE;
Branch: 1 branch
BranchTrueFalseTotal
if (!p) return FALSE; 205 602215 602420
522 602215 p++;
523 }
524 1399382 *s = p;
525 1399382 const char *c = (const char*)memchr(p, ':', (size_t)(e - p));
526 1399382 ▶ *f = c ? c : e;
Branch: 1 branch
BranchTrueFalseTotal
*f = c ? c : e; 554114 845268 1399382
527 1399382 return TRUE;
528 }
529  
530 /*The chromosome that CHROM p..f names, numbered as PLINK numbers them: 1 to
531 22, 23 for X and 24 for Y, and 0 for any other (MT, an unplaced contig). A
532 "chr" prefix, in any case, is dropped.*/
533 442777 static unsigned short int vcf_chrom(const char *p, const char *f) {
534 442777 ▶ if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3;
Branch: 7 branches
BranchTrueFalseTotal
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 245890 196887 442777
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 0 245890 245890
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 0 0 0
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 0 245890 245890
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 0 0 0
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 0 245890 245890
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 0 0 0
535 442777 ▶ if (f - p == 1 && (*p == 'X' || *p == 'x')) return 23;
Branch: 3 branches
BranchTrueFalseTotal
if (f - p == 1 && (*p == 'X' || *p == 'x')) return 23; 231203 211574 442777
if (f - p == 1 && (*p == 'X' || *p == 'x')) return 23; 229293 1910 231203
if (f - p == 1 && (*p == 'X' || *p == 'x')) return 23; 0 229293 229293
536 440867 ▶ if (f - p == 1 && (*p == 'Y' || *p == 'y')) return 24;
Branch: 3 branches
BranchTrueFalseTotal
if (f - p == 1 && (*p == 'Y' || *p == 'y')) return 24; 229293 211574 440867
if (f - p == 1 && (*p == 'Y' || *p == 'y')) return 24; 229090 203 229293
if (f - p == 1 && (*p == 'Y' || *p == 'y')) return 24; 0 229090 229090
537 440664 ▶ if (f - p < 1 || f - p > 2 || *p < '1' || *p > '9') return 0;// "01" is not chromosome 1
Branch: 4 branches
BranchTrueFalseTotal
if (f - p < 1 || f - p > 2 || *p < '1' || *p > '9') return 0;// "01" is not chromosome 1 440664 0 440664
if (f - p < 1 || f - p > 2 || *p < '1' || *p > '9') return 0;// "01" is not chromosome 1 440533 131 440664
if (f - p < 1 || f - p > 2 || *p < '1' || *p > '9') return 0;// "01" is not chromosome 1 440402 131 440533
if (f - p < 1 || f - p > 2 || *p < '1' || *p > '9') return 0;// "01" is not chromosome 1 131 440271 440402
538 440271 unsigned short int c = (unsigned short int)(*p - '0');
539 440271 ▶ if (f - p == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (f - p == 2) { 211312 228959 440271
540 211312 ▶ if (p[1] < '0' || p[1] > '9') return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (p[1] < '0' || p[1] > '9') return 0; 211312 0 211312
if (p[1] < '0' || p[1] > '9') return 0; 0 211312 211312
541 211312 c = (unsigned short int)(c * 10 + (p[1] - '0'));
542 }
543 440271 ▶ return c <= 24 ? c : 0;
Branch: 1 branch
BranchTrueFalseTotal
return c <= 24 ? c : 0; 440271 0 440271
544 }
545  
546 /*The index of base c, 0 to 3 for A, C, G and T in either case, or 4 for
547 anything else.*/
548 1010044 static unsigned short int vcf_base_index(char c) {
549 1010044 switch (c) {
550 310732 case 'A': case 'a': return 0;
551 195462 case 'C': case 'c': return 1;
552 308014 case 'G': case 'g': return 2;
553 195602 case 'T': case 't': return 3;
554 234 default: return 4;
555 }
556 }
557  
558 /*Whether p..e is one base, as a SNV's REF and ALT are. An ALT of ".", "*" or
559 "<NON_REF>", or with a comma, is not.*/
560 663986 static bool vcf_base(const char *p, const char *e) {
561 663986 ▶ return e - p == 1 && vcf_base_index(*p) < 4;
Branch: 2 branches
BranchTrueFalseTotal
return e - p == 1 && vcf_base_index(*p) < 4; 663716 270 663986
return e - p == 1 && vcf_base_index(*p) < 4; 663482 234 663716
562 }
563  
564 /*Where each of the 9 fixed columns of the record p..e starts, in col, given
565 that CHROM ends at f; returns where FORMAT ends, so that col[i + 1] - 1 ends
566 column i.*/
567 346572 static const char *vcf_columns(pTHX_ const vcf_reader *r, const char *p, const char *f, const char *e, const char **col) {
568 346572 col[0] = p;
569 3119139 ▶ for (unsigned short int i = 1; i < 9; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int i = 1; i < 9; i++) { 2772569 346570 3119139
570 2772569 ▶ if (f >= e) croak("%s: %s line %" UVuf " has %u columns, and a record needs 9 and a sample", __func__, r->name, r->line, (unsigned)i);
Branch: 1 branch
BranchTrueFalseTotal
if (f >= e) croak("%s: %s line %" UVuf " has %u columns, and a record needs 9 and a sample", __func__, r->name, r->line, (unsigned)i); 2 2772567 2772569
571 2772567 col[i] = f + 1;
572 2772567 f = vcf_field_end(col[i], e);
573 }
574 346570 return f;
575 }
576  
577 /*POS, the field p..f.*/
578 186428 static UV vcf_pos(pTHX_ const vcf_reader *r, const char *p, const char *f) {
579 186428 ▶ if (p == f) croak("%s: %s line %" UVuf " has an empty POS", __func__, r->name, r->line);
Branch: 1 branch
BranchTrueFalseTotal
if (p == f) croak("%s: %s line %" UVuf " has an empty POS", __func__, r->name, r->line); 1 186427 186428
580 186427 UV pos = 0;
581 1377134 ▶ for (const char *q = p; q < f; q++) {
Branch: 1 branch
BranchTrueFalseTotal
for (const char *q = p; q < f; q++) { 1190711 186423 1377134
582 1190711 ▶ if (*q < '0' || *q > '9' || pos > (UV_MAX - 9) / 10) croak("%s: %s line %" UVuf " has POS \"%.*s\", which isn't a position", __func__, r->name, r->line, (int)(f - p), p);
Branch: 3 branches
BranchTrueFalseTotal
if (*q < '0' || *q > '9' || pos > (UV_MAX - 9) / 10) croak("%s: %s line %" UVuf " has POS \"%.*s\", which isn't a position", __func__, r->name, r->line, (int)(f - p), p); 1190711 0 1190711
if (*q < '0' || *q > '9' || pos > (UV_MAX - 9) / 10) croak("%s: %s line %" UVuf " has POS \"%.*s\", which isn't a position", __func__, r->name, r->line, (int)(f - p), p); 1190708 3 1190711
if (*q < '0' || *q > '9' || pos > (UV_MAX - 9) / 10) croak("%s: %s line %" UVuf " has POS \"%.*s\", which isn't a position", __func__, r->name, r->line, (int)(f - p), p); 1 1190707 1190708
583 1190707 pos = pos * 10 + (UV)(*q - '0');
584 }
585 186423 return pos;
586 }
587  
588 #define VCF_ABSENT ((size_t)-1) // a key that FORMAT doesn't name
589  
590 /*GT's and DP's places in FORMAT, the field p..e, in *gt and *dp, or
591 VCF_ABSENT.*/
592 345780 static void vcf_format(const char *p, const char *e, size_t *gt, size_t *dp) {
593 345780 *gt = *dp = VCF_ABSENT;
594 345780 size_t k = 0;
595 964054 ▶ for (const char *s = p; s <= e; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (const char *s = p; s <= e; k++) { 618274 345780 964054
596 618274 const char *c = (const char*)memchr(s, ':', (size_t)(e - s));
597 618274 ▶ const char *ce = c ? c : e;
Branch: 1 branch
BranchTrueFalseTotal
const char *ce = c ? c : e; 272494 345780 618274
598 618274 ▶ if (ce - s == 2 && s[0] == 'G' && s[1] == 'T') *gt = k;
Branch: 3 branches
BranchTrueFalseTotal
if (ce - s == 2 && s[0] == 'G' && s[1] == 'T') *gt = k; 618274 0 618274
if (ce - s == 2 && s[0] == 'G' && s[1] == 'T') *gt = k; 345606 272668 618274
if (ce - s == 2 && s[0] == 'G' && s[1] == 'T') *gt = k; 345606 0 345606
599 272668 ▶ else if (ce - s == 2 && s[0] == 'D' && s[1] == 'P') *dp = k;
Branch: 3 branches
BranchTrueFalseTotal
else if (ce - s == 2 && s[0] == 'D' && s[1] == 'P') *dp = k; 272668 0 272668
else if (ce - s == 2 && s[0] == 'D' && s[1] == 'P') *dp = k; 272668 0 272668
else if (ce - s == 2 && s[0] == 'D' && s[1] == 'P') *dp = k; 272668 0 272668
600 618274 s = ce + 1;
601 }
602 345780 }
603  
604 //What vcf_call() found
605 enum {
606 VCF_SHALLOW, // a DP below min_depth: the genotype is not counted at all
607 VCF_NO_CALL, // missing, partly missing ("./1"), cut short ("1/"), more than two alleles, or an allele the site lacks
608 VCF_CALL // one or two alleles, each REF or the one ALT
609 };
610  
611 /*Whether the sample field p..e, whose FORMAT has DP at dp, has a DP below
612 r->min_depth. A DP that is absent, "." or not a whole number is not.*/
613 845268 static bool vcf_shallow(const vcf_reader *r, const char *p, const char *e, size_t dp) {
614 const char *s, *sf;
615 845268 ▶ if (dp == VCF_ABSENT || !vcf_subfield(p, e, dp, &s, &sf) || s == sf || *s == '.') return FALSE;
Branch: 4 branches
BranchTrueFalseTotal
if (dp == VCF_ABSENT || !vcf_subfield(p, e, dp, &s, &sf) || s == sf || *s == '.') return FALSE; 602420 242848 845268
if (dp == VCF_ABSENT || !vcf_subfield(p, e, dp, &s, &sf) || s == sf || *s == '.') return FALSE; 602215 205 602420
if (dp == VCF_ABSENT || !vcf_subfield(p, e, dp, &s, &sf) || s == sf || *s == '.') return FALSE; 602215 0 602215
if (dp == VCF_ABSENT || !vcf_subfield(p, e, dp, &s, &sf) || s == sf || *s == '.') return FALSE; 164 602051 602215
616 602051 UV depth = 0;
617 1757650 ▶ for (; s < sf; s++) {
Branch: 1 branch
BranchTrueFalseTotal
for (; s < sf; s++) { 1155599 602051 1757650
618 1155599 ▶ if (*s < '0' || *s > '9' || depth > (UV_MAX - 9) / 10) return FALSE;
Branch: 3 branches
BranchTrueFalseTotal
if (*s < '0' || *s > '9' || depth > (UV_MAX - 9) / 10) return FALSE; 1155599 0 1155599
if (*s < '0' || *s > '9' || depth > (UV_MAX - 9) / 10) return FALSE; 1155599 0 1155599
if (*s < '0' || *s > '9' || depth > (UV_MAX - 9) / 10) return FALSE; 0 1155599 1155599
619 1155599 depth = depth * 10 + (UV)(*s - '0');
620 }
621 602051 return depth < r->min_depth;
622 }
623  
624 /*The call in the sample field p..e of a biallelic site, whose FORMAT has GT
625 at gt and DP at dp: one of the values above, and for VCF_CALL the number of
626 alleles in *alleles and how many of them are the ALT in *alt. A DP that is
627 absent, "." or not a whole number leaves the genotype counted.*/
628 830285 static short int vcf_call(const vcf_reader *r, const char *p, const char *e, size_t gt, size_t dp, unsigned short int *alleles, unsigned short int *alt) {
629 const char *s, *sf;
630 830285 ▶ if (vcf_shallow(r, p, e, dp)) return VCF_SHALLOW;
Branch: 1 branch
BranchTrueFalseTotal
if (vcf_shallow(r, p, e, dp)) return VCF_SHALLOW; 47983 782302 830285
631 782302 *alleles = *alt = 0;
632 782302 ▶ if (!vcf_subfield(p, e, gt, &s, &sf) || s == sf) return VCF_NO_CALL;
Branch: 2 branches
BranchTrueFalseTotal
if (!vcf_subfield(p, e, gt, &s, &sf) || s == sf) return VCF_NO_CALL; 782302 0 782302
if (!vcf_subfield(p, e, gt, &s, &sf) || s == sf) return VCF_NO_CALL; 0 782302 782302
633 3108129 ▶ while (s < sf) {
Branch: 1 branch
BranchTrueFalseTotal
while (s < sf) { 1554059 771768 2325827
634 1554059 ▶ if (++*alleles > 2 || *s == '.') return VCF_NO_CALL;
Branch: 2 branches
BranchTrueFalseTotal
if (++*alleles > 2 || *s == '.') return VCF_NO_CALL; 1553950 109 1554059
if (++*alleles > 2 || *s == '.') return VCF_NO_CALL; 10313 1543637 1553950
635 1543637 ▶ if (*s == '1') ++*alt;
Branch: 1 branch
BranchTrueFalseTotal
if (*s == '1') ++*alt; 809996 733641 1543637
636 733641 ▶ else if (*s != '0') return VCF_NO_CALL;// no other allele exists at a biallelic site
Branch: 1 branch
BranchTrueFalseTotal
else if (*s != '0') return VCF_NO_CALL;// no other allele exists at a biallelic site 110 733531 733641
637 1543527 s++;
638 1543527 ▶ if (s < sf) {
Branch: 1 branch
BranchTrueFalseTotal
if (s < sf) { 771768 771759 1543527
639 771759 ▶ if (*s != '/' && *s != '|') return VCF_NO_CALL;
Branch: 2 branches
BranchTrueFalseTotal
if (*s != '/' && *s != '|') return VCF_NO_CALL; 160566 611193 771759
if (*s != '/' && *s != '|') return VCF_NO_CALL; 0 160566 160566
640 771759 ▶ if (++s == sf) return VCF_NO_CALL;// "1/": a separator with no allele after it is a call cut short, not a haploid one
Branch: 1 branch
BranchTrueFalseTotal
if (++s == sf) return VCF_NO_CALL;// "1/": a separator with no allele after it is a call cut short, not a haploid one 2 771757 771759
641 }
642 }
643 771768 return VCF_CALL;
644 }
645  
646 /*The end of sample i's field, which starts at p; dies when the record ends
647 before it.*/
648 1388912 static const char *vcf_sample(pTHX_ const vcf_reader *r, const char *p, const char *e, size_t i) {
649 1388912 ▶ if (p > e) croak("%s: %s line %" UVuf " has %" UVuf " samples, and the #CHROM line names %" UVuf, __func__, r->name, r->line, (UV)i, (UV)r->n);
Branch: 1 branch
BranchTrueFalseTotal
if (p > e) croak("%s: %s line %" UVuf " has %" UVuf " samples, and the #CHROM line names %" UVuf, __func__, r->name, r->line, (UV)i, (UV)r->n); 10 1388902 1388912
650 1388902 return vcf_field_end(p, e);
651 }
652  
653 /*Dies when anything is left of the record after its last sample, which would
654 start at p.*/
655 345672 static void vcf_samples_end(pTHX_ const vcf_reader *r, const char *p, const char *e) {
656 345672 ▶ if (p <= e) croak("%s: %s line %" UVuf " has more samples than the %" UVuf " its #CHROM line names", __func__, r->name, r->line, (UV)r->n);
Branch: 1 branch
BranchTrueFalseTotal
if (p <= e) croak("%s: %s line %" UVuf " has more samples than the %" UVuf " its #CHROM line names", __func__, r->name, r->line, (UV)r->n); 14 345658 345672
657 345658 }
658  
659 /*The first 5 of names, quoted, and how many more there are, which is enough
660 to show how a VCF's samples are named; a mortal's PV.*/
661 5 static const char *vcf_names_list(pTHX_ AV *names) {
662 5 SV *some = sv_2mortal(newSVpvs(""));
663 5 const SSize_t last = av_len(names);
664 20 ▶ for (SSize_t i = 0; i <= last && i < 5; i++) {
Branch: 2 branches
BranchTrueFalseTotal
for (SSize_t i = 0; i <= last && i < 5; i++) { 17 3 20
for (SSize_t i = 0; i <= last && i < 5; i++) { 15 2 17
665 15 SV **s = av_fetch(names, i, 0);
666 30 ▶ sv_catpvf(some, "%s\"%s\"", i ? ", " : "", s ? SvPV_nolen(*s) : "");
Branch: 2 branches
BranchTrueFalseTotal
sv_catpvf(some, "%s\"%s\"", i ? ", " : "", s ? SvPV_nolen(*s) : ""); 15 0 15
sv_catpvf(some, "%s\"%s\"", i ? ", " : "", s ? SvPV_nolen(*s) : ""); 10 5 15
667 }
668 5 ▶ if (last >= 5) sv_catpvf(some, " and %" UVuf " more", (UV)(last - 4));
Branch: 1 branch
BranchTrueFalseTotal
if (last >= 5) sv_catpvf(some, " and %" UVuf " more", (UV)(last - 4)); 2 3 5
669 5 return SvPV_nolen(some);
670 }
671  
672 /*The #CHROM line p..e: each sample after FORMAT gets its column in samples
673 and its place in names, and then the reader's on_header is called.*/
674 503 static void vcf_header(pTHX_ vcf_reader *r, const char *p, const char *e) {
675 503 ▶ if (r->header) croak("%s: %s line %" UVuf " is a second #CHROM line", __func__, r->name, r->line);
Branch: 1 branch
BranchTrueFalseTotal
if (r->header) croak("%s: %s line %" UVuf " is a second #CHROM line", __func__, r->name, r->line); 1 502 503
676 502 r->header = 1;
677 502 unsigned short int col = 0;// columns passed; the samples start after the 9th, FORMAT
678 5019 ▶ while (p <= e && col < 9) {
Branch: 2 branches
BranchTrueFalseTotal
while (p <= e && col < 9) { 5016 3 5019
while (p <= e && col < 9) { 4517 499 5016
679 4517 p = vcf_field_end(p, e) + 1;
680 4517 col++;
681 }
682 502 ▶ if (p > e) croak("%s: %s has no samples: its #CHROM line (line %" UVuf ") ends at %s", __func__, r->name, r->line, col < 9 ? "INFO or before" : "FORMAT");
Branch: 2 branches
BranchTrueFalseTotal
if (p > e) croak("%s: %s has no samples: its #CHROM line (line %" UVuf ") ends at %s", __func__, r->name, r->line, col < 9 ? "INFO or before" : "FORMAT"); 3 499 502
if (p > e) croak("%s: %s has no samples: its #CHROM line (line %" UVuf ") ends at %s", __func__, r->name, r->line, col < 9 ? "INFO or before" : "FORMAT"); 1 2 3
683 2413 ▶ while (p <= e) {
Branch: 1 branch
BranchTrueFalseTotal
while (p <= e) { 1916 497 2413
684 1916 const char *f = vcf_field_end(p, e);
685 // up to 2026-11-10 a tab at the end of the line made a sample named ""
686 1916 ▶ if (f == p) croak("%s: %s has an empty sample name in its #CHROM line (line %" UVuf "), column %" UVuf "; a tab at the end of the line, or two together, makes one", __func__, r->name, r->line, (UV)(r->n + 10));
Branch: 1 branch
BranchTrueFalseTotal
if (f == p) croak("%s: %s has an empty sample name in its #CHROM line (line %" UVuf "), column %" UVuf "; a tab at the end of the line, or two together, makes one", __func__, r->name, r->line, (UV)(r->n + 10)); 1 1915 1916
687 1915 SV *name = newSVpvn(p, (STRLEN)(f - p));
688 1915 ▶ if (hv_exists_ent(r->samples, name, 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (hv_exists_ent(r->samples, name, 0)) { 1 1914 1915
689 // mortal on a line of its own: SvPV_nolen() is a macro that evaluates its
690 // argument twice on perl 5.10.1 to 5.32.1, which then freed the name twice
691 // ("Attempt to free unreferenced scalar"); 5.42.3 and 5.44.0 were unaffected
692 1 sv_2mortal(name);
693 1 const char *dup = SvPV_nolen(name);
694 1 croak("%s: %s names sample \"%s\" twice in its #CHROM line", __func__, r->name, dup);
695 }
696 1914 (void)hv_store_ent(r->samples, name, newSVuv((UV)r->n), 0);
697 1914 av_push(r->names, name);
698 1914 r->n++;
699 1914 p = f + 1;
700 }
701 497 ▶ if (r->on_header) r->on_header(aTHX_ r);
Branch: 1 branch
BranchTrueFalseTotal
if (r->on_header) r->on_header(aTHX_ r); 497 0 497
702 490 }
703  
704 /*The line p..e, its '\n' gone.*/
705 357938 static void vcf_line(pTHX_ vcf_reader *r, const char *p, const char *e) {
706 357938 r->line++;
707 357938 ▶ if (e > p && e[-1] == '\r') e--;
Branch: 2 branches
BranchTrueFalseTotal
if (e > p && e[-1] == '\r') e--; 357937 1 357938
if (e > p && e[-1] == '\r') e--; 1419 356518 357937
708 357938 ▶ if (p == e) return;
Branch: 1 branch
BranchTrueFalseTotal
if (p == e) return; 1 357937 357938
709 357937 ▶ if (*p != '#') {
Branch: 1 branch
BranchTrueFalseTotal
if (*p != '#') { 356147 1790 357937
710 356147 ▶ if (!r->header) croak("%s: %s line %" UVuf " is a record, but no #CHROM line has come before it", __func__, r->name, r->line);
Branch: 1 branch
BranchTrueFalseTotal
if (!r->header) croak("%s: %s line %" UVuf " is a record, but no #CHROM line has come before it", __func__, r->name, r->line); 2 356145 356147
711 356145 r->on_record(aTHX_ r, p, e);
712 1790 ▶ } else if (e - p >= 6 && memcmp(p, "#CHROM", 6) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (e - p >= 6 && memcmp(p, "#CHROM", 6) == 0) { 1790 0 1790
} else if (e - p >= 6 && memcmp(p, "#CHROM", 6) == 0) { 503 1287 1790
713 503 vcf_header(aTHX_ r, p, e);
714 }
715 }
716  
717 /*The VCF r->name, which next, a perl sub, returns a block of at a time and
718 then undef. r's name, min_depth, on_header and on_record are the caller's to
719 set; the rest is set here.
720  
721 next may grow perl's stack, which moves it, so an XSUB that reaches this must
722 PUTBACK before and SPAGAIN after, and push nothing with the SP it had on entry.
723 Up to 2026-10-26 none did, and a reader that grew the stack lost the results
724 or corrupted the heap ("realloc(): invalid next size"); t/checks.t grows it.*/
725 512 static void vcf_read(pTHX_ SV *next, vcf_reader *r) {
726 512 r->line = 0;
727 512 r->n = 0;
728 512 r->header = FALSE;
729 512 r->samples = (HV*)sv_2mortal((SV*)newHV());
730 512 r->names = (AV*)sv_2mortal((SV*)newAV());
731 512 SV *carry = sv_2mortal(newSVpvs(""));// the start of a line that the last block ended inside
732 /*The block, copied out of the scope that next's own temporaries are freed
733 with, so that whatever on_header saves for freeing (with SAVEFREEPV, say)
734 lands in the caller's scope rather than that one; from perl 5.20 the copy
735 is copy-on-write, and moves no bytes.*/
736 512 SV *block = sv_newmortal();
737 880 for (;;) {
738 1392 dSP;
739 1392 ENTER;
740 1392 SAVETMPS;
741 1392 ▶ PUSHMARK(SP);
Branch: 1 branch
BranchTrueFalseTotal
PUSHMARK(SP); 0 1392 1392
742 1392 PUTBACK;
743 1392 I32 got = call_sv(next, G_SCALAR);
744 1390 SPAGAIN;
745 1390 ▶ sv_setsv(block, got ? POPs : &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
sv_setsv(block, got ? POPs : &PL_sv_undef); 1390 0 1390
746 1390 PUTBACK;
747 1390 ▶ FREETMPS;
Branch: 1 branch
BranchTrueFalseTotal
FREETMPS; 1390 0 1390
748 1390 LEAVE;
749 1390 ▶ if (!SvOK(block) || r->stop) break;
Branch: 2 branches
BranchTrueFalseTotal
if (!SvOK(block) || r->stop) break; 942 448 1390
if (!SvOK(block) || r->stop) break; 939 3 942
750 STRLEN n;
751 939 const char *b = SvPV_const(block, n), *end = b + n;// not restrict: perl's buffer
752 358817 ▶ while (b < end && !r->stop) {
Branch: 2 branches
BranchTrueFalseTotal
while (b < end && !r->stop) { 358429 388 358817
while (b < end && !r->stop) { 358369 60 358429
753 358369 const char *nl = (const char*)memchr(b, '\n', (size_t)(end - b));
754 358369 ▶ if (!nl) {
Branch: 1 branch
BranchTrueFalseTotal
if (!nl) { 432 357937 358369
755 432 sv_catpvn(carry, b, (STRLEN)(end - b));
756 432 break;
757 }
758 357937 ▶ if (SvCUR(carry)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvCUR(carry)) { 304 357633 357937
759 304 sv_catpvn(carry, b, (STRLEN)(nl - b));
760 304 vcf_line(aTHX_ r, SvPVX_const(carry), SvPVX_const(carry) + SvCUR(carry));
761 304 SvCUR_set(carry, 0);
762 } else {
763 357633 vcf_line(aTHX_ r, b, nl);
764 }
765 357878 b = nl + 1;
766 }
767 }
768 451 ▶ if (SvCUR(carry) && !r->stop) vcf_line(aTHX_ r, SvPVX_const(carry), SvPVX_const(carry) + SvCUR(carry));
Branch: 2 branches
BranchTrueFalseTotal
if (SvCUR(carry) && !r->stop) vcf_line(aTHX_ r, SvPVX_const(carry), SvPVX_const(carry) + SvCUR(carry)); 1 450 451
if (SvCUR(carry) && !r->stop) vcf_line(aTHX_ r, SvPVX_const(carry), SvPVX_const(carry) + SvCUR(carry)); 1 0 1
769 451 ▶ if (!r->header) croak("%s: %s has no #CHROM line, so it isn't a VCF", __func__, r->name);
Branch: 1 branch
BranchTrueFalseTotal
if (!r->header) croak("%s: %s has no #CHROM line, so it isn't a VCF", __func__, r->name); 6 445 451
770 445 }
771  
772 /*The genotype counts behind sex_check().
773  
774 The method is peddy 0.4.3's sex_check() (peddy/peddy.py): on X outside its
775 pseudo-autosomal regions, count each sample's heterozygous and homozygous-ALT
776 calls at biallelic sites, leaving out a genotype whose depth is below a
777 minimum. Its PAR bounds, X:10000-2781479 and X:154931044-156030895, cover both
778 GRCh37's and GRCh38's, so no build need be named. It departs from peddy in
779 three ways. Every site is read, where peddy stops at 10,000. Only SNVs are
780 counted, where peddy keeps an insertion (its test is len(REF) > 1 alone). And
781 peddy's cohort filters (a call rate of at least 0.5, an ALT frequency of at
782 least 0.01) are left out, since they mean nothing for a VCF of one genome,
783 which is the usual input here.
784  
785 Non-PAR Y is counted too, for the caller to see, but decides nothing: on
786 2026-10-18 the mother's exome, whose X is plainly female (2,592 het to 2,673
787 hom-ALT), had 530 called SNVs on non-PAR Y, and the father's exome had 659.
788 Y's PARs are GRCh37's (Y:10001-2649520, Y:59034050-59363566) and GRCh38's
789 (Y:10001-2781479, Y:56887903-57217415), from the GRC's assembly reports.
790  
791 Nothing is kept but a fixed set of counters for each sample.*/
792  
793 /*The counters kept for each sample, in this order in sex_tally's count; their
794 names in the hash returned to perl are SEX_NAME's.*/
795 enum { SEX_X_HET, SEX_X_HOM_ALT, SEX_X_HOM_REF, SEX_X_HAPLOID, SEX_X_MISSING, SEX_Y_CALLED, SEX_Y_ALT, SEX_FIELDS };
796 static const char *const SEX_NAME[SEX_FIELDS] = { "x_het", "x_hom_alt", "x_hom_ref", "x_haploid", "x_missing", "y_called", "y_alt" };
797  
798 typedef struct {
799 vcf_reader r;// first, so that the vcf_reader * that sex_header() and sex_record() are given is this
800 UV x_sites;// non-PAR X SNVs read, for perl to say when there were none
801 UV *count;// r.n * SEX_FIELDS counters, sample by sample
802 } sex_tally;
803  
804 /*Whether pos on chrom (23 for X, 24 for Y) lies in a pseudo-autosomal
805 region; see the comment above SEX_NAME for the bounds.*/
806 1767 static bool sex_par(unsigned short int chrom, UV pos) {
807 1767 ▶ if (chrom == 23) return (pos >= 10000 && pos <= 2781479) || (pos >= 154931044 && pos <= 156030895);
Branch: 5 branches
BranchTrueFalseTotal
if (chrom == 23) return (pos >= 10000 && pos <= 2781479) || (pos >= 154931044 && pos <= 156030895); 1614 153 1767
if (chrom == 23) return (pos >= 10000 && pos <= 2781479) || (pos >= 154931044 && pos <= 156030895); 1614 0 1614
if (chrom == 23) return (pos >= 10000 && pos <= 2781479) || (pos >= 154931044 && pos <= 156030895); 1578 36 1614
if (chrom == 23) return (pos >= 10000 && pos <= 2781479) || (pos >= 154931044 && pos <= 156030895); 36 1542 1578
if (chrom == 23) return (pos >= 10000 && pos <= 2781479) || (pos >= 154931044 && pos <= 156030895); 18 18 36
808 153 ▶ return (pos >= 10001 && pos <= 2781479) || (pos >= 56887903 && pos <= 57217415) || (pos >= 59034050 && pos <= 59363566);
Branch: 6 branches
BranchTrueFalseTotal
return (pos >= 10001 && pos <= 2781479) || (pos >= 56887903 && pos <= 57217415) || (pos >= 59034050 && pos <= 59363566); 153 0 153
return (pos >= 10001 && pos <= 2781479) || (pos >= 56887903 && pos <= 57217415) || (pos >= 59034050 && pos <= 59363566); 135 18 153
return (pos >= 10001 && pos <= 2781479) || (pos >= 56887903 && pos <= 57217415) || (pos >= 59034050 && pos <= 59363566); 36 99 135
return (pos >= 10001 && pos <= 2781479) || (pos >= 56887903 && pos <= 57217415) || (pos >= 59034050 && pos <= 59363566); 18 18 36
return (pos >= 10001 && pos <= 2781479) || (pos >= 56887903 && pos <= 57217415) || (pos >= 59034050 && pos <= 59363566); 18 99 117
return (pos >= 10001 && pos <= 2781479) || (pos >= 56887903 && pos <= 57217415) || (pos >= 59034050 && pos <= 59363566); 18 0 18
809 }
810  
811 /*Each sample's counters, once the #CHROM line has said how many samples
812 there are.*/
813 44 static void sex_header(pTHX_ vcf_reader *r) {
814 44 sex_tally *t = (sex_tally*)r;
815 44 ▶ Newxz(t->count, r->n * SEX_FIELDS, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(t->count, r->n * SEX_FIELDS, UV); 0 44 44
816 44 SAVEFREEPV(t->count);// freed at the caller's LEAVE, croak or not; see vcf_read()'s block
817 44 }
818  
819 /*Whether the record of chrom (23 for X, 24 for Y), whose columns vcf_columns()
820 put in col, is one that sex counts: outside the PARs, a biallelic SNV, and with
821 GT, whose place in FORMAT goes in *gt and DP's in *dp. format_end is
822 vcf_columns()'s.*/
823 1770 static bool sex_site(pTHX_ const vcf_reader *r, unsigned short int chrom, const char **col, const char *format_end, size_t *gt, size_t *dp) {
824 1770 UV pos = vcf_pos(aTHX_ r, col[1], col[2] - 1);
825 1767 ▶ if (sex_par(chrom, pos) || !vcf_base(col[3], col[4] - 1) || !vcf_base(col[4], col[5] - 1)) return FALSE;
Branch: 3 branches
BranchTrueFalseTotal
if (sex_par(chrom, pos) || !vcf_base(col[3], col[4] - 1) || !vcf_base(col[4], col[5] - 1)) return FALSE; 1659 108 1767
if (sex_par(chrom, pos) || !vcf_base(col[3], col[4] - 1) || !vcf_base(col[4], col[5] - 1)) return FALSE; 1623 36 1659
if (sex_par(chrom, pos) || !vcf_base(col[3], col[4] - 1) || !vcf_base(col[4], col[5] - 1)) return FALSE; 36 1587 1623
826 1587 vcf_format(col[8], format_end, gt, dp);
827 1587 return *gt != VCF_ABSENT;
828 }
829  
830 /*One sample's call, the field p..e, at a site of chrom that sex_site() took,
831 into c, the sample's SEX_FIELDS counters.*/
832 8005 static void sex_count(const vcf_reader *r, UV *c, unsigned short int chrom, const char *p, const char *e, size_t gt, size_t dp) {
833 unsigned short int alleles, alt;
834 8005 short int call = vcf_call(r, p, e, gt, dp, &alleles, &alt);
835 8053 ▶ if (call == VCF_SHALLOW) return;
Branch: 1 branch
BranchTrueFalseTotal
if (call == VCF_SHALLOW) return; 63 7942 8005
836 7942 ▶ if (chrom == 24) {
Branch: 1 branch
BranchTrueFalseTotal
if (chrom == 24) { 299 7643 7942
837 299 ▶ if (call == VCF_NO_CALL) return;
Branch: 1 branch
BranchTrueFalseTotal
if (call == VCF_NO_CALL) return; 48 251 299
838 251 c[SEX_Y_CALLED]++;
839 251 ▶ if (alt) c[SEX_Y_ALT]++;
Branch: 1 branch
BranchTrueFalseTotal
if (alt) c[SEX_Y_ALT]++; 100 151 251
840 7643 ▶ } else if (call == VCF_NO_CALL) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (call == VCF_NO_CALL) { 427 7216 7643
841 427 c[SEX_X_MISSING]++;
842 } else {
843 7216 ▶ if (alleles == 1) c[SEX_X_HAPLOID]++;
Branch: 1 branch
BranchTrueFalseTotal
if (alleles == 1) c[SEX_X_HAPLOID]++; 165 7051 7216
844 // a haploid call is hom-ALT or hom-REF, as peddy's cyvcf2 counts it
845 7216 ▶ c[alt == 0 ? SEX_X_HOM_REF : alt == alleles ? SEX_X_HOM_ALT : SEX_X_HET]++;
Branch: 2 branches
BranchTrueFalseTotal
c[alt == 0 ? SEX_X_HOM_REF : alt == alleles ? SEX_X_HOM_ALT : SEX_X_HET]++; 5200 2016 7216
c[alt == 0 ? SEX_X_HOM_REF : alt == alleles ? SEX_X_HOM_ALT : SEX_X_HET]++; 3604 1596 5200
846 }
847 }
848  
849 //The record p..e.*/
850 9739 static void sex_record(pTHX_ vcf_reader *r, const char *p, const char *e) {
851 9739 sex_tally *t = (sex_tally*)r;
852 9739 const char *f = vcf_field_end(p, e);
853 9739 unsigned short int chrom = vcf_chrom(p, f);// only 23 (X) and 24 (Y) are read
854 9937 ▶ if (chrom != 23 && chrom != 24) return;
Branch: 2 branches
BranchTrueFalseTotal
if (chrom != 23 && chrom != 24) return; 9004 735 9739
if (chrom != 23 && chrom != 24) return; 8892 112 9004
855 const char *col[9];
856 847 const char *format_end = vcf_columns(aTHX_ r, p, f, e, col);
857 size_t gt, dp;
858 846 ▶ if (!sex_site(aTHX_ r, chrom, col, format_end, &gt, &dp)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sex_site(aTHX_ r, chrom, col, format_end, &gt, &dp)) return; 198 645 843
859 645 ▶ if (chrom == 23) t->x_sites++;
Branch: 1 branch
BranchTrueFalseTotal
if (chrom == 23) t->x_sites++; 605 40 645
860 645 p = format_end + 1;
861 4416 ▶ for (size_t i = 0; i < r->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < r->n; i++) { 3777 639 4416
862 3777 const char *se = vcf_sample(aTHX_ r, p, e, i);
863 3771 sex_count(r, t->count + i * SEX_FIELDS, chrom, p, se, gt, dp);
864 3771 p = se + 1;
865 }
866 639 vcf_samples_end(aTHX_ r, p, e);
867 }
868  
869 /*The SEX_FIELDS counts in count of the n samples in names, each stored in out
870 as sample => hash of counts, in place of anything out held for it.*/
871 77 static void sex_rows(pTHX_ HV *out, AV *names, const UV *count, size_t n, const char *name) {
872 386 ▶ for (size_t i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < n; i++) { 309 77 386
873 309 SV **sample = av_fetch(names, (SSize_t)i, 0);
874 309 ▶ if (!sample) croak("%s: sample %" UVuf " of %s has lost its name", __func__, (UV)i, name);// cannot happen: every sample read was pushed
Branch: 1 branch
BranchTrueFalseTotal
if (!sample) croak("%s: sample %" UVuf " of %s has lost its name", __func__, (UV)i, name);// cannot happen: every sample read was pushed 0 309 309
875 309 HV *row = newHV();
876 2472 ▶ for (unsigned short int k = 0; k < SEX_FIELDS; k++) (void)hv_store(row, SEX_NAME[k], (I32)strlen(SEX_NAME[k]), newSVuv(count[i * SEX_FIELDS + k]), 0);
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int k = 0; k < SEX_FIELDS; k++) (void)hv_store(row, SEX_NAME[k], (I32)strlen(SEX_NAME[k]), newSVuv(count[i * SEX_FIELDS + k]), 0); 2163 309 2472
877 309 (void)hv_store_ent(out, *sample, newRV_noinc((SV*)row), 0);
878 }
879 77 }
880  
881 /*The counts of every sample of the VCF name, which next returns a block of
882 at a time. Returns sample => hash of counts, and sets *x_sites and *names,
883 the samples in file order, for the report.*/
884 52 static HV *sex_tally_vcf(pTHX_ SV *next, const char *name, UV min_depth, UV *x_sites, AV **names) {
885 sex_tally t;
886 52 Zero(&t, 1, sex_tally);
887 52 t.r.name = name;
888 52 t.r.min_depth = min_depth;
889 52 t.r.on_header = sex_header;
890 52 t.r.on_record = sex_record;
891 52 vcf_read(aTHX_ next, &t.r);
892 32 HV *out = t.r.samples;
893 32 sex_rows(aTHX_ out, t.r.names, t.count, t.r.n, name);// in place of the columns vcf_header() stored
894 32 *x_sites = t.x_sites;
895 32 *names = t.r.names;
896 32 return out;
897 }
898  
899 /*The genotype counts behind parent(): how many autosomal biallelic SNVs the
900 child and the parent have with each pair of ALT counts, 0 to 2. perl takes
901 IBS0, IBS1, IBS2 and the KING-robust kinship from those nine numbers.
902  
903 The two samples are either columns of one VCF, which is read a record at a
904 time and nothing kept but the nine counts, or each the one sample of its own
905 VCF. A VCF of one genome usually lists only the sites where its sample
906 carries an ALT allele, so that a site absent from it stands for hom-REF; the
907 two are then compared site by site, which takes each file's sites in memory,
908 8 bytes a site, sorted (by C89's qsort(), since the two files need not list
909 their chromosomes in the same order). A position is left out when either file
910 has more than one SNV there, a call that is not a diploid call of REF and
911 ALT, a DP below min_depth, or more than one ALT, or when the files give it
912 different REF or ALT alleles. A file that leaves out filtered sites, or
913 off-target ones, makes the comparison see hom-REF where the sample was never
914 called; perl's report gives the sites each file had alone, for that reason.*/
915  
916 #define PARENT_NONE 3 // the code of a sample with no diploid call of REF and ALT, or a DP below min_depth
917  
918 /*A site of an own VCF is one uint64_t, packed so that sorting the numbers
919 sorts the sites by chromosome and then position, and the sites at one
920 position share every bit from bit 7 up:
921  
922 chromosome (1-22) << 39 | POS (32 bits) << 7 | REF << 5 | ALT << 2 | code
923  
924 where REF and ALT are vcf_base_index()'s 0 to 3, ALT is 4 for a record of
925 more than one ALT, and code is the ALT count or PARENT_NONE.*/
926 #define PARENT_POS_SHIFT 7
927 #define PARENT_ALLELES(k) (((k) >> 2) & 0x1f) // REF and ALT together
928 #define PARENT_ALT(k) (((k) >> 2) & 7)
929 #define PARENT_CODE(k) ((unsigned short int)((k) & 3))
930  
931 /*An own VCF's sites, in a holder that the scope's destructor frees, since
932 Renew() moves the array.*/
933 typedef struct {
934 uint64_t *site;
935 size_t n, room;// sites used and allocated
936 } parent_sites;
937  
938 131 static void parent_sites_free(pTHX_ void *p) {
939 131 parent_sites *s = (parent_sites*)p;
940 131 Safefree(s->site);
941 131 Safefree(s);
942 131 }
943  
944 typedef struct {
945 vcf_reader r;// first, so that the vcf_reader * that the callbacks are given is this
946 SV *want[2];// one VCF: the child's and the parent's sample names; unused for own VCFs
947 size_t col[2];// one VCF: their columns among the samples
948 UV t[9];// one VCF: t[3 * child + parent], sites by the two codes
949 parent_sites *sites;// own VCF: the file's sites
950 } parent_reader;
951  
952 //The code of the call in the sample field p..e: its ALT count, or PARENT_NONE
953 661468 static unsigned short int parent_code(const vcf_reader *r, const char *p, const char *e, size_t gt, size_t dp) {
954 unsigned short int alleles, alt;
955 661468 ▶ return vcf_call(r, p, e, gt, dp, &alleles, &alt) == VCF_CALL && alleles == 2 ? alt : PARENT_NONE;
Branch: 2 branches
BranchTrueFalseTotal
return vcf_call(r, p, e, gt, dp, &alleles, &alt) == VCF_CALL && alleles == 2 ? alt : PARENT_NONE; 603819 57649 661468
return vcf_call(r, p, e, gt, dp, &alleles, &alt) == VCF_CALL && alleles == 2 ? alt : PARENT_NONE; 603728 91 603819
956 }
957  
958 //One VCF: where the child's and the parent's columns are.
959 60 static void parent_header_one(pTHX_ vcf_reader *r) {
960 60 parent_reader *t = (parent_reader*)r;
961 179 ▶ for (unsigned short int k = 0; k < 2; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int k = 0; k < 2; k++) { 120 59 179
962 120 HE *he = hv_fetch_ent(r->samples, t->want[k], 0, 0);
963 120 ▶ if (he) {
Branch: 1 branch
BranchTrueFalseTotal
if (he) { 119 1 120
964 119 t->col[k] = (size_t)SvUV(HeVAL(he));
965 119 continue;
966 }
967 2 const char *want = SvPV_nolen(t->want[k]), *list = vcf_names_list(aTHX_ r->names);
968 1 croak("%s: %s has no sample \"%s\"; its samples are %s", __func__, r->name, want, list);
969 }
970 59 }
971  
972 //One VCF: the record p..e.
973 111040 static void parent_record_one(pTHX_ vcf_reader *r, const char *p, const char *e) {
974 111040 parent_reader *t = (parent_reader*)r;
975 111040 const char *f = vcf_field_end(p, e);
976 111040 unsigned short int chrom = vcf_chrom(p, f);
977 111275 ▶ if (chrom < 1 || chrom > 22) return;
Branch: 2 branches
BranchTrueFalseTotal
if (chrom < 1 || chrom > 22) return; 110899 141 111040
if (chrom < 1 || chrom > 22) return; 143 110756 110899
978 const char *col[9];
979 110756 const char *format_end = vcf_columns(aTHX_ r, p, f, e, col);
980 110756 ▶ if (!vcf_base(col[3], col[4] - 1) || !vcf_base(col[4], col[5] - 1)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!vcf_base(col[3], col[4] - 1) || !vcf_base(col[4], col[5] - 1)) return; 110709 47 110756
if (!vcf_base(col[3], col[4] - 1) || !vcf_base(col[4], col[5] - 1)) return; 141 110568 110709
981 size_t gt, dp;
982 110568 vcf_format(col[8], format_end, &gt, &dp);
983 110568 ▶ if (gt == VCF_ABSENT) return;
Branch: 1 branch
BranchTrueFalseTotal
if (gt == VCF_ABSENT) return; 47 110521 110568
984 110521 unsigned short int code[2] = { PARENT_NONE, PARENT_NONE };// the child's and the parent's
985 110521 p = format_end + 1;
986 874148 ▶ for (size_t i = 0; i < r->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < r->n; i++) { 763627 110521 874148
987 763627 const char *se = vcf_sample(aTHX_ r, p, e, i);
988 2290881 ▶ for (unsigned short int k = 0; k < 2; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int k = 0; k < 2; k++) { 1527254 763627 2290881
989 1527254 ▶ if (i == t->col[k]) code[k] = parent_code(r, p, se, gt, dp);
Branch: 1 branch
BranchTrueFalseTotal
if (i == t->col[k]) code[k] = parent_code(r, p, se, gt, dp); 221042 1306212 1527254
990 }
991 763627 p = se + 1;
992 }
993 110521 vcf_samples_end(aTHX_ r, p, e);
994 110520 ▶ if (code[0] != PARENT_NONE && code[1] != PARENT_NONE) t->t[3 * code[0] + code[1]]++;
Branch: 2 branches
BranchTrueFalseTotal
if (code[0] != PARENT_NONE && code[1] != PARENT_NONE) t->t[3 * code[0] + code[1]]++; 100590 9930 110520
if (code[0] != PARENT_NONE && code[1] != PARENT_NONE) t->t[3 * code[0] + code[1]]++; 92407 8183 100590
995 }
996  
997 /*Own VCF: one sample, or it isn't.*/
998 56 static void parent_header_own(pTHX_ vcf_reader *r) {
999 56 ▶ if (r->n != 1) croak("%s: %s has %" UVuf " samples, and a VCF given as \"child\" or \"parent\" must have one; give a VCF of several as \"vcf\", and the samples by name", __func__, r->name, (UV)r->n);
Branch: 1 branch
BranchTrueFalseTotal
if (r->n != 1) croak("%s: %s has %" UVuf " samples, and a VCF given as \"child\" or \"parent\" must have one; give a VCF of several as \"vcf\", and the samples by name", __func__, r->name, (UV)r->n); 1 55 56
1000 55 }
1001  
1002 /*Own VCF: the record p..e, kept as a site.*/
1003 173492 static void parent_record_own(pTHX_ vcf_reader *r, const char *p, const char *e) {
1004 173492 parent_reader *t = (parent_reader*)r;
1005 173492 const char *f = vcf_field_end(p, e);
1006 173492 unsigned short int chrom = vcf_chrom(p, f);
1007 173612 ▶ if (chrom < 1 || chrom > 22) return;
Branch: 2 branches
BranchTrueFalseTotal
if (chrom < 1 || chrom > 22) return; 173372 120 173492
if (chrom < 1 || chrom > 22) return; 63 173309 173372
1008 const char *col[9];
1009 173309 const char *format_end = vcf_columns(aTHX_ r, p, f, e, col);
1010 173309 ▶ if (!vcf_base(col[3], col[4] - 1)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!vcf_base(col[3], col[4] - 1)) return; 40 173269 173309
1011 unsigned short int alt;// vcf_base_index()'s, or 4 for more than one ALT
1012 173269 ▶ if (vcf_base(col[4], col[5] - 1)) alt = vcf_base_index(*col[4]);
Branch: 1 branch
BranchTrueFalseTotal
if (vcf_base(col[4], col[5] - 1)) alt = vcf_base_index(*col[4]); 173149 120 173269
1013 120 ▶ else if (memchr(col[4], ',', (size_t)(col[5] - 1 - col[4]))) alt = 4;
Branch: 1 branch
BranchTrueFalseTotal
else if (memchr(col[4], ',', (size_t)(col[5] - 1 - col[4]))) alt = 4; 40 80 120
1014 80 else return;// an indel, or an ALT of "." or "<NON_REF>"
1015 173189 UV pos = vcf_pos(aTHX_ r, col[1], col[2] - 1);
1016 173189 ▶ if (pos > UINT32_MAX) croak("%s: %s line %" UVuf " has POS %" UVuf ", beyond the 4294967295 that parent can compare", __func__, r->name, r->line, pos);
Branch: 1 branch
BranchTrueFalseTotal
if (pos > UINT32_MAX) croak("%s: %s line %" UVuf " has POS %" UVuf ", beyond the 4294967295 that parent can compare", __func__, r->name, r->line, pos); 1 173188 173189
1017 size_t gt, dp;
1018 173188 vcf_format(col[8], format_end, &gt, &dp);
1019 173188 p = format_end + 1;
1020 173188 const char *se = vcf_sample(aTHX_ r, p, e, 0);
1021 173187 vcf_samples_end(aTHX_ r, se + 1, e);
1022 173179 ▶ unsigned short int code = alt == 4 || gt == VCF_ABSENT ? PARENT_NONE : parent_code(r, p, se, gt, dp);
Branch: 2 branches
BranchTrueFalseTotal
unsigned short int code = alt == 4 || gt == VCF_ABSENT ? PARENT_NONE : parent_code(r, p, se, gt, dp); 173139 40 173179
unsigned short int code = alt == 4 || gt == VCF_ABSENT ? PARENT_NONE : parent_code(r, p, se, gt, dp); 173052 87 173139
1023 173179 parent_sites *s = t->sites;
1024 173179 ▶ if (s->n == s->room) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->n == s->room) { 115 173064 173179
1025 115 ▶ s->room = s->room ? 2 * s->room : 65536;// 512 KiB, a sixth of an exome's 280,000 records
Branch: 1 branch
BranchTrueFalseTotal
s->room = s->room ? 2 * s->room : 65536;// 512 KiB, a sixth of an exome's 280,000 records 0 115 115
1026 115 ▶ Renew(s->site, s->room, uint64_t);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->site, s->room, uint64_t); 0 115 115
1027 }
1028 173179 s->site[s->n++] = (uint64_t)chrom << 39 | (uint64_t)pos << PARENT_POS_SHIFT | (uint64_t)vcf_base_index(*col[3]) << 5 | (uint64_t)alt << 2 | code;
1029 }
1030  
1031 949057 static int parent_cmp(const void *a, const void *b) {
1032 949057 const uint64_t x = *(const uint64_t*)a, y = *(const uint64_t*)b;
1033 949057 return (x > y) - (x < y);
1034 }
1035  
1036 /*Own VCF: the sites of the VCF that next returns a block of at a time, read
1037 by t, whose name, min_depth and callbacks the caller has set, sorted.*/
1038 131 static parent_sites *parent_sites_read(pTHX_ parent_reader *t, SV *next) {
1039 131 Newxz(t->sites, 1, parent_sites);
1040 131 SAVEDESTRUCTOR_X(parent_sites_free, t->sites);// at the caller's LEAVE, croak or not
1041 131 vcf_read(aTHX_ next, &t->r);
1042 115 ▶ if (t->sites->n) qsort(t->sites->site, t->sites->n, sizeof *t->sites->site, parent_cmp);
Branch: 1 branch
BranchTrueFalseTotal
if (t->sites->n) qsort(t->sites->site, t->sites->n, sizeof *t->sites->site, parent_cmp); 115 0 115
1043 115 return t->sites;
1044 }
1045  
1046 /*Own VCF: the sites of the VCF name, which next returns a block of at a
1047 time, sorted.*/
1048 57 static parent_sites *parent_sites_vcf(pTHX_ SV *next, const char *name, UV min_depth) {
1049 parent_reader t;
1050 57 Zero(&t, 1, parent_reader);
1051 57 t.r.name = name;
1052 57 t.r.min_depth = min_depth;
1053 57 t.r.on_header = parent_header_own;
1054 57 t.r.on_record = parent_record_own;
1055 57 return parent_sites_read(aTHX_ &t, next);
1056 }
1057  
1058 /*The sites of the child's VCF, a, and of the parent's, b, both sorted, as t
1059 counts them; in[0], in[1] and in[2] get the sites where either carries the
1060 ALT that were in both files, in the child's alone, and in the parent's alone.
1061 The rules are in the comment above PARENT_NONE.*/
1062 21 static void parent_merge(const parent_sites *a, const parent_sites *b, UV *t, UV *in) {
1063 21 size_t i = 0, j = 0;
1064 36720 ▶ while (i < a->n || j < b->n) {
Branch: 2 branches
BranchTrueFalseTotal
while (i < a->n || j < b->n) { 36277 443 36720
while (i < a->n || j < b->n) { 422 21 443
1065 36699 ▶ const uint64_t pa = i < a->n ? a->site[i] >> PARENT_POS_SHIFT : UINT64_MAX, pb = j < b->n ? b->site[j] >> PARENT_POS_SHIFT : UINT64_MAX;
Branch: 2 branches
BranchTrueFalseTotal
const uint64_t pa = i < a->n ? a->site[i] >> PARENT_POS_SHIFT : UINT64_MAX, pb = j < b->n ? b->site[j] >> PARENT_POS_SHIFT : UINT64_MAX; 36277 422 36699
const uint64_t pa = i < a->n ? a->site[i] >> PARENT_POS_SHIFT : UINT64_MAX, pb = j < b->n ? b->site[j] >> PARENT_POS_SHIFT : UINT64_MAX; 36299 400 36699
1066 36699 const uint64_t at = pa < pb ? pa : pb;// the position to compare
1067 36699 size_t na = 0, nb = 0;// its sites in each file
1068 70221 ▶ while (i + na < a->n && a->site[i + na] >> PARENT_POS_SHIFT == at) na++;
Branch: 2 branches
BranchTrueFalseTotal
while (i + na < a->n && a->site[i + na] >> PARENT_POS_SHIFT == at) na++; 69778 443 70221
while (i + na < a->n && a->site[i + na] >> PARENT_POS_SHIFT == at) na++; 33522 36256 69778
1069 69107 ▶ while (j + nb < b->n && b->site[j + nb] >> PARENT_POS_SHIFT == at) nb++;
Branch: 2 branches
BranchTrueFalseTotal
while (j + nb < b->n && b->site[j + nb] >> PARENT_POS_SHIFT == at) nb++; 68686 421 69107
while (j + nb < b->n && b->site[j + nb] >> PARENT_POS_SHIFT == at) nb++; 32408 36278 68686
1070 36699 ▶ const uint64_t ka = na ? a->site[i] : 0, kb = nb ? b->site[j] : 0;
Branch: 2 branches
BranchTrueFalseTotal
const uint64_t ka = na ? a->site[i] : 0, kb = nb ? b->site[j] : 0; 33510 3189 36699
const uint64_t ka = na ? a->site[i] : 0, kb = nb ? b->site[j] : 0; 32406 4293 36699
1071 36699 i += na;
1072 36699 j += nb;
1073 36699 ▶ if (na > 1 || nb > 1) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (na > 1 || nb > 1) continue; 36687 12 36699
if (na > 1 || nb > 1) continue; 2 36685 36687
1074 36685 ▶ if (na && (PARENT_CODE(ka) == PARENT_NONE || PARENT_ALT(ka) == 4)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (na && (PARENT_CODE(ka) == PARENT_NONE || PARENT_ALT(ka) == 4)) continue; 33498 3187 36685
if (na && (PARENT_CODE(ka) == PARENT_NONE || PARENT_ALT(ka) == 4)) continue; 31814 1684 33498
if (na && (PARENT_CODE(ka) == PARENT_NONE || PARENT_ALT(ka) == 4)) continue; 0 31814 31814
1075 35001 ▶ if (nb && (PARENT_CODE(kb) == PARENT_NONE || PARENT_ALT(kb) == 4)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (nb && (PARENT_CODE(kb) == PARENT_NONE || PARENT_ALT(kb) == 4)) continue; 31055 3946 35001
if (nb && (PARENT_CODE(kb) == PARENT_NONE || PARENT_ALT(kb) == 4)) continue; 29602 1453 31055
if (nb && (PARENT_CODE(kb) == PARENT_NONE || PARENT_ALT(kb) == 4)) continue; 0 29602 29602
1076 33548 ▶ if (na && nb && PARENT_ALLELES(ka) != PARENT_ALLELES(kb)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (na && nb && PARENT_ALLELES(ka) != PARENT_ALLELES(kb)) continue; 30707 2841 33548
if (na && nb && PARENT_ALLELES(ka) != PARENT_ALLELES(kb)) continue; 26761 3946 30707
if (na && nb && PARENT_ALLELES(ka) != PARENT_ALLELES(kb)) continue; 24 26737 26761
1077 33524 ▶ const unsigned short int c = na ? PARENT_CODE(ka) : 0, p = nb ? PARENT_CODE(kb) : 0;// a site absent from a file is hom-REF there
Branch: 2 branches
BranchTrueFalseTotal
const unsigned short int c = na ? PARENT_CODE(ka) : 0, p = nb ? PARENT_CODE(kb) : 0;// a site absent from a file is hom-REF there 30683 2841 33524
const unsigned short int c = na ? PARENT_CODE(ka) : 0, p = nb ? PARENT_CODE(kb) : 0;// a site absent from a file is hom-REF there 29578 3946 33524
1078 33524 t[3 * c + p]++;
1079 33524 ▶ if (c || p) in[na && nb ? 0 : na ? 1 : 2]++;
Branch: 5 branches
BranchTrueFalseTotal
if (c || p) in[na && nb ? 0 : na ? 1 : 2]++; 4953 28571 33524
if (c || p) in[na && nb ? 0 : na ? 1 : 2]++; 4950 3 4953
if (c || p) in[na && nb ? 0 : na ? 1 : 2]++; 30681 2840 33521
if (c || p) in[na && nb ? 0 : na ? 1 : 2]++; 3946 26735 30681
if (c || p) in[na && nb ? 0 : na ? 1 : 2]++; 3946 2840 6786
1080 }
1081 21 }
1082  
1083 /*The genotype counts behind relatedness(): for every pair of samples, what
1084 parent() counts for one pair, and for every sample what sex_check() counts,
1085 from the same reading, so that brothers can be told from a brother and a
1086 sister.
1087  
1088 The samples are either all those of one VCF, or each the one sample of a VCF
1089 of its own. One VCF is read a record at a time and nothing kept but the
1090 counts: each sample's call at an autosomal site sets a bit in one of three
1091 words, for 0, 1 and 2 ALTs, and at the end of a block of 64 sites each pair's
1092 counts are taken from those words by popcount, 8 per pair, where taking them a
1093 site at a time would be 64 tests of the pair's two calls. Own VCFs are each
1094 read into parent_sites, as parent() reads them, and all of them held, and
1095 then merged in one pass, which applies parent_merge()'s rules to each pair.
1096 The files are opened by perl one at a time, so that only one is open.
1097  
1098 A pair's counts are REL_T UVs, in the order rel_pair() numbers the pairs: t[1]
1099 to t[8] of parent(), the sites by the first sample's ALT count and then the
1100 second's, flattened as t[3 * first + second] -- t[0], where both are hom-REF,
1101 is not a site compared, and is not kept -- and then, for own VCFs, in[0] to
1102 in[2] of parent_merge(): the sites in both files, in the first's alone and in
1103 the second's alone. For one VCF those three are left 0 and perl fills them.*/
1104 #define REL_T 11
1105  
1106 /*The number of pair (i, j), i < j, of n samples, when they are taken in the
1107 order (0, 1), (0, 2) .. (0, n - 1), (1, 2) ..*/
1108 90107 static size_t rel_pair(size_t n, size_t i, size_t j) {
1109 90107 return i * (2 * n - i - 1) / 2 + (j - i - 1);
1110 }
1111  
1112 /*The pairs of n samples, which dies when their counters could not be
1113 addressed.*/
1114 110 static size_t rel_pairs(pTHX_ size_t n) {
1115 110 ▶ if (n < 2) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n < 2) return 0; 0 110 110
1116 110 ▶ if (n > ((size_t)-1 / sizeof(UV) / REL_T) / n) croak("%s: %" UVuf " samples make too many pairs to count", __func__, (UV)n);
Branch: 1 branch
BranchTrueFalseTotal
if (n > ((size_t)-1 / sizeof(UV) / REL_T) / n) croak("%s: %" UVuf " samples make too many pairs to count", __func__, (UV)n); 0 110 110
1117 110 return n * (n - 1) / 2;
1118 }
1119  
1120 /*The 1 bits in w, by the SWAR count of Sean Eron Anderson's "Bit Twiddling
1121 Hacks" (graphics.stanford.edu/~seander/bithacks.html, section
1122 CountBitsSetParallel), which needs no compiler builtin and no POPCNT
1123 instruction.*/
1124 93976 static unsigned short int rel_popcount(uint64_t w) {
1125 93976 w -= (w >> 1) & UINT64_C(0x5555555555555555);
1126 93976 w = (w & UINT64_C(0x3333333333333333)) + ((w >> 2) & UINT64_C(0x3333333333333333));
1127 93976 w = (w + (w >> 4)) & UINT64_C(0x0f0f0f0f0f0f0f0f);
1128 93976 return (unsigned short int)((w * UINT64_C(0x0101010101010101)) >> 56);
1129 }
1130  
1131 typedef struct {
1132 vcf_reader r;// first, so that the vcf_reader * that the callbacks are given is this
1133 uint64_t *plane;// 3 words a sample: bit k of plane[3 * s + c] is set when sample s has c ALTs at the block's site k
1134 unsigned short int k;// the block's sites so far, 0 to 63
1135 UV *t;// REL_T counters a pair
1136 UV *sex;// SEX_FIELDS counters a sample
1137 } rel_reader;
1138  
1139 /*One VCF: its counters, once the #CHROM line has said how many samples there
1140 are.*/
1141 30 static void rel_header_one(pTHX_ vcf_reader *r) {
1142 30 rel_reader *t = (rel_reader*)r;
1143 30 ▶ if (r->n < 2) croak("%s: %s has 1 sample, and relatedness compares two or more; give each person's VCF, as relatedness($file, $file2)", __func__, r->name);
Branch: 1 branch
BranchTrueFalseTotal
if (r->n < 2) croak("%s: %s has 1 sample, and relatedness compares two or more; give each person's VCF, as relatedness($file, $file2)", __func__, r->name); 1 29 30
1144 29 size_t pairs = rel_pairs(aTHX_ r->n);
1145 29 ▶ Newxz(t->plane, 3 * r->n, uint64_t);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(t->plane, 3 * r->n, uint64_t); 0 29 29
1146 29 SAVEFREEPV(t->plane);// these three at the caller's LEAVE, croak or not; see vcf_read()'s block
1147 29 ▶ Newxz(t->t, pairs * REL_T, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(t->t, pairs * REL_T, UV); 0 29 29
1148 29 SAVEFREEPV(t->t);
1149 29 ▶ Newxz(t->sex, r->n * SEX_FIELDS, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(t->sex, r->n * SEX_FIELDS, UV); 0 29 29
1150 29 SAVEFREEPV(t->sex);
1151 29 }
1152  
1153 /*One VCF: the block's sites added to every pair's counts, and the block
1154 emptied.*/
1155 739 static void rel_flush(rel_reader *t) {
1156 739 const size_t n = t->r.n;
1157 739 const uint64_t *pl = t->plane;
1158 739 UV *c = t->t;
1159 4262 ▶ for (size_t i = 0; i + 1 < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i + 1 < n; i++) { 3523 739 4262
1160 3523 const uint64_t a0 = pl[3 * i], a1 = pl[3 * i + 1], a2 = pl[3 * i + 2];
1161 15270 ▶ for (size_t j = i + 1; j < n; j++, c += REL_T) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t j = i + 1; j < n; j++, c += REL_T) { 11747 3523 15270
1162 11747 const uint64_t *b = pl + 3 * j;
1163 11747 c[0] += rel_popcount(a0 & b[1]);// c[3 * first + second - 1]
1164 11747 c[1] += rel_popcount(a0 & b[2]);
1165 11747 c[2] += rel_popcount(a1 & b[0]);
1166 11747 c[3] += rel_popcount(a1 & b[1]);
1167 11747 c[4] += rel_popcount(a1 & b[2]);
1168 11747 c[5] += rel_popcount(a2 & b[0]);
1169 11747 c[6] += rel_popcount(a2 & b[1]);
1170 11747 c[7] += rel_popcount(a2 & b[2]);
1171 }
1172 }
1173 739 ▶ Zero(t->plane, 3 * n, uint64_t);
Branch: 1 branch
BranchTrueFalseTotal
Zero(t->plane, 3 * n, uint64_t); 0 739 739
1174 739 t->k = 0;
1175 739 }
1176  
1177 /*One VCF: the record p..e, an autosomal site for the pairs or an X or Y one
1178 for each sample's sex.*/
1179 47270 static void rel_record_one(pTHX_ vcf_reader *r, const char *p, const char *e) {
1180 47270 rel_reader *t = (rel_reader*)r;
1181 47270 const char *f = vcf_field_end(p, e);
1182 47270 unsigned short int chrom = vcf_chrom(p, f);
1183 48240 ▶ if (chrom == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (chrom == 0) return; 63 47207 47270
1184 const char *col[9];
1185 47207 const char *format_end = vcf_columns(aTHX_ r, p, f, e, col);
1186 size_t gt, dp;
1187 47207 p = format_end + 1;
1188 47207 ▶ if (chrom > 22) {
Branch: 1 branch
BranchTrueFalseTotal
if (chrom > 22) { 866 46341 47207
1189 866 ▶ if (!sex_site(aTHX_ r, chrom, col, format_end, &gt, &dp)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sex_site(aTHX_ r, chrom, col, format_end, &gt, &dp)) return; 0 866 866
1190 5043 ▶ for (size_t i = 0; i < r->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < r->n; i++) { 4178 865 5043
1191 4178 const char *se = vcf_sample(aTHX_ r, p, e, i);
1192 4177 sex_count(r, t->sex + i * SEX_FIELDS, chrom, p, se, gt, dp);
1193 4177 p = se + 1;
1194 }
1195 865 vcf_samples_end(aTHX_ r, p, e);
1196 865 return;
1197 }
1198 46341 ▶ if (!vcf_base(col[3], col[4] - 1) || !vcf_base(col[4], col[5] - 1)) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!vcf_base(col[3], col[4] - 1) || !vcf_base(col[4], col[5] - 1)) return; 46320 21 46341
if (!vcf_base(col[3], col[4] - 1) || !vcf_base(col[4], col[5] - 1)) return; 63 46257 46320
1199 46257 vcf_format(col[8], format_end, &gt, &dp);
1200 46257 ▶ if (gt == VCF_ABSENT) return;
Branch: 1 branch
BranchTrueFalseTotal
if (gt == VCF_ABSENT) return; 21 46236 46257
1201 46236 const uint64_t bit = (uint64_t)1 << t->k;
1202 313610 ▶ for (size_t i = 0; i < r->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < r->n; i++) { 267374 46236 313610
1203 267374 const char *se = vcf_sample(aTHX_ r, p, e, i);
1204 267374 unsigned short int code = parent_code(r, p, se, gt, dp);
1205 267374 ▶ if (code != PARENT_NONE) t->plane[3 * i + code] |= bit;
Branch: 1 branch
BranchTrueFalseTotal
if (code != PARENT_NONE) t->plane[3 * i + code] |= bit; 239102 28272 267374
1206 267374 p = se + 1;
1207 }
1208 46236 vcf_samples_end(aTHX_ r, p, e);
1209 46235 ▶ if (++t->k == 64) rel_flush(t);
Branch: 1 branch
BranchTrueFalseTotal
if (++t->k == 64) rel_flush(t); 712 45523 46235
1210 }
1211  
1212 typedef struct {
1213 parent_reader p;// first, so that the vcf_reader * that the callbacks are given is this, and parent_record_own() can read it
1214 UV *sex;// the SEX_FIELDS counters of the file's one sample
1215 HV *seen;// every file's sample so far => that file's name
1216 AV *names;// every file's sample so far, in the files' order
1217 } rel_own_reader;
1218  
1219 /*Own VCF: one sample, or it isn't, and not one that an earlier file named.*/
1220 73 static void rel_header_own(pTHX_ vcf_reader *r) {
1221 73 rel_own_reader *t = (rel_own_reader*)r;
1222 73 ▶ if (r->n != 1) croak("%s: %s has %" UVuf " samples, and each of several VCFs must have one; give a VCF of several samples alone, as relatedness($file)", __func__, r->name, (UV)r->n);
Branch: 1 branch
BranchTrueFalseTotal
if (r->n != 1) croak("%s: %s has %" UVuf " samples, and each of several VCFs must have one; give a VCF of several samples alone, as relatedness($file)", __func__, r->name, (UV)r->n); 1 72 73
1223 72 SV **sample = av_fetch(r->names, 0, 0);
1224 72 ▶ if (!sample) croak("%s: the sample of %s has lost its name", __func__, r->name);// cannot happen: vcf_header() pushed it
Branch: 1 branch
BranchTrueFalseTotal
if (!sample) croak("%s: the sample of %s has lost its name", __func__, r->name);// cannot happen: vcf_header() pushed it 0 72 72
1225 72 HE *he = hv_fetch_ent(t->seen, *sample, 0, 0);
1226 72 ▶ if (he) {
Branch: 1 branch
BranchTrueFalseTotal
if (he) { 1 71 72
1227 2 ▶ const char *first = SvPV_nolen(HeVAL(he)), *name = SvPV_nolen(*sample);
Branch: 1 branch
BranchTrueFalseTotal
const char *first = SvPV_nolen(HeVAL(he)), *name = SvPV_nolen(*sample); 1 0 1
1228 1 croak("%s: %s and %s both name their sample \"%s\"", __func__, first, r->name, name);
1229 }
1230 71 (void)hv_store_ent(t->seen, *sample, newSVpv(r->name, 0), 0);
1231 71 av_push(t->names, newSVsv(*sample));
1232 71 }
1233  
1234 /*Own VCF: the record p..e, counted for the sample's sex on X and Y and kept
1235 as a site, as parent() keeps it, on the autosomes.*/
1236 97751 static void rel_record_own(pTHX_ vcf_reader *r, const char *p, const char *e) {
1237 97751 const char *f = vcf_field_end(p, e);
1238 97751 unsigned short int chrom = vcf_chrom(p, f);
1239 97751 ▶ if (chrom != 23 && chrom != 24) {
Branch: 2 branches
BranchTrueFalseTotal
if (chrom != 23 && chrom != 24) { 97713 38 97751
if (chrom != 23 && chrom != 24) { 97693 20 97713
1240 97693 parent_record_own(aTHX_ r, p, e);
1241 97689 return;
1242 }
1243 const char *col[9];
1244 58 const char *format_end = vcf_columns(aTHX_ r, p, f, e, col);
1245 size_t gt, dp;
1246 58 ▶ if (!sex_site(aTHX_ r, chrom, col, format_end, &gt, &dp)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!sex_site(aTHX_ r, chrom, col, format_end, &gt, &dp)) return; 0 58 58
1247 58 p = format_end + 1;
1248 58 const char *se = vcf_sample(aTHX_ r, p, e, 0);
1249 58 vcf_samples_end(aTHX_ r, se + 1, e);
1250 57 sex_count(r, ((rel_own_reader*)r)->sex, chrom, p, se, gt, dp);
1251 }
1252  
1253 //What a file has at the position rel_merge() is comparing
1254 enum {
1255 REL_ABSENT, // no site: its sample is hom-REF there
1256 REL_PRESENT, // one site, whose call counts
1257 REL_UNUSABLE // more than one, a call that does not count, or more than one ALT: every pair with its sample leaves the position out
1258 };
1259  
1260 /*Own VCFs: the sites of the n files in s, each sorted, counted into t, pair by
1261 pair, by parent_merge()'s rules. Each position is found by looking at every
1262 file's next site, which is n steps, and then counted for each file that
1263 carries the ALT there against every other file, so that a pair where both are
1264 hom-REF costs nothing.*/
1265 18 static void rel_merge(pTHX_ parent_sites *const *s, size_t n, UV *t) {
1266 size_t *at, *carrier;// each file's next site; the files that carry the ALT at this position
1267 uint64_t *key;// each file's site at this position, when REL_PRESENT
1268 unsigned short int *state;// each file's REL_ABSENT, REL_PRESENT or REL_UNUSABLE at this position
1269 18 ▶ Newxz(at, n, size_t);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(at, n, size_t); 0 18 18
1270 18 SAVEFREEPV(at);// these four at the caller's LEAVE, croak or not
1271 18 ▶ Newx(carrier, n, size_t);
Branch: 1 branch
BranchTrueFalseTotal
Newx(carrier, n, size_t); 0 18 18
1272 18 SAVEFREEPV(carrier);
1273 18 ▶ Newx(key, n, uint64_t);
Branch: 1 branch
BranchTrueFalseTotal
Newx(key, n, uint64_t); 0 18 18
1274 18 SAVEFREEPV(key);
1275 18 ▶ Newx(state, n, unsigned short int);
Branch: 1 branch
BranchTrueFalseTotal
Newx(state, n, unsigned short int); 0 18 18
1276 18 SAVEFREEPV(state);
1277 32216 for (;;) {
1278 32234 uint64_t pos = UINT64_MAX;// the position to compare, as the sites' bits from PARENT_POS_SHIFT up
1279 128790 ▶ for (size_t f = 0; f < n; f++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t f = 0; f < n; f++) { 96556 32234 128790
1280 96556 ▶ if (at[f] < s[f]->n && s[f]->site[at[f]] >> PARENT_POS_SHIFT < pos) pos = s[f]->site[at[f]] >> PARENT_POS_SHIFT;
Branch: 2 branches
BranchTrueFalseTotal
if (at[f] < s[f]->n && s[f]->site[at[f]] >> PARENT_POS_SHIFT < pos) pos = s[f]->site[at[f]] >> PARENT_POS_SHIFT; 95680 876 96556
if (at[f] < s[f]->n && s[f]->site[at[f]] >> PARENT_POS_SHIFT < pos) pos = s[f]->site[at[f]] >> PARENT_POS_SHIFT; 36320 59360 95680
1281 }
1282 32234 ▶ if (pos == UINT64_MAX) break;
Branch: 1 branch
BranchTrueFalseTotal
if (pos == UINT64_MAX) break; 18 32216 32234
1283 32216 size_t m = 0;// carriers
1284 128718 ▶ for (size_t f = 0; f < n; f++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t f = 0; f < n; f++) { 96502 32216 128718
1285 96502 size_t k = 0;
1286 177473 ▶ while (at[f] + k < s[f]->n && s[f]->site[at[f] + k] >> PARENT_POS_SHIFT == pos) k++;
Branch: 2 branches
BranchTrueFalseTotal
while (at[f] + k < s[f]->n && s[f]->site[at[f] + k] >> PARENT_POS_SHIFT == pos) k++; 176597 876 177473
while (at[f] + k < s[f]->n && s[f]->site[at[f] + k] >> PARENT_POS_SHIFT == pos) k++; 80971 95626 176597
1287 96502 ▶ if (!k) {
Branch: 1 branch
BranchTrueFalseTotal
if (!k) { 15542 80960 96502
1288 15542 state[f] = REL_ABSENT;
1289 15542 continue;
1290 }
1291 80960 key[f] = s[f]->site[at[f]];
1292 80960 at[f] += k;
1293 80960 ▶ state[f] = k > 1 || PARENT_CODE(key[f]) == PARENT_NONE || PARENT_ALT(key[f]) == 4 ? REL_UNUSABLE : REL_PRESENT;
Branch: 3 branches
BranchTrueFalseTotal
state[f] = k > 1 || PARENT_CODE(key[f]) == PARENT_NONE || PARENT_ALT(key[f]) == 4 ? REL_UNUSABLE : REL_PRESENT; 80949 11 80960
state[f] = k > 1 || PARENT_CODE(key[f]) == PARENT_NONE || PARENT_ALT(key[f]) == 4 ? REL_UNUSABLE : REL_PRESENT; 76441 4508 80949
state[f] = k > 1 || PARENT_CODE(key[f]) == PARENT_NONE || PARENT_ALT(key[f]) == 4 ? REL_UNUSABLE : REL_PRESENT; 0 76441 76441
1294 80960 ▶ if (state[f] == REL_PRESENT && PARENT_CODE(key[f])) carrier[m++] = f;
Branch: 2 branches
BranchTrueFalseTotal
if (state[f] == REL_PRESENT && PARENT_CODE(key[f])) carrier[m++] = f; 76441 4519 80960
if (state[f] == REL_PRESENT && PARENT_CODE(key[f])) carrier[m++] = f; 72201 4240 76441
1295 }
1296 104417 ▶ for (size_t q = 0; q < m; q++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t q = 0; q < m; q++) { 72201 32216 104417
1297 72201 const size_t i = carrier[q];
1298 72201 const unsigned short int ci = PARENT_CODE(key[i]);
1299 305577 ▶ for (size_t j = 0; j < n; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t j = 0; j < n; j++) { 233376 72201 305577
1300 233376 ▶ if (j == i || state[j] == REL_UNUSABLE) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (j == i || state[j] == REL_UNUSABLE) continue; 161175 72201 233376
if (j == i || state[j] == REL_UNUSABLE) continue; 9097 152078 161175
1301 152078 const bool both = state[j] == REL_PRESENT;
1302 152078 ▶ const unsigned short int cj = both ? PARENT_CODE(key[j]) : 0;// a site absent from a file is hom-REF there
Branch: 1 branch
BranchTrueFalseTotal
const unsigned short int cj = both ? PARENT_CODE(key[j]) : 0;// a site absent from a file is hom-REF there 128138 23940 152078
1303 152078 ▶ if (cj && j < i) continue;// counted when j was the carrier
Branch: 2 branches
BranchTrueFalseTotal
if (cj && j < i) continue;// counted when j was the carrier 123898 28180 152078
if (cj && j < i) continue;// counted when j was the carrier 61949 61949 123898
1304 90129 ▶ if (both && PARENT_ALLELES(key[i]) != PARENT_ALLELES(key[j])) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (both && PARENT_ALLELES(key[i]) != PARENT_ALLELES(key[j])) continue; 66189 23940 90129
if (both && PARENT_ALLELES(key[i]) != PARENT_ALLELES(key[j])) continue; 22 66167 66189
1305 90107 ▶ UV *c = t + REL_T * (i < j ? rel_pair(n, i, j) : rel_pair(n, j, i));
Branch: 1 branch
BranchTrueFalseTotal
UV *c = t + REL_T * (i < j ? rel_pair(n, i, j) : rel_pair(n, j, i)); 76076 14031 90107
1306 90107 ▶ c[i < j ? 3 * ci + cj - 1 : 3 * cj + ci - 1]++;
Branch: 1 branch
BranchTrueFalseTotal
c[i < j ? 3 * ci + cj - 1 : 3 * cj + ci - 1]++; 76076 14031 90107
1307 90107 ▶ c[8 + (both ? 0 : i < j ? 1 : 2)]++;
Branch: 2 branches
BranchTrueFalseTotal
c[8 + (both ? 0 : i < j ? 1 : 2)]++; 66167 23940 90107
c[8 + (both ? 0 : i < j ? 1 : 2)]++; 12021 11919 23940
1308 }
1309 }
1310 }
1311 18 }
1312  
1313 /*The n samples' pair counters t as one string of UVs, for perl to unpack with
1314 "J". For 1,000 samples, an array of a scalar per counter took 226 MB where
1315 this takes 44 MB (2026-10-19).*/
1316 45 static SV *rel_counts(pTHX_ const UV *t, size_t n) {
1317 45 return newSVpvn((const char*)t, rel_pairs(aTHX_ n) * REL_T * sizeof(UV));
1318 }
1319  
1320 /*The genotype comparison behind concordance().
1321  
1322 The method is ~/Scripts/old/x.low_ram_local_concordance.pl's (its
1323 assay_concordance(), concordance() and metrics(), as they stood on
1324 2026-10-19), which compared each sample of a directory of test VCFs with the
1325 same sample in a directory of truth VCFs. Every record of the test is compared,
1326 sample by sample, with the truth's record of the same site, and a site that
1327 the truth lacks is a no-call there; a site that the truth has and the test
1328 lacks is not compared at all. Each comparison is one of the 45 kinds of
1329 CONC_NAME, and the metrics are taken from their counts as metrics() took them.
1330  
1331 It departs from that script where the script died or could not match:
1332 - A site is CHROM, POS, REF and ALT. The script also took ID, so that "rs123"
1333 in one file and "." in the other were two sites, and it dropped a "chr" from
1334 the truth's CHROM alone, so that two files that both had one shared no site;
1335 here "chr", in any case, is dropped from both.
1336 - A call is compared as its alleles, in either order, so that "1/0", "0|1" and
1337 "0/1" are one call; the script compared GT strings, and died on the first two.
1338 - A call missing in both ("." and "./.") is concordant_no_call, where the
1339 script made it discordant_no_call_to_no_call, a kind outside its 45.
1340 - A partly missing call ("./1"), one of more than two alleles, and one whose
1341 DP is below min_depth are each a no-call, where the script died on the first
1342 two and had no min_depth.
1343 - The metrics' true positives and true negatives are corrected, and a
1344 discordance of two ALT-carrying calls is a false positive and a false
1345 negative, as the comment above CONC_TP says.
1346  
1347 The test is read first, and every site of it kept with its calls for the
1348 samples compared, and then the truth is read a record at a time and looked up
1349 among them. RAM thus goes with the test's sites, which for the usual input, a
1350 panel against a genome, are the fewer, and a truth record that matches no
1351 test site costs no more than finding its end.*/
1352  
1353 //What one call is. The order is that of the classes' names, which CONC_NAME's kinds are sorted by
1354 enum { CONC_HAPLOID_ALT, CONC_HAPLOID_REF, CONC_HET_ALT, CONC_HET_REF, CONC_HOM_ALT, CONC_HOM_REF, CONC_NO_CALL };
1355  
1356 /*The kinds of comparison, truth first and then test, in the order and with the
1357 names of the script's @concordance_types.*/
1358 #define CONC_KINDS 45
1359 static const char *const CONC_NAME[CONC_KINDS] = {
1360 "concordant_diploid_ref_to_haploid_ref", "concordant_haploid_alt", "concordant_haploid_alt_to_hom_alt",
1361 "concordant_haploid_ref", "concordant_haploid_ref_to_diploid_ref", "concordant_het_alt", "concordant_het_ref",
1362 "concordant_hom_alt", "concordant_hom_alt_to_diploid_alt", "concordant_hom_ref", "concordant_no_call",
1363 "discordant_haploid_alt_to_haploid_alt", "discordant_haploid_alt_to_haploid_ref", "discordant_haploid_alt_to_het_alt",
1364 "discordant_haploid_alt_to_het_ref", "discordant_haploid_alt_to_hom_alt", "discordant_haploid_alt_to_hom_ref",
1365 "discordant_haploid_ref_to_haploid_alt", "discordant_haploid_ref_to_het_alt", "discordant_haploid_ref_to_het_ref",
1366 "discordant_haploid_ref_to_hom_alt",
1367 "discordant_het_alt_to_haploid_alt", "discordant_het_alt_to_haploid_ref", "discordant_het_alt_to_het_alt",
1368 "discordant_het_alt_to_het_ref", "discordant_het_alt_to_hom_alt", "discordant_het_alt_to_hom_ref",
1369 "discordant_het_ref_to_haploid_alt", "discordant_het_ref_to_haploid_ref", "discordant_het_ref_to_het_alt",
1370 "discordant_het_ref_to_het_ref", "discordant_het_ref_to_hom_alt", "discordant_het_ref_to_hom_ref",
1371 "discordant_hom_alt_to_haploid_alt", "discordant_hom_alt_to_haploid_ref", "discordant_hom_alt_to_het_alt",
1372 "discordant_hom_alt_to_het_ref", "discordant_hom_alt_to_hom_alt", "discordant_hom_alt_to_hom_ref",
1373 "discordant_hom_ref_to_haploid_alt", "discordant_hom_ref_to_het_alt", "discordant_hom_ref_to_het_ref",
1374 "discordant_hom_ref_to_hom_alt",
1375 "gained_site", "lost_site"
1376 };
1377 //The kinds that conc_kind() names, as indexes into CONC_NAME
1378 enum {
1379 CONC_DIPLOID_REF_TO_HAPLOID_REF = 0,
1380 CONC_HAPLOID_ALT_TO_HOM_ALT = 2,
1381 CONC_HAPLOID_REF_TO_DIPLOID_REF = 4,
1382 CONC_HOM_ALT_TO_DIPLOID_ALT = 8,
1383 CONC_DISCORDANT = 11, // the first discordant_ kind; every kind before it is concordant_
1384 CONC_GAINED = 43, // the truth a no-call, the test not
1385 CONC_LOST = 44 // the test a no-call, the truth not
1386 };
1387 //concordant_<class>, by the class of the two calls, which are the same
1388 static const unsigned short int CONC_SAME[7] = { 1, 3, 5, 6, 7, 9, 10 };
1389 /*discordant_<truth's class>_to_<test's class>, by the two classes. -1 marks
1390 the four pairs of reference calls, which are concordant whatever their
1391 ploidy.*/
1392 static const short int CONC_DIFFERENT[6][6] = {
1393 { 11, 12, 13, 14, 15, 16 },
1394 { 17, -1, 18, 19, 20, -1 },
1395 { 21, 22, 23, 24, 25, 26 },
1396 { 27, 28, 29, 30, 31, 32 },
1397 { 33, 34, 35, 36, 37, 38 },
1398 { 39, -1, 40, 41, 42, -1 }
1399 };
1400  
1401 /*The sets of kinds that metrics() summed, as bits of CONC_NAME's indexes,
1402 written out so that the rule cannot drift with the names. Each is what the
1403 script's regex picked out of @concordance_types, but for CONC_TP, CONC_TN and
1404 CONC_MISMATCH, which correct it (since 2026-10-19):
1405 - CONC_TP, the true positives, is every concordant kind whose call carries an
1406 ALT. The script's /^conc\w+(?:alt|hom)/ took concordant_hom_ref, by the "hom"
1407 in it, so that a hom-REF site counted as a true positive and a true negative
1408 both, and it left out concordant_het_ref, the commonest true positive.
1409 - CONC_TN, the true negatives, is every concordant kind of reference calls,
1410 whatever the ploidy of either. The script's tn_site,
1411 /^concordant_(?:hom|haploid)\w+ref$/, left out
1412 concordant_diploid_ref_to_haploid_ref, the mirror of a kind it took; and its
1413 tn_genotype was concordant_hom_ref alone, though CONC_FP_REF counts a
1414 haploid-REF truth called otherwise, so that specificity gave no credit for a
1415 haploid-REF truth called right, as on a male's X. Here tn_genotype is
1416 tn_site.
1417 - CONC_MISMATCH is every discordant kind where both calls carry an ALT (0/1
1418 against 1/1, or 0/1 against 0/2), which the script counted in neither
1419 fp_genotype, which was CONC_FP_REF alone, nor fn_genotype, which was
1420 CONC_FN_REF alone, so that it changed no precision or recall. It is now in
1421 both, as benchmarking tools count it: the test's call is wrong, and the
1422 truth's is missed. Specificity still takes CONC_FP_REF alone, since only a
1423 reference truth is a negative.*/
1424 #define CONC_BIT(k) ((uint64_t)1 << (k))
1425 #define CONC_TP (CONC_BIT(1) | CONC_BIT(2) | CONC_BIT(5) | CONC_BIT(6) | CONC_BIT(7) | CONC_BIT(8))
1426 #define CONC_TN (CONC_BIT(0) | CONC_BIT(3) | CONC_BIT(4) | CONC_BIT(9))
1427 #define CONC_FP_REF (CONC_BIT(17) | CONC_BIT(18) | CONC_BIT(19) | CONC_BIT(20) | CONC_BIT(39) | CONC_BIT(40) | CONC_BIT(41) | CONC_BIT(42)) // /^discordant_(haploid|hom)_ref_\w+/: a reference truth, the test carrying an ALT
1428 #define CONC_FN_REF (CONC_BIT(12) | CONC_BIT(16) | CONC_BIT(22) | CONC_BIT(26) | CONC_BIT(28) | CONC_BIT(32) | CONC_BIT(34) | CONC_BIT(38)) // /^discordant_\w+_(?:hom|haploid)_ref$/: the truth carrying an ALT, a reference test
1429 #define CONC_MISMATCH (CONC_BIT(11) | CONC_BIT(13) | CONC_BIT(14) | CONC_BIT(15) | CONC_BIT(21) | CONC_BIT(23) | CONC_BIT(24) | CONC_BIT(25) \
1430 | CONC_BIT(27) | CONC_BIT(29) | CONC_BIT(30) | CONC_BIT(31) | CONC_BIT(33) | CONC_BIT(35) | CONC_BIT(36) | CONC_BIT(37))
1431 #define CONC_AGREE (CONC_BIT(CONC_DISCORDANT - 1) - 1) // /^concordant_\w+(?:alt|ref)$/: every concordant_ kind but concordant_no_call
1432 #define CONC_CALLED (((CONC_BIT(CONC_GAINED) - 1) & ~CONC_BIT(CONC_DISCORDANT - 1))) // /(?:alt|ref)$/: every kind but concordant_no_call, gained_site and lost_site
1433  
1434 /*One sample's call. Alleles are held in 16 bits, which keeps a call to 6
1435 bytes, two of which each test site keeps for each sample compared; conc_gt()
1436 dies on an allele above 65535, which no VCF of real data has.*/
1437 typedef struct {
1438 uint16_t a, b;// the alleles, in GT's order; b is 0 for a haploid call
1439 unsigned char n;// 0 = no-call, 1 = haploid, 2 = diploid
1440 bool phased;// GT separated them with '|'
1441 } conc_call;
1442  
1443 /*A site of the test.*/
1444 typedef struct {
1445 uint64_t hash;// conc_hash()'s, of CHROM, POS, REF and ALT
1446 UV pos;
1447 size_t text;// where its CHROM to ALT, as the test has them and ended by '\n', start in conc_store's text
1448 bool found;// the truth has it
1449 } conc_site;
1450  
1451 /*Everything the test's reading keeps and the truth's reading looks in, in a
1452 holder that the scope's destructor frees, since Renew() moves the arrays.*/
1453 typedef struct {
1454 char *text;// every site's CHROM to ALT, each ended by '\n'
1455 size_t text_n, text_room;
1456 conc_site *site;
1457 size_t n, room;// sites used and allocated
1458 size_t *slot;// an open-addressed table of the sites by hash: a site's index + 1, or 0 for an empty slot
1459 size_t slots;// 0, or a power of 2 at least twice n
1460 conc_call *call;// 2 * pairs a site: for each pair, the test's call and then the truth's
1461 size_t *hit;// the sites that one truth record matches
1462 size_t hit_room;
1463 conc_call *truth;// a truth record's calls, one a pair
1464 size_t pairs;// samples compared
1465 size_t *test_col;// each pair's column among the test's samples
1466 size_t *truth_col;// and among the truth's
1467 size_t *test_pair;// each test column's pair + 1, or 0 when it is not compared
1468 size_t *truth_pair;// each truth column's pair + 1, or 0
1469 size_t truth_n;// the truth's samples, as read before the test
1470 UV found;// test sites that the truth has
1471 } conc_store;
1472  
1473 61 static void conc_store_free(pTHX_ void *p) {
1474 61 conc_store *s = (conc_store*)p;
1475 61 Safefree(s->text);
1476 61 Safefree(s->site);
1477 61 Safefree(s->slot);
1478 61 Safefree(s->call);
1479 61 Safefree(s->hit);
1480 61 Safefree(s->truth);
1481 61 Safefree(s->test_col);
1482 61 Safefree(s->truth_col);
1483 61 Safefree(s->test_pair);
1484 61 Safefree(s->truth_pair);
1485 61 Safefree(s);
1486 61 }
1487  
1488 typedef struct {
1489 vcf_reader r;// first, so that the vcf_reader * that the callbacks are given is this
1490 conc_store *s;
1491 AV *truth_names;// the test's reader: the truth's samples, in its order
1492 } conc_reader;
1493  
1494 /*CHROM p..f without a "chr" prefix, in any case, as vcf_chrom() drops it; the
1495 start is returned.*/
1496 16580 static const char *conc_chrom(const char *p, const char *f) {
1497 16580 ▶ if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3;
Branch: 7 branches
BranchTrueFalseTotal
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 5 16575 16580
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 2 3 5
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 2 0 2
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 2 3 5
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 2 0 2
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 2 3 5
if (f - p > 3 && (p[0] == 'c' || p[0] == 'C') && (p[1] == 'h' || p[1] == 'H') && (p[2] == 'r' || p[2] == 'R')) p += 3; 2 0 2
1498 16580 return p;
1499 }
1500  
1501 /*FNV-1a, 64-bit (Fowler, Noll and Vo; www.isthe.com/chongo/tech/comp/fnv/,
1502 read 2026-10-19), of the bytes p..e, continuing from h.*/
1503 144625 static uint64_t conc_fnv(uint64_t h, const char *p, const char *e) {
1504 293234 ▶ for (; p < e; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (; p < e; p++) { 148609 144625 293234
1505 148609 h ^= (unsigned char)*p;
1506 148609 h *= UINT64_C(0x100000001b3);
1507 }
1508 144625 return h;
1509 }
1510  
1511 /*The hash of a site: its CHROM (less "chr") c..cf, POS, REF r..rf and ALT
1512 a..af, with a byte that no field holds between the fields, so that moving a
1513 byte from one to the next changes it.*/
1514 11125 static uint64_t conc_hash(const char *c, const char *cf, UV pos, const char *r, const char *rf, const char *a, const char *af) {
1515 static const char tab = '\t';
1516 11125 uint64_t h = conc_fnv(UINT64_C(0xcbf29ce484222325), c, cf);
1517 11125 h = conc_fnv(h, &tab, &tab + 1);
1518 100125 ▶ for (unsigned short int i = 0; i < 64; i += 8) { // POS's 8 bytes, low first, whatever the width of a UV
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int i = 0; i < 64; i += 8) { // POS's 8 bytes, low first, whatever the width of a UV 89000 11125 100125
1519 89000 const char byte = (char)(((uint64_t)pos >> i) & 0xff);
1520 89000 h = conc_fnv(h, &byte, &byte + 1);
1521 }
1522 11125 h = conc_fnv(h, r, rf);
1523 11125 h = conc_fnv(h, &tab, &tab + 1);
1524 11125 return conc_fnv(h, a, af);
1525 }
1526  
1527 /*Where each of the five fields of site k's text starts, in fld, with fld[5]
1528 one past its '\n', so that fld[i + 1] - 1 ends field i. The text has its four
1529 tabs and its '\n', as conc_record_test() stored it.*/
1530 5767 static void conc_fields(const conc_store *s, size_t k, const char **fld) {
1531 5767 const char *e = s->text + s->text_n;
1532 5767 fld[0] = s->text + s->site[k].text;
1533 28835 ▶ for (unsigned short int i = 1; i < 5; i++) fld[i] = (const char*)memchr(fld[i - 1], '\t', (size_t)(e - fld[i - 1])) + 1;
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int i = 1; i < 5; i++) fld[i] = (const char*)memchr(fld[i - 1], '\t', (size_t)(e - fld[i - 1])) + 1; 23068 5767 28835
1534 5767 fld[5] = (const char*)memchr(fld[4], '\n', (size_t)(e - fld[4])) + 1;
1535 5767 }
1536  
1537 /*Whether two byte ranges are equal.*/
1538 16365 static bool conc_eq(const char *p, const char *pe, const char *q, const char *qe) {
1539 16365 ▶ return pe - p == qe - q && memcmp(p, q, (size_t)(pe - p)) == 0;
Branch: 2 branches
BranchTrueFalseTotal
return pe - p == qe - q && memcmp(p, q, (size_t)(pe - p)) == 0; 16365 0 16365
return pe - p == qe - q && memcmp(p, q, (size_t)(pe - p)) == 0; 16365 0 16365
1540 }
1541  
1542 /*The call in the sample field p..e, whose FORMAT has GT at gt and DP at dp,
1543 into *c. A GT that FORMAT lacks, an empty or missing one, a partly missing one
1544 ("./1"), one of more than two alleles, and a DP below min_depth are each a
1545 no-call. Dies on a GT that is not one, naming the sample of column i.*/
1546 12036 static void conc_gt(pTHX_ const vcf_reader *r, const char *p, const char *e, size_t gt, size_t dp, size_t i, conc_call *c) {
1547 12036 c->a = c->b = 0;
1548 12036 c->n = 0;
1549 12036 c->phased = FALSE;
1550 const char *s, *sf;
1551 12036 ▶ if (gt == VCF_ABSENT || vcf_shallow(r, p, e, dp) || !vcf_subfield(p, e, gt, &s, &sf) || s == sf) return;
Branch: 4 branches
BranchTrueFalseTotal
if (gt == VCF_ABSENT || vcf_shallow(r, p, e, dp) || !vcf_subfield(p, e, gt, &s, &sf) || s == sf) return; 12035 1 12036
if (gt == VCF_ABSENT || vcf_shallow(r, p, e, dp) || !vcf_subfield(p, e, gt, &s, &sf) || s == sf) return; 12033 2 12035
if (gt == VCF_ABSENT || vcf_shallow(r, p, e, dp) || !vcf_subfield(p, e, gt, &s, &sf) || s == sf) return; 12033 0 12033
if (gt == VCF_ABSENT || vcf_shallow(r, p, e, dp) || !vcf_subfield(p, e, gt, &s, &sf) || s == sf) return; 0 12033 12033
1552 12033 const char *g = s;// GT, for messages
1553 12033 UV allele[2] = { 0, 0 };
1554 12033 size_t n = 0;// alleles
1555 12033 bool missing = FALSE, phased = FALSE;
1556 11628 for (;;) {
1557 23661 UV v = 0;
1558 23661 ▶ if (s < sf && *s == '.') {
Branch: 2 branches
BranchTrueFalseTotal
if (s < sf && *s == '.') { 23661 0 23661
if (s < sf && *s == '.') { 152 23509 23661
1559 152 missing = TRUE;
1560 152 s++;
1561 } else {
1562 23509 const char *d = s;
1563 47022 ▶ for (; s < sf && *s >= '0' && *s <= '9'; s++) {
Branch: 3 branches
BranchTrueFalseTotal
for (; s < sf && *s >= '0' && *s <= '9'; s++) { 35076 11946 47022
for (; s < sf && *s >= '0' && *s <= '9'; s++) { 23525 11551 35076
for (; s < sf && *s >= '0' && *s <= '9'; s++) { 23515 10 23525
1564 23515 v = v * 10 + (UV)(*s - '0');
1565 23515 ▶ if (v > 65535) {
Branch: 1 branch
BranchTrueFalseTotal
if (v > 65535) { 2 23513 23515
1566 2 SV **name = av_fetch(r->names, (SSize_t)i, 0);
1567 4 ▶ croak("%s: %s line %" UVuf " has GT \"%.*s\" for sample \"%s\", whose allele is beyond the 65535 that concordance can compare", __func__, r->name, r->line, (int)(sf - g), g, name ? SvPV_nolen(*name) : "");
Branch: 1 branch
BranchTrueFalseTotal
croak("%s: %s line %" UVuf " has GT \"%.*s\" for sample \"%s\", whose allele is beyond the 65535 that concordance can compare", __func__, r->name, r->line, (int)(sf - g), g, name ? SvPV_nolen(*name) : ""); 2 0 2
1568 }
1569 }
1570 23507 ▶ if (s == d) break;// not an allele: said below
Branch: 1 branch
BranchTrueFalseTotal
if (s == d) break;// not an allele: said below 6 23501 23507
1571 }
1572 23653 ▶ if (n < 2) allele[n] = v;
Branch: 1 branch
BranchTrueFalseTotal
if (n < 2) allele[n] = v; 23652 1 23653
1573 23653 n++;
1574 23653 ▶ if (s == sf) {
Branch: 1 branch
BranchTrueFalseTotal
if (s == sf) { 12021 11632 23653
1575 12021 ▶ if (missing || n > 2) return;
Branch: 2 branches
BranchTrueFalseTotal
if (missing || n > 2) return; 11945 76 12021
if (missing || n > 2) return; 1 11944 11945
1576 11944 c->n = (unsigned char)n;
1577 11944 c->a = (uint16_t)allele[0];
1578 11944 c->b = (uint16_t)allele[1];
1579 11944 c->phased = phased;
1580 11944 return;
1581 }
1582 11632 ▶ if (*s == '|') phased = TRUE;
Branch: 1 branch
BranchTrueFalseTotal
if (*s == '|') phased = TRUE; 4 11628 11632
1583 11628 ▶ else if (*s != '/') break;
Branch: 1 branch
BranchTrueFalseTotal
else if (*s != '/') break; 2 11626 11628
1584 11630 ▶ if (++s == sf) break;// "0/"
Branch: 1 branch
BranchTrueFalseTotal
if (++s == sf) break;// "0/" 2 11628 11630
1585 }
1586 10 SV **name = av_fetch(r->names, (SSize_t)i, 0);
1587 20 ▶ croak("%s: %s line %" UVuf " has GT \"%.*s\" for sample \"%s\", which isn't a genotype", __func__, r->name, r->line, (int)(sf - g), g, name ? SvPV_nolen(*name) : "");
Branch: 1 branch
BranchTrueFalseTotal
croak("%s: %s line %" UVuf " has GT \"%.*s\" for sample \"%s\", which isn't a genotype", __func__, r->name, r->line, (int)(sf - g), g, name ? SvPV_nolen(*name) : ""); 10 0 10
1588 }
1589  
1590 /*The class of call c.*/
1591 11668 static unsigned short int conc_class(const conc_call *c) {
1592 11668 ▶ if (c->n == 0) return CONC_NO_CALL;
Branch: 1 branch
BranchTrueFalseTotal
if (c->n == 0) return CONC_NO_CALL; 93 11575 11668
1593 11575 ▶ if (c->n == 1) return c->a ? CONC_HAPLOID_ALT : CONC_HAPLOID_REF;
Branch: 1 branch
BranchTrueFalseTotal
if (c->n == 1) return c->a ? CONC_HAPLOID_ALT : CONC_HAPLOID_REF; 329 11246 11575
1594 11246 ▶ if (c->a == c->b) return c->a ? CONC_HOM_ALT : CONC_HOM_REF;
Branch: 2 branches
BranchTrueFalseTotal
if (c->a == c->b) return c->a ? CONC_HOM_ALT : CONC_HOM_REF; 3510 7736 11246
if (c->a == c->b) return c->a ? CONC_HOM_ALT : CONC_HOM_REF; 2887 623 3510
1595 7736 ▶ return c->a && c->b ? CONC_HET_ALT : CONC_HET_REF;
Branch: 2 branches
BranchTrueFalseTotal
return c->a && c->b ? CONC_HET_ALT : CONC_HET_REF; 163 7573 7736
return c->a && c->b ? CONC_HET_ALT : CONC_HET_REF; 160 3 163
1596 }
1597  
1598 /*Whether two calls are the same: both no-calls, or of one ploidy with the same
1599 alleles, in either order.*/
1600 5834 static bool conc_same(const conc_call *x, const conc_call *y) {
1601 5834 ▶ if (x->n != y->n) return FALSE;
Branch: 1 branch
BranchTrueFalseTotal
if (x->n != y->n) return FALSE; 274 5560 5834
1602 5560 ▶ if (x->n < 2) return x->a == y->a;
Branch: 1 branch
BranchTrueFalseTotal
if (x->n < 2) return x->a == y->a; 74 5486 5560
1603 5486 ▶ return (x->a == y->a && x->b == y->b) || (x->a == y->b && x->b == y->a);
Branch: 4 branches
BranchTrueFalseTotal
return (x->a == y->a && x->b == y->b) || (x->a == y->b && x->b == y->a); 3374 2112 5486
return (x->a == y->a && x->b == y->b) || (x->a == y->b && x->b == y->a); 63 3311 3374
return (x->a == y->a && x->b == y->b) || (x->a == y->b && x->b == y->a); 1382 793 2175
return (x->a == y->a && x->b == y->b) || (x->a == y->b && x->b == y->a); 3 1379 1382
1604 }
1605  
1606 /*The kind of comparison, an index into CONC_NAME, of the truth's call and the
1607 test's, by the script's assay_concordance(), in its order.*/
1608 5834 static unsigned short int conc_kind(const conc_call *truth, const conc_call *test) {
1609 5834 const unsigned short int ct = conc_class(truth), cs = conc_class(test);
1610 5834 ▶ if (conc_same(truth, test)) return CONC_SAME[ct];
Branch: 1 branch
BranchTrueFalseTotal
if (conc_same(truth, test)) return CONC_SAME[ct]; 3360 2474 5834
1611 2474 ▶ if (cs == CONC_NO_CALL) return CONC_LOST;// the truth is not, or the two would be the same
Branch: 1 branch
BranchTrueFalseTotal
if (cs == CONC_NO_CALL) return CONC_LOST;// the truth is not, or the two would be the same 13 2461 2474
1612 2461 ▶ if (ct == CONC_NO_CALL) return CONC_GAINED;
Branch: 1 branch
BranchTrueFalseTotal
if (ct == CONC_NO_CALL) return CONC_GAINED; 42 2419 2461
1613 2419 ▶ if (ct == CONC_HOM_REF && cs == CONC_HAPLOID_REF) return CONC_DIPLOID_REF_TO_HAPLOID_REF;
Branch: 2 branches
BranchTrueFalseTotal
if (ct == CONC_HOM_REF && cs == CONC_HAPLOID_REF) return CONC_DIPLOID_REF_TO_HAPLOID_REF; 56 2363 2419
if (ct == CONC_HOM_REF && cs == CONC_HAPLOID_REF) return CONC_DIPLOID_REF_TO_HAPLOID_REF; 10 46 56
1614 2409 ▶ if (ct == CONC_HAPLOID_REF && cs == CONC_HOM_REF) return CONC_HAPLOID_REF_TO_DIPLOID_REF;
Branch: 2 branches
BranchTrueFalseTotal
if (ct == CONC_HAPLOID_REF && cs == CONC_HOM_REF) return CONC_HAPLOID_REF_TO_DIPLOID_REF; 62 2347 2409
if (ct == CONC_HAPLOID_REF && cs == CONC_HOM_REF) return CONC_HAPLOID_REF_TO_DIPLOID_REF; 17 45 62
1615 2392 ▶ if (ct == CONC_HOM_ALT && test->n == 1 && test->a == truth->a) return CONC_HOM_ALT_TO_DIPLOID_ALT;
Branch: 3 branches
BranchTrueFalseTotal
if (ct == CONC_HOM_ALT && test->n == 1 && test->a == truth->a) return CONC_HOM_ALT_TO_DIPLOID_ALT; 1413 979 2392
if (ct == CONC_HOM_ALT && test->n == 1 && test->a == truth->a) return CONC_HOM_ALT_TO_DIPLOID_ALT; 35 1378 1413
if (ct == CONC_HOM_ALT && test->n == 1 && test->a == truth->a) return CONC_HOM_ALT_TO_DIPLOID_ALT; 9 26 35
1616 2383 ▶ if (cs == CONC_HOM_ALT && truth->n == 1 && truth->a == test->a) return CONC_HAPLOID_ALT_TO_HOM_ALT;
Branch: 3 branches
BranchTrueFalseTotal
if (cs == CONC_HOM_ALT && truth->n == 1 && truth->a == test->a) return CONC_HAPLOID_ALT_TO_HOM_ALT; 756 1627 2383
if (cs == CONC_HOM_ALT && truth->n == 1 && truth->a == test->a) return CONC_HAPLOID_ALT_TO_HOM_ALT; 27 729 756
if (cs == CONC_HOM_ALT && truth->n == 1 && truth->a == test->a) return CONC_HAPLOID_ALT_TO_HOM_ALT; 9 18 27
1617 2374 return (unsigned short int)CONC_DIFFERENT[ct][cs];// never -1: those four pairs were taken above
1618 }
1619  
1620 /*Call c as GT would write it, a mortal: "." for a no-call.*/
1621 764 static SV *conc_call_sv(pTHX_ const conc_call *c) {
1622 764 ▶ if (c->n == 0) return sv_2mortal(newSVpvs("."));
Branch: 1 branch
BranchTrueFalseTotal
if (c->n == 0) return sv_2mortal(newSVpvs(".")); 50 714 764
1623 714 ▶ if (c->n == 1) return sv_2mortal(newSVpvf("%u", (unsigned)c->a));
Branch: 1 branch
BranchTrueFalseTotal
if (c->n == 1) return sv_2mortal(newSVpvf("%u", (unsigned)c->a)); 204 510 714
1624 510 ▶ return sv_2mortal(newSVpvf("%u%c%u", (unsigned)c->a, c->phased ? '|' : '/', (unsigned)c->b));
Branch: 1 branch
BranchTrueFalseTotal
return sv_2mortal(newSVpvf("%u%c%u", (unsigned)c->a, c->phased ? '|' : '/', (unsigned)c->b)); 1 509 510
1625 }
1626  
1627 /*The test's #CHROM line: the pairs of samples to compare. Two VCFs of one
1628 sample each are compared whatever their samples are called; otherwise each of
1629 the test's samples is compared with the truth's of the same name.*/
1630 60 static void conc_header_test(pTHX_ vcf_reader *r) {
1631 60 conc_reader *t = (conc_reader*)r;
1632 60 conc_store *s = t->s;
1633 60 ▶ Newxz(s->test_col, r->n, size_t);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(s->test_col, r->n, size_t); 0 60 60
1634 60 ▶ Newxz(s->truth_col, r->n, size_t);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(s->truth_col, r->n, size_t); 0 60 60
1635 60 ▶ Newxz(s->test_pair, r->n, size_t);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(s->test_pair, r->n, size_t); 0 60 60
1636 60 ▶ Newxz(s->truth_pair, s->truth_n, size_t);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(s->truth_pair, s->truth_n, size_t); 0 60 60
1637 60 ▶ if (r->n == 1 && s->truth_n == 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (r->n == 1 && s->truth_n == 1) { 45 15 60
if (r->n == 1 && s->truth_n == 1) { 44 1 45
1638 44 s->pairs = 1;
1639 44 s->test_pair[0] = s->truth_pair[0] = 1;
1640 } else {
1641 16 HV *truth = (HV*)sv_2mortal((SV*)newHV());// the truth's sample => its column
1642 56 ▶ for (size_t j = 0; j < s->truth_n; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t j = 0; j < s->truth_n; j++) { 40 16 56
1643 40 SV **name = av_fetch(t->truth_names, (SSize_t)j, 0);
1644 40 ▶ if (name) (void)hv_store_ent(truth, *name, newSVuv((UV)j), 0);
Branch: 1 branch
BranchTrueFalseTotal
if (name) (void)hv_store_ent(truth, *name, newSVuv((UV)j), 0); 40 0 40
1645 }
1646 63 ▶ for (size_t i = 0; i < r->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < r->n; i++) { 47 16 63
1647 47 SV **name = av_fetch(r->names, (SSize_t)i, 0);
1648 47 ▶ HE *he = name ? hv_fetch_ent(truth, *name, 0, 0) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
HE *he = name ? hv_fetch_ent(truth, *name, 0, 0) : NULL; 47 0 47
1649 47 ▶ if (!he) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!he) continue; 19 28 47
1650 28 const size_t j = (size_t)SvUV(HeVAL(he));
1651 28 s->test_col[s->pairs] = i;
1652 28 s->truth_col[s->pairs] = j;
1653 28 s->test_pair[i] = s->truth_pair[j] = ++s->pairs;
1654 }
1655 }
1656 60 ▶ if (!s->pairs) {
Branch: 1 branch
BranchTrueFalseTotal
if (!s->pairs) { 2 58 60
1657 2 const char *test = vcf_names_list(aTHX_ r->names), *truth = vcf_names_list(aTHX_ t->truth_names);
1658 2 croak("%s: %s and the truth share no sample: the test's are %s, and the truth's %s", __func__, r->name, test, truth);
1659 }
1660 58 ▶ Newx(s->truth, s->pairs, conc_call);
Branch: 1 branch
BranchTrueFalseTotal
Newx(s->truth, s->pairs, conc_call); 0 58 58
1661 58 }
1662  
1663 /*Room for one more site of the test r, its calls, and a slot in the table,
1664 which is rebuilt at twice the size when it would be more than half full. Dies,
1665 naming r, when the calls' size would not fit in a size_t: on a 32-bit perl,
1666 349,526 samples or more do at the first 1,024 sites. Renew() checks only the
1667 multiplication by the type's size, and only on a perl built with
1668 usemallocwrap (the default), where it died with "panic: memory wrap", naming
1669 nothing; on one built without, the calls were allocated too small.*/
1670 5658 static void conc_grow(pTHX_ const vcf_reader *r, conc_store *s) {
1671 5658 ▶ if (s->n == s->room) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->n == s->room) { 60 5598 5658
1672 60 ▶ const size_t room = s->room ? 2 * s->room : 1024;// small, since its calls are 12 bytes a pair each: 1,000 samples start at 12 MB
Branch: 1 branch
BranchTrueFalseTotal
const size_t room = s->room ? 2 * s->room : 1024;// small, since its calls are 12 bytes a pair each: 1,000 samples start at 12 MB 3 57 60
1673 60 ▶ if (room < s->room || room > ((size_t)-1 / sizeof(conc_call) / 2) / s->pairs)
Branch: 2 branches
BranchTrueFalseTotal
if (room < s->room || room > ((size_t)-1 / sizeof(conc_call) / 2) / s->pairs) 60 0 60
if (room < s->room || room > ((size_t)-1 / sizeof(conc_call) / 2) / s->pairs) 0 60 60
1674 0 croak("%s: %s has more sites of its %" UVuf " samples compared than this perl can hold (%" UVuf " already)", __func__, r->name, (UV)s->pairs, (UV)s->n);
1675 60 s->room = room;
1676 60 ▶ Renew(s->site, s->room, conc_site);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->site, s->room, conc_site); 0 60 60
1677 60 ▶ Renew(s->call, s->room * 2 * s->pairs, conc_call);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->call, s->room * 2 * s->pairs, conc_call); 0 60 60
1678 }
1679 5658 ▶ if (2 * (s->n + 1) <= s->slots) return;
Branch: 1 branch
BranchTrueFalseTotal
if (2 * (s->n + 1) <= s->slots) return; 5598 60 5658
1680 60 ▶ s->slots = s->slots ? 2 * s->slots : 2048;
Branch: 1 branch
BranchTrueFalseTotal
s->slots = s->slots ? 2 * s->slots : 2048; 3 57 60
1681 60 Safefree(s->slot);
1682 60 ▶ Newxz(s->slot, s->slots, size_t);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(s->slot, s->slots, size_t); 0 60 60
1683 7228 ▶ for (size_t k = 0; k < s->n; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t k = 0; k < s->n; k++) { 7168 60 7228
1684 7168 size_t at = (size_t)s->site[k].hash & (s->slots - 1);
1685 11118 ▶ while (s->slot[at]) at = (at + 1) & (s->slots - 1);
Branch: 1 branch
BranchTrueFalseTotal
while (s->slot[at]) at = (at + 1) & (s->slots - 1); 3950 7168 11118
1686 7168 s->slot[at] = k + 1;
1687 }
1688 }
1689  
1690 /*The test's record p..e, kept as a site with its calls for each pair. A site
1691 the test lists twice is kept twice, and each compared, as the script compared
1692 each line.*/
1693 5658 static void conc_record_test(pTHX_ vcf_reader *r, const char *p, const char *e) {
1694 5658 conc_store *s = ((conc_reader*)r)->s;
1695 5658 const char *f = vcf_field_end(p, e);
1696 const char *col[9];
1697 5658 const char *format_end = vcf_columns(aTHX_ r, p, f, e, col);
1698 5658 conc_grow(aTHX_ r, s);
1699 5658 conc_site *site = s->site + s->n;
1700 5658 site->pos = vcf_pos(aTHX_ r, col[1], col[2] - 1);
1701 5657 const char *chrom = conc_chrom(col[0], col[1] - 1);
1702 5657 site->hash = conc_hash(chrom, col[1] - 1, site->pos, col[3], col[4] - 1, col[4], col[5] - 1);
1703 5657 site->found = FALSE;
1704 5657 const size_t len = (size_t)(col[5] - p);// CHROM to ALT, and the tab after ALT, which becomes the '\n'
1705 5657 ▶ if (s->text_n + len > s->text_room) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->text_n + len > s->text_room) { 56 5601 5657
1706 112 ▶ while (s->text_n + len > s->text_room) {
Branch: 1 branch
BranchTrueFalseTotal
while (s->text_n + len > s->text_room) { 56 56 112
1707 56 ▶ if (s->text_room > (size_t)-1 / 2) croak("%s: %s has more sites than this perl can hold (%" UVuf " already)", __func__, r->name, (UV)s->n);// doubling would wrap to 0, and loop for ever
Branch: 1 branch
BranchTrueFalseTotal
if (s->text_room > (size_t)-1 / 2) croak("%s: %s has more sites than this perl can hold (%" UVuf " already)", __func__, r->name, (UV)s->n);// doubling would wrap to 0, and loop for ever 0 56 56
1708 56 ▶ s->text_room = s->text_room ? 2 * s->text_room : 1 << 20;
Branch: 1 branch
BranchTrueFalseTotal
s->text_room = s->text_room ? 2 * s->text_room : 1 << 20; 0 56 56
1709 }
1710 56 Renew(s->text, s->text_room, char);
1711 }
1712 5657 site->text = s->text_n;
1713 5657 Copy(p, s->text + s->text_n, len, char);
1714 5657 s->text_n += len;
1715 5657 s->text[s->text_n - 1] = '\n';
1716 5657 size_t at = (size_t)site->hash & (s->slots - 1);
1717 11348 ▶ while (s->slot[at]) at = (at + 1) & (s->slots - 1);
Branch: 1 branch
BranchTrueFalseTotal
while (s->slot[at]) at = (at + 1) & (s->slots - 1); 5691 5657 11348
1718 5657 s->slot[at] = ++s->n;
1719 5657 conc_call *call = s->call + (s->n - 1) * 2 * s->pairs;
1720 5657 ▶ Zero(call, 2 * s->pairs, conc_call);// the truth's calls stay no-calls unless it has the site
Branch: 1 branch
BranchTrueFalseTotal
Zero(call, 2 * s->pairs, conc_call);// the truth's calls stay no-calls unless it has the site 0 5657 5657
1721 size_t gt, dp;
1722 5657 vcf_format(col[8], format_end, &gt, &dp);
1723 5657 p = format_end + 1;
1724 12419 ▶ for (size_t i = 0; i < r->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < r->n; i++) { 6767 5652 12419
1725 6767 const char *se = vcf_sample(aTHX_ r, p, e, i);
1726 6766 ▶ if (s->test_pair[i]) conc_gt(aTHX_ r, p, se, gt, dp, i, call + 2 * (s->test_pair[i] - 1));
Branch: 1 branch
BranchTrueFalseTotal
if (s->test_pair[i]) conc_gt(aTHX_ r, p, se, gt, dp, i, call + 2 * (s->test_pair[i] - 1)); 6214 552 6766
1727 6762 p = se + 1;
1728 }
1729 5652 vcf_samples_end(aTHX_ r, p, e);
1730 5651 }
1731  
1732 /*The truth's #CHROM line, which must be the one read before the test was.*/
1733 51 static void conc_header_truth(pTHX_ vcf_reader *r) {
1734 51 conc_store *s = ((conc_reader*)r)->s;
1735 51 ▶ if (r->n != s->truth_n) croak("%s: %s had %" UVuf " samples when it was first read, and has %" UVuf " now", __func__, r->name, (UV)s->truth_n, (UV)r->n);
Branch: 1 branch
BranchTrueFalseTotal
if (r->n != s->truth_n) croak("%s: %s had %" UVuf " samples when it was first read, and has %" UVuf " now", __func__, r->name, (UV)s->truth_n, (UV)r->n); 0 51 51
1736 51 }
1737  
1738 /*The truth's record p..e: its calls for each pair, given to every test site
1739 that it is. A site the truth lists twice gives the test its last calls, as the
1740 script's hash of the truth's sites did.*/
1741 5470 static void conc_record_truth(pTHX_ vcf_reader *r, const char *p, const char *e) {
1742 5470 conc_store *s = ((conc_reader*)r)->s;
1743 5485 ▶ if (!s->slots) return;// the test has no sites
Branch: 1 branch
BranchTrueFalseTotal
if (!s->slots) return;// the test has no sites 1 5469 5470
1744 5469 const char *f = vcf_field_end(p, e);
1745 const char *col[9];
1746 5469 const char *format_end = vcf_columns(aTHX_ r, p, f, e, col);
1747 5469 const UV pos = vcf_pos(aTHX_ r, col[1], col[2] - 1);
1748 5468 const char *chrom = conc_chrom(col[0], col[1] - 1);
1749 5468 const uint64_t hash = conc_hash(chrom, col[1] - 1, pos, col[3], col[4] - 1, col[4], col[5] - 1);
1750 5468 size_t hits = 0;
1751 19083 ▶ for (size_t at = (size_t)hash & (s->slots - 1); s->slot[at]; at = (at + 1) & (s->slots - 1)) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t at = (size_t)hash & (s->slots - 1); s->slot[at]; at = (at + 1) & (s->slots - 1)) { 13615 5468 19083
1752 13615 const size_t k = s->slot[at] - 1;
1753 13615 const conc_site *site = s->site + k;
1754 13615 ▶ if (site->hash != hash || site->pos != pos) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (site->hash != hash || site->pos != pos) continue; 5455 8160 13615
if (site->hash != hash || site->pos != pos) continue; 0 5455 5455
1755 const char *fld[6];
1756 5455 conc_fields(s, k, fld);
1757 5455 ▶ if (!conc_eq(conc_chrom(fld[0], fld[1] - 1), fld[1] - 1, chrom, col[1] - 1) || !conc_eq(fld[3], fld[4] - 1, col[3], col[4] - 1)
Branch: 2 branches
BranchTrueFalseTotal
if (!conc_eq(conc_chrom(fld[0], fld[1] - 1), fld[1] - 1, chrom, col[1] - 1) || !conc_eq(fld[3], fld[4] - 1, col[3], col[4] - 1) 5455 0 5455
if (!conc_eq(conc_chrom(fld[0], fld[1] - 1), fld[1] - 1, chrom, col[1] - 1) || !conc_eq(fld[3], fld[4] - 1, col[3], col[4] - 1) 5455 0 5455
1758 5455 ▶ || !conc_eq(fld[4], fld[5] - 1, col[4], col[5] - 1)) continue;
Branch: 1 branch
BranchTrueFalseTotal
|| !conc_eq(fld[4], fld[5] - 1, col[4], col[5] - 1)) continue; 0 5455 5455
1759 5455 ▶ if (hits == s->hit_room) {
Branch: 1 branch
BranchTrueFalseTotal
if (hits == s->hit_room) { 43 5412 5455
1760 43 ▶ s->hit_room = s->hit_room ? 2 * s->hit_room : 8;// a site the test lists more than once, which is rare
Branch: 1 branch
BranchTrueFalseTotal
s->hit_room = s->hit_room ? 2 * s->hit_room : 8;// a site the test lists more than once, which is rare 0 43 43
1761 43 ▶ Renew(s->hit, s->hit_room, size_t);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->hit, s->hit_room, size_t); 0 43 43
1762 }
1763 5455 s->hit[hits++] = k;
1764 }
1765 5468 ▶ if (!hits) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!hits) return; 15 5453 5468
1766 size_t gt, dp;
1767 5453 vcf_format(col[8], format_end, &gt, &dp);
1768 5453 p = format_end + 1;
1769 11627 ▶ for (size_t i = 0; i < r->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < r->n; i++) { 6183 5444 11627
1770 6183 const char *se = vcf_sample(aTHX_ r, p, e, i);
1771 6182 ▶ if (s->truth_pair[i]) conc_gt(aTHX_ r, p, se, gt, dp, i, s->truth + (s->truth_pair[i] - 1));
Branch: 1 branch
BranchTrueFalseTotal
if (s->truth_pair[i]) conc_gt(aTHX_ r, p, se, gt, dp, i, s->truth + (s->truth_pair[i] - 1)); 5822 360 6182
1772 6174 p = se + 1;
1773 }
1774 5444 vcf_samples_end(aTHX_ r, p, e);
1775 10888 ▶ for (size_t h = 0; h < hits; h++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t h = 0; h < hits; h++) { 5445 5443 10888
1776 5445 conc_site *site = s->site + s->hit[h];
1777 5445 ▶ if (!site->found) s->found++;
Branch: 1 branch
BranchTrueFalseTotal
if (!site->found) s->found++; 5443 2 5445
1778 5445 site->found = TRUE;
1779 5445 conc_call *call = s->call + s->hit[h] * 2 * s->pairs;
1780 11256 ▶ for (size_t k = 0; k < s->pairs; k++) call[2 * k + 1] = s->truth[k];
Branch: 1 branch
BranchTrueFalseTotal
for (size_t k = 0; k < s->pairs; k++) call[2 * k + 1] = s->truth[k]; 5811 5445 11256
1781 }
1782 }
1783  
1784 /*The sum of the counts c of the kinds in set, CONC_BIT()s.*/
1785 350 static UV conc_sum(const UV *c, uint64_t set) {
1786 350 UV sum = 0;
1787 16100 ▶ for (unsigned short int k = 0; k < CONC_KINDS; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int k = 0; k < CONC_KINDS; k++) { 15750 350 16100
1788 15750 ▶ if (set & CONC_BIT(k)) sum += c[k];
Branch: 1 branch
BranchTrueFalseTotal
if (set & CONC_BIT(k)) sum += c[k]; 4700 11050 15750
1789 }
1790 350 return sum;
1791 }
1792  
1793 /*x / y as a mortal, or undef when y is 0, where the script gave the string
1794 "undefined" (and, for genotype_concordance, died).*/
1795 300 static SV *conc_ratio(pTHX_ UV x, UV y) {
1796 300 ▶ return y ? sv_2mortal(newSVnv((NV)x / (NV)y)) : sv_newmortal();
Branch: 1 branch
BranchTrueFalseTotal
return y ? sv_2mortal(newSVnv((NV)x / (NV)y)) : sv_newmortal(); 217 83 300
1797 }
1798  
1799 3956 static void conc_store_sv(pTHX_ HV *h, const char *key, SV *v) {
1800 3956 (void)hv_store(h, key, (I32)strlen(key), SvREFCNT_inc_simple_NN(v), 0);
1801 3956 }
1802  
1803 /*The metrics of counts c, by the script's metrics() called as its main
1804 program called it, with no-calls left out ("no"), and with the corrections
1805 given above CONC_TP.*/
1806 50 static HV *conc_metrics(pTHX_ const UV *c) {
1807 50 HV *m = newHV();
1808 50 const UV tp = conc_sum(c, CONC_TP), fp_site = c[CONC_GAINED], fn_site = c[CONC_LOST];
1809 50 const UV fp_ref = conc_sum(c, CONC_FP_REF), mismatch = conc_sum(c, CONC_MISMATCH);
1810 50 const UV fp_genotype = fp_ref + mismatch, fn_genotype = conc_sum(c, CONC_FN_REF) + mismatch;
1811 50 const UV tn = conc_sum(c, CONC_TN);
1812 50 conc_store_sv(aTHX_ m, "tp_site", sv_2mortal(newSVuv(tp)));
1813 50 conc_store_sv(aTHX_ m, "fp_site", sv_2mortal(newSVuv(fp_site)));
1814 50 conc_store_sv(aTHX_ m, "fn_site", sv_2mortal(newSVuv(fn_site)));
1815 50 conc_store_sv(aTHX_ m, "tn_site", sv_2mortal(newSVuv(tn)));
1816 50 conc_store_sv(aTHX_ m, "tp_genotype", sv_2mortal(newSVuv(tp)));
1817 50 conc_store_sv(aTHX_ m, "fp_genotype", sv_2mortal(newSVuv(fp_genotype)));
1818 50 conc_store_sv(aTHX_ m, "fn_genotype", sv_2mortal(newSVuv(fn_genotype)));
1819 50 conc_store_sv(aTHX_ m, "tn_genotype", sv_2mortal(newSVuv(tn)));
1820 50 conc_store_sv(aTHX_ m, "genotype_concordance", conc_ratio(aTHX_ conc_sum(c, CONC_AGREE), conc_sum(c, CONC_CALLED)));
1821 50 conc_store_sv(aTHX_ m, "precision_site", conc_ratio(aTHX_ tp, tp + fp_site));
1822 50 conc_store_sv(aTHX_ m, "recall_site", conc_ratio(aTHX_ tp, tp + fn_site));
1823 50 conc_store_sv(aTHX_ m, "precision_genotype", conc_ratio(aTHX_ tp, tp + fp_genotype));
1824 50 conc_store_sv(aTHX_ m, "recall_genotype", conc_ratio(aTHX_ tp, tp + fn_genotype));
1825 50 conc_store_sv(aTHX_ m, "specificity_genotype", conc_ratio(aTHX_ tn, tn + fp_ref));
1826 50 return m;
1827 }
1828  
1829 /*Each pair's results, keyed by the test's name for its sample, from the test
1830 and truth names, the sites s holds, and whether to list the discordant,
1831 gained and lost ones.*/
1832 40 static HV *conc_results(pTHX_ const conc_store *s, AV *test_names, AV *truth_names, bool discordances) {
1833 UV *count;// CONC_KINDS a pair
1834 40 ▶ Newxz(count, s->pairs * CONC_KINDS, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(count, s->pairs * CONC_KINDS, UV); 0 40 40
1835 40 SAVEFREEPV(count);
1836 AV **list;// each pair's discordances, or NULL
1837 40 ▶ Newxz(list, s->pairs, AV*);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(list, s->pairs, AV*); 0 40 40
1838 40 SAVEFREEPV(list);
1839 87 ▶ for (size_t k = 0; k < s->pairs && discordances; k++) list[k] = (AV*)sv_2mortal((SV*)newAV());
Branch: 2 branches
BranchTrueFalseTotal
for (size_t k = 0; k < s->pairs && discordances; k++) list[k] = (AV*)sv_2mortal((SV*)newAV()); 49 38 87
for (size_t k = 0; k < s->pairs && discordances; k++) list[k] = (AV*)sv_2mortal((SV*)newAV()); 47 2 49
1840 5500 ▶ for (size_t i = 0; i < s->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < s->n; i++) { 5460 40 5500
1841 5460 const conc_call *call = s->call + i * 2 * s->pairs;
1842 const char *fld[6];
1843 5460 bool split = FALSE;// fld has been set
1844 11294 ▶ for (size_t k = 0; k < s->pairs; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t k = 0; k < s->pairs; k++) { 5834 5460 11294
1845 5834 const unsigned short int kind = conc_kind(call + 2 * k + 1, call + 2 * k);
1846 5834 count[k * CONC_KINDS + kind]++;
1847 5834 ▶ if (!list[k] || kind < CONC_DISCORDANT) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!list[k] || kind < CONC_DISCORDANT) continue; 742 5092 5834
if (!list[k] || kind < CONC_DISCORDANT) continue; 360 382 742
1848 382 ▶ if (!split) {
Branch: 1 branch
BranchTrueFalseTotal
if (!split) { 312 70 382
1849 312 conc_fields(s, i, fld);
1850 312 split = TRUE;
1851 }
1852 382 HV *row = newHV();
1853 382 conc_store_sv(aTHX_ row, "chrom", sv_2mortal(newSVpvn(fld[0], (STRLEN)(fld[1] - 1 - fld[0]))));
1854 382 conc_store_sv(aTHX_ row, "pos", sv_2mortal(newSVuv(s->site[i].pos)));
1855 382 conc_store_sv(aTHX_ row, "id", sv_2mortal(newSVpvn(fld[2], (STRLEN)(fld[3] - 1 - fld[2]))));
1856 382 conc_store_sv(aTHX_ row, "ref", sv_2mortal(newSVpvn(fld[3], (STRLEN)(fld[4] - 1 - fld[3]))));
1857 382 conc_store_sv(aTHX_ row, "alt", sv_2mortal(newSVpvn(fld[4], (STRLEN)(fld[5] - 1 - fld[4]))));
1858 382 conc_store_sv(aTHX_ row, "type", sv_2mortal(newSVpvn(CONC_NAME[kind], strlen(CONC_NAME[kind]))));
1859 382 conc_store_sv(aTHX_ row, "test", conc_call_sv(aTHX_ call + 2 * k));
1860 382 conc_store_sv(aTHX_ row, "truth", conc_call_sv(aTHX_ call + 2 * k + 1));
1861 382 av_push(list[k], newRV_noinc((SV*)row));
1862 }
1863 }
1864 40 HV *out = (HV*)sv_2mortal((SV*)newHV());
1865 90 ▶ for (size_t k = 0; k < s->pairs; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t k = 0; k < s->pairs; k++) { 50 40 90
1866 50 SV **test = av_fetch(test_names, (SSize_t)s->test_col[k], 0), **truth = av_fetch(truth_names, (SSize_t)s->truth_col[k], 0);
1867 50 ▶ if (!test || !truth) croak("%s: pair %" UVuf " has lost a sample's name", __func__, (UV)k);// cannot happen: both headers pushed every name
Branch: 2 branches
BranchTrueFalseTotal
if (!test || !truth) croak("%s: pair %" UVuf " has lost a sample's name", __func__, (UV)k);// cannot happen: both headers pushed every name 50 0 50
if (!test || !truth) croak("%s: pair %" UVuf " has lost a sample's name", __func__, (UV)k);// cannot happen: both headers pushed every name 0 50 50
1868 50 const UV *c = count + k * CONC_KINDS;
1869 50 HV *pair = newHV();
1870 50 HV *counts = newHV();
1871 2300 ▶ for (unsigned short int j = 0; j < CONC_KINDS; j++) (void)hv_store(counts, CONC_NAME[j], (I32)strlen(CONC_NAME[j]), newSVuv(c[j]), 0);
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int j = 0; j < CONC_KINDS; j++) (void)hv_store(counts, CONC_NAME[j], (I32)strlen(CONC_NAME[j]), newSVuv(c[j]), 0); 2250 50 2300
1872 50 conc_store_sv(aTHX_ pair, "test_sample", sv_2mortal(newSVsv(*test)));
1873 50 conc_store_sv(aTHX_ pair, "truth_sample", sv_2mortal(newSVsv(*truth)));
1874 50 conc_store_sv(aTHX_ pair, "sites", sv_2mortal(newSVuv((UV)s->n)));
1875 50 conc_store_sv(aTHX_ pair, "in_truth", sv_2mortal(newSVuv(s->found)));
1876 50 (void)hv_store(pair, "counts", 6, newRV_noinc((SV*)counts), 0);
1877 50 (void)hv_store(pair, "metrics", 7, newRV_noinc((SV*)conc_metrics(aTHX_ c)), 0);
1878 50 ▶ (void)hv_store(pair, "discordances", 12, list[k] ? newRV_inc((SV*)list[k]) : newSV(0), 0);
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_store(pair, "discordances", 12, list[k] ? newRV_inc((SV*)list[k]) : newSV(0), 0); 47 3 50
1879 50 (void)hv_store_ent(out, *test, newRV_noinc((SV*)pair), 0);
1880 }
1881 40 return out;
1882 }
1883  
1884 /*An on_header that reads no further, and an on_record that is never called
1885 after it, for _vcf_samples(), which reads only the #CHROM line.*/
1886 61 static void conc_stop(pTHX_ vcf_reader *r) {
1887 61 r->stop = TRUE;
1888 61 }
1889  
1890 0 static void conc_skip(pTHX_ vcf_reader *r, const char *p, const char *e) {
1891 PERL_UNUSED_ARG(r);
1892 PERL_UNUSED_ARG(p);
1893 PERL_UNUSED_ARG(e);
1894 0 }
1895  
1896 /*The genotypes of a marker panel, for hirisplex_genotypes().
1897  
1898 The panel is 41 markers and a VCF of a whole genome is tens of millions of
1899 records, so each record is tested against the panel rather than the panel
1900 searched for in the file. Matching by position tests the chromosome against a
1901 bitmap first, which turns away a record on one test, and reads POS and
1902 searches only when that passes; matching by ID compares the ID column against
1903 the markers' rs numbers. Either way a record that matches nothing is read no
1904 further than its first three fields.
1905  
1906 Which allele is counted is perl's to say, from share/hirisplex_s_panel.tsv:
1907 the panel names the allele on the forward strand, so nothing here complements
1908 anything. The allele is looked for among REF and the ALTs, and its place
1909 there is what the genotypes are counted against, so that a site written with
1910 several ALTs, or with the counted allele as its REF, is counted the same way.
1911 A record whose REF is longer than one base is passed over for every marker but
1912 the one that is an indel, since it is some other variant that shares the
1913 position. That one, an insertion, is counted from the ALT that is REF with its
1914 base put in once, which is the same test however the VCF anchors the indel.
1915 Bases are compared regardless of case, as CHROM is.
1916  
1917 What is kept is one byte for each sample at each marker, so a file costs one
1918 byte times its samples times the panel, however many records it holds.*/
1919  
1920 #define HPS_ID 16 // an rs number and its NUL; the longest the panel holds is "rs796296176", 11 characters
1921  
1922 //What hps_dose() gives for a sample at a marker; 0, 1 and 2 are counts of the counted allele
1923 enum {
1924 HPS_ABSENT = 3, // no record of the marker was in the file; set for every sample before reading
1925 HPS_NO_CALL = 4 // the marker was in the file, and this sample had no diploid call of it
1926 };
1927  
1928 typedef struct {
1929 unsigned short int chrom;// vcf_chrom()'s numbering, 1 to 24; 0 when the panel gives no position
1930 UV pos;
1931 char allele;// the base counted, or the base inserted when insertion is TRUE
1932 bool insertion;// TRUE = count the ALT that is REF with allele put in once, for the one marker of the panel that is an indel
1933 size_t k;// the marker's place in the panel perl gave, which its genotypes are stored under
1934 char id[HPS_ID];// the marker's rs number, for matching by ID
1935 } hps_site;
1936  
1937 typedef struct {
1938 vcf_reader r;// first, so that the vcf_reader * hps_header() and hps_record() are given is this
1939 hps_site *site;// what is searched, sorted by chromosome and position, or by rs number when by_id
1940 size_t entries;// how many site's holds, which is more than sites when a marker is searched for under more than one rs number
1941 size_t sites;// markers in the panel, which is what each sample's genotypes are counted into
1942 bool by_id;// TRUE = match the ID column, FALSE = CHROM and POS
1943 uint32_t chroms;// bit c set for each chromosome c the panel uses, tested before POS is read
1944 unsigned char *dose;// r.n * sites, sample-major: a count, or one of the codes above
1945 bool *seen;// one per marker: the file held a record for it
1946 bool *carried;// one per marker: a record of it held the counted allele among REF and the ALTs
1947 } hps_reader;
1948  
1949 /*Orders the panel by chromosome and position, for hps_find().*/
1950 3030 static int hps_cmp_pos(const void *a, const void *b) {
1951 3030 const hps_site *x = (const hps_site*)a, *y = (const hps_site*)b;
1952 3030 ▶ if (x->chrom != y->chrom) return x->chrom < y->chrom ? -1 : 1;
Branch: 2 branches
BranchTrueFalseTotal
if (x->chrom != y->chrom) return x->chrom < y->chrom ? -1 : 1; 1342 1688 3030
if (x->chrom != y->chrom) return x->chrom < y->chrom ? -1 : 1; 330 1012 1342
1953 1688 ▶ if (x->pos != y->pos) return x->pos < y->pos ? -1 : 1;
Branch: 2 branches
BranchTrueFalseTotal
if (x->pos != y->pos) return x->pos < y->pos ? -1 : 1; 1688 0 1688
if (x->pos != y->pos) return x->pos < y->pos ? -1 : 1; 1294 394 1688
1954 0 return 0;
1955 }
1956  
1957 /*Orders the panel by rs number, for hps_find_id().*/
1958 522 static int hps_cmp_id(const void *a, const void *b) {
1959 522 return strcmp(((const hps_site*)a)->id, ((const hps_site*)b)->id);
1960 }
1961  
1962 /*The marker at chrom and pos, or NULL.*/
1963 332 static const hps_site *hps_find(const hps_reader *t, unsigned short int chrom, UV pos) {
1964 332 size_t lo = 0, hi = t->entries;
1965 1349 ▶ while (lo < hi) {
Branch: 1 branch
BranchTrueFalseTotal
while (lo < hi) { 1324 25 1349
1966 1324 size_t mid = lo + (hi - lo) / 2;
1967 1324 const hps_site *s = t->site + mid;
1968 1324 ▶ if (s->chrom < chrom || (s->chrom == chrom && s->pos < pos)) lo = mid + 1;
Branch: 3 branches
BranchTrueFalseTotal
if (s->chrom < chrom || (s->chrom == chrom && s->pos < pos)) lo = mid + 1; 1102 222 1324
if (s->chrom < chrom || (s->chrom == chrom && s->pos < pos)) lo = mid + 1; 964 138 1102
if (s->chrom < chrom || (s->chrom == chrom && s->pos < pos)) lo = mid + 1; 194 770 964
1969 908 ▶ else if (s->chrom == chrom && s->pos == pos) return s;
Branch: 2 branches
BranchTrueFalseTotal
else if (s->chrom == chrom && s->pos == pos) return s; 770 138 908
else if (s->chrom == chrom && s->pos == pos) return s; 307 463 770
1970 601 else hi = mid;
1971 }
1972 25 return NULL;
1973 }
1974  
1975 /*The marker whose rs number is the one name p..f, or NULL.*/
1976 151 static const hps_site *hps_find_name(const hps_reader *t, const char *p, const char *f) {
1977 151 size_t n = (size_t)(f - p);
1978 151 ▶ if (n == 0 || n >= HPS_ID) return NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (n == 0 || n >= HPS_ID) return NULL; 151 0 151
if (n == 0 || n >= HPS_ID) return NULL; 0 151 151
1979 151 size_t lo = 0, hi = t->entries;
1980 827 ▶ while (lo < hi) {
Branch: 1 branch
BranchTrueFalseTotal
while (lo < hi) { 772 55 827
1981 772 size_t mid = lo + (hi - lo) / 2;
1982 772 const hps_site *s = t->site + mid;
1983 772 int c = strncmp(s->id, p, n);
1984 772 ▶ if (c == 0 && s->id[n] != '\0') c = 1;// s->id runs on where p..f has ended, so it sorts after
Branch: 2 branches
BranchTrueFalseTotal
if (c == 0 && s->id[n] != '\0') c = 1;// s->id runs on where p..f has ended, so it sorts after 102 670 772
if (c == 0 && s->id[n] != '\0') c = 1;// s->id runs on where p..f has ended, so it sorts after 6 96 102
1985 772 ▶ if (c < 0) lo = mid + 1;
Branch: 1 branch
BranchTrueFalseTotal
if (c < 0) lo = mid + 1; 168 604 772
1986 604 ▶ else if (c == 0) return s;
Branch: 1 branch
BranchTrueFalseTotal
else if (c == 0) return s; 96 508 604
1987 508 else hi = mid;
1988 }
1989 55 return NULL;
1990 }
1991  
1992 /*The marker whose rs number is in the ID field p..f, or NULL. An ID of several
1993 names, which the VCF specification separates with semicolons ("Semicolon-
1994 separated list of unique identifiers where available", VCFv4.2 section 1.4.1,
1995 field 3), is matched on the first of them that is a marker's. Up to 2026-11-10
1996 only its first name was looked at, so that "foo;rs12913832" matched nothing.*/
1997 103 static const hps_site *hps_find_id(const hps_reader *t, const char *p, const char *f) {
1998 48 for (;;) {
1999 151 const char *semi = (const char*)memchr(p, ';', (size_t)(f - p));
2000 151 ▶ const hps_site *s = hps_find_name(t, p, semi ? semi : f);
Branch: 1 branch
BranchTrueFalseTotal
const hps_site *s = hps_find_name(t, p, semi ? semi : f); 96 55 151
2001 151 ▶ if (s || !semi) return s;
Branch: 2 branches
BranchTrueFalseTotal
if (s || !semi) return s; 55 96 151
if (s || !semi) return s; 7 48 55
2002 48 p = semi + 1;
2003 }
2004 }
2005  
2006 /*Whether the ALT a..ae is the REF r..re with the one base put in, in either
2007 case. Past the bases the two share at the start, the first base of ALT that
2008 differs is the one put in, and the rest of ALT must be the rest of REF; in a
2009 run of that base it could have gone anywhere in the run, and gives the same
2010 ALT. An MNV or a symbolic ALT such as <INS> fails it.*/
2011 28 static bool hps_inserts(char base, const char *r, const char *re, const char *a, const char *ae) {
2012 28 const size_t rl = (size_t)(re - r);
2013 28 ▶ if ((size_t)(ae - a) != rl + 1) return FALSE;
Branch: 1 branch
BranchTrueFalseTotal
if ((size_t)(ae - a) != rl + 1) return FALSE; 2 26 28
2014 26 size_t i = 0;// the first place ALT differs from REF, read after the loop
2015 52 ▶ while (i < rl && toUPPER(r[i]) == toUPPER(a[i])) i++;
Branch: 4 branches
BranchTrueFalseTotal
while (i < rl && toUPPER(r[i]) == toUPPER(a[i])) i++; 27 25 52
while (i < rl && toUPPER(r[i]) == toUPPER(a[i])) i++; 1 26 27
while (i < rl && toUPPER(r[i]) == toUPPER(a[i])) i++; 1 26 27
while (i < rl && toUPPER(r[i]) == toUPPER(a[i])) i++; 26 1 27
2016 26 ▶ if (toUPPER(a[i]) != toUPPER(base)) return FALSE;
Branch: 3 branches
BranchTrueFalseTotal
if (toUPPER(a[i]) != toUPPER(base)) return FALSE; 1 25 26
if (toUPPER(a[i]) != toUPPER(base)) return FALSE; 0 26 26
if (toUPPER(a[i]) != toUPPER(base)) return FALSE; 2 24 26
2017 24 ▶ for (size_t j = i; j < rl; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t j = i; j < rl; j++) { 0 24 24
2018 0 ▶ if (toUPPER(r[j]) != toUPPER(a[j + 1])) return FALSE;
Branch: 3 branches
BranchTrueFalseTotal
if (toUPPER(r[j]) != toUPPER(a[j + 1])) return FALSE; 0 0 0
if (toUPPER(r[j]) != toUPPER(a[j + 1])) return FALSE; 0 0 0
if (toUPPER(r[j]) != toUPPER(a[j + 1])) return FALSE; 0 0 0
2019 }
2020 24 return TRUE;
2021 }
2022  
2023 /*Where the marker's counted allele is among REF (0) and the ALTs (1, 2, ...),
2024 or -1 when the record does not carry it at all, which leaves every call of the
2025 record 0 copies of it. REF is ref..ref_end and ALT is alt..alt_end.*/
2026 400 static short int hps_allele(const hps_site *s, const char *ref, const char *ref_end, const char *alt, const char *alt_end) {
2027 400 size_t ref_len = (size_t)(ref_end - ref);
2028 400 ▶ if (!s->insertion && ref_len == 1 && toUPPER(*ref) == toUPPER(s->allele)) return 0;
Branch: 5 branches
BranchTrueFalseTotal
if (!s->insertion && ref_len == 1 && toUPPER(*ref) == toUPPER(s->allele)) return 0; 373 27 400
if (!s->insertion && ref_len == 1 && toUPPER(*ref) == toUPPER(s->allele)) return 0; 373 0 373
if (!s->insertion && ref_len == 1 && toUPPER(*ref) == toUPPER(s->allele)) return 0; 1 372 373
if (!s->insertion && ref_len == 1 && toUPPER(*ref) == toUPPER(s->allele)) return 0; 0 373 373
if (!s->insertion && ref_len == 1 && toUPPER(*ref) == toUPPER(s->allele)) return 0; 81 292 373
2029 319 short int i = 1;
2030 390 ▶ for (const char *q = alt; q <= alt_end; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (const char *q = alt; q <= alt_end; i++) { 347 43 390
2031 347 const char *c = (const char*)memchr(q, ',', (size_t)(alt_end - q));
2032 347 ▶ const char *ce = c ? c : alt_end;
Branch: 1 branch
BranchTrueFalseTotal
const char *ce = c ? c : alt_end; 28 319 347
2033 347 ▶ if (s->insertion ? hps_inserts(s->allele, ref, ref_end, q, ce) : (ce - q == 1 && toUPPER(*q) == toUPPER(s->allele))) return i;
Branch: 6 branches
BranchTrueFalseTotal
if (s->insertion ? hps_inserts(s->allele, ref, ref_end, q, ce) : (ce - q == 1 && toUPPER(*q) == toUPPER(s->allele))) return i; 28 319 347
if (s->insertion ? hps_inserts(s->allele, ref, ref_end, q, ce) : (ce - q == 1 && toUPPER(*q) == toUPPER(s->allele))) return i; 319 0 319
if (s->insertion ? hps_inserts(s->allele, ref, ref_end, q, ce) : (ce - q == 1 && toUPPER(*q) == toUPPER(s->allele))) return i; 0 319 319
if (s->insertion ? hps_inserts(s->allele, ref, ref_end, q, ce) : (ce - q == 1 && toUPPER(*q) == toUPPER(s->allele))) return i; 0 319 319
if (s->insertion ? hps_inserts(s->allele, ref, ref_end, q, ce) : (ce - q == 1 && toUPPER(*q) == toUPPER(s->allele))) return i; 252 67 319
if (s->insertion ? hps_inserts(s->allele, ref, ref_end, q, ce) : (ce - q == 1 && toUPPER(*q) == toUPPER(s->allele))) return i; 276 71 347
2034 71 ▶ if (i == 127) break;// a short int holds no more, and no record of these markers has so many ALTs
Branch: 1 branch
BranchTrueFalseTotal
if (i == 127) break;// a short int holds no more, and no record of these markers has so many ALTs 0 71 71
2035 71 q = ce + 1;
2036 }
2037 43 return -1;
2038 }
2039  
2040 /*The sample field p..e at a marker whose counted allele is at idx, whose
2041 FORMAT has GT at gt and DP at dp: how many of the two alleles are idx, or
2042 HPS_NO_CALL for a genotype that is missing or partly missing, is not diploid,
2043 or has a DP below min_depth. The panel is autosomal, so a haploid call is not
2044 a dosage and is not counted as one.*/
2045 2948 static unsigned char hps_dose(const vcf_reader *r, const char *p, const char *e, size_t gt, size_t dp, short int idx) {
2046 const char *s, *sf;
2047 2948 ▶ if (vcf_shallow(r, p, e, dp)) return HPS_NO_CALL;
Branch: 1 branch
BranchTrueFalseTotal
if (vcf_shallow(r, p, e, dp)) return HPS_NO_CALL; 116 2832 2948
2048 2832 ▶ if (gt == VCF_ABSENT || !vcf_subfield(p, e, gt, &s, &sf) || s == sf) return HPS_NO_CALL;
Branch: 3 branches
BranchTrueFalseTotal
if (gt == VCF_ABSENT || !vcf_subfield(p, e, gt, &s, &sf) || s == sf) return HPS_NO_CALL; 2832 0 2832
if (gt == VCF_ABSENT || !vcf_subfield(p, e, gt, &s, &sf) || s == sf) return HPS_NO_CALL; 2832 0 2832
if (gt == VCF_ABSENT || !vcf_subfield(p, e, gt, &s, &sf) || s == sf) return HPS_NO_CALL; 0 2832 2832
2049 2832 unsigned short int alleles = 0, carried = 0;
2050 8139 ▶ while (s < sf) {
Branch: 1 branch
BranchTrueFalseTotal
while (s < sf) { 5462 2677 8139
2051 5462 ▶ if (*s < '0' || *s > '9') return HPS_NO_CALL;// missing ("."), or a separator where an allele belongs
Branch: 2 branches
BranchTrueFalseTotal
if (*s < '0' || *s > '9') return HPS_NO_CALL;// missing ("."), or a separator where an allele belongs 5307 155 5462
if (*s < '0' || *s > '9') return HPS_NO_CALL;// missing ("."), or a separator where an allele belongs 0 5307 5307
2052 5307 UV a = 0;
2053 10614 ▶ for (; s < sf && *s >= '0' && *s <= '9'; s++) {
Branch: 3 branches
BranchTrueFalseTotal
for (; s < sf && *s >= '0' && *s <= '9'; s++) { 7937 2677 10614
for (; s < sf && *s >= '0' && *s <= '9'; s++) { 5471 2466 7937
for (; s < sf && *s >= '0' && *s <= '9'; s++) { 5307 164 5471
2054 5307 ▶ if (a > (UV_MAX - 9) / 10) return HPS_NO_CALL;
Branch: 1 branch
BranchTrueFalseTotal
if (a > (UV_MAX - 9) / 10) return HPS_NO_CALL; 0 5307 5307
2055 5307 a = a * 10 + (UV)(*s - '0');
2056 }
2057 5307 ▶ if (++alleles > 2) return HPS_NO_CALL;
Branch: 1 branch
BranchTrueFalseTotal
if (++alleles > 2) return HPS_NO_CALL; 0 5307 5307
2058 5307 ▶ if (idx >= 0 && a == (UV)idx) carried++;
Branch: 2 branches
BranchTrueFalseTotal
if (idx >= 0 && a == (UV)idx) carried++; 5141 166 5307
if (idx >= 0 && a == (UV)idx) carried++; 2611 2530 5141
2059 5307 ▶ if (s < sf) {
Branch: 1 branch
BranchTrueFalseTotal
if (s < sf) { 2630 2677 5307
2060 2630 ▶ if (*s != '/' && *s != '|') return HPS_NO_CALL;
Branch: 2 branches
BranchTrueFalseTotal
if (*s != '/' && *s != '|') return HPS_NO_CALL; 164 2466 2630
if (*s != '/' && *s != '|') return HPS_NO_CALL; 0 164 164
2061 2630 ▶ if (++s == sf) return HPS_NO_CALL;// a separator with no allele after it
Branch: 1 branch
BranchTrueFalseTotal
if (++s == sf) return HPS_NO_CALL;// a separator with no allele after it 0 2630 2630
2062 }
2063 }
2064 2677 ▶ if (alleles != 2) return HPS_NO_CALL;
Branch: 1 branch
BranchTrueFalseTotal
if (alleles != 2) return HPS_NO_CALL; 47 2630 2677
2065 2630 return (unsigned char)carried;
2066 }
2067  
2068 49 static void hps_header(pTHX_ vcf_reader *r) {
2069 49 hps_reader *t = (hps_reader*)r;
2070 49 Newx(t->dose, r->n * t->sites, unsigned char);
2071 49 SAVEFREEPV(t->dose);// freed at the caller's LEAVE, croak or not; see vcf_read()'s block
2072 49 memset(t->dose, HPS_ABSENT, r->n * t->sites);
2073 49 Newxz(t->seen, t->sites, bool);
2074 49 SAVEFREEPV(t->seen);
2075 49 Newxz(t->carried, t->sites, bool);
2076 49 SAVEFREEPV(t->carried);
2077 49 }
2078  
2079 440 static void hps_record(pTHX_ vcf_reader *r, const char *p, const char *e) {
2080 440 hps_reader *t = (hps_reader*)r;
2081 440 const char *f = vcf_field_end(p, e);
2082 const hps_site *s;
2083 440 ▶ if (t->by_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (t->by_id) { 103 337 440
2084 163 ▶ if (f >= e) return;
Branch: 1 branch
BranchTrueFalseTotal
if (f >= e) return; 0 103 103
2085 103 const char *pos = f + 1;
2086 103 const char *pos_end = vcf_field_end(pos, e);
2087 103 ▶ if (pos_end >= e) return;
Branch: 1 branch
BranchTrueFalseTotal
if (pos_end >= e) return; 0 103 103
2088 103 const char *id = pos_end + 1;
2089 103 s = hps_find_id(t, id, vcf_field_end(id, e));
2090 } else {
2091 337 unsigned short int chrom = vcf_chrom(p, f);
2092 337 ▶ if (chrom == 0 || chrom > 31 || !(t->chroms & ((uint32_t)1 << chrom))) return;
Branch: 3 branches
BranchTrueFalseTotal
if (chrom == 0 || chrom > 31 || !(t->chroms & ((uint32_t)1 << chrom))) return; 337 0 337
if (chrom == 0 || chrom > 31 || !(t->chroms & ((uint32_t)1 << chrom))) return; 337 0 337
if (chrom == 0 || chrom > 31 || !(t->chroms & ((uint32_t)1 << chrom))) return; 5 332 337
2093 332 ▶ if (f >= e) return;
Branch: 1 branch
BranchTrueFalseTotal
if (f >= e) return; 0 332 332
2094 332 const char *pos = f + 1;
2095 332 s = hps_find(t, chrom, vcf_pos(aTHX_ r, pos, vcf_field_end(pos, e)));
2096 }
2097 435 ▶ if (!s) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!s) return; 32 403 435
2098 const char *col[9];
2099 403 const char *format_end = vcf_columns(aTHX_ r, p, f, e, col);
2100 403 const char *ref = col[3], *ref_end = col[4] - 1;
2101 403 ▶ if (!s->insertion && ref_end - ref != 1) return;// some other variant sharing the marker's position
Branch: 2 branches
BranchTrueFalseTotal
if (!s->insertion && ref_end - ref != 1) return;// some other variant sharing the marker's position 376 27 403
if (!s->insertion && ref_end - ref != 1) return;// some other variant sharing the marker's position 3 373 376
2102 400 short int idx = hps_allele(s, ref, ref_end, col[4], col[5] - 1);
2103 // A site split into one record per ALT reaches here once for each, and only
2104 // the record that carries the counted allele says anything about it; the
2105 // others would count every call 0. So a marker already counted from a record
2106 // that carried it is left alone, and one counted from a record that did not
2107 // is counted again when a later record does carry it.
2108 400 ▶ if (t->seen[s->k] && (t->carried[s->k] || idx < 0)) return;
Branch: 3 branches
BranchTrueFalseTotal
if (t->seen[s->k] && (t->carried[s->k] || idx < 0)) return; 40 360 400
if (t->seen[s->k] && (t->carried[s->k] || idx < 0)) return; 20 20 40
if (t->seen[s->k] && (t->carried[s->k] || idx < 0)) return; 0 20 20
2109 size_t gt, dp;
2110 380 vcf_format(col[8], format_end, &gt, &dp);
2111 380 t->seen[s->k] = TRUE;
2112 380 ▶ if (idx >= 0) t->carried[s->k] = TRUE;
Branch: 1 branch
BranchTrueFalseTotal
if (idx >= 0) t->carried[s->k] = TRUE; 357 23 380
2113 380 p = format_end + 1;
2114 3318 ▶ for (size_t i = 0; i < r->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < r->n; i++) { 2938 380 3318
2115 2938 const char *se = vcf_sample(aTHX_ r, p, e, i);
2116 2938 t->dose[i * t->sites + s->k] = hps_dose(r, p, se, gt, dp, idx);
2117 2938 p = se + 1;
2118 }
2119 380 vcf_samples_end(aTHX_ r, p, e);
2120 }
2121  
2122 /*What perl gave to search for, as hps_site's. Each element of panel is
2123 [chromosome, position, allele, insertion, rs number, marker], the chromosome
2124 PLINK's number or 0 where no position is given, and marker the 0-based place
2125 in the panel of markers that the entry's genotypes belong to. There is
2126 normally one entry for each marker, and more than one where a marker is
2127 searched for under an rs number that has since been merged into another, which
2128 the file may use either of; markers says how many markers there are in all.*/
2129 52 static void hps_panel(pTHX_ hps_reader *t, AV *panel, size_t markers) {
2130 52 t->entries = (size_t)(av_len(panel) + 1);
2131 52 t->sites = markers;
2132 52 ▶ if (!t->entries || !markers) croak("%s: the panel is empty", __func__);
Branch: 2 branches
BranchTrueFalseTotal
if (!t->entries || !markers) croak("%s: the panel is empty", __func__); 52 0 52
if (!t->entries || !markers) croak("%s: the panel is empty", __func__); 0 52 52
2133 52 ▶ Newxz(t->site, t->entries, hps_site);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(t->site, t->entries, hps_site); 0 52 52
2134 52 SAVEFREEPV(t->site);
2135 1174 ▶ for (SSize_t i = 0; i <= av_len(panel); i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (SSize_t i = 0; i <= av_len(panel); i++) { 1123 51 1174
2136 1123 SV **row = av_fetch(panel, i, 0);
2137 1123 ▶ if (!row || !SvROK(*row) || SvTYPE(SvRV(*row)) != SVt_PVAV) croak("%s: entry %" IVdf " of the panel isn't an array ref", __func__, (IV)i);
Branch: 3 branches
BranchTrueFalseTotal
if (!row || !SvROK(*row) || SvTYPE(SvRV(*row)) != SVt_PVAV) croak("%s: entry %" IVdf " of the panel isn't an array ref", __func__, (IV)i); 1123 0 1123
if (!row || !SvROK(*row) || SvTYPE(SvRV(*row)) != SVt_PVAV) croak("%s: entry %" IVdf " of the panel isn't an array ref", __func__, (IV)i); 1123 0 1123
if (!row || !SvROK(*row) || SvTYPE(SvRV(*row)) != SVt_PVAV) croak("%s: entry %" IVdf " of the panel isn't an array ref", __func__, (IV)i); 0 1123 1123
2138 1123 AV *m = (AV*)SvRV(*row);
2139 1123 ▶ if (av_len(m) != 5) croak("%s: entry %" IVdf " of the panel has %" IVdf " fields, and needs 6", __func__, (IV)i, (IV)(av_len(m) + 1));
Branch: 1 branch
BranchTrueFalseTotal
if (av_len(m) != 5) croak("%s: entry %" IVdf " of the panel has %" IVdf " fields, and needs 6", __func__, (IV)i, (IV)(av_len(m) + 1)); 0 1123 1123
2140 SV **fld[6];
2141 7861 ▶ for (unsigned short int k = 0; k < 6; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int k = 0; k < 6; k++) { 6738 1123 7861
2142 6738 fld[k] = av_fetch(m, (SSize_t)k, 0);
2143 6738 ▶ if (!fld[k]) croak("%s: field %u of entry %" IVdf " of the panel is missing", __func__, (unsigned)k, (IV)i);
Branch: 1 branch
BranchTrueFalseTotal
if (!fld[k]) croak("%s: field %u of entry %" IVdf " of the panel is missing", __func__, (unsigned)k, (IV)i); 0 6738 6738
2144 }
2145 1123 hps_site *s = t->site + i;
2146 1123 s->k = (size_t)SvUV(*fld[5]);
2147 1123 ▶ if (s->k >= markers) croak("%s: entry %" IVdf " of the panel is marker %" UVuf ", and there are %" UVuf, __func__, (IV)i, (UV)s->k, (UV)markers);
Branch: 1 branch
BranchTrueFalseTotal
if (s->k >= markers) croak("%s: entry %" IVdf " of the panel is marker %" UVuf ", and there are %" UVuf, __func__, (IV)i, (UV)s->k, (UV)markers); 0 1123 1123
2148 1123 s->chrom = (unsigned short int)SvUV(*fld[0]);
2149 1123 s->pos = SvUV(*fld[1]);
2150 1123 s->insertion = SvTRUE(*fld[3]) ? TRUE : FALSE;
2151 STRLEN len;
2152 1123 const char *allele = SvPV(*fld[2], len);
2153 1123 ▶ if (len != 1) croak("%s: entry %" IVdf " of the panel counts \"%.*s\", which isn't one base", __func__, (IV)i, (int)len, allele);
Branch: 1 branch
BranchTrueFalseTotal
if (len != 1) croak("%s: entry %" IVdf " of the panel counts \"%.*s\", which isn't one base", __func__, (IV)i, (int)len, allele); 1 1122 1123
2154 1122 s->allele = allele[0];
2155 1122 const char *id = SvPV(*fld[4], len);
2156 1122 ▶ if (!len || len >= HPS_ID) croak("%s: entry %" IVdf " of the panel is named \"%.*s\", which is %s", __func__, (IV)i, (int)len, id,
Branch: 3 branches
BranchTrueFalseTotal
if (!len || len >= HPS_ID) croak("%s: entry %" IVdf " of the panel is named \"%.*s\", which is %s", __func__, (IV)i, (int)len, id, 1122 0 1122
if (!len || len >= HPS_ID) croak("%s: entry %" IVdf " of the panel is named \"%.*s\", which is %s", __func__, (IV)i, (int)len, id, 0 1122 1122
if (!len || len >= HPS_ID) croak("%s: entry %" IVdf " of the panel is named \"%.*s\", which is %s", __func__, (IV)i, (int)len, id, 0 0 0
2157 len ? "longer than an rs number" : "empty");
2158 1122 memcpy(s->id, id, len);
2159 1122 s->id[len] = '\0';
2160 1122 ▶ if (s->chrom && s->chrom < 32) t->chroms |= (uint32_t)1 << s->chrom;
Branch: 2 branches
BranchTrueFalseTotal
if (s->chrom && s->chrom < 32) t->chroms |= (uint32_t)1 << s->chrom; 996 126 1122
if (s->chrom && s->chrom < 32) t->chroms |= (uint32_t)1 << s->chrom; 996 0 996
2161 }
2162 51 ▶ qsort(t->site, t->entries, sizeof(hps_site), t->by_id ? hps_cmp_id : hps_cmp_pos);
Branch: 1 branch
BranchTrueFalseTotal
qsort(t->site, t->entries, sizeof(hps_site), t->by_id ? hps_cmp_id : hps_cmp_pos); 3 48 51
2163 51 }
2164  
2165 /*The panel's genotypes for every sample of the VCF name, which next returns a
2166 block of at a time. Returns sample => an array of one value for each marker of
2167 the panel, in the panel's order: 0, 1 or 2 copies of the counted allele, or
2168 undef where the sample had no call. *names is the samples in file order and
2169 *seen one 0 or 1 for each marker, saying whether the file held a record of it
2170 at all, which tells a marker nobody was called at from one nobody carries.*/
2171 17 static HV *hps_dosage_vcf(pTHX_ SV *next, const char *name, UV min_depth, AV *panel, size_t markers, bool by_id, AV **names, AV **seen) {
2172 hps_reader t;
2173 17 Zero(&t, 1, hps_reader);
2174 17 t.r.name = name;
2175 17 t.r.min_depth = min_depth;
2176 17 t.r.on_header = hps_header;
2177 17 t.r.on_record = hps_record;
2178 17 t.by_id = by_id;
2179 17 hps_panel(aTHX_ &t, panel, markers);
2180 16 vcf_read(aTHX_ next, &t.r);
2181 15 HV *out = t.r.samples;
2182 47 ▶ for (size_t i = 0; i < t.r.n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < t.r.n; i++) { 32 15 47
2183 32 SV **sample = av_fetch(t.r.names, (SSize_t)i, 0);
2184 32 ▶ if (!sample) croak("%s: sample %" UVuf " of %s has lost its name", __func__, (UV)i, name);// cannot happen: every sample read was pushed
Branch: 1 branch
BranchTrueFalseTotal
if (!sample) croak("%s: sample %" UVuf " of %s has lost its name", __func__, (UV)i, name);// cannot happen: every sample read was pushed 0 32 32
2185 32 AV *row = newAV();
2186 32 av_extend(row, (SSize_t)t.sites - 1);
2187 1188 ▶ for (size_t k = 0; k < t.sites; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t k = 0; k < t.sites; k++) { 1156 32 1188
2188 1156 unsigned char d = t.dose[i * t.sites + k];
2189 1156 ▶ av_push(row, d <= 2 ? newSVuv(d) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(row, d <= 2 ? newSVuv(d) : newSV(0)); 705 451 1156
2190 }
2191 32 (void)hv_store_ent(out, *sample, newRV_noinc((SV*)row), 0);// in place of the column vcf_header() stored
2192 }
2193 15 AV *was = newAV();
2194 15 av_extend(was, (SSize_t)t.sites - 1);
2195 552 ▶ for (size_t k = 0; k < t.sites; k++) av_push(was, newSVuv(t.seen[k] ? 1 : 0));
Branch: 1 branch
BranchTrueFalseTotal
for (size_t k = 0; k < t.sites; k++) av_push(was, newSVuv(t.seen[k] ? 1 : 0)); 537 15 552
2196 15 *names = t.r.names;
2197 15 *seen = was;
2198 15 return out;
2199 }
2200  
2201 /*The genotypes behind blood_type().
2202  
2203 Its markers are a panel like hirisplex_genotypes()'s -- three of ABO and the
2204 sites of RHD at which somebody who has the gene almost always differs from
2205 the reference -- so hps_record() reads them, and this adds the two things a
2206 panel of markers cannot say.
2207  
2208 One is a record of a deletion that covers the whole RHD gene, which is how
2209 1000 Genomes' phase 3 writes the usual cause of RhD negative (1:25592642,
2210 ALT <CN0>, END=25661222): its genotype is the answer, where the SNVs can only
2211 say whether a sample has the gene at all. A deletion is an ALT of <CN0>,
2212 <DEL> or <DEL:...>, the VCF specification's symbolic alleles, and how far it
2213 runs is INFO's END, or else POS plus SVLEN (VCFv4.2, "INFO keys used for
2214 structural variants").
2215  
2216 The other is what the file could have shown. A VCF of one genome usually
2217 lists only the sites where its sample carries an ALT allele, so perl takes a
2218 marker with no record as homozygous REF; that is wrong for a file that could
2219 not have held the record, so each chromosome a marker is on is noted when any
2220 record of it is read, and again when a record of it has an allele longer than
2221 one base, without which a file cannot have held ABO's insertion.
2222  
2223 What is kept is hps_reader's byte a sample a marker and one more byte a
2224 sample for the deletion.*/
2225  
2226 typedef struct {
2227 hps_reader h;// first, so that the vcf_reader * bt_header() and bt_record() are given is this, and is what hps_record() takes
2228 unsigned short int chrom;// the gene's chromosome, in vcf_chrom()'s numbering
2229 UV start, end;// the gene, 1-based and inclusive, which a deletion has to cover
2230 uint32_t chroms;// bit c set for each chromosome c that a marker or the gene is on; a record of any other is read no further than CHROM
2231 uint32_t seen;// bit c set once a record of chromosome c has been read
2232 uint32_t longer;// bit c set once a record of chromosome c had a REF or an ALT longer than one base
2233 unsigned char *deleted;// one per sample: how many copies of a deletion covering the gene it has, 0 to 2, or HPS_ABSENT or HPS_NO_CALL
2234 } bt_reader;
2235  
2236 34 static void bt_header(pTHX_ vcf_reader *r) {
2237 34 bt_reader *t = (bt_reader*)r;
2238 34 hps_header(aTHX_ r);
2239 34 Newx(t->deleted, r->n, unsigned char);
2240 34 SAVEFREEPV(t->deleted);// freed at the caller's LEAVE, croak or not; see vcf_read()'s block
2241 34 memset(t->deleted, HPS_ABSENT, r->n);
2242 34 }
2243  
2244 /*Whether any allele of the ALT field p..e is longer than one base. A symbolic
2245 allele ("<DEL>", "<NON_REF>") is a name, not bases, and is not one.*/
2246 169 static bool bt_longer(const char *p, const char *e) {
2247 177 ▶ for (const char *q = p; q < e;) {
Branch: 1 branch
BranchTrueFalseTotal
for (const char *q = p; q < e;) { 177 0 177
2248 177 const char *c = (const char*)memchr(q, ',', (size_t)(e - q));
2249 177 ▶ const char *ce = c ? c : e;
Branch: 1 branch
BranchTrueFalseTotal
const char *ce = c ? c : e; 8 169 177
2250 177 ▶ if (ce - q > 1 && *q != '<') return TRUE;
Branch: 2 branches
BranchTrueFalseTotal
if (ce - q > 1 && *q != '<') return TRUE; 28 149 177
if (ce - q > 1 && *q != '<') return TRUE; 16 12 28
2251 161 ▶ if (!c) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!c) break; 153 8 161
2252 8 q = ce + 1;
2253 }
2254 153 return FALSE;
2255 }
2256  
2257 /*Where a deletion is among the alleles of the ALT field p..e: 1 for the first
2258 ALT, 2 for the second and so on, or -1 when none of them is one.*/
2259 132 static short int bt_deletion(const char *p, const char *e) {
2260 132 short int i = 1;
2261 132 ▶ for (const char *q = p; q < e; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (const char *q = p; q < e; i++) { 132 0 132
2262 132 const char *c = (const char*)memchr(q, ',', (size_t)(e - q));
2263 132 ▶ const char *ce = c ? c : e;
Branch: 1 branch
BranchTrueFalseTotal
const char *ce = c ? c : e; 1 131 132
2264 132 const size_t n = (size_t)(ce - q);
2265 132 ▶ if ((n == 5 && (memcmp(q, "<CN0>", 5) == 0 || memcmp(q, "<DEL>", 5) == 0)) || (n > 5 && memcmp(q, "<DEL:", 5) == 0)) return i;
Branch: 5 branches
BranchTrueFalseTotal
if ((n == 5 && (memcmp(q, "<CN0>", 5) == 0 || memcmp(q, "<DEL>", 5) == 0)) || (n > 5 && memcmp(q, "<DEL:", 5) == 0)) return i; 10 122 132
if ((n == 5 && (memcmp(q, "<CN0>", 5) == 0 || memcmp(q, "<DEL>", 5) == 0)) || (n > 5 && memcmp(q, "<DEL:", 5) == 0)) return i; 8 2 10
if ((n == 5 && (memcmp(q, "<CN0>", 5) == 0 || memcmp(q, "<DEL>", 5) == 0)) || (n > 5 && memcmp(q, "<DEL:", 5) == 0)) return i; 1 7 8
if ((n == 5 && (memcmp(q, "<CN0>", 5) == 0 || memcmp(q, "<DEL>", 5) == 0)) || (n > 5 && memcmp(q, "<DEL:", 5) == 0)) return i; 1 122 123
if ((n == 5 && (memcmp(q, "<CN0>", 5) == 0 || memcmp(q, "<DEL>", 5) == 0)) || (n > 5 && memcmp(q, "<DEL:", 5) == 0)) return i; 1 0 1
2266 122 ▶ if (!c || i == 127) break;// a short int holds no more, and no record has so many ALTs
Branch: 2 branches
BranchTrueFalseTotal
if (!c || i == 127) break;// a short int holds no more, and no record has so many ALTs 0 122 122
if (!c || i == 127) break;// a short int holds no more, and no record has so many ALTs 0 0 0
2267 0 q = ce + 1;
2268 }
2269 122 return -1;
2270 }
2271  
2272 /*The whole number that key, which ends in its "=", has in the INFO field
2273 p..e, in *v, or FALSE when INFO lacks the key or its value is not one. A "-"
2274 before the number is passed over, since SVLEN is negative for a deletion, and
2275 the number ends at a comma, since SVLEN has a value for each ALT.*/
2276 13 static bool bt_info(const char *p, const char *e, const char *key, UV *v) {
2277 13 const size_t kl = strlen(key);
2278 16 ▶ for (const char *q = p; q < e;) {
Branch: 1 branch
BranchTrueFalseTotal
for (const char *q = p; q < e;) { 16 0 16
2279 16 const char *semi = (const char*)memchr(q, ';', (size_t)(e - q));
2280 16 ▶ const char *qe = semi ? semi : e;
Branch: 1 branch
BranchTrueFalseTotal
const char *qe = semi ? semi : e; 4 12 16
2281 16 ▶ if ((size_t)(qe - q) > kl && memcmp(q, key, kl) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if ((size_t)(qe - q) > kl && memcmp(q, key, kl) == 0) { 16 0 16
if ((size_t)(qe - q) > kl && memcmp(q, key, kl) == 0) { 9 7 16
2282 9 const char *s = q + kl;
2283 9 ▶ if (s < qe && *s == '-') s++;
Branch: 2 branches
BranchTrueFalseTotal
if (s < qe && *s == '-') s++; 9 0 9
if (s < qe && *s == '-') s++; 2 7 9
2284 9 ▶ if (s == qe || *s < '0' || *s > '9') return FALSE;
Branch: 3 branches
BranchTrueFalseTotal
if (s == qe || *s < '0' || *s > '9') return FALSE; 9 0 9
if (s == qe || *s < '0' || *s > '9') return FALSE; 9 0 9
if (s == qe || *s < '0' || *s > '9') return FALSE; 0 9 9
2285 9 UV n = 0;
2286 74 ▶ for (; s < qe && *s != ','; s++) {
Branch: 2 branches
BranchTrueFalseTotal
for (; s < qe && *s != ','; s++) { 65 9 74
for (; s < qe && *s != ','; s++) { 65 0 65
2287 65 ▶ if (*s < '0' || *s > '9' || n > (UV_MAX - 9) / 10) return FALSE;
Branch: 3 branches
BranchTrueFalseTotal
if (*s < '0' || *s > '9' || n > (UV_MAX - 9) / 10) return FALSE; 65 0 65
if (*s < '0' || *s > '9' || n > (UV_MAX - 9) / 10) return FALSE; 65 0 65
if (*s < '0' || *s > '9' || n > (UV_MAX - 9) / 10) return FALSE; 0 65 65
2288 65 n = n * 10 + (UV)(*s - '0');
2289 }
2290 9 *v = n;
2291 9 return TRUE;
2292 }
2293 7 ▶ if (!semi) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!semi) break; 4 3 7
2294 3 q = qe + 1;
2295 }
2296 4 return FALSE;
2297 }
2298  
2299 174 static void bt_record(pTHX_ vcf_reader *r, const char *p, const char *e) {
2300 174 bt_reader *t = (bt_reader*)r;
2301 174 const char *f = vcf_field_end(p, e);
2302 174 const unsigned short int chrom = vcf_chrom(p, f);
2303 341 ▶ if (chrom == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (chrom == 0) return; 0 174 174
2304 174 const uint32_t bit = (uint32_t)1 << chrom;// chrom is 24 at most
2305 174 ▶ if (!(t->chroms & bit)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!(t->chroms & bit)) return; 3 171 174
2306 171 t->seen |= bit;
2307 const char *col[9];
2308 171 const char *format_end = vcf_columns(aTHX_ r, p, f, e, col);
2309 170 const char *alt = col[4], *alt_end = col[5] - 1;
2310 170 ▶ if (col[4] - 1 - col[3] > 1 || bt_longer(alt, alt_end)) t->longer |= bit;
Branch: 2 branches
BranchTrueFalseTotal
if (col[4] - 1 - col[3] > 1 || bt_longer(alt, alt_end)) t->longer |= bit; 169 1 170
if (col[4] - 1 - col[3] > 1 || bt_longer(alt, alt_end)) t->longer |= bit; 16 153 169
2311 170 ▶ if (t->h.chroms & bit) hps_record(aTHX_ r, p, e);
Branch: 1 branch
BranchTrueFalseTotal
if (t->h.chroms & bit) hps_record(aTHX_ r, p, e); 170 0 170
2312 170 ▶ if (chrom != t->chrom) return;
Branch: 1 branch
BranchTrueFalseTotal
if (chrom != t->chrom) return; 38 132 170
2313 132 const short int idx = bt_deletion(alt, alt_end);
2314 132 ▶ if (idx < 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (idx < 0) return; 122 10 132
2315 10 const UV pos = vcf_pos(aTHX_ r, col[1], col[2] - 1);
2316 10 const char *info = col[7], *info_end = col[8] - 1;
2317 10 UV end = 0, len = 0;
2318 10 ▶ if (!bt_info(info, info_end, "END=", &end) && bt_info(info, info_end, "SVLEN=", &len)) end = pos + len;
Branch: 2 branches
BranchTrueFalseTotal
if (!bt_info(info, info_end, "END=", &end) && bt_info(info, info_end, "SVLEN=", &len)) end = pos + len; 3 7 10
if (!bt_info(info, info_end, "END=", &end) && bt_info(info, info_end, "SVLEN=", &len)) end = pos + len; 2 1 3
2319 10 ▶ if (pos > t->start || end < t->end) return;// some other deletion, which leaves part of the gene
Branch: 2 branches
BranchTrueFalseTotal
if (pos > t->start || end < t->end) return;// some other deletion, which leaves part of the gene 9 1 10
if (pos > t->start || end < t->end) return;// some other deletion, which leaves part of the gene 3 6 9
2320 size_t gt, dp;
2321 6 vcf_format(col[8], format_end, &gt, &dp);
2322 6 p = format_end + 1;
2323 16 ▶ for (size_t i = 0; i < r->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < r->n; i++) { 10 6 16
2324 10 const char *se = vcf_sample(aTHX_ r, p, e, i);
2325 // the first record that calls a sample is kept, should a file hold two
2326 10 ▶ if (t->deleted[i] > 2) t->deleted[i] = hps_dose(r, p, se, gt, dp, idx);
Branch: 1 branch
BranchTrueFalseTotal
if (t->deleted[i] > 2) t->deleted[i] = hps_dose(r, p, se, gt, dp, idx); 10 0 10
2327 10 p = se + 1;
2328 }
2329 6 vcf_samples_end(aTHX_ r, p, e);
2330 }
2331  
2332 /*blood_type()'s panel for every sample of the VCF name, which next returns a
2333 block of at a time. panel and markers are hps_panel()'s; chrom, start and end
2334 are the gene a deletion has to cover. Returns, as hps_dosage_vcf() does,
2335 sample => an array of one value for each marker, and sets *names and *seen as
2336 it does. *deleted is one value for each sample, in file order: how many copies
2337 of a deletion covering the gene it has, or undef where the file has no such
2338 record or the sample no call of it. flags[0] has bit c set for each
2339 chromosome c of the panel that the file has a record of, and flags[1] for each
2340 that it has an allele longer than one base on.*/
2341 37 static HV *bt_tally_vcf(pTHX_ SV *next, const char *name, UV min_depth, AV *panel, size_t markers, UV chrom, UV start, UV end, AV **names, AV **seen, AV **deleted, UV *flags) {
2342 37 ▶ if (chrom < 1 || chrom > 24 || start < 1 || start > end)
Branch: 4 branches
BranchTrueFalseTotal
if (chrom < 1 || chrom > 24 || start < 1 || start > end) 37 0 37
if (chrom < 1 || chrom > 24 || start < 1 || start > end) 36 1 37
if (chrom < 1 || chrom > 24 || start < 1 || start > end) 36 0 36
if (chrom < 1 || chrom > 24 || start < 1 || start > end) 1 35 36
2343 2 croak("%s: the gene is chromosome %" UVuf ", %" UVuf " to %" UVuf ", which isn't a stretch of a chromosome", __func__, chrom, start, end);
2344 bt_reader t;
2345 35 Zero(&t, 1, bt_reader);
2346 35 t.h.r.name = name;
2347 35 t.h.r.min_depth = min_depth;
2348 35 t.h.r.on_header = bt_header;
2349 35 t.h.r.on_record = bt_record;
2350 35 t.chrom = (unsigned short int)chrom;
2351 35 t.start = start;
2352 35 t.end = end;
2353 35 hps_panel(aTHX_ &t.h, panel, markers);
2354 35 t.chroms = t.h.chroms | ((uint32_t)1 << t.chrom);
2355 35 vcf_read(aTHX_ next, &t.h.r);
2356 33 HV *out = t.h.r.samples;
2357 33 AV *lost = newAV();
2358 33 av_extend(lost, (SSize_t)t.h.r.n - 1);
2359 177 ▶ for (size_t i = 0; i < t.h.r.n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < t.h.r.n; i++) { 144 33 177
2360 144 SV **sample = av_fetch(t.h.r.names, (SSize_t)i, 0);
2361 144 ▶ if (!sample) croak("%s: sample %" UVuf " of %s has lost its name", __func__, (UV)i, name);// cannot happen: every sample read was pushed
Branch: 1 branch
BranchTrueFalseTotal
if (!sample) croak("%s: sample %" UVuf " of %s has lost its name", __func__, (UV)i, name);// cannot happen: every sample read was pushed 0 144 144
2362 144 AV *row = newAV();
2363 144 av_extend(row, (SSize_t)t.h.sites - 1);
2364 2672 ▶ for (size_t k = 0; k < t.h.sites; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t k = 0; k < t.h.sites; k++) { 2528 144 2672
2365 2528 const unsigned char d = t.h.dose[i * t.h.sites + k];
2366 2528 ▶ av_push(row, d <= 2 ? newSVuv(d) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(row, d <= 2 ? newSVuv(d) : newSV(0)); 1836 692 2528
2367 }
2368 144 (void)hv_store_ent(out, *sample, newRV_noinc((SV*)row), 0);// in place of the column vcf_header() stored
2369 144 ▶ av_push(lost, t.deleted[i] <= 2 ? newSVuv(t.deleted[i]) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(lost, t.deleted[i] <= 2 ? newSVuv(t.deleted[i]) : newSV(0)); 9 135 144
2370 }
2371 33 AV *was = newAV();
2372 33 av_extend(was, (SSize_t)t.h.sites - 1);
2373 595 ▶ for (size_t k = 0; k < t.h.sites; k++) av_push(was, newSVuv(t.h.seen[k] ? 1 : 0));
Branch: 1 branch
BranchTrueFalseTotal
for (size_t k = 0; k < t.h.sites; k++) av_push(was, newSVuv(t.h.seen[k] ? 1 : 0)); 562 33 595
2374 33 *names = t.h.r.names;
2375 33 *seen = was;
2376 33 *deleted = lost;
2377 33 flags[0] = (UV)t.seen;
2378 33 flags[1] = (UV)t.longer;
2379 33 return out;
2380 }
2381  
2382 /*---- translation and k-mers: translate(), translate_six_frames(), find_orfs()
2383 and kmer_count().
2384  
2385 A genetic code arrives as the 64 letters of one line of
2386 share/genetic_codes.tsv, which is NCBI's ncbieaa: the amino acid of each codon
2387 in the order TTT, TTC, TTA, TTG, TCT .. GGG, with '*' for a stop. The rules for
2388 a codon with an ambiguous base are Biopython 1.87's (Bio/Seq.py,
2389 _translate_str(), and AmbiguousForwardTable in Bio/Data/CodonTable.py), which
2390 t/seq.t checks against that library's own tests.*/
2391  
2392 /*The bases that the IUPAC nucleotide letter c stands for, as a set of bits in
2393 the codes' own base order: 1 = T or U, 2 = C, 4 = A, 8 = G; 0 when c is not a
2394 nucleotide letter. The letters are those of NC-IUB's "Nomenclature for
2395 incompletely specified bases in nucleic acid sequences" (1984), as Biopython
2396 1.87 lists them in ambiguous_dna_values of Bio/Data/IUPACData.py. That table
2397 also has X, kept there "for historical reasons although it is not an IUPAC
2398 nucleotide"; it is left out here, so a codon with an X is refused.*/
2399 445437 static unsigned char nt_set(char c) {
2400 445437 switch (c) {
2401 119682 case 'T': case 't': case 'U': case 'u': return 1;
2402 102829 case 'C': case 'c': return 2;
2403 119750 case 'A': case 'a': return 4;
2404 103079 case 'G': case 'g': return 8;
2405 3 case 'Y': case 'y': return 1 | 2;// C or T
2406 5 case 'W': case 'w': return 1 | 4;// A or T
2407 3 case 'K': case 'k': return 1 | 8;// G or T
2408 8 case 'M': case 'm': return 2 | 4;// A or C
2409 3 case 'S': case 's': return 2 | 8;// C or G
2410 19 case 'R': case 'r': return 4 | 8;// A or G
2411 2 case 'H': case 'h': return 1 | 2 | 4;// not G
2412 0 case 'B': case 'b': return 1 | 2 | 8;// not A
2413 0 case 'D': case 'd': return 1 | 4 | 8;// not C
2414 0 case 'V': case 'v': return 2 | 4 | 8;// not T
2415 20 case 'N': case 'n': return 1 | 2 | 4 | 8;
2416 34 default: return 0;
2417 }
2418 }
2419  
2420 /*Whether the base set s holds exactly one base.*/
2421 #define NT_ONE(s) (((s) & ((s) - 1)) == 0)
2422 /*The place in T, C, A, G order of the one base in the set s: 1, 2, 4, 8 give
2423 0, 1, 2, 3.*/
2424 #define NT_INDEX(s) (((s) >> 1) - ((s) >> 3))
2425 /*The bit that stands for the letter c of a code in codon_letter()'s set: one
2426 for each letter from 'A' on, and bit 63 for a stop. A 64-bit set rather than a
2427 32-bit one, so that it also holds on EBCDIC, where 'Z' - 'A' is 40.*/
2428 #define AA_BIT(c) (UINT64_C(1) << ((c) == '*' ? 63 : (c) - 'A'))
2429  
2430 /*The letter that a codon is translated to under code, where s1, s2 and s3 are
2431 nt_set() of its three letters, none of them 0: '*' for a stop.
2432  
2433 A codon of three plain bases is looked up. One with an ambiguous base stands
2434 for several codons, and is given what they agree on: their amino acid when they
2435 have one between them, '*' when every one is a stop, B for D and N together, Z
2436 for E and Q, J for I and L, and X for anything else, a mix of stops and amino
2437 acids included. Those are Biopython's rules: B, Z and J are the only letters of
2438 its extended_protein_values that stand for two amino acids, and X is its
2439 pos_stop.*/
2440 148461 static char codon_letter(const char *code, unsigned char s1, unsigned char s2, unsigned char s3) {
2441 148461 ▶ if (NT_ONE(s1) && NT_ONE(s2) && NT_ONE(s3)) return code[16 * NT_INDEX(s1) + 4 * NT_INDEX(s2) + NT_INDEX(s3)];
Branch: 3 branches
BranchTrueFalseTotal
if (NT_ONE(s1) && NT_ONE(s2) && NT_ONE(s3)) return code[16 * NT_INDEX(s1) + 4 * NT_INDEX(s2) + NT_INDEX(s3)]; 148438 23 148461
if (NT_ONE(s1) && NT_ONE(s2) && NT_ONE(s3)) return code[16 * NT_INDEX(s1) + 4 * NT_INDEX(s2) + NT_INDEX(s3)]; 148432 6 148438
if (NT_ONE(s1) && NT_ONE(s2) && NT_ONE(s3)) return code[16 * NT_INDEX(s1) + 4 * NT_INDEX(s2) + NT_INDEX(s3)]; 148416 16 148432
2442 45 uint64_t seen = 0;// AA_BIT() of every letter the codon could be
2443 45 char last = 'X';// one of those letters, which is the answer when there is only one
2444 225 ▶ for (unsigned short int i = 0; i < 4; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int i = 0; i < 4; i++) { 180 45 225
2445 180 ▶ if (!(s1 >> i & 1)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(s1 >> i & 1)) continue; 101 79 180
2446 395 ▶ for (unsigned short int j = 0; j < 4; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int j = 0; j < 4; j++) { 316 79 395
2447 316 ▶ if (!(s2 >> j & 1)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(s2 >> j & 1)) continue; 171 145 316
2448 725 ▶ for (unsigned short int k = 0; k < 4; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int k = 0; k < 4; k++) { 580 145 725
2449 580 ▶ if (!(s3 >> k & 1)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(s3 >> k & 1)) continue; 159 421 580
2450 421 last = code[16 * i + 4 * j + k];
2451 421 ▶ seen |= AA_BIT(last);
Branch: 1 branch
BranchTrueFalseTotal
seen |= AA_BIT(last); 390 31 421
2452 }
2453 }
2454 }
2455 45 ▶ if (NT_ONE(seen)) return last;
Branch: 1 branch
BranchTrueFalseTotal
if (NT_ONE(seen)) return last; 14 31 45
2456 31 ▶ if (seen == (AA_BIT('D') | AA_BIT('N'))) return 'B';
Branch: 1 branch
BranchTrueFalseTotal
if (seen == (AA_BIT('D') | AA_BIT('N'))) return 'B'; 5 26 31
2457 26 ▶ if (seen == (AA_BIT('E') | AA_BIT('Q'))) return 'Z';
Branch: 1 branch
BranchTrueFalseTotal
if (seen == (AA_BIT('E') | AA_BIT('Q'))) return 'Z'; 3 23 26
2458 23 ▶ if (seen == (AA_BIT('I') | AA_BIT('L'))) return 'J';
Branch: 1 branch
BranchTrueFalseTotal
if (seen == (AA_BIT('I') | AA_BIT('L'))) return 'J'; 9 14 23
2459 14 return 'X';
2460 }
2461  
2462 /*seq translated under code, as a new mortal SV: one letter for each three of
2463 seq's, a stop written as stop_symbol, and whatever is left after the last whole
2464 codon dropped. With to_stop, the translation ends before the first stop. With
2465 gap other than NULL, a codon of three *gap is written as *gap.
2466  
2467 A codon with any other letter that is not a nucleotide's dies, and names the
2468 codon. The SV is mortal so that dying then does not leak it.*/
2469 260 static SV *translate_codons(pTHX_ SV *seq, SV *code_sv, char stop_symbol, bool to_stop, const char *gap) {
2470 STRLEN code_len, len;
2471 260 const char *code = SvPV_const(code_sv, code_len);// not restrict: perl's buffer
2472 260 ▶ if (code_len != 64) croak("%s: a genetic code is 64 letters, not %" UVuf, __func__, (UV)code_len);
Branch: 1 branch
BranchTrueFalseTotal
if (code_len != 64) croak("%s: a genetic code is 64 letters, not %" UVuf, __func__, (UV)code_len); 0 260 260
2473 16900 ▶ for (unsigned short int i = 0; i < 64; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int i = 0; i < 64; i++) { 16640 260 16900
2474 16640 ▶ if (code[i] != '*' && !isUPPER(code[i])) croak("%s: letter %" UVuf " of the genetic code \"%s\" is neither a capital letter nor *", __func__, (UV)i + 1, code);
Branch: 2 branches
BranchTrueFalseTotal
if (code[i] != '*' && !isUPPER(code[i])) croak("%s: letter %" UVuf " of the genetic code \"%s\" is neither a capital letter nor *", __func__, (UV)i + 1, code); 15969 671 16640
if (code[i] != '*' && !isUPPER(code[i])) croak("%s: letter %" UVuf " of the genetic code \"%s\" is neither a capital letter nor *", __func__, (UV)i + 1, code); 0 15969 15969
2475 }
2476 260 const char *p = SvPV_const(seq, len);// not restrict: perl's buffer
2477 260 const size_t codons = len / 3;
2478 260 ▶ SV *out = sv_2mortal(newSV(codons ? codons : 1));
Branch: 1 branch
BranchTrueFalseTotal
SV *out = sv_2mortal(newSV(codons ? codons : 1)); 249 11 260
2479 260 SvPOK_only(out);
2480 260 char *o = SvPVX(out);
2481 260 size_t n = 0;// letters written, which is read after the loop
2482 148718 ▶ for (size_t i = 0; i < codons; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < codons; i++) { 148479 239 148718
2483 148479 const char *c = p + 3 * i;
2484 148479 const unsigned char s1 = nt_set(c[0]), s2 = nt_set(c[1]), s3 = nt_set(c[2]);
2485 148479 ▶ if (!s1 || !s2 || !s3) {
Branch: 3 branches
BranchTrueFalseTotal
if (!s1 || !s2 || !s3) { 148471 8 148479
if (!s1 || !s2 || !s3) { 148470 1 148471
if (!s1 || !s2 || !s3) { 9 148461 148470
2486 18 ▶ if (gap && c[0] == *gap && c[1] == *gap && c[2] == *gap) {
Branch: 4 branches
BranchTrueFalseTotal
if (gap && c[0] == *gap && c[1] == *gap && c[2] == *gap) { 7 11 18
if (gap && c[0] == *gap && c[1] == *gap && c[2] == *gap) { 5 2 7
if (gap && c[0] == *gap && c[1] == *gap && c[2] == *gap) { 5 0 5
if (gap && c[0] == *gap && c[1] == *gap && c[2] == *gap) { 5 0 5
2487 5 o[n++] = *gap;
2488 5 continue;
2489 }
2490 13 croak("%s: codon %" UVuf ", \"%.3s\", has a letter that isn't a nucleotide's", __func__, (UV)(i + 1), c);
2491 }
2492 148461 const char aa = codon_letter(code, s1, s2, s3);
2493 148461 ▶ if (aa != '*') {
Branch: 1 branch
BranchTrueFalseTotal
if (aa != '*') { 143787 4674 148461
2494 143787 o[n++] = aa;
2495 4674 ▶ } else if (to_stop) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (to_stop) { 8 4666 4674
2496 8 break;
2497 } else {
2498 4666 o[n++] = stop_symbol;
2499 }
2500 }
2501 247 o[n] = '\0';
2502 247 SvCUR_set(out, n);
2503 247 return out;
2504 }
2505  
2506 /*How many times each run of k bytes occurs in seq, as a new hash of run =>
2507 count: the run at every step-th byte, so step 1 counts every k-mer and step k
2508 those that do not overlap. A k of 0 or longer than seq gives an empty hash.
2509  
2510 The runs are bytes, so lib/Cn/Bioinf.pm counts a string that holds a character
2511 above 255 itself. A hash key's length is an I32, and a negative one means a
2512 UTF-8 key, so a k beyond I32_MAX dies; perl refuses it first.*/
2513 24 static HV *kmer_tally(pTHX_ SV *seq, UV k, UV step) {
2514 STRLEN len;
2515 24 const char *p = SvPV_const(seq, len);// not restrict: perl's buffer
2516 24 HV *h = (HV*)sv_2mortal((SV*)newHV());
2517 24 ▶ if (k > (UV)I32_MAX) croak("%s: k is %" UVuf ", and a hash key can be no longer than %" IVdf, __func__, k, (IV)I32_MAX);
Branch: 1 branch
BranchTrueFalseTotal
if (k > (UV)I32_MAX) croak("%s: k is %" UVuf ", and a hash key can be no longer than %" IVdf, __func__, k, (IV)I32_MAX); 0 24 24
2518 24 ▶ if (step == 0) croak("%s: a step of 0 would count the first k-mer for ever", __func__);// cannot happen: perl passes 1 or k
Branch: 1 branch
BranchTrueFalseTotal
if (step == 0) croak("%s: a step of 0 would count the first k-mer for ever", __func__);// cannot happen: perl passes 1 or k 0 24 24
2519 24 ▶ if (k == 0 || k > len) return h;
Branch: 2 branches
BranchTrueFalseTotal
if (k == 0 || k > len) return h; 24 0 24
if (k == 0 || k > len) return h; 8 16 24
2520 16 const size_t last = len - (size_t)k;// where the last k-mer starts
2521 9685 ▶ for (size_t i = 0; i <= last; i += (size_t)step) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i <= last; i += (size_t)step) { 9685 0 9685
2522 9685 SV **count = hv_fetch(h, p + i, (I32)k, 1);
2523 9685 ▶ if (!count) croak("%s: couldn't count the k-mer at %" UVuf, __func__, (UV)i);// cannot happen: an lvalue fetch from a plain hash
Branch: 1 branch
BranchTrueFalseTotal
if (!count) croak("%s: couldn't count the k-mer at %" UVuf, __func__, (UV)i);// cannot happen: an lvalue fetch from a plain hash 0 9685 9685
2524 9685 ▶ sv_setuv(*count, SvOK(*count) ? SvUV(*count) + 1 : 1);
Branch: 1 branch
BranchTrueFalseTotal
sv_setuv(*count, SvOK(*count) ? SvUV(*count) + 1 : 1); 9571 114 9685
2525 9685 ▶ if (step > last - i) break;// i + step would pass the end, and could wrap
Branch: 1 branch
BranchTrueFalseTotal
if (step > last - i) break;// i + step would pass the end, and could wrap 16 9669 9685
2526 }
2527 16 return h;
2528 }
2529  
2530 /*Width-correct libm for NV, behind admixture()'s fit.
2531  
2532 This is the macro scheme of ~/Scripts/stats/LikeR.xs, cut down to the two
2533 functions the fit calls, log() and sqrt(), where LikeR.xs defines thirty:
2534 copying the rest would only be unused code. C's log() and sqrt() take a double,
2535 so on a long-double or __float128 perl an NV would be computed at a double's
2536 precision; the macros paste on the suffix for the width NV is. Makefile.PL
2537 link-tests logl() and sqrtl() on a long-double perl and defines
2538 BIOINF_HAVE_LONG_DOUBLE_MATH when both resolve, and the double functions are
2539 used otherwise. A quadmath perl's $Config{perllibs} already carries
2540 -lquadmath, and perl.h has already included <quadmath.h>.*/
2541 #if defined(USE_QUADMATH)
2542 # define BIOINF_NVFN(base) base ## q
2543 #elif defined(USE_LONG_DOUBLE) && defined(BIOINF_HAVE_LONG_DOUBLE_MATH)
2544 # define BIOINF_NVFN(base) base ## l
2545 #else
2546 # define BIOINF_NVFN(base) base
2547 #endif
2548 #define nv_log(x) BIOINF_NVFN(log)(x)
2549 #define nv_sqrt(x) BIOINF_NVFN(sqrt)(x)
2550  
2551 /*Admixture proportions, for admixture() (since 2026-11-17).
2552  
2553 The model is ADMIXTURE's (Alexander, Novembre and Lange 2009, "Fast
2554 model-based estimation of ancestry in unrelated individuals", Genome Research
2555 19:1655-1664): sample i descends from K ancestral populations in the
2556 fractions q[i][0..K-1], which sum to 1, and population l carries variant j's
2557 ALT allele at the frequency p[j][l]. Sample i's ALT count g at variant j is
2558 then binomial, of 2 draws with probability f = sum over l of q[i][l] p[j][l],
2559 and the log-likelihood is the sum over the called genotypes of
2560 g log f + (2 - g) log(1 - f), which leaves out the binomial coefficient, as
2561 ADMIXTURE's printed log-likelihood does.
2562  
2563 It is maximized by the EM algorithm of Tang, Peng, Wang and Risch (2005,
2564 "Estimation of individual admixture: analytical and study design
2565 considerations", Genetic Epidemiology 28:289-301, the method of their program
2566 frappe): with a = g q[i][l] p[j][l] / f and b = (2 - g) q[i][l] (1 - p[j][l]) /
2567 (1 - f), the new p[j][l] is the sum over i of a divided by the sum of a + b, and
2568 the new q[i][l] the sum over j of a + b divided by twice sample i's called
2569 genotypes. The steps are accelerated by SQUAREM (Varadhan and Roland 2008,
2570 "Simple and globally convergent methods for accelerating the convergence of any
2571 EM algorithm", Scandinavian Journal of Statistics 35:335-353), their scheme S3
2572 with the steplength held at -1 or below, a stabilizing EM step after each
2573 extrapolation, and the second plain EM step kept instead whenever the
2574 extrapolation lowers the likelihood, so that no iteration does. ADMIXTURE
2575 itself climbs the same likelihood by block relaxation and quasi-Newton
2576 acceleration. The likelihood has local maxima, so lib/Cn/Bioinf.pm fits from
2577 several random starts and keeps the best.*/
2578 #define ADMIX_MISSING 3 // a genotype byte with no call; 0 to 2 are its ALT count
2579 /*The least q and p, and 1 less it the most: ADMIXTURE 1.3.0's bounds, which
2580 its .Q files show as 0.000010 for a fraction it drove to the bound. A
2581 frequency of exactly 0 or 1 would make log(0) of a genotype that disagrees.*/
2582 #define ADMIX_BOUND ((NV)1e-5)
2583  
2584 typedef struct {
2585 vcf_reader r;// first, so that the vcf_reader * that the callbacks are given is this
2586 SV *g;// the genotype bytes, r.n to a variant, in the VCF's order
2587 AV *variants;// each variant kept, as "CHROM\tPOS\tID\tREF\tALT"
2588 UV *called;// each sample's called genotypes
2589 } admix_reader;
2590  
2591 13 static void admix_header(pTHX_ vcf_reader *r) {
2592 13 admix_reader *t = (admix_reader*)r;
2593 13 ▶ Newxz(t->called, r->n, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(t->called, r->n, UV); 0 13 13
2594 13 SAVEFREEPV(t->called);// at the caller's LEAVE, croak or not; see vcf_read()'s block
2595 13 }
2596  
2597 /*The record p..e, kept when it is on an autosome and biallelic: one ALT,
2598 which is not "." (no ALT) or "*" (a deletion's overlap), as PLINK 2's
2599 --max-alleles 2 --min-alleles 2 keeps them, which is what made t/admixture.t's
2600 reference input. A call of one allele, or of none, is missing.*/
2601 2974 static void admix_record(pTHX_ vcf_reader *r, const char *p, const char *e) {
2602 2974 admix_reader *t = (admix_reader*)r;
2603 2974 const char *f = vcf_field_end(p, e);
2604 2974 const unsigned short int chrom = vcf_chrom(p, f);
2605 2984 ▶ if (chrom == 0 || chrom > 22) return;
Branch: 2 branches
BranchTrueFalseTotal
if (chrom == 0 || chrom > 22) return; 2974 0 2974
if (chrom == 0 || chrom > 22) return; 280 2694 2974
2606 const char *col[9];
2607 2694 const char *format_end = vcf_columns(aTHX_ r, p, f, e, col);
2608 2694 const char *alt = col[4], *alt_end = col[5] - 1;
2609 2694 ▶ if (alt == alt_end || memchr(alt, ',', (size_t)(alt_end - alt)) || (alt_end - alt == 1 && (*alt == '.' || *alt == '*'))) return;
Branch: 5 branches
BranchTrueFalseTotal
if (alt == alt_end || memchr(alt, ',', (size_t)(alt_end - alt)) || (alt_end - alt == 1 && (*alt == '.' || *alt == '*'))) return; 2694 0 2694
if (alt == alt_end || memchr(alt, ',', (size_t)(alt_end - alt)) || (alt_end - alt == 1 && (*alt == '.' || *alt == '*'))) return; 2684 10 2694
if (alt == alt_end || memchr(alt, ',', (size_t)(alt_end - alt)) || (alt_end - alt == 1 && (*alt == '.' || *alt == '*'))) return; 2684 0 2684
if (alt == alt_end || memchr(alt, ',', (size_t)(alt_end - alt)) || (alt_end - alt == 1 && (*alt == '.' || *alt == '*'))) return; 2684 0 2684
if (alt == alt_end || memchr(alt, ',', (size_t)(alt_end - alt)) || (alt_end - alt == 1 && (*alt == '.' || *alt == '*'))) return; 0 2684 2684
2610 size_t gt, dp;
2611 2684 vcf_format(col[8], format_end, &gt, &dp);
2612 2684 ▶ if (gt == VCF_ABSENT) return;
Branch: 1 branch
BranchTrueFalseTotal
if (gt == VCF_ABSENT) return; 0 2684 2684
2613 2684 const STRLEN at = SvCUR(t->g);
2614 2684 ▶ if ((STRLEN)r->n > ((STRLEN)-1 - at) / 2 - 1) croak("%s: %s has too many genotypes to hold, at line %" UVuf, __func__, r->name, r->line);
Branch: 1 branch
BranchTrueFalseTotal
if ((STRLEN)r->n > ((STRLEN)-1 - at) / 2 - 1) croak("%s: %s has too many genotypes to hold, at line %" UVuf, __func__, r->name, r->line); 0 2684 2684
2615 // doubled when full, so that the bytes are copied O(log variants) times, not once a record
2616 2684 ▶ if (SvLEN(t->g) < at + r->n + 1) SvGROW(t->g, 2 * (at + r->n) + 1);
Branch: 3 branches
BranchTrueFalseTotal
if (SvLEN(t->g) < at + r->n + 1) SvGROW(t->g, 2 * (at + r->n) + 1); 79 2605 2684
if (SvLEN(t->g) < at + r->n + 1) SvGROW(t->g, 2 * (at + r->n) + 1); 79 0 79
if (SvLEN(t->g) < at + r->n + 1) SvGROW(t->g, 2 * (at + r->n) + 1); 79 0 79
2617 2684 unsigned char *row = (unsigned char*)SvPVX(t->g) + at;// not restrict: perl's buffer
2618 2684 p = format_end + 1;
2619 163496 ▶ for (size_t i = 0; i < r->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < r->n; i++) { 160812 2684 163496
2620 160812 const char *se = vcf_sample(aTHX_ r, p, e, i);
2621 160812 unsigned short int alleles = 0, alts = 0;
2622 160812 ▶ const bool call = vcf_call(r, p, se, gt, dp, &alleles, &alts) == VCF_CALL && alleles == 2;
Branch: 2 branches
BranchTrueFalseTotal
const bool call = vcf_call(r, p, se, gt, dp, &alleles, &alts) == VCF_CALL && alleles == 2; 160482 330 160812
const bool call = vcf_call(r, p, se, gt, dp, &alleles, &alts) == VCF_CALL && alleles == 2; 160472 10 160482
2623 160812 ▶ row[i] = call ? (unsigned char)alts : ADMIX_MISSING;
Branch: 1 branch
BranchTrueFalseTotal
row[i] = call ? (unsigned char)alts : ADMIX_MISSING; 160472 340 160812
2624 160812 ▶ if (call) t->called[i]++;
Branch: 1 branch
BranchTrueFalseTotal
if (call) t->called[i]++; 160472 340 160812
2625 160812 p = se + 1;
2626 }
2627 2684 vcf_samples_end(aTHX_ r, p, e);
2628 2684 SvCUR_set(t->g, at + r->n);
2629 2684 av_push(t->variants, newSVpvf("%.*s\t%.*s\t%.*s\t%.*s\t%.*s", (int)(col[1] - 1 - col[0]), col[0], (int)(col[2] - 1 - col[1]), col[1],
2630 (int)(col[3] - 1 - col[2]), col[2], (int)(col[4] - 1 - col[3]), col[3], (int)(alt_end - alt), alt));
2631 }
2632  
2633 typedef struct {
2634 const unsigned char *g;// m rows of n genotype bytes; perl's buffer, not written
2635 size_t n, m, k;// samples, variants, ancestral populations
2636 NV *twice;// each sample's called genotypes, twice: the alleles its q is a share of
2637 NV *num, *den;// k each, admix_em()'s sums for one variant
2638 } admix_fit;
2639  
2640 /*The parameters, q (n rows of k) and then p (m rows of k), held to the
2641 bounds: each q row clamped and made to sum to 1 again, each p clamped.*/
2642 5273 static void admix_bound(const admix_fit *a, NV *th) {
2643 5273 const size_t k = a->k;
2644 309740 ▶ for (size_t i = 0; i < a->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < a->n; i++) { 304467 5273 309740
2645 304467 NV *q = th + i * k;
2646 304467 NV sum = 0;
2647 1217241 ▶ for (size_t l = 0; l < k; l++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t l = 0; l < k; l++) { 912774 304467 1217241
2648 912774 ▶ if (!(q[l] >= ADMIX_BOUND)) q[l] = ADMIX_BOUND;// also NaN, which an extrapolation can make
Branch: 1 branch
BranchTrueFalseTotal
if (!(q[l] >= ADMIX_BOUND)) q[l] = ADMIX_BOUND;// also NaN, which an extrapolation can make 253429 659345 912774
2649 659345 ▶ else if (q[l] > 1 - ADMIX_BOUND) q[l] = 1 - ADMIX_BOUND;
Branch: 1 branch
BranchTrueFalseTotal
else if (q[l] > 1 - ADMIX_BOUND) q[l] = 1 - ADMIX_BOUND; 303 659042 659345
2650 912774 sum += q[l];
2651 }
2652 1217241 ▶ for (size_t l = 0; l < k; l++) q[l] /= sum;
Branch: 1 branch
BranchTrueFalseTotal
for (size_t l = 0; l < k; l++) q[l] /= sum; 912774 304467 1217241
2653 }
2654 5273 NV *p = th + a->n * k;
2655 4102129 ▶ for (size_t x = 0; x < a->m * k; x++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t x = 0; x < a->m * k; x++) { 4096856 5273 4102129
2656 4096856 ▶ if (!(p[x] >= ADMIX_BOUND)) p[x] = ADMIX_BOUND;
Branch: 1 branch
BranchTrueFalseTotal
if (!(p[x] >= ADMIX_BOUND)) p[x] = ADMIX_BOUND; 448915 3647941 4096856
2657 3647941 ▶ else if (p[x] > 1 - ADMIX_BOUND) p[x] = 1 - ADMIX_BOUND;
Branch: 1 branch
BranchTrueFalseTotal
else if (p[x] > 1 - ADMIX_BOUND) p[x] = 1 - ADMIX_BOUND; 172881 3475060 3647941
2658 }
2659 5273 }
2660  
2661 1458 static NV admix_loglik(const admix_fit *a, const NV *th) {
2662 1458 const size_t n = a->n, k = a->k;
2663 1458 const NV *q = th, *p = th + n * k;
2664 1458 NV ll = 0;
2665 380414 ▶ for (size_t j = 0; j < a->m; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t j = 0; j < a->m; j++) { 378956 1458 380414
2666 378956 const unsigned char *row = a->g + j * n;
2667 378956 const NV *pj = p + j * k;
2668 23110274 ▶ for (size_t i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < n; i++) { 22731318 378956 23110274
2669 22731318 const unsigned char c = row[i];
2670 22731318 ▶ if (c == ADMIX_MISSING) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (c == ADMIX_MISSING) continue; 14890 22716428 22731318
2671 22716428 const NV *qi = q + i * k;
2672 22716428 NV f = 0;
2673 90865394 ▶ for (size_t l = 0; l < k; l++) f += qi[l] * pj[l];
Branch: 1 branch
BranchTrueFalseTotal
for (size_t l = 0; l < k; l++) f += qi[l] * pj[l]; 68148966 22716428 90865394
2674 22716428 ▶ if (c) ll += (NV)c * nv_log(f);
Branch: 1 branch
BranchTrueFalseTotal
if (c) ll += (NV)c * nv_log(f); 12192554 10523874 22716428
2675 22716428 ▶ if (c < 2) ll += (NV)(2 - c) * nv_log(1 - f);
Branch: 1 branch
BranchTrueFalseTotal
if (c < 2) ll += (NV)(2 - c) * nv_log(1 - f); 17689713 5026715 22716428
2676 }
2677 }
2678 1458 return ll;
2679 }
2680  
2681 /*One EM step from th into out, both laid out as admix_bound() describes.*/
2682 3939 static void admix_em(const admix_fit *a, const NV *th, NV *out) {
2683 3939 const size_t n = a->n, k = a->k;
2684 3939 const NV *q = th, *p = th + n * k;
2685 3939 NV *q2 = out, *p2 = out + n * k;
2686 3939 ▶ Zero(q2, n * k, NV);
Branch: 1 branch
BranchTrueFalseTotal
Zero(q2, n * k, NV); 0 3939 3939
2687 1024221 ▶ for (size_t j = 0; j < a->m; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t j = 0; j < a->m; j++) { 1020282 3939 1024221
2688 1020282 const unsigned char *row = a->g + j * n;
2689 1020282 const NV *pj = p + j * k;
2690 1020282 ▶ Zero(a->num, k, NV);
Branch: 1 branch
BranchTrueFalseTotal
Zero(a->num, k, NV); 0 1020282 1020282
2691 1020282 ▶ Zero(a->den, k, NV);
Branch: 1 branch
BranchTrueFalseTotal
Zero(a->den, k, NV); 0 1020282 1020282
2692 62219418 ▶ for (size_t i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < n; i++) { 61199136 1020282 62219418
2693 61199136 const unsigned char c = row[i];
2694 61199136 ▶ if (c == ADMIX_MISSING) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (c == ADMIX_MISSING) continue; 41238 61157898 61199136
2695 61157898 const NV *qi = q + i * k;
2696 61157898 NV f = 0;
2697 244630656 ▶ for (size_t l = 0; l < k; l++) f += qi[l] * pj[l];
Branch: 1 branch
BranchTrueFalseTotal
for (size_t l = 0; l < k; l++) f += qi[l] * pj[l]; 183472758 61157898 244630656
2698 61157898 ▶ const NV x = c ? (NV)c / f : 0, y = c < 2 ? (NV)(2 - c) / (1 - f) : 0;
Branch: 2 branches
BranchTrueFalseTotal
const NV x = c ? (NV)c / f : 0, y = c < 2 ? (NV)(2 - c) / (1 - f) : 0; 32825130 28332768 61157898
const NV x = c ? (NV)c / f : 0, y = c < 2 ? (NV)(2 - c) / (1 - f) : 0; 47624703 13533195 61157898
2699 61157898 NV *q2i = q2 + i * k;
2700 244630656 ▶ for (size_t l = 0; l < k; l++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t l = 0; l < k; l++) { 183472758 61157898 244630656
2701 183472758 const NV alt = x * qi[l] * pj[l], ref = y * qi[l] * (1 - pj[l]);
2702 183472758 q2i[l] += alt + ref;
2703 183472758 a->num[l] += alt;
2704 183472758 a->den[l] += alt + ref;
2705 }
2706 }
2707 4080816 ▶ for (size_t l = 0; l < k; l++) p2[j * k + l] = a->den[l] > 0 ? a->num[l] / a->den[l] : pj[l];
Branch: 2 branches
BranchTrueFalseTotal
for (size_t l = 0; l < k; l++) p2[j * k + l] = a->den[l] > 0 ? a->num[l] / a->den[l] : pj[l]; 3060534 0 3060534
for (size_t l = 0; l < k; l++) p2[j * k + l] = a->den[l] > 0 ? a->num[l] / a->den[l] : pj[l]; 3060534 1020282 4080816
2708 }
2709 231387 ▶ for (size_t i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < n; i++) { 227448 3939 231387
2710 227448 NV *q2i = q2 + i * k;
2711 // a sample with no called genotype says nothing of its ancestry, and keeps an even share
2712 909324 ▶ for (size_t l = 0; l < k; l++) q2i[l] = a->twice[i] > 0 ? q2i[l] / a->twice[i] : (NV)1 / (NV)k;
Branch: 2 branches
BranchTrueFalseTotal
for (size_t l = 0; l < k; l++) q2i[l] = a->twice[i] > 0 ? q2i[l] / a->twice[i] : (NV)1 / (NV)k; 681678 198 681876
for (size_t l = 0; l < k; l++) q2i[l] = a->twice[i] > 0 ? q2i[l] / a->twice[i] : (NV)1 / (NV)k; 681876 227448 909324
2713 }
2714 3939 admix_bound(a, out);
2715 3939 }
2716  
2717 /*The next of the 64-bit numbers that *s seeds, by SplitMix64 (Steele, Lea
2718 and Flood 2014; the constants of Sebastiano Vigna's public-domain
2719 splitmix64.c, prng.di.unimi.it), which gives the same numbers on every
2720 platform, where rand() and perl's own do not.*/
2721 19750 static uint64_t admix_rand(uint64_t *s) {
2722 19750 uint64_t z = (*s += UINT64_C(0x9E3779B97F4A7C15));
2723 19750 z = (z ^ (z >> 30)) * UINT64_C(0xBF58476D1CE4E5B9);
2724 19750 z = (z ^ (z >> 27)) * UINT64_C(0x94D049BB133111EB);
2725 19750 return z ^ (z >> 31);
2726 }
2727  
2728 /*A random start from seed: each q row uniform numbers made to sum to 1, and
2729 each p uniform, then held to the bounds. The top 53 bits of each number are
2730 used, which a double holds exactly, so that the start is the same on a
2731 long-double perl.*/
2732 21 static void admix_start(const admix_fit *a, NV *th, uint64_t seed) {
2733 21 const NV unit = (NV)1 / (NV)UINT64_C(9007199254740992);// 2^-53
2734 19771 ▶ for (size_t x = 0; x < (a->n + a->m) * a->k; x++) th[x] = (NV)(admix_rand(&seed) >> 11) * unit;
Branch: 1 branch
BranchTrueFalseTotal
for (size_t x = 0; x < (a->n + a->m) * a->k; x++) th[x] = (NV)(admix_rand(&seed) >> 11) * unit; 19750 21 19771
2735 21 admix_bound(a, th);
2736 21 }
2737  
2738 /*Fits from the start in th, leaving the fit there; returns its
2739 log-likelihood, with the iterations in *iterations, and whether it converged
2740 (the log-likelihood rose by less than tol in the last) in *converged. Each
2741 iteration is a SQUAREM cycle of three EM steps.*/
2742 21 static NV admix_run(pTHX_ const admix_fit *a, NV *th, UV max_iterations, NV tol, UV *iterations, bool *converged) {
2743 21 const size_t len = (a->n + a->m) * a->k;
2744 NV *t1, *t2, *t3;
2745 21 ▶ Newx(t1, len, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(t1, len, NV); 0 21 21
2746 21 SAVEFREEPV(t1);
2747 21 ▶ Newx(t2, len, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(t2, len, NV); 0 21 21
2748 21 SAVEFREEPV(t2);
2749 21 ▶ Newx(t3, len, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(t3, len, NV); 0 21 21
2750 21 SAVEFREEPV(t3);
2751 21 NV ll = admix_loglik(a, th);
2752 21 *converged = FALSE;
2753 21 *iterations = 0;
2754 1326 ▶ while (*iterations < max_iterations) {
Branch: 1 branch
BranchTrueFalseTotal
while (*iterations < max_iterations) { 1313 13 1326
2755 1313 ++*iterations;
2756 1313 admix_em(a, th, t1);
2757 1313 admix_em(a, t1, t2);
2758 1313 NV sr = 0, sv = 0;
2759 1248783 ▶ for (size_t x = 0; x < len; x++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t x = 0; x < len; x++) { 1247470 1313 1248783
2760 1247470 const NV r = t1[x] - th[x], v = t2[x] - 2 * t1[x] + th[x];
2761 1247470 sr += r * r;
2762 1247470 sv += v * v;
2763 }
2764 NV next;
2765 1313 const NV *keep = t2;// the parameters this iteration ends at
2766 1313 ▶ if (sv > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (sv > 0) { 1313 0 1313
2767 1313 NV alpha = -nv_sqrt(sr / sv);
2768 1313 ▶ if (alpha > -1) alpha = -1;
Branch: 1 branch
BranchTrueFalseTotal
if (alpha > -1) alpha = -1; 1 1312 1313
2769 1248783 ▶ for (size_t x = 0; x < len; x++) t3[x] = th[x] - 2 * alpha * (t1[x] - th[x]) + alpha * alpha * (t2[x] - 2 * t1[x] + th[x]);
Branch: 1 branch
BranchTrueFalseTotal
for (size_t x = 0; x < len; x++) t3[x] = th[x] - 2 * alpha * (t1[x] - th[x]) + alpha * alpha * (t2[x] - 2 * t1[x] + th[x]); 1247470 1313 1248783
2770 1313 admix_bound(a, t3);
2771 1313 admix_em(a, t3, t1);// t1 is not needed again
2772 1313 next = admix_loglik(a, t1);
2773 1313 ▶ if (next >= ll) keep = t1;// not NaN, and no lower
Branch: 1 branch
BranchTrueFalseTotal
if (next >= ll) keep = t1;// not NaN, and no lower 1189 124 1313
2774 124 else next = admix_loglik(a, t2);
2775 } else {
2776 0 next = admix_loglik(a, t2);
2777 }
2778 1313 ▶ Copy(keep, th, len, NV);
Branch: 1 branch
BranchTrueFalseTotal
Copy(keep, th, len, NV); 0 1313 1313
2779 1313 const NV rise = next - ll;
2780 1313 ll = next;
2781 1313 ▶ if (rise < tol) {
Branch: 1 branch
BranchTrueFalseTotal
if (rise < tol) { 8 1305 1313
2782 8 *converged = TRUE;
2783 8 break;
2784 }
2785 }
2786 21 return ll;
2787 }
2788  
2789 MODULE = Cn::Bioinf PACKAGE = Cn::Bioinf
2790 PROTOTYPES: DISABLE
2791  
2792 SV *
2793 _read_fasta(fh, key, name, order = NULL)
2794 PerlIO *fh
2795 SV *key
2796 const char *name
2797 AV *order
2798 CODE:
2799 62 ▶ RETVAL = read_fasta(aTHX_ fh, SvOK(key) ? key : NULL, name, order);
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = read_fasta(aTHX_ fh, SvOK(key) ? key : NULL, name, order); 16 46 62
2800 OUTPUT:
2801 RETVAL
2802  
2803 void
2804 _write_fasta(fh, h, order, width)
2805 PerlIO *fh
2806 HV *h
2807 AV *order
2808 UV width
2809 CODE:
2810 24 write_fasta(aTHX_ fh, h, order, (STRLEN)width);
2811  
2812 void
2813 _fai_build(fh)
2814 PerlIO *fh
2815 PPCODE:
2816 fai_state s;
2817 21 Zero(&s, 1, fai_state);
2818 21 s.text = sv_2mortal(newSVpvs(""));
2819 21 s.seen = (HV*)sv_2mortal((SV*)newHV());
2820 21 s.dups = (AV*)sv_2mortal((SV*)newAV());
2821 21 s.def = sv_2mortal(newSVpvs(""));
2822 21 s.name = sv_2mortal(newSVpvs(""));
2823 char *restrict buf;
2824 21 Newx(buf, FASTA_BLOCK, char);
2825 21 SAVEFREEPV(buf);// freed at this call's LEAVE, croak or not
2826 21 fai_scan(aTHX_ fh, &s, buf);
2827 21 ▶ EXTEND(SP, 6);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 6); 0 21 21
2828 21 PUSHs(s.text);
2829 21 PUSHs(sv_2mortal(newRV_inc((SV*)s.dups)));
2830 21 ▶ PUSHs(s.error ? sv_2mortal(newSVpv(s.error, 0)) : &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(s.error ? sv_2mortal(newSVpv(s.error, 0)) : &PL_sv_undef); 12 9 21
2831 21 PUSHs(sv_2mortal(fai_number(aTHX_ s.line)));
2832 21 ▶ PUSHs(s.named ? s.name : &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(s.named ? s.name : &PL_sv_undef); 17 4 21
2833 21 ▶ PUSHs(s.error && strEQ(s.error, "read") ? sv_2mortal(newSVpv(Strerror(s.read_errno), 0)) : &PL_sv_undef);
Branch: 2 branches
BranchTrueFalseTotal
PUSHs(s.error && strEQ(s.error, "read") ? sv_2mortal(newSVpv(Strerror(s.read_errno), 0)) : &PL_sv_undef); 12 9 21
PUSHs(s.error && strEQ(s.error, "read") ? sv_2mortal(newSVpv(Strerror(s.read_errno), 0)) : &PL_sv_undef); 0 12 12
2834  
2835 void
2836 _sex_tally(next, name, min_depth)
2837 SV *next
2838 const char *name
2839 UV min_depth
2840 PPCODE:
2841 UV x_sites;
2842 AV *names;
2843 52 PUTBACK;
2844 52 HV *out = sex_tally_vcf(aTHX_ next, name, min_depth, &x_sites, &names);
2845 32 SPAGAIN;
2846 32 ▶ EXTEND(SP, 3);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 3); 0 32 32
2847 32 PUSHs(sv_2mortal(newRV_inc((SV*)out)));
2848 32 PUSHs(sv_2mortal(newSVuv(x_sites)));
2849 32 PUSHs(sv_2mortal(newRV_inc((SV*)names)));
2850  
2851 void
2852 _parent_one(next, name, min_depth, child, parent)
2853 SV *next
2854 const char *name
2855 UV min_depth
2856 SV *child
2857 SV *parent
2858 PPCODE:
2859 parent_reader t;
2860 60 Zero(&t, 1, parent_reader);
2861 60 t.r.name = name;
2862 60 t.r.min_depth = min_depth;
2863 60 t.r.on_header = parent_header_one;
2864 60 t.r.on_record = parent_record_one;
2865 60 t.want[0] = child;
2866 60 t.want[1] = parent;
2867 60 PUTBACK;
2868 60 vcf_read(aTHX_ next, &t.r);
2869 58 SPAGAIN;
2870 58 UV in = 0;// the sites where either carries the ALT, every one of them in both, since there is one file
2871 522 ▶ for (unsigned short int k = 1; k < 9; k++) in += t.t[k];
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int k = 1; k < 9; k++) in += t.t[k]; 464 58 522
2872 58 ▶ EXTEND(SP, 12);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 12); 0 58 58
2873 580 ▶ for (unsigned short int k = 0; k < 9; k++) PUSHs(sv_2mortal(newSVuv(t.t[k])));
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int k = 0; k < 9; k++) PUSHs(sv_2mortal(newSVuv(t.t[k]))); 522 58 580
2874 58 PUSHs(sv_2mortal(newSVuv(in)));
2875 58 PUSHs(sv_2mortal(newSVuv(0)));
2876 58 PUSHs(sv_2mortal(newSVuv(0)));
2877  
2878 void
2879 _parent_own(child_next, child_name, parent_next, parent_name, min_depth)
2880 SV *child_next
2881 const char *child_name
2882 SV *parent_next
2883 const char *parent_name
2884 UV min_depth
2885 PPCODE:
2886 29 PUTBACK;
2887 29 const parent_sites *a = parent_sites_vcf(aTHX_ child_next, child_name, min_depth);
2888 28 const parent_sites *b = parent_sites_vcf(aTHX_ parent_next, parent_name, min_depth);
2889 21 SPAGAIN;
2890 21 UV t[9] = { 0 }, in[3] = { 0 };// as parent_merge() fills them
2891 21 parent_merge(a, b, t, in);
2892 21 ▶ EXTEND(SP, 12);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 12); 0 21 21
2893 210 ▶ for (unsigned short int k = 0; k < 9; k++) PUSHs(sv_2mortal(newSVuv(t[k])));
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int k = 0; k < 9; k++) PUSHs(sv_2mortal(newSVuv(t[k]))); 189 21 210
2894 84 ▶ for (unsigned short int k = 0; k < 3; k++) PUSHs(sv_2mortal(newSVuv(in[k])));
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short int k = 0; k < 3; k++) PUSHs(sv_2mortal(newSVuv(in[k]))); 63 21 84
2895  
2896 void
2897 _relatedness_one(next, name, min_depth)
2898 SV *next
2899 const char *name
2900 UV min_depth
2901 PPCODE:
2902 rel_reader t;
2903 30 Zero(&t, 1, rel_reader);
2904 30 t.r.name = name;
2905 30 t.r.min_depth = min_depth;
2906 30 t.r.on_header = rel_header_one;
2907 30 t.r.on_record = rel_record_one;
2908 30 PUTBACK;
2909 30 vcf_read(aTHX_ next, &t.r);
2910 27 ▶ if (t.k) rel_flush(&t);
Branch: 1 branch
BranchTrueFalseTotal
if (t.k) rel_flush(&t); 27 0 27
2911 27 SPAGAIN;
2912 27 HV *sex = (HV*)sv_2mortal((SV*)newHV());
2913 27 sex_rows(aTHX_ sex, t.r.names, t.sex, t.r.n, name);
2914 27 ▶ EXTEND(SP, 3);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 3); 0 27 27
2915 27 PUSHs(sv_2mortal(newRV_inc((SV*)t.r.names)));
2916 27 PUSHs(sv_2mortal(rel_counts(aTHX_ t.t, t.r.n)));
2917 27 PUSHs(sv_2mortal(newRV_inc((SV*)sex)));
2918  
2919 void
2920 _relatedness_own(nexts, files, min_depth)
2921 AV *nexts
2922 AV *files
2923 UV min_depth
2924 PPCODE:
2925 28 const size_t n = (size_t)(av_len(nexts) + 1);
2926 28 ▶ if ((SSize_t)n != av_len(files) + 1) croak("_relatedness_own: %" UVuf " readers for %" UVuf " files", (UV)n, (UV)(av_len(files) + 1));// cannot happen: perl makes one for each; named literally, since __func__ in an XSUB is XS_Cn__Bioinf__relatedness_own
Branch: 1 branch
BranchTrueFalseTotal
if ((SSize_t)n != av_len(files) + 1) croak("_relatedness_own: %" UVuf " readers for %" UVuf " files", (UV)n, (UV)(av_len(files) + 1));// cannot happen: perl makes one for each; named literally, since __func__ in an XSUB is XS_Cn__Bioinf__relatedness_own 1 27 28
2927 parent_sites **s;// each file's sites, freed by parent_sites_read()'s destructor
2928 27 ▶ Newx(s, n, parent_sites*);
Branch: 1 branch
BranchTrueFalseTotal
Newx(s, n, parent_sites*); 0 27 27
2929 27 SAVEFREEPV(s);
2930 UV *count;// SEX_FIELDS counters a file
2931 27 ▶ Newxz(count, n * SEX_FIELDS, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(count, n * SEX_FIELDS, UV); 0 27 27
2932 27 SAVEFREEPV(count);
2933 27 HV *seen = (HV*)sv_2mortal((SV*)newHV());
2934 27 AV *names = (AV*)sv_2mortal((SV*)newAV());
2935 27 PUTBACK;
2936 93 ▶ for (size_t f = 0; f < n; f++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t f = 0; f < n; f++) { 75 18 93
2937 75 SV **next = av_fetch(nexts, (SSize_t)f, 0), **file = av_fetch(files, (SSize_t)f, 0);
2938 75 ▶ if (!next || !file) croak("_relatedness_own: file %" UVuf " has no reader", (UV)f);// cannot happen: perl fills both arrays
Branch: 2 branches
BranchTrueFalseTotal
if (!next || !file) croak("_relatedness_own: file %" UVuf " has no reader", (UV)f);// cannot happen: perl fills both arrays 75 0 75
if (!next || !file) croak("_relatedness_own: file %" UVuf " has no reader", (UV)f);// cannot happen: perl fills both arrays 1 74 75
2939 rel_own_reader t;
2940 74 Zero(&t, 1, rel_own_reader);
2941 74 t.p.r.name = SvPV_nolen(*file);
2942 74 t.p.r.min_depth = min_depth;
2943 74 t.p.r.on_header = rel_header_own;
2944 74 t.p.r.on_record = rel_record_own;
2945 74 t.sex = count + f * SEX_FIELDS;
2946 74 t.seen = seen;
2947 74 t.names = names;
2948 74 s[f] = parent_sites_read(aTHX_ &t.p, *next);
2949 }
2950 18 SPAGAIN;
2951 UV *t;// REL_T counters a pair
2952 18 ▶ Newxz(t, rel_pairs(aTHX_ n) * REL_T, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(t, rel_pairs(aTHX_ n) * REL_T, UV); 0 18 18
2953 18 SAVEFREEPV(t);
2954 18 rel_merge(aTHX_ (parent_sites *const *)s, n, t);
2955 18 HV *sex = (HV*)sv_2mortal((SV*)newHV());
2956 18 sex_rows(aTHX_ sex, names, count, n, "the VCFs");
2957 18 ▶ EXTEND(SP, 3);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 3); 0 18 18
2958 18 PUSHs(sv_2mortal(newRV_inc((SV*)names)));
2959 18 PUSHs(sv_2mortal(rel_counts(aTHX_ t, n)));
2960 18 PUSHs(sv_2mortal(newRV_inc((SV*)sex)));
2961  
2962 void
2963 _vcf_samples(next, name)
2964 SV *next
2965 const char *name
2966 PPCODE:
2967 vcf_reader r;
2968 63 Zero(&r, 1, vcf_reader);
2969 63 r.name = name;
2970 63 r.on_header = conc_stop;
2971 63 r.on_record = conc_skip;
2972 63 PUTBACK;
2973 63 vcf_read(aTHX_ next, &r);
2974 61 SPAGAIN;
2975 61 ▶ XPUSHs(sv_2mortal(newRV_inc((SV*)r.names)));
Branch: 1 branch
BranchTrueFalseTotal
XPUSHs(sv_2mortal(newRV_inc((SV*)r.names))); 0 61 61
2976  
2977 void
2978 _concordance(test_next, test_name, truth_next, truth_name, truth_names, min_depth, discordances)
2979 SV *test_next
2980 const char *test_name
2981 SV *truth_next
2982 const char *truth_name
2983 AV *truth_names
2984 UV min_depth
2985 bool discordances
2986 PPCODE:
2987 conc_store *s;
2988 61 Newxz(s, 1, conc_store);
2989 61 SAVEDESTRUCTOR_X(conc_store_free, s);// at this call's LEAVE, croak or not
2990 61 s->truth_n = (size_t)(av_len(truth_names) + 1);
2991 conc_reader test;
2992 61 Zero(&test, 1, conc_reader);
2993 61 test.r.name = test_name;
2994 61 test.r.min_depth = min_depth;
2995 61 test.r.on_header = conc_header_test;
2996 61 test.r.on_record = conc_record_test;
2997 61 test.s = s;
2998 61 test.truth_names = truth_names;
2999 61 PUTBACK;
3000 61 vcf_read(aTHX_ test_next, &test.r);
3001 conc_reader truth;
3002 51 Zero(&truth, 1, conc_reader);
3003 51 truth.r.name = truth_name;
3004 51 truth.r.min_depth = min_depth;
3005 51 truth.r.on_header = conc_header_truth;
3006 51 truth.r.on_record = conc_record_truth;
3007 51 truth.s = s;
3008 51 vcf_read(aTHX_ truth_next, &truth.r);
3009 40 SPAGAIN;
3010 40 HV *out = conc_results(aTHX_ s, test.r.names, truth.r.names, discordances);
3011 40 ▶ EXTEND(SP, 2);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 2); 0 40 40
3012 40 PUSHs(sv_2mortal(newRV_inc((SV*)out)));
3013 40 PUSHs(sv_2mortal(newRV_inc((SV*)test.r.names)));
3014  
3015 void
3016 _hirisplex_dosage(next, name, min_depth, panel, markers, by_id)
3017 SV *next
3018 const char *name
3019 UV min_depth
3020 AV *panel
3021 UV markers
3022 UV by_id
3023 PPCODE:
3024 AV *names, *seen;
3025 17 PUTBACK;
3026 17 HV *out = hps_dosage_vcf(aTHX_ next, name, min_depth, panel, (size_t)markers, by_id ? TRUE : FALSE, &names, &seen);
3027 15 SPAGAIN;
3028 15 ▶ EXTEND(SP, 3);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 3); 0 15 15
3029 15 PUSHs(sv_2mortal(newRV_inc((SV*)out)));
3030 15 PUSHs(sv_2mortal(newRV_inc((SV*)names)));
3031 15 PUSHs(sv_2mortal(newRV_noinc((SV*)seen)));
3032  
3033 void
3034 _blood_type_tally(next, name, min_depth, panel, markers, chrom, start, end)
3035 SV *next
3036 const char *name
3037 UV min_depth
3038 AV *panel
3039 UV markers
3040 UV chrom
3041 UV start
3042 UV end
3043 PPCODE:
3044 AV *names, *seen, *deleted;
3045 UV flags[2];// bt_tally_vcf()'s: the chromosomes read, and those with an allele longer than a base
3046 37 PUTBACK;
3047 37 HV *out = bt_tally_vcf(aTHX_ next, name, min_depth, panel, (size_t)markers, chrom, start, end, &names, &seen, &deleted, flags);
3048 33 SPAGAIN;
3049 33 ▶ EXTEND(SP, 6);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 6); 0 33 33
3050 33 PUSHs(sv_2mortal(newRV_inc((SV*)out)));
3051 33 PUSHs(sv_2mortal(newRV_inc((SV*)names)));
3052 33 PUSHs(sv_2mortal(newRV_noinc((SV*)seen)));
3053 33 PUSHs(sv_2mortal(newRV_noinc((SV*)deleted)));
3054 33 PUSHs(sv_2mortal(newSVuv(flags[0])));
3055 33 PUSHs(sv_2mortal(newSVuv(flags[1])));
3056  
3057 SV *
3058 _translate(seq, code, stop_symbol, to_stop, gap)
3059 SV *seq
3060 SV *code
3061 char stop_symbol
3062 UV to_stop
3063 SV *gap
3064 CODE:
3065 // On a line of its own: SvREFCNT_inc_simple_NN() is a macro that evaluates
3066 // its argument twice, and would translate twice. The mortal is kept by
3067 // taking a second reference to it.
3068 267 ▶ SV *protein = translate_codons(aTHX_ seq, code, stop_symbol, to_stop ? TRUE : FALSE, SvOK(gap) ? SvPV_nolen(gap) : NULL);
Branch: 1 branch
BranchTrueFalseTotal
SV *protein = translate_codons(aTHX_ seq, code, stop_symbol, to_stop ? TRUE : FALSE, SvOK(gap) ? SvPV_nolen(gap) : NULL); 7 253 260
3069 247 RETVAL = SvREFCNT_inc_simple_NN(protein);
3070 OUTPUT:
3071 RETVAL
3072  
3073 SV *
3074 _kmer_count(seq, k, step)
3075 SV *seq
3076 UV k
3077 UV step
3078 CODE:
3079 24 RETVAL = newRV_inc((SV*)kmer_tally(aTHX_ seq, k, step));// inc, since the hash is mortal
3080 OUTPUT:
3081 RETVAL
3082  
3083 void
3084 _admixture_genotypes(next, name, min_depth)
3085 SV *next
3086 const char *name
3087 UV min_depth
3088 PPCODE:
3089 admix_reader t;
3090 13 Zero(&t, 1, admix_reader);
3091 13 t.r.name = name;
3092 13 t.r.min_depth = min_depth;
3093 13 t.r.on_header = admix_header;
3094 13 t.r.on_record = admix_record;
3095 13 t.g = sv_2mortal(newSVpvs(""));
3096 13 t.variants = (AV*)sv_2mortal((SV*)newAV());
3097 13 PUTBACK;
3098 13 vcf_read(aTHX_ next, &t.r);
3099 13 SPAGAIN;
3100 13 AV *called = (AV*)sv_2mortal((SV*)newAV());
3101 679 ▶ for (size_t i = 0; i < t.r.n; i++) av_push(called, newSVuv(t.called[i]));
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < t.r.n; i++) av_push(called, newSVuv(t.called[i])); 666 13 679
3102 13 ▶ EXTEND(SP, 4);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 4); 0 13 13
3103 13 PUSHs(t.g);
3104 13 PUSHs(sv_2mortal(newRV_inc((SV*)t.variants)));
3105 13 PUSHs(sv_2mortal(newRV_inc((SV*)t.r.names)));
3106 13 PUSHs(sv_2mortal(newRV_inc((SV*)called)));
3107  
3108 void
3109 _admixture_fit(g, n, k, seed, max_iterations, tolerance)
3110 SV *g
3111 UV n
3112 UV k
3113 UV seed
3114 UV max_iterations
3115 NV tolerance
3116 PPCODE:
3117 STRLEN len;
3118 21 const unsigned char *bytes = (const unsigned char*)SvPV_const(g, len);// not restrict: perl's buffer
3119 // named literally, since __func__ in an XSUB is XS_Cn__Bioinf__admixture_fit
3120 21 ▶ if (n == 0 || k == 0 || len % n) croak("_admixture_fit: %" UVuf " genotype bytes for %" UVuf " samples and K %" UVuf, (UV)len, n, k);// cannot happen: perl checks
Branch: 3 branches
BranchTrueFalseTotal
if (n == 0 || k == 0 || len % n) croak("_admixture_fit: %" UVuf " genotype bytes for %" UVuf " samples and K %" UVuf, (UV)len, n, k);// cannot happen: perl checks 21 0 21
if (n == 0 || k == 0 || len % n) croak("_admixture_fit: %" UVuf " genotype bytes for %" UVuf " samples and K %" UVuf, (UV)len, n, k);// cannot happen: perl checks 21 0 21
if (n == 0 || k == 0 || len % n) croak("_admixture_fit: %" UVuf " genotype bytes for %" UVuf " samples and K %" UVuf, (UV)len, n, k);// cannot happen: perl checks 0 21 21
3121 admix_fit a;
3122 21 a.g = bytes;
3123 21 a.n = (size_t)n;
3124 21 a.m = len / n;
3125 21 a.k = (size_t)k;
3126 21 ▶ if (a.k > ((size_t)-1 / sizeof(NV) / 4) / (a.n + a.m)) croak("_admixture_fit: %" UVuf " samples and %" UVuf " variants at K %" UVuf " are too many to fit", n, (UV)a.m, k);
Branch: 1 branch
BranchTrueFalseTotal
if (a.k > ((size_t)-1 / sizeof(NV) / 4) / (a.n + a.m)) croak("_admixture_fit: %" UVuf " samples and %" UVuf " variants at K %" UVuf " are too many to fit", n, (UV)a.m, k); 0 21 21
3127 21 const size_t params = (a.n + a.m) * a.k;
3128 NV *th;
3129 21 ▶ Newx(th, params, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(th, params, NV); 0 21 21
3130 21 SAVEFREEPV(th);
3131 21 ▶ Newxz(a.twice, a.n, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(a.twice, a.n, NV); 0 21 21
3132 21 SAVEFREEPV(a.twice);
3133 21 ▶ Newx(a.num, a.k, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(a.num, a.k, NV); 0 21 21
3134 21 SAVEFREEPV(a.num);
3135 21 ▶ Newx(a.den, a.k, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(a.den, a.k, NV); 0 21 21
3136 21 SAVEFREEPV(a.den);
3137 5403 ▶ for (size_t j = 0; j < a.m; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t j = 0; j < a.m; j++) { 5382 21 5403
3138 328188 ▶ for (size_t i = 0; i < a.n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < a.n; i++) { 322806 5382 328188
3139 322806 ▶ if (bytes[j * a.n + i] != ADMIX_MISSING) a.twice[i] += 2;
Branch: 1 branch
BranchTrueFalseTotal
if (bytes[j * a.n + i] != ADMIX_MISSING) a.twice[i] += 2; 322406 400 322806
3140 }
3141 }
3142 21 admix_start(&a, th, (uint64_t)seed);
3143 UV iterations;
3144 bool converged;
3145 21 const NV ll = admix_run(aTHX_ &a, th, max_iterations, tolerance, &iterations, &converged);
3146 21 AV *q = (AV*)sv_2mortal((SV*)newAV()), *p = (AV*)sv_2mortal((SV*)newAV());
3147 6606 ▶ for (size_t i = 0; i < a.n + a.m; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < a.n + a.m; i++) { 6585 21 6606
3148 6585 AV *row = newAV();
3149 26335 ▶ for (size_t l = 0; l < a.k; l++) av_push(row, newSVnv(th[i * a.k + l]));
Branch: 1 branch
BranchTrueFalseTotal
for (size_t l = 0; l < a.k; l++) av_push(row, newSVnv(th[i * a.k + l])); 19750 6585 26335
3150 6585 ▶ av_push(i < a.n ? q : p, newRV_noinc((SV*)row));
Branch: 1 branch
BranchTrueFalseTotal
av_push(i < a.n ? q : p, newRV_noinc((SV*)row)); 1203 5382 6585
3151 }
3152 21 ▶ EXTEND(SP, 5);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 5); 0 21 21
3153 21 PUSHs(sv_2mortal(newRV_inc((SV*)q)));
3154 21 PUSHs(sv_2mortal(newRV_inc((SV*)p)));
3155 21 PUSHs(sv_2mortal(newSVnv(ll)));
3156 21 PUSHs(sv_2mortal(newSVuv(iterations)));
3157 21 PUSHs(sv_2mortal(newSVuv(converged ? 1 : 0)));
« blib/lib/Cn/Bioinf.pm ↑ Summary