Parser.xs

filter: Statementstmt 97.1% 5192 / 5343 Branchbran 83.0% 4588 / 5522 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 90.0% 9780 / 10865 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« blib/lib/Chem/Structure/Parser.pm ↑ Summary
1 #ifndef _GNU_SOURCE
2 #define _GNU_SOURCE // glibc / Linux
3 #endif
4 #ifndef __EXTENSIONS__
5 #define __EXTENSIONS__ 1 // Solaris/illumos
6 #endif
7 #define PERL_NO_GET_CONTEXT
8 #include "EXTERN.h"
9 #include "perl.h"
10 #include "XSUB.h"
11 #include "ppport.h"
12 #include <string.h>
13 #include <stdlib.h>
14 #include <errno.h>
15 #include <math.h>
16 #include <float.h>
17 /*No <ctype.h>: every classification in this file is ASCII by definition -- an
18 element symbol, a residue name, a one-letter code, a CIF keyword -- and the
19 ctype.h functions answer for the locale perl set from the environment at
20 startup. In a Latin-1 locale isalpha() calls an accented byte a letter, so a
21 stray one in the atom name column guesses an element that is not ASCII; in a
22 Turkish one tolower('I') is not 'i', so cif_iskw() stops recognising an mmCIF
23 file whose tags are written in capitals. perl's toUPPER(), toLOWER(),
24 isALPHA() and isDIGIT() (handy.h, and ASCII-only on every non-EBCDIC build
25 since long before 5.10) do not consult the locale. The two read a directory of
26 PDBbind in the same time to the noise, so what this buys is the locale and not
27 speed.*/
28 /*Chem::Structure::Parser -- the parts of reading a PDB file worth doing in C.
29  
30 A PDB file is one record per line with every field at a fixed column range
31 (the format is punched-card old). Two things about that make XS pay for
32 itself here, and only two: the coordinate section is enormous -- the largest
33 file in PDBbind v2020 is 33 MB, ~400,000 ATOM/HETATM lines -- and every one
34 of those lines wants a dozen substr()s and three numeric conversions, which
35 in Perl is a dozen SVs per line born and buried; and residue names are looked
36 up constantly (three letters -> one letter, "amino acid, nucleotide or
37 water?"), a switch on three bytes in C against a hash lookup plus a sub call
38 in Perl.
39  
40 So C does exactly that: one pass over the bytes, ATOM/HETATM split into
41 parallel column arrays (one array per field, not one hash per atom, which
42 keeps peak memory down by roughly an order of magnitude), residue boundaries
43 marked as it goes, every other record handed back as raw lines grouped by
44 record name. The header records (HEADER, COMPND, REMARK, SEQRES, ...) are
45 parsed in Perl: a few dozen of them, irregular, and the part most likely to
46 need fixing later.*/
47  
48 /*CSP_RESTRICT -- "no other pointer here reaches this object". Worth spelling
49 out because perl's ccflags carry -fno-strict-aliasing, which switches off the
50 type-based aliasing analysis a C compiler would otherwise use; restrict is one
51 of the few aliasing facts still available to it, and the parse below is full of
52 the pattern it wants -- a const char * into the file buffer read alongside a
53 char * being written, both the same type, neither able to touch the other.
54  
55 Not spelled `restrict' directly: that is C99, and the perls this builds against
56 are configured with whatever -std their Configure chose (5.10 on an old gcc gets
57 gnu89). GCC and clang take __restrict__ in any mode, MSVC takes __restrict,
58 and a compiler with neither loses the hint and nothing else. Predefine it empty
59 -- OPTIMIZE='-O2 -DCSP_RESTRICT=' -- to build without the hint, which is how the
60 before/after timings were taken and the escape hatch if a compiler mishandles
61 it.*/
62 #ifndef CSP_RESTRICT
63 #if defined(__cplusplus)
64 # if defined(__GNUC__) || defined(_MSC_VER)
65 # define CSP_RESTRICT __restrict
66 # else
67 # define CSP_RESTRICT
68 # endif
69 #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
70 # define CSP_RESTRICT restrict
71 #elif defined(__GNUC__) && __GNUC__ >= 3
72 # define CSP_RESTRICT __restrict__
73 #elif defined(_MSC_VER) && _MSC_VER >= 1400
74 # define CSP_RESTRICT __restrict
75 #else
76 # define CSP_RESTRICT
77 #endif
78 #endif
79  
80 /*Width-correct libm for NV.
81  
82 C has no type-generic <math.h>: sqrt(), cos() and acos() are declared to take a
83 double, so calling one with an NV on a long-double or __float128 build converts
84 the argument down, computes at 53 bits of mantissa and converts back. Nothing
85 warns and nothing fails to compile; the answer is simply less accurate than the
86 perl running it. So every NV-valued libm call in this file goes through the
87 nv_* macros below, which paste on the suffix for the width NV actually is: none
88 for double, `l' for long double, `q' for __float128 (perl.h has already included
89 <quadmath.h> by this point, and the quadmath perl's $Config{perllibs} already
90 carries -lquadmath, so the q functions need nothing at link time).
91  
92 The long-double row is conditional because the `l' variants are C99 but not
93 universally present -- some BSD libms are thin on them. Makefile.PL link-tests
94 the set and defines CSP_HAVE_LONG_DOUBLE_MATH only when every one resolves;
95 without it this falls back to the double functions, which costs accuracy on a
96 long-double perl and nothing else.
97  
98 This layer is the same one Stats::LikeR carries, cut down to the six functions
99 the feature calculations below need. Adding a sixth means adding it to the
100 Makefile.PL probe in the same edit, or the probe passes on a libm that does not
101 have it and the build breaks on a machine nobody here owns.*/
102 #if defined(USE_QUADMATH)
103 # define CSP_NVFN(base) base ## q
104 #elif defined(USE_LONG_DOUBLE) && defined(CSP_HAVE_LONG_DOUBLE_MATH)
105 # define CSP_NVFN(base) base ## l
106 #else
107 # define CSP_NVFN(base) base
108 #endif
109 #define nv_fabs(x) CSP_NVFN(fabs)(x)
110 #define nv_sqrt(x) CSP_NVFN(sqrt)(x)
111 #define nv_acos(x) CSP_NVFN(acos)(x)
112 #define nv_cos(x) CSP_NVFN(cos)(x)
113 #define nv_sin(x) CSP_NVFN(sin)(x)
114 #define nv_atan2(y,x) CSP_NVFN(atan2)((y),(x))
115  
116 /*pi at the full width of an NV. A literal cannot supply this: an unsuffixed C
117 floating constant is a double, so spelling the digits out would round pi to 53
118 bits on a long-double or __float128 build, and the `L' / `Q' suffixes that would
119 avoid that are per-build (and `Q' is a GNU extension). acos(-1) is pi correctly
120 rounded to the working width on every libm, and nv_acos() picks the right
121 width's acos. M_PI is not used: it is not in C89 or C99, MSVC hides it behind
122 _USE_MATH_DEFINES, and where it exists it is a double.*/
123 #define CSP_PI nv_acos((NV)-1.0)
124  
125 /*residue table. One table serves aa3to1(), res1() and res_type(), so the
126 three can never disagree about what a residue is. Keyed on the three-byte
127 name packed into a U32, left-padded with blanks, so that "ALA", " DA" and
128 " A" are all one switch on an integer.*/
129 #define RT_OTHER 0 //a ligand, an ion, a sugar: not in the table
130 #define RT_AA 1 //amino acid, standard or modified
131 #define RT_NUC 2 //nucleotide, DNA or RNA
132 #define RT_WATER 3 //HOH, DOD, WAT, and the rest of the spellings
133  
134 /*U32 and not unsigned: the key is three bytes wide and the top one is shifted
135 16 places, which plain unsigned is only guaranteed 16 bits for.*/
136 #define K3(a, b, c) (((U32)(a) << 16) | ((U32)(b) << 8) | (U32)(c))
137  
138 typedef struct {
139 char one;//single-letter code; '\0' when there isn't one
140 unsigned char type;//RT_*
141 } res_info;
142  
143 //pack a (possibly blank-padded, possibly short) residue name into a key
144 299229 static U32 res_key(const char *CSP_RESTRICT s, STRLEN len)
145 {
146 char b[3];
147 STRLEN i;
148 299239 ▶ while (len && (*s == ' ' || *s == '\t')) { s++; len--; }
Branch: 3 branches
BranchTrueFalseTotal
while (len && (*s == ' ' || *s == '\t')) { s++; len--; } 299236 3 299239
while (len && (*s == ' ' || *s == '\t')) { s++; len--; } 10 299226 299236
while (len && (*s == ' ' || *s == '\t')) { s++; len--; } 0 299226 299226
149 299232 ▶ while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--;
Branch: 3 branches
BranchTrueFalseTotal
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--; 299229 3 299232
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--; 3 299226 299229
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--; 0 299226 299226
150 299229 ▶ if (len == 0 || len > 3) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (len == 0 || len > 3) return 0; 299226 3 299229
if (len == 0 || len > 3) return 0; 3 299223 299226
151 299223 b[0] = b[1] = b[2] = ' ';
152 1110911 ▶ for (i = 0; i < len; i++) b[3 - len + i] = (char)toUPPER((unsigned char)s[i]);
Branch: 2 branches
BranchTrueFalseTotal
for (i = 0; i < len; i++) b[3 - len + i] = (char)toUPPER((unsigned char)s[i]); 5 811683 811688
for (i = 0; i < len; i++) b[3 - len + i] = (char)toUPPER((unsigned char)s[i]); 811688 299223 1110911
153 299223 return K3((unsigned char)b[0], (unsigned char)b[1], (unsigned char)b[2]);
154 }
155  
156 /*res_lookup() -- classify a residue name. True when the name is known, false
157 when it is not (a ligand, an ion, a sugar: anything the caller has to work out
158 for itself from the atoms).*/
159 281191 static bool res_lookup(const char *CSP_RESTRICT s, STRLEN len, res_info *CSP_RESTRICT out)
160 {
161 char one;
162 281191 unsigned char type = RT_AA;
163 281191 switch (res_key(s, len)) {
164 //the twenty, plus the ambiguity codes the format allows
165 10972 case K3('A','L','A'): one = 'A'; break;
166 8614 case K3('A','R','G'): one = 'R'; break;
167 5697 case K3('A','S','N'): one = 'N'; break;
168 9632 case K3('A','S','P'): one = 'D'; break;
169 6460 case K3('C','Y','S'): one = 'C'; break;
170 3697 case K3('G','L','N'): one = 'Q'; break;
171 9109 case K3('G','L','U'): one = 'E'; break;
172 9231 case K3('G','L','Y'): one = 'G'; break;
173 12414 case K3('H','I','S'): one = 'H'; break;
174 6715 case K3('I','L','E'): one = 'I'; break;
175 13856 case K3('L','E','U'): one = 'L'; break;
176 12846 case K3('L','Y','S'): one = 'K'; break;
177 4991 case K3('M','E','T'): one = 'M'; break;
178 6863 case K3('P','H','E'): one = 'F'; break;
179 22220 case K3('P','R','O'): one = 'P'; break;
180 9642 case K3('S','E','R'): one = 'S'; break;
181 3920 case K3('T','H','R'): one = 'T'; break;
182 10442 case K3('T','R','P'): one = 'W'; break;
183 14875 case K3('T','Y','R'): one = 'Y'; break;
184 6030 case K3('V','A','L'): one = 'V'; break;
185 6 case K3('A','S','X'): one = 'B'; break;//ASX ASP or ASN
186 6 case K3('G','L','X'): one = 'Z'; break;//GLX GLU or GLN
187 6 case K3('X','L','E'): one = 'J'; break;//XLE LEU or ILE
188 6 case K3('S','E','C'): one = 'U'; break;//SEC selenocysteine
189 6 case K3('P','Y','L'): one = 'O'; break;//PYL pyrrolysine
190 13 case K3('U','N','K'): case K3('X','A','A'): one = 'X'; break;
191  
192 /*modified residues, mapped to the parent they were made from. A
193 structure that soaked in selenomethionine is still the same sequence,
194 and a sequence with an 'X' every seventh position is no use to anyone.*/
195 2752 case K3('M','S','E'): case K3('M','H','O'): case K3('F','M','E'): case K3('C','X','M'):
196 2752 case K3('S','M','E'): case K3('M','E','D'): one = 'M'; break;//MSE selenomethionine
197 56 case K3('C','S','O'): case K3('C','S','D'): case K3('C','S','S'): case K3('C','S','X'):
198 case K3('C','S','W'): case K3('C','M','E'): case K3('C','M','T'): case K3('C','Y','X'):
199 case K3('C','A','S'): case K3('C','A','F'): case K3('O','C','S'): case K3('S','M','C'):
200 56 case K3('S','N','C'): case K3('Y','C','M'): one = 'C'; break;
201 8 case K3('S','E','P'): case K3('S','A','C'): one = 'S'; break;//SEP phosphoserine
202 4 case K3('T','P','O'): one = 'T'; break;//TPO phosphothreonine
203 32 case K3('P','T','R'): case K3('T','Y','S'): case K3('T','Y','I'): case K3('T','Y','Q'):
204 case K3('T','P','Q'): case K3('P','A','Q'): case K3('S','T','Y'): case K3('I','Y','R'):
205 32 one = 'Y'; break;//PTR phosphotyrosine
206 28 case K3('K','C','X'): case K3('L','L','P'): case K3('M','L','Y'): case K3('M','L','Z'):
207 28 case K3('M','3','L'): case K3('A','L','Y'): case K3('L','Y','Z'): one = 'K'; break;
208 8 case K3('H','Y','P'): case K3('H','Y','3'): one = 'P'; break;//HYP hydroxyproline
209 //PCA pyroglutamate
210 15 case K3('P','C','A'): case K3('C','G','U'): case K3('G','M','A'): one = 'E'; break;
211 36 case K3('H','I','C'): case K3('H','I','D'): case K3('H','I','E'): case K3('H','I','P'):
212 case K3('H','S','D'): case K3('H','S','E'): case K3('H','S','P'): case K3('M','H','S'):
213 36 case K3('N','E','P'): one = 'H'; break;
214 20 case K3('A','I','B'): case K3('A','B','A'): case K3('A','L','M'): case K3('A','Y','A'):
215 20 case K3('B','A','L'): one = 'A'; break;
216 4 case K3('S','A','R'): one = 'G'; break;//SAR sarcosine
217 8 case K3('M','L','E'): case K3('N','L','E'): one = 'L'; break;
218 4 case K3('M','V','A'): one = 'V'; break;
219 4 case K3('C','I','R'): one = 'R'; break;//CIR citrulline
220 8 case K3('O','R','N'): case K3('D','A','B'): one = 'X'; break;//ORN ornithine
221 4 case K3('T','R','O'): one = 'W'; break;
222 12 case K3('P','H','I'): case K3('P','H','L'): case K3('M','E','A'): one = 'F'; break;
223  
224 /*D-amino acids -- common in the peptide ligands this was written for,
225 and the same letter as their L partner*/
226 4 case K3('D','A','L'): one = 'A'; break;
227 4 case K3('D','A','R'): one = 'R'; break;
228 4 case K3('D','S','G'): one = 'N'; break;
229 4 case K3('D','A','S'): one = 'D'; break;
230 4 case K3('D','C','Y'): one = 'C'; break;
231 4 case K3('D','G','N'): one = 'Q'; break;
232 4 case K3('D','G','L'): one = 'E'; break;
233 4 case K3('D','H','I'): one = 'H'; break;
234 4 case K3('D','I','L'): one = 'I'; break;
235 4 case K3('D','L','E'): one = 'L'; break;
236 4 case K3('D','L','Y'): one = 'K'; break;
237 4 case K3('D','P','N'): one = 'F'; break;
238 4 case K3('D','P','R'): one = 'P'; break;
239 4 case K3('D','S','N'): one = 'S'; break;
240 4 case K3('D','T','H'): one = 'T'; break;
241 4 case K3('D','T','R'): one = 'W'; break;
242 4 case K3('D','T','Y'): one = 'Y'; break;
243 8 case K3('D','V','A'): case K3('D','I','V'): one = 'V'; break;
244  
245 //nucleotides: DNA (" DA"), RNA (" A"), and the pre-v3 spellings
246 6395 case K3(' ','D','A'): one = 'A'; type = RT_NUC; break;
247 4818 case K3(' ','D','C'): one = 'C'; type = RT_NUC; break;
248 5451 case K3(' ','D','G'): one = 'G'; type = RT_NUC; break;
249 6174 case K3(' ','D','T'): one = 'T'; type = RT_NUC; break;
250 3 case K3(' ','D','U'): one = 'U'; type = RT_NUC; break;
251 3 case K3(' ','D','I'): one = 'I'; type = RT_NUC; break;
252 7994 case K3(' ',' ','A'): one = 'A'; type = RT_NUC; break;
253 6774 case K3(' ',' ','C'): one = 'C'; type = RT_NUC; break;
254 10625 case K3(' ',' ','G'): one = 'G'; type = RT_NUC; break;
255 3 case K3(' ',' ','T'): one = 'T'; type = RT_NUC; break;
256 4330 case K3(' ',' ','U'): one = 'U'; type = RT_NUC; break;
257 3 case K3(' ',' ','I'): one = 'I'; type = RT_NUC; break;
258 3 case K3(' ',' ','N'): one = 'N'; type = RT_NUC; break;
259 23 case K3('A','D','E'): one = 'A'; type = RT_NUC; break;
260 11 case K3('C','Y','T'): one = 'C'; type = RT_NUC; break;
261 61 case K3('G','U','A'): one = 'G'; type = RT_NUC; break;
262 3 case K3('T','H','Y'): one = 'T'; type = RT_NUC; break;
263 /*5MU is 5-methyluridine, ribothymidine: a U methylated in the tRNA, and
264 so a U by the rule the rest of this table follows -- 5MC is a C, 1MA an
265 A. gemmi 0.7.5 ('u') and Biopython 1.85's PDBData ("5MU": "U") agree;
266 a T here put a DNA letter in an RNA sequence.*/
267 16 case K3('U','R','I'): case K3('P','S','U'): case K3('H','2','U'): case K3('4','S','U'):
268 16 case K3('5','M','U'): one = 'U'; type = RT_NUC; break;//PSU pseudouridine
269 7 case K3('5','M','C'): case K3('O','M','C'): one = 'C'; type = RT_NUC; break;
270 3 case K3('1','M','A'): one = 'A'; type = RT_NUC; break;
271 25 case K3('2','M','G'): case K3('7','M','G'): case K3('1','M','G'): case K3('M','2','G'):
272 25 case K3('O','M','G'): one = 'G'; type = RT_NUC; break;
273  
274 //water, under every name it gets written with
275 32341 case K3('H','O','H'): case K3('W','A','T'): case K3('D','O','D'): case K3('H','2','O'):
276 32341 case K3('S','O','L'): case K3('T','I','P'): one = '\0'; type = RT_WATER; break;
277  
278 4777 default: return 0;
279 }
280 276414 out->one = one;
281 276414 out->type = type;
282 276414 return 1;
283 }
284  
285 /*the reverse direction. res_lookup() is many-to-one: sixty-odd names come
286 back as 'C'. Going the other way there is one answer worth giving, the parent
287 residue the letter stands for, so this is a plain table indexed by the letter
288 -- 104 bytes of read-only memory, one bounds check and one index per call, and
289 no hash to build at load time.
290  
291 Every letter A-Z is spoken for, because the ambiguity codes have names of
292 their own. There is nothing here for the nucleotides -- 'A' is ALA on the way
293 back, and a caller who wants " DA" knows already that the chain is DNA and
294 does not need this to guess.
295  
296 t/residue_names.t rounds every letter back through aa3to1() so that this table
297 and the switch above cannot drift apart.*/
298 static const char aa1to3_name[26][4] = {
299 "ALA", "ASX", "CYS", "ASP", "GLU", "PHE", "GLY", "HIS", "ILE", //A-I
300 "XLE", "LYS", "LEU", "MET", "ASN", "PYL", "PRO", "GLN", "ARG", //J-R
301 "SER", "THR", "SEC", "VAL", "TRP", "UNK", "TYR", "GLX" //S-Z
302 };//B ASP or ASN, J LEU or ILE, O pyrrolysine, U selenocysteine, Z GLU or GLN
303  
304 /*aa1to3_lookup() -- the name for a single-letter code, or NULL. Blanks and
305 case are forgiven, as they are in res_key(), because the letter usually
306 arrives out of a sequence string that has been through something else.*/
307 89 static const char *aa1to3_lookup(const char *CSP_RESTRICT s, STRLEN len)
308 {
309 92 ▶ while (len && (*s == ' ' || *s == '\t')) { s++; len--; }
Branch: 3 branches
BranchTrueFalseTotal
while (len && (*s == ' ' || *s == '\t')) { s++; len--; } 90 2 92
while (len && (*s == ' ' || *s == '\t')) { s++; len--; } 3 87 90
while (len && (*s == ' ' || *s == '\t')) { s++; len--; } 0 87 87
310 90 ▶ while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--;
Branch: 3 branches
BranchTrueFalseTotal
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--; 88 2 90
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--; 1 87 88
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--; 0 87 87
311 89 ▶ if (len != 1) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (len != 1) return NULL; 3 86 89
312 86 ▶ int c = toUPPER((unsigned char)*s);
Branch: 1 branch
BranchTrueFalseTotal
int c = toUPPER((unsigned char)*s); 2 84 86
313 86 ▶ if (c < 'A' || c > 'Z') return NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (c < 'A' || c > 'Z') return NULL; 83 3 86
if (c < 'A' || c > 'Z') return NULL; 0 83 83
314 83 return aa1to3_name[c - 'A'];
315 }
316  
317 /*column fields. Every accessor below clips to the line's real length first:
318 PDB files in the wild are right-trimmed, so a line can stop before the element
319 column (or before the B-factor) and that is not an error.*/
320  
321 1617557 static STRLEN trim_ptr(const char **CSP_RESTRICT sp, STRLEN len)
322 {
323 1617557 const char *s = *sp;
324 4046762 ▶ while (len && (*s == ' ' || *s == '\t')) { s++; len--; }
Branch: 3 branches
BranchTrueFalseTotal
while (len && (*s == ' ' || *s == '\t')) { s++; len--; } 3902883 143879 4046762
while (len && (*s == ' ' || *s == '\t')) { s++; len--; } 2429205 1473678 3902883
while (len && (*s == ' ' || *s == '\t')) { s++; len--; } 0 1473678 1473678
325 1773696 ▶ while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--;
Branch: 3 branches
BranchTrueFalseTotal
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--; 1629817 143879 1773696
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--; 156139 1473678 1629817
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--; 0 1473678 1473678
326 1617557 *sp = s;
327 1617557 return len;
328 }
329  
330 //fld() -- the trimmed contents of columns [from, to], zero-based inclusive
331 1761486 static STRLEN fld(const char *CSP_RESTRICT line, STRLEN llen, STRLEN from, STRLEN to,
332 const char **CSP_RESTRICT out)
333 {
334 const char *s;
335 STRLEN n;
336 1761486 *out = line;
337 1761486 ▶ if (from >= llen) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (from >= llen) return 0; 143929 1617557 1761486
338 1617557 ▶ if (to >= llen) to = llen - 1;
Branch: 1 branch
BranchTrueFalseTotal
if (to >= llen) to = llen - 1; 797 1616760 1617557
339 1617557 s = line + from;
340 1617557 n = to - from + 1;
341 1617557 n = trim_ptr(&s, n);
342 1617557 *out = s;
343 1617557 return n;
344 }
345  
346 /*str2iv() -- integers, exactly, without going through a double. '*****'
347 (what a serial number becomes once it overflows five columns) and anything
348 else non-numeric report failure rather than a wrong number.
349  
350 A number too big for an IV is declined for the same reason and not wrapped.
351 The accumulator is a UV tested before each digit, because a signed overflow is
352 undefined behaviour rather than a wrap: the fields a PDB record gives this are
353 four and five columns wide and cannot reach it, but an mmCIF value is free-form
354 and nothing stops a file writing twenty digits of _atom_site.id. One did, in
355 t/numbers.t, and came back as 200376420520689663 and a negative residue
356 number.*/
357 530223 static bool str2iv(const char *CSP_RESTRICT s, STRLEN n, IV *CSP_RESTRICT out)
358 {
359 530223 bool neg = 0, seen = 0;
360 530223 UV v = 0, limit;
361 530223 STRLEN i = 0;
362 530223 ▶ if (i < n && (s[i] == '+' || s[i] == '-')) { neg = (s[i] == '-'); i++; }
Branch: 3 branches
BranchTrueFalseTotal
if (i < n && (s[i] == '+' || s[i] == '-')) { neg = (s[i] == '-'); i++; } 530223 0 530223
if (i < n && (s[i] == '+' || s[i] == '-')) { neg = (s[i] == '-'); i++; } 530223 0 530223
if (i < n && (s[i] == '+' || s[i] == '-')) { neg = (s[i] == '-'); i++; } 52 530171 530223
363 //one more magnitude on the negative side, which is where IV_MIN lives
364 530223 ▶ limit = neg ? (UV)IV_MAX + 1 : (UV)IV_MAX;
Branch: 1 branch
BranchTrueFalseTotal
limit = neg ? (UV)IV_MAX + 1 : (UV)IV_MAX; 52 530171 530223
365 1720770 ▶ for (; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (; i < n; i++) { 1190641 530129 1720770
366 UV d;
367 1190641 ▶ if (!isDIGIT((unsigned char)s[i])) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!isDIGIT((unsigned char)s[i])) return 0; 92 1190549 1190641
368 1190549 d = (UV)(s[i] - '0');
369 1190549 ▶ if (v > (limit - d) / 10) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (v > (limit - d) / 10) return 0; 2 1190547 1190549
370 1190547 v = v * 10 + d;
371 1190547 seen = 1;
372 }
373 530129 ▶ if (!seen) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!seen) return 0; 0 530129 530129
374 //IV_MIN is not -(IV)v: its magnitude has no positive IV to be negated from
375 530129 ▶ *out = neg ? (v == (UV)IV_MAX + 1 ? IV_MIN : -(IV)v) : (IV)v;
Branch: 2 branches
BranchTrueFalseTotal
*out = neg ? (v == (UV)IV_MAX + 1 ? IV_MIN : -(IV)v) : (IV)v; 52 530077 530129
*out = neg ? (v == (UV)IV_MAX + 1 ? IV_MIN : -(IV)v) : (IV)v; 50 2 52
376 530129 return 1;
377 }
378  
379 /*hy36_decode() -- a PDB integer field written in hybrid-36, the encoding that
380 lets a fixed-width field go past its decimal range.
381  
382 A four-column residue number runs out at 9999 and a five-column serial at
383 99999, and a structure bigger than that -- a ribosome, a solvated simulation
384 box -- has to write the next one somehow. Hybrid-36 is the convention cctbx,
385 phenix and gemmi write it in: Grosse-Kunstleve, R W, "hybrid_36",
386 https://cci.lbl.gov/hybrid_36/ (the reference hy36decode() in hybrid_36_c.c).
387 A width-w field holds plain decimal up to 10**w - 1; past that it is w base-36
388 digits beginning with a letter, upper case first and then lower case:
389  
390 "A000" (w = 4) is 10000, "ZZZZ" is 10000 + 26 * 36**3 - 1, "a000" the next
391  
392 so an upper-case field is its base-36 value less 10 * 36**(w-1) plus 10**w, and
393 a lower-case one its base-36 value plus 16 * 36**(w-1) plus 10**w. A field that
394 mixes the two cases, or does not fill the whole width, is not hybrid-36 and is
395 declined. gemmi 0.7.5 reads 'A000' as residue 10000 and 'A0000' as serial
396 100000, and so does this; t/data/numbering.pdb is where the two are compared.
397  
398 Only ever reached after str2iv() has declined the field, so a decimal field
399 keeps its meaning exactly. w is at most five, and 36**5 is 60,466,176, which an
400 IV holds on every perl.*/
401 89 static bool hy36_decode(const char *CSP_RESTRICT s, STRLEN n, unsigned short width,
402 IV *CSP_RESTRICT out)
403 {
404 89 IV v = 0, p = 1, dec = 1;
405 bool upper;
406 89 ▶ if (n != width || !isALPHA((unsigned char)s[0])) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (n != width || !isALPHA((unsigned char)s[0])) return 0; 89 0 89
if (n != width || !isALPHA((unsigned char)s[0])) return 0; 3 86 89
407 86 ▶ upper = (s[0] >= 'A' && s[0] <= 'Z');
Branch: 2 branches
BranchTrueFalseTotal
upper = (s[0] >= 'A' && s[0] <= 'Z'); 86 0 86
upper = (s[0] >= 'A' && s[0] <= 'Z'); 77 9 86
408 460 ▶ for (STRLEN i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (STRLEN i = 0; i < n; i++) { 375 85 460
409 375 const unsigned char c = (unsigned char)s[i];
410 IV d;
411 375 ▶ if (isDIGIT(c)) d = c - '0';
Branch: 1 branch
BranchTrueFalseTotal
if (isDIGIT(c)) d = c - '0'; 263 112 375
412 112 ▶ else if (upper && c >= 'A' && c <= 'Z') d = c - 'A' + 10;
Branch: 3 branches
BranchTrueFalseTotal
else if (upper && c >= 'A' && c <= 'Z') d = c - 'A' + 10; 82 30 112
else if (upper && c >= 'A' && c <= 'Z') d = c - 'A' + 10; 82 0 82
else if (upper && c >= 'A' && c <= 'Z') d = c - 'A' + 10; 81 1 82
413 31 ▶ else if (!upper && c >= 'a' && c <= 'z') d = c - 'a' + 10;
Branch: 3 branches
BranchTrueFalseTotal
else if (!upper && c >= 'a' && c <= 'z') d = c - 'a' + 10; 30 1 31
else if (!upper && c >= 'a' && c <= 'z') d = c - 'a' + 10; 30 0 30
else if (!upper && c >= 'a' && c <= 'z') d = c - 'a' + 10; 30 0 30
414 1 else return 0;
415 374 v = v * 36 + d;
416 }
417 371 ▶ for (unsigned short i = 1; i < width; i++) p *= 36;
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 1; i < width; i++) p *= 36; 286 85 371
418 456 ▶ for (unsigned short i = 0; i < width; i++) dec *= 10;
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < width; i++) dec *= 10; 371 85 456
419 85 ▶ *out = upper ? v - 10 * p + dec : v + 16 * p + dec;
Branch: 1 branch
BranchTrueFalseTotal
*out = upper ? v - 10 * p + dec : v + 16 * p + dec; 76 9 85
420 85 return 1;
421 }
422  
423 /*STR2NV_STRTOD() -- the strtod() that reads a whole NV. A perl built with
424 -Duselongdouble or -Dusequadmath has an NV wider than a double, and parsing
425 into a double first loses the bits that the wider type would have kept: 0.60
426 becomes 0.599999999999999978 once perl prints it back at full NV precision.
427 Perl's own Strtod() picks the right one, but it only exists from 5.22 on, so
428 older perls get the choice made here.*/
429 #ifdef Strtod
430 # define STR2NV_STRTOD(s, e) Strtod((s), (e))
431 #elif defined(USE_QUADMATH)
432 # define STR2NV_STRTOD(s, e) strtoflt128((s), (e))
433 #elif defined(USE_LONG_DOUBLE) && defined(HAS_STRTOLD)
434 # define STR2NV_STRTOD(s, e) strtold((s), (e))
435 #else
436 # define STR2NV_STRTOD(s, e) strtod((s), (e))
437 #endif
438  
439 /*str2nv_slow() -- whatever the fixed-point reader below declines: an exponent,
440 a hex float, inf/nan. strtod() on a stack copy, because the fields are
441 adjacent in the record (x ends where y begins, with no separator when a
442 coordinate is wide) and so strtod() cannot be pointed at the record buffer
443 itself.
444  
445 The number has to be the whole field, as it does for str2nv_fixed() and
446 str2iv(). strtod() stops at the first thing that is not part of a number and
447 reports what it read, and taking that is how a coordinate that overflowed its
448 eight columns became a wrong one: x = -1000.000 pushes its last digit into y's
449 columns, y reads '0-200.00', and the prefix made it 0 where the answer is that
450 the file does not say. Trailing blanks are still a number: an mmCIF value has
451 none, and a PDB field has them trimmed, but a caller handing one over is not
452 writing rubbish.*/
453 391 static bool str2nv_slow(const char *CSP_RESTRICT s, STRLEN n, NV *CSP_RESTRICT out)
454 {
455 /*64 is far above the eight columns a coordinate field has, and a longer
456 string is declined below rather than truncated into the buffer.*/
457 char buf[64], *end;
458 NV v;
459 391 ▶ if (n == 0 || n >= sizeof(buf)) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (n == 0 || n >= sizeof(buf)) return 0; 390 1 391
if (n == 0 || n >= sizeof(buf)) return 0; 0 390 390
460 390 memcpy(buf, s, n);
461 390 buf[n] = '\0';
462 390 errno = 0;
463 390 v = STR2NV_STRTOD(buf, &end);
464 390 ▶ if (end == buf) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (end == buf) return 0; 13 377 390
465 391 ▶ while (*end && isSPACE((unsigned char)*end)) end++;
Branch: 2 branches
BranchTrueFalseTotal
while (*end && isSPACE((unsigned char)*end)) end++; 29 362 391
while (*end && isSPACE((unsigned char)*end)) end++; 14 15 29
466 377 ▶ if (*end) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (*end) return 0; 15 362 377
467 362 *out = v;
468 362 return 1;
469 }
470  
471 /*str2nv_fixed() -- [+-]?digits[.digits], which is every number a coordinate
472 section actually contains. Worth a reader of its own because glibc's strtod()
473 was 22% of the instructions in a whole-file parse (____strtod_l_internal,
474 str_to_mpn, round_and_return): it is a fully general conversion -- locale, hex
475 floats, exponents, an arbitrary-precision slow path -- and none of that can
476 appear in a field eight columns wide.
477  
478 It returns 1 only on consuming the whole field, so anything it does not
479 understand falls through to str2nv_slow() and keeps its old meaning.
480  
481 What it produces is not an approximation of strtod(), it is the same NV bit for
482 bit, and the reasoning is worth keeping because a change here could silently
483 cost a digit. Both operands of the division are exact: the mantissa is
484 accumulated as an integer in an NV, and every integer up to 2**53 is exact even
485 on the narrowest NV perl configures (a plain double), which the fifteen-digit
486 cap stays well inside; 10**frac is exact for every power of ten to 10**22. An
487 IEEE 754 division of two exact operands is correctly rounded, and correctly
488 rounding the true decimal value is exactly what strtod() is required to return
489 -- so they agree, and agree the same way on a long double or __float128 perl.
490 Dividing by 10**frac rather than multiplying by 10**-frac is the part that has
491 to be this way round: 1e-3 is not representable, so multiplying would round
492 once into the reciprocal and again into the product.
493  
494 Leading zeros count against the cap, which costs a little generality that no
495 eight-column field could use, and buys the invariant that keeps the table index
496 in range: frac never exceeds the digit count, so it never exceeds the cap.
497  
498 "Correctly rounded" assumes the division is rounded once, to the NV. A compiler
499 whose FLT_EVAL_METHOD is 2 evaluates a double division in long double and
500 rounds that to double on the way out -- twice, which need not land where once
501 would. That is gcc on 32-bit x86, where the FPU is the x87: built with
502 perlbrew's 5.44.0-i686, whose NV is double, 103 of the 400,001 six-decimal
503 strings from 0.000000 to 0.400000 came back one ulp off strtod(), the first
504 being 0.002877, and none of the one- to five-decimal ones tried (every value
505 to 200 at one to three decimals, to 40 at four and to 4 at five). So on a
506 double-NV build that rounds double arithmetic wider, or will not say how it
507 does (-1), the fast path takes integers only, which are exact at any width, and
508 leaves every fraction to strtod(). A long double or __float128 NV is evaluated
509 at its own width there, and is unaffected.*/
510 #define STR2NV_MAX_DIGITS 15
511 #if defined(FLT_EVAL_METHOD) && (FLT_EVAL_METHOD < 0 || FLT_EVAL_METHOD > 1) \
512 && !defined(USE_LONG_DOUBLE) && !defined(USE_QUADMATH)
513 # define STR2NV_FAST_FRACTIONS FALSE //the division would round twice
514 #else
515 # define STR2NV_FAST_FRACTIONS TRUE
516 #endif
517 static const NV str2nv_pow10[STR2NV_MAX_DIGITS + 1] = {
518 1.0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7,
519 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15
520 };
521  
522 1116705 static bool str2nv_fixed(const char *CSP_RESTRICT s, STRLEN n, NV *CSP_RESTRICT out)
523 {
524 1116705 NV m = 0;
525 1116705 STRLEN i = 0, nd = 0, frac = 0;
526 1116705 bool neg = 0, dot = 0;
527  
528 1116705 ▶ if (n == 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) return 0; 1 1116704 1116705
529 1116704 ▶ if (s[0] == '+' || s[0] == '-') { neg = (s[0] == '-'); i = 1; }
Branch: 2 branches
BranchTrueFalseTotal
if (s[0] == '+' || s[0] == '-') { neg = (s[0] == '-'); i = 1; } 1116596 108 1116704
if (s[0] == '+' || s[0] == '-') { neg = (s[0] == '-'); i = 1; } 102737 1013859 1116596
530 6947562 ▶ for (; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (; i < n; i++) { 5830905 1116657 6947562
531 5830905 const char c = s[i];
532 5830905 ▶ if (c >= '0' && c <= '9') {
Branch: 2 branches
BranchTrueFalseTotal
if (c >= '0' && c <= '9') { 4714310 1116595 5830905
if (c >= '0' && c <= '9') { 4714283 27 4714310
533 4714283 ▶ if (++nd > STR2NV_MAX_DIGITS) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (++nd > STR2NV_MAX_DIGITS) return 0; 2 4714281 4714283
534 4714281 m = m * 10 + (NV)(c - '0');
535 4714281 ▶ if (dot) frac++;
Branch: 1 branch
BranchTrueFalseTotal
if (dot) frac++; 2902850 1811431 4714281
536 1116622 ▶ } else if (c == '.' && !dot) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (c == '.' && !dot) { 1116578 44 1116622
} else if (c == '.' && !dot) { 1116577 1 1116578
537 1116577 dot = 1;
538 } else {
539 45 return 0;//an exponent, a stray letter, the '*****' of an overflowed field
540 }
541 }
542 1116657 ▶ if (nd == 0) return 0;//"", "-", ".", "+."
Branch: 1 branch
BranchTrueFalseTotal
if (nd == 0) return 0;//"", "-", ".", "+." 5 1116652 1116657
543 1116652 ▶ if (frac) {
Branch: 1 branch
BranchTrueFalseTotal
if (frac) { 1116559 93 1116652
544 if (!STR2NV_FAST_FRACTIONS) return 0;
545 1116559 m /= str2nv_pow10[frac];
546 }
547 1116652 ▶ *out = neg ? -m : m;
Branch: 1 branch
BranchTrueFalseTotal
*out = neg ? -m : m; 102734 1013918 1116652
548 1116652 return 1;
549 }
550  
551 //str2nv() -- coordinates and the like
552 1116344 static bool str2nv(const char *CSP_RESTRICT s, STRLEN n, NV *CSP_RESTRICT out)
553 {
554 1116344 ▶ return str2nv_fixed(s, n, out) || str2nv_slow(s, n, out);
Branch: 2 branches
BranchTrueFalseTotal
return str2nv_fixed(s, n, out) || str2nv_slow(s, n, out); 30 1116314 1116344
return str2nv_fixed(s, n, out) || str2nv_slow(s, n, out); 15 15 30
555 }
556  
557 /*The two above are reachable individually from Perl as _str2nv_paths(), which
558 exists for t/numbers.t and asserts that they return the same NV bit for bit.
559 There is no other way to compare them: only one of the two is ever reached for
560 any given field, and Perl's own string-to-NV conversion cannot referee the
561 question because on an older -Duselongdouble perl Perl_my_atof is a hand-rolled
562 decimal accumulator rather than strtod(). _str2nv_fast_fractions() beside it
563 says whether this build lets the fast path take a fraction at all, so the test
564 knows which of the two to expect. The XSUBs are at the foot of the file with
565 the rest of them.*/
566  
567 705 static bool fld_iv(const char *CSP_RESTRICT line, STRLEN llen, STRLEN from, STRLEN to,
568 IV *CSP_RESTRICT out)
569 {
570 const char *s;
571 705 STRLEN n = fld(line, llen, from, to, &s);
572 705 ▶ return n ? str2iv(s, n, out) : FALSE;
Branch: 2 branches
BranchTrueFalseTotal
return n ? str2iv(s, n, out) : FALSE; 704 1 705
return n ? str2iv(s, n, out) : FALSE; 704 0 704
573 }
574  
575 /*the same for the two fields the format lets overflow into hybrid-36: the
576 serial number and the residue number*/
577 289449 static bool fld_hy36(const char *CSP_RESTRICT line, STRLEN llen, STRLEN from, STRLEN to,
578 IV *CSP_RESTRICT out)
579 {
580 const char *s;
581 289449 STRLEN n = fld(line, llen, from, to, &s);
582 289449 ▶ if (!n) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!n) return 0; 43 289406 289449
583 289406 ▶ return str2iv(s, n, out) || hy36_decode(s, n, (unsigned short)(to - from + 1), out);
Branch: 2 branches
BranchTrueFalseTotal
return str2iv(s, n, out) || hy36_decode(s, n, (unsigned short)(to - from + 1), out); 89 289317 289406
return str2iv(s, n, out) || hy36_decode(s, n, (unsigned short)(to - from + 1), out); 85 4 89
584 }
585  
586 543335 static bool fld_nv(const char *CSP_RESTRICT line, STRLEN llen, STRLEN from, STRLEN to,
587 NV *CSP_RESTRICT out){
588 const char *s;
589 543335 STRLEN n = fld(line, llen, from, to, &s);
590 543335 ▶ return n ? str2nv(s, n, out) : FALSE;
Branch: 2 branches
BranchTrueFalseTotal
return n ? str2nv(s, n, out) : FALSE; 543277 58 543335
return n ? str2nv(s, n, out) : FALSE; 543264 13 543277
591 }
592  
593 /*charge_ok() -- columns 79-80 hold a digit and a sign, '1+' as the format
594 writes it and '+1' as some programs do (4byf and 4ui0 in PDBbind v2020 write
595 '-1'; the caller turns those round). A file old enough to keep the entry id
596 in columns 73-80 has the tail of it here instead, and 'DR' is not a charge, nor
597 is '09'. A field that is not one reads as the empty string a blank field would
598 have given, which is the answer for "the file does not say".*/
599 144425 static bool charge_ok(const char *CSP_RESTRICT s, STRLEN n){
600 144425 ▶ if (n == 0 || n > 2) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (n == 0 || n > 2) return 0; 1496 142929 144425
if (n == 0 || n > 2) return 0; 0 1496 1496
601 1496 STRLEN digits = 0, signs = 0;
602 4480 ▶ for (STRLEN i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (STRLEN i = 0; i < n; i++) { 2986 1494 4480
603 2986 ▶ if (s[i] >= '0' && s[i] <= '9') digits++;
Branch: 2 branches
BranchTrueFalseTotal
if (s[i] >= '0' && s[i] <= '9') digits++; 2967 19 2986
if (s[i] >= '0' && s[i] <= '9') digits++; 2965 2 2967
604 21 ▶ else if (s[i] == '+' || s[i] == '-') signs++;
Branch: 2 branches
BranchTrueFalseTotal
else if (s[i] == '+' || s[i] == '-') signs++; 10 11 21
else if (s[i] == '+' || s[i] == '-') signs++; 8 2 10
605 2 else return 0;
606 }
607 1494 ▶ return digits <= 1 && signs <= 1;
Branch: 2 branches
BranchTrueFalseTotal
return digits <= 1 && signs <= 1; 23 1471 1494
return digits <= 1 && signs <= 1; 23 0 23
608 }
609  
610 /*nv_is_finite() -- x - x is 0 for a finite x and NaN for a NaN or an infinity,
611 which is the test without isfinite(), a C99 macro, or Perl_isinf(); see
612 grid_build() for why neither of those. str2nv() hands a field that says nan or
613 inf through as the NV it names, so everything that sums or compares
614 coordinates over a whole structure asks this first.*/
615 718372 static bool nv_is_finite(NV v){
616 718372 return v - v == 0.0;
617 }
618  
619 //the first n characters of a record name, compared without regard to case; kw
620 //is upper case
621 347729 static bool rec_is(const char *CSP_RESTRICT s, const char *CSP_RESTRICT kw, STRLEN n){
622 1059058 ▶ for (STRLEN i = 0; i < n; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (STRLEN i = 0; i < n; i++) 892642 166416 1059058
623 892642 ▶ if (toUPPER((unsigned char)s[i]) != kw[i]) return FALSE;
Branch: 2 branches
BranchTrueFalseTotal
if (toUPPER((unsigned char)s[i]) != kw[i]) return FALSE; 4 892638 892642
if (toUPPER((unsigned char)s[i]) != kw[i]) return FALSE; 181313 711329 892642
624 166416 return TRUE;
625 }
626  
627 /*pdb_coord_rec() -- whether a record is an ATOM or a HETATM, and the column its
628 serial number starts in.
629  
630 The record name is six columns and the serial the five after it. A writer
631 with more than 99,999 atoms to number lets the serial run leftwards into the
632 record name -- 'ATOM 100000' -- and every other column stays where it was; gemmi
633 0.7.5 reads such a line by its first four letters, as the atom it is, and so
634 does this, the serial taken from the digits that start in column 5 or 6. Those
635 atoms used to be filed as header records named 'ATOM 1' and missing from every
636 count. HETATM has no blank to give up and cannot be written that way. The name
637 is matched without regard to case, as gemmi matches it.*/
638 184889 static bool pdb_coord_rec(const char *CSP_RESTRICT line, STRLEN llen, bool *CSP_RESTRICT het,
639 STRLEN *CSP_RESTRICT serial_from){
640 184889 ▶ if (llen < 6) return FALSE;
Branch: 1 branch
BranchTrueFalseTotal
if (llen < 6) return FALSE; 864 184025 184889
641 184025 ▶ if (rec_is(line, "HETATM", 6)) { *het = TRUE; *serial_from = 6; return TRUE; }
Branch: 1 branch
BranchTrueFalseTotal
if (rec_is(line, "HETATM", 6)) { *het = TRUE; *serial_from = 6; return TRUE; } 21183 162842 184025
642 162842 ▶ if (!rec_is(line, "ATOM", 4)) return FALSE;
Branch: 1 branch
BranchTrueFalseTotal
if (!rec_is(line, "ATOM", 4)) return FALSE; 18453 144389 162842
643 144389 *het = FALSE;
644 144389 ▶ if (line[4] == ' ' && line[5] == ' ') { *serial_from = 6; return TRUE; }
Branch: 2 branches
BranchTrueFalseTotal
if (line[4] == ' ' && line[5] == ' ') { *serial_from = 6; return TRUE; } 144389 0 144389
if (line[4] == ' ' && line[5] == ' ') { *serial_from = 6; return TRUE; } 144388 1 144389
645 1 ▶ if (line[4] == ' ' && isDIGIT((unsigned char)line[5])) { *serial_from = 5; return TRUE; }
Branch: 2 branches
BranchTrueFalseTotal
if (line[4] == ' ' && isDIGIT((unsigned char)line[5])) { *serial_from = 5; return TRUE; } 1 0 1
if (line[4] == ' ' && isDIGIT((unsigned char)line[5])) { *serial_from = 5; return TRUE; } 1 0 1
646 0 ▶ if (isDIGIT((unsigned char)line[4]) && isDIGIT((unsigned char)line[5])) { *serial_from = 4; return TRUE; }
Branch: 2 branches
BranchTrueFalseTotal
if (isDIGIT((unsigned char)line[4]) && isDIGIT((unsigned char)line[5])) { *serial_from = 4; return TRUE; } 0 0 0
if (isDIGIT((unsigned char)line[4]) && isDIGIT((unsigned char)line[5])) { *serial_from = 4; return TRUE; } 0 0 0
647 0 return FALSE;
648 }
649  
650 /*guess_element() -- only when columns 77-78 are absent, which happens in
651 files written before the element column existed and in files written by
652 programs that should know better.
653  
654 The atom name is right-justified from column 14 for one-letter elements and
655 from column 13 for two-letter ones, so " CA " is a carbon alpha and "CA " is
656 a calcium. That rule is worth following exactly, because the alternative --
657 taking the first two letters -- turns every "HG11" hydrogen into mercury.*/
658 1940 static STRLEN guess_element(const char *CSP_RESTRICT raw, STRLEN rawlen,
659 char *CSP_RESTRICT buf)
660 {
661 1940 ▶ if (rawlen == 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (rawlen == 0) return 0; 0 1940 1940
662 /*A hydrogen with a long name -- HG11, HD22, HE21 -- fills all four columns
663 and starts in column 13, exactly where a two-letter element starts. Column
664 position alone cannot separate the two, so take the full field as the
665 tie-breaker: no two-letter element has a four character atom name, while
666 nearly every hydrogen past the first does. Without this, every HG11 in the
667 file becomes mercury.*/
668 1940 ▶ if (rawlen >= 4 && raw[0] != ' ' && raw[1] != ' ' && raw[2] != ' ' && raw[3] != ' '
Branch: 5 branches
BranchTrueFalseTotal
if (rawlen >= 4 && raw[0] != ' ' && raw[1] != ' ' && raw[2] != ' ' && raw[3] != ' ' 1940 0 1940
if (rawlen >= 4 && raw[0] != ' ' && raw[1] != ' ' && raw[2] != ' ' && raw[3] != ' ' 9 1931 1940
if (rawlen >= 4 && raw[0] != ' ' && raw[1] != ' ' && raw[2] != ' ' && raw[3] != ' ' 9 0 9
if (rawlen >= 4 && raw[0] != ' ' && raw[1] != ' ' && raw[2] != ' ' && raw[3] != ' ' 5 4 9
if (rawlen >= 4 && raw[0] != ' ' && raw[1] != ' ' && raw[2] != ' ' && raw[3] != ' ' 2 3 5
669 2 ▶ && (raw[0] == 'H' || raw[0] == 'D' || raw[0] == 'h' || raw[0] == 'd')) {
Branch: 4 branches
BranchTrueFalseTotal
&& (raw[0] == 'H' || raw[0] == 'D' || raw[0] == 'h' || raw[0] == 'd')) { 0 2 2
&& (raw[0] == 'H' || raw[0] == 'D' || raw[0] == 'h' || raw[0] == 'd')) { 0 0 0
&& (raw[0] == 'H' || raw[0] == 'D' || raw[0] == 'h' || raw[0] == 'd')) { 0 0 0
&& (raw[0] == 'H' || raw[0] == 'D' || raw[0] == 'h' || raw[0] == 'd')) { 0 0 0
670 2 ▶ buf[0] = (char)toUPPER((unsigned char)raw[0]);
Branch: 1 branch
BranchTrueFalseTotal
buf[0] = (char)toUPPER((unsigned char)raw[0]); 0 2 2
671 2 return 1;
672 }
673 /*a name that starts in column 13 with two letters is a two-letter element
674 (FE, ZN, CL, MG); a digit there is a hydrogen count (1HB)*/
675 1938 ▶ if (raw[0] != ' ' && isALPHA((unsigned char)raw[0])
Branch: 2 branches
BranchTrueFalseTotal
if (raw[0] != ' ' && isALPHA((unsigned char)raw[0]) 7 1931 1938
if (raw[0] != ' ' && isALPHA((unsigned char)raw[0]) 6 1 7
676 6 ▶ && rawlen >= 2 && isALPHA((unsigned char)raw[1])) {
Branch: 2 branches
BranchTrueFalseTotal
&& rawlen >= 2 && isALPHA((unsigned char)raw[1])) { 6 0 6
&& rawlen >= 2 && isALPHA((unsigned char)raw[1])) { 6 0 6
677 6 ▶ buf[0] = (char)toUPPER((unsigned char)raw[0]);
Branch: 1 branch
BranchTrueFalseTotal
buf[0] = (char)toUPPER((unsigned char)raw[0]); 0 6 6
678 6 ▶ buf[1] = (char)toUPPER((unsigned char)raw[1]);
Branch: 1 branch
BranchTrueFalseTotal
buf[1] = (char)toUPPER((unsigned char)raw[1]); 0 6 6
679 6 return 2;
680 }
681 { //otherwise the first letter in the field is the element
682 STRLEN i;
683 3867 ▶ for (i = 0; i < rawlen; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < rawlen; i++) { 3866 1 3867
684 3866 ▶ if (isALPHA((unsigned char)raw[i])) {
Branch: 1 branch
BranchTrueFalseTotal
if (isALPHA((unsigned char)raw[i])) { 1931 1935 3866
685 1931 ▶ buf[0] = (char)toUPPER((unsigned char)raw[i]);
Branch: 1 branch
BranchTrueFalseTotal
buf[0] = (char)toUPPER((unsigned char)raw[i]); 0 1931 1931
686 1931 return 1;
687 }
688 }
689 }
690 1 return 0;
691 }
692  
693 /*elem_case() -- the official spelling of an element symbol.
694  
695 Columns 77-78 are uppercase in the PDB format, mmCIF's type_symbol is uppercased
696 on the way in to match, and guess_element() uppercases what it takes from the
697 atom name, so a symbol arrives here as 'ZN' whichever of the three read it.
698 IUPAC writes it Zn, and a caller tallying elements wants the symbol rather than
699 the file's shouted version of it. Only the second letter is ever in question:
700 every symbol begins with a capital, and every one-letter symbol is that capital
701 by itself.
702  
703 A field that spells no element is left exactly as it came, so the 'XX' of a
704 broken file stays 'XX' instead of turning into a plausible-looking 'Xx'. D for
705 deuterium is left alone for the same reason -- the PDB writes it, IUPAC has no
706 symbol to correct it to, and the readers below test for it by name.
707  
708 The list is the 118 named elements of IUPAC's 2021 periodic table (the red book
709 table, https://iupac.org/what-we-do/periodic-table-of-elements/), less the
710 fourteen whose symbol is a single letter -- H B C N O F P S K V Y I W U -- which
711 need nothing done to them.*/
712 #define K2(a, b) (((U32)(a) << 8) | (U32)(b))
713  
714 224880 static void elem_case(char *CSP_RESTRICT buf, STRLEN n)
715 {
716 224880 ▶ if (n != 2) return;
Branch: 1 branch
BranchTrueFalseTotal
if (n != 2) return; 224188 692 224880
717 692 ▶ switch (K2((unsigned char)buf[0], (unsigned char)buf[1])) {
Branch: 1 branch
BranchTrueFalseTotal
switch (K2((unsigned char)buf[0], (unsigned char)buf[1])) { 687 5 692
718 687 case K2('H','E'): case K2('L','I'): case K2('B','E'): case K2('N','E'):
719 case K2('N','A'): case K2('M','G'): case K2('A','L'): case K2('S','I'):
720 case K2('C','L'): case K2('A','R'): case K2('C','A'): case K2('S','C'):
721 case K2('T','I'): case K2('C','R'): case K2('M','N'): case K2('F','E'):
722 case K2('C','O'): case K2('N','I'): case K2('C','U'): case K2('Z','N'):
723 case K2('G','A'): case K2('G','E'): case K2('A','S'): case K2('S','E'):
724 case K2('B','R'): case K2('K','R'): case K2('R','B'): case K2('S','R'):
725 case K2('Z','R'): case K2('N','B'): case K2('M','O'): case K2('T','C'):
726 case K2('R','U'): case K2('R','H'): case K2('P','D'): case K2('A','G'):
727 case K2('C','D'): case K2('I','N'): case K2('S','N'): case K2('S','B'):
728 case K2('T','E'): case K2('X','E'): case K2('C','S'): case K2('B','A'):
729 case K2('L','A'): case K2('C','E'): case K2('P','R'): case K2('N','D'):
730 case K2('P','M'): case K2('S','M'): case K2('E','U'): case K2('G','D'):
731 case K2('T','B'): case K2('D','Y'): case K2('H','O'): case K2('E','R'):
732 case K2('T','M'): case K2('Y','B'): case K2('L','U'): case K2('H','F'):
733 case K2('T','A'): case K2('R','E'): case K2('O','S'): case K2('I','R'):
734 case K2('P','T'): case K2('A','U'): case K2('H','G'): case K2('T','L'):
735 case K2('P','B'): case K2('B','I'): case K2('P','O'): case K2('A','T'):
736 case K2('R','N'): case K2('F','R'): case K2('R','A'): case K2('A','C'):
737 case K2('T','H'): case K2('P','A'): case K2('N','P'): case K2('P','U'):
738 case K2('A','M'): case K2('C','M'): case K2('B','K'): case K2('C','F'):
739 case K2('E','S'): case K2('F','M'): case K2('M','D'): case K2('N','O'):
740 case K2('L','R'): case K2('R','F'): case K2('D','B'): case K2('S','G'):
741 case K2('B','H'): case K2('H','S'): case K2('M','T'): case K2('D','S'):
742 case K2('R','G'): case K2('C','N'): case K2('N','H'): case K2('F','L'):
743 case K2('M','C'): case K2('L','V'): case K2('T','S'): case K2('O','G'):
744 687 ▶ buf[1] = (char)toLOWER((unsigned char)buf[1]);
Branch: 1 branch
BranchTrueFalseTotal
buf[1] = (char)toLOWER((unsigned char)buf[1]); 687 0 687
745 687 break;
746 5 default: break;//not a symbol: leave it as the file wrote it
747 }
748 }
749  
750 /*elem_symbol() -- whether n upper-case letters spell an element: one of the
751 fourteen one-letter symbols or D, which elem_case() keeps for deuterium, or one
752 of the two-letter ones, which are exactly the fields elem_case() changes.*/
753 1949 static bool elem_symbol(const char *CSP_RESTRICT buf, STRLEN n){
754 1949 ▶ if (n == 1) return memchr("HBCNOFPSKVYIWUD", buf[0], 15) != NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (n == 1) return memchr("HBCNOFPSKVYIWUD", buf[0], 15) != NULL; 1935 14 1949
755 14 ▶ if (n == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == 2) { 14 0 14
756 char t[2];
757 14 t[0] = buf[0];
758 14 t[1] = buf[1];
759 14 elem_case(t, 2);
760 14 return t[1] != buf[1];
761 }
762 0 return FALSE;
763 }
764  
765 /*guess_element_res() -- guess_element(), for a name in a residue named resname.
766  
767 guess_element() reads the symbol off where the name sits in its four columns,
768 which is right for a name in its proper place and gives a symbol that spells
769 nothing for one that is not: a zinc written ' ZN ' reads as Z, an 'HB1 ' or 'OXT '
770 started in column 13 as HB or OX, and every name read out of an mmCIF file,
771 which has no columns, is put in column 14 first -- so its ZN, MG and FE came back
772 Z, M and F. Two readings are tried before that one:
773  
774 * an atom named for its own residue, in two letters that spell an element, is
775 the ion of that element: ZN in ZN, NA in NA, CL in CL. A carbon alpha is
776 named CA in a residue called something else, so it is not taken for calcium.
777 * a guess that spells no element is read the other way: a one-letter one as
778 the two letters the name starts with (' ZN ' is Zn), a two-letter one as its
779 first letter ('HB1 ' is H).
780  
781 A guess that already spells an element is not second-guessed, so a name in its
782 proper place reads exactly as it did.*/
783 1947 static STRLEN guess_element_res(const char *CSP_RESTRICT raw, STRLEN rawlen,
784 const char *CSP_RESTRICT resname, STRLEN resname_len,
785 char *CSP_RESTRICT buf)
786 {
787 1947 STRLEN from = 0, to = rawlen, n;
788 3886 ▶ while (from < to && raw[from] == ' ') from++;
Branch: 2 branches
BranchTrueFalseTotal
while (from < to && raw[from] == ' ') from++; 3885 1 3886
while (from < to && raw[from] == ' ') from++; 1939 1946 3885
789 4178 ▶ while (to > from && raw[to - 1] == ' ') to--;
Branch: 2 branches
BranchTrueFalseTotal
while (to > from && raw[to - 1] == ' ') to--; 4177 1 4178
while (to > from && raw[to - 1] == ' ') to--; 2231 1946 4177
790 1947 ▶ if (to - from == 2 && resname_len == 2
Branch: 2 branches
BranchTrueFalseTotal
if (to - from == 2 && resname_len == 2 1656 291 1947
if (to - from == 2 && resname_len == 2 8 1648 1656
791 8 ▶ && isALPHA((unsigned char)raw[from]) && isALPHA((unsigned char)raw[from + 1])
Branch: 2 branches
BranchTrueFalseTotal
&& isALPHA((unsigned char)raw[from]) && isALPHA((unsigned char)raw[from + 1]) 8 0 8
&& isALPHA((unsigned char)raw[from]) && isALPHA((unsigned char)raw[from + 1]) 8 0 8
792 8 ▶ && toUPPER((unsigned char)raw[from]) == toUPPER((unsigned char)resname[0])
Branch: 3 branches
BranchTrueFalseTotal
&& toUPPER((unsigned char)raw[from]) == toUPPER((unsigned char)resname[0]) 0 8 8
&& toUPPER((unsigned char)raw[from]) == toUPPER((unsigned char)resname[0]) 0 8 8
&& toUPPER((unsigned char)raw[from]) == toUPPER((unsigned char)resname[0]) 7 1 8
793 7 ▶ && toUPPER((unsigned char)raw[from + 1]) == toUPPER((unsigned char)resname[1])) {
Branch: 3 branches
BranchTrueFalseTotal
&& toUPPER((unsigned char)raw[from + 1]) == toUPPER((unsigned char)resname[1])) { 0 7 7
&& toUPPER((unsigned char)raw[from + 1]) == toUPPER((unsigned char)resname[1])) { 0 7 7
&& toUPPER((unsigned char)raw[from + 1]) == toUPPER((unsigned char)resname[1])) { 7 0 7
794 char two[2];
795 7 ▶ two[0] = (char)toUPPER((unsigned char)raw[from]);
Branch: 1 branch
BranchTrueFalseTotal
two[0] = (char)toUPPER((unsigned char)raw[from]); 0 7 7
796 7 ▶ two[1] = (char)toUPPER((unsigned char)raw[from + 1]);
Branch: 1 branch
BranchTrueFalseTotal
two[1] = (char)toUPPER((unsigned char)raw[from + 1]); 0 7 7
797 7 ▶ if (elem_symbol(two, 2)) { buf[0] = two[0]; buf[1] = two[1]; return 2; }
Branch: 1 branch
BranchTrueFalseTotal
if (elem_symbol(two, 2)) { buf[0] = two[0]; buf[1] = two[1]; return 2; } 7 0 7
798 }
799 1940 n = guess_element(raw, rawlen, buf);
800 1940 ▶ if (n == 2 && !elem_symbol(buf, 2) && elem_symbol(buf, 1)) return 1;
Branch: 3 branches
BranchTrueFalseTotal
if (n == 2 && !elem_symbol(buf, 2) && elem_symbol(buf, 1)) return 1; 6 1934 1940
if (n == 2 && !elem_symbol(buf, 2) && elem_symbol(buf, 1)) return 1; 2 4 6
if (n == 2 && !elem_symbol(buf, 2) && elem_symbol(buf, 1)) return 1; 2 0 2
801 1938 ▶ if (n == 1 && !elem_symbol(buf, 1)) {
Branch: 2 branches
BranchTrueFalseTotal
if (n == 1 && !elem_symbol(buf, 1)) { 1933 5 1938
if (n == 1 && !elem_symbol(buf, 1)) { 1 1932 1933
802 1 STRLEN i = from;
803 1 ▶ while (i < to && !isALPHA((unsigned char)raw[i])) i++;
Branch: 2 branches
BranchTrueFalseTotal
while (i < to && !isALPHA((unsigned char)raw[i])) i++; 1 0 1
while (i < to && !isALPHA((unsigned char)raw[i])) i++; 0 1 1
804 1 ▶ if (i + 1 < to && isALPHA((unsigned char)raw[i + 1])) {
Branch: 2 branches
BranchTrueFalseTotal
if (i + 1 < to && isALPHA((unsigned char)raw[i + 1])) { 1 0 1
if (i + 1 < to && isALPHA((unsigned char)raw[i + 1])) { 1 0 1
805 char two[2];
806 1 ▶ two[0] = (char)toUPPER((unsigned char)raw[i]);
Branch: 1 branch
BranchTrueFalseTotal
two[0] = (char)toUPPER((unsigned char)raw[i]); 0 1 1
807 1 ▶ two[1] = (char)toUPPER((unsigned char)raw[i + 1]);
Branch: 1 branch
BranchTrueFalseTotal
two[1] = (char)toUPPER((unsigned char)raw[i + 1]); 0 1 1
808 1 ▶ if (elem_symbol(two, 2)) { buf[0] = two[0]; buf[1] = two[1]; return 2; }
Branch: 1 branch
BranchTrueFalseTotal
if (elem_symbol(two, 2)) { buf[0] = two[0]; buf[1] = two[1]; return 2; } 1 0 1
809 }
810 }
811 1937 return n;
812 }
813  
814 /*elem_bump() -- add one to a tally kept in a hash.
815  
816 Written out rather than left to sv_inc() so that the count is a UV: these are
817 counted up from nothing and never down, an IV would promise a sign the tally
818 cannot have, and a Perl caller printing one gets the same digits either way.*/
819 316506 static void elem_bump(pTHX_ HV *CSP_RESTRICT tally, const char *CSP_RESTRICT sym, STRLEN len)
820 {
821 316506 SV **cnt = hv_fetch(tally, sym, (I32)len, 1);
822 316506 ▶ if (cnt && *cnt) sv_setuv(*cnt, SvOK(*cnt) ? SvUV(*cnt) + 1 : 1);
Branch: 3 branches
BranchTrueFalseTotal
if (cnt && *cnt) sv_setuv(*cnt, SvOK(*cnt) ? SvUV(*cnt) + 1 : 1); 316506 0 316506
if (cnt && *cnt) sv_setuv(*cnt, SvOK(*cnt) ? SvUV(*cnt) + 1 : 1); 316506 0 316506
if (cnt && *cnt) sv_setuv(*cnt, SvOK(*cnt) ? SvUV(*cnt) + 1 : 1); 305212 11294 316506
823 316506 }
824  
825 /*csp_str() -- one of the short, endlessly repeated strings of an atom record:
826 its name, altloc, residue name, chain, insertion code, element and charge.
827  
828 Made as a shared hash key SV rather than with newSVpvn(), so that it points at
829 perl's one copy of the string instead of owning a buffer of its own. Every
830 atom has seven of these and the file has a few hundred distinct values among
831 all of them, so what that saves is seven mallocs an atom and the few dozen bytes
832 each one costs -- which was the largest thing in the parse's profile, ahead of
833 any of the arithmetic. Measured on 4fqr (PDBbind v2020, 90,792 atoms), gcc -O2,
834 perl 5.44.0, best of ten: the columnar parse from 0.109 s to 0.068 s and its
835 peak memory from 113 MB to 92 MB; with atom_hashes from 0.087 s to 0.070 s and
836 130 MB to 105 MB; structure_info(features => 0) over 200 files of the set from
837 5.18 s to 4.38 s, best of three.
838  
839 Nothing about the value changes for a caller. The SV is an ordinary writable
840 string -- perl copies it out of the shared table the first time anything
841 modifies it -- and it compares, stringifies and hashes exactly as the
842 newSVpvn() one did. Copying it into another SV or using it as a hash key, which
843 the Perl half does with most of them, is cheaper than it was, because the
844 shared string is shared again rather than copied.*/
845 743642 static SV *csp_str(pTHX_ const char *CSP_RESTRICT s, STRLEN n){
846 743642 return newSVpvn_share(s, (I32)n, 0);
847 }
848  
849 /*sub_hv() -- the hash under a key, made on first use. Two levels of these are
850 what the per-chain tallies hang from; the same shape as the meta table below,
851 which grows an array under a record name the same way.*/
852 45926 static HV *sub_hv(pTHX_ HV *CSP_RESTRICT parent, const char *CSP_RESTRICT key, STRLEN klen){
853 45926 SV **slot = hv_fetch(parent, key, (I32)klen, 0);
854 HV *h;
855 45926 ▶ if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVHV)
Branch: 4 branches
BranchTrueFalseTotal
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVHV) 42692 3234 45926
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVHV) 42692 0 42692
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVHV) 42692 0 42692
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVHV) 42692 0 42692
856 42692 return (HV *)SvRV(*slot);
857 3234 h = newHV();
858 3234 (void)hv_store(parent, key, (I32)klen, newRV_noinc((SV *)h), 0);
859 3234 return h;
860 }
861  
862 /*chain_tally() -- the element tally of one chain of one model.
863  
864 Kept per model as well as per chain because with model => 'all' the same chain
865 id is a different chain in each model and Perl builds them separately; with the
866 default model => 1 there is only ever the one key. The model number is spelled
867 here the way Perl spells it when it looks the chain up, which is what a decimal
868 IV stringifies to on both sides.
869  
870 Reached once per residue rather than once per atom -- chain and model are both
871 part of a residue's identity, so neither can change without the readers below
872 noticing a new residue -- which leaves the per-atom cost at the one hash
873 increment the whole-structure tally already costs.*/
874 22963 static HV *chain_tally(pTHX_ HV *CSP_RESTRICT root, IV model, const char *CSP_RESTRICT chain, STRLEN chain_len){
875 char mbuf[32];//an IV prints in at most 21 characters, sign included
876 22963 STRLEN mlen = (STRLEN)my_snprintf(mbuf, sizeof(mbuf), "%" IVdf, model);
877 22963 return sub_hv(aTHX_ sub_hv(aTHX_ root, mbuf, mlen), chain, chain_len);
878 }
879  
880 //options
881 19555 static SV *opt_get(pTHX_ HV *CSP_RESTRICT o, const char *CSP_RESTRICT k){
882 19555 ▶ if (!o) return NULL;
Branch: 1 branch
BranchTrueFalseTotal
if (!o) return NULL; 12 19543 19555
883 SV **p;
884 19543 p = hv_fetch(o, k, (I32)strlen(k), 0);
885 19543 ▶ return (p && *p && SvOK(*p)) ? *p : NULL;
Branch: 3 branches
BranchTrueFalseTotal
return (p && *p && SvOK(*p)) ? *p : NULL; 17597 1946 19543
return (p && *p && SvOK(*p)) ? *p : NULL; 17597 0 17597
return (p && *p && SvOK(*p)) ? *p : NULL; 17597 0 17597
886 }
887  
888 2521 static IV opt_iv(pTHX_ HV *CSP_RESTRICT o, const char *CSP_RESTRICT k, IV dflt){
889 2521 SV *v = opt_get(aTHX_ o, k);
890 2521 ▶ return v ? SvIV(v) : dflt;
Branch: 1 branch
BranchTrueFalseTotal
return v ? SvIV(v) : dflt; 2402 119 2521
891 }
892  
893 /*A switch given as undef is off, as it is in the Perl half (%SWITCH in
894 Parser.pm): hydrogens => $keep with $keep unset means the caller did not ask
895 for them. opt_get() treats undef as not given, which for a switch whose
896 default is on would turn it on, so a key that is present is read here.*/
897 23786 static bool opt_bool(pTHX_ HV *CSP_RESTRICT o, const char *CSP_RESTRICT k, bool dflt){
898 SV **p;
899 23786 ▶ if (!o) return dflt;
Branch: 1 branch
BranchTrueFalseTotal
if (!o) return dflt; 52 23734 23786
900 23734 p = hv_fetch(o, k, (I32)strlen(k), 0);
901 23734 ▶ if (!p || !*p) return dflt;
Branch: 2 branches
BranchTrueFalseTotal
if (!p || !*p) return dflt; 20126 3608 23734
if (!p || !*p) return dflt; 0 20126 20126
902 20126 return SvTRUE(*p) ? TRUE : FALSE;
903 }
904  
905 //the parse
906 #define NCOL 17 //parallel per-atom columns
907 static const char *const col_name[NCOL] = {
908 "serial", "name", "altloc", "resname", "chain", "resseq", "icode",
909 "x", "y", "z", "occupancy", "bfactor", "element", "charge",
910 "het", "model", "line"
911 };
912 enum {
913 C_SERIAL, C_NAME, C_ALTLOC, C_RESNAME, C_CHAIN, C_RESSEQ, C_ICODE,
914 C_X, C_Y, C_Z, C_OCC, C_B, C_ELEMENT, C_CHARGE, C_HET, C_MODEL, C_LINENO
915 };
916  
917 /*The per-residue sums, kept as sums rather than means so that Perl can add
918 two of them together: a residue whose atoms are written in two runs -- an
919 alternate conformer group split apart, a ligand interleaved with the polymer
920 -- arrives here as two entries and is one residue by the time Perl is done
921 with it. Means computed here could not be recombined without the counts, and
922 with the counts they may as well be sums.*/
923 #define NRSUM 6
924 static const char *const res_sum_name[NRSUM] = { "sx", "sy", "sz", "n_xyz", "sb", "n_b" };
925 enum { R_SX, R_SY, R_SZ, R_NXYZ, R_SB, R_NB };
926  
927 22963 static void flush_residue(pTHX_ AV **CSP_RESTRICT rs, NV sx, NV sy, NV sz, UV nc, NV sb, UV nb){
928 22963 ▶ av_push(rs[R_SX], nc ? newSVnv(sx) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(rs[R_SX], nc ? newSVnv(sx) : newSV(0)); 22953 10 22963
929 22963 ▶ av_push(rs[R_SY], nc ? newSVnv(sy) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(rs[R_SY], nc ? newSVnv(sy) : newSV(0)); 22953 10 22963
930 22963 ▶ av_push(rs[R_SZ], nc ? newSVnv(sz) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(rs[R_SZ], nc ? newSVnv(sz) : newSV(0)); 22953 10 22963
931 22963 av_push(rs[R_NXYZ], newSVuv(nc));
932 22963 ▶ av_push(rs[R_SB], nb ? newSVnv(sb) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(rs[R_SB], nb ? newSVnv(sb) : newSV(0)); 22894 69 22963
933 22963 av_push(rs[R_NB], newSVuv(nb));
934 22963 }
935  
936 /*The eleven keys of an atom hash, and what each one's hash is.
937  
938 Every atom the parse builds a hash for gets the same eleven keys, and hv_stores()
939 works out the hash of a constant key afresh on every call: eleven string hashes
940 an atom, a million of them over 4fqr. They are worked out once per parse here
941 instead and handed to hv_store(), which takes a precomputed hash for exactly
942 this. PERL_HASH() is run at parse time and not frozen into the source, because
943 the hash function is seeded per process.*/
944 #define NAKEY 11
945 static const char *const akey_name[NAKEY] = {
946 "name", "serial", "altloc", "x", "y", "z", "occupancy", "bfactor",
947 "element", "charge", "hetero"
948 };
949 enum {
950 AK_NAME, AK_SERIAL, AK_ALTLOC, AK_X, AK_Y, AK_Z, AK_OCC, AK_B,
951 AK_ELEMENT, AK_CHARGE, AK_HETERO
952 };
953 typedef struct {
954 U32 hash[NAKEY];
955 I32 len[NAKEY];
956 } atom_keys;
957  
958 1144 static void atom_keys_init(pTHX_ atom_keys *CSP_RESTRICT k){
959 13728 ▶ for (unsigned short i = 0; i < NAKEY; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < NAKEY; i++) { 12584 1144 13728
960 12584 k->len[i] = (I32)strlen(akey_name[i]);
961 12584 ▶ PERL_HASH(k->hash[i], akey_name[i], k->len[i]);
Branch: 1 branch
BranchTrueFalseTotal
PERL_HASH(k->hash[i], akey_name[i], k->len[i]); 12584 0 12584
962 }
963 1144 }
964  
965 /*one atom's fields, as both readers hand them to atom_hash()*/
966 typedef struct {
967 SV *name;//the shared-key name SV, which filer_atom() keys on
968 const char *alt, *el, *chg;
969 STRLEN alt_n, el_n, chg_n;
970 IV serial;
971 NV x, y, z, occ, b;
972 bool have_serial, have_xyz, have_occ, have_b, het;
973 } atom_fields;
974  
975 /*atom_hash() -- the atom's hash, built the one way both readers build it.
976  
977 Pre-split to sixteen buckets. A fresh hash has eight and an atom has eleven
978 keys, twelve with its altlocs, so every atom hash was split and rehashed once on
979 the way to being filled; asking for the sixteen up front is the size it ends at
980 anyway, so it costs no memory and saves the split.*/
981 155266 static HV *atom_hash(pTHX_ const atom_keys *CSP_RESTRICT k, const atom_fields *CSP_RESTRICT f){
982 155266 HV *a = newHV();
983 155266 hv_ksplit(a, 16);
984 #define AK_STORE(i, v) (void)hv_store(a, akey_name[i], k->len[i], (v), k->hash[i])
985 155266 AK_STORE(AK_NAME, f->name);
986 155266 ▶ AK_STORE(AK_SERIAL, f->have_serial ? newSViv(f->serial) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
AK_STORE(AK_SERIAL, f->have_serial ? newSViv(f->serial) : newSV(0)); 155265 1 155266
987 155266 AK_STORE(AK_ALTLOC, csp_str(aTHX_ f->alt, f->alt_n));
988 155266 ▶ AK_STORE(AK_X, f->have_xyz ? newSVnv(f->x) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
AK_STORE(AK_X, f->have_xyz ? newSVnv(f->x) : newSV(0)); 155262 4 155266
989 155266 ▶ AK_STORE(AK_Y, f->have_xyz ? newSVnv(f->y) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
AK_STORE(AK_Y, f->have_xyz ? newSVnv(f->y) : newSV(0)); 155262 4 155266
990 155266 ▶ AK_STORE(AK_Z, f->have_xyz ? newSVnv(f->z) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
AK_STORE(AK_Z, f->have_xyz ? newSVnv(f->z) : newSV(0)); 155262 4 155266
991 155266 ▶ AK_STORE(AK_OCC, f->have_occ ? newSVnv(f->occ) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
AK_STORE(AK_OCC, f->have_occ ? newSVnv(f->occ) : newSV(0)); 155219 47 155266
992 155266 ▶ AK_STORE(AK_B, f->have_b ? newSVnv(f->b) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
AK_STORE(AK_B, f->have_b ? newSVnv(f->b) : newSV(0)); 155217 49 155266
993 155266 AK_STORE(AK_ELEMENT, csp_str(aTHX_ f->el, f->el_n));
994 155266 AK_STORE(AK_CHARGE, csp_str(aTHX_ f->chg, f->chg_n));
995 155266 AK_STORE(AK_HETERO, newSViv(f->het));
996 #undef AK_STORE
997 155266 return a;
998 }
999  
1000 /*Filing the atoms into their residues, as the parse builds them.
1001  
1002 Chem::Structure::Parser's residue hash holds its atoms by name, with an
1003 atom_order beside them, and an atom written twice under one name -- the
1004 alternate conformers of a disordered side chain -- is one atom with every
1005 conformer on its altlocs list. That used to be done in Perl, one atom at a
1006 time over the atom hashes the parse had just built, and it was a fifth of a
1007 read with features => 0: 0.045 s of 4fqr's. It is done here instead, where
1008 the atoms are, for 0.018 s of the parse, and 60 entries of PDBbind v2020 read
1009 with features => 0 went from 1.17 s to 1.00 s, best of three. The rules are
1010 the same:
1011  
1012 * the first record under a name is the atom; a later one is a conformer of
1013 it, and both go on the list -- the first when the second turns up, since
1014 the first record of a pair may have no altloc letter at all (Biopython's
1015 disordered.pdb writes ARG 27's CZ that way).
1016 * an atom that has an altloc letter has the list even when it is the only
1017 conformer, so "was this modelled twice?" is one question.
1018 * with altloc => 'highest', a later conformer of higher occupancy supplies
1019 the atom's altloc, serial, coordinates, occupancy and B-factor.
1020  
1021 A residue is keyed as assemble() keys it -- model, chain, and the residue number
1022 with its insertion code -- because one can be met twice, an altloc group
1023 written apart or a ligand interleaved with the polymer, and the two runs are
1024 one residue with one set of atoms. The key has to be assemble()'s to the
1025 byte, or a run would be filed where assemble() does not look; t/options.t
1026 reads both shapes of every fixture and compares them.*/
1027 typedef struct {
1028 HV *index;//residue key -> the run index its containers were made at
1029 AV *res_atoms;//per run: a reference to its residue's atoms hash
1030 AV *res_order;//per run: a reference to its residue's atom_order
1031 HV *cur_atoms;//the current run's two, which it shares with its residue
1032 AV *cur_order;
1033 bool highest;//altloc => 'highest'
1034 atom_keys keys;//the atom hash's keys, hashed once; see atom_keys_init()
1035 } atom_filer;
1036  
1037 1144 static void filer_init(pTHX_ atom_filer *CSP_RESTRICT f, bool highest){
1038 1144 atom_keys_init(aTHX_ &f->keys);
1039 1144 f->index = newHV();
1040 1144 f->res_atoms = newAV();
1041 1144 f->res_order = newAV();
1042 1144 f->cur_atoms = NULL;
1043 1144 f->cur_order = NULL;
1044 1144 f->highest = highest;
1045 1144 }
1046  
1047 /*run_key() -- the key a residue run is filed under, and whether it is a residue
1048 of its own that shares its chain, number and insertion code with an earlier one.
1049  
1050 Runs that share those three are one residue -- an altloc group written apart, a
1051 ligand interleaved with the polymer -- and are filed together, here and in the
1052 Perl half. The exception is a run of another residue name, whose first record
1053 has no altloc letter, where one of the two is a HETATM: a water written after
1054 TER under the protein's chain and a number the protein already used, or a
1055 docked ligand numbered 1 in the protein's chain. The archive never writes one;
1056 other programs do, and it used to vanish into the residue it collided with, its
1057 atoms filed as that residue's conformers.
1058  
1059 Both conditions are other readers'. Biopython 1.85 identifies a residue by its
1060 hetero field, number and insertion code, and the hetero field of a HETATM
1061 residue is its name ('H_LIG', or 'W' for a water) where an ATOM residue's is
1062 blank -- so it keeps an ATOM and a HETATM residue apart, and two HETATM residues
1063 of different names, as gemmi 0.7.5 does; two ATOM residues under one number are
1064 one residue to it, which is the reading t/foreign.t takes from its
1065 a_structure.pdb. And one residue modelled in two chemical states writes every
1066 record of the second with an altloc letter -- 3zeu's MSE/MET, 2ftm's IAS/ASP,
1067 5nai's CSD/CYS, 5za2's SEP/SER and 6e4z's NEP/HIP all start each run with one --
1068 which keeps those one residue here, as they always were.
1069  
1070 The key is the model, a NUL, the chain, a NUL, and the number and insertion
1071 code as Perl stringifies them. The NULs cannot be in a chain id read off a
1072 record line, which is what makes the three fields one unambiguous key. A run
1073 that is apart has a NUL and its residue name on the end, so that the next run of
1074 the same residue finds it. seen maps each key to 'H' or 'A', for the record
1075 type the residue was first filed under, followed by its residue name. An IV
1076 prints in at most 21 characters, so 64 holds either number.*/
1077 22963 static SV *run_key(pTHX_ HV *CSP_RESTRICT seen, IV model, const char *CSP_RESTRICT chain,
1078 STRLEN chain_len, bool have_rs, IV rs, const char *CSP_RESTRICT icode,
1079 const char *CSP_RESTRICT resname, STRLEN resname_len, bool het,
1080 bool lettered, bool *CSP_RESTRICT apart)
1081 {
1082 char head[64];
1083 22963 SV *key = sv_2mortal(newSVpvs(""));
1084 SV **slot;
1085 22963 STRLEN hn = (STRLEN)my_snprintf(head, sizeof(head), "%" IVdf, model);
1086 22963 sv_catpvn(key, head, hn);
1087 22963 sv_catpvn(key, "\0", 1);
1088 22963 sv_catpvn(key, chain, chain_len);
1089 22963 sv_catpvn(key, "\0", 1);
1090 22963 ▶ if (have_rs) {
Branch: 1 branch
BranchTrueFalseTotal
if (have_rs) { 22928 35 22963
1091 22928 hn = (STRLEN)my_snprintf(head, sizeof(head), "%" IVdf, rs);
1092 22928 sv_catpvn(key, head, hn);
1093 }
1094 22963 sv_catpv(key, icode);
1095 22963 *apart = FALSE;
1096 22963 slot = hv_fetch(seen, SvPVX(key), (I32)SvCUR(key), 0);
1097 22963 ▶ if (!slot || !*slot) {
Branch: 2 branches
BranchTrueFalseTotal
if (!slot || !*slot) { 27 22936 22963
if (!slot || !*slot) { 0 27 27
1098 22936 ▶ SV *first = newSVpvn(het ? "H" : "A", 1);
Branch: 1 branch
BranchTrueFalseTotal
SV *first = newSVpvn(het ? "H" : "A", 1); 5846 17090 22936
1099 22936 sv_catpvn(first, resname, resname_len);
1100 22936 (void)hv_store(seen, SvPVX(key), (I32)SvCUR(key), first, 0);
1101 22936 return key;
1102 }
1103 27 ▶ if (lettered) return key;
Branch: 1 branch
BranchTrueFalseTotal
if (lettered) return key; 2 25 27
1104 25 ▶ if (SvCUR(*slot) == resname_len + 1 && memcmp(SvPVX(*slot) + 1, resname, resname_len) == 0)
Branch: 2 branches
BranchTrueFalseTotal
if (SvCUR(*slot) == resname_len + 1 && memcmp(SvPVX(*slot) + 1, resname, resname_len) == 0) 25 0 25
if (SvCUR(*slot) == resname_len + 1 && memcmp(SvPVX(*slot) + 1, resname, resname_len) == 0) 6 19 25
1105 6 return key;
1106 19 ▶ if (!het && SvPVX(*slot)[0] == 'A') return key;//two ATOM residues: one, to Biopython
Branch: 2 branches
BranchTrueFalseTotal
if (!het && SvPVX(*slot)[0] == 'A') return key;//two ATOM residues: one, to Biopython 2 17 19
if (!het && SvPVX(*slot)[0] == 'A') return key;//two ATOM residues: one, to Biopython 2 0 2
1107 17 *apart = TRUE;
1108 17 sv_catpvn(key, "\0", 1);
1109 17 sv_catpvn(key, resname, resname_len);
1110 17 return key;
1111 }
1112  
1113 //a residue run begins, under the key run_key() gave it
1114 22288 static void filer_run(pTHX_ atom_filer *CSP_RESTRICT f, SV *CSP_RESTRICT key)
1115 {
1116 22288 SV **slot = hv_fetch(f->index, SvPVX(key), (I32)SvCUR(key), 0);
1117 22288 ▶ if (slot && *slot) {
Branch: 2 branches
BranchTrueFalseTotal
if (slot && *slot) { 8 22280 22288
if (slot && *slot) { 8 0 8
1118 8 const SSize_t at = (SSize_t)SvIV(*slot);
1119 8 SV **a = av_fetch(f->res_atoms, at, 0);
1120 8 SV **o = av_fetch(f->res_order, at, 0);
1121 8 f->cur_atoms = (HV *)SvRV(*a);
1122 8 f->cur_order = (AV *)SvRV(*o);
1123 } else {
1124 22280 (void)hv_store(f->index, SvPVX(key), (I32)SvCUR(key),
1125 newSViv((IV)(av_len(f->res_atoms) + 1)), 0);
1126 22280 f->cur_atoms = newHV();
1127 22280 f->cur_order = newAV();
1128 22280 av_push(f->res_atoms, newRV_noinc((SV *)f->cur_atoms));
1129 22280 av_push(f->res_order, newRV_noinc((SV *)f->cur_order));
1130 22280 return;
1131 }
1132 8 av_push(f->res_atoms, newRV_inc((SV *)f->cur_atoms));
1133 8 av_push(f->res_order, newRV_inc((SV *)f->cur_order));
1134 }
1135  
1136 //the seven fields that differ between conformers, in _conformer()'s order
1137 static const char *const conf_field[7] = {
1138 "altloc", "serial", "x", "y", "z", "occupancy", "bfactor"
1139 };
1140  
1141 //one conformer's worth of an atom, for the altlocs list: copies, not aliases
1142 704 static SV *conformer(pTHX_ HV *CSP_RESTRICT a){
1143 704 HV *c = newHV();
1144 5632 ▶ for (unsigned short k = 0; k < 7; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < 7; k++) { 4928 704 5632
1145 4928 SV **v = hv_fetch(a, conf_field[k], (I32)strlen(conf_field[k]), 0);
1146 4928 ▶ (void)hv_store(c, conf_field[k], (I32)strlen(conf_field[k]),
Branch: 2 branches
BranchTrueFalseTotal
(void)hv_store(c, conf_field[k], (I32)strlen(conf_field[k]), 4928 0 4928
(void)hv_store(c, conf_field[k], (I32)strlen(conf_field[k]), 4928 0 4928
1147 v && *v ? newSVsv(*v) : newSV(0), 0);
1148 }
1149 704 return newRV_noinc((SV *)c);
1150 }
1151  
1152 /*a new atom hash, a, into the current run's residue. name is the shared-key
1153 string a was given as its name, and alt_len the length of its altloc.
1154  
1155 One hash operation an atom, not two: the slot is fetched for storing into, and
1156 the name's hash is the one its shared key already carries. Not restrict: a and
1157 name are both reachable through the residue hash once a has been filed there.*/
1158 155266 static void filer_atom(pTHX_ atom_filer *CSP_RESTRICT f, HV *a, SV *name, STRLEN alt_len, bool have_occ, NV occ){
1159 155266 HE *he = hv_fetch_ent(f->cur_atoms, name, 1, SvSHARED_HASH(name));
1160 155266 SV *slot = HeVAL(he), **list, **ho;
1161 HV *h;
1162 AV *l;
1163 155266 ▶ if (!SvOK(slot)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(slot)) { 154917 349 155266
1164 /*the new slot made into a reference to a, as newRV_inc() would make
1165 one. SVt_RV, not SVt_IV: a reference had a type of its own before
1166 5.12, and a 5.10 slot upgraded no further than an IV is a reference
1167 sv_clear() does not know to let go of. Later perls define SVt_RV as
1168 SVt_IV for exactly this use.*/
1169 154917 ▶ SvUPGRADE(slot, SVt_RV);
Branch: 1 branch
BranchTrueFalseTotal
SvUPGRADE(slot, SVt_RV); 154917 0 154917
1170 154917 SvRV_set(slot, SvREFCNT_inc_simple_NN((SV *)a));
1171 154917 SvROK_on(slot);
1172 154917 av_push(f->cur_order, newSVsv(name));
1173 154917 ▶ if (alt_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (alt_len) { 348 154569 154917
1174 348 l = newAV();
1175 348 av_push(l, conformer(aTHX_ a));
1176 348 (void)hv_stores(a, "altlocs", newRV_noinc((SV *)l));
1177 }
1178 154917 return;
1179 }
1180 349 h = (HV *)SvRV(slot);
1181 349 list = hv_fetchs(h, "altlocs", 0);
1182 349 ▶ if (list && *list && SvROK(*list)) {
Branch: 3 branches
BranchTrueFalseTotal
if (list && *list && SvROK(*list)) { 342 7 349
if (list && *list && SvROK(*list)) { 342 0 342
if (list && *list && SvROK(*list)) { 342 0 342
1183 342 l = (AV *)SvRV(*list);
1184 } else {
1185 7 l = newAV();
1186 7 av_push(l, conformer(aTHX_ h));
1187 7 (void)hv_stores(h, "altlocs", newRV_noinc((SV *)l));
1188 }
1189 349 av_push(l, conformer(aTHX_ a));
1190 349 ▶ if (!f->highest || !have_occ) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!f->highest || !have_occ) return; 4 345 349
if (!f->highest || !have_occ) return; 0 4 4
1191 4 ho = hv_fetchs(h, "occupancy", 0);
1192 4 ▶ if (!ho || !*ho || !SvOK(*ho) || !(occ > SvNV(*ho))) return;
Branch: 4 branches
BranchTrueFalseTotal
if (!ho || !*ho || !SvOK(*ho) || !(occ > SvNV(*ho))) return; 4 0 4
if (!ho || !*ho || !SvOK(*ho) || !(occ > SvNV(*ho))) return; 4 0 4
if (!ho || !*ho || !SvOK(*ho) || !(occ > SvNV(*ho))) return; 4 0 4
if (!ho || !*ho || !SvOK(*ho) || !(occ > SvNV(*ho))) return; 0 4 4
1193 32 ▶ for (unsigned short k = 0; k < 7; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < 7; k++) { 28 4 32
1194 28 SV **v = hv_fetch(a, conf_field[k], (I32)strlen(conf_field[k]), 0);
1195 28 ▶ (void)hv_store(h, conf_field[k], (I32)strlen(conf_field[k]),
Branch: 2 branches
BranchTrueFalseTotal
(void)hv_store(h, conf_field[k], (I32)strlen(conf_field[k]), 28 0 28
(void)hv_store(h, conf_field[k], (I32)strlen(conf_field[k]), 28 0 28
1196 v && *v ? newSVsv(*v) : newSV(0), 0);
1197 }
1198 }
1199  
1200 //the two arrays into the parse's output, and the index freed
1201 1144 static void filer_done(pTHX_ atom_filer *CSP_RESTRICT f, HV *CSP_RESTRICT out){
1202 1144 (void)hv_stores(out, "res_atoms", newRV_noinc((SV *)f->res_atoms));
1203 1144 (void)hv_stores(out, "res_order", newRV_noinc((SV *)f->res_order));
1204 1144 SvREFCNT_dec((SV *)f->index);
1205 1144 }
1206  
1207 /*The chains option, as the set of chain ids to keep, or NULL for every chain.
1208  
1209 Both readers ask it about every atom, in the middle of the parse, when a die
1210 would leave everything built so far unreachable -- and a tied hash can die in
1211 EXISTS. A plain hash cannot, and a plain hash is all the Perl half ever
1212 passes, so anything with magic on it is refused here, while the options are
1213 being read and nothing has been allocated. _parse_string() handed a tied hash
1214 whose EXISTS died leaked 448 SVs; _parse_cif_string(), 1,365.*/
1215 2164 static HV *opt_plain_hv(pTHX_ HV *CSP_RESTRICT opts, const char *CSP_RESTRICT key){
1216 2164 SV *c = opt_get(aTHX_ opts, key);
1217 2164 ▶ if (!c || !SvROK(c) || SvTYPE(SvRV(c)) != SVt_PVHV) return NULL;
Branch: 3 branches
BranchTrueFalseTotal
if (!c || !SvROK(c) || SvTYPE(SvRV(c)) != SVt_PVHV) return NULL; 493 1671 2164
if (!c || !SvROK(c) || SvTYPE(SvRV(c)) != SVt_PVHV) return NULL; 493 0 493
if (!c || !SvROK(c) || SvTYPE(SvRV(c)) != SVt_PVHV) return NULL; 0 493 493
1218 HV *h;
1219 493 h = (HV *)SvRV(c);
1220 493 ▶ if (SvRMAGICAL((SV *)h)) croak("%s must be a plain hash reference, not a tied one", key);
Branch: 1 branch
BranchTrueFalseTotal
if (SvRMAGICAL((SV *)h)) croak("%s must be a plain hash reference, not a tied one", key); 6 487 493
1221 487 return h;
1222 }
1223  
1224 1723 static HV *opt_chains(pTHX_ HV *CSP_RESTRICT opts){
1225 1723 return opt_plain_hv(aTHX_ opts, "chains");
1226 }
1227  
1228 /*columns 79-80 as the PDB reader spells a charge: nothing unless the field is
1229 one (see charge_ok()), a sign written first turned round, and a zero without its
1230 sign. swap is room for the turned-round spelling, which *out then points at.
1231  
1232 '-1' is '1-' written sign first, and is spelled the way the format and the mmCIF
1233 reader spell it, so that 4byf's O-1 atoms carry the same charge from either
1234 file; and 4iu3 writes '0-', which is the '0' the mmCIF reader gives for the same
1235 charge, and which was true in Perl where a charge of zero is not.*/
1236 144425 static STRLEN pdb_charge(const char *CSP_RESTRICT line, STRLEN llen, char *CSP_RESTRICT swap,
1237 const char **CSP_RESTRICT out){
1238 const char *s;
1239 144425 STRLEN n = fld(line, llen, 78, 79, &s);
1240 144425 ▶ if (!charge_ok(s, n)) n = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!charge_ok(s, n)) n = 0; 144402 23 144425
1241 144425 ▶ if (n == 2 && (s[0] == '+' || s[0] == '-')) {
Branch: 3 branches
BranchTrueFalseTotal
if (n == 2 && (s[0] == '+' || s[0] == '-')) { 19 144406 144425
if (n == 2 && (s[0] == '+' || s[0] == '-')) { 18 1 19
if (n == 2 && (s[0] == '+' || s[0] == '-')) { 2 16 18
1242 3 swap[0] = s[1];
1243 3 swap[1] = s[0];
1244 3 s = swap;
1245 }
1246 144425 ▶ if (n == 2 && s[0] == '0') n = 1;
Branch: 2 branches
BranchTrueFalseTotal
if (n == 2 && s[0] == '0') n = 1; 19 144406 144425
if (n == 2 && s[0] == '0') n = 1; 2 17 19
1247 144425 *out = s;
1248 144425 return n;
1249 }
1250  
1251 //defined with the mmCIF lexer below, and wanted by the writer here
1252 static bool cif_iskw(const char *CSP_RESTRICT s, STRLEN n, const char *CSP_RESTRICT kw, STRLEN kwn);
1253  
1254 /*Conversion -- convert() writes what one of the readers has read, in the other
1255 format or in its own.
1256  
1257 The readers do the reading. parse_buf() and parse_cif_buf() are handed a cv_w
1258 by convert(), and each atom they keep goes to it rather than into SVs: the
1259 model, chain, hydrogen, water and HETATM options are applied by the code that
1260 applies them for structure_info(), and the fields arrive as that code has
1261 settled them -- the element worked out where the file gives none, the charge in
1262 the PDB spelling, auth_* before label_*, `.' and `?' as nothing. So a converted
1263 file reads back as the structure the original read as, and no rule about either
1264 format is written down twice. What is here is the other half: an atom as a PDB
1265 record or as a row of _atom_site, the ANISOU record or _atom_site_anisotrop row
1266 that goes with it, and MODEL and TER. The header is converted in Perl, out of
1267 what the readers keep of it, for the reason the header is read in Perl.
1268  
1269 A number goes across as the characters the file wrote it in wherever the target
1270 has room for them, so that the converted file reads back to the same NV bit for
1271 bit and not to within a rounding. An mmCIF value can be longer than its PDB
1272 column, and is then written to the column's decimals and counted in n_rounded,
1273 which convert() hands back. A field the PDB format has no room for at all -- a
1274 chain id of two characters, a residue name of five, a coordinate past
1275 9999.999 -- ends the conversion with a message naming the atom, because the
1276 alternatives are a file with every column after it one out, or chain ids made up
1277 for it.
1278  
1279 The output is one string per model for a PDB file, because an mmCIF file need
1280 not list its models in order and a PDB file has to, and one string for the
1281 _atom_site loop of an mmCIF file. Nothing per atom is kept besides the text
1282 written, and -- for an mmCIF file going to mmCIF -- the atom's id, which is how
1283 the _atom_site_anisotrop rows of the atoms that were left out are found.*/
1284 #define CV_LINE 81 //a PDB record as written here: 80 columns, blank-padded, and its newline
1285  
1286 //an atom's five numbers, in the order cv_atom holds them
1287 enum { CV_X, CV_Y, CV_Z, CV_OCC, CV_B, CV_NNUM };
1288  
1289 /*One atom, as a reader has settled it. The pointers are into the file buffer or
1290 the reader's own stack, and are good for the one call.*/
1291 typedef struct {
1292 const char *name, *alt, *resname, *chain, *icode, *el, *chg;
1293 STRLEN name_n, alt_n, resname_n, chain_n, icode_n, el_n, chg_n;
1294 /*columns 13-16 as a PDB file wrote them, alignment and all, which a PDB file
1295 going back out to PDB keeps; NULL from an mmCIF file, which has no columns*/
1296 const char *name4;
1297 STRLEN name4_n;
1298 //each number as the file wrote it -- trimmed, its uncertainty taken off -- and as it was read
1299 const char *num_s[CV_NNUM];
1300 STRLEN num_n[CV_NNUM];
1301 NV num[CV_NNUM];
1302 IV serial, resseq, model;
1303 bool het, have_serial, have_rs, have_xyz, have_occ, have_b;
1304 unsigned char rtype;//RT_* of the residue name
1305 } cv_atom;
1306  
1307 //one row of an mmCIF file's _atom_site_anisotrop, kept until every atom is written
1308 typedef struct {
1309 const char *sym, *u[6];//U11 U22 U33 U12 U13 U23, pointing into the file buffer
1310 STRLEN sym_n, u_n[6];
1311 IV id;
1312 bool have_id;
1313 } cv_aniso;
1314  
1315 typedef struct {
1316 bool to_pdb, from_cif, keep_aniso;
1317 SV *err;//the first thing that would not fit, as convert()'s message; NULL while nothing has
1318 UV n_atom, n_aniso, n_rounded;
1319 /*every model written, in the order each was first met, and for a PDB file
1320 the text of each: m_buf stays NULL going to mmCIF, which needs no grouping*/
1321 IV *m_num;
1322 SV **m_buf;
1323 size_t n_model, cap_model, cur;
1324 //the polymer run a TER will close: its last atom, and the model it is in
1325 bool ter_open, ter_have_serial, ter_have_rs;
1326 IV ter_serial, ter_resseq;
1327 size_t ter_m;
1328 char ter_resname[3], ter_chain, ter_icode;
1329 STRLEN ter_resname_n, ter_chain_n;
1330 //the atom an ANISOU record that follows it belongs to: whether it was written, and what it was
1331 bool last_kept, last_have_serial;
1332 IV last_serial;
1333 char last_el[2];
1334 STRLEN last_el_n;
1335 char last_line[CV_LINE];//going to PDB: the record as written, whose columns an ANISOU repeats
1336 //going to mmCIF: the _atom_site loop and the _atom_site_anisotrop one
1337 SV *atoms, *aniso;
1338 //from mmCIF: the _atom_site_anisotrop rows, and going to mmCIF the ids of the atoms written
1339 cv_aniso *at;
1340 size_t n_at, cap_at;
1341 IV *wid;
1342 size_t n_wid, cap_wid;
1343 //the chains, in the order an atom of each was first written, for the header's SEQRES
1344 HV *chain_seen;
1345 AV *chain_order;
1346 SV *p_chain;//the last written atom's chain, so that chain_seen is asked only on a change
1347 bool have_p_chain;//FALSE until an atom has been written: p_chain is no chain yet
1348 } cv_w;
1349  
1350 /*cv_fail() -- the first field that will not go across, as the message convert()
1351 dies with, with the atom it belongs to named after it. The parse is not stopped:
1352 a croak from inside it would leave everything it has built unreachable, so the
1353 remaining atoms are passed over and convert_do() croaks once the parse has
1354 returned and its hash can be freed.*/
1355 18 static void cv_fail(pTHX_ cv_w *CSP_RESTRICT w, const cv_atom *CSP_RESTRICT a, const char *CSP_RESTRICT pat, ...)
1356 {
1357 va_list args;
1358 23 ▶ if (w->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (w->err) return; 0 18 18
1359 18 va_start(args, pat);
1360 18 w->err = vnewSVpvf(pat, &args);
1361 18 va_end(args);
1362 18 ▶ if (!a) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!a) return; 5 13 18
1363 13 sv_catpvs(w->err, " (atom ");
1364 13 ▶ if (a->have_serial) sv_catpvf(w->err, "%" IVdf ", ", a->serial);
Branch: 1 branch
BranchTrueFalseTotal
if (a->have_serial) sv_catpvf(w->err, "%" IVdf ", ", a->serial); 13 0 13
1365 13 sv_catpvf(w->err, "'%.*s' of %.*s ", (int)a->name_n, a->name, (int)a->resname_n, a->resname);
1366 13 ▶ if (a->have_rs) sv_catpvf(w->err, "%" IVdf, a->resseq);
Branch: 1 branch
BranchTrueFalseTotal
if (a->have_rs) sv_catpvf(w->err, "%" IVdf, a->resseq); 13 0 13
1367 13 sv_catpvf(w->err, "%.*s in chain '%.*s', model %" IVdf ")",
1368 (int)a->icode_n, a->icode, (int)a->chain_n, a->chain, a->model);
1369 }
1370  
1371 //[+-]?digits[.digits], the number str2nv_fixed() reads, which a PDB column takes as written
1372 163764 static bool cv_plain(const char *CSP_RESTRICT s, STRLEN n){
1373 163764 STRLEN i = 0, nd = 0;
1374 163764 bool dot = FALSE;
1375 163764 ▶ if (n && (s[0] == '+' || s[0] == '-')) i = 1;
Branch: 3 branches
BranchTrueFalseTotal
if (n && (s[0] == '+' || s[0] == '-')) i = 1; 163764 0 163764
if (n && (s[0] == '+' || s[0] == '-')) i = 1; 163764 0 163764
if (n && (s[0] == '+' || s[0] == '-')) i = 1; 12525 151239 163764
1376 1023768 ▶ for (; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (; i < n; i++) { 860006 163762 1023768
1377 860006 ▶ if (isDIGIT((unsigned char)s[i])) nd++;
Branch: 1 branch
BranchTrueFalseTotal
if (isDIGIT((unsigned char)s[i])) nd++; 696242 163764 860006
1378 163764 ▶ else if (s[i] == '.' && !dot) dot = TRUE;
Branch: 2 branches
BranchTrueFalseTotal
else if (s[i] == '.' && !dot) dot = TRUE; 163762 2 163764
else if (s[i] == '.' && !dot) dot = TRUE; 163762 0 163762
1379 2 else return FALSE;
1380 }
1381 163762 return nd > 0;
1382 }
1383  
1384 /*cv_hy36() -- an integer into a PDB field of width columns, right-justified:
1385 decimal while it fits, hybrid-36 past that, which is hy36_decode() run
1386 backwards and what the PDB reader reads back. Below the decimal range there is
1387 no encoding, and FALSE says so; out is not touched then. width is 4 or 5, and
1388 the largest the five columns hold, 87,440,031, is well inside an IV.*/
1389 66195 static bool cv_hy36(IV v, unsigned short width, char *CSP_RESTRICT out){
1390 66195 IV dec = 1, p = 1;
1391 364078 ▶ for (unsigned short i = 0; i < width; i++) dec *= 10;
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < width; i++) dec *= 10; 297883 66195 364078
1392 297883 ▶ for (unsigned short i = 1; i < width; i++) p *= 36;
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 1; i < width; i++) p *= 36; 231688 66195 297883
1393 66195 ▶ if (v > -(dec / 10) && v < dec) {
Branch: 2 branches
BranchTrueFalseTotal
if (v > -(dec / 10) && v < dec) { 66194 1 66195
if (v > -(dec / 10) && v < dec) { 66155 39 66194
1394 char tmp[32];//an IV prints in at most 21 characters, sign included
1395 66155 const STRLEN k = (STRLEN)my_snprintf(tmp, sizeof(tmp), "%" IVdf, v);
1396 66155 memcpy(out + width - k, tmp, k);
1397 66155 return TRUE;
1398 }
1399 40 ▶ if (v < 0 || v - dec >= 52 * p) return FALSE;
Branch: 2 branches
BranchTrueFalseTotal
if (v < 0 || v - dec >= 52 * p) return FALSE; 39 1 40
if (v < 0 || v - dec >= 52 * p) return FALSE; 3 36 39
1400 {
1401 /*upper case for the first 26 * 36**(w-1) past the decimal range, lower
1402 case for the next, each digit string offset by 10 * 36**(w-1) so that it
1403 begins with a letter*/
1404 36 IV d = v - dec;
1405 36 ▶ const char *CSP_RESTRICT digits = d < 26 * p ? "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Branch: 1 branch
BranchTrueFalseTotal
const char *CSP_RESTRICT digits = d < 26 * p ? "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" 31 5 36
1406 : "0123456789abcdefghijklmnopqrstuvwxyz";
1407 36 ▶ if (d >= 26 * p) d -= 26 * p;
Branch: 1 branch
BranchTrueFalseTotal
if (d >= 26 * p) d -= 26 * p; 5 31 36
1408 36 d += 10 * p;
1409 194 ▶ for (unsigned short i = width; i > 0; i--) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = width; i > 0; i--) { 158 36 194
1410 158 out[i - 1] = digits[d % 36];
1411 158 d /= 36;
1412 }
1413 }
1414 36 return TRUE;
1415 }
1416  
1417 /*cv_nv_text() -- v to three decimals, or two, as the PDB columns want it.
1418  
1419 my_snprintf() everywhere else, but not on a quadmath perl. There NVff is "Qf",
1420 which gcc's printf format checking -- my_snprintf() carries the attribute --
1421 does not know, and the build that is meant to be clean under -Wall printed four
1422 warnings for these two calls. quadmath_snprintf() is what my_snprintf() hands a
1423 single %Q conversion to on that build anyway (util.c), and <quadmath.h> is in
1424 by way of perl.h there.*/
1425 6 static int cv_nv_text(char *CSP_RESTRICT buf, size_t size, bool three, NV v){
1426 #ifdef USE_QUADMATH
1427 return quadmath_snprintf(buf, size, three ? "%.3Qf" : "%.2Qf", v);
1428 #else
1429 6 ▶ return three ? my_snprintf(buf, size, "%.3" NVff, v) : my_snprintf(buf, size, "%.2" NVff, v);
Branch: 1 branch
BranchTrueFalseTotal
return three ? my_snprintf(buf, size, "%.3" NVff, v) : my_snprintf(buf, size, "%.2" NVff, v); 4 2 6
1430 #endif
1431 }
1432  
1433 /*cv_num() -- one of an atom's five numbers into its PDB column, right-justified:
1434 as written when it is a plain decimal that fits, and otherwise at the decimals
1435 the format gives the column -- three for a coordinate, two for occupancy and B
1436 -- counted in n_rounded unless that reads back as the same NV. A NaN or an
1437 infinity has no decimals to round to and goes across as written, or not at all.*/
1438 163769 static bool cv_num(pTHX_ cv_w *CSP_RESTRICT w, const cv_atom *CSP_RESTRICT a, unsigned short i,
1439 char *CSP_RESTRICT dst, STRLEN width, const char *CSP_RESTRICT what)
1440 {
1441 163769 const char *CSP_RESTRICT s = a->num_s[i];
1442 163769 const STRLEN n = a->num_n[i];
1443 163769 const NV v = a->num[i];
1444 char tmp[64];
1445 int k;
1446 NV back;
1447 163769 ▶ if (n <= width && cv_plain(s, n)) {
Branch: 2 branches
BranchTrueFalseTotal
if (n <= width && cv_plain(s, n)) { 163764 5 163769
if (n <= width && cv_plain(s, n)) { 163762 2 163764
1448 163762 memcpy(dst + width - n, s, n);
1449 163762 return TRUE;
1450 }
1451 7 ▶ if (!nv_is_finite(v)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!nv_is_finite(v)) { 1 6 7
1452 1 ▶ if (n <= width) {
Branch: 1 branch
BranchTrueFalseTotal
if (n <= width) { 1 0 1
1453 1 memcpy(dst + width - n, s, n);
1454 1 return TRUE;
1455 }
1456 0 k = -1;
1457 /*Bounded first: my_snprintf() croaks rather than truncates, and a value this
1458 size has no room in eight columns at any number of decimals anyway.*/
1459 6 ▶ } else if (v <= -1e7 || v >= 1e8) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (v <= -1e7 || v >= 1e8) { 6 0 6
} else if (v <= -1e7 || v >= 1e8) { 0 6 6
1460 0 k = -1;
1461 } else {
1462 6 k = cv_nv_text(tmp, sizeof(tmp), i <= CV_Z, v);
1463 }
1464 6 ▶ if (k <= 0 || (STRLEN)k > width) {
Branch: 2 branches
BranchTrueFalseTotal
if (k <= 0 || (STRLEN)k > width) { 6 0 6
if (k <= 0 || (STRLEN)k > width) { 2 4 6
1465 2 cv_fail(aTHX_ w, a, "convert: the %s '%.*s' does not fit the %u columns a PDB record has for it",
1466 what, (int)n, s, (unsigned int)width);
1467 2 return FALSE;
1468 }
1469 4 memcpy(dst + width - (STRLEN)k, tmp, (STRLEN)k);
1470 4 ▶ if (!str2nv(tmp, (STRLEN)k, &back) || back != v) w->n_rounded++;
Branch: 2 branches
BranchTrueFalseTotal
if (!str2nv(tmp, (STRLEN)k, &back) || back != v) w->n_rounded++; 4 0 4
if (!str2nv(tmp, (STRLEN)k, &back) || back != v) w->n_rounded++; 3 1 4
1471 4 return TRUE;
1472 }
1473  
1474 /*cv_model() -- the index of a model in m_num[], added if it is new. Asked of
1475 every atom, and the answer is nearly always the model before; a PDB file lists
1476 its models in order, so a new one is only ever searched for once.*/
1477 65017 static size_t cv_model(pTHX_ cv_w *CSP_RESTRICT w, IV model){
1478 size_t i;
1479 65017 ▶ if (w->n_model && w->m_num[w->cur] == model) return w->cur;
Branch: 2 branches
BranchTrueFalseTotal
if (w->n_model && w->m_num[w->cur] == model) return w->cur; 64609 408 65017
if (w->n_model && w->m_num[w->cur] == model) return w->cur; 64459 150 64609
1480 803 ▶ for (i = 0; i < w->n_model; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < w->n_model; i++) { 247 556 803
1481 247 ▶ if (w->m_num[i] == model) return w->cur = i;
Branch: 1 branch
BranchTrueFalseTotal
if (w->m_num[i] == model) return w->cur = i; 2 245 247
1482 }
1483 556 ▶ if (w->n_model == w->cap_model) {
Branch: 1 branch
BranchTrueFalseTotal
if (w->n_model == w->cap_model) { 408 148 556
1484 408 ▶ w->cap_model = w->cap_model ? 2 * w->cap_model : 4;
Branch: 1 branch
BranchTrueFalseTotal
w->cap_model = w->cap_model ? 2 * w->cap_model : 4; 0 408 408
1485 408 ▶ Renew(w->m_num, w->cap_model, IV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(w->m_num, w->cap_model, IV); 0 408 408
1486 408 ▶ if (w->to_pdb) Renew(w->m_buf, w->cap_model, SV *);
Branch: 2 branches
BranchTrueFalseTotal
if (w->to_pdb) Renew(w->m_buf, w->cap_model, SV *); 211 197 408
if (w->to_pdb) Renew(w->m_buf, w->cap_model, SV *); 0 211 211
1487 }
1488 556 w->m_num[w->n_model] = model;
1489 556 ▶ if (w->to_pdb) w->m_buf[w->n_model] = newSVpvs("");
Branch: 1 branch
BranchTrueFalseTotal
if (w->to_pdb) w->m_buf[w->n_model] = newSVpvs(""); 292 264 556
1490 556 return w->cur = w->n_model++;
1491 }
1492  
1493 33335 static void cv_blank(char *CSP_RESTRICT line){
1494 33335 memset(line, ' ', CV_LINE - 1);
1495 33335 line[CV_LINE - 1] = '\n';
1496 33335 }
1497  
1498 /*cv_ter() -- the TER that closes the open polymer run, after its last atom.
1499  
1500 It takes the serial after its atom's, as the archive numbers it; nothing refers
1501 to a TER by its serial, and one past the five columns is left blank.*/
1502 336 static void cv_ter(pTHX_ cv_w *CSP_RESTRICT w){
1503 char line[CV_LINE];
1504 336 w->ter_open = FALSE;
1505 336 cv_blank(line);
1506 336 memcpy(line, "TER", 3);
1507 336 ▶ if (w->ter_have_serial && w->ter_serial < IV_MAX) (void)cv_hy36(w->ter_serial + 1, 5, line + 6);
Branch: 2 branches
BranchTrueFalseTotal
if (w->ter_have_serial && w->ter_serial < IV_MAX) (void)cv_hy36(w->ter_serial + 1, 5, line + 6); 336 0 336
if (w->ter_have_serial && w->ter_serial < IV_MAX) (void)cv_hy36(w->ter_serial + 1, 5, line + 6); 336 0 336
1508 336 memcpy(line + 20 - w->ter_resname_n, w->ter_resname, w->ter_resname_n);
1509 336 ▶ if (w->ter_chain_n) line[21] = w->ter_chain;
Branch: 1 branch
BranchTrueFalseTotal
if (w->ter_chain_n) line[21] = w->ter_chain; 330 6 336
1510 336 ▶ if (w->ter_have_rs) (void)cv_hy36(w->ter_resseq, 4, line + 22);
Branch: 1 branch
BranchTrueFalseTotal
if (w->ter_have_rs) (void)cv_hy36(w->ter_resseq, 4, line + 22); 336 0 336
1511 336 ▶ if (w->ter_icode) line[26] = w->ter_icode;
Branch: 1 branch
BranchTrueFalseTotal
if (w->ter_icode) line[26] = w->ter_icode; 0 336 336
1512 336 sv_catpvn(w->m_buf[w->ter_m], line, CV_LINE);
1513 336 }
1514  
1515 /*cv_pdb_atom() -- an ATOM or HETATM record, in the columns of the wwPDB format
1516 v3.3, into its model's text.
1517  
1518 The atom name is the one column rule with a judgement in it. A name read from a
1519 PDB file goes back where that file put it. One from an mmCIF file has no
1520 columns, and goes where the format puts it: from column 14 when it is shorter
1521 than four characters, begins with a letter, and its element is one letter -- "
1522 CA " is a carbon alpha -- and from column 13 otherwise -- "CA " is a calcium,
1523 "1HB " a hydrogen. That is Biopython 1.85's rule (PDBIO._get_atom_line) and the
1524 one the PDB reader's element guess reads back.
1525  
1526 TER goes in after the last atom of each run of polymer: of ATOM records, and of
1527 HETATM records of a residue the residue table calls an amino acid or a
1528 nucleotide, so that a selenomethionine at the end of a chain is inside its TER
1529 and the ligands and waters after it are outside. The run ends at a change of
1530 chain or of model, or at the first atom that is neither. Nothing in this
1531 module reads TER; gemmi does, to tell the polymer from what follows it.*/
1532 32775 static void cv_pdb_atom(pTHX_ cv_w *CSP_RESTRICT w, const cv_atom *CSP_RESTRICT a)
1533 {
1534 32775 char *CSP_RESTRICT line = w->last_line;
1535 32775 ▶ const bool polymer = !a->het || a->rtype == RT_AA || a->rtype == RT_NUC;
Branch: 3 branches
BranchTrueFalseTotal
const bool polymer = !a->het || a->rtype == RT_AA || a->rtype == RT_NUC; 3727 29048 32775
const bool polymer = !a->het || a->rtype == RT_AA || a->rtype == RT_NUC; 3523 204 3727
const bool polymer = !a->het || a->rtype == RT_AA || a->rtype == RT_NUC; 0 3523 3523
1536 size_t m;
1537 32775 ▶ if (a->chain_n > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (a->chain_n > 1) { 5 32770 32775
1538 5 cv_fail(aTHX_ w, a, "convert: the chain id '%.*s' has no PDB spelling: "
1539 5 "a PDB record has one column for it", (int)a->chain_n, a->chain);
1540 5 return;
1541 }
1542 32770 ▶ if (a->resname_n > 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (a->resname_n > 3) { 1 32769 32770
1543 1 cv_fail(aTHX_ w, a, "convert: the residue name '%.*s' has no PDB spelling: "
1544 1 "a PDB record has three columns for it", (int)a->resname_n, a->resname);
1545 1 return;
1546 }
1547 32769 ▶ if (a->name_n > 4) {
Branch: 1 branch
BranchTrueFalseTotal
if (a->name_n > 4) { 1 32768 32769
1548 1 cv_fail(aTHX_ w, a, "convert: the atom name '%.*s' has no PDB spelling: "
1549 1 "a PDB record has four columns for it", (int)a->name_n, a->name);
1550 1 return;
1551 }
1552 32768 ▶ if (a->alt_n > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (a->alt_n > 1) { 1 32767 32768
1553 1 cv_fail(aTHX_ w, a, "convert: the alternate location '%.*s' has no PDB spelling: "
1554 1 "a PDB record has one column for it", (int)a->alt_n, a->alt);
1555 1 return;
1556 }
1557 32767 cv_blank(line);
1558 32767 ▶ memcpy(line, a->het ? "HETATM" : "ATOM ", 6);
Branch: 1 branch
BranchTrueFalseTotal
memcpy(line, a->het ? "HETATM" : "ATOM ", 6); 3725 29042 32767
1559 32767 ▶ if (a->have_serial && !cv_hy36(a->serial, 5, line + 6)) {
Branch: 2 branches
BranchTrueFalseTotal
if (a->have_serial && !cv_hy36(a->serial, 5, line + 6)) { 32767 0 32767
if (a->have_serial && !cv_hy36(a->serial, 5, line + 6)) { 1 32766 32767
1560 1 cv_fail(aTHX_ w, a, "convert: the serial number %" IVdf " is past what the five "
1561 1 "columns of a PDB record hold, in decimal or hybrid-36", a->serial);
1562 1 return;
1563 }
1564 32766 ▶ if (a->name4) {
Branch: 1 branch
BranchTrueFalseTotal
if (a->name4) { 14235 18531 32766
1565 14235 memcpy(line + 12, a->name4, a->name4_n);
1566 } else {
1567 18531 ▶ const bool col14 = a->name_n > 0 && a->name_n < 4 && a->el_n < 2
Branch: 2 branches
BranchTrueFalseTotal
const bool col14 = a->name_n > 0 && a->name_n < 4 && a->el_n < 2 18289 242 18531
const bool col14 = a->name_n > 0 && a->name_n < 4 && a->el_n < 2 18233 56 18289
1568 37062 ▶ && isALPHA((unsigned char)a->name[0]);
Branch: 2 branches
BranchTrueFalseTotal
&& isALPHA((unsigned char)a->name[0]); 18531 0 18531
&& isALPHA((unsigned char)a->name[0]); 18231 2 18233
1569 18531 ▶ memcpy(line + (col14 ? 13 : 12), a->name, a->name_n);
Branch: 1 branch
BranchTrueFalseTotal
memcpy(line + (col14 ? 13 : 12), a->name, a->name_n); 18231 300 18531
1570 }
1571 32766 ▶ if (a->alt_n) line[16] = a->alt[0];
Branch: 1 branch
BranchTrueFalseTotal
if (a->alt_n) line[16] = a->alt[0]; 120 32646 32766
1572 32766 memcpy(line + 20 - a->resname_n, a->resname, a->resname_n);
1573 32766 ▶ if (a->chain_n) line[21] = a->chain[0];
Branch: 1 branch
BranchTrueFalseTotal
if (a->chain_n) line[21] = a->chain[0]; 32136 630 32766
1574 32766 ▶ if (a->have_rs && !cv_hy36(a->resseq, 4, line + 22)) {
Branch: 2 branches
BranchTrueFalseTotal
if (a->have_rs && !cv_hy36(a->resseq, 4, line + 22)) { 32756 10 32766
if (a->have_rs && !cv_hy36(a->resseq, 4, line + 22)) { 2 32754 32756
1575 2 cv_fail(aTHX_ w, a, "convert: the residue number %" IVdf " is outside what the four "
1576 2 "columns of a PDB record hold, in decimal or hybrid-36", a->resseq);
1577 2 return;
1578 }
1579 32764 ▶ if (a->icode_n) line[26] = a->icode[0];
Branch: 1 branch
BranchTrueFalseTotal
if (a->icode_n) line[26] = a->icode[0]; 186 32578 32764
1580 32764 ▶ if (a->have_xyz && !(cv_num(aTHX_ w, a, CV_X, line + 30, 8, "x coordinate")
Branch: 2 branches
BranchTrueFalseTotal
if (a->have_xyz && !(cv_num(aTHX_ w, a, CV_X, line + 30, 8, "x coordinate") 32764 0 32764
if (a->have_xyz && !(cv_num(aTHX_ w, a, CV_X, line + 30, 8, "x coordinate") 32763 1 32764
1581 32763 ▶ && cv_num(aTHX_ w, a, CV_Y, line + 38, 8, "y coordinate")
Branch: 1 branch
BranchTrueFalseTotal
&& cv_num(aTHX_ w, a, CV_Y, line + 38, 8, "y coordinate") 32762 1 32763
1582 32762 ▶ && cv_num(aTHX_ w, a, CV_Z, line + 46, 8, "z coordinate")))
Branch: 1 branch
BranchTrueFalseTotal
&& cv_num(aTHX_ w, a, CV_Z, line + 46, 8, "z coordinate"))) 0 32762 32762
1583 2 return;
1584 32762 ▶ if (a->have_occ && !cv_num(aTHX_ w, a, CV_OCC, line + 54, 6, "occupancy")) return;
Branch: 2 branches
BranchTrueFalseTotal
if (a->have_occ && !cv_num(aTHX_ w, a, CV_OCC, line + 54, 6, "occupancy")) return; 32740 22 32762
if (a->have_occ && !cv_num(aTHX_ w, a, CV_OCC, line + 54, 6, "occupancy")) return; 0 32740 32740
1585 32762 ▶ if (a->have_b && !cv_num(aTHX_ w, a, CV_B, line + 60, 6, "B-factor")) return;
Branch: 2 branches
BranchTrueFalseTotal
if (a->have_b && !cv_num(aTHX_ w, a, CV_B, line + 60, 6, "B-factor")) return; 32740 22 32762
if (a->have_b && !cv_num(aTHX_ w, a, CV_B, line + 60, 6, "B-factor")) return; 0 32740 32740
1586 //the element upper case, as the format writes it; both readers cap it at two
1587 {
1588 32762 const STRLEN el_n = a->el_n > 2 ? 2 : a->el_n;
1589 65600 ▶ for (STRLEN k = 0; k < el_n; k++)
Branch: 1 branch
BranchTrueFalseTotal
for (STRLEN k = 0; k < el_n; k++) 32838 32762 65600
1590 32838 ▶ line[78 - el_n + k] = (char)toUPPER((unsigned char)a->el[k]);
Branch: 1 branch
BranchTrueFalseTotal
line[78 - el_n + k] = (char)toUPPER((unsigned char)a->el[k]); 76 32762 32838
1591 }
1592 32762 memcpy(line + 78, a->chg, a->chg_n > 2 ? 2 : a->chg_n);
1593  
1594 //before the model is switched: the run a TER closes is in the old model
1595 32762 ▶ if (w->ter_open && (w->m_num[w->ter_m] != a->model || !polymer
Branch: 3 branches
BranchTrueFalseTotal
if (w->ter_open && (w->m_num[w->ter_m] != a->model || !polymer 29061 3701 32762
if (w->ter_open && (w->m_num[w->ter_m] != a->model || !polymer 28978 83 29061
if (w->ter_open && (w->m_num[w->ter_m] != a->model || !polymer 28917 61 28978
1596 28917 ▶ || w->ter_chain_n != a->chain_n
Branch: 1 branch
BranchTrueFalseTotal
|| w->ter_chain_n != a->chain_n 28917 0 28917
1597 28917 ▶ || (a->chain_n && w->ter_chain != a->chain[0])))
Branch: 2 branches
BranchTrueFalseTotal
|| (a->chain_n && w->ter_chain != a->chain[0]))) 28293 624 28917
|| (a->chain_n && w->ter_chain != a->chain[0]))) 12 28281 28293
1598 156 cv_ter(aTHX_ w);
1599 32762 m = cv_model(aTHX_ w, a->model);
1600 32762 sv_catpvn(w->m_buf[m], line, CV_LINE);
1601 32762 ▶ if (polymer) {
Branch: 1 branch
BranchTrueFalseTotal
if (polymer) { 29241 3521 32762
1602 29241 w->ter_open = TRUE;
1603 29241 w->ter_m = m;
1604 29241 w->ter_have_serial = a->have_serial;
1605 29241 w->ter_serial = a->serial;
1606 29241 w->ter_have_rs = a->have_rs;
1607 29241 w->ter_resseq = a->resseq;
1608 29241 w->ter_resname_n = a->resname_n;
1609 29241 memcpy(w->ter_resname, a->resname, a->resname_n);
1610 29241 w->ter_chain_n = a->chain_n;
1611 29241 ▶ w->ter_chain = a->chain_n ? a->chain[0] : ' ';
Branch: 1 branch
BranchTrueFalseTotal
w->ter_chain = a->chain_n ? a->chain[0] : ' '; 28611 630 29241
1612 29241 ▶ w->ter_icode = a->icode_n ? a->icode[0] : '\0';
Branch: 1 branch
BranchTrueFalseTotal
w->ter_icode = a->icode_n ? a->icode[0] : '\0'; 180 29061 29241
1613 }
1614 }
1615  
1616 /*cv_cif_val() -- one value of an mmCIF row and the blank after it, quoted when
1617 it has to be: when it holds a blank, begins with a character that means
1618 something to the format, is a bare . or ?, or is one of the reserved words.
1619 null stands in for an empty value: `.' where the field does not apply, `?'
1620 where it is not known, which both readers take as an empty field.
1621  
1622 Quoted with ' unless the value holds a ' followed by a blank, which would end
1623 it there -- a quote followed by anything else is part of the value, which is
1624 how O5' goes unescaped -- and with " on the same terms; FALSE for a value
1625 neither can hold, which only a text field could, and a text field cannot start
1626 partway along a row.*/
1627 483864 static bool cv_cif_val(pTHX_ SV *CSP_RESTRICT o, const char *CSP_RESTRICT s, STRLEN n, char null){
1628 483864 bool quote = FALSE, sq = TRUE, dq = TRUE;//sq, dq: whether ' and " could quote it
1629 char q;
1630 483864 ▶ if (n == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) { 97753 386111 483864
1631 97753 const char t[2] = { null, ' ' };
1632 97753 sv_catpvn(o, t, 2);
1633 97753 return TRUE;
1634 }
1635 386111 ▶ switch (s[0]) {
Branch: 1 branch
BranchTrueFalseTotal
switch (s[0]) { 6 386105 386111
1636 6 case '_': case '#': case '$': case '\'': case '"': case '[': case ']': case ';':
1637 6 quote = TRUE;
1638 6 break;
1639 386105 default: break;
1640 }
1641 386111 ▶ if (n == 1 && (s[0] == '.' || s[0] == '?')) quote = TRUE;
Branch: 3 branches
BranchTrueFalseTotal
if (n == 1 && (s[0] == '.' || s[0] == '?')) quote = TRUE; 123503 262608 386111
if (n == 1 && (s[0] == '.' || s[0] == '?')) quote = TRUE; 123501 2 123503
if (n == 1 && (s[0] == '.' || s[0] == '?')) quote = TRUE; 0 123501 123501
1642 386111 ▶ if ((n >= 5 && (cif_iskw(s, n, "data_", 5) || cif_iskw(s, n, "save_", 5)))
Branch: 3 branches
BranchTrueFalseTotal
if ((n >= 5 && (cif_iskw(s, n, "data_", 5) || cif_iskw(s, n, "save_", 5))) 114160 271951 386111
if ((n >= 5 && (cif_iskw(s, n, "data_", 5) || cif_iskw(s, n, "save_", 5))) 114158 2 114160
if ((n >= 5 && (cif_iskw(s, n, "data_", 5) || cif_iskw(s, n, "save_", 5))) 114158 0 114158
1643 386109 ▶ || (n == 5 && (cif_iskw(s, n, "loop_", 5) || cif_iskw(s, n, "stop_", 5)))
Branch: 3 branches
BranchTrueFalseTotal
|| (n == 5 && (cif_iskw(s, n, "loop_", 5) || cif_iskw(s, n, "stop_", 5))) 37250 348859 386109
|| (n == 5 && (cif_iskw(s, n, "loop_", 5) || cif_iskw(s, n, "stop_", 5))) 37248 2 37250
|| (n == 5 && (cif_iskw(s, n, "loop_", 5) || cif_iskw(s, n, "stop_", 5))) 37248 0 37248
1644 386107 ▶ || (n == 7 && cif_iskw(s, n, "global_", 7)))
Branch: 2 branches
BranchTrueFalseTotal
|| (n == 7 && cif_iskw(s, n, "global_", 7))) 23550 362557 386107
|| (n == 7 && cif_iskw(s, n, "global_", 7))) 0 23550 23550
1645 4 quote = TRUE;
1646 1641142 ▶ for (STRLEN i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (STRLEN i = 0; i < n; i++) { 1255031 386111 1641142
1647 1255031 ▶ if (s[i] == '\n' || s[i] == '\r') return FALSE;
Branch: 2 branches
BranchTrueFalseTotal
if (s[i] == '\n' || s[i] == '\r') return FALSE; 1255031 0 1255031
if (s[i] == '\n' || s[i] == '\r') return FALSE; 0 1255031 1255031
1648 1255031 ▶ if (s[i] == ' ' || s[i] == '\t') {
Branch: 2 branches
BranchTrueFalseTotal
if (s[i] == ' ' || s[i] == '\t') { 1255027 4 1255031
if (s[i] == ' ' || s[i] == '\t') { 0 1255027 1255027
1649 4 quote = TRUE;
1650 4 ▶ if (i && s[i - 1] == '\'') sq = FALSE;
Branch: 2 branches
BranchTrueFalseTotal
if (i && s[i - 1] == '\'') sq = FALSE; 4 0 4
if (i && s[i - 1] == '\'') sq = FALSE; 2 2 4
1651 4 ▶ if (i && s[i - 1] == '"') dq = FALSE;
Branch: 2 branches
BranchTrueFalseTotal
if (i && s[i - 1] == '"') dq = FALSE; 4 0 4
if (i && s[i - 1] == '"') dq = FALSE; 0 4 4
1652 }
1653 }
1654 386111 ▶ if (!quote) {
Branch: 1 branch
BranchTrueFalseTotal
if (!quote) { 386095 16 386111
1655 386095 sv_catpvn(o, s, n);
1656 386095 sv_catpvs(o, " ");
1657 386095 return TRUE;
1658 }
1659 16 ▶ if (!sq && !dq) return FALSE;
Branch: 2 branches
BranchTrueFalseTotal
if (!sq && !dq) return FALSE; 2 14 16
if (!sq && !dq) return FALSE; 0 2 2
1660 16 ▶ q = sq ? '\'' : '"';
Branch: 1 branch
BranchTrueFalseTotal
q = sq ? '\'' : '"'; 14 2 16
1661 16 sv_catpvn(o, &q, 1);
1662 16 sv_catpvn(o, s, n);
1663 16 sv_catpvn(o, &q, 1);
1664 16 sv_catpvs(o, " ");
1665 16 return TRUE;
1666 }
1667  
1668 96786 static void cv_cif_iv(pTHX_ SV *CSP_RESTRICT o, bool have, IV v){
1669 char tmp[32];//an IV prints in at most 21 characters, sign included
1670 96786 ▶ if (!have) {
Branch: 1 branch
BranchTrueFalseTotal
if (!have) { 9 96777 96786
1671 9 sv_catpvs(o, "? ");
1672 9 return;
1673 }
1674 96777 sv_catpvn(o, tmp, (STRLEN)my_snprintf(tmp, sizeof(tmp), "%" IVdf " ", v));
1675 }
1676  
1677 /*a charge in the PDB spelling the readers hand back, as mmCIF's signed integer:
1678 '1-' is -1, '2+' is 2 and '0' is 0. Anything else is what cif_charge() passes
1679 through as it stands, and goes across as it stands, so that it reads back as
1680 itself. A bare digit, which a PDB file can write, is that many plus.*/
1681 32255 static bool cv_cif_charge(pTHX_ SV *CSP_RESTRICT o, const char *CSP_RESTRICT s, STRLEN n){
1682 char t[3];
1683 32255 ▶ if (n == 2 && isDIGIT((unsigned char)s[0]) && (s[1] == '+' || s[1] == '-')) {
Branch: 4 branches
BranchTrueFalseTotal
if (n == 2 && isDIGIT((unsigned char)s[0]) && (s[1] == '+' || s[1] == '-')) { 12 32243 32255
if (n == 2 && isDIGIT((unsigned char)s[0]) && (s[1] == '+' || s[1] == '-')) { 12 0 12
if (n == 2 && isDIGIT((unsigned char)s[0]) && (s[1] == '+' || s[1] == '-')) { 4 8 12
if (n == 2 && isDIGIT((unsigned char)s[0]) && (s[1] == '+' || s[1] == '-')) { 4 0 4
1684 12 ▶ if (s[1] == '-' && s[0] != '0') {
Branch: 2 branches
BranchTrueFalseTotal
if (s[1] == '-' && s[0] != '0') { 4 8 12
if (s[1] == '-' && s[0] != '0') { 4 0 4
1685 4 t[0] = '-';
1686 4 t[1] = s[0];
1687 4 t[2] = ' ';
1688 4 sv_catpvn(o, t, 3);
1689 } else {
1690 8 t[0] = s[0];
1691 8 t[1] = ' ';
1692 8 sv_catpvn(o, t, 2);
1693 }
1694 12 return TRUE;
1695 }
1696 32243 return cv_cif_val(aTHX_ o, s, n, '?');
1697 }
1698  
1699 /*cv_cif_atom() -- a row of _atom_site, with the loop's header in front of the
1700 first one.
1701  
1702 The auth_* columns carry the identifiers, which is what the PDB record had and
1703 what the mmCIF reader reads first. The label_* ones are what the archive
1704 assigns -- an asym id per entity instance, a position in the entity's sequence
1705 -- and none of that is in a PDB file: label_asym_id repeats the chain id, which
1706 is what Biopython 1.85's MMCIFIO and PyMOL write as well, and label_seq_id and
1707 label_entity_id are `?' (unknown) for a polymer residue and `.' (not applicable)
1708 for a HETATM one, rather than numbers made up to look like the archive's.
1709 label_atom_id and label_comp_id repeat the auth ones, as the archive's own files
1710 do; gemmi reads the atom name from label_atom_id.*/
1711 32255 static void cv_cif_atom(pTHX_ cv_w *CSP_RESTRICT w, const cv_atom *CSP_RESTRICT a){
1712 32255 SV *CSP_RESTRICT o = w->atoms;
1713 32255 const STRLEN start = SvCUR(o);//to take a row back off that could not be written
1714 char el[2];
1715 32255 bool ok = TRUE;
1716 32255 ▶ if (!w->n_atom) {
Branch: 1 branch
BranchTrueFalseTotal
if (!w->n_atom) { 197 32058 32255
1717 197 sv_catpvs(o, "loop_\n_atom_site.group_PDB\n_atom_site.id\n_atom_site.type_symbol\n"
1718 "_atom_site.label_atom_id\n_atom_site.label_alt_id\n"
1719 "_atom_site.label_comp_id\n_atom_site.label_asym_id\n"
1720 "_atom_site.label_entity_id\n_atom_site.label_seq_id\n"
1721 "_atom_site.pdbx_PDB_ins_code\n_atom_site.Cartn_x\n_atom_site.Cartn_y\n"
1722 "_atom_site.Cartn_z\n_atom_site.occupancy\n_atom_site.B_iso_or_equiv\n"
1723 "_atom_site.pdbx_formal_charge\n_atom_site.auth_seq_id\n"
1724 "_atom_site.auth_comp_id\n_atom_site.auth_asym_id\n"
1725 "_atom_site.auth_atom_id\n_atom_site.pdbx_PDB_model_num\n");
1726 }
1727 32255 ▶ if (a->het) sv_catpvs(o, "HETATM ");
Branch: 1 branch
BranchTrueFalseTotal
if (a->het) sv_catpvs(o, "HETATM "); 3654 28601 32255
1728 28601 else sv_catpvs(o, "ATOM ");
1729 32255 cv_cif_iv(aTHX_ o, a->have_serial, a->serial);
1730 64572 ▶ for (STRLEN k = 0; k < a->el_n && k < 2; k++) el[k] = (char)toUPPER((unsigned char)a->el[k]);
Branch: 3 branches
BranchTrueFalseTotal
for (STRLEN k = 0; k < a->el_n && k < 2; k++) el[k] = (char)toUPPER((unsigned char)a->el[k]); 62 32255 32317
for (STRLEN k = 0; k < a->el_n && k < 2; k++) el[k] = (char)toUPPER((unsigned char)a->el[k]); 32317 32255 64572
for (STRLEN k = 0; k < a->el_n && k < 2; k++) el[k] = (char)toUPPER((unsigned char)a->el[k]); 32317 0 32317
1731 32255 ok = cv_cif_val(aTHX_ o, el, a->el_n > 2 ? 2 : a->el_n, '?')
1732 32255 ▶ && cv_cif_val(aTHX_ o, a->name, a->name_n, '?')
Branch: 1 branch
BranchTrueFalseTotal
&& cv_cif_val(aTHX_ o, a->name, a->name_n, '?') 32255 0 32255
1733 32255 ▶ && cv_cif_val(aTHX_ o, a->alt, a->alt_n, '.')
Branch: 1 branch
BranchTrueFalseTotal
&& cv_cif_val(aTHX_ o, a->alt, a->alt_n, '.') 32255 0 32255
1734 32255 ▶ && cv_cif_val(aTHX_ o, a->resname, a->resname_n, '?')
Branch: 1 branch
BranchTrueFalseTotal
&& cv_cif_val(aTHX_ o, a->resname, a->resname_n, '?') 32255 0 32255
1735 64510 ▶ && cv_cif_val(aTHX_ o, a->chain, a->chain_n, '.');
Branch: 2 branches
BranchTrueFalseTotal
&& cv_cif_val(aTHX_ o, a->chain, a->chain_n, '.'); 32255 0 32255
&& cv_cif_val(aTHX_ o, a->chain, a->chain_n, '.'); 32255 0 32255
1736 //label_entity_id and label_seq_id
1737 32255 ▶ if (a->het) sv_catpvs(o, ". . ");
Branch: 1 branch
BranchTrueFalseTotal
if (a->het) sv_catpvs(o, ". . "); 3654 28601 32255
1738 28601 else sv_catpvs(o, "? ? ");
1739 32255 ▶ ok = ok && cv_cif_val(aTHX_ o, a->icode, a->icode_n, '?');
Branch: 2 branches
BranchTrueFalseTotal
ok = ok && cv_cif_val(aTHX_ o, a->icode, a->icode_n, '?'); 32255 0 32255
ok = ok && cv_cif_val(aTHX_ o, a->icode, a->icode_n, '?'); 32255 0 32255
1740 129020 ▶ for (unsigned short i = CV_X; i <= CV_Z; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = CV_X; i <= CV_Z; i++) { 96765 32255 129020
1741 96765 ▶ if (a->have_xyz) ok = ok && cv_cif_val(aTHX_ o, a->num_s[i], a->num_n[i], '?');
Branch: 3 branches
BranchTrueFalseTotal
if (a->have_xyz) ok = ok && cv_cif_val(aTHX_ o, a->num_s[i], a->num_n[i], '?'); 96765 0 96765
if (a->have_xyz) ok = ok && cv_cif_val(aTHX_ o, a->num_s[i], a->num_n[i], '?'); 96765 0 96765
if (a->have_xyz) ok = ok && cv_cif_val(aTHX_ o, a->num_s[i], a->num_n[i], '?'); 96765 0 96765
1742 0 else sv_catpvs(o, "? ");
1743 }
1744 32255 ▶ if (a->have_occ) ok = ok && cv_cif_val(aTHX_ o, a->num_s[CV_OCC], a->num_n[CV_OCC], '?');
Branch: 3 branches
BranchTrueFalseTotal
if (a->have_occ) ok = ok && cv_cif_val(aTHX_ o, a->num_s[CV_OCC], a->num_n[CV_OCC], '?'); 32237 18 32255
if (a->have_occ) ok = ok && cv_cif_val(aTHX_ o, a->num_s[CV_OCC], a->num_n[CV_OCC], '?'); 32237 0 32237
if (a->have_occ) ok = ok && cv_cif_val(aTHX_ o, a->num_s[CV_OCC], a->num_n[CV_OCC], '?'); 32237 0 32237
1745 18 else sv_catpvs(o, "? ");
1746 32255 ▶ if (a->have_b) ok = ok && cv_cif_val(aTHX_ o, a->num_s[CV_B], a->num_n[CV_B], '?');
Branch: 3 branches
BranchTrueFalseTotal
if (a->have_b) ok = ok && cv_cif_val(aTHX_ o, a->num_s[CV_B], a->num_n[CV_B], '?'); 32237 18 32255
if (a->have_b) ok = ok && cv_cif_val(aTHX_ o, a->num_s[CV_B], a->num_n[CV_B], '?'); 32237 0 32237
if (a->have_b) ok = ok && cv_cif_val(aTHX_ o, a->num_s[CV_B], a->num_n[CV_B], '?'); 32237 0 32237
1747 18 else sv_catpvs(o, "? ");
1748 32255 ▶ ok = ok && cv_cif_charge(aTHX_ o, a->chg, a->chg_n);
Branch: 2 branches
BranchTrueFalseTotal
ok = ok && cv_cif_charge(aTHX_ o, a->chg, a->chg_n); 32255 0 32255
ok = ok && cv_cif_charge(aTHX_ o, a->chg, a->chg_n); 32255 0 32255
1749 32255 cv_cif_iv(aTHX_ o, a->have_rs, a->resseq);
1750 32255 ▶ ok = ok && cv_cif_val(aTHX_ o, a->resname, a->resname_n, '?')
Branch: 1 branch
BranchTrueFalseTotal
ok = ok && cv_cif_val(aTHX_ o, a->resname, a->resname_n, '?') 32255 0 32255
1751 32255 ▶ && cv_cif_val(aTHX_ o, a->chain, a->chain_n, '.')
Branch: 1 branch
BranchTrueFalseTotal
&& cv_cif_val(aTHX_ o, a->chain, a->chain_n, '.') 32255 0 32255
1752 64510 ▶ && cv_cif_val(aTHX_ o, a->name, a->name_n, '?');
Branch: 2 branches
BranchTrueFalseTotal
&& cv_cif_val(aTHX_ o, a->name, a->name_n, '?'); 32255 0 32255
&& cv_cif_val(aTHX_ o, a->name, a->name_n, '?'); 32255 0 32255
1753 32255 cv_cif_iv(aTHX_ o, TRUE, a->model);
1754 32255 ▶ if (!ok) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ok) { 0 32255 32255
1755 0 SvCUR_set(o, start);
1756 0 cv_fail(aTHX_ w, a, "convert: a field of this atom has a line end in it, "
1757 "and an mmCIF row has no way to quote one");
1758 0 return;
1759 }
1760 32255 SvPVX(o)[SvCUR(o) - 1] = '\n';
1761 32255 (void)cv_model(aTHX_ w, a->model);
1762 }
1763  
1764 /*cv_put() -- an atom a reader has kept, written in the format asked for, and
1765 noted as the one an ANISOU record after it belongs to*/
1766 65037 static void cv_put(pTHX_ cv_w *CSP_RESTRICT w, const cv_atom *CSP_RESTRICT a){
1767 65037 ▶ if (w->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (w->err) return; 7 65030 65037
1768 65030 ▶ if (w->to_pdb) cv_pdb_atom(aTHX_ w, a);
Branch: 1 branch
BranchTrueFalseTotal
if (w->to_pdb) cv_pdb_atom(aTHX_ w, a); 32775 32255 65030
1769 32255 else cv_cif_atom(aTHX_ w, a);
1770 65030 ▶ if (w->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (w->err) return; 13 65017 65030
1771 65017 w->n_atom++;
1772 65017 w->last_kept = TRUE;
1773 65017 w->last_have_serial = a->have_serial;
1774 65017 w->last_serial = a->serial;
1775 65017 w->last_el_n = a->el_n > 2 ? 2 : a->el_n;
1776 65017 memcpy(w->last_el, a->el, w->last_el_n);
1777 65017 ▶ if (w->from_cif && !w->to_pdb && a->have_serial) {
Branch: 3 branches
BranchTrueFalseTotal
if (w->from_cif && !w->to_pdb && a->have_serial) { 29259 35758 65017
if (w->from_cif && !w->to_pdb && a->have_serial) { 10732 18527 29259
if (w->from_cif && !w->to_pdb && a->have_serial) { 10732 0 10732
1778 10732 ▶ if (w->n_wid == w->cap_wid) {
Branch: 1 branch
BranchTrueFalseTotal
if (w->n_wid == w->cap_wid) { 78 10654 10732
1779 78 ▶ w->cap_wid = w->cap_wid ? 2 * w->cap_wid : 1024;
Branch: 1 branch
BranchTrueFalseTotal
w->cap_wid = w->cap_wid ? 2 * w->cap_wid : 1024; 0 78 78
1780 78 ▶ Renew(w->wid, w->cap_wid, IV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(w->wid, w->cap_wid, IV); 0 78 78
1781 }
1782 10732 w->wid[w->n_wid++] = a->serial;
1783 }
1784 65017 ▶ if (!w->have_p_chain || SvCUR(w->p_chain) != a->chain_n
Branch: 2 branches
BranchTrueFalseTotal
if (!w->have_p_chain || SvCUR(w->p_chain) != a->chain_n 64609 408 65017
if (!w->have_p_chain || SvCUR(w->p_chain) != a->chain_n 64605 4 64609
1785 64605 ▶ || memcmp(SvPVX(w->p_chain), a->chain, a->chain_n) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
|| memcmp(SvPVX(w->p_chain), a->chain, a->chain_n) != 0) { 125 64480 64605
1786 537 w->have_p_chain = TRUE;
1787 537 sv_setpvn(w->p_chain, a->chain, a->chain_n);
1788 537 ▶ if (!hv_exists(w->chain_seen, a->chain, (I32)a->chain_n)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hv_exists(w->chain_seen, a->chain, (I32)a->chain_n)) { 535 2 537
1789 535 (void)hv_store(w->chain_seen, a->chain, (I32)a->chain_n, newSV(0), 0);
1790 535 av_push(w->chain_order, newSVpvn(a->chain, a->chain_n));
1791 }
1792 }
1793 }
1794  
1795 /*cv_u_text() -- a PDB anisotropic factor, an integer in units of 10**-4 A**2,
1796 as the decimal it stands for: 1234 is 0.1234, exactly, with no NV in between*/
1797 146 static STRLEN cv_u_text(IV u, char *CSP_RESTRICT buf, STRLEN size){
1798 146 const bool neg = u < 0;
1799 146 ▶ const UV m = neg ? (UV)0 - (UV)u : (UV)u;//(UV)0 - (UV)u is the magnitude even of IV_MIN
Branch: 1 branch
BranchTrueFalseTotal
const UV m = neg ? (UV)0 - (UV)u : (UV)u;//(UV)0 - (UV)u is the magnitude even of IV_MIN 20 126 146
1800 146 ▶ return (STRLEN)my_snprintf(buf, size, "%s%" UVuf ".%04" UVuf, neg ? "-" : "",
Branch: 1 branch
BranchTrueFalseTotal
return (STRLEN)my_snprintf(buf, size, "%s%" UVuf ".%04" UVuf, neg ? "-" : "", 20 126 146
1801 m / 10000, m % 10000);
1802 }
1803  
1804 /*cv_pdb_anisou() -- an ANISOU record for the atom record line, which it repeats
1805 the columns of but for the six factors in 29-70*/
1806 26 static void cv_pdb_anisou(pTHX_ SV *CSP_RESTRICT out, const char *CSP_RESTRICT line,
1807 const IV *CSP_RESTRICT u, const bool *CSP_RESTRICT have){
1808 char rec[CV_LINE];
1809 26 memcpy(rec, line, CV_LINE);
1810 26 memcpy(rec, "ANISOU", 6);
1811 26 memset(rec + 27, ' ', 76 - 27);
1812 182 ▶ for (unsigned short i = 0; i < 6; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < 6; i++) { 156 26 182
1813 char tmp[32];//an IV prints in at most 21 characters, sign included
1814 STRLEN k;
1815 156 ▶ if (!have[i]) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!have[i]) continue; 10 146 156
1816 146 k = (STRLEN)my_snprintf(tmp, sizeof(tmp), "%" IVdf, u[i]);
1817 146 ▶ if (k <= 7) memcpy(rec + 28 + 7 * i + 7 - k, tmp, k);
Branch: 1 branch
BranchTrueFalseTotal
if (k <= 7) memcpy(rec + 28 + 7 * i + 7 - k, tmp, k); 146 0 146
1818 }
1819 26 sv_catpvn(out, rec, CV_LINE);
1820 26 }
1821  
1822 //the _atom_site_anisotrop loop's header, as cv_anisou_pdb() and cv_cif_aniso_rows() write it
1823 static const char cv_aniso_head[] =
1824 "loop_\n_atom_site_anisotrop.id\n_atom_site_anisotrop.type_symbol\n"
1825 "_atom_site_anisotrop.U[1][1]\n_atom_site_anisotrop.U[2][2]\n"
1826 "_atom_site_anisotrop.U[3][3]\n_atom_site_anisotrop.U[1][2]\n"
1827 "_atom_site_anisotrop.U[1][3]\n_atom_site_anisotrop.U[2][3]\n";
1828  
1829 /*cv_anisou_pdb() -- an ANISOU record of a PDB file, for the atom just written.
1830 One per atom: a record after one that has had its own is passed over, as is one
1831 after an atom the options left out.*/
1832 32 static void cv_anisou_pdb(pTHX_ cv_w *CSP_RESTRICT w, const char *CSP_RESTRICT line, STRLEN llen){
1833 IV u[6];
1834 bool have[6];
1835 32 ▶ if (!w->keep_aniso || !w->last_kept || w->err) return;
Branch: 3 branches
BranchTrueFalseTotal
if (!w->keep_aniso || !w->last_kept || w->err) return; 22 10 32
if (!w->keep_aniso || !w->last_kept || w->err) return; 20 2 22
if (!w->keep_aniso || !w->last_kept || w->err) return; 0 20 20
1836 20 w->last_kept = FALSE;
1837 140 ▶ for (unsigned short i = 0; i < 6; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < 6; i++) 120 20 140
1838 120 have[i] = fld_iv(line, llen, (STRLEN)(28 + 7 * i), (STRLEN)(34 + 7 * i), &u[i]);
1839 20 ▶ if (w->to_pdb) {
Branch: 1 branch
BranchTrueFalseTotal
if (w->to_pdb) { 10 10 20
1840 10 cv_pdb_anisou(aTHX_ w->m_buf[w->cur], w->last_line, u, have);
1841 } else {
1842 10 SV *CSP_RESTRICT o = w->aniso;
1843 10 ▶ if (!w->n_aniso) sv_catpvn(o, cv_aniso_head, sizeof(cv_aniso_head) - 1);
Branch: 1 branch
BranchTrueFalseTotal
if (!w->n_aniso) sv_catpvn(o, cv_aniso_head, sizeof(cv_aniso_head) - 1); 3 7 10
1844 10 cv_cif_iv(aTHX_ o, w->last_have_serial, w->last_serial);
1845 {
1846 char el[2];
1847 20 ▶ for (STRLEN k = 0; k < w->last_el_n; k++) el[k] = (char)toUPPER((unsigned char)w->last_el[k]);
Branch: 2 branches
BranchTrueFalseTotal
for (STRLEN k = 0; k < w->last_el_n; k++) el[k] = (char)toUPPER((unsigned char)w->last_el[k]); 0 10 10
for (STRLEN k = 0; k < w->last_el_n; k++) el[k] = (char)toUPPER((unsigned char)w->last_el[k]); 10 10 20
1848 //an element is letters, and needs no quoting that could fail
1849 10 (void)cv_cif_val(aTHX_ o, el, w->last_el_n, '?');
1850 }
1851 70 ▶ for (unsigned short i = 0; i < 6; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < 6; i++) { 60 10 70
1852 char tmp[48];
1853 60 ▶ if (!have[i]) {
Branch: 1 branch
BranchTrueFalseTotal
if (!have[i]) { 0 60 60
1854 0 sv_catpvs(o, "? ");
1855 0 continue;
1856 }
1857 60 sv_catpvn(o, tmp, cv_u_text(u[i], tmp, sizeof(tmp)));
1858 60 sv_catpvs(o, " ");
1859 }
1860 10 SvPVX(o)[SvCUR(o) - 1] = '\n';
1861 }
1862 20 w->n_aniso++;
1863 }
1864  
1865 /*cv_aniso_add() -- a row of an mmCIF file's _atom_site_anisotrop, held until the
1866 atoms have all been written: the table usually comes after _atom_site, and
1867 going to PDB each row is written after its atom's record. v[] is in the order
1868 of cif_aniso_item[], NULL where the row has nothing.*/
1869 33 static void cv_aniso_add(pTHX_ cv_w *CSP_RESTRICT w, const char *const *CSP_RESTRICT v,
1870 const STRLEN *CSP_RESTRICT vn){
1871 cv_aniso *CSP_RESTRICT e;
1872 33 ▶ if (!w->keep_aniso || w->err) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!w->keep_aniso || w->err) return; 33 0 33
if (!w->keep_aniso || w->err) return; 0 33 33
1873 33 ▶ if (w->n_at == w->cap_at) {
Branch: 1 branch
BranchTrueFalseTotal
if (w->n_at == w->cap_at) { 9 24 33
1874 9 ▶ w->cap_at = w->cap_at ? 2 * w->cap_at : 256;
Branch: 1 branch
BranchTrueFalseTotal
w->cap_at = w->cap_at ? 2 * w->cap_at : 256; 0 9 9
1875 9 ▶ Renew(w->at, w->cap_at, cv_aniso);
Branch: 1 branch
BranchTrueFalseTotal
Renew(w->at, w->cap_at, cv_aniso); 0 9 9
1876 }
1877 33 e = &w->at[w->n_at++];
1878 33 ▶ e->have_id = v[0] && str2iv(v[0], vn[0], &e->id);
Branch: 2 branches
BranchTrueFalseTotal
e->have_id = v[0] && str2iv(v[0], vn[0], &e->id); 33 0 33
e->have_id = v[0] && str2iv(v[0], vn[0], &e->id); 33 0 33
1879 33 e->sym = v[1];
1880 33 ▶ e->sym_n = v[1] ? vn[1] : 0;
Branch: 1 branch
BranchTrueFalseTotal
e->sym_n = v[1] ? vn[1] : 0; 25 8 33
1881 231 ▶ for (unsigned short i = 0; i < 6; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < 6; i++) { 198 33 231
1882 198 e->u[i] = v[2 + i];
1883 198 ▶ e->u_n[i] = v[2 + i] ? vn[2 + i] : 0;
Branch: 1 branch
BranchTrueFalseTotal
e->u_n[i] = v[2 + i] ? vn[2 + i] : 0; 158 40 198
1884 }
1885 }
1886  
1887 446 static void cv_free(pTHX_ cv_w *CSP_RESTRICT w){
1888 738 ▶ if (w->m_buf) for (size_t i = 0; i < w->n_model; i++) SvREFCNT_dec(w->m_buf[i]);
Branch: 2 branches
BranchTrueFalseTotal
if (w->m_buf) for (size_t i = 0; i < w->n_model; i++) SvREFCNT_dec(w->m_buf[i]); 211 235 446
if (w->m_buf) for (size_t i = 0; i < w->n_model; i++) SvREFCNT_dec(w->m_buf[i]); 292 211 503
1889 446 Safefree(w->m_buf);
1890 446 Safefree(w->m_num);
1891 446 Safefree(w->at);
1892 446 Safefree(w->wid);
1893 446 SvREFCNT_dec(w->atoms);
1894 446 SvREFCNT_dec(w->aniso);
1895 446 SvREFCNT_dec(w->err);
1896 446 SvREFCNT_dec(w->p_chain);
1897 446 SvREFCNT_dec((SV *)w->chain_seen);
1898 446 SvREFCNT_dec((SV *)w->chain_order);
1899 446 Zero(w, 1, cv_w);
1900 446 }
1901  
1902 /*No CSP_RESTRICT on the parameter: the prototype is SAVEDESTRUCTOR_X's, not this
1903 file's.*/
1904 446 static void cv_free_cb(pTHX_ void *p){
1905 446 cv_free(aTHX_ (cv_w *)p);
1906 446 }
1907  
1908 /*buf is the whole file, and restrict here is the one that earns the most: every
1909 pointer the loop reads a field through -- line, s, nm_raw -- is derived from it,
1910 so one qualifier on the parameter covers all of them, and the compiler no longer
1911 has to assume that av_push() and the newSV*() calls between two reads of a
1912 record might have rewritten the record. It holds because the buffer belongs to
1913 the caller for the duration: slurp()'s Newx() block in _parse_file, and an SV we
1914 never touch again in _parse_string. Nothing in here writes through it.*/
1915 1067 static HV *parse_buf(pTHX_ const char *CSP_RESTRICT buf, STRLEN len, HV *CSP_RESTRICT opts,
1916 cv_w *CSP_RESTRICT cv)
1917 {
1918 //allocated once the options have been read; see below
1919 HV *out, *meta, *elements, *chain_elements;
1920 /*the tally of the chain the current residue belongs to, refreshed at each
1921 residue boundary; see chain_tally()*/
1922 1067 HV *cur_chain = NULL, *want_chain = NULL;
1923 //every residue key met so far, for run_key(); and per run, whether it was apart
1924 HV *res_seen;
1925 /*convert(): the header records it will read, by name, or NULL for every one;
1926 see the note at keep_loop in parse_cif_buf()*/
1927 HV *keep_rec;
1928 AV *res_apart;
1929 AV *atom_hv, *col[NCOL], *res_sum[NRSUM], *res_first, *res_last, *ter, *model_nums;
1930 //whole-structure statistics over the atoms that were kept
1931 1067 UV n_hydrogen = 0, n_water_atom = 0, bn = 0;
1932 1067 NV bmin = 0, bmax = 0, bsum = 0, xmin = 0, ymin = 0, zmin = 0, xmax = 0, ymax = 0, zmax = 0;
1933 1067 bool have_bbox = 0, have_res = 0;
1934 //the residue being accumulated
1935 1067 NV rsx = 0, rsy = 0, rsz = 0, rsb = 0;
1936 1067 UV rnc = 0, rnb = 0;
1937 /*counts of what was read, all of them only ever counted up. The model and
1938 residue numbers next to them stay signed: those are read out of the file's
1939 own columns, where a negative number is legal (residue numbering routinely
1940 starts before 1) or at worst is damage, and either way is better carried as
1941 the negative it was written as than wrapped to a huge unsigned one.*/
1942 1067 UV n_models = 0, n_anisou = 0, n_skipped = 0, n_atom = 0;
1943 1067 UV n_atom_rec = 0, n_het_rec = 0, lineno = 0;
1944 1067 IV want_model, cur_model = 1;
1945 bool keep_h, keep_water, keep_het, keep_meta, keep_anisou, keep_lineno, build_atoms;
1946 //the third shape, for a caller who wants no atoms; see where it is emitted
1947 bool slim, highest;
1948 //the atoms filed into their residues, when build_atoms; see filer_atom()
1949 atom_filer filer;
1950 //previous kept atom's residue identity, for boundary detection
1951 char p_chain[8], p_icode[4], p_resname[8];
1952 1067 IV p_resseq = 0, p_model = 0;
1953 1067 bool p_het = 0;
1954 //whether p_resseq was read off the record or is the 0 left by a field that was not a number
1955 1067 bool p_have_rs = 0;
1956 1067 STRLEN pos = 0;
1957  
1958 /*a negative model number means every model. Zero cannot be the sentinel:
1959 an ensemble whose models are numbered from 0 is unusual but legal, and
1960 "model 0" would then quietly mean "all of them".*/
1961 1067 want_model = opt_iv(aTHX_ opts, "model", 1);
1962 1061 keep_h = opt_bool(aTHX_ opts, "hydrogens", 1);
1963 1061 keep_water = opt_bool(aTHX_ opts, "waters", 1);
1964 1061 keep_het = opt_bool(aTHX_ opts, "hetatm", 1);
1965 1061 keep_meta = opt_bool(aTHX_ opts, "meta", 1);
1966 1061 keep_anisou = opt_bool(aTHX_ opts, "anisou", 0);
1967 1061 keep_lineno = opt_bool(aTHX_ opts, "lineno", 0);
1968 1061 build_atoms = opt_bool(aTHX_ opts, "atom_hashes", 0);
1969 1061 ▶ slim = !build_atoms && opt_bool(aTHX_ opts, "slim", 0);
Branch: 2 branches
BranchTrueFalseTotal
slim = !build_atoms && opt_bool(aTHX_ opts, "slim", 0); 317 744 1061
slim = !build_atoms && opt_bool(aTHX_ opts, "slim", 0); 32 285 317
1970 1061 highest = opt_bool(aTHX_ opts, "altloc_highest", 0);
1971 1061 want_chain = opt_chains(aTHX_ opts);
1972 1059 ▶ keep_rec = cv ? opt_plain_hv(aTHX_ opts, "keep") : NULL;
Branch: 1 branch
BranchTrueFalseTotal
keep_rec = cv ? opt_plain_hv(aTHX_ opts, "keep") : NULL; 212 847 1059
1973 1057 p_chain[0] = p_icode[0] = p_resname[0] = '\0';
1974  
1975 /*Nothing is allocated until the options are in hand, because reading one
1976 can die -- an object whose numeric overload throws, handed in as `model' --
1977 and everything made before that would be unreachable and never freed.*/
1978 1057 out = newHV(); meta = newHV(); elements = newHV(); chain_elements = newHV();
1979 1057 atom_hv = newAV();
1980 1057 res_first = newAV(); res_last = newAV();
1981 1057 ter = newAV(); model_nums = newAV();
1982 1057 res_seen = newHV(); res_apart = newAV();
1983 19026 ▶ for (unsigned short i = 0; i < NCOL; i++) col[i] = newAV();
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < NCOL; i++) col[i] = newAV(); 17969 1057 19026
1984 7399 ▶ for (unsigned short i = 0; i < NRSUM; i++) res_sum[i] = newAV();
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < NRSUM; i++) res_sum[i] = newAV(); 6342 1057 7399
1985 1057 ▶ if (build_atoms) filer_init(aTHX_ &filer, highest);
Branch: 1 branch
BranchTrueFalseTotal
if (build_atoms) filer_init(aTHX_ &filer, highest); 744 313 1057
1986  
1987 185103 ▶ while (pos < len) {
Branch: 1 branch
BranchTrueFalseTotal
while (pos < len) { 184890 213 185103
1988 184890 const char *CSP_RESTRICT line = buf + pos;
1989 184890 const char *nl = (const char *)memchr(line, '\n', len - pos);
1990 184890 ▶ STRLEN llen = nl ? (STRLEN)(nl - line) : (len - pos);
Branch: 1 branch
BranchTrueFalseTotal
STRLEN llen = nl ? (STRLEN)(nl - line) : (len - pos); 184845 45 184890
1991 bool het;
1992 STRLEN serial_from;
1993 bool at_end;//this line is END, and the last one read
1994 184890 ▶ pos += llen + (nl ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
pos += llen + (nl ? 1 : 0); 184845 45 184890
1995 184890 lineno++;
1996 993009 ▶ while (llen && (line[llen - 1] == '\r' || line[llen - 1] == ' ' || line[llen - 1] == '\t'))
Branch: 4 branches
BranchTrueFalseTotal
while (llen && (line[llen - 1] == '\r' || line[llen - 1] == ' ' || line[llen - 1] == '\t')) 993008 1 993009
while (llen && (line[llen - 1] == '\r' || line[llen - 1] == ' ' || line[llen - 1] == '\t')) 4 993004 993008
while (llen && (line[llen - 1] == '\r' || line[llen - 1] == ' ' || line[llen - 1] == '\t')) 808115 184889 993004
while (llen && (line[llen - 1] == '\r' || line[llen - 1] == ' ' || line[llen - 1] == '\t')) 0 184889 184889
1997 808119 llen--;//DOS line ends, and the trailing blanks of a padded record
1998 352368 ▶ if (llen == 0) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (llen == 0) continue; 1 184889 184890
1999 /*END closes the file, as gemmi 0.7.5 reads it. What follows it -- the
2000 second pose a docking program appends, a second structure concatenated
2001 onto the first -- is not this structure, and was read into it, its
2002 residues filed over the first one's under the same numbers. The record
2003 itself is filed and counted below, as it always was; the loop ends after
2004 it.*/
2005 184889 ▶ at_end = (llen == 3 && rec_is(line, "END", 3));
Branch: 2 branches
BranchTrueFalseTotal
at_end = (llen == 3 && rec_is(line, "END", 3)); 862 184027 184889
at_end = (llen == 3 && rec_is(line, "END", 3)); 844 18 862
2006  
2007 184889 ▶ if (pdb_coord_rec(line, llen, &het, &serial_from)) {
Branch: 1 branch
BranchTrueFalseTotal
if (pdb_coord_rec(line, llen, &het, &serial_from)) { 165572 19317 184889
2008 const char *s, *nm_raw;
2009 STRLEN nm_rawlen, n;
2010 char elbuf[4], chain[4], icode[2], resname[8];;
2011 STRLEN ellen;
2012 bool known, have_rs;
2013 res_info ri;
2014 //the residue number, read once: the boundary test below wants it,
2015 //and so does whichever of the two shapes the record is emitted in
2016 165572 IV rs = 0;
2017 STRLEN resname_len;
2018  
2019 165572 ▶ if (het) n_het_rec++; else n_atom_rec++;
Branch: 1 branch
BranchTrueFalseTotal
if (het) n_het_rec++; else n_atom_rec++; 21183 144389 165572
2020 //an ANISOU after an atom the options leave out is left out with it
2021 165572 ▶ if (cv) cv->last_kept = FALSE;
Branch: 1 branch
BranchTrueFalseTotal
if (cv) cv->last_kept = FALSE; 41088 124484 165572
2022 165572 ▶ if (want_model >= 0 && cur_model != want_model) { n_skipped++; continue; }
Branch: 2 branches
BranchTrueFalseTotal
if (want_model >= 0 && cur_model != want_model) { n_skipped++; continue; } 95236 70336 165572
if (want_model >= 0 && cur_model != want_model) { n_skipped++; continue; } 12215 83021 95236
2023 153357 ▶ if (het && !keep_het) { n_skipped++; continue; }
Branch: 2 branches
BranchTrueFalseTotal
if (het && !keep_het) { n_skipped++; continue; } 20100 133257 153357
if (het && !keep_het) { n_skipped++; continue; } 1175 18925 20100
2024  
2025 //residue name, columns 18-20
2026 152182 n = fld(line, llen, 17, 19, &s);
2027 152182 resname_len = n > sizeof(resname) - 1 ? sizeof(resname) - 1 : n;
2028 152182 memcpy(resname, s, resname_len);
2029 152182 resname[resname_len] = '\0';
2030 152182 known = res_lookup(resname, resname_len, &ri);
2031 152182 ▶ if (!keep_water && known && ri.type == RT_WATER) { n_skipped++; continue; }
Branch: 3 branches
BranchTrueFalseTotal
if (!keep_water && known && ri.type == RT_WATER) { n_skipped++; continue; } 7648 144534 152182
if (!keep_water && known && ri.type == RT_WATER) { n_skipped++; continue; } 7553 95 7648
if (!keep_water && known && ri.type == RT_WATER) { n_skipped++; continue; } 2180 5373 7553
2032  
2033 /*chain, column 22 and nothing else. Column 21 is blank in the
2034 format, and what a file puts there is the fourth letter of a
2035 CHARMM or NAMD residue name -- TIP3, POPC -- which the column-21
2036 fallback this used to have read as chain '3' or 'C' whenever the
2037 chain column was left blank. It never served the two-character
2038 chain id it was written for either: that fills column 22 too, so
2039 the fallback was not reached and "AB" came back "B" regardless.
2040 Column 22 alone is Biopython's rule (PDBParser, line[21]); gemmi
2041 reads 21-22 as one field and so answers '3' for the TIP3.*/
2042 150002 chain[0] = '\0';
2043 150002 ▶ if (llen > 21 && line[21] != ' ') { chain[0] = line[21]; chain[1] = '\0'; }
Branch: 2 branches
BranchTrueFalseTotal
if (llen > 21 && line[21] != ' ') { chain[0] = line[21]; chain[1] = '\0'; } 150002 0 150002
if (llen > 21 && line[21] != ' ') { chain[0] = line[21]; chain[1] = '\0'; } 148109 1893 150002
2044 150002 ▶ if (want_chain) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_chain) { 7107 142895 150002
2045 7107 ▶ if (!hv_exists(want_chain, chain, (I32)strlen(chain))) { n_skipped++; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (!hv_exists(want_chain, chain, (I32)strlen(chain))) { n_skipped++; continue; } 4013 3094 7107
2046 }
2047 //atom name, columns 13-16, kept untrimmed for the element rule
2048 145989 nm_rawlen = 0;
2049 145989 nm_raw = line;
2050 145989 ▶ if (llen > 12) {
Branch: 1 branch
BranchTrueFalseTotal
if (llen > 12) { 145989 0 145989
2051 145989 STRLEN to = 15 >= llen ? llen - 1 : 15;
2052 145989 nm_raw = line + 12;
2053 145989 nm_rawlen = to - 12 + 1;
2054 }
2055 //element, columns 77-78, guessed from the name when absent
2056 145989 ellen = fld(line, llen, 76, 77, &s);
2057 145989 ▶ if (ellen) {
Branch: 1 branch
BranchTrueFalseTotal
if (ellen) { 145674 315 145989
2058 STRLEN k;
2059 145674 ▶ if (ellen > 2) ellen = 2;
Branch: 1 branch
BranchTrueFalseTotal
if (ellen > 2) ellen = 2; 0 145674 145674
2060 291749 ▶ for (k = 0; k < ellen; k++) elbuf[k] = (char)toUPPER((unsigned char)s[k]);
Branch: 2 branches
BranchTrueFalseTotal
for (k = 0; k < ellen; k++) elbuf[k] = (char)toUPPER((unsigned char)s[k]); 1 146074 146075
for (k = 0; k < ellen; k++) elbuf[k] = (char)toUPPER((unsigned char)s[k]); 146075 145674 291749
2061 /*and not believed unless it spells an element. A file written
2062 before the element column existed keeps the entry id in columns
2063 73-80 instead, so what sits where the element goes is '1G' and
2064 every atom in pdb1gdr reads as element '1' -- which also stops
2065 hydrogens => 0 from finding the hydrogens. A field that is not
2066 letters is not an element, and the atom name knows better.*/
2067 290277 ▶ for (k = 0; k < ellen; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < ellen; k++) { 146074 144203 290277
2068 146074 ▶ if (!isALPHA((unsigned char)elbuf[k])) { ellen = 0; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (!isALPHA((unsigned char)elbuf[k])) { ellen = 0; break; } 1471 144603 146074
2069 }
2070 }
2071 145989 ▶ if (!ellen) ellen = guess_element_res(nm_raw, nm_rawlen, resname, resname_len, elbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (!ellen) ellen = guess_element_res(nm_raw, nm_rawlen, resname, resname_len, elbuf); 1786 144203 145989
2072 /*settled: the one spelling everything downstream sees, so that the
2073 atom's own element, the whole-structure tally and the per-chain
2074 tally cannot disagree about what to call a zinc*/
2075 145989 elem_case(elbuf, ellen);
2076 145989 ▶ if (!keep_h && ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) { n_skipped++; continue; }
Branch: 4 branches
BranchTrueFalseTotal
if (!keep_h && ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) { n_skipped++; continue; } 7204 138785 145989
if (!keep_h && ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) { n_skipped++; continue; } 7168 36 7204
if (!keep_h && ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) { n_skipped++; continue; } 5604 1564 7168
if (!keep_h && ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) { n_skipped++; continue; } 0 5604 5604
2077  
2078 /*Kept, and for convert() written out rather than built: what it wants is
2079 the record's fields as read, and none of the residue bookkeeping below.*/
2080 144425 ▶ if (cv) {
Branch: 1 branch
BranchTrueFalseTotal
if (cv) { 35758 108667 144425
2081 //the five numbers' columns, in CV_* order
2082 static const STRLEN num_from[CV_NNUM] = { 30, 38, 46, 54, 60 };
2083 static const STRLEN num_to[CV_NNUM] = { 37, 45, 53, 59, 65 };
2084 bool got[CV_NNUM];
2085 char chg_swap[2];//a sign-first charge, turned round
2086 cv_atom ca;
2087 35758 ca.het = het;
2088 35758 ▶ ca.rtype = known ? ri.type : RT_OTHER;
Branch: 1 branch
BranchTrueFalseTotal
ca.rtype = known ? ri.type : RT_OTHER; 35367 391 35758
2089 35758 ca.model = cur_model;
2090 35758 ca.serial = ca.resseq = 0;
2091 35758 ca.have_serial = fld_hy36(line, llen, serial_from, 10, &ca.serial);
2092 35758 ca.name_n = fld(line, llen, 12, 15, &ca.name);
2093 35758 ca.name4 = nm_raw;
2094 35758 ca.name4_n = nm_rawlen;
2095 35758 ca.alt_n = fld(line, llen, 16, 16, &ca.alt);
2096 35758 ca.resname = resname;
2097 35758 ca.resname_n = resname_len;
2098 35758 ca.chain = chain;
2099 35758 ca.chain_n = strlen(chain);
2100 35758 ca.have_rs = fld_hy36(line, llen, 22, 25, &ca.resseq);
2101 35758 ▶ ca.icode = line + (llen > 26 ? 26 : 0);
Branch: 1 branch
BranchTrueFalseTotal
ca.icode = line + (llen > 26 ? 26 : 0); 35758 0 35758
2102 35758 ▶ ca.icode_n = (llen > 26 && line[26] != ' ') ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
ca.icode_n = (llen > 26 && line[26] != ' ') ? 1 : 0; 35758 0 35758
ca.icode_n = (llen > 26 && line[26] != ' ') ? 1 : 0; 161 35597 35758
2103 35758 ca.el = elbuf;
2104 35758 ca.el_n = ellen;
2105 35758 ca.chg_n = pdb_charge(line, llen, chg_swap, &ca.chg);
2106 214548 ▶ for (unsigned short k = 0; k < CV_NNUM; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < CV_NNUM; k++) { 178790 35758 214548
2107 178790 ca.num[k] = 0;
2108 178790 ca.num_n[k] = fld(line, llen, num_from[k], num_to[k], &ca.num_s[k]);
2109 178790 ▶ got[k] = ca.num_n[k] && str2nv(ca.num_s[k], ca.num_n[k], &ca.num[k]);
Branch: 2 branches
BranchTrueFalseTotal
got[k] = ca.num_n[k] && str2nv(ca.num_s[k], ca.num_n[k], &ca.num[k]); 178790 0 178790
got[k] = ca.num_n[k] && str2nv(ca.num_s[k], ca.num_n[k], &ca.num[k]); 178790 0 178790
2110 }
2111 35758 ▶ ca.have_xyz = got[CV_X] && got[CV_Y] && got[CV_Z];
Branch: 3 branches
BranchTrueFalseTotal
ca.have_xyz = got[CV_X] && got[CV_Y] && got[CV_Z]; 35758 0 35758
ca.have_xyz = got[CV_X] && got[CV_Y] && got[CV_Z]; 35758 0 35758
ca.have_xyz = got[CV_X] && got[CV_Y] && got[CV_Z]; 35758 0 35758
2112 35758 ca.have_occ = got[CV_OCC];
2113 35758 ca.have_b = got[CV_B];
2114 35758 cv_put(aTHX_ cv, &ca);
2115 35758 n_atom++;
2116 35758 continue;
2117 }
2118  
2119 /*kept. The residue boundary is settled first, before this atom has
2120 been added to anything, so that closing the previous residue is a
2121 matter of flushing what is already there. Everything the test needs
2122 is read from the record's own columns.*/
2123 {
2124 bool changed;
2125 108667 have_rs = fld_hy36(line, llen, 22, 25, &rs);
2126 108667 ▶ icode[0] = (llen > 26 && line[26] != ' ') ? line[26] : '\0';
Branch: 2 branches
BranchTrueFalseTotal
icode[0] = (llen > 26 && line[26] != ' ') ? line[26] : '\0'; 108666 1 108667
icode[0] = (llen > 26 && line[26] != ' ') ? line[26] : '\0'; 849 107817 108666
2127 108667 icode[1] = '\0';
2128 217334 changed = !have_res
2129 107855 ▶ || have_rs != p_have_rs
Branch: 1 branch
BranchTrueFalseTotal
|| have_rs != p_have_rs 107839 16 107855
2130 107839 ▶ || rs != p_resseq
Branch: 1 branch
BranchTrueFalseTotal
|| rs != p_resseq 92969 14870 107839
2131 92969 ▶ || p_model != cur_model
Branch: 1 branch
BranchTrueFalseTotal
|| p_model != cur_model 92968 1 92969
2132 92968 ▶ || p_het != het
Branch: 1 branch
BranchTrueFalseTotal
|| p_het != het 92957 11 92968
2133 92957 ▶ || strcmp(p_chain, chain) != 0
Branch: 1 branch
BranchTrueFalseTotal
|| strcmp(p_chain, chain) != 0 92948 9 92957
2134 92948 ▶ || strcmp(p_icode, icode) != 0
Branch: 1 branch
BranchTrueFalseTotal
|| strcmp(p_icode, icode) != 0 92774 174 92948
2135 216522 ▶ || strcmp(p_resname, resname) != 0;
Branch: 2 branches
BranchTrueFalseTotal
|| strcmp(p_resname, resname) != 0; 107855 812 108667
|| strcmp(p_resname, resname) != 0; 7 92767 92774
2136 108667 ▶ if (changed) {
Branch: 1 branch
BranchTrueFalseTotal
if (changed) { 15900 92767 108667
2137 15900 ▶ if (have_res) {
Branch: 1 branch
BranchTrueFalseTotal
if (have_res) { 15088 812 15900
2138 15088 av_push(res_last, newSVuv(n_atom - 1));
2139 15088 flush_residue(aTHX_ res_sum, rsx, rsy, rsz, rnc, rsb, rnb);
2140 }
2141 15900 rsx = rsy = rsz = rsb = 0; rnc = rnb = 0;
2142 15900 av_push(res_first, newSVuv(n_atom));
2143 15900 have_res = 1;
2144 15900 p_resseq = rs;
2145 15900 p_have_rs = have_rs;
2146 15900 p_model = cur_model;
2147 15900 p_het = het;
2148 15900 my_strlcpy(p_chain, chain, sizeof(p_chain));
2149 15900 my_strlcpy(p_icode, icode, sizeof(p_icode));
2150 15900 my_strlcpy(p_resname, resname, sizeof(p_resname));
2151 15900 cur_chain = chain_tally(aTHX_ chain_elements, cur_model,
2152 chain, strlen(chain));
2153 {
2154 //the altloc, column 17, of the record the run starts on
2155 bool apart;
2156 15900 SV *key = run_key(aTHX_ res_seen, cur_model, chain, strlen(chain),
2157 have_rs, rs, icode, resname, resname_len, het,
2158 15900 ▶ llen > 16 && line[16] != ' ', &apart);
Branch: 2 branches
BranchTrueFalseTotal
llen > 16 && line[16] != ' ', &apart); 15900 0 15900
llen > 16 && line[16] != ' ', &apart); 25 15875 15900
2159 15900 av_push(res_apart, newSViv(apart));
2160 /*and the residue's identity, once, where the residue
2161 begins: see the note where the atom's own fields are
2162 emitted for why this is per residue in this shape and per
2163 atom in the other*/
2164 15900 ▶ if (build_atoms) filer_run(aTHX_ &filer, key);
Branch: 1 branch
BranchTrueFalseTotal
if (build_atoms) filer_run(aTHX_ &filer, key); 15389 511 15900
2165 }
2166 15900 ▶ if (build_atoms || slim) {
Branch: 2 branches
BranchTrueFalseTotal
if (build_atoms || slim) { 511 15389 15900
if (build_atoms || slim) { 348 163 511
2167 15737 av_push(col[C_RESNAME], csp_str(aTHX_ resname, resname_len));
2168 15737 av_push(col[C_CHAIN], csp_str(aTHX_ chain, strlen(chain)));
2169 15737 ▶ av_push(col[C_RESSEQ], have_rs ? newSViv(rs) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(col[C_RESSEQ], have_rs ? newSViv(rs) : newSV(0)); 15720 17 15737
2170 15737 av_push(col[C_ICODE], csp_str(aTHX_ icode, icode[0] ? 1 : 0));
2171 15737 av_push(col[C_HET], newSViv(het));
2172 15737 av_push(col[C_MODEL], newSViv(cur_model));
2173 }
2174 //the first atom's element, which is all slim keeps of it
2175 15900 ▶ if (slim) av_push(col[C_ELEMENT], csp_str(aTHX_ elbuf, ellen));
Branch: 1 branch
BranchTrueFalseTotal
if (slim) av_push(col[C_ELEMENT], csp_str(aTHX_ elbuf, ellen)); 348 15552 15900
2176 }
2177 }
2178 //the atom's own fields
2179 {
2180 const char *nm_s, *alt_s, *chg_s;
2181 STRLEN nm_n, alt_n, chg_n;
2182 char chg_swap[2];//a sign-first charge, turned round
2183 108667 IV serial = 0;
2184 bool have_serial, have_occ;
2185 NV xv, yv, zv, bv, ov;
2186 108667 bool have_xyz = fld_nv(line, llen, 30, 37, &xv)
2187 108667 & fld_nv(line, llen, 38, 45, &yv)
2188 108667 & fld_nv(line, llen, 46, 53, &zv);
2189 108667 bool have_b = fld_nv(line, llen, 60, 65, &bv);
2190  
2191 108667 have_occ = fld_nv(line, llen, 54, 59, &ov);
2192 108667 have_serial = fld_hy36(line, llen, serial_from, 10, &serial);
2193 108667 nm_n = fld(line, llen, 12, 15, &nm_s);
2194 108667 alt_n = fld(line, llen, 16, 16, &alt_s);
2195 108667 chg_n = pdb_charge(line, llen, chg_swap, &chg_s);
2196 /*The sums and extremes are gathered here rather than in Perl
2197 because they have to touch every atom whether or not the caller
2198 wanted per-atom hashes. Doing them in the loop that is already
2199 reading the numbers costs nothing; doing them again in Perl
2200 costs more than the whole parse.
2201  
2202 Over the finite ones only. A field that says nan is passed through
2203 as the NaN it names, and the box, the centres and the B-factor
2204 extremes took it in or not according to where in the file it fell:
2205 first, and every comparison after it failed, so the box was NaN;
2206 anywhere later, and it was quietly left out.*/
2207 108667 ▶ if (have_xyz && nv_is_finite(xv) && nv_is_finite(yv) && nv_is_finite(zv)) {
Branch: 4 branches
BranchTrueFalseTotal
if (have_xyz && nv_is_finite(xv) && nv_is_finite(yv) && nv_is_finite(zv)) { 108659 8 108667
if (have_xyz && nv_is_finite(xv) && nv_is_finite(yv) && nv_is_finite(zv)) { 108652 7 108659
if (have_xyz && nv_is_finite(xv) && nv_is_finite(yv) && nv_is_finite(zv)) { 108652 0 108652
if (have_xyz && nv_is_finite(xv) && nv_is_finite(yv) && nv_is_finite(zv)) { 108652 0 108652
2208 108652 rsx += xv; rsy += yv; rsz += zv; rnc++;
2209 108652 ▶ if (!have_bbox) {
Branch: 1 branch
BranchTrueFalseTotal
if (!have_bbox) { 805 107847 108652
2210 805 xmin = xmax = xv; ymin = ymax = yv; zmin = zmax = zv;
2211 805 have_bbox = 1;
2212 } else {
2213 107847 ▶ if (xv < xmin) xmin = xv; else if (xv > xmax) xmax = xv;
Branch: 2 branches
BranchTrueFalseTotal
if (xv < xmin) xmin = xv; else if (xv > xmax) xmax = xv; 8003 99844 107847
if (xv < xmin) xmin = xv; else if (xv > xmax) xmax = xv; 10240 89604 99844
2214 107847 ▶ if (yv < ymin) ymin = yv; else if (yv > ymax) ymax = yv;
Branch: 2 branches
BranchTrueFalseTotal
if (yv < ymin) ymin = yv; else if (yv > ymax) ymax = yv; 4728 103119 107847
if (yv < ymin) ymin = yv; else if (yv > ymax) ymax = yv; 7865 95254 103119
2215 107847 ▶ if (zv < zmin) zmin = zv; else if (zv > zmax) zmax = zv;
Branch: 2 branches
BranchTrueFalseTotal
if (zv < zmin) zmin = zv; else if (zv > zmax) zmax = zv; 4961 102886 107847
if (zv < zmin) zmin = zv; else if (zv > zmax) zmax = zv; 11632 91254 102886
2216 }
2217 }
2218 108667 ▶ if (have_b && nv_is_finite(bv)) {
Branch: 2 branches
BranchTrueFalseTotal
if (have_b && nv_is_finite(bv)) { 108640 27 108667
if (have_b && nv_is_finite(bv)) { 108638 2 108640
2219 108638 rsb += bv; rnb++;
2220 108638 ▶ if (!bn++) { bmin = bmax = bv; }
Branch: 1 branch
BranchTrueFalseTotal
if (!bn++) { bmin = bmax = bv; } 796 107842 108638
2221 107842 ▶ else if (bv < bmin) bmin = bv;
Branch: 1 branch
BranchTrueFalseTotal
else if (bv < bmin) bmin = bv; 3465 104377 107842
2222 104377 ▶ else if (bv > bmax) bmax = bv;
Branch: 1 branch
BranchTrueFalseTotal
else if (bv > bmax) bmax = bv; 2748 101629 104377
2223 108638 bsum += bv;
2224 }
2225 108667 ▶ if (ellen) {
Branch: 1 branch
BranchTrueFalseTotal
if (ellen) { 108667 0 108667
2226 108667 elem_bump(aTHX_ elements, elbuf, ellen);
2227 108667 ▶ if (cur_chain) elem_bump(aTHX_ cur_chain, elbuf, ellen);
Branch: 1 branch
BranchTrueFalseTotal
if (cur_chain) elem_bump(aTHX_ cur_chain, elbuf, ellen); 108667 0 108667
2228 108667 ▶ if (ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) n_hydrogen++;
Branch: 3 branches
BranchTrueFalseTotal
if (ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) n_hydrogen++; 108320 347 108667
if (ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) n_hydrogen++; 93908 14412 108320
if (ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) n_hydrogen++; 1 93907 93908
2229 }
2230 108667 ▶ if (known && ri.type == RT_WATER) n_water_atom++;
Branch: 2 branches
BranchTrueFalseTotal
if (known && ri.type == RT_WATER) n_water_atom++; 106871 1796 108667
if (known && ri.type == RT_WATER) n_water_atom++; 8197 98674 106871
2231  
2232 /*Two shapes to hand back, and never both, because building every
2233 atom twice -- once as columns here, once as a hash in Perl
2234 afterwards -- was costing more than everything else in the read
2235 put together. The hash is what Chem::Structure::Parser wants, built here
2236 where the fields already are; the columns are what the low-level
2237 parse hands to anyone calling it directly.*/
2238 108667 ▶ if (build_atoms) {
Branch: 1 branch
BranchTrueFalseTotal
if (build_atoms) { 106459 2208 108667
2239 atom_fields af;
2240 HV *a;
2241 106459 af.name = csp_str(aTHX_ nm_s, nm_n);
2242 106459 af.alt = alt_s; af.alt_n = alt_n;
2243 106459 af.el = elbuf; af.el_n = ellen;
2244 106459 af.chg = chg_s; af.chg_n = chg_n;
2245 106459 af.serial = serial; af.have_serial = have_serial;
2246 106459 af.x = xv; af.y = yv; af.z = zv; af.have_xyz = have_xyz;
2247 106459 af.occ = ov; af.have_occ = have_occ;
2248 106459 af.b = bv; af.have_b = have_b;
2249 106459 af.het = het;
2250 106459 a = atom_hash(aTHX_ &filer.keys, &af);
2251 106459 av_push(atom_hv, newRV_noinc((SV *)a));
2252 106459 filer_atom(aTHX_ &filer, a, af.name, alt_n, have_occ, ov);
2253 2208 ▶ } else if (slim) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (slim) { 1787 421 2208
2254 /*Slim: a caller who asked for no atoms gets the name and
2255 the position and nothing else, per atom. Those four are
2256 what the Perl half still asks of the atoms once there are
2257 no atom hashes -- whether a nucleotide-named residue has a
2258 sugar, and whether a HETATM residue after the polymer is
2259 bonded to it -- and the rest were twelve SVs an atom that
2260 nothing read: 4fqr's atoms => 0 read peaked at 98 MB
2261 with them.*/
2262 1787 av_push(col[C_NAME], csp_str(aTHX_ nm_s, nm_n));
2263 1787 ▶ av_push(col[C_X], have_xyz ? newSVnv(xv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(col[C_X], have_xyz ? newSVnv(xv) : newSV(0)); 1787 0 1787
2264 1787 ▶ av_push(col[C_Y], have_xyz ? newSVnv(yv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(col[C_Y], have_xyz ? newSVnv(yv) : newSV(0)); 1787 0 1787
2265 1787 ▶ av_push(col[C_Z], have_xyz ? newSVnv(zv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(col[C_Z], have_xyz ? newSVnv(zv) : newSV(0)); 1787 0 1787
2266 } else {
2267 421 ▶ av_push(col[C_SERIAL], have_serial ? newSViv(serial) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(col[C_SERIAL], have_serial ? newSViv(serial) : newSV(0)); 420 1 421
2268 421 av_push(col[C_NAME], csp_str(aTHX_ nm_s, nm_n));
2269 421 av_push(col[C_ALTLOC], csp_str(aTHX_ alt_s, alt_n));
2270 421 ▶ av_push(col[C_X], have_xyz ? newSVnv(xv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(col[C_X], have_xyz ? newSVnv(xv) : newSV(0)); 417 4 421
2271 421 ▶ av_push(col[C_Y], have_xyz ? newSVnv(yv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(col[C_Y], have_xyz ? newSVnv(yv) : newSV(0)); 417 4 421
2272 421 ▶ av_push(col[C_Z], have_xyz ? newSVnv(zv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(col[C_Z], have_xyz ? newSVnv(zv) : newSV(0)); 417 4 421
2273 421 ▶ av_push(col[C_OCC], have_occ ? newSVnv(ov) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(col[C_OCC], have_occ ? newSVnv(ov) : newSV(0)); 402 19 421
2274 421 ▶ av_push(col[C_B], have_b ? newSVnv(bv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(col[C_B], have_b ? newSVnv(bv) : newSV(0)); 402 19 421
2275 421 av_push(col[C_ELEMENT], csp_str(aTHX_ elbuf, ellen));
2276 421 av_push(col[C_CHARGE], csp_str(aTHX_ chg_s, chg_n));
2277 }
2278 }
2279  
2280 /*The residue's identity, per atom, for the columnar shape. In the
2281 other shape it was emitted at the residue boundary above, one entry
2282 per residue rather than one per atom: it is read at the index a
2283 residue starts on either way, and six strings and integers per atom
2284 against six per residue was a third of everything the parse built:
2285 reading the coordinate section of 200 entries of PDBbind v2020 went
2286 from 1.95 s to 1.59 s, and the peak memory of parsing the largest of
2287 them (4fqr, 90,792 atoms) from 153 MB to 126 MB. Per atom is still
2288 what a caller who asked for columns gets, because there the columns
2289 are the answer. The line number below stays per atom in both, being
2290 a fact about the record rather than about the residue.*/
2291 108667 ▶ if (!build_atoms && !slim) {
Branch: 2 branches
BranchTrueFalseTotal
if (!build_atoms && !slim) { 2208 106459 108667
if (!build_atoms && !slim) { 421 1787 2208
2292 421 av_push(col[C_RESNAME], csp_str(aTHX_ resname, resname_len));
2293 421 av_push(col[C_CHAIN], csp_str(aTHX_ chain, strlen(chain)));
2294 421 ▶ av_push(col[C_RESSEQ], have_rs ? newSViv(rs) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(col[C_RESSEQ], have_rs ? newSViv(rs) : newSV(0)); 420 1 421
2295 421 av_push(col[C_ICODE], csp_str(aTHX_ icode, icode[0] ? 1 : 0));
2296 421 av_push(col[C_HET], newSViv(het));
2297 421 av_push(col[C_MODEL], newSViv(cur_model));
2298 }
2299 108667 ▶ if (keep_lineno) av_push(col[C_LINENO], newSVuv(lineno));
Branch: 1 branch
BranchTrueFalseTotal
if (keep_lineno) av_push(col[C_LINENO], newSVuv(lineno)); 0 108667 108667
2300  
2301 108667 n_atom++;
2302 108667 continue;
2303 }
2304  
2305 19317 ▶ if (llen >= 6 && memcmp(line, "ANISOU", 6) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (llen >= 6 && memcmp(line, "ANISOU", 6) == 0) { 18453 864 19317
if (llen >= 6 && memcmp(line, "ANISOU", 6) == 0) { 34 18419 18453
2306 34 n_anisou++;
2307 34 ▶ if (cv) {
Branch: 1 branch
BranchTrueFalseTotal
if (cv) { 32 2 34
2308 32 cv_anisou_pdb(aTHX_ cv, line, llen);
2309 32 continue;
2310 }
2311 2 ▶ if (!keep_anisou) continue;//fall through to meta
Branch: 1 branch
BranchTrueFalseTotal
if (!keep_anisou) continue;//fall through to meta 1 1 2
2312 }
2313 19284 ▶ if (llen >= 5 && memcmp(line, "MODEL", 5) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (llen >= 5 && memcmp(line, "MODEL", 5) == 0) { 18421 863 19284
if (llen >= 5 && memcmp(line, "MODEL", 5) == 0) { 585 17836 18421
2314 IV m;
2315 585 n_models++;
2316 585 ▶ cur_model = fld_iv(line, llen, 10, 13, &m) ? m : (IV)n_models;
Branch: 1 branch
BranchTrueFalseTotal
cur_model = fld_iv(line, llen, 10, 13, &m) ? m : (IV)n_models; 584 1 585
2317 585 av_push(model_nums, newSViv(cur_model));
2318 585 continue;
2319 }
2320 18699 ▶ if (llen >= 6 && memcmp(line, "ENDMDL", 6) == 0) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (llen >= 6 && memcmp(line, "ENDMDL", 6) == 0) continue; 17836 863 18699
if (llen >= 6 && memcmp(line, "ENDMDL", 6) == 0) continue; 585 17251 17836
2321 18114 ▶ if (llen >= 3 && memcmp(line, "TER", 3) == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (llen >= 3 && memcmp(line, "TER", 3) == 0) { 18114 0 18114
if (llen >= 3 && memcmp(line, "TER", 3) == 0) { 703 17411 18114
2322 HV *t;
2323 const char *s;
2324 STRLEN n;
2325 IV iv;
2326 //convert() writes its own, where its polymer runs end
2327 703 ▶ if (cv) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (cv) continue; 122 581 703
2328 581 t = newHV();
2329 581 n = fld(line, llen, 17, 19, &s); (void)hv_stores(t, "resname", newSVpvn(s, n));
2330 581 n = fld(line, llen, 21, 21, &s); (void)hv_stores(t, "chain", newSVpvn(s, n));
2331 581 n = fld(line, llen, 26, 26, &s); (void)hv_stores(t, "icode", newSVpvn(s, n));
2332 581 ▶ (void)hv_stores(t, "resseq", fld_hy36(line, llen, 22, 25, &iv) ? newSViv(iv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(t, "resseq", fld_hy36(line, llen, 22, 25, &iv) ? newSViv(iv) : newSV(0)); 563 18 581
2333 581 (void)hv_stores(t, "model", newSViv(cur_model));
2334 581 av_push(ter, newRV_noinc((SV *)t));
2335 581 continue;
2336 }
2337  
2338 /*everything else is a header/annotation record: keep the line whole and
2339 let Perl take it apart by column*/
2340 17411 ▶ if (keep_meta) {
Branch: 1 branch
BranchTrueFalseTotal
if (keep_meta) { 16018 1393 17411
2341 const char *s;
2342 16018 STRLEN n = fld(line, llen, 0, 5, &s);
2343 16018 ▶ if (n && (!keep_rec || hv_exists(keep_rec, s, (I32)n))) {
Branch: 3 branches
BranchTrueFalseTotal
if (n && (!keep_rec || hv_exists(keep_rec, s, (I32)n))) { 16018 0 16018
if (n && (!keep_rec || hv_exists(keep_rec, s, (I32)n))) { 3651 12367 16018
if (n && (!keep_rec || hv_exists(keep_rec, s, (I32)n))) { 2092 1559 3651
2344 14459 SV **slot = hv_fetch(meta, s, (I32)n, 0);
2345 AV *av;
2346 14459 ▶ if (slot && *slot && SvROK(*slot)) {
Branch: 3 branches
BranchTrueFalseTotal
if (slot && *slot && SvROK(*slot)) { 8122 6337 14459
if (slot && *slot && SvROK(*slot)) { 8122 0 8122
if (slot && *slot && SvROK(*slot)) { 8122 0 8122
2347 8122 av = (AV *)SvRV(*slot);
2348 } else {
2349 6337 av = newAV();
2350 6337 (void)hv_store(meta, s, (I32)n, newRV_noinc((SV *)av), 0);
2351 }
2352 14459 av_push(av, newSVpvn(line, llen));
2353 }
2354 }
2355 17411 ▶ if (at_end) break;
Branch: 1 branch
BranchTrueFalseTotal
if (at_end) break; 844 16567 17411
2356 }
2357 1057 ▶ if (have_res) {
Branch: 1 branch
BranchTrueFalseTotal
if (have_res) { 812 245 1057
2358 812 av_push(res_last, newSVuv(n_atom - 1));
2359 812 flush_residue(aTHX_ res_sum, rsx, rsy, rsz, rnc, rsb, rnb);
2360 }
2361  
2362 1057 (void)hv_stores(out, "atoms", newRV_noinc((SV *)atom_hv));
2363 7399 ▶ for (unsigned short i = 0; i < NRSUM; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < NRSUM; i++) 6342 1057 7399
2364 6342 (void)hv_store(out, res_sum_name[i], (I32)strlen(res_sum_name[i]),
2365 newRV_noinc((SV *)res_sum[i]), 0);
2366 1057 (void)hv_stores(out, "elements", newRV_noinc((SV *)elements));
2367 1057 (void)hv_stores(out, "chain_elements", newRV_noinc((SV *)chain_elements));
2368 1057 (void)hv_stores(out, "n_hydrogens", newSVuv(n_hydrogen));
2369 1057 (void)hv_stores(out, "n_water_atoms", newSVuv(n_water_atom));
2370 1057 ▶ if (bn) {
Branch: 1 branch
BranchTrueFalseTotal
if (bn) { 796 261 1057
2371 796 HV *b = newHV();
2372 796 (void)hv_stores(b, "min", newSVnv(bmin));
2373 796 (void)hv_stores(b, "max", newSVnv(bmax));
2374 796 (void)hv_stores(b, "mean", newSVnv(bsum / (NV)bn));
2375 796 (void)hv_stores(b, "n", newSVuv(bn));
2376 796 (void)hv_stores(out, "bfactor_stats", newRV_noinc((SV *)b));
2377 } else {
2378 261 (void)hv_stores(out, "bfactor_stats", newSV(0));
2379 }
2380 1057 ▶ if (have_bbox) {
Branch: 1 branch
BranchTrueFalseTotal
if (have_bbox) { 805 252 1057
2381 805 HV *bb = newHV();
2382 805 AV *ctr = newAV();
2383 805 (void)hv_stores(bb, "xmin", newSVnv(xmin));
2384 805 (void)hv_stores(bb, "ymin", newSVnv(ymin));
2385 805 (void)hv_stores(bb, "zmin", newSVnv(zmin));
2386 805 (void)hv_stores(bb, "xmax", newSVnv(xmax));
2387 805 (void)hv_stores(bb, "ymax", newSVnv(ymax));
2388 805 (void)hv_stores(bb, "zmax", newSVnv(zmax));
2389 805 av_push(ctr, newSVnv((xmin + xmax) / 2));
2390 805 av_push(ctr, newSVnv((ymin + ymax) / 2));
2391 805 av_push(ctr, newSVnv((zmin + zmax) / 2));
2392 805 (void)hv_stores(out, "bbox", newRV_noinc((SV *)bb));
2393 805 (void)hv_stores(out, "center", newRV_noinc((SV *)ctr));
2394 } else {
2395 252 (void)hv_stores(out, "bbox", newSV(0));
2396 252 (void)hv_stores(out, "center", newSV(0));
2397 }
2398  
2399 19026 ▶ for (unsigned short i = 0; i < NCOL; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < NCOL; i++) { 17969 1057 19026
2400 17969 ▶ if (i == C_LINENO && !keep_lineno) { SvREFCNT_dec((SV *)col[i]); continue; }
Branch: 2 branches
BranchTrueFalseTotal
if (i == C_LINENO && !keep_lineno) { SvREFCNT_dec((SV *)col[i]); continue; } 1057 16912 17969
if (i == C_LINENO && !keep_lineno) { SvREFCNT_dec((SV *)col[i]); continue; } 1057 0 1057
2401 16912 (void)hv_store(out, col_name[i], (I32)strlen(col_name[i]), newRV_noinc((SV *)col[i]), 0);
2402 }
2403 1057 (void)hv_stores(out, "res_first", newRV_noinc((SV *)res_first));
2404 1057 (void)hv_stores(out, "res_last", newRV_noinc((SV *)res_last));
2405 1057 (void)hv_stores(out, "res_apart", newRV_noinc((SV *)res_apart));
2406 1057 SvREFCNT_dec((SV *)res_seen);
2407 1057 ▶ if (build_atoms) filer_done(aTHX_ &filer, out);
Branch: 1 branch
BranchTrueFalseTotal
if (build_atoms) filer_done(aTHX_ &filer, out); 744 313 1057
2408 1057 (void)hv_stores(out, "ter", newRV_noinc((SV *)ter));
2409 1057 (void)hv_stores(out, "meta", newRV_noinc((SV *)meta));
2410 1057 (void)hv_stores(out, "model_numbers", newRV_noinc((SV *)model_nums));
2411 1057 (void)hv_stores(out, "n_atoms", newSVuv(n_atom));
2412 1057 (void)hv_stores(out, "n_residues", newSVuv((UV)(av_len(res_first) + 1)));
2413 1057 ▶ (void)hv_stores(out, "n_models", newSVuv(n_models ? n_models : 1));
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(out, "n_models", newSVuv(n_models ? n_models : 1)); 175 882 1057
2414 1057 (void)hv_stores(out, "n_anisou", newSVuv(n_anisou));
2415 1057 (void)hv_stores(out, "n_skipped", newSVuv(n_skipped));
2416 1057 (void)hv_stores(out, "n_atom_records", newSVuv(n_atom_rec));
2417 1057 (void)hv_stores(out, "n_hetatm_records", newSVuv(n_het_rec));
2418 1057 (void)hv_stores(out, "n_lines", newSVuv(lineno));
2419 1057 (void)hv_stores(out, "format", newSVpvs("pdb"));
2420 1057 return out;
2421 }
2422  
2423 /*mmCIF -- the same structures, written down differently.
2424  
2425 The same structures, written down differently. A PDB file is fixed columns; an
2426 mmCIF file is tag/value pairs and `loop_' tables, free-form, with quoting. So
2427 none of the column arithmetic above applies and the whole reader is separate --
2428 but it fills in exactly the same output hash, atom for atom and field for field,
2429 because everything above this point in the module and everything in Perl below
2430 it is written against that hash and not against either file format. A caller
2431 who reads 1cka.pdb and 1cka.cif gets two structures that compare equal.
2432  
2433 Where the two formats disagree about how to write the same fact, this reader
2434 converts to what the PDB reader would have produced: a formal charge of -1 comes
2435 back as "1-", auth_* identifiers are preferred over label_* ones because auth_*
2436 is what the PDB record carried, and a `.' or `?' -- mmCIF for "not applicable"
2437 and "unknown" -- comes back as the empty field the PDB record would have had*/
2438  
2439 //the token kinds the lexer below returns
2440 #define CT_EOF 0 //end of the buffer
2441 #define CT_VALUE 1 //a value, quoted or bare, including '.' and '?'
2442 #define CT_TAG 2 //_category.item
2443 #define CT_LOOP 3 //loop_
2444 #define CT_DATA 4 //data_<block>, with t->s the block name
2445 #define CT_SAVE 5 //save_<frame>, which this reader steps over
2446 #define CT_STOP 6 //stop_ or global_, likewise
2447  
2448 typedef struct {
2449 const char *buf, *end, *p;
2450 /*per quote character, ' then ": the stretch of one line that has been
2451 scanned for a closing quote and has none, from where the scan started to
2452 the line's end; NULL until one is found. See cif_next().*/
2453 const char *open_from[2], *open_eol[2];
2454 } cif_lex;
2455  
2456 typedef struct {
2457 const char *s;
2458 STRLEN n;
2459 unsigned short kind;//CT_*: seven token kinds and no sentinel
2460 /*a quoted value is text and nothing else: '.' in quotes is a full stop, and
2461 only a bare '.' is the null the format means*/
2462 bool quoted;
2463 } cif_tok;
2464  
2465 1294433 static bool cif_iskw(const char *CSP_RESTRICT s, STRLEN n, const char *CSP_RESTRICT kw, STRLEN kwn){
2466 1294433 ▶ if (n < kwn) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n < kwn) return 0; 0 1294433 1294433
2467 1560620 ▶ for (STRLEN i = 0; i < kwn; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (STRLEN i = 0; i < kwn; i++) 1532749 27871 1560620
2468 1532749 ▶ if (toLOWER((unsigned char)s[i]) != kw[i]) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (toLOWER((unsigned char)s[i]) != kw[i]) return 0; 90668 1442081 1532749
if (toLOWER((unsigned char)s[i]) != kw[i]) return 0; 1266562 266187 1532749
2469 27871 return 1;
2470 }
2471  
2472 11156064 static bool cif_space(char c){
2473 11156064 ▶ return c == ' ' || c == '\t' || c == '\r' || c == '\n';
Branch: 4 branches
BranchTrueFalseTotal
return c == ' ' || c == '\t' || c == '\r' || c == '\n'; 7629434 3526630 11156064
return c == ' ' || c == '\t' || c == '\r' || c == '\n'; 7629434 0 7629434
return c == ' ' || c == '\t' || c == '\r' || c == '\n'; 7629427 7 7629434
return c == ' ' || c == '\t' || c == '\r' || c == '\n'; 267421 7362006 7629427
2474 }
2475  
2476 //a bare '.' (not applicable) or '?' (unknown): the field was not filled in
2477 1702010 static bool cif_null(const cif_tok *CSP_RESTRICT t){
2478 1702010 ▶ return !t->quoted && t->n == 1 && (t->s[0] == '.' || t->s[0] == '?');
Branch: 4 branches
BranchTrueFalseTotal
return !t->quoted && t->n == 1 && (t->s[0] == '.' || t->s[0] == '?'); 1688547 13463 1702010
return !t->quoted && t->n == 1 && (t->s[0] == '.' || t->s[0] == '?'); 758865 929682 1688547
return !t->quoted && t->n == 1 && (t->s[0] == '.' || t->s[0] == '?'); 666367 92498 758865
return !t->quoted && t->n == 1 && (t->s[0] == '.' || t->s[0] == '?'); 193428 472939 666367
2479 }
2480  
2481 /*cif_next() -- one token. The four shapes a value can arrive in are a bare
2482 word, a quoted string, and a semicolon-delimited text field, which is the only
2483 one that can span lines and the only one whose delimiter is position-sensitive:
2484 a ';' is a delimiter only as the first character of a line, and anywhere else it
2485 is an ordinary character in a value.*/
2486 1834153 static void cif_next(cif_lex *CSP_RESTRICT lx, cif_tok *CSP_RESTRICT t){
2487 1834153 const char *p = lx->p, *end = lx->end;
2488 1834153 t->quoted = 0;
2489 for (;;) {
2490 3804146 ▶ while (p < end && cif_space(*p)) p++;
Branch: 2 branches
BranchTrueFalseTotal
while (p < end && cif_space(*p)) p++; 3802877 1269 3804146
while (p < end && cif_space(*p)) p++; 1961306 1841571 3802877
2491 1842840 ▶ if (p >= end) { lx->p = end; t->kind = CT_EOF; t->s = end; t->n = 0; return; }
Branch: 1 branch
BranchTrueFalseTotal
if (p >= end) { lx->p = end; t->kind = CT_EOF; t->s = end; t->n = 0; return; } 1269 1841571 1842840
2492 1841571 ▶ if (*p == '#') { //a comment runs to the end of its line
Branch: 1 branch
BranchTrueFalseTotal
if (*p == '#') { //a comment runs to the end of its line 8687 1832884 1841571
2493 23209 ▶ while (p < end && *p != '\n') p++;
Branch: 2 branches
BranchTrueFalseTotal
while (p < end && *p != '\n') p++; 23205 4 23209
while (p < end && *p != '\n') p++; 14522 8683 23205
2494 8687 continue;
2495 }
2496 1832884 break;
2497 }
2498 1832884 ▶ if (*p == ';' && (p == lx->buf || p[-1] == '\n')) {
Branch: 3 branches
BranchTrueFalseTotal
if (*p == ';' && (p == lx->buf || p[-1] == '\n')) { 131 1832753 1832884
if (*p == ';' && (p == lx->buf || p[-1] == '\n')) { 131 0 131
if (*p == ';' && (p == lx->buf || p[-1] == '\n')) { 131 0 131
2499 131 const char *s = p + 1, *q = s;
2500 7 for (;;) {
2501 138 const char *CSP_RESTRICT nl = (const char *)memchr(q, '\n', (STRLEN)(end - q));
2502 138 ▶ if (!nl) { q = end; lx->p = end; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (!nl) { q = end; lx->p = end; break; } 0 138 138
2503 138 ▶ if (nl + 1 < end && nl[1] == ';') { q = nl; lx->p = nl + 2; break; }
Branch: 2 branches
BranchTrueFalseTotal
if (nl + 1 < end && nl[1] == ';') { q = nl; lx->p = nl + 2; break; } 137 1 138
if (nl + 1 < end && nl[1] == ';') { q = nl; lx->p = nl + 2; break; } 130 7 137
2504 8 ▶ if (nl + 1 >= end) { q = nl; lx->p = end; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (nl + 1 >= end) { q = nl; lx->p = end; break; } 1 7 8
2505 7 q = nl + 1;
2506 }
2507 //the CR of a DOS line end is the line end's, not the value's; the ones
2508 //inside the field are taken out by cif_sv()
2509 131 ▶ if (q > s && q[-1] == '\r') q--;
Branch: 2 branches
BranchTrueFalseTotal
if (q > s && q[-1] == '\r') q--; 131 0 131
if (q > s && q[-1] == '\r') q--; 1 130 131
2510 131 t->s = s;
2511 131 t->n = (STRLEN)(q - s);
2512 131 t->kind = CT_VALUE;
2513 131 t->quoted = 1;
2514 131 return;
2515 }
2516 1832753 ▶ if (*p == '\'' || *p == '"') {
Branch: 2 branches
BranchTrueFalseTotal
if (*p == '\'' || *p == '"') { 1809607 23146 1832753
if (*p == '\'' || *p == '"') { 10959 1798648 1809607
2517 /*the closing quote is one followed by whitespace or the end of the file.
2518 Anything else is a quote inside the value, which is how a CIF writes
2519 O5' without escaping it.
2520  
2521 A quoted value cannot run past the end of its line -- CIF 1.1 has no
2522 such string, and a multi-line value is the semicolon field above. So a
2523 quote its line does not close was never an opening quote, and the token
2524 is read as a bare word that happens to begin with one. Scanning on for
2525 the closing quote would instead swallow every row below it into one
2526 atom's name; ending the value at the line end would keep the rows but
2527 leave this one short, and every value after it one column out. Read as
2528 a word, 'CA in an _atom_site row is an atom named 'CA and the loop stays
2529 in step.
2530  
2531 Every such word sent the scan to the end of its line again, so a line of
2532 them cost the square of its length: 40,000 unclosed quotes on one line
2533 took a second, against a hundredth for the same words without the quotes.
2534 A scan that found no closing quote from s to the end of the line has
2535 answered the question for any later s on that line too, since the stretch
2536 it would search is part of the one already searched; that answer is kept
2537 per quote character, and reused.*/
2538 34105 char qc = *p;
2539 34105 const unsigned short qi = (qc == '"');//which slot of open_from[]
2540 34105 const char *CSP_RESTRICT s = p + 1, *q = s;
2541 34105 bool closed = TRUE;//FALSE = the line or file ended first: not a quote after all
2542 34105 ▶ if (lx->open_eol[qi] && s >= lx->open_from[qi] && s <= lx->open_eol[qi]) {
Branch: 3 branches
BranchTrueFalseTotal
if (lx->open_eol[qi] && s >= lx->open_from[qi] && s <= lx->open_eol[qi]) { 14105 20000 34105
if (lx->open_eol[qi] && s >= lx->open_from[qi] && s <= lx->open_eol[qi]) { 0 20000 20000
if (lx->open_eol[qi] && s >= lx->open_from[qi] && s <= lx->open_eol[qi]) { 0 20000 20000
2543 20000 closed = FALSE;
2544 } else {
2545 for (;;) {
2546 250588 ▶ while (q < end && *q != qc && *q != '\n') q++;
Branch: 3 branches
BranchTrueFalseTotal
while (q < end && *q != qc && *q != '\n') q++; 250587 1 250588
while (q < end && *q != qc && *q != '\n') q++; 216484 34103 250587
while (q < end && *q != qc && *q != '\n') q++; 216481 3 216484
2547 34107 ▶ if (q >= end || *q == '\n') { closed = FALSE; break; }
Branch: 2 branches
BranchTrueFalseTotal
if (q >= end || *q == '\n') { closed = FALSE; break; } 34106 1 34107
if (q >= end || *q == '\n') { closed = FALSE; break; } 3 34103 34106
2548 34103 ▶ if (q + 1 >= end || cif_space(q[1])) break;
Branch: 2 branches
BranchTrueFalseTotal
if (q + 1 >= end || cif_space(q[1])) break; 34103 0 34103
if (q + 1 >= end || cif_space(q[1])) break; 20002 14101 34103
2549 20002 q++;
2550 }
2551 14105 ▶ if (!closed) { lx->open_from[qi] = s; lx->open_eol[qi] = q; }
Branch: 1 branch
BranchTrueFalseTotal
if (!closed) { lx->open_from[qi] = s; lx->open_eol[qi] = q; } 4 14101 14105
2552 }
2553 34105 ▶ if (closed) {
Branch: 1 branch
BranchTrueFalseTotal
if (closed) { 14101 20004 34105
2554 14101 t->s = s;
2555 14101 t->n = (STRLEN)(q - s);
2556 14101 t->kind = CT_VALUE;
2557 14101 t->quoted = 1;
2558 14101 ▶ lx->p = q < end ? q + 1 : end;
Branch: 1 branch
BranchTrueFalseTotal
lx->p = q < end ? q + 1 : end; 14101 0 14101
2559 14101 return;
2560 }
2561 }
2562  
2563 {
2564 1818652 const char *s = p;
2565 STRLEN n;
2566 7319085 ▶ while (p < end && !cif_space(*p)) p++;
Branch: 2 branches
BranchTrueFalseTotal
while (p < end && !cif_space(*p)) p++; 7319084 1 7319085
while (p < end && !cif_space(*p)) p++; 5500433 1818651 7319084
2567 1818652 n = (STRLEN)(p - s);
2568 1818652 lx->p = p;
2569 1818652 t->s = s;
2570 1818652 t->n = n;
2571 1818652 ▶ if (s[0] == '_') t->kind = CT_TAG;
Branch: 1 branch
BranchTrueFalseTotal
if (s[0] == '_') t->kind = CT_TAG; 32361 1786291 1818652
2572 1786291 ▶ else if (n == 5 && cif_iskw(s, n, "loop_", 5)) t->kind = CT_LOOP;
Branch: 2 branches
BranchTrueFalseTotal
else if (n == 5 && cif_iskw(s, n, "loop_", 5)) t->kind = CT_LOOP; 108231 1678060 1786291
else if (n == 5 && cif_iskw(s, n, "loop_", 5)) t->kind = CT_LOOP; 5300 102931 108231
2573 1780991 ▶ else if (n == 5 && cif_iskw(s, n, "stop_", 5)) t->kind = CT_STOP;
Branch: 2 branches
BranchTrueFalseTotal
else if (n == 5 && cif_iskw(s, n, "stop_", 5)) t->kind = CT_STOP; 102931 1678060 1780991
else if (n == 5 && cif_iskw(s, n, "stop_", 5)) t->kind = CT_STOP; 0 102931 102931
2574 1780991 ▶ else if (n == 7 && cif_iskw(s, n, "global_", 7)) t->kind = CT_STOP;
Branch: 2 branches
BranchTrueFalseTotal
else if (n == 7 && cif_iskw(s, n, "global_", 7)) t->kind = CT_STOP; 61301 1719690 1780991
else if (n == 7 && cif_iskw(s, n, "global_", 7)) t->kind = CT_STOP; 0 61301 61301
2575 1780991 ▶ else if (n >= 5 && cif_iskw(s, n, "data_", 5)) { t->kind = CT_DATA; t->s = s + 5; t->n = n - 5; }
Branch: 2 branches
BranchTrueFalseTotal
else if (n >= 5 && cif_iskw(s, n, "data_", 5)) { t->kind = CT_DATA; t->s = s + 5; t->n = n - 5; } 331241 1449750 1780991
else if (n >= 5 && cif_iskw(s, n, "data_", 5)) { t->kind = CT_DATA; t->s = s + 5; t->n = n - 5; } 651 330590 331241
2576 1780340 ▶ else if (n >= 5 && cif_iskw(s, n, "save_", 5)) { t->kind = CT_SAVE; t->s = s + 5; t->n = n - 5; }
Branch: 2 branches
BranchTrueFalseTotal
else if (n >= 5 && cif_iskw(s, n, "save_", 5)) { t->kind = CT_SAVE; t->s = s + 5; t->n = n - 5; } 330590 1449750 1780340
else if (n >= 5 && cif_iskw(s, n, "save_", 5)) { t->kind = CT_SAVE; t->s = s + 5; t->n = n - 5; } 0 330590 330590
2577 1780340 else t->kind = CT_VALUE;
2578 }
2579 }
2580  
2581 /*a tag is _category.item. Both halves are wanted -- the category says which
2582 table a loop is, the item says which column -- and both are matched without
2583 regard to case, which the format allows and real files use.*/
2584 46988 static STRLEN cif_split_tag(const char *CSP_RESTRICT s, STRLEN n, const char **CSP_RESTRICT item, STRLEN *CSP_RESTRICT itemn){
2585 46988 const char *dot = (const char *)memchr(s, '.', n);
2586 46988 ▶ if (!dot) { *item = s; *itemn = n; return n; } //core CIF: no category half
Branch: 1 branch
BranchTrueFalseTotal
if (!dot) { *item = s; *itemn = n; return n; } //core CIF: no category half 7 46981 46988
2587 46981 *item = dot + 1;
2588 46981 *itemn = n - (STRLEN)(dot - s) - 1;
2589 46981 return (STRLEN)(dot - s);
2590 }
2591  
2592 //the _atom_site columns this reader knows what to do with
2593 static const char *const cif_atom_item[] = {
2594 "group_pdb", "id", "type_symbol", "label_atom_id", "label_alt_id",
2595 "label_comp_id", "label_asym_id", "label_seq_id", "pdbx_pdb_ins_code",
2596 "cartn_x", "cartn_y", "cartn_z", "occupancy", "b_iso_or_equiv",
2597 "pdbx_formal_charge", "auth_seq_id", "auth_comp_id", "auth_asym_id",
2598 "auth_atom_id", "pdbx_pdb_model_num"
2599 };
2600 enum {
2601 A_GROUP, A_ID, A_SYMBOL, A_LATOM, A_ALT, A_LCOMP, A_LASYM, A_LSEQ, A_ICODE,
2602 A_X, A_Y, A_Z, A_OCC, A_B, A_CHARGE, A_ASEQ, A_ACOMP, A_AASYM, A_AATOM,
2603 A_MODEL, A_NFIELD
2604 };
2605  
2606 12282 static short int cif_atom_field(const char *CSP_RESTRICT item, STRLEN n){
2607 133338 ▶ for (short int i = 0; i < A_NFIELD; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (short int i = 0; i < A_NFIELD; i++) { 132802 536 133338
2608 132802 STRLEN kn = strlen(cif_atom_item[i]);
2609 132802 ▶ if (kn == n && cif_iskw(item, n, cif_atom_item[i], kn)) return i;
Branch: 2 branches
BranchTrueFalseTotal
if (kn == n && cif_iskw(item, n, cif_atom_item[i], kn)) return i; 22809 109993 132802
if (kn == n && cif_iskw(item, n, cif_atom_item[i], kn)) return i; 11746 11063 22809
2610 }
2611 536 return -1;
2612 }
2613  
2614 /*the _atom_site_anisotrop columns convert() carries, in the order cv_aniso_add()
2615 takes them. U only: the archive writes U, and a table written as B would want
2616 dividing by 8 pi**2 on the way to an ANISOU record, which is a conversion of the
2617 numbers and not of the format.*/
2618 static const char *const cif_aniso_item[] = {
2619 "id", "type_symbol", "u[1][1]", "u[2][2]", "u[3][3]", "u[1][2]", "u[1][3]", "u[2][3]"
2620 };
2621 #define CIF_NANISO 8
2622  
2623 48 static short int cif_aniso_field(const char *CSP_RESTRICT item, STRLEN n){
2624 196 ▶ for (short int i = 0; i < CIF_NANISO; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (short int i = 0; i < CIF_NANISO; i++) { 196 0 196
2625 196 STRLEN kn = strlen(cif_aniso_item[i]);
2626 196 ▶ if (kn == n && cif_iskw(item, n, cif_aniso_item[i], kn)) return i;
Branch: 2 branches
BranchTrueFalseTotal
if (kn == n && cif_iskw(item, n, cif_aniso_item[i], kn)) return i; 123 73 196
if (kn == n && cif_iskw(item, n, cif_aniso_item[i], kn)) return i; 48 75 123
2627 }
2628 0 return -1;
2629 }
2630  
2631 /*whether convert() reads a category of the header, by its lowercased name: the
2632 keep set it passes, or every category when there is none. No category it reads
2633 is anywhere near 64 characters long.*/
2634 7512 static bool cif_kept(pTHX_ HV *CSP_RESTRICT keep, const char *CSP_RESTRICT cat, STRLEN n){
2635 char lc[64];
2636 7512 ▶ if (!keep) return TRUE;
Branch: 1 branch
BranchTrueFalseTotal
if (!keep) return TRUE; 5291 2221 7512
2637 2221 ▶ if (n >= sizeof(lc)) return FALSE;
Branch: 1 branch
BranchTrueFalseTotal
if (n >= sizeof(lc)) return FALSE; 0 2221 2221
2638 28080 ▶ for (STRLEN i = 0; i < n; i++) lc[i] = (char)toLOWER((unsigned char)cat[i]);
Branch: 2 branches
BranchTrueFalseTotal
for (STRLEN i = 0; i < n; i++) lc[i] = (char)toLOWER((unsigned char)cat[i]); 0 25859 25859
for (STRLEN i = 0; i < n; i++) lc[i] = (char)toLOWER((unsigned char)cat[i]); 25859 2221 28080
2639 2221 return hv_exists(keep, lc, (I32)n);
2640 }
2641  
2642 /*A number in mmCIF, which may carry its standard uncertainty in parentheses
2643 after it: 1.000(2) is 1.000, as CIF 1.1's numeric syntax has it and as gemmi's
2644 cif::as_number() reads it. str2nv() takes the whole field or nothing -- the
2645 rule that keeps a PDB coordinate which overflowed into the next field from
2646 reading as its prefix -- so the uncertainty is taken off here, on the mmCIF
2647 side only, and a PDB field is held to the stricter rule.*/
2648 540462 static STRLEN cif_num_len(const char *CSP_RESTRICT s, STRLEN n){
2649 540462 ▶ if (n >= 3 && s[n - 1] == ')') {
Branch: 2 branches
BranchTrueFalseTotal
if (n >= 3 && s[n - 1] == ')') { 540438 24 540462
if (n >= 3 && s[n - 1] == ')') { 10 540428 540438
2650 10 STRLEN open_at = n - 2;
2651 20 ▶ while (open_at > 0 && isDIGIT((unsigned char)s[open_at])) open_at--;
Branch: 2 branches
BranchTrueFalseTotal
while (open_at > 0 && isDIGIT((unsigned char)s[open_at])) open_at--; 20 0 20
while (open_at > 0 && isDIGIT((unsigned char)s[open_at])) open_at--; 10 10 20
2652 10 ▶ if (s[open_at] == '(' && open_at < n - 2) n = open_at;
Branch: 2 branches
BranchTrueFalseTotal
if (s[open_at] == '(' && open_at < n - 2) n = open_at; 10 0 10
if (s[open_at] == '(' && open_at < n - 2) n = open_at; 9 1 10
2653 }
2654 540462 return n;
2655 }
2656  
2657 394099 static bool cif_nv(const char *CSP_RESTRICT s, STRLEN n, NV *CSP_RESTRICT out){
2658 394099 return str2nv(s, cif_num_len(s, n), out);
2659 }
2660  
2661 /*mmCIF writes a formal charge as a signed integer and PDB as a magnitude
2662 followed by its sign, so -1 there is "1-" here. A value of two characters that
2663 is not an integer is passed through: some writers already put the PDB spelling
2664 in this field.
2665  
2666 A charge of zero comes back as "0" rather than as nothing, because the two are
2667 different answers and the PDB reader keeps them apart: "the field was blank"
2668 against "the field said zero". mmCIF spells the first '?', which arrives here
2669 as a field that was never set, so nothing is lost by reading the second
2670 literally -- and 6cc9, which writes a 0 in columns 79-80, reads the same from
2671 either format because of it.*/
2672 85 static STRLEN cif_charge(const char *CSP_RESTRICT s, STRLEN n, char *CSP_RESTRICT buf){
2673 IV c;
2674 85 ▶ if (n == 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) return 0; 0 85 85
2675 85 ▶ if (!str2iv(s, n, &c)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!str2iv(s, n, &c)) { 1 84 85
2676 /*Passed through only when it could be the PDB spelling, which is two
2677 columns wide. Anything longer is not a charge, and was cut to its first
2678 two characters: an integer too wide for an IV -- twenty digits of one, or
2679 ten on a 32-bit perl -- came back as "-9".*/
2680 1 ▶ if (n > 2) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n > 2) return 0; 0 1 1
2681 //and a zero has no sign in that spelling either: '0-' reads as the '0'
2682 //the PDB reader gives for 4iu3's '0-'
2683 1 ▶ if (n == 2 && s[0] == '0' && (s[1] == '+' || s[1] == '-')) { buf[0] = '0'; return 1; }
Branch: 4 branches
BranchTrueFalseTotal
if (n == 2 && s[0] == '0' && (s[1] == '+' || s[1] == '-')) { buf[0] = '0'; return 1; } 1 0 1
if (n == 2 && s[0] == '0' && (s[1] == '+' || s[1] == '-')) { buf[0] = '0'; return 1; } 0 1 1
if (n == 2 && s[0] == '0' && (s[1] == '+' || s[1] == '-')) { buf[0] = '0'; return 1; } 0 0 0
if (n == 2 && s[0] == '0' && (s[1] == '+' || s[1] == '-')) { buf[0] = '0'; return 1; } 0 0 0
2684 1 memcpy(buf, s, n);
2685 1 return n;
2686 }
2687 84 ▶ if (c == 0) { buf[0] = '0'; return 1; }
Branch: 1 branch
BranchTrueFalseTotal
if (c == 0) { buf[0] = '0'; return 1; } 19 65 84
2688 /*out of range before the sign is taken off, because -c of IV_MIN -- which
2689 str2iv() accepts -- overflows, and came back as the charge "0-"*/
2690 65 ▶ if (c < -9 || c > 9) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (c < -9 || c > 9) return 0; 63 2 65
if (c < -9 || c > 9) return 0; 2 61 63
2691 61 ▶ if (c < 0) { c = -c; buf[1] = '-'; } else buf[1] = '+';
Branch: 1 branch
BranchTrueFalseTotal
if (c < 0) { c = -c; buf[1] = '-'; } else buf[1] = '+'; 22 39 61
2692 61 buf[0] = (char)('0' + c);
2693 61 return 2;
2694 }
2695  
2696 /*guess_element() reads an atom name out of the four columns a PDB record gives
2697 it, and its rule is where in those four the name starts. mmCIF has no columns,
2698 so the name goes back where the PDB convention would have put it before the
2699 question is asked. Only reached when _atom_site.type_symbol is missing, which
2700 is rare -- but a file without it should still not read CA as calcium, and, the
2701 residue name being what tells an ion apart, should not read ZN as Z either; see
2702 guess_element_res().*/
2703 161 static STRLEN cif_guess_element(const char *CSP_RESTRICT s, STRLEN n,
2704 const char *CSP_RESTRICT resname, STRLEN resname_len,
2705 char *CSP_RESTRICT buf){
2706 char pad[4];
2707 161 ▶ if (n >= 4) return guess_element_res(s, 4, resname, resname_len, buf);
Branch: 1 branch
BranchTrueFalseTotal
if (n >= 4) return guess_element_res(s, 4, resname, resname_len, buf); 0 161 161
2708 161 pad[0] = ' ';
2709 STRLEN i;
2710 391 ▶ for (i = 0; i < n; i++) pad[1 + i] = s[i];
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) pad[1 + i] = s[i]; 230 161 391
2711 414 ▶ for (i = n + 1; i < 4; i++) pad[i] = ' ';
Branch: 1 branch
BranchTrueFalseTotal
for (i = n + 1; i < 4; i++) pad[i] = ' '; 253 161 414
2712 161 return guess_element_res(pad, 4, resname, resname_len, buf);
2713 }
2714  
2715 /*Everything one _atom_site row needs to add itself to, gathered up so that a
2716 row can be handed to one function. A loop_ is the ordinary way to write the
2717 table and a run of plain tags is the legal way to write a table with one row in
2718 it; both end up in cif_atom_row() rather than in two copies of it.*/
2719 typedef struct {
2720 AV **col, **res_sum, *res_first, *res_last, *atom_hv, *model_nums;
2721 AV *res_apart;//per run, as in parse_buf(); see run_key()
2722 HV *elements, *chain_elements, *want_chain;
2723 HV *res_seen;//every residue key met so far, for run_key()
2724 HV *models_seen;//every model number met so far, as its decimal string
2725 //the tally of the chain the current residue belongs to; see chain_tally()
2726 HV *cur_chain;
2727 UV n_hydrogen, n_water_atom, bn;
2728 NV bmin, bmax, bsum, xmin, ymin, zmin, xmax, ymax, zmax, rsx, rsy, rsz, rsb;
2729 bool have_bbox, p_het, p_have_rs;//p_have_rs as in parse_buf()
2730 UV rnc, rnb, n_models, n_anisou, n_skipped, n_atom, n_atom_rec, n_het_rec;
2731 //counted up only; the numbers read out of the file stay signed, as in parse_buf
2732 IV want_model, cur_model;
2733 bool have_res, seen_model, keep_h, keep_water, keep_het, keep_anisou, build_atoms, slim;//as in parse_buf()
2734 bool model_col;//the _atom_site loop has a pdbx_PDB_model_num column; see cif_atom_row()
2735 atom_filer filer;//likewise, when build_atoms
2736 cv_w *cv;//convert()'s writer, which the kept atoms go to instead; NULL for a parse
2737 char p_icode[4], p_resname[8];
2738 /*the previous residue's chain id, as a pointer into the file buffer rather
2739 than a copy: an mmCIF chain id has no width, and a fixed buffer cut
2740 'SEG1PROA' to 'SEG1PRO', filing two chains that share seven letters as
2741 one. The buffer outlives the parse and is only read; see parse_buf().*/
2742 const char *p_chain;
2743 STRLEN p_chain_len;
2744 IV p_resseq, p_model;
2745 } cif_state;
2746  
2747 /*cif_model_seen() -- a row of a model not met before: counted, and listed.
2748  
2749 Counted as distinct numbers, not as changes of number from one row to the
2750 next. mmCIF does not require the rows to be in model order, and a file that
2751 lists chain A of models 1 and 2 and then chain B of models 1 and 2 has two
2752 models, not the four the changes add up to -- gemmi 0.7.5 finds two.*/
2753 890 static void cif_model_seen(pTHX_ cif_state *CSP_RESTRICT st, IV model){
2754 char mbuf[32];//an IV prints in at most 21 characters, sign included
2755 890 const STRLEN mlen = (STRLEN)my_snprintf(mbuf, sizeof(mbuf), "%" IVdf, model);
2756 890 ▶ if (hv_exists(st->models_seen, mbuf, (I32)mlen)) return;
Branch: 1 branch
BranchTrueFalseTotal
if (hv_exists(st->models_seen, mbuf, (I32)mlen)) return; 8 882 890
2757 882 (void)hv_store(st->models_seen, mbuf, (I32)mlen, newSV(0), 0);
2758 882 st->n_models++;
2759 882 av_push(st->model_nums, newSViv(model));
2760 }
2761  
2762 /*one row of _atom_site. v[] holds a pointer and a length per known column, or
2763 NULL where the row said `.' or `?' or the file has no such column, so that "the
2764 field was not given" is one test wherever it is asked.
2765  
2766 The order of the tests below is the order the PDB reader uses -- model, then
2767 HETATM, then water, then chain, then hydrogen -- because n_skipped counts what
2768 was thrown away and the two readers have to agree on the count as well as on
2769 the structure.*/
2770 82468 static void cif_atom_row(pTHX_ cif_state *CSP_RESTRICT st, const char **CSP_RESTRICT v, STRLEN *CSP_RESTRICT vn){
2771 char resname[8], icode[4], elbuf[4], chgbuf[4];
2772 STRLEN resname_len, chain_len, ellen, chg_n;
2773 //into the file buffer, as st->p_chain is, and for the same reason
2774 const char *chain, *CSP_RESTRICT nm_s, *CSP_RESTRICT alt_s;
2775 STRLEN nm_n, alt_n;
2776 res_info ri;
2777 bool known, het, changed, have_rs, have_serial, have_occ, have_xyz, have_b;
2778 82468 IV rs = 0, serial = 0, model;
2779 82468 NV xv = 0, yv = 0, zv = 0, ov = 0, bv = 0;
2780 /*Which model this row belongs to, counted before anything can skip the row.
2781  
2782 A loop with no pdbx_PDB_model_num column is model 1, as a PDB file with no
2783 MODEL record is. A row whose number is null -- `.' or `?' -- or is not a
2784 number is model 0, a model of its own: gemmi 0.7.5 files a null there (and
2785 refuses a file whose number is not one at all). Until 0.040 such a row was
2786 in whatever model the row before it was, which is an answer that depends on
2787 the order of the rows, and mmCIF does not fix that order; see
2788 cif_model_seen().*/
2789 82468 ▶ if (!st->model_col)
Branch: 1 branch
BranchTrueFalseTotal
if (!st->model_col) 161 82307 82468
2790 161 model = 1;
2791 82307 ▶ else if (!v[A_MODEL] || !str2iv(v[A_MODEL], vn[A_MODEL], &model))
Branch: 2 branches
BranchTrueFalseTotal
else if (!v[A_MODEL] || !str2iv(v[A_MODEL], vn[A_MODEL], &model)) 82289 18 82307
else if (!v[A_MODEL] || !str2iv(v[A_MODEL], vn[A_MODEL], &model)) 2 82287 82289
2792 20 model = 0;
2793 82468 ▶ if (!st->seen_model || model != st->cur_model) {
Branch: 2 branches
BranchTrueFalseTotal
if (!st->seen_model || model != st->cur_model) { 81845 623 82468
if (!st->seen_model || model != st->cur_model) { 267 81578 81845
2794 890 st->cur_model = model;
2795 890 st->seen_model = TRUE;
2796 890 cif_model_seen(aTHX_ st, model);
2797 }
2798  
2799 82468 ▶ het = v[A_GROUP] && vn[A_GROUP] >= 6 && cif_iskw(v[A_GROUP], vn[A_GROUP], "hetatm", 6);
Branch: 3 branches
BranchTrueFalseTotal
het = v[A_GROUP] && vn[A_GROUP] >= 6 && cif_iskw(v[A_GROUP], vn[A_GROUP], "hetatm", 6); 82465 3 82468
het = v[A_GROUP] && vn[A_GROUP] >= 6 && cif_iskw(v[A_GROUP], vn[A_GROUP], "hetatm", 6); 9455 73010 82465
het = v[A_GROUP] && vn[A_GROUP] >= 6 && cif_iskw(v[A_GROUP], vn[A_GROUP], "hetatm", 6); 9455 0 9455
2800 82468 ▶ if (het) st->n_het_rec++; else st->n_atom_rec++;
Branch: 1 branch
BranchTrueFalseTotal
if (het) st->n_het_rec++; else st->n_atom_rec++; 9455 73013 82468
2801  
2802 112116 ▶ if (st->want_model >= 0 && st->cur_model != st->want_model) { st->n_skipped++; return; }
Branch: 2 branches
BranchTrueFalseTotal
if (st->want_model >= 0 && st->cur_model != st->want_model) { st->n_skipped++; return; } 30641 51827 82468
if (st->want_model >= 0 && st->cur_model != st->want_model) { st->n_skipped++; return; } 3233 27408 30641
2803 79235 ▶ if (het && !st->keep_het) { st->n_skipped++; return; }
Branch: 2 branches
BranchTrueFalseTotal
if (het && !st->keep_het) { st->n_skipped++; return; } 9272 69963 79235
if (het && !st->keep_het) { st->n_skipped++; return; } 91 9181 9272
2804  
2805 //residue name: auth_comp_id is the name the PDB record carried
2806 {
2807 79144 ▶ const char *s = v[A_ACOMP] ? v[A_ACOMP] : v[A_LCOMP];
Branch: 1 branch
BranchTrueFalseTotal
const char *s = v[A_ACOMP] ? v[A_ACOMP] : v[A_LCOMP]; 79007 137 79144
2808 79144 ▶ STRLEN n = v[A_ACOMP] ? vn[A_ACOMP] : (v[A_LCOMP] ? vn[A_LCOMP] : 0);
Branch: 2 branches
BranchTrueFalseTotal
STRLEN n = v[A_ACOMP] ? vn[A_ACOMP] : (v[A_LCOMP] ? vn[A_LCOMP] : 0); 79007 137 79144
STRLEN n = v[A_ACOMP] ? vn[A_ACOMP] : (v[A_LCOMP] ? vn[A_LCOMP] : 0); 136 1 137
2809 79144 ▶ if (!s) { s = ""; n = 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (!s) { s = ""; n = 0; } 1 79143 79144
2810 79144 resname_len = n > sizeof(resname) - 1 ? sizeof(resname) - 1 : n;
2811 79144 memcpy(resname, s, resname_len);
2812 79144 resname[resname_len] = '\0';
2813 }
2814 79144 known = res_lookup(resname, resname_len, &ri);
2815 79144 ▶ if (!st->keep_water && known && ri.type == RT_WATER) { st->n_skipped++; return; }
Branch: 3 branches
BranchTrueFalseTotal
if (!st->keep_water && known && ri.type == RT_WATER) { st->n_skipped++; return; } 892 78252 79144
if (!st->keep_water && known && ri.type == RT_WATER) { st->n_skipped++; return; } 847 45 892
if (!st->keep_water && known && ri.type == RT_WATER) { st->n_skipped++; return; } 18 829 847
2816  
2817 79126 ▶ chain = v[A_AASYM] ? v[A_AASYM] : v[A_LASYM];
Branch: 1 branch
BranchTrueFalseTotal
chain = v[A_AASYM] ? v[A_AASYM] : v[A_LASYM]; 78632 494 79126
2818 79126 ▶ chain_len = v[A_AASYM] ? vn[A_AASYM] : (v[A_LASYM] ? vn[A_LASYM] : 0);
Branch: 2 branches
BranchTrueFalseTotal
chain_len = v[A_AASYM] ? vn[A_AASYM] : (v[A_LASYM] ? vn[A_LASYM] : 0); 78632 494 79126
chain_len = v[A_AASYM] ? vn[A_AASYM] : (v[A_LASYM] ? vn[A_LASYM] : 0); 73 421 494
2819 79126 ▶ if (!chain) { chain = ""; chain_len = 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (!chain) { chain = ""; chain_len = 0; } 421 78705 79126
2820 79126 ▶ if (st->want_chain && !hv_exists(st->want_chain, chain, (I32)chain_len)) {
Branch: 2 branches
BranchTrueFalseTotal
if (st->want_chain && !hv_exists(st->want_chain, chain, (I32)chain_len)) { 709 78417 79126
if (st->want_chain && !hv_exists(st->want_chain, chain, (I32)chain_len)) { 249 460 709
2821 249 st->n_skipped++;
2822 249 return;
2823 }
2824  
2825 78877 ▶ nm_s = v[A_AATOM] ? v[A_AATOM] : v[A_LATOM];
Branch: 1 branch
BranchTrueFalseTotal
nm_s = v[A_AATOM] ? v[A_AATOM] : v[A_LATOM]; 78731 146 78877
2826 78877 ▶ nm_n = v[A_AATOM] ? vn[A_AATOM] : (v[A_LATOM] ? vn[A_LATOM] : 0);
Branch: 2 branches
BranchTrueFalseTotal
nm_n = v[A_AATOM] ? vn[A_AATOM] : (v[A_LATOM] ? vn[A_LATOM] : 0); 78731 146 78877
nm_n = v[A_AATOM] ? vn[A_AATOM] : (v[A_LATOM] ? vn[A_LATOM] : 0); 141 5 146
2827 78877 ▶ if (!nm_s) { nm_s = ""; nm_n = 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (!nm_s) { nm_s = ""; nm_n = 0; } 5 78872 78877
2828 78877 ▶ alt_s = v[A_ALT] ? v[A_ALT] : "";
Branch: 1 branch
BranchTrueFalseTotal
alt_s = v[A_ALT] ? v[A_ALT] : ""; 398 78479 78877
2829 78877 ▶ alt_n = v[A_ALT] ? vn[A_ALT] : 0;
Branch: 1 branch
BranchTrueFalseTotal
alt_n = v[A_ALT] ? vn[A_ALT] : 0; 398 78479 78877
2830  
2831 78877 ellen = 0;
2832 78877 ▶ if (v[A_SYMBOL]) {
Branch: 1 branch
BranchTrueFalseTotal
if (v[A_SYMBOL]) { 78718 159 78877
2833 STRLEN k;
2834 78718 ellen = vn[A_SYMBOL] > 2 ? 2 : vn[A_SYMBOL];
2835 157702 ▶ for (k = 0; k < ellen; k++) elbuf[k] = (char)toUPPER((unsigned char)v[A_SYMBOL][k]);
Branch: 2 branches
BranchTrueFalseTotal
for (k = 0; k < ellen; k++) elbuf[k] = (char)toUPPER((unsigned char)v[A_SYMBOL][k]); 2 78982 78984
for (k = 0; k < ellen; k++) elbuf[k] = (char)toUPPER((unsigned char)v[A_SYMBOL][k]); 78984 78718 157702
2836 /*and not believed unless it spells an element, which is the rule parse_buf()
2837 applies to columns 77-80: a file converted from a pre-1996 entry carries that
2838 entry's id where the element goes ('1G' in pdb1gdr), and a type_symbol
2839 written as an empty string rather than as '.' or '?' is a null field that
2840 looks like a value. Either way the atom name knows better, and the PDB
2841 reader would have guessed -- which is the answer the two formats owe each
2842 other.*/
2843 157700 ▶ for (k = 0; k < ellen; k++)
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < ellen; k++) 78983 78717 157700
2844 78983 ▶ if (!isALPHA((unsigned char)elbuf[k])) { ellen = 0; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (!isALPHA((unsigned char)elbuf[k])) { ellen = 0; break; } 1 78982 78983
2845 }
2846 78877 ▶ if (!ellen) ellen = cif_guess_element(nm_s, nm_n, resname, resname_len, elbuf);
Branch: 1 branch
BranchTrueFalseTotal
if (!ellen) ellen = cif_guess_element(nm_s, nm_n, resname, resname_len, elbuf); 161 78716 78877
2847 //settled, and spelled as the PDB reader spells it; see elem_case()
2848 78877 elem_case(elbuf, ellen);
2849 78877 ▶ if (!st->keep_h && ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) {
Branch: 4 branches
BranchTrueFalseTotal
if (!st->keep_h && ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) { 848 78029 78877
if (!st->keep_h && ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) { 830 18 848
if (!st->keep_h && ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) { 819 11 830
if (!st->keep_h && ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) { 0 819 819
2850 11 st->n_skipped++;
2851 11 return;
2852 }
2853  
2854 //kept. auth_seq_id is the residue number the PDB record carried; label_seq_id
2855 //is the position in the entity, and is null for everything that is not polymer
2856 78866 have_rs = 0;
2857 78866 ▶ if (v[A_ASEQ]) have_rs = str2iv(v[A_ASEQ], vn[A_ASEQ], &rs);
Branch: 1 branch
BranchTrueFalseTotal
if (v[A_ASEQ]) have_rs = str2iv(v[A_ASEQ], vn[A_ASEQ], &rs); 78841 25 78866
2858 78866 ▶ if (!have_rs && v[A_LSEQ]) have_rs = str2iv(v[A_LSEQ], vn[A_LSEQ], &rs);
Branch: 2 branches
BranchTrueFalseTotal
if (!have_rs && v[A_LSEQ]) have_rs = str2iv(v[A_LSEQ], vn[A_LSEQ], &rs); 26 78840 78866
if (!have_rs && v[A_LSEQ]) have_rs = str2iv(v[A_LSEQ], vn[A_LSEQ], &rs); 0 26 26
2859 78866 ▶ if (!have_rs) rs = 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!have_rs) rs = 0; 26 78840 78866
2860 78866 ▶ icode[0] = (v[A_ICODE] && vn[A_ICODE]) ? v[A_ICODE][0] : '\0';
Branch: 2 branches
BranchTrueFalseTotal
icode[0] = (v[A_ICODE] && vn[A_ICODE]) ? v[A_ICODE][0] : '\0'; 659 78207 78866
icode[0] = (v[A_ICODE] && vn[A_ICODE]) ? v[A_ICODE][0] : '\0'; 659 0 659
2861 78866 icode[1] = '\0';
2862 78865 ▶ have_xyz = v[A_X] && v[A_Y] && v[A_Z]
Branch: 2 branches
BranchTrueFalseTotal
have_xyz = v[A_X] && v[A_Y] && v[A_Z] 78865 0 78865
have_xyz = v[A_X] && v[A_Y] && v[A_Z] 78865 0 78865
2863 78865 ▶ && cif_nv(v[A_X], vn[A_X], &xv)
Branch: 1 branch
BranchTrueFalseTotal
&& cif_nv(v[A_X], vn[A_X], &xv) 78865 0 78865
2864 78865 ▶ && cif_nv(v[A_Y], vn[A_Y], &yv)
Branch: 1 branch
BranchTrueFalseTotal
&& cif_nv(v[A_Y], vn[A_Y], &yv) 78865 0 78865
2865 157731 ▶ && cif_nv(v[A_Z], vn[A_Z], &zv);
Branch: 2 branches
BranchTrueFalseTotal
&& cif_nv(v[A_Z], vn[A_Z], &zv); 78865 1 78866
&& cif_nv(v[A_Z], vn[A_Z], &zv); 78865 0 78865
2866 78866 ▶ have_occ = v[A_OCC] && cif_nv(v[A_OCC], vn[A_OCC], &ov);
Branch: 2 branches
BranchTrueFalseTotal
have_occ = v[A_OCC] && cif_nv(v[A_OCC], vn[A_OCC], &ov); 78752 114 78866
have_occ = v[A_OCC] && cif_nv(v[A_OCC], vn[A_OCC], &ov); 78752 0 78752
2867 78866 ▶ have_b = v[A_B] && cif_nv(v[A_B], vn[A_B], &bv);
Branch: 2 branches
BranchTrueFalseTotal
have_b = v[A_B] && cif_nv(v[A_B], vn[A_B], &bv); 78752 114 78866
have_b = v[A_B] && cif_nv(v[A_B], vn[A_B], &bv); 78750 2 78752
2868 78866 ▶ have_serial = v[A_ID] && str2iv(v[A_ID], vn[A_ID], &serial);
Branch: 2 branches
BranchTrueFalseTotal
have_serial = v[A_ID] && str2iv(v[A_ID], vn[A_ID], &serial); 78865 1 78866
have_serial = v[A_ID] && str2iv(v[A_ID], vn[A_ID], &serial); 78864 1 78865
2869 78866 ▶ chg_n = v[A_CHARGE] ? cif_charge(v[A_CHARGE], vn[A_CHARGE], chgbuf) : 0;
Branch: 1 branch
BranchTrueFalseTotal
chg_n = v[A_CHARGE] ? cif_charge(v[A_CHARGE], vn[A_CHARGE], chgbuf) : 0; 85 78781 78866
2870  
2871 //convert(): written out rather than built, as in parse_buf()
2872 78866 ▶ if (st->cv) {
Branch: 1 branch
BranchTrueFalseTotal
if (st->cv) { 29279 49587 78866
2873 //the five numbers' columns, in CV_* order
2874 static const unsigned short num_col[CV_NNUM] = { A_X, A_Y, A_Z, A_OCC, A_B };
2875 cv_atom ca;
2876 29279 ca.het = het;
2877 29279 ▶ ca.rtype = known ? ri.type : RT_OTHER;
Branch: 1 branch
BranchTrueFalseTotal
ca.rtype = known ? ri.type : RT_OTHER; 28899 380 29279
2878 29279 ca.model = st->cur_model;
2879 29279 ca.have_serial = have_serial;
2880 29279 ca.serial = serial;
2881 29279 ca.name = nm_s;
2882 29279 ca.name_n = nm_n;
2883 29279 ca.name4 = NULL;
2884 29279 ca.name4_n = 0;
2885 29279 ca.alt = alt_s;
2886 29279 ca.alt_n = alt_n;
2887 29279 ca.resname = resname;
2888 29279 ca.resname_n = resname_len;
2889 29279 ca.chain = chain;
2890 29279 ca.chain_n = chain_len;
2891 29279 ca.have_rs = have_rs;
2892 29279 ca.resseq = rs;
2893 29279 ca.icode = icode;
2894 29279 ca.icode_n = icode[0] ? 1 : 0;
2895 29279 ca.el = elbuf;
2896 29279 ca.el_n = ellen;
2897 29279 ca.chg = chgbuf;
2898 29279 ca.chg_n = chg_n;
2899 29279 ca.num[CV_X] = xv;
2900 29279 ca.num[CV_Y] = yv;
2901 29279 ca.num[CV_Z] = zv;
2902 29279 ca.num[CV_OCC] = ov;
2903 29279 ca.num[CV_B] = bv;
2904 175674 ▶ for (unsigned short k = 0; k < CV_NNUM; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < CV_NNUM; k++) { 146395 29279 175674
2905 146395 const char *CSP_RESTRICT t = v[num_col[k]];
2906 146395 ▶ ca.num_s[k] = t ? t : "";
Branch: 1 branch
BranchTrueFalseTotal
ca.num_s[k] = t ? t : ""; 146275 120 146395
2907 146395 ▶ ca.num_n[k] = t ? cif_num_len(t, vn[num_col[k]]) : 0;
Branch: 1 branch
BranchTrueFalseTotal
ca.num_n[k] = t ? cif_num_len(t, vn[num_col[k]]) : 0; 146275 120 146395
2908 }
2909 29279 ca.have_xyz = have_xyz;
2910 29279 ca.have_occ = have_occ;
2911 29279 ca.have_b = have_b;
2912 29279 cv_put(aTHX_ st->cv, &ca);
2913 29279 st->n_atom++;
2914 29279 return;
2915 }
2916  
2917 99174 changed = !st->have_res
2918 49191 ▶ || have_rs != st->p_have_rs
Branch: 1 branch
BranchTrueFalseTotal
|| have_rs != st->p_have_rs 49176 15 49191
2919 49176 ▶ || rs != st->p_resseq
Branch: 1 branch
BranchTrueFalseTotal
|| rs != st->p_resseq 42631 6545 49176
2920 42631 ▶ || st->p_model != st->cur_model
Branch: 1 branch
BranchTrueFalseTotal
|| st->p_model != st->cur_model 42624 7 42631
2921 42624 ▶ || st->p_het != het
Branch: 1 branch
BranchTrueFalseTotal
|| st->p_het != het 42622 2 42624
2922 42622 ▶ || st->p_chain_len != chain_len
Branch: 1 branch
BranchTrueFalseTotal
|| st->p_chain_len != chain_len 42622 0 42622
2923 42622 ▶ || memcmp(st->p_chain, chain, chain_len) != 0
Branch: 1 branch
BranchTrueFalseTotal
|| memcmp(st->p_chain, chain, chain_len) != 0 42620 2 42622
2924 42620 ▶ || strcmp(st->p_icode, icode) != 0
Branch: 1 branch
BranchTrueFalseTotal
|| strcmp(st->p_icode, icode) != 0 42527 93 42620
2925 98778 ▶ || strcmp(st->p_resname, resname) != 0;
Branch: 2 branches
BranchTrueFalseTotal
|| strcmp(st->p_resname, resname) != 0; 49191 396 49587
|| strcmp(st->p_resname, resname) != 0; 3 42524 42527
2926 49587 ▶ if (changed) {
Branch: 1 branch
BranchTrueFalseTotal
if (changed) { 7063 42524 49587
2927 7063 ▶ if (st->have_res) {
Branch: 1 branch
BranchTrueFalseTotal
if (st->have_res) { 6667 396 7063
2928 6667 av_push(st->res_last, newSVuv(st->n_atom - 1));
2929 6667 flush_residue(aTHX_ st->res_sum, st->rsx, st->rsy, st->rsz, st->rnc, st->rsb, st->rnb);
2930 }
2931 7063 st->rsx = st->rsy = st->rsz = st->rsb = 0;
2932 7063 st->rnc = st->rnb = 0;
2933 7063 av_push(st->res_first, newSVuv(st->n_atom));
2934 7063 st->have_res = 1;
2935 7063 st->p_resseq = rs;
2936 7063 st->p_have_rs = have_rs;
2937 7063 st->p_model = st->cur_model;
2938 7063 st->p_het = het;
2939 7063 st->p_chain = chain;
2940 7063 st->p_chain_len = chain_len;
2941 7063 my_strlcpy(st->p_icode, icode, sizeof(st->p_icode));
2942 7063 my_strlcpy(st->p_resname, resname, sizeof(st->p_resname));
2943 7063 st->cur_chain = chain_tally(aTHX_ st->chain_elements, st->cur_model,
2944 chain, chain_len);
2945 {
2946 bool apart;
2947 7063 SV *key = run_key(aTHX_ st->res_seen, st->cur_model, chain, chain_len,
2948 have_rs, rs, icode, resname, resname_len, het, alt_n > 0, &apart);
2949 7063 av_push(st->res_apart, newSViv(apart));
2950 7063 ▶ if (st->build_atoms) filer_run(aTHX_ &st->filer, key);
Branch: 1 branch
BranchTrueFalseTotal
if (st->build_atoms) filer_run(aTHX_ &st->filer, key); 6899 164 7063
2951 }
2952 //and the residue's identity, once per residue, as parse_buf() emits it
2953 7063 ▶ if (st->build_atoms || st->slim) {
Branch: 2 branches
BranchTrueFalseTotal
if (st->build_atoms || st->slim) { 164 6899 7063
if (st->build_atoms || st->slim) { 97 67 164
2954 6996 av_push(st->col[C_RESNAME], csp_str(aTHX_ resname, resname_len));
2955 6996 av_push(st->col[C_CHAIN], csp_str(aTHX_ chain, chain_len));
2956 6996 ▶ av_push(st->col[C_RESSEQ], have_rs ? newSViv(rs) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(st->col[C_RESSEQ], have_rs ? newSViv(rs) : newSV(0)); 6981 15 6996
2957 6996 av_push(st->col[C_ICODE], csp_str(aTHX_ icode, icode[0] ? 1 : 0));
2958 6996 av_push(st->col[C_HET], newSViv(het));
2959 6996 av_push(st->col[C_MODEL], newSViv(st->cur_model));
2960 }
2961 7063 ▶ if (st->slim) av_push(st->col[C_ELEMENT], csp_str(aTHX_ elbuf, ellen));
Branch: 1 branch
BranchTrueFalseTotal
if (st->slim) av_push(st->col[C_ELEMENT], csp_str(aTHX_ elbuf, ellen)); 97 6966 7063
2962 }
2963  
2964 //over the finite values only, as parse_buf() gathers them and for its reason
2965 49587 ▶ if (have_xyz && nv_is_finite(xv) && nv_is_finite(yv) && nv_is_finite(zv)) {
Branch: 4 branches
BranchTrueFalseTotal
if (have_xyz && nv_is_finite(xv) && nv_is_finite(yv) && nv_is_finite(zv)) { 49586 1 49587
if (have_xyz && nv_is_finite(xv) && nv_is_finite(yv) && nv_is_finite(zv)) { 49586 0 49586
if (have_xyz && nv_is_finite(xv) && nv_is_finite(yv) && nv_is_finite(zv)) { 49586 0 49586
if (have_xyz && nv_is_finite(xv) && nv_is_finite(yv) && nv_is_finite(zv)) { 49586 0 49586
2966 49586 st->rsx += xv; st->rsy += yv; st->rsz += zv; st->rnc++;
2967 49586 ▶ if (!st->have_bbox) {
Branch: 1 branch
BranchTrueFalseTotal
if (!st->have_bbox) { 395 49191 49586
2968 395 st->xmin = st->xmax = xv; st->ymin = st->ymax = yv; st->zmin = st->zmax = zv;
2969 395 st->have_bbox = 1;
2970 } else {
2971 49191 ▶ if (xv < st->xmin) st->xmin = xv; else if (xv > st->xmax) st->xmax = xv;
Branch: 2 branches
BranchTrueFalseTotal
if (xv < st->xmin) st->xmin = xv; else if (xv > st->xmax) st->xmax = xv; 2996 46195 49191
if (xv < st->xmin) st->xmin = xv; else if (xv > st->xmax) st->xmax = xv; 5592 40603 46195
2972 49191 ▶ if (yv < st->ymin) st->ymin = yv; else if (yv > st->ymax) st->ymax = yv;
Branch: 2 branches
BranchTrueFalseTotal
if (yv < st->ymin) st->ymin = yv; else if (yv > st->ymax) st->ymax = yv; 2153 47038 49191
if (yv < st->ymin) st->ymin = yv; else if (yv > st->ymax) st->ymax = yv; 4048 42990 47038
2973 49191 ▶ if (zv < st->zmin) st->zmin = zv; else if (zv > st->zmax) st->zmax = zv;
Branch: 2 branches
BranchTrueFalseTotal
if (zv < st->zmin) st->zmin = zv; else if (zv > st->zmax) st->zmax = zv; 2480 46711 49191
if (zv < st->zmin) st->zmin = zv; else if (zv > st->zmax) st->zmax = zv; 5521 41190 46711
2974 }
2975 }
2976 49587 ▶ if (have_b && nv_is_finite(bv)) {
Branch: 2 branches
BranchTrueFalseTotal
if (have_b && nv_is_finite(bv)) { 49531 56 49587
if (have_b && nv_is_finite(bv)) { 49531 0 49531
2977 49531 st->rsb += bv; st->rnb++;
2978 49531 ▶ if (!st->bn++) { st->bmin = st->bmax = bv; }
Branch: 1 branch
BranchTrueFalseTotal
if (!st->bn++) { st->bmin = st->bmax = bv; } 372 49159 49531
2979 49159 ▶ else if (bv < st->bmin) st->bmin = bv;
Branch: 1 branch
BranchTrueFalseTotal
else if (bv < st->bmin) st->bmin = bv; 1918 47241 49159
2980 47241 ▶ else if (bv > st->bmax) st->bmax = bv;
Branch: 1 branch
BranchTrueFalseTotal
else if (bv > st->bmax) st->bmax = bv; 1633 45608 47241
2981 49531 st->bsum += bv;
2982 }
2983 49587 ▶ if (ellen) {
Branch: 1 branch
BranchTrueFalseTotal
if (ellen) { 49586 1 49587
2984 49586 elem_bump(aTHX_ st->elements, elbuf, ellen);
2985 49586 ▶ if (st->cur_chain) elem_bump(aTHX_ st->cur_chain, elbuf, ellen);
Branch: 1 branch
BranchTrueFalseTotal
if (st->cur_chain) elem_bump(aTHX_ st->cur_chain, elbuf, ellen); 49586 0 49586
2986 49586 ▶ if (ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) st->n_hydrogen++;
Branch: 3 branches
BranchTrueFalseTotal
if (ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) st->n_hydrogen++; 49393 193 49586
if (ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) st->n_hydrogen++; 43063 6330 49393
if (ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) st->n_hydrogen++; 0 43063 43063
2987 }
2988 49587 ▶ if (known && ri.type == RT_WATER) st->n_water_atom++;
Branch: 2 branches
BranchTrueFalseTotal
if (known && ri.type == RT_WATER) st->n_water_atom++; 48831 756 49587
if (known && ri.type == RT_WATER) st->n_water_atom++; 4316 44515 48831
2989  
2990 49587 ▶ if (st->build_atoms) {
Branch: 1 branch
BranchTrueFalseTotal
if (st->build_atoms) { 48807 780 49587
2991 atom_fields af;
2992 HV *a;
2993 48807 af.name = csp_str(aTHX_ nm_s, nm_n);
2994 48807 af.alt = alt_s; af.alt_n = alt_n;
2995 48807 af.el = elbuf; af.el_n = ellen;
2996 48807 af.chg = chgbuf; af.chg_n = chg_n;
2997 48807 af.serial = serial; af.have_serial = have_serial;
2998 48807 af.x = xv; af.y = yv; af.z = zv; af.have_xyz = have_xyz;
2999 48807 af.occ = ov; af.have_occ = have_occ;
3000 48807 af.b = bv; af.have_b = have_b;
3001 48807 af.het = het;
3002 48807 a = atom_hash(aTHX_ &st->filer.keys, &af);
3003 48807 av_push(st->atom_hv, newRV_noinc((SV *)a));
3004 48807 filer_atom(aTHX_ &st->filer, a, af.name, alt_n, have_occ, ov);
3005 780 ▶ } else if (st->slim) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (st->slim) { 558 222 780
3006 558 av_push(st->col[C_NAME], csp_str(aTHX_ nm_s, nm_n));
3007 558 ▶ av_push(st->col[C_X], have_xyz ? newSVnv(xv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(st->col[C_X], have_xyz ? newSVnv(xv) : newSV(0)); 558 0 558
3008 558 ▶ av_push(st->col[C_Y], have_xyz ? newSVnv(yv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(st->col[C_Y], have_xyz ? newSVnv(yv) : newSV(0)); 558 0 558
3009 558 ▶ av_push(st->col[C_Z], have_xyz ? newSVnv(zv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(st->col[C_Z], have_xyz ? newSVnv(zv) : newSV(0)); 558 0 558
3010 } else {
3011 222 ▶ av_push(st->col[C_SERIAL], have_serial ? newSViv(serial) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(st->col[C_SERIAL], have_serial ? newSViv(serial) : newSV(0)); 221 1 222
3012 222 av_push(st->col[C_NAME], csp_str(aTHX_ nm_s, nm_n));
3013 222 av_push(st->col[C_ALTLOC], csp_str(aTHX_ alt_s, alt_n));
3014 222 ▶ av_push(st->col[C_X], have_xyz ? newSVnv(xv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(st->col[C_X], have_xyz ? newSVnv(xv) : newSV(0)); 221 1 222
3015 222 ▶ av_push(st->col[C_Y], have_xyz ? newSVnv(yv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(st->col[C_Y], have_xyz ? newSVnv(yv) : newSV(0)); 221 1 222
3016 222 ▶ av_push(st->col[C_Z], have_xyz ? newSVnv(zv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(st->col[C_Z], have_xyz ? newSVnv(zv) : newSV(0)); 221 1 222
3017 222 ▶ av_push(st->col[C_OCC], have_occ ? newSVnv(ov) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(st->col[C_OCC], have_occ ? newSVnv(ov) : newSV(0)); 210 12 222
3018 222 ▶ av_push(st->col[C_B], have_b ? newSVnv(bv) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(st->col[C_B], have_b ? newSVnv(bv) : newSV(0)); 210 12 222
3019 222 av_push(st->col[C_ELEMENT], csp_str(aTHX_ elbuf, ellen));
3020 222 av_push(st->col[C_CHARGE], csp_str(aTHX_ chgbuf, chg_n));
3021 }
3022  
3023 49587 ▶ if (!st->build_atoms && !st->slim) {
Branch: 2 branches
BranchTrueFalseTotal
if (!st->build_atoms && !st->slim) { 780 48807 49587
if (!st->build_atoms && !st->slim) { 222 558 780
3024 222 av_push(st->col[C_RESNAME], csp_str(aTHX_ resname, resname_len));
3025 222 av_push(st->col[C_CHAIN], csp_str(aTHX_ chain, chain_len));
3026 222 ▶ av_push(st->col[C_RESSEQ], have_rs ? newSViv(rs) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(st->col[C_RESSEQ], have_rs ? newSViv(rs) : newSV(0)); 220 2 222
3027 222 av_push(st->col[C_ICODE], csp_str(aTHX_ icode, icode[0] ? 1 : 0));
3028 222 av_push(st->col[C_HET], newSViv(het));
3029 222 av_push(st->col[C_MODEL], newSViv(st->cur_model));
3030 }
3031 49587 st->n_atom++;
3032 }
3033  
3034 /*a token as the SV a caller reads: a null field is undef, not an empty string.
3035 A text field written with DOS line ends has a CR before every newline inside it,
3036 and the same field written with Unix ones would not; each CRLF comes back as
3037 the LF it stands for, so the value does not depend on which the file used.*/
3038 54384 static SV *cif_sv(pTHX_ const cif_tok *CSP_RESTRICT t){
3039 SV *sv;
3040 char *CSP_RESTRICT d;
3041 54384 STRLEN k = 0;
3042 54384 ▶ if (cif_null(t)) return newSV(0);
Branch: 1 branch
BranchTrueFalseTotal
if (cif_null(t)) return newSV(0); 1994 52390 54384
3043 52390 ▶ if (!t->quoted || !memchr(t->s, '\r', t->n)) return newSVpvn(t->s, t->n);
Branch: 2 branches
BranchTrueFalseTotal
if (!t->quoted || !memchr(t->s, '\r', t->n)) return newSVpvn(t->s, t->n); 2565 49825 52390
if (!t->quoted || !memchr(t->s, '\r', t->n)) return newSVpvn(t->s, t->n); 2564 1 2565
3044 1 sv = newSV(t->n + 1);
3045 1 d = SvPVX(sv);
3046 37 ▶ for (STRLEN i = 0; i < t->n; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (STRLEN i = 0; i < t->n; i++) 36 1 37
3047 36 ▶ if (!(t->s[i] == '\r' && i + 1 < t->n && t->s[i + 1] == '\n')) d[k++] = t->s[i];
Branch: 3 branches
BranchTrueFalseTotal
if (!(t->s[i] == '\r' && i + 1 < t->n && t->s[i + 1] == '\n')) d[k++] = t->s[i]; 2 34 36
if (!(t->s[i] == '\r' && i + 1 < t->n && t->s[i + 1] == '\n')) d[k++] = t->s[i]; 2 0 2
if (!(t->s[i] == '\r' && i + 1 < t->n && t->s[i + 1] == '\n')) d[k++] = t->s[i]; 0 2 2
3048 1 d[k] = '\0';
3049 1 SvCUR_set(sv, k);
3050 1 SvPOK_only(sv);
3051 1 return sv;
3052 }
3053  
3054 //lowercased, so that a caller looking a tag up never has to guess at its case
3055 18541 static SV *cif_key(pTHX_ const char *CSP_RESTRICT s, STRLEN n){
3056 18541 SV *sv = newSVpvn(s, n);
3057 18541 char *CSP_RESTRICT p = SvPVX(sv);
3058 285133 ▶ for (STRLEN i = 0; i < n; i++) p[i] = (char)toLOWER((unsigned char)p[i]);
Branch: 2 branches
BranchTrueFalseTotal
for (STRLEN i = 0; i < n; i++) p[i] = (char)toLOWER((unsigned char)p[i]); 2848 263744 266592
for (STRLEN i = 0; i < n; i++) p[i] = (char)toLOWER((unsigned char)p[i]); 266592 18541 285133
3059 18541 return sv;
3060 }
3061  
3062 4706 static void cif_store_lc(pTHX_ HV *CSP_RESTRICT h, const char *CSP_RESTRICT k, STRLEN kn, SV *CSP_RESTRICT val){
3063 4706 SV *key = cif_key(aTHX_ k, kn);
3064 4706 (void)hv_store_ent(h, key, val, 0);
3065 4706 SvREFCNT_dec(key);
3066 4706 }
3067  
3068 2019 static AV *cif_loop_av(pTHX_ HV *CSP_RESTRICT loops, const char *CSP_RESTRICT cat, STRLEN catn) {
3069 2019 SV *key = cif_key(aTHX_ cat, catn);
3070 2019 HE *he = hv_fetch_ent(loops, key, 0, 0);
3071 AV *av;
3072 2019 ▶ if (he && HeVAL(he) && SvROK(HeVAL(he))) {
Branch: 3 branches
BranchTrueFalseTotal
if (he && HeVAL(he) && SvROK(HeVAL(he))) { 1 2018 2019
if (he && HeVAL(he) && SvROK(HeVAL(he))) { 1 0 1
if (he && HeVAL(he) && SvROK(HeVAL(he))) { 1 0 1
3073 1 av = (AV *)SvRV(HeVAL(he));
3074 } else {
3075 2018 av = newAV();
3076 2018 (void)hv_store_ent(loops, key, newRV_noinc((SV *)av), 0);
3077 }
3078 2019 SvREFCNT_dec(key);
3079 2019 return av;
3080 }
3081  
3082 /*parse_cif_buf() -- the whole file, once through, into the same hash
3083 parse_buf() fills. The atom table goes to cif_atom_row(); everything else is
3084 kept as it was written, single tags in `cif' and loops in `cif_loops', for Perl
3085 to make sense of. Nothing here decides what a category means: that is the same
3086 division of labour the PDB reader keeps, where C reads the coordinates and Perl
3087 reads the header.*/
3088 666 static HV *parse_cif_buf(pTHX_ const char *CSP_RESTRICT buf, STRLEN len, HV *CSP_RESTRICT opts,
3089 cv_w *CSP_RESTRICT cv)
3090 {
3091 //allocated once the options have been read, as in parse_buf()
3092 HV *out, *meta, *cif, *loops;
3093 AV *col[NCOL], *res_sum[NRSUM];
3094 cif_state st;
3095 cif_lex lx;
3096 cif_tok tk;
3097 666 bool keep_meta, have_single = 0;;
3098 //an _atom_site_anisotrop of one row written as plain tags; see below
3099 666 bool have_aniso_single = FALSE;
3100 666 bool seen_block = FALSE;
3101 666 UV lineno = 0;
3102 666 SV *block = NULL;
3103 const char *v[A_NFIELD], *sv_[A_NFIELD];
3104 STRLEN vn[A_NFIELD];
3105 //an _atom_site table written as plain tags rather than as a loop_
3106 STRLEN svn_[A_NFIELD];
3107 /*convert(): an _atom_site_anisotrop row, from a loop and from plain tags, in
3108 cif_aniso_item[] order; and the categories of the header it reads*/
3109 const char *av_[CIF_NANISO], *sav_[CIF_NANISO];
3110 STRLEN avn_[CIF_NANISO], savn_[CIF_NANISO];
3111 HV *keep_cat;
3112  
3113 666 Zero(&st, 1, cif_state);
3114 size_t i;
3115 666 st.cur_model = 1;
3116 666 st.want_model = opt_iv(aTHX_ opts, "model", 1);
3117 662 st.keep_h = opt_bool(aTHX_ opts, "hydrogens", 1);
3118 662 st.keep_water = opt_bool(aTHX_ opts, "waters", 1);
3119 662 st.keep_het = opt_bool(aTHX_ opts, "hetatm", 1);
3120 //convert() takes the table row by row through cv, and keeps none of it as rows
3121 662 ▶ st.keep_anisou= !cv && opt_bool(aTHX_ opts, "anisou", 0);
Branch: 2 branches
BranchTrueFalseTotal
st.keep_anisou= !cv && opt_bool(aTHX_ opts, "anisou", 0); 433 229 662
st.keep_anisou= !cv && opt_bool(aTHX_ opts, "anisou", 0); 3 430 433
3122 662 st.build_atoms= opt_bool(aTHX_ opts, "atom_hashes", 0);
3123 662 ▶ st.slim = !st.build_atoms && opt_bool(aTHX_ opts, "slim", 0);
Branch: 2 branches
BranchTrueFalseTotal
st.slim = !st.build_atoms && opt_bool(aTHX_ opts, "slim", 0); 262 400 662
st.slim = !st.build_atoms && opt_bool(aTHX_ opts, "slim", 0); 12 250 262
3124 662 st.filer.highest = opt_bool(aTHX_ opts, "altloc_highest", 0);
3125 662 keep_meta = opt_bool(aTHX_ opts, "meta", 1);
3126 662 st.want_chain = opt_chains(aTHX_ opts);
3127 660 st.cv = cv;
3128 660 ▶ keep_cat = cv ? opt_plain_hv(aTHX_ opts, "keep") : NULL;
Branch: 1 branch
BranchTrueFalseTotal
keep_cat = cv ? opt_plain_hv(aTHX_ opts, "keep") : NULL; 229 431 660
3129  
3130 660 out = newHV(); meta = newHV(); cif = newHV(); loops = newHV();
3131 11880 ▶ for (i = 0; i < NCOL; i++) col[i] = newAV();
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < NCOL; i++) col[i] = newAV(); 11220 660 11880
3132 4620 ▶ for (i = 0; i < NRSUM; i++) res_sum[i] = newAV();
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < NRSUM; i++) res_sum[i] = newAV(); 3960 660 4620
3133 13860 ▶ for (i = 0; i < A_NFIELD; i++) { sv_[i] = NULL; svn_[i] = 0; }
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < A_NFIELD; i++) { sv_[i] = NULL; svn_[i] = 0; } 13200 660 13860
3134 5940 ▶ for (i = 0; i < CIF_NANISO; i++) { sav_[i] = NULL; savn_[i] = 0; }
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < CIF_NANISO; i++) { sav_[i] = NULL; savn_[i] = 0; } 5280 660 5940
3135 660 st.col = col;
3136 660 st.res_sum = res_sum;
3137 660 st.res_first = newAV();
3138 660 st.res_last = newAV();
3139 660 st.atom_hv = newAV();
3140 660 st.model_nums = newAV();
3141 660 st.res_apart = newAV();
3142 660 st.res_seen = newHV();
3143 660 st.models_seen = newHV();
3144 660 st.elements = newHV();
3145 660 st.chain_elements = newHV();
3146 660 ▶ if (st.build_atoms) filer_init(aTHX_ &st.filer, st.filer.highest);
Branch: 1 branch
BranchTrueFalseTotal
if (st.build_atoms) filer_init(aTHX_ &st.filer, st.filer.highest); 400 260 660
3147  
3148 { //lines are not what this format is made of, but callers still count them
3149 660 const char *CSP_RESTRICT p = buf, *CSP_RESTRICT e = buf + len;
3150 131815 ▶ while (p < e) {
Branch: 1 branch
BranchTrueFalseTotal
while (p < e) { 131158 657 131815
3151 131158 const char *CSP_RESTRICT nl = (const char *)memchr(p, '\n', (STRLEN)(e - p));
3152 131158 lineno++;
3153 131158 ▶ if (!nl) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!nl) break; 3 131155 131158
3154 131155 p = nl + 1;
3155 }
3156 }
3157  
3158 660 lx.buf = buf;
3159 660 lx.end = buf + len;
3160 660 lx.p = buf;
3161 660 lx.open_from[0] = lx.open_from[1] = lx.open_eol[0] = lx.open_eol[1] = NULL;
3162  
3163 for (;;) {
3164 11093 cif_next(&lx, &tk);
3165 11093 ▶ if (tk.kind == CT_EOF) break;
Branch: 1 branch
BranchTrueFalseTotal
if (tk.kind == CT_EOF) break; 657 10436 11093
3166  
3167 /*The first data block is the structure, and a second one ends it. The
3168 blocks were read as one, so a file of two structures came back as one
3169 with every atom twice -- the second block's under the first's residue
3170 numbers, as conformers of them -- and the second block's header over the
3171 first's. gemmi 0.7.5 takes a file of several blocks only when the
3172 first is the one with the coordinates, and reads that one.*/
3173 10436 ▶ if (tk.kind == CT_DATA) {
Branch: 1 branch
BranchTrueFalseTotal
if (tk.kind == CT_DATA) { 650 9786 10436
3174 650 ▶ if (seen_block) break;
Branch: 1 branch
BranchTrueFalseTotal
if (seen_block) break; 3 647 650
3175 647 seen_block = TRUE;
3176 647 ▶ if (tk.n) block = newSVpvn(tk.s, tk.n);
Branch: 1 branch
BranchTrueFalseTotal
if (tk.n) block = newSVpvn(tk.s, tk.n); 647 0 647
3177 647 continue;
3178 }
3179 9786 ▶ if (tk.kind == CT_STOP || tk.kind == CT_SAVE) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (tk.kind == CT_STOP || tk.kind == CT_SAVE) continue; 9786 0 9786
if (tk.kind == CT_STOP || tk.kind == CT_SAVE) continue; 0 9786 9786
3180  
3181 9786 ▶ if (tk.kind == CT_LOOP) {
Branch: 1 branch
BranchTrueFalseTotal
if (tk.kind == CT_LOOP) { 3099 6687 9786
3182 3099 const char **CSP_RESTRICT tags = NULL, *CSP_RESTRICT cat = NULL;
3183 3099 STRLEN *CSP_RESTRICT tagn = NULL;
3184 3099 short int *CSP_RESTRICT fld_of = NULL;//a column this reader ignores is -1
3185 3099 size_t ntags = 0, cap = 16;//an _atom_site loop has 21 tags: one Renew
3186 3099 bool is_atom = 0, is_aniso = 0, keep_loop = 0;
3187 3099 STRLEN catn = 0;
3188 3099 AV *rows = NULL;
3189 /*the kept loop's column names, lowercased and made shared-key SVs once
3190 for the loop rather than once for every cell: a row's hash is keyed by
3191 them, so hv_store_ent() takes each one's hash off the SV instead of
3192 lowercasing, allocating and hashing the name all over again for every
3193 row of _pdbx_poly_seq_scheme or _struct_conn*/
3194 3099 SV **CSP_RESTRICT col_key = NULL;
3195  
3196 3099 ▶ Newx(tags, cap, const char *);
Branch: 1 branch
BranchTrueFalseTotal
Newx(tags, cap, const char *); 0 3099 3099
3197 3099 ▶ Newx(tagn, cap, STRLEN);
Branch: 1 branch
BranchTrueFalseTotal
Newx(tagn, cap, STRLEN); 0 3099 3099
3198 26608 for (;;) {
3199 29707 const char *CSP_RESTRICT save = lx.p;
3200 29707 cif_next(&lx, &tk);
3201 29707 ▶ if (tk.kind != CT_TAG) { lx.p = save; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (tk.kind != CT_TAG) { lx.p = save; break; } 3099 26608 29707
3202 26608 ▶ if (ntags == cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (ntags == cap) { 565 26043 26608
3203 565 cap *= 2;
3204 565 ▶ Renew(tags, cap, const char *);
Branch: 1 branch
BranchTrueFalseTotal
Renew(tags, cap, const char *); 0 565 565
3205 565 ▶ Renew(tagn, cap, STRLEN);
Branch: 1 branch
BranchTrueFalseTotal
Renew(tagn, cap, STRLEN); 0 565 565
3206 }
3207 26608 tags[ntags] = tk.s;
3208 26608 tagn[ntags] = tk.n;
3209 26608 ntags++;
3210 }
3211 3099 ▶ if (ntags == 0) { Safefree(tags); Safefree(tagn); continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (ntags == 0) { Safefree(tags); Safefree(tagn); continue; } 2 3097 3099
3212  
3213 {
3214 const char *item;
3215 STRLEN itemn;
3216 3097 catn = cif_split_tag(tags[0], tagn[0], &item, &itemn);
3217 3097 cat = tags[0];
3218 3097 ▶ is_atom = (catn == 10 && cif_iskw(cat, catn, "_atom_site", 10));
Branch: 2 branches
BranchTrueFalseTotal
is_atom = (catn == 10 && cif_iskw(cat, catn, "_atom_site", 10)); 736 2361 3097
is_atom = (catn == 10 && cif_iskw(cat, catn, "_atom_site", 10)); 624 112 736
3219 3097 ▶ is_aniso = (catn == 20 && cif_iskw(cat, catn, "_atom_site_anisotrop", 20));
Branch: 2 branches
BranchTrueFalseTotal
is_aniso = (catn == 20 && cif_iskw(cat, catn, "_atom_site_anisotrop", 20)); 233 2864 3097
is_aniso = (catn == 20 && cif_iskw(cat, catn, "_atom_site_anisotrop", 20)); 10 223 233
3220 }
3221 /*_atom_site_anisotrop is as long as the atom table and is wanted about
3222 as often as ANISOU is, which is to say hardly ever; it is counted
3223 always and kept only when the caller asked for it.
3224  
3225 convert() reads the header for a dozen categories, and asks for those
3226 alone: the others are as many rows as the structure has residues --
3227 _pdbx_poly_seq_scheme, _pdbx_nonpoly_scheme -- and each row is a hash of
3228 a dozen SVs, built to be thrown away, where an atom costs a conversion
3229 none. An 11,406-row _pdbx_poly_seq_scheme on 4fqr took its conversion
3230 from 55 MB to 82 MB; notes.txt has the measurement.*/
3231 2955 ▶ keep_loop = keep_meta && !is_atom && (!is_aniso || st.keep_anisou)
Branch: 3 branches
BranchTrueFalseTotal
keep_loop = keep_meta && !is_atom && (!is_aniso || st.keep_anisou) 2347 608 2955
keep_loop = keep_meta && !is_atom && (!is_aniso || st.keep_anisou) 10 2337 2347
keep_loop = keep_meta && !is_atom && (!is_aniso || st.keep_anisou) 0 10 10
3232 6052 ▶ && cif_kept(aTHX_ keep_cat, cat, catn);
Branch: 2 branches
BranchTrueFalseTotal
&& cif_kept(aTHX_ keep_cat, cat, catn); 2955 142 3097
&& cif_kept(aTHX_ keep_cat, cat, catn); 2019 318 2337
3233 3097 ▶ if (keep_loop) {
Branch: 1 branch
BranchTrueFalseTotal
if (keep_loop) { 2019 1078 3097
3234 2019 rows = cif_loop_av(aTHX_ loops, cat, catn);
3235 2019 ▶ Newx(col_key, ntags, SV *);
Branch: 1 branch
BranchTrueFalseTotal
Newx(col_key, ntags, SV *); 0 2019 2019
3236 13835 ▶ for (i = 0; i < ntags; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < ntags; i++) { 11816 2019 13835
3237 const char *item;
3238 STRLEN itemn;
3239 SV *lc;
3240 11816 (void)cif_split_tag(tags[i], tagn[i], &item, &itemn);
3241 11816 lc = cif_key(aTHX_ item, itemn);
3242 11816 col_key[i] = newSVpvn_share(SvPVX(lc), (I32)SvCUR(lc), 0);
3243 11816 SvREFCNT_dec(lc);
3244 }
3245 }
3246  
3247 3097 ▶ Newx(fld_of, ntags, short int);
Branch: 1 branch
BranchTrueFalseTotal
Newx(fld_of, ntags, short int); 0 3097 3097
3248 29705 ▶ for (i = 0; i < ntags; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < ntags; i++) { 26608 3097 29705
3249 const char *item;
3250 STRLEN itemn;
3251 26608 (void)cif_split_tag(tags[i], tagn[i], &item, &itemn);
3252 26664 ▶ fld_of[i] = is_atom ? cif_atom_field(item, itemn)
Branch: 2 branches
BranchTrueFalseTotal
fld_of[i] = is_atom ? cif_atom_field(item, itemn) 12270 14338 26608
fld_of[i] = is_atom ? cif_atom_field(item, itemn) 56 14282 14338
3253 56 ▶ : (is_aniso && cv) ? cif_aniso_field(item, itemn) : -1;
Branch: 1 branch
BranchTrueFalseTotal
: (is_aniso && cv) ? cif_aniso_field(item, itemn) : -1; 48 8 56
3254 26608 ▶ if (is_atom && fld_of[i] == A_MODEL) st.model_col = TRUE;
Branch: 2 branches
BranchTrueFalseTotal
if (is_atom && fld_of[i] == A_MODEL) st.model_col = TRUE; 12270 14338 26608
if (is_atom && fld_of[i] == A_MODEL) st.model_col = TRUE; 577 11693 12270
3255 }
3256  
3257 109211 for (;;) {
3258 112308 const char *CSP_RESTRICT save = lx.p;
3259 size_t col_i;
3260 112308 HV *row = NULL;
3261 112308 bool whole = FALSE;//the row had a value for every tag
3262 112308 cif_next(&lx, &tk);
3263 112308 ▶ if (tk.kind != CT_VALUE) { lx.p = save; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (tk.kind != CT_VALUE) { lx.p = save; break; } 3093 109215 112308
3264 1758635 ▶ if (is_atom) for (i = 0; i < A_NFIELD; i++) { v[i] = NULL; vn[i] = 0; }
Branch: 2 branches
BranchTrueFalseTotal
if (is_atom) for (i = 0; i < A_NFIELD; i++) { v[i] = NULL; vn[i] = 0; } 82471 26744 109215
if (is_atom) for (i = 0; i < A_NFIELD; i++) { v[i] = NULL; vn[i] = 0; } 1649420 82471 1731891
3265 109479 ▶ if (is_aniso && cv) for (i = 0; i < CIF_NANISO; i++) { av_[i] = NULL; avn_[i] = 0; }
Branch: 3 branches
BranchTrueFalseTotal
if (is_aniso && cv) for (i = 0; i < CIF_NANISO; i++) { av_[i] = NULL; avn_[i] = 0; } 38 109177 109215
if (is_aniso && cv) for (i = 0; i < CIF_NANISO; i++) { av_[i] = NULL; avn_[i] = 0; } 33 5 38
if (is_aniso && cv) for (i = 0; i < CIF_NANISO; i++) { av_[i] = NULL; avn_[i] = 0; } 264 33 297
3266 109215 ▶ if (keep_loop) {
Branch: 1 branch
BranchTrueFalseTotal
if (keep_loop) { 25673 83542 109215
3267 25673 row = newHV();
3268 //the size it grows to anyway, so that a wide table is not
3269 //rehashed on the way to being filled
3270 25673 hv_ksplit(row, (IV)ntags);
3271 }
3272  
3273 1784793 for (col_i = 0; ; col_i++) {
3274 1784793 ▶ if (col_i > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (col_i > 0) { 1675578 109215 1784793
3275 1675578 save = lx.p;
3276 1675578 cif_next(&lx, &tk);
3277 1675578 ▶ if (tk.kind != CT_VALUE) { lx.p = save; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (tk.kind != CT_VALUE) { lx.p = save; break; } 4 1675574 1675578
3278 }
3279 1784789 ▶ if (is_atom) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_atom) { 1729618 55171 1784789
3280 1729618 short int f = fld_of[col_i];
3281 1729618 ▶ if (f >= 0 && !cif_null(&tk)) { v[f] = tk.s; vn[f] = tk.n; }
Branch: 2 branches
BranchTrueFalseTotal
if (f >= 0 && !cif_null(&tk)) { v[f] = tk.s; vn[f] = tk.n; } 1647398 82220 1729618
if (f >= 0 && !cif_null(&tk)) { v[f] = tk.s; vn[f] = tk.n; } 1363466 283932 1647398
3282 55387 ▶ } else if (is_aniso && cv) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (is_aniso && cv) { 256 54915 55171
} else if (is_aniso && cv) { 216 40 256
3283 216 short int f = fld_of[col_i];
3284 216 ▶ if (f >= 0 && !cif_null(&tk)) { av_[f] = tk.s; avn_[f] = tk.n; }
Branch: 2 branches
BranchTrueFalseTotal
if (f >= 0 && !cif_null(&tk)) { av_[f] = tk.s; avn_[f] = tk.n; } 216 0 216
if (f >= 0 && !cif_null(&tk)) { av_[f] = tk.s; avn_[f] = tk.n; } 216 0 216
3285 54955 ▶ } else if (row) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (row) { 49678 5277 54955
3286 49678 (void)hv_store_ent(row, col_key[col_i], cif_sv(aTHX_ &tk), 0);
3287 }
3288 1784789 ▶ if (col_i + 1 >= ntags) { whole = TRUE; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (col_i + 1 >= ntags) { whole = TRUE; break; } 109211 1675578 1784789
3289 }
3290 /*A row with fewer values than the loop has tags is the last one,
3291 since only something other than a value can have ended it, and it
3292 means the file was cut short: gemmi 0.7.5 refuses the file, 'Wrong
3293 number of values in loop'. It is left out rather than read as a row,
3294 which made an atom of an _atom_site row that stopped after its x --
3295 no y, no z, and the label_* chain and number for want of the auth_*
3296 ones further along -- and counted it among the atoms. Every whole
3297 row before it is read, as the whole lines of a cut-short PDB file
3298 are.*/
3299 109215 ▶ if (!whole) {
Branch: 1 branch
BranchTrueFalseTotal
if (!whole) { 4 109211 109215
3300 4 ▶ if (row) SvREFCNT_dec((SV *)row);
Branch: 1 branch
BranchTrueFalseTotal
if (row) SvREFCNT_dec((SV *)row); 0 4 4
3301 4 break;
3302 }
3303 109211 ▶ if (is_atom) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_atom) { 82467 26744 109211
3304 82467 cif_atom_row(aTHX_ &st, v, vn);
3305 26744 ▶ } else if (is_aniso) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (is_aniso) { 38 26706 26744
3306 38 st.n_anisou++;
3307 38 ▶ if (cv) cv_aniso_add(aTHX_ cv, av_, avn_);
Branch: 1 branch
BranchTrueFalseTotal
if (cv) cv_aniso_add(aTHX_ cv, av_, avn_); 33 5 38
3308 }
3309 109211 ▶ if (row) av_push(rows, newRV_noinc((SV *)row));
Branch: 1 branch
BranchTrueFalseTotal
if (row) av_push(rows, newRV_noinc((SV *)row)); 25673 83538 109211
3310 }
3311 3097 ▶ if (col_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (col_key) { 2019 1078 3097
3312 13835 ▶ for (i = 0; i < ntags; i++) SvREFCNT_dec(col_key[i]);
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < ntags; i++) SvREFCNT_dec(col_key[i]); 11816 2019 13835
3313 2019 Safefree(col_key);
3314 }
3315 3097 Safefree(tags); Safefree(tagn); Safefree(fld_of);
3316 3097 continue;
3317 }
3318  
3319 6687 ▶ if (tk.kind == CT_TAG) {
Branch: 1 branch
BranchTrueFalseTotal
if (tk.kind == CT_TAG) { 5467 1220 6687
3320 5467 const char *tag = tk.s, *item;
3321 5467 STRLEN tagn = tk.n, itemn, catn;
3322 5467 const char *save = lx.p;
3323 5467 catn = cif_split_tag(tag, tagn, &item, &itemn);
3324 5467 cif_next(&lx, &tk);
3325 5467 ▶ if (tk.kind != CT_VALUE) { lx.p = save; continue; } //a tag with no value
Branch: 1 branch
BranchTrueFalseTotal
if (tk.kind != CT_VALUE) { lx.p = save; continue; } //a tag with no value 1 5466 5467
3326 5466 ▶ if (catn == 10 && cif_iskw(tag, catn, "_atom_site", 10)) {
Branch: 2 branches
BranchTrueFalseTotal
if (catn == 10 && cif_iskw(tag, catn, "_atom_site", 10)) { 63 5403 5466
if (catn == 10 && cif_iskw(tag, catn, "_atom_site", 10)) { 12 51 63
3327 12 short int f = cif_atom_field(item, itemn);
3328 12 ▶ if (f >= 0 && !cif_null(&tk)) { sv_[f] = tk.s; svn_[f] = tk.n; have_single = 1; }
Branch: 2 branches
BranchTrueFalseTotal
if (f >= 0 && !cif_null(&tk)) { sv_[f] = tk.s; svn_[f] = tk.n; have_single = 1; } 12 0 12
if (f >= 0 && !cif_null(&tk)) { sv_[f] = tk.s; svn_[f] = tk.n; have_single = 1; } 12 0 12
3329 12 continue;
3330 }
3331 /*One row of _atom_site_anisotrop written as plain tags, which is the
3332 table the loop above counts a row of at a time: one record, however
3333 many tags it took, and counted below. Each tag counted one, so a
3334 record of eight tags came back as eight; and, kept nowhere, it was lost
3335 with anisou => 1 where the loop's rows were kept.*/
3336 5454 ▶ if (catn == 20 && cif_iskw(tag, catn, "_atom_site_anisotrop", 20)) {
Branch: 2 branches
BranchTrueFalseTotal
if (catn == 20 && cif_iskw(tag, catn, "_atom_site_anisotrop", 20)) { 354 5100 5454
if (catn == 20 && cif_iskw(tag, catn, "_atom_site_anisotrop", 20)) { 21 333 354
3337 21 have_aniso_single = TRUE;
3338 21 ▶ if (keep_meta && st.keep_anisou) cif_store_lc(aTHX_ cif, tag, tagn, cif_sv(aTHX_ &tk));
Branch: 2 branches
BranchTrueFalseTotal
if (keep_meta && st.keep_anisou) cif_store_lc(aTHX_ cif, tag, tagn, cif_sv(aTHX_ &tk)); 21 0 21
if (keep_meta && st.keep_anisou) cif_store_lc(aTHX_ cif, tag, tagn, cif_sv(aTHX_ &tk)); 12 9 21
3339 21 ▶ if (cv) {
Branch: 1 branch
BranchTrueFalseTotal
if (cv) { 0 21 21
3340 0 short int f = cif_aniso_field(item, itemn);
3341 0 ▶ if (f >= 0 && !cif_null(&tk)) { sav_[f] = tk.s; savn_[f] = tk.n; }
Branch: 2 branches
BranchTrueFalseTotal
if (f >= 0 && !cif_null(&tk)) { sav_[f] = tk.s; savn_[f] = tk.n; } 0 0 0
if (f >= 0 && !cif_null(&tk)) { sav_[f] = tk.s; savn_[f] = tk.n; } 0 0 0
3342 }
3343 21 continue;
3344 }
3345 5433 ▶ if (keep_meta && cif_kept(aTHX_ keep_cat, tag, catn))
Branch: 2 branches
BranchTrueFalseTotal
if (keep_meta && cif_kept(aTHX_ keep_cat, tag, catn)) 5175 258 5433
if (keep_meta && cif_kept(aTHX_ keep_cat, tag, catn)) 4694 481 5175
3346 4694 cif_store_lc(aTHX_ cif, tag, tagn, cif_sv(aTHX_ &tk));
3347 5433 continue;
3348 }
3349 //a stray value with no tag in front of it: nothing to attach it to
3350 }
3351 660 ▶ if (have_aniso_single) {
Branch: 1 branch
BranchTrueFalseTotal
if (have_aniso_single) { 5 655 660
3352 5 st.n_anisou++;
3353 5 ▶ if (cv) cv_aniso_add(aTHX_ cv, sav_, savn_);
Branch: 1 branch
BranchTrueFalseTotal
if (cv) cv_aniso_add(aTHX_ cv, sav_, savn_); 0 5 5
3354 }
3355 660 ▶ if (have_single) cif_atom_row(aTHX_ &st, sv_, svn_);
Branch: 1 branch
BranchTrueFalseTotal
if (have_single) cif_atom_row(aTHX_ &st, sv_, svn_); 1 659 660
3356 660 ▶ if (st.have_res) {
Branch: 1 branch
BranchTrueFalseTotal
if (st.have_res) { 396 264 660
3357 396 av_push(st.res_last, newSVuv(st.n_atom - 1));
3358 396 flush_residue(aTHX_ res_sum, st.rsx, st.rsy, st.rsz, st.rnc, st.rsb, st.rnb);
3359 }
3360 660 (void)hv_stores(out, "atoms", newRV_noinc((SV *)st.atom_hv));
3361 4620 ▶ for (i = 0; i < NRSUM; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < NRSUM; i++) 3960 660 4620
3362 3960 (void)hv_store(out, res_sum_name[i], (I32)strlen(res_sum_name[i]),
3363 newRV_noinc((SV *)res_sum[i]), 0);
3364 660 (void)hv_stores(out, "elements", newRV_noinc((SV *)st.elements));
3365 660 (void)hv_stores(out, "chain_elements", newRV_noinc((SV *)st.chain_elements));
3366 660 (void)hv_stores(out, "n_hydrogens", newSVuv(st.n_hydrogen));
3367 660 (void)hv_stores(out, "n_water_atoms", newSVuv(st.n_water_atom));
3368 660 ▶ if (st.bn) {
Branch: 1 branch
BranchTrueFalseTotal
if (st.bn) { 372 288 660
3369 372 HV *b = newHV();
3370 372 (void)hv_stores(b, "min", newSVnv(st.bmin));
3371 372 (void)hv_stores(b, "max", newSVnv(st.bmax));
3372 372 (void)hv_stores(b, "mean", newSVnv(st.bsum / (NV)st.bn));
3373 372 (void)hv_stores(b, "n", newSVuv(st.bn));
3374 372 (void)hv_stores(out, "bfactor_stats", newRV_noinc((SV *)b));
3375 } else {
3376 288 (void)hv_stores(out, "bfactor_stats", newSV(0));
3377 }
3378 660 ▶ if (st.have_bbox) {
Branch: 1 branch
BranchTrueFalseTotal
if (st.have_bbox) { 395 265 660
3379 395 HV *bb = newHV();
3380 395 AV *ctr = newAV();
3381 395 (void)hv_stores(bb, "xmin", newSVnv(st.xmin));
3382 395 (void)hv_stores(bb, "ymin", newSVnv(st.ymin));
3383 395 (void)hv_stores(bb, "zmin", newSVnv(st.zmin));
3384 395 (void)hv_stores(bb, "xmax", newSVnv(st.xmax));
3385 395 (void)hv_stores(bb, "ymax", newSVnv(st.ymax));
3386 395 (void)hv_stores(bb, "zmax", newSVnv(st.zmax));
3387 395 av_push(ctr, newSVnv((st.xmin + st.xmax) / 2));
3388 395 av_push(ctr, newSVnv((st.ymin + st.ymax) / 2));
3389 395 av_push(ctr, newSVnv((st.zmin + st.zmax) / 2));
3390 395 (void)hv_stores(out, "bbox", newRV_noinc((SV *)bb));
3391 395 (void)hv_stores(out, "center", newRV_noinc((SV *)ctr));
3392 } else {
3393 265 (void)hv_stores(out, "bbox", newSV(0));
3394 265 (void)hv_stores(out, "center", newSV(0));
3395 }
3396  
3397 11880 ▶ for (i = 0; i < NCOL; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < NCOL; i++) { 11220 660 11880
3398 11220 ▶ if (i == C_LINENO) { SvREFCNT_dec((SV *)col[i]); continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (i == C_LINENO) { SvREFCNT_dec((SV *)col[i]); continue; } 660 10560 11220
3399 10560 (void)hv_store(out, col_name[i], (I32)strlen(col_name[i]),
3400 newRV_noinc((SV *)col[i]), 0);
3401 }
3402 660 (void)hv_stores(out, "res_first", newRV_noinc((SV *)st.res_first));
3403 660 (void)hv_stores(out, "res_apart", newRV_noinc((SV *)st.res_apart));
3404 660 SvREFCNT_dec((SV *)st.res_seen);
3405 660 SvREFCNT_dec((SV *)st.models_seen);
3406 660 ▶ if (st.build_atoms) filer_done(aTHX_ &st.filer, out);
Branch: 1 branch
BranchTrueFalseTotal
if (st.build_atoms) filer_done(aTHX_ &st.filer, out); 400 260 660
3407 660 (void)hv_stores(out, "res_last", newRV_noinc((SV *)st.res_last));
3408 //TER is a PDB record and has no mmCIF counterpart; the key is here so that
3409 //a caller reading it does not have to know which format the file was
3410 660 (void)hv_stores(out, "ter", newRV_noinc((SV *)newAV()));
3411 660 (void)hv_stores(out, "meta", newRV_noinc((SV *)meta));
3412 660 (void)hv_stores(out, "cif", newRV_noinc((SV *)cif));
3413 660 (void)hv_stores(out, "cif_loops", newRV_noinc((SV *)loops));
3414 660 ▶ (void)hv_stores(out, "data_block", block ? block : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(out, "data_block", block ? block : newSV(0)); 13 647 660
3415 660 (void)hv_stores(out, "model_numbers", newRV_noinc((SV *)st.model_nums));
3416 660 (void)hv_stores(out, "n_atoms", newSVuv(st.n_atom));
3417 660 (void)hv_stores(out, "n_residues", newSVuv((UV)(av_len(st.res_first) + 1)));
3418 660 ▶ (void)hv_stores(out, "n_models", newSVuv(st.n_models ? st.n_models : 1));
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(out, "n_models", newSVuv(st.n_models ? st.n_models : 1)); 623 37 660
3419 660 (void)hv_stores(out, "n_anisou", newSVuv(st.n_anisou));
3420 660 (void)hv_stores(out, "n_skipped", newSVuv(st.n_skipped));
3421 660 (void)hv_stores(out, "n_atom_records", newSVuv(st.n_atom_rec));
3422 660 (void)hv_stores(out, "n_hetatm_records", newSVuv(st.n_het_rec));
3423 660 (void)hv_stores(out, "n_lines", newSVuv(lineno));
3424 660 (void)hv_stores(out, "format", newSVpvs("mmcif"));
3425 660 return out;
3426 }
3427  
3428 /*slurp() -- read the whole file. Chunked rather than stat-then-read so that
3429 a named pipe or /dev/stdin works the same as a file on disk.
3430  
3431 Read through PerlIO, not stdio, so the file goes through the same layer perl's
3432 own opens do on whatever this was built for. The mode is "rb": PerlIOBase_pushed()
3433 clears PERLIO_F_CRLF for a mode with a `b' in it, which is what keeps a Windows
3434 build from translating line endings under the fixed-column reader. The buffered
3435 layer copies the file once more than glibc's fread() does, which on 2wy2 -- the
3436 33 MB largest entry in PDBbind v2020 -- is 1 ms of a 23 ms read (best of seven,
3437 warm cache) and nothing measurable on an ordinary entry.
3438  
3439 A directory is refused before the open, because what happens when one is read is
3440 not the same on two systems: glibc opens it and fails the first fread() with
3441 EISDIR, Windows will not open it at all, and NetBSD hands back the raw directory
3442 blocks, which parse as a structure with nothing in it -- a silent empty answer
3443 for what is always a mistake. Both of the others came back as t/errors.t
3444 failures from 0.031 smokers (Strawberry 5.42.0 on Win2012, and perl 5.42.3 on
3445 NetBSD 11). structure_info() rejects a directory in Perl before it ever gets
3446 here; this is the same complaint for a caller that reached past it.*/
3447 1102 static char *slurp(pTHX_ const char *CSP_RESTRICT path, STRLEN *CSP_RESTRICT lenp){
3448 //no CSP_RESTRICT on fh: it is perl-managed, and the layers below it alias it
3449 PerlIO *fh;
3450 char *CSP_RESTRICT buf;
3451 Stat_t st;
3452 /*1 MB to start and doubling from there, for what stat() cannot size: a
3453 pipe, /dev/stdin. A regular file is allocated at its size plus one byte,
3454 the byte being room for the read that comes back 0 at the end, so the loop
3455 below never grows the buffer at all. Doubling would have left the 33 MB
3456 largest entry in PDBbind v2020 in a 64 MB block, reallocated six times on
3457 the way, and that block lives for the whole parse.*/
3458 1102 STRLEN cap = 1 << 20, len = 0;
3459 1102 const bool have_stat = PerlLIO_stat(path, &st) == 0;
3460 1102 ▶ if (have_stat && S_ISDIR(st.st_mode))
Branch: 2 branches
BranchTrueFalseTotal
if (have_stat && S_ISDIR(st.st_mode)) 1098 4 1102
if (have_stat && S_ISDIR(st.st_mode)) 3 1095 1098
3461 3 croak("Chem::Structure::Parser: cannot read '%s': it is a directory", path);
3462 //the comparison is the test that the size fits a STRLEN at all
3463 1099 ▶ if (have_stat && S_ISREG(st.st_mode) && st.st_size > 0
Branch: 2 branches
BranchTrueFalseTotal
if (have_stat && S_ISREG(st.st_mode) && st.st_size > 0 1095 4 1099
if (have_stat && S_ISREG(st.st_mode) && st.st_size > 0 1094 1 1095
3464 1094 ▶ && (Off_t)(STRLEN)st.st_size == st.st_size && (STRLEN)st.st_size < (STRLEN)-1)
Branch: 2 branches
BranchTrueFalseTotal
&& (Off_t)(STRLEN)st.st_size == st.st_size && (STRLEN)st.st_size < (STRLEN)-1) 1065 29 1094
&& (Off_t)(STRLEN)st.st_size == st.st_size && (STRLEN)st.st_size < (STRLEN)-1) 1065 0 1065
3465 1065 cap = (STRLEN)st.st_size + 1;
3466 1099 fh = PerlIO_open(path, "rb");
3467 1099 ▶ if (!fh) croak("Chem::Structure::Parser: cannot read '%s': %s", path, Strerror(errno));
Branch: 1 branch
BranchTrueFalseTotal
if (!fh) croak("Chem::Structure::Parser: cannot read '%s': %s", path, Strerror(errno)); 6 1093 1099
3468 1093 Newx(buf, cap, char);
3469 1064 for (;;) {
3470 SSize_t got;
3471 2157 ▶ if (len == cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (len == cap) { 0 2157 2157
3472 /*Only a stream reaches here, and only one past half the address
3473 space would wrap the doubling to a small cap -- 2 GB on a 32-bit
3474 perl, where that is a pipe and not unthinkable.*/
3475 0 ▶ if (cap > (STRLEN)-1 / 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (cap > (STRLEN)-1 / 2) { 0 0 0
3476 0 Safefree(buf);
3477 0 PerlIO_close(fh);
3478 0 croak("Chem::Structure::Parser: '%s' is too large to read into memory", path);
3479 }
3480 0 cap *= 2;
3481 0 Renew(buf, cap, char);
3482 }
3483 2157 got = PerlIO_read(fh, buf + len, cap - len);
3484 2157 ▶ if (got <= 0) break;// 0 is end of file, -1 an error PerlIO_error() reports
Branch: 1 branch
BranchTrueFalseTotal
if (got <= 0) break;// 0 is end of file, -1 an error PerlIO_error() reports 1093 1064 2157
3485 1064 len += (STRLEN)got;
3486 }
3487 1093 ▶ if (PerlIO_error(fh)) {
Branch: 1 branch
BranchTrueFalseTotal
if (PerlIO_error(fh)) { 0 1093 1093
3488 0 int e = errno;
3489 0 Safefree(buf);
3490 0 PerlIO_close(fh);
3491 0 croak("Chem::Structure::Parser: error reading '%s': %s", path, Strerror(e));
3492 }
3493 1093 PerlIO_close(fh);
3494 1093 *lenp = len;
3495 1093 return buf;
3496 }
3497  
3498 /*text_bytes() -- the bytes of a structure handed over as a string, the same
3499 bytes whichever way perl happens to be holding it.
3500  
3501 SvPV() hands back a string's buffer as it is stored, and a string perl has
3502 upgraded to UTF-8 stores an author's name with one accented letter in it as a
3503 byte longer than the same string not upgraded -- equal strings, eq says so,
3504 that parsed differently: the upgraded one's author came back as those bytes,
3505 the accented letter printing as two, and a character past ASCII in an ATOM
3506 line put every column after it one out. A caller who decoded a file before
3507 handing it over got that. So a string holding UTF-8 is read through a copy
3508 downgraded to one byte per character, which every string whose characters fit
3509 in a byte has, and that is every structure file there is. A string with a
3510 character beyond U+00FF cannot be downgraded and is read as the UTF-8 it
3511 holds, which is what reading the file it came from would have given.
3512  
3513 The string is fetched once, so a tied one is read once, and the flag is asked
3514 after the fetch, which is when it is true of what was fetched. The copy is
3515 mortal and lives until the XSUB that asked for it has returned, and is only
3516 read, as the whole-file buffer is.*/
3517 //text is not CSP_RESTRICT: it is a perl SV, and perl may alias it
3518 640 static const char *text_bytes(pTHX_ SV *text, STRLEN *CSP_RESTRICT len){
3519 640 const char *p = SvPV_const(text, *len);
3520 SV *copy;
3521 640 ▶ if (!SvUTF8(text)) return p;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvUTF8(text)) return p; 636 4 640
3522 4 copy = sv_2mortal(newSVpvn(p, *len));
3523 4 SvUTF8_on(copy);
3524 4 (void)sv_utf8_downgrade(copy, TRUE);
3525 4 return SvPV_const(copy, *len);
3526 }
3527  
3528 /*The rest of convert(): what can only be written once every atom has been.*/
3529  
3530 //by id, and the rows that have none after every row that has one
3531 57 static int cv_aniso_cmp(const void *pa, const void *pb){
3532 57 const cv_aniso *a = (const cv_aniso *)pa, *b = (const cv_aniso *)pb;
3533 57 ▶ if (a->have_id != b->have_id) return a->have_id ? -1 : 1;
Branch: 2 branches
BranchTrueFalseTotal
if (a->have_id != b->have_id) return a->have_id ? -1 : 1; 0 57 57
if (a->have_id != b->have_id) return a->have_id ? -1 : 1; 0 0 0
3534 57 ▶ if (!a->have_id) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!a->have_id) return 0; 0 57 57
3535 57 ▶ return a->id < b->id ? -1 : (a->id > b->id ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
return a->id < b->id ? -1 : (a->id > b->id ? 1 : 0); 24 33 57
3536 }
3537  
3538 168587 static int cv_iv_cmp(const void *pa, const void *pb){
3539 168587 const IV a = *(const IV *)pa, b = *(const IV *)pb;
3540 168587 ▶ return a < b ? -1 : (a > b ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
return a < b ? -1 : (a > b ? 1 : 0); 29416 139171 168587
3541 }
3542  
3543 /*cv_u_iv() -- an mmCIF U as the integer an ANISOU record holds it as, in units
3544 of 10**-4 A**2, rounded to the nearest; FALSE for one that is not a number or
3545 has no room in the record's seven columns. *exact says whether that integer is
3546 the value as written, which is the test cv_num() makes of a coordinate.*/
3547 88 static bool cv_u_iv(const char *CSP_RESTRICT s, STRLEN n, IV *CSP_RESTRICT out, bool *CSP_RESTRICT exact){
3548 NV v, t, back;
3549 char tmp[48];
3550 88 ▶ if (!str2nv(s, cif_num_len(s, n), &v) || !nv_is_finite(v)) return FALSE;
Branch: 2 branches
BranchTrueFalseTotal
if (!str2nv(s, cif_num_len(s, n), &v) || !nv_is_finite(v)) return FALSE; 88 0 88
if (!str2nv(s, cif_num_len(s, n), &v) || !nv_is_finite(v)) return FALSE; 0 88 88
3551 88 t = v * 10000.0;
3552 88 ▶ if (!(t > -999999.5 && t < 9999999.5)) return FALSE;
Branch: 2 branches
BranchTrueFalseTotal
if (!(t > -999999.5 && t < 9999999.5)) return FALSE; 88 0 88
if (!(t > -999999.5 && t < 9999999.5)) return FALSE; 2 86 88
3553 86 ▶ *out = (IV)(t < 0 ? t - 0.5 : t + 0.5);
Branch: 1 branch
BranchTrueFalseTotal
*out = (IV)(t < 0 ? t - 0.5 : t + 0.5); 11 75 86
3554 86 ▶ *exact = str2nv(tmp, cv_u_text(*out, tmp, sizeof(tmp)), &back) && back == v;
Branch: 2 branches
BranchTrueFalseTotal
*exact = str2nv(tmp, cv_u_text(*out, tmp, sizeof(tmp)), &back) && back == v; 86 0 86
*exact = str2nv(tmp, cv_u_text(*out, tmp, sizeof(tmp)), &back) && back == v; 85 1 86
3555 86 return TRUE;
3556 }
3557  
3558 /*cv_merge() -- one model's records onto out, each atom's with its
3559 _atom_site_anisotrop row after it as an ANISOU record. The atom is found by
3560 the serial its record was written with, which is its _atom_site.id.*/
3561 7 static bool cv_merge(pTHX_ cv_w *CSP_RESTRICT w, SV *CSP_RESTRICT out, SV *CSP_RESTRICT buf){
3562 7 const char *CSP_RESTRICT p = SvPVX(buf);
3563 7 const char *CSP_RESTRICT end = p + SvCUR(buf);
3564 28 ▶ for (; p < end; p += CV_LINE) {
Branch: 1 branch
BranchTrueFalseTotal
for (; p < end; p += CV_LINE) { 23 5 28
3565 cv_aniso key;
3566 const cv_aniso *e;
3567 IV u[6];
3568 bool have[6];
3569 23 sv_catpvn(out, p, CV_LINE);
3570 23 ▶ if (memcmp(p, "ATOM ", 6) != 0 && memcmp(p, "HETATM", 6) != 0) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (memcmp(p, "ATOM ", 6) != 0 && memcmp(p, "HETATM", 6) != 0) continue; 5 18 23
if (memcmp(p, "ATOM ", 6) != 0 && memcmp(p, "HETATM", 6) != 0) continue; 5 0 5
3571 18 key.have_id = fld_hy36(p, CV_LINE - 1, 6, 10, &key.id);
3572 18 ▶ if (!key.have_id) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!key.have_id) continue; 0 18 18
3573 18 e = (const cv_aniso *)bsearch(&key, w->at, w->n_at, sizeof(cv_aniso), cv_aniso_cmp);
3574 18 ▶ if (!e) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!e) continue; 0 18 18
3575 114 ▶ for (unsigned short i = 0; i < 6; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < 6; i++) { 98 16 114
3576 98 bool exact = TRUE;
3577 98 have[i] = e->u_n[i] > 0;
3578 98 ▶ if (have[i] && !cv_u_iv(e->u[i], e->u_n[i], &u[i], &exact)) {
Branch: 2 branches
BranchTrueFalseTotal
if (have[i] && !cv_u_iv(e->u[i], e->u_n[i], &u[i], &exact)) { 88 10 98
if (have[i] && !cv_u_iv(e->u[i], e->u_n[i], &u[i], &exact)) { 2 86 88
3579 2 cv_fail(aTHX_ w, NULL, "convert: the anisotropic displacement '%.*s' of atom %" IVdf
3580 " does not fit the seven columns an ANISOU record has for it",
3581 2 (int)e->u_n[i], e->u[i], e->id);
3582 2 return FALSE;
3583 }
3584 96 ▶ if (have[i] && !exact) w->n_rounded++;
Branch: 2 branches
BranchTrueFalseTotal
if (have[i] && !exact) w->n_rounded++; 86 10 96
if (have[i] && !exact) w->n_rounded++; 1 85 86
3585 }
3586 16 cv_pdb_anisou(aTHX_ out, p, u, have);
3587 16 w->n_aniso++;
3588 }
3589 5 return TRUE;
3590 }
3591  
3592 /*cv_pdb_join() -- the coordinate section of a PDB file: the models, each inside
3593 MODEL and ENDMDL when there is more than one or the one there is is not model 1
3594 (which is what a file without MODEL records reads as), with the ANISOU records
3595 of an mmCIF file put in. The models' own strings are given back as each is
3596 copied, so the peak is one model over the whole, not the whole twice.*/
3597 221 static SV *cv_pdb_join(pTHX_ cv_w *CSP_RESTRICT w){
3598 221 ▶ const bool wrap = w->n_model > 1 || (w->n_model == 1 && w->m_num[0] != 1);
Branch: 3 branches
BranchTrueFalseTotal
const bool wrap = w->n_model > 1 || (w->n_model == 1 && w->m_num[0] != 1); 181 40 221
const bool wrap = w->n_model > 1 || (w->n_model == 1 && w->m_num[0] != 1); 171 10 181
const bool wrap = w->n_model > 1 || (w->n_model == 1 && w->m_num[0] != 1); 3 168 171
3599 221 STRLEN total = 0;
3600 SV *out;
3601 221 ▶ if (w->ter_open) cv_ter(aTHX_ w);
Branch: 1 branch
BranchTrueFalseTotal
if (w->ter_open) cv_ter(aTHX_ w); 180 41 221
3602 221 ▶ if (!w->n_model) return newSVpvs("");
Branch: 1 branch
BranchTrueFalseTotal
if (!w->n_model) return newSVpvs(""); 10 211 221
3603 211 ▶ if (!wrap && !w->n_at) {
Branch: 2 branches
BranchTrueFalseTotal
if (!wrap && !w->n_at) { 168 43 211
if (!wrap && !w->n_at) { 165 3 168
3604 165 out = w->m_buf[0];
3605 165 w->m_buf[0] = NULL;
3606 165 return out;
3607 }
3608 173 ▶ for (size_t i = 0; i < w->n_model; i++) total += SvCUR(w->m_buf[i]);
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < w->n_model; i++) total += SvCUR(w->m_buf[i]); 127 46 173
3609 46 ▶ if (wrap) total += 2 * CV_LINE * w->n_model;
Branch: 1 branch
BranchTrueFalseTotal
if (wrap) total += 2 * CV_LINE * w->n_model; 43 3 46
3610 46 ▶ if (w->n_at) {
Branch: 1 branch
BranchTrueFalseTotal
if (w->n_at) { 6 40 46
3611 6 qsort(w->at, w->n_at, sizeof(cv_aniso), cv_aniso_cmp);
3612 6 total += w->n_at * CV_LINE;
3613 }
3614 46 out = newSVpvs("");
3615 46 ▶ SvGROW(out, total + 1);
Branch: 2 branches
BranchTrueFalseTotal
SvGROW(out, total + 1); 46 0 46
SvGROW(out, total + 1); 46 0 46
3616 164 ▶ for (size_t i = 0; i < w->n_model; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < w->n_model; i++) { 123 41 164
3617 char line[CV_LINE];
3618 123 ▶ if (wrap) {
Branch: 1 branch
BranchTrueFalseTotal
if (wrap) { 120 3 123
3619 char tmp[32];//an IV prints in at most 21 characters, sign included
3620 STRLEN k;
3621 //columns 11-14, which is all the PDB reader reads a model number from
3622 120 ▶ if (w->m_num[i] <= -1000 || w->m_num[i] > 9999) {
Branch: 2 branches
BranchTrueFalseTotal
if (w->m_num[i] <= -1000 || w->m_num[i] > 9999) { 120 0 120
if (w->m_num[i] <= -1000 || w->m_num[i] > 9999) { 3 117 120
3623 3 cv_fail(aTHX_ w, NULL, "convert: model %" IVdf " has no PDB spelling: "
3624 3 "a MODEL record has four columns for its number", w->m_num[i]);
3625 3 SvREFCNT_dec(out);
3626 3 return NULL;
3627 }
3628 117 cv_blank(line);
3629 117 memcpy(line, "MODEL", 5);
3630 117 k = (STRLEN)my_snprintf(tmp, sizeof(tmp), "%" IVdf, w->m_num[i]);
3631 117 memcpy(line + 14 - k, tmp, k);
3632 117 sv_catpvn(out, line, CV_LINE);
3633 }
3634 120 ▶ if (!w->n_at) {
Branch: 1 branch
BranchTrueFalseTotal
if (!w->n_at) { 113 7 120
3635 113 sv_catpvn(out, SvPVX(w->m_buf[i]), SvCUR(w->m_buf[i]));
3636 7 ▶ } else if (!cv_merge(aTHX_ w, out, w->m_buf[i])) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (!cv_merge(aTHX_ w, out, w->m_buf[i])) { 2 5 7
3637 2 SvREFCNT_dec(out);
3638 2 return NULL;
3639 }
3640 118 ▶ if (wrap) {
Branch: 1 branch
BranchTrueFalseTotal
if (wrap) { 115 3 118
3641 115 cv_blank(line);
3642 115 memcpy(line, "ENDMDL", 6);
3643 115 sv_catpvn(out, line, CV_LINE);
3644 }
3645 118 SvREFCNT_dec(w->m_buf[i]);
3646 118 w->m_buf[i] = NULL;
3647 }
3648 41 return out;
3649 }
3650  
3651 /*cv_cif_aniso_rows() -- an mmCIF file's _atom_site_anisotrop going back out to
3652 mmCIF: the rows of the atoms that were written, as the file wrote them*/
3653 3 static void cv_cif_aniso_rows(pTHX_ cv_w *CSP_RESTRICT w){
3654 3 SV *CSP_RESTRICT o = w->aniso;
3655 3 qsort(w->wid, w->n_wid, sizeof(IV), cv_iv_cmp);
3656 15 ▶ for (size_t i = 0; i < w->n_at; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < w->n_at; i++) { 12 3 15
3657 12 const cv_aniso *CSP_RESTRICT e = &w->at[i];
3658 bool ok;
3659 12 ▶ if (!e->have_id || !bsearch(&e->id, w->wid, w->n_wid, sizeof(IV), cv_iv_cmp)) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!e->have_id || !bsearch(&e->id, w->wid, w->n_wid, sizeof(IV), cv_iv_cmp)) continue; 12 0 12
if (!e->have_id || !bsearch(&e->id, w->wid, w->n_wid, sizeof(IV), cv_iv_cmp)) continue; 1 11 12
3660 11 ▶ if (!w->n_aniso) sv_catpvn(o, cv_aniso_head, sizeof(cv_aniso_head) - 1);
Branch: 1 branch
BranchTrueFalseTotal
if (!w->n_aniso) sv_catpvn(o, cv_aniso_head, sizeof(cv_aniso_head) - 1); 3 8 11
3661 11 cv_cif_iv(aTHX_ o, TRUE, e->id);
3662 11 ok = cv_cif_val(aTHX_ o, e->sym, e->sym_n, '?');
3663 77 ▶ for (unsigned short k = 0; k < 6; k++) ok = ok && cv_cif_val(aTHX_ o, e->u[k], e->u_n[k], '?');
Branch: 3 branches
BranchTrueFalseTotal
for (unsigned short k = 0; k < 6; k++) ok = ok && cv_cif_val(aTHX_ o, e->u[k], e->u_n[k], '?'); 66 0 66
for (unsigned short k = 0; k < 6; k++) ok = ok && cv_cif_val(aTHX_ o, e->u[k], e->u_n[k], '?'); 66 0 66
for (unsigned short k = 0; k < 6; k++) ok = ok && cv_cif_val(aTHX_ o, e->u[k], e->u_n[k], '?'); 66 11 77
3664 11 ▶ if (!ok) {
Branch: 1 branch
BranchTrueFalseTotal
if (!ok) { 0 11 11
3665 0 cv_fail(aTHX_ w, NULL, "convert: a field of the _atom_site_anisotrop row of atom %" IVdf
3666 0 " has a line end in it, and an mmCIF row has no way to quote one", e->id);
3667 0 return;
3668 }
3669 11 SvPVX(o)[SvCUR(o) - 1] = '\n';
3670 11 w->n_aniso++;
3671 }
3672 }
3673  
3674 426 static void cv_finish(pTHX_ cv_w *CSP_RESTRICT w, HV *CSP_RESTRICT out){
3675 AV *models;
3676 426 ▶ if (w->to_pdb) {
Branch: 1 branch
BranchTrueFalseTotal
if (w->to_pdb) { 221 205 426
3677 221 SV *text = cv_pdb_join(aTHX_ w);
3678 221 ▶ if (!text) return;
Branch: 1 branch
BranchTrueFalseTotal
if (!text) return; 5 216 221
3679 216 (void)hv_stores(out, "coordinates", text);
3680 } else {
3681 205 ▶ if (w->n_at) cv_cif_aniso_rows(aTHX_ w);
Branch: 1 branch
BranchTrueFalseTotal
if (w->n_at) cv_cif_aniso_rows(aTHX_ w); 3 202 205
3682 205 ▶ if (w->err) return;
Branch: 1 branch
BranchTrueFalseTotal
if (w->err) return; 0 205 205
3683 205 (void)hv_stores(out, "coordinates", w->atoms);
3684 205 (void)hv_stores(out, "anisotrop", w->aniso);
3685 205 w->atoms = w->aniso = NULL;
3686 }
3687 421 models = newAV();
3688 967 ▶ for (size_t i = 0; i < w->n_model; i++) av_push(models, newSViv(w->m_num[i]));
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < w->n_model; i++) av_push(models, newSViv(w->m_num[i])); 546 421 967
3689 421 (void)hv_stores(out, "models_written", newRV_noinc((SV *)models));
3690 421 (void)hv_stores(out, "chains_written", newRV_inc((SV *)w->chain_order));
3691 421 (void)hv_stores(out, "n_written", newSVuv(w->n_atom));
3692 421 (void)hv_stores(out, "n_anisou_written", newSVuv(w->n_aniso));
3693 421 (void)hv_stores(out, "n_rounded", newSVuv(w->n_rounded));
3694 }
3695  
3696 /*the writer for one conversion. The caller has Zero()ed it and handed it to
3697 SAVEDESTRUCTOR_X(cv_free_cb) first, so that a die reading the anisou option
3698 frees what there is.*/
3699 446 static void cv_init(pTHX_ cv_w *CSP_RESTRICT w, bool from_cif, bool to_pdb, HV *CSP_RESTRICT o){
3700 446 w->keep_aniso = opt_bool(aTHX_ o, "anisou", TRUE);
3701 444 w->from_cif = from_cif;
3702 444 w->to_pdb = to_pdb;
3703 444 w->chain_seen = newHV();
3704 444 w->chain_order = newAV();
3705 444 w->p_chain = newSVpvs("");
3706 444 ▶ if (!to_pdb) {
Branch: 1 branch
BranchTrueFalseTotal
if (!to_pdb) { 205 239 444
3707 205 w->atoms = newSVpvs("");
3708 205 w->aniso = newSVpvs("");
3709 }
3710 444 }
3711  
3712 /*convert_do() -- one file's worth of bytes through the reader for its format
3713 and the writer w was set up for; the parse's hash comes back, with what was
3714 written added to it. Run between the XSUB's ENTER and LEAVE, which free w
3715 whichever way this ends. A field that would not go across croaks here, once
3716 the parse has returned and its hash can be given back.*/
3717 443 static HV *convert_do(pTHX_ cv_w *CSP_RESTRICT w, const char *CSP_RESTRICT buf, STRLEN len,
3718 HV *CSP_RESTRICT o){
3719 443 ▶ HV *res = w->from_cif ? parse_cif_buf(aTHX_ buf, len, o, w) : parse_buf(aTHX_ buf, len, o, w);
Branch: 1 branch
BranchTrueFalseTotal
HV *res = w->from_cif ? parse_cif_buf(aTHX_ buf, len, o, w) : parse_buf(aTHX_ buf, len, o, w); 229 214 443
3720 439 ▶ if (!w->err) cv_finish(aTHX_ w, res);
Branch: 1 branch
BranchTrueFalseTotal
if (!w->err) cv_finish(aTHX_ w, res); 426 13 439
3721 439 ▶ if (w->err) {
Branch: 1 branch
BranchTrueFalseTotal
if (w->err) { 18 421 439
3722 18 SV *e = sv_2mortal(w->err);
3723 18 w->err = NULL;
3724 18 SvREFCNT_dec((SV *)res);
3725 18 croak("%s", SvPV_nolen(e));
3726 }
3727 421 return res;
3728 }
3729  
3730 /*asking a parsed chain a question.
3731  
3732 Reading the hash of hashes back is Perl's job nine times in ten -- one lookup
3733 is one line of Perl and nothing to be gained by crossing into C for it. A
3734 question asked once per chain of every chain of every file in a set is the
3735 exception: a structure with a dozen ions has more chains that are one ion than
3736 chains that are a polymer, and the loop that has to tell them apart runs the
3737 whole way down the set.
3738  
3739 Nothing here re-does chemistry, and nothing here consults it either: the answer
3740 is in the shape of the chain.*/
3741  
3742 /*the chain hash the caller means, from either shape of argument: a chain on
3743 its own, or the structure and a chain id. Every wrong argument that has an
3744 obvious right one nearby says so, since the three hashes in a parsed structure
3745 -- structure, chain, residue -- all look alike from inside a hash reference and
3746 a false answer would be taken at face value.*/
3747 43 static HV *chain_arg(pTHX_ SV *CSP_RESTRICT first, SV *CSP_RESTRICT id, const char *CSP_RESTRICT who){
3748 HV *h;
3749 43 ▶ if (!SvROK(first) || SvTYPE(SvRV(first)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(first) || SvTYPE(SvRV(first)) != SVt_PVHV) 40 3 43
if (!SvROK(first) || SvTYPE(SvRV(first)) != SVt_PVHV) 1 39 40
3750 4 croak("%s: expected the chain hash reference from structure_info()", who);
3751 39 h = (HV *)SvRV(first);
3752 39 ▶ if (SvOK(id)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(id)) { 23 16 39
3753 HE *he;
3754 23 SV **p = hv_fetchs(h, "chains", 0);
3755 23 ▶ if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVHV)
Branch: 4 branches
BranchTrueFalseTotal
if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVHV) 23 0 23
if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVHV) 23 0 23
if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVHV) 22 1 23
if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVHV) 0 22 22
3756 1 croak("%s: expected the hash reference from structure_info()", who);
3757 22 he = hv_fetch_ent((HV *)SvRV(*p), id, 0, 0);
3758 22 ▶ if (!he || !SvROK(HeVAL(he)) || SvTYPE(SvRV(HeVAL(he))) != SVt_PVHV)
Branch: 3 branches
BranchTrueFalseTotal
if (!he || !SvROK(HeVAL(he)) || SvTYPE(SvRV(HeVAL(he))) != SVt_PVHV) 19 3 22
if (!he || !SvROK(HeVAL(he)) || SvTYPE(SvRV(HeVAL(he))) != SVt_PVHV) 19 0 19
if (!he || !SvROK(HeVAL(he)) || SvTYPE(SvRV(HeVAL(he))) != SVt_PVHV) 0 19 19
3759 3 croak("%s: no chain '%s'", who, SvPV_nolen(id));
3760 19 h = (HV *)SvRV(HeVAL(he));
3761 }
3762 //residue_order is what every chain has and nothing else in the structure does
3763 35 ▶ if (!hv_exists(h, "residue_order", 13)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!hv_exists(h, "residue_order", 13)) { 6 29 35
3764 6 ▶ if (hv_exists(h, "chains", 6))
Branch: 1 branch
BranchTrueFalseTotal
if (hv_exists(h, "chains", 6)) 3 3 6
3765 3 croak("%s: that is the whole structure, not a chain: pass one of $info->{chains}, or call %s($info, $chain)", who, who);
3766 3 ▶ if (hv_exists(h, "atom_order", 10))
Branch: 1 branch
BranchTrueFalseTotal
if (hv_exists(h, "atom_order", 10)) 2 1 3
3767 2 croak("%s: that is a residue, not a chain: a residue answers for itself, in $res->{type}", who);
3768 1 croak("%s: expected the chain hash reference from structure_info()", who);
3769 }
3770 29 return h;
3771 }
3772  
3773 /*is_single_ion() -- true when a chain holds exactly one residue.
3774  
3775 An ion is often numbered into the chain it sits in -- the zinc of a zinc finger
3776 is residue 202 of chain A -- and just as often given a chain of its own, which
3777 is a chain with one residue in it and no sequence to read. A caller walking
3778 chain_order wants those out of the way before it asks for a sequence or an
3779 alignment, and the count is the whole of the question: single means one residue
3780 in the chain, so a chain of two zincs is not one and a zinc numbered into a
3781 protein chain does not make that chain one.
3782  
3783 Single says nothing about how many atoms the residue has. A sulphate is five
3784 atoms and a perchlorate is five different ones, and both are one residue, so
3785 both answer the same -- which they would not if the count were of atoms, and
3786 would not either if this asked whether the residue types as an ion. That type
3787 comes off a table of names, and a table of names cannot be complete: SO4 is on
3788 the module's list and BF4 is not, and the difference between them is which ions
3789 someone got round to writing down, not anything about the file. Counting
3790 residues asks nothing of the table and so cannot inherit its gaps.
3791  
3792 The residue is therefore not asked what it is, and the answer is about the shape
3793 of the chain rather than the chemistry in it: a chain that is one sugar, one
3794 buffer molecule, one water or one free amino acid answers true as well. In a
3795 real file those are rare next to the ions and are the same nuisance to a caller
3796 walking chains -- one residue, no sequence -- but a caller who needs to tell
3797 them apart has it a lookup away, in the residue's own type.*/
3798 29 static bool chain_is_single_ion(pTHX_ HV *CSP_RESTRICT c){
3799 29 SV **p = hv_fetchs(c, "residue_order", 0);
3800 29 ▶ if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVAV) return 0;
Branch: 4 branches
BranchTrueFalseTotal
if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVAV) return 0; 29 0 29
if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVAV) return 0; 29 0 29
if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVAV) return 0; 29 0 29
if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVAV) return 0; 0 29 29
3801 /*residue_order rather than n_residues or the residues hash: it is the
3802 chain's own list of what is in it, in the order the file had them, and
3803 counting it needs no iterator reset that a caller mid-each() would feel.
3804 av_len() is the last index, so 0 is one residue and -1 is none.*/
3805 29 return av_len((AV *)SvRV(*p)) == 0;
3806 }
3807  
3808 /*Physical properties of a structure.
3809  
3810 Everything from here to the MODULE line answers questions about a structure
3811 that has already been read: how much of it the solvent can touch, how big it
3812 is, how heavy it is, and which of its aromatic rings are stacked on each
3813 other. None of it is part of the parse -- it is asked for by name, on an
3814 $info that already exists -- but all of it has to touch every atom, so by the
3815 rule in notes.txt it belongs here rather than in Perl.
3816  
3817 The walk is the reason. A structure is a hash of chains of residues of atoms,
3818 and the calculations below want it as flat arrays of coordinates: doing that
3819 in Perl would mean building a second copy of the coordinate section, which is
3820 the mistake the second round of benchmarking found and took out. set_build()
3821 walks the hash once into four NV arrays and hands them to whichever of the
3822 calculations were asked for, so a caller who wants all of them pays for one
3823 walk.
3824  
3825 Provenance -- every number below came from somebody else's implementation, and
3826 the tests compare against those implementations rather than against this one:
3827  
3828 SASA Shrake, A; Rupley, JA (1973) J Mol Biol 79(2):351-71, as
3829 mdtraj 1.11's mdtraj.geometry.shrake_rupley (sasa.py and the
3830 C kernel behind mdtraj.geometry._geometry._sasa): golden
3831 section spiral sphere points, a probe rolled over the van der
3832 Waals surface, the accessible fraction of each atom's points.
3833 vdW radii mdtraj's _ATOMIC_RADII (mdtraj/geometry/sasa.py), which is
3834 Bondi, A (1964) J Phys Chem 68:441 as extended by Mantina, M
3835 et al. (2009) J Phys Chem A 113:5806, with Shannon, R D (1976)
3836 Acta Cryst A32:751 ionic radii substituted for the ions that
3837 are always ionised in a biophysical setting (Li Na K Cs Be Mg
3838 Ca Ba Cl), and 2.0 A for an element with no measured value.
3839 masses mdtraj/core/element.py. The five elements it names no mass
3840 for are marked below.
3841 pi-stacking mdtraj.geometry.pi_stacking (mdtraj/geometry/pi_stacking.py),
3842 which is itself ProLIF's FaceToFace and EdgeToFace geometry.
3843 max ASA Tien, M Z; Meyer, A G; Sydykova, D K; Spielman, S J; Wilke, C O
3844 (2013) PLoS ONE 8(11):e80635, Table 1, the "Theoretical"
3845 column, for the relative accessibility of a residue.
3846  
3847 mdtraj works in nanometres and float32; this file works in angstrom and NV,
3848 which is what the PDB and mmCIF formats are written in and what the rest of
3849 the module already returns. The formulae are the same ones -- an area is
3850 4*pi*r^2 times the accessible fraction whichever unit r is in -- so the answers
3851 agree to the width of a float32, which is what t/features.t measures rather
3852 than assumes.*/
3853  
3854 /*elem_prop_of() -- the van der Waals radius and standard atomic weight of an
3855 element symbol, or false for a field that spells no element.
3856  
3857 Keyed the way elem_case() is, on the symbol's one or two bytes packed into a
3858 U32 and upper-cased first, so that a symbol arriving as "ZN", "Zn" or "zn" is
3859 one lookup. The four heaviest are spelled Nh, Mc, Ts and Og -- IUPAC's 2016
3860 names, which is what elem_case() puts in an $info -- where mdtraj's tables
3861 still carry the placeholder Uut, Uup, Uus and Uuo.*/
3862 typedef struct {
3863 NV vdw;//van der Waals radius, angstrom
3864 NV mass;//standard atomic weight, dalton; 0.0 where mdtraj names none
3865 U32 key;//the symbol packed and upper-cased, so a caller can ask which it was
3866 } elem_prop;
3867  
3868 //mdtraj's own fallback: "Where no van der Waals value is known, a default of
3869 //2 angstroms is used"
3870 #define CSP_VDW_DEFAULT 2.0
3871  
3872 120318 static bool elem_prop_of(const char *CSP_RESTRICT s, STRLEN len, elem_prop *CSP_RESTRICT out){
3873 //initialised because the compiler cannot see that every case assigns and
3874 //the default returns; the values are never the ones used
3875 120318 NV r = CSP_VDW_DEFAULT, m = 0.0;
3876 U32 key;
3877 120318 ▶ while (len && (*s == ' ' || *s == '\t')) { s++; len--; }
Branch: 3 branches
BranchTrueFalseTotal
while (len && (*s == ' ' || *s == '\t')) { s++; len--; } 120318 0 120318
while (len && (*s == ' ' || *s == '\t')) { s++; len--; } 0 120318 120318
while (len && (*s == ' ' || *s == '\t')) { s++; len--; } 0 120318 120318
3878 120318 ▶ while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--;
Branch: 3 branches
BranchTrueFalseTotal
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--; 120318 0 120318
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--; 0 120318 120318
while (len && (s[len - 1] == ' ' || s[len - 1] == '\t')) len--; 0 120318 120318
3879 120318 ▶ if (len == 0 || len > 2) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (len == 0 || len > 2) return 0; 120318 0 120318
if (len == 0 || len > 2) return 0; 0 120318 120318
3880 120318 key = (len == 1)
3881 120007 ▶ ? K2((unsigned char)toUPPER((unsigned char)s[0]), 0)
Branch: 1 branch
BranchTrueFalseTotal
? K2((unsigned char)toUPPER((unsigned char)s[0]), 0) 0 120007 120007
3882 240325 ▶ : K2((unsigned char)toUPPER((unsigned char)s[0]),
Branch: 3 branches
BranchTrueFalseTotal
: K2((unsigned char)toUPPER((unsigned char)s[0]), 120007 311 120318
: K2((unsigned char)toUPPER((unsigned char)s[0]), 0 311 311
: K2((unsigned char)toUPPER((unsigned char)s[0]), 308 3 311
3883 (unsigned char)toUPPER((unsigned char)s[1]));
3884 120318 switch (key) {
3885 2 case K2('B',0): r = 1.92; m = 10.8117; break;
3886 59023 case K2('C',0): r = 1.70; m = 12.01078; break;
3887 5 case K2('F',0): r = 1.47; m = 18.99840325; break;
3888 14137 case K2('H',0): r = 1.20; m = 1.007947; break;
3889 /*Deuterium, which the readers, the hydrogens filter and atom_is_h()
3890 all take for a hydrogen, as a neutron structure writes it. The mass
3891 and the 0.12 nm radius are mdtraj/core/element.py's `deuterium';
3892 mdtraj's own _ATOMIC_RADII has no D, and raises on one.*/
3893 1 case K2('D',0): r = 1.20; m = 2.0135532127; break;
3894 0 case K2('I',0): r = 1.98; m = 126.904473; break;
3895 0 case K2('K',0): r = 1.38; m = 39.09831; break;
3896 19268 case K2('N',0): r = 1.55; m = 14.00672; break;
3897 25536 case K2('O',0): r = 1.52; m = 15.99943; break;
3898 1590 case K2('P',0): r = 1.80; m = 30.9737622; break;
3899 441 case K2('S',0): r = 1.80; m = 32.0655; break;
3900 0 case K2('U',0): r = 1.86; m = 238.028913; break;
3901 0 case K2('V',0): r = 2.00; m = 50.94151; break;
3902 0 case K2('W',0): r = 2.00; m = 183.841; break;
3903 0 case K2('Y',0): r = 2.00; m = 88.905852; break;
3904 0 case K2('A','C'): r = 2.00; m = 227.0; break;
3905 0 case K2('A','G'): r = 1.72; m = 107.86822; break;
3906 0 case K2('A','L'): r = 1.84; m = 26.98153868; break;
3907 0 case K2('A','M'): r = 2.00; m = 243.0; break;
3908 0 case K2('A','R'): r = 1.88; m = 39.9481; break;
3909 0 case K2('A','S'): r = 1.85; m = 74.921602; break;
3910 0 case K2('A','T'): r = 2.02; m = 210.0; break;
3911 0 case K2('A','U'): r = 1.66; m = 196.9665694; break;
3912 0 case K2('B','A'): r = 1.49; m = 137.3277; break;
3913 0 case K2('B','E'): r = 0.59; m = 9.0121823; break;
3914 0 case K2('B','H'): r = 2.00; m = 264.0; break;
3915 0 case K2('B','I'): r = 2.07; m = 208.980401; break;
3916 0 case K2('B','K'): r = 2.00; m = 247.0; break;
3917 0 case K2('B','R'): r = 1.85; m = 79.9041; break;
3918 1 case K2('C','A'): r = 1.14; m = 40.0784; break;
3919 0 case K2('C','D'): r = 1.58; m = 112.4118; break;
3920 0 case K2('C','E'): r = 2.00; m = 140.1161; break;
3921 0 case K2('C','F'): r = 2.00; m = 251.0; break;
3922 1 case K2('C','L'): r = 1.81; m = 35.4532; break;
3923 0 case K2('C','M'): r = 2.00; m = 247.0; break;
3924 0 case K2('C','N'): r = 2.00; m = 0.0; break;
3925 0 case K2('C','O'): r = 2.00; m = 58.9331955; break;
3926 0 case K2('C','R'): r = 2.00; m = 51.99616; break;
3927 0 case K2('C','S'): r = 1.67; m = 132.90545192; break;
3928 0 case K2('C','U'): r = 1.40; m = 63.5463; break;
3929 0 case K2('D','B'): r = 2.00; m = 262.0; break;
3930 0 case K2('D','S'): r = 2.00; m = 281.0; break;
3931 0 case K2('D','Y'): r = 2.00; m = 162.5001; break;
3932 0 case K2('E','R'): r = 2.00; m = 167.2593; break;
3933 0 case K2('E','S'): r = 2.00; m = 252.0; break;
3934 0 case K2('E','U'): r = 2.00; m = 151.9641; break;
3935 1 case K2('F','E'): r = 2.00; m = 55.8452; break;
3936 0 case K2('F','L'): r = 2.00; m = 0.0; break;
3937 0 case K2('F','M'): r = 2.00; m = 257.0; break;
3938 0 case K2('F','R'): r = 3.48; m = 223.0; break;
3939 0 case K2('G','A'): r = 1.87; m = 69.7231; break;
3940 0 case K2('G','D'): r = 2.00; m = 157.253; break;
3941 0 case K2('G','E'): r = 2.11; m = 72.641; break;
3942 0 case K2('H','E'): r = 1.40; m = 4.003; break;
3943 0 case K2('H','F'): r = 2.00; m = 178.492; break;
3944 0 case K2('H','G'): r = 1.55; m = 200.592; break;
3945 0 case K2('H','O'): r = 2.00; m = 164.930322; break;
3946 0 case K2('H','S'): r = 2.00; m = 269.0; break;
3947 0 case K2('I','N'): r = 1.93; m = 114.8183; break;
3948 0 case K2('I','R'): r = 2.00; m = 192.2173; break;
3949 0 case K2('K','R'): r = 2.02; m = 83.7982; break;
3950 0 case K2('L','A'): r = 2.00; m = 138.905477; break;
3951 0 case K2('L','I'): r = 0.76; m = 6.9412; break;
3952 0 case K2('L','R'): r = 2.00; m = 262.0; break;
3953 0 case K2('L','U'): r = 2.00; m = 174.9671; break;
3954 0 case K2('L','V'): r = 2.00; m = 0.0; break;
3955 0 case K2('M','C'): r = 2.00; m = 288.0; break;
3956 0 case K2('M','D'): r = 2.00; m = 258.0; break;
3957 0 case K2('M','G'): r = 0.86; m = 24.30506; break;
3958 0 case K2('M','N'): r = 2.00; m = 54.9380455; break;
3959 0 case K2('M','O'): r = 2.00; m = 95.942; break;
3960 0 case K2('M','T'): r = 2.00; m = 268.0; break;
3961 1 case K2('N','A'): r = 1.02; m = 22.989769282; break;
3962 0 case K2('N','B'): r = 2.00; m = 92.906382; break;
3963 0 case K2('N','D'): r = 2.00; m = 144.2423; break;
3964 0 case K2('N','E'): r = 1.54; m = 20.17976; break;
3965 0 case K2('N','H'): r = 2.00; m = 284.0; break;
3966 0 case K2('N','I'): r = 1.63; m = 58.69342; break;
3967 0 case K2('N','O'): r = 2.00; m = 259.0; break;
3968 0 case K2('N','P'): r = 2.00; m = 237.0; break;
3969 0 case K2('O','G'): r = 2.00; m = 0.0; break;
3970 0 case K2('O','S'): r = 2.00; m = 190.233; break;
3971 0 case K2('P','A'): r = 2.00; m = 231.035882; break;
3972 0 case K2('P','B'): r = 2.02; m = 207.21; break;
3973 0 case K2('P','D'): r = 1.63; m = 106.421; break;
3974 0 case K2('P','M'): r = 2.00; m = 145.0; break;
3975 0 case K2('P','O'): r = 1.97; m = 209.0; break;
3976 0 case K2('P','R'): r = 2.00; m = 140.907652; break;
3977 0 case K2('P','T'): r = 1.75; m = 195.0849; break;
3978 0 case K2('P','U'): r = 2.00; m = 244.0; break;
3979 0 case K2('R','A'): r = 2.83; m = 226.0; break;
3980 0 case K2('R','B'): r = 3.03; m = 85.46783; break;
3981 0 case K2('R','E'): r = 2.00; m = 186.2071; break;
3982 0 case K2('R','F'): r = 2.00; m = 261.0; break;
3983 0 case K2('R','G'): r = 2.00; m = 272.0; break;
3984 0 case K2('R','H'): r = 2.00; m = 102.905502; break;
3985 0 case K2('R','N'): r = 2.20; m = 222.018; break;
3986 0 case K2('R','U'): r = 2.00; m = 101.072; break;
3987 0 case K2('S','B'): r = 2.06; m = 121.7601; break;
3988 0 case K2('S','C'): r = 2.11; m = 44.9559126; break;
3989 145 case K2('S','E'): r = 1.90; m = 78.963; break;
3990 0 case K2('S','G'): r = 2.00; m = 266.0; break;
3991 0 case K2('S','I'): r = 2.10; m = 28.08553; break;
3992 0 case K2('S','M'): r = 2.00; m = 150.362; break;
3993 0 case K2('S','N'): r = 2.17; m = 118.7107; break;
3994 0 case K2('S','R'): r = 2.49; m = 87.621; break;
3995 0 case K2('T','A'): r = 2.00; m = 180.947882; break;
3996 0 case K2('T','B'): r = 2.00; m = 158.925352; break;
3997 0 case K2('T','C'): r = 2.00; m = 98.0; break;
3998 0 case K2('T','E'): r = 2.06; m = 127.603; break;
3999 0 case K2('T','H'): r = 2.00; m = 232.038062; break;
4000 0 case K2('T','I'): r = 2.00; m = 47.8671; break;
4001 0 case K2('T','L'): r = 1.96; m = 204.38332; break;
4002 0 case K2('T','M'): r = 2.00; m = 168.934212; break;
4003 0 case K2('T','S'): r = 2.00; m = 0.0; break;
4004 0 case K2('X','E'): r = 2.16; m = 131.2936; break;
4005 0 case K2('Y','B'): r = 2.00; m = 173.043; break;
4006 159 case K2('Z','N'): r = 1.39; m = 65.4094; break;
4007 0 case K2('Z','R'): r = 2.00; m = 91.2242; break;
4008 7 default: return 0;//not a symbol: the caller decides what to do
4009 }
4010 120311 out->vdw = r;
4011 120311 out->mass = m;
4012 120311 out->key = key;
4013 120311 return 1;
4014 }
4015  
4016 /*max_asa[] -- the largest solvent-accessible surface a residue of each kind
4017 can have, in angstrom^2, indexed by its single-letter code less 'A'.
4018  
4019 Dividing a residue's SASA by this gives its relative accessibility, which is
4020 the number the buried/exposed question is actually asked of: 130 A^2 is most of
4021 an alanine and a sliver of a tryptophan. The values are the "Theoretical"
4022 column of Table 1 of Tien et al. (2013) -- a Gly-X-Gly tripeptide extended to
4023 its maximum -- rather than the empirical column of the same table, because the
4024 empirical one is the largest value seen in a particular set of structures and
4025 so goes stale as the archive grows.
4026  
4027 0.0 means the letter has no value: the six ambiguity and placeholder codes
4028 (B J O U X Z), and the twenty letters that are not amino acid codes at all.
4029 A residue with no value gets no relative accessibility rather than a wrong
4030 one.*/
4031 static const NV max_asa[26] = {
4032 129.0, 0.0, 167.0, 193.0, 223.0, 240.0, 104.0, 224.0, 197.0, 0.0, //A-J
4033 236.0, 201.0, 224.0, 195.0, 0.0, 159.0, 225.0, 274.0, 155.0, 172.0, //K-T
4034 0.0, 174.0, 285.0, 0.0, 263.0, 0.0 //U-Z
4035 };
4036  
4037 /*Aromatic rings, by residue name.
4038  
4039 A ring is a list of atom names, and the pi-stacking geometry needs it in a
4040 fixed order: mdtraj's compute_ring_normal() takes the plane's normal from the
4041 cross product of the first two atoms' offsets from the centroid, so two readers
4042 that list the same ring in a different order get normals that differ by
4043 whatever the ring departs from planarity in a real structure. The order below
4044 is the one t/data/features.py hands mdtraj, which is what makes the two
4045 comparable.
4046  
4047 Only the residues whose ring is fixed by the format's own atom naming are
4048 here: the four aromatic amino acids and the nucleobases. A ligand's rings
4049 would need bond perception, which this module does not do -- it never reads a
4050 CONECT record or guesses a bond -- so a ligand contributes no rings and
4051 structure_pi_stacking() says so rather than quietly finding none.
4052  
4053 HID/HIE/HIP and HSD/HSE/HSP are histidine under the names AMBER and CHARMM
4054 give its three protonation states; a structure that has been through either
4055 comes back with those spellings and the same five ring atoms.*/
4056 #define RING_MAX 6 //the most atoms any ring in the table below has
4057  
4058 typedef struct {
4059 const char *const *atom;//ring atom names, normal taken from the first two
4060 unsigned short n;//how many
4061 char label;//'6' six-membered, '5' five-membered
4062 } ring_def;
4063  
4064 static const char *const ring_phe[6] = { "CG", "CD1", "CD2", "CE1", "CE2", "CZ" };
4065 static const char *const ring_his[5] = { "CG", "ND1", "CE1", "NE2", "CD2" };
4066 static const char *const ring_trp5[5] = { "CG", "CD1", "NE1", "CE2", "CD2" };
4067 static const char *const ring_trp6[6] = { "CD2", "CE2", "CZ2", "CH2", "CZ3", "CE3" };
4068 static const char *const ring_pur6[6] = { "N1", "C2", "N3", "C4", "C5", "C6" };
4069 static const char *const ring_pur5[5] = { "C4", "C5", "N7", "C8", "N9" };
4070 static const char *const ring_pyr6[6] = { "N1", "C2", "N3", "C4", "C5", "C6" };
4071  
4072 static const ring_def rings_phe[1] = { { ring_phe, 6, '6' } };
4073 static const ring_def rings_his[1] = { { ring_his, 5, '5' } };
4074 static const ring_def rings_trp[2] = { { ring_trp6, 6, '6' }, { ring_trp5, 5, '5' } };
4075 static const ring_def rings_pur[2] = { { ring_pur6, 6, '6' }, { ring_pur5, 5, '5' } };
4076 static const ring_def rings_pyr[1] = { { ring_pyr6, 6, '6' } };
4077  
4078 //how many rings a residue name has, and where they are; 0 for everything else
4079 15327 static unsigned short ring_defs(U32 key, const ring_def *CSP_RESTRICT *CSP_RESTRICT out)
4080 {
4081 15327 switch (key) {
4082 589 case K3('P','H','E'): case K3('T','Y','R'):
4083 589 *out = rings_phe; return 1;
4084 683 case K3('H','I','S'):
4085 case K3('H','I','D'): case K3('H','I','E'): case K3('H','I','P'):
4086 case K3('H','S','D'): case K3('H','S','E'): case K3('H','S','P'):
4087 683 *out = rings_his; return 1;
4088 382 case K3('T','R','P'):
4089 382 *out = rings_trp; return 2;
4090 //purines: adenine and guanine, DNA and RNA
4091 842 case K3(' ',' ','A'): case K3(' ',' ','G'):
4092 case K3(' ','D','A'): case K3(' ','D','G'):
4093 842 *out = rings_pur; return 2;
4094 //pyrimidines: cytosine, thymine and uracil, DNA and RNA
4095 750 case K3(' ',' ','C'): case K3(' ',' ','T'): case K3(' ',' ','U'):
4096 case K3(' ','D','C'): case K3(' ','D','T'): case K3(' ','D','U'):
4097 750 *out = rings_pyr; return 1;
4098 12081 default: *out = NULL; return 0;
4099 }
4100 }
4101  
4102 //hash field accessors, for walking an $info that Perl built
4103 3157871 static SV *hvf_sv(pTHX_ HV *CSP_RESTRICT h, const char *CSP_RESTRICT k, STRLEN klen){
4104 3157871 SV **p = hv_fetch(h, k, (I32)klen, 0);
4105 3157871 ▶ return (p && *p && SvOK(*p)) ? *p : NULL;
Branch: 3 branches
BranchTrueFalseTotal
return (p && *p && SvOK(*p)) ? *p : NULL; 3001617 156254 3157871
return (p && *p && SvOK(*p)) ? *p : NULL; 3001617 0 3001617
return (p && *p && SvOK(*p)) ? *p : NULL; 3001504 113 3001617
4106 }
4107  
4108 63464 static AV *hvf_av(pTHX_ HV *CSP_RESTRICT h, const char *CSP_RESTRICT k, STRLEN klen){
4109 63464 SV *s = hvf_sv(aTHX_ h, k, klen);
4110 63464 ▶ return (s && SvROK(s) && SvTYPE(SvRV(s)) == SVt_PVAV) ? (AV *)SvRV(s) : NULL;
Branch: 3 branches
BranchTrueFalseTotal
return (s && SvROK(s) && SvTYPE(SvRV(s)) == SVt_PVAV) ? (AV *)SvRV(s) : NULL; 49956 13508 63464
return (s && SvROK(s) && SvTYPE(SvRV(s)) == SVt_PVAV) ? (AV *)SvRV(s) : NULL; 49956 0 49956
return (s && SvROK(s) && SvTYPE(SvRV(s)) == SVt_PVAV) ? (AV *)SvRV(s) : NULL; 49956 0 49956
4111 }
4112  
4113 149650 static HV *hvf_hv(pTHX_ HV *CSP_RESTRICT h, const char *CSP_RESTRICT k, STRLEN klen){
4114 149650 SV *s = hvf_sv(aTHX_ h, k, klen);
4115 149650 ▶ return (s && SvROK(s) && SvTYPE(SvRV(s)) == SVt_PVHV) ? (HV *)SvRV(s) : NULL;
Branch: 3 branches
BranchTrueFalseTotal
return (s && SvROK(s) && SvTYPE(SvRV(s)) == SVt_PVHV) ? (HV *)SvRV(s) : NULL; 149628 22 149650
return (s && SvROK(s) && SvTYPE(SvRV(s)) == SVt_PVHV) ? (HV *)SvRV(s) : NULL; 149628 0 149628
return (s && SvROK(s) && SvTYPE(SvRV(s)) == SVt_PVHV) ? (HV *)SvRV(s) : NULL; 149628 0 149628
4116 }
4117  
4118 //the hash an array element refers to, or NULL if it is not a hash reference
4119 150623 static HV *hvf_ent_hv(pTHX_ HV *CSP_RESTRICT h, SV *CSP_RESTRICT key){
4120 150623 HE *e = hv_fetch_ent(h, key, 0, 0);
4121 150623 ▶ SV *v = e ? HeVAL(e) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV *v = e ? HeVAL(e) : NULL; 150619 4 150623
4122 150623 ▶ return (v && SvROK(v) && SvTYPE(SvRV(v)) == SVt_PVHV) ? (HV *)SvRV(v) : NULL;
Branch: 3 branches
BranchTrueFalseTotal
return (v && SvROK(v) && SvTYPE(SvRV(v)) == SVt_PVHV) ? (HV *)SvRV(v) : NULL; 150619 4 150623
return (v && SvROK(v) && SvTYPE(SvRV(v)) == SVt_PVHV) ? (HV *)SvRV(v) : NULL; 150619 0 150619
return (v && SvROK(v) && SvTYPE(SvRV(v)) == SVt_PVHV) ? (HV *)SvRV(v) : NULL; 150619 0 150619
4123 }
4124  
4125 /*Assembly -- the parse's runs, gathered into residues, chains and models.
4126  
4127 Both readers hand back a structure as runs: one entry per run of consecutive
4128 records of one residue, carrying that residue's identity, the span of its atoms,
4129 and the sums of its coordinates and B-factors -- and, when the caller wanted
4130 atoms, the atoms already filed into one atoms hash per residue (filer_atom()).
4131 What is left is to gather the runs into residues and the residues into chains
4132 and models, to type each residue, and to roll each chain up into its sequence,
4133 its counts, its type and its gaps. That was the Perl's, as _assemble(),
4134 _demote_free_residues() and _finish_chains(), and it was most of what a read
4135 with features => 0 spent after the parse; see notes.txt for what moving it
4136 here saved. The rules are the ones the Perl applied, in the same order, and
4137 each residue hash is built once with its final values rather than built and
4138 then rewritten as each rule had its say.
4139  
4140 The rules:
4141  
4142 * runs that share a model, a chain and a key are one residue -- an altloc
4143 group written apart, a ligand interleaved with the polymer -- and their
4144 counts and sums add up. The key is the residue number as Perl prints it
4145 and the insertion code, with the residue name in brackets after them for a
4146 run the parse marked apart, '1(HOH)': see run_key().
4147 * a residue's type and letter are res_lookup()'s. One not in the table is
4148 an ion if it is named as one (ion_res[]) or is a single atom of the element
4149 its name spells, and a ligand otherwise.
4150 * ADE, CYT, GUA, THY and URI mean two things depending on how old the file
4151 is: in a pre-v3 entry they are the nucleotides of a nucleic acid chain, and
4152 in a modern one free bases sitting in an active site. The sugar tells them
4153 apart -- a nucleotide has a P, a C1' or an O5' -- and without it the
4154 guanine bound to 1czc reads as a G on the end of a 396-residue protein.
4155 * a residue of a polymer type that comes after the polymer is a free one: a
4156 ligand, with no letter, not modified, and marked free. The polymer ends at
4157 its last ATOM residue of a polymer type, and a HETATM residue after that is
4158 still part of it if it is bonded to the residue before it -- a modified
4159 residue capping the terminus -- by gemmi's have_peptide_bond() or
4160 have_nucleotide_bond() (see CSP_LINK_CN). 1hsl has a histidine bound after
4161 each of its 238-residue chains, and counting it made a 239-residue protein
4162 with an n_missing of -1. The residue numbers cannot draw the line, which
4163 is what was tried first: heterogens are numbered after the polymer by
4164 convention and no more than that, so 3lms chain A runs 4, 567, 1501, 1889
4165 and its free GLY 501 falls inside the polymer's numbering. Where a residue
4166 sits in the file and what it is bonded to are the same in both formats, so
4167 neither needs a TER record. A chain written entirely as HETATM -- a
4168 synthetic peptide ligand -- has no ATOM polymer to end, and reads as the
4169 peptide it is.
4170 * the gaps of a chain are its unmodelled stretches, and missing_residues the
4171 same fact one number at a time. A jump in the numbering means missing
4172 residues only if the chain has that many to be missing: from its first
4173 polymer residue to its last it covers so many numbers, and the ones it does
4174 not use are the budget. A jump wider than the whole budget is a change of
4175 numbering scheme and not a gap -- an antibody numbered by the Kabat scheme
4176 runs 27, 1027, 2027, 28, and read literally that made 1a4k a 214-residue
4177 light chain missing five thousand residues. Insertion codes share a
4178 number, so distinct numbers are counted and not residues: otherwise
4179 thrombin's 149A..149E spend budget that its real gap at 217..219 then has
4180 none of. The budget is read off the coordinates alone, so a chain answers
4181 the same from a PDB file and an mmCIF one, with or without the header.*/
4182 #define RT_LIGAND 4 //assembly's own, after res_lookup()'s four: not in the table, and not an ion
4183 #define RT_ION 5 //assembly's own: named as an ion, or one atom of the element its name spells
4184  
4185 //the type a residue hash names, by RT_*; an RT_OTHER never survives assembly
4186 static const char *const rt_name[6] = {
4187 "other", "amino_acid", "nucleotide", "water", "ligand", "ion"
4188 };
4189  
4190 /*the residues that need no explanation; every other one res_lookup() calls an
4191 amino acid or a nucleotide is flagged modified. Compared as the file spelled
4192 them and not as res_key() folds them, so 'ala' is not standard, as it was not
4193 to the Perl hash this replaces.*/
4194 static const char *const std_res[] = {
4195 "ALA", "ARG", "ASN", "ASP", "CYS", "GLN", "GLU", "GLY", "HIS", "ILE",
4196 "LEU", "LYS", "MET", "PHE", "PRO", "SER", "THR", "TRP", "TYR", "VAL",
4197 "DA", "DC", "DG", "DT", "DU", "A", "C", "G", "U"
4198 };
4199  
4200 /*single-atom residues that are ions rather than ligands. The atom-count rule
4201 catches most of them; these are the ones whose name and element disagree.*/
4202 static const char *const ion_res[] = {
4203 "ZN", "MG", "CA", "MN", "FE", "FE2", "CU", "CU1", "NA", "K", "CL", "BR",
4204 "IOD", "CD", "CO", "NI", "HG", "PT", "AU", "AG", "CS", "RB", "SR", "BA",
4205 "LI", "AL", "GA", "IN", "PB", "SE4", "SO4", "PO4", "NO3", "CO3", "NH4", "F"
4206 };
4207  
4208 //nucleotides in an old file and free bases in a new one; see the rules above
4209 static const char *const free_base_res[] = { "ADE", "CYT", "GUA", "THY", "URI" };
4210  
4211 //whether s is one of the names in list, byte for byte
4212 26144 static bool name_listed(const char *CSP_RESTRICT s, STRLEN n,
4213 const char *const *CSP_RESTRICT list, size_t count){
4214 420168 ▶ for (size_t i = 0; i < count; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (size_t i = 0; i < count; i++) 411188 8980 420168
4215 411188 ▶ if (strlen(list[i]) == n && memcmp(list[i], s, n) == 0) return TRUE;
Branch: 2 branches
BranchTrueFalseTotal
if (strlen(list[i]) == n && memcmp(list[i], s, n) == 0) return TRUE; 273159 138029 411188
if (strlen(list[i]) == n && memcmp(list[i], s, n) == 0) return TRUE; 17164 255995 273159
4216 8980 return FALSE;
4217 }
4218 #define NAME_LISTED(s, n, list) name_listed((s), (n), (list), sizeof(list) / sizeof((list)[0]))
4219  
4220 /*The bonds that continue a polymer past its last ATOM residue: gemmi 0.7.0
4221 polyheur.hpp, have_peptide_bond() and have_nucleotide_bond() -- a C to the next
4222 N within 1.5 times 1.341 A, an O3' to the next P within 1.5 times 1.6 A. Worked
4223 out as NV quotients of integers, so that a long-double or quadmath build tests
4224 against its own width's 1.341 rather than a double's, as the Perl %LINK this
4225 replaces did. _peptide_linked() in the Perl keeps the first for itself. The
4226 square is a multiplication where the Perl wrote ** 2, which can differ from
4227 pow() in the last bit only, and only for a separation exactly on the bound.*/
4228 #define CSP_LINK_CN ((NV)1341 / (NV)1000 * (NV)1.5)
4229 #define CSP_LINK_OP ((NV)16 / (NV)10 * (NV)1.5)
4230  
4231 /*The sixteen keys a residue hash can have, hashed once per call, for the reason
4232 atom_keys gives.*/
4233 #define NRKEY 16
4234 static const char *const rkey_name[NRKEY] = {
4235 "chain", "resname", "number", "icode", "key", "one", "type", "hetero",
4236 "standard", "modified", "n_atoms", "atoms", "atom_order", "center", "b_mean", "free"
4237 };
4238 enum {
4239 RK_CHAIN, RK_RESNAME, RK_NUMBER, RK_ICODE, RK_KEY, RK_ONE, RK_TYPE, RK_HETERO,
4240 RK_STANDARD, RK_MODIFIED, RK_NATOMS, RK_ATOMS, RK_ORDER, RK_CENTER, RK_BMEAN, RK_FREE
4241 };
4242 typedef struct {
4243 U32 hash[NRKEY];
4244 I32 len[NRKEY];
4245 } res_keys;
4246  
4247 /*a string the parse handed back, as its bytes; "" for an undefined one, which
4248 the parse never hands back and which SvPV would warn about under the caller's
4249 FATAL warnings*/
4250 85211 static const char *asm_pv(pTHX_ SV *v, STRLEN *CSP_RESTRICT n){
4251 85211 ▶ if (!SvOK(v)) { *n = 0; return ""; }
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(v)) { *n = 0; return ""; } 0 85211 85211
4252 85211 return SvPV_const(v, *n);
4253 }
4254  
4255 //one residue, while its runs are gathered
4256 typedef struct {
4257 SV *key;//the key it is filed under: a mortal of its own
4258 //the rest borrowed from the parse's arrays, which outlive the assembly
4259 SV *rn, *num, *ic, *cid, *het, *atoms, *order;
4260 size_t chain;//index of its chain
4261 UV i0, i1;//its first run's atoms, which is where asm_xyz() looks
4262 UV n_atoms, nc, nb;//records, and the ones with coordinates and with a B-factor
4263 NV sx, sy, sz, sb;//the sums the centre and b_mean are taken from
4264 unsigned char type;//RT_*
4265 char one;//its letter; '\0' when it has none
4266 bool het_b, standard, modified, is_free;
4267 } asm_res;
4268  
4269 //one chain, while its residues are gathered
4270 typedef struct {
4271 SV *model, *id;//borrowed, as asm_res's are
4272 UV n_atoms, n_hetatm;
4273 } asm_chain;
4274  
4275 //the working arrays, in one place so one destructor frees them on a croak too
4276 typedef struct {
4277 asm_res *res;
4278 asm_chain *ch;
4279 size_t *list;//residue indices, chain after chain, each chain's in file order
4280 size_t *off;//per chain: where its residues start in list; one more for the end
4281 size_t *poly;//one chain's polymer residues
4282 IV *nums;//their numbers
4283 IV *miss;//the numbers its gaps pass over
4284 size_t miss_cap;
4285 } asm_work;
4286  
4287 1168 static void asm_work_free(pTHX_ void *p){
4288 1168 asm_work *w = (asm_work *)p;
4289 1168 Safefree(w->res); Safefree(w->ch); Safefree(w->list); Safefree(w->off);
4290 1168 Safefree(w->poly); Safefree(w->nums); Safefree(w->miss);
4291 1168 }
4292  
4293 //an array the parse handed back, or NULL; croaks for one it always hands back
4294 26683 static AV *asm_col(pTHX_ HV *CSP_RESTRICT p, const char *CSP_RESTRICT k, bool need){
4295 26683 AV *a = hvf_av(aTHX_ p, k, strlen(k));
4296 26683 ▶ if (!a && need) croak("Chem::Structure::Parser: the parse has no '%s' array", k);
Branch: 2 branches
BranchTrueFalseTotal
if (!a && need) croak("Chem::Structure::Parser: the parse has no '%s' array", k); 2 26681 26683
if (!a && need) croak("Chem::Structure::Parser: the parse has no '%s' array", k); 2 0 2
4297 26681 return a;
4298 }
4299  
4300 //an element of one of those arrays, undef where it has none
4301 431094 static SV *asm_at(pTHX_ AV *a, SSize_t i){
4302 431094 ▶ SV **e = a ? av_fetch(a, i, 0) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
SV **e = a ? av_fetch(a, i, 0) : NULL; 431094 0 431094
4303 431094 ▶ return (e && *e) ? *e : &PL_sv_undef;
Branch: 2 branches
BranchTrueFalseTotal
return (e && *e) ? *e : &PL_sv_undef; 431094 0 431094
return (e && *e) ? *e : &PL_sv_undef; 431094 0 431094
4304 }
4305  
4306 //the parse's atoms, in whichever of its shapes it built them
4307 typedef struct {
4308 AV *atoms;//the atom hashes, or NULL for the columns below
4309 AV *name, *x, *y, *z;
4310 } asm_src;
4311  
4312 //atom i's field: from its hash, or from the column it has when there is none
4313 841 static SV *asm_field(pTHX_ const asm_src *CSP_RESTRICT src, SSize_t i,
4314 const char *CSP_RESTRICT k, STRLEN kn, AV *col){
4315 841 ▶ if (src->atoms) {
Branch: 1 branch
BranchTrueFalseTotal
if (src->atoms) { 808 33 841
4316 808 SV *a = asm_at(aTHX_ src->atoms, i);
4317 SV **v;
4318 808 ▶ if (!SvROK(a) || SvTYPE(SvRV(a)) != SVt_PVHV) return &PL_sv_undef;
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(a) || SvTYPE(SvRV(a)) != SVt_PVHV) return &PL_sv_undef; 808 0 808
if (!SvROK(a) || SvTYPE(SvRV(a)) != SVt_PVHV) return &PL_sv_undef; 0 808 808
4319 808 v = hv_fetch((HV *)SvRV(a), k, (I32)kn, 0);
4320 808 ▶ return (v && *v) ? *v : &PL_sv_undef;
Branch: 2 branches
BranchTrueFalseTotal
return (v && *v) ? *v : &PL_sv_undef; 808 0 808
return (v && *v) ? *v : &PL_sv_undef; 808 0 808
4321 }
4322 33 return asm_at(aTHX_ col, i);
4323 }
4324  
4325 /*the position of the first atom of r's first run named want; FALSE where it
4326 has none, or has it with no coordinates*/
4327 20 static bool asm_xyz(pTHX_ const asm_src *CSP_RESTRICT src, const asm_res *CSP_RESTRICT r,
4328 const char *CSP_RESTRICT want, NV *CSP_RESTRICT out){
4329 20 const STRLEN wn = strlen(want);
4330 40 ▶ for (UV i = r->i0; i <= r->i1; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV i = r->i0; i <= r->i1; i++) { 40 0 40
4331 40 SV *nm = asm_field(aTHX_ src, (SSize_t)i, "name", 4, src->name);
4332 SV *c[3];
4333 STRLEN n;
4334 const char *s;
4335 60 ▶ if (!SvOK(nm)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(nm)) continue; 0 40 40
4336 40 s = SvPV_const(nm, n);
4337 40 ▶ if (n != wn || memcmp(s, want, n) != 0) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (n != wn || memcmp(s, want, n) != 0) continue; 30 10 40
if (n != wn || memcmp(s, want, n) != 0) continue; 10 20 30
4338 20 c[0] = asm_field(aTHX_ src, (SSize_t)i, "x", 1, src->x);
4339 20 c[1] = asm_field(aTHX_ src, (SSize_t)i, "y", 1, src->y);
4340 20 c[2] = asm_field(aTHX_ src, (SSize_t)i, "z", 1, src->z);
4341 40 ▶ if (!SvOK(c[0]) || !SvOK(c[1]) || !SvOK(c[2])) return FALSE;
Branch: 3 branches
BranchTrueFalseTotal
if (!SvOK(c[0]) || !SvOK(c[1]) || !SvOK(c[2])) return FALSE; 20 0 20
if (!SvOK(c[0]) || !SvOK(c[1]) || !SvOK(c[2])) return FALSE; 20 0 20
if (!SvOK(c[0]) || !SvOK(c[1]) || !SvOK(c[2])) return FALSE; 0 20 20
4342 80 ▶ for (unsigned short k = 0; k < 3; k++) out[k] = SvNV(c[k]);
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < 3; k++) out[k] = SvNV(c[k]); 60 20 80
4343 20 return TRUE;
4344 }
4345 0 return FALSE;
4346 }
4347  
4348 //whether b continues the polymer a is the end of; see CSP_LINK_CN
4349 344 static bool asm_bonded(pTHX_ const asm_src *CSP_RESTRICT src,
4350 const asm_res *CSP_RESTRICT a, const asm_res *CSP_RESTRICT b){
4351 344 NV p[3], q[3], d2 = 0.0, lim;
4352 344 ▶ if (a->type != b->type) return FALSE;
Branch: 1 branch
BranchTrueFalseTotal
if (a->type != b->type) return FALSE; 334 10 344
4353 10 ▶ if (b->type == RT_AA) {
Branch: 1 branch
BranchTrueFalseTotal
if (b->type == RT_AA) { 8 2 10
4354 8 ▶ if (!asm_xyz(aTHX_ src, a, "C", p) || !asm_xyz(aTHX_ src, b, "N", q)) return FALSE;
Branch: 2 branches
BranchTrueFalseTotal
if (!asm_xyz(aTHX_ src, a, "C", p) || !asm_xyz(aTHX_ src, b, "N", q)) return FALSE; 8 0 8
if (!asm_xyz(aTHX_ src, a, "C", p) || !asm_xyz(aTHX_ src, b, "N", q)) return FALSE; 0 8 8
4355 8 lim = CSP_LINK_CN;
4356 2 ▶ } else if (b->type == RT_NUC) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (b->type == RT_NUC) { 2 0 2
4357 2 ▶ if (!asm_xyz(aTHX_ src, a, "O3'", p) || !asm_xyz(aTHX_ src, b, "P", q)) return FALSE;
Branch: 2 branches
BranchTrueFalseTotal
if (!asm_xyz(aTHX_ src, a, "O3'", p) || !asm_xyz(aTHX_ src, b, "P", q)) return FALSE; 2 0 2
if (!asm_xyz(aTHX_ src, a, "O3'", p) || !asm_xyz(aTHX_ src, b, "P", q)) return FALSE; 0 2 2
4358 2 lim = CSP_LINK_OP;
4359 } else {
4360 0 return FALSE;
4361 }
4362 40 ▶ for (unsigned short k = 0; k < 3; k++) d2 += (p[k] - q[k]) * (p[k] - q[k]);
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < 3; k++) d2 += (p[k] - q[k]) * (p[k] - q[k]); 30 10 40
4363 10 return d2 < lim * lim;
4364 }
4365  
4366 /*whether a name is one that says a nucleotide has its sugar or phosphate: P,
4367 C1' or O5', the prime written either way*/
4368 40 static bool asm_backbone_name(const char *CSP_RESTRICT s, STRLEN n){
4369 40 ▶ if (n == 1) return s[0] == 'P';
Branch: 1 branch
BranchTrueFalseTotal
if (n == 1) return s[0] == 'P'; 7 33 40
4370 33 ▶ if (n != 3 || (s[2] != '\'' && s[2] != '*')) return FALSE;
Branch: 3 branches
BranchTrueFalseTotal
if (n != 3 || (s[2] != '\'' && s[2] != '*')) return FALSE; 0 33 33
if (n != 3 || (s[2] != '\'' && s[2] != '*')) return FALSE; 0 0 0
if (n != 3 || (s[2] != '\'' && s[2] != '*')) return FALSE; 0 0 0
4371 0 ▶ return (s[0] == 'C' && s[1] == '1') || (s[0] == 'O' && s[1] == '5');
Branch: 4 branches
BranchTrueFalseTotal
return (s[0] == 'C' && s[1] == '1') || (s[0] == 'O' && s[1] == '5'); 0 0 0
return (s[0] == 'C' && s[1] == '1') || (s[0] == 'O' && s[1] == '5'); 0 0 0
return (s[0] == 'C' && s[1] == '1') || (s[0] == 'O' && s[1] == '5'); 0 0 0
return (s[0] == 'C' && s[1] == '1') || (s[0] == 'O' && s[1] == '5'); 0 0 0
4372 }
4373  
4374 //whether a and b are the same letters but for case, as Perl's uc() eq uc() asks
4375 24 static bool asm_eq_nocase(const char *CSP_RESTRICT a, STRLEN an,
4376 const char *CSP_RESTRICT b, STRLEN bn){
4377 24 ▶ if (an != bn) return FALSE;
Branch: 1 branch
BranchTrueFalseTotal
if (an != bn) return FALSE; 24 0 24
4378 0 ▶ for (STRLEN i = 0; i < an; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (STRLEN i = 0; i < an; i++) 0 0 0
4379 0 ▶ if (toUPPER((unsigned char)a[i]) != toUPPER((unsigned char)b[i])) return FALSE;
Branch: 3 branches
BranchTrueFalseTotal
if (toUPPER((unsigned char)a[i]) != toUPPER((unsigned char)b[i])) return FALSE; 0 0 0
if (toUPPER((unsigned char)a[i]) != toUPPER((unsigned char)b[i])) return FALSE; 0 0 0
if (toUPPER((unsigned char)a[i]) != toUPPER((unsigned char)b[i])) return FALSE; 0 0 0
4380 0 return TRUE;
4381 }
4382  
4383 //a sum the residue carries forward: the first one taken as it is, as Perl's
4384 //+= on an undefined value takes it
4385 90718 static void asm_add(pTHX_ NV *CSP_RESTRICT sum, bool first, SV *v){
4386 90718 ▶ *sum = first ? SvNV(v) : *sum + SvNV(v);
Branch: 1 branch
BranchTrueFalseTotal
*sum = first ? SvNV(v) : *sum + SvNV(v); 90686 32 90718
4387 90718 }
4388  
4389 /*one chain's roll-up: its residue hashes, then the chain's own keys. ci is the
4390 chain's index, whose residues are list[off[ci]] up to off[ci + 1]; w also holds
4391 the scratch the gaps are worked out in; c is the chain hash to fill.*/
4392 1718 static void asm_chain_finish(pTHX_ asm_work *CSP_RESTRICT w, size_t ci, const res_keys *CSP_RESTRICT rk,
4393 HV *CSP_RESTRICT c){
4394 1718 HV *residues = newHV(), *types = newHV();
4395 1718 AV *order = newAV(), *gaps = newAV(), *missing = newAV();
4396 1718 const size_t *CSP_RESTRICT list = w->list + w->off[ci];
4397 1718 const size_t nl = w->off[ci + 1] - w->off[ci];
4398 1718 size_t npoly = 0, nnum = 0, ndist = 0, nmiss = 0, k;
4399 1718 UV count[6] = { 0, 0, 0, 0, 0, 0 };//by RT_*
4400 1718 UV deoxy = 0;
4401 1718 IV budget = 0;
4402 1718 SV *seq = newSVpvs("");
4403 const char *ctype;
4404  
4405 1718 ▶ if (nl) av_extend(order, (SSize_t)nl - 1);
Branch: 1 branch
BranchTrueFalseTotal
if (nl) av_extend(order, (SSize_t)nl - 1); 1718 0 1718
4406 24403 ▶ for (k = 0; k < nl; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < nl; k++) { 22685 1718 24403
4407 22685 asm_res *CSP_RESTRICT r = w->res + list[k];
4408 22685 HV *h = newHV();
4409 #define RK_STORE(i, v) (void)hv_store(h, rkey_name[i], rk->len[i], (v), rk->hash[i])
4410 22685 hv_ksplit(h, 16);
4411 22685 RK_STORE(RK_CHAIN, newSVsv(r->cid));
4412 22685 RK_STORE(RK_RESNAME, newSVsv(r->rn));
4413 22685 RK_STORE(RK_NUMBER, newSVsv(r->num));
4414 22685 RK_STORE(RK_ICODE, newSVsv(r->ic));
4415 22685 RK_STORE(RK_KEY, newSVsv(r->key));
4416 22685 ▶ RK_STORE(RK_ONE, r->one ? csp_str(aTHX_ &r->one, 1) : csp_str(aTHX_ "", 0));
Branch: 1 branch
BranchTrueFalseTotal
RK_STORE(RK_ONE, r->one ? csp_str(aTHX_ &r->one, 1) : csp_str(aTHX_ "", 0)); 17132 5553 22685
4417 22685 RK_STORE(RK_TYPE, csp_str(aTHX_ rt_name[r->type], strlen(rt_name[r->type])));
4418 22685 RK_STORE(RK_HETERO, newSVsv(r->het));
4419 22685 RK_STORE(RK_STANDARD, newSViv(r->standard ? 1 : 0));
4420 22685 RK_STORE(RK_MODIFIED, newSViv(r->modified ? 1 : 0));
4421 22685 RK_STORE(RK_NATOMS, newSVuv(r->n_atoms));
4422 22685 ▶ RK_STORE(RK_ATOMS, r->atoms ? newSVsv(r->atoms) : newRV_noinc((SV *)newHV()));
Branch: 1 branch
BranchTrueFalseTotal
RK_STORE(RK_ATOMS, r->atoms ? newSVsv(r->atoms) : newRV_noinc((SV *)newHV())); 22240 445 22685
4423 22685 ▶ RK_STORE(RK_ORDER, r->order ? newSVsv(r->order) : newRV_noinc((SV *)newAV()));
Branch: 1 branch
BranchTrueFalseTotal
RK_STORE(RK_ORDER, r->order ? newSVsv(r->order) : newRV_noinc((SV *)newAV())); 22240 445 22685
4424 22685 ▶ if (r->nc) {
Branch: 1 branch
BranchTrueFalseTotal
if (r->nc) { 22680 5 22685
4425 22680 AV *ctr = newAV();
4426 22680 av_push(ctr, newSVnv(r->sx / (NV)r->nc));
4427 22680 av_push(ctr, newSVnv(r->sy / (NV)r->nc));
4428 22680 av_push(ctr, newSVnv(r->sz / (NV)r->nc));
4429 22680 RK_STORE(RK_CENTER, newRV_noinc((SV *)ctr));
4430 }
4431 22685 ▶ if (r->nb) RK_STORE(RK_BMEAN, newSVnv(r->sb / (NV)r->nb));
Branch: 1 branch
BranchTrueFalseTotal
if (r->nb) RK_STORE(RK_BMEAN, newSVnv(r->sb / (NV)r->nb)); 22646 39 22685
4432 22685 ▶ if (r->is_free) RK_STORE(RK_FREE, newSViv(1));
Branch: 1 branch
BranchTrueFalseTotal
if (r->is_free) RK_STORE(RK_FREE, newSViv(1)); 6 22679 22685
4433 #undef RK_STORE
4434 22685 (void)hv_store_ent(residues, r->key, newRV_noinc((SV *)h), 0);
4435 22685 av_push(order, newSVsv(r->key));
4436 22685 count[r->type]++;
4437 22685 ▶ if (r->type != RT_AA && r->type != RT_NUC) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (r->type != RT_AA && r->type != RT_NUC) continue; 7989 14696 22685
if (r->type != RT_AA && r->type != RT_NUC) continue; 5553 2436 7989
4438 17132 ▶ sv_catpvn(seq, r->one ? &r->one : "X", 1);
Branch: 1 branch
BranchTrueFalseTotal
sv_catpvn(seq, r->one ? &r->one : "X", 1); 17132 0 17132
4439 17132 w->poly[npoly++] = list[k];
4440 17132 ▶ if (SvOK(r->num)) w->nums[nnum++] = SvIV(r->num);
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(r->num)) w->nums[nnum++] = SvIV(r->num); 17131 1 17132
4441 {//a deoxynucleotide's name, for the chain's type: D and one of ACGTUI
4442 STRLEN n;
4443 17132 const char *s = asm_pv(aTHX_ r->rn, &n);
4444 17132 ▶ if (n == 2 && s[0] == 'D' && s[1] && strchr("ACGTUI", s[1])) deoxy++;
Branch: 4 branches
BranchTrueFalseTotal
if (n == 2 && s[0] == 'D' && s[1] && strchr("ACGTUI", s[1])) deoxy++; 1500 15632 17132
if (n == 2 && s[0] == 'D' && s[1] && strchr("ACGTUI", s[1])) deoxy++; 1500 0 1500
if (n == 2 && s[0] == 'D' && s[1] && strchr("ACGTUI", s[1])) deoxy++; 1500 0 1500
if (n == 2 && s[0] == 'D' && s[1] && strchr("ACGTUI", s[1])) deoxy++; 1500 0 1500
4445 }
4446 }
4447  
4448 /*the budget: the numbers the polymer spans less the distinct ones it uses.
4449 nums is in file order, which is what the span is taken in -- a polymer
4450 numbered backwards has a negative span and no gaps -- and is sorted only
4451 after its two ends are read.*/
4452 1718 ▶ if (nnum) {
Branch: 1 branch
BranchTrueFalseTotal
if (nnum) { 1603 115 1718
4453 1603 const IV first = w->nums[0], last = w->nums[nnum - 1];
4454 1603 qsort(w->nums, nnum, sizeof(IV), cv_iv_cmp);
4455 18734 ▶ for (k = 0; k < nnum; k++)
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < nnum; k++) 17131 1603 18734
4456 17131 ▶ if (k == 0 || w->nums[k] != w->nums[ndist - 1]) w->nums[ndist++] = w->nums[k];
Branch: 2 branches
BranchTrueFalseTotal
if (k == 0 || w->nums[k] != w->nums[ndist - 1]) w->nums[ndist++] = w->nums[k]; 15528 1603 17131
if (k == 0 || w->nums[k] != w->nums[ndist - 1]) w->nums[ndist++] = w->nums[k]; 15272 256 15528
4457 1603 budget = last - first + 1 - (IV)ndist;
4458 }
4459 17246 ▶ for (k = 1; k < npoly; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 1; k < npoly; k++) { 15528 1718 17246
4460 15528 const asm_res *CSP_RESTRICT a = w->res + w->poly[k - 1];
4461 15528 const asm_res *CSP_RESTRICT b = w->res + w->poly[k];
4462 IV an, bn, n, x;
4463 HV *g;
4464 30274 ▶ if (!SvOK(a->num) || !SvOK(b->num)) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!SvOK(a->num) || !SvOK(b->num)) continue; 15528 0 15528
if (!SvOK(a->num) || !SvOK(b->num)) continue; 0 15528 15528
4465 15528 an = SvIV(a->num);
4466 15528 bn = SvIV(b->num);
4467 15528 n = bn - an - 1;
4468 15528 ▶ if (n < 1 || n > budget) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (n < 1 || n > budget) continue; 784 14744 15528
if (n < 1 || n > budget) continue; 2 782 784
4469 782 g = newHV();
4470 782 (void)hv_stores(g, "after", newSVsv(a->key));
4471 782 (void)hv_stores(g, "before", newSVsv(b->key));
4472 782 (void)hv_stores(g, "missing", newSViv(n));
4473 782 av_push(gaps, newRV_noinc((SV *)g));
4474 /*the numbers the jump passes over, less any the chain has after all: a
4475 polymer numbered out of order has jumps that overlap and jumps that pass
4476 over a residue further down, and a set is what keeps "is 47 modelled?"
4477 answerable. n is at most the budget, so this is at most the span.*/
4478 20827 ▶ for (x = an + 1; x < bn; x++) {
Branch: 1 branch
BranchTrueFalseTotal
for (x = an + 1; x < bn; x++) { 20045 782 20827
4479 20045 ▶ if (bsearch(&x, w->nums, ndist, sizeof(IV), cv_iv_cmp)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (bsearch(&x, w->nums, ndist, sizeof(IV), cv_iv_cmp)) continue; 2 20043 20045
4480 20043 ▶ if (nmiss == w->miss_cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (nmiss == w->miss_cap) { 558 19485 20043
4481 558 ▶ w->miss_cap = w->miss_cap ? 2 * w->miss_cap : 64;
Branch: 1 branch
BranchTrueFalseTotal
w->miss_cap = w->miss_cap ? 2 * w->miss_cap : 64; 173 385 558
4482 558 ▶ Renew(w->miss, w->miss_cap, IV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(w->miss, w->miss_cap, IV); 0 558 558
4483 }
4484 20043 w->miss[nmiss++] = x;
4485 }
4486 }
4487 1718 ▶ if (nmiss) {
Branch: 1 branch
BranchTrueFalseTotal
if (nmiss) { 385 1333 1718
4488 385 size_t u = 0;
4489 385 qsort(w->miss, nmiss, sizeof(IV), cv_iv_cmp);
4490 20428 ▶ for (k = 0; k < nmiss; k++)
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < nmiss; k++) 20043 385 20428
4491 20043 ▶ if (k == 0 || w->miss[k] != w->miss[u - 1]) w->miss[u++] = w->miss[k];
Branch: 2 branches
BranchTrueFalseTotal
if (k == 0 || w->miss[k] != w->miss[u - 1]) w->miss[u++] = w->miss[k]; 19658 385 20043
if (k == 0 || w->miss[k] != w->miss[u - 1]) w->miss[u++] = w->miss[k]; 19654 4 19658
4492 385 av_extend(missing, (SSize_t)u - 1);
4493 20424 ▶ for (k = 0; k < u; k++) av_push(missing, newSViv(w->miss[k]));
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < u; k++) av_push(missing, newSViv(w->miss[k])); 20039 385 20424
4494 }
4495  
4496 12026 ▶ for (unsigned short t = 0; t < 6; t++)
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short t = 0; t < 6; t++) 10308 1718 12026
4497 10308 ▶ if (count[t]) (void)hv_store(types, rt_name[t], (I32)strlen(rt_name[t]), newSVuv(count[t]), 0);
Branch: 1 branch
BranchTrueFalseTotal
if (count[t]) (void)hv_store(types, rt_name[t], (I32)strlen(rt_name[t]), newSVuv(count[t]), 0); 2716 7592 10308
4498 1718 ▶ if (count[RT_AA] || count[RT_NUC])
Branch: 2 branches
BranchTrueFalseTotal
if (count[RT_AA] || count[RT_NUC]) 605 1113 1718
if (count[RT_AA] || count[RT_NUC]) 491 114 605
4499 1604 ▶ ctype = count[RT_AA] >= count[RT_NUC] ? "protein" : (deoxy * 2 >= count[RT_NUC] ? "dna" : "rna");
Branch: 2 branches
BranchTrueFalseTotal
ctype = count[RT_AA] >= count[RT_NUC] ? "protein" : (deoxy * 2 >= count[RT_NUC] ? "dna" : "rna"); 491 1113 1604
ctype = count[RT_AA] >= count[RT_NUC] ? "protein" : (deoxy * 2 >= count[RT_NUC] ? "dna" : "rna"); 359 132 491
4500 114 ▶ else if (count[RT_WATER] && !count[RT_LIGAND] && !count[RT_ION])
Branch: 3 branches
BranchTrueFalseTotal
else if (count[RT_WATER] && !count[RT_LIGAND] && !count[RT_ION]) 66 48 114
else if (count[RT_WATER] && !count[RT_LIGAND] && !count[RT_ION]) 65 1 66
else if (count[RT_WATER] && !count[RT_LIGAND] && !count[RT_ION]) 64 1 65
4501 64 ctype = "water";
4502 50 ▶ else if (count[RT_LIGAND] || count[RT_ION] || count[RT_WATER])
Branch: 3 branches
BranchTrueFalseTotal
else if (count[RT_LIGAND] || count[RT_ION] || count[RT_WATER]) 13 37 50
else if (count[RT_LIGAND] || count[RT_ION] || count[RT_WATER]) 0 13 13
else if (count[RT_LIGAND] || count[RT_ION] || count[RT_WATER]) 0 0 0
4503 50 ctype = "hetero";
4504 else
4505 0 ctype = "unknown";
4506  
4507 1718 (void)hv_stores(c, "residues", newRV_noinc((SV *)residues));
4508 1718 (void)hv_stores(c, "residue_order", newRV_noinc((SV *)order));
4509 1718 (void)hv_stores(c, "sequence", seq);
4510 1718 (void)hv_stores(c, "n_residues", newSVuv((UV)nl));
4511 1718 (void)hv_stores(c, "n_polymer", newSVuv((UV)npoly));
4512 1718 (void)hv_stores(c, "n_water", newSVuv(count[RT_WATER]));
4513 1718 (void)hv_stores(c, "n_ligand", newSVuv(count[RT_LIGAND] + count[RT_ION]));
4514 1718 (void)hv_stores(c, "residue_types", newRV_noinc((SV *)types));
4515 1718 (void)hv_stores(c, "type", csp_str(aTHX_ ctype, strlen(ctype)));
4516 1718 ▶ (void)hv_stores(c, "first", npoly ? newSVsv(w->res[w->poly[0]].key) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(c, "first", npoly ? newSVsv(w->res[w->poly[0]].key) : newSV(0)); 1604 114 1718
4517 1718 ▶ (void)hv_stores(c, "last", npoly ? newSVsv(w->res[w->poly[npoly - 1]].key) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(c, "last", npoly ? newSVsv(w->res[w->poly[npoly - 1]].key) : newSV(0)); 1604 114 1718
4518 1718 (void)hv_stores(c, "n_gaps", newSVuv((UV)(av_len(gaps) + 1)));
4519 1718 (void)hv_stores(c, "gaps", newRV_noinc((SV *)gaps));
4520 1718 (void)hv_stores(c, "missing_residues", newRV_noinc((SV *)missing));
4521 1718 }
4522  
4523 /*assemble() -- the parse p as the models of chains of residues that
4524 structure_info() returns, keyed by model number: { chains, chain_order } each.
4525 want_atoms is the atoms option; stats is $info->{stats}, whose n_hetatm is
4526 counted here. The parse's arrays are borrowed for as long as this runs, which
4527 is no longer than the call that handed them in.*/
4528 1170 static HV *assemble(pTHX_ HV *CSP_RESTRICT p, bool want_atoms, HV *CSP_RESTRICT stats){
4529 1170 AV *rf = asm_col(aTHX_ p, "res_first", TRUE), *rl = asm_col(aTHX_ p, "res_last", TRUE);
4530 1168 AV *chain = asm_col(aTHX_ p, "chain", TRUE), *resname = asm_col(aTHX_ p, "resname", TRUE);
4531 1168 AV *resseq = asm_col(aTHX_ p, "resseq", TRUE), *icode = asm_col(aTHX_ p, "icode", TRUE);
4532 1168 AV *het = asm_col(aTHX_ p, "het", TRUE), *model = asm_col(aTHX_ p, "model", TRUE);
4533 1168 AV *rsx = asm_col(aTHX_ p, "sx", TRUE), *rsy = asm_col(aTHX_ p, "sy", TRUE);
4534 1168 AV *rsz = asm_col(aTHX_ p, "sz", TRUE), *rnxyz = asm_col(aTHX_ p, "n_xyz", TRUE);
4535 1168 AV *rsb = asm_col(aTHX_ p, "sb", TRUE), *rnb = asm_col(aTHX_ p, "n_b", TRUE);
4536 1168 AV *apart = asm_col(aTHX_ p, "res_apart", FALSE), *elem = asm_col(aTHX_ p, "element", FALSE);
4537 1168 AV *res_atoms = NULL, *res_order = NULL;
4538 1168 HV *chain_elem = hvf_hv(aTHX_ p, "chain_elements", 14);
4539 1168 HV *out = (HV *)sv_2mortal((SV *)newHV());
4540 //"model\0chain" -> chain index, and "chain index\0key" -> residue index
4541 1168 HV *cidx = (HV *)sv_2mortal((SV *)newHV()), *ridx = (HV *)sv_2mortal((SV *)newHV());
4542 1168 SV *ik = sv_2mortal(newSVpvs(""));//the index key being built
4543 1168 const SSize_t nrun = av_len(rf) + 1;
4544 1168 size_t nres = 0, nch = 0, k;
4545 1168 UV n_het = 0;
4546 asm_src src;
4547 asm_work w;
4548 res_keys rk;
4549 bool per_res;
4550  
4551 1168 Zero(&w, 1, asm_work);
4552 1168 src.atoms = asm_col(aTHX_ p, "atoms", FALSE);
4553 1168 ▶ if (!want_atoms || (src.atoms && av_len(src.atoms) < 0)) src.atoms = NULL;
Branch: 3 branches
BranchTrueFalseTotal
if (!want_atoms || (src.atoms && av_len(src.atoms) < 0)) src.atoms = NULL; 1124 44 1168
if (!want_atoms || (src.atoms && av_len(src.atoms) < 0)) src.atoms = NULL; 1124 0 1124
if (!want_atoms || (src.atoms && av_len(src.atoms) < 0)) src.atoms = NULL; 48 1076 1124
4554 1168 ▶ if (src.atoms) {
Branch: 1 branch
BranchTrueFalseTotal
if (src.atoms) { 1076 92 1168
4555 1076 res_atoms = asm_col(aTHX_ p, "res_atoms", TRUE);
4556 1076 res_order = asm_col(aTHX_ p, "res_order", TRUE);
4557 }
4558 1168 src.name = asm_col(aTHX_ p, "name", FALSE);
4559 1168 src.x = asm_col(aTHX_ p, "x", FALSE);
4560 1168 src.y = asm_col(aTHX_ p, "y", FALSE);
4561 1168 src.z = asm_col(aTHX_ p, "z", FALSE);
4562 /*the residue's identity is one entry per run when the parse built atom
4563 hashes or the slim columns, and one per atom in the full columns, where it
4564 is read at the run's first atom*/
4565 1168 ▶ per_res = src.atoms || !want_atoms;
Branch: 2 branches
BranchTrueFalseTotal
per_res = src.atoms || !want_atoms; 92 1076 1168
per_res = src.atoms || !want_atoms; 44 48 92
4566 19856 ▶ for (unsigned short i = 0; i < NRKEY; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < NRKEY; i++) { 18688 1168 19856
4567 18688 rk.len[i] = (I32)strlen(rkey_name[i]);
4568 18688 ▶ PERL_HASH(rk.hash[i], rkey_name[i], rk.len[i]);
Branch: 1 branch
BranchTrueFalseTotal
PERL_HASH(rk.hash[i], rkey_name[i], rk.len[i]); 18688 0 18688
4569 }
4570  
4571 1168 ENTER;
4572 1168 SAVEDESTRUCTOR_X(asm_work_free, &w);
4573 1168 ▶ Newx(w.res, nrun ? (size_t)nrun : 1, asm_res);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.res, nrun ? (size_t)nrun : 1, asm_res); 1120 48 1168
Newx(w.res, nrun ? (size_t)nrun : 1, asm_res); 0 1120 1120
Newx(w.res, nrun ? (size_t)nrun : 1, asm_res); 1120 48 1168
4574 1168 ▶ Newx(w.ch, nrun ? (size_t)nrun : 1, asm_chain);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.ch, nrun ? (size_t)nrun : 1, asm_chain); 1120 48 1168
Newx(w.ch, nrun ? (size_t)nrun : 1, asm_chain); 0 1120 1120
Newx(w.ch, nrun ? (size_t)nrun : 1, asm_chain); 1120 48 1168
4575  
4576 23861 ▶ for (SSize_t r = 0; r < nrun; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (SSize_t r = 0; r < nrun; r++) { 22693 1168 23861
4577 22693 const UV i0 = SvUV(asm_at(aTHX_ rf, r)), i1 = SvUV(asm_at(aTHX_ rl, r));
4578 22693 ▶ const SSize_t ri = per_res ? r : (SSize_t)i0;
Branch: 1 branch
BranchTrueFalseTotal
const SSize_t ri = per_res ? r : (SSize_t)i0; 22693 0 22693
4579 22693 SV *m = asm_at(aTHX_ model, ri), *cid = asm_at(aTHX_ chain, ri);
4580 22693 SV *rn = asm_at(aTHX_ resname, ri), *num = asm_at(aTHX_ resseq, ri);
4581 22693 SV *ic = asm_at(aTHX_ icode, ri), *hs = asm_at(aTHX_ het, ri);
4582 22693 const bool is_het = SvTRUE(hs);
4583 22693 const UV n = i1 - i0 + 1;
4584 STRLEN rnn, ln;
4585 22693 const char *rns = asm_pv(aTHX_ rn, &rnn), *ls;
4586 char head[32];//a UV prints in at most 20 characters
4587 SV **slot;
4588 size_t c, ix;
4589 asm_res *CSP_RESTRICT R;
4590  
4591 //the chain: model and chain id, NUL between
4592 22693 ls = asm_pv(aTHX_ m, &ln);
4593 22693 sv_setpvn(ik, ls, ln);
4594 22693 sv_catpvn(ik, "\0", 1);
4595 22693 ls = asm_pv(aTHX_ cid, &ln);
4596 22693 sv_catpvn(ik, ls, ln);
4597 22693 slot = hv_fetch(cidx, SvPVX(ik), (I32)SvCUR(ik), 1);
4598 22693 ▶ if (!slot) croak("Chem::Structure::Parser: cannot index a chain");
Branch: 1 branch
BranchTrueFalseTotal
if (!slot) croak("Chem::Structure::Parser: cannot index a chain"); 0 22693 22693
4599 22693 ▶ if (SvOK(*slot)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(*slot)) { 20975 1718 22693
4600 20975 c = (size_t)SvUV(*slot);
4601 } else {
4602 1718 c = nch++;
4603 1718 sv_setuv(*slot, (UV)c);
4604 1718 w.ch[c].model = m;
4605 1718 w.ch[c].id = cid;
4606 1718 w.ch[c].n_atoms = w.ch[c].n_hetatm = 0;
4607 }
4608  
4609 //the residue: its chain's index and its key, NUL between
4610 {
4611 22693 SV *key = sv_2mortal(newSVpvs(""));
4612 22693 ▶ if (SvOK(num)) sv_catsv(key, num);
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(num)) sv_catsv(key, num); 22661 32 22693
4613 22693 ▶ if (SvOK(ic)) sv_catsv(key, ic);
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(ic)) sv_catsv(key, ic); 22693 0 22693
4614 22693 ▶ if (SvTRUE(asm_at(aTHX_ apart, r))) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvTRUE(asm_at(aTHX_ apart, r))) { 16 22677 22693
4615 16 sv_catpvs(key, "(");
4616 16 sv_catpvn(key, rns, rnn);
4617 16 sv_catpvs(key, ")");
4618 }
4619 22693 sv_setpvn(ik, head, (STRLEN)my_snprintf(head, sizeof(head), "%" UVuf, (UV)c));
4620 22693 sv_catpvn(ik, "\0", 1);
4621 22693 ls = SvPV_const(key, ln);
4622 22693 sv_catpvn(ik, ls, ln);
4623 22693 slot = hv_fetch(ridx, SvPVX(ik), (I32)SvCUR(ik), 1);
4624 22693 ▶ if (!slot) croak("Chem::Structure::Parser: cannot index a residue");
Branch: 1 branch
BranchTrueFalseTotal
if (!slot) croak("Chem::Structure::Parser: cannot index a residue"); 0 22693 22693
4625 22693 ▶ if (!SvOK(*slot)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(*slot)) { 22685 8 22693
4626 res_info info;
4627 22685 ix = nres++;
4628 22685 sv_setuv(*slot, (UV)ix);
4629 22685 R = w.res + ix;
4630 22685 Zero(R, 1, asm_res);
4631 22685 R->key = key;
4632 22685 R->rn = rn; R->num = num; R->ic = ic; R->cid = cid; R->het = hs;
4633 22685 R->chain = c;
4634 22685 R->i0 = i0; R->i1 = i1;
4635 22685 R->het_b = is_het;
4636 22685 ▶ if (res_lookup(rns, rnn, &info)) {
Branch: 1 branch
BranchTrueFalseTotal
if (res_lookup(rns, rnn, &info)) { 21938 747 22685
4637 21938 R->type = info.type;
4638 21938 R->one = info.one;
4639 } else {
4640 747 R->type = RT_OTHER;
4641 747 R->one = '\0';
4642 }
4643 22685 R->standard = NAME_LISTED(rns, rnn, std_res);
4644 22685 ▶ R->modified = (R->type == RT_AA || R->type == RT_NUC) && !R->standard;
Branch: 3 branches
BranchTrueFalseTotal
R->modified = (R->type == RT_AA || R->type == RT_NUC) && !R->standard; 7984 14701 22685
R->modified = (R->type == RT_AA || R->type == RT_NUC) && !R->standard; 2440 5544 7984
R->modified = (R->type == RT_AA || R->type == RT_NUC) && !R->standard; 255 16886 17141
4645 22685 ▶ if (src.atoms) {
Branch: 1 branch
BranchTrueFalseTotal
if (src.atoms) { 22240 445 22685
4646 22240 R->atoms = asm_at(aTHX_ res_atoms, r);
4647 22240 R->order = asm_at(aTHX_ res_order, r);
4648 }
4649 } else {
4650 8 ix = (size_t)SvUV(*slot);
4651 8 R = w.res + ix;
4652 }
4653 }
4654  
4655 //counts and sums, which a residue met twice adds up
4656 22693 R->n_atoms += n;
4657 22693 ▶ if (SvOK(asm_at(aTHX_ rsx, r))) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(asm_at(aTHX_ rsx, r))) { 22688 5 22693
4658 22688 const bool first = R->nc == 0;
4659 22688 asm_add(aTHX_ &R->sx, first, asm_at(aTHX_ rsx, r));
4660 22688 asm_add(aTHX_ &R->sy, first, asm_at(aTHX_ rsy, r));
4661 22688 asm_add(aTHX_ &R->sz, first, asm_at(aTHX_ rsz, r));
4662 }
4663 22693 R->nc += SvUV(asm_at(aTHX_ rnxyz, r));
4664 22693 ▶ if (SvOK(asm_at(aTHX_ rsb, r))) asm_add(aTHX_ &R->sb, R->nb == 0, asm_at(aTHX_ rsb, r));
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(asm_at(aTHX_ rsb, r))) asm_add(aTHX_ &R->sb, R->nb == 0, asm_at(aTHX_ rsb, r)); 22654 39 22693
4665 22693 R->nb += SvUV(asm_at(aTHX_ rnb, r));
4666 22693 w.ch[c].n_atoms += n;
4667 22693 ▶ if (is_het) {//the record type is part of a residue's identity
Branch: 1 branch
BranchTrueFalseTotal
if (is_het) {//the record type is part of a residue's identity 5798 16895 22693
4668 5798 w.ch[c].n_hetatm += n;
4669 5798 n_het += n;
4670 }
4671  
4672 //the type of a residue the table does not know, now its atoms are counted
4673 22693 ▶ if (R->type == RT_OTHER) {
Branch: 1 branch
BranchTrueFalseTotal
if (R->type == RT_OTHER) { 747 21946 22693
4674 701 SV *el = src.atoms ? asm_field(aTHX_ &src, (SSize_t)i0, "element", 7, NULL)
4675 747 ▶ : asm_at(aTHX_ elem, ri);
Branch: 1 branch
BranchTrueFalseTotal
: asm_at(aTHX_ elem, ri); 701 46 747
4676 747 STRLEN en = 0;
4677 1494 ▶ const char *es = SvTRUE(el) ? SvPV_const(el, en) : "";
Branch: 1 branch
BranchTrueFalseTotal
const char *es = SvTRUE(el) ? SvPV_const(el, en) : ""; 747 0 747
4678 1227 ▶ R->type = (NAME_LISTED(rns, rnn, ion_res)
Branch: 1 branch
BranchTrueFalseTotal
R->type = (NAME_LISTED(rns, rnn, ion_res) 480 267 747
4679 480 ▶ || (R->n_atoms == 1 && asm_eq_nocase(es, en, rns, rnn))) ? RT_ION : RT_LIGAND;
Branch: 2 branches
BranchTrueFalseTotal
|| (R->n_atoms == 1 && asm_eq_nocase(es, en, rns, rnn))) ? RT_ION : RT_LIGAND; 24 456 480
|| (R->n_atoms == 1 && asm_eq_nocase(es, en, rns, rnn))) ? RT_ION : RT_LIGAND; 0 24 24
4680 }
4681 //a free base: a nucleotide's name and no sugar or phosphate in this run
4682 22693 ▶ if (R->type == RT_NUC && NAME_LISTED(rns, rnn, free_base_res)) {
Branch: 2 branches
BranchTrueFalseTotal
if (R->type == RT_NUC && NAME_LISTED(rns, rnn, free_base_res)) { 2440 20253 22693
if (R->type == RT_NUC && NAME_LISTED(rns, rnn, free_base_res)) { 10 2430 2440
4683 10 bool backbone = FALSE;
4684 50 ▶ for (UV i = i0; i <= i1 && !backbone; i++) {
Branch: 2 branches
BranchTrueFalseTotal
for (UV i = i0; i <= i1 && !backbone; i++) { 47 3 50
for (UV i = i0; i <= i1 && !backbone; i++) { 40 7 47
4685 40 SV *nm = asm_field(aTHX_ &src, (SSize_t)i, "name", 4, src.name);
4686 STRLEN nn;
4687 const char *ns;
4688 40 ▶ if (!SvOK(nm)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(nm)) continue; 0 40 40
4689 40 ns = SvPV_const(nm, nn);
4690 40 backbone = asm_backbone_name(ns, nn);
4691 }
4692 10 ▶ if (!backbone) {
Branch: 1 branch
BranchTrueFalseTotal
if (!backbone) { 3 7 10
4693 3 R->type = RT_LIGAND;
4694 3 R->one = '\0';
4695 3 R->modified = FALSE;
4696 }
4697 }
4698 }
4699  
4700 //each chain's residues in file order, as one list cut at off[]
4701 1168 ▶ Newxz(w.off, nch + 1, size_t);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(w.off, nch + 1, size_t); 0 1168 1168
4702 1168 ▶ Newx(w.list, nres ? nres : 1, size_t);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.list, nres ? nres : 1, size_t); 1120 48 1168
Newx(w.list, nres ? nres : 1, size_t); 0 1120 1120
Newx(w.list, nres ? nres : 1, size_t); 1120 48 1168
4703 1168 ▶ Newx(w.poly, nres ? nres : 1, size_t);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.poly, nres ? nres : 1, size_t); 1120 48 1168
Newx(w.poly, nres ? nres : 1, size_t); 0 1120 1120
Newx(w.poly, nres ? nres : 1, size_t); 1120 48 1168
4704 1168 ▶ Newx(w.nums, nres ? nres : 1, IV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.nums, nres ? nres : 1, IV); 1120 48 1168
Newx(w.nums, nres ? nres : 1, IV); 0 1120 1120
Newx(w.nums, nres ? nres : 1, IV); 1120 48 1168
4705 23853 ▶ for (k = 0; k < nres; k++) w.off[w.res[k].chain + 1]++;
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < nres; k++) w.off[w.res[k].chain + 1]++; 22685 1168 23853
4706 2886 ▶ for (k = 0; k < nch; k++) w.off[k + 1] += w.off[k];
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < nch; k++) w.off[k + 1] += w.off[k]; 1718 1168 2886
4707 {
4708 size_t *CSP_RESTRICT fill;
4709 1168 ▶ Newx(fill, nch ? nch : 1, size_t);
Branch: 3 branches
BranchTrueFalseTotal
Newx(fill, nch ? nch : 1, size_t); 1120 48 1168
Newx(fill, nch ? nch : 1, size_t); 0 1120 1120
Newx(fill, nch ? nch : 1, size_t); 1120 48 1168
4710 1168 SAVEFREEPV((char *)fill);
4711 1168 ▶ Copy(w.off, fill, nch ? nch : 1, size_t);
Branch: 3 branches
BranchTrueFalseTotal
Copy(w.off, fill, nch ? nch : 1, size_t); 1120 48 1168
Copy(w.off, fill, nch ? nch : 1, size_t); 0 1120 1120
Copy(w.off, fill, nch ? nch : 1, size_t); 1120 48 1168
4712 23853 ▶ for (k = 0; k < nres; k++) w.list[fill[w.res[k].chain]++] = k;
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < nres; k++) w.list[fill[w.res[k].chain]++] = k; 22685 1168 23853
4713 }
4714  
4715 2886 ▶ for (size_t c = 0; c < nch; c++) {
Branch: 1 branch
BranchTrueFalseTotal
for (size_t c = 0; c < nch; c++) { 1718 1168 2886
4716 1718 const size_t *CSP_RESTRICT list = w.list + w.off[c];
4717 1718 const size_t nl = w.off[c + 1] - w.off[c];
4718 1718 HV *ch = newHV(), *mm, *chains;
4719 AV *corder;
4720 HE *he;
4721 SV *er;
4722 1718 size_t end = 0;
4723 1718 bool have_end = FALSE;
4724  
4725 //where the polymer ends, and the polymer-named residues after it set free
4726 24403 ▶ for (k = 0; k < nl; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < nl; k++) { 22685 1718 24403
4727 22685 const asm_res *CSP_RESTRICT r = w.res + list[k];
4728 22685 ▶ if (!r->het_b && (r->type == RT_AA || r->type == RT_NUC)) { end = k; have_end = TRUE; }
Branch: 3 branches
BranchTrueFalseTotal
if (!r->het_b && (r->type == RT_AA || r->type == RT_NUC)) { end = k; have_end = TRUE; } 16887 5798 22685
if (!r->het_b && (r->type == RT_AA || r->type == RT_NUC)) { end = k; have_end = TRUE; } 2435 14452 16887
if (!r->het_b && (r->type == RT_AA || r->type == RT_NUC)) { end = k; have_end = TRUE; } 2435 0 2435
4729 }
4730 1718 ▶ if (have_end) {
Branch: 1 branch
BranchTrueFalseTotal
if (have_end) { 1602 116 1718
4731 1606 ▶ while (end + 1 < nl && asm_bonded(aTHX_ &src, w.res + list[end], w.res + list[end + 1])) end++;
Branch: 2 branches
BranchTrueFalseTotal
while (end + 1 < nl && asm_bonded(aTHX_ &src, w.res + list[end], w.res + list[end + 1])) end++; 344 1262 1606
while (end + 1 < nl && asm_bonded(aTHX_ &src, w.res + list[end], w.res + list[end + 1])) end++; 4 340 344
4732 6742 ▶ for (k = end + 1; k < nl; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = end + 1; k < nl; k++) { 5140 1602 6742
4733 5140 asm_res *CSP_RESTRICT r = w.res + list[k];
4734 5140 ▶ if (r->type != RT_AA && r->type != RT_NUC) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (r->type != RT_AA && r->type != RT_NUC) continue; 5135 5 5140
if (r->type != RT_AA && r->type != RT_NUC) continue; 5134 1 5135
4735 6 r->type = RT_LIGAND;
4736 6 r->one = '\0';
4737 6 r->modified = FALSE;
4738 6 r->is_free = TRUE;
4739 }
4740 }
4741  
4742 //the model it belongs to, made the first time one of its chains is met
4743 1718 he = hv_fetch_ent(out, w.ch[c].model, 0, 0);
4744 1718 ▶ if (he && SvROK(HeVAL(he))) {
Branch: 2 branches
BranchTrueFalseTotal
if (he && SvROK(HeVAL(he))) { 390 1328 1718
if (he && SvROK(HeVAL(he))) { 390 0 390
4745 390 mm = (HV *)SvRV(HeVAL(he));
4746 } else {
4747 1328 mm = newHV();
4748 1328 (void)hv_stores(mm, "chains", newRV_noinc((SV *)newHV()));
4749 1328 (void)hv_stores(mm, "chain_order", newRV_noinc((SV *)newAV()));
4750 1328 (void)hv_store_ent(out, w.ch[c].model, newRV_noinc((SV *)mm), 0);
4751 }
4752 1718 chains = hvf_hv(aTHX_ mm, "chains", 6);
4753 1718 corder = hvf_av(aTHX_ mm, "chain_order", 11);
4754 1718 ▶ if (!chains || !corder) croak("Chem::Structure::Parser: a model without its chains");
Branch: 2 branches
BranchTrueFalseTotal
if (!chains || !corder) croak("Chem::Structure::Parser: a model without its chains"); 1718 0 1718
if (!chains || !corder) croak("Chem::Structure::Parser: a model without its chains"); 0 1718 1718
4755 1718 (void)hv_store_ent(chains, w.ch[c].id, newRV_noinc((SV *)ch), 0);
4756 1718 av_push(corder, newSVsv(w.ch[c].id));
4757  
4758 1718 (void)hv_stores(ch, "id", newSVsv(w.ch[c].id));
4759 1718 (void)hv_stores(ch, "n_atoms", newSVuv(w.ch[c].n_atoms));
4760 1718 (void)hv_stores(ch, "n_hetatm", newSVuv(w.ch[c].n_hetatm));
4761 /*how many atoms of each element the chain holds, which the parse
4762 tallied by model and chain as it read them. The counts add up to
4763 n_atoms, alternate conformers and all, because both count records.*/
4764 1718 er = NULL;
4765 1718 ▶ if (chain_elem) {
Branch: 1 branch
BranchTrueFalseTotal
if (chain_elem) { 1718 0 1718
4766 1718 HV *em = hvf_ent_hv(aTHX_ chain_elem, w.ch[c].model);
4767 1718 ▶ HE *e2 = em ? hv_fetch_ent(em, w.ch[c].id, 0, 0) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
HE *e2 = em ? hv_fetch_ent(em, w.ch[c].id, 0, 0) : NULL; 1718 0 1718
4768 1718 ▶ if (e2 && SvROK(HeVAL(e2))) er = newSVsv(HeVAL(e2));
Branch: 2 branches
BranchTrueFalseTotal
if (e2 && SvROK(HeVAL(e2))) er = newSVsv(HeVAL(e2)); 1718 0 1718
if (e2 && SvROK(HeVAL(e2))) er = newSVsv(HeVAL(e2)); 1718 0 1718
4769 }
4770 1718 ▶ (void)hv_stores(ch, "elements", er ? er : newRV_noinc((SV *)newHV()));
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(ch, "elements", er ? er : newRV_noinc((SV *)newHV())); 0 1718 1718
4771 1718 asm_chain_finish(aTHX_ &w, c, &rk, ch);
4772 }
4773  
4774 1168 (void)hv_stores(stats, "n_hetatm", newSVuv(n_het));
4775 1168 LEAVE;
4776 1168 return (HV *)SvREFCNT_inc_simple_NN((SV *)out);
4777 }
4778  
4779 /*atoms_flat() -- structure_atoms(): every atom of the chains named in cids, in
4780 chain, residue and atom order, each a copy of its atom hash with the residue's
4781 identity added -- chain, resname, resseq, icode and reskey. The copy is
4782 shallow, as the Perl's %{ $atom } was: an altlocs list is the same list.
4783  
4784 In C because it is one hash an atom: 4fqr's 88,416 atoms took 0.111 s in Perl
4785 and take 0.088 s here, and most of that is allocating the copies; see
4786 notes.txt. The Perl half has
4787 checked the structure and the chain ids before it gets here, so the messages a
4788 caller sees for those are its own. No CSP_RESTRICT on chains: the residue and
4789 atom hashes reached through it are perl's, and so are the copies.*/
4790 #define NFKEY 5
4791 static const char *const fkey_name[NFKEY] = { "chain", "resname", "resseq", "icode", "reskey" };
4792 13 static AV *atoms_flat(pTHX_ HV *chains, AV *CSP_RESTRICT cids){
4793 13 AV *out = (AV *)sv_2mortal((SV *)newAV());
4794 U32 fhash[NFKEY];
4795 I32 flen[NFKEY];
4796 13 const SSize_t nc = av_len(cids) + 1;
4797 78 ▶ for (unsigned short i = 0; i < NFKEY; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < NFKEY; i++) { 65 13 78
4798 65 flen[i] = (I32)strlen(fkey_name[i]);
4799 65 ▶ PERL_HASH(fhash[i], fkey_name[i], flen[i]);
Branch: 1 branch
BranchTrueFalseTotal
PERL_HASH(fhash[i], fkey_name[i], flen[i]); 65 0 65
4800 }
4801 31 ▶ for (SSize_t ci = 0; ci < nc; ci++) {
Branch: 1 branch
BranchTrueFalseTotal
for (SSize_t ci = 0; ci < nc; ci++) { 20 11 31
4802 20 SV **cs = av_fetch(cids, ci, 0);
4803 HV *c, *residues;
4804 AV *ro;
4805 SSize_t nr;
4806 20 ▶ if (!cs || !*cs) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!cs || !*cs) continue; 20 0 20
if (!cs || !*cs) continue; 0 20 20
4807 20 c = hvf_ent_hv(aTHX_ chains, *cs);
4808 20 ▶ if (!c) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!c) continue; 0 20 20
4809 20 ro = hvf_av(aTHX_ c, "residue_order", 13);
4810 20 residues = hvf_hv(aTHX_ c, "residues", 8);
4811 20 ▶ nr = (ro && residues) ? av_len(ro) + 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
nr = (ro && residues) ? av_len(ro) + 1 : 0; 20 0 20
nr = (ro && residues) ? av_len(ro) + 1 : 0; 20 0 20
4812 128 ▶ for (SSize_t ri = 0; ri < nr; ri++) {
Branch: 1 branch
BranchTrueFalseTotal
for (SSize_t ri = 0; ri < nr; ri++) { 110 18 128
4813 110 SV **rk = av_fetch(ro, ri, 0);
4814 HV *r, *atoms;
4815 AV *order;
4816 SV *rv[NFKEY];
4817 SSize_t na;
4818 110 ▶ if (!rk || !*rk) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!rk || !*rk) continue; 110 0 110
if (!rk || !*rk) continue; 0 110 110
4819 110 r = hvf_ent_hv(aTHX_ residues, *rk);
4820 110 ▶ if (!r) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!r) continue; 0 110 110
4821 110 atoms = hvf_hv(aTHX_ r, "atoms", 5);
4822 110 order = hvf_av(aTHX_ r, "atom_order", 10);
4823 110 ▶ na = order ? av_len(order) + 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
na = order ? av_len(order) + 1 : 0; 110 0 110
4824 110 rv[0] = *cs;
4825 110 rv[1] = hvf_sv(aTHX_ r, "resname", 7);
4826 110 rv[2] = hvf_sv(aTHX_ r, "number", 6);
4827 110 rv[3] = hvf_sv(aTHX_ r, "icode", 5);
4828 110 rv[4] = *rk;
4829 506 ▶ for (SSize_t ai = 0; ai < na; ai++) {
Branch: 1 branch
BranchTrueFalseTotal
for (SSize_t ai = 0; ai < na; ai++) { 398 108 506
4830 398 SV **an = av_fetch(order, ai, 0);
4831 398 ▶ HV *a = (an && *an && atoms) ? hvf_ent_hv(aTHX_ atoms, *an) : NULL;
Branch: 3 branches
BranchTrueFalseTotal
HV *a = (an && *an && atoms) ? hvf_ent_hv(aTHX_ atoms, *an) : NULL; 398 0 398
HV *a = (an && *an && atoms) ? hvf_ent_hv(aTHX_ atoms, *an) : NULL; 398 0 398
HV *a = (an && *an && atoms) ? hvf_ent_hv(aTHX_ atoms, *an) : NULL; 398 0 398
4832 HV *h;
4833 HE *he;
4834 398 ▶ if (!a) {
Branch: 1 branch
BranchTrueFalseTotal
if (!a) { 2 396 398
4835 STRLEN kn, nn;
4836 2 const char *ks = SvPV_const(*rk, kn);
4837 4 ▶ const char *ns = (an && *an && SvOK(*an)) ? SvPV_const(*an, nn) : "";
Branch: 3 branches
BranchTrueFalseTotal
const char *ns = (an && *an && SvOK(*an)) ? SvPV_const(*an, nn) : ""; 2 0 2
const char *ns = (an && *an && SvOK(*an)) ? SvPV_const(*an, nn) : ""; 2 0 2
const char *ns = (an && *an && SvOK(*an)) ? SvPV_const(*an, nn) : ""; 2 0 2
4838 2 croak("structure_atoms: residue '%s' lists an atom '%s' it does not have", ks, ns);
4839 }
4840 396 h = newHV();
4841 396 av_push(out, newRV_noinc((SV *)h));
4842 396 ▶ hv_ksplit(h, HvUSEDKEYS(a) + NFKEY);
Branch: 1 branch
BranchTrueFalseTotal
hv_ksplit(h, HvUSEDKEYS(a) + NFKEY); 0 396 396
4843 396 hv_iterinit(a);
4844 5083 ▶ while ((he = hv_iternext(a))) {
Branch: 1 branch
BranchTrueFalseTotal
while ((he = hv_iternext(a))) { 4687 396 5083
4845 4687 I32 kl = (I32)HeKLEN(he);
4846 4687 ▶ (void)hv_store(h, HeKEY(he), HeKUTF8(he) ? -kl : kl,
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_store(h, HeKEY(he), HeKUTF8(he) ? -kl : kl, 0 4687 4687
4847 newSVsv(HeVAL(he)), HeHASH(he));
4848 }
4849 2376 ▶ for (unsigned short i = 0; i < NFKEY; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < NFKEY; i++) 1980 396 2376
4850 1980 ▶ (void)hv_store(h, fkey_name[i], flen[i],
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_store(h, fkey_name[i], flen[i], 1978 2 1980
4851 rv[i] ? newSVsv(rv[i]) : newSV(0), fhash[i]);
4852 }
4853 }
4854 }
4855 11 return (AV *)SvREFCNT_inc_simple_NN((SV *)out);
4856 }
4857  
4858 /*A uniform grid over a set of points, for "which points are within cut of this
4859 one?".
4860  
4861 The Shrake-Rupley kernel asks that question once per atom and mdtraj answers it
4862 by comparing every atom against every other, which is fine for the few thousand
4863 atoms an MD frame holds and is not fine here: the largest entry in PDBbind
4864 v2020 is ~400,000 atoms, and 1.6e11 distance comparisons is not a wait anybody
4865 would sit through. A grid of cells one cutoff wide gives the same neighbour
4866 set from the 27 cells around each atom, in time proportional to the number of
4867 atoms rather than its square.
4868  
4869 Same set, not a similar one: an atom is a neighbour when the distance is below
4870 the cutoff, and the cutoff is twice the largest radius, so every neighbour is
4871 inside the 27-cell block whatever the cell size is as long as it is at least
4872 the cutoff. Which is why the loop that widens the cells to keep their number
4873 down is safe -- it can only make the block bigger. The order neighbours come
4874 back in does change, and does not matter: the kernel asks whether any of them
4875 covers a point and stops at the first that does.
4876  
4877 The cell count is capped at eight per atom so that the grid cannot cost more
4878 memory than the coordinates it indexes -- a thin, extended structure in a large
4879 box would otherwise want more cells than there are atoms to put in them*/
4880 typedef struct {
4881 UV *start;//ncell + 1 offsets into idx
4882 UV *idx;//point indices, grouped by cell
4883 NV x0, y0, z0, cell;//edge length, angstrom
4884 UV nx, ny, nz;
4885 } cell_grid;
4886  
4887 6425 static void grid_free(pTHX_ cell_grid *CSP_RESTRICT g){
4888 6425 Safefree(g->start);
4889 6425 Safefree(g->idx);
4890 6425 Zero(g, 1, cell_grid);
4891 6425 }
4892  
4893 /*Aromatic rings, found and given a plane.
4894  
4895 The centroid is the mean of the ring atoms' positions and the normal is the
4896 cross product of the first two atoms' offsets from it, normalised -- which is
4897 mdtraj's compute_centroid() and compute_ring_normal() exactly, including the
4898 part where only two of the ring's atoms decide the plane. A ring in a real
4899 structure is not quite planar, so a least-squares plane through all six atoms
4900 would be a different vector; it would also be a different answer from the one
4901 the reference implementation gives, and the reference implementation is what
4902 this is tested against.
4903  
4904 The direction the normal points in is arbitrary -- it flips if the ring is
4905 listed the other way round -- and nothing below depends on it, because every
4906 angle is folded into 0..90 degrees before it is compared with anything.*/
4907 typedef struct {
4908 NV cx, cy, cz;//centroid
4909 NV nx, ny, nz;//unit normal
4910 UV res;//which residue it belongs to
4911 char label;//'6' or '5': the ring size, which is what names it
4912 } ring_t;
4913  
4914 /*The four backbone atoms of a residue, where they are, read once.
4915  
4916 The hydrogen bonds, the secondary structure, the torsions and the peptide-bond
4917 test that three of them make all reach for a residue's N, CA, C and O by name,
4918 and each used to do it for itself: the same four hash lookups per residue made
4919 three and four times over in one walk. bb_get() reads them the first time any
4920 of those asks and keeps them on the structset; the positions are the NVs
4921 atom_xyz() returns, so what each caller computes from them is unchanged.*/
4922 typedef struct {
4923 NV n[3], ca[3], c[3], o[3];
4924 bool has_n, has_ca, has_c, has_o;
4925 } bb_xyz;
4926  
4927 /*The coordinate section of an $info, flattened.
4928  
4929 Atoms are in walk order, which is chain by chain, residue by residue and, inside
4930 a residue, the order the file wrote them: so a residue's atoms are one
4931 contiguous run and a chain's residues are another, and the roll-ups below are
4932 sums over ranges rather than lookups. Same shape the parse itself hands back,
4933 for the same reason.*/
4934 typedef struct {
4935 //per atom
4936 NV *x, *y, *z;
4937 //rad, mass and apolar are all read off the element, and are all NULL for a
4938 //set built coords_only -- see set_build()
4939 NV *rad;//van der Waals radius plus the probe, angstrom
4940 NV *area;//solvent-accessible surface, angstrom^2; NULL until computed
4941 NV *alone;//the same with the other chains taken away; NULL unless asked for
4942 NV *mass;//dalton; 0.0 for an atom whose element has no mass
4943 unsigned char *apolar;//1 = carbon or sulphur, 0 = everything else
4944 HV **atom_hv;//the atom hash the row was read from, for writing back
4945 UV n_atom;
4946 //per residue: the atom range [first, last)
4947 HV **res_hv;
4948 UV *res_first, *res_last;
4949 char *res_one;//single-letter code, '\0' when the residue has none
4950 unsigned char *res_type;//RT_*, for the questions only an amino acid answers
4951 unsigned char *res_std;//1 = one of the twenty, as the residue hash says
4952 U32 *res_key;//packed residue name, for ring_defs()
4953 UV n_res;
4954 /*Kabsch-Sander: each residue's two best acceptors and their energies, laid
4955 out two per residue. An entry of n_res means there is no bond there.*/
4956 UV *ks_acc;
4957 NV *ks_e;
4958 //per chain: the residue range [first, last)
4959 HV **chain_hv;
4960 UV *chain_first, *chain_last, n_chain;
4961 //tallies gathered on the way past
4962 NV mass_total;
4963 UV n_no_element;//atoms whose element field spells no element
4964 /*How many names the residues' atom_order lists held, which is not n_atom:
4965 that one counts the atoms a position could be read from. The two differ for
4966 a file whose coordinate columns are unreadable, and telling them apart is
4967 what keeps such a file from being mistaken for one read with atoms => 0.*/
4968 UV n_atom_slots;
4969 /*Worked out once, by whichever calculation first needs them, and shared by
4970 the rest; each is NULL, or for grid unbuilt, until then.*/
4971 ring_t *rings;//rings_get(): every aromatic ring of the walk
4972 UV n_rings;
4973 bool have_rings;//FALSE = rings_get() has not run, as distinct from no rings
4974 bb_xyz *bb;//bb_get(): per residue
4975 /*The whole-structure SASA kernel's neighbour grid, kept for the interface,
4976 which asks the same question of the same atoms at the same cutoff; see
4977 sasa_compute(). grid_cut is that cutoff.*/
4978 cell_grid grid;
4979 NV grid_cut;
4980 } structset;
4981  
4982 905 static void set_free(pTHX_ structset *CSP_RESTRICT s)
4983 {
4984 905 Safefree(s->x); Safefree(s->y); Safefree(s->z);
4985 905 Safefree(s->rad); Safefree(s->area); Safefree(s->alone);
4986 905 Safefree(s->mass);
4987 905 Safefree(s->apolar); Safefree(s->atom_hv);
4988 905 Safefree(s->res_hv); Safefree(s->res_first); Safefree(s->res_last);
4989 905 Safefree(s->res_one); Safefree(s->res_type); Safefree(s->res_std);
4990 905 Safefree(s->res_key);
4991 905 Safefree(s->ks_acc); Safefree(s->ks_e);
4992 905 Safefree(s->chain_hv); Safefree(s->chain_first); Safefree(s->chain_last);
4993 905 Safefree(s->rings); Safefree(s->bb);
4994 905 grid_free(aTHX_ &s->grid);
4995 905 Zero(s, 1, structset);
4996 905 }
4997  
4998 /*set_add_residue() -- one residue of an $info into the arrays above, with
4999 every atom of it that has a position.
5000  
5001 Taken out of set_build(), its one caller. The caller has checked that there is
5002 room for the residue; the atom arrays grow here if the residue holds more atoms
5003 than *cap_atom left room for.
5004  
5005 No CSP_RESTRICT on r: it is a hash perl built, and the perl API may reach it by
5006 another route inside the calls below.*/
5007 18039 static void set_add_residue(pTHX_ structset *CSP_RESTRICT s, HV *r, NV probe,
5008 bool coords_only, UV *CSP_RESTRICT cap_atom)
5009 {
5010 AV *ao;
5011 HV *atoms;
5012 SV *one, *rn;
5013 SSize_t ai, nai;
5014 18039 s->res_hv[s->n_res] = r;
5015 18039 s->res_first[s->n_res] = s->n_atom;
5016 18039 one = hvf_sv(aTHX_ r, "one", 3);
5017 18039 ▶ if (one) {
Branch: 1 branch
BranchTrueFalseTotal
if (one) { 18038 1 18039
5018 STRLEN olen;
5019 18038 const char *op = SvPV_const(one, olen);
5020 //a residue with no single-letter code has an empty string here,
5021 //not a missing key, so length is what tells them apart
5022 18038 ▶ s->res_one[s->n_res] = (olen == 1) ? *op : '\0';
Branch: 1 branch
BranchTrueFalseTotal
s->res_one[s->n_res] = (olen == 1) ? *op : '\0'; 12621 5417 18038
5023 } else {
5024 1 s->res_one[s->n_res] = '\0';
5025 }
5026 18039 rn = hvf_sv(aTHX_ r, "resname", 7);
5027 18039 ▶ if (rn) {
Branch: 1 branch
BranchTrueFalseTotal
if (rn) { 18038 1 18039
5028 STRLEN rl;
5029 res_info named;
5030 18038 const char *rp = SvPV_const(rn, rl);
5031 18038 s->res_key[s->n_res] = res_key(rp, rl);
5032 18038 ▶ s->res_type[s->n_res] = res_lookup(rp, rl, &named) ? named.type : RT_OTHER;
Branch: 1 branch
BranchTrueFalseTotal
s->res_type[s->n_res] = res_lookup(rp, rl, &named) ? named.type : RT_OTHER; 17510 528 18038
5033 } else {
5034 1 s->res_key[s->n_res] = 0;
5035 1 s->res_type[s->n_res] = RT_OTHER;
5036 }
5037 {
5038 18039 SV *st = hvf_sv(aTHX_ r, "standard", 8);
5039 18039 ▶ s->res_std[s->n_res] = (st && SvTRUE(st)) ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
s->res_std[s->n_res] = (st && SvTRUE(st)) ? 1 : 0; 18038 1 18039
s->res_std[s->n_res] = (st && SvTRUE(st)) ? 1 : 0; 12451 5587 18038
5040 }
5041 18039 ao = hvf_av(aTHX_ r, "atom_order", 10);
5042 18039 atoms = hvf_hv(aTHX_ r, "atoms", 5);
5043 18039 ▶ nai = (ao && atoms) ? av_len(ao) + 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
nai = (ao && atoms) ? av_len(ao) + 1 : 0; 18039 0 18039
nai = (ao && atoms) ? av_len(ao) + 1 : 0; 18039 0 18039
5044 18039 s->n_atom_slots += (UV)nai;
5045 146125 ▶ for (ai = 0; ai < nai; ai++) {
Branch: 1 branch
BranchTrueFalseTotal
for (ai = 0; ai < nai; ai++) { 128086 18039 146125
5046 128086 SV **as = av_fetch(ao, ai, 0);
5047 HV *a;
5048 SV *xs, *ys, *zs, *es;
5049 elem_prop ep;
5050 unsigned char apolar;
5051 128092 ▶ if (!as || !*as || !SvOK(*as)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!as || !*as || !SvOK(*as)) continue; 128086 0 128086
if (!as || !*as || !SvOK(*as)) continue; 128086 0 128086
if (!as || !*as || !SvOK(*as)) continue; 0 128086 128086
5052 128086 a = hvf_ent_hv(aTHX_ atoms, *as);
5053 128086 ▶ if (!a) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!a) continue; 2 128084 128086
5054 /*The chain's n_atoms counts records and so is an upper bound on
5055 the atoms its residues hold -- for every structure this module
5056 read. One assembled somewhere else can say less than it holds,
5057 or not say at all, and the answer then has to be about the atoms
5058 that are there rather than about the number the chain claimed:
5059 the arrays grow instead of the walk stopping. Never reached for
5060 a structure this module built, which is why the first pass sizes
5061 from the counts at all.*/
5062 128084 ▶ if (s->n_atom >= *cap_atom) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->n_atom >= *cap_atom) { 1 128083 128084
5063 1 ▶ *cap_atom = *cap_atom ? *cap_atom * 2 : 16;
Branch: 1 branch
BranchTrueFalseTotal
*cap_atom = *cap_atom ? *cap_atom * 2 : 16; 0 1 1
5064 1 ▶ Renew(s->x, *cap_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->x, *cap_atom, NV); 0 1 1
5065 1 ▶ Renew(s->y, *cap_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->y, *cap_atom, NV); 0 1 1
5066 1 ▶ Renew(s->z, *cap_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->z, *cap_atom, NV); 0 1 1
5067 1 ▶ if (!coords_only) {
Branch: 1 branch
BranchTrueFalseTotal
if (!coords_only) { 1 0 1
5068 1 ▶ Renew(s->rad, *cap_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->rad, *cap_atom, NV); 0 1 1
5069 1 ▶ Renew(s->mass, *cap_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->mass, *cap_atom, NV); 0 1 1
5070 1 Renew(s->apolar, *cap_atom, unsigned char);
5071 }
5072 1 ▶ Renew(s->atom_hv, *cap_atom, HV *);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->atom_hv, *cap_atom, HV *); 0 1 1
5073 }
5074 128084 xs = hvf_sv(aTHX_ a, "x", 1);
5075 128084 ys = hvf_sv(aTHX_ a, "y", 1);
5076 128084 zs = hvf_sv(aTHX_ a, "z", 1);
5077 /*an atom whose line was truncated before the coordinates has
5078 no position, and a position is what every one of these
5079 calculations is about; it is left out and counted nowhere*/
5080 128084 ▶ if (!xs || !ys || !zs) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!xs || !ys || !zs) continue; 128080 4 128084
if (!xs || !ys || !zs) continue; 128080 0 128080
if (!xs || !ys || !zs) continue; 0 128080 128080
5081 128080 ▶ es = coords_only ? NULL : hvf_sv(aTHX_ a, "element", 7);
Branch: 1 branch
BranchTrueFalseTotal
es = coords_only ? NULL : hvf_sv(aTHX_ a, "element", 7); 113077 15003 128080
5082 128080 apolar = 0;
5083 128080 ▶ if (coords_only) {
Branch: 1 branch
BranchTrueFalseTotal
if (coords_only) { 15003 113077 128080
5084 //the element decides rad, mass and apolar and none of the
5085 //three is wanted: not fetched, not looked up, not stored,
5086 //and no tally kept of the atoms that spell none
5087 15003 ep.vdw = CSP_VDW_DEFAULT;
5088 15003 ep.mass = 0.0;
5089 113077 ▶ } else if (es) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (es) { 113076 1 113077
5090 STRLEN el;
5091 113076 const char *ep_s = SvPV_const(es, el);
5092 /*Carbon and sulphur are the apolar surface and everything
5093 else is the polar one, which is the split Chothia, C (1974)
5094 Nature 248:338 made when he first added a protein's buried
5095 surface up. Only the symbol decides it, so a sulphur that
5096 is part of a sulphate counts as apolar here; a caller who
5097 wants a chemistry-aware split has the per-atom areas.
5098  
5099 Asked of the packed key rather than of the field, so that a
5100 field written " C" or "c" answers the same as "C" -- the
5101 same normalisation the radius lookup just did.*/
5102 113076 ▶ if (!elem_prop_of(ep_s, el, &ep)) {
Branch: 1 branch
BranchTrueFalseTotal
if (!elem_prop_of(ep_s, el, &ep)) { 7 113069 113076
5103 7 ep.vdw = CSP_VDW_DEFAULT;
5104 7 ep.mass = 0.0;
5105 7 s->n_no_element++;
5106 113069 ▶ } else if (ep.key == K2('C', 0) || ep.key == K2('S', 0)) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (ep.key == K2('C', 0) || ep.key == K2('S', 0)) { 57668 55401 113069
} else if (ep.key == K2('C', 0) || ep.key == K2('S', 0)) { 441 57227 57668
5107 55842 apolar = 1;
5108 }
5109 } else {
5110 1 s->n_no_element++;
5111 }
5112 128080 s->x[s->n_atom] = SvNV(xs);
5113 128080 s->y[s->n_atom] = SvNV(ys);
5114 128080 s->z[s->n_atom] = SvNV(zs);
5115 128080 ▶ if (!coords_only) {
Branch: 1 branch
BranchTrueFalseTotal
if (!coords_only) { 113077 15003 128080
5116 113077 s->rad[s->n_atom] = ep.vdw + probe;
5117 113077 s->mass[s->n_atom] = ep.mass;
5118 113077 s->apolar[s->n_atom] = apolar;
5119 113077 s->mass_total += ep.mass;
5120 }
5121 128080 s->atom_hv[s->n_atom] = a;
5122 128080 s->n_atom++;
5123 }
5124 18039 s->res_last[s->n_res] = s->n_atom;
5125 18039 s->n_res++;
5126 18039 }
5127  
5128 /*set_build() -- walk an $info into the arrays above.
5129  
5130 Sized from what the structure already says about itself rather than by counting
5131 first: a chain's n_atoms counts records, so it is an upper bound on how many
5132 distinct atoms its residues hold (alternate conformers of one atom are one
5133 entry in the residue's atoms hash and several records), and the residue counts
5134 are exact. One over-allocation, trimmed with Renew afterwards, against a
5135 second walk of the same hashes.
5136  
5137 Croaks rather than returning an empty set when there are atom records to be had
5138 and no atom hashes to read them from: that is a structure read with atoms => 0,
5139 and the only thing wrong with it is that nobody said so.
5140  
5141 coords_only says the caller wants positions and nothing else: rad, mass and
5142 apolar are left unallocated and NULL, and the element field they are all three
5143 derived from is not fetched. That is one hash lookup and one element-table
5144 search per atom, and 2 NV + 1 byte per atom of memory, spent on three arrays
5145 structure_rmsd() never reads -- and it has every structure in the call in
5146 memory at once, which is what makes the per-atom bytes worth the parameter.
5147 probe is meaningless then and is not read.*/
5148 899 static void set_build(pTHX_ HV *CSP_RESTRICT info, structset *CSP_RESTRICT s,
5149 NV probe, bool coords_only, const char *CSP_RESTRICT who)
5150 {
5151 899 AV *order = hvf_av(aTHX_ info, "chain_order", 11);
5152 899 HV *chains = hvf_hv(aTHX_ info, "chains", 6);
5153 899 UV cap_atom = 0, cap_res = 0, n_chain = 0;
5154 SSize_t ci, nci;
5155  
5156 899 Zero(s, 1, structset);
5157 930 ▶ if (!order || !chains) return;
Branch: 2 branches
BranchTrueFalseTotal
if (!order || !chains) return; 898 1 899
if (!order || !chains) return; 0 898 898
5158 898 nci = av_len(order) + 1;
5159  
5160 //first pass: the chains only, which is a few dozen fetches, for the sizes
5161 2024 ▶ for (ci = 0; ci < nci; ci++) {
Branch: 1 branch
BranchTrueFalseTotal
for (ci = 0; ci < nci; ci++) { 1126 898 2024
5162 1126 SV **cs = av_fetch(order, ci, 0);
5163 HV *c;
5164 AV *ro;
5165 SV *na;
5166 1126 ▶ if (!cs || !*cs || !SvOK(*cs)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!cs || !*cs || !SvOK(*cs)) continue; 1126 0 1126
if (!cs || !*cs || !SvOK(*cs)) continue; 1126 0 1126
if (!cs || !*cs || !SvOK(*cs)) continue; 0 1126 1126
5167 1126 c = hvf_ent_hv(aTHX_ chains, *cs);
5168 1126 ▶ if (!c) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!c) continue; 0 1126 1126
5169 1126 n_chain++;
5170 1126 ro = hvf_av(aTHX_ c, "residue_order", 13);
5171 1126 ▶ if (ro) cap_res += (UV)(av_len(ro) + 1);
Branch: 1 branch
BranchTrueFalseTotal
if (ro) cap_res += (UV)(av_len(ro) + 1); 1126 0 1126
5172 1126 na = hvf_sv(aTHX_ c, "n_atoms", 7);
5173 1126 ▶ if (na) cap_atom += SvUV(na);
Branch: 1 branch
BranchTrueFalseTotal
if (na) cap_atom += SvUV(na); 1125 1 1126
5174 }
5175 898 ▶ if (n_chain == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (n_chain == 0) return; 31 867 898
5176  
5177 867 ▶ Newx(s->x, cap_atom ? cap_atom : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(s->x, cap_atom ? cap_atom : 1, NV); 866 1 867
Newx(s->x, cap_atom ? cap_atom : 1, NV); 0 866 866
Newx(s->x, cap_atom ? cap_atom : 1, NV); 866 1 867
5178 867 ▶ Newx(s->y, cap_atom ? cap_atom : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(s->y, cap_atom ? cap_atom : 1, NV); 866 1 867
Newx(s->y, cap_atom ? cap_atom : 1, NV); 0 866 866
Newx(s->y, cap_atom ? cap_atom : 1, NV); 866 1 867
5179 867 ▶ Newx(s->z, cap_atom ? cap_atom : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(s->z, cap_atom ? cap_atom : 1, NV); 866 1 867
Newx(s->z, cap_atom ? cap_atom : 1, NV); 0 866 866
Newx(s->z, cap_atom ? cap_atom : 1, NV); 866 1 867
5180 867 ▶ if (!coords_only) {
Branch: 1 branch
BranchTrueFalseTotal
if (!coords_only) { 667 200 867
5181 667 ▶ Newx(s->rad, cap_atom ? cap_atom : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(s->rad, cap_atom ? cap_atom : 1, NV); 666 1 667
Newx(s->rad, cap_atom ? cap_atom : 1, NV); 0 666 666
Newx(s->rad, cap_atom ? cap_atom : 1, NV); 666 1 667
5182 667 ▶ Newx(s->mass, cap_atom ? cap_atom : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(s->mass, cap_atom ? cap_atom : 1, NV); 666 1 667
Newx(s->mass, cap_atom ? cap_atom : 1, NV); 0 666 666
Newx(s->mass, cap_atom ? cap_atom : 1, NV); 666 1 667
5183 667 ▶ Newx(s->apolar, cap_atom ? cap_atom : 1, unsigned char);
Branch: 1 branch
BranchTrueFalseTotal
Newx(s->apolar, cap_atom ? cap_atom : 1, unsigned char); 666 1 667
5184 }
5185 867 ▶ Newx(s->atom_hv, cap_atom ? cap_atom : 1, HV *);
Branch: 3 branches
BranchTrueFalseTotal
Newx(s->atom_hv, cap_atom ? cap_atom : 1, HV *); 866 1 867
Newx(s->atom_hv, cap_atom ? cap_atom : 1, HV *); 0 866 866
Newx(s->atom_hv, cap_atom ? cap_atom : 1, HV *); 866 1 867
5186 867 ▶ Newx(s->res_hv, cap_res ? cap_res : 1, HV *);
Branch: 3 branches
BranchTrueFalseTotal
Newx(s->res_hv, cap_res ? cap_res : 1, HV *); 867 0 867
Newx(s->res_hv, cap_res ? cap_res : 1, HV *); 0 867 867
Newx(s->res_hv, cap_res ? cap_res : 1, HV *); 867 0 867
5187 867 ▶ Newx(s->res_first, cap_res ? cap_res : 1, UV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(s->res_first, cap_res ? cap_res : 1, UV); 867 0 867
Newx(s->res_first, cap_res ? cap_res : 1, UV); 0 867 867
Newx(s->res_first, cap_res ? cap_res : 1, UV); 867 0 867
5188 867 ▶ Newx(s->res_last, cap_res ? cap_res : 1, UV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(s->res_last, cap_res ? cap_res : 1, UV); 867 0 867
Newx(s->res_last, cap_res ? cap_res : 1, UV); 0 867 867
Newx(s->res_last, cap_res ? cap_res : 1, UV); 867 0 867
5189 867 ▶ Newx(s->res_one, cap_res ? cap_res : 1, char);
Branch: 1 branch
BranchTrueFalseTotal
Newx(s->res_one, cap_res ? cap_res : 1, char); 867 0 867
5190 867 ▶ Newx(s->res_type, cap_res ? cap_res : 1, unsigned char);
Branch: 1 branch
BranchTrueFalseTotal
Newx(s->res_type, cap_res ? cap_res : 1, unsigned char); 867 0 867
5191 867 ▶ Newx(s->res_std, cap_res ? cap_res : 1, unsigned char);
Branch: 1 branch
BranchTrueFalseTotal
Newx(s->res_std, cap_res ? cap_res : 1, unsigned char); 867 0 867
5192 867 ▶ Newx(s->res_key, cap_res ? cap_res : 1, U32);
Branch: 3 branches
BranchTrueFalseTotal
Newx(s->res_key, cap_res ? cap_res : 1, U32); 867 0 867
Newx(s->res_key, cap_res ? cap_res : 1, U32); 0 867 867
Newx(s->res_key, cap_res ? cap_res : 1, U32); 867 0 867
5193 867 ▶ Newx(s->chain_hv, n_chain, HV *);
Branch: 1 branch
BranchTrueFalseTotal
Newx(s->chain_hv, n_chain, HV *); 0 867 867
5194 867 ▶ Newx(s->chain_first, n_chain, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(s->chain_first, n_chain, UV); 0 867 867
5195 867 ▶ Newx(s->chain_last, n_chain, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(s->chain_last, n_chain, UV); 0 867 867
5196  
5197 1993 ▶ for (ci = 0; ci < nci; ci++) {
Branch: 1 branch
BranchTrueFalseTotal
for (ci = 0; ci < nci; ci++) { 1126 867 1993
5198 1126 SV **cs = av_fetch(order, ci, 0);
5199 HV *c;
5200 AV *ro;
5201 HV *residues;
5202 SSize_t ri, nri;
5203 1126 ▶ if (!cs || !*cs || !SvOK(*cs)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!cs || !*cs || !SvOK(*cs)) continue; 1126 0 1126
if (!cs || !*cs || !SvOK(*cs)) continue; 1126 0 1126
if (!cs || !*cs || !SvOK(*cs)) continue; 0 1126 1126
5204 1126 c = hvf_ent_hv(aTHX_ chains, *cs);
5205 1126 ▶ if (!c) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!c) continue; 0 1126 1126
5206 1126 s->chain_hv[s->n_chain] = c;
5207 1126 s->chain_first[s->n_chain] = s->n_res;
5208 1126 ro = hvf_av(aTHX_ c, "residue_order", 13);
5209 1126 residues = hvf_hv(aTHX_ c, "residues", 8);
5210 1126 ▶ nri = (ro && residues) ? av_len(ro) + 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
nri = (ro && residues) ? av_len(ro) + 1 : 0; 1126 0 1126
nri = (ro && residues) ? av_len(ro) + 1 : 0; 1126 0 1126
5211 19165 ▶ for (ri = 0; ri < nri; ri++) {
Branch: 1 branch
BranchTrueFalseTotal
for (ri = 0; ri < nri; ri++) { 18039 1126 19165
5212 18039 SV **rs = av_fetch(ro, ri, 0);
5213 HV *r;
5214 18039 ▶ if (!rs || !*rs || !SvOK(*rs)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!rs || !*rs || !SvOK(*rs)) continue; 18039 0 18039
if (!rs || !*rs || !SvOK(*rs)) continue; 18039 0 18039
if (!rs || !*rs || !SvOK(*rs)) continue; 0 18039 18039
5215 18039 r = hvf_ent_hv(aTHX_ residues, *rs);
5216 18039 ▶ if (!r || s->n_res >= cap_res) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!r || s->n_res >= cap_res) continue; 18039 0 18039
if (!r || s->n_res >= cap_res) continue; 0 18039 18039
5217 18039 set_add_residue(aTHX_ s, r, probe, coords_only, &cap_atom);
5218 }
5219 1126 s->chain_last[s->n_chain] = s->n_res;
5220 1126 s->n_chain++;
5221 }
5222 /*No atom hashes at all, in a structure whose chains count atom records:
5223 that is atoms => 0, and the only thing wrong with it is that nobody said so.
5224 A structure whose atoms are all there but have no readable coordinates is a
5225 different thing and is not an error -- t/errors.t reads one -- so the test is
5226 on the names the residues listed, not on the positions that came back.*/
5227 867 ▶ if (s->n_atom_slots == 0 && cap_atom > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (s->n_atom_slots == 0 && cap_atom > 0) { 4 863 867
if (s->n_atom_slots == 0 && cap_atom > 0) { 4 0 4
5228 4 set_free(aTHX_ s);
5229 4 croak("%s: this structure has no atom hashes to work from; "
5230 "read it again without atoms => 0", who);
5231 }
5232 //give the over-allocation back before the calculations pile their own
5233 //working arrays on top of it
5234 863 ▶ if (s->n_atom < cap_atom && s->n_atom > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (s->n_atom < cap_atom && s->n_atom > 0) { 222 641 863
if (s->n_atom < cap_atom && s->n_atom > 0) { 219 3 222
5235 219 ▶ Renew(s->x, s->n_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->x, s->n_atom, NV); 0 219 219
5236 219 ▶ Renew(s->y, s->n_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->y, s->n_atom, NV); 0 219 219
5237 219 ▶ Renew(s->z, s->n_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->z, s->n_atom, NV); 0 219 219
5238 219 ▶ if (!coords_only) {
Branch: 1 branch
BranchTrueFalseTotal
if (!coords_only) { 202 17 219
5239 202 ▶ Renew(s->rad, s->n_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->rad, s->n_atom, NV); 0 202 202
5240 202 ▶ Renew(s->mass, s->n_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->mass, s->n_atom, NV); 0 202 202
5241 202 Renew(s->apolar, s->n_atom, unsigned char);
5242 }
5243 219 ▶ Renew(s->atom_hv, s->n_atom, HV *);
Branch: 1 branch
BranchTrueFalseTotal
Renew(s->atom_hv, s->n_atom, HV *); 0 219 219
5244 }
5245 }
5246  
5247 //which cell along one axis a coordinate falls in, clamped to the grid. Written
5248 //so that no non-finite value is ever cast to a UV, which is undefined
5249 //behaviour: a NaN fails `d > 0.0' and an infinity fails `k < n'.
5250 3037812 static UV grid_axis(NV d, NV cell, UV n){
5251 NV k;
5252 3037812 ▶ if (n <= 1) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n <= 1) return 0; 146896 2890916 3037812
5253 2890916 ▶ if (!(d > 0.0)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!(d > 0.0)) return 0; 94162 2796754 2890916
5254 2796754 k = d / cell;
5255 2796754 ▶ if (!(k < (NV)n)) return n - 1;
Branch: 1 branch
BranchTrueFalseTotal
if (!(k < (NV)n)) return n - 1; 11538 2785216 2796754
5256 2785216 return (UV)k;//truncation is floor here: k is positive
5257 }
5258  
5259 //qsort()'s order for NVs; grid_trim() hands it finite values only
5260 43660 static int nv_cmp(const void *pa, const void *pb){
5261 43660 const NV a = *(const NV *)pa, b = *(const NV *)pb;
5262 43660 return (a > b) - (a < b);
5263 }
5264  
5265 /*grid_trim() -- the box over the bulk of the points, leaving out the few far
5266 from the rest.
5267  
5268 grid_build() caps the cells at eight per point, and a box much larger than the
5269 structure meets the cap by widening the cells. One far point is enough to make
5270 the box that: a zinc at (9999.999, 9999.999, 9999.999) beside 4fqr's 90,792 atoms
5271 (PDBbind v2020) widened the cells to 110 A, made every atom a neighbour of
5272 thousands, and took structure_sasa() of it from 1.4 s to 29.5 s. So where the
5273 box over every point would need wider cells, the box is taken per axis from the
5274 k-th smallest coordinate to the k-th largest, k a hundredth of the points, and
5275 grid_axis() puts the points outside it in the end cells, as it already does a
5276 non-finite one.
5277  
5278 That changes no answer, only the time and the order a search meets the points
5279 in -- which is the order a list of pairs found by walking the grid comes out
5280 in, and structure_contacts() and the rest promise none. Clamping into the box
5281 never moves two coordinates further apart, so two points within a cell's width
5282 of each other still land in the same or adjacent cells, which are the ones
5283 every search here looks in; a point outside the box is compared with what lies
5284 near the box's edge, and the distance test, not the cell, is what decides
5285 whether it is a neighbour.
5286  
5287 lo and hi hold the box over every finite point on the way in and the trimmed one
5288 on the way out, x then y then z. x, y and z are not CSP_RESTRICT: each is read
5289 again through the axis pointer the loop below takes from it. Sorted with
5290 qsort() rather than selected, because this runs only for a box the cap has
5291 already had to widen, which in a real structure is a sparse set of a few
5292 hundred points at most -- ring or base centroids -- and in a whole structure
5293 only one with a point far from the rest.*/
5294 18 static void grid_trim(pTHX_ const NV *x, const NV *y, const NV *z, UV n,
5295 NV *CSP_RESTRICT lo, NV *CSP_RESTRICT hi)
5296 {
5297 NV *CSP_RESTRICT v;
5298 const NV *axis[3];
5299 18 axis[0] = x; axis[1] = y; axis[2] = z;
5300 18 ▶ Newx(v, n, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(v, n, NV); 0 18 18
5301 72 ▶ for (unsigned short a = 0; a < 3; a++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short a = 0; a < 3; a++) { 54 18 72
5302 54 UV m = 0, k;
5303 6993 ▶ for (UV i = 0; i < n; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (UV i = 0; i < n; i++) 6939 54 6993
5304 6939 ▶ if (nv_is_finite(x[i]) && nv_is_finite(y[i]) && nv_is_finite(z[i]))
Branch: 3 branches
BranchTrueFalseTotal
if (nv_is_finite(x[i]) && nv_is_finite(y[i]) && nv_is_finite(z[i])) 6936 3 6939
if (nv_is_finite(x[i]) && nv_is_finite(y[i]) && nv_is_finite(z[i])) 6936 0 6936
if (nv_is_finite(x[i]) && nv_is_finite(y[i]) && nv_is_finite(z[i])) 6936 0 6936
5305 6936 v[m++] = axis[a][i];
5306 54 k = m / 100;
5307 54 ▶ if (k == 0) continue;//too few points to leave any out
Branch: 1 branch
BranchTrueFalseTotal
if (k == 0) continue;//too few points to leave any out 42 12 54
5308 12 qsort(v, (size_t)m, sizeof(NV), nv_cmp);
5309 12 lo[a] = v[k];
5310 12 hi[a] = v[m - 1 - k];
5311 }
5312 18 Safefree(v);
5313 18 }
5314  
5315 4827 static void grid_build(pTHX_ cell_grid *CSP_RESTRICT g, const NV *CSP_RESTRICT x, const NV *CSP_RESTRICT y, const NV *CSP_RESTRICT z, UV n, NV cut){
5316 4827 NV xmax, ymax, zmax, cells = 0.0;
5317 UV ncell, c;
5318 4827 bool have_box = 0;
5319 4827 Zero(g, 1, cell_grid);
5320 4827 ▶ if (n == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) return; 0 4827 4827
5321 /*The box is taken over the finite points only. str2nv() hands a field
5322 that says nan or inf through as the NV it names, and one such point
5323 anywhere in the set made the extent non-finite, so the loop below never
5324 settled and every point went into one cell: a whole-structure surface
5325 quadratic in the atoms. grid_axis() already puts a non-finite point in an
5326 end cell, where it is found as nobody's neighbour: every distance to it
5327 compares false, and every search is written as the test a neighbour passes,
5328 so false is no. x - x is 0 for a finite x and NaN otherwise, which is
5329 the test without isfinite(), a C99 macro, or Perl_isinf(), which on perls
5330 before 5.22 can route through a Perl_fp_class() block that never compiled.*/
5331 4827 g->x0 = g->y0 = g->z0 = xmax = ymax = zmax = 0.0;
5332 346556 ▶ for (UV i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV i = 0; i < n; i++) { 341729 4827 346556
5333 341729 ▶ if (!(x[i] - x[i] == 0.0 && y[i] - y[i] == 0.0 && z[i] - z[i] == 0.0)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!(x[i] - x[i] == 0.0 && y[i] - y[i] == 0.0 && z[i] - z[i] == 0.0)) continue; 341713 16 341729
if (!(x[i] - x[i] == 0.0 && y[i] - y[i] == 0.0 && z[i] - z[i] == 0.0)) continue; 341713 0 341713
if (!(x[i] - x[i] == 0.0 && y[i] - y[i] == 0.0 && z[i] - z[i] == 0.0)) continue; 0 341713 341713
5334 341713 ▶ if (!have_box) {
Branch: 1 branch
BranchTrueFalseTotal
if (!have_box) { 4821 336892 341713
5335 4821 g->x0 = xmax = x[i]; g->y0 = ymax = y[i]; g->z0 = zmax = z[i];
5336 4821 have_box = 1;
5337 4821 continue;
5338 }
5339 336892 ▶ if (x[i] < g->x0) g->x0 = x[i]; else if (x[i] > xmax) xmax = x[i];
Branch: 2 branches
BranchTrueFalseTotal
if (x[i] < g->x0) g->x0 = x[i]; else if (x[i] > xmax) xmax = x[i]; 24859 312033 336892
if (x[i] < g->x0) g->x0 = x[i]; else if (x[i] > xmax) xmax = x[i]; 46292 265741 312033
5340 336892 ▶ if (y[i] < g->y0) g->y0 = y[i]; else if (y[i] > ymax) ymax = y[i];
Branch: 2 branches
BranchTrueFalseTotal
if (y[i] < g->y0) g->y0 = y[i]; else if (y[i] > ymax) ymax = y[i]; 20528 316364 336892
if (y[i] < g->y0) g->y0 = y[i]; else if (y[i] > ymax) ymax = y[i]; 34805 281559 316364
5341 336892 ▶ if (z[i] < g->z0) g->z0 = z[i]; else if (z[i] > zmax) zmax = z[i];
Branch: 2 branches
BranchTrueFalseTotal
if (z[i] < g->z0) g->z0 = z[i]; else if (z[i] > zmax) zmax = z[i]; 20313 316579 336892
if (z[i] < g->z0) g->z0 = z[i]; else if (z[i] > zmax) zmax = z[i]; 49359 267220 316579
5342 }
5343 4827 ▶ g->cell = (cut > 0.0) ? cut : 1.0;
Branch: 1 branch
BranchTrueFalseTotal
g->cell = (cut > 0.0) ? cut : 1.0; 4827 0 4827
5344 /*A box the cells would have to be widened for, which a few far points can
5345 make of one that is otherwise compact: see grid_trim(). The trimmed box is
5346 taken only where it is at least eight times smaller in cells, which takes a
5347 point far outside the rest. A sparse set needs the widening without one --
5348 the ring centroids of a large protein, a few hundred points through its
5349 whole volume -- and trimming a hundredth of them off each end moved its
5350 grid enough to list the same pi-stacked pairs in another order: 50 of 1,012
5351 entries of PDBbind v2020 did, with grid_trim() taken on any box the cap
5352 widened. At eight times, none does, and 4fqr with a zinc at 9999.999 is
5353 trimmed by a factor of a million.*/
5354 4827 ▶ if (have_box) {
Branch: 1 branch
BranchTrueFalseTotal
if (have_box) { 4821 6 4827
5355 4821 const NV whole = ((xmax - g->x0) / g->cell + 1.0) * ((ymax - g->y0) / g->cell + 1.0)
5356 4821 * ((zmax - g->z0) / g->cell + 1.0);
5357 4821 ▶ if (whole > (NV)n * 8.0 + 1024.0) {
Branch: 1 branch
BranchTrueFalseTotal
if (whole > (NV)n * 8.0 + 1024.0) { 18 4803 4821
5358 NV lo[3], hi[3];
5359 18 lo[0] = g->x0; lo[1] = g->y0; lo[2] = g->z0;
5360 18 hi[0] = xmax; hi[1] = ymax; hi[2] = zmax;
5361 18 grid_trim(aTHX_ x, y, z, n, lo, hi);
5362 18 if (((hi[0] - lo[0]) / g->cell + 1.0) * ((hi[1] - lo[1]) / g->cell + 1.0)
5363 18 ▶ * ((hi[2] - lo[2]) / g->cell + 1.0) * 8.0 < whole) {
Branch: 1 branch
BranchTrueFalseTotal
* ((hi[2] - lo[2]) / g->cell + 1.0) * 8.0 < whole) { 4 14 18
5364 4 g->x0 = lo[0]; g->y0 = lo[1]; g->z0 = lo[2];
5365 4 xmax = hi[0]; ymax = hi[1]; zmax = hi[2];
5366 }
5367 }
5368 }
5369 /*Widen the cells until there are at most eight per point. Doubling, so a
5370 box a kilometre across settles in a few dozen turns; the counter is there for
5371 the case the extent is not a finite number at all, where the test below can
5372 never come true and the grid falls back to a single cell.*/
5373 {
5374 4827 NV ex = 0.0, ey = 0.0, ez = 0.0;
5375 4843 ▶ for (unsigned short turn = 0; turn < 4096; turn++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short turn = 0; turn < 4096; turn++) { 4843 0 4843
5376 4843 ex = (xmax - g->x0) / g->cell;
5377 4843 ey = (ymax - g->y0) / g->cell;
5378 4843 ez = (zmax - g->z0) / g->cell;
5379 4843 cells = (ex + 1.0) * (ey + 1.0) * (ez + 1.0);
5380 4843 ▶ if (cells <= (NV)n * 8.0 + 1024.0) break;
Branch: 1 branch
BranchTrueFalseTotal
if (cells <= (NV)n * 8.0 + 1024.0) break; 4827 16 4843
5381 16 g->cell *= 2.0;
5382 }
5383 //the cast is safe only under that test, which bounds each extent by the
5384 //cell count it just passed
5385 4827 ▶ if (cells <= (NV)n * 8.0 + 1024.0) {
Branch: 1 branch
BranchTrueFalseTotal
if (cells <= (NV)n * 8.0 + 1024.0) { 4827 0 4827
5386 4827 g->nx = (UV)ex + 1;
5387 4827 g->ny = (UV)ey + 1;
5388 4827 g->nz = (UV)ez + 1;
5389 } else {
5390 0 g->nx = g->ny = g->nz = 1;
5391 }
5392 }
5393 4827 ncell = g->nx * g->ny * g->nz;
5394 4827 ▶ Newxz(g->start, ncell + 1, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(g->start, ncell + 1, UV); 0 4827 4827
5395 4827 ▶ Newx(g->idx, n, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(g->idx, n, UV); 0 4827 4827
5396 346556 ▶ for (UV i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV i = 0; i < n; i++) { 341729 4827 346556
5397 341729 c = (grid_axis(x[i] - g->x0, g->cell, g->nx) * g->ny
5398 341729 + grid_axis(y[i] - g->y0, g->cell, g->ny)) * g->nz
5399 341729 + grid_axis(z[i] - g->z0, g->cell, g->nz);
5400 341729 g->start[c]++;
5401 }
5402 //counting sort: prefix the counts into starts, fill, then shift the ends
5403 //back into starts, which is one array rather than a second cursor one
5404 {
5405 4827 UV run = 0;
5406 301496 ▶ for (c = 0; c < ncell; c++) { UV t = g->start[c]; g->start[c] = run; run += t; }
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < ncell; c++) { UV t = g->start[c]; g->start[c] = run; run += t; } 296669 4827 301496
5407 }
5408 346556 ▶ for (UV i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV i = 0; i < n; i++) { 341729 4827 346556
5409 341729 c = (grid_axis(x[i] - g->x0, g->cell, g->nx) * g->ny
5410 341729 + grid_axis(y[i] - g->y0, g->cell, g->ny)) * g->nz
5411 341729 + grid_axis(z[i] - g->z0, g->cell, g->nz);
5412 341729 g->idx[g->start[c]++] = i;
5413 }
5414 301496 ▶ for (c = ncell; c > 0; c--) g->start[c] = g->start[c - 1];
Branch: 1 branch
BranchTrueFalseTotal
for (c = ncell; c > 0; c--) g->start[c] = g->start[c - 1]; 296669 4827 301496
5415 4827 g->start[0] = 0;
5416 }
5417  
5418 /*sasa_sphere() -- n points spread over the unit sphere by the golden section
5419 spiral, which is what mdtraj's kernel uses.
5420  
5421 The spiral is cheap and very nearly even, which is all the algorithm needs: the
5422 area an atom contributes is 4*pi*r^2 times the fraction of its points that no
5423 other atom covers, and that fraction is only as good as the points are evenly
5424 spread. mdtraj's own note says as much -- points that repelled each other to an
5425 energy minimum would be better and would cost more than the rest of the
5426 calculation*/
5427 1612 static void sasa_sphere(NV *CSP_RESTRICT pts, UV n){
5428 1612 const NV inc = CSP_PI * (3.0 - nv_sqrt((NV)5.0));
5429 1612 const NV offset = 2.0 / (NV)n;
5430 810351 ▶ for (UV i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV i = 0; i < n; i++) { 808739 1612 810351
5431 808739 NV y = (NV)i * offset - 1.0 + offset / 2.0;
5432 808739 NV t = 1.0 - y * y;
5433 808739 ▶ NV r = (t > 0.0) ? nv_sqrt(t) : 0.0;//the half-offset keeps |y| < 1; this is in
Branch: 1 branch
BranchTrueFalseTotal
NV r = (t > 0.0) ? nv_sqrt(t) : 0.0;//the half-offset keeps |y| < 1; this is in 808739 0 808739
5434 808739 NV phi = (NV)i * inc;//case rounding at n = 1 says otherwise
5435 808739 pts[3 * i] = nv_cos(phi) * r;
5436 808739 pts[3 * i + 1] = y;
5437 808739 pts[3 * i + 2] = nv_sin(phi) * r;
5438 }
5439 1612 }
5440  
5441 /*sasa_bins_build() -- the sphere points in bins by direction, so that a bin
5442 every point of which is covered can be passed over without trying any of them.
5443  
5444 A neighbour k at distance d from atom i covers the point of i's sphere in
5445 direction u when |ri u - v| < rk, v being the vector from i to k, and that is
5446 the cap of every u within an angle theta of v's direction, where
5447 cos(theta) = (ri^2 + d^2 - rk^2) / (2 ri d). A bin whose points all lie within
5448 rho of its centre is inside that cap whole when its centre is within
5449 theta - rho of v, and then every point in it is covered and acc gains nothing
5450 from it -- which is what trying its points one at a time would have found, so
5451 the area is the same NV, bit for bit. That was checked rather than argued: over
5452 a 56-structure spread of PDBbind v2020 (every 250th entry, 4fqr, and the PDB
5453 files in t/data), every atom, chain and total surface printed as %.17g compares
5454 byte for byte with the kernel before the bins, at the default 960 points, at 200,
5455 and at 50 with a 1.2 A probe.
5456  
5457 It is the buried points that cost. Most of a structure's sphere points are
5458 covered -- 95% of 4fqr's -- and before the bins each was found covered by
5459 trying, 1.2 neighbours a point on average; with them, the points of 4fqr's
5460 atoms that are tried at all are the ones in bins no single neighbour covers.
5461 The spread's surfaces went from 5.89 s to 2.08 s, best of three, and at 200
5462 points from 1.98 s to 1.41 s.
5463  
5464 SASA_BINS is 48 bins, which over 960 points hold 17 to 23 points each and
5465 reach 0.27 to 0.37 radian from their centres. 48 was the fastest of 32, 48,
5466 60, 64, 96 and 128 on the spread; more, smaller bins are covered whole more
5467 often and cost more to ask about. Below SASA_BIN_MIN_POINTS, twice as many
5468 points as bins, they are not built: at 50 points, one to a bin, the spread took
5469 1.11 s with them and 1.09 s without, and at 100 points 1.27 s against 1.39 s.
5470  
5471 SASA_BIN_TRY is how many neighbours are asked whether they cover a bin whole:
5472 the one that covered the bin before it, and then the nearest, which have the
5473 largest caps. A bin only a further neighbour covers is walked point by point,
5474 and is no less right for it. 12 was as fast as asking all of them on the
5475 spread and faster at 200 points (1.41 s against 1.46 s).
5476  
5477 SASA_BIN_MARGIN is added to every bin's radius, so that a bin is only called
5478 covered where the exact test in the kernel, which is computed in floating
5479 point, would cover every point in it too. A coordinate a hundred angstrom out
5480 carries about 1e-14 A of rounding on a double, which moves the rim of a cap by
5481 that over ri sin(theta); a cap only covers a bin whole when theta is more than
5482 rho, a quarter of a radian at the least, so the rim moves by 1e-13 radian or
5483 so. 1e-4 radian is nine orders of magnitude to spare, and against bins a
5484 quarter of a radian across it costs nothing that can be measured.*/
5485 #define SASA_BINS 48
5486 #define SASA_BIN_MIN_POINTS (2 * SASA_BINS)
5487 #define SASA_BIN_TRY 12
5488 #define SASA_BIN_MARGIN 1e-4
5489  
5490 typedef struct {
5491 UV nbin;
5492 NV *centre;//3 per bin, a unit vector
5493 NV *cos_r, *sin_r;//of the bin's angular radius plus SASA_BIN_MARGIN
5494 UV *first;//nbin + 1 offsets into pts
5495 NV *pts;//the sphere points, 3 each, grouped by bin
5496 } sasa_bins;
5497  
5498 806 static void sasa_bins_free(pTHX_ sasa_bins *CSP_RESTRICT b)
5499 {
5500 806 Safefree(b->centre); Safefree(b->cos_r); Safefree(b->sin_r);
5501 806 Safefree(b->first); Safefree(b->pts);
5502 806 Zero(b, 1, sasa_bins);
5503 806 }
5504  
5505 806 static void sasa_bins_build(pTHX_ sasa_bins *CSP_RESTRICT b, const NV *CSP_RESTRICT pts, UV npts)
5506 {
5507 806 ▶ UV nb = npts >= SASA_BIN_MIN_POINTS ? SASA_BINS : 1, j, q;
Branch: 1 branch
BranchTrueFalseTotal
UV nb = npts >= SASA_BIN_MIN_POINTS ? SASA_BINS : 1, j, q; 804 2 806
5508 806 UV *CSP_RESTRICT of = NULL, *CSP_RESTRICT at = NULL;
5509 806 NV *CSP_RESTRICT mindot = NULL;
5510 806 b->nbin = nb;
5511 806 ▶ Newx(b->centre, 3 * nb, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(b->centre, 3 * nb, NV); 0 806 806
5512 806 ▶ Newx(b->cos_r, nb, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(b->cos_r, nb, NV); 0 806 806
5513 806 ▶ Newx(b->sin_r, nb, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(b->sin_r, nb, NV); 0 806 806
5514 806 ▶ Newxz(b->first, nb + 1, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(b->first, nb + 1, UV); 0 806 806
5515 806 ▶ Newx(b->pts, 3 * (npts ? npts : 1), NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(b->pts, 3 * (npts ? npts : 1), NV); 806 0 806
Newx(b->pts, 3 * (npts ? npts : 1), NV); 0 806 806
Newx(b->pts, 3 * (npts ? npts : 1), NV); 806 0 806
5516 806 ▶ Newx(of, npts ? npts : 1, UV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(of, npts ? npts : 1, UV); 806 0 806
Newx(of, npts ? npts : 1, UV); 0 806 806
Newx(of, npts ? npts : 1, UV); 806 0 806
5517 806 ▶ Newx(at, nb, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(at, nb, UV); 0 806 806
5518 806 ▶ Newx(mindot, nb, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(mindot, nb, NV); 0 806 806
5519 806 sasa_sphere(b->centre, nb);
5520 39400 ▶ for (q = 0; q < nb; q++) mindot[q] = 1.0;
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < nb; q++) mindot[q] = 1.0; 38594 806 39400
5521 //each point to the bin whose centre is nearest it
5522 770951 ▶ for (j = 0; j < npts; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < npts; j++) { 770145 806 770951
5523 770145 UV best = 0;
5524 770145 NV bd = -2.0;
5525 37735930 ▶ for (q = 0; q < nb; q++) {
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < nb; q++) { 36965785 770145 37735930
5526 36965785 const NV dot = b->centre[3 * q] * pts[3 * j] + b->centre[3 * q + 1] * pts[3 * j + 1]
5527 36965785 + b->centre[3 * q + 2] * pts[3 * j + 2];
5528 36965785 ▶ if (dot > bd) { bd = dot; best = q; }
Branch: 1 branch
BranchTrueFalseTotal
if (dot > bd) { bd = dot; best = q; } 5459847 31505938 36965785
5529 }
5530 770145 of[j] = best;
5531 770145 b->first[best + 1]++;
5532 770145 ▶ if (bd < mindot[best]) mindot[best] = bd;
Branch: 1 branch
BranchTrueFalseTotal
if (bd < mindot[best]) mindot[best] = bd; 88370 681775 770145
5533 }
5534 39400 ▶ for (q = 0; q < nb; q++) b->first[q + 1] += b->first[q];
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < nb; q++) b->first[q + 1] += b->first[q]; 38594 806 39400
5535 39400 ▶ for (q = 0; q < nb; q++) at[q] = b->first[q];
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < nb; q++) at[q] = b->first[q]; 38594 806 39400
5536 //in spiral order within each bin, so neighbouring points stay neighbours
5537 770951 ▶ for (j = 0; j < npts; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < npts; j++) { 770145 806 770951
5538 770145 const UV w = at[of[j]]++;
5539 770145 b->pts[3 * w] = pts[3 * j];
5540 770145 b->pts[3 * w + 1] = pts[3 * j + 1];
5541 770145 b->pts[3 * w + 2] = pts[3 * j + 2];
5542 }
5543 39400 ▶ for (q = 0; q < nb; q++) {
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < nb; q++) { 38594 806 39400
5544 38594 ▶ const NV c = mindot[q] > 1.0 ? 1.0 : mindot[q] < -1.0 ? -1.0 : mindot[q];
Branch: 2 branches
BranchTrueFalseTotal
const NV c = mindot[q] > 1.0 ? 1.0 : mindot[q] < -1.0 ? -1.0 : mindot[q]; 0 38594 38594
const NV c = mindot[q] > 1.0 ? 1.0 : mindot[q] < -1.0 ? -1.0 : mindot[q]; 0 38594 38594
5545 38594 const NV rho = nv_acos(c) + SASA_BIN_MARGIN;
5546 //a bin reaching round the back of the sphere prunes nothing
5547 38594 ▶ if (rho >= CSP_PI) { b->cos_r[q] = -1.0; b->sin_r[q] = 0.0; }
Branch: 1 branch
BranchTrueFalseTotal
if (rho >= CSP_PI) { b->cos_r[q] = -1.0; b->sin_r[q] = 0.0; } 0 38594 38594
5548 38594 else { b->cos_r[q] = nv_cos(rho); b->sin_r[q] = nv_sin(rho); }
5549 }
5550 806 Safefree(of); Safefree(at); Safefree(mindot);
5551 806 }
5552  
5553 /*What the kernel is asked to do besides the surface itself, or NULL for the
5554 plain run. All three exist for the interface pass below, which runs the kernel
5555 again over each chain alone: an atom whose every neighbour is in its own chain
5556 has the same surface either way, so the whole-structure run marks the ones that
5557 have a neighbour outside it and the per-chain runs compute those and leave the
5558 rest of the array as they found it. Over 60 entries of PDBbind v2020 that took
5559 the pass from 5.7 seconds to 0.75.*/
5560 typedef struct {
5561 //one chain index per atom, so a neighbour can be asked which chain it is in
5562 const UV *CSP_RESTRICT chain_of;
5563 //set to 1 for an atom that has a neighbour outside its own chain
5564 unsigned char *CSP_RESTRICT cross;
5565 //when given, an atom whose flag is 0 is left alone: area[i] is not written
5566 const unsigned char *CSP_RESTRICT only;
5567 } sasa_aux;
5568  
5569 /*How long a neighbour list may be and still be worth sorting. 141 is the
5570 longest over a 405-structure spread of PDBbind v2020 and the low tens is the
5571 ordinary length, so 512 is three and a half times anything a real structure
5572 produced, and a list that short is sorted for far less than the thousand sphere
5573 points the order goes on to shorten.
5574  
5575 The cap is not tidiness. The sort is quadratic in the length of the list, and
5576 nothing about a *file* bounds that length: 3,000 atoms scattered through a 6 A
5577 ball -- which is what an unmodelled ligand or a badly converted model looks
5578 like -- makes every atom a neighbour of nearly every other, and the surface of
5579 it goes from 0.12 s to 8.3 s with the sort left uncapped. With the cap it is
5580 0.10 s, and the answer is the same NV in all three cases.*/
5581 #define SASA_SORT_MAX 512
5582  
5583 /*sasa_open() -- how many of points first..last-1 of atom i's sphere no
5584 neighbour covers. The rotation is mdtraj's: consecutive points are close
5585 together, so the neighbour that covered the last one is the one most likely to
5586 cover this one, and the scan starts there. *k_closest carries it from one call
5587 to the next.*/
5588 1610397 static UV sasa_open(const NV *CSP_RESTRICT pts, UV first, UV last, NV xi, NV yi, NV zi, NV ri, const NV *CSP_RESTRICT nx, const NV *CSP_RESTRICT ny, const NV *CSP_RESTRICT nz, const NV *CSP_RESTRICT nr2, UV n_nbr, UV *CSP_RESTRICT k_closest) {
5589 1610397 UV acc = 0, kc = *k_closest;
5590 33864096 ▶ for (UV j = first; j < last; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV j = first; j < last; j++) { 32253699 1610397 33864096
5591 32253699 const NV px = xi + ri * pts[3 * j];
5592 32253699 const NV py = yi + ri * pts[3 * j + 1];
5593 32253699 const NV pz = zi + ri * pts[3 * j + 2];
5594 32253699 bool open = TRUE;
5595 292828229 ▶ for (UV k = 0; k < n_nbr; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV k = 0; k < n_nbr; k++) { 280952776 11875453 292828229
5596 280952776 UV kp = kc + k;
5597 NV dx, dy, dz;
5598 280952776 ▶ if (kp >= n_nbr) kp -= n_nbr;
Branch: 1 branch
BranchTrueFalseTotal
if (kp >= n_nbr) kp -= n_nbr; 49378474 231574302 280952776
5599 280952776 dx = px - nx[kp]; dy = py - ny[kp]; dz = pz - nz[kp];
5600 280952776 ▶ if (dx * dx + dy * dy + dz * dz < nr2[kp]) {
Branch: 1 branch
BranchTrueFalseTotal
if (dx * dx + dy * dy + dz * dz < nr2[kp]) { 20378246 260574530 280952776
5601 20378246 kc = kp;
5602 20378246 open = FALSE;
5603 20378246 break;
5604 }
5605 }
5606 32253699 ▶ if (open) acc++;
Branch: 1 branch
BranchTrueFalseTotal
if (open) acc++; 11875453 20378246 32253699
5607 }
5608 1610397 *k_closest = kc;
5609 1610397 return acc;
5610 }
5611  
5612 /*sasa_compute() -- Shrake and Rupley, as mdtraj computes it.
5613  
5614 Each atom gets a sphere of npts points at its van der Waals radius plus the
5615 probe radius; a point is accessible when no other atom's sphere covers it; the
5616 atom's area is 4*pi*r^2 times the accessible fraction.
5617  
5618 Three departures from a literal transcription of mdtraj's kernel, none of
5619 which changes an answer:
5620  
5621 The neighbour search is the grid above rather than a scan of every other atom.
5622  
5623 The points are tried a bin at a time, and a bin that one neighbour covers whole
5624 is not tried at all; see sasa_bins_build().
5625  
5626 The distance test is squared -- d2 < (ri+rj)^2 rather than sqrt(d2) < ri+rj --
5627 which saves a square root per pair. The two differ only for a pair whose
5628 separation is within an ulp of the sum of their radii, and a neighbour at
5629 exactly that separation covers none of the other's points: its sphere touches
5630 at one point and covers an open region of measure zero around it.
5631  
5632 The rotation of the neighbour list is mdtraj's and is kept: consecutive points
5633 on the spiral are close together, so the atom that covered the last one is the
5634 one most likely to cover this one, and starting the scan there rather than at
5635 the beginning is most of the kernel's speed.
5636  
5637 The list is also sorted by how near the neighbour is before the points are
5638 walked, which the rotation does not make redundant: the rotation says where to
5639 start, the order says what to try next, and a nearer neighbour hides more of
5640 the sphere and so is likelier to end the scan. Only which neighbour is found
5641 first changes -- acc counts the points that no neighbour covers at all -- so
5642 the area is the same NV to the last bit. That is what was checked rather than
5643 argued: over a 60-structure spread of PDBbind v2020, all 369,621 atom, residue
5644 and chain surfaces printed as %.17g compare byte for byte, and the surface of
5645 40 of them goes from 4.64 s to 4.24 s, best of three.
5646  
5647 The neighbours are copied out of the coordinate arrays rather than kept as
5648 indices into them, with the square of each one's radius worked out while it is
5649 being copied. The innermost loop is the whole cost of the surface -- it runs
5650 once per sphere point per neighbour, which over a structure is billions of
5651 times -- and as indices each turn of it was four loads scattered across four
5652 arrays by a number the compiler cannot predict, plus a multiply to square a
5653 radius that does not change. Copied, it is four sequential loads and no
5654 multiply. The arithmetic is identical: ra * ra computed once per neighbour is
5655 the same NV as ra * ra computed once per point.
5656  
5657 keep, when it is given, receives the neighbour grid the run was made with, and
5658 the caller frees it; otherwise it is freed here.*/
5659 1672 static void sasa_kernel(pTHX_ const NV *CSP_RESTRICT x, const NV *CSP_RESTRICT y,
5660 const NV *CSP_RESTRICT z, const NV *CSP_RESTRICT rad, UV n,
5661 const sasa_bins *CSP_RESTRICT bins, UV npts, NV *CSP_RESTRICT area,
5662 const sasa_aux *CSP_RESTRICT aux, cell_grid *CSP_RESTRICT keep)
5663 {
5664  
5665 1672 ▶ if (n == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) return; 0 1672 1672
5666 /*the neighbours of the atom being worked on: position and squared radius,
5667 grown by doubling as needed. 64 covers every atom of a protein, where the
5668 neighbour count runs to the low tens, without a single reallocation.*/
5669 1672 NV *CSP_RESTRICT nx = NULL, *CSP_RESTRICT ny = NULL, *CSP_RESTRICT nz = NULL;
5670 1672 NV *CSP_RESTRICT nr2 = NULL, *CSP_RESTRICT nd2 = NULL;
5671 1672 const NV *CSP_RESTRICT pts = bins->pts;
5672 1672 const UV nbin = bins->nbin;
5673 1672 UV nbr_cap = 64;
5674 cell_grid g;
5675 1672 NV rmax = 0.0, constant;
5676 183229 ▶ for (UV i = 0; i < n; i++) if (rad[i] > rmax) rmax = rad[i];
Branch: 2 branches
BranchTrueFalseTotal
for (UV i = 0; i < n; i++) if (rad[i] > rmax) rmax = rad[i]; 4039 177518 181557
for (UV i = 0; i < n; i++) if (rad[i] > rmax) rmax = rad[i]; 181557 1672 183229
5677 1672 grid_build(aTHX_ &g, x, y, z, n, 2.0 * rmax);
5678 1672 ▶ Newx(nx, nbr_cap, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(nx, nbr_cap, NV); 0 1672 1672
5679 1672 ▶ Newx(ny, nbr_cap, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(ny, nbr_cap, NV); 0 1672 1672
5680 1672 ▶ Newx(nz, nbr_cap, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(nz, nbr_cap, NV); 0 1672 1672
5681 1672 ▶ Newx(nr2, nbr_cap, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(nr2, nbr_cap, NV); 0 1672 1672
5682 1672 ▶ Newx(nd2, nbr_cap, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(nd2, nbr_cap, NV); 0 1672 1672
5683 1672 constant = 4.0 * CSP_PI / (NV)npts;
5684  
5685 183229 ▶ for (UV i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV i = 0; i < n; i++) { 181557 1672 183229
5686 181557 const NV xi = x[i], yi = y[i], zi = z[i], ri = rad[i];
5687 181557 UV n_nbr = 0, acc = 0, k_closest = 0;
5688 UV cx, cy, cz, ax0, ax1, ay0, ay1, az0, az1, bx, by, bz;
5689 //an atom the caller has already answered for: area[i] is left as it was
5690 181557 ▶ if (aux && aux->only && !aux->only[i]) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (aux && aux->only && !aux->only[i]) continue; 123365 58192 181557
if (aux && aux->only && !aux->only[i]) continue; 92076 31289 123365
if (aux && aux->only && !aux->only[i]) continue; 67265 24811 92076
5691 114292 cx = grid_axis(xi - g.x0, g.cell, g.nx);
5692 114292 cy = grid_axis(yi - g.y0, g.cell, g.ny);
5693 114292 cz = grid_axis(zi - g.z0, g.cell, g.nz);
5694 114292 ▶ ax0 = cx ? cx - 1 : 0; ax1 = (cx + 1 < g.nx) ? cx + 1 : g.nx - 1;
Branch: 2 branches
BranchTrueFalseTotal
ax0 = cx ? cx - 1 : 0; ax1 = (cx + 1 < g.nx) ? cx + 1 : g.nx - 1; 91059 23233 114292
ax0 = cx ? cx - 1 : 0; ax1 = (cx + 1 < g.nx) ? cx + 1 : g.nx - 1; 102623 11669 114292
5695 114292 ▶ ay0 = cy ? cy - 1 : 0; ay1 = (cy + 1 < g.ny) ? cy + 1 : g.ny - 1;
Branch: 2 branches
BranchTrueFalseTotal
ay0 = cy ? cy - 1 : 0; ay1 = (cy + 1 < g.ny) ? cy + 1 : g.ny - 1; 91568 22724 114292
ay0 = cy ? cy - 1 : 0; ay1 = (cy + 1 < g.ny) ? cy + 1 : g.ny - 1; 103338 10954 114292
5696 114292 ▶ az0 = cz ? cz - 1 : 0; az1 = (cz + 1 < g.nz) ? cz + 1 : g.nz - 1;
Branch: 2 branches
BranchTrueFalseTotal
az0 = cz ? cz - 1 : 0; az1 = (cz + 1 < g.nz) ? cz + 1 : g.nz - 1; 91157 23135 114292
az0 = cz ? cz - 1 : 0; az1 = (cz + 1 < g.nz) ? cz + 1 : g.nz - 1; 99132 15160 114292
5697 422266 ▶ for (bx = ax0; bx <= ax1; bx++)
Branch: 1 branch
BranchTrueFalseTotal
for (bx = ax0; bx <= ax1; bx++) 307974 114292 422266
5698 1150412 ▶ for (by = ay0; by <= ay1; by++)
Branch: 1 branch
BranchTrueFalseTotal
for (by = ay0; by <= ay1; by++) 842438 307974 1150412
5699 3129988 ▶ for (bz = az0; bz <= az1; bz++) {
Branch: 1 branch
BranchTrueFalseTotal
for (bz = az0; bz <= az1; bz++) { 2287550 842438 3129988
5700 2287550 UV c = (bx * g.ny + by) * g.nz + bz;
5701 UV p;
5702 17624414 ▶ for (p = g.start[c]; p < g.start[c + 1]; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = g.start[c]; p < g.start[c + 1]; p++) { 15336864 2287550 17624414
5703 15336864 UV a = g.idx[p];
5704 NV dx, dy, dz, sum, d2;
5705 15336864 ▶ if (a == i) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (a == i) continue; 114292 15222572 15336864
5706 15222572 dx = x[a] - xi; dy = y[a] - yi; dz = z[a] - zi;
5707 15222572 sum = ri + rad[a];
5708 15222572 d2 = dx * dx + dy * dy + dz * dz;
5709 15222572 ▶ if (!(d2 < sum * sum)) continue;//not >=: a NaN distance is no neighbour
Branch: 1 branch
BranchTrueFalseTotal
if (!(d2 < sum * sum)) continue;//not >=: a NaN distance is no neighbour 11075064 4147508 15222572
5710 4147508 ▶ if (n_nbr == nbr_cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (n_nbr == nbr_cap) { 118 4147390 4147508
5711 118 nbr_cap *= 2;
5712 118 ▶ Renew(nx, nbr_cap, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(nx, nbr_cap, NV); 0 118 118
5713 118 ▶ Renew(ny, nbr_cap, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(ny, nbr_cap, NV); 0 118 118
5714 118 ▶ Renew(nz, nbr_cap, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(nz, nbr_cap, NV); 0 118 118
5715 118 ▶ Renew(nr2, nbr_cap, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(nr2, nbr_cap, NV); 0 118 118
5716 118 ▶ Renew(nd2, nbr_cap, NV);
Branch: 1 branch
BranchTrueFalseTotal
Renew(nd2, nbr_cap, NV); 0 118 118
5717 }
5718 4147508 nx[n_nbr] = x[a]; ny[n_nbr] = y[a]; nz[n_nbr] = z[a];
5719 4147508 nr2[n_nbr] = rad[a] * rad[a];
5720 //kept for the sort below, and already worked out for the test above
5721 4147508 nd2[n_nbr] = d2;
5722 4147508 n_nbr++;
5723 //a neighbour in another chain is what makes this atom's surface
5724 //depend on that chain being there
5725 4147508 ▶ if (aux && aux->cross && aux->chain_of[a] != aux->chain_of[i])
Branch: 3 branches
BranchTrueFalseTotal
if (aux && aux->cross && aux->chain_of[a] != aux->chain_of[i]) 1866938 2280570 4147508
if (aux && aux->cross && aux->chain_of[a] != aux->chain_of[i]) 1010614 856324 1866938
if (aux && aux->cross && aux->chain_of[a] != aux->chain_of[i]) 62410 948204 1010614
5726 62410 aux->cross[i] = 1;
5727 }
5728 }
5729 /*nearest neighbour first. An insertion sort and not qsort(): the list
5730 runs to the low tens, where the call through a comparison pointer costs
5731 more than the loop it would be speeding up.
5732  
5733 Skipped above SASA_SORT_MAX, where that sort would be the cost rather than
5734 the saving: it is quadratic in the length of the list, and the length is
5735 bounded by physics only as long as the file describes a structure. A file
5736 that writes thousands of atoms on one coordinate -- an unmodelled ligand
5737 left at the origin -- has no such bound, and there the first neighbour tried
5738 covers every point already, so there is nothing for an order to save.*/
5739 114292 ▶ if (n_nbr <= SASA_SORT_MAX) {
Branch: 1 branch
BranchTrueFalseTotal
if (n_nbr <= SASA_SORT_MAX) { 113563 729 114292
5740 3627880 ▶ for (UV q = 1; q < n_nbr; q++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV q = 1; q < n_nbr; q++) { 3514317 113563 3627880
5741 3514317 const NV kx = nx[q], ky = ny[q], kz = nz[q], kr = nr2[q], kd = nd2[q];
5742 3514317 UV w = q;
5743 38310960 ▶ while (w && nd2[w - 1] > kd) {
Branch: 2 branches
BranchTrueFalseTotal
while (w && nd2[w - 1] > kd) { 37831382 479578 38310960
while (w && nd2[w - 1] > kd) { 34796643 3034739 37831382
5744 34796643 nx[w] = nx[w - 1]; ny[w] = ny[w - 1]; nz[w] = nz[w - 1];
5745 34796643 nr2[w] = nr2[w - 1]; nd2[w] = nd2[w - 1];
5746 34796643 w--;
5747 }
5748 3514317 nx[w] = kx; ny[w] = ky; nz[w] = kz; nr2[w] = kr; nd2[w] = kd;
5749 }
5750 }
5751 /*The bins, where there are any: each is asked whether one of the
5752 nearest neighbours covers it whole, and only the points of those that
5753 are not are tried. The neighbour that covered the last bin is asked
5754 first, as the one that covered the last point is.*/
5755 228417 ▶ if (nbin > 1 && n_nbr > 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (nbin > 1 && n_nbr > 0) { 114204 88 114292
if (nbin > 1 && n_nbr > 0) { 114125 79 114204
5756 114125 const UV kmax = n_nbr < SASA_BIN_TRY ? n_nbr : SASA_BIN_TRY;
5757 NV ncos[SASA_BIN_TRY], nsin[SASA_BIN_TRY], ndist[SASA_BIN_TRY];
5758 114125 UV b, k, k_cov = 0;
5759 1447289 ▶ for (k = 0; k < kmax; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < kmax; k++) { 1333164 114125 1447289
5760 1333164 const NV d = nv_sqrt(nd2[k]);
5761 NV c;
5762 //a neighbour on top of this atom has no direction: it covers
5763 //no bin whole
5764 1333164 ▶ if (d > 0.0) c = (ri * ri + nd2[k] - nr2[k]) / (2.0 * ri * d);
Branch: 1 branch
BranchTrueFalseTotal
if (d > 0.0) c = (ri * ri + nd2[k] - nr2[k]) / (2.0 * ri * d); 1332350 814 1333164
5765 814 else c = 1.0;
5766 1333164 ▶ if (c > 1.0) c = 1.0;
Branch: 1 branch
BranchTrueFalseTotal
if (c > 1.0) c = 1.0; 2 1333162 1333164
5767 1333164 ▶ if (c < -1.0) c = -1.0;
Branch: 1 branch
BranchTrueFalseTotal
if (c < -1.0) c = -1.0; 2 1333162 1333164
5768 1333164 ncos[k] = c;
5769 1333164 nsin[k] = nv_sqrt(1.0 - c * c);
5770 1333164 ndist[k] = d;
5771 }
5772 5592125 ▶ for (b = 0; b < nbin; b++) {
Branch: 1 branch
BranchTrueFalseTotal
for (b = 0; b < nbin; b++) { 5478000 114125 5592125
5773 5478000 const NV bx = bins->centre[3 * b], by = bins->centre[3 * b + 1],
5774 5478000 bz = bins->centre[3 * b + 2];
5775 5478000 const NV cr = bins->cos_r[b], sr = bins->sin_r[b];
5776 5478000 bool whole = FALSE;
5777 38810759 ▶ for (UV q = 0; q <= kmax && !whole; q++) {
Branch: 2 branches
BranchTrueFalseTotal
for (UV q = 0; q <= kmax && !whole; q++) { 37152013 1658746 38810759
for (UV q = 0; q <= kmax && !whole; q++) { 33332759 3819254 37152013
5778 NV dot;
5779 33332759 ▶ k = q ? q - 1 : k_cov;
Branch: 1 branch
BranchTrueFalseTotal
k = q ? q - 1 : k_cov; 27854759 5478000 33332759
5780 33332759 ▶ if (q && k == k_cov) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (q && k == k_cov) continue; 27854759 5478000 33332759
if (q && k == k_cov) continue; 3025535 24829224 27854759
5781 //a cap no wider than the bin cannot hold it
5782 30307224 ▶ if (!(ncos[k] < cr)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(ncos[k] < cr)) continue; 213636 30093588 30307224
5783 30093588 dot = bx * (nx[k] - xi) + by * (ny[k] - yi) + bz * (nz[k] - zi);
5784 //within theta - rho: cos(theta - rho), scaled by d
5785 30093588 ▶ if (dot > ndist[k] * (ncos[k] * cr + nsin[k] * sr)) { whole = TRUE; k_cov = k; }
Branch: 1 branch
BranchTrueFalseTotal
if (dot > ndist[k] * (ncos[k] * cr + nsin[k] * sr)) { whole = TRUE; k_cov = k; } 3867770 26225818 30093588
5786 }
5787 5478000 ▶ if (!whole)
Branch: 1 branch
BranchTrueFalseTotal
if (!whole) 1610230 3867770 5478000
5788 1610230 acc += sasa_open(pts, bins->first[b], bins->first[b + 1], xi, yi, zi, ri,
5789 nx, ny, nz, nr2, n_nbr, &k_closest);
5790 }
5791 } else {
5792 167 acc = sasa_open(pts, 0, npts, xi, yi, zi, ri, nx, ny, nz, nr2, n_nbr, &k_closest);
5793 }
5794 114292 area[i] = (NV)acc * constant * ri * ri;
5795 }
5796 1672 Safefree(nx); Safefree(ny); Safefree(nz); Safefree(nr2); Safefree(nd2);
5797 //handed to the caller who asked to keep it, and freed otherwise
5798 1672 ▶ if (keep) *keep = g;
Branch: 1 branch
BranchTrueFalseTotal
if (keep) *keep = g; 203 1469 1672
5799 1469 else grid_free(aTHX_ &g);
5800 }
5801  
5802 /*sasa_compute() -- the whole structure, and then each chain on its own.
5803  
5804 The second half is what an interface costs: a chain's surface with the rest of
5805 the structure taken away, less the surface it has with the rest of the structure
5806 there, is the area the two bury between them. It is one more kernel run per
5807 chain, and a chain's run touches only that chain's atoms, so all of them
5808 together cost about what the first run cost -- not the number of chains times
5809 it. The chains' atoms are one contiguous run each, which is what makes the
5810 range the kernel takes enough to say which.
5811  
5812 Most of those atoms are not asked twice. An atom's surface is decided by the
5813 atoms whose spheres reach it, and if every one of those is in its own chain then
5814 taking the other chains away changes nothing about it: its isolated area *is*
5815 its area, bit for bit, and computing it again is a thousand sphere points spent
5816 to arrive at the number already in hand. The whole-structure run above marks
5817 the atoms that do have a neighbour in another chain -- the interface and nothing
5818 else, which on the entries benchmarked is a few per cent of a complex -- and the
5819 per-chain runs compute those and copy the rest. What is saved is the sphere
5820 points; the neighbour search still runs for every atom of the chain, because an
5821 interface atom needs its neighbours found.
5822  
5823 keep_grid keeps the whole-structure run's neighbour grid on s instead of freeing
5824 it, for iface_compute(), which asks the same atoms the same question at the same
5825 cutoff. It is asked for only when there is an interface to compute: the grid is
5826 up to nine UVs an atom, which on 4fqr is 6.5 MB held to the end of the walk.*/
5827 613 static void sasa_compute(pTHX_ structset *CSP_RESTRICT s, UV npts, bool want_iface, bool keep_grid){
5828 613 NV *CSP_RESTRICT pts = NULL;
5829 613 UV *CSP_RESTRICT chain_of = NULL;
5830 613 unsigned char *CSP_RESTRICT cross = NULL;
5831 sasa_aux aux;
5832 sasa_bins bins;
5833 UV c, i;
5834 613 ▶ const bool split = want_iface && s->n_chain > 1;
Branch: 2 branches
BranchTrueFalseTotal
const bool split = want_iface && s->n_chain > 1; 610 3 613
const bool split = want_iface && s->n_chain > 1; 202 408 610
5835  
5836 613 ▶ Newxz(s->area, s->n_atom ? s->n_atom : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newxz(s->area, s->n_atom ? s->n_atom : 1, NV); 581 32 613
Newxz(s->area, s->n_atom ? s->n_atom : 1, NV); 0 581 581
Newxz(s->area, s->n_atom ? s->n_atom : 1, NV); 581 32 613
5837 613 ▶ if (s->n_atom == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (s->n_atom == 0) return; 32 581 613
5838 581 ▶ Newx(pts, npts * 3, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(pts, npts * 3, NV); 0 581 581
5839 581 sasa_sphere(pts, npts);
5840 581 sasa_bins_build(aTHX_ &bins, pts, npts);
5841 581 Zero(&aux, 1, sasa_aux);
5842 581 ▶ if (split) {
Branch: 1 branch
BranchTrueFalseTotal
if (split) { 202 379 581
5843 //which chain each atom is in, so that the run below can tell a
5844 //neighbour of its own chain from one of another
5845 202 ▶ Newxz(chain_of, s->n_atom, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(chain_of, s->n_atom, UV); 0 202 202
5846 202 Newxz(cross, s->n_atom, unsigned char);
5847 618 ▶ for (c = 0; c < s->n_chain; c++) {
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < s->n_chain; c++) { 416 202 618
5848 416 UV r0 = s->chain_first[c], r1 = s->chain_last[c];
5849 416 ▶ if (r0 >= r1) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (r0 >= r1) continue; 0 416 416
5850 31705 ▶ for (i = s->res_first[r0]; i < s->res_last[r1 - 1]; i++) chain_of[i] = c;
Branch: 1 branch
BranchTrueFalseTotal
for (i = s->res_first[r0]; i < s->res_last[r1 - 1]; i++) chain_of[i] = c; 31289 416 31705
5851 }
5852 202 aux.chain_of = chain_of;
5853 202 aux.cross = cross;
5854 }
5855 581 ▶ sasa_kernel(aTHX_ s->x, s->y, s->z, s->rad, s->n_atom, &bins, npts, s->area,
Branch: 2 branches
BranchTrueFalseTotal
sasa_kernel(aTHX_ s->x, s->y, s->z, s->rad, s->n_atom, &bins, npts, s->area, 203 378 581
sasa_kernel(aTHX_ s->x, s->y, s->z, s->rad, s->n_atom, &bins, npts, s->area, 202 379 581
5856 split ? &aux : NULL, keep_grid ? &s->grid : NULL);
5857 581 ▶ if (keep_grid) {
Branch: 1 branch
BranchTrueFalseTotal
if (keep_grid) { 203 378 581
5858 //the cutoff the kernel built it at, which is twice the largest radius
5859 203 NV rmax = 0.0;
5860 30907 ▶ for (i = 0; i < s->n_atom; i++) if (s->rad[i] > rmax) rmax = s->rad[i];
Branch: 2 branches
BranchTrueFalseTotal
for (i = 0; i < s->n_atom; i++) if (s->rad[i] > rmax) rmax = s->rad[i]; 682 30022 30704
for (i = 0; i < s->n_atom; i++) if (s->rad[i] > rmax) rmax = s->rad[i]; 30704 203 30907
5861 203 s->grid_cut = 2.0 * rmax;
5862 }
5863  
5864 581 ▶ if (split) {
Branch: 1 branch
BranchTrueFalseTotal
if (split) { 202 379 581
5865 sasa_aux only;
5866 202 ▶ Newx(s->alone, s->n_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(s->alone, s->n_atom, NV); 0 202 202
5867 //every atom starts with the surface it has in the whole structure,
5868 //which is the answer for all but the interface
5869 202 ▶ Copy(s->area, s->alone, s->n_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Copy(s->area, s->alone, s->n_atom, NV); 0 202 202
5870 202 Zero(&only, 1, sasa_aux);
5871 618 ▶ for (c = 0; c < s->n_chain; c++) {
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < s->n_chain; c++) { 416 202 618
5872 416 UV r0 = s->chain_first[c], r1 = s->chain_last[c], first, last;
5873 416 ▶ if (r0 >= r1) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (r0 >= r1) continue; 0 416 416
5874 416 first = s->res_first[r0];
5875 416 last = s->res_last[r1 - 1];
5876 416 ▶ if (last <= first) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (last <= first) continue; 0 416 416
5877 416 only.only = cross + first;
5878 416 sasa_kernel(aTHX_ s->x + first, s->y + first, s->z + first,
5879 416 s->rad + first, last - first, &bins, npts, s->alone + first,
5880 &only, NULL);
5881 }
5882 202 Safefree(chain_of);
5883 202 Safefree(cross);
5884 379 ▶ } else if (want_iface) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (want_iface) { 376 3 379
5885 /*One chain buries nothing against anything: its isolated surface is the
5886 surface it already has, and saying so is cheaper than computing it
5887 again to arrive at zero.*/
5888 376 ▶ Newx(s->alone, s->n_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(s->alone, s->n_atom, NV); 0 376 376
5889 376 ▶ Copy(s->area, s->alone, s->n_atom, NV);
Branch: 1 branch
BranchTrueFalseTotal
Copy(s->area, s->alone, s->n_atom, NV); 0 376 376
5890 }
5891 581 sasa_bins_free(aTHX_ &bins);
5892 581 Safefree(pts);
5893 }
5894  
5895 /*Eigenvalues of a symmetric 3x3 matrix, ascending.
5896  
5897 The gyration tensor's three eigenvalues are the principal moments, and the shape
5898 descriptors below are all built out of them. numpy reaches for LAPACK's
5899 eigvalsh here; this is the cyclic Jacobi method, which for a 3x3 is a handful of
5900 plane rotations and needs nothing linked in.
5901  
5902 Jacobi rather than the closed form. A symmetric 3x3's eigenvalues can be
5903 written with an arccosine, and that expression loses most of its digits when two
5904 of the three are close -- which for a globular structure, whose tensor is nearly
5905 isotropic, is the ordinary case rather than the awkward one. Jacobi is
5906 backward-stable and converges quadratically; the sweep count below is a bound
5907 that is never reached in practice, not a tuning parameter.*/
5908 661 static void sym3_eigenvalues(const NV m[3][3], NV *CSP_RESTRICT out){
5909 NV a[3][3];
5910 unsigned short sweep, p, q, i;
5911 2644 ▶ for (p = 0; p < 3; p++)
Branch: 1 branch
BranchTrueFalseTotal
for (p = 0; p < 3; p++) 1983 661 2644
5912 7932 ▶ for (q = 0; q < 3; q++)
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < 3; q++) 5949 1983 7932
5913 5949 a[p][q] = m[p][q];
5914 /*Twelve sweeps: each annihilates all three off-diagonal entries, and the
5915 classical bound for a 3x3 is met in five or six. The loop leaves early on
5916 any matrix that is already diagonal to working precision.*/
5917 2326 ▶ for (sweep = 0; sweep < 12; sweep++) {
Branch: 1 branch
BranchTrueFalseTotal
for (sweep = 0; sweep < 12; sweep++) { 2326 0 2326
5918 2326 NV off = nv_fabs(a[0][1]) + nv_fabs(a[0][2]) + nv_fabs(a[1][2]);
5919 2326 NV scale = nv_fabs(a[0][0]) + nv_fabs(a[1][1]) + nv_fabs(a[2][2]);
5920 2326 ▶ if (!(off > scale * NV_EPSILON)) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!(off > scale * NV_EPSILON)) break; 661 1665 2326
5921 4995 ▶ for (p = 0; p < 2; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = 0; p < 2; p++) { 3330 1665 4995
5922 8325 ▶ for (q = (unsigned short)(p + 1); q < 3; q++) {
Branch: 1 branch
BranchTrueFalseTotal
for (q = (unsigned short)(p + 1); q < 3; q++) { 4995 3330 8325
5923 4995 NV apq = a[p][q], theta, t, c, sn;
5924 4995 ▶ if (!(nv_fabs(apq) > 0.0)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(nv_fabs(apq) > 0.0)) continue; 41 4954 4995
5925 4954 theta = (a[q][q] - a[p][p]) / (2.0 * apq);
5926 /*the smaller root, which is the rotation that does not swap the
5927 two diagonal entries and so keeps the iteration converging*/
5928 4954 ▶ t = (theta >= 0.0 ? 1.0 : -1.0)
Branch: 1 branch
BranchTrueFalseTotal
t = (theta >= 0.0 ? 1.0 : -1.0) 2343 2611 4954
5929 4954 / (nv_fabs(theta) + nv_sqrt(1.0 + theta * theta));
5930 4954 c = 1.0 / nv_sqrt(1.0 + t * t);
5931 4954 sn = t * c;
5932 {
5933 4954 NV app = a[p][p], aqq = a[q][q];
5934 4954 unsigned short r = (unsigned short)(3 - p - q);
5935 4954 NV apr = a[p][r], aqr = a[q][r];
5936 4954 a[p][p] = app - t * apq;
5937 4954 a[q][q] = aqq + t * apq;
5938 4954 a[p][q] = a[q][p] = 0.0;
5939 4954 a[p][r] = a[r][p] = c * apr - sn * aqr;
5940 4954 a[q][r] = a[r][q] = sn * apr + c * aqr;
5941 }
5942 }
5943 }
5944 }
5945 661 out[0] = a[0][0]; out[1] = a[1][1]; out[2] = a[2][2];
5946 //three values: an insertion sort is the whole of it
5947 1983 ▶ for (i = 1; i < 3; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 1; i < 3; i++) { 1322 661 1983
5948 1322 NV v = out[i];
5949 1322 short int j = (short int)(i - 1);
5950 2581 ▶ while (j >= 0 && out[j] > v) { out[j + 1] = out[j]; j--; }
Branch: 2 branches
BranchTrueFalseTotal
while (j >= 0 && out[j] > v) { out[j + 1] = out[j]; j--; } 1775 806 2581
while (j >= 0 && out[j] > v) { out[j + 1] = out[j]; j--; } 1259 516 1775
5951 1322 out[j + 1] = v;
5952 }
5953 661 }
5954  
5955 //the coordinates of a named atom of a residue, false when the residue has no
5956 //atom of that name (a side chain modelled only as far as CB, most often).
5957 //Named for what it does rather than for the first thing that wanted it: the
5958 //rings, the disulfides and the dihedrals all reach for atoms by name.
5959 601463 static bool atom_xyz(pTHX_ HV *CSP_RESTRICT atoms, const char *CSP_RESTRICT name, NV *CSP_RESTRICT px, NV *CSP_RESTRICT py, NV *CSP_RESTRICT pz){
5960 601463 STRLEN nlen = strlen(name);
5961 601463 SV **slot = hv_fetch(atoms, name, (I32)nlen, 0);
5962 HV *a;
5963 SV *xs, *ys, *zs;
5964 601463 ▶ if (!slot || !*slot || !SvROK(*slot) || SvTYPE(SvRV(*slot)) != SVt_PVHV) return 0;
Branch: 4 branches
BranchTrueFalseTotal
if (!slot || !*slot || !SvROK(*slot) || SvTYPE(SvRV(*slot)) != SVt_PVHV) return 0; 333340 268123 601463
if (!slot || !*slot || !SvROK(*slot) || SvTYPE(SvRV(*slot)) != SVt_PVHV) return 0; 333340 0 333340
if (!slot || !*slot || !SvROK(*slot) || SvTYPE(SvRV(*slot)) != SVt_PVHV) return 0; 333340 0 333340
if (!slot || !*slot || !SvROK(*slot) || SvTYPE(SvRV(*slot)) != SVt_PVHV) return 0; 0 333340 333340
5965 333340 a = (HV *)SvRV(*slot);
5966 333340 xs = hvf_sv(aTHX_ a, "x", 1);
5967 333340 ys = hvf_sv(aTHX_ a, "y", 1);
5968 333340 zs = hvf_sv(aTHX_ a, "z", 1);
5969 333340 ▶ if (!xs || !ys || !zs) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (!xs || !ys || !zs) return 0; 333308 32 333340
if (!xs || !ys || !zs) return 0; 333308 0 333308
if (!xs || !ys || !zs) return 0; 0 333308 333308
5970 333308 *px = SvNV(xs); *py = SvNV(ys); *pz = SvNV(zs);
5971 333308 return 1;
5972 }
5973  
5974 /*rings_get() -- every complete aromatic ring of the walk, found the first time
5975 it is asked for and kept on the structset: the pi-stacking, the base pairs and
5976 the interface's cation-pi each want the same list. The caller reads s->rings
5977 and does not free it; set_free() does.*/
5978 1459 static UV rings_get(pTHX_ structset *CSP_RESTRICT s){
5979 1459 ring_t *rings = NULL;
5980 1459 UV cap = 0, n = 0, r;
5981 1459 ▶ if (s->have_rings) return s->n_rings;
Branch: 1 branch
BranchTrueFalseTotal
if (s->have_rings) return s->n_rings; 806 653 1459
5982 15980 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 15327 653 15980
5983 const ring_def *defs;
5984 15327 unsigned short nd = ring_defs(s->res_key[r], &defs), d;
5985 HV *atoms;
5986 15327 ▶ if (nd == 0) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (nd == 0) continue; 12081 3246 15327
5987 3246 atoms = hvf_hv(aTHX_ s->res_hv[r], "atoms", 5);
5988 3246 ▶ if (!atoms) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!atoms) continue; 0 3246 3246
5989 7716 ▶ for (d = 0; d < nd; d++) {
Branch: 1 branch
BranchTrueFalseTotal
for (d = 0; d < nd; d++) { 4470 3246 7716
5990 //the largest ring in the table is six-membered; the array is the
5991 //size of the table's largest entry, not of anything the file says
5992 NV px[RING_MAX], py[RING_MAX], pz[RING_MAX];
5993 4470 NV cx = 0.0, cy = 0.0, cz = 0.0, ux, uy, uz, vx, vy, vz, wx, wy, wz, wl;
5994 4470 unsigned short i, na = defs[d].n;
5995 4470 bool whole = 1;
5996 22098 ▶ for (i = 0; i < na; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < na; i++) { 18952 3146 22098
5997 18952 ▶ if (!atom_xyz(aTHX_ atoms, defs[d].atom[i], &px[i], &py[i], &pz[i])) {
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ atoms, defs[d].atom[i], &px[i], &py[i], &pz[i])) { 1324 17628 18952
5998 1324 whole = 0;
5999 1324 break;
6000 }
6001 17628 cx += px[i]; cy += py[i]; cz += pz[i];
6002 }
6003 4470 ▶ if (!whole) continue;//an incomplete ring has no plane to speak of
Branch: 1 branch
BranchTrueFalseTotal
if (!whole) continue;//an incomplete ring has no plane to speak of 1324 3146 4470
6004 3146 cx /= (NV)na; cy /= (NV)na; cz /= (NV)na;
6005 3146 ux = px[0] - cx; uy = py[0] - cy; uz = pz[0] - cz;
6006 3146 vx = px[1] - cx; vy = py[1] - cy; vz = pz[1] - cz;
6007 3146 wx = uy * vz - uz * vy;
6008 3146 wy = uz * vx - ux * vz;
6009 3146 wz = ux * vy - uy * vx;
6010 3146 wl = nv_sqrt(wx * wx + wy * wy + wz * wz);
6011 //three collinear points define no plane; a structure with two ring
6012 //atoms deposited at the same position is the way that happens
6013 3146 ▶ if (!(wl > 0.0)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(wl > 0.0)) continue; 0 3146 3146
6014 3146 ▶ if (n == cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == cap) { 275 2871 3146
6015 275 ▶ cap = cap ? cap * 2 : 32;
Branch: 1 branch
BranchTrueFalseTotal
cap = cap ? cap * 2 : 32; 0 275 275
6016 275 ▶ Renew(rings, cap, ring_t);
Branch: 1 branch
BranchTrueFalseTotal
Renew(rings, cap, ring_t); 0 275 275
6017 }
6018 3146 rings[n].cx = cx; rings[n].cy = cy; rings[n].cz = cz;
6019 3146 rings[n].nx = wx / wl; rings[n].ny = wy / wl; rings[n].nz = wz / wl;
6020 3146 rings[n].res = r;
6021 3146 rings[n].label = defs[d].label;
6022 3146 n++;
6023 }
6024 }
6025 653 s->rings = rings;
6026 653 s->n_rings = n;
6027 653 s->have_rings = TRUE;
6028 653 return n;
6029 }
6030  
6031 //the angle between two vectors, folded into 0..pi/2 -- mdtraj's compute_angles()
6032 //followed by its cap_angle(), which is how a plane's two-sided normal is made to
6033 //mean one thing. The cosine is clamped before acos() sees it: a dot product of
6034 //two unit vectors can land a fraction of an ulp outside [-1, 1] and acos() of
6035 //that is a NaN, which numpy warns about and carries and this would not.
6036 8473 static NV vec_angle_capped(NV ax, NV ay, NV az, NV bx, NV by, NV bz){
6037 8473 NV la = nv_sqrt(ax * ax + ay * ay + az * az);
6038 8473 NV lb = nv_sqrt(bx * bx + by * by + bz * bz);
6039 NV c, a;
6040 8473 ▶ if (!(la > 0.0) || !(lb > 0.0)) return -1.0;//no angle: the caller drops the pair
Branch: 2 branches
BranchTrueFalseTotal
if (!(la > 0.0) || !(lb > 0.0)) return -1.0;//no angle: the caller drops the pair 8473 0 8473
if (!(la > 0.0) || !(lb > 0.0)) return -1.0;//no angle: the caller drops the pair 0 8473 8473
6041 8473 c = (ax * bx + ay * by + az * bz) / (la * lb);
6042 8473 ▶ if (c > 1.0) c = 1.0; else if (c < -1.0) c = -1.0;
Branch: 2 branches
BranchTrueFalseTotal
if (c > 1.0) c = 1.0; else if (c < -1.0) c = -1.0; 0 8473 8473
if (c > 1.0) c = 1.0; else if (c < -1.0) c = -1.0; 0 8473 8473
6043 8473 a = nv_acos(c);
6044 8473 ▶ return (a > CSP_PI / 2.0) ? CSP_PI - a : a;
Branch: 1 branch
BranchTrueFalseTotal
return (a > CSP_PI / 2.0) ? CSP_PI - a : a; 3974 4499 8473
6045 }
6046  
6047 1084 static NV det3(NV a, NV b, NV c, NV d, NV e, NV f, NV g, NV h, NV i){
6048 1084 return a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
6049 }
6050  
6051 //the length of (vx, vy, vz) once its component along the unit vector u is removed
6052 542 static NV line_dist(NV vx, NV vy, NV vz, NV ux, NV uy, NV uz){
6053 542 NV t = ux * vx + uy * vy + uz * vz;
6054 542 vx -= ux * t; vy -= uy * t; vz -= uz * t;
6055 542 return nv_sqrt(vx * vx + vy * vy + vz * vz);
6056 }
6057  
6058 /*The distance from the nearer of two rings' centroids to the line where their
6059 planes meet -- mdtraj's calculate_intersection_point() and the two norms it
6060 is fed to, made symmetric in the two rings.
6061  
6062 An edge-to-face stack is one ring pointing its edge at the other's face, and
6063 what tells it from two rings merely at right angles some way apart is that the
6064 line their planes share passes close to one of them. Solving [n1; n2; n1xn2]
6065 p = [n1.c1, n2.c2, 0] puts p on that line, and each centroid's distance from the
6066 line is what is left of it once its component along the line is taken away; the
6067 smaller of the two is what gets compared with the radius.
6068  
6069 mdtraj projects only its first group's centroid onto the line and measures the
6070 second group's from that projected point rather than from the line, so its
6071 answer for one pair depends on which ring it was handed first. Asked both ways
6072 round -- which is how t/data/features.py asks it, every ring against every ring
6073 -- the union of its two answers is exactly this one, because a centroid is never
6074 nearer a point on the line than it is to the line. Asked one way it misses
6075 real stacks: 1b6c's PHE A99 lies 0.66 A from the line, and with TRP A59 handed
6076 first, 5.06 A from it, the edge stack between the two is not found.
6077  
6078 False when the planes are parallel and there is no line. mdtraj tests the
6079 determinant against zero and lets a NaN fall through its threshold; this is
6080 only ever reached with the planes 50 degrees or more apart, where the
6081 determinant is |n1 x n2|^2 >= sin^2(50) = 0.587, so the test is a formality
6082 either way.*/
6083 271 static bool ring_intersect(const ring_t *CSP_RESTRICT a, const ring_t *CSP_RESTRICT b, NV *CSP_RESTRICT dmin){
6084 271 NV dx = a->ny * b->nz - a->nz * b->ny;
6085 271 NV dy = a->nz * b->nx - a->nx * b->nz;
6086 271 NV dz = a->nx * b->ny - a->ny * b->nx;
6087 271 NV det = det3(a->nx, a->ny, a->nz, b->nx, b->ny, b->nz, dx, dy, dz);
6088 NV o1, o2, px, py, pz, dl, da, db;
6089 271 ▶ if (nv_fabs(det) <= NV_EPSILON) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (nv_fabs(det) <= NV_EPSILON) return 0; 0 271 271
6090 271 o1 = a->nx * a->cx + a->ny * a->cy + a->nz * a->cz;
6091 271 o2 = b->nx * b->cx + b->ny * b->cy + b->nz * b->cz;
6092 //Cramer's rule on [n_a; n_b; n_a x n_b] p = [o1, o2, 0]
6093 271 px = det3(o1, a->ny, a->nz, o2, b->ny, b->nz, 0.0, dy, dz) / det;
6094 271 py = det3(a->nx, o1, a->nz, b->nx, o2, b->nz, dx, 0.0, dz) / det;
6095 271 pz = det3(a->nx, a->ny, o1, b->nx, b->ny, o2, dx, dy, 0.0) / det;
6096 271 dl = nv_sqrt(dx * dx + dy * dy + dz * dz);
6097 271 ▶ if (!(dl > 0.0)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!(dl > 0.0)) return 0; 0 271 271
6098 271 dx /= dl; dy /= dl; dz /= dl;
6099 271 da = line_dist(a->cx - px, a->cy - py, a->cz - pz, dx, dy, dz);
6100 271 db = line_dist(b->cx - px, b->cy - py, b->cz - pz, dx, dy, dz);
6101 271 ▶ *dmin = (da < db) ? da : db;
Branch: 1 branch
BranchTrueFalseTotal
*dmin = (da < db) ? da : db; 150 121 271
6102 271 return 1;
6103 }
6104  
6105 /*Where a pair of rings has to be for the pair to count as stacked.
6106  
6107 Angles are radians here and degrees in the option hash, distances are angstrom
6108 here and nanometres in mdtraj. The defaults Perl passes down are mdtraj's, in
6109 this file's units, with the one exception argued at the head of
6110 structure_pi_stacking() in the Perl: mdtraj's face-to-face centroid distance is
6111 5.5 in a function whose every other distance is nanometres, which is 55 A -- far
6112 enough that any two aromatic rings in a small protein would qualify. ProLIF,
6113 which mdtraj's geometry is taken from, has 5.5 A, and mdtraj's three other
6114 distances are ProLIF's converted to nanometres. So this takes 5.5 A as what
6115 was meant, and the option is there for a caller who wants the number mdtraj
6116 actually ships.*/
6117 typedef struct {
6118 NV face_dist;//centroid separation, angstrom
6119 NV face_plane_lo, face_plane_hi;//angle between the ring planes, radians
6120 NV face_norm_lo, face_norm_hi;//normal to centroid-to-centroid, radians
6121 NV edge_dist, edge_plane_lo, edge_plane_hi, edge_norm_lo, edge_norm_hi;
6122 NV edge_radius;//centroid to the planes' shared line, angstrom
6123 } pi_opt;
6124  
6125 //one field of the residue a ring sits in, copied into the interaction hash
6126 946406 static void pi_field(pTHX_ HV *CSP_RESTRICT out, const char *CSP_RESTRICT key, STRLEN klen, HV *CSP_RESTRICT res, const char *CSP_RESTRICT from, STRLEN flen){
6127 946406 SV *v = hvf_sv(aTHX_ res, from, flen);
6128 946406 ▶ (void)hv_store(out, key, (I32)klen, v ? newSVsv(v) : newSVpvn("", 0), 0);
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_store(out, key, (I32)klen, v ? newSVsv(v) : newSVpvn("", 0), 0); 946406 0 946406
6129 946406 }
6130  
6131 /*pi_stacking() -- every stacked pair of rings in the structure.
6132  
6133 mdtraj asks the question of one named ligand group against one named receptor
6134 group; this asks it of every pair of rings in the structure, which is the same
6135 geometry run over a different set of pairs. Two of them are dropped: a ring
6136 paired with itself, which mdtraj drops too because the vector between the two
6137 centroids is the zero vector and every angle taken from it is a NaN, and the
6138 two rings of one tryptophan or one purine, which mdtraj would happily call a
6139 face-to-face stack because they are coplanar and 1.2 A apart. Two rings fused
6140 along a bond are one aromatic system, not two systems stacked.
6141  
6142 The pairs are found through the same grid the SASA uses, on the centroids: a
6143 structure with a few thousand aromatic rings has a few million pairs, and all
6144 but a handful of them are nowhere near each other.*/
6145 609 static AV *pi_stacking(pTHX_ structset *CSP_RESTRICT s, const pi_opt *CSP_RESTRICT po)
6146 {
6147 609 AV *out = newAV();
6148 const ring_t *rings;
6149 609 NV *cx = NULL, *cy = NULL, *cz = NULL;
6150 609 ▶ NV cut = (po->face_dist > po->edge_dist) ? po->face_dist : po->edge_dist;
Branch: 1 branch
BranchTrueFalseTotal
NV cut = (po->face_dist > po->edge_dist) ? po->face_dist : po->edge_dist; 1 608 609
6151 609 const NV to_deg = 180.0 / CSP_PI;
6152 cell_grid g;
6153 UV n, i;
6154  
6155 609 n = rings_get(aTHX_ s);
6156 609 rings = s->rings;
6157 609 ▶ if (n == 0) return out;
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) return out; 374 235 609
6158 235 ▶ Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV); 0 235 235
Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV); 0 235 235
Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV); 0 235 235
6159 2818 ▶ for (i = 0; i < n; i++) { cx[i] = rings[i].cx; cy[i] = rings[i].cy; cz[i] = rings[i].cz; }
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { cx[i] = rings[i].cx; cy[i] = rings[i].cy; cz[i] = rings[i].cz; } 2583 235 2818
6160 235 grid_build(aTHX_ &g, cx, cy, cz, n, cut);
6161  
6162 2818 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 2583 235 2818
6163 UV bx, by, bz;
6164 2583 UV ci = grid_axis(cx[i] - g.x0, g.cell, g.nx);
6165 2583 UV cj = grid_axis(cy[i] - g.y0, g.cell, g.ny);
6166 2583 UV ck = grid_axis(cz[i] - g.z0, g.cell, g.nz);
6167 2583 ▶ UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1;
Branch: 2 branches
BranchTrueFalseTotal
UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1; 1157 1426 2583
UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1; 1788 795 2583
6168 2583 ▶ UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1;
Branch: 2 branches
BranchTrueFalseTotal
UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1; 1464 1119 2583
UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1; 1780 803 2583
6169 2583 ▶ UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1;
Branch: 2 branches
BranchTrueFalseTotal
UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1; 1215 1368 2583
UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1; 1824 759 2583
6170 8111 ▶ for (bx = ax0; bx <= ax1; bx++)
Branch: 1 branch
BranchTrueFalseTotal
for (bx = ax0; bx <= ax1; bx++) 5528 2583 8111
6171 18215 ▶ for (by = ay0; by <= ay1; by++)
Branch: 1 branch
BranchTrueFalseTotal
for (by = ay0; by <= ay1; by++) 12687 5528 18215
6172 40644 ▶ for (bz = az0; bz <= az1; bz++) {
Branch: 1 branch
BranchTrueFalseTotal
for (bz = az0; bz <= az1; bz++) { 27957 12687 40644
6173 27957 UV cell = (bx * g.ny + by) * g.nz + bz, p;
6174 47382 ▶ for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = g.start[cell]; p < g.start[cell + 1]; p++) { 19425 27957 47382
6175 19425 UV j = g.idx[p];
6176 19425 NV vx, vy, vz, d, plane, ang_i, ang_j, inter = 0.0;
6177 19425 bool face, edge = 0;
6178 const char *kind;
6179 HV *h;
6180 26808 ▶ if (j <= i) continue;//each pair once
Branch: 1 branch
BranchTrueFalseTotal
if (j <= i) continue;//each pair once 11004 8421 19425
6181 8421 ▶ if (rings[i].res == rings[j].res) continue;//fused, not stacked
Branch: 1 branch
BranchTrueFalseTotal
if (rings[i].res == rings[j].res) continue;//fused, not stacked 708 7713 8421
6182 7713 vx = cx[j] - cx[i]; vy = cy[j] - cy[i]; vz = cz[j] - cz[i];
6183 7713 d = nv_sqrt(vx * vx + vy * vy + vz * vz);
6184 7713 ▶ if (!(d <= cut)) continue;//not >: a NaN distance is no pair
Branch: 1 branch
BranchTrueFalseTotal
if (!(d <= cut)) continue;//not >: a NaN distance is no pair 4971 2742 7713
6185 2742 plane = vec_angle_capped(rings[i].nx, rings[i].ny, rings[i].nz,
6186 2742 rings[j].nx, rings[j].ny, rings[j].nz);
6187 /*One capped angle serves for both of mdtraj's: it takes the
6188 angle of each ring's normal against the vector from that ring to
6189 the other, and the two vectors differ only in sign, which
6190 cap_angle() folds away.*/
6191 2742 ang_i = vec_angle_capped(rings[i].nx, rings[i].ny, rings[i].nz, vx, vy, vz);
6192 2742 ang_j = vec_angle_capped(rings[j].nx, rings[j].ny, rings[j].nz, vx, vy, vz);
6193 2742 ▶ if (plane < 0.0 || ang_i < 0.0 || ang_j < 0.0) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (plane < 0.0 || ang_i < 0.0 || ang_j < 0.0) continue; 2742 0 2742
if (plane < 0.0 || ang_i < 0.0 || ang_j < 0.0) continue; 2742 0 2742
if (plane < 0.0 || ang_i < 0.0 || ang_j < 0.0) continue; 0 2742 2742
6194 5484 face = (d <= po->face_dist
6195 1972 ▶ && plane >= po->face_plane_lo && plane <= po->face_plane_hi
Branch: 2 branches
BranchTrueFalseTotal
&& plane >= po->face_plane_lo && plane <= po->face_plane_hi 1972 0 1972
&& plane >= po->face_plane_lo && plane <= po->face_plane_hi 1713 259 1972
6196 5563 ▶ && ((ang_i >= po->face_norm_lo && ang_i <= po->face_norm_hi)
Branch: 3 branches
BranchTrueFalseTotal
&& ((ang_i >= po->face_norm_lo && ang_i <= po->face_norm_hi) 1972 770 2742
&& ((ang_i >= po->face_norm_lo && ang_i <= po->face_norm_hi) 1713 0 1713
&& ((ang_i >= po->face_norm_lo && ang_i <= po->face_norm_hi) 849 864 1713
6197 849 ▶ || (ang_j >= po->face_norm_lo && ang_j <= po->face_norm_hi)));
Branch: 2 branches
BranchTrueFalseTotal
|| (ang_j >= po->face_norm_lo && ang_j <= po->face_norm_hi))); 849 0 849
|| (ang_j >= po->face_norm_lo && ang_j <= po->face_norm_hi))); 25 824 849
6198 2742 ▶ if (!face) {
Branch: 1 branch
BranchTrueFalseTotal
if (!face) { 1853 889 2742
6199 1853 edge = (d <= po->edge_dist
6200 1819 ▶ && plane >= po->edge_plane_lo && plane <= po->edge_plane_hi
Branch: 2 branches
BranchTrueFalseTotal
&& plane >= po->edge_plane_lo && plane <= po->edge_plane_hi 634 1185 1819
&& plane >= po->edge_plane_lo && plane <= po->edge_plane_hi 634 0 634
6201 634 ▶ && ((ang_i >= po->edge_norm_lo && ang_i <= po->edge_norm_hi)
Branch: 2 branches
BranchTrueFalseTotal
&& ((ang_i >= po->edge_norm_lo && ang_i <= po->edge_norm_hi) 634 0 634
&& ((ang_i >= po->edge_norm_lo && ang_i <= po->edge_norm_hi) 484 150 634
6202 484 ▶ || (ang_j >= po->edge_norm_lo && ang_j <= po->edge_norm_hi))
Branch: 2 branches
BranchTrueFalseTotal
|| (ang_j >= po->edge_norm_lo && ang_j <= po->edge_norm_hi)) 484 0 484
|| (ang_j >= po->edge_norm_lo && ang_j <= po->edge_norm_hi)) 121 363 484
6203 271 ▶ && ring_intersect(&rings[i], &rings[j], &inter)
Branch: 1 branch
BranchTrueFalseTotal
&& ring_intersect(&rings[i], &rings[j], &inter) 271 0 271
6204 3672 ▶ && inter <= po->edge_radius);
Branch: 2 branches
BranchTrueFalseTotal
&& inter <= po->edge_radius); 1819 34 1853
&& inter <= po->edge_radius); 149 122 271
6205 }
6206 2742 ▶ if (!face && !edge) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!face && !edge) continue; 1853 889 2742
if (!face && !edge) continue; 1704 149 1853
6207 1038 ▶ kind = face ? "face" : "edge";
Branch: 1 branch
BranchTrueFalseTotal
kind = face ? "face" : "edge"; 889 149 1038
6208 1038 h = newHV();
6209 1038 (void)hv_stores(h, "type", newSVpv(kind, 0));
6210 1038 pi_field(aTHX_ h, "chain1", 6, s->res_hv[rings[i].res], "chain", 5);
6211 1038 pi_field(aTHX_ h, "residue1", 8, s->res_hv[rings[i].res], "key", 3);
6212 1038 pi_field(aTHX_ h, "resname1", 8, s->res_hv[rings[i].res], "resname", 7);
6213 1038 (void)hv_stores(h, "ring1", newSVpvn(&rings[i].label, 1));
6214 1038 pi_field(aTHX_ h, "chain2", 6, s->res_hv[rings[j].res], "chain", 5);
6215 1038 pi_field(aTHX_ h, "residue2", 8, s->res_hv[rings[j].res], "key", 3);
6216 1038 pi_field(aTHX_ h, "resname2", 8, s->res_hv[rings[j].res], "resname", 7);
6217 1038 (void)hv_stores(h, "ring2", newSVpvn(&rings[j].label, 1));
6218 1038 (void)hv_stores(h, "distance", newSVnv(d));
6219 1038 (void)hv_stores(h, "plane_angle", newSVnv(plane * to_deg));
6220 1038 (void)hv_stores(h, "normal_angle1", newSVnv(ang_i * to_deg));
6221 1038 (void)hv_stores(h, "normal_angle2", newSVnv(ang_j * to_deg));
6222 1038 ▶ if (edge) (void)hv_stores(h, "intersect_distance", newSVnv(inter));
Branch: 1 branch
BranchTrueFalseTotal
if (edge) (void)hv_stores(h, "intersect_distance", newSVnv(inter)); 149 889 1038
6223 1038 av_push(out, newRV_noinc((SV *)h));
6224 }
6225 }
6226 }
6227 235 grid_free(aTHX_ &g);
6228 235 Safefree(cx); Safefree(cy); Safefree(cz);
6229 235 return out;
6230 }
6231  
6232 /*Watson-Crick base pairs, and the G-U wobble that stands in for one.
6233  
6234 A base pair is not something the file declares; like the disulfides below it is
6235 something the coordinates show. What is looked for is the canonical pairing and
6236 only that -- the three geometries a double helix is built from -- because those
6237 are the ones whose hydrogen bonds are fixed by the pair itself rather than by
6238 whatever else the two bases happen to be doing. The atom pairs are the ones
6239 Watson, J D; Crick, F H C (1953) Nature 171(4356):737-8 drew, and the numbers
6240 beside them are Saenger, W (1984) Principles of Nucleic Acid Structure, chapter
6241 6, where the twenty-eight ways two bases can pair are tabulated and these are
6242 numbers 19, 20 and 28. That is the same numbering the archive's own annotation
6243 uses, in _ndb_struct_na_base_pair.hbond_type_28.
6244  
6245 **Where the two thresholds come from.** No reader on this machine finds base
6246 pairs -- gemmi, mdtraj and Biopython all stop short of it -- so the rule was
6247 measured against the annotation the wwPDB deposits with the entry, which is
6248 3DNA's. The forty entries below are the ones of those read that carry an
6249 _ndb_struct_na_base_pair loop, and between them they hold 1372 pairs of type 19,
6250 20 or 28 in model 1 of the asymmetric unit:
6251  
6252 1B94 1B97 1BNA 1D23 1D61 1D8X 1D9R 1EHZ 1FIR 1GID 1I9V 1JJ2 1KD3 1MSY
6253 1NJW 1NJX 1NK0 1NK4 1NK7 1NK8 1NK9 1NKC 1NKE 1SDR 1U8D 1Y26 1ZBI 2GIS
6254 2O1I 2R8S 355D 3AU6 3DNB 3SWP 3V9D 456D 4GLX 4OFA 5YTY 5YTZ
6255  
6256 Two bases are a pair when both of the following hold.
6257  
6258 - Every hydrogen bond of that pair type is at most CSP_BP_HBOND long. The
6259 longest one in the 1354 annotated pairs built from unmodified bases is
6260 3.4941 A and the shortest one in a candidate the annotation does not call a
6261 pair is 3.5144 A, so 3.5 -- which is also the conventional heavy-atom
6262 hydrogen bond distance -- falls between the two, with 0.006 A over the
6263 population it has to cover.
6264 - The two bases are coplanar to within CSP_BP_STAGGER, measured as the offset
6265 between their ring centroids projected on their ring normals, whichever of
6266 the two projections is larger. That is what tells a pair from the stacked
6267 neighbour above or below it, which brings the same atoms within reach but
6268 sits a rise away rather than beside it: the largest stagger in a real pair
6269 is 2.5408 A, the smallest in a rejected candidate 2.6983 A, and the stacked
6270 population proper begins near 3.0 A.
6271  
6272 Run that way the rule finds all 1354 and misses none. The other eighteen of the
6273 1372 are not pairs this can see at all, for two reasons that are both about the
6274 file rather than the geometry. Eleven have a modified base on one side -- 5MC,
6275 2MG, BRU, DDG -- which res_lookup() does not spell, so they have no
6276 single-letter code to match the table with. The other seven are in 1D61 and
6277 2O1I, whose asymmetric unit holds one strand of a self-complementary duplex and
6278 whose second strand is a crystallographic symmetry mate: the annotation names
6279 both strands with the same chain and the same residue numbers, and the two are
6280 thirty and forty angstrom apart in the coordinates as deposited, which is what
6281 this reads.
6282  
6283 Two pairs are found that the annotation does not list, and both are worth
6284 reading rather than a fault: 1JJ2's C2542-G2617, a G-C with all three bonds
6285 under 2.94 A and half an angstrom of stagger that appears nowhere in that
6286 entry's 1121 annotated rows, and 3SWP's DT4-DA24, where the entry is 4.11 A, the
6287 annotation pairs its DT4 with DA25 instead, and cannot put a Saenger number on
6288 that pair either.
6289  
6290 Every base came out of the set with at most one partner, over all 1354 pairs.
6291 That is what the geometry did, not something imposed, so a residue's answer is a
6292 list as its disulfides are: nothing in the rule forbids a second.*/
6293 #define CSP_BP_HBOND 3.5 //angstrom: the longest hydrogen bond a pair may have
6294 #define CSP_BP_STAGGER 2.6 //angstrom: the furthest out of plane it may be
6295 /*How far from its own ring centroid any atom named in the table below can sit,
6296 which is what makes the centroid grid a safe screen: if every bond is at most
6297 CSP_BP_HBOND then the centroids are at most CSP_BP_HBOND + 2 * CSP_BASE_REACH
6298 apart. The furthest such atom over the 11,525 in the forty entries above is an
6299 adenine N6 at 2.7734 A.*/
6300 #define CSP_BASE_REACH 3.0
6301 #define CSP_BP_BONDS 3 //the most hydrogen bonds any pair in the table has
6302  
6303 typedef struct {
6304 char a, b;//the two bases, the purine first
6305 unsigned short saenger;//which of Saenger's twenty-eight this is
6306 unsigned short n;//how many of the bonds below define it
6307 const char *atom[CSP_BP_BONDS][2];//the a atom and the b atom of each bond
6308 } bp_def;
6309  
6310 static const bp_def bp_kinds[] = {
6311 { 'G', 'C', 19, 3, { { "O6", "N4" }, { "N1", "N3" }, { "N2", "O2" } } },
6312 { 'A', 'U', 20, 2, { { "N6", "O4" }, { "N1", "N3" }, { NULL, NULL } } },
6313 { 'A', 'T', 20, 2, { { "N6", "O4" }, { "N1", "N3" }, { NULL, NULL } } },
6314 //the wobble, and the G-T that is the same pair with a methyl on it: the
6315 //archive numbers that one 28 as well, in 1NJW, 1NJX, 1NK8 and 1NKC
6316 { 'G', 'U', 28, 2, { { "O6", "N3" }, { "N1", "O2" }, { NULL, NULL } } },
6317 { 'G', 'T', 28, 2, { { "O6", "N3" }, { "N1", "O2" }, { NULL, NULL } } }
6318 };
6319  
6320 typedef struct {
6321 NV cx, cy, cz;//the six-membered ring's centroid
6322 NV nx, ny, nz;//and its normal
6323 HV *atoms;//the residue's atoms, for reaching the pairing atoms by name
6324 UV res;//which residue it belongs to
6325 char one;//A, C, G, T or U
6326 } base_t;
6327  
6328 /*The bases, out of the rings pi_stacking() already knows how to find. A purine
6329 has two rings and only the six-membered one is here, because it is the one both
6330 purines and pyrimidines have and the one every atom in the table above hangs
6331 off. A modified base has no single-letter code and so is not a base here; that
6332 is the eighteen pairs the header comment accounts for.*/
6333 624 static UV bases_find(pTHX_ structset *CSP_RESTRICT s, base_t *CSP_RESTRICT *CSP_RESTRICT out){
6334 const ring_t *rings;
6335 624 base_t *b = NULL;
6336 624 UV n, k, m = 0;
6337 624 *out = NULL;
6338 624 n = rings_get(aTHX_ s);
6339 624 rings = s->rings;
6340 624 ▶ if (n == 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) return 0; 374 250 624
6341 250 ▶ Newx(b, n, base_t);
Branch: 1 branch
BranchTrueFalseTotal
Newx(b, n, base_t); 0 250 250
6342 3135 ▶ for (k = 0; k < n; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n; k++) { 2885 250 3135
6343 2885 const UV r = rings[k].res;
6344 2885 const char one = s->res_one[r];
6345 2885 ▶ if (rings[k].label != '6') continue;
Branch: 1 branch
BranchTrueFalseTotal
if (rings[k].label != '6') continue; 1176 1709 2885
6346 1709 ▶ if (s->res_type[r] != RT_NUC) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (s->res_type[r] != RT_NUC) continue; 735 974 1709
6347 974 ▶ if (one != 'A' && one != 'C' && one != 'G' && one != 'T' && one != 'U') continue;
Branch: 5 branches
BranchTrueFalseTotal
if (one != 'A' && one != 'C' && one != 'G' && one != 'T' && one != 'U') continue; 760 214 974
if (one != 'A' && one != 'C' && one != 'G' && one != 'T' && one != 'U') continue; 520 240 760
if (one != 'A' && one != 'C' && one != 'G' && one != 'T' && one != 'U') continue; 204 316 520
if (one != 'A' && one != 'C' && one != 'G' && one != 'T' && one != 'U') continue; 132 72 204
if (one != 'A' && one != 'C' && one != 'G' && one != 'T' && one != 'U') continue; 0 132 132
6348 974 b[m].cx = rings[k].cx; b[m].cy = rings[k].cy; b[m].cz = rings[k].cz;
6349 974 b[m].nx = rings[k].nx; b[m].ny = rings[k].ny; b[m].nz = rings[k].nz;
6350 974 b[m].atoms = hvf_hv(aTHX_ s->res_hv[r], "atoms", 5);
6351 974 b[m].res = r;
6352 974 b[m].one = one;
6353 974 ▶ if (b[m].atoms) m++;
Branch: 1 branch
BranchTrueFalseTotal
if (b[m].atoms) m++; 974 0 974
6354 }
6355 250 *out = b;
6356 250 return m;
6357 }
6358  
6359 //which entry of bp_kinds two bases could be, and which way round; NULL for a
6360 //combination that is not one of the canonical pairs
6361 3972 static const bp_def *bp_kind_of(char x, char y, bool *CSP_RESTRICT swapped){
6362 17496 ▶ for (unsigned short i = 0; i < (unsigned short)C_ARRAY_LENGTH(bp_kinds); i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short i = 0; i < (unsigned short)C_ARRAY_LENGTH(bp_kinds); i++) { 15326 2170 17496
6363 15326 ▶ if (bp_kinds[i].a == x && bp_kinds[i].b == y) { *swapped = 0; return &bp_kinds[i]; }
Branch: 2 branches
BranchTrueFalseTotal
if (bp_kinds[i].a == x && bp_kinds[i].b == y) { *swapped = 0; return &bp_kinds[i]; } 3972 11354 15326
if (bp_kinds[i].a == x && bp_kinds[i].b == y) { *swapped = 0; return &bp_kinds[i]; } 627 3345 3972
6364 14699 ▶ if (bp_kinds[i].a == y && bp_kinds[i].b == x) { *swapped = 1; return &bp_kinds[i]; }
Branch: 2 branches
BranchTrueFalseTotal
if (bp_kinds[i].a == y && bp_kinds[i].b == x) { *swapped = 1; return &bp_kinds[i]; } 4881 9818 14699
if (bp_kinds[i].a == y && bp_kinds[i].b == x) { *swapped = 1; return &bp_kinds[i]; } 1175 3706 4881
6365 }
6366 2170 return NULL;
6367 }
6368  
6369 //the partner half of one pair, pushed onto a base's own list
6370 482 static void bp_note(pTHX_ HV *CSP_RESTRICT res, HV *CSP_RESTRICT partner, const char *CSP_RESTRICT type, unsigned short saenger){
6371 482 SV **slot = hv_fetch(res, "base_pair", 9, 0);
6372 AV *list;
6373 HV *e;
6374 482 ▶ if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) {
Branch: 4 branches
BranchTrueFalseTotal
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) { 2 480 482
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) { 2 0 2
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) { 2 0 2
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) { 2 0 2
6375 2 list = (AV *)SvRV(*slot);
6376 } else {
6377 480 list = newAV();
6378 480 (void)hv_stores(res, "base_pair", newRV_noinc((SV *)list));
6379 }
6380 482 e = newHV();
6381 482 pi_field(aTHX_ e, "chain", 5, partner, "chain", 5);
6382 482 pi_field(aTHX_ e, "residue", 7, partner, "key", 3);
6383 482 pi_field(aTHX_ e, "resname", 7, partner, "resname", 7);
6384 482 (void)hv_stores(e, "type", newSVpv(type, 0));
6385 482 (void)hv_stores(e, "saenger", newSVuv((UV)saenger));
6386 482 av_push(list, newRV_noinc((SV *)e));
6387 482 }
6388  
6389 624 static AV *base_pairs(pTHX_ structset *CSP_RESTRICT s, NV hb, NV stagger, bool store){
6390 624 AV *out = newAV();
6391 624 base_t *bases = NULL;
6392 624 NV *cx = NULL, *cy = NULL, *cz = NULL;
6393 624 const NV cut = hb + 2.0 * CSP_BASE_REACH;
6394 624 const NV to_deg = 180.0 / CSP_PI;
6395 cell_grid g;
6396 UV n, i;
6397  
6398 624 n = bases_find(aTHX_ s, &bases);
6399 624 ▶ if (n < 2) { Safefree(bases); return out; }
Branch: 1 branch
BranchTrueFalseTotal
if (n < 2) { Safefree(bases); return out; } 507 117 624
6400 117 ▶ Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV); 0 117 117
Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV); 0 117 117
Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV); 0 117 117
6401 1091 ▶ for (i = 0; i < n; i++) { cx[i] = bases[i].cx; cy[i] = bases[i].cy; cz[i] = bases[i].cz; }
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { cx[i] = bases[i].cx; cy[i] = bases[i].cy; cz[i] = bases[i].cz; } 974 117 1091
6402 /*Clear what an earlier call left on these residues, so that asking twice
6403 replaces the answer rather than adding to it. Which residues are candidates
6404 is decided by the residue's name and its ring atoms alone, never by either
6405 threshold, so these are exactly the ones a previous call could have written
6406 to.*/
6407 117 ▶ if (store)
Branch: 1 branch
BranchTrueFalseTotal
if (store) 115 2 117
6408 1065 ▶ for (i = 0; i < n; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) 950 115 1065
6409 950 (void)hv_delete(s->res_hv[bases[i].res], "base_pair", 9, G_DISCARD);
6410 117 grid_build(aTHX_ &g, cx, cy, cz, n, cut);
6411  
6412 1091 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 974 117 1091
6413 UV bx, by, bz;
6414 974 UV ci = grid_axis(cx[i] - g.x0, g.cell, g.nx);
6415 974 UV cj = grid_axis(cy[i] - g.y0, g.cell, g.ny);
6416 974 UV ck = grid_axis(cz[i] - g.z0, g.cell, g.nz);
6417 974 ▶ UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1;
Branch: 2 branches
BranchTrueFalseTotal
UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1; 36 938 974
UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1; 72 902 974
6418 974 ▶ UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1;
Branch: 2 branches
BranchTrueFalseTotal
UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1; 37 937 974
UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1; 359 615 974
6419 974 ▶ UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1;
Branch: 2 branches
BranchTrueFalseTotal
UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1; 333 641 974
UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1; 537 437 974
6420 2056 ▶ for (bx = ax0; bx <= ax1; bx++)
Branch: 1 branch
BranchTrueFalseTotal
for (bx = ax0; bx <= ax1; bx++) 1082 974 2056
6421 2560 ▶ for (by = ay0; by <= ay1; by++)
Branch: 1 branch
BranchTrueFalseTotal
for (by = ay0; by <= ay1; by++) 1478 1082 2560
6422 4226 ▶ for (bz = az0; bz <= az1; bz++) {
Branch: 1 branch
BranchTrueFalseTotal
for (bz = az0; bz <= az1; bz++) { 2748 1478 4226
6423 2748 UV cell = (bx * g.ny + by) * g.nz + bz, p;
6424 11666 ▶ for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = g.start[cell]; p < g.start[cell + 1]; p++) { 8918 2748 11666
6425 8918 UV j = g.idx[p];
6426 const bp_def *kind;
6427 8918 bool swapped = 0;
6428 NV vx, vy, vz, d, plane, sag_i, sag_j, sag;
6429 NV bond[CSP_BP_BONDS];
6430 unsigned short k;
6431 8918 bool whole = 1;
6432 char tname[4];
6433 HV *h;
6434 AV *hbs;
6435 12643 ▶ if (j <= i) continue;//each pair once
Branch: 1 branch
BranchTrueFalseTotal
if (j <= i) continue;//each pair once 4946 3972 8918
6436 //one residue's two rings cannot pair with each other, and
6437 //neither can two conformers sharing a residue
6438 3972 ▶ if (bases[i].res == bases[j].res) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (bases[i].res == bases[j].res) continue; 0 3972 3972
6439 3972 kind = bp_kind_of(bases[i].one, bases[j].one, &swapped);
6440 3972 ▶ if (!kind) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!kind) continue; 2170 1802 3972
6441 1802 vx = cx[j] - cx[i]; vy = cy[j] - cy[i]; vz = cz[j] - cz[i];
6442 1802 d = nv_sqrt(vx * vx + vy * vy + vz * vz);
6443 1802 ▶ if (!(d <= cut)) continue;//not >: a NaN distance is no pair
Branch: 1 branch
BranchTrueFalseTotal
if (!(d <= cut)) continue;//not >: a NaN distance is no pair 631 1171 1802
6444 2185 ▶ for (k = 0; k < kind->n; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < kind->n; k++) { 1842 343 2185
6445 /*the table names the purine's atom first, so a pair whose
6446 purine is the later residue reads its two names backwards*/
6447 1842 const char *an = kind->atom[k][swapped ? 1 : 0];
6448 1842 const char *bn = kind->atom[k][swapped ? 0 : 1];
6449 NV ax, ay, az, bx2, by2, bz2, dx, dy, dz;
6450 1842 ▶ if (!atom_xyz(aTHX_ bases[i].atoms, an, &ax, &ay, &az)
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ bases[i].atoms, an, &ax, &ay, &az) 1839 3 1842
6451 1839 ▶ || !atom_xyz(aTHX_ bases[j].atoms, bn, &bx2, &by2, &bz2)) {
Branch: 1 branch
BranchTrueFalseTotal
|| !atom_xyz(aTHX_ bases[j].atoms, bn, &bx2, &by2, &bz2)) { 1 1838 1839
6452 4 whole = 0;
6453 828 break;
6454 }
6455 1838 dx = bx2 - ax; dy = by2 - ay; dz = bz2 - az;
6456 1838 bond[k] = nv_sqrt(dx * dx + dy * dy + dz * dz);
6457 1838 ▶ if (bond[k] > hb) { whole = 0; break; }
Branch: 1 branch
BranchTrueFalseTotal
if (bond[k] > hb) { whole = 0; break; } 824 1014 1838
6458 }
6459 1171 ▶ if (!whole) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!whole) continue; 828 343 1171
6460 343 sag_i = nv_fabs(vx * bases[i].nx + vy * bases[i].ny + vz * bases[i].nz);
6461 343 sag_j = nv_fabs(vx * bases[j].nx + vy * bases[j].ny + vz * bases[j].nz);
6462 343 ▶ sag = (sag_i > sag_j) ? sag_i : sag_j;
Branch: 1 branch
BranchTrueFalseTotal
sag = (sag_i > sag_j) ? sag_i : sag_j; 189 154 343
6463 343 ▶ if (sag > stagger) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (sag > stagger) continue; 96 247 343
6464 247 plane = vec_angle_capped(bases[i].nx, bases[i].ny, bases[i].nz,
6465 247 bases[j].nx, bases[j].ny, bases[j].nz);
6466 247 ▶ if (plane < 0.0) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (plane < 0.0) continue; 0 247 247
6467 /*the pair is named in the order it is reported, so that the
6468 two letters and the two resname fields read the same way round*/
6469 247 tname[0] = bases[i].one; tname[1] = '-';
6470 247 tname[2] = bases[j].one; tname[3] = '\0';
6471 247 h = newHV();
6472 247 (void)hv_stores(h, "type", newSVpvn(tname, 3));
6473 247 (void)hv_stores(h, "saenger", newSVuv((UV)kind->saenger));
6474 247 pi_field(aTHX_ h, "chain1", 6, s->res_hv[bases[i].res], "chain", 5);
6475 247 pi_field(aTHX_ h, "residue1", 8, s->res_hv[bases[i].res], "key", 3);
6476 247 pi_field(aTHX_ h, "resname1", 8, s->res_hv[bases[i].res], "resname", 7);
6477 247 pi_field(aTHX_ h, "chain2", 6, s->res_hv[bases[j].res], "chain", 5);
6478 247 pi_field(aTHX_ h, "residue2", 8, s->res_hv[bases[j].res], "key", 3);
6479 247 pi_field(aTHX_ h, "resname2", 8, s->res_hv[bases[j].res], "resname", 7);
6480 247 (void)hv_stores(h, "distance", newSVnv(d));
6481 247 (void)hv_stores(h, "plane_angle", newSVnv(plane * to_deg));
6482 247 (void)hv_stores(h, "stagger", newSVnv(sag));
6483 247 hbs = newAV();
6484 878 ▶ for (k = 0; k < kind->n; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < kind->n; k++) { 631 247 878
6485 631 HV *e = newHV();
6486 631 (void)hv_stores(e, "atom1", newSVpv(kind->atom[k][swapped ? 1 : 0], 0));
6487 631 (void)hv_stores(e, "atom2", newSVpv(kind->atom[k][swapped ? 0 : 1], 0));
6488 631 (void)hv_stores(e, "distance", newSVnv(bond[k]));
6489 631 av_push(hbs, newRV_noinc((SV *)e));
6490 }
6491 247 (void)hv_stores(h, "hbonds", newRV_noinc((SV *)hbs));
6492 247 av_push(out, newRV_noinc((SV *)h));
6493 247 ▶ if (store) {
Branch: 1 branch
BranchTrueFalseTotal
if (store) { 241 6 247
6494 241 bp_note(aTHX_ s->res_hv[bases[i].res], s->res_hv[bases[j].res],
6495 241 tname, kind->saenger);
6496 241 tname[0] = bases[j].one; tname[2] = bases[i].one;
6497 241 bp_note(aTHX_ s->res_hv[bases[j].res], s->res_hv[bases[i].res],
6498 241 tname, kind->saenger);
6499 }
6500 }
6501 }
6502 }
6503 117 grid_free(aTHX_ &g);
6504 117 Safefree(cx); Safefree(cy); Safefree(cz);
6505 117 Safefree(bases);
6506 117 return out;
6507 }
6508  
6509 /*Base stacking, scored the way Condon's tetramer benchmark scores it.
6510  
6511 base_pairs() above answers whether two bases lie side by side in a plane; this
6512 answers the other question a nucleic acid poses, which is whether one base lies
6513 on the face of another. pi_stacking() answers a version of it too, but as a
6514 yes/no over a ring's centroid and normal, with mdtraj's thresholds; this is the
6515 question asked the way the RNA literature asks it -- three geometric variables
6516 and one number between -100% and 100% built out of them -- so that a caller can
6517 see how stacked a pair is rather than only that it passed.
6518  
6519 Provenance. The definition and every constant below are
6520  
6521 Condon, D E; Kennedy, S D; Mort, B C; Kierzek, R; Yildirim, I; Turner, D H
6522 (2015) "Stacking in RNA: NMR of Four Tetramers Benchmark Molecular
6523 Dynamics", J Chem Theory Comput 11(6):2729-2742, doi:10.1021/ct501025q,
6524 section 2.4 "Criteria for Stacking", equations 9 and 10 and Figures 4 and 5,
6525  
6526 and the implementation those numbers were produced with, which is the author's
6527 own PDB_stacker (https://github.com/hhg7/PDB_stacker, pdb_stacking.pl). The
6528 paper is the definition of record and the script is what was run; where the two
6529 disagree the script is what the published percentages mean, and each such place
6530 is marked below with the measurement that settles it. The measurement is
6531 Figure 4, which is the one worked example either gives: residues 13 (C) and 14
6532 (G) of chain B of PDB entry 157D, for which the caption reports d0 = 4.5 A,
6533 omega = 40.7 degrees and Xi = 17.3 degrees. Those residues are t/data/aform.pdb
6534 and t/stacking.t is where the three numbers are checked.
6535  
6536 **The base's frame.** Each base gets a centre of mass over the heavy atoms
6537 listed in nucbase_of() and two vectors a and b from that centre to two named
6538 atoms far apart on the ring, chosen so that the pair spans the base and so that
6539 out-of-plane distortion moves the cross product as little as possible. a x b
6540 and b x a are the base's two normal vectors, one above the plane and one below;
6541 which is which is arbitrary and nothing here depends on it, because every
6542 quantity below is a minimum over the two.
6543  
6544 The normals are *not* normalised, and that is load-bearing rather than an
6545 oversight: |a x b| is the d1 of equation 9, so the length of the cross product
6546 enters omega as a lever arm. It has units of area and is used as a length,
6547 which is what the reference implementation does and what the published angles
6548 were computed with.
6549  
6550 **The three variables**, for an ordered pair of bases (the 5' one first):
6551  
6552 d0 the distance between the two centres of mass.
6553 omega "oh-mega", for overlap: the angle at the 5' centre of mass in the
6554 triangle whose sides are d0, d1 = |a x b| of the 5' base, and d2, the
6555 distance from the tip of whichever of the 5' base's two normals lands
6556 nearer to the 3' base's centre of mass. Equation 9, by the law of
6557 cosines. It is small when the 3' base sits over the 5' base's face
6558 and large when it sits beside it, like the angle between the steps of
6559 a staircase.
6560 Xi the angle between the two bases' normal vectors, 0 when the planes are
6561 parallel. Equation 10 and Figure 5: Xi near 0 is a parallel stack and
6562 Xi near 90 a T-shape, which is a different interaction and is scored
6563 negative rather than dropped.
6564  
6565 **Which base is the 5' one.** omega is not symmetric -- it is measured from
6566 one base's normal against the other's centre of mass -- so the pair has to be
6567 ordered. The order is the order the file lists the two residues in, which for
6568 a strand written 5' to 3' as the formats and the archive write it is the
6569 chemical order. Two bases in different chains have no 5'/3' relation at all;
6570 there the order is the chain order, and the reported omega is the one measured
6571 from the base the pair names first.
6572  
6573 **Where this departs from the paper's text, and why.**
6574  
6575 - Equation 10 as printed is min(arcsin(|(a5 x b5) x (a3 x b3)| / ...),
6576 arcsin(|(a5 x b5) x (b3 x a3)| / ...)). The two arguments differ only in
6577 the sign of the second cross product, so the two arcsines are equal and the
6578 minimum is a formality; and taken literally the expression is the angle
6579 between the two normals with no reference to where the bases are. The
6580 script instead compares the 5' base's normal with the 3' base's normal
6581 *translated so that both are drawn from the 5' base's centre of mass* --
6582 its comment says "pretend that both vectors are centered on the 5'
6583 nucleotide's Center of Mass" -- and takes the smaller of the two answers
6584 the 3' base's two normals give. On the Figure 4 pair the printed equation
6585 gives 9.5 degrees and the script gives 17.31; the caption says 17.3, so the
6586 script is what Xi means and is what is implemented here.
6587 - Guanine's centre of mass is taken over ten atoms and not eleven: N2, the
6588 exocyclic amino nitrogen, is not in the script's list, though adenine's N6
6589 and cytosine's N4 are in theirs. It reads like an omission, but it is the
6590 omission the published numbers were computed with -- on the Figure 4 pair
6591 including N2 gives d0 = 4.77 A and omega = 43.56 degrees against the
6592 caption's 4.5 and 40.7, and leaving it out gives 4.53 and 40.74.
6593 - Criterion I in the paper's text puts the distance knee at 3.5 A ("If
6594 d0 <= 3.5 A, the stacking score is incremented +1"); the script's
6595 $DISTANCE_MIN is 4. 4 is used here, again because it is the number behind
6596 the published percentages. It is not an option: the two cutoffs that
6597 decide whether a pair is reported at all are options below, and the shape
6598 of the ramp between them is the definition.
6599 - The masses are this module's own standard atomic weights, from
6600 elem_prop_of(), where the script uses the mass numbers 12, 14 and 16. One
6601 mass table in the file is worth more than agreement in the last place the
6602 difference reaches: on the Figure 4 pair the two centres of mass differ by
6603 enough to move d0 from 4.528 A to 4.529 A, and omega and Xi not at all to
6604 two decimal places.
6605  
6606 **What it does not do.** A base whose letter is not one of the six below, or
6607 that is missing any atom the letter's entry names, contributes no frame and so
6608 appears in no pair -- the same rule rings_get() applies to an incomplete ring.
6609 That covers a 4-thiouridine, whose O4 is a sulphur, as well as a base whose
6610 density ran out; no geometry is invented for either.*/
6611  
6612 /*The distance beyond which two bases are not stacked, from CCSD(T) calculations
6613 on stacked uracil and adenine dimers -- the paper's criterion I, citing its
6614 references 63 and 45. This and the angle below are defaults: the caller's two
6615 cutoffs are what base_stacks() builds its grid on and scores against.*/
6616 #define CSP_STACK_DIST 5.0
6617 //the angle beyond which they are not stacked either, and Xi is not computed;
6618 //criterion II, chosen there from X-ray statistics
6619 #define CSP_STACK_OMEGA 50.0
6620 //the knees of the two ramps: full marks at or below these, falling to nothing
6621 //at the cutoffs above. PDB_stacker's $DISTANCE_MIN and $OMEGA_MIN.
6622 #define CSP_STACK_DIST_KNEE 4.0
6623 #define CSP_STACK_OMEGA_KNEE 25.0
6624 //Xi above this is a T-shape rather than a stack, and flips the score's sign.
6625 //The paper's "45.0 < chi < 135.0" over an angle its own equation confines to
6626 //0..90, so only the lower bound can ever be reached.
6627 #define CSP_STACK_T 45.0
6628  
6629 typedef struct {
6630 const char *const *atom;//the heavy atoms the centre of mass is taken over
6631 unsigned short n;//how many
6632 const char *a, *b;//the two atoms the normal's cross product is built from
6633 } nucbase_def;
6634  
6635 /*Adenine's ten heavy atoms, guanine's ten (see N2, above), cytosine's eight and
6636 uracil's eight, exactly as PDB_stacker's %atoms lists them. Every name in every
6637 list begins with the atom's element, which is what lets the masses be looked up
6638 from the first byte alone; that is true of these fourteen names and is not a
6639 general fact about PDB atom names.*/
6640 static const char *const base_ade[10] = {
6641 "N1", "C2", "N3", "C4", "C5", "C6", "N6", "N7", "C8", "N9"
6642 };
6643 static const char *const base_gua[10] = {
6644 "N1", "C2", "N3", "C4", "C5", "C6", "O6", "N7", "C8", "N9"
6645 };
6646 static const char *const base_cyt[8] = {
6647 "N1", "C2", "O2", "N3", "C4", "N4", "C5", "C6"
6648 };
6649 static const char *const base_ura[8] = {
6650 "N1", "C2", "O2", "N3", "C4", "O4", "C5", "C6"
6651 };
6652  
6653 /*The frame for a base, by the single-letter code res_lookup() gave its residue,
6654 or false for a letter that names no base this can build one for.
6655  
6656 Six letters out of the four entries. Inosine has guanine's ring and guanine's
6657 O6 and simply has no N2, so the ten atoms guanine is measured over are ten
6658 inosine also has; thymine is uracil with a methyl on C5, and takes uracil's
6659 eight, which leaves C7 out of the centre of mass exactly as guanine's N2 is left
6660 out. N -- the archive's unknown nucleotide -- names no base and gets none.
6661  
6662 Every modified base res_lookup() spells reaches its parent's entry through its
6663 letter: a pseudouridine is measured as a uridine, a 7-methylguanosine as a
6664 guanosine, and so on, which is right as long as the modification leaves the
6665 named atoms where they were. Where it does not, the atom is missing under that
6666 name and the base is dropped rather than mismeasured.*/
6667 1393 static bool nucbase_of(char one, const nucbase_def *CSP_RESTRICT *CSP_RESTRICT out){
6668 /*the two vectors are the paper's: (CoM -> C8, CoM -> N6) for adenine,
6669 (CoM -> C8, CoM -> O6) for guanine, (CoM -> O2, CoM -> N4) for cytosine
6670 and (CoM -> O2, CoM -> O4) for uracil*/
6671 static const nucbase_def defs[4] = {
6672 { base_ade, 10, "C8", "N6" },
6673 { base_gua, 10, "C8", "O6" },
6674 { base_cyt, 8, "O2", "N4" },
6675 { base_ura, 8, "O2", "O4" }
6676 };
6677 1393 switch (one) {
6678 358 case 'A': *out = &defs[0]; return 1;
6679 391 case 'G': case 'I': *out = &defs[1]; return 1;
6680 345 case 'C': *out = &defs[2]; return 1;
6681 296 case 'U': case 'T': *out = &defs[3]; return 1;
6682 3 default: *out = NULL; return 0;
6683 }
6684 }
6685  
6686 typedef struct {
6687 NV cx, cy, cz;//centre of mass over the base's heavy atoms
6688 NV nx, ny, nz;//a x b, the normal above the plane; NOT a unit vector
6689 NV nlen;//|a x b|, which is the d1 of equation 9
6690 UV res;//which residue it belongs to
6691 char one;//A, C, G, I, T or U
6692 } nucbase_t;//nucbase_t and not stack_t: POSIX <signal.h> has that name
6693  
6694 /*Every base in the structure that has a frame, in walk order -- which is chain
6695 order and then the order the file listed the residues, so a lower index is the
6696 5' base of any pair drawn from one strand.*/
6697 612 static UV stacks_find(pTHX_ structset *CSP_RESTRICT s, nucbase_t *CSP_RESTRICT *CSP_RESTRICT out)
6698 {
6699 612 nucbase_t *b = NULL;
6700 612 UV n = 0, r;
6701 612 *out = NULL;
6702 612 ▶ if (s->n_res == 0) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (s->n_res == 0) return 0; 29 583 612
6703 583 ▶ Newx(b, s->n_res, nucbase_t);
Branch: 1 branch
BranchTrueFalseTotal
Newx(b, s->n_res, nucbase_t); 0 583 583
6704 12225 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 11642 583 12225
6705 const nucbase_def *def;
6706 HV *atoms;
6707 11642 NV cx = 0.0, cy = 0.0, cz = 0.0, tot = 0.0;
6708 NV ax, ay, az, bx, by, bz, wx, wy, wz, wl;
6709 unsigned short i;
6710 11642 bool whole = 1;
6711 12242 ▶ if (s->res_type[r] != RT_NUC) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (s->res_type[r] != RT_NUC) continue; 10249 1393 11642
6712 1393 ▶ if (!nucbase_of(s->res_one[r], &def)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!nucbase_of(s->res_one[r], &def)) continue; 3 1390 1393
6713 1390 atoms = hvf_hv(aTHX_ s->res_hv[r], "atoms", 5);
6714 1390 ▶ if (!atoms) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!atoms) continue; 0 1390 1390
6715 //summed as it goes: unlike rings_get(), which needs its first two
6716 //atoms again to take the plane from, nothing here looks at an atom a
6717 //second time -- a and b are fetched by name below
6718 8632 ▶ for (i = 0; i < def->n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < def->n; i++) { 7839 793 8632
6719 elem_prop ep;
6720 NV px, py, pz;
6721 7839 ▶ if (!atom_xyz(aTHX_ atoms, def->atom[i], &px, &py, &pz)
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ atoms, def->atom[i], &px, &py, &pz) 7242 597 7839
6722 7242 ▶ || !elem_prop_of(def->atom[i], 1, &ep) || !(ep.mass > 0.0)) {
Branch: 2 branches
BranchTrueFalseTotal
|| !elem_prop_of(def->atom[i], 1, &ep) || !(ep.mass > 0.0)) { 7242 0 7242
|| !elem_prop_of(def->atom[i], 1, &ep) || !(ep.mass > 0.0)) { 0 7242 7242
6723 597 whole = 0;
6724 597 break;
6725 }
6726 7242 cx += ep.mass * px; cy += ep.mass * py; cz += ep.mass * pz;
6727 7242 tot += ep.mass;
6728 }
6729 //an incomplete base has no centre of mass to speak of, the same way an
6730 //incomplete ring has no plane
6731 1390 ▶ if (!whole || !(tot > 0.0)) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!whole || !(tot > 0.0)) continue; 793 597 1390
if (!whole || !(tot > 0.0)) continue; 0 793 793
6732 793 cx /= tot; cy /= tot; cz /= tot;
6733 793 ▶ if (!atom_xyz(aTHX_ atoms, def->a, &ax, &ay, &az)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ atoms, def->a, &ax, &ay, &az)) continue; 0 793 793
6734 793 ▶ if (!atom_xyz(aTHX_ atoms, def->b, &bx, &by, &bz)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ atoms, def->b, &bx, &by, &bz)) continue; 0 793 793
6735 793 ax -= cx; ay -= cy; az -= cz;
6736 793 bx -= cx; by -= cy; bz -= cz;
6737 793 wx = ay * bz - az * by;
6738 793 wy = az * bx - ax * bz;
6739 793 wz = ax * by - ay * bx;
6740 793 wl = nv_sqrt(wx * wx + wy * wy + wz * wz);
6741 //a and b collinear with the centre of mass define no plane, and d1
6742 //would be zero in the denominator of equation 9
6743 793 ▶ if (!(wl > 0.0)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(wl > 0.0)) continue; 0 793 793
6744 793 b[n].cx = cx; b[n].cy = cy; b[n].cz = cz;
6745 793 b[n].nx = wx; b[n].ny = wy; b[n].nz = wz;
6746 793 b[n].nlen = wl;
6747 793 b[n].res = r;
6748 793 b[n].one = s->res_one[r];
6749 793 n++;
6750 }
6751 583 *out = b;
6752 583 return n;
6753 }
6754  
6755 /*The stacking score, as a percentage: the paper's criteria I, II and III and
6756 PDB_stacker's stacking_score(), which award a point for the distance and a point
6757 for the overlap, flip the sign for a T-shape, and report the two points as
6758 100%.
6759  
6760 d0 <= knee 1
6761 knee < d0 <= cut 1 / (d0 - knee + 1)^3, the paper's "decreased as
6762 r^-3 from 1 to 0"
6763 omega <= knee 1
6764 knee < om <= cut linear from 1 at the knee to 0 at the cutoff
6765 Xi > 45 degrees the whole score is multiplied by -1
6766  
6767 Both cutoffs are the caller's, so that a caller who wants the paper's 3.5 A
6768 criterion or a different overlap limit has them; the knees are not. A caller
6769 who moves a cutoff below its knee gets a ramp that never runs, which is the
6770 honest answer to the question asked rather than a croak.
6771  
6772 Reached only for a pair already inside both cutoffs, which is where the score
6773 is defined: outside them the paper does not compute the angles at all, and the
6774 score is 0 without being calculated.*/
6775 620 static NV stack_score(NV d0, NV omega, NV xi, NV dist_cut, NV omega_cut)
6776 {
6777 620 NV score = 0.0;
6778 620 ▶ if (d0 <= CSP_STACK_DIST_KNEE) {
Branch: 1 branch
BranchTrueFalseTotal
if (d0 <= CSP_STACK_DIST_KNEE) { 399 221 620
6779 399 score += 1.0;
6780 221 ▶ } else if (d0 <= dist_cut) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (d0 <= dist_cut) { 221 0 221
6781 221 const NV t = d0 - CSP_STACK_DIST_KNEE + 1.0;
6782 221 score += 1.0 / (t * t * t);
6783 }
6784 620 ▶ if (omega <= CSP_STACK_OMEGA_KNEE) {
Branch: 1 branch
BranchTrueFalseTotal
if (omega <= CSP_STACK_OMEGA_KNEE) { 294 326 620
6785 294 score += 1.0;
6786 326 ▶ } else if (omega <= omega_cut && omega_cut > CSP_STACK_OMEGA_KNEE) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (omega <= omega_cut && omega_cut > CSP_STACK_OMEGA_KNEE) { 326 0 326
} else if (omega <= omega_cut && omega_cut > CSP_STACK_OMEGA_KNEE) { 326 0 326
6787 326 score += (omega_cut - omega) / (omega_cut - CSP_STACK_OMEGA_KNEE);
6788 }
6789 620 ▶ if (xi > CSP_STACK_T) score = -score;
Branch: 1 branch
BranchTrueFalseTotal
if (xi > CSP_STACK_T) score = -score; 0 620 620
6790 620 return 100.0 * score / 2.0;
6791 }
6792  
6793 /*The partner half of one stack, pushed onto a base's own list, as bp_note()
6794 does for a pair. The three variables go on with it, because a residue's own
6795 list is the only place a caller walking residues will look for them.
6796  
6797 Both residues get the same d0, omega, Xi and score -- they are the pair's, not
6798 either base's. What differs is `side', which says which end of the pair this
6799 residue is: omega is measured from the 5' base against the 3' base's centre of
6800 mass, so a residue that reads its own list needs to know which one it was.*/
6801 1300 static void stack_note(pTHX_ HV *CSP_RESTRICT res, HV *CSP_RESTRICT partner, const char *CSP_RESTRICT type, NV d0, NV omega, const NV *CSP_RESTRICT xi, NV score, bool five_prime){
6802 1300 SV **slot = hv_fetch(res, "base_stack", 10, 0);
6803 AV *list;
6804 HV *e;
6805 1300 ▶ if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) {
Branch: 4 branches
BranchTrueFalseTotal
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) { 533 767 1300
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) { 533 0 533
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) { 533 0 533
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) { 533 0 533
6806 533 list = (AV *)SvRV(*slot);
6807 } else {
6808 767 list = newAV();
6809 767 (void)hv_stores(res, "base_stack", newRV_noinc((SV *)list));
6810 }
6811 1300 e = newHV();
6812 1300 pi_field(aTHX_ e, "chain", 5, partner, "chain", 5);
6813 1300 pi_field(aTHX_ e, "residue", 7, partner, "key", 3);
6814 1300 pi_field(aTHX_ e, "resname", 7, partner, "resname", 7);
6815 1300 (void)hv_stores(e, "type", newSVpv(type, 0));
6816 1300 (void)hv_stores(e, "distance", newSVnv(d0));
6817 1300 (void)hv_stores(e, "omega", newSVnv(omega));
6818 1300 ▶ if (xi) (void)hv_stores(e, "xi", newSVnv(*xi));
Branch: 1 branch
BranchTrueFalseTotal
if (xi) (void)hv_stores(e, "xi", newSVnv(*xi)); 1226 74 1300
6819 1300 (void)hv_stores(e, "score", newSVnv(score));
6820 //which end of the pair this residue is, because omega is measured from the
6821 //5' base and means nothing read the other way round
6822 1300 ▶ (void)hv_stores(e, "side", newSVpv(five_prime ? "5'" : "3'", 0));
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(e, "side", newSVpv(five_prime ? "5'" : "3'", 0)); 650 650 1300
6823 1300 av_push(list, newRV_noinc((SV *)e));
6824 1300 }
6825  
6826 /*base_stacks() -- d0, omega, Xi and the score for every pair of bases close
6827 enough for the paper to compute them.
6828  
6829 Every pair within the distance cutoff is reported, stacked or not, because the
6830 three variables are the answer and the score is a summary of them: a caller
6831 benchmarking a force field wants the pair that scored 12% as much as the one
6832 that scored 98%. A pair whose omega is past its cutoff carries no Xi, which is
6833 criterion II -- "the base is not considered stacked and Xi is not computed" --
6834 and scores 0.
6835  
6836 The pairs come off the same centroid grid base_pairs() uses, on the centres of
6837 mass.*/
6838 612 static AV *base_stacks(pTHX_ structset *CSP_RESTRICT s, NV dist_cut, NV omega_cut,
6839 bool store)
6840 {
6841 612 AV *out = newAV();
6842 612 nucbase_t *bases = NULL;
6843 612 NV *cx = NULL, *cy = NULL, *cz = NULL;
6844 612 const NV to_deg = 180.0 / CSP_PI;
6845 cell_grid g;
6846 UV n, i;
6847  
6848 612 n = stacks_find(aTHX_ s, &bases);
6849 612 ▶ if (n < 2) { Safefree(bases); return out; }
Branch: 1 branch
BranchTrueFalseTotal
if (n < 2) { Safefree(bases); return out; } 507 105 612
6850 105 ▶ Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV); 0 105 105
Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV); 0 105 105
Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV); 0 105 105
6851 898 ▶ for (i = 0; i < n; i++) { cx[i] = bases[i].cx; cy[i] = bases[i].cy; cz[i] = bases[i].cz; }
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { cx[i] = bases[i].cx; cy[i] = bases[i].cy; cz[i] = bases[i].cz; } 793 105 898
6852 /*Clear what an earlier call left behind, so that asking twice replaces the
6853 answer rather than adding to it. Which residues are candidates is decided
6854 by the residue's name and its atoms alone, never by either cutoff, so these
6855 are exactly the ones a previous call could have written to.*/
6856 105 ▶ if (store)
Branch: 1 branch
BranchTrueFalseTotal
if (store) 103 2 105
6857 884 ▶ for (i = 0; i < n; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) 781 103 884
6858 781 (void)hv_delete(s->res_hv[bases[i].res], "base_stack", 10, G_DISCARD);
6859 105 grid_build(aTHX_ &g, cx, cy, cz, n, dist_cut);
6860  
6861 898 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 793 105 898
6862 UV bx, by, bz;
6863 793 UV ci = grid_axis(cx[i] - g.x0, g.cell, g.nx);
6864 793 UV cj = grid_axis(cy[i] - g.y0, g.cell, g.ny);
6865 793 UV ck = grid_axis(cz[i] - g.z0, g.cell, g.nz);
6866 793 ▶ UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1;
Branch: 2 branches
BranchTrueFalseTotal
UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1; 257 536 793
UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1; 566 227 793
6867 793 ▶ UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1;
Branch: 2 branches
BranchTrueFalseTotal
UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1; 405 388 793
UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1; 543 250 793
6868 793 ▶ UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1;
Branch: 2 branches
BranchTrueFalseTotal
UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1; 426 367 793
UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1; 594 199 793
6869 2409 ▶ for (bx = ax0; bx <= ax1; bx++)
Branch: 1 branch
BranchTrueFalseTotal
for (bx = ax0; bx <= ax1; bx++) 1616 793 2409
6870 5164 ▶ for (by = ay0; by <= ay1; by++)
Branch: 1 branch
BranchTrueFalseTotal
for (by = ay0; by <= ay1; by++) 3548 1616 5164
6871 11752 ▶ for (bz = az0; bz <= az1; bz++) {
Branch: 1 branch
BranchTrueFalseTotal
for (bz = az0; bz <= az1; bz++) { 8204 3548 11752
6872 8204 UV cell = (bx * g.ny + by) * g.nz + bz, p;
6873 12631 ▶ for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = g.start[cell]; p < g.start[cell + 1]; p++) { 4427 8204 12631
6874 4427 UV j = g.idx[p];
6875 4427 NV vx, vy, vz, d0, d1, d2, cosw, omega, xi = 0.0, score;
6876 4427 bool have_xi = 0;
6877 char tname[4];
6878 HV *h;
6879 unsigned short k;
6880 5584 ▶ if (j <= i) continue;//each pair once, the earlier residue first
Branch: 1 branch
BranchTrueFalseTotal
if (j <= i) continue;//each pair once, the earlier residue first 2610 1817 4427
6881 //two conformers of one residue are not two bases
6882 1817 ▶ if (bases[i].res == bases[j].res) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (bases[i].res == bases[j].res) continue; 0 1817 1817
6883 1817 vx = cx[j] - cx[i]; vy = cy[j] - cy[i]; vz = cz[j] - cz[i];
6884 1817 d0 = nv_sqrt(vx * vx + vy * vy + vz * vz);
6885 1817 ▶ if (d0 > dist_cut || !(d0 > 0.0)) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (d0 > dist_cut || !(d0 > 0.0)) continue; 660 1157 1817
if (d0 > dist_cut || !(d0 > 0.0)) continue; 0 660 660
6886 /*d2: the 5' base's two normals are its centre of mass plus and
6887 minus a x b, and the one that lands nearer the 3' base's centre
6888 of mass is the one equation 9 wants -- the base has two faces
6889 and the 3' base is over one of them.*/
6890 660 d1 = bases[i].nlen;
6891 660 d2 = 0.0;
6892 1980 ▶ for (k = 0; k < 2; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < 2; k++) { 1320 660 1980
6893 1320 ▶ const NV sign = k ? -1.0 : 1.0;
Branch: 1 branch
BranchTrueFalseTotal
const NV sign = k ? -1.0 : 1.0; 660 660 1320
6894 1320 const NV ex = vx - sign * bases[i].nx;
6895 1320 const NV ey = vy - sign * bases[i].ny;
6896 1320 const NV ez = vz - sign * bases[i].nz;
6897 1320 const NV e = nv_sqrt(ex * ex + ey * ey + ez * ez);
6898 1320 ▶ if (k == 0 || e < d2) d2 = e;
Branch: 2 branches
BranchTrueFalseTotal
if (k == 0 || e < d2) d2 = e; 660 660 1320
if (k == 0 || e < d2) d2 = e; 350 310 660
6899 }
6900 /*equation 9, the law of cosines. The cosine is clamped before
6901 acos() sees it for the reason vec_angle_capped() clamps its
6902 own: a value a fraction of an ulp outside [-1, 1] is a NaN
6903 that would travel all the way out to the caller*/
6904 660 cosw = (d0 * d0 + d1 * d1 - d2 * d2) / (2.0 * d0 * d1);
6905 660 ▶ if (cosw > 1.0) cosw = 1.0; else if (cosw < -1.0) cosw = -1.0;
Branch: 2 branches
BranchTrueFalseTotal
if (cosw > 1.0) cosw = 1.0; else if (cosw < -1.0) cosw = -1.0; 0 660 660
if (cosw > 1.0) cosw = 1.0; else if (cosw < -1.0) cosw = -1.0; 0 660 660
6906 660 omega = nv_acos(cosw) * to_deg;
6907 660 ▶ if (omega <= omega_cut) {
Branch: 1 branch
BranchTrueFalseTotal
if (omega <= omega_cut) { 620 40 660
6908 /*equation 10 as PDB_stacker computes it: the 3' base's
6909 normal is redrawn from the 5' base's centre of mass, so the
6910 vector compared is (CoM3 - CoM5) +/- n3, and the smaller of
6911 the two answers is Xi. atan2(|u x v|, |u . v|) rather than
6912 the arcsine the paper prints: it is the same angle for
6913 vectors this cannot fold past 90 degrees, and it keeps its
6914 precision near 0, which is where a good stack sits and where
6915 an arcsine of a quotient near 0 has the least of it.*/
6916 1860 ▶ for (k = 0; k < 2; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < 2; k++) { 1240 620 1860
6917 1240 ▶ const NV sign = k ? -1.0 : 1.0;
Branch: 1 branch
BranchTrueFalseTotal
const NV sign = k ? -1.0 : 1.0; 620 620 1240
6918 1240 const NV ux = bases[i].nx, uy = bases[i].ny, uz = bases[i].nz;
6919 1240 const NV wx2 = vx + sign * bases[j].nx;
6920 1240 const NV wy2 = vy + sign * bases[j].ny;
6921 1240 const NV wz2 = vz + sign * bases[j].nz;
6922 1240 const NV qx = uy * wz2 - uz * wy2;
6923 1240 const NV qy = uz * wx2 - ux * wz2;
6924 1240 const NV qz = ux * wy2 - uy * wx2;
6925 1240 const NV cr = nv_sqrt(qx * qx + qy * qy + qz * qz);
6926 1240 const NV dp = ux * wx2 + uy * wy2 + uz * wz2;
6927 NV t;
6928 1240 ▶ if (!(nv_fabs(dp) > 0.0) && !(cr > 0.0)) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!(nv_fabs(dp) > 0.0) && !(cr > 0.0)) continue; 0 1240 1240
if (!(nv_fabs(dp) > 0.0) && !(cr > 0.0)) continue; 0 0 0
6929 1240 t = nv_atan2(cr, nv_fabs(dp)) * to_deg;
6930 1240 ▶ if (!have_xi || t < xi) { xi = t; have_xi = 1; }
Branch: 2 branches
BranchTrueFalseTotal
if (!have_xi || t < xi) { xi = t; have_xi = 1; } 620 620 1240
if (!have_xi || t < xi) { xi = t; have_xi = 1; } 401 219 620
6931 }
6932 }
6933 660 ▶ score = have_xi ? stack_score(d0, omega, xi, dist_cut, omega_cut) : 0.0;
Branch: 1 branch
BranchTrueFalseTotal
score = have_xi ? stack_score(d0, omega, xi, dist_cut, omega_cut) : 0.0; 620 40 660
6934 //named in the order it is reported, so the two letters and the
6935 //two resname fields read the same way round
6936 660 tname[0] = bases[i].one; tname[1] = '-';
6937 660 tname[2] = bases[j].one; tname[3] = '\0';
6938 660 h = newHV();
6939 660 (void)hv_stores(h, "type", newSVpvn(tname, 3));
6940 660 pi_field(aTHX_ h, "chain1", 6, s->res_hv[bases[i].res], "chain", 5);
6941 660 pi_field(aTHX_ h, "residue1", 8, s->res_hv[bases[i].res], "key", 3);
6942 660 pi_field(aTHX_ h, "resname1", 8, s->res_hv[bases[i].res], "resname", 7);
6943 660 pi_field(aTHX_ h, "chain2", 6, s->res_hv[bases[j].res], "chain", 5);
6944 660 pi_field(aTHX_ h, "residue2", 8, s->res_hv[bases[j].res], "key", 3);
6945 660 pi_field(aTHX_ h, "resname2", 8, s->res_hv[bases[j].res], "resname", 7);
6946 660 (void)hv_stores(h, "distance", newSVnv(d0));
6947 660 (void)hv_stores(h, "omega", newSVnv(omega));
6948 660 ▶ if (have_xi) (void)hv_stores(h, "xi", newSVnv(xi));
Branch: 1 branch
BranchTrueFalseTotal
if (have_xi) (void)hv_stores(h, "xi", newSVnv(xi)); 620 40 660
6949 660 (void)hv_stores(h, "score", newSVnv(score));
6950 660 (void)hv_stores(h, "stacked", newSViv(score > 50.0 ? 1 : 0));
6951 660 av_push(out, newRV_noinc((SV *)h));
6952 660 ▶ if (store) {
Branch: 1 branch
BranchTrueFalseTotal
if (store) { 650 10 660
6953 650 ▶ stack_note(aTHX_ s->res_hv[bases[i].res], s->res_hv[bases[j].res],
Branch: 1 branch
BranchTrueFalseTotal
stack_note(aTHX_ s->res_hv[bases[i].res], s->res_hv[bases[j].res], 613 37 650
6954 tname, d0, omega, have_xi ? &xi : NULL, score, 1);
6955 650 tname[0] = bases[j].one; tname[2] = bases[i].one;
6956 650 ▶ stack_note(aTHX_ s->res_hv[bases[j].res], s->res_hv[bases[i].res],
Branch: 1 branch
BranchTrueFalseTotal
stack_note(aTHX_ s->res_hv[bases[j].res], s->res_hv[bases[i].res], 613 37 650
6957 tname, d0, omega, have_xi ? &xi : NULL, score, 0);
6958 }
6959 }
6960 }
6961 }
6962 105 grid_free(aTHX_ &g);
6963 105 Safefree(cx); Safefree(cy); Safefree(cz); Safefree(bases);
6964 105 return out;
6965 }
6966  
6967 /*Disulfide bonds, found by geometry.
6968  
6969 $info->{ssbond} is what the file *says* -- an SSBOND record, or an mmCIF
6970 _struct_conn row of type disulf -- and a deposited file is not obliged to be
6971 right or to say anything at all. This is the other half of that: the bonds the
6972 coordinates show, which a caller can compare with the declared ones. Neither is
6973 the authority; a disagreement is a fact about the entry, and 1AHW's four bonds
6974 are declared and found alike while 1A4K declares four of the eight it has,
6975 because the depositor listed one copy of a Fab that is in the file twice.
6976  
6977 The rule is mdtraj's, from Topology.create_disulfide_bonds() in
6978 mdtraj/core/topology.py: a residue named CYS that has an SG and has no HG,
6979 paired with another when the two SG atoms are less than 0.3 nm apart. The HG
6980 test is what separates a cysteine whose thiol hydrogen was modelled -- so it is
6981 reduced, and holds no bond -- from one that was not; a crystal structure with no
6982 hydrogens in it has no HG anywhere and every cysteine is a candidate, which is
6983 right.
6984  
6985 **mdtraj's own implementation of that rule never fires**, and t/features.t
6986 cannot call it. PDBTrajectoryFile hands create_disulfide_bonds() the positions
6987 it read out of the file, which are angstrom, and the function compares them with
6988 0.3 -- "this is supposed to be nm. I think we're good", says the comment beside
6989 it. So it tests for an SG-SG separation under 0.3 A, which no pair of atoms has,
6990 and finds nothing on any file: measured on 1A4K, 8 pairs under 0.3 nm and 0
6991 under 0.3 A. The SG-SG bonds that do turn up in mdtraj's topology.bonds come
6992 from the file's own CONECT records instead, which is the declared answer wearing
6993 a different hat. So what t/data/features.txt freezes is mdtraj's rule
6994 transcribed into numpy with its units made consistent -- the same thing the
6995 float64 surface column is, and for the same reason.
6996  
6997 CYS and not CYX: AMBER and CHARMM rename a bonded cysteine, and matching those
6998 spellings would be matching something the reference implementation does not. A
6999 structure that has been through a force field needs its residues named the way
7000 the archive names them.*/
7001 typedef struct {
7002 NV x, y, z;//where the SG is
7003 UV res;//which residue it belongs to
7004 } sulfur_t;
7005  
7006 607 static UV sulfur_find(pTHX_ structset *CSP_RESTRICT s, sulfur_t *CSP_RESTRICT *CSP_RESTRICT out){
7007 607 sulfur_t *sg = NULL;
7008 607 UV cap = 0, n = 0, r;
7009 607 *out = NULL;
7010 12209 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 11602 607 12209
7011 HV *atoms;
7012 NV x, y, z;
7013 11603 ▶ if (s->res_key[r] != K3('C','Y','S')) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (s->res_key[r] != K3('C','Y','S')) continue; 11241 361 11602
7014 361 atoms = hvf_hv(aTHX_ s->res_hv[r], "atoms", 5);
7015 361 ▶ if (!atoms) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!atoms) continue; 0 361 361
7016 //a modelled thiol hydrogen means a reduced cysteine, which holds no bond
7017 361 ▶ if (hv_exists(atoms, "HG", 2)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (hv_exists(atoms, "HG", 2)) continue; 1 360 361
7018 360 ▶ if (!atom_xyz(aTHX_ atoms, "SG", &x, &y, &z)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ atoms, "SG", &x, &y, &z)) continue; 0 360 360
7019 360 ▶ if (n == cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == cap) { 161 199 360
7020 161 ▶ cap = cap ? cap * 2 : 16;
Branch: 1 branch
BranchTrueFalseTotal
cap = cap ? cap * 2 : 16; 0 161 161
7021 161 ▶ Renew(sg, cap, sulfur_t);
Branch: 1 branch
BranchTrueFalseTotal
Renew(sg, cap, sulfur_t); 0 161 161
7022 }
7023 360 sg[n].x = x; sg[n].y = y; sg[n].z = z; sg[n].res = r;
7024 360 n++;
7025 }
7026 607 *out = sg;
7027 607 return n;
7028 }
7029  
7030 /*disulfides() -- every pair of those within the cutoff.
7031  
7032 Through the same grid the surface uses, on the sulphurs alone. A structure has
7033 a few dozen cysteines and comparing every pair would cost nothing, which is what
7034 mdtraj does; the grid is here because it is already written and because a
7035 ribosome-sized entry has thousands.
7036  
7037 A cysteine can hold only one disulfide, so a second partner means something is
7038 wrong with the entry -- alternate conformers refined into each other, most often
7039 -- and both pairs are reported rather than one of them silently dropped.*/
7040 //the partner half of one bond, pushed onto a residue's own list
7041 54 static void ss_note(pTHX_ HV *CSP_RESTRICT res, HV *CSP_RESTRICT partner, NV d){
7042 54 SV **slot = hv_fetch(res, "disulfide", 9, 0);
7043 AV *list;
7044 HV *e;
7045 54 ▶ if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) {
Branch: 4 branches
BranchTrueFalseTotal
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) { 3 51 54
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) { 3 0 3
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) { 3 0 3
if (slot && *slot && SvROK(*slot) && SvTYPE(SvRV(*slot)) == SVt_PVAV) { 3 0 3
7046 3 list = (AV *)SvRV(*slot);
7047 } else {
7048 51 list = newAV();
7049 51 (void)hv_stores(res, "disulfide", newRV_noinc((SV *)list));
7050 }
7051 54 e = newHV();
7052 54 pi_field(aTHX_ e, "chain", 5, partner, "chain", 5);
7053 54 pi_field(aTHX_ e, "residue", 7, partner, "key", 3);
7054 54 (void)hv_stores(e, "distance", newSVnv(d));
7055 54 av_push(list, newRV_noinc((SV *)e));
7056 54 }
7057  
7058 607 static AV *disulfides(pTHX_ structset *CSP_RESTRICT s, NV cut, bool store){
7059 607 AV *out = newAV();
7060 607 sulfur_t *sg = NULL;
7061 607 NV *sx = NULL, *sy = NULL, *sz = NULL;
7062 cell_grid g;
7063 UV n, i;
7064  
7065 607 n = sulfur_find(aTHX_ s, &sg);
7066 607 ▶ if (n < 2) { Safefree(sg); return out; }
Branch: 1 branch
BranchTrueFalseTotal
if (n < 2) { Safefree(sg); return out; } 447 160 607
7067 160 ▶ Newx(sx, n, NV); Newx(sy, n, NV); Newx(sz, n, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(sx, n, NV); Newx(sy, n, NV); Newx(sz, n, NV); 0 160 160
Newx(sx, n, NV); Newx(sy, n, NV); Newx(sz, n, NV); 0 160 160
Newx(sx, n, NV); Newx(sy, n, NV); Newx(sz, n, NV); 0 160 160
7068 519 ▶ for (i = 0; i < n; i++) { sx[i] = sg[i].x; sy[i] = sg[i].y; sz[i] = sg[i].z; }
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { sx[i] = sg[i].x; sy[i] = sg[i].y; sz[i] = sg[i].z; } 359 160 519
7069 /*Clear what an earlier call left on these residues, so that asking twice
7070 replaces the answer rather than adding to it. The candidate set is decided
7071 by residue name and atom names alone, never by the cutoff, so the residues
7072 cleared here are exactly the ones a previous call could have written to.*/
7073 160 ▶ if (store)
Branch: 1 branch
BranchTrueFalseTotal
if (store) 160 0 160
7074 519 ▶ for (i = 0; i < n; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) 359 160 519
7075 359 (void)hv_delete(s->res_hv[sg[i].res], "disulfide", 9, G_DISCARD);
7076 160 grid_build(aTHX_ &g, sx, sy, sz, n, cut);
7077  
7078 519 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 359 160 519
7079 UV bx, by, bz;
7080 359 UV ci = grid_axis(sx[i] - g.x0, g.cell, g.nx);
7081 359 UV cj = grid_axis(sy[i] - g.y0, g.cell, g.ny);
7082 359 UV ck = grid_axis(sz[i] - g.z0, g.cell, g.nz);
7083 359 ▶ UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1;
Branch: 2 branches
BranchTrueFalseTotal
UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1; 179 180 359
UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1; 168 191 359
7084 359 ▶ UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1;
Branch: 2 branches
BranchTrueFalseTotal
UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1; 181 178 359
UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1; 198 161 359
7085 359 ▶ UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1;
Branch: 2 branches
BranchTrueFalseTotal
UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1; 195 164 359
UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1; 186 173 359
7086 1065 ▶ for (bx = ax0; bx <= ax1; bx++)
Branch: 1 branch
BranchTrueFalseTotal
for (bx = ax0; bx <= ax1; bx++) 706 359 1065
7087 2160 ▶ for (by = ay0; by <= ay1; by++)
Branch: 1 branch
BranchTrueFalseTotal
for (by = ay0; by <= ay1; by++) 1454 706 2160
7088 4498 ▶ for (bz = az0; bz <= az1; bz++) {
Branch: 1 branch
BranchTrueFalseTotal
for (bz = az0; bz <= az1; bz++) { 3044 1454 4498
7089 3044 UV cell = (bx * g.ny + by) * g.nz + bz, p;
7090 3469 ▶ for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = g.start[cell]; p < g.start[cell + 1]; p++) { 425 3044 3469
7091 425 UV j = g.idx[p];
7092 NV dx, dy, dz, d;
7093 HV *h;
7094 425 ▶ if (j <= i) continue;//each pair once
Branch: 1 branch
BranchTrueFalseTotal
if (j <= i) continue;//each pair once 392 33 425
7095 //two SG atoms of one residue are alternate conformers of the
7096 //same sulphur, not two sulphurs bonded to each other
7097 33 ▶ if (sg[i].res == sg[j].res) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (sg[i].res == sg[j].res) continue; 0 33 33
7098 33 dx = sx[j] - sx[i]; dy = sy[j] - sy[i]; dz = sz[j] - sz[i];
7099 33 d = nv_sqrt(dx * dx + dy * dy + dz * dz);
7100 33 ▶ if (!(d < cut)) continue;//`<', as the reference has it
Branch: 1 branch
BranchTrueFalseTotal
if (!(d < cut)) continue;//`<', as the reference has it 6 27 33
7101 27 h = newHV();
7102 27 pi_field(aTHX_ h, "chain1", 6, s->res_hv[sg[i].res], "chain", 5);
7103 27 pi_field(aTHX_ h, "residue1", 8, s->res_hv[sg[i].res], "key", 3);
7104 27 pi_field(aTHX_ h, "chain2", 6, s->res_hv[sg[j].res], "chain", 5);
7105 27 pi_field(aTHX_ h, "residue2", 8, s->res_hv[sg[j].res], "key", 3);
7106 27 (void)hv_stores(h, "distance", newSVnv(d));
7107 27 av_push(out, newRV_noinc((SV *)h));
7108 27 ▶ if (store) {
Branch: 1 branch
BranchTrueFalseTotal
if (store) { 27 0 27
7109 27 ss_note(aTHX_ s->res_hv[sg[i].res], s->res_hv[sg[j].res], d);
7110 27 ss_note(aTHX_ s->res_hv[sg[j].res], s->res_hv[sg[i].res], d);
7111 }
7112 }
7113 }
7114 }
7115 160 grid_free(aTHX_ &g);
7116 160 Safefree(sx); Safefree(sy); Safefree(sz);
7117 160 Safefree(sg);
7118 160 return out;
7119 }
7120  
7121 /*Backbone and side chain torsion angles.
7122  
7123 phi, psi and omega say how the backbone is folded and chi1..chi5 how each side
7124 chain is rotated, and between them they are what a Ramachandran plot and a
7125 rotamer library are drawn from. The atoms of each are mdtraj's, from
7126 PHI_ATOMS, PSI_ATOMS, OMEGA_ATOMS and CHI1_ATOMS..CHI5_ATOMS in
7127 mdtraj/geometry/dihedral.py:
7128  
7129 phi C of the residue before, then N, CA, C
7130 psi N, CA, C, then N of the residue after
7131 omega CA, C, then N and CA of the residue after
7132  
7133 A chi has alternatives, because the fourth atom is whatever that side chain
7134 happens to be built from: chi1's is CG for most residues, CG1 for valine and
7135 isoleucine, SG for cysteine, OG for serine and OG1 for threonine. The first
7136 alternative all of whose atoms are present is the one used, which is how mdtraj
7137 picks too, and each chi is looked for on its own -- a residue that has chi2 and
7138 not chi1 gets chi2 and a hole where chi1 would be, rather than neither.
7139  
7140 **Where this departs from mdtraj, and why.** mdtraj takes the residue before
7141 and after to be the ones next to this one in the file, within the same chain,
7142 and asks nothing else of them. A chain with a gap in it -- residues nobody
7143 could see, which is most crystal structures -- therefore gets a phi and a psi
7144 measured across the gap, between two residues that are not bonded and may be
7145 half the protein apart. That is a number rather than an answer. So the link is
7146 tested here: the C of the earlier residue must be within 1.8 A of the N of the
7147 later one, which is the distance Biopython's Bio.PDB.Polypeptide.PPBuilder uses
7148 to decide the same question (its `radius' argument, default 1.8). A chi needs
7149 no link, being inside one residue, and is unaffected.
7150  
7151 t/features.t holds both halves of that: mdtraj's angle for every residue whose
7152 neighbours really are bonded, and nothing at all for the residues where it is
7153 measuring across a gap.*/
7154 #define CHI_MAX 5 //chi1 to chi5, which is as many as any side chain has
7155  
7156 typedef struct {
7157 const char *const *atom;//the four atom names
7158 unsigned short n;//how many alternatives follow this one
7159 } chi_alt;
7160  
7161 static const char *const chi1_a[5][4] = {
7162 { "N", "CA", "CB", "CG" }, { "N", "CA", "CB", "CG1" }, { "N", "CA", "CB", "SG" },
7163 { "N", "CA", "CB", "OG" }, { "N", "CA", "CB", "OG1" }
7164 };
7165 static const char *const chi2_a[6][4] = {
7166 { "CA", "CB", "CG", "CD" }, { "CA", "CB", "CG", "CD1" }, { "CA", "CB", "CG1", "CD1" },
7167 { "CA", "CB", "CG", "OD1" }, { "CA", "CB", "CG", "ND1" }, { "CA", "CB", "CG", "SD" }
7168 };
7169 static const char *const chi3_a[4][4] = {
7170 { "CB", "CG", "CD", "NE" }, { "CB", "CG", "CD", "CE" },
7171 { "CB", "CG", "CD", "OE1" }, { "CB", "CG", "SD", "CE" }
7172 };
7173 static const char *const chi4_a[2][4] = {
7174 { "CG", "CD", "NE", "CZ" }, { "CG", "CD", "CE", "NZ" }
7175 };
7176 static const char *const chi5_a[1][4] = { { "CD", "NE", "CZ", "NH1" } };
7177  
7178 /*The torsion angle about the p1-p2 bond, in radians, by the usual construction:
7179 project the two outer bonds onto the plane across the middle one and take the
7180 angle between them, signed by which side of that plane the second falls on.
7181  
7182 False when there is no such angle, which is when either outer bond lies along
7183 the middle one -- four collinear atoms have no torsion, and every value is as
7184 good as every other. A structure with real coordinates never gets close, and
7185 one built on a straight line (t/data/mini.pdb, whose atoms are laid out along a
7186 line on purpose) is entirely made of them. The alternative is to return the
7187 zero that atan2(0, 0) gives, which is a number where there is no answer.
7188  
7189 The test is on the shorter projected length against the bond it was projected
7190 from, which is the sine of the angle between them, and the two cases are nowhere
7191 near each other. Measured: over phi, psi, omega, chi1 and chi2 of 1A42 the
7192 smallest that ratio gets is 0.736, because a real bond angle is nowhere near
7193 straight; over the deliberately collinear t/data/mini.pdb it runs from 5.4e-7 to
7194 1.1e-6, which is float32 rounding on coordinates that are collinear exactly.
7195 1e-3 sits a thousand times above the second and seven hundred times below the
7196 first. t/data/features.py applies the same rule with the same constant, so the
7197 frozen answer and this agree about which angles exist.*/
7198 #define CSP_COLLINEAR 1e-3
7199  
7200 33902 static bool dihedral4(const NV *CSP_RESTRICT p0, const NV *CSP_RESTRICT p1, const NV *CSP_RESTRICT p2, const NV *CSP_RESTRICT p3, NV *CSP_RESTRICT out){
7201 NV b0[3], b1[3], b2[3], v[3], w[3], cr[3], len, d0, d2, x, y;
7202 unsigned short k;
7203 135608 ▶ for (k = 0; k < 3; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < 3; k++) { 101706 33902 135608
7204 101706 b0[k] = p0[k] - p1[k];
7205 101706 b1[k] = p2[k] - p1[k];
7206 101706 b2[k] = p3[k] - p2[k];
7207 }
7208 33902 len = nv_sqrt(b1[0] * b1[0] + b1[1] * b1[1] + b1[2] * b1[2]);
7209 33902 ▶ if (!(len > 0.0)) return 0;//two atoms at one position: no bond, no angle
Branch: 1 branch
BranchTrueFalseTotal
if (!(len > 0.0)) return 0;//two atoms at one position: no bond, no angle 2 33900 33902
7210 135600 ▶ for (k = 0; k < 3; k++) b1[k] /= len;
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < 3; k++) b1[k] /= len; 101700 33900 135600
7211 33900 d0 = b0[0] * b1[0] + b0[1] * b1[1] + b0[2] * b1[2];
7212 33900 d2 = b2[0] * b1[0] + b2[1] * b1[1] + b2[2] * b1[2];
7213 135600 ▶ for (k = 0; k < 3; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < 3; k++) { 101700 33900 135600
7214 101700 v[k] = b0[k] - d0 * b1[k];
7215 101700 w[k] = b2[k] - d2 * b1[k];
7216 }
7217 {
7218 33900 NV l0 = nv_sqrt(b0[0] * b0[0] + b0[1] * b0[1] + b0[2] * b0[2]);
7219 33900 NV l2 = nv_sqrt(b2[0] * b2[0] + b2[1] * b2[1] + b2[2] * b2[2]);
7220 33900 NV lv = nv_sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
7221 33900 NV lw = nv_sqrt(w[0] * w[0] + w[1] * w[1] + w[2] * w[2]);
7222 33900 ▶ if (!(l0 > 0.0) || !(l2 > 0.0)) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!(l0 > 0.0) || !(l2 > 0.0)) return 0; 33900 0 33900
if (!(l0 > 0.0) || !(l2 > 0.0)) return 0; 0 33900 33900
7223 33900 ▶ if (lv <= l0 * CSP_COLLINEAR || lw <= l2 * CSP_COLLINEAR) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (lv <= l0 * CSP_COLLINEAR || lw <= l2 * CSP_COLLINEAR) return 0; 32732 1168 33900
if (lv <= l0 * CSP_COLLINEAR || lw <= l2 * CSP_COLLINEAR) return 0; 1150 31582 32732
7224 }
7225 31582 cr[0] = b1[1] * v[2] - b1[2] * v[1];
7226 31582 cr[1] = b1[2] * v[0] - b1[0] * v[2];
7227 31582 cr[2] = b1[0] * v[1] - b1[1] * v[0];
7228 31582 x = v[0] * w[0] + v[1] * w[1] + v[2] * w[2];
7229 31582 y = cr[0] * w[0] + cr[1] * w[1] + cr[2] * w[2];
7230 /*an infinite coordinate passes every test above and arrives here as a
7231 NaN, which is no angle: refused, as a point that makes none is*/
7232 {
7233 31582 const NV angle = nv_atan2(y, x);
7234 31582 ▶ if (!nv_is_finite(angle)) return FALSE;
Branch: 1 branch
BranchTrueFalseTotal
if (!nv_is_finite(angle)) return FALSE; 1 31581 31582
7235 31581 *out = angle;
7236 }
7237 31581 return 1;
7238 }
7239  
7240 //the four named atoms of one residue, or of a pair of them: `which' says where
7241 //each comes from, 0 for the first residue's hash and 1 for the second's
7242 251201 static bool four_atoms(pTHX_ HV *CSP_RESTRICT a, HV *CSP_RESTRICT b,
7243 const char *const *CSP_RESTRICT name,
7244 const unsigned short *CSP_RESTRICT which,
7245 NV p[4][3])
7246 {
7247 506796 ▶ for (unsigned short k = 0; k < 4; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < 4; k++) { 472894 33902 506796
7248 472894 ▶ HV *from = which[k] ? b : a;
Branch: 1 branch
BranchTrueFalseTotal
HV *from = which[k] ? b : a; 35955 436939 472894
7249 472894 ▶ if (!from) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!from) return 0; 0 472894 472894
7250 472894 ▶ if (!atom_xyz(aTHX_ from, name[k], &p[k][0], &p[k][1], &p[k][2])) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ from, name[k], &p[k][0], &p[k][1], &p[k][2])) return 0; 217299 255595 472894
7251 }
7252 33902 return 1;
7253 }
7254  
7255 //Biopython's PPBuilder radius: two residues are peptide-bonded when the C of
7256 //the earlier is this close to the N of the later
7257 #define CSP_PEPTIDE_BOND 1.8
7258  
7259 //the backbone of every residue of the walk, read the first time it is asked for
7260 33378 static const bb_xyz *bb_get(pTHX_ structset *CSP_RESTRICT s)
7261 {
7262 33378 ▶ if (s->bb) return s->bb;
Branch: 1 branch
BranchTrueFalseTotal
if (s->bb) return s->bb; 32765 613 33378
7263 613 ▶ Newxz(s->bb, s->n_res ? s->n_res : 1, bb_xyz);
Branch: 3 branches
BranchTrueFalseTotal
Newxz(s->bb, s->n_res ? s->n_res : 1, bb_xyz); 584 29 613
Newxz(s->bb, s->n_res ? s->n_res : 1, bb_xyz); 0 584 584
Newxz(s->bb, s->n_res ? s->n_res : 1, bb_xyz); 584 29 613
7264 12595 ▶ for (UV r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV r = 0; r < s->n_res; r++) { 11982 613 12595
7265 11982 bb_xyz *b = &s->bb[r];
7266 11982 HV *at = hvf_hv(aTHX_ s->res_hv[r], "atoms", 5);
7267 11982 ▶ if (!at) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!at) continue; 0 11982 11982
7268 11982 b->has_n = atom_xyz(aTHX_ at, "N", &b->n[0], &b->n[1], &b->n[2]);
7269 11982 b->has_ca = atom_xyz(aTHX_ at, "CA", &b->ca[0], &b->ca[1], &b->ca[2]);
7270 11982 b->has_c = atom_xyz(aTHX_ at, "C", &b->c[0], &b->c[1], &b->c[2]);
7271 11982 b->has_o = atom_xyz(aTHX_ at, "O", &b->o[0], &b->o[1], &b->o[2]);
7272 }
7273 613 return s->bb;
7274 }
7275  
7276 //is residue prev's C within cut of residue next's N, both residues of the walk
7277 32194 static bool peptide_linked(pTHX_ structset *CSP_RESTRICT s, UV prev, UV next, NV cut){
7278 32194 const bb_xyz *bb = bb_get(aTHX_ s);
7279 NV dx, dy, dz;
7280 32194 ▶ if (!bb[prev].has_c || !bb[next].has_n) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!bb[prev].has_c || !bb[next].has_n) return 0; 18565 13629 32194
if (!bb[prev].has_c || !bb[next].has_n) return 0; 715 17850 18565
7281 17850 dx = bb[next].n[0] - bb[prev].c[0];
7282 17850 dy = bb[next].n[1] - bb[prev].c[1];
7283 17850 dz = bb[next].n[2] - bb[prev].c[2];
7284 17850 return (dx * dx + dy * dy + dz * dz) < cut * cut;
7285 }
7286  
7287 //one chi, from whichever of its alternatives the residue is built from
7288 56390 static bool chi_of(pTHX_ HV *CSP_RESTRICT atoms, const char *const alt[][4], unsigned short n_alt, NV *CSP_RESTRICT out){
7289 static const unsigned short here[4] = { 0, 0, 0, 0 };
7290 unsigned short k;
7291 220935 ▶ for (k = 0; k < n_alt; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n_alt; k++) { 173828 47107 220935
7292 NV p[4][3];
7293 173828 ▶ if (!four_atoms(aTHX_ atoms, NULL, alt[k], here, p)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!four_atoms(aTHX_ atoms, NULL, alt[k], here, p)) continue; 164545 9283 173828
7294 9283 return dihedral4(p[0], p[1], p[2], p[3], out);
7295 }
7296 47107 return 0;
7297 }
7298  
7299 /*Nucleic acid torsion angles, and the shape of the sugar ring.
7300  
7301 A nucleotide's conformation is six backbone torsions, one glycosidic torsion and
7302 the pucker of its ribose, and between them they are what tells an A-form helix
7303 from a B-form one and either from what a loop does. The names and the atoms of
7304 each are the IUPAC-IUB Joint Commission on Biochemical Nomenclature's (1983)
7305 "Abbreviations and symbols for the description of conformations of
7306 polynucleotide chains", Eur J Biochem 131:9-15:
7307  
7308 alpha O3' of the residue before, then P, O5', C5'
7309 beta P, O5', C5', C4'
7310 gamma O5', C5', C4', C3'
7311 delta C5', C4', C3', O3'
7312 epsilon C4', C3', O3', then P of the residue after
7313 zeta C3', O3', then P and O5' of the residue after
7314 chi O4', C1', then N9 and C4 of a purine or N1 and C2 of a pyrimidine
7315 nu0..nu4 the ring itself, C4'-O4'-C1'-C2' round to C3'-C4'-O4'-C1'
7316  
7317 chi is stored under the same key an amino acid's side chain torsions are, and no
7318 residue has both -- an amino acid has no C1' and a nucleotide has no CB -- but an
7319 amino acid's chi is a list of up to five and a nucleotide's is one number.
7320  
7321 Which four atoms it is turns on N9 rather than on trying one quadruple and then
7322 the other: only a purine has an N9, while a purine has N1 and C2 as well as N9
7323 and C4, so a purine missing its C4 would fall through to the pyrimidine atoms
7324 and answer a different torsion under the same name. Asking for the atom that
7325 separates the two cases costs one lookup and cannot do that.
7326  
7327 Nothing here asks whether the residue is a nucleotide: the atoms decide, as they
7328 do for phi and psi. A protein residue has no O3' and gets none of these, and a
7329 nucleotide sitting in a binding site as a ligand rather than in a chain gets the
7330 ones its own atoms define, which is the right answer rather than an accident.
7331  
7332 alpha needs the residue before and epsilon and zeta the one after, and both
7333 links are tested rather than assumed, for the reason phi and psi test theirs: a
7334 gap in the model puts two residues next to each other that are not bonded, and a
7335 torsion across one is a number rather than an answer. The test is gemmi's, from
7336 are_connected() in gemmi/polyheur.hpp -- an O3'-to-P separation under 1.5 times
7337 the 1.6 A ideal bond, so 2.4 A -- which is the polynucleotide half of the same
7338 function whose polypeptide half supplies the 1.8 A used above.
7339  
7340 **The pucker.** Altona, C; Sundaralingam, M (1972) J Am Chem Soc 94(23):8205-12
7341 describes the ring with two numbers instead of five, on the observation that the
7342 five nu are one sinusoid sampled at five points: a phase angle P saying which of
7343 the ring's ten envelope shapes it is nearest, and an amplitude nu_max saying how
7344 far from flat it is. Their equations 1 and 2:
7345  
7346 tan P = ((nu4 + nu1) - (nu3 + nu0)) / (2 * nu2 * (sin 36 + sin 72))
7347 nu_max = nu2 / cos P
7348  
7349 Written as an atan2 of the two halves rather than a division, which puts P in
7350 the right half of the circle without a separate test: the denominator carries
7351 the sign of nu2, so cos P and nu2 always agree in sign and nu_max comes out
7352 positive, which is the paper's convention. Both sides of the fraction are
7353 linear in the nu, so the units cancel and the radians this file works in give
7354 the same P as the degrees the paper is written in.
7355  
7356 P is reported in 0 to 360 rather than the -180 to 180 every other angle here is
7357 in, because the cycle is conventionally read that way and the pucker names are
7358 ranges of it. They are the ten envelope forms, each the 36 degrees of P centred
7359 on it, as tabulated by Altona and Sundaralingam and by Saenger, W (1984)
7360 Principles of Nucleic Acid Structure, chapter 2. C3'-endo (P near 18) is what
7361 an A-form helix and almost every ribose are in and C2'-endo (P near 162) what a
7362 B-form helix is, so the name is often the whole answer.
7363  
7364 **glycosidic** is which side of the sugar the base is turned to, read off chi:
7365 syn within 90 degrees of 0, anti within 90 of 180, which is Saenger's division
7366 in the same chapter and the one DSSR reports. Nearly everything is anti, which
7367 is what makes a syn guanosine worth being told about. It is a bisection and not
7368 a classification with a gap, so the band around -90 that the literature calls
7369 high-anti comes back here as syn: chi itself is beside it for a caller who wants
7370 the third name.*/
7371  
7372 //gemmi's are_connected(): 1.5 times the 1.6 A ideal O3'-P bond
7373 #define CSP_PHOSPHO_BOND 2.4
7374  
7375 /*The ten envelope forms, each named for the ring atom furthest out of the plane
7376 of the other four and which face of the ring it is on. Entry k covers the phase
7377 angle from 36k to 36(k+1) degrees.*/
7378 static const char *const nuc_pucker[10] = {
7379 "C3'-endo", "C4'-exo", "O4'-endo", "C1'-exo", "C2'-endo",
7380 "C3'-exo", "C4'-endo", "O4'-exo", "C1'-endo", "C2'-exo"
7381 };
7382  
7383 //the keys below, so that asking twice replaces the answer rather than leaving
7384 //half of an older one beside it
7385 static const char *const nuc_keys[] = {
7386 "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "glycosidic",
7387 "nu", "pucker", "pucker_phase", "pucker_amplitude"
7388 };
7389  
7390 //gemmi's nucleotide bond: the O3' of the earlier residue this close to the P of
7391 //the later one
7392 22556 static bool nucleotide_linked(pTHX_ HV *CSP_RESTRICT prev, HV *CSP_RESTRICT next, NV cut)
7393 {
7394 HV *pa, *na;
7395 NV ox, oy, oz, px, py, pz, dx, dy, dz;
7396 22556 ▶ if (!prev || !next) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!prev || !next) return 0; 21773 783 22556
if (!prev || !next) return 0; 783 20990 21773
7397 20990 pa = hvf_hv(aTHX_ prev, "atoms", 5);
7398 20990 na = hvf_hv(aTHX_ next, "atoms", 5);
7399 20990 ▶ if (!pa || !na) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (!pa || !na) return 0; 20990 0 20990
if (!pa || !na) return 0; 0 20990 20990
7400 20990 ▶ if (!atom_xyz(aTHX_ pa, "O3'", &ox, &oy, &oz)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ pa, "O3'", &ox, &oy, &oz)) return 0; 19732 1258 20990
7401 1258 ▶ if (!atom_xyz(aTHX_ na, "P", &px, &py, &pz)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ na, "P", &px, &py, &pz)) return 0; 0 1258 1258
7402 1258 dx = px - ox; dy = py - oy; dz = pz - oz;
7403 1258 return (dx * dx + dy * dy + dz * dz) < cut * cut;
7404 }
7405  
7406 //one nucleotide's torsions, onto its residue hash. Degrees, and a torsion
7407 //whose atoms are not all present simply has no key.
7408 11278 static void nuc_torsions(pTHX_ HV *CSP_RESTRICT me, HV *CSP_RESTRICT my_at,
7409 HV *CSP_RESTRICT pv_at, HV *CSP_RESTRICT nx_at,
7410 bool prev_linked, bool next_linked)
7411 {
7412 static const unsigned short here[4] = { 0, 0, 0, 0 };
7413 static const unsigned short prev_w[4] = { 0, 1, 1, 1 };
7414 static const unsigned short eps_w[4] = { 0, 0, 0, 1 };
7415 static const unsigned short zeta_w[4] = { 0, 0, 1, 1 };
7416 static const char *const alpha_n[4] = { "O3'", "P", "O5'", "C5'" };
7417 static const char *const beta_n[4] = { "P", "O5'", "C5'", "C4'" };
7418 static const char *const gamma_n[4] = { "O5'", "C5'", "C4'", "C3'" };
7419 static const char *const delta_n[4] = { "C5'", "C4'", "C3'", "O3'" };
7420 static const char *const eps_n[4] = { "C4'", "C3'", "O3'", "P" };
7421 static const char *const zeta_n[4] = { "C3'", "O3'", "P", "O5'" };
7422 static const char *const chi_pur[4] = { "O4'", "C1'", "N9", "C4" };
7423 static const char *const chi_pyr[4] = { "O4'", "C1'", "N1", "C2" };
7424 static const char *const nu_n[5][4] = {
7425 { "C4'", "O4'", "C1'", "C2'" }, { "O4'", "C1'", "C2'", "C3'" },
7426 { "C1'", "C2'", "C3'", "C4'" }, { "C2'", "C3'", "C4'", "O4'" },
7427 { "C3'", "C4'", "O4'", "C1'" }
7428 };
7429 11278 const NV to_deg = 180.0 / CSP_PI;
7430 NV p[4][3], v, nu[5];
7431 11278 bool have_nu = 1;
7432 unsigned short k;
7433  
7434 135336 ▶ for (k = 0; k < (unsigned short)C_ARRAY_LENGTH(nuc_keys); k++)
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < (unsigned short)C_ARRAY_LENGTH(nuc_keys); k++) 124058 11278 135336
7435 124058 (void)hv_delete(me, nuc_keys[k], (I32)strlen(nuc_keys[k]), G_DISCARD);
7436  
7437 11278 ▶ if (prev_linked && four_atoms(aTHX_ pv_at, my_at, alpha_n, prev_w, p)
Branch: 2 branches
BranchTrueFalseTotal
if (prev_linked && four_atoms(aTHX_ pv_at, my_at, alpha_n, prev_w, p) 598 10680 11278
if (prev_linked && four_atoms(aTHX_ pv_at, my_at, alpha_n, prev_w, p) 596 2 598
7438 596 ▶ && dihedral4(p[0], p[1], p[2], p[3], &v))
Branch: 1 branch
BranchTrueFalseTotal
&& dihedral4(p[0], p[1], p[2], p[3], &v)) 596 0 596
7439 596 (void)hv_stores(me, "alpha", newSVnv(v * to_deg));
7440 11278 ▶ if (four_atoms(aTHX_ my_at, NULL, beta_n, here, p)
Branch: 1 branch
BranchTrueFalseTotal
if (four_atoms(aTHX_ my_at, NULL, beta_n, here, p) 688 10590 11278
7441 688 ▶ && dihedral4(p[0], p[1], p[2], p[3], &v))
Branch: 1 branch
BranchTrueFalseTotal
&& dihedral4(p[0], p[1], p[2], p[3], &v)) 688 0 688
7442 688 (void)hv_stores(me, "beta", newSVnv(v * to_deg));
7443 11278 ▶ if (four_atoms(aTHX_ my_at, NULL, gamma_n, here, p)
Branch: 1 branch
BranchTrueFalseTotal
if (four_atoms(aTHX_ my_at, NULL, gamma_n, here, p) 746 10532 11278
7444 746 ▶ && dihedral4(p[0], p[1], p[2], p[3], &v))
Branch: 1 branch
BranchTrueFalseTotal
&& dihedral4(p[0], p[1], p[2], p[3], &v)) 746 0 746
7445 746 (void)hv_stores(me, "gamma", newSVnv(v * to_deg));
7446 11278 ▶ if (four_atoms(aTHX_ my_at, NULL, delta_n, here, p)
Branch: 1 branch
BranchTrueFalseTotal
if (four_atoms(aTHX_ my_at, NULL, delta_n, here, p) 746 10532 11278
7447 746 ▶ && dihedral4(p[0], p[1], p[2], p[3], &v))
Branch: 1 branch
BranchTrueFalseTotal
&& dihedral4(p[0], p[1], p[2], p[3], &v)) 746 0 746
7448 746 (void)hv_stores(me, "delta", newSVnv(v * to_deg));
7449 11278 ▶ if (next_linked) {
Branch: 1 branch
BranchTrueFalseTotal
if (next_linked) { 598 10680 11278
7450 598 ▶ if (four_atoms(aTHX_ my_at, nx_at, eps_n, eps_w, p)
Branch: 1 branch
BranchTrueFalseTotal
if (four_atoms(aTHX_ my_at, nx_at, eps_n, eps_w, p) 596 2 598
7451 596 ▶ && dihedral4(p[0], p[1], p[2], p[3], &v))
Branch: 1 branch
BranchTrueFalseTotal
&& dihedral4(p[0], p[1], p[2], p[3], &v)) 596 0 596
7452 596 (void)hv_stores(me, "epsilon", newSVnv(v * to_deg));
7453 598 ▶ if (four_atoms(aTHX_ my_at, nx_at, zeta_n, zeta_w, p)
Branch: 1 branch
BranchTrueFalseTotal
if (four_atoms(aTHX_ my_at, nx_at, zeta_n, zeta_w, p) 596 2 598
7454 596 ▶ && dihedral4(p[0], p[1], p[2], p[3], &v))
Branch: 1 branch
BranchTrueFalseTotal
&& dihedral4(p[0], p[1], p[2], p[3], &v)) 596 0 596
7455 596 (void)hv_stores(me, "zeta", newSVnv(v * to_deg));
7456 }
7457 {
7458 NV n9[3];
7459 11278 const char *const *CSP_RESTRICT chi_n =
7460 11278 ▶ atom_xyz(aTHX_ my_at, "N9", &n9[0], &n9[1], &n9[2]) ? chi_pur : chi_pyr;
Branch: 1 branch
BranchTrueFalseTotal
atom_xyz(aTHX_ my_at, "N9", &n9[0], &n9[1], &n9[2]) ? chi_pur : chi_pyr; 424 10854 11278
7461 11278 ▶ if (four_atoms(aTHX_ my_at, NULL, chi_n, here, p)
Branch: 1 branch
BranchTrueFalseTotal
if (four_atoms(aTHX_ my_at, NULL, chi_n, here, p) 746 10532 11278
7462 746 ▶ && dihedral4(p[0], p[1], p[2], p[3], &v)) {
Branch: 1 branch
BranchTrueFalseTotal
&& dihedral4(p[0], p[1], p[2], p[3], &v)) { 746 0 746
7463 746 const NV deg = v * to_deg;
7464 746 (void)hv_stores(me, "chi", newSVnv(deg));
7465 746 ▶ (void)hv_stores(me, "glycosidic",
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(me, "glycosidic", 50 696 746
7466 newSVpv(nv_fabs(deg) <= 90.0 ? "syn" : "anti", 0));
7467 }
7468 }
7469  
7470 15003 ▶ for (k = 0; k < 5; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < 5; k++) { 14258 745 15003
7471 14258 ▶ if (four_atoms(aTHX_ my_at, NULL, nu_n[k], here, p)
Branch: 1 branch
BranchTrueFalseTotal
if (four_atoms(aTHX_ my_at, NULL, nu_n[k], here, p) 3726 10532 14258
7472 3726 ▶ && dihedral4(p[0], p[1], p[2], p[3], &nu[k])) continue;
Branch: 1 branch
BranchTrueFalseTotal
&& dihedral4(p[0], p[1], p[2], p[3], &nu[k])) continue; 3725 1 3726
7473 10533 have_nu = 0;
7474 10533 break;
7475 }
7476 11278 ▶ if (have_nu) {
Branch: 1 branch
BranchTrueFalseTotal
if (have_nu) { 745 10533 11278
7477 /*sin 36 + sin 72, the constant of Altona and Sundaralingam's equation 1.
7478 Computed rather than written out, so that it is exact to whatever width
7479 this perl's NV is rather than to however many digits were typed.*/
7480 745 const NV k1 = nv_sin(CSP_PI / 5.0) + nv_sin(2.0 * CSP_PI / 5.0);
7481 745 const NV num = (nu[4] + nu[1]) - (nu[3] + nu[0]);
7482 745 const NV den = 2.0 * nu[2] * k1;
7483 745 AV *list = newAV();
7484 4470 ▶ for (k = 0; k < 5; k++) av_push(list, newSVnv(nu[k] * to_deg));
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < 5; k++) av_push(list, newSVnv(nu[k] * to_deg)); 3725 745 4470
7485 745 (void)hv_stores(me, "nu", newRV_noinc((SV *)list));
7486 /*A ring flat to the last bit has no phase -- every P describes it as
7487 well as every other, and atan2(0, 0) would answer 0 as though one of
7488 them did. Real geometry never gets there; a fixture built on a straight
7489 line has no nu at all, dihedral4() having refused them. Nor does a
7490 phase that is not a number name a pucker: it is cast to an index
7491 below, and a NaN cast to an integer is undefined behaviour.*/
7492 745 ▶ if ((num != 0.0 || den != 0.0) && nv_is_finite(num) && nv_is_finite(den)) {
Branch: 4 branches
BranchTrueFalseTotal
if ((num != 0.0 || den != 0.0) && nv_is_finite(num) && nv_is_finite(den)) { 0 745 745
if ((num != 0.0 || den != 0.0) && nv_is_finite(num) && nv_is_finite(den)) { 0 0 0
if ((num != 0.0 || den != 0.0) && nv_is_finite(num) && nv_is_finite(den)) { 745 0 745
if ((num != 0.0 || den != 0.0) && nv_is_finite(num) && nv_is_finite(den)) { 745 0 745
7493 745 const NV pr = nv_atan2(num, den);
7494 745 const NV cp = nv_cos(pr);
7495 745 NV phase = pr * to_deg;
7496 745 ▶ if (phase < 0.0) phase += 360.0;
Branch: 1 branch
BranchTrueFalseTotal
if (phase < 0.0) phase += 360.0; 108 637 745
7497 //an angle a hair below zero adds the whole turn and rounds to it,
7498 //and 360 is 0: the cycle closes, and the range is documented as
7499 //0 to 360 with the upper end not in it
7500 745 ▶ if (phase >= 360.0) phase = 0.0;
Branch: 1 branch
BranchTrueFalseTotal
if (phase >= 360.0) phase = 0.0; 0 745 745
7501 745 (void)hv_stores(me, "pucker_phase", newSVnv(phase));
7502 745 (void)hv_stores(me, "pucker",
7503 newSVpv(nuc_pucker[(unsigned short)(phase / 36.0)], 0));
7504 //cos P is zero only when nu2 is exactly zero, where the amplitude
7505 //is the other half of the fraction; there is no ring like that in
7506 //a real file and none is invented here
7507 745 ▶ if (cp != 0.0)
Branch: 1 branch
BranchTrueFalseTotal
if (cp != 0.0) 745 0 745
7508 745 (void)hv_stores(me, "pucker_amplitude", newSVnv(nu[2] / cp * to_deg));
7509 }
7510 }
7511 11278 }
7512  
7513 /*chain_torsions() -- the same angles again, as one array per torsion.
7514  
7515 The block above writes each angle onto the residue it belongs to, which is where
7516 a question about one residue is asked. A question about the chain -- a
7517 Ramachandran plot, a rotamer census, the mean of an angle along a helix -- wants
7518 them as columns instead, so they are gathered onto the chain as well, under
7519 `torsions': $info->{chains}{A}{torsions}{phi} and its relatives.
7520  
7521 Each array runs parallel to the chain's `residue_order', one element per residue
7522 in the order the walk saw them, and a residue with no such torsion holds an
7523 undef rather than being left out -- the position is what says which residue a
7524 value came from, and a compacted array would lose that. A key no residue in the
7525 chain has at all is absent instead, so a protein chain carries phi, psi, omega
7526 and chi and a nucleic acid one alpha to zeta, and neither carries eleven arrays
7527 of nothing.
7528  
7529 The elements are copies of the residues' scalars, so writing to one does not
7530 reach back; `chi' and `nu' copy the reference, which means the chain and the
7531 residue name one list between them, as two references to a thing always do.*/
7532  
7533 /*every key the torsions above write onto a residue: the amino acid ones, then
7534 the nucleotide ones, which are nuc_keys[] with the chi the two kinds share
7535 lifted out of it*/
7536 static const char *const tors_name[] = {
7537 "phi", "psi", "omega", "chi",
7538 "alpha", "beta", "gamma", "delta", "epsilon", "zeta",
7539 "nu", "pucker", "pucker_phase", "pucker_amplitude", "glycosidic"
7540 };
7541 #define NTORS ((unsigned short)(sizeof tors_name / sizeof *tors_name))
7542  
7543 783 static void chain_torsions(pTHX_ HV *CSP_RESTRICT chain, HV *CSP_RESTRICT *CSP_RESTRICT res, UV n){
7544 783 HV *out = newHV();
7545 AV *col[NTORS];
7546 STRLEN len[NTORS];
7547 bool any[NTORS];//FALSE until some residue turns out to have the key
7548 unsigned short k;
7549 UV i;
7550  
7551 12528 ▶ for (k = 0; k < NTORS; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < NTORS; k++) { 11745 783 12528
7552 11745 col[k] = newAV();
7553 11745 len[k] = strlen(tors_name[k]);
7554 11745 any[k] = 0;
7555 //n undefs, of which the loop below fills in the ones there are
7556 11745 ▶ if (n) av_fill(col[k], (SSize_t)n - 1);
Branch: 1 branch
BranchTrueFalseTotal
if (n) av_fill(col[k], (SSize_t)n - 1); 11745 0 11745
7557 }
7558 12061 ▶ for (i = 0; i < n; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) 11278 783 12061
7559 180448 ▶ for (k = 0; k < NTORS; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < NTORS; k++) { 169170 11278 180448
7560 169170 SV *v = hvf_sv(aTHX_ res[i], tors_name[k], len[k]);
7561 169170 ▶ if (!v) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!v) continue; 142716 26454 169170
7562 26454 (void)av_store(col[k], (SSize_t)i, newSVsv(v));
7563 26454 any[k] = 1;
7564 }
7565 12528 ▶ for (k = 0; k < NTORS; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < NTORS; k++) { 11745 783 12528
7566 11745 ▶ if (any[k])
Branch: 1 branch
BranchTrueFalseTotal
if (any[k]) 2045 9700 11745
7567 2045 (void)hv_store(out, tors_name[k], (I32)len[k],
7568 newRV_noinc((SV *)col[k]), 0);
7569 else
7570 9700 SvREFCNT_dec((SV *)col[k]);
7571 }
7572 //replaced whole rather than added to, so that asking twice gives one answer
7573 783 (void)hv_stores(chain, "torsions", newRV_noinc((SV *)out));
7574 783 }
7575  
7576 /*dihedrals() -- every torsion angle of every residue, written onto the residue.
7577  
7578 Degrees, in -180 to 180, which is what the rest of the module reports an angle
7579 in. A residue that has no phi -- the first of a chain, or the one after a gap
7580 -- simply has no phi key, rather than a zero that would plot. The one exception
7581 is the pucker phase, which nuc_torsions() reports in 0 to 360 because that is
7582 how the pseudorotation cycle is read.
7583  
7584 One loop for both kinds of residue: the protein torsions and the nucleic ones
7585 want the same three residue hashes and the same two link tests, and a residue is
7586 one or the other, so asking twice would be walking twice. `bond' is the peptide
7587 cutoff and `phospho' the phosphodiester one.
7588  
7589 Each chain is then handed to chain_torsions(), which collects what its residues
7590 were just given into one array per angle; that is the same walk again, on one
7591 chain's worth of residue hashes, rather than a second pass over the structure.*/
7592 597 static void dihedrals(pTHX_ structset *CSP_RESTRICT s, NV bond, NV phospho){
7593 static const char *const phi_n[4] = { "C", "N", "CA", "C" };
7594 static const unsigned short phi_w[4] = { 0, 1, 1, 1 };
7595 static const char *const psi_n[4] = { "N", "CA", "C", "N" };
7596 static const unsigned short psi_w[4] = { 0, 0, 0, 1 };
7597 static const char *const omg_n[4] = { "CA", "C", "N", "CA" };
7598 static const unsigned short omg_w[4] = { 0, 0, 1, 1 };
7599 597 const NV to_deg = 180.0 / CSP_PI;
7600  
7601 1380 ▶ for (UV c = 0; c < s->n_chain; c++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV c = 0; c < s->n_chain; c++) { 783 597 1380
7602 12061 ▶ for (UV r = s->chain_first[c]; r < s->chain_last[c]; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV r = s->chain_first[c]; r < s->chain_last[c]; r++) { 11278 783 12061
7603 11278 HV *me = s->res_hv[r];
7604 11278 ▶ HV *prev = (r > s->chain_first[c]) ? s->res_hv[r - 1] : NULL;
Branch: 1 branch
BranchTrueFalseTotal
HV *prev = (r > s->chain_first[c]) ? s->res_hv[r - 1] : NULL; 10495 783 11278
7605 11278 ▶ HV *next = (r + 1 < s->chain_last[c]) ? s->res_hv[r + 1] : NULL;
Branch: 1 branch
BranchTrueFalseTotal
HV *next = (r + 1 < s->chain_last[c]) ? s->res_hv[r + 1] : NULL; 10495 783 11278
7606 11278 HV *my_at = hvf_hv(aTHX_ me, "atoms", 5);
7607 11278 ▶ HV *pv_at = prev ? hvf_hv(aTHX_ prev, "atoms", 5) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
HV *pv_at = prev ? hvf_hv(aTHX_ prev, "atoms", 5) : NULL; 10495 783 11278
7608 11278 ▶ HV *nx_at = next ? hvf_hv(aTHX_ next, "atoms", 5) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
HV *nx_at = next ? hvf_hv(aTHX_ next, "atoms", 5) : NULL; 10495 783 11278
7609 NV p[4][3], v;
7610 11278 unsigned short k, last = 0;
7611 NV chi[CHI_MAX];
7612 bool have[CHI_MAX];
7613 11278 ▶ if (!my_at) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!my_at) continue; 0 11278 11278
7614 //everything written here is replaced rather than added to, so that
7615 //asking twice gives one answer
7616 11278 (void)hv_delete(me, "phi", 3, G_DISCARD);
7617 11278 (void)hv_delete(me, "psi", 3, G_DISCARD);
7618 11278 (void)hv_delete(me, "omega", 5, G_DISCARD);
7619 11278 (void)hv_delete(me, "chi", 3, G_DISCARD);
7620  
7621 11278 ▶ if (prev && peptide_linked(aTHX_ s, r - 1, r, bond)
Branch: 2 branches
BranchTrueFalseTotal
if (prev && peptide_linked(aTHX_ s, r - 1, r, bond) 10495 783 11278
if (prev && peptide_linked(aTHX_ s, r - 1, r, bond) 5403 5092 10495
7622 5403 ▶ && four_atoms(aTHX_ pv_at, my_at, phi_n, phi_w, p)
Branch: 1 branch
BranchTrueFalseTotal
&& four_atoms(aTHX_ pv_at, my_at, phi_n, phi_w, p) 5402 1 5403
7623 5402 ▶ && dihedral4(p[0], p[1], p[2], p[3], &v))
Branch: 1 branch
BranchTrueFalseTotal
&& dihedral4(p[0], p[1], p[2], p[3], &v)) 4246 1156 5402
7624 4246 (void)hv_stores(me, "phi", newSVnv(v * to_deg));
7625 11278 ▶ if (next && peptide_linked(aTHX_ s, r, r + 1, bond)) {
Branch: 2 branches
BranchTrueFalseTotal
if (next && peptide_linked(aTHX_ s, r, r + 1, bond)) { 10495 783 11278
if (next && peptide_linked(aTHX_ s, r, r + 1, bond)) { 5403 5092 10495
7626 5403 ▶ if (four_atoms(aTHX_ my_at, nx_at, psi_n, psi_w, p)
Branch: 1 branch
BranchTrueFalseTotal
if (four_atoms(aTHX_ my_at, nx_at, psi_n, psi_w, p) 5389 14 5403
7627 5389 ▶ && dihedral4(p[0], p[1], p[2], p[3], &v))
Branch: 1 branch
BranchTrueFalseTotal
&& dihedral4(p[0], p[1], p[2], p[3], &v)) 4233 1156 5389
7628 4233 (void)hv_stores(me, "psi", newSVnv(v * to_deg));
7629 5403 ▶ if (four_atoms(aTHX_ my_at, nx_at, omg_n, omg_w, p)
Branch: 1 branch
BranchTrueFalseTotal
if (four_atoms(aTHX_ my_at, nx_at, omg_n, omg_w, p) 5388 15 5403
7630 5388 ▶ && dihedral4(p[0], p[1], p[2], p[3], &v))
Branch: 1 branch
BranchTrueFalseTotal
&& dihedral4(p[0], p[1], p[2], p[3], &v)) 5382 6 5388
7631 5382 (void)hv_stores(me, "omega", newSVnv(v * to_deg));
7632 }
7633  
7634 11278 have[0] = chi_of(aTHX_ my_at, chi1_a, 5, &chi[0]);
7635 11278 have[1] = chi_of(aTHX_ my_at, chi2_a, 6, &chi[1]);
7636 11278 have[2] = chi_of(aTHX_ my_at, chi3_a, 4, &chi[2]);
7637 11278 have[3] = chi_of(aTHX_ my_at, chi4_a, 2, &chi[3]);
7638 11278 have[4] = chi_of(aTHX_ my_at, chi5_a, 1, &chi[4]);
7639 67668 ▶ for (k = 0; k < CHI_MAX; k++) if (have[k]) last = (unsigned short)(k + 1);
Branch: 2 branches
BranchTrueFalseTotal
for (k = 0; k < CHI_MAX; k++) if (have[k]) last = (unsigned short)(k + 1); 9281 47109 56390
for (k = 0; k < CHI_MAX; k++) if (have[k]) last = (unsigned short)(k + 1); 56390 11278 67668
7640 11278 ▶ if (last) {
Branch: 1 branch
BranchTrueFalseTotal
if (last) { 4153 7125 11278
7641 4153 AV *list = newAV();
7642 13434 ▶ for (k = 0; k < last; k++)
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < last; k++) 9281 4153 13434
7643 9281 ▶ av_push(list, have[k] ? newSVnv(chi[k] * to_deg) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(list, have[k] ? newSVnv(chi[k] * to_deg) : newSV(0)); 9281 0 9281
7644 4153 (void)hv_stores(me, "chi", newRV_noinc((SV *)list));
7645 }
7646  
7647 11278 nuc_torsions(aTHX_ me, my_at, pv_at, nx_at,
7648 11278 nucleotide_linked(aTHX_ prev, me, phospho),
7649 11278 nucleotide_linked(aTHX_ me, next, phospho));
7650 }
7651 //and the chain's own view of what the residues above were given
7652 783 chain_torsions(aTHX_ s->chain_hv[c], s->res_hv + s->chain_first[c],
7653 783 s->chain_last[c] - s->chain_first[c]);
7654 }
7655 597 }
7656  
7657 /*Residue contacts, and how much of a residue's own half of the world is full.
7658  
7659 Two things that both answer "what is near this residue", from two different
7660 implementations, and both through the grid the surface already builds.
7661  
7662 **Contacts** are mdtraj's compute_contacts() with its default `closest-heavy'
7663 scheme: the distance between two residues is the shortest distance between any
7664 pair of their heavy atoms, hydrogens left out. mdtraj's `all' pairs up
7665 residues in the same chain that are three or more apart in it, which is the
7666 question a contact map of one chain asks; this reports those and the pairs that
7667 cross a chain as well, because a caller looking at a complex wants the interface
7668 and dropping it would be a strange thing to do silently. t/features.t compares
7669 the subset mdtraj has an opinion about.
7670  
7671 **Half-sphere exposure** is Biopython's Bio.PDB.HSExposure.HSExposureCB: draw
7672 the vector from a residue's CA to its CB, count the CA atoms of other amino acid
7673 residues within 12 A, and split that count by which side of the plane through CA
7674 they fall -- hse_up towards the side chain, hse_down away from it. It says
7675 something the accessible surface does not: a residue can be buried and still
7676 have its side chain pointing into a cavity. Glycine has no CB, and gets the
7677 virtual one Biopython builds, the N position rotated 120 degrees the other way
7678 about the CA-C axis; any other residue without a CB gets no figure.
7679  
7680 The radius, the offset of 0 (no flanking residues skipped) and the CB variant
7681 rather than the CA one are Biopython's defaults.
7682  
7683 Only a residue in one of CaPPBuilder's polypeptides takes part, which is a run
7684 of at least two standard amino acids, each next to the one before it in its
7685 chain and with a CA within CSP_HSE_LINK of that one's -- any conformer of either
7686 CA will do, as Bio/PDB/Polypeptide.py's CaPPBuilder._is_connected() has it. A
7687 standard residue on its own, such as the GLU of 1a08's ACE-FTY-GLU-DIP peptide
7688 between two residues that are not standard, is in no polypeptide: Biopython
7689 gives it no figure and does not count it towards its neighbours'.*/
7690 #define CSP_HSE_RADIUS 12.0 //HSExposureCB's `radius'
7691 #define CSP_HSE_LINK 4.3 //CaPPBuilder's `radius', angstrom
7692  
7693 //is this atom name a hydrogen or deuterium? Contacts are between heavy atoms,
7694 //and the element is what says so -- a name beginning H is not enough, HG being
7695 //mercury as often as a hydrogen
7696 88595 static bool atom_is_h(pTHX_ HV *CSP_RESTRICT a){
7697 88595 SV *e = hvf_sv(aTHX_ a, "element", 7);
7698 STRLEN n;
7699 const char *p;
7700 88595 ▶ if (!e) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!e) return 0; 1 88594 88595
7701 88594 p = SvPV_const(e, n);
7702 88594 ▶ return n == 1 && (*p == 'H' || *p == 'D');
Branch: 3 branches
BranchTrueFalseTotal
return n == 1 && (*p == 'H' || *p == 'D'); 88299 295 88594
return n == 1 && (*p == 'H' || *p == 'D'); 73931 14368 88299
return n == 1 && (*p == 'H' || *p == 'D'); 1 73930 73931
7703 }
7704  
7705 //glycine's CB, where there is none: the N position turned -120 degrees about
7706 //the CA-to-C axis, which is Biopython's _get_gly_cb_vector(). Returns the
7707 //CA-to-CB vector, as the real one does.
7708 522 static bool gly_cb(pTHX_ HV *CSP_RESTRICT atoms, NV *CSP_RESTRICT out){
7709 NV nx, ny, nz, cx, cy, cz, ax, ay, az, k[3], v[3], len, c, sn, dot;
7710 522 const NV ang = -CSP_PI * 120.0 / 180.0;
7711 unsigned short i;
7712 522 ▶ if (!atom_xyz(aTHX_ atoms, "N", &nx, &ny, &nz)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ atoms, "N", &nx, &ny, &nz)) return 0; 33 489 522
7713 489 ▶ if (!atom_xyz(aTHX_ atoms, "C", &cx, &cy, &cz)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ atoms, "C", &cx, &cy, &cz)) return 0; 1 488 489
7714 488 ▶ if (!atom_xyz(aTHX_ atoms, "CA", &ax, &ay, &az)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ atoms, "CA", &ax, &ay, &az)) return 0; 0 488 488
7715 488 v[0] = nx - ax; v[1] = ny - ay; v[2] = nz - az;
7716 488 k[0] = cx - ax; k[1] = cy - ay; k[2] = cz - az;
7717 488 len = nv_sqrt(k[0] * k[0] + k[1] * k[1] + k[2] * k[2]);
7718 488 ▶ if (!(len > 0.0)) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!(len > 0.0)) return 0; 0 488 488
7719 1952 ▶ for (i = 0; i < 3; i++) k[i] /= len;
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < 3; i++) k[i] /= len; 1464 488 1952
7720 488 c = nv_cos(ang);
7721 488 sn = nv_sin(ang);
7722 488 dot = k[0] * v[0] + k[1] * v[1] + k[2] * v[2];
7723 //Rodrigues: v cos + (k x v) sin + k (k.v)(1 - cos)
7724 488 out[0] = v[0] * c + (k[1] * v[2] - k[2] * v[1]) * sn + k[0] * dot * (1.0 - c);
7725 488 out[1] = v[1] * c + (k[2] * v[0] - k[0] * v[2]) * sn + k[1] * dot * (1.0 - c);
7726 488 out[2] = v[2] * c + (k[0] * v[1] - k[1] * v[0]) * sn + k[2] * dot * (1.0 - c);
7727 488 return 1;
7728 }
7729  
7730 //one residue's running list of the residues it touches and how closely
7731 typedef struct {
7732 UV res;
7733 NV d;
7734 } touch;
7735  
7736 603 static AV *contacts_find(pTHX_ structset *CSP_RESTRICT s, NV cut, bool store){
7737 603 AV *out = newAV();
7738 603 unsigned char *CSP_RESTRICT heavy = NULL;
7739 603 NV *CSP_RESTRICT hx = NULL, *CSP_RESTRICT hy = NULL, *CSP_RESTRICT hz = NULL;
7740 603 UV *CSP_RESTRICT hres = NULL;
7741 /*`touching', not the obvious `near': <windows.h> still carries the 16-bit
7742 segment keywords as empty object-like macros -- `#define near' and
7743 `#define far' -- and perl.h includes it on Win32, so a variable of that
7744 name is deleted by the preprocessor and its declaration becomes a syntax
7745 error. 0.03 shipped with it and a Strawberry 5.42.2 smoker rejected the
7746 whole file over the one word.*/
7747 603 touch *CSP_RESTRICT touching = NULL;
7748 603 UV touch_cap = 32;
7749 cell_grid g;
7750 603 UV n = 0, i, r, lo;
7751  
7752 603 ▶ if (s->n_atom == 0) return out;
Branch: 1 branch
BranchTrueFalseTotal
if (s->n_atom == 0) return out; 32 571 603
7753 571 Newx(heavy, s->n_atom, unsigned char);
7754 77218 ▶ for (i = 0; i < s->n_atom; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < s->n_atom; i++) 76647 571 77218
7755 76647 heavy[i] = atom_is_h(aTHX_ s->atom_hv[i]) ? 0 : 1;
7756 571 ▶ Newx(hx, s->n_atom, NV); Newx(hy, s->n_atom, NV); Newx(hz, s->n_atom, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(hx, s->n_atom, NV); Newx(hy, s->n_atom, NV); Newx(hz, s->n_atom, NV); 0 571 571
Newx(hx, s->n_atom, NV); Newx(hy, s->n_atom, NV); Newx(hz, s->n_atom, NV); 0 571 571
Newx(hx, s->n_atom, NV); Newx(hy, s->n_atom, NV); Newx(hz, s->n_atom, NV); 0 571 571
7757 571 ▶ Newx(hres, s->n_atom, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(hres, s->n_atom, UV); 0 571 571
7758 12044 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 11473 571 12044
7759 88120 ▶ for (i = s->res_first[r]; i < s->res_last[r]; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = s->res_first[r]; i < s->res_last[r]; i++) { 76647 11473 88120
7760 76647 ▶ if (!heavy[i]) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!heavy[i]) continue; 6739 69908 76647
7761 69908 hx[n] = s->x[i]; hy[n] = s->y[i]; hz[n] = s->z[i];
7762 69908 hres[n] = r;
7763 69908 n++;
7764 }
7765 }
7766 571 Safefree(heavy);
7767 571 ▶ if (n == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) { 3 568 571
7768 3 Safefree(hx); Safefree(hy); Safefree(hz); Safefree(hres);
7769 3 return out;
7770 }
7771 568 grid_build(aTHX_ &g, hx, hy, hz, n, cut);
7772 568 ▶ Newx(touching, touch_cap, touch);
Branch: 1 branch
BranchTrueFalseTotal
Newx(touching, touch_cap, touch); 0 568 568
7773  
7774 568 ▶ if (store)
Branch: 1 branch
BranchTrueFalseTotal
if (store) 563 5 568
7775 11894 ▶ for (r = 0; r < s->n_res; r++)
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) 11331 563 11894
7776 11331 (void)hv_stores(s->res_hv[r], "n_contacts", newSVuv(0));
7777  
7778 /*The heavy atoms were gathered residue by residue, so one residue's are one
7779 run of them and hres is never anything but ascending: `lo' walks that run
7780 forward rather than each residue scanning the whole array for its own atoms.
7781 The scan was the whole cost of this function on anything large -- residues
7782 times heavy atoms, which is 4fqr's 11,406 by 88,416 -- and asking for the
7783 contacts of that entry took 2.25 s. It is 0.15 s this way and finds the
7784 same pairs: the loop body has not changed, only how it is reached.*/
7785 568 lo = 0;
7786 12038 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 11470 568 12038
7787 11470 UV n_touch = 0, k, hi = lo;
7788 81378 ▶ while (hi < n && hres[hi] == r) hi++;
Branch: 2 branches
BranchTrueFalseTotal
while (hi < n && hres[hi] == r) hi++; 80808 570 81378
while (hi < n && hres[hi] == r) hi++; 69908 10900 80808
7789 81378 ▶ for (i = lo; i < hi; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = lo; i < hi; i++) { 69908 11470 81378
7790 UV bx, by, bz, ci, cj, ck;
7791 69908 ci = grid_axis(hx[i] - g.x0, g.cell, g.nx);
7792 69908 cj = grid_axis(hy[i] - g.y0, g.cell, g.ny);
7793 69908 ck = grid_axis(hz[i] - g.z0, g.cell, g.nz);
7794 267519 ▶ for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++)
Branch: 3 branches
BranchTrueFalseTotal
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++) 60208 9700 69908
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++) 260534 6985 267519
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++) 197611 69908 267519
7795 751528 ▶ for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++)
Branch: 3 branches
BranchTrueFalseTotal
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++) 170325 27286 197611
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++) 717365 34163 751528
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++) 553917 197611 751528
7796 2123419 ▶ for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) {
Branch: 3 branches
BranchTrueFalseTotal
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) { 483389 70528 553917
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) { 2061338 62081 2123419
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) { 1569502 553917 2123419
7797 1569502 UV cell = (bx * g.ny + by) * g.nz + bz, p;
7798 5626988 ▶ for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = g.start[cell]; p < g.start[cell + 1]; p++) { 4057486 1569502 5626988
7799 4057486 UV j = g.idx[p];
7800 NV dx, dy, dz, d2, d;
7801 4057486 ▶ if (hres[j] <= r) continue;//each residue pair once
Branch: 1 branch
BranchTrueFalseTotal
if (hres[j] <= r) continue;//each residue pair once 2387490 1669996 4057486
7802 1669996 dx = hx[j] - hx[i]; dy = hy[j] - hy[i]; dz = hz[j] - hz[i];
7803 1669996 d2 = dx * dx + dy * dy + dz * dz;
7804 1669996 ▶ if (!(d2 < cut * cut)) continue;//not >=: a NaN distance is no contact
Branch: 1 branch
BranchTrueFalseTotal
if (!(d2 < cut * cut)) continue;//not >=: a NaN distance is no contact 1217577 452419 1669996
7805 452419 d = nv_sqrt(d2);
7806 35077065 ▶ for (k = 0; k < n_touch; k++)
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n_touch; k++) 34850248 226817 35077065
7807 34850248 ▶ if (touching[k].res == hres[j]) break;
Branch: 1 branch
BranchTrueFalseTotal
if (touching[k].res == hres[j]) break; 225602 34624646 34850248
7808 452419 ▶ if (k < n_touch) {
Branch: 1 branch
BranchTrueFalseTotal
if (k < n_touch) { 225602 226817 452419
7809 225602 ▶ if (d < touching[k].d) touching[k].d = d;
Branch: 1 branch
BranchTrueFalseTotal
if (d < touching[k].d) touching[k].d = d; 36415 189187 225602
7810 } else {
7811 226817 ▶ if (n_touch == touch_cap) { touch_cap *= 2; Renew(touching, touch_cap, touch); }
Branch: 2 branches
BranchTrueFalseTotal
if (n_touch == touch_cap) { touch_cap *= 2; Renew(touching, touch_cap, touch); } 5 226812 226817
if (n_touch == touch_cap) { touch_cap *= 2; Renew(touching, touch_cap, touch); } 0 5 5
7812 226817 touching[n_touch].res = hres[j];
7813 226817 touching[n_touch].d = d;
7814 226817 n_touch++;
7815 }
7816 }
7817 }
7818 }
7819 238287 ▶ for (k = 0; k < n_touch; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n_touch; k++) { 226817 11470 238287
7820 226817 HV *h = newHV();
7821 226817 pi_field(aTHX_ h, "chain1", 6, s->res_hv[r], "chain", 5);
7822 226817 pi_field(aTHX_ h, "residue1", 8, s->res_hv[r], "key", 3);
7823 226817 pi_field(aTHX_ h, "chain2", 6, s->res_hv[touching[k].res], "chain", 5);
7824 226817 pi_field(aTHX_ h, "residue2", 8, s->res_hv[touching[k].res], "key", 3);
7825 226817 (void)hv_stores(h, "distance", newSVnv(touching[k].d));
7826 226817 av_push(out, newRV_noinc((SV *)h));
7827 226817 ▶ if (!store) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!store) continue; 331 226486 226817
7828 {
7829 226486 SV **a = hv_fetch(s->res_hv[r], "n_contacts", 10, 0);
7830 226486 SV **b = hv_fetch(s->res_hv[touching[k].res], "n_contacts", 10, 0);
7831 226486 ▶ if (a && *a) sv_setuv(*a, SvUV(*a) + 1);
Branch: 2 branches
BranchTrueFalseTotal
if (a && *a) sv_setuv(*a, SvUV(*a) + 1); 226486 0 226486
if (a && *a) sv_setuv(*a, SvUV(*a) + 1); 226486 0 226486
7832 226486 ▶ if (b && *b) sv_setuv(*b, SvUV(*b) + 1);
Branch: 2 branches
BranchTrueFalseTotal
if (b && *b) sv_setuv(*b, SvUV(*b) + 1); 226486 0 226486
if (b && *b) sv_setuv(*b, SvUV(*b) + 1); 226486 0 226486
7833 }
7834 }
7835 11470 lo = hi;
7836 }
7837 568 Safefree(touching);
7838 568 grid_free(aTHX_ &g);
7839 568 Safefree(hx); Safefree(hy); Safefree(hz); Safefree(hres);
7840 568 return out;
7841 }
7842  
7843 /*Is any conformer of one CA within CSP_HSE_LINK of any conformer of the other?
7844 An atom with alternate conformers lists every one of them, its own included, in
7845 altlocs; one without has only its own coordinates.*/
7846 6524 static bool ca_linked(pTHX_ HV *CSP_RESTRICT at1, HV *CSP_RESTRICT at2){
7847 HV *ca[2];
7848 AV *alt[2];
7849 SSize_t top[2], i, j;
7850 19572 ▶ for (unsigned short k = 0; k < 2; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < 2; k++) { 13048 6524 19572
7851 13048 ▶ ca[k] = hvf_hv(aTHX_ k ? at2 : at1, "CA", 2);
Branch: 1 branch
BranchTrueFalseTotal
ca[k] = hvf_hv(aTHX_ k ? at2 : at1, "CA", 2); 6524 6524 13048
7852 13048 ▶ if (!ca[k]) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!ca[k]) return 0; 0 13048 13048
7853 13048 alt[k] = hvf_av(aTHX_ ca[k], "altlocs", 7);
7854 13048 ▶ if (alt[k] && av_len(alt[k]) < 0) alt[k] = NULL;
Branch: 2 branches
BranchTrueFalseTotal
if (alt[k] && av_len(alt[k]) < 0) alt[k] = NULL; 6 13042 13048
if (alt[k] && av_len(alt[k]) < 0) alt[k] = NULL; 0 6 6
7855 13048 ▶ top[k] = alt[k] ? av_len(alt[k]) : 0;
Branch: 1 branch
BranchTrueFalseTotal
top[k] = alt[k] ? av_len(alt[k]) : 0; 6 13042 13048
7856 }
7857 6942 ▶ for (i = 0; i <= top[0]; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i <= top[0]; i++) { 6524 418 6942
7858 6524 HV *p = ca[0];
7859 NV px, py, pz;
7860 6524 ▶ if (alt[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (alt[0]) { 4 6520 6524
7861 4 SV **e = av_fetch(alt[0], i, 0);
7862 4 ▶ if (!e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) continue; 4 0 4
if (!e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) continue; 4 0 4
if (!e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) continue; 0 4 4
7863 4 p = (HV *)SvRV(*e);
7864 }
7865 {
7866 6524 SV *xs = hvf_sv(aTHX_ p, "x", 1), *ys = hvf_sv(aTHX_ p, "y", 1),
7867 6524 *zs = hvf_sv(aTHX_ p, "z", 1);
7868 6524 ▶ if (!xs || !ys || !zs) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!xs || !ys || !zs) continue; 6524 0 6524
if (!xs || !ys || !zs) continue; 6524 0 6524
if (!xs || !ys || !zs) continue; 0 6524 6524
7869 6524 px = SvNV(xs); py = SvNV(ys); pz = SvNV(zs);
7870 }
7871 6942 ▶ for (j = 0; j <= top[1]; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j <= top[1]; j++) { 6524 418 6942
7872 6524 HV *q = ca[1];
7873 SV *xs, *ys, *zs;
7874 NV dx, dy, dz;
7875 6524 ▶ if (alt[1]) {
Branch: 1 branch
BranchTrueFalseTotal
if (alt[1]) { 2 6522 6524
7876 2 SV **e = av_fetch(alt[1], j, 0);
7877 2 ▶ if (!e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) continue; 2 0 2
if (!e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) continue; 2 0 2
if (!e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) continue; 0 2 2
7878 2 q = (HV *)SvRV(*e);
7879 }
7880 6524 xs = hvf_sv(aTHX_ q, "x", 1); ys = hvf_sv(aTHX_ q, "y", 1);
7881 6524 zs = hvf_sv(aTHX_ q, "z", 1);
7882 6524 ▶ if (!xs || !ys || !zs) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!xs || !ys || !zs) continue; 6524 0 6524
if (!xs || !ys || !zs) continue; 6524 0 6524
if (!xs || !ys || !zs) continue; 0 6524 6524
7883 6524 dx = SvNV(xs) - px; dy = SvNV(ys) - py; dz = SvNV(zs) - pz;
7884 6524 ▶ if (dx * dx + dy * dy + dz * dz < CSP_HSE_LINK * CSP_HSE_LINK) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (dx * dx + dy * dy + dz * dz < CSP_HSE_LINK * CSP_HSE_LINK) return 1; 6106 418 6524
7885 }
7886 }
7887 418 return 0;
7888 }
7889  
7890 //half-sphere exposure, onto each amino acid residue that has a CA and a CB
7891 597 static void hse_compute(pTHX_ structset *CSP_RESTRICT s, NV radius){
7892 597 NV *CSP_RESTRICT cax = NULL, *CSP_RESTRICT cay = NULL, *CSP_RESTRICT caz = NULL;
7893 597 UV *CSP_RESTRICT cares = NULL;
7894 597 HV **CSP_RESTRICT ok = NULL;//each residue's atoms if it may take part, else NULL
7895 597 bool *CSP_RESTRICT inpp = NULL;
7896 cell_grid g;
7897 597 UV n = 0, r, c;
7898  
7899 860 ▶ if (s->n_res == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (s->n_res == 0) return; 29 568 597
7900 568 ▶ Newxz(ok, s->n_res, HV *);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(ok, s->n_res, HV *); 0 568 568
7901 568 Newxz(inpp, s->n_res, bool);
7902 11846 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 11278 568 11846
7903 HV *at;
7904 /*One of the twenty, not merely an amino acid. Biopython's
7905 CaPPBuilder.build_peptides() runs with aa_only => 1, which keeps only
7906 the standard names, so a selenomethionine is invisible to HSExposureCB
7907 -- it neither gets a figure nor counts towards anybody else's. Matching
7908 that is what lets t/features.t hold this to it; the cost is that a
7909 structure full of modified residues gets a count that ignores them*/
7910 11278 ▶ if (s->res_type[r] != RT_AA || !s->res_std[r]) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (s->res_type[r] != RT_AA || !s->res_std[r]) continue; 7273 4005 11278
if (s->res_type[r] != RT_AA || !s->res_std[r]) continue; 143 7130 7273
7911 7130 at = hvf_hv(aTHX_ s->res_hv[r], "atoms", 5);
7912 7130 ▶ if (at && hvf_hv(aTHX_ at, "CA", 2)) ok[r] = at;
Branch: 2 branches
BranchTrueFalseTotal
if (at && hvf_hv(aTHX_ at, "CA", 2)) ok[r] = at; 7130 0 7130
if (at && hvf_hv(aTHX_ at, "CA", 2)) ok[r] = at; 7108 22 7130
7913 }
7914 //a residue is in a polypeptide if it is linked to its neighbour on either side
7915 1351 ▶ for (c = 0; c < s->n_chain; c++)
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < s->n_chain; c++) 783 568 1351
7916 11278 ▶ for (r = s->chain_first[c] + 1; r < s->chain_last[c]; r++)
Branch: 1 branch
BranchTrueFalseTotal
for (r = s->chain_first[c] + 1; r < s->chain_last[c]; r++) 10495 783 11278
7917 10495 ▶ if (ok[r - 1] && ok[r] && ca_linked(aTHX_ ok[r - 1], ok[r]))
Branch: 3 branches
BranchTrueFalseTotal
if (ok[r - 1] && ok[r] && ca_linked(aTHX_ ok[r - 1], ok[r])) 6840 3655 10495
if (ok[r - 1] && ok[r] && ca_linked(aTHX_ ok[r - 1], ok[r])) 6524 316 6840
if (ok[r - 1] && ok[r] && ca_linked(aTHX_ ok[r - 1], ok[r])) 6106 418 6524
7918 6106 inpp[r - 1] = inpp[r] = TRUE;
7919 568 ▶ Newx(cax, s->n_res, NV); Newx(cay, s->n_res, NV); Newx(caz, s->n_res, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(cax, s->n_res, NV); Newx(cay, s->n_res, NV); Newx(caz, s->n_res, NV); 0 568 568
Newx(cax, s->n_res, NV); Newx(cay, s->n_res, NV); Newx(caz, s->n_res, NV); 0 568 568
Newx(cax, s->n_res, NV); Newx(cay, s->n_res, NV); Newx(caz, s->n_res, NV); 0 568 568
7920 568 ▶ Newx(cares, s->n_res, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(cares, s->n_res, UV); 0 568 568
7921 11846 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 11278 568 11846
7922 11278 ▶ if (!inpp[r]) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!inpp[r]) continue; 4619 6659 11278
7923 6659 ▶ if (!atom_xyz(aTHX_ ok[r], "CA", &cax[n], &cay[n], &caz[n])) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!atom_xyz(aTHX_ ok[r], "CA", &cax[n], &cay[n], &caz[n])) continue; 0 6659 6659
7924 6659 cares[n] = r;
7925 6659 n++;
7926 }
7927 568 Safefree(ok); Safefree(inpp);
7928 568 ▶ if (n == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) { 263 305 568
7929 263 Safefree(cax); Safefree(cay); Safefree(caz); Safefree(cares);
7930 263 return;
7931 }
7932 305 grid_build(aTHX_ &g, cax, cay, caz, n, radius);
7933  
7934 6964 ▶ for (r = 0; r < n; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < n; r++) { 6659 305 6964
7935 6659 HV *me = s->res_hv[cares[r]];
7936 6659 HV *at = hvf_hv(aTHX_ me, "atoms", 5);
7937 NV pcb[3], bx, by, bz;
7938 6659 UV up = 0, down = 0, ax, ay, az;
7939 8055 ▶ if (!at) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!at) continue; 0 6659 6659
7940 /*Glycine gets the virtual CB and nothing else does: a side chain
7941 deposited without its CB, as 5x0w's are -- LYS, SER and THR cut back to
7942 the backbone -- has no figure from HSExposureCB._get_cb(), though its CA
7943 still counts towards its neighbours'.*/
7944 6659 ▶ if (s->res_key[cares[r]] == K3('G','L','Y')) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->res_key[cares[r]] == K3('G','L','Y')) { 522 6137 6659
7945 522 ▶ if (!gly_cb(aTHX_ at, pcb)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!gly_cb(aTHX_ at, pcb)) continue; 34 488 522
7946 6137 ▶ } else if (atom_xyz(aTHX_ at, "CB", &bx, &by, &bz)) {
Branch: 1 branch
BranchTrueFalseTotal
} else if (atom_xyz(aTHX_ at, "CB", &bx, &by, &bz)) { 4775 1362 6137
7947 4775 pcb[0] = bx - cax[r]; pcb[1] = by - cay[r]; pcb[2] = bz - caz[r];
7948 } else {
7949 1362 continue;//no side chain direction: no half to be on
7950 }
7951 {
7952 5263 UV ci = grid_axis(cax[r] - g.x0, g.cell, g.nx);
7953 5263 UV cj = grid_axis(cay[r] - g.y0, g.cell, g.ny);
7954 5263 UV ck = grid_axis(caz[r] - g.z0, g.cell, g.nz);
7955 18067 ▶ for (ax = ci ? ci - 1 : 0; ax <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); ax++)
Branch: 3 branches
BranchTrueFalseTotal
for (ax = ci ? ci - 1 : 0; ax <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); ax++) 3104 2159 5263
for (ax = ci ? ci - 1 : 0; ax <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); ax++) 15722 2345 18067
for (ax = ci ? ci - 1 : 0; ax <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); ax++) 12804 5263 18067
7956 36497 ▶ for (ay = cj ? cj - 1 : 0; ay <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); ay++)
Branch: 3 branches
BranchTrueFalseTotal
for (ay = cj ? cj - 1 : 0; ay <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); ay++) 5723 7081 12804
for (ay = cj ? cj - 1 : 0; ay <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); ay++) 15906 20591 36497
for (ay = cj ? cj - 1 : 0; ay <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); ay++) 23693 12804 36497
7957 79356 ▶ for (az = ck ? ck - 1 : 0; az <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); az++) {
Branch: 3 branches
BranchTrueFalseTotal
for (az = ck ? ck - 1 : 0; az <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); az++) { 12968 10725 23693
for (az = ck ? ck - 1 : 0; az <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); az++) { 67606 11750 79356
for (az = ck ? ck - 1 : 0; az <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); az++) { 55663 23693 79356
7958 55663 UV cell = (ax * g.ny + ay) * g.nz + az, p;
7959 220221 ▶ for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = g.start[cell]; p < g.start[cell + 1]; p++) { 164558 55663 220221
7960 164558 UV j = g.idx[p];
7961 NV dx, dy, dz;
7962 164558 ▶ if (j == r) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (j == r) continue; 5263 159295 164558
7963 159295 dx = cax[j] - cax[r]; dy = cay[j] - cay[r]; dz = caz[j] - caz[r];
7964 159295 ▶ if (!(dx * dx + dy * dy + dz * dz < radius * radius)) continue;//a NaN is no neighbour
Branch: 1 branch
BranchTrueFalseTotal
if (!(dx * dx + dy * dy + dz * dz < radius * radius)) continue;//a NaN is no neighbour 93510 65785 159295
7965 65785 ▶ if (dx * pcb[0] + dy * pcb[1] + dz * pcb[2] > 0.0) up++;
Branch: 1 branch
BranchTrueFalseTotal
if (dx * pcb[0] + dy * pcb[1] + dz * pcb[2] > 0.0) up++; 25880 39905 65785
7966 39905 else down++;
7967 }
7968 }
7969 }
7970 5263 (void)hv_stores(me, "hse_up", newSVuv(up));
7971 5263 (void)hv_stores(me, "hse_down", newSVuv(down));
7972 }
7973 305 grid_free(aTHX_ &g);
7974 305 Safefree(cax); Safefree(cay); Safefree(caz); Safefree(cares);
7975 }
7976  
7977 /*Backbone hydrogen bonds, by Kabsch and Sander's electrostatic definition.
7978  
7979 Kabsch, W; Sander, C (1983) Biopolymers 22(12):2577-637 put a charge of -0.42 e
7980 on the carbonyl oxygen and +0.20 e on the amide hydrogen, their opposites on the
7981 carbon and the nitrogen, and called the four-way Coulomb sum the bond energy:
7982  
7983 E = 0.42 * 0.20 * 332 * (1/r_ON + 1/r_CH - 1/r_OH - 1/r_CN) kcal/mol
7984  
7985 with the distances in angstrom. Anything below -0.5 kcal/mol is a bond. The
7986 implementation is mdtraj's kabsch_sander(), and every rule below was checked
7987 against it pair by pair on four real entries -- 1A42, 1A22, 1AHW and 3AU6 --
7988 where the two agree on which bonds exist and on their energies to 4e-5 kcal/mol,
7989 which is float32 rounding on mdtraj's side:
7990  
7991 * the amide hydrogen is not read from the file, it is placed: one angstrom
7992 from N along the direction of the previous residue's C=O. A crystal
7993 structure has no hydrogens, and this is the construction that lets the
7994 definition be used on one anyway.
7995 * proline has no amide hydrogen at all and can never donate.
7996 * a donor's own carbonyl, and the one its hydrogen was built from, are not
7997 acceptors: acceptor == donor and acceptor == donor - 1 are both skipped.
7998 The second is the important one -- an "H-bond" to the very carbonyl that
7999 placed the hydrogen is an artefact of the construction.
8000 * only pairs whose CA atoms are within 9 A are considered, which is DSSP's
8001 own screen and is what the grid here is built at.
8002 * a nitrogen has two lone pairs' worth of hydrogen to give and no more, so
8003 each donor keeps its two best acceptors and no others.
8004 * the energy is clipped at -9.9 kcal/mol, for the pathological case of two
8005 atoms refined on top of each other.
8006  
8007 **Where this departs from mdtraj**, in the same way and for the same reason as
8008 the torsion angles: mdtraj takes "the previous residue" to be whichever one
8009 comes before this one in the file and builds the hydrogen from its carbonyl,
8010 even across a chain break, which puts the hydrogen somewhere the chemistry never
8011 put it. Here the two must be peptide-bonded first. t/features.t freezes
8012 mdtraj's answer together with whether the link is real, and holds this to the
8013 first where the second is true.*/
8014 #define CSP_KS_Q 27.888 //0.42 * 0.20 * 332, kcal A / mol
8015 #define CSP_KS_CUTOFF (-0.5) //kcal/mol: below this it is a bond
8016 #define CSP_KS_FLOOR (-9.9) //kcal/mol: no bond is reported as stronger
8017 #define CSP_KS_CA 9.0 //angstrom: DSSP's CA-to-CA screen
8018 #define CSP_KS_KEEP 2 //acceptors per donor
8019  
8020 //the backbone atoms one residue offers, and whether it has them all
8021 typedef struct {
8022 NV n[3], ca[3], c[3], o[3];
8023 bool whole;//all four present, so it can donate and accept
8024 bool proline;//no amide hydrogen: it can accept but never donate
8025 bool linked;//peptide-bonded to the residue before it in the walk
8026 } backbone;
8027  
8028 605 static void backbone_read(pTHX_ structset *CSP_RESTRICT s, backbone *CSP_RESTRICT bb, NV bond)
8029 {
8030 605 const bb_xyz *x = bb_get(aTHX_ s);
8031 UV r;
8032 12199 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 11594 605 12199
8033 11594 backbone *b = &bb[r];
8034 11594 b->proline = (s->res_key[r] == K3('P','R','O'));
8035 11594 b->linked = 0;
8036 11594 ▶ b->whole = x[r].has_n && x[r].has_ca && x[r].has_c && x[r].has_o;
Branch: 4 branches
BranchTrueFalseTotal
b->whole = x[r].has_n && x[r].has_ca && x[r].has_c && x[r].has_o; 6547 5047 11594
b->whole = x[r].has_n && x[r].has_ca && x[r].has_c && x[r].has_o; 6534 13 6547
b->whole = x[r].has_n && x[r].has_ca && x[r].has_c && x[r].has_o; 6530 4 6534
b->whole = x[r].has_n && x[r].has_ca && x[r].has_c && x[r].has_o; 6484 46 6530
8037 11594 ▶ if (!b->whole) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!b->whole) continue; 5110 6484 11594
8038 6484 Copy(x[r].n, b->n, 3, NV);
8039 6484 Copy(x[r].ca, b->ca, 3, NV);
8040 6484 Copy(x[r].c, b->c, 3, NV);
8041 6484 Copy(x[r].o, b->o, 3, NV);
8042 }
8043 11623 ▶ for (r = 1; r < s->n_res; r++)
Branch: 1 branch
BranchTrueFalseTotal
for (r = 1; r < s->n_res; r++) 11018 605 11623
8044 11018 bb[r].linked = peptide_linked(aTHX_ s, r - 1, r, bond);
8045 605 }
8046  
8047 //the energy of the bond from acceptor a's C=O to donor d's N-H, with the
8048 //hydrogen already placed
8049 31478 static NV ks_energy(const backbone *CSP_RESTRICT a, const NV *CSP_RESTRICT h,
8050 const NV *CSP_RESTRICT nd)
8051 {
8052 31478 NV r_on = 0.0, r_ch = 0.0, r_oh = 0.0, r_cn = 0.0, e;
8053 125912 ▶ for (unsigned short k = 0; k < 3; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < 3; k++) { 94434 31478 125912
8054 NV d;
8055 94434 d = a->o[k] - nd[k]; r_on += d * d;
8056 94434 d = a->c[k] - h[k]; r_ch += d * d;
8057 94434 d = a->o[k] - h[k]; r_oh += d * d;
8058 94434 d = a->c[k] - nd[k]; r_cn += d * d;
8059 }
8060 31478 r_on = nv_sqrt(r_on); r_ch = nv_sqrt(r_ch);
8061 31478 r_oh = nv_sqrt(r_oh); r_cn = nv_sqrt(r_cn);
8062 /*an atom that read as nan is no bond at all. It failed the `> 0.0' tests
8063 below the way two atoms at one point do, and came back as the strongest
8064 bond there is: a NaN on one carbonyl O gave eleven bonds of -9.9 to fold.pdb,
8065 which crowded real ones out of each donor's best two.*/
8066 31478 ▶ if (!nv_is_finite(r_on + r_ch + r_oh + r_cn)) return 0.0;
Branch: 1 branch
BranchTrueFalseTotal
if (!nv_is_finite(r_on + r_ch + r_oh + r_cn)) return 0.0; 11 31467 31478
8067 31467 ▶ if (!(r_on > 0.0) || !(r_ch > 0.0) || !(r_oh > 0.0) || !(r_cn > 0.0))
Branch: 4 branches
BranchTrueFalseTotal
if (!(r_on > 0.0) || !(r_ch > 0.0) || !(r_oh > 0.0) || !(r_cn > 0.0)) 31466 1 31467
if (!(r_on > 0.0) || !(r_ch > 0.0) || !(r_oh > 0.0) || !(r_cn > 0.0)) 31466 0 31466
if (!(r_on > 0.0) || !(r_ch > 0.0) || !(r_oh > 0.0) || !(r_cn > 0.0)) 31466 0 31466
if (!(r_on > 0.0) || !(r_ch > 0.0) || !(r_oh > 0.0) || !(r_cn > 0.0)) 0 31466 31466
8068 1 return CSP_KS_FLOOR;
8069 31466 e = CSP_KS_Q * (1.0 / r_on + 1.0 / r_ch - 1.0 / r_oh - 1.0 / r_cn);
8070 31466 ▶ return (e < CSP_KS_FLOOR) ? CSP_KS_FLOOR : e;
Branch: 1 branch
BranchTrueFalseTotal
return (e < CSP_KS_FLOOR) ? CSP_KS_FLOOR : e; 0 31466 31466
8071 }
8072  
8073 /*ks_compute() -- each residue's two best acceptors, and their energies.
8074  
8075 Kept on the structset rather than returned, because the secondary structure
8076 below reads the same table: DSSP is these bonds and nothing else, read for the
8077 patterns they fall into. acc[r][k] is the residue whose carbonyl residue r's
8078 amide hydrogen is bonded to, or the count of residues when there is none.*/
8079 605 static void ks_compute(pTHX_ structset *CSP_RESTRICT s, const backbone *CSP_RESTRICT bb)
8080 {
8081 605 NV *CSP_RESTRICT cx = NULL, *CSP_RESTRICT cy = NULL, *CSP_RESTRICT cz = NULL;
8082 605 UV *CSP_RESTRICT which = NULL;
8083 cell_grid g;
8084 605 UV n = 0, r;
8085  
8086 605 ▶ Newx(s->ks_acc, s->n_res ? s->n_res * CSP_KS_KEEP : 1, UV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(s->ks_acc, s->n_res ? s->n_res * CSP_KS_KEEP : 1, UV); 576 29 605
Newx(s->ks_acc, s->n_res ? s->n_res * CSP_KS_KEEP : 1, UV); 0 576 576
Newx(s->ks_acc, s->n_res ? s->n_res * CSP_KS_KEEP : 1, UV); 576 29 605
8087 605 ▶ Newx(s->ks_e, s->n_res ? s->n_res * CSP_KS_KEEP : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(s->ks_e, s->n_res ? s->n_res * CSP_KS_KEEP : 1, NV); 576 29 605
Newx(s->ks_e, s->n_res ? s->n_res * CSP_KS_KEEP : 1, NV); 0 576 576
Newx(s->ks_e, s->n_res ? s->n_res * CSP_KS_KEEP : 1, NV); 576 29 605
8088 23793 ▶ for (r = 0; r < s->n_res * CSP_KS_KEEP; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res * CSP_KS_KEEP; r++) { 23188 605 23793
8089 23188 s->ks_acc[r] = s->n_res;//"none": one past the last residue
8090 23188 s->ks_e[r] = 0.0;
8091 }
8092 810 ▶ if (s->n_res == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (s->n_res == 0) return; 29 576 605
8093  
8094 576 ▶ Newx(cx, s->n_res, NV); Newx(cy, s->n_res, NV); Newx(cz, s->n_res, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(cx, s->n_res, NV); Newx(cy, s->n_res, NV); Newx(cz, s->n_res, NV); 0 576 576
Newx(cx, s->n_res, NV); Newx(cy, s->n_res, NV); Newx(cz, s->n_res, NV); 0 576 576
Newx(cx, s->n_res, NV); Newx(cy, s->n_res, NV); Newx(cz, s->n_res, NV); 0 576 576
8095 576 ▶ Newx(which, s->n_res, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(which, s->n_res, UV); 0 576 576
8096 12170 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 11594 576 12170
8097 11594 ▶ if (!bb[r].whole) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!bb[r].whole) continue; 5110 6484 11594
8098 6484 cx[n] = bb[r].ca[0]; cy[n] = bb[r].ca[1]; cz[n] = bb[r].ca[2];
8099 6484 which[n] = r;
8100 6484 n++;
8101 }
8102 576 ▶ if (n == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) { 205 371 576
8103 205 Safefree(cx); Safefree(cy); Safefree(cz); Safefree(which);
8104 205 return;
8105 }
8106 371 grid_build(aTHX_ &g, cx, cy, cz, n, CSP_KS_CA);
8107  
8108 6855 ▶ for (UV k = 0; k < n; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV k = 0; k < n; k++) { 6484 371 6855
8109 6484 UV d = which[k];
8110 NV h[3], len;
8111 UV bx, by, bz, ci, cj, ck;
8112 unsigned short j;
8113 6485 ▶ if (bb[d].proline || !bb[d].linked) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (bb[d].proline || !bb[d].linked) continue; 6011 473 6484
if (bb[d].proline || !bb[d].linked) continue; 817 5194 6011
8114 5194 ▶ if (d == 0 || !bb[d - 1].whole) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (d == 0 || !bb[d - 1].whole) continue; 5194 0 5194
if (d == 0 || !bb[d - 1].whole) continue; 0 5194 5194
8115 5194 len = 0.0;
8116 20776 ▶ for (j = 0; j < 3; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < 3; j++) { 15582 5194 20776
8117 15582 h[j] = bb[d - 1].c[j] - bb[d - 1].o[j];
8118 15582 len += h[j] * h[j];
8119 }
8120 5194 len = nv_sqrt(len);
8121 5194 ▶ if (!(len > 0.0)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(len > 0.0)) continue; 1 5193 5194
8122 20772 ▶ for (j = 0; j < 3; j++) h[j] = bb[d].n[j] + h[j] / len;
Branch: 1 branch
BranchTrueFalseTotal
for (j = 0; j < 3; j++) h[j] = bb[d].n[j] + h[j] / len; 15579 5193 20772
8123  
8124 5193 ci = grid_axis(cx[k] - g.x0, g.cell, g.nx);
8125 5193 cj = grid_axis(cy[k] - g.y0, g.cell, g.ny);
8126 5193 ck = grid_axis(cz[k] - g.z0, g.cell, g.nz);
8127 18173 ▶ for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++)
Branch: 3 branches
BranchTrueFalseTotal
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++) 3702 1491 5193
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++) 14849 3324 18173
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++) 12980 5193 18173
8128 40973 ▶ for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++)
Branch: 3 branches
BranchTrueFalseTotal
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++) 6689 6291 12980
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++) 29794 11179 40973
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++) 27993 12980 40973
8129 96853 ▶ for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) {
Branch: 3 branches
BranchTrueFalseTotal
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) { 19293 8700 27993
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) { 80385 16468 96853
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) { 68860 27993 96853
8130 68860 UV cell = (bx * g.ny + by) * g.nz + bz, p;
8131 180579 ▶ for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = g.start[cell]; p < g.start[cell + 1]; p++) { 111719 68860 180579
8132 111719 UV q = g.idx[p], a = which[q];
8133 NV dx, dy, dz, e;
8134 111719 ▶ if (a == d || (d > 0 && a == d - 1)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (a == d || (d > 0 && a == d - 1)) continue; 106526 5193 111719
if (a == d || (d > 0 && a == d - 1)) continue; 106526 0 106526
if (a == d || (d > 0 && a == d - 1)) continue; 5193 101333 106526
8135 101333 dx = cx[q] - cx[k]; dy = cy[q] - cy[k]; dz = cz[q] - cz[k];
8136 101333 ▶ if (!(dx * dx + dy * dy + dz * dz < CSP_KS_CA * CSP_KS_CA)) continue;//a NaN is no neighbour
Branch: 1 branch
BranchTrueFalseTotal
if (!(dx * dx + dy * dy + dz * dz < CSP_KS_CA * CSP_KS_CA)) continue;//a NaN is no neighbour 69855 31478 101333
8137 31478 e = ks_energy(&bb[a], h, bb[d].n);
8138 31478 ▶ if (!(e < CSP_KS_CUTOFF)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(e < CSP_KS_CUTOFF)) continue; 29294 2184 31478
8139 //keep the two best, best first
8140 2184 ▶ if (e < s->ks_e[d * CSP_KS_KEEP] || s->ks_acc[d * CSP_KS_KEEP] == s->n_res) {
Branch: 2 branches
BranchTrueFalseTotal
if (e < s->ks_e[d * CSP_KS_KEEP] || s->ks_acc[d * CSP_KS_KEEP] == s->n_res) { 110 2074 2184
if (e < s->ks_e[d * CSP_KS_KEEP] || s->ks_acc[d * CSP_KS_KEEP] == s->n_res) { 0 110 110
8141 2074 s->ks_acc[d * CSP_KS_KEEP + 1] = s->ks_acc[d * CSP_KS_KEEP];
8142 2074 s->ks_e[d * CSP_KS_KEEP + 1] = s->ks_e[d * CSP_KS_KEEP];
8143 2074 s->ks_acc[d * CSP_KS_KEEP] = a;
8144 2074 s->ks_e[d * CSP_KS_KEEP] = e;
8145 110 ▶ } else if (e < s->ks_e[d * CSP_KS_KEEP + 1]
Branch: 1 branch
BranchTrueFalseTotal
} else if (e < s->ks_e[d * CSP_KS_KEEP + 1] 0 110 110
8146 0 ▶ || s->ks_acc[d * CSP_KS_KEEP + 1] == s->n_res) {
Branch: 1 branch
BranchTrueFalseTotal
|| s->ks_acc[d * CSP_KS_KEEP + 1] == s->n_res) { 0 0 0
8147 110 s->ks_acc[d * CSP_KS_KEEP + 1] = a;
8148 110 s->ks_e[d * CSP_KS_KEEP + 1] = e;
8149 }
8150 }
8151 }
8152 }
8153 371 grid_free(aTHX_ &g);
8154 371 Safefree(cx); Safefree(cy); Safefree(cz); Safefree(which);
8155 }
8156  
8157 //the bonds ks_compute() found, as a list a caller can read
8158 605 static AV *hbond_list(pTHX_ structset *CSP_RESTRICT s)
8159 {
8160 605 AV *out = newAV();
8161 UV d;
8162 12199 ▶ for (d = 0; d < s->n_res; d++) {
Branch: 1 branch
BranchTrueFalseTotal
for (d = 0; d < s->n_res; d++) { 11594 605 12199
8163 34782 ▶ for (unsigned short k = 0; k < CSP_KS_KEEP; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < CSP_KS_KEEP; k++) { 23188 11594 34782
8164 23188 UV a = s->ks_acc[d * CSP_KS_KEEP + k];
8165 HV *h;
8166 23188 ▶ if (a >= s->n_res) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (a >= s->n_res) continue; 21004 2184 23188
8167 2184 h = newHV();
8168 //the donor gives the hydrogen, the acceptor the carbonyl
8169 2184 pi_field(aTHX_ h, "donor_chain", 11, s->res_hv[d], "chain", 5);
8170 2184 pi_field(aTHX_ h, "donor_residue", 13, s->res_hv[d], "key", 3);
8171 2184 pi_field(aTHX_ h, "acceptor_chain", 14, s->res_hv[a], "chain", 5);
8172 2184 pi_field(aTHX_ h, "acceptor_residue", 16, s->res_hv[a], "key", 3);
8173 2184 (void)hv_stores(h, "energy", newSVnv(s->ks_e[d * CSP_KS_KEEP + k]));
8174 2184 av_push(out, newRV_noinc((SV *)h));
8175 }
8176 }
8177 605 return out;
8178 }
8179  
8180 /*Secondary structure, by the Kabsch-Sander dictionary.
8181  
8182 DSSP reads the backbone hydrogen bonds and nothing else: it gives every residue
8183 one of eight letters for the pattern the bonds around it fall into. Kabsch, W;
8184 Sander, C (1983) Biopolymers 22(12):2577-637 is the definition.
8185  
8186 H alpha helix: a 4-turn beginning at this residue and the one before it
8187 G 3-10 helix, from 3-turns; I pi helix, from 5-turns
8188 E extended strand: a residue in a beta ladder
8189 B isolated beta bridge: a bridge with no ladder around it
8190 T hydrogen-bonded turn: in an n-turn but in none of the above
8191 S bend: the chain turns through more than 70 degrees here
8192 coil: none of them, written as a space
8193  
8194 What follows is not the paper read afresh. It is mdtraj 1.11.1 transcribed
8195 function for function: mdtraj/geometry/src/dssp.cpp, which is DSSP 2.2.0 ported
8196 by Robert T. McGibbon, together with the kabsch_sander() it calls out of
8197 mdtraj/geometry/src/geometry.cpp and the fvec4 those two compute through,
8198 mdtraj/geometry/include/vectorize_sse.h. Agreeing with mdtraj letter for letter
8199 is the point of it, so t/features.t holds it to mdtraj's answer exactly rather
8200 than to a percentage of it.
8201  
8202 Measured: over every tenth entry of PDBbind v2020 -- 1,011 of the 1,012 read,
8203 the other being a file mdtraj will not open at all -- the two give the same
8204 letter for all 619,067 residues that have a backbone. Not most of them; all of
8205 them.
8206  
8207 There is one place where agreement is luck rather than construction, and it is
8208 mdtraj's end. It places an amide hydrogen from the residue before in its array
8209 without checking that that residue has a carbonyl, so where it has none --
8210 nco_indices holds -1 -- ks_assign_hydrogens() indexes the coordinate array with
8211 -1 and reads whatever lies in front of it. What it finds is not a structure and
8212 the hydrogen it places from it bonds to nothing, which is what this code does
8213 deliberately; if it ever found something, the two would part company there.
8214  
8215 Nothing here is the hydrogen bonds that structure_hbonds() reports. Those are
8216 the same energy over a table built to this module's own rules -- a donor has to
8217 be peptide-bonded to the residue its hydrogen is placed from -- and the two
8218 tables differ in a handful of bonds per structure. DSSP is defined on mdtraj's
8219 table and is computed from a second one, because a table built to be right and a
8220 table built to be mdtraj's cannot be the same table.*/
8221  
8222 /*The kernel is float, in nanometre.
8223  
8224 Everything else in this file computes in NV, so that it is as accurate as the
8225 perl running it. This block does not, and the departure is deliberate. mdtraj
8226 computes in float32 throughout -- coordinates, distances, energies -- and the
8227 assignment turns on two comparisons against constants: an energy below
8228 -0.5 kcal/mol is a bond, and a CA-to-CA separation under 0.9 nm is worth
8229 testing at all. Computing them wider does not make them better, it makes them
8230 different, and a pair that a float32 puts at -0.49999997 and an NV at
8231 -0.50000001 is a bond in one and not in the other. One bond is worth several
8232 residues' letters. So this rounds where mdtraj rounds:
8233  
8234 * Coordinates arrive as (float)((double)angstrom * 0.1). That is what
8235 mdtraj's PDB reader does -- it parses to double, multiplies by the double
8236 nearest 0.1 in mdtraj/utils/unit, and casts the array to float32 -- and it
8237 reproduces t.xyz bit for bit. The cast to double is not decoration: a
8238 long-double or __float128 NV multiplied at its own width and then narrowed
8239 would round twice and need not land on the same float.
8240 * Four products are summed as (p0 + p1) + (p2 + p3), not left to right,
8241 because mdtraj reaches them through fvec4's dot3() and dot4(), which are
8242 _mm_dp_ps2() -- a software DPPS whose horizontal add is two HADDPS.
8243 * Every intermediate is assigned to a named float, and nothing is left to be
8244 read back out of a wider expression. ISO C rounds at an assignment
8245 whatever FLT_EVAL_METHOD is, and gcc honours that in an ISO mode; in the
8246 -std=gnu99 Makefile.PL asks for it is free not to, and on an x87 target --
8247 a 32-bit build -- the wider format is 64 bits of mantissa. Written this
8248 way it comes out the same either way in practice: built with the 32-bit
8249 perlbrew perl, which is x87, it gives letter-for-letter the same answer as
8250 the x86-64 build over 307 entries of PDBbind v2020.
8251  
8252 sqrt() and acos() are called at double and the result cast back to float rather
8253 than calling sqrtf() and acosf(). For the square root that is exactly mdtraj's
8254 answer and not an approximation to it: double carries more than twice float's
8255 mantissa plus two bits, so rounding a correctly-rounded double square root down
8256 to float is the correctly-rounded float square root, which is what mdtraj's
8257 _mm_sqrt_ps returns. acos is not correctly rounded in either width, so that one
8258 is the same answer to within a last-place bit of the float, on a comparison
8259 against 70 degrees that a structure would have to be built to sit on. Neither
8260 goes through the nv_* macros: there is no NV here, the width is the point, and
8261 sqrtf()/acosf() are C99 where sqrt() and acos() are C89.*/
8262 #define SS_COIL ' '
8263 #define SS_BEND 'S'
8264 #define SS_TURN 'T'
8265 #define SS_PI 'I'
8266 #define SS_G310 'G'
8267 #define SS_BRIDGE 'B'
8268 #define SS_STRAND 'E'
8269 #define SS_HELIX 'H'
8270  
8271 #define DSSP_KEEP 2 //acceptors kept per donor
8272 #define DSSP_CA2 0.81f //(0.9 nm)^2: a pair further apart is not tested
8273 #define DSSP_CUTOFF (-0.5f) //kcal/mol: below this it is a bond
8274 #define DSSP_FLOOR (-9.9f) //kcal/mol: no bond is reported as stronger
8275 #define DSSP_H 0.1f //nm: N to the amide hydrogen it is given
8276 #define DSSP_COUPLE 2.7888f //332 kcal A/mol * 0.42 * 0.20, as kcal nm/mol
8277 /*70 degrees in radians, as the double mdtraj's `70 * (M_PI / 180.0)' is. The
8278 digits are M_PI's: CSP_PI is an NV and would be a different constant on a
8279 long-double or a quadmath build, and this comparison is mdtraj's, not this
8280 file's.*/
8281 #define DSSP_BEND (70.0 * (3.14159265358979323846 / 180.0))
8282  
8283 //one residue's backbone, in the width and the units the kernel works in
8284 typedef struct {
8285 float n[3], ca[3], c[3], o[3], h[3];//the amide H, placed from the residue before this one
8286 bool has_n, has_ca, has_c, has_o;
8287 bool whole;//all four: mdtraj's skip[] is the negation of this
8288 bool proline;//no amide hydrogen of its own: it accepts and never donates
8289 bool donor;//whole, not proline, and a hydrogen was placed for it
8290 } dssp_res;
8291  
8292 //angstrom as this module reads it to nanometre as mdtraj holds it; see the
8293 //block above for why the double is in the middle
8294 140244 static float dssp_nm(NV a)
8295 {
8296 140244 double d = (double)a * 0.1;
8297 140244 return (float)d;
8298 }
8299  
8300 /*The three products of two vectors, summed the way fvec4::dot3() sums them.
8301  
8302 No CSP_RESTRICT on the two: dot3(v, v) is how a squared length is asked for
8303 here, so they are routinely the same vector.*/
8304 205237 static float dssp_dot3(const float *a, const float *b){
8305 205237 float p0 = a[0] * b[0], p1 = a[1] * b[1], p2 = a[2] * b[2];
8306 205237 float lo = p0 + p1, hi = p2 + 0.0f;
8307 205237 return lo + hi;
8308 }
8309  
8310 202146 static void dssp_sub3(const float *CSP_RESTRICT a, const float *CSP_RESTRICT b, float *CSP_RESTRICT out){
8311 202146 out[0] = a[0] - b[0];
8312 202146 out[1] = a[1] - b[1];
8313 202146 out[2] = a[2] - b[2];
8314 202146 }
8315  
8316 /*The energy of the bond from acceptor a's C=O to donor d's N-H.
8317  
8318 E = 2.7888 * (1/r_ON + 1/r_CH - 1/r_OH - 1/r_CN), kcal/mol, with the four
8319 reciprocals summed in the order fvec4::dot4() sums them: the pairs are
8320 (ON, CH) and (OH, CN) in mdtraj's `coupling' vector, which lists them
8321 OH, CN, CH, ON with the first two negated.*/
8322 32112 static float dssp_energy(const dssp_res *CSP_RESTRICT a, const dssp_res *CSP_RESTRICT d){
8323 float v[3], r[4], lo, hi, e;
8324 32112 dssp_sub3(d->h, a->o, v); r[0] = dssp_dot3(v, v);
8325 32112 dssp_sub3(d->n, a->c, v); r[1] = dssp_dot3(v, v);
8326 32112 dssp_sub3(d->h, a->c, v); r[2] = dssp_dot3(v, v);
8327 32112 dssp_sub3(d->n, a->o, v); r[3] = dssp_dot3(v, v);
8328 160560 ▶ for (unsigned short k = 0; k < 4; k++) r[k] = 1.0f / (float)sqrt((double)r[k]);
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < 4; k++) r[k] = 1.0f / (float)sqrt((double)r[k]); 128448 32112 160560
8329 32112 lo = (-DSSP_COUPLE) * r[0] + (-DSSP_COUPLE) * r[1];
8330 32112 hi = DSSP_COUPLE * r[2] + DSSP_COUPLE * r[3];
8331 32112 e = lo + hi;
8332 32112 ▶ return (e < DSSP_FLOOR) ? DSSP_FLOOR : e;
Branch: 1 branch
BranchTrueFalseTotal
return (e < DSSP_FLOOR) ? DSSP_FLOOR : e; 0 32112 32112
8333 }
8334  
8335 /*Which DSSP chain each residue is in.
8336  
8337 mdtraj is handed one chain index per residue and will not let a turn, a bridge
8338 or a bend reach from one chain into another. Its chains are not this module's:
8339 reading PDB it starts a new one at every TER and at every change of chain id, so
8340 a chain's ligands and its waters are chains of their own, and reading mmCIF it
8341 takes them from label_asym_id, which draws the same line. This module keeps a
8342 chain whole -- polymer, ligands and waters under the one author id -- so the
8343 division has to be made here.
8344  
8345 The rule that reproduces the TER is to cut an author chain in two after the last
8346 residue of its polymer. A residue counts as polymer when the Perl half typed it
8347 an amino acid or a nucleotide -- not when its name merely looks like one -- and
8348 when it is either an ATOM record or a modified residue. Each of those three
8349 clauses is there for cases that come up:
8350  
8351 * The name is not enough. A residue the table has never heard of can sit in
8352 the middle of a chain and is part of it in mdtraj too (5MAD's chromophore
8353 CRO 66, 5TTW's trimethyl-lysine M3L 3); a free amino acid sitting after the
8354 chain is a ligand and a chain of its own (3TDJ's GLU 401, 1XQH's SAH, the
8355 free SER 502 that follows 6BMI's GLU 416).
8356 * The type alone is not enough either, or was not: the Perl half used to
8357 tell a free residue from a modified one by its number, and 3LMS chain A,
8358 numbered 4, 567, 1501, 1889 and so on, left its free GLY 501 an amino
8359 acid. It now goes by where the residue sits and whether it is bonded to
8360 the chain, which calls GLY 501 a ligand, but that bond is gemmi's C-N
8361 length and this cut uses Biopython's, so the HETATM test stays: which
8362 residues DSSP calls one chain should not move with the Perl half's rule.
8363 * HETATM alone is not enough, because a modified residue capping a terminus is
8364 a HETATM inside the chain.
8365  
8366 None of the three catches a residue the name table has never heard of that is
8367 nonetheless the last residue of the chain: 1CMX ends chains B and D with a GLZ,
8368 a glycine capped at the carboxyl, and the TER is after it. So once the cut has
8369 been found it is walked forward over anything that is peptide-bonded to what
8370 comes before it, which is the difference between a cap and a free amino acid in
8371 a binding site and the only difference there is. Forward from the cut and not
8372 anywhere: 4QFP has a free valyl-threonine dipeptide sitting after chain A, and
8373 its two residues are bonded to each other but not to the chain. The bond length
8374 is this file's own constant rather than the peptide_bond option -- which
8375 residues DSSP calls one chain is not something to tune underneath it.
8376  
8377 A residue with no backbone is skipped by the assignment wherever it sits, so
8378 what the cut is really for is the handful of guards that ask whether i-1 and
8379 i+1, or i-2 and i+2, are in one chain without asking whether they are protein.*/
8380 11687 static bool dssp_is_polymer(pTHX_ HV *CSP_RESTRICT res){
8381 11687 SV *t = hvf_sv(aTHX_ res, "type", 4);
8382 SV *h, *m;
8383 23373 ▶ const char *p = t ? SvPV_nolen(t) : NULL;
Branch: 1 branch
BranchTrueFalseTotal
const char *p = t ? SvPV_nolen(t) : NULL; 11686 1 11687
8384 11687 ▶ if (!p || !(strEQ(p, "amino_acid") || strEQ(p, "nucleotide"))) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (!p || !(strEQ(p, "amino_acid") || strEQ(p, "nucleotide"))) return 0; 11686 1 11687
if (!p || !(strEQ(p, "amino_acid") || strEQ(p, "nucleotide"))) return 0; 4024 7662 11686
if (!p || !(strEQ(p, "amino_acid") || strEQ(p, "nucleotide"))) return 0; 2674 1350 4024
8385 9012 h = hvf_sv(aTHX_ res, "hetero", 6);
8386 9012 ▶ if (!h || !SvTRUE(h)) return 1;
Branch: 2 branches
BranchTrueFalseTotal
if (!h || !SvTRUE(h)) return 1; 9012 0 9012
if (!h || !SvTRUE(h)) return 1; 8865 147 9012
8387 147 m = hvf_sv(aTHX_ res, "modified", 8);
8388 147 ▶ return (m && SvTRUE(m)) ? TRUE : FALSE;
Branch: 2 branches
BranchTrueFalseTotal
return (m && SvTRUE(m)) ? TRUE : FALSE; 147 0 147
return (m && SvTRUE(m)) ? TRUE : FALSE; 144 3 147
8389 }
8390  
8391 579 static void dssp_segments(pTHX_ structset *CSP_RESTRICT s, UV *CSP_RESTRICT seg){
8392 579 UV r, k = 0;
8393 1375 ▶ for (UV c = 0; c < s->n_chain; c++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV c = 0; c < s->n_chain; c++) { 796 579 1375
8394 796 UV first = s->chain_first[c], last = s->chain_last[c], cut = first;
8395 12483 ▶ for (r = first; r < last; r++)
Branch: 1 branch
BranchTrueFalseTotal
for (r = first; r < last; r++) 11687 796 12483
8396 11687 ▶ if (dssp_is_polymer(aTHX_ s->res_hv[r])) cut = r + 1;
Branch: 1 branch
BranchTrueFalseTotal
if (dssp_is_polymer(aTHX_ s->res_hv[r])) cut = r + 1; 9009 2678 11687
8397 1546 ▶ while (cut > first && cut < last
Branch: 1 branch
BranchTrueFalseTotal
while (cut > first && cut < last 186 564 750
8398 984 ▶ && peptide_linked(aTHX_ s, cut - 1, cut, CSP_PEPTIDE_BOND))
Branch: 2 branches
BranchTrueFalseTotal
&& peptide_linked(aTHX_ s, cut - 1, cut, CSP_PEPTIDE_BOND)) 750 48 798
&& peptide_linked(aTHX_ s, cut - 1, cut, CSP_PEPTIDE_BOND)) 2 184 186
8399 2 cut++;
8400 12483 ▶ for (r = first; r < last; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = first; r < last; r++) { 11687 796 12483
8401 11687 ▶ if (r == cut && r != first) k++;
Branch: 2 branches
BranchTrueFalseTotal
if (r == cut && r != first) k++; 232 11455 11687
if (r == cut && r != first) k++; 184 48 232
8402 11687 seg[r] = k;
8403 }
8404 796 k++;
8405 }
8406 579 }
8407  
8408 /*The backbone, and the amide hydrogen on it.
8409  
8410 mdtraj places the hydrogen of residue r from the carbonyl of residue r-1 in its
8411 array: one angstrom from r's nitrogen, along the direction from that carbonyl's
8412 carbon to its oxygen. It does so whether or not the two are bonded, whether or
8413 not they are in the same chain, and -- see the head of this block -- whether or
8414 not r-1 has a carbonyl at all. Here r-1 is the residue before r in the walk,
8415 and the hydrogen is placed only when that residue is in the same DSSP chain and
8416 does have a C and an O. A residue with no hydrogen cannot donate.
8417  
8418 That is the one place this deliberately does not follow mdtraj to the letter,
8419 and the two cases it covers are the two mdtraj has no answer for: the first
8420 residue of the whole structure, which mdtraj gives a hydrogen sitting on top of
8421 its own nitrogen, and a residue whose predecessor has no carbonyl, where mdtraj
8422 reads off the front of its array. A hydrogen placed from either is a hydrogen
8423 in a direction nothing chose, and over the thousand entries measured at the head
8424 of this block, refusing to place it changes no letter.*/
8425 579 static void dssp_read(pTHX_ structset *CSP_RESTRICT s, dssp_res *CSP_RESTRICT bb, const UV *CSP_RESTRICT seg){
8426 579 const bb_xyz *x = bb_get(aTHX_ s);
8427 12266 ▶ for (UV r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV r = 0; r < s->n_res; r++) { 11687 579 12266
8428 11687 dssp_res *b = &bb[r];
8429 11687 Zero(b, 1, dssp_res);
8430 11687 b->proline = (s->res_key[r] == K3('P','R','O'));
8431 46748 ▶ for (unsigned short k = 0; k < 3; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < 3; k++) { 35061 11687 46748
8432 35061 b->n[k] = dssp_nm(x[r].n[k]);
8433 35061 b->ca[k] = dssp_nm(x[r].ca[k]);
8434 35061 b->c[k] = dssp_nm(x[r].c[k]);
8435 35061 b->o[k] = dssp_nm(x[r].o[k]);
8436 }
8437 11687 b->has_n = x[r].has_n; b->has_ca = x[r].has_ca;
8438 11687 b->has_c = x[r].has_c; b->has_o = x[r].has_o;
8439 11687 ▶ b->whole = b->has_n && b->has_ca && b->has_c && b->has_o;
Branch: 4 branches
BranchTrueFalseTotal
b->whole = b->has_n && b->has_ca && b->has_c && b->has_o; 6624 5063 11687
b->whole = b->has_n && b->has_ca && b->has_c && b->has_o; 6611 13 6624
b->whole = b->has_n && b->has_ca && b->has_c && b->has_o; 6607 4 6611
b->whole = b->has_n && b->has_ca && b->has_c && b->has_o; 6561 46 6607
8440 }
8441 11687 ▶ for (UV r = 1; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV r = 1; r < s->n_res; r++) { 11108 579 11687
8442 11108 dssp_res *b = &bb[r];
8443 11108 const dssp_res *p = &bb[r - 1];
8444 float co[3], len;
8445 11113 ▶ if (!b->whole || b->proline) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!b->whole || b->proline) continue; 6201 4907 11108
if (!b->whole || b->proline) continue; 478 5723 6201
8446 5723 ▶ if (seg[r] != seg[r - 1] || !p->has_c || !p->has_o) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (seg[r] != seg[r - 1] || !p->has_c || !p->has_o) continue; 5719 4 5723
if (seg[r] != seg[r - 1] || !p->has_c || !p->has_o) continue; 5719 0 5719
if (seg[r] != seg[r - 1] || !p->has_c || !p->has_o) continue; 0 5719 5719
8447 5719 dssp_sub3(p->c, p->o, co);
8448 5719 len = (float)sqrt((double)dssp_dot3(co, co));
8449 5719 ▶ if (!(len > 0.0f)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(len > 0.0f)) continue; 1 5718 5719
8450 22872 ▶ for (unsigned short k = 0; k < 3; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < 3; k++) { 17154 5718 22872
8451 //one step per named float, so that each is rounded to float where
8452 //it is in mdtraj, rather than a wider product reaching the sum
8453 17154 float u = co[k] / len;
8454 17154 float step = u * DSSP_H;
8455 17154 b->h[k] = b->n[k] + step;
8456 }
8457 5718 b->donor = 1;
8458 }
8459 579 }
8460  
8461 /*Keep the two lowest energies a donor has, best first.
8462  
8463 mdtraj's store_energies(), which tests its slots for NaN because the array
8464 kabsch_sander() fills for its own caller starts as NaN; the one the DSSP pass
8465 fills starts as zero, so the NaN arm is never taken there and an empty slot is
8466 the one with no acceptor in it. Which slot an acceptor lands in does not depend
8467 on the order they arrive in.*/
8468 2330 static void dssp_store(UV n_res, UV *CSP_RESTRICT acc, float *CSP_RESTRICT en, UV donor, UV a, float e){
8469 2330 UV slot = donor * DSSP_KEEP;
8470 2330 ▶ if (acc[slot] >= n_res || e < en[slot]) {
Branch: 2 branches
BranchTrueFalseTotal
if (acc[slot] >= n_res || e < en[slot]) { 207 2123 2330
if (acc[slot] >= n_res || e < en[slot]) { 88 119 207
8471 2211 acc[slot + 1] = acc[slot];
8472 2211 en[slot + 1] = en[slot];
8473 2211 acc[slot] = a;
8474 2211 en[slot] = e;
8475 119 ▶ } else if (acc[slot + 1] >= n_res || e < en[slot + 1]) {
Branch: 2 branches
BranchTrueFalseTotal
} else if (acc[slot + 1] >= n_res || e < en[slot + 1]) { 7 112 119
} else if (acc[slot + 1] >= n_res || e < en[slot + 1]) { 0 7 7
8476 112 acc[slot + 1] = a;
8477 112 en[slot + 1] = e;
8478 }
8479 2330 }
8480  
8481 /*The hydrogen bonds DSSP is read from: each residue's two best acceptors.
8482  
8483 mdtraj walks every pair of residues and tests the CA separation first; this
8484 walks a cell grid over the CA atoms instead, which finds the same pairs and does
8485 not take a ribosome quadratically. The grid is only a sieve: what decides is
8486 the float comparison against 0.81 below, which is mdtraj's own.
8487  
8488 The cell is 0.9001 nm and not 0.9 because the two are not measuring quite the
8489 same thing. The float dot3() carries three products and two sums, each rounded,
8490 so it can sit as much as 4 * 2^-24 below the exact squared distance; a pair it
8491 puts just inside 0.81 can therefore be as far apart as 0.90000011 nm, and a
8492 0.9 nm cell would have thrown it away before the comparison that keeps it.
8493 0.0001 nm of cell is eight hundred times that bound and costs nothing -- the
8494 cell count changes by a part in ten thousand.
8495  
8496 Which of two acceptors ends up in which slot does not depend on the order the
8497 pairs arrive in -- the pair kept is the two lowest energies either way -- so the
8498 grid's order is free. Two acceptors at bit-identical energies would be the
8499 exception, and that is a structure built to have one.
8500  
8501 acc[d * DSSP_KEEP + k] is the residue whose carbonyl residue d's amide hydrogen
8502 is bonded to, or n_res where there is no such bond.*/
8503 579 static void dssp_hbonds(pTHX_ structset *CSP_RESTRICT s, const dssp_res *CSP_RESTRICT bb, UV *CSP_RESTRICT acc, float *CSP_RESTRICT en){
8504 579 NV *CSP_RESTRICT cx = NULL, *CSP_RESTRICT cy = NULL, *CSP_RESTRICT cz = NULL;
8505 579 UV *CSP_RESTRICT which = NULL;
8506 cell_grid g;
8507 579 UV n = 0;
8508  
8509 23953 ▶ for (UV r = 0; r < s->n_res * DSSP_KEEP; r++) { acc[r] = s->n_res; en[r] = 0.0f; }
Branch: 1 branch
BranchTrueFalseTotal
for (UV r = 0; r < s->n_res * DSSP_KEEP; r++) { acc[r] = s->n_res; en[r] = 0.0f; } 23374 579 23953
8510 784 ▶ if (s->n_res == 0) return;
Branch: 1 branch
BranchTrueFalseTotal
if (s->n_res == 0) return; 0 579 579
8511  
8512 579 ▶ Newx(cx, s->n_res, NV); Newx(cy, s->n_res, NV); Newx(cz, s->n_res, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(cx, s->n_res, NV); Newx(cy, s->n_res, NV); Newx(cz, s->n_res, NV); 0 579 579
Newx(cx, s->n_res, NV); Newx(cy, s->n_res, NV); Newx(cz, s->n_res, NV); 0 579 579
Newx(cx, s->n_res, NV); Newx(cy, s->n_res, NV); Newx(cz, s->n_res, NV); 0 579 579
8513 579 ▶ Newx(which, s->n_res, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(which, s->n_res, UV); 0 579 579
8514 12266 ▶ for (UV r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV r = 0; r < s->n_res; r++) { 11687 579 12266
8515 11687 ▶ if (!bb[r].whole) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!bb[r].whole) continue; 5126 6561 11687
8516 6561 cx[n] = (NV)bb[r].ca[0]; cy[n] = (NV)bb[r].ca[1]; cz[n] = (NV)bb[r].ca[2];
8517 6561 which[n] = r;
8518 6561 n++;
8519 }
8520 579 ▶ if (n == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) { 205 374 579
8521 205 Safefree(cx); Safefree(cy); Safefree(cz); Safefree(which);
8522 205 return;
8523 }
8524 374 grid_build(aTHX_ &g, cx, cy, cz, n, 0.9001);//nm; see the head of this function
8525  
8526 6935 ▶ for (UV k = 0; k < n; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV k = 0; k < n; k++) { 6561 374 6935
8527 6561 UV i = which[k];
8528 UV bx, by, bz, ci, cj, ck;
8529 6561 ci = grid_axis(cx[k] - g.x0, g.cell, g.nx);
8530 6561 cj = grid_axis(cy[k] - g.y0, g.cell, g.ny);
8531 6561 ck = grid_axis(cz[k] - g.z0, g.cell, g.nz);
8532 22339 ▶ for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++)
Branch: 3 branches
BranchTrueFalseTotal
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++) 4133 2428 6561
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++) 18110 4229 22339
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++) 15778 6561 22339
8533 49378 ▶ for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++)
Branch: 3 branches
BranchTrueFalseTotal
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++) 7901 7877 15778
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++) 35255 14123 49378
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++) 33600 15778 49378
8534 115585 ▶ for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) {
Branch: 3 branches
BranchTrueFalseTotal
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) { 22505 11095 33600
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) { 95873 19712 115585
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) { 81985 33600 115585
8535 81985 UV cell = (bx * g.ny + by) * g.nz + bz, p;
8536 212140 ▶ for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = g.start[cell]; p < g.start[cell + 1]; p++) { 130155 81985 212140
8537 130155 UV j = which[g.idx[p]];
8538 float d[3], e;
8539 171050 ▶ if (j <= i) continue;//each pair once, in mdtraj's i < j order
Branch: 1 branch
BranchTrueFalseTotal
if (j <= i) continue;//each pair once, in mdtraj's i < j order 68358 61797 130155
8540 61797 dssp_sub3(bb[i].ca, bb[j].ca, d);
8541 61797 ▶ if (!(dssp_dot3(d, d) < DSSP_CA2)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(dssp_dot3(d, d) < DSSP_CA2)) continue; 40895 20902 61797
8542 20902 ▶ if (bb[i].donor) {
Branch: 1 branch
BranchTrueFalseTotal
if (bb[i].donor) { 18580 2322 20902
8543 18580 e = dssp_energy(&bb[j], &bb[i]);
8544 18580 ▶ if (e < DSSP_CUTOFF) dssp_store(s->n_res, acc, en, i, j, e);
Branch: 1 branch
BranchTrueFalseTotal
if (e < DSSP_CUTOFF) dssp_store(s->n_res, acc, en, i, j, e); 389 18191 18580
8545 }
8546 /*The pair a residue makes with the one before it is not a bond
8547 to test in that direction: j's hydrogen was placed from i's own
8548 carbonyl, so the two are one peptide unit and the energy between
8549 them is an artefact of having placed it. mdtraj skips it as
8550 rj == ri + 1 in its array, which is the same residue as this.*/
8551 20902 ▶ if (j != i + 1 && bb[j].donor) {
Branch: 2 branches
BranchTrueFalseTotal
if (j != i + 1 && bb[j].donor) { 14990 5912 20902
if (j != i + 1 && bb[j].donor) { 13532 1458 14990
8552 13532 e = dssp_energy(&bb[i], &bb[j]);
8553 13532 ▶ if (e < DSSP_CUTOFF) dssp_store(s->n_res, acc, en, j, i, e);
Branch: 1 branch
BranchTrueFalseTotal
if (e < DSSP_CUTOFF) dssp_store(s->n_res, acc, en, j, i, e); 1941 11591 13532
8554 }
8555 }
8556 }
8557 }
8558 374 grid_free(aTHX_ &g);
8559 374 Safefree(cx); Safefree(cy); Safefree(cz); Safefree(which);
8560 }
8561  
8562 //is the C=O of `a' bonded to the N-H of `d'? Two acceptors are kept per donor,
8563 //so this is two comparisons rather than a search
8564 43351 static bool dssp_bonded(UV n_res, const UV *CSP_RESTRICT acc, UV d, UV a){
8565 43351 ▶ if (d >= n_res || a >= n_res) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (d >= n_res || a >= n_res) return 0; 43351 0 43351
if (d >= n_res || a >= n_res) return 0; 0 43351 43351
8566 43351 ▶ return acc[d * DSSP_KEEP] == a || acc[d * DSSP_KEEP + 1] == a;
Branch: 2 branches
BranchTrueFalseTotal
return acc[d * DSSP_KEEP] == a || acc[d * DSSP_KEEP + 1] == a; 40579 2772 43351
return acc[d * DSSP_KEEP] == a || acc[d * DSSP_KEEP + 1] == a; 212 40367 40579
8567 }
8568  
8569 #define BR_NONE 0
8570 #define BR_PARA 1 //the two strands run the same way
8571 #define BR_ANTI 2 //they run opposite ways
8572  
8573 /*Is the pair (i, j) a beta bridge, and of which kind?
8574  
8575 mdtraj's MResidue::TestBridge(), which is the 1983 paper's definition with one
8576 thing added: the residue on each side needs a neighbour before and after it in
8577 the same chain, whether or not the pattern names that neighbour. The two
8578 strands themselves may be in different chains, and often are.*/
8579 3241 static unsigned char dssp_test_bridge(UV n_res, const UV *CSP_RESTRICT seg, const UV *CSP_RESTRICT acc, UV i, UV j){
8580 3241 UV a, b = i, c = i + 1, d, e = j, f = j + 1;
8581 3241 ▶ if (i == 0 || j == 0) return BR_NONE;
Branch: 2 branches
BranchTrueFalseTotal
if (i == 0 || j == 0) return BR_NONE; 3241 0 3241
if (i == 0 || j == 0) return BR_NONE; 0 3241 3241
8582 3241 a = i - 1; d = j - 1;
8583 3241 ▶ if (c >= n_res || f >= n_res) return BR_NONE;
Branch: 2 branches
BranchTrueFalseTotal
if (c >= n_res || f >= n_res) return BR_NONE; 3241 0 3241
if (c >= n_res || f >= n_res) return BR_NONE; 0 3241 3241
8584 3241 ▶ if (seg[a] != seg[c] || seg[d] != seg[f]) return BR_NONE;
Branch: 2 branches
BranchTrueFalseTotal
if (seg[a] != seg[c] || seg[d] != seg[f]) return BR_NONE; 3241 0 3241
if (seg[a] != seg[c] || seg[d] != seg[f]) return BR_NONE; 0 3241 3241
8585 3241 ▶ if ((dssp_bonded(n_res, acc, c, e) && dssp_bonded(n_res, acc, e, a))
Branch: 2 branches
BranchTrueFalseTotal
if ((dssp_bonded(n_res, acc, c, e) && dssp_bonded(n_res, acc, e, a)) 589 2652 3241
if ((dssp_bonded(n_res, acc, c, e) && dssp_bonded(n_res, acc, e, a)) 589 0 589
8586 3241 ▶ || (dssp_bonded(n_res, acc, f, b) && dssp_bonded(n_res, acc, b, d)))
Branch: 2 branches
BranchTrueFalseTotal
|| (dssp_bonded(n_res, acc, f, b) && dssp_bonded(n_res, acc, b, d))) 327 2914 3241
|| (dssp_bonded(n_res, acc, f, b) && dssp_bonded(n_res, acc, b, d))) 17 310 327
8587 17 return BR_PARA;
8588 3224 ▶ if ((dssp_bonded(n_res, acc, c, d) && dssp_bonded(n_res, acc, f, a))
Branch: 2 branches
BranchTrueFalseTotal
if ((dssp_bonded(n_res, acc, c, d) && dssp_bonded(n_res, acc, f, a)) 247 2977 3224
if ((dssp_bonded(n_res, acc, c, d) && dssp_bonded(n_res, acc, f, a)) 104 143 247
8589 3081 ▶ || (dssp_bonded(n_res, acc, e, b) && dssp_bonded(n_res, acc, b, e)))
Branch: 2 branches
BranchTrueFalseTotal
|| (dssp_bonded(n_res, acc, e, b) && dssp_bonded(n_res, acc, b, e))) 327 2754 3081
|| (dssp_bonded(n_res, acc, e, b) && dssp_bonded(n_res, acc, b, e))) 149 178 327
8590 292 return BR_ANTI;
8591 2932 return BR_NONE;
8592 }
8593  
8594 /*A bridge, and then a ladder: the run of residues [i_first, i_last] paired with
8595 the run [j_first, j_last]. Both runs are contiguous while the ladder is being
8596 built -- a bridge only extends one residue at a time, at one end -- and stop
8597 being so when two ladders are joined across a bulge, which is why the ends are
8598 kept rather than the runs. n_i is the count the join does not disturb, and
8599 tells an isolated bridge from a ladder.*/
8600 typedef struct {
8601 unsigned char type;//BR_PARA or BR_ANTI
8602 /*the DSSP chain the i run is in. mdtraj's Bridge keeps the j run's as well
8603 and never reads it, so this does not keep it.*/
8604 UV chain_i;
8605 UV i_first, i_last, j_first, j_last, n_i;
8606 UV seq;//the order it was found in, so the sort below is stable
8607 } dssp_bridge;
8608  
8609 165 static int dssp_bridge_cmp(const void *pa, const void *pb){
8610 /*No CSP_RESTRICT and no const on the parameters beyond what qsort asks for:
8611 the prototype is the C library's, not this file's.*/
8612 165 const dssp_bridge *a = (const dssp_bridge *)pa;
8613 165 const dssp_bridge *b = (const dssp_bridge *)pb;
8614 165 ▶ if (a->chain_i != b->chain_i) return (a->chain_i < b->chain_i) ? -1 : 1;
Branch: 2 branches
BranchTrueFalseTotal
if (a->chain_i != b->chain_i) return (a->chain_i < b->chain_i) ? -1 : 1; 0 165 165
if (a->chain_i != b->chain_i) return (a->chain_i < b->chain_i) ? -1 : 1; 0 0 0
8615 165 ▶ if (a->i_first != b->i_first) return (a->i_first < b->i_first) ? -1 : 1;
Branch: 2 branches
BranchTrueFalseTotal
if (a->i_first != b->i_first) return (a->i_first < b->i_first) ? -1 : 1; 165 0 165
if (a->i_first != b->i_first) return (a->i_first < b->i_first) ? -1 : 1; 165 0 165
8616 0 ▶ return (a->seq < b->seq) ? -1 : (a->seq > b->seq);
Branch: 1 branch
BranchTrueFalseTotal
return (a->seq < b->seq) ? -1 : (a->seq > b->seq); 0 0 0
8617 }
8618  
8619 //a candidate pair for the bridge search, and the order the search visits them in
8620 typedef struct { UV i, j; } dssp_pair;
8621  
8622 15493 static int dssp_pair_cmp(const void *pa, const void *pb){
8623 15493 const dssp_pair *a = (const dssp_pair *)pa;
8624 15493 const dssp_pair *b = (const dssp_pair *)pb;
8625 15493 ▶ if (a->i != b->i) return (a->i < b->i) ? -1 : 1;
Branch: 2 branches
BranchTrueFalseTotal
if (a->i != b->i) return (a->i < b->i) ? -1 : 1; 11766 3727 15493
if (a->i != b->i) return (a->i < b->i) ? -1 : 1; 8125 3641 11766
8626 3727 ▶ return (a->j < b->j) ? -1 : (a->j > b->j);
Branch: 1 branch
BranchTrueFalseTotal
return (a->j < b->j) ? -1 : (a->j > b->j); 2098 1629 3727
8627 }
8628  
8629 /*The pairs the bridge search has to look at.
8630  
8631 mdtraj walks every (i, j) with 1 <= i < n-4 and i+3 <= j < n-1 and asks
8632 dssp_test_bridge() about each, which is quadratic in the residues; a ribosome
8633 has half a million of them. Every one of the four bridge patterns names two
8634 hydrogen bonds, though, so a pair with no bond in any of the eight positions the
8635 patterns can put one in cannot be a bridge and the walk would only have thrown
8636 it away. Reading each bond back through the eight positions gives the same
8637 pairs, in a list linear in the bonds; sorting it puts them in the order the walk
8638 would have reached them, which is the order the ladders are built in and so part
8639 of the answer.*/
8640 579 static UV dssp_candidates(pTHX_ UV n_res, const UV *CSP_RESTRICT acc, dssp_pair *CSP_RESTRICT *CSP_RESTRICT out){
8641 579 dssp_pair *CSP_RESTRICT p = NULL;
8642 579 ▶ if (n_res < 6) { *out = NULL; return 0; }
Branch: 1 branch
BranchTrueFalseTotal
if (n_res < 6) { *out = NULL; return 0; } 193 386 579
8643 386 UV cap = 0, n = 0, d, w;
8644 11594 ▶ for (d = 0; d < n_res; d++) {
Branch: 1 branch
BranchTrueFalseTotal
for (d = 0; d < n_res; d++) { 11208 386 11594
8645 33624 ▶ for (unsigned short k = 0; k < DSSP_KEEP; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short k = 0; k < DSSP_KEEP; k++) { 22416 11208 33624
8646 22416 UV a = acc[d * DSSP_KEEP + k], cand[8][2];
8647 22416 ▶ if (a >= n_res) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (a >= n_res) continue; 20205 2211 22416
8648 {
8649 /*the eight (i, j) the bond d -> a can be half of. d - 1 where d
8650 is 0 is mdtraj's -1, a position no pair can use; it is written
8651 as n_res, which the bounds test below drops.*/
8652 2211 ▶ UV dm1 = d ? d - 1 : n_res;
Branch: 1 branch
BranchTrueFalseTotal
UV dm1 = d ? d - 1 : n_res; 2211 0 2211
8653 2211 cand[0][0] = a; cand[0][1] = dm1;
8654 2211 cand[1][0] = d; cand[1][1] = a + 1;
8655 2211 cand[2][0] = dm1; cand[2][1] = a;
8656 2211 cand[3][0] = a + 1; cand[3][1] = d;
8657 2211 cand[4][0] = a + 1; cand[4][1] = dm1;
8658 2211 cand[5][0] = dm1; cand[5][1] = a + 1;
8659 2211 cand[6][0] = d; cand[6][1] = a;
8660 2211 cand[7][0] = a; cand[7][1] = d;
8661 }
8662 19899 ▶ for (unsigned short c = 0; c < 8; c++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short c = 0; c < 8; c++) { 17688 2211 19899
8663 17688 UV i = cand[c][0], j = cand[c][1];
8664 17688 ▶ if (i < 1 || i + 4 >= n_res) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (i < 1 || i + 4 >= n_res) continue; 17638 50 17688
if (i < 1 || i + 4 >= n_res) continue; 612 17026 17638
8665 17026 ▶ if (j < i + 3 || j + 1 >= n_res) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (j < i + 3 || j + 1 >= n_res) continue; 4143 12883 17026
if (j < i + 3 || j + 1 >= n_res) continue; 12 4131 4143
8666 4131 ▶ if (n == cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (n == cap) { 99 4032 4131
8667 99 ▶ cap = cap ? cap * 2 : 64;
Branch: 1 branch
BranchTrueFalseTotal
cap = cap ? cap * 2 : 64; 23 76 99
8668 99 ▶ Renew(p, cap, dssp_pair);
Branch: 1 branch
BranchTrueFalseTotal
Renew(p, cap, dssp_pair); 0 99 99
8669 }
8670 4131 p[n].i = i; p[n].j = j;
8671 4131 n++;
8672 }
8673 }
8674 }
8675 386 ▶ if (n > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (n > 1) { 76 310 386
8676 76 qsort(p, (size_t)n, sizeof(dssp_pair), dssp_pair_cmp);
8677 //the same pair is reached from several bonds; keep one of each
8678 4131 ▶ for (w = 1, d = 1; d < n; d++)
Branch: 1 branch
BranchTrueFalseTotal
for (w = 1, d = 1; d < n; d++) 4055 76 4131
8679 4055 ▶ if (p[d].i != p[w - 1].i || p[d].j != p[w - 1].j) p[w++] = p[d];
Branch: 2 branches
BranchTrueFalseTotal
if (p[d].i != p[w - 1].i || p[d].j != p[w - 1].j) p[w++] = p[d]; 2442 1613 4055
if (p[d].i != p[w - 1].i || p[d].j != p[w - 1].j) p[w++] = p[d]; 1552 890 2442
8680 76 n = w;
8681 }
8682 386 *out = p;
8683 386 return n;
8684 }
8685  
8686 /*The beta secondary structure, onto `ss'.
8687  
8688 mdtraj's MProtein::CalculateBetaSheets(): find the bridges, join the ladders
8689 that a bulge separates, then write E over every residue between the ends of a
8690 ladder and B over a bridge that stands alone.*/
8691 579 static void dssp_sheets(pTHX_ UV n_res, const UV *CSP_RESTRICT seg, const UV *CSP_RESTRICT acc, const dssp_res *CSP_RESTRICT bb, char *CSP_RESTRICT ss){
8692 579 dssp_pair *CSP_RESTRICT cand = NULL;
8693 579 dssp_bridge *CSP_RESTRICT br = NULL;
8694 579 UV ncand, nbr = 0, cap = 0, c;
8695  
8696 579 ncand = dssp_candidates(aTHX_ n_res, acc, &cand);
8697 3820 ▶ for (c = 0; c < ncand; c++) {
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < ncand; c++) { 3241 579 3820
8698 3241 UV i = cand[c].i, j = cand[c].j;
8699 3241 unsigned char type = dssp_test_bridge(n_res, seg, acc, j, i);
8700 3241 bool found = 0;
8701 3241 ▶ if (type == BR_NONE || !bb[i].whole || !bb[j].whole) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (type == BR_NONE || !bb[i].whole || !bb[j].whole) continue; 309 2932 3241
if (type == BR_NONE || !bb[i].whole || !bb[j].whole) continue; 309 0 309
if (type == BR_NONE || !bb[i].whole || !bb[j].whole) continue; 0 309 309
8702 1189 ▶ for (UV x = 0; x < nbr; x++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV x = 0; x < nbr; x++) { 1052 137 1189
8703 1052 ▶ if (type != br[x].type || i != br[x].i_last + 1) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (type != br[x].type || i != br[x].i_last + 1) continue; 865 187 1052
if (type != br[x].type || i != br[x].i_last + 1) continue; 676 189 865
8704 189 ▶ if (type == BR_PARA && br[x].j_last + 1 == j) {
Branch: 2 branches
BranchTrueFalseTotal
if (type == BR_PARA && br[x].j_last + 1 == j) { 0 189 189
if (type == BR_PARA && br[x].j_last + 1 == j) { 0 0 0
8705 0 br[x].i_last = i; br[x].j_last = j; br[x].n_i++;
8706 0 found = 1;
8707 0 break;
8708 }
8709 189 ▶ if (type == BR_ANTI && br[x].j_first > 0 && br[x].j_first - 1 == j) {
Branch: 3 branches
BranchTrueFalseTotal
if (type == BR_ANTI && br[x].j_first > 0 && br[x].j_first - 1 == j) { 189 0 189
if (type == BR_ANTI && br[x].j_first > 0 && br[x].j_first - 1 == j) { 189 0 189
if (type == BR_ANTI && br[x].j_first > 0 && br[x].j_first - 1 == j) { 172 17 189
8710 172 br[x].i_last = i; br[x].j_first = j; br[x].n_i++;
8711 172 found = 1;
8712 172 break;
8713 }
8714 }
8715 309 ▶ if (found) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (found) continue; 172 137 309
8716 137 ▶ if (nbr == cap) {
Branch: 1 branch
BranchTrueFalseTotal
if (nbr == cap) { 23 114 137
8717 23 ▶ cap = cap ? cap * 2 : 32;
Branch: 1 branch
BranchTrueFalseTotal
cap = cap ? cap * 2 : 32; 0 23 23
8718 23 ▶ Renew(br, cap, dssp_bridge);
Branch: 1 branch
BranchTrueFalseTotal
Renew(br, cap, dssp_bridge); 0 23 23
8719 }
8720 137 br[nbr].type = type;
8721 137 br[nbr].chain_i = seg[i];
8722 137 br[nbr].i_first = br[nbr].i_last = i;
8723 137 br[nbr].j_first = br[nbr].j_last = j;
8724 137 br[nbr].n_i = 1;
8725 137 br[nbr].seq = nbr;
8726 137 nbr++;
8727 }
8728 579 Safefree(cand);
8729 //join the ladders a beta bulge separates
8730 579 ▶ if (nbr > 1) qsort(br, (size_t)nbr, sizeof(dssp_bridge), dssp_bridge_cmp);
Branch: 1 branch
BranchTrueFalseTotal
if (nbr > 1) qsort(br, (size_t)nbr, sizeof(dssp_bridge), dssp_bridge_cmp); 23 556 579
8731 699 ▶ for (UV x = 0; x < nbr; x++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV x = 0; x < nbr; x++) { 120 579 699
8732 478 ▶ for (UV y = x + 1; y < nbr; y++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV y = x + 1; y < nbr; y++) { 358 120 478
8733 /*IV and not UV: mdtraj's are ints and three of the tests below are
8734 written to be false when the difference comes out negative, which is
8735 the ordinary case for two ladders that do not overlap. Read at
8736 unsigned width a negative difference is an enormous positive one and
8737 every one of those tests flips.*/
8738 358 IV ibi = (IV)br[x].i_first, iei = (IV)br[x].i_last;
8739 358 IV jbi = (IV)br[x].j_first, jei = (IV)br[x].j_last;
8740 358 IV ibj = (IV)br[y].i_first, iej = (IV)br[y].i_last;
8741 358 IV jbj = (IV)br[y].j_first, jej = (IV)br[y].j_last;
8742 bool bulge;
8743 358 ▶ if (br[x].type != br[y].type) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (br[x].type != br[y].type) continue; 102 256 358
8744 256 ▶ if (seg[(UV)(ibi < ibj ? ibi : ibj)] != seg[(UV)(iei > iej ? iei : iej)])
Branch: 3 branches
BranchTrueFalseTotal
if (seg[(UV)(ibi < ibj ? ibi : ibj)] != seg[(UV)(iei > iej ? iei : iej)]) 256 0 256
if (seg[(UV)(ibi < ibj ? ibi : ibj)] != seg[(UV)(iei > iej ? iei : iej)]) 0 256 256
if (seg[(UV)(ibi < ibj ? ibi : ibj)] != seg[(UV)(iei > iej ? iei : iej)]) 0 256 256
8745 0 continue;
8746 256 ▶ if (seg[(UV)(jbi < jbj ? jbi : jbj)] != seg[(UV)(jei > jej ? jei : jej)])
Branch: 3 branches
BranchTrueFalseTotal
if (seg[(UV)(jbi < jbj ? jbi : jbj)] != seg[(UV)(jei > jej ? jei : jej)]) 148 108 256
if (seg[(UV)(jbi < jbj ? jbi : jbj)] != seg[(UV)(jei > jej ? jei : jej)]) 108 148 256
if (seg[(UV)(jbi < jbj ? jbi : jbj)] != seg[(UV)(jei > jej ? jei : jej)]) 0 256 256
8747 0 continue;
8748 256 ▶ if (ibj - iei >= 6 || (iei >= ibj && ibi <= iej)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (ibj - iei >= 6 || (iei >= ibj && ibi <= iej)) continue; 74 182 256
if (ibj - iei >= 6 || (iei >= ibj && ibi <= iej)) continue; 17 57 74
if (ibj - iei >= 6 || (iei >= ibj && ibi <= iej)) continue; 17 0 17
8749 57 ▶ if (br[x].type == BR_PARA)
Branch: 1 branch
BranchTrueFalseTotal
if (br[x].type == BR_PARA) 0 57 57
8750 0 bulge = (jbj > jbi)
8751 0 ▶ && ((jbj - jei < 6 && ibj - iei < 3) || (jbj - jei < 3));
Branch: 4 branches
BranchTrueFalseTotal
&& ((jbj - jei < 6 && ibj - iei < 3) || (jbj - jei < 3)); 0 0 0
&& ((jbj - jei < 6 && ibj - iei < 3) || (jbj - jei < 3)); 0 0 0
&& ((jbj - jei < 6 && ibj - iei < 3) || (jbj - jei < 3)); 0 0 0
&& ((jbj - jei < 6 && ibj - iei < 3) || (jbj - jei < 3)); 0 0 0
8752 else
8753 57 bulge = (jbj < jbi)
8754 57 ▶ && ((jbi - jej < 6 && ibj - iei < 3) || (jbi - jej < 3));
Branch: 4 branches
BranchTrueFalseTotal
&& ((jbi - jej < 6 && ibj - iei < 3) || (jbi - jej < 3)); 57 0 57
&& ((jbi - jej < 6 && ibj - iei < 3) || (jbi - jej < 3)); 34 23 57
&& ((jbi - jej < 6 && ibj - iei < 3) || (jbi - jej < 3)); 17 17 34
&& ((jbi - jej < 6 && ibj - iei < 3) || (jbi - jej < 3)); 0 40 40
8755 57 ▶ if (!bulge) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!bulge) continue; 40 17 57
8756 17 br[x].i_last = (UV)iej;
8757 17 br[x].n_i += br[y].n_i;
8758 17 ▶ if (br[x].type == BR_PARA) br[x].j_last = (UV)jej;
Branch: 1 branch
BranchTrueFalseTotal
if (br[x].type == BR_PARA) br[x].j_last = (UV)jej; 0 17 17
8759 17 else br[x].j_first = (UV)jbj;
8760 34 ▶ for (c = y; c + 1 < nbr; c++) br[c] = br[c + 1];
Branch: 1 branch
BranchTrueFalseTotal
for (c = y; c + 1 < nbr; c++) br[c] = br[c + 1]; 17 17 34
8761 17 nbr--;
8762 17 y--;
8763 }
8764 }
8765  
8766 699 ▶ for (UV x = 0; x < nbr; x++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV x = 0; x < nbr; x++) { 120 579 699
8767 120 ▶ char lt = (br[x].n_i > 1) ? SS_STRAND : SS_BRIDGE;
Branch: 1 branch
BranchTrueFalseTotal
char lt = (br[x].n_i > 1) ? SS_STRAND : SS_BRIDGE; 80 40 120
8768 UV r;
8769 446 ▶ for (r = br[x].i_first; r <= br[x].i_last; r++)
Branch: 1 branch
BranchTrueFalseTotal
for (r = br[x].i_first; r <= br[x].i_last; r++) 326 120 446
8770 326 ▶ if (ss[r] != SS_STRAND) ss[r] = lt;
Branch: 1 branch
BranchTrueFalseTotal
if (ss[r] != SS_STRAND) ss[r] = lt; 229 97 326
8771 429 ▶ for (r = br[x].j_first; r <= br[x].j_last; r++)
Branch: 1 branch
BranchTrueFalseTotal
for (r = br[x].j_first; r <= br[x].j_last; r++) 309 120 429
8772 309 ▶ if (ss[r] != SS_STRAND) ss[r] = lt;
Branch: 1 branch
BranchTrueFalseTotal
if (ss[r] != SS_STRAND) ss[r] = lt; 309 0 309
8773 }
8774 579 Safefree(br);
8775 579 }
8776  
8777 //mdtraj's helix_flag_t, at its own values: what an n-turn makes of a residue
8778 #define HX_NONE 0
8779 #define HX_START 1
8780 #define HX_END 2
8781 #define HX_BOTH 3 //a turn ends here and another begins
8782 #define HX_MID 4
8783 #define HX_BEGINS(f) ((f) == HX_START || (f) == HX_BOTH)
8784  
8785 /*Is the chain bent at i? The angle between the CA of i-2, i and i+2, past 70
8786 degrees. mdtraj's MProtein::CalculateBends(), in its own arithmetic: see the
8787 head of this block for why the width matters and why acos is not acosf.*/
8788 3964 static bool dssp_is_bend(UV n_res, const UV *CSP_RESTRICT seg, const dssp_res *CSP_RESTRICT bb, UV i){
8789 float u[3], v[3], du, dv, prod, cosangle, kappa;
8790 3964 ▶ if (i < 2 || i + 2 >= n_res) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (i < 2 || i + 2 >= n_res) return 0; 3620 344 3964
if (i < 2 || i + 2 >= n_res) return 0; 123 3497 3620
8791 3497 ▶ if (seg[i - 2] != seg[i + 2]) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (seg[i - 2] != seg[i + 2]) return 0; 375 3122 3497
8792 3122 ▶ if (!bb[i - 2].whole || !bb[i].whole || !bb[i + 2].whole) return 0;
Branch: 3 branches
BranchTrueFalseTotal
if (!bb[i - 2].whole || !bb[i].whole || !bb[i + 2].whole) return 0; 3108 14 3122
if (!bb[i - 2].whole || !bb[i].whole || !bb[i + 2].whole) return 0; 3108 0 3108
if (!bb[i - 2].whole || !bb[i].whole || !bb[i + 2].whole) return 0; 17 3091 3108
8793 3091 dssp_sub3(bb[i - 2].ca, bb[i].ca, u);
8794 3091 dssp_sub3(bb[i].ca, bb[i + 2].ca, v);
8795 3091 du = dssp_dot3(u, u);
8796 3091 dv = dssp_dot3(v, v);
8797 3091 prod = du * dv;//rounded to float before the root, as mdtraj's sqrtf() has it
8798 3091 cosangle = dssp_dot3(u, v) / (float)sqrt((double)prod);
8799 3091 ▶ if (cosangle < -1.0f) cosangle = -1.0f;
Branch: 1 branch
BranchTrueFalseTotal
if (cosangle < -1.0f) cosangle = -1.0f; 0 3091 3091
8800 3091 ▶ else if (cosangle > 1.0f) cosangle = 1.0f;
Branch: 1 branch
BranchTrueFalseTotal
else if (cosangle > 1.0f) cosangle = 1.0f; 9 3082 3091
8801 3091 kappa = (float)acos((double)cosangle);
8802 3091 return (double)kappa > DSSP_BEND;
8803 }
8804  
8805 /*The helices, the turns and the bends, onto `ss'.
8806  
8807 mdtraj's MProtein::CalculateAlphaHelices() with inPreferPiHelices set, which is
8808 what the port hardcodes. The order is the answer: the alpha helices go down
8809 first and over whatever the sheets left, then the 3-10 helices only where the
8810 whole run of three is free, then the pi helices only where the whole run of five
8811 is free or alpha helix -- which is what preferring pi helices means, and is why
8812 a pi helix can overwrite an alpha one and a 3-10 helix can never overwrite
8813 anything. Turns and bends come last, over coil alone.*/
8814 579 static void dssp_helices(pTHX_ UV n_res, const UV *CSP_RESTRICT seg, const UV *CSP_RESTRICT acc, const dssp_res *CSP_RESTRICT bb, char *CSP_RESTRICT ss){
8815 579 unsigned char *CSP_RESTRICT hf = NULL;
8816 UV i, j, first;
8817 unsigned short stride, k;
8818 579 Newxz(hf, n_res * 3, unsigned char);
8819 //the n-turns, chain by chain and then stride by stride, as mdtraj walks them
8820 579 first = 0;
8821 1559 ▶ while (first < n_res) {
Branch: 1 branch
BranchTrueFalseTotal
while (first < n_res) { 980 579 1559
8822 980 UV last = first;
8823 12667 ▶ while (last < n_res && seg[last] == seg[first]) last++;
Branch: 2 branches
BranchTrueFalseTotal
while (last < n_res && seg[last] == seg[first]) last++; 12088 579 12667
while (last < n_res && seg[last] == seg[first]) last++; 11687 401 12088
8824 3920 ▶ for (stride = 3; stride <= 5; stride++) {
Branch: 1 branch
BranchTrueFalseTotal
for (stride = 3; stride <= 5; stride++) { 2940 980 3920
8825 2940 unsigned short off = (unsigned short)(stride - 3);
8826 38001 ▶ for (i = first; i < last; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = first; i < last; i++) { 35061 2940 38001
8827 35061 UV t = i + stride;
8828 35061 ▶ if (t >= n_res || !dssp_bonded(n_res, acc, t, i) || seg[t] != seg[i])
Branch: 3 branches
BranchTrueFalseTotal
if (t >= n_res || !dssp_bonded(n_res, acc, t, i) || seg[t] != seg[i]) 29074 5987 35061
if (t >= n_res || !dssp_bonded(n_res, acc, t, i) || seg[t] != seg[i]) 1185 27889 29074
if (t >= n_res || !dssp_bonded(n_res, acc, t, i) || seg[t] != seg[i]) 0 1185 1185
8829 33876 continue;
8830 1185 hf[t * 3 + off] = HX_END;
8831 3940 ▶ for (j = i + 1; j < t; j++)
Branch: 1 branch
BranchTrueFalseTotal
for (j = i + 1; j < t; j++) 2755 1185 3940
8832 2755 ▶ if (hf[j * 3 + off] == HX_NONE) hf[j * 3 + off] = HX_MID;
Branch: 1 branch
BranchTrueFalseTotal
if (hf[j * 3 + off] == HX_NONE) hf[j * 3 + off] = HX_MID; 1679 1076 2755
8833 1185 ▶ hf[i * 3 + off] = (hf[i * 3 + off] == HX_END) ? HX_BOTH : HX_START;
Branch: 1 branch
BranchTrueFalseTotal
hf[i * 3 + off] = (hf[i * 3 + off] == HX_END) ? HX_BOTH : HX_START; 294 891 1185
8834 }
8835 }
8836 980 first = last;
8837 }
8838 9857 ▶ for (i = 1; i + 4 < n_res; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i = 1; i + 4 < n_res; i++) 9278 579 9857
8839 9278 ▶ if (HX_BEGINS(hf[i * 3 + 1]) && HX_BEGINS(hf[(i - 1) * 3 + 1]))
Branch: 4 branches
BranchTrueFalseTotal
if (HX_BEGINS(hf[i * 3 + 1]) && HX_BEGINS(hf[(i - 1) * 3 + 1])) 9072 206 9278
if (HX_BEGINS(hf[i * 3 + 1]) && HX_BEGINS(hf[(i - 1) * 3 + 1])) 136 8936 9072
if (HX_BEGINS(hf[i * 3 + 1]) && HX_BEGINS(hf[(i - 1) * 3 + 1])) 294 48 342
if (HX_BEGINS(hf[i * 3 + 1]) && HX_BEGINS(hf[(i - 1) * 3 + 1])) 64 230 294
8840 560 ▶ for (j = i; j <= i + 3; j++) ss[j] = SS_HELIX;
Branch: 1 branch
BranchTrueFalseTotal
for (j = i; j <= i + 3; j++) ss[j] = SS_HELIX; 448 112 560
8841  
8842 10267 ▶ for (i = 1; i + 3 < n_res; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 1; i + 3 < n_res; i++) { 9688 579 10267
8843 9688 bool empty = 1;
8844 9688 ▶ if (!(HX_BEGINS(hf[i * 3]) && HX_BEGINS(hf[(i - 1) * 3]))) continue;
Branch: 4 branches
BranchTrueFalseTotal
if (!(HX_BEGINS(hf[i * 3]) && HX_BEGINS(hf[(i - 1) * 3]))) continue; 9030 658 9688
if (!(HX_BEGINS(hf[i * 3]) && HX_BEGINS(hf[(i - 1) * 3]))) continue; 158 8872 9030
if (!(HX_BEGINS(hf[i * 3]) && HX_BEGINS(hf[(i - 1) * 3]))) continue; 569 247 816
if (!(HX_BEGINS(hf[i * 3]) && HX_BEGINS(hf[(i - 1) * 3]))) continue; 516 53 569
8845 968 ▶ for (j = i; empty && j <= i + 2; j++)
Branch: 2 branches
BranchTrueFalseTotal
for (j = i; empty && j <= i + 2; j++) 852 116 968
for (j = i; empty && j <= i + 2; j++) 668 184 852
8846 668 ▶ empty = (ss[j] == SS_COIL || ss[j] == SS_G310);
Branch: 2 branches
BranchTrueFalseTotal
empty = (ss[j] == SS_COIL || ss[j] == SS_G310); 222 446 668
empty = (ss[j] == SS_COIL || ss[j] == SS_G310); 106 116 222
8847 300 ▶ if (!empty) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!empty) continue; 116 184 300
8848 736 ▶ for (j = i; j <= i + 2; j++) ss[j] = SS_G310;
Branch: 1 branch
BranchTrueFalseTotal
for (j = i; j <= i + 2; j++) ss[j] = SS_G310; 552 184 736
8849 }
8850 9471 ▶ for (i = 1; i + 5 < n_res; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 1; i + 5 < n_res; i++) { 8892 579 9471
8851 8892 bool empty = 1;
8852 8892 ▶ if (!(HX_BEGINS(hf[i * 3 + 2]) && HX_BEGINS(hf[(i - 1) * 3 + 2]))) continue;
Branch: 4 branches
BranchTrueFalseTotal
if (!(HX_BEGINS(hf[i * 3 + 2]) && HX_BEGINS(hf[(i - 1) * 3 + 2]))) continue; 8874 18 8892
if (!(HX_BEGINS(hf[i * 3 + 2]) && HX_BEGINS(hf[(i - 1) * 3 + 2]))) continue; 0 8874 8874
if (!(HX_BEGINS(hf[i * 3 + 2]) && HX_BEGINS(hf[(i - 1) * 3 + 2]))) continue; 12 6 18
if (!(HX_BEGINS(hf[i * 3 + 2]) && HX_BEGINS(hf[(i - 1) * 3 + 2]))) continue; 12 0 12
8853 36 ▶ for (j = i; empty && j <= i + 4; j++)
Branch: 2 branches
BranchTrueFalseTotal
for (j = i; empty && j <= i + 4; j++) 36 0 36
for (j = i; empty && j <= i + 4; j++) 30 6 36
8854 30 ▶ empty = (ss[j] == SS_COIL || ss[j] == SS_PI || ss[j] == SS_HELIX);
Branch: 3 branches
BranchTrueFalseTotal
empty = (ss[j] == SS_COIL || ss[j] == SS_PI || ss[j] == SS_HELIX); 24 6 30
empty = (ss[j] == SS_COIL || ss[j] == SS_PI || ss[j] == SS_HELIX); 24 0 24
empty = (ss[j] == SS_COIL || ss[j] == SS_PI || ss[j] == SS_HELIX); 24 0 24
8855 6 ▶ if (!empty) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!empty) continue; 0 6 6
8856 36 ▶ for (j = i; j <= i + 4; j++) ss[j] = SS_PI;
Branch: 1 branch
BranchTrueFalseTotal
for (j = i; j <= i + 4; j++) ss[j] = SS_PI; 30 6 36
8857 }
8858 11171 ▶ for (i = 1; i + 1 < n_res; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 1; i + 1 < n_res; i++) { 10592 579 11171
8859 10592 bool turn = 0;
8860 10592 ▶ if (ss[i] != SS_COIL || !bb[i].whole) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (ss[i] != SS_COIL || !bb[i].whole) continue; 9315 1277 10592
if (ss[i] != SS_COIL || !bb[i].whole) continue; 4586 4729 9315
8861 17511 ▶ for (stride = 3; stride <= 5 && !turn; stride++)
Branch: 2 branches
BranchTrueFalseTotal
for (stride = 3; stride <= 5 && !turn; stride++) 13541 3970 17511
for (stride = 3; stride <= 5 && !turn; stride++) 12782 759 13541
8862 50046 ▶ for (k = 1; k < stride && !turn; k++)
Branch: 2 branches
BranchTrueFalseTotal
for (k = 1; k < stride && !turn; k++) 37587 12459 50046
for (k = 1; k < stride && !turn; k++) 37264 323 37587
8863 37264 ▶ turn = (i >= k) && HX_BEGINS(hf[(i - k) * 3 + stride - 3]);
Branch: 3 branches
BranchTrueFalseTotal
turn = (i >= k) && HX_BEGINS(hf[(i - k) * 3 + stride - 3]); 34101 3163 37264
turn = (i >= k) && HX_BEGINS(hf[(i - k) * 3 + stride - 3]); 33606 495 34101
turn = (i >= k) && HX_BEGINS(hf[(i - k) * 3 + stride - 3]); 270 33336 33606
8864 4729 ▶ if (turn) ss[i] = SS_TURN;
Branch: 1 branch
BranchTrueFalseTotal
if (turn) ss[i] = SS_TURN; 765 3964 4729
8865 3964 ▶ else if (dssp_is_bend(n_res, seg, bb, i)) ss[i] = SS_BEND;
Branch: 1 branch
BranchTrueFalseTotal
else if (dssp_is_bend(n_res, seg, bb, i)) ss[i] = SS_BEND; 642 3322 3964
8866 }
8867 579 Safefree(hf);
8868 579 }
8869  
8870 /*dssp_compute() -- the eight-letter assignment, and the roll-up of it.
8871  
8872 `ss' goes onto each residue, with `ss_simple' beside it: mdtraj's three-state
8873 reduction, H for the three helices, E for the two sheet letters and C for
8874 everything else. A residue with no backbone to speak of gets neither key rather
8875 than a letter saying it is coil, because it is not coil, it is not protein.
8876  
8877 What comes back is the same assignment read the other way round: chain id, then
8878 letter, then the positions in that chain's residue_order of the residues that
8879 have it. A chain with no assigned residue is not a key, and neither is a letter
8880 no residue in the chain has. The position is counted off this walk rather than
8881 off residue_order itself, which is the same number for any structure this module
8882 built: set_build() takes the chains in chain_order and each chain's residues in
8883 residue_order, and drops one only if the structure it was handed has a key in
8884 residue_order with no residue behind it.*/
8885 608 static HV *dssp_compute(pTHX_ structset *CSP_RESTRICT s, bool store){
8886 608 HV *out = newHV();
8887 608 ▶ if (s->n_res == 0) return out;
Branch: 1 branch
BranchTrueFalseTotal
if (s->n_res == 0) return out; 29 579 608
8888 579 UV *CSP_RESTRICT seg = NULL;
8889 579 UV *CSP_RESTRICT acc = NULL;
8890 579 float *CSP_RESTRICT en = NULL;
8891 579 char *CSP_RESTRICT ss = NULL;
8892 579 dssp_res *CSP_RESTRICT bb = NULL;
8893  
8894 UV r;
8895 579 ▶ Newx(seg, s->n_res, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(seg, s->n_res, UV); 0 579 579
8896 579 ▶ Newxz(bb, s->n_res, dssp_res);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(bb, s->n_res, dssp_res); 0 579 579
8897 579 ▶ Newx(acc, s->n_res * DSSP_KEEP, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(acc, s->n_res * DSSP_KEEP, UV); 0 579 579
8898 579 ▶ Newx(en, s->n_res * DSSP_KEEP, float);
Branch: 1 branch
BranchTrueFalseTotal
Newx(en, s->n_res * DSSP_KEEP, float); 0 579 579
8899 579 Newx(ss, s->n_res, char);
8900 12266 ▶ for (r = 0; r < s->n_res; r++) ss[r] = SS_COIL;
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) ss[r] = SS_COIL; 11687 579 12266
8901  
8902 579 dssp_segments(aTHX_ s, seg);
8903 579 dssp_read(aTHX_ s, bb, seg);
8904 579 dssp_hbonds(aTHX_ s, bb, acc, en);
8905 //the sheets first and the helices over them, which is mdtraj's order and
8906 //not the priority list's: an alpha helix overwrites an E, a pi helix
8907 //overwrites an alpha helix, and a 3-10 helix overwrites nothing
8908 579 dssp_sheets(aTHX_ s->n_res, seg, acc, bb, ss);
8909 579 dssp_helices(aTHX_ s->n_res, seg, acc, bb, ss);
8910  
8911 1375 ▶ for (UV c = 0; c < s->n_chain; c++) {
Branch: 1 branch
BranchTrueFalseTotal
for (UV c = 0; c < s->n_chain; c++) { 796 579 1375
8912 796 SV *cid = hvf_sv(aTHX_ s->chain_hv[c], "id", 2);
8913 796 HV *per = NULL;
8914 796 ▶ if (!cid) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!cid) continue; 0 796 796
8915 12483 ▶ for (r = s->chain_first[c]; r < s->chain_last[c]; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = s->chain_first[c]; r < s->chain_last[c]; r++) { 11687 796 12483
8916 SV **have;
8917 AV *list;
8918 11687 ▶ if (!bb[r].whole) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!bb[r].whole) continue; 5126 6561 11687
8919 6561 ▶ if (!per) per = newHV();
Branch: 1 branch
BranchTrueFalseTotal
if (!per) per = newHV(); 391 6170 6561
8920 6561 have = hv_fetch(per, &ss[r], 1, 0);
8921 6561 ▶ if (have && *have && SvROK(*have) && SvTYPE(SvRV(*have)) == SVt_PVAV) {
Branch: 4 branches
BranchTrueFalseTotal
if (have && *have && SvROK(*have) && SvTYPE(SvRV(*have)) == SVt_PVAV) { 5783 778 6561
if (have && *have && SvROK(*have) && SvTYPE(SvRV(*have)) == SVt_PVAV) { 5783 0 5783
if (have && *have && SvROK(*have) && SvTYPE(SvRV(*have)) == SVt_PVAV) { 5783 0 5783
if (have && *have && SvROK(*have) && SvTYPE(SvRV(*have)) == SVt_PVAV) { 5783 0 5783
8922 5783 list = (AV *)SvRV(*have);
8923 } else {
8924 778 list = newAV();
8925 778 (void)hv_store(per, &ss[r], 1, newRV_noinc((SV *)list), 0);
8926 }
8927 6561 av_push(list, newSVuv(r - s->chain_first[c]));
8928 }
8929 796 ▶ if (per) (void)hv_store_ent(out, cid, newRV_noinc((SV *)per), 0);
Branch: 1 branch
BranchTrueFalseTotal
if (per) (void)hv_store_ent(out, cid, newRV_noinc((SV *)per), 0); 391 405 796
8930 }
8931  
8932 579 ▶ if (store) {
Branch: 1 branch
BranchTrueFalseTotal
if (store) { 574 5 579
8933 12122 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 11548 574 12122
8934 char simple;
8935 11548 (void)hv_delete(s->res_hv[r], "ss", 2, G_DISCARD);
8936 11548 (void)hv_delete(s->res_hv[r], "ss_simple", 9, G_DISCARD);
8937 11548 ▶ if (!bb[r].whole) continue;//not protein: it has no secondary structure
Branch: 1 branch
BranchTrueFalseTotal
if (!bb[r].whole) continue;//not protein: it has no secondary structure 5126 6422 11548
8938 12110 ▶ simple = (ss[r] == SS_HELIX || ss[r] == SS_G310 || ss[r] == SS_PI) ? 'H'
Branch: 3 branches
BranchTrueFalseTotal
simple = (ss[r] == SS_HELIX || ss[r] == SS_G310 || ss[r] == SS_PI) ? 'H' 6150 272 6422
simple = (ss[r] == SS_HELIX || ss[r] == SS_G310 || ss[r] == SS_PI) ? 'H' 5718 432 6150
simple = (ss[r] == SS_HELIX || ss[r] == SS_G310 || ss[r] == SS_PI) ? 'H' 5688 30 5718
8939 5688 ▶ : (ss[r] == SS_STRAND || ss[r] == SS_BRIDGE) ? 'E' : 'C';
Branch: 2 branches
BranchTrueFalseTotal
: (ss[r] == SS_STRAND || ss[r] == SS_BRIDGE) ? 'E' : 'C'; 5224 464 5688
: (ss[r] == SS_STRAND || ss[r] == SS_BRIDGE) ? 'E' : 'C'; 57 5167 5224
8940 6422 (void)hv_stores(s->res_hv[r], "ss", newSVpvn(&ss[r], 1));
8941 6422 (void)hv_stores(s->res_hv[r], "ss_simple", newSVpvn(&simple, 1));
8942 }
8943 }
8944 579 Safefree(seg); Safefree(bb); Safefree(acc); Safefree(en); Safefree(ss);
8945 579 return out;
8946 }
8947  
8948 /*The interface between two partners.
8949  
8950 Everything above answers a question about the structure as a whole or about
8951 each chain on its own. A binding affinity is a question about two things --
8952 a receptor and the peptide or ligand it holds -- and the numbers that predict
8953 one are measured between them: which residues touch across the gap, what
8954 surface the two bury, which charged groups meet. The two partners are sets of
8955 residues, chosen in Perl (structure_features()'s partners option, or the split
8956 it makes by itself), and handed down as two lists of residue hashes. Nothing
8957 else in the structure is part of either: waters, ions and ligands that belong
8958 to neither are left out of the complex, as PRODIGY leaves them out, and the
8959 waters come back in only to be asked whether they bridge the two.
8960  
8961 Where each definition comes from, which is also what it is checked against:
8962  
8963 contacts two residues, one in each partner, with heavy atoms closer
8964 than contact_distance. PRODIGY's calculate_ic() in
8965 prodigy-prot 2.4.0 (Vangone, A and Bonvin, A M J J (2015)
8966 eLife 4:e07454), whose d_cutoff of 5.5 A is the default.
8967 salt_bridges a LYS NZ or ARG NE/NH1/NH2 and an ASP OD1/OD2 or GLU
8968 OE1/OE2, one in each partner, closer than 4.0 A: Barlow, D J
8969 and Thornton, J M (1983) J Mol Biol 168(4):867-85, and the
8970 SB_STRICT_CUTOFF_NM of ~/ui/pepPriML/py/features.pdb.20260806.py,
8971 which counts them the same way, once per residue pair.
8972 polar_contacts an N, O or S atom in each partner closer than 3.5 A: the
8973 crystallographic hydrogen-bond criterion, which needs no
8974 hydrogens and so cannot check an angle -- that script's
8975 _geometric_hbonds(), atom pair by atom pair.
8976 cation_pi a LYS NZ or ARG CZ within 6.0 A of the centroid of a PHE,
8977 TYR or TRP ring in the other partner: the distance filter of
8978 Gallivan, J P and Dougherty, D A (1999) PNAS 96(17):9459-64,
8979 without the energy they then computed for each candidate.
8980 That script counts histidine as both a cation and a ring;
8981 Gallivan and Dougherty count it as neither, and so does this.
8982 bridging_waters a water with a heavy atom within 3.5 A of a heavy atom of
8983 each partner: that script's WATER_CONTACT_NM and
8984 n_bridging_waters.
8985 pocket the first partner's atoms, hydrogens included, within 6.0 A
8986 of any atom of the second, and the first partner's heavy
8987 atoms within 8.0 A of a heavy atom of the second per heavy
8988 atom of the second: that script's pocket_block(), with its
8989 POCKET_CUTOFF_NM and the 0.8 nm of pocket_packing_density.
8990  
8991 The surfaces are the kernel's, run on the two partners alone. Most of that run
8992 is already done: an atom's surface depends only on which atoms are its
8993 neighbours, so an atom of either partner whose neighbours are all in the two
8994 partners has, in the complex, the surface the whole structure gave it -- the
8995 same NV, bit for bit, because the kernel's answer is a count of open points
8996 and the neighbours' order does not enter into it (see sasa_kernel()). Only the
8997 atoms touching something outside the partners are computed again, and only the
8998 atoms touching the other partner are computed a third time with that partner
8999 taken away. Without the whole-structure surface to start from -- sasa => 0 --
9000 the complex is computed whole.*/
9001 typedef struct {
9002 NV contact;//residue contacts, angstrom
9003 NV salt;//salt bridges
9004 NV polar;//N/O/S pairs
9005 NV cation_pi;//cation to ring centroid
9006 NV water;//a bridging water to each partner
9007 NV pocket;//an atom of the first partner to any atom of the second
9008 NV packing;//a heavy atom of the first to a heavy atom of the second
9009 bool want_pocket;
9010 } iface_opt;
9011  
9012 //what an atom of either partner is, for the search across the interface
9013 #define IA_HEAVY 0x01 //not hydrogen or deuterium
9014 #define IA_POLAR 0x02 //N, O or S
9015 #define IA_CATION 0x04 //LYS NZ; ARG NE, NH1, NH2
9016 #define IA_ANION 0x08 //ASP OD1, OD2; GLU OE1, OE2
9017 #define IA_BACKBONE 0x10 //N, CA, C, O, OXT
9018 #define IA_IFACE 0x20 //within contact distance of the other partner
9019  
9020 typedef struct {//a residue hash's address, and where set_build() put it
9021 UV addr, res;
9022 } res_addr;
9023  
9024 37447 static int res_addr_cmp(const void *pa, const void *pb){
9025 37447 const res_addr *a = (const res_addr *)pa, *b = (const res_addr *)pb;
9026 37447 ▶ return a->addr < b->addr ? -1 : a->addr > b->addr ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
return a->addr < b->addr ? -1 : a->addr > b->addr ? 1 : 0; 9358 28089 37447
9027 }
9028  
9029 //which residue of s a hash is, or s->n_res when it is none of them
9030 13044 static UV res_addr_find(const res_addr *CSP_RESTRICT tab, UV n, UV addr, UV none){
9031 13044 UV lo = 0, hi = n;
9032 66629 ▶ while (lo < hi) {
Branch: 1 branch
BranchTrueFalseTotal
while (lo < hi) { 66628 1 66629
9033 66628 UV mid = lo + (hi - lo) / 2;
9034 66628 ▶ if (tab[mid].addr < addr) lo = mid + 1;
Branch: 1 branch
BranchTrueFalseTotal
if (tab[mid].addr < addr) lo = mid + 1; 20651 45977 66628
9035 45977 ▶ else if (tab[mid].addr > addr) hi = mid;
Branch: 1 branch
BranchTrueFalseTotal
else if (tab[mid].addr > addr) hi = mid; 32934 13043 45977
9036 13043 else return tab[mid].res;
9037 }
9038 1 return none;
9039 }
9040  
9041 /*The points of a grid within cut of (px, py, pz), into *buf, which grows.
9042 The grid's cells are at least cut wide, so the 27 around the point hold every
9043 one of them.*/
9044 70993 static UV grid_within(pTHX_ const cell_grid *CSP_RESTRICT g, const NV *CSP_RESTRICT x, const NV *CSP_RESTRICT y, const NV *CSP_RESTRICT z, NV px, NV py, NV pz, NV cut, UV **CSP_RESTRICT buf, UV *CSP_RESTRICT cap){
9045 70993 ▶ if (g->start == NULL) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (g->start == NULL) return 0; 0 70993 70993
9046 70993 UV n = 0, ci, cj, ck, bx, by, bz;
9047 70993 ci = grid_axis(px - g->x0, g->cell, g->nx);
9048 70993 cj = grid_axis(py - g->y0, g->cell, g->ny);
9049 70993 ck = grid_axis(pz - g->z0, g->cell, g->nz);
9050 246668 ▶ for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g->nx ? ci + 1 : g->nx - 1); bx++)
Branch: 3 branches
BranchTrueFalseTotal
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g->nx ? ci + 1 : g->nx - 1); bx++) 38209 32784 70993
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g->nx ? ci + 1 : g->nx - 1); bx++) 234313 12355 246668
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g->nx ? ci + 1 : g->nx - 1); bx++) 175675 70993 246668
9051 633149 ▶ for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g->ny ? cj + 1 : g->ny - 1); by++)
Branch: 3 branches
BranchTrueFalseTotal
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g->ny ? cj + 1 : g->ny - 1); by++) 134969 40706 175675
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g->ny ? cj + 1 : g->ny - 1); by++) 560869 72280 633149
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g->ny ? cj + 1 : g->ny - 1); by++) 457474 175675 633149
9052 1675936 ▶ for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g->nz ? ck + 1 : g->nz - 1); bz++) {
Branch: 3 branches
BranchTrueFalseTotal
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g->nz ? ck + 1 : g->nz - 1); bz++) { 373438 84036 457474
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g->nz ? ck + 1 : g->nz - 1); bz++) { 1480403 195533 1675936
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g->nz ? ck + 1 : g->nz - 1); bz++) { 1218462 457474 1675936
9053 1218462 UV cell = (bx * g->ny + by) * g->nz + bz, p;
9054 9153955 ▶ for (p = g->start[cell]; p < g->start[cell + 1]; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = g->start[cell]; p < g->start[cell + 1]; p++) { 7935493 1218462 9153955
9055 7935493 UV j = g->idx[p];
9056 7935493 NV dx = x[j] - px, dy = y[j] - py, dz = z[j] - pz;
9057 /*written as the test a neighbour passes, not the one it fails: a
9058 distance to a NaN coordinate compares false either way, and `>='
9059 let it through, so an atom that read as nan was every atom's
9060 neighbour -- a contact with each residue near the end cell it was
9061 put in, at a distance of NaN*/
9062 7935493 ▶ if (!(dx * dx + dy * dy + dz * dz < cut * cut)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(dx * dx + dy * dy + dz * dz < cut * cut)) continue; 6148160 1787333 7935493
9063 1787333 ▶ if (n == *cap) { *cap = *cap ? *cap * 2 : 64; Renew(*buf, *cap, UV); }
Branch: 3 branches
BranchTrueFalseTotal
if (n == *cap) { *cap = *cap ? *cap * 2 : 64; Renew(*buf, *cap, UV); } 263 1787070 1787333
if (n == *cap) { *cap = *cap ? *cap * 2 : 64; Renew(*buf, *cap, UV); } 37 226 263
if (n == *cap) { *cap = *cap ? *cap * 2 : 64; Renew(*buf, *cap, UV); } 0 263 263
9064 1787333 (*buf)[n++] = j;
9065 }
9066 }
9067 70993 return n;
9068 }
9069  
9070 /*Whether any point of a grid is within cut of (px, py, pz): grid_within()
9071 stopped at the first, for a question that only wants to know there is one.*/
9072 52227 static bool grid_any(const cell_grid *CSP_RESTRICT g, const NV *CSP_RESTRICT x, const NV *CSP_RESTRICT y, const NV *CSP_RESTRICT z, NV px, NV py, NV pz, NV cut){
9073 52227 ▶ if (g->start == NULL) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (g->start == NULL) return 0; 0 52227 52227
9074 UV ci, cj, ck, bx, by, bz;
9075 52227 ci = grid_axis(px - g->x0, g->cell, g->nx);
9076 52227 cj = grid_axis(py - g->y0, g->cell, g->ny);
9077 52227 ck = grid_axis(pz - g->z0, g->cell, g->nz);
9078 134046 ▶ for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g->nx ? ci + 1 : g->nx - 1); bx++)
Branch: 3 branches
BranchTrueFalseTotal
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g->nx ? ci + 1 : g->nx - 1); bx++) 3965 48262 52227
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g->nx ? ci + 1 : g->nx - 1); bx++) 124464 9582 134046
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g->nx ? ci + 1 : g->nx - 1); bx++) 92995 41051 134046
9079 258932 ▶ for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g->ny ? cj + 1 : g->ny - 1); by++)
Branch: 3 branches
BranchTrueFalseTotal
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g->ny ? cj + 1 : g->ny - 1); by++) 51423 41572 92995
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g->ny ? cj + 1 : g->ny - 1); by++) 145140 113792 258932
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g->ny ? cj + 1 : g->ny - 1); by++) 177113 81819 258932
9080 537372 ▶ for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g->nz ? ck + 1 : g->nz - 1); bz++) {
Branch: 3 branches
BranchTrueFalseTotal
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g->nz ? ck + 1 : g->nz - 1); bz++) { 123570 53543 177113
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g->nz ? ck + 1 : g->nz - 1); bz++) { 286242 251130 537372
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g->nz ? ck + 1 : g->nz - 1); bz++) { 371435 165937 537372
9081 371435 UV cell = (bx * g->ny + by) * g->nz + bz, p;
9082 1871530 ▶ for (p = g->start[cell]; p < g->start[cell + 1]; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = g->start[cell]; p < g->start[cell + 1]; p++) { 1511271 360259 1871530
9083 1511271 UV j = g->idx[p];
9084 1511271 NV dx = x[j] - px, dy = y[j] - py, dz = z[j] - pz;
9085 1511271 ▶ if (dx * dx + dy * dy + dz * dz < cut * cut) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (dx * dx + dy * dy + dz * dz < cut * cut) return 1; 11176 1500095 1511271
9086 }
9087 }
9088 41051 return 0;
9089 }
9090  
9091 //an atom's name and element, as the classification below wants them
9092 37047 static unsigned char iface_class(pTHX_ HV *CSP_RESTRICT a, char one, unsigned char rtype){
9093 37047 unsigned char f = 0;
9094 37047 SV *e = hvf_sv(aTHX_ a, "element", 7);
9095 37047 SV *nm = hvf_sv(aTHX_ a, "name", 4);
9096 37047 STRLEN en = 0, nn = 0;
9097 74094 ▶ const char *ep = e ? SvPV_const(e, en) : "";
Branch: 1 branch
BranchTrueFalseTotal
const char *ep = e ? SvPV_const(e, en) : ""; 37047 0 37047
9098 74094 ▶ const char *np = nm ? SvPV_const(nm, nn) : "";
Branch: 1 branch
BranchTrueFalseTotal
const char *np = nm ? SvPV_const(nm, nn) : ""; 37047 0 37047
9099 37047 ▶ if (!(en == 1 && (*ep == 'H' || *ep == 'D'))) f |= IA_HEAVY;
Branch: 3 branches
BranchTrueFalseTotal
if (!(en == 1 && (*ep == 'H' || *ep == 'D'))) f |= IA_HEAVY; 36905 142 37047
if (!(en == 1 && (*ep == 'H' || *ep == 'D'))) f |= IA_HEAVY; 32905 4000 36905
if (!(en == 1 && (*ep == 'H' || *ep == 'D'))) f |= IA_HEAVY; 32905 0 32905
9100 37047 ▶ if (en == 1 && (*ep == 'N' || *ep == 'O' || *ep == 'S')) f |= IA_POLAR;
Branch: 4 branches
BranchTrueFalseTotal
if (en == 1 && (*ep == 'N' || *ep == 'O' || *ep == 'S')) f |= IA_POLAR; 36905 142 37047
if (en == 1 && (*ep == 'N' || *ep == 'O' || *ep == 'S')) f |= IA_POLAR; 31326 5579 36905
if (en == 1 && (*ep == 'N' || *ep == 'O' || *ep == 'S')) f |= IA_POLAR; 24438 6888 31326
if (en == 1 && (*ep == 'N' || *ep == 'O' || *ep == 'S')) f |= IA_POLAR; 332 24106 24438
9101 37047 ▶ if (rtype != RT_AA) return f;
Branch: 1 branch
BranchTrueFalseTotal
if (rtype != RT_AA) return f; 5878 31169 37047
9102 31169 ▶ if ((nn == 1 && (*np == 'N' || *np == 'C' || *np == 'O'))
Branch: 4 branches
BranchTrueFalseTotal
if ((nn == 1 && (*np == 'N' || *np == 'C' || *np == 'O')) 13328 17841 31169
if ((nn == 1 && (*np == 'N' || *np == 'C' || *np == 'O')) 9493 3835 13328
if ((nn == 1 && (*np == 'N' || *np == 'C' || *np == 'O')) 5661 3832 9493
if ((nn == 1 && (*np == 'N' || *np == 'C' || *np == 'O')) 1900 3761 5661
9103 19741 ▶ || (nn == 2 && np[0] == 'C' && np[1] == 'A')
Branch: 3 branches
BranchTrueFalseTotal
|| (nn == 2 && np[0] == 'C' && np[1] == 'A') 12051 7690 19741
|| (nn == 2 && np[0] == 'C' && np[1] == 'A') 10637 1414 12051
|| (nn == 2 && np[0] == 'C' && np[1] == 'A') 6788 3849 10637
9104 15892 ▶ || (nn == 3 && memcmp(np, "OXT", 3) == 0))
Branch: 2 branches
BranchTrueFalseTotal
|| (nn == 3 && memcmp(np, "OXT", 3) == 0)) 4974 10918 15892
|| (nn == 3 && memcmp(np, "OXT", 3) == 0)) 0 4974 4974
9105 15277 f |= IA_BACKBONE;
9106 31169 switch (one) {
9107 3223 case 'K':
9108 3223 ▶ if (nn == 2 && memcmp(np, "NZ", 2) == 0) f |= IA_CATION;
Branch: 2 branches
BranchTrueFalseTotal
if (nn == 2 && memcmp(np, "NZ", 2) == 0) f |= IA_CATION; 1540 1683 3223
if (nn == 2 && memcmp(np, "NZ", 2) == 0) f |= IA_CATION; 256 1284 1540
9109 3223 break;
9110 2400 case 'R':
9111 2400 ▶ if ((nn == 2 && memcmp(np, "NE", 2) == 0)
Branch: 2 branches
BranchTrueFalseTotal
if ((nn == 2 && memcmp(np, "NE", 2) == 0) 1000 1400 2400
if ((nn == 2 && memcmp(np, "NE", 2) == 0) 856 144 1000
9112 2256 ▶ || (nn == 3 && (memcmp(np, "NH1", 3) == 0 || memcmp(np, "NH2", 3) == 0)))
Branch: 3 branches
BranchTrueFalseTotal
|| (nn == 3 && (memcmp(np, "NH1", 3) == 0 || memcmp(np, "NH2", 3) == 0))) 288 1968 2256
|| (nn == 3 && (memcmp(np, "NH1", 3) == 0 || memcmp(np, "NH2", 3) == 0))) 144 144 288
|| (nn == 3 && (memcmp(np, "NH1", 3) == 0 || memcmp(np, "NH2", 3) == 0))) 144 0 144
9113 432 f |= IA_CATION;
9114 2400 break;
9115 1996 case 'D':
9116 1996 ▶ if (nn == 3 && (memcmp(np, "OD1", 3) == 0 || memcmp(np, "OD2", 3) == 0))
Branch: 3 branches
BranchTrueFalseTotal
if (nn == 3 && (memcmp(np, "OD1", 3) == 0 || memcmp(np, "OD2", 3) == 0)) 448 1548 1996
if (nn == 3 && (memcmp(np, "OD1", 3) == 0 || memcmp(np, "OD2", 3) == 0)) 224 224 448
if (nn == 3 && (memcmp(np, "OD1", 3) == 0 || memcmp(np, "OD2", 3) == 0)) 224 0 224
9117 448 f |= IA_ANION;
9118 1996 break;
9119 2796 case 'E':
9120 2796 ▶ if (nn == 3 && (memcmp(np, "OE1", 3) == 0 || memcmp(np, "OE2", 3) == 0))
Branch: 3 branches
BranchTrueFalseTotal
if (nn == 3 && (memcmp(np, "OE1", 3) == 0 || memcmp(np, "OE2", 3) == 0)) 560 2236 2796
if (nn == 3 && (memcmp(np, "OE1", 3) == 0 || memcmp(np, "OE2", 3) == 0)) 280 280 560
if (nn == 3 && (memcmp(np, "OE1", 3) == 0 || memcmp(np, "OE2", 3) == 0)) 280 0 280
9121 560 f |= IA_ANION;
9122 2796 break;
9123 20754 default:
9124 20754 break;
9125 }
9126 31169 return f;
9127 }
9128  
9129 //the name of atom i, for the atom-level lists
9130 1572 static SV *iface_name(pTHX_ HV *CSP_RESTRICT a)
9131 {
9132 1572 SV *nm = hvf_sv(aTHX_ a, "name", 4);
9133 1572 ▶ return nm ? newSVsv(nm) : newSVpvn("", 0);
Branch: 1 branch
BranchTrueFalseTotal
return nm ? newSVsv(nm) : newSVpvn("", 0); 1572 0 1572
9134 }
9135  
9136 /*the residue of s an atom of s is in. The atoms are in residue order and each
9137 residue is the range [res_first, res_last), so it is a binary search over the
9138 ends.*/
9139 24197 static UV res_of_atom(const structset *CSP_RESTRICT s, UV a)
9140 {
9141 24197 UV lo = 0, hi = s->n_res;
9142 172747 ▶ while (lo < hi) {
Branch: 1 branch
BranchTrueFalseTotal
while (lo < hi) { 148550 24197 172747
9143 148550 UV mid = lo + (hi - lo) / 2;
9144 148550 ▶ if (s->res_last[mid] <= a) lo = mid + 1; else hi = mid;
Branch: 1 branch
BranchTrueFalseTotal
if (s->res_last[mid] <= a) lo = mid + 1; else hi = mid; 81959 66591 148550
9145 }
9146 24197 return lo;
9147 }
9148  
9149 //a residue pair, with both residues' chain, key and name
9150 2117 static HV *iface_pair(pTHX_ HV *CSP_RESTRICT r1, HV *CSP_RESTRICT r2, NV d)
9151 {
9152 2117 HV *h = newHV();
9153 2117 pi_field(aTHX_ h, "chain1", 6, r1, "chain", 5);
9154 2117 pi_field(aTHX_ h, "residue1", 8, r1, "key", 3);
9155 2117 pi_field(aTHX_ h, "resname1", 8, r1, "resname", 7);
9156 2117 pi_field(aTHX_ h, "chain2", 6, r2, "chain", 5);
9157 2117 pi_field(aTHX_ h, "residue2", 8, r2, "key", 3);
9158 2117 pi_field(aTHX_ h, "resname2", 8, r2, "resname", 7);
9159 2117 (void)hv_stores(h, "distance", newSVnv(d));
9160 2117 return h;
9161 }
9162  
9163 //one side-1 residue's running list of what it meets in side 2
9164 typedef struct {
9165 UV res;//the side-2 residue
9166 NV d;//closest approach
9167 UV a1, a2;//the atoms that make it, for the salt bridges
9168 } iface_touch;
9169  
9170 20832 static void touch_note(pTHX_ iface_touch **CSP_RESTRICT list, UV *CSP_RESTRICT n,
9171 UV *CSP_RESTRICT cap, UV res, NV d, UV a1, UV a2)
9172 {
9173 UV k;
9174 36975 ▶ for (k = 0; k < *n; k++) if ((*list)[k].res == res) break;
Branch: 2 branches
BranchTrueFalseTotal
for (k = 0; k < *n; k++) if ((*list)[k].res == res) break; 19402 16143 35545
for (k = 0; k < *n; k++) if ((*list)[k].res == res) break; 35545 1430 36975
9175 20832 ▶ if (k < *n) {
Branch: 1 branch
BranchTrueFalseTotal
if (k < *n) { 19402 1430 20832
9176 19402 ▶ if (d < (*list)[k].d) { (*list)[k].d = d; (*list)[k].a1 = a1; (*list)[k].a2 = a2; }
Branch: 1 branch
BranchTrueFalseTotal
if (d < (*list)[k].d) { (*list)[k].d = d; (*list)[k].a1 = a1; (*list)[k].a2 = a2; } 4187 15215 19402
9177 19402 return;
9178 }
9179 1430 ▶ if (*n == *cap) { *cap = *cap ? *cap * 2 : 16; Renew(*list, *cap, iface_touch); }
Branch: 3 branches
BranchTrueFalseTotal
if (*n == *cap) { *cap = *cap ? *cap * 2 : 16; Renew(*list, *cap, iface_touch); } 111 1319 1430
if (*n == *cap) { *cap = *cap ? *cap * 2 : 16; Renew(*list, *cap, iface_touch); } 0 111 111
if (*n == *cap) { *cap = *cap ? *cap * 2 : 16; Renew(*list, *cap, iface_touch); } 0 111 111
9180 1430 (*list)[*n].res = res; (*list)[*n].d = d; (*list)[*n].a1 = a1; (*list)[*n].a2 = a2;
9181 1430 (*n)++;
9182 }
9183  
9184 //the NV of an array of two, or undef for a side that has no such number
9185 452 static SV *pair_av(pTHX_ const NV *CSP_RESTRICT v, const bool *CSP_RESTRICT have)
9186 {
9187 452 AV *av = newAV();
9188 unsigned short k;
9189 1356 ▶ for (k = 0; k < 2; k++) av_push(av, have[k] ? newSVnv(v[k]) : newSV(0));
Branch: 2 branches
BranchTrueFalseTotal
for (k = 0; k < 2; k++) av_push(av, have[k] ? newSVnv(v[k]) : newSV(0)); 604 300 904
for (k = 0; k < 2; k++) av_push(av, have[k] ? newSVnv(v[k]) : newSV(0)); 904 452 1356
9190 452 return newRV_noinc((SV *)av);
9191 }
9192  
9193 /*Everything the two partners' working arrays hold, so that one destructor can
9194 free them on the croak path as well as the ordinary one.*/
9195 typedef struct {
9196 res_addr *tab;
9197 unsigned char *side_res;//per residue of s: 0 = neither partner, 1 or 2
9198 unsigned char *side_at;//the same, per atom of s
9199 unsigned char *cls;//IA_* per atom of s, for the partners' atoms
9200 UV *map;//sub atom -> atom of s
9201 UV *sub_first;//per residue of s: its first atom in the sub arrays
9202 NV *sx, *sy, *sz, *srad, *carea, *aarea, *pts;
9203 unsigned char *ex, *other;
9204 NV *h1x, *h1y, *h1z, *h2x, *h2y, *h2z;
9205 UV *h1, *h2;//heavy atoms of each partner, as atoms of s
9206 UV *buf;
9207 iface_touch *ct, *sb;
9208 sasa_bins bins;
9209 cell_grid g_all, g1, g2;
9210 cell_grid g_pk, g_pack;//the second partner's atoms, and its heavy atoms
9211 UV *pk_n;//per residue of s: its atoms in the pocket
9212 NV *pk_a;//... and their surface in the first partner alone
9213 NV *pk_h;//the residue's heavy atoms' surface in it alone
9214 bool have_bins;
9215 } iface_work;
9216  
9217 229 static void iface_work_free(pTHX_ iface_work *CSP_RESTRICT w){
9218 229 Safefree(w->tab); Safefree(w->side_res); Safefree(w->side_at); Safefree(w->cls);
9219 229 Safefree(w->map); Safefree(w->sub_first);
9220 229 Safefree(w->sx); Safefree(w->sy); Safefree(w->sz); Safefree(w->srad);
9221 229 Safefree(w->carea); Safefree(w->aarea); Safefree(w->ex); Safefree(w->other);
9222 229 Safefree(w->h1x); Safefree(w->h1y); Safefree(w->h1z);
9223 229 Safefree(w->h2x); Safefree(w->h2y); Safefree(w->h2z);
9224 229 Safefree(w->h1); Safefree(w->h2); Safefree(w->buf);
9225 229 Safefree(w->ct); Safefree(w->sb); Safefree(w->pts);
9226 229 ▶ if (w->have_bins) sasa_bins_free(aTHX_ &w->bins);
Branch: 1 branch
BranchTrueFalseTotal
if (w->have_bins) sasa_bins_free(aTHX_ &w->bins); 225 4 229
9227 229 grid_free(aTHX_ &w->g_all); grid_free(aTHX_ &w->g1); grid_free(aTHX_ &w->g2);
9228 229 grid_free(aTHX_ &w->g_pk); grid_free(aTHX_ &w->g_pack);
9229 229 Safefree(w->pk_n); Safefree(w->pk_a); Safefree(w->pk_h);
9230 229 Zero(w, 1, iface_work);
9231 229 }
9232  
9233 //as set_free_cb(), for the same reason
9234 229 static void iface_work_free_cb(pTHX_ void *p){
9235 229 iface_work_free(aTHX_ (iface_work *)p);
9236 229 }
9237  
9238 /*iface_compute() -- the interface between two lists of residues of s.
9239  
9240 sides holds the two lists; each element must be a residue hash that set_build()
9241 walked into s, and a residue in both, or in neither list's structure, is an
9242 error the Perl has already ruled out and this only refuses. Returns the hash
9243 the Perl finishes: the per-residue surfaces come back as arrays parallel to the
9244 two lists, and the residue pairs and atom pairs already carry the chain and
9245 residue keys a caller wants; no CSP_RESTRICT on sides, whose two elements are
9246 perl's arrays. want_surface false leaves the surfaces out
9247 altogether -- no neighbour marking, no kernel, and no surface keys in the hash
9248 -- which is what sasa => 0 asks of the whole walk. Nor does it allocate what
9249 only a surface reads: srad, ex, other, carea and aarea per partner atom, res_c
9250 and res_a per residue, and the pocket's pk_a and pk_h all stay NULL, which
9251 iface_work_free() and Safefree() take as nothing to free.*/
9252 229 static HV *iface_compute(pTHX_ structset *CSP_RESTRICT s, AV *sides[2], UV npts, bool want_surface, const iface_opt *CSP_RESTRICT io, const char *CSP_RESTRICT who){
9253 iface_work w;
9254 HV *out;
9255 229 AV *res_sasa[2] = { NULL, NULL }, *res_alone[2] = { NULL, NULL };//built when want_surface
9256 AV *contacts, *polar, *salt, *cpi, *bridge;
9257 229 NV *res_c = NULL, *res_a = NULL;
9258 229 UV n_sub = 0, n1 = 0, n_h1 = 0, n_h2 = 0, i, k, r, buf_cap = 0;
9259 229 UV ct_cap = 0, sb_cap = 0, n_atom_contacts = 0, n_pack = 0;
9260 229 NV reach = io->contact, min_d = 0.0;
9261 229 NV sasa_c = 0.0, alone[2] = { 0.0, 0.0 }, bur_ap = 0.0, bur_po = 0.0;
9262 229 NV bsum[2] = { 0.0, 0.0 }, bisum[2] = { 0.0, 0.0 }, bmean[2], bimean[2];
9263 229 UV bn[2] = { 0, 0 }, bin[2] = { 0, 0 }, n_at[2] = { 0, 0 };
9264 229 NV mass[2] = { 0.0, 0.0 }, com[2][3];
9265 229 bool have_min = 0, have_b[2], have_bi[2];
9266 unsigned short sd;
9267  
9268 229 ▶ if (io->salt > reach) reach = io->salt;
Branch: 1 branch
BranchTrueFalseTotal
if (io->salt > reach) reach = io->salt; 0 229 229
9269 229 ▶ if (io->polar > reach) reach = io->polar;
Branch: 1 branch
BranchTrueFalseTotal
if (io->polar > reach) reach = io->polar; 0 229 229
9270 229 ▶ if (io->water > reach) reach = io->water;
Branch: 1 branch
BranchTrueFalseTotal
if (io->water > reach) reach = io->water; 0 229 229
9271  
9272 229 ENTER;
9273 229 Zero(&w, 1, iface_work);
9274 229 SAVEDESTRUCTOR_X(iface_work_free_cb, &w);
9275  
9276 //which residue of s each hash in the two lists is
9277 229 ▶ Newx(w.tab, s->n_res ? s->n_res : 1, res_addr);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.tab, s->n_res ? s->n_res : 1, res_addr); 229 0 229
Newx(w.tab, s->n_res ? s->n_res : 1, res_addr); 0 229 229
Newx(w.tab, s->n_res ? s->n_res : 1, res_addr); 229 0 229
9278 10038 ▶ for (r = 0; r < s->n_res; r++) { w.tab[r].addr = PTR2UV(s->res_hv[r]); w.tab[r].res = r; }
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { w.tab[r].addr = PTR2UV(s->res_hv[r]); w.tab[r].res = r; } 9809 229 10038
9279 229 qsort(w.tab, s->n_res, sizeof(res_addr), res_addr_cmp);
9280 229 ▶ Newxz(w.side_res, s->n_res ? s->n_res : 1, unsigned char);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(w.side_res, s->n_res ? s->n_res : 1, unsigned char); 229 0 229
9281 229 ▶ Newxz(w.side_at, s->n_atom ? s->n_atom : 1, unsigned char);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(w.side_at, s->n_atom ? s->n_atom : 1, unsigned char); 229 0 229
9282 229 ▶ if (want_surface) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_surface) { 225 4 229
9283 225 ▶ Newxz(res_c, s->n_res ? s->n_res : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newxz(res_c, s->n_res ? s->n_res : 1, NV); 225 0 225
Newxz(res_c, s->n_res ? s->n_res : 1, NV); 0 225 225
Newxz(res_c, s->n_res ? s->n_res : 1, NV); 225 0 225
9284 225 SAVEFREEPV((char *)res_c);
9285 225 ▶ Newxz(res_a, s->n_res ? s->n_res : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newxz(res_a, s->n_res ? s->n_res : 1, NV); 225 0 225
Newxz(res_a, s->n_res ? s->n_res : 1, NV); 0 225 225
Newxz(res_a, s->n_res ? s->n_res : 1, NV); 225 0 225
9286 225 SAVEFREEPV((char *)res_a);
9287 }
9288 684 ▶ for (sd = 0; sd < 2; sd++) {
Branch: 1 branch
BranchTrueFalseTotal
for (sd = 0; sd < 2; sd++) { 458 226 684
9289 458 SSize_t e, ne = av_len(sides[sd]) + 1;
9290 5577 ▶ for (e = 0; e < ne; e++) {
Branch: 1 branch
BranchTrueFalseTotal
for (e = 0; e < ne; e++) { 5122 455 5577
9291 5122 SV **p = av_fetch(sides[sd], e, 0);
9292 5122 ▶ if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVHV)
Branch: 4 branches
BranchTrueFalseTotal
if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVHV) 5122 0 5122
if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVHV) 5122 0 5122
if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVHV) 5121 1 5122
if (!p || !*p || !SvROK(*p) || SvTYPE(SvRV(*p)) != SVt_PVHV) 0 5121 5121
9293 1 croak("%s: partner %u holds something that is not a residue", who,
9294 (unsigned int)sd + 1);
9295 5121 r = res_addr_find(w.tab, s->n_res, PTR2UV(SvRV(*p)), s->n_res);
9296 5121 ▶ if (r == s->n_res)
Branch: 1 branch
BranchTrueFalseTotal
if (r == s->n_res) 1 5120 5121
9297 1 croak("%s: partner %u holds a residue that is not in this structure",
9298 who, (unsigned int)sd + 1);
9299 5120 ▶ if (w.side_res[r] && w.side_res[r] != sd + 1)
Branch: 2 branches
BranchTrueFalseTotal
if (w.side_res[r] && w.side_res[r] != sd + 1) 1 5119 5120
if (w.side_res[r] && w.side_res[r] != sd + 1) 1 0 1
9300 1 croak("%s: a residue is in both partners", who);
9301 5119 w.side_res[r] = (unsigned char)(sd + 1);
9302 }
9303 }
9304  
9305 /*The two partners' atoms, partner 1 first, each in the order of s: so a
9306 residue's atoms are still one run, and each partner is one range for the
9307 kernel.*/
9308 226 ▶ Newx(w.sub_first, s->n_res ? s->n_res : 1, UV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.sub_first, s->n_res ? s->n_res : 1, UV); 226 0 226
Newx(w.sub_first, s->n_res ? s->n_res : 1, UV); 0 226 226
Newx(w.sub_first, s->n_res ? s->n_res : 1, UV); 226 0 226
9309 678 ▶ for (sd = 1; sd <= 2; sd++)
Branch: 1 branch
BranchTrueFalseTotal
for (sd = 1; sd <= 2; sd++) 452 226 678
9310 18960 ▶ for (r = 0; r < s->n_res; r++)
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) 18508 452 18960
9311 18508 ▶ if (w.side_res[r] == sd) n_sub += s->res_last[r] - s->res_first[r];
Branch: 1 branch
BranchTrueFalseTotal
if (w.side_res[r] == sd) n_sub += s->res_last[r] - s->res_first[r]; 4630 13878 18508
9312 226 ▶ Newx(w.map, n_sub ? n_sub : 1, UV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.map, n_sub ? n_sub : 1, UV); 226 0 226
Newx(w.map, n_sub ? n_sub : 1, UV); 0 226 226
Newx(w.map, n_sub ? n_sub : 1, UV); 226 0 226
9313 226 ▶ Newx(w.sx, n_sub ? n_sub : 1, NV); Newx(w.sy, n_sub ? n_sub : 1, NV);
Branch: 6 branches
BranchTrueFalseTotal
Newx(w.sx, n_sub ? n_sub : 1, NV); Newx(w.sy, n_sub ? n_sub : 1, NV); 226 0 226
Newx(w.sx, n_sub ? n_sub : 1, NV); Newx(w.sy, n_sub ? n_sub : 1, NV); 0 226 226
Newx(w.sx, n_sub ? n_sub : 1, NV); Newx(w.sy, n_sub ? n_sub : 1, NV); 226 0 226
Newx(w.sx, n_sub ? n_sub : 1, NV); Newx(w.sy, n_sub ? n_sub : 1, NV); 226 0 226
Newx(w.sx, n_sub ? n_sub : 1, NV); Newx(w.sy, n_sub ? n_sub : 1, NV); 0 226 226
Newx(w.sx, n_sub ? n_sub : 1, NV); Newx(w.sy, n_sub ? n_sub : 1, NV); 226 0 226
9314 226 ▶ Newx(w.sz, n_sub ? n_sub : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.sz, n_sub ? n_sub : 1, NV); 226 0 226
Newx(w.sz, n_sub ? n_sub : 1, NV); 0 226 226
Newx(w.sz, n_sub ? n_sub : 1, NV); 226 0 226
9315 226 ▶ if (want_surface) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_surface) { 225 1 226
9316 225 ▶ Newx(w.srad, n_sub ? n_sub : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.srad, n_sub ? n_sub : 1, NV); 225 0 225
Newx(w.srad, n_sub ? n_sub : 1, NV); 0 225 225
Newx(w.srad, n_sub ? n_sub : 1, NV); 225 0 225
9317 225 ▶ Newxz(w.ex, n_sub ? n_sub : 1, unsigned char);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(w.ex, n_sub ? n_sub : 1, unsigned char); 225 0 225
9318 225 ▶ Newxz(w.other, n_sub ? n_sub : 1, unsigned char);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(w.other, n_sub ? n_sub : 1, unsigned char); 225 0 225
9319 }
9320 226 ▶ Newxz(w.cls, s->n_atom ? s->n_atom : 1, unsigned char);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(w.cls, s->n_atom ? s->n_atom : 1, unsigned char); 226 0 226
9321 226 k = 0;
9322 678 ▶ for (sd = 1; sd <= 2; sd++) {
Branch: 1 branch
BranchTrueFalseTotal
for (sd = 1; sd <= 2; sd++) { 452 226 678
9323 452 ▶ if (sd == 2) n1 = k;
Branch: 1 branch
BranchTrueFalseTotal
if (sd == 2) n1 = k; 226 226 452
9324 18960 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 18508 452 18960
9325 18508 ▶ if (w.side_res[r] != sd) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (w.side_res[r] != sd) continue; 13878 4630 18508
9326 4630 w.sub_first[r] = k;
9327 41677 ▶ for (i = s->res_first[r]; i < s->res_last[r]; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = s->res_first[r]; i < s->res_last[r]; i++) { 37047 4630 41677
9328 37047 w.map[k] = i;
9329 37047 w.sx[k] = s->x[i]; w.sy[k] = s->y[i]; w.sz[k] = s->z[i];
9330 37047 ▶ if (want_surface) w.srad[k] = s->rad[i];
Branch: 1 branch
BranchTrueFalseTotal
if (want_surface) w.srad[k] = s->rad[i]; 36388 659 37047
9331 37047 w.side_at[i] = (unsigned char)sd;
9332 37047 w.cls[i] = iface_class(aTHX_ s->atom_hv[i], s->res_one[r], s->res_type[r]);
9333 37047 k++;
9334 }
9335 }
9336 }
9337 226 n_at[0] = n1;
9338 226 n_at[1] = n_sub - n1;
9339  
9340 /*Which of the partners' atoms have a neighbour outside the complex (ex) and
9341 which have one in the other partner (other), by the kernel's own test: a
9342 neighbour is an atom whose sphere overlaps, d < ri + rj.*/
9343 226 ▶ if (n_sub && want_surface) {
Branch: 2 branches
BranchTrueFalseTotal
if (n_sub && want_surface) { 226 0 226
if (n_sub && want_surface) { 225 1 226
9344 225 NV rmax = 0.0;
9345 const cell_grid *g;
9346 49478 ▶ for (i = 0; i < s->n_atom; i++) if (s->rad[i] > rmax) rmax = s->rad[i];
Branch: 2 branches
BranchTrueFalseTotal
for (i = 0; i < s->n_atom; i++) if (s->rad[i] > rmax) rmax = s->rad[i]; 752 48501 49253
for (i = 0; i < s->n_atom; i++) if (s->rad[i] > rmax) rmax = s->rad[i]; 49253 225 49478
9347 /*The whole-structure surface built this grid already, over these atoms
9348 at this cutoff, and sasa_compute() kept it for here; it is built afresh
9349 only when that surface was not computed.*/
9350 225 ▶ if (s->grid.start && s->grid_cut == 2.0 * rmax) {
Branch: 2 branches
BranchTrueFalseTotal
if (s->grid.start && s->grid_cut == 2.0 * rmax) { 203 22 225
if (s->grid.start && s->grid_cut == 2.0 * rmax) { 203 0 203
9351 203 g = &s->grid;
9352 } else {
9353 22 grid_build(aTHX_ &w.g_all, s->x, s->y, s->z, s->n_atom, 2.0 * rmax);
9354 22 g = &w.g_all;
9355 }
9356 36613 ▶ for (k = 0; k < n_sub; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n_sub; k++) { 36388 225 36613
9357 36388 const UV a = w.map[k];
9358 36388 UV m = grid_within(aTHX_ g, s->x, s->y, s->z, s->x[a], s->y[a], s->z[a],
9359 2.0 * rmax, &w.buf, &buf_cap), q;
9360 1796112 ▶ for (q = 0; q < m; q++) {
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < m; q++) { 1759724 36388 1796112
9361 1759724 const UV j = w.buf[q];
9362 NV dx, dy, dz, sum;
9363 1759724 ▶ if (j == a) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (j == a) continue; 36387 1723337 1759724
9364 1723337 dx = s->x[j] - s->x[a]; dy = s->y[j] - s->y[a]; dz = s->z[j] - s->z[a];
9365 1723337 sum = s->rad[a] + s->rad[j];
9366 1723337 ▶ if (!(dx * dx + dy * dy + dz * dz < sum * sum)) continue;//a NaN is no neighbour
Branch: 1 branch
BranchTrueFalseTotal
if (!(dx * dx + dy * dy + dz * dz < sum * sum)) continue;//a NaN is no neighbour 302430 1420907 1723337
9367 1420907 ▶ if (w.side_at[j] == 0) w.ex[k] = 1;
Branch: 1 branch
BranchTrueFalseTotal
if (w.side_at[j] == 0) w.ex[k] = 1; 226173 1194734 1420907
9368 1194734 ▶ else if (w.side_at[j] != w.side_at[a]) w.other[k] = 1;
Branch: 1 branch
BranchTrueFalseTotal
else if (w.side_at[j] != w.side_at[a]) w.other[k] = 1; 75906 1118828 1194734
9369 }
9370 }
9371 225 grid_free(aTHX_ &w.g_all);
9372 }
9373  
9374 //the complex, then each partner alone
9375 226 ▶ if (want_surface) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_surface) { 225 1 226
9376 225 ▶ Newxz(w.carea, n_sub ? n_sub : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newxz(w.carea, n_sub ? n_sub : 1, NV); 225 0 225
Newxz(w.carea, n_sub ? n_sub : 1, NV); 0 225 225
Newxz(w.carea, n_sub ? n_sub : 1, NV); 225 0 225
9377 225 ▶ Newxz(w.aarea, n_sub ? n_sub : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newxz(w.aarea, n_sub ? n_sub : 1, NV); 225 0 225
Newxz(w.aarea, n_sub ? n_sub : 1, NV); 0 225 225
Newxz(w.aarea, n_sub ? n_sub : 1, NV); 225 0 225
9378 }
9379 226 ▶ if (n_sub && want_surface) {
Branch: 2 branches
BranchTrueFalseTotal
if (n_sub && want_surface) { 226 0 226
if (n_sub && want_surface) { 225 1 226
9380 sasa_aux only;
9381 225 ▶ Newx(w.pts, npts * 3, NV);
Branch: 1 branch
BranchTrueFalseTotal
Newx(w.pts, npts * 3, NV); 0 225 225
9382 225 sasa_sphere(w.pts, npts);
9383 225 sasa_bins_build(aTHX_ &w.bins, w.pts, npts);
9384 225 w.have_bins = TRUE;
9385 225 Zero(&only, 1, sasa_aux);
9386 225 ▶ if (s->area) {
Branch: 1 branch
BranchTrueFalseTotal
if (s->area) { 203 22 225
9387 24602 ▶ for (k = 0; k < n_sub; k++) w.carea[k] = s->area[w.map[k]];
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n_sub; k++) w.carea[k] = s->area[w.map[k]]; 24399 203 24602
9388 203 only.only = w.ex;
9389 203 sasa_kernel(aTHX_ w.sx, w.sy, w.sz, w.srad, n_sub, &w.bins, npts, w.carea, &only, NULL);
9390 } else {
9391 22 sasa_kernel(aTHX_ w.sx, w.sy, w.sz, w.srad, n_sub, &w.bins, npts, w.carea, NULL, NULL);
9392 }
9393 225 ▶ Copy(w.carea, w.aarea, n_sub, NV);
Branch: 1 branch
BranchTrueFalseTotal
Copy(w.carea, w.aarea, n_sub, NV); 0 225 225
9394 225 only.only = w.other;
9395 225 ▶ if (n1)
Branch: 1 branch
BranchTrueFalseTotal
if (n1) 225 0 225
9396 225 sasa_kernel(aTHX_ w.sx, w.sy, w.sz, w.srad, n1, &w.bins, npts, w.aarea, &only, NULL);
9397 225 only.only = w.other + n1;
9398 225 ▶ if (n_sub > n1)
Branch: 1 branch
BranchTrueFalseTotal
if (n_sub > n1) 225 0 225
9399 225 sasa_kernel(aTHX_ w.sx + n1, w.sy + n1, w.sz + n1, w.srad + n1, n_sub - n1,
9400 225 &w.bins, npts, w.aarea + n1, &only, NULL);
9401 }
9402 226 ▶ if (want_surface) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_surface) { 225 1 226
9403 36613 ▶ for (k = 0; k < n_sub; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n_sub; k++) { 36388 225 36613
9404 36388 const UV a = w.map[k];
9405 36388 const NV b = w.aarea[k] - w.carea[k];
9406 36388 sasa_c += w.carea[k];
9407 36388 alone[k < n1 ? 0 : 1] += w.aarea[k];
9408 36388 ▶ if (s->apolar[a]) bur_ap += b; else bur_po += b;
Branch: 1 branch
BranchTrueFalseTotal
if (s->apolar[a]) bur_ap += b; else bur_po += b; 19319 17069 36388
9409 }
9410 9294 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 9069 225 9294
9411 UV f, l;
9412 9069 ▶ if (!w.side_res[r]) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!w.side_res[r]) continue; 4505 4564 9069
9413 4564 f = w.sub_first[r];
9414 4564 l = f + (s->res_last[r] - s->res_first[r]);
9415 40952 ▶ for (k = f; k < l; k++) { res_c[r] += w.carea[k]; res_a[r] += w.aarea[k]; }
Branch: 1 branch
BranchTrueFalseTotal
for (k = f; k < l; k++) { res_c[r] += w.carea[k]; res_a[r] += w.aarea[k]; } 36388 4564 40952
9416 }
9417 }
9418  
9419 //the heavy atoms of each partner, for everything that follows
9420 226 ▶ Newx(w.h1, n_sub ? n_sub : 1, UV); Newx(w.h2, n_sub ? n_sub : 1, UV);
Branch: 6 branches
BranchTrueFalseTotal
Newx(w.h1, n_sub ? n_sub : 1, UV); Newx(w.h2, n_sub ? n_sub : 1, UV); 226 0 226
Newx(w.h1, n_sub ? n_sub : 1, UV); Newx(w.h2, n_sub ? n_sub : 1, UV); 0 226 226
Newx(w.h1, n_sub ? n_sub : 1, UV); Newx(w.h2, n_sub ? n_sub : 1, UV); 226 0 226
Newx(w.h1, n_sub ? n_sub : 1, UV); Newx(w.h2, n_sub ? n_sub : 1, UV); 226 0 226
Newx(w.h1, n_sub ? n_sub : 1, UV); Newx(w.h2, n_sub ? n_sub : 1, UV); 0 226 226
Newx(w.h1, n_sub ? n_sub : 1, UV); Newx(w.h2, n_sub ? n_sub : 1, UV); 226 0 226
9421 37273 ▶ for (k = 0; k < n_sub; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n_sub; k++) { 37047 226 37273
9422 37047 const UV a = w.map[k];
9423 37047 ▶ if (!(w.cls[a] & IA_HEAVY)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(w.cls[a] & IA_HEAVY)) continue; 4000 33047 37047
9424 33047 ▶ if (k < n1) w.h1[n_h1++] = a; else w.h2[n_h2++] = a;
Branch: 1 branch
BranchTrueFalseTotal
if (k < n1) w.h1[n_h1++] = a; else w.h2[n_h2++] = a; 25969 7078 33047
9425 }
9426 226 ▶ Newx(w.h1x, n_h1 ? n_h1 : 1, NV); Newx(w.h1y, n_h1 ? n_h1 : 1, NV);
Branch: 6 branches
BranchTrueFalseTotal
Newx(w.h1x, n_h1 ? n_h1 : 1, NV); Newx(w.h1y, n_h1 ? n_h1 : 1, NV); 226 0 226
Newx(w.h1x, n_h1 ? n_h1 : 1, NV); Newx(w.h1y, n_h1 ? n_h1 : 1, NV); 0 226 226
Newx(w.h1x, n_h1 ? n_h1 : 1, NV); Newx(w.h1y, n_h1 ? n_h1 : 1, NV); 226 0 226
Newx(w.h1x, n_h1 ? n_h1 : 1, NV); Newx(w.h1y, n_h1 ? n_h1 : 1, NV); 226 0 226
Newx(w.h1x, n_h1 ? n_h1 : 1, NV); Newx(w.h1y, n_h1 ? n_h1 : 1, NV); 0 226 226
Newx(w.h1x, n_h1 ? n_h1 : 1, NV); Newx(w.h1y, n_h1 ? n_h1 : 1, NV); 226 0 226
9427 226 ▶ Newx(w.h1z, n_h1 ? n_h1 : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.h1z, n_h1 ? n_h1 : 1, NV); 226 0 226
Newx(w.h1z, n_h1 ? n_h1 : 1, NV); 0 226 226
Newx(w.h1z, n_h1 ? n_h1 : 1, NV); 226 0 226
9428 226 ▶ Newx(w.h2x, n_h2 ? n_h2 : 1, NV); Newx(w.h2y, n_h2 ? n_h2 : 1, NV);
Branch: 6 branches
BranchTrueFalseTotal
Newx(w.h2x, n_h2 ? n_h2 : 1, NV); Newx(w.h2y, n_h2 ? n_h2 : 1, NV); 226 0 226
Newx(w.h2x, n_h2 ? n_h2 : 1, NV); Newx(w.h2y, n_h2 ? n_h2 : 1, NV); 0 226 226
Newx(w.h2x, n_h2 ? n_h2 : 1, NV); Newx(w.h2y, n_h2 ? n_h2 : 1, NV); 226 0 226
Newx(w.h2x, n_h2 ? n_h2 : 1, NV); Newx(w.h2y, n_h2 ? n_h2 : 1, NV); 226 0 226
Newx(w.h2x, n_h2 ? n_h2 : 1, NV); Newx(w.h2y, n_h2 ? n_h2 : 1, NV); 0 226 226
Newx(w.h2x, n_h2 ? n_h2 : 1, NV); Newx(w.h2y, n_h2 ? n_h2 : 1, NV); 226 0 226
9429 226 ▶ Newx(w.h2z, n_h2 ? n_h2 : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.h2z, n_h2 ? n_h2 : 1, NV); 226 0 226
Newx(w.h2z, n_h2 ? n_h2 : 1, NV); 0 226 226
Newx(w.h2z, n_h2 ? n_h2 : 1, NV); 226 0 226
9430 26195 ▶ for (k = 0; k < n_h1; k++) { w.h1x[k] = s->x[w.h1[k]]; w.h1y[k] = s->y[w.h1[k]]; w.h1z[k] = s->z[w.h1[k]]; }
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n_h1; k++) { w.h1x[k] = s->x[w.h1[k]]; w.h1y[k] = s->y[w.h1[k]]; w.h1z[k] = s->z[w.h1[k]]; } 25969 226 26195
9431 7304 ▶ for (k = 0; k < n_h2; k++) { w.h2x[k] = s->x[w.h2[k]]; w.h2y[k] = s->y[w.h2[k]]; w.h2z[k] = s->z[w.h2[k]]; }
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n_h2; k++) { w.h2x[k] = s->x[w.h2[k]]; w.h2y[k] = s->y[w.h2[k]]; w.h2z[k] = s->z[w.h2[k]]; } 7078 226 7304
9432 226 grid_build(aTHX_ &w.g1, w.h1x, w.h1y, w.h1z, n_h1, reach);
9433 226 grid_build(aTHX_ &w.g2, w.h2x, w.h2y, w.h2z, n_h2, reach);
9434  
9435 /*Across the gap: every side-1 heavy atom against the side-2 heavy atoms
9436 within reach, residue by residue so that each side-1 residue's partners
9437 are gathered and written out before the next one starts. Partner 1's heavy
9438 atoms were gathered in the order of s, so a residue's are one run.*/
9439 226 contacts = newAV(); sv_2mortal((SV *)contacts);
9440 226 polar = newAV(); sv_2mortal((SV *)polar);
9441 226 salt = newAV(); sv_2mortal((SV *)salt);
9442 {
9443 226 UV lo = 0;
9444 3756 ▶ while (lo < n_h1) {
Branch: 1 branch
BranchTrueFalseTotal
while (lo < n_h1) { 3530 226 3756
9445 3530 UV hi = lo, n_ct = 0, n_sb = 0, q, res1;
9446 3530 res1 = res_of_atom(s, w.h1[lo]);
9447 29499 ▶ while (hi < n_h1 && w.h1[hi] < s->res_last[res1]) hi++;
Branch: 2 branches
BranchTrueFalseTotal
while (hi < n_h1 && w.h1[hi] < s->res_last[res1]) hi++; 29273 226 29499
while (hi < n_h1 && w.h1[hi] < s->res_last[res1]) hi++; 25969 3304 29273
9448 29499 ▶ for (i = lo; i < hi; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = lo; i < hi; i++) { 25969 3530 29499
9449 25969 const UV a = w.h1[i];
9450 25969 const UV m = grid_within(aTHX_ &w.g2, w.h2x, w.h2y, w.h2z,
9451 25969 s->x[a], s->y[a], s->z[a], reach, &w.buf, &buf_cap);
9452 46636 ▶ for (q = 0; q < m; q++) {
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < m; q++) { 20667 25969 46636
9453 20667 const UV b = w.h2[w.buf[q]];
9454 20667 NV dx = s->x[b] - s->x[a], dy = s->y[b] - s->y[a], dz = s->z[b] - s->z[a];
9455 20667 const NV d2 = dx * dx + dy * dy + dz * dz;
9456 20667 const NV d = nv_sqrt(d2);
9457 UV res2;
9458 20667 ▶ if (!have_min || d < min_d) { min_d = d; have_min = TRUE; }
Branch: 2 branches
BranchTrueFalseTotal
if (!have_min || d < min_d) { min_d = d; have_min = TRUE; } 20589 78 20667
if (!have_min || d < min_d) { min_d = d; have_min = TRUE; } 502 20087 20589
9459 20667 res2 = res_of_atom(s, b);
9460 20667 ▶ if (d2 < io->contact * io->contact) {
Branch: 1 branch
BranchTrueFalseTotal
if (d2 < io->contact * io->contact) { 20667 0 20667
9461 20667 n_atom_contacts++;
9462 20667 w.cls[a] |= IA_IFACE;
9463 20667 w.cls[b] |= IA_IFACE;
9464 20667 touch_note(aTHX_ &w.ct, &n_ct, &ct_cap, res2, d, a, b);
9465 }
9466 20667 ▶ if (d2 < io->polar * io->polar && (w.cls[a] & IA_POLAR) && (w.cls[b] & IA_POLAR)) {
Branch: 3 branches
BranchTrueFalseTotal
if (d2 < io->polar * io->polar && (w.cls[a] & IA_POLAR) && (w.cls[b] & IA_POLAR)) { 1439 19228 20667
if (d2 < io->polar * io->polar && (w.cls[a] & IA_POLAR) && (w.cls[b] & IA_POLAR)) { 997 442 1439
if (d2 < io->polar * io->polar && (w.cls[a] & IA_POLAR) && (w.cls[b] & IA_POLAR)) { 654 343 997
9467 654 HV *h = iface_pair(aTHX_ s->res_hv[res1], s->res_hv[res2], d);
9468 654 (void)hv_stores(h, "atom1", iface_name(aTHX_ s->atom_hv[a]));
9469 654 (void)hv_stores(h, "atom2", iface_name(aTHX_ s->atom_hv[b]));
9470 654 (void)hv_stores(h, "backbone1", newSViv((w.cls[a] & IA_BACKBONE) ? 1 : 0));
9471 654 (void)hv_stores(h, "backbone2", newSViv((w.cls[b] & IA_BACKBONE) ? 1 : 0));
9472 654 av_push(polar, newRV_noinc((SV *)h));
9473 }
9474 20667 ▶ if (d2 < io->salt * io->salt
Branch: 1 branch
BranchTrueFalseTotal
if (d2 < io->salt * io->salt 4935 15732 20667
9475 4935 ▶ && (((w.cls[a] & IA_CATION) && (w.cls[b] & IA_ANION))
Branch: 2 branches
BranchTrueFalseTotal
&& (((w.cls[a] & IA_CATION) && (w.cls[b] & IA_ANION)) 22 4913 4935
&& (((w.cls[a] & IA_CATION) && (w.cls[b] & IA_ANION)) 12 10 22
9476 4925 ▶ || ((w.cls[a] & IA_ANION) && (w.cls[b] & IA_CATION))))
Branch: 2 branches
BranchTrueFalseTotal
|| ((w.cls[a] & IA_ANION) && (w.cls[b] & IA_CATION)))) 527 4398 4925
|| ((w.cls[a] & IA_ANION) && (w.cls[b] & IA_CATION)))) 155 372 527
9477 165 touch_note(aTHX_ &w.sb, &n_sb, &sb_cap, res2, d, a, b);
9478 }
9479 }
9480 4828 ▶ for (q = 0; q < n_ct; q++)
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < n_ct; q++) 1298 3530 4828
9481 1298 av_push(contacts, newRV_noinc((SV *)iface_pair(aTHX_ s->res_hv[res1],
9482 s->res_hv[w.ct[q].res], w.ct[q].d)));
9483 3662 ▶ for (q = 0; q < n_sb; q++) {
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < n_sb; q++) { 132 3530 3662
9484 132 HV *h = iface_pair(aTHX_ s->res_hv[res1], s->res_hv[w.sb[q].res], w.sb[q].d);
9485 132 (void)hv_stores(h, "atom1", iface_name(aTHX_ s->atom_hv[w.sb[q].a1]));
9486 132 (void)hv_stores(h, "atom2", iface_name(aTHX_ s->atom_hv[w.sb[q].a2]));
9487 132 av_push(salt, newRV_noinc((SV *)h));
9488 }
9489 3530 lo = hi;
9490 }
9491 }
9492  
9493 /*Cation-pi: every LYS NZ and ARG CZ against every PHE, TYR and TRP ring
9494 of the other partner. A few dozen of each at an interface, so the pairs
9495 are simply all tried; one entry per cation and ring residue, at the
9496 nearest ring, so a tryptophan's two rings are one aromatic residue.*/
9497 226 cpi = newAV(); sv_2mortal((SV *)cpi);
9498 {
9499 226 const UV nr = rings_get(aTHX_ s);
9500 226 const ring_t *CSP_RESTRICT rings = s->rings;
9501 UV q;
9502 9480 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 9254 226 9480
9503 9254 const char one = s->res_one[r];
9504 NV px, py, pz;
9505 HV *atoms;
9506 UV t;
9507 9256 ▶ if (!w.side_res[r] || s->res_type[r] != RT_AA || (one != 'K' && one != 'R')) continue;
Branch: 4 branches
BranchTrueFalseTotal
if (!w.side_res[r] || s->res_type[r] != RT_AA || (one != 'K' && one != 'R')) continue; 4630 4624 9254
if (!w.side_res[r] || s->res_type[r] != RT_AA || (one != 'K' && one != 'R')) continue; 3849 781 4630
if (!w.side_res[r] || s->res_type[r] != RT_AA || (one != 'K' && one != 'R')) continue; 3591 258 3849
if (!w.side_res[r] || s->res_type[r] != RT_AA || (one != 'K' && one != 'R')) continue; 3447 144 3591
9508 402 atoms = hvf_hv(aTHX_ s->res_hv[r], "atoms", 5);
9509 402 ▶ if (!atoms || !atom_xyz(aTHX_ atoms, one == 'K' ? "NZ" : "CZ", &px, &py, &pz)) continue;
Branch: 3 branches
BranchTrueFalseTotal
if (!atoms || !atom_xyz(aTHX_ atoms, one == 'K' ? "NZ" : "CZ", &px, &py, &pz)) continue; 402 0 402
if (!atoms || !atom_xyz(aTHX_ atoms, one == 'K' ? "NZ" : "CZ", &px, &py, &pz)) continue; 258 144 402
if (!atoms || !atom_xyz(aTHX_ atoms, one == 'K' ? "NZ" : "CZ", &px, &py, &pz)) continue; 2 400 402
9510 /*nearest ring per aromatic residue: rings of one residue are
9511 consecutive in what rings_get() returns, so t is stepped over the
9512 residue's run before it is asked whether the residue is the other
9513 partner's aromatic one, and only that residue's are measured*/
9514 3852 ▶ for (q = 0; q < nr; q = t) {
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < nr; q = t) { 3452 400 3852
9515 3452 const UV rres = rings[q].res;
9516 3452 NV best = -1.0;
9517 3452 const char ro = s->res_one[rres];
9518 UV u;
9519 7816 ▶ for (t = q; t < nr && rings[t].res == rres; t++) ;
Branch: 2 branches
BranchTrueFalseTotal
for (t = q; t < nr && rings[t].res == rres; t++) ; 7416 400 7816
for (t = q; t < nr && rings[t].res == rres; t++) ; 4364 3052 7416
9520 3452 ▶ if (!w.side_res[rres] || w.side_res[rres] == w.side_res[r]) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (!w.side_res[rres] || w.side_res[rres] == w.side_res[r]) continue; 3452 0 3452
if (!w.side_res[rres] || w.side_res[rres] == w.side_res[r]) continue; 2756 696 3452
9521 696 ▶ if (s->res_type[rres] != RT_AA || (ro != 'F' && ro != 'Y' && ro != 'W')) continue;
Branch: 4 branches
BranchTrueFalseTotal
if (s->res_type[rres] != RT_AA || (ro != 'F' && ro != 'Y' && ro != 'W')) continue; 528 168 696
if (s->res_type[rres] != RT_AA || (ro != 'F' && ro != 'Y' && ro != 'W')) continue; 330 198 528
if (s->res_type[rres] != RT_AA || (ro != 'F' && ro != 'Y' && ro != 'W')) continue; 132 198 330
if (s->res_type[rres] != RT_AA || (ro != 'F' && ro != 'Y' && ro != 'W')) continue; 0 132 132
9522 1188 ▶ for (u = q; u < t; u++) {
Branch: 1 branch
BranchTrueFalseTotal
for (u = q; u < t; u++) { 660 528 1188
9523 660 NV dx = rings[u].cx - px, dy = rings[u].cy - py, dz = rings[u].cz - pz;
9524 660 NV d = nv_sqrt(dx * dx + dy * dy + dz * dz);
9525 660 ▶ if (best < 0.0 || d < best) best = d;
Branch: 2 branches
BranchTrueFalseTotal
if (best < 0.0 || d < best) best = d; 132 528 660
if (best < 0.0 || d < best) best = d; 99 33 132
9526 }
9527 528 ▶ if (!(best < io->cation_pi)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(best < io->cation_pi)) continue; 495 33 528
9528 {
9529 33 const bool first = w.side_res[r] == 1;
9530 33 HV *h = iface_pair(aTHX_ s->res_hv[first ? r : rres],
9531 33 ▶ s->res_hv[first ? rres : r], best);
Branch: 2 branches
BranchTrueFalseTotal
s->res_hv[first ? rres : r], best); 2 31 33
s->res_hv[first ? rres : r], best); 2 31 33
9532 33 ▶ (void)hv_stores(h, "cation", newSVuv(first ? 1 : 2));
Branch: 1 branch
BranchTrueFalseTotal
(void)hv_stores(h, "cation", newSVuv(first ? 1 : 2)); 2 31 33
9533 33 av_push(cpi, newRV_noinc((SV *)h));
9534 }
9535 }
9536 }
9537 }
9538  
9539 //waters that reach both partners
9540 226 bridge = newAV(); sv_2mortal((SV *)bridge);
9541 9480 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 9254 226 9480
9542 9254 bool t1 = FALSE, t2 = FALSE;
9543 9254 ▶ if (s->res_type[r] != RT_WATER || w.side_res[r]) continue;
Branch: 2 branches
BranchTrueFalseTotal
if (s->res_type[r] != RT_WATER || w.side_res[r]) continue; 4318 4936 9254
if (s->res_type[r] != RT_WATER || w.side_res[r]) continue; 0 4318 4318
9544 16266 ▶ for (i = s->res_first[r]; i < s->res_last[r] && !(t1 && t2); i++) {
Branch: 3 branches
BranchTrueFalseTotal
for (i = s->res_first[r]; i < s->res_last[r] && !(t1 && t2); i++) { 12179 4087 16266
for (i = s->res_first[r]; i < s->res_last[r] && !(t1 && t2); i++) { 7234 4945 12179
for (i = s->res_first[r]; i < s->res_last[r] && !(t1 && t2); i++) { 4714 231 4945
9545 11948 ▶ if (atom_is_h(aTHX_ s->atom_hv[i])) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (atom_is_h(aTHX_ s->atom_hv[i])) continue; 7630 4318 11948
9546 8636 if (!t1 && grid_within(aTHX_ &w.g1, w.h1x, w.h1y, w.h1z, s->x[i], s->y[i], s->z[i],
9547 6909 io->water, &w.buf, &buf_cap)) t1 = TRUE;
9548 8636 if (!t2 && grid_within(aTHX_ &w.g2, w.h2x, w.h2y, w.h2z, s->x[i], s->y[i], s->z[i],
9549 4915 io->water, &w.buf, &buf_cap)) t2 = TRUE;
9550 }
9551 4318 ▶ if (t1 && t2) {
Branch: 2 branches
BranchTrueFalseTotal
if (t1 && t2) { 2591 1727 4318
if (t1 && t2) { 234 2357 2591
9552 234 HV *h = newHV();
9553 234 pi_field(aTHX_ h, "chain", 5, s->res_hv[r], "chain", 5);
9554 234 pi_field(aTHX_ h, "residue", 7, s->res_hv[r], "key", 3);
9555 234 av_push(bridge, newRV_noinc((SV *)h));
9556 }
9557 }
9558  
9559 /*The pocket: which of the first partner's atoms, hydrogens and all, come
9560 within io->pocket of any atom of the second, tallied per residue with their
9561 surface in the first partner alone; and how many of its heavy atoms come
9562 within io->packing of a heavy atom of the second. The second partner's
9563 atoms are the tail of the sub arrays, one range.*/
9564 226 ▶ if (io->want_pocket) {
Branch: 1 branch
BranchTrueFalseTotal
if (io->want_pocket) { 223 3 226
9565 223 ▶ Newxz(w.pk_n, s->n_res ? s->n_res : 1, UV);
Branch: 3 branches
BranchTrueFalseTotal
Newxz(w.pk_n, s->n_res ? s->n_res : 1, UV); 223 0 223
Newxz(w.pk_n, s->n_res ? s->n_res : 1, UV); 0 223 223
Newxz(w.pk_n, s->n_res ? s->n_res : 1, UV); 223 0 223
9566 223 ▶ if (want_surface) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_surface) { 222 1 223
9567 222 ▶ Newxz(w.pk_a, s->n_res ? s->n_res : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newxz(w.pk_a, s->n_res ? s->n_res : 1, NV); 222 0 222
Newxz(w.pk_a, s->n_res ? s->n_res : 1, NV); 0 222 222
Newxz(w.pk_a, s->n_res ? s->n_res : 1, NV); 222 0 222
9568 222 ▶ Newxz(w.pk_h, s->n_res ? s->n_res : 1, NV);
Branch: 3 branches
BranchTrueFalseTotal
Newxz(w.pk_h, s->n_res ? s->n_res : 1, NV); 222 0 222
Newxz(w.pk_h, s->n_res ? s->n_res : 1, NV); 0 222 222
Newxz(w.pk_h, s->n_res ? s->n_res : 1, NV); 222 0 222
9569 }
9570 223 grid_build(aTHX_ &w.g_pk, w.sx + n1, w.sy + n1, w.sz + n1, n_sub - n1, io->pocket);
9571 8922 ▶ for (r = 0; r < s->n_res; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = 0; r < s->n_res; r++) { 8699 223 8922
9572 UV f, l;
9573 8699 ▶ if (w.side_res[r] != 1) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (w.side_res[r] != 1) continue; 5340 3359 8699
9574 3359 f = w.sub_first[r];
9575 3359 l = f + (s->res_last[r] - s->res_first[r]);
9576 31057 ▶ for (k = f; k < l; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = f; k < l; k++) { 27698 3359 31057
9577 27698 ▶ if (want_surface && (w.cls[w.map[k]] & IA_HEAVY)) w.pk_h[r] += w.aarea[k];
Branch: 2 branches
BranchTrueFalseTotal
if (want_surface && (w.cls[w.map[k]] & IA_HEAVY)) w.pk_h[r] += w.aarea[k]; 27114 584 27698
if (want_surface && (w.cls[w.map[k]] & IA_HEAVY)) w.pk_h[r] += w.aarea[k]; 24049 3065 27114
9578 27698 ▶ if (!grid_any(&w.g_pk, w.sx + n1, w.sy + n1, w.sz + n1,
Branch: 1 branch
BranchTrueFalseTotal
if (!grid_any(&w.g_pk, w.sx + n1, w.sy + n1, w.sz + n1, 23149 4549 27698
9579 50847 w.sx[k], w.sy[k], w.sz[k], io->pocket)) continue;
9580 4549 w.pk_n[r]++;
9581 4549 ▶ if (want_surface) w.pk_a[r] += w.aarea[k];
Branch: 1 branch
BranchTrueFalseTotal
if (want_surface) w.pk_a[r] += w.aarea[k]; 4419 130 4549
9582 }
9583 }
9584 223 grid_free(aTHX_ &w.g_pk);
9585 223 grid_build(aTHX_ &w.g_pack, w.h2x, w.h2y, w.h2z, n_h2, io->packing);
9586 24752 ▶ for (k = 0; k < n_h1; k++)
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n_h1; k++) 24529 223 24752
9587 24529 ▶ if (grid_any(&w.g_pack, w.h2x, w.h2y, w.h2z,
Branch: 1 branch
BranchTrueFalseTotal
if (grid_any(&w.g_pack, w.h2x, w.h2y, w.h2z, 6627 17902 24529
9588 31156 w.h1x[k], w.h1y[k], w.h1z[k], io->packing)) n_pack++;
9589 223 grid_free(aTHX_ &w.g_pack);
9590 }
9591  
9592 //centres of mass, and the B-factors of each partner and of its interface
9593 226 Zero(com, 1, NV[2][3]);
9594 37273 ▶ for (k = 0; k < n_sub; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < n_sub; k++) { 37047 226 37273
9595 37047 const UV a = w.map[k];
9596 37047 const unsigned short p = k < n1 ? 0 : 1;
9597 37047 mass[p] += s->mass[a];
9598 37047 com[p][0] += s->mass[a] * s->x[a];
9599 37047 com[p][1] += s->mass[a] * s->y[a];
9600 37047 com[p][2] += s->mass[a] * s->z[a];
9601 37047 ▶ if (w.cls[a] & IA_HEAVY) {
Branch: 1 branch
BranchTrueFalseTotal
if (w.cls[a] & IA_HEAVY) { 33047 4000 37047
9602 33047 SV *bs = hvf_sv(aTHX_ s->atom_hv[a], "bfactor", 7);
9603 33047 ▶ if (bs && looks_like_number(bs)) {
Branch: 2 branches
BranchTrueFalseTotal
if (bs && looks_like_number(bs)) { 33044 3 33047
if (bs && looks_like_number(bs)) { 33044 0 33044
9604 33044 const NV b = SvNV(bs);
9605 33044 bsum[p] += b; bn[p]++;
9606 33044 ▶ if (w.cls[a] & IA_IFACE) { bisum[p] += b; bin[p]++; }
Branch: 1 branch
BranchTrueFalseTotal
if (w.cls[a] & IA_IFACE) { bisum[p] += b; bin[p]++; } 6341 26703 33044
9607 }
9608 }
9609 }
9610 678 ▶ for (sd = 0; sd < 2; sd++) {
Branch: 1 branch
BranchTrueFalseTotal
for (sd = 0; sd < 2; sd++) { 452 226 678
9611 452 have_b[sd] = bn[sd] > 0;
9612 452 have_bi[sd] = bin[sd] > 0;
9613 452 ▶ bmean[sd] = have_b[sd] ? bsum[sd] / (NV)bn[sd] : 0.0;
Branch: 1 branch
BranchTrueFalseTotal
bmean[sd] = have_b[sd] ? bsum[sd] / (NV)bn[sd] : 0.0; 450 2 452
9614 452 ▶ bimean[sd] = have_bi[sd] ? bisum[sd] / (NV)bin[sd] : 0.0;
Branch: 1 branch
BranchTrueFalseTotal
bimean[sd] = have_bi[sd] ? bisum[sd] / (NV)bin[sd] : 0.0; 154 298 452
9615 }
9616  
9617 676 ▶ for (sd = 0; sd < 2 && want_surface; sd++) {
Branch: 2 branches
BranchTrueFalseTotal
for (sd = 0; sd < 2 && want_surface; sd++) { 451 225 676
for (sd = 0; sd < 2 && want_surface; sd++) { 450 1 451
9618 450 SSize_t e, ne = av_len(sides[sd]) + 1;
9619 450 res_sasa[sd] = newAV(); sv_2mortal((SV *)res_sasa[sd]);
9620 450 res_alone[sd] = newAV(); sv_2mortal((SV *)res_alone[sd]);
9621 5014 ▶ for (e = 0; e < ne; e++) {
Branch: 1 branch
BranchTrueFalseTotal
for (e = 0; e < ne; e++) { 4564 450 5014
9622 4564 SV **p = av_fetch(sides[sd], e, 0);
9623 4564 r = res_addr_find(w.tab, s->n_res, PTR2UV(SvRV(*p)), s->n_res);
9624 4564 av_push(res_sasa[sd], newSVnv(res_c[r]));
9625 4564 av_push(res_alone[sd], newSVnv(res_a[r]));
9626 }
9627 }
9628  
9629 //built last, so that nothing between here and the return can croak with it
9630 //half-filled and unreferenced
9631 226 out = newHV();
9632 /*The pocket, parallel to the first list as the surfaces are: each
9633 residue's atoms in it, their surface alone, and the residue's relative
9634 surface alone, over max_asa[] as rsa is, where it has one. The relative
9635 surface is of the heavy atoms only, as the script's residue_sasa() sums
9636 it: Tien's maxima are surfaces of tripeptides with no hydrogens, and a
9637 structure that has them would otherwise add their surface to the
9638 numerator alone.*/
9639 226 ▶ if (io->want_pocket) {
Branch: 1 branch
BranchTrueFalseTotal
if (io->want_pocket) { 223 3 226
9640 223 SSize_t e, ne = av_len(sides[0]) + 1;
9641 223 AV *pn = newAV(), *pa = NULL, *pr = NULL;
9642 223 (void)hv_stores(out, "pocket_atoms", newRV_noinc((SV *)pn));
9643 223 ▶ if (want_surface) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_surface) { 222 1 223
9644 222 pa = newAV();
9645 222 pr = newAV();
9646 222 (void)hv_stores(out, "pocket_sasa", newRV_noinc((SV *)pa));
9647 222 (void)hv_stores(out, "pocket_rsa", newRV_noinc((SV *)pr));
9648 }
9649 3582 ▶ for (e = 0; e < ne; e++) {
Branch: 1 branch
BranchTrueFalseTotal
for (e = 0; e < ne; e++) { 3359 223 3582
9650 3359 SV **p = av_fetch(sides[0], e, 0);
9651 3359 NV maxa = 0.0;
9652 3359 r = res_addr_find(w.tab, s->n_res, PTR2UV(SvRV(*p)), s->n_res);
9653 3359 av_push(pn, newSVuv(w.pk_n[r]));
9654 3359 ▶ if (!want_surface) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!want_surface) continue; 57 3302 3359
9655 3302 av_push(pa, newSVnv(w.pk_a[r]));
9656 3302 ▶ if (s->res_type[r] == RT_AA && s->res_one[r] >= 'A' && s->res_one[r] <= 'Z')
Branch: 3 branches
BranchTrueFalseTotal
if (s->res_type[r] == RT_AA && s->res_one[r] >= 'A' && s->res_one[r] <= 'Z') 3208 94 3302
if (s->res_type[r] == RT_AA && s->res_one[r] >= 'A' && s->res_one[r] <= 'Z') 3208 0 3208
if (s->res_type[r] == RT_AA && s->res_one[r] >= 'A' && s->res_one[r] <= 'Z') 3208 0 3208
9657 3208 maxa = max_asa[s->res_one[r] - 'A'];
9658 3302 ▶ av_push(pr, maxa > 0.0 ? newSVnv(w.pk_h[r] / maxa) : newSV(0));
Branch: 1 branch
BranchTrueFalseTotal
av_push(pr, maxa > 0.0 ? newSVnv(w.pk_h[r] / maxa) : newSV(0)); 3208 94 3302
9659 }
9660 223 ▶ if (n_h2) (void)hv_stores(out, "pocket_packing", newSVnv((NV)n_pack / (NV)n_h2));
Branch: 1 branch
BranchTrueFalseTotal
if (n_h2) (void)hv_stores(out, "pocket_packing", newSVnv((NV)n_pack / (NV)n_h2)); 223 0 223
9661 }
9662 {
9663 226 AV *na = newAV();
9664 226 av_push(na, newSVuv(n_at[0])); av_push(na, newSVuv(n_at[1]));
9665 226 (void)hv_stores(out, "n_atoms", newRV_noinc((SV *)na));
9666 }
9667 226 ▶ if (want_surface) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_surface) { 225 1 226
9668 225 AV *al = newAV(), *rs = newAV(), *ra = newAV();
9669 225 av_push(al, newSVnv(alone[0])); av_push(al, newSVnv(alone[1]));
9670 675 ▶ for (sd = 0; sd < 2; sd++) {
Branch: 1 branch
BranchTrueFalseTotal
for (sd = 0; sd < 2; sd++) { 450 225 675
9671 450 av_push(rs, newRV_inc((SV *)res_sasa[sd]));
9672 450 av_push(ra, newRV_inc((SV *)res_alone[sd]));
9673 }
9674 225 (void)hv_stores(out, "sasa_alone", newRV_noinc((SV *)al));
9675 225 (void)hv_stores(out, "residue_sasa", newRV_noinc((SV *)rs));
9676 225 (void)hv_stores(out, "residue_sasa_alone", newRV_noinc((SV *)ra));
9677 225 (void)hv_stores(out, "sasa_complex", newSVnv(sasa_c));
9678 225 (void)hv_stores(out, "buried_apolar", newSVnv(bur_ap));
9679 225 (void)hv_stores(out, "buried_polar", newSVnv(bur_po));
9680 }
9681 226 (void)hv_stores(out, "contacts", newRV_inc((SV *)contacts));
9682 226 (void)hv_stores(out, "n_atom_contacts", newSVuv(n_atom_contacts));
9683 226 (void)hv_stores(out, "polar_contacts", newRV_inc((SV *)polar));
9684 226 (void)hv_stores(out, "salt_bridges", newRV_inc((SV *)salt));
9685 226 (void)hv_stores(out, "cation_pi", newRV_inc((SV *)cpi));
9686 226 (void)hv_stores(out, "bridging_waters", newRV_inc((SV *)bridge));
9687 /*the closest two heavy atoms come a pair apart, and only a pair within
9688 reach is ever measured: partners further apart than that have no
9689 min_distance rather than a wrong one*/
9690 226 ▶ if (have_min) (void)hv_stores(out, "min_distance", newSVnv(min_d));
Branch: 1 branch
BranchTrueFalseTotal
if (have_min) (void)hv_stores(out, "min_distance", newSVnv(min_d)); 78 148 226
9691 226 ▶ if (mass[0] > 0.0 && mass[1] > 0.0) {
Branch: 2 branches
BranchTrueFalseTotal
if (mass[0] > 0.0 && mass[1] > 0.0) { 226 0 226
if (mass[0] > 0.0 && mass[1] > 0.0) { 226 0 226
9692 226 NV dx = com[0][0] / mass[0] - com[1][0] / mass[1];
9693 226 NV dy = com[0][1] / mass[0] - com[1][1] / mass[1];
9694 226 NV dz = com[0][2] / mass[0] - com[1][2] / mass[1];
9695 226 (void)hv_stores(out, "com_distance", newSVnv(nv_sqrt(dx * dx + dy * dy + dz * dz)));
9696 }
9697 226 (void)hv_stores(out, "bfactor_mean", pair_av(aTHX_ bmean, have_b));
9698 226 (void)hv_stores(out, "bfactor_interface", pair_av(aTHX_ bimean, have_bi));
9699 226 LEAVE;
9700 226 return out;
9701 }
9702  
9703 //an option that is a number, with the default the caller wrote down
9704 14714 static NV opt_nv(pTHX_ HV *CSP_RESTRICT o, const char *CSP_RESTRICT k, NV dflt)
9705 {
9706 14714 SV *v = opt_get(aTHX_ o, k);
9707 14714 ▶ return v ? SvNV(v) : dflt;
Branch: 1 branch
BranchTrueFalseTotal
return v ? SvNV(v) : dflt; 14560 154 14714
9708 }
9709  
9710 /*set_free() as a scope destructor, so that a croak between set_build() and the
9711 end of features_do() -- which at this point can only be an allocation failing --
9712 does not walk off with the coordinate arrays.
9713  
9714 No CSP_RESTRICT on the parameter: the prototype is SAVEDESTRUCTOR_X's, not this
9715 file's, and a qualifier there would say something about a pointer perl chose.*/
9716 696 static void set_free_cb(pTHX_ void *p)
9717 {
9718 696 set_free(aTHX_ (structset *)p);
9719 696 }
9720  
9721 //degrees in the option hash, radians in the comparison
9722 4888 static NV opt_rad(pTHX_ HV *CSP_RESTRICT o, const char *CSP_RESTRICT k, NV dflt_deg)
9723 {
9724 4888 return opt_nv(aTHX_ o, k, dflt_deg) * CSP_PI / 180.0;
9725 }
9726  
9727 /*features_do() -- one walk of the structure, every property that was asked for.
9728  
9729 The roll-ups are sums over the contiguous ranges set_build() left behind: a
9730 residue's atoms are one run and a chain's residues are another, so the
9731 per-residue and per-chain areas are the same loop the per-atom areas came out
9732 of rather than a second pass keyed on anything.
9733  
9734 What is written back into $info -- an atom's sasa, a residue's sasa and rsa, a
9735 chain's sasa -- is written here rather than returned and grafted on in Perl,
9736 for the reason the whole file exists: a 400,000-atom structure would otherwise
9737 mean 400,000 more SVs and a Perl loop to put them in place.*/
9738 712 static HV *features_do(pTHX_ HV *CSP_RESTRICT info, HV *CSP_RESTRICT o,
9739 const char *CSP_RESTRICT who)
9740 {
9741 structset s;
9742 HV *out;
9743 712 HV *sasa_hv = NULL, *ssq = NULL;
9744 712 AV *pi = NULL, *ss = NULL, *bp = NULL, *bs = NULL, *cont = NULL, *hb = NULL;
9745 712 HV *iface = NULL;
9746 712 const bool want_sasa = opt_bool(aTHX_ o, "sasa", TRUE);
9747 712 const bool want_iface = opt_bool(aTHX_ o, "interface", TRUE);
9748 712 const bool want_shape = opt_bool(aTHX_ o, "shape", TRUE);
9749 712 const bool want_pi = opt_bool(aTHX_ o, "pi_stacking", TRUE);
9750 712 const bool want_ss = opt_bool(aTHX_ o, "disulfides", TRUE);
9751 712 const bool want_bp = opt_bool(aTHX_ o, "base_pairs", TRUE);
9752 712 const bool want_bs = opt_bool(aTHX_ o, "base_stacks", TRUE);
9753 712 const bool want_tors = opt_bool(aTHX_ o, "dihedrals", TRUE);
9754 712 const bool want_cont = opt_bool(aTHX_ o, "contacts", TRUE);
9755 712 const bool want_hse = opt_bool(aTHX_ o, "exposure", TRUE);
9756 712 const bool want_hb = opt_bool(aTHX_ o, "hbonds", TRUE);
9757 712 const bool want_ssq = opt_bool(aTHX_ o, "secondary", TRUE);
9758 712 const bool store = opt_bool(aTHX_ o, "store", TRUE);
9759 712 const NV probe = opt_nv(aTHX_ o, "probe", 1.4);
9760 712 const IV points = opt_iv(aTHX_ o, "points", 960);
9761 712 NV total = 0.0, apolar = 0.0, buried = 0.0, mass_total = 0.0;
9762 NV gyr[3][3], moment[3];
9763 712 NV cx = 0.0, cy = 0.0, cz = 0.0, mx = 0.0, my = 0.0, mz = 0.0;
9764 712 NV rg = 0.0, rg_mass = 0.0;
9765 712 bool have_rg_mass = 0;
9766 UV i, r, c;
9767  
9768 712 ▶ if (probe < 0.0) croak("%s: probe must not be negative", who);
Branch: 1 branch
BranchTrueFalseTotal
if (probe < 0.0) croak("%s: probe must not be negative", who); 2 710 712
9769 //The upper bound is memory, not accuracy: the sphere points are three NVs
9770 //each, so ten million of them is 240 MB on a double perl and four times
9771 //that on a quadmath one, for an atom whose area is one number.
9772 710 ▶ if (points < 1 || points > 10000000)
Branch: 2 branches
BranchTrueFalseTotal
if (points < 1 || points > 10000000) 709 1 710
if (points < 1 || points > 10000000) 1 708 709
9773 2 croak("%s: points must be between 1 and 10000000", who);
9774  
9775 /*Every other option, read and checked before anything is computed. A
9776 threshold found to be wrong halfway down would croak with the surface
9777 already worked out and already written into $info, which is a structure
9778 left half-annotated by a call that failed.*/
9779 708 const NV bond = opt_nv(aTHX_ o, "peptide_bond", CSP_PEPTIDE_BOND);
9780 708 const NV phospho = opt_nv(aTHX_ o, "phosphodiester_bond", CSP_PHOSPHO_BOND);
9781 708 const NV cont_cut = opt_nv(aTHX_ o, "contact_distance", 4.5);
9782 708 const NV ss_cut = opt_nv(aTHX_ o, "disulfide_distance", 3.0);
9783 708 const NV bp_hb = opt_nv(aTHX_ o, "base_pair_hbond", CSP_BP_HBOND);
9784 708 const NV bp_sag = opt_nv(aTHX_ o, "base_pair_stagger", CSP_BP_STAGGER);
9785 708 const NV bs_dist = opt_nv(aTHX_ o, "base_stack_distance", CSP_STACK_DIST);
9786 708 const NV bs_om = opt_nv(aTHX_ o, "base_stack_omega", CSP_STACK_OMEGA);
9787 pi_opt po;
9788 iface_opt io;
9789 708 AV *two[2] = { NULL, NULL };//the interface's two partners, when the Perl gave them
9790 708 bool want_isasa = want_sasa;
9791 708 ▶ if (want_tors && store) {
Branch: 2 branches
BranchTrueFalseTotal
if (want_tors && store) { 612 96 708
if (want_tors && store) { 607 5 612
9792 607 ▶ if (bond <= 0.0) croak("%s: peptide_bond must be a positive number", who);
Branch: 1 branch
BranchTrueFalseTotal
if (bond <= 0.0) croak("%s: peptide_bond must be a positive number", who); 1 606 607
9793 606 ▶ if (phospho <= 0.0)
Branch: 1 branch
BranchTrueFalseTotal
if (phospho <= 0.0) 1 605 606
9794 1 croak("%s: phosphodiester_bond must be a positive number", who);
9795 }
9796 706 ▶ if (want_cont && cont_cut <= 0.0)
Branch: 2 branches
BranchTrueFalseTotal
if (want_cont && cont_cut <= 0.0) 612 94 706
if (want_cont && cont_cut <= 0.0) 2 610 612
9797 2 croak("%s: contact_distance must be a positive number", who);
9798 704 ▶ if (want_ss && ss_cut < 0.0) croak("%s: disulfide_distance must not be negative", who);
Branch: 2 branches
BranchTrueFalseTotal
if (want_ss && ss_cut < 0.0) croak("%s: disulfide_distance must not be negative", who); 614 90 704
if (want_ss && ss_cut < 0.0) croak("%s: disulfide_distance must not be negative", who); 1 613 614
9799 703 ▶ if (want_bp) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_bp) { 630 73 703
9800 630 ▶ if (bp_hb <= 0.0) croak("%s: base_pair_hbond must be a positive number", who);
Branch: 1 branch
BranchTrueFalseTotal
if (bp_hb <= 0.0) croak("%s: base_pair_hbond must be a positive number", who); 1 629 630
9801 629 ▶ if (bp_sag < 0.0) croak("%s: base_pair_stagger must not be negative", who);
Branch: 1 branch
BranchTrueFalseTotal
if (bp_sag < 0.0) croak("%s: base_pair_stagger must not be negative", who); 1 628 629
9802 }
9803 701 ▶ if (want_bs) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_bs) { 616 85 701
9804 616 ▶ if (bs_dist <= 0.0) croak("%s: base_stack_distance must be a positive number", who);
Branch: 1 branch
BranchTrueFalseTotal
if (bs_dist <= 0.0) croak("%s: base_stack_distance must be a positive number", who); 1 615 616
9805 615 ▶ if (bs_om < 0.0 || bs_om > 180.0)
Branch: 2 branches
BranchTrueFalseTotal
if (bs_om < 0.0 || bs_om > 180.0) 615 0 615
if (bs_om < 0.0 || bs_om > 180.0) 1 614 615
9806 1 croak("%s: base_stack_omega must be between 0 and 180", who);
9807 }
9808 699 ▶ if (want_pi) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_pi) { 611 88 699
9809 611 po.face_dist = opt_nv(aTHX_ o, "face_distance", 5.5);
9810 611 po.face_plane_lo = opt_rad(aTHX_ o, "face_plane_min", 0.0);
9811 611 po.face_plane_hi = opt_rad(aTHX_ o, "face_plane_max", 35.0);
9812 611 po.face_norm_lo = opt_rad(aTHX_ o, "face_normal_min", 0.0);
9813 611 po.face_norm_hi = opt_rad(aTHX_ o, "face_normal_max", 33.0);
9814 611 po.edge_dist = opt_nv(aTHX_ o, "edge_distance", 6.5);
9815 611 po.edge_plane_lo = opt_rad(aTHX_ o, "edge_plane_min", 50.0);
9816 611 po.edge_plane_hi = opt_rad(aTHX_ o, "edge_plane_max", 90.0);
9817 611 po.edge_norm_lo = opt_rad(aTHX_ o, "edge_normal_min", 0.0);
9818 611 po.edge_norm_hi = opt_rad(aTHX_ o, "edge_normal_max", 30.0);
9819 611 po.edge_radius = opt_nv(aTHX_ o, "edge_radius", 1.5);
9820 }
9821 /*The two partners, when the Perl found or was told of two: `sides' is
9822 the Perl's own key, holding the two residue lists, and never an option a
9823 caller writes.*/
9824 699 ▶ if (want_iface) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_iface) { 695 4 699
9825 695 AV *sd = hvf_av(aTHX_ o, "sides", 5);
9826 695 ▶ if (sd && av_len(sd) == 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (sd && av_len(sd) == 1) { 232 463 695
if (sd && av_len(sd) == 1) { 232 0 232
9827 232 SV **p0 = av_fetch(sd, 0, 0), **p1 = av_fetch(sd, 1, 0);
9828 232 ▶ if (!p0 || !*p0 || !SvROK(*p0) || SvTYPE(SvRV(*p0)) != SVt_PVAV
Branch: 4 branches
BranchTrueFalseTotal
if (!p0 || !*p0 || !SvROK(*p0) || SvTYPE(SvRV(*p0)) != SVt_PVAV 232 0 232
if (!p0 || !*p0 || !SvROK(*p0) || SvTYPE(SvRV(*p0)) != SVt_PVAV 232 0 232
if (!p0 || !*p0 || !SvROK(*p0) || SvTYPE(SvRV(*p0)) != SVt_PVAV 232 0 232
if (!p0 || !*p0 || !SvROK(*p0) || SvTYPE(SvRV(*p0)) != SVt_PVAV 232 0 232
9829 232 ▶ || !p1 || !*p1 || !SvROK(*p1) || SvTYPE(SvRV(*p1)) != SVt_PVAV)
Branch: 4 branches
BranchTrueFalseTotal
|| !p1 || !*p1 || !SvROK(*p1) || SvTYPE(SvRV(*p1)) != SVt_PVAV) 232 0 232
|| !p1 || !*p1 || !SvROK(*p1) || SvTYPE(SvRV(*p1)) != SVt_PVAV) 232 0 232
|| !p1 || !*p1 || !SvROK(*p1) || SvTYPE(SvRV(*p1)) != SVt_PVAV) 231 1 232
|| !p1 || !*p1 || !SvROK(*p1) || SvTYPE(SvRV(*p1)) != SVt_PVAV) 0 231 231
9830 1 croak("%s: sides must be two array references", who);
9831 231 two[0] = (AV *)SvRV(*p0);
9832 231 two[1] = (AV *)SvRV(*p1);
9833 231 io.contact = opt_nv(aTHX_ o, "interface_distance", 5.5);
9834 231 io.salt = opt_nv(aTHX_ o, "salt_bridge_distance", 4.0);
9835 231 io.polar = opt_nv(aTHX_ o, "polar_distance", 3.5);
9836 231 io.cation_pi = opt_nv(aTHX_ o, "cation_pi_distance", 6.0);
9837 231 io.water = opt_nv(aTHX_ o, "water_distance", 3.5);
9838 231 io.pocket = opt_nv(aTHX_ o, "pocket_distance", 6.0);
9839 231 io.packing = opt_nv(aTHX_ o, "packing_distance", 8.0);
9840 231 io.want_pocket = opt_bool(aTHX_ o, "pocket", TRUE);
9841 231 ▶ if (io.contact <= 0.0 || io.salt <= 0.0 || io.polar <= 0.0
Branch: 3 branches
BranchTrueFalseTotal
if (io.contact <= 0.0 || io.salt <= 0.0 || io.polar <= 0.0 231 0 231
if (io.contact <= 0.0 || io.salt <= 0.0 || io.polar <= 0.0 231 0 231
if (io.contact <= 0.0 || io.salt <= 0.0 || io.polar <= 0.0 231 0 231
9842 231 ▶ || io.cation_pi <= 0.0 || io.water <= 0.0 || io.pocket <= 0.0
Branch: 3 branches
BranchTrueFalseTotal
|| io.cation_pi <= 0.0 || io.water <= 0.0 || io.pocket <= 0.0 231 0 231
|| io.cation_pi <= 0.0 || io.water <= 0.0 || io.pocket <= 0.0 230 1 231
|| io.cation_pi <= 0.0 || io.water <= 0.0 || io.pocket <= 0.0 229 1 230
9843 229 ▶ || io.packing <= 0.0)
Branch: 1 branch
BranchTrueFalseTotal
|| io.packing <= 0.0) 0 229 229
9844 2 croak("%s: the interface distances must be positive numbers", who);
9845 /*sasa => 0 is a request for no surface, and the interface's is
9846 one; interface_sasa is the Perl's own key, set by
9847 structure_interface(), which wants the interface's surface
9848 without paying for the whole structure's*/
9849 229 want_isasa = opt_bool(aTHX_ o, "interface_sasa", want_sasa);
9850 }
9851 }
9852  
9853 696 ENTER;
9854 696 Zero(&s, 1, structset);
9855 696 SAVEDESTRUCTOR_X(set_free_cb, &s);
9856 696 set_build(aTHX_ info, &s, probe, FALSE, who);
9857  
9858 693 ▶ if (want_sasa) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_sasa) { 613 80 693
9859 //the grid is kept only when the interface below will ask for it again
9860 613 ▶ sasa_compute(aTHX_ &s, (UV)points, want_iface, two[0] && want_isasa);
Branch: 2 branches
BranchTrueFalseTotal
sasa_compute(aTHX_ &s, (UV)points, want_iface, two[0] && want_isasa); 203 410 613
sasa_compute(aTHX_ &s, (UV)points, want_iface, two[0] && want_isasa); 203 0 203
9861 78105 ▶ for (i = 0; i < s.n_atom; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < s.n_atom; i++) { 77492 613 78105
9862 77492 total += s.area[i];
9863 77492 ▶ if (s.apolar[i]) apolar += s.area[i];
Branch: 1 branch
BranchTrueFalseTotal
if (s.apolar[i]) apolar += s.area[i]; 40835 36657 77492
9864 77492 ▶ if (s.alone) buried += s.alone[i] - s.area[i];
Branch: 1 branch
BranchTrueFalseTotal
if (s.alone) buried += s.alone[i] - s.area[i]; 75518 1974 77492
9865 77492 ▶ if (store) (void)hv_stores(s.atom_hv[i], "sasa", newSVnv(s.area[i]));
Branch: 1 branch
BranchTrueFalseTotal
if (store) (void)hv_stores(s.atom_hv[i], "sasa", newSVnv(s.area[i])); 75886 1606 77492
9866 }
9867 1412 ▶ for (c = 0; c < s.n_chain; c++) {
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < s.n_chain; c++) { 799 613 1412
9868 799 NV c_area = 0.0, c_alone = 0.0;
9869 12300 ▶ for (r = s.chain_first[c]; r < s.chain_last[c]; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = s.chain_first[c]; r < s.chain_last[c]; r++) { 11501 799 12300
9870 11501 NV r_area = 0.0;
9871 88993 ▶ for (i = s.res_first[r]; i < s.res_last[r]; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = s.res_first[r]; i < s.res_last[r]; i++) { 77492 11501 88993
9872 77492 r_area += s.area[i];
9873 77492 ▶ if (s.alone) c_alone += s.alone[i];
Branch: 1 branch
BranchTrueFalseTotal
if (s.alone) c_alone += s.alone[i]; 75518 1974 77492
9874 }
9875 11501 c_area += r_area;
9876 11501 ▶ if (!store) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!store) continue; 192 11309 11501
9877 11309 (void)hv_stores(s.res_hv[r], "sasa", newSVnv(r_area));
9878 /*Relative accessibility, and only for an amino acid: the
9879 single-letter codes of the nucleotides are amino acid codes
9880 too, and dividing a guanine's area by glycine's maximum would
9881 be a number rather than an answer.*/
9882 11309 ▶ if (s.res_type[r] == RT_AA && s.res_one[r] >= 'A' && s.res_one[r] <= 'Z') {
Branch: 3 branches
BranchTrueFalseTotal
if (s.res_type[r] == RT_AA && s.res_one[r] >= 'A' && s.res_one[r] <= 'Z') { 7414 3895 11309
if (s.res_type[r] == RT_AA && s.res_one[r] >= 'A' && s.res_one[r] <= 'Z') { 7410 4 7414
if (s.res_type[r] == RT_AA && s.res_one[r] >= 'A' && s.res_one[r] <= 'Z') { 7410 0 7410
9883 7410 NV maxa = max_asa[s.res_one[r] - 'A'];
9884 7410 ▶ if (maxa > 0.0)
Branch: 1 branch
BranchTrueFalseTotal
if (maxa > 0.0) 7409 1 7410
9885 7409 (void)hv_stores(s.res_hv[r], "rsa", newSVnv(r_area / maxa));
9886 }
9887 }
9888 799 ▶ if (!store) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!store) continue; 6 793 799
9889 793 (void)hv_stores(s.chain_hv[c], "sasa", newSVnv(c_area));
9890 793 ▶ if (s.alone) {
Branch: 1 branch
BranchTrueFalseTotal
if (s.alone) { 786 7 793
9891 786 (void)hv_stores(s.chain_hv[c], "sasa_alone", newSVnv(c_alone));
9892 786 (void)hv_stores(s.chain_hv[c], "buried", newSVnv(c_alone - c_area));
9893 }
9894 }
9895 }
9896  
9897 /*Size and weight. The unweighted radius of gyration is mdtraj's
9898 compute_rg() with its default masses -- the root mean square distance from
9899 the centroid -- and is comparable with it directly. The mass-weighted one
9900 is taken about the centre of mass, which is what the quantity means and is
9901 not what mdtraj does: compute_rg(traj, masses=m) weights the distances by
9902 mass but still measures them from the geometric centroid, so the two answers
9903 differ by however far the two centres are apart. t/features.t pins this one
9904 against the corrected expression rather than against that call.*/
9905 113770 ▶ for (i = 0; i < s.n_atom; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < s.n_atom; i++) { 113077 693 113770
9906 113077 cx += s.x[i]; cy += s.y[i]; cz += s.z[i];
9907 113077 mass_total += s.mass[i];
9908 113077 mx += s.mass[i] * s.x[i]; my += s.mass[i] * s.y[i]; mz += s.mass[i] * s.z[i];
9909 }
9910 693 Zero(gyr, 1, NV[3][3]);
9911 693 Zero(moment, 3, NV);
9912 693 ▶ if (s.n_atom) {
Branch: 1 branch
BranchTrueFalseTotal
if (s.n_atom) { 661 32 693
9913 661 NV sum = 0.0;
9914 661 cx /= (NV)s.n_atom; cy /= (NV)s.n_atom; cz /= (NV)s.n_atom;
9915 113738 ▶ for (i = 0; i < s.n_atom; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < s.n_atom; i++) { 113077 661 113738
9916 113077 NV dx = s.x[i] - cx, dy = s.y[i] - cy, dz = s.z[i] - cz;
9917 113077 sum += dx * dx + dy * dy + dz * dz;
9918 /*The gyration tensor, in the same pass: it is the outer product of
9919 the same offsets whose squares the radius of gyration sums, so its
9920 trace is that sum and rg*rg is the trace over n. Six entries rather
9921 than nine, because it is symmetric by construction.*/
9922 113077 gyr[0][0] += dx * dx; gyr[1][1] += dy * dy; gyr[2][2] += dz * dz;
9923 113077 gyr[0][1] += dx * dy; gyr[0][2] += dx * dz; gyr[1][2] += dy * dz;
9924 }
9925 661 rg = nv_sqrt(sum / (NV)s.n_atom);
9926 661 gyr[0][0] /= (NV)s.n_atom; gyr[1][1] /= (NV)s.n_atom; gyr[2][2] /= (NV)s.n_atom;
9927 661 gyr[0][1] /= (NV)s.n_atom; gyr[0][2] /= (NV)s.n_atom; gyr[1][2] /= (NV)s.n_atom;
9928 661 gyr[1][0] = gyr[0][1]; gyr[2][0] = gyr[0][2]; gyr[2][1] = gyr[1][2];
9929 661 sym3_eigenvalues(gyr, moment);
9930 }
9931 693 ▶ if (mass_total > 0.0) {
Branch: 1 branch
BranchTrueFalseTotal
if (mass_total > 0.0) { 659 34 693
9932 659 NV sum = 0.0;
9933 659 mx /= mass_total; my /= mass_total; mz /= mass_total;
9934 113734 ▶ for (i = 0; i < s.n_atom; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < s.n_atom; i++) { 113075 659 113734
9935 113075 NV dx = s.x[i] - mx, dy = s.y[i] - my, dz = s.z[i] - mz;
9936 113075 sum += s.mass[i] * (dx * dx + dy * dy + dz * dz);
9937 }
9938 659 rg_mass = nv_sqrt(sum / mass_total);
9939 659 have_rg_mass = 1;
9940 }
9941  
9942 693 ▶ if (want_pi) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_pi) { 609 84 693
9943 609 pi = pi_stacking(aTHX_ &s, &po);
9944 609 sv_2mortal((SV *)pi);
9945 }
9946  
9947 693 ▶ if (want_tors && store) dihedrals(aTHX_ &s, bond, phospho);
Branch: 2 branches
BranchTrueFalseTotal
if (want_tors && store) dihedrals(aTHX_ &s, bond, phospho); 602 91 693
if (want_tors && store) dihedrals(aTHX_ &s, bond, phospho); 597 5 602
9948  
9949 693 ▶ if (want_hb) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_hb) { 605 88 693
9950 605 backbone *CSP_RESTRICT bb = NULL;
9951 /*a scope of its own, so that bb is freed as soon as the bonds are found
9952 and still freed when either call croaks*/
9953 605 ENTER;
9954 605 ▶ Newxz(bb, s.n_res ? s.n_res : 1, backbone);
Branch: 3 branches
BranchTrueFalseTotal
Newxz(bb, s.n_res ? s.n_res : 1, backbone); 576 29 605
Newxz(bb, s.n_res ? s.n_res : 1, backbone); 0 576 576
Newxz(bb, s.n_res ? s.n_res : 1, backbone); 576 29 605
9955 605 SAVEFREEPV((char *)bb);
9956 605 backbone_read(aTHX_ &s, bb, bond);
9957 605 ks_compute(aTHX_ &s, bb);
9958 605 LEAVE;
9959 605 hb = hbond_list(aTHX_ &s);
9960 605 sv_2mortal((SV *)hb);
9961 }
9962 //the secondary structure reads a hydrogen bond table of its own; see the
9963 //head of that block for why it cannot be the one above
9964 693 ▶ if (want_ssq) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_ssq) { 608 85 693
9965 608 ssq = dssp_compute(aTHX_ &s, store);
9966 608 sv_2mortal((SV *)ssq);
9967 }
9968  
9969 693 ▶ if (want_cont) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_cont) { 603 90 693
9970 603 cont = contacts_find(aTHX_ &s, cont_cut, store);
9971 603 sv_2mortal((SV *)cont);
9972 }
9973 693 ▶ if (want_hse && store) hse_compute(aTHX_ &s, CSP_HSE_RADIUS);
Branch: 2 branches
BranchTrueFalseTotal
if (want_hse && store) hse_compute(aTHX_ &s, CSP_HSE_RADIUS); 602 91 693
if (want_hse && store) hse_compute(aTHX_ &s, CSP_HSE_RADIUS); 597 5 602
9974  
9975 //run after the whole-structure surface, which it starts from
9976 693 ▶ if (two[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (two[0]) { 229 464 693
9977 229 iface = iface_compute(aTHX_ &s, two, (UV)points, want_isasa, &io, who);
9978 226 sv_2mortal((SV *)iface);
9979 }
9980  
9981 690 ▶ if (want_ss) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_ss) { 607 83 690
9982 607 ss = disulfides(aTHX_ &s, ss_cut, store);
9983 607 sv_2mortal((SV *)ss);
9984 }
9985  
9986 690 ▶ if (want_bp) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_bp) { 624 66 690
9987 624 bp = base_pairs(aTHX_ &s, bp_hb, bp_sag, store);
9988 624 sv_2mortal((SV *)bp);
9989 }
9990  
9991 690 ▶ if (want_bs) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_bs) { 612 78 690
9992 612 bs = base_stacks(aTHX_ &s, bs_dist, bs_om, store);
9993 612 sv_2mortal((SV *)bs);
9994 }
9995  
9996 //the result hash is built last, so that nothing between here and the return
9997 //can croak with it half-filled and unreferenced
9998 690 out = newHV();
9999 690 (void)hv_stores(out, "n_atoms", newSVuv(s.n_atom));
10000 690 (void)hv_stores(out, "n_residues", newSVuv(s.n_res));
10001 690 (void)hv_stores(out, "n_chains", newSVuv(s.n_chain));
10002 690 (void)hv_stores(out, "n_no_element", newSVuv(s.n_no_element));
10003 690 (void)hv_stores(out, "mass", newSVnv(mass_total));
10004 690 ▶ if (s.n_atom) {
Branch: 1 branch
BranchTrueFalseTotal
if (s.n_atom) { 658 32 690
10005 658 AV *ctr = newAV();
10006 658 av_push(ctr, newSVnv(cx)); av_push(ctr, newSVnv(cy)); av_push(ctr, newSVnv(cz));
10007 658 (void)hv_stores(out, "center", newRV_noinc((SV *)ctr));
10008 658 (void)hv_stores(out, "rg", newSVnv(rg));
10009 }
10010 690 ▶ if (have_rg_mass) {
Branch: 1 branch
BranchTrueFalseTotal
if (have_rg_mass) { 656 34 690
10011 656 AV *com = newAV();
10012 656 av_push(com, newSVnv(mx)); av_push(com, newSVnv(my)); av_push(com, newSVnv(mz));
10013 656 (void)hv_stores(out, "center_of_mass", newRV_noinc((SV *)com));
10014 656 (void)hv_stores(out, "rg_mass", newSVnv(rg_mass));
10015 }
10016 690 ▶ if (want_sasa) {
Branch: 1 branch
BranchTrueFalseTotal
if (want_sasa) { 613 77 690
10017 613 sasa_hv = newHV();
10018 613 (void)hv_stores(sasa_hv, "total", newSVnv(total));
10019 613 (void)hv_stores(sasa_hv, "apolar", newSVnv(apolar));
10020 613 (void)hv_stores(sasa_hv, "polar", newSVnv(total - apolar));
10021 613 (void)hv_stores(sasa_hv, "probe", newSVnv(probe));
10022 613 (void)hv_stores(sasa_hv, "points", newSVuv((UV)points));
10023 /*What the chains bury against each other: the surface they have apart
10024 less the surface they have together. A two-body interface is usually
10025 quoted as half of this, because the number is counted once on each side
10026 of it, and a caller with more than two chains has the per-chain figures
10027 to add up however the question was asked.*/
10028 613 ▶ if (s.alone) (void)hv_stores(sasa_hv, "buried", newSVnv(buried));
Branch: 1 branch
BranchTrueFalseTotal
if (s.alone) (void)hv_stores(sasa_hv, "buried", newSVnv(buried)); 578 35 613
10029 613 (void)hv_stores(out, "sasa", newRV_noinc((SV *)sasa_hv));
10030 }
10031 690 ▶ if (want_shape && s.n_atom) {
Branch: 2 branches
BranchTrueFalseTotal
if (want_shape && s.n_atom) { 602 88 690
if (want_shape && s.n_atom) { 570 32 602
10032 /*The gyration tensor's eigenvalues, and the three numbers mdtraj builds
10033 out of them in mdtraj/geometry/shape.py: asphericity is how far the
10034 largest moment stands above the mean of the other two, acylindricity how
10035 far the middle one stands above the smallest, and the relative shape
10036 anisotropy is 0 for a sphere and 1 for a straight line. All in
10037 angstrom^2, where mdtraj's are nm^2; the anisotropy has no units.*/
10038 570 HV *sh = newHV();
10039 570 AV *pm = newAV();
10040 570 AV *tensor = newAV();
10041 570 NV tr = moment[0] + moment[1] + moment[2];
10042 unsigned short a, b;
10043 2280 ▶ for (a = 0; a < 3; a++) av_push(pm, newSVnv(moment[a]));
Branch: 1 branch
BranchTrueFalseTotal
for (a = 0; a < 3; a++) av_push(pm, newSVnv(moment[a])); 1710 570 2280
10044 2280 ▶ for (a = 0; a < 3; a++) {
Branch: 1 branch
BranchTrueFalseTotal
for (a = 0; a < 3; a++) { 1710 570 2280
10045 1710 AV *row = newAV();
10046 6840 ▶ for (b = 0; b < 3; b++) av_push(row, newSVnv(gyr[a][b]));
Branch: 1 branch
BranchTrueFalseTotal
for (b = 0; b < 3; b++) av_push(row, newSVnv(gyr[a][b])); 5130 1710 6840
10047 1710 av_push(tensor, newRV_noinc((SV *)row));
10048 }
10049 570 (void)hv_stores(sh, "gyration_tensor", newRV_noinc((SV *)tensor));
10050 570 (void)hv_stores(sh, "principal_moments", newRV_noinc((SV *)pm));
10051 570 (void)hv_stores(sh, "asphericity", newSVnv(moment[2] - (moment[0] + moment[1]) / 2.0));
10052 570 (void)hv_stores(sh, "acylindricity", newSVnv(moment[1] - moment[0]));
10053 570 ▶ if (tr > 0.0)
Branch: 1 branch
BranchTrueFalseTotal
if (tr > 0.0) 518 52 570
10054 518 (void)hv_stores(sh, "anisotropy", newSVnv(
10055 1.5 * (moment[0] * moment[0] + moment[1] * moment[1] + moment[2] * moment[2])
10056 / (tr * tr) - 0.5));
10057 570 (void)hv_stores(out, "shape", newRV_noinc((SV *)sh));
10058 }
10059 690 ▶ if (want_pi) (void)hv_stores(out, "pi_stacking", newRV_inc((SV *)pi));
Branch: 1 branch
BranchTrueFalseTotal
if (want_pi) (void)hv_stores(out, "pi_stacking", newRV_inc((SV *)pi)); 609 81 690
10060 690 ▶ if (want_ss) (void)hv_stores(out, "disulfides", newRV_inc((SV *)ss));
Branch: 1 branch
BranchTrueFalseTotal
if (want_ss) (void)hv_stores(out, "disulfides", newRV_inc((SV *)ss)); 607 83 690
10061 690 ▶ if (want_bp) (void)hv_stores(out, "base_pairs", newRV_inc((SV *)bp));
Branch: 1 branch
BranchTrueFalseTotal
if (want_bp) (void)hv_stores(out, "base_pairs", newRV_inc((SV *)bp)); 624 66 690
10062 690 ▶ if (want_bs) (void)hv_stores(out, "base_stacks", newRV_inc((SV *)bs));
Branch: 1 branch
BranchTrueFalseTotal
if (want_bs) (void)hv_stores(out, "base_stacks", newRV_inc((SV *)bs)); 612 78 690
10063 690 ▶ if (want_cont) (void)hv_stores(out, "contacts", newRV_inc((SV *)cont));
Branch: 1 branch
BranchTrueFalseTotal
if (want_cont) (void)hv_stores(out, "contacts", newRV_inc((SV *)cont)); 603 87 690
10064 690 ▶ if (want_hb) (void)hv_stores(out, "hbonds", newRV_inc((SV *)hb));
Branch: 1 branch
BranchTrueFalseTotal
if (want_hb) (void)hv_stores(out, "hbonds", newRV_inc((SV *)hb)); 605 85 690
10065 690 ▶ if (want_ssq) (void)hv_stores(out, "dssp", newRV_inc((SV *)ssq));
Branch: 1 branch
BranchTrueFalseTotal
if (want_ssq) (void)hv_stores(out, "dssp", newRV_inc((SV *)ssq)); 608 82 690
10066 690 ▶ if (iface) (void)hv_stores(out, "interface", newRV_inc((SV *)iface));
Branch: 1 branch
BranchTrueFalseTotal
if (iface) (void)hv_stores(out, "interface", newRV_inc((SV *)iface)); 226 464 690
10067 690 LEAVE;
10068 690 return out;
10069 }
10070  
10071 /*Comparing two structures: RMSD.
10072  
10073 Everything above this point answers a question about one structure. This
10074 answers the one question that takes two: given two copies of the same molecule
10075 -- two models of an NMR ensemble, the same protein solved twice, a docked pose
10076 and the crystallographic one -- how far apart are they?
10077  
10078 The answer is the root mean square deviation over the atoms the two have in
10079 common, after the rigid-body move that makes it as small as it can be. It is
10080 three separate jobs, and two of them are somebody else's:
10081  
10082 pairing which atom of one structure is which atom of the other. Keyed
10083 on the chain, the residue as this module keys it and the atom
10084 name -- the identity the file itself gives an atom -- so two
10085 models of one ensemble pair exactly and two files of the same
10086 protein pair over whatever they have in common. Nothing is
10087 aligned and nothing is guessed: an atom that is not in both
10088 structures under the same name is not in the answer.
10089 superposition Theobald, D L (2005) Acta Cryst A61(4):478-80, the quaternion
10090 characteristic polynomial, as its reference implementation
10091 qcprot.c (Liu, P; Agrafiotis, D K; Theobald, D L (2010)
10092 J Comput Chem 31(7):1561-3) writes it and as Biopython 1.85
10093 ships it in Bio/PDB/qcprot.py. The inner-product matrix of
10094 the two centred point sets, the quartic whose largest root is
10095 the maximum of the rotation's trace, Newton-Raphson for that
10096 root, and the eigenvector of the 4x4 key matrix for the
10097 quaternion the rotation is built from.
10098 the deviation measured, not inferred; see qcp_rotation() for why.
10099  
10100 t/rmsd.t compares the whole of it against Biopython's QCPSuperimposer and
10101 SVDSuperimposer and against gemmi 0.7.5's superpose_positions, on the fixtures
10102 in t/data and on the NMR ensembles of PDBbind v2020.
10103  
10104 Angstrom throughout, as everything else here is.*/
10105  
10106 //which atoms take part. The option is spelled out in Perl; these are what it
10107 //comes down to here.
10108 #define RS_ALL 0 //every atom the two structures share
10109 #define RS_HEAVY 1 //all but hydrogen and deuterium
10110 #define RS_BACKBONE 2 //N CA C O of an amino acid, P O5' C5' C4' C3' O3' of a nucleotide
10111 #define RS_CA 3 //CA of an amino acid, P of a nucleotide
10112  
10113 //how the atoms of one structure are matched to the atoms of the other
10114 #define RM_KEY 0 //by chain, residue and atom name: the identity in the file
10115 #define RM_ORDER 1 //by position in the walk: the nth selected atom of each
10116  
10117 /*One atom, as the pairing sees it: three interned strings and the row the
10118 position is in.
10119  
10120 Interned rather than compared as text because the comparison happens
10121 n log n times per structure and then once more per pair of structures, and
10122 because an integer triple is a key qsort() can order without a call back into
10123 perl. The table is one per call, so two structures agree on an id exactly when
10124 they agree on the string.*/
10125 typedef struct {
10126 U32 chain;//the chain id
10127 U32 res;//the residue key: its number and insertion code, as this module files it
10128 U32 name;//the atom name
10129 UV idx;//the atom's row in its structset
10130 } rmsd_key;
10131  
10132 28727 static int rmsd_key_cmp(const void *pa, const void *pb)
10133 {
10134 /*No CSP_RESTRICT and no const on the parameters beyond what qsort asks
10135 for: the prototype is the C library's, not this file's.*/
10136 28727 const rmsd_key *a = (const rmsd_key *)pa;
10137 28727 const rmsd_key *b = (const rmsd_key *)pb;
10138 28727 ▶ if (a->chain != b->chain) return (a->chain < b->chain) ? -1 : 1;
Branch: 2 branches
BranchTrueFalseTotal
if (a->chain != b->chain) return (a->chain < b->chain) ? -1 : 1; 132 28595 28727
if (a->chain != b->chain) return (a->chain < b->chain) ? -1 : 1; 54 78 132
10139 28595 ▶ if (a->res != b->res) return (a->res < b->res) ? -1 : 1;
Branch: 2 branches
BranchTrueFalseTotal
if (a->res != b->res) return (a->res < b->res) ? -1 : 1; 10158 18437 28595
if (a->res != b->res) return (a->res < b->res) ? -1 : 1; 10158 0 10158
10140 18437 ▶ if (a->name != b->name) return (a->name < b->name) ? -1 : 1;
Branch: 2 branches
BranchTrueFalseTotal
if (a->name != b->name) return (a->name < b->name) ? -1 : 1; 18436 1 18437
if (a->name != b->name) return (a->name < b->name) ? -1 : 1; 15633 2803 18436
10141 1 return 0;
10142 }
10143  
10144 //the same order, without going through qsort's void pointers
10145 29507 static int rmsd_key_ord(const rmsd_key *CSP_RESTRICT a, const rmsd_key *CSP_RESTRICT b)
10146 {
10147 29507 ▶ if (a->chain != b->chain) return (a->chain < b->chain) ? -1 : 1;
Branch: 2 branches
BranchTrueFalseTotal
if (a->chain != b->chain) return (a->chain < b->chain) ? -1 : 1; 63 29444 29507
if (a->chain != b->chain) return (a->chain < b->chain) ? -1 : 1; 53 10 63
10148 29444 ▶ if (a->res != b->res) return (a->res < b->res) ? -1 : 1;
Branch: 2 branches
BranchTrueFalseTotal
if (a->res != b->res) return (a->res < b->res) ? -1 : 1; 2083 27361 29444
if (a->res != b->res) return (a->res < b->res) ? -1 : 1; 217 1866 2083
10149 27361 ▶ if (a->name != b->name) return (a->name < b->name) ? -1 : 1;
Branch: 2 branches
BranchTrueFalseTotal
if (a->name != b->name) return (a->name < b->name) ? -1 : 1; 17509 9852 27361
if (a->name != b->name) return (a->name < b->name) ? -1 : 1; 44 17465 17509
10150 9852 return 0;
10151 }
10152  
10153 /*rmsd_intern() -- a string to a small integer, the same integer for the same
10154 string for as long as the table lives.
10155  
10156 One table for every structure in the call, so that an id compares equal across
10157 structures. A missing or undefined field interns as 0 and so matches another
10158 missing one, which is what a blank chain id has to do: the PDB writes one as a
10159 space and mmCIF as a dot, and both come back here as the empty string.*/
10160 10634 static U32 rmsd_intern(pTHX_ HV *CSP_RESTRICT tab, SV *CSP_RESTRICT sv, U32 *CSP_RESTRICT next)
10161 {
10162 STRLEN len;
10163 const char *s;
10164 SV **slot;
10165 10634 ▶ if (!sv) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (!sv) return 0; 0 10634 10634
10166 10634 s = SvPV_const(sv, len);
10167 //hv_fetch with lval: the entry is created holding an undef SV when the
10168 //string is new, which is what tells a new id from one already given out
10169 10634 slot = hv_fetch(tab, s, (I32)len, 1);
10170 10634 ▶ if (!slot || !*slot) croak("structure_rmsd: out of memory interning an atom name");
Branch: 2 branches
BranchTrueFalseTotal
if (!slot || !*slot) croak("structure_rmsd: out of memory interning an atom name"); 10634 0 10634
if (!slot || !*slot) croak("structure_rmsd: out of memory interning an atom name"); 0 10634 10634
10171 10634 ▶ if (!SvOK(*slot)) sv_setuv(*slot, (UV)++(*next));
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(*slot)) sv_setuv(*slot, (UV)++(*next)); 1814 8820 10634
10172 10634 return (U32)SvUV(*slot);
10173 }
10174  
10175 /*rmsd_name_is() -- is this atom called that?
10176  
10177 Written out rather than strEQ because a prime in a nucleotide's atom name is
10178 written ' in a modern file and * in an old one -- O5' and O5* are the same
10179 atom, and a file old enough to use * is exactly the kind this module is asked
10180 to read. The wanted name is spelled with ' here and matches both.*/
10181 11836 static bool rmsd_name_is(const char *CSP_RESTRICT s, STRLEN len, const char *CSP_RESTRICT want)
10182 {
10183 STRLEN i;
10184 16176 ▶ for (i = 0; i < len; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < len; i++) { 15140 1036 16176
10185 15140 char c = s[i];
10186 15140 ▶ if (c == '*') c = '\'';
Branch: 1 branch
BranchTrueFalseTotal
if (c == '*') c = '\''; 120 15020 15140
10187 15140 ▶ if (want[i] == '\0' || want[i] != c) return 0;
Branch: 2 branches
BranchTrueFalseTotal
if (want[i] == '\0' || want[i] != c) return 0; 14876 264 15140
if (want[i] == '\0' || want[i] != c) return 0; 10536 4340 14876
10188 }
10189 1036 return want[len] == '\0';
10190 }
10191  
10192 /*rmsd_wanted() -- does this atom take part, under the caller's selection?
10193  
10194 RS_BACKBONE and RS_CA name atoms of a polymer, so a ligand, an ion or a water
10195 is out of both whatever it is called: a HETATM named CA is a calcium ion far
10196 more often than it is an alpha carbon, and the residue type is what tells them
10197 apart.
10198  
10199 Takes the atom hash rather than its element, because only RS_HEAVY reads one
10200 and the fetch is per atom: handed the SV instead, every selection pays for a
10201 hash lookup three of the four never look at.*/
10202 15002 static bool rmsd_wanted(pTHX_ short int sel, unsigned char rtype,
10203 const char *CSP_RESTRICT name, STRLEN nlen,
10204 HV *CSP_RESTRICT atom)
10205 {
10206 15002 ▶ if (sel == RS_ALL) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (sel == RS_ALL) return 1; 8210 6792 15002
10207 6792 ▶ if (sel == RS_HEAVY) {
Branch: 1 branch
BranchTrueFalseTotal
if (sel == RS_HEAVY) { 1780 5012 6792
10208 1780 SV *elem = hvf_sv(aTHX_ atom, "element", 7);
10209 STRLEN el;
10210 const char *e;
10211 int c;
10212 //an atom whose line was written before the element column existed, or
10213 //trimmed before it, has no element to go on and is taken as heavy:
10214 //the alternative is dropping an atom because a column is missing
10215 1780 ▶ if (!elem) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (!elem) return 1; 0 1780 1780
10216 1780 e = SvPV_const(elem, el);
10217 //both ends: this module's own readers trim the field, and a structure
10218 //assembled elsewhere can hand over the column as it stood
10219 1780 ▶ while (el && (*e == ' ' || *e == '\t')) { e++; el--; }
Branch: 3 branches
BranchTrueFalseTotal
while (el && (*e == ' ' || *e == '\t')) { e++; el--; } 1780 0 1780
while (el && (*e == ' ' || *e == '\t')) { e++; el--; } 0 1780 1780
while (el && (*e == ' ' || *e == '\t')) { e++; el--; } 0 1780 1780
10220 1780 ▶ while (el && (e[el - 1] == ' ' || e[el - 1] == '\t')) el--;
Branch: 3 branches
BranchTrueFalseTotal
while (el && (e[el - 1] == ' ' || e[el - 1] == '\t')) el--; 1780 0 1780
while (el && (e[el - 1] == ' ' || e[el - 1] == '\t')) el--; 0 1780 1780
while (el && (e[el - 1] == ' ' || e[el - 1] == '\t')) el--; 0 1780 1780
10221 1780 ▶ if (el != 1) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (el != 1) return 1; 0 1780 1780
10222 1780 ▶ c = toUPPER((unsigned char)*e);
Branch: 1 branch
BranchTrueFalseTotal
c = toUPPER((unsigned char)*e); 0 1780 1780
10223 1780 ▶ return (c != 'H' && c != 'D');
Branch: 2 branches
BranchTrueFalseTotal
return (c != 'H' && c != 'D'); 900 880 1780
return (c != 'H' && c != 'D'); 900 0 900
10224 }
10225 5012 ▶ if (rtype == RT_AA) {
Branch: 1 branch
BranchTrueFalseTotal
if (rtype == RT_AA) { 3172 1840 5012
10226 3172 ▶ if (rmsd_name_is(name, nlen, "CA")) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (rmsd_name_is(name, nlen, "CA")) return 1; 216 2956 3172
10227 2956 ▶ if (sel == RS_CA) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (sel == RS_CA) return 0; 2020 936 2956
10228 1812 ▶ return rmsd_name_is(name, nlen, "N") || rmsd_name_is(name, nlen, "C")
Branch: 1 branch
BranchTrueFalseTotal
return rmsd_name_is(name, nlen, "N") || rmsd_name_is(name, nlen, "C") 816 60 876
10229 1812 ▶ || rmsd_name_is(name, nlen, "O");
Branch: 2 branches
BranchTrueFalseTotal
|| rmsd_name_is(name, nlen, "O"); 876 60 936
|| rmsd_name_is(name, nlen, "O"); 60 756 816
10230 }
10231 1840 ▶ if (rtype == RT_NUC) {
Branch: 1 branch
BranchTrueFalseTotal
if (rtype == RT_NUC) { 1596 244 1840
10232 1596 ▶ if (rmsd_name_is(name, nlen, "P")) return 1;
Branch: 1 branch
BranchTrueFalseTotal
if (rmsd_name_is(name, nlen, "P")) return 1; 88 1508 1596
10233 1508 ▶ if (sel == RS_CA) return 0;
Branch: 1 branch
BranchTrueFalseTotal
if (sel == RS_CA) return 0; 524 984 1508
10234 1920 ▶ return rmsd_name_is(name, nlen, "O5'") || rmsd_name_is(name, nlen, "C5'")
Branch: 1 branch
BranchTrueFalseTotal
return rmsd_name_is(name, nlen, "O5'") || rmsd_name_is(name, nlen, "C5'") 888 48 936
10235 888 ▶ || rmsd_name_is(name, nlen, "C4'") || rmsd_name_is(name, nlen, "C3'")
Branch: 2 branches
BranchTrueFalseTotal
|| rmsd_name_is(name, nlen, "C4'") || rmsd_name_is(name, nlen, "C3'") 840 48 888
|| rmsd_name_is(name, nlen, "C4'") || rmsd_name_is(name, nlen, "C3'") 792 48 840
10236 1920 ▶ || rmsd_name_is(name, nlen, "O3'");
Branch: 2 branches
BranchTrueFalseTotal
|| rmsd_name_is(name, nlen, "O3'"); 936 48 984
|| rmsd_name_is(name, nlen, "O3'"); 48 744 792
10237 }
10238 244 return 0;
10239 }
10240  
10241 /*rmsd_keys() -- the selected atoms of one structure, as pairing keys.
10242  
10243 The chain id and the residue key are interned once each per chain and per
10244 residue rather than once per atom: there are a few dozen of the first and a few
10245 thousand of the second against several hundred thousand atoms, and the hash
10246 lookup is the whole cost of this walk.
10247  
10248 ids says whether the three identifiers are wanted at all. RM_ORDER pairs the
10249 nth atom with the nth atom and never compares a key, so interning for it is one
10250 hash lookup per atom spent on a number nothing reads; the fields are still
10251 written, as zero, because a structure left holding whatever Newx() found there
10252 is a trap for the next thing that sorts these. The atom's name is read either
10253 way: it is what rmsd_wanted() selects on, and an atom that has none is left out
10254 under both pairings.*/
10255 202 static UV rmsd_keys(pTHX_ const structset *CSP_RESTRICT s, HV *CSP_RESTRICT tab, U32 *CSP_RESTRICT next, short int sel, bool ids, rmsd_key *CSP_RESTRICT out){
10256 202 UV n = 0, c, r, i;
10257 414 ▶ for (c = 0; c < s->n_chain; c++) {
Branch: 1 branch
BranchTrueFalseTotal
for (c = 0; c < s->n_chain; c++) { 212 202 414
10258 212 const U32 cid = ids
10259 212 ▶ ? rmsd_intern(aTHX_ tab, hvf_sv(aTHX_ s->chain_hv[c], "id", 2), next) : 0;
Branch: 1 branch
BranchTrueFalseTotal
? rmsd_intern(aTHX_ tab, hvf_sv(aTHX_ s->chain_hv[c], "id", 2), next) : 0; 203 9 212
10260 1450 ▶ for (r = s->chain_first[c]; r < s->chain_last[c]; r++) {
Branch: 1 branch
BranchTrueFalseTotal
for (r = s->chain_first[c]; r < s->chain_last[c]; r++) { 1238 212 1450
10261 1238 const U32 rid = ids
10262 1238 ▶ ? rmsd_intern(aTHX_ tab, hvf_sv(aTHX_ s->res_hv[r], "key", 3), next) : 0;
Branch: 1 branch
BranchTrueFalseTotal
? rmsd_intern(aTHX_ tab, hvf_sv(aTHX_ s->res_hv[r], "key", 3), next) : 0; 1179 59 1238
10263 16241 ▶ for (i = s->res_first[r]; i < s->res_last[r]; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = s->res_first[r]; i < s->res_last[r]; i++) { 15003 1238 16241
10264 15003 SV *nm = hvf_sv(aTHX_ s->atom_hv[i], "name", 4);
10265 STRLEN nlen;
10266 const char *np;
10267 20171 ▶ if (!nm) continue;//an atom with no name is an atom with no identity
Branch: 1 branch
BranchTrueFalseTotal
if (!nm) continue;//an atom with no name is an atom with no identity 1 15002 15003
10268 15002 np = SvPV_const(nm, nlen);
10269 15002 ▶ if (!rmsd_wanted(aTHX_ sel, s->res_type[r], np, nlen, s->atom_hv[i]))
Branch: 1 branch
BranchTrueFalseTotal
if (!rmsd_wanted(aTHX_ sel, s->res_type[r], np, nlen, s->atom_hv[i])) 5168 9834 15002
10270 5168 continue;
10271 9834 out[n].chain = cid;
10272 9834 out[n].res = rid;
10273 9834 ▶ out[n].name = ids ? rmsd_intern(aTHX_ tab, nm, next) : 0;
Branch: 1 branch
BranchTrueFalseTotal
out[n].name = ids ? rmsd_intern(aTHX_ tab, nm, next) : 0; 9252 582 9834
10274 9834 out[n].idx = i;
10275 9834 n++;
10276 }
10277 }
10278 }
10279 202 return n;
10280 }
10281  
10282 /*rmsd_pair_by_key() -- the atoms two structures have in common, as two parallel
10283 lists of rows, by merging their sorted key lists.
10284  
10285 A key that appears more than once on either side names no single atom -- the
10286 same atom name twice in one residue, which this module's own reader cannot
10287 produce (alternate conformers of an atom are one entry with a list of
10288 conformers) but a structure assembled elsewhere can -- so the whole run is
10289 passed over rather than paired in whatever order it happens to be in.*/
10290 205 static UV rmsd_pair_by_key(const rmsd_key *CSP_RESTRICT a, UV na, const rmsd_key *CSP_RESTRICT b, UV nb, UV *CSP_RESTRICT ia, UV *CSP_RESTRICT ib){
10291 205 UV i = 0, j = 0, n = 0;
10292 10404 ▶ while (i < na && j < nb) {
Branch: 2 branches
BranchTrueFalseTotal
while (i < na && j < nb) { 10199 205 10404
while (i < na && j < nb) { 10199 0 10199
10293 10199 const int c = rmsd_key_ord(&a[i], &b[j]);
10294 10199 ▶ if (c < 0) { i++; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (c < 0) { i++; continue; } 314 9885 10199
10295 9885 ▶ if (c > 0) { j++; continue; }
Branch: 1 branch
BranchTrueFalseTotal
if (c > 0) { j++; continue; } 34 9851 9885
10296 {
10297 9851 UV i2 = i + 1, j2 = j + 1;
10298 9852 ▶ while (i2 < na && rmsd_key_ord(&a[i2], &a[i]) == 0) i2++;
Branch: 2 branches
BranchTrueFalseTotal
while (i2 < na && rmsd_key_ord(&a[i2], &a[i]) == 0) i2++; 9654 198 9852
while (i2 < na && rmsd_key_ord(&a[i2], &a[i]) == 0) i2++; 1 9653 9654
10299 9851 ▶ while (j2 < nb && rmsd_key_ord(&b[j2], &b[j]) == 0) j2++;
Branch: 2 branches
BranchTrueFalseTotal
while (j2 < nb && rmsd_key_ord(&b[j2], &b[j]) == 0) j2++; 9654 197 9851
while (j2 < nb && rmsd_key_ord(&b[j2], &b[j]) == 0) j2++; 0 9654 9654
10300 9851 ▶ if (i2 - i == 1 && j2 - j == 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (i2 - i == 1 && j2 - j == 1) { 9850 1 9851
if (i2 - i == 1 && j2 - j == 1) { 9850 0 9850
10301 9850 ia[n] = a[i].idx;
10302 9850 ib[n] = b[j].idx;
10303 9850 n++;
10304 }
10305 9851 i = i2;
10306 9851 j = j2;
10307 }
10308 }
10309 205 return n;
10310 }
10311  
10312 /*Newton-Raphson on the characteristic quartic, capped.
10313  
10314 qcprot stops at 50 iterations and at a relative change of 1e-11, and says five
10315 are enough on average. 1e-11 is a double's answer to "as close as it is worth
10316 going"; this stops at the width of an NV instead, because the whole file does,
10317 and because Newton doubles the number of correct figures every step -- the
10318 extra width costs one iteration, not a proportional number of them. Measured
10319 over every pair of models of the 40 NMR entries in the first 2,000 files of
10320 PDBbind v2020, 5,598 superpositions: a mean of 4.98 iterations and at most 9
10321 on a double or long-double perl, at most 10 on a __float128 one. The cap is
10322 qcprot's own and stands at five times the worst seen; reaching it would mean
10323 Newton had not converged, and the answer is then whatever the last iterate
10324 was, which is what qcprot does too.*/
10325 #define CSP_QCP_ITER 50
10326  
10327 /*sym4_top() -- the eigenvector of the largest eigenvalue of a symmetric 4x4, by
10328 the cyclic Jacobi method sym3_eigenvalues() uses, with the rotations gathered
10329 into the eigenvectors as they are applied. m is worked on in place. A Jacobi
10330 rotation neither knows nor cares whether an eigenvalue repeats, which is the
10331 case qcp_rotation() needs it for; the answer is then any unit vector of that
10332 eigenvalue's plane, and every one of them is as good a rotation as the others.
10333  
10334 A matrix that is zero, or already diagonal, is left alone, and the eigenvector
10335 is the axis of its largest diagonal entry -- the first axis, the identity
10336 quaternion, for the zero one. Sixty-four sweeps is a bound and not a tuning
10337 parameter: a 4x4 converges quadratically in a handful. m and out are array
10338 parameters, without CSP_RESTRICT for qcp_rotation()'s reason.*/
10339 8 static void sym4_top(NV m[4][4], NV out[4]){
10340 NV v[4][4];
10341 unsigned short sweep, p, q, k, top;
10342 40 ▶ for (p = 0; p < 4; p++)
Branch: 1 branch
BranchTrueFalseTotal
for (p = 0; p < 4; p++) 32 8 40
10343 160 ▶ for (q = 0; q < 4; q++)
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < 4; q++) 128 32 160
10344 128 ▶ v[p][q] = (p == q) ? 1.0 : 0.0;
Branch: 1 branch
BranchTrueFalseTotal
v[p][q] = (p == q) ? 1.0 : 0.0; 32 96 128
10345 16 ▶ for (sweep = 0; sweep < 64; sweep++) {
Branch: 1 branch
BranchTrueFalseTotal
for (sweep = 0; sweep < 64; sweep++) { 16 0 16
10346 16 NV off = 0.0, diag = 0.0;
10347 80 ▶ for (p = 0; p < 4; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = 0; p < 4; p++) { 64 16 80
10348 64 diag += m[p][p] * m[p][p];
10349 160 ▶ for (q = (unsigned short)(p + 1); q < 4; q++) off += m[p][q] * m[p][q];
Branch: 1 branch
BranchTrueFalseTotal
for (q = (unsigned short)(p + 1); q < 4; q++) off += m[p][q] * m[p][q]; 96 64 160
10350 }
10351 16 ▶ if (!(off > NV_EPSILON * NV_EPSILON * diag)) break;
Branch: 1 branch
BranchTrueFalseTotal
if (!(off > NV_EPSILON * NV_EPSILON * diag)) break; 8 8 16
10352 32 ▶ for (p = 0; p < 3; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = 0; p < 3; p++) { 24 8 32
10353 72 ▶ for (q = (unsigned short)(p + 1); q < 4; q++) {
Branch: 1 branch
BranchTrueFalseTotal
for (q = (unsigned short)(p + 1); q < 4; q++) { 48 24 72
10354 48 const NV apq = m[p][q];
10355 NV theta, th2, t, c, sn;
10356 48 ▶ if (!(nv_fabs(apq) > 0.0)) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (!(nv_fabs(apq) > 0.0)) continue; 24 24 48
10357 24 theta = (m[q][q] - m[p][p]) / (2.0 * apq);
10358 24 th2 = theta * theta;
10359 //the smaller root, as in sym3_eigenvalues(); 1/(2 theta) is its
10360 //limit where theta squared would overflow
10361 24 t = nv_is_finite(th2)
10362 24 ▶ ? (theta >= 0.0 ? 1.0 : -1.0) / (nv_fabs(theta) + nv_sqrt(1.0 + th2))
Branch: 1 branch
BranchTrueFalseTotal
? (theta >= 0.0 ? 1.0 : -1.0) / (nv_fabs(theta) + nv_sqrt(1.0 + th2)) 16 8 24
10363 48 ▶ : 0.5 / theta;
Branch: 1 branch
BranchTrueFalseTotal
: 0.5 / theta; 24 0 24
10364 24 c = 1.0 / nv_sqrt(1.0 + t * t);
10365 24 sn = t * c;
10366 120 ▶ for (k = 0; k < 4; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < 4; k++) { 96 24 120
10367 96 const NV mkp = m[k][p], mkq = m[k][q];
10368 96 m[k][p] = c * mkp - sn * mkq;
10369 96 m[k][q] = sn * mkp + c * mkq;
10370 }
10371 120 ▶ for (k = 0; k < 4; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < 4; k++) { 96 24 120
10372 96 const NV mpk = m[p][k], mqk = m[q][k];
10373 96 m[p][k] = c * mpk - sn * mqk;
10374 96 m[q][k] = sn * mpk + c * mqk;
10375 }
10376 120 ▶ for (k = 0; k < 4; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < 4; k++) { 96 24 120
10377 96 const NV vkp = v[k][p], vkq = v[k][q];
10378 96 v[k][p] = c * vkp - sn * vkq;
10379 96 v[k][q] = sn * vkp + c * vkq;
10380 }
10381 }
10382 }
10383 }
10384 8 top = 0;
10385 32 ▶ for (k = 1; k < 4; k++) if (m[k][k] > m[top][top]) top = k;
Branch: 2 branches
BranchTrueFalseTotal
for (k = 1; k < 4; k++) if (m[k][k] > m[top][top]) top = k; 4 20 24
for (k = 1; k < 4; k++) if (m[k][k] > m[top][top]) top = k; 24 8 32
10386 40 ▶ for (k = 0; k < 4; k++) out[k] = v[k][top];
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < 4; k++) out[k] = v[k][top]; 32 8 40
10387 8 }
10388  
10389 /*quat_rot() -- the rotation a quaternion stands for, normalised first, in the
10390 column-vector convention qcp_rotation() returns; the arithmetic is Biopython
10391 1.85's qcprot.py, transposed. Array parameters, so no CSP_RESTRICT, for
10392 qcp_rotation()'s reason.*/
10393 188 static void quat_rot(const NV qv[4], NV rot[3][3]){
10394 188 const NV qn = nv_sqrt(qv[0] * qv[0] + qv[1] * qv[1] + qv[2] * qv[2] + qv[3] * qv[3]);
10395 188 const NV q1 = qv[0] / qn, q2 = qv[1] / qn, q3 = qv[2] / qn, q4 = qv[3] / qn;
10396 188 const NV a2 = q1 * q1, x2 = q2 * q2, y2 = q3 * q3, z2 = q4 * q4;
10397 188 const NV xy = q2 * q3, az = q1 * q4, zx = q4 * q2;
10398 188 const NV ay = q1 * q3, yz = q3 * q4, ax = q1 * q2;
10399 188 rot[0][0] = a2 + x2 - y2 - z2;
10400 188 rot[1][0] = 2.0 * (xy + az);
10401 188 rot[2][0] = 2.0 * (zx - ay);
10402 188 rot[0][1] = 2.0 * (xy - az);
10403 188 rot[1][1] = a2 - x2 + y2 - z2;
10404 188 rot[2][1] = 2.0 * (yz + ax);
10405 188 rot[0][2] = 2.0 * (zx + ay);
10406 188 rot[1][2] = 2.0 * (yz - ax);
10407 188 rot[2][2] = a2 - x2 - y2 + z2;
10408 188 }
10409  
10410 /*qcp_rotation() -- the rotation that best superposes one centred point set on
10411 another, from the inner-product matrix of the two.
10412  
10413 s[p][q] is the sum over paired atoms of a[p] * b[q], both centred, where a is
10414 the set being moved and b the set it is moved onto; e0 is half the sum of the
10415 two sets' squared radii. Those are the only things about the atoms this needs,
10416 which is what makes the method fast: everything below is a fixed amount of
10417 arithmetic on nine numbers, however many atoms they came from.
10418  
10419 Transcribed from Bio/PDB/qcprot.py of Biopython 1.85, which is the qcprot.c of
10420 Liu, Agrafiotis and Theobald (2010) with the point sets swapped so that the
10421 first argument is the reference; the variable names are theirs. Two things are
10422 deliberately not theirs:
10423  
10424 The RMSD is not taken from the eigenvalue. sqrt(2|E0 - L|/n) is the point of
10425 the method -- it never forms the rotation at all -- and it is a subtraction of
10426 two numbers that agree in as many figures as the two structures do: at an RMSD
10427 of 1e-4 A over a few thousand atoms, E0 and L agree in ten of a double's
10428 sixteen and the answer keeps six of them. A caller here can ask for the
10429 rotation anyway, so the deviation is measured with it instead -- rotate,
10430 subtract, square, sum -- which is one more pass over the paired atoms, has no
10431 cancellation anywhere in it (every term is a square), and is the same quantity
10432 Biopython's SVDSuperimposer and gemmi's superpose_positions report. So this
10433 function returns the rotation and rmsd_measure() below returns the number.
10434  
10435 Which row of cofactors the quaternion comes from is not theirs either. The
10436 4x4 key matrix less its largest eigenvalue is singular and symmetric, so its
10437 adjugate is v.v' for the eigenvector v and every row of it is a multiple of v;
10438 qcprot tries four of them in turn and takes the first whose squared length
10439 clears 1e-6, which is an absolute threshold on a quantity that scales as the
10440 sixth power of the coordinates -- what it means for a tetrapeptide and what it
10441 means for a ribosome are different things. All four are computed here and the
10442 longest is taken, which is the same vector whenever qcprot finds one and needs
10443 no threshold to choose. Only "all four are too short to trust" is left to
10444 decide, and that one is scaled; what is done then is argued where it is done.
10445  
10446 Returns the rotation as rot[p][q] with b = rot . a, the column-vector
10447 convention -- the transpose of the one Biopython applies as coords.dot(rot).
10448  
10449 No CSP_RESTRICT and no const on the two matrices, which is the one place in
10450 this file a pointer parameter goes without: they are array parameters, and the
10451 portable spelling of the qualifier on one of those is C99's `NV s[restrict
10452 3][3]', which the pre-C99 fallbacks the macro exists for do not take. They are
10453 two distinct locals of rmsd_measure() and nothing else can reach them.*/
10454 188 static void qcp_rotation(NV s[3][3], NV e0, NV rot[3][3]){
10455 188 const NV Sxx = s[0][0], Sxy = s[0][1], Sxz = s[0][2];
10456 188 const NV Syx = s[1][0], Syy = s[1][1], Syz = s[1][2];
10457 188 const NV Szx = s[2][0], Szy = s[2][1], Szz = s[2][2];
10458 188 const NV Sxx2 = Sxx * Sxx, Syy2 = Syy * Syy, Szz2 = Szz * Szz;
10459 188 const NV Sxy2 = Sxy * Sxy, Syz2 = Syz * Syz, Sxz2 = Sxz * Sxz;
10460 188 const NV Syx2 = Syx * Syx, Szy2 = Szy * Szy, Szx2 = Szx * Szx;
10461 188 const NV SyzSzymSyySzz2 = 2.0 * (Syz * Szy - Syy * Szz);
10462 188 const NV Sxx2Syy2Szz2Syz2Szy2 = Syy2 + Szz2 - Sxx2 + Syz2 + Szy2;
10463 188 const NV c2 = -2.0 * (Sxx2 + Syy2 + Szz2 + Sxy2 + Syx2 + Sxz2 + Szx2 + Syz2 + Szy2);
10464 188 const NV c1 = 8.0 * (Sxx * Syz * Szy + Syy * Szx * Sxz + Szz * Sxy * Syx
10465 188 - Sxx * Syy * Szz - Syz * Szx * Sxy - Szy * Syx * Sxz);
10466 188 const NV SxzpSzx = Sxz + Szx, SyzpSzy = Syz + Szy, SxypSyx = Sxy + Syx;
10467 188 const NV SyzmSzy = Syz - Szy, SxzmSzx = Sxz - Szx, SxymSyx = Sxy - Syx;
10468 188 const NV SxxpSyy = Sxx + Syy, SxxmSyy = Sxx - Syy;
10469 188 const NV Sxy2Sxz2Syx2Szx2 = Sxy2 + Sxz2 - Syx2 - Szx2;
10470 188 const NV SxxpSyy_p_Szz = SxxpSyy + Szz;
10471 188 const NV c0 = Sxy2Sxz2Syx2Szx2 * Sxy2Sxz2Syx2Szx2
10472 188 + (Sxx2Syy2Szz2Syz2Szy2 + SyzSzymSyySzz2) * (Sxx2Syy2Szz2Syz2Szy2 - SyzSzymSyySzz2)
10473 188 + (-SxzpSzx * SyzmSzy + SxymSyx * (SxxmSyy - Szz))
10474 188 * (-SxzmSzx * SyzpSzy + SxymSyx * (SxxmSyy + Szz))
10475 188 + (-SxzpSzx * SyzpSzy - SxypSyx * (SxxpSyy - Szz))
10476 188 * (-SxzmSzx * SyzmSzy - SxypSyx * SxxpSyy_p_Szz)
10477 188 + (SxypSyx * SyzpSzy + SxzpSzx * (SxxmSyy + Szz))
10478 188 * (-SxymSyx * SyzmSzy + SxzpSzx * SxxpSyy_p_Szz)
10479 188 + (SxypSyx * SyzmSzy + SxzmSzx * (SxxmSyy - Szz))
10480 188 * (-SxymSyx * SyzpSzy + SxzmSzx * (SxxpSyy - Szz));
10481 /*f(x) = x^4 + c2 x^2 + c1 x + c0, eq. 8 of Theobald (2005), whose largest
10482 root is the maximum of the rotation's trace and lies just below E0.*/
10483 188 NV lambda = e0;
10484 NV a11, a12, a13, a14, a21, a22, a23, a24;
10485 NV a31, a32, a33, a34, a41, a42, a43, a44;
10486 NV a3344_4334, a3244_4234, a3243_4233, a3143_4133, a3144_4134, a3142_4132;
10487 NV q[4][4], qsqr[4], best, scale;
10488 unsigned short it, k, kbest;
10489  
10490 1076 ▶ for (it = 0; it < CSP_QCP_ITER; it++) {
Branch: 1 branch
BranchTrueFalseTotal
for (it = 0; it < CSP_QCP_ITER; it++) { 1074 2 1076
10491 1074 const NV old = lambda;
10492 1074 const NV l2 = lambda * lambda;
10493 1074 const NV b = (l2 + c2) * lambda;
10494 1074 const NV a = b + c1;
10495 1074 const NV f = a * lambda + c0;
10496 1074 const NV fp = 2.0 * l2 * lambda + b + a;
10497 NV delta;
10498 1074 ▶ if (!(nv_fabs(fp) > 0.0)) break;//a stationary point: Newton has nothing to follow
Branch: 1 branch
BranchTrueFalseTotal
if (!(nv_fabs(fp) > 0.0)) break;//a stationary point: Newton has nothing to follow 4 1070 1074
10499 1070 delta = f / fp;
10500 1070 lambda = nv_fabs(lambda - delta);
10501 1070 ▶ if (nv_fabs(lambda - old) <= 4.0 * NV_EPSILON * nv_fabs(lambda)) break;
Branch: 1 branch
BranchTrueFalseTotal
if (nv_fabs(lambda - old) <= 4.0 * NV_EPSILON * nv_fabs(lambda)) break; 182 888 1070
10502 }
10503  
10504 188 a11 = SxxpSyy + Szz - lambda; a12 = SyzmSzy; a13 = -SxzmSzx; a14 = SxymSyx;
10505 188 a21 = a12; a22 = SxxmSyy - Szz - lambda; a23 = SxypSyx; a24 = SxzpSzx;
10506 188 a31 = a13; a32 = a23; a33 = Syy - Sxx - Szz - lambda; a34 = SyzpSzy;
10507 188 a41 = a14; a42 = a24; a43 = a34; a44 = Szz - SxxpSyy - lambda;
10508 188 a3344_4334 = a33 * a44 - a43 * a34;
10509 188 a3244_4234 = a32 * a44 - a42 * a34;
10510 188 a3243_4233 = a32 * a43 - a42 * a33;
10511 188 a3143_4133 = a31 * a43 - a41 * a33;
10512 188 a3144_4134 = a31 * a44 - a41 * a34;
10513 188 a3142_4132 = a31 * a42 - a41 * a32;
10514 188 q[0][0] = a22 * a3344_4334 - a23 * a3244_4234 + a24 * a3243_4233;
10515 188 q[0][1] = -a21 * a3344_4334 + a23 * a3144_4134 - a24 * a3143_4133;
10516 188 q[0][2] = a21 * a3244_4234 - a22 * a3144_4134 + a24 * a3142_4132;
10517 188 q[0][3] = -a21 * a3243_4233 + a22 * a3143_4133 - a23 * a3142_4132;
10518 188 q[1][0] = a12 * a3344_4334 - a13 * a3244_4234 + a14 * a3243_4233;
10519 188 q[1][1] = -a11 * a3344_4334 + a13 * a3144_4134 - a14 * a3143_4133;
10520 188 q[1][2] = a11 * a3244_4234 - a12 * a3144_4134 + a14 * a3142_4132;
10521 188 q[1][3] = -a11 * a3243_4233 + a12 * a3143_4133 - a13 * a3142_4132;
10522 {
10523 188 const NV a1324_1423 = a13 * a24 - a14 * a23;
10524 188 const NV a1224_1422 = a12 * a24 - a14 * a22;
10525 188 const NV a1223_1322 = a12 * a23 - a13 * a22;
10526 188 const NV a1124_1421 = a11 * a24 - a14 * a21;
10527 188 const NV a1123_1321 = a11 * a23 - a13 * a21;
10528 188 const NV a1122_1221 = a11 * a22 - a12 * a21;
10529 188 q[2][0] = a42 * a1324_1423 - a43 * a1224_1422 + a44 * a1223_1322;
10530 188 q[2][1] = -a41 * a1324_1423 + a43 * a1124_1421 - a44 * a1123_1321;
10531 188 q[2][2] = a41 * a1224_1422 - a42 * a1124_1421 + a44 * a1122_1221;
10532 188 q[2][3] = -a41 * a1223_1322 + a42 * a1123_1321 - a43 * a1122_1221;
10533 188 q[3][0] = a32 * a1324_1423 - a33 * a1224_1422 + a34 * a1223_1322;
10534 188 q[3][1] = -a31 * a1324_1423 + a33 * a1124_1421 - a34 * a1123_1321;
10535 188 q[3][2] = a31 * a1224_1422 - a32 * a1124_1421 + a34 * a1122_1221;
10536 188 q[3][3] = -a31 * a1223_1322 + a32 * a1123_1321 - a33 * a1122_1221;
10537 }
10538 188 kbest = 0;
10539 188 best = -1.0;
10540 940 ▶ for (k = 0; k < 4; k++) {
Branch: 1 branch
BranchTrueFalseTotal
for (k = 0; k < 4; k++) { 752 188 940
10541 752 qsqr[k] = q[k][0] * q[k][0] + q[k][1] * q[k][1] + q[k][2] * q[k][2] + q[k][3] * q[k][3];
10542 752 ▶ if (qsqr[k] > best) { best = qsqr[k]; kbest = k; }
Branch: 1 branch
BranchTrueFalseTotal
if (qsqr[k] > best) { best = qsqr[k]; kbest = k; } 188 564 752
10543 }
10544 /*How long the longest row is, against the size of a row's entries. Each
10545 cofactor is a 3x3 determinant of a[][] entries, so it scales as the cube of
10546 the largest of them and its square as the sixth power.
10547  
10548 A short row is a row that has lost its figures. The rows vanish together
10549 when the largest eigenvalue of the key matrix is a repeated one, which is
10550 not only the zero matrix of one paired atom or of atoms all at one point,
10551 but every set of points on one line: it can be turned about the line
10552 freely, there is a plane of eigenvectors, and no row picks one out. qcprot
10553 survives that by never forming the rotation; this module measures with the
10554 rotation, and took the identity there, which for three carbons along x
10555 against the same three along y answered 1.732 A where Biopython 1.85's
10556 SVDSuperimposer and QCPSuperimposer both say 0. So below a length the
10557 eigenvector is found directly instead, by sym4_top(), whose Jacobi
10558 rotations do not care whether the eigenvalue repeats.
10559  
10560 The length is the row's against the cofactors' scale, a fraction that says
10561 how nearly the largest eigenvalue repeats -- a property of the shape and not
10562 of the NV, which is why the bound is a fixed fraction and not a multiple of
10563 NV_EPSILON. It was the square root of NV_EPSILON at first, which let a row
10564 lose half its figures before it was refused: eight on a double, and nine and
10565 a half on a long double, where a line bent by 0.0002 A kept its row and came
10566 out 1.6e-11 A from itself instead of 0. Measured with the row's length
10567 printed, over 5,876 superpositions of the models of t/data/ensemble.pdb and
10568 of 1h0t, 1jm4, 2l6j and 2ll7 (PDBbind v2020), each with every selection,
10569 the first percentile is 0.35 and nothing that is not three atoms on a line
10570 falls under 0.01; the bent line is 9e-9 and three carbons on a line 1e-13.
10571 1e-4 is two decades under every real structure and four over the line, and
10572 a row that long has lost at most four of its figures. Every ordinary
10573 structure takes the path argued for above, bit for bit as it did.*/
10574 188 scale = nv_fabs(a11);
10575 {
10576 //the ten distinct entries of a symmetric 4x4
10577 188 const NV cand[9] = { nv_fabs(a22), nv_fabs(a33), nv_fabs(a44),
10578 188 nv_fabs(a12), nv_fabs(a13), nv_fabs(a14),
10579 188 nv_fabs(a23), nv_fabs(a24), nv_fabs(a34) };
10580 1880 ▶ for (k = 0; k < 9; k++) if (cand[k] > scale) scale = cand[k];
Branch: 2 branches
BranchTrueFalseTotal
for (k = 0; k < 9; k++) if (cand[k] > scale) scale = cand[k]; 376 1316 1692
for (k = 0; k < 9; k++) if (cand[k] > scale) scale = cand[k]; 1692 188 1880
10581 }
10582 188 scale = scale * scale * scale;
10583 188 ▶ if (!(best > (1e-4 * scale) * (1e-4 * scale))) {
Branch: 1 branch
BranchTrueFalseTotal
if (!(best > (1e-4 * scale) * (1e-4 * scale))) { 8 180 188
10584 NV m[4][4], qj[4];
10585 8 m[0][0] = a11; m[0][1] = a12; m[0][2] = a13; m[0][3] = a14;
10586 8 m[1][0] = a21; m[1][1] = a22; m[1][2] = a23; m[1][3] = a24;
10587 8 m[2][0] = a31; m[2][1] = a32; m[2][2] = a33; m[2][3] = a34;
10588 8 m[3][0] = a41; m[3][1] = a42; m[3][2] = a43; m[3][3] = a44;
10589 8 sym4_top(m, qj);
10590 8 quat_rot(qj, rot);
10591 8 return;
10592 }
10593 //transposed against Biopython's, which multiplies a row vector on the right
10594 180 quat_rot(q[kbest], rot);
10595 }
10596  
10597 /*rmsd_measure() -- the deviation of one paired set of atoms from the other.
10598  
10599 Three passes over the pairs: the two centroids, the inner-product matrix, and
10600 the deviation itself. Without a fit there is one pass and no centroid: an
10601 in-place RMSD is asked about two structures already in the same frame -- two
10602 models of an ensemble, a minimised copy against what went into the minimiser --
10603 and moving one of them onto the other is exactly what the question was not.
10604  
10605 The sums are ordinary running sums. Every term of the last one is a square, so
10606 the relative error of the total is bounded by n * NV_EPSILON and there is no
10607 cancellation anywhere in it to make that worse. At the largest structure in
10608 PDBbind v2020 -- 4fqr, 90,792 atoms, which is more than any pairing here will
10609 have -- that bound is 2e-11 on a double perl, eight figures below the 0.001 A
10610 a PDB coordinate is written to.
10611  
10612 rot and tran come back as b = rot . a + tran, which is the move that puts the
10613 first structure on the second; both are the identity when there was no fit.
10614 Unqualified, for the reason qcp_rotation() gives: they are array parameters and
10615 the qualifier has no portable spelling on one.*/
10616 193 static NV rmsd_measure(const structset *CSP_RESTRICT A, const structset *CSP_RESTRICT B, const UV *CSP_RESTRICT ia, const UV *CSP_RESTRICT ib, UV n, bool fit, NV rot[3][3], NV tran[3]){
10617 193 NV acx = 0.0, acy = 0.0, acz = 0.0, bcx = 0.0, bcy = 0.0, bcz = 0.0, sum = 0.0;
10618 UV i;
10619 193 Zero(rot, 1, NV[3][3]);
10620 193 rot[0][0] = rot[1][1] = rot[2][2] = 1.0;
10621 193 Zero(tran, 3, NV);
10622 /*after the identity, which is what n == 0 owes the caller too. Returning
10623 before it, as 7c498ea did, also failed seven of t/rmsd.t's exactly-zero
10624 answers on perlbrew's 5.44.0-i686: the x87 build of the reordered function
10625 kept other intermediates at 80 bits.*/
10626 193 ▶ if (n == 0) return 0.0;
Branch: 1 branch
BranchTrueFalseTotal
if (n == 0) return 0.0; 0 193 193
10627 193 ▶ if (fit) {
Branch: 1 branch
BranchTrueFalseTotal
if (fit) { 188 5 193
10628 188 NV s[3][3], e0 = 0.0;
10629 10410 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 10222 188 10410
10630 10222 acx += A->x[ia[i]]; acy += A->y[ia[i]]; acz += A->z[ia[i]];
10631 10222 bcx += B->x[ib[i]]; bcy += B->y[ib[i]]; bcz += B->z[ib[i]];
10632 }
10633 188 acx /= (NV)n; acy /= (NV)n; acz /= (NV)n;
10634 188 bcx /= (NV)n; bcy /= (NV)n; bcz /= (NV)n;
10635 188 Zero(s, 1, NV[3][3]);
10636 10410 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 10222 188 10410
10637 10222 const NV ax = A->x[ia[i]] - acx, ay = A->y[ia[i]] - acy, az = A->z[ia[i]] - acz;
10638 10222 const NV bx = B->x[ib[i]] - bcx, by = B->y[ib[i]] - bcy, bz = B->z[ib[i]] - bcz;
10639 10222 s[0][0] += ax * bx; s[0][1] += ax * by; s[0][2] += ax * bz;
10640 10222 s[1][0] += ay * bx; s[1][1] += ay * by; s[1][2] += ay * bz;
10641 10222 s[2][0] += az * bx; s[2][1] += az * by; s[2][2] += az * bz;
10642 10222 e0 += ax * ax + ay * ay + az * az + bx * bx + by * by + bz * bz;
10643 }
10644 188 qcp_rotation(s, e0 * 0.5, rot);
10645 //b = rot . a + tran, with the two centroids fixing tran
10646 {
10647 188 const NV ac[3] = { acx, acy, acz };
10648 188 const NV bc[3] = { bcx, bcy, bcz };
10649 752 ▶ for (unsigned short p = 0; p < 3; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short p = 0; p < 3; p++) { 564 188 752
10650 564 NV t = bc[p];
10651 2256 ▶ for (unsigned short q = 0; q < 3; q++) t -= rot[p][q] * ac[q];
Branch: 1 branch
BranchTrueFalseTotal
for (unsigned short q = 0; q < 3; q++) t -= rot[p][q] * ac[q]; 1692 564 2256
10652 564 tran[p] = t;
10653 }
10654 }
10655 }
10656  
10657 10552 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 10359 193 10552
10658 10359 const NV ax = A->x[ia[i]], ay = A->y[ia[i]], az = A->z[ia[i]];
10659 10359 const NV dx = rot[0][0] * ax + rot[0][1] * ay + rot[0][2] * az + tran[0] - B->x[ib[i]];
10660 10359 const NV dy = rot[1][0] * ax + rot[1][1] * ay + rot[1][2] * az + tran[1] - B->y[ib[i]];
10661 10359 const NV dz = rot[2][0] * ax + rot[2][1] * ay + rot[2][2] * az + tran[2] - B->z[ib[i]];
10662 10359 sum += dx * dx + dy * dy + dz * dz;
10663 }
10664 193 return nv_sqrt(sum / (NV)n);
10665 }
10666  
10667 /*Everything one call to structure_rmsd() allocates, so that a croak anywhere
10668 in the middle of it gives all of it back. Zeroed before the destructor is
10669 registered, and Safefree() of a null pointer is a no-op, so a croak between any
10670 two of the allocations below is safe.*/
10671 typedef struct {
10672 structset *set;
10673 rmsd_key **key;
10674 UV *nkey, n_set, *ia, *ib;
10675 //each structure's row of the RMSD and count matrices, borrowed: the AVs
10676 //belong to the matrices, and only these two arrays of pointers are ours
10677 AV **mrow, **crow;
10678 } rmsd_work;
10679  
10680 74 static void rmsd_work_free(pTHX_ rmsd_work *CSP_RESTRICT w){
10681 UV i;
10682 279 ▶ if (w->set) for (i = 0; i < w->n_set; i++) set_free(aTHX_ &w->set[i]);
Branch: 2 branches
BranchTrueFalseTotal
if (w->set) for (i = 0; i < w->n_set; i++) set_free(aTHX_ &w->set[i]); 74 0 74
if (w->set) for (i = 0; i < w->n_set; i++) set_free(aTHX_ &w->set[i]); 205 74 279
10683 279 ▶ if (w->key) for (i = 0; i < w->n_set; i++) Safefree(w->key[i]);
Branch: 2 branches
BranchTrueFalseTotal
if (w->key) for (i = 0; i < w->n_set; i++) Safefree(w->key[i]); 74 0 74
if (w->key) for (i = 0; i < w->n_set; i++) Safefree(w->key[i]); 205 74 279
10684 74 Safefree(w->set); Safefree(w->key); Safefree(w->nkey); Safefree(w->ia); Safefree(w->ib); Safefree(w->mrow); Safefree(w->crow);
10685 74 Zero(w, 1, rmsd_work);
10686 74 }
10687  
10688 /*No CSP_RESTRICT on the parameter: the prototype is SAVEDESTRUCTOR_X's, not
10689 this file's.*/
10690 74 static void rmsd_work_free_cb(pTHX_ void *p){
10691 74 rmsd_work_free(aTHX_ (rmsd_work *)p);
10692 74 }
10693  
10694 /*An option that is one of a few words, as the index of the word: the tables
10695 below are in the order of the RS_* and RM_* values, which is what makes the
10696 index the value.
10697  
10698 Perl has already checked these -- this is the backstop for a caller who reaches
10699 _rmsd() directly -- so the message only has to be true, not helpful.*/
10700 156 static short int rmsd_word(pTHX_ HV *CSP_RESTRICT o, const char *CSP_RESTRICT k, const char *const *CSP_RESTRICT words, const char *CSP_RESTRICT list, short int dflt,const char *CSP_RESTRICT who){
10701 156 SV *v = opt_get(aTHX_ o, k);
10702 156 ▶ if (!v) return dflt;
Branch: 1 branch
BranchTrueFalseTotal
if (!v) return dflt; 14 142 156
10703 343 ▶ for (unsigned short i = 0; words[i]; i++) if (strEQ(SvPV_nolen(v), words[i])) return i;
Branch: 2 branches
BranchTrueFalseTotal
for (unsigned short i = 0; words[i]; i++) if (strEQ(SvPV_nolen(v), words[i])) return i; 139 62 201
for (unsigned short i = 0; words[i]; i++) if (strEQ(SvPV_nolen(v), words[i])) return i; 201 3 204
10704 3 croak("%s: %s must be %s, not '%s'", who, k, list, SvPV_nolen(v));
10705 }
10706  
10707 /*rmsd_do() -- the RMSD of every pair of a list of structures.
10708  
10709 Each element of sets is a hash with chains and chain_order in it, which is an
10710 $info, or one model of an $info read with model => 'all': the same shape, which
10711 is why an ensemble costs nothing extra here. Perl has already made the list
10712 and knows what to call each of them; this returns the numbers.
10713  
10714 One set_build() per structure and not one per pair: the walk is the expensive
10715 part -- it is the thing notes.txt says not to do twice -- and twenty models
10716 make a hundred and ninety pairs out of twenty walks. Same for the key lists,
10717 which are built and sorted once each and merged pairwise.*/
10718 79 static HV *rmsd_do(pTHX_ AV *CSP_RESTRICT sets, HV *CSP_RESTRICT o, const char *CSP_RESTRICT who){
10719 //in RS_* order and in RM_* order: rmsd_word() returns the index
10720 static const char *const sel_words[] = { "all", "heavy", "backbone", "ca", NULL };
10721 static const char *const match_words[] = { "key", "order", NULL };
10722 79 const short int sel = rmsd_word(aTHX_ o, "select", sel_words, "'all', 'heavy', 'backbone' or 'ca'", RS_ALL, who);
10723 77 const short int match = rmsd_word(aTHX_ o, "match", match_words, "'key' or 'order'", RM_KEY, who);
10724 76 const bool fit = opt_bool(aTHX_ o, "fit", TRUE);
10725 76 const bool want_transform = opt_bool(aTHX_ o, "transform", FALSE);
10726 76 const IV min_atoms = opt_iv(aTHX_ o, "min_atoms", 3);
10727 76 const SSize_t nsv = av_len(sets) + 1;
10728 HV *tab;
10729 76 U32 next = 0;
10730 76 UV nmax = 0;
10731 rmsd_work w;
10732 HV *out;
10733 AV *mat, *cnt, *sizes;
10734 //the move that puts the first structure on the second, when it was asked
10735 //for; there is only one pair to ask it of, and Perl only asks then
10736 76 AV *rotation = NULL, *translation = NULL;
10737 SSize_t si, sj;
10738 UV i;
10739  
10740 76 ▶ if (min_atoms < 1) croak("%s: min_atoms must be at least 1", who);
Branch: 1 branch
BranchTrueFalseTotal
if (min_atoms < 1) croak("%s: min_atoms must be at least 1", who); 1 75 76
10741 75 ▶ if (nsv < 2) croak("%s: nothing to compare", who);
Branch: 1 branch
BranchTrueFalseTotal
if (nsv < 2) croak("%s: nothing to compare", who); 1 74 75
10742  
10743 74 ENTER;
10744 74 Zero(&w, 1, rmsd_work);
10745 74 SAVEDESTRUCTOR_X(rmsd_work_free_cb, &w);
10746 74 ▶ Newxz(w.set, (UV)nsv, structset);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(w.set, (UV)nsv, structset); 0 74 74
10747 74 ▶ Newxz(w.key, (UV)nsv, rmsd_key *);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(w.key, (UV)nsv, rmsd_key *); 0 74 74
10748 74 ▶ Newxz(w.nkey, (UV)nsv, UV);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(w.nkey, (UV)nsv, UV); 0 74 74
10749 74 ▶ Newxz(w.mrow, (UV)nsv, AV *);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(w.mrow, (UV)nsv, AV *); 0 74 74
10750 74 ▶ Newxz(w.crow, (UV)nsv, AV *);
Branch: 1 branch
BranchTrueFalseTotal
Newxz(w.crow, (UV)nsv, AV *); 0 74 74
10751 74 w.n_set = (UV)nsv;
10752  
10753 //the intern table, mortal so that a croak below does not keep it
10754 74 tab = newHV();
10755 74 sv_2mortal((SV *)tab);
10756  
10757 276 ▶ for (si = 0; si < nsv; si++) {
Branch: 1 branch
BranchTrueFalseTotal
for (si = 0; si < nsv; si++) { 204 72 276
10758 204 SV **e = av_fetch(sets, si, 0);
10759 204 ▶ if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV)
Branch: 4 branches
BranchTrueFalseTotal
if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) 204 0 204
if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) 204 0 204
if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) 203 1 204
if (!e || !*e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) 0 203 203
10760 1 croak("%s: structure %" IVdf " is not a hash reference", who, (IV)(si + 1));
10761 //positions only: the pairing reads names out of the atom hashes and
10762 //the measurement reads x, y and z, and nothing here asks what an atom
10763 //weighs or how big it is
10764 203 set_build(aTHX_ (HV *)SvRV(*e), &w.set[si], 0.0, TRUE, who);
10765 202 ▶ Newx(w.key[si], w.set[si].n_atom ? w.set[si].n_atom : 1, rmsd_key);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.key[si], w.set[si].n_atom ? w.set[si].n_atom : 1, rmsd_key); 199 3 202
Newx(w.key[si], w.set[si].n_atom ? w.set[si].n_atom : 1, rmsd_key); 0 199 199
Newx(w.key[si], w.set[si].n_atom ? w.set[si].n_atom : 1, rmsd_key); 199 3 202
10766 404 w.nkey[si] = rmsd_keys(aTHX_ &w.set[si], tab, &next, sel,
10767 202 match == RM_KEY, w.key[si]);
10768 /*sized from the atom count because the selection is not known until
10769 the walk has been made; given back before the next structure's is taken,
10770 since select => 'ca' keeps one atom in eight and the lists of every
10771 structure in the call are alive at once*/
10772 202 ▶ if (w.nkey[si] > 0 && w.nkey[si] < w.set[si].n_atom)
Branch: 2 branches
BranchTrueFalseTotal
if (w.nkey[si] > 0 && w.nkey[si] < w.set[si].n_atom) 199 3 202
if (w.nkey[si] > 0 && w.nkey[si] < w.set[si].n_atom) 73 126 199
10773 73 ▶ Renew(w.key[si], w.nkey[si], rmsd_key);
Branch: 1 branch
BranchTrueFalseTotal
Renew(w.key[si], w.nkey[si], rmsd_key); 0 73 73
10774 202 ▶ if (match == RM_KEY && w.nkey[si] > 1)
Branch: 2 branches
BranchTrueFalseTotal
if (match == RM_KEY && w.nkey[si] > 1) 194 8 202
if (match == RM_KEY && w.nkey[si] > 1) 187 7 194
10775 187 qsort(w.key[si], (size_t)w.nkey[si], sizeof(rmsd_key), rmsd_key_cmp);
10776 202 ▶ if (w.nkey[si] > nmax) nmax = w.nkey[si];
Branch: 1 branch
BranchTrueFalseTotal
if (w.nkey[si] > nmax) nmax = w.nkey[si]; 73 129 202
10777 }
10778 72 ▶ Newx(w.ia, nmax ? nmax : 1, UV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.ia, nmax ? nmax : 1, UV); 71 1 72
Newx(w.ia, nmax ? nmax : 1, UV); 0 71 71
Newx(w.ia, nmax ? nmax : 1, UV); 71 1 72
10779 72 ▶ Newx(w.ib, nmax ? nmax : 1, UV);
Branch: 3 branches
BranchTrueFalseTotal
Newx(w.ib, nmax ? nmax : 1, UV); 71 1 72
Newx(w.ib, nmax ? nmax : 1, UV); 0 71 71
Newx(w.ib, nmax ? nmax : 1, UV); 71 1 72
10780  
10781 72 mat = newAV();
10782 72 cnt = newAV();
10783 72 sizes = newAV();
10784 72 sv_2mortal((SV *)mat);
10785 72 sv_2mortal((SV *)cnt);
10786 72 sv_2mortal((SV *)sizes);
10787 /*Both matrices are given their full length up front and filled in below.
10788 A cell of the count matrix is always written; a cell of the RMSD matrix is
10789 written only where there was an RMSD to write, and the ones that are not
10790 are the pairs with too few atoms in common -- which is undef, which is what
10791 a slot nobody stored into reads back as. The rows are kept in w as they
10792 are made, rather than fetched back out of the matrices, so that nothing
10793 below dereferences what av_fetch() returned.*/
10794 273 ▶ for (si = 0; si < nsv; si++) {
Branch: 1 branch
BranchTrueFalseTotal
for (si = 0; si < nsv; si++) { 201 72 273
10795 201 av_push(sizes, newSVuv(w.nkey[si]));
10796 201 w.mrow[si] = newAV();
10797 201 w.crow[si] = newAV();
10798 201 av_push(mat, newRV_noinc((SV *)w.mrow[si]));
10799 201 av_push(cnt, newRV_noinc((SV *)w.crow[si]));
10800 201 av_fill(w.mrow[si], nsv - 1);
10801 201 av_fill(w.crow[si], nsv - 1);
10802 }
10803  
10804 273 ▶ for (si = 0; si < nsv; si++) {
Branch: 1 branch
BranchTrueFalseTotal
for (si = 0; si < nsv; si++) { 201 72 273
10805 201 AV *mrow = w.mrow[si];
10806 201 AV *crow = w.crow[si];
10807 /*a structure against itself is zero by construction and needs neither
10808 the pairing nor the fit; what it pairs with is everything it has*/
10809 201 (void)av_store(mrow, si, newSVnv(0.0));
10810 201 (void)av_store(crow, si, newSVuv(w.nkey[si]));
10811 414 ▶ for (sj = si + 1; sj < nsv; sj++) {
Branch: 1 branch
BranchTrueFalseTotal
for (sj = si + 1; sj < nsv; sj++) { 213 201 414
10812 213 AV *mrow2 = w.mrow[sj];
10813 213 AV *crow2 = w.crow[sj];
10814 NV rot[3][3], tran[3], r;
10815 UV n;
10816 213 ▶ if (match == RM_ORDER) {
Branch: 1 branch
BranchTrueFalseTotal
if (match == RM_ORDER) { 8 205 213
10817 /*pairing by position is the nth atom against the nth atom, and
10818 two lists of different lengths are not a correspondence at all:
10819 there is no nth atom to pair with past the end of the shorter*/
10820 8 ▶ n = (w.nkey[si] == w.nkey[sj]) ? w.nkey[si] : 0;
Branch: 1 branch
BranchTrueFalseTotal
n = (w.nkey[si] == w.nkey[sj]) ? w.nkey[si] : 0; 7 1 8
10821 578 ▶ for (i = 0; i < n; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i = 0; i < n; i++) { 570 8 578
10822 570 w.ia[i] = w.key[si][i].idx;
10823 570 w.ib[i] = w.key[sj][i].idx;
10824 }
10825 } else {
10826 205 n = rmsd_pair_by_key(w.key[si], w.nkey[si], w.key[sj], w.nkey[sj],
10827 w.ia, w.ib);
10828 }
10829 213 (void)av_store(crow, sj, newSVuv(n));
10830 213 (void)av_store(crow2, si, newSVuv(n));
10831 213 ▶ if (n < (UV)min_atoms) continue;
Branch: 1 branch
BranchTrueFalseTotal
if (n < (UV)min_atoms) continue; 20 193 213
10832 193 r = rmsd_measure(&w.set[si], &w.set[sj], w.ia, w.ib, n, fit, rot, tran);
10833 193 (void)av_store(mrow, sj, newSVnv(r));
10834 193 (void)av_store(mrow2, si, newSVnv(r));
10835 193 ▶ if (want_transform && !rotation) {
Branch: 2 branches
BranchTrueFalseTotal
if (want_transform && !rotation) { 19 174 193
if (want_transform && !rotation) { 19 0 19
10836 unsigned short p, q;
10837 19 rotation = newAV();
10838 19 translation = newAV();
10839 19 sv_2mortal((SV *)rotation);
10840 19 sv_2mortal((SV *)translation);
10841 76 ▶ for (p = 0; p < 3; p++) {
Branch: 1 branch
BranchTrueFalseTotal
for (p = 0; p < 3; p++) { 57 19 76
10842 57 AV *row = newAV();
10843 228 ▶ for (q = 0; q < 3; q++) av_push(row, newSVnv(rot[p][q]));
Branch: 1 branch
BranchTrueFalseTotal
for (q = 0; q < 3; q++) av_push(row, newSVnv(rot[p][q])); 171 57 228
10844 57 av_push(rotation, newRV_noinc((SV *)row));
10845 57 av_push(translation, newSVnv(tran[p]));
10846 }
10847 }
10848 }
10849 }
10850  
10851 //the result hash is built last, so that nothing between here and the
10852 //return can croak with it half-filled and unreferenced
10853 72 out = newHV();
10854 72 (void)hv_stores(out, "rmsd", newRV_inc((SV *)mat));
10855 72 (void)hv_stores(out, "n", newRV_inc((SV *)cnt));
10856 72 (void)hv_stores(out, "n_atoms", newRV_inc((SV *)sizes));
10857 72 ▶ if (rotation) {
Branch: 1 branch
BranchTrueFalseTotal
if (rotation) { 19 53 72
10858 19 (void)hv_stores(out, "rotation", newRV_inc((SV *)rotation));
10859 19 (void)hv_stores(out, "translation", newRV_inc((SV *)translation));
10860 }
10861 72 LEAVE;
10862 72 return out;
10863 }
10864  
10865 MODULE = Chem::Structure::Parser PACKAGE = Chem::Structure::Parser
10866  
10867 PROTOTYPES: DISABLE
10868  
10869 SV * _parse_file(path, opts = &PL_sv_undef)
10870 SV *path
10871 SV *opts
10872 PREINIT:
10873 char *CSP_RESTRICT buf;
10874 STRLEN len;
10875 527 ▶ HV *o = NULL, *res;
Branch: 1 branch
BranchTrueFalseTotal
HV *o = NULL, *res; 5 522 527
10876 const char *CSP_RESTRICT p;
10877 CODE:
10878 527 ▶ if (!SvOK(path)) croak("Chem::Structure::Parser: file name is undefined");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(path)) croak("Chem::Structure::Parser: file name is undefined"); 2 525 527
10879 525 ▶ if (SvOK(opts)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(opts)) { 521 4 525
10880 521 ▶ if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 520 1 521
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 1 519 520
10881 2 croak("Chem::Structure::Parser: options must be a hash reference");
10882 519 o = (HV *)SvRV(opts);
10883 }
10884 523 p = SvPV_nolen(path);
10885 /*the buffer is freed by LEAVE rather than by hand, so that a croak
10886 out of the parse gives it back too*/
10887 523 ENTER;
10888 523 buf = slurp(aTHX_ p, &len);
10889 517 SAVEFREEPV(buf);
10890 517 res = parse_buf(aTHX_ buf, len, o, NULL);
10891 515 LEAVE;
10892 515 (void)hv_stores(res, "file", newSVsv(path));
10893 515 RETVAL = newRV_noinc((SV *)res);
10894 OUTPUT:
10895 RETVAL
10896  
10897 SV * _parse_string(text, opts = &PL_sv_undef)
10898 SV *text
10899 SV *opts
10900 PREINIT:
10901 STRLEN len;
10902 const char *CSP_RESTRICT buf;
10903 342 ▶ HV *o = NULL, *res;
Branch: 1 branch
BranchTrueFalseTotal
HV *o = NULL, *res; 2 340 342
10904 CODE:
10905 342 ▶ if (!SvOK(text)) croak("Chem::Structure::Parser: PDB text is undefined");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(text)) croak("Chem::Structure::Parser: PDB text is undefined"); 2 340 342
10906 340 ▶ if (SvOK(opts)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(opts)) { 339 1 340
10907 339 ▶ if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 336 3 339
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 1 335 336
10908 4 croak("Chem::Structure::Parser: options must be a hash reference");
10909 335 o = (HV *)SvRV(opts);
10910 }
10911 336 buf = text_bytes(aTHX_ text, &len);
10912 336 res = parse_buf(aTHX_ buf, len, o, NULL);
10913 332 RETVAL = newRV_noinc((SV *)res);
10914 OUTPUT:
10915 RETVAL
10916  
10917 SV *
10918 _parse_cif_file(path, opts = &PL_sv_undef)
10919 SV *path
10920 SV *opts
10921 PREINIT:
10922 char *CSP_RESTRICT buf;
10923 STRLEN len;
10924 268 ▶ HV *o = NULL, *res;
Branch: 1 branch
BranchTrueFalseTotal
HV *o = NULL, *res; 1 267 268
10925 const char *CSP_RESTRICT p;
10926 CODE:
10927 268 ▶ if (!SvOK(path)) croak("Chem::Structure::Parser: file name is undefined");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(path)) croak("Chem::Structure::Parser: file name is undefined"); 1 267 268
10928 267 ▶ if (SvOK(opts)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(opts)) { 266 1 267
10929 266 ▶ if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 265 1 266
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 1 264 265
10930 2 croak("Chem::Structure::Parser: options must be a hash reference");
10931 264 o = (HV *)SvRV(opts);
10932 }
10933 265 p = SvPV_nolen(path);
10934 /*the buffer is freed by LEAVE rather than by hand, so that a croak
10935 out of the parse gives it back too*/
10936 265 ENTER;
10937 265 buf = slurp(aTHX_ p, &len);
10938 263 SAVEFREEPV(buf);
10939 263 res = parse_cif_buf(aTHX_ buf, len, o, NULL);
10940 261 LEAVE;
10941 261 (void)hv_stores(res, "file", newSVsv(path));
10942 261 RETVAL = newRV_noinc((SV *)res);
10943 OUTPUT:
10944 RETVAL
10945  
10946 SV *
10947 _parse_cif_string(text, opts = &PL_sv_undef)
10948 SV *text
10949 SV *opts
10950 PREINIT:
10951 STRLEN len;
10952 const char *CSP_RESTRICT buf;
10953 177 ▶ HV *o = NULL, *res;
Branch: 1 branch
BranchTrueFalseTotal
HV *o = NULL, *res; 1 176 177
10954 CODE:
10955 177 ▶ if (!SvOK(text)) croak("Chem::Structure::Parser: mmCIF text is undefined");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(text)) croak("Chem::Structure::Parser: mmCIF text is undefined"); 1 176 177
10956 176 ▶ if (SvOK(opts)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(opts)) { 175 1 176
10957 175 ▶ if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 174 1 175
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 1 173 174
10958 2 croak("Chem::Structure::Parser: options must be a hash reference");
10959 173 o = (HV *)SvRV(opts);
10960 }
10961 174 buf = text_bytes(aTHX_ text, &len);
10962 174 res = parse_cif_buf(aTHX_ buf, len, o, NULL);
10963 170 RETVAL = newRV_noinc((SV *)res);
10964 OUTPUT:
10965 RETVAL
10966  
10967 SV *
10968 _convert_file(path, from_cif, to_pdb, opts = &PL_sv_undef)
10969 SV *path
10970 bool from_cif
10971 bool to_pdb
10972 SV *opts
10973 PREINIT:
10974 char *CSP_RESTRICT buf;
10975 STRLEN len;
10976 315 ▶ HV *o = NULL, *res;
Branch: 1 branch
BranchTrueFalseTotal
HV *o = NULL, *res; 0 315 315
10977 cv_w w;
10978 CODE:
10979 315 ▶ if (!SvOK(path)) croak("Chem::Structure::Parser: file name is undefined");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(path)) croak("Chem::Structure::Parser: file name is undefined"); 0 315 315
10980 315 ▶ if (SvOK(opts)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(opts)) { 315 0 315
10981 315 ▶ if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 315 0 315
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 0 315 315
10982 0 croak("Chem::Structure::Parser: options must be a hash reference");
10983 315 o = (HV *)SvRV(opts);
10984 }
10985 /*the writer and the buffer are both freed by LEAVE, so that a croak out
10986 of the conversion gives them back too*/
10987 315 ENTER;
10988 315 Zero(&w, 1, cv_w);
10989 315 SAVEDESTRUCTOR_X(cv_free_cb, &w);
10990 315 cv_init(aTHX_ &w, from_cif, to_pdb, o);
10991 314 buf = slurp(aTHX_ SvPV_nolen(path), &len);
10992 313 SAVEFREEPV(buf);
10993 313 res = convert_do(aTHX_ &w, buf, len, o);
10994 312 LEAVE;
10995 312 RETVAL = newRV_noinc((SV *)res);
10996 OUTPUT:
10997 RETVAL
10998  
10999 SV *
11000 _convert_string(text, from_cif, to_pdb, opts = &PL_sv_undef)
11001 SV *text
11002 bool from_cif
11003 bool to_pdb
11004 SV *opts
11005 PREINIT:
11006 STRLEN len;
11007 const char *CSP_RESTRICT buf;
11008 131 ▶ HV *o = NULL, *res;
Branch: 1 branch
BranchTrueFalseTotal
HV *o = NULL, *res; 0 131 131
11009 cv_w w;
11010 CODE:
11011 131 ▶ if (!SvOK(text)) croak("Chem::Structure::Parser: structure text is undefined");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(text)) croak("Chem::Structure::Parser: structure text is undefined"); 0 131 131
11012 131 ▶ if (SvOK(opts)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(opts)) { 131 0 131
11013 131 ▶ if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 131 0 131
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 0 131 131
11014 0 croak("Chem::Structure::Parser: options must be a hash reference");
11015 131 o = (HV *)SvRV(opts);
11016 }
11017 131 ENTER;
11018 131 Zero(&w, 1, cv_w);
11019 131 SAVEDESTRUCTOR_X(cv_free_cb, &w);
11020 131 cv_init(aTHX_ &w, from_cif, to_pdb, o);
11021 130 buf = text_bytes(aTHX_ text, &len);
11022 130 res = convert_do(aTHX_ &w, buf, len, o);
11023 109 LEAVE;
11024 109 RETVAL = newRV_noinc((SV *)res);
11025 OUTPUT:
11026 RETVAL
11027  
11028 void
11029 _str2nv_paths(text)
11030 SV *text
11031 PREINIT:
11032 STRLEN n;
11033 const char *CSP_RESTRICT s;
11034 361 NV a = 0, b = 0;
11035 bool ok_a, ok_b;
11036 PPCODE:
11037 361 ▶ if (!SvOK(text)) croak("_str2nv_paths: string is undefined");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(text)) croak("_str2nv_paths: string is undefined"); 0 361 361
11038 361 s = SvPV_const(text, n);
11039 361 ok_a = str2nv_fixed(s, n, &a);
11040 361 ok_b = str2nv_slow(s, n, &b);
11041 361 ▶ EXTEND(SP, 4);
Branch: 1 branch
BranchTrueFalseTotal
EXTEND(SP, 4); 0 361 361
11042 361 PUSHs(sv_2mortal(newSViv(ok_a)));
11043 361 ▶ PUSHs(ok_a ? sv_2mortal(newSVnv(a)) : &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(ok_a ? sv_2mortal(newSVnv(a)) : &PL_sv_undef); 338 23 361
11044 361 PUSHs(sv_2mortal(newSViv(ok_b)));
11045 361 ▶ PUSHs(ok_b ? sv_2mortal(newSVnv(b)) : &PL_sv_undef);
Branch: 1 branch
BranchTrueFalseTotal
PUSHs(ok_b ? sv_2mortal(newSVnv(b)) : &PL_sv_undef); 347 14 361
11046  
11047 bool
11048 _str2nv_fast_fractions()
11049 CODE:
11050 1 ▶ RETVAL = STR2NV_FAST_FRACTIONS;
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = STR2NV_FAST_FRACTIONS; 1 0 1
11051 OUTPUT:
11052 RETVAL
11053  
11054 SV *
11055 aa3to1(name)
11056 SV *name
11057 PREINIT:
11058 STRLEN n;
11059 const char *s;
11060 res_info ri;
11061 CODE:
11062 351 ▶ if (!SvOK(name)) croak("aa3to1: residue name is undefined");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(name)) croak("aa3to1: residue name is undefined"); 2 349 351
11063 349 s = SvPV_const(name, n);
11064 1039 ▶ RETVAL = (res_lookup(s, n, &ri) && ri.type == RT_AA)
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = (res_lookup(s, n, &ri) && ri.type == RT_AA) 307 34 341
11065 307 ? newSVpvn(&ri.one, 1)
11066 383 ▶ : newSVpvn("", 0);
Branch: 1 branch
BranchTrueFalseTotal
: newSVpvn("", 0); 341 8 349
11067 OUTPUT:
11068 RETVAL
11069  
11070 SV *aa1to3(one)
11071 SV *one
11072 PREINIT:
11073 STRLEN n;
11074 const char *s;
11075 const char *name;
11076 CODE:
11077 90 ▶ if (!SvOK(one)) croak("aa1to3: single-letter code is undefined");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(one)) croak("aa1to3: single-letter code is undefined"); 1 89 90
11078 89 s = SvPV_const(one, n);
11079 89 name = aa1to3_lookup(s, n);
11080 89 ▶ RETVAL = name ? newSVpvn(name, 3) : newSVpvn("", 0);
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = name ? newSVpvn(name, 3) : newSVpvn("", 0); 83 6 89
11081 OUTPUT:
11082 RETVAL
11083  
11084 SV *res1(name)
11085 SV *name
11086 PREINIT:
11087 STRLEN n;
11088 const char *s;
11089 res_info ri;
11090 CODE:
11091 8064 ▶ if (!SvOK(name)) croak("res1: residue name is undefined");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(name)) croak("res1: residue name is undefined"); 1 8063 8064
11092 8063 s = SvPV_const(name, n);
11093 24129 ▶ RETVAL = (res_lookup(s, n, &ri) && ri.one)
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = (res_lookup(s, n, &ri) && ri.one) 7996 7 8003
11094 7996 ? newSVpvn(&ri.one, 1)
11095 8070 ▶ : newSVpvn("", 0);
Branch: 1 branch
BranchTrueFalseTotal
: newSVpvn("", 0); 8003 60 8063
11096 OUTPUT:
11097 RETVAL
11098  
11099 SV *res_type(name)
11100 SV *name
11101 PREINIT:
11102 STRLEN n;
11103 const char *CSP_RESTRICT s;
11104 res_info ri;
11105 const char *CSP_RESTRICT t;
11106 CODE:
11107 731 ▶ if (!SvOK(name)) croak("res_type: residue name is undefined");
Branch: 1 branch
BranchTrueFalseTotal
if (!SvOK(name)) croak("res_type: residue name is undefined"); 1 730 731
11108 730 s = SvPV_const(name, n);
11109 730 ▶ if (!res_lookup(s, n, &ri)) t = "other";
Branch: 1 branch
BranchTrueFalseTotal
if (!res_lookup(s, n, &ri)) t = "other"; 14 716 730
11110 716 ▶ else if (ri.type == RT_AA) t = "amino_acid";
Branch: 1 branch
BranchTrueFalseTotal
else if (ri.type == RT_AA) t = "amino_acid"; 551 165 716
11111 165 ▶ else if (ri.type == RT_NUC) t = "nucleotide";
Branch: 1 branch
BranchTrueFalseTotal
else if (ri.type == RT_NUC) t = "nucleotide"; 153 12 165
11112 12 ▶ else if (ri.type == RT_WATER) t = "water";
Branch: 1 branch
BranchTrueFalseTotal
else if (ri.type == RT_WATER) t = "water"; 12 0 12
11113 0 else t = "other";
11114 730 RETVAL = newSVpv(t, 0);
11115 OUTPUT:
11116 RETVAL
11117  
11118 SV * _assemble(parse, atoms, stats)
11119 SV *parse
11120 SV *atoms
11121 SV *stats
11122 CODE:
11123 1172 ▶ if (!SvROK(parse) || SvTYPE(SvRV(parse)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(parse) || SvTYPE(SvRV(parse)) != SVt_PVHV) 1172 0 1172
if (!SvROK(parse) || SvTYPE(SvRV(parse)) != SVt_PVHV) 1 1171 1172
11124 1 croak("Chem::Structure::Parser: the parse must be a hash reference");
11125 1171 ▶ if (!SvROK(stats) || SvTYPE(SvRV(stats)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(stats) || SvTYPE(SvRV(stats)) != SVt_PVHV) 1171 0 1171
if (!SvROK(stats) || SvTYPE(SvRV(stats)) != SVt_PVHV) 1 1170 1171
11126 1 croak("Chem::Structure::Parser: stats must be a hash reference");
11127 1170 RETVAL = newRV_noinc((SV *)assemble(aTHX_ (HV *)SvRV(parse), SvTRUE(atoms) ? TRUE : FALSE,
11128 (HV *)SvRV(stats)));
11129 OUTPUT:
11130 RETVAL
11131  
11132 SV * _structure_atoms(chains, cids)
11133 SV *chains
11134 SV *cids
11135 CODE:
11136 15 ▶ if (!SvROK(chains) || SvTYPE(SvRV(chains)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(chains) || SvTYPE(SvRV(chains)) != SVt_PVHV) 15 0 15
if (!SvROK(chains) || SvTYPE(SvRV(chains)) != SVt_PVHV) 1 14 15
11137 1 croak("structure_atoms: chains must be a hash reference");
11138 14 ▶ if (!SvROK(cids) || SvTYPE(SvRV(cids)) != SVt_PVAV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(cids) || SvTYPE(SvRV(cids)) != SVt_PVAV) 14 0 14
if (!SvROK(cids) || SvTYPE(SvRV(cids)) != SVt_PVAV) 1 13 14
11139 1 croak("structure_atoms: the chain ids must be an array reference");
11140 13 RETVAL = newRV_noinc((SV *)atoms_flat(aTHX_ (HV *)SvRV(chains), (AV *)SvRV(cids)));
11141 OUTPUT:
11142 RETVAL
11143  
11144 bool _standard_res(name)
11145 SV *name
11146 PREINIT:
11147 STRLEN n;
11148 const char *s;
11149 CODE:
11150 //std_res[], for the mmCIF header's _chem_comp, so the list is kept once
11151 544 ▶ s = SvOK(name) ? SvPV_const(name, n) : (n = 0, "");
Branch: 1 branch
BranchTrueFalseTotal
s = SvOK(name) ? SvPV_const(name, n) : (n = 0, ""); 272 0 272
11152 272 RETVAL = NAME_LISTED(s, n, std_res);
11153 OUTPUT:
11154 RETVAL
11155  
11156 bool is_single_ion(chain, id = &PL_sv_undef)
11157 SV *chain
11158 SV *id
11159 CODE:
11160 //two arguments mean the structure and a chain: an undefined id there is
11161 //a chain that was not given, not a chain hash passed on its own
11162 45 ▶ if (items > 1 && !SvOK(id)) croak("is_single_ion: no chain given");
Branch: 2 branches
BranchTrueFalseTotal
if (items > 1 && !SvOK(id)) croak("is_single_ion: no chain given"); 25 20 45
if (items > 1 && !SvOK(id)) croak("is_single_ion: no chain given"); 2 23 25
11163 43 RETVAL = chain_is_single_ion(aTHX_ chain_arg(aTHX_ chain, id, "is_single_ion"));
11164 OUTPUT:
11165 RETVAL
11166  
11167 SV * _features(info, opts, who)
11168 SV *info
11169 SV *opts
11170 SV *who
11171 PREINIT:
11172 714 HV *o = NULL;
11173 CODE:
11174 714 ▶ if (!SvROK(info) || SvTYPE(SvRV(info)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(info) || SvTYPE(SvRV(info)) != SVt_PVHV) 714 0 714
if (!SvROK(info) || SvTYPE(SvRV(info)) != SVt_PVHV) 1 713 714
11175 1 croak("Chem::Structure::Parser: structure must be a hash reference");
11176 713 ▶ if (SvOK(opts)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(opts)) { 713 0 713
11177 713 ▶ if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 713 0 713
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 1 712 713
11178 1 croak("Chem::Structure::Parser: options must be a hash reference");
11179 712 o = (HV *)SvRV(opts);
11180 }
11181 1423 ▶ RETVAL = newRV_noinc((SV *)features_do(aTHX_ (HV *)SvRV(info), o,
Branch: 1 branch
BranchTrueFalseTotal
RETVAL = newRV_noinc((SV *)features_do(aTHX_ (HV *)SvRV(info), o, 711 1 712
11182 SvOK(who) ? SvPV_nolen(who) : "structure_features"));
11183 OUTPUT:
11184 RETVAL
11185  
11186 SV * _rmsd(sets, opts)
11187 SV *sets
11188 SV *opts
11189 PREINIT:
11190 81 HV *o = NULL;
11191 CODE:
11192 81 ▶ if (!SvROK(sets) || SvTYPE(SvRV(sets)) != SVt_PVAV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(sets) || SvTYPE(SvRV(sets)) != SVt_PVAV) 81 0 81
if (!SvROK(sets) || SvTYPE(SvRV(sets)) != SVt_PVAV) 1 80 81
11193 1 croak("structure_rmsd: the structures must be an array reference");
11194 80 ▶ if (SvOK(opts)) {
Branch: 1 branch
BranchTrueFalseTotal
if (SvOK(opts)) { 80 0 80
11195 80 ▶ if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV)
Branch: 2 branches
BranchTrueFalseTotal
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 79 1 80
if (!SvROK(opts) || SvTYPE(SvRV(opts)) != SVt_PVHV) 0 79 79
11196 1 croak("structure_rmsd: options must be a hash reference");
11197 79 o = (HV *)SvRV(opts);
11198 }
11199 79 RETVAL = newRV_noinc((SV *)rmsd_do(aTHX_ (AV *)SvRV(sets), o, "structure_rmsd"));
11200 OUTPUT:
11201 RETVAL
« blib/lib/Chem/Structure/Parser.pm ↑ Summary