Chem-Structure-Parser
view release on metacpan or search on metacpan
//str2nv() -- coordinates and the like
static bool str2nv(const char *CSP_RESTRICT s, STRLEN n, NV *CSP_RESTRICT out)
{
return str2nv_fixed(s, n, out) || str2nv_slow(s, n, out);
}
/*The two above are reachable individually from Perl as _str2nv_paths(), which
exists for t/numbers.t and asserts that they return the same NV bit for bit.
There is no other way to compare them: only one of the two is ever reached for
any given field, and Perl's own string-to-NV conversion cannot referee the
question because on an older -Duselongdouble perl Perl_my_atof is a hand-rolled
decimal accumulator rather than strtod(). _str2nv_fast_fractions() beside it
says whether this build lets the fast path take a fraction at all, so the test
knows which of the two to expect. The XSUBs are at the foot of the file with
the rest of them.*/
static bool fld_iv(const char *CSP_RESTRICT line, STRLEN llen, STRLEN from, STRLEN to,
IV *CSP_RESTRICT out)
{
const char *s;
STRLEN n = fld(line, llen, from, to, &s);
return n ? str2iv(s, n, out) : FALSE;
}
/*the same for the two fields the format lets overflow into hybrid-36: the
serial number and the residue number*/
static bool fld_hy36(const char *CSP_RESTRICT line, STRLEN llen, STRLEN from, STRLEN to,
IV *CSP_RESTRICT out)
{
const char *s;
STRLEN n = fld(line, llen, from, to, &s);
if (!n) return 0;
return str2iv(s, n, out) || hy36_decode(s, n, (unsigned short)(to - from + 1), out);
}
static bool fld_nv(const char *CSP_RESTRICT line, STRLEN llen, STRLEN from, STRLEN to,
NV *CSP_RESTRICT out){
const char *s;
STRLEN n = fld(line, llen, from, to, &s);
return n ? str2nv(s, n, out) : FALSE;
}
/*charge_ok() -- columns 79-80 hold a digit and a sign, '1+' as the format
writes it and '+1' as some programs do (4byf and 4ui0 in PDBbind v2020 write
'-1'; the caller turns those round). A file old enough to keep the entry id
in columns 73-80 has the tail of it here instead, and 'DR' is not a charge, nor
is '09'. A field that is not one reads as the empty string a blank field would
have given, which is the answer for "the file does not say".*/
static bool charge_ok(const char *CSP_RESTRICT s, STRLEN n){
if (n == 0 || n > 2) return 0;
STRLEN digits = 0, signs = 0;
for (STRLEN i = 0; i < n; i++) {
if (s[i] >= '0' && s[i] <= '9') digits++;
else if (s[i] == '+' || s[i] == '-') signs++;
else return 0;
}
return digits <= 1 && signs <= 1;
}
/*nv_is_finite() -- x - x is 0 for a finite x and NaN for a NaN or an infinity,
which is the test without isfinite(), a C99 macro, or Perl_isinf(); see
grid_build() for why neither of those. str2nv() hands a field that says nan or
inf through as the NV it names, so everything that sums or compares
coordinates over a whole structure asks this first.*/
static bool nv_is_finite(NV v){
return v - v == 0.0;
}
//the first n characters of a record name, compared without regard to case; kw
//is upper case
static bool rec_is(const char *CSP_RESTRICT s, const char *CSP_RESTRICT kw, STRLEN n){
for (STRLEN i = 0; i < n; i++)
if (toUPPER((unsigned char)s[i]) != kw[i]) return FALSE;
return TRUE;
}
/*pdb_coord_rec() -- whether a record is an ATOM or a HETATM, and the column its
serial number starts in.
The record name is six columns and the serial the five after it. A writer
with more than 99,999 atoms to number lets the serial run leftwards into the
record name -- 'ATOM 100000' -- and every other column stays where it was; gemmi
0.7.5 reads such a line by its first four letters, as the atom it is, and so
does this, the serial taken from the digits that start in column 5 or 6. Those
atoms used to be filed as header records named 'ATOM 1' and missing from every
count. HETATM has no blank to give up and cannot be written that way. The name
is matched without regard to case, as gemmi matches it.*/
static bool pdb_coord_rec(const char *CSP_RESTRICT line, STRLEN llen, bool *CSP_RESTRICT het,
STRLEN *CSP_RESTRICT serial_from){
if (llen < 6) return FALSE;
if (rec_is(line, "HETATM", 6)) { *het = TRUE; *serial_from = 6; return TRUE; }
if (!rec_is(line, "ATOM", 4)) return FALSE;
*het = FALSE;
if (line[4] == ' ' && line[5] == ' ') { *serial_from = 6; return TRUE; }
if (line[4] == ' ' && isDIGIT((unsigned char)line[5])) { *serial_from = 5; return TRUE; }
if (isDIGIT((unsigned char)line[4]) && isDIGIT((unsigned char)line[5])) { *serial_from = 4; return TRUE; }
return FALSE;
}
/*guess_element() -- only when columns 77-78 are absent, which happens in
files written before the element column existed and in files written by
programs that should know better.
The atom name is right-justified from column 14 for one-letter elements and
from column 13 for two-letter ones, so " CA " is a carbon alpha and "CA " is
a calcium. That rule is worth following exactly, because the alternative --
taking the first two letters -- turns every "HG11" hydrogen into mercury.*/
static STRLEN guess_element(const char *CSP_RESTRICT raw, STRLEN rawlen,
char *CSP_RESTRICT buf)
{
if (rawlen == 0) return 0;
/*A hydrogen with a long name -- HG11, HD22, HE21 -- fills all four columns
and starts in column 13, exactly where a two-letter element starts. Column
position alone cannot separate the two, so take the full field as the
tie-breaker: no two-letter element has a four character atom name, while
nearly every hydrogen past the first does. Without this, every HG11 in the
file becomes mercury.*/
if (rawlen >= 4 && raw[0] != ' ' && raw[1] != ' ' && raw[2] != ' ' && raw[3] != ' '
&& (raw[0] == 'H' || raw[0] == 'D' || raw[0] == 'h' || raw[0] == 'd')) {
buf[0] = (char)toUPPER((unsigned char)raw[0]);
for (; i < n; i++) {
if (isDIGIT((unsigned char)s[i])) nd++;
else if (s[i] == '.' && !dot) dot = TRUE;
else return FALSE;
}
return nd > 0;
}
/*cv_hy36() -- an integer into a PDB field of width columns, right-justified:
decimal while it fits, hybrid-36 past that, which is hy36_decode() run
backwards and what the PDB reader reads back. Below the decimal range there is
no encoding, and FALSE says so; out is not touched then. width is 4 or 5, and
the largest the five columns hold, 87,440,031, is well inside an IV.*/
static bool cv_hy36(IV v, unsigned short width, char *CSP_RESTRICT out){
IV dec = 1, p = 1;
for (unsigned short i = 0; i < width; i++) dec *= 10;
for (unsigned short i = 1; i < width; i++) p *= 36;
if (v > -(dec / 10) && v < dec) {
char tmp[32];//an IV prints in at most 21 characters, sign included
const STRLEN k = (STRLEN)my_snprintf(tmp, sizeof(tmp), "%" IVdf, v);
memcpy(out + width - k, tmp, k);
return TRUE;
}
if (v < 0 || v - dec >= 52 * p) return FALSE;
{
/*upper case for the first 26 * 36**(w-1) past the decimal range, lower
case for the next, each digit string offset by 10 * 36**(w-1) so that it
begins with a letter*/
IV d = v - dec;
const char *CSP_RESTRICT digits = d < 26 * p ? "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
: "0123456789abcdefghijklmnopqrstuvwxyz";
if (d >= 26 * p) d -= 26 * p;
d += 10 * p;
for (unsigned short i = width; i > 0; i--) {
out[i - 1] = digits[d % 36];
d /= 36;
}
}
return TRUE;
}
/*cv_nv_text() -- v to three decimals, or two, as the PDB columns want it.
my_snprintf() everywhere else, but not on a quadmath perl. There NVff is "Qf",
which gcc's printf format checking -- my_snprintf() carries the attribute --
does not know, and the build that is meant to be clean under -Wall printed four
warnings for these two calls. quadmath_snprintf() is what my_snprintf() hands a
single %Q conversion to on that build anyway (util.c), and <quadmath.h> is in
by way of perl.h there.*/
static int cv_nv_text(char *CSP_RESTRICT buf, size_t size, bool three, NV v){
#ifdef USE_QUADMATH
return quadmath_snprintf(buf, size, three ? "%.3Qf" : "%.2Qf", v);
#else
return three ? my_snprintf(buf, size, "%.3" NVff, v) : my_snprintf(buf, size, "%.2" NVff, v);
#endif
}
/*cv_num() -- one of an atom's five numbers into its PDB column, right-justified:
as written when it is a plain decimal that fits, and otherwise at the decimals
the format gives the column -- three for a coordinate, two for occupancy and B
-- counted in n_rounded unless that reads back as the same NV. A NaN or an
infinity has no decimals to round to and goes across as written, or not at all.*/
static bool cv_num(pTHX_ cv_w *CSP_RESTRICT w, const cv_atom *CSP_RESTRICT a, unsigned short i,
char *CSP_RESTRICT dst, STRLEN width, const char *CSP_RESTRICT what)
{
const char *CSP_RESTRICT s = a->num_s[i];
const STRLEN n = a->num_n[i];
const NV v = a->num[i];
char tmp[64];
int k;
NV back;
if (n <= width && cv_plain(s, n)) {
memcpy(dst + width - n, s, n);
return TRUE;
}
if (!nv_is_finite(v)) {
if (n <= width) {
memcpy(dst + width - n, s, n);
return TRUE;
}
k = -1;
/*Bounded first: my_snprintf() croaks rather than truncates, and a value this
size has no room in eight columns at any number of decimals anyway.*/
} else if (v <= -1e7 || v >= 1e8) {
k = -1;
} else {
k = cv_nv_text(tmp, sizeof(tmp), i <= CV_Z, v);
}
if (k <= 0 || (STRLEN)k > width) {
cv_fail(aTHX_ w, a, "convert: the %s '%.*s' does not fit the %u columns a PDB record has for it",
what, (int)n, s, (unsigned int)width);
return FALSE;
}
memcpy(dst + width - (STRLEN)k, tmp, (STRLEN)k);
if (!str2nv(tmp, (STRLEN)k, &back) || back != v) w->n_rounded++;
return TRUE;
}
/*cv_model() -- the index of a model in m_num[], added if it is new. Asked of
every atom, and the answer is nearly always the model before; a PDB file lists
its models in order, so a new one is only ever searched for once.*/
static size_t cv_model(pTHX_ cv_w *CSP_RESTRICT w, IV model){
size_t i;
if (w->n_model && w->m_num[w->cur] == model) return w->cur;
for (i = 0; i < w->n_model; i++) {
if (w->m_num[i] == model) return w->cur = i;
}
if (w->n_model == w->cap_model) {
w->cap_model = w->cap_model ? 2 * w->cap_model : 4;
Renew(w->m_num, w->cap_model, IV);
if (w->to_pdb) Renew(w->m_buf, w->cap_model, SV *);
}
w->m_num[w->n_model] = model;
if (w->to_pdb) w->m_buf[w->n_model] = newSVpvs("");
return w->cur = w->n_model++;
}
static void cv_blank(char *CSP_RESTRICT line){
memset(line, ' ', CV_LINE - 1);
line[CV_LINE - 1] = '\n';
}
have_res = 1;
p_resseq = rs;
p_have_rs = have_rs;
p_model = cur_model;
p_het = het;
my_strlcpy(p_chain, chain, sizeof(p_chain));
my_strlcpy(p_icode, icode, sizeof(p_icode));
my_strlcpy(p_resname, resname, sizeof(p_resname));
cur_chain = chain_tally(aTHX_ chain_elements, cur_model,
chain, strlen(chain));
{
//the altloc, column 17, of the record the run starts on
bool apart;
SV *key = run_key(aTHX_ res_seen, cur_model, chain, strlen(chain),
have_rs, rs, icode, resname, resname_len, het,
llen > 16 && line[16] != ' ', &apart);
av_push(res_apart, newSViv(apart));
/*and the residue's identity, once, where the residue
begins: see the note where the atom's own fields are
emitted for why this is per residue in this shape and per
atom in the other*/
if (build_atoms) filer_run(aTHX_ &filer, key);
}
if (build_atoms || slim) {
av_push(col[C_RESNAME], csp_str(aTHX_ resname, resname_len));
av_push(col[C_CHAIN], csp_str(aTHX_ chain, strlen(chain)));
av_push(col[C_RESSEQ], have_rs ? newSViv(rs) : newSV(0));
av_push(col[C_ICODE], csp_str(aTHX_ icode, icode[0] ? 1 : 0));
av_push(col[C_HET], newSViv(het));
av_push(col[C_MODEL], newSViv(cur_model));
}
//the first atom's element, which is all slim keeps of it
if (slim) av_push(col[C_ELEMENT], csp_str(aTHX_ elbuf, ellen));
}
}
//the atom's own fields
{
const char *nm_s, *alt_s, *chg_s;
STRLEN nm_n, alt_n, chg_n;
char chg_swap[2];//a sign-first charge, turned round
IV serial = 0;
bool have_serial, have_occ;
NV xv, yv, zv, bv, ov;
bool have_xyz = fld_nv(line, llen, 30, 37, &xv)
& fld_nv(line, llen, 38, 45, &yv)
& fld_nv(line, llen, 46, 53, &zv);
bool have_b = fld_nv(line, llen, 60, 65, &bv);
have_occ = fld_nv(line, llen, 54, 59, &ov);
have_serial = fld_hy36(line, llen, serial_from, 10, &serial);
nm_n = fld(line, llen, 12, 15, &nm_s);
alt_n = fld(line, llen, 16, 16, &alt_s);
chg_n = pdb_charge(line, llen, chg_swap, &chg_s);
/*The sums and extremes are gathered here rather than in Perl
because they have to touch every atom whether or not the caller
wanted per-atom hashes. Doing them in the loop that is already
reading the numbers costs nothing; doing them again in Perl
costs more than the whole parse.
Over the finite ones only. A field that says nan is passed through
as the NaN it names, and the box, the centres and the B-factor
extremes took it in or not according to where in the file it fell:
first, and every comparison after it failed, so the box was NaN;
anywhere later, and it was quietly left out.*/
if (have_xyz && nv_is_finite(xv) && nv_is_finite(yv) && nv_is_finite(zv)) {
rsx += xv; rsy += yv; rsz += zv; rnc++;
if (!have_bbox) {
xmin = xmax = xv; ymin = ymax = yv; zmin = zmax = zv;
have_bbox = 1;
} else {
if (xv < xmin) xmin = xv; else if (xv > xmax) xmax = xv;
if (yv < ymin) ymin = yv; else if (yv > ymax) ymax = yv;
if (zv < zmin) zmin = zv; else if (zv > zmax) zmax = zv;
}
}
if (have_b && nv_is_finite(bv)) {
rsb += bv; rnb++;
if (!bn++) { bmin = bmax = bv; }
else if (bv < bmin) bmin = bv;
else if (bv > bmax) bmax = bv;
bsum += bv;
}
if (ellen) {
elem_bump(aTHX_ elements, elbuf, ellen);
if (cur_chain) elem_bump(aTHX_ cur_chain, elbuf, ellen);
if (ellen == 1 && (elbuf[0] == 'H' || elbuf[0] == 'D')) n_hydrogen++;
}
if (known && ri.type == RT_WATER) n_water_atom++;
/*Two shapes to hand back, and never both, because building every
atom twice -- once as columns here, once as a hash in Perl
afterwards -- was costing more than everything else in the read
put together. The hash is what Chem::Structure::Parser wants, built here
where the fields already are; the columns are what the low-level
parse hands to anyone calling it directly.*/
if (build_atoms) {
atom_fields af;
HV *a;
af.name = csp_str(aTHX_ nm_s, nm_n);
af.alt = alt_s; af.alt_n = alt_n;
af.el = elbuf; af.el_n = ellen;
af.chg = chg_s; af.chg_n = chg_n;
af.serial = serial; af.have_serial = have_serial;
af.x = xv; af.y = yv; af.z = zv; af.have_xyz = have_xyz;
af.occ = ov; af.have_occ = have_occ;
af.b = bv; af.have_b = have_b;
af.het = het;
a = atom_hash(aTHX_ &filer.keys, &af);
av_push(atom_hv, newRV_noinc((SV *)a));
filer_atom(aTHX_ &filer, a, af.name, alt_n, have_occ, ov);
} else if (slim) {
/*Slim: a caller who asked for no atoms gets the name and
the position and nothing else, per atom. Those four are
what the Perl half still asks of the atoms once there are
no atom hashes -- whether a nucleotide-named residue has a
sugar, and whether a HETATM residue after the polymer is
bonded to it -- and the rest were twelve SVs an atom that
nothing read: 4fqr's atoms => 0 read peaked at 98 MB
with them.*/
av_push(col[C_NAME], csp_str(aTHX_ nm_s, nm_n));
av_push(col[C_X], have_xyz ? newSVnv(xv) : newSV(0));
av_push(col[C_Y], have_xyz ? newSVnv(yv) : newSV(0));
av_push(col[C_Z], have_xyz ? newSVnv(zv) : newSV(0));
Newx(s->res_one, cap_res ? cap_res : 1, char);
Newx(s->res_type, cap_res ? cap_res : 1, unsigned char);
Newx(s->res_std, cap_res ? cap_res : 1, unsigned char);
Newx(s->res_key, cap_res ? cap_res : 1, U32);
Newx(s->chain_hv, n_chain, HV *);
Newx(s->chain_first, n_chain, UV);
Newx(s->chain_last, n_chain, UV);
for (ci = 0; ci < nci; ci++) {
SV **cs = av_fetch(order, ci, 0);
HV *c;
AV *ro;
HV *residues;
SSize_t ri, nri;
if (!cs || !*cs || !SvOK(*cs)) continue;
c = hvf_ent_hv(aTHX_ chains, *cs);
if (!c) continue;
s->chain_hv[s->n_chain] = c;
s->chain_first[s->n_chain] = s->n_res;
ro = hvf_av(aTHX_ c, "residue_order", 13);
residues = hvf_hv(aTHX_ c, "residues", 8);
nri = (ro && residues) ? av_len(ro) + 1 : 0;
for (ri = 0; ri < nri; ri++) {
SV **rs = av_fetch(ro, ri, 0);
HV *r;
if (!rs || !*rs || !SvOK(*rs)) continue;
r = hvf_ent_hv(aTHX_ residues, *rs);
if (!r || s->n_res >= cap_res) continue;
set_add_residue(aTHX_ s, r, probe, coords_only, &cap_atom);
}
s->chain_last[s->n_chain] = s->n_res;
s->n_chain++;
}
/*No atom hashes at all, in a structure whose chains count atom records:
that is atoms => 0, and the only thing wrong with it is that nobody said so.
A structure whose atoms are all there but have no readable coordinates is a
different thing and is not an error -- t/errors.t reads one -- so the test is
on the names the residues listed, not on the positions that came back.*/
if (s->n_atom_slots == 0 && cap_atom > 0) {
set_free(aTHX_ s);
croak("%s: this structure has no atom hashes to work from; "
"read it again without atoms => 0", who);
}
//give the over-allocation back before the calculations pile their own
//working arrays on top of it
if (s->n_atom < cap_atom && s->n_atom > 0) {
Renew(s->x, s->n_atom, NV);
Renew(s->y, s->n_atom, NV);
Renew(s->z, s->n_atom, NV);
if (!coords_only) {
Renew(s->rad, s->n_atom, NV);
Renew(s->mass, s->n_atom, NV);
Renew(s->apolar, s->n_atom, unsigned char);
}
Renew(s->atom_hv, s->n_atom, HV *);
}
}
//which cell along one axis a coordinate falls in, clamped to the grid. Written
//so that no non-finite value is ever cast to a UV, which is undefined
//behaviour: a NaN fails `d > 0.0' and an infinity fails `k < n'.
static UV grid_axis(NV d, NV cell, UV n){
NV k;
if (n <= 1) return 0;
if (!(d > 0.0)) return 0;
k = d / cell;
if (!(k < (NV)n)) return n - 1;
return (UV)k;//truncation is floor here: k is positive
}
//qsort()'s order for NVs; grid_trim() hands it finite values only
static int nv_cmp(const void *pa, const void *pb){
const NV a = *(const NV *)pa, b = *(const NV *)pb;
return (a > b) - (a < b);
}
/*grid_trim() -- the box over the bulk of the points, leaving out the few far
from the rest.
grid_build() caps the cells at eight per point, and a box much larger than the
structure meets the cap by widening the cells. One far point is enough to make
the box that: a zinc at (9999.999, 9999.999, 9999.999) beside 4fqr's 90,792 atoms
(PDBbind v2020) widened the cells to 110 A, made every atom a neighbour of
thousands, and took structure_sasa() of it from 1.4 s to 29.5 s. So where the
box over every point would need wider cells, the box is taken per axis from the
k-th smallest coordinate to the k-th largest, k a hundredth of the points, and
grid_axis() puts the points outside it in the end cells, as it already does a
non-finite one.
That changes no answer, only the time and the order a search meets the points
in -- which is the order a list of pairs found by walking the grid comes out
in, and structure_contacts() and the rest promise none. Clamping into the box
never moves two coordinates further apart, so two points within a cell's width
of each other still land in the same or adjacent cells, which are the ones
every search here looks in; a point outside the box is compared with what lies
near the box's edge, and the distance test, not the cell, is what decides
whether it is a neighbour.
lo and hi hold the box over every finite point on the way in and the trimmed one
on the way out, x then y then z. x, y and z are not CSP_RESTRICT: each is read
again through the axis pointer the loop below takes from it. Sorted with
qsort() rather than selected, because this runs only for a box the cap has
already had to widen, which in a real structure is a sparse set of a few
hundred points at most -- ring or base centroids -- and in a whole structure
only one with a point far from the rest.*/
static void grid_trim(pTHX_ const NV *x, const NV *y, const NV *z, UV n,
NV *CSP_RESTRICT lo, NV *CSP_RESTRICT hi)
{
NV *CSP_RESTRICT v;
const NV *axis[3];
axis[0] = x; axis[1] = y; axis[2] = z;
Newx(v, n, NV);
for (unsigned short a = 0; a < 3; a++) {
UV m = 0, k;
for (UV i = 0; i < n; i++)
if (nv_is_finite(x[i]) && nv_is_finite(y[i]) && nv_is_finite(z[i]))
v[m++] = axis[a][i];
k = m / 100;
if (k == 0) continue;//too few points to leave any out
qsort(v, (size_t)m, sizeof(NV), nv_cmp);
lo[a] = v[k];
hi[a] = v[m - 1 - k];
}
Safefree(v);
}
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){
NV xmax, ymax, zmax, cells = 0.0;
UV ncell, c;
bool have_box = 0;
Zero(g, 1, cell_grid);
if (n == 0) return;
/*The box is taken over the finite points only. str2nv() hands a field
that says nan or inf through as the NV it names, and one such point
anywhere in the set made the extent non-finite, so the loop below never
settled and every point went into one cell: a whole-structure surface
quadratic in the atoms. grid_axis() already puts a non-finite point in an
end cell, where it is found as nobody's neighbour: every distance to it
compares false, and every search is written as the test a neighbour passes,
so false is no. x - x is 0 for a finite x and NaN otherwise, which is
the test without isfinite(), a C99 macro, or Perl_isinf(), which on perls
before 5.22 can route through a Perl_fp_class() block that never compiled.*/
g->x0 = g->y0 = g->z0 = xmax = ymax = zmax = 0.0;
for (UV i = 0; i < n; i++) {
if (!(x[i] - x[i] == 0.0 && y[i] - y[i] == 0.0 && z[i] - z[i] == 0.0)) continue;
if (!have_box) {
g->x0 = xmax = x[i]; g->y0 = ymax = y[i]; g->z0 = zmax = z[i];
have_box = 1;
continue;
}
if (x[i] < g->x0) g->x0 = x[i]; else if (x[i] > xmax) xmax = x[i];
if (y[i] < g->y0) g->y0 = y[i]; else if (y[i] > ymax) ymax = y[i];
if (z[i] < g->z0) g->z0 = z[i]; else if (z[i] > zmax) zmax = z[i];
}
g->cell = (cut > 0.0) ? cut : 1.0;
/*A box the cells would have to be widened for, which a few far points can
make of one that is otherwise compact: see grid_trim(). The trimmed box is
taken only where it is at least eight times smaller in cells, which takes a
point far outside the rest. A sparse set needs the widening without one --
the ring centroids of a large protein, a few hundred points through its
whole volume -- and trimming a hundredth of them off each end moved its
grid enough to list the same pi-stacked pairs in another order: 50 of 1,012
entries of PDBbind v2020 did, with grid_trim() taken on any box the cap
widened. At eight times, none does, and 4fqr with a zinc at 9999.999 is
trimmed by a factor of a million.*/
if (have_box) {
const NV whole = ((xmax - g->x0) / g->cell + 1.0) * ((ymax - g->y0) / g->cell + 1.0)
* ((zmax - g->z0) / g->cell + 1.0);
if (whole > (NV)n * 8.0 + 1024.0) {
NV lo[3], hi[3];
lo[0] = g->x0; lo[1] = g->y0; lo[2] = g->z0;
hi[0] = xmax; hi[1] = ymax; hi[2] = zmax;
grid_trim(aTHX_ x, y, z, n, lo, hi);
if (((hi[0] - lo[0]) / g->cell + 1.0) * ((hi[1] - lo[1]) / g->cell + 1.0)
* ((hi[2] - lo[2]) / g->cell + 1.0) * 8.0 < whole) {
g->x0 = lo[0]; g->y0 = lo[1]; g->z0 = lo[2];
xmax = hi[0]; ymax = hi[1]; zmax = hi[2];
}
}
}
/*Widen the cells until there are at most eight per point. Doubling, so a
box a kilometre across settles in a few dozen turns; the counter is there for
the case the extent is not a finite number at all, where the test below can
never come true and the grid falls back to a single cell.*/
{
NV ex = 0.0, ey = 0.0, ez = 0.0;
for (unsigned short turn = 0; turn < 4096; turn++) {
ex = (xmax - g->x0) / g->cell;
ey = (ymax - g->y0) / g->cell;
ez = (zmax - g->z0) / g->cell;
cells = (ex + 1.0) * (ey + 1.0) * (ez + 1.0);
if (cells <= (NV)n * 8.0 + 1024.0) break;
g->cell *= 2.0;
}
//the cast is safe only under that test, which bounds each extent by the
//cell count it just passed
if (cells <= (NV)n * 8.0 + 1024.0) {
g->nx = (UV)ex + 1;
g->ny = (UV)ey + 1;
g->nz = (UV)ez + 1;
being copied. The innermost loop is the whole cost of the surface -- it runs
once per sphere point per neighbour, which over a structure is billions of
times -- and as indices each turn of it was four loads scattered across four
arrays by a number the compiler cannot predict, plus a multiply to square a
radius that does not change. Copied, it is four sequential loads and no
multiply. The arithmetic is identical: ra * ra computed once per neighbour is
the same NV as ra * ra computed once per point.
keep, when it is given, receives the neighbour grid the run was made with, and
the caller frees it; otherwise it is freed here.*/
static void sasa_kernel(pTHX_ const NV *CSP_RESTRICT x, const NV *CSP_RESTRICT y,
const NV *CSP_RESTRICT z, const NV *CSP_RESTRICT rad, UV n,
const sasa_bins *CSP_RESTRICT bins, UV npts, NV *CSP_RESTRICT area,
const sasa_aux *CSP_RESTRICT aux, cell_grid *CSP_RESTRICT keep)
{
if (n == 0) return;
/*the neighbours of the atom being worked on: position and squared radius,
grown by doubling as needed. 64 covers every atom of a protein, where the
neighbour count runs to the low tens, without a single reallocation.*/
NV *CSP_RESTRICT nx = NULL, *CSP_RESTRICT ny = NULL, *CSP_RESTRICT nz = NULL;
NV *CSP_RESTRICT nr2 = NULL, *CSP_RESTRICT nd2 = NULL;
const NV *CSP_RESTRICT pts = bins->pts;
const UV nbin = bins->nbin;
UV nbr_cap = 64;
cell_grid g;
NV rmax = 0.0, constant;
for (UV i = 0; i < n; i++) if (rad[i] > rmax) rmax = rad[i];
grid_build(aTHX_ &g, x, y, z, n, 2.0 * rmax);
Newx(nx, nbr_cap, NV);
Newx(ny, nbr_cap, NV);
Newx(nz, nbr_cap, NV);
Newx(nr2, nbr_cap, NV);
Newx(nd2, nbr_cap, NV);
constant = 4.0 * CSP_PI / (NV)npts;
for (UV i = 0; i < n; i++) {
const NV xi = x[i], yi = y[i], zi = z[i], ri = rad[i];
UV n_nbr = 0, acc = 0, k_closest = 0;
UV cx, cy, cz, ax0, ax1, ay0, ay1, az0, az1, bx, by, bz;
//an atom the caller has already answered for: area[i] is left as it was
if (aux && aux->only && !aux->only[i]) continue;
cx = grid_axis(xi - g.x0, g.cell, g.nx);
cy = grid_axis(yi - g.y0, g.cell, g.ny);
cz = grid_axis(zi - g.z0, g.cell, g.nz);
ax0 = cx ? cx - 1 : 0; ax1 = (cx + 1 < g.nx) ? cx + 1 : g.nx - 1;
ay0 = cy ? cy - 1 : 0; ay1 = (cy + 1 < g.ny) ? cy + 1 : g.ny - 1;
az0 = cz ? cz - 1 : 0; az1 = (cz + 1 < g.nz) ? cz + 1 : g.nz - 1;
for (bx = ax0; bx <= ax1; bx++)
for (by = ay0; by <= ay1; by++)
for (bz = az0; bz <= az1; bz++) {
UV c = (bx * g.ny + by) * g.nz + bz;
UV p;
for (p = g.start[c]; p < g.start[c + 1]; p++) {
UV a = g.idx[p];
NV dx, dy, dz, sum, d2;
if (a == i) continue;
dx = x[a] - xi; dy = y[a] - yi; dz = z[a] - zi;
sum = ri + rad[a];
d2 = dx * dx + dy * dy + dz * dz;
if (!(d2 < sum * sum)) continue;//not >=: a NaN distance is no neighbour
if (n_nbr == nbr_cap) {
nbr_cap *= 2;
Renew(nx, nbr_cap, NV);
Renew(ny, nbr_cap, NV);
Renew(nz, nbr_cap, NV);
Renew(nr2, nbr_cap, NV);
Renew(nd2, nbr_cap, NV);
}
nx[n_nbr] = x[a]; ny[n_nbr] = y[a]; nz[n_nbr] = z[a];
nr2[n_nbr] = rad[a] * rad[a];
//kept for the sort below, and already worked out for the test above
nd2[n_nbr] = d2;
n_nbr++;
//a neighbour in another chain is what makes this atom's surface
//depend on that chain being there
if (aux && aux->cross && aux->chain_of[a] != aux->chain_of[i])
aux->cross[i] = 1;
}
}
/*nearest neighbour first. An insertion sort and not qsort(): the list
runs to the low tens, where the call through a comparison pointer costs
more than the loop it would be speeding up.
Skipped above SASA_SORT_MAX, where that sort would be the cost rather than
the saving: it is quadratic in the length of the list, and the length is
bounded by physics only as long as the file describes a structure. A file
that writes thousands of atoms on one coordinate -- an unmodelled ligand
left at the origin -- has no such bound, and there the first neighbour tried
covers every point already, so there is nothing for an order to save.*/
if (n_nbr <= SASA_SORT_MAX) {
for (UV q = 1; q < n_nbr; q++) {
const NV kx = nx[q], ky = ny[q], kz = nz[q], kr = nr2[q], kd = nd2[q];
UV w = q;
while (w && nd2[w - 1] > kd) {
nx[w] = nx[w - 1]; ny[w] = ny[w - 1]; nz[w] = nz[w - 1];
nr2[w] = nr2[w - 1]; nd2[w] = nd2[w - 1];
w--;
}
nx[w] = kx; ny[w] = ky; nz[w] = kz; nr2[w] = kr; nd2[w] = kd;
}
}
/*The bins, where there are any: each is asked whether one of the
nearest neighbours covers it whole, and only the points of those that
are not are tried. The neighbour that covered the last bin is asked
first, as the one that covered the last point is.*/
if (nbin > 1 && n_nbr > 0) {
const UV kmax = n_nbr < SASA_BIN_TRY ? n_nbr : SASA_BIN_TRY;
NV ncos[SASA_BIN_TRY], nsin[SASA_BIN_TRY], ndist[SASA_BIN_TRY];
UV b, k, k_cov = 0;
for (k = 0; k < kmax; k++) {
const NV d = nv_sqrt(nd2[k]);
NV c;
//a neighbour on top of this atom has no direction: it covers
//no bin whole
if (d > 0.0) c = (ri * ri + nd2[k] - nr2[k]) / (2.0 * ri * d);
else c = 1.0;
if (c > 1.0) c = 1.0;
if (c < -1.0) c = -1.0;
ncos[k] = c;
nsin[k] = nv_sqrt(1.0 - c * c);
it is asked for and kept on the structset: the pi-stacking, the base pairs and
the interface's cation-pi each want the same list. The caller reads s->rings
and does not free it; set_free() does.*/
static UV rings_get(pTHX_ structset *CSP_RESTRICT s){
ring_t *rings = NULL;
UV cap = 0, n = 0, r;
if (s->have_rings) return s->n_rings;
for (r = 0; r < s->n_res; r++) {
const ring_def *defs;
unsigned short nd = ring_defs(s->res_key[r], &defs), d;
HV *atoms;
if (nd == 0) continue;
atoms = hvf_hv(aTHX_ s->res_hv[r], "atoms", 5);
if (!atoms) continue;
for (d = 0; d < nd; d++) {
//the largest ring in the table is six-membered; the array is the
//size of the table's largest entry, not of anything the file says
NV px[RING_MAX], py[RING_MAX], pz[RING_MAX];
NV cx = 0.0, cy = 0.0, cz = 0.0, ux, uy, uz, vx, vy, vz, wx, wy, wz, wl;
unsigned short i, na = defs[d].n;
bool whole = 1;
for (i = 0; i < na; i++) {
if (!atom_xyz(aTHX_ atoms, defs[d].atom[i], &px[i], &py[i], &pz[i])) {
whole = 0;
break;
}
cx += px[i]; cy += py[i]; cz += pz[i];
}
if (!whole) continue;//an incomplete ring has no plane to speak of
cx /= (NV)na; cy /= (NV)na; cz /= (NV)na;
ux = px[0] - cx; uy = py[0] - cy; uz = pz[0] - cz;
vx = px[1] - cx; vy = py[1] - cy; vz = pz[1] - cz;
wx = uy * vz - uz * vy;
wy = uz * vx - ux * vz;
wz = ux * vy - uy * vx;
wl = nv_sqrt(wx * wx + wy * wy + wz * wz);
//three collinear points define no plane; a structure with two ring
//atoms deposited at the same position is the way that happens
if (!(wl > 0.0)) continue;
if (n == cap) {
cap = cap ? cap * 2 : 32;
Renew(rings, cap, ring_t);
}
rings[n].cx = cx; rings[n].cy = cy; rings[n].cz = cz;
rings[n].nx = wx / wl; rings[n].ny = wy / wl; rings[n].nz = wz / wl;
rings[n].res = r;
rings[n].label = defs[d].label;
n++;
}
}
s->rings = rings;
s->n_rings = n;
s->have_rings = TRUE;
return n;
}
//the angle between two vectors, folded into 0..pi/2 -- mdtraj's compute_angles()
//followed by its cap_angle(), which is how a plane's two-sided normal is made to
//mean one thing. The cosine is clamped before acos() sees it: a dot product of
//two unit vectors can land a fraction of an ulp outside [-1, 1] and acos() of
//that is a NaN, which numpy warns about and carries and this would not.
static NV vec_angle_capped(NV ax, NV ay, NV az, NV bx, NV by, NV bz){
NV la = nv_sqrt(ax * ax + ay * ay + az * az);
NV lb = nv_sqrt(bx * bx + by * by + bz * bz);
NV c, a;
if (!(la > 0.0) || !(lb > 0.0)) return -1.0;//no angle: the caller drops the pair
c = (ax * bx + ay * by + az * bz) / (la * lb);
if (c > 1.0) c = 1.0; else if (c < -1.0) c = -1.0;
a = nv_acos(c);
return (a > CSP_PI / 2.0) ? CSP_PI - a : a;
}
static NV det3(NV a, NV b, NV c, NV d, NV e, NV f, NV g, NV h, NV i){
return a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
}
//the length of (vx, vy, vz) once its component along the unit vector u is removed
static NV line_dist(NV vx, NV vy, NV vz, NV ux, NV uy, NV uz){
NV t = ux * vx + uy * vy + uz * vz;
vx -= ux * t; vy -= uy * t; vz -= uz * t;
return nv_sqrt(vx * vx + vy * vy + vz * vz);
}
/*The distance from the nearer of two rings' centroids to the line where their
planes meet -- mdtraj's calculate_intersection_point() and the two norms it
is fed to, made symmetric in the two rings.
An edge-to-face stack is one ring pointing its edge at the other's face, and
what tells it from two rings merely at right angles some way apart is that the
line their planes share passes close to one of them. Solving [n1; n2; n1xn2]
p = [n1.c1, n2.c2, 0] puts p on that line, and each centroid's distance from the
line is what is left of it once its component along the line is taken away; the
smaller of the two is what gets compared with the radius.
mdtraj projects only its first group's centroid onto the line and measures the
second group's from that projected point rather than from the line, so its
answer for one pair depends on which ring it was handed first. Asked both ways
round -- which is how t/data/features.py asks it, every ring against every ring
-- the union of its two answers is exactly this one, because a centroid is never
nearer a point on the line than it is to the line. Asked one way it misses
real stacks: 1b6c's PHE A99 lies 0.66 A from the line, and with TRP A59 handed
first, 5.06 A from it, the edge stack between the two is not found.
False when the planes are parallel and there is no line. mdtraj tests the
determinant against zero and lets a NaN fall through its threshold; this is
only ever reached with the planes 50 degrees or more apart, where the
determinant is |n1 x n2|^2 >= sin^2(50) = 0.587, so the test is a formality
either way.*/
static bool ring_intersect(const ring_t *CSP_RESTRICT a, const ring_t *CSP_RESTRICT b, NV *CSP_RESTRICT dmin){
NV dx = a->ny * b->nz - a->nz * b->ny;
NV dy = a->nz * b->nx - a->nx * b->nz;
NV dz = a->nx * b->ny - a->ny * b->nx;
NV det = det3(a->nx, a->ny, a->nz, b->nx, b->ny, b->nz, dx, dy, dz);
NV o1, o2, px, py, pz, dl, da, db;
if (nv_fabs(det) <= NV_EPSILON) return 0;
o1 = a->nx * a->cx + a->ny * a->cy + a->nz * a->cz;
o2 = b->nx * b->cx + b->ny * b->cy + b->nz * b->cz;
//Cramer's rule on [n_a; n_b; n_a x n_b] p = [o1, o2, 0]
px = det3(o1, a->ny, a->nz, o2, b->ny, b->nz, 0.0, dy, dz) / det;
py = det3(a->nx, o1, a->nz, b->nx, o2, b->nz, dx, 0.0, dz) / det;
pz = det3(a->nx, a->ny, o1, b->nx, b->ny, o2, dx, dy, 0.0) / det;
dl = nv_sqrt(dx * dx + dy * dy + dz * dz);
if (!(dl > 0.0)) return 0;
dx /= dl; dy /= dl; dz /= dl;
da = line_dist(a->cx - px, a->cy - py, a->cz - pz, dx, dy, dz);
db = line_dist(b->cx - px, b->cy - py, b->cz - pz, dx, dy, dz);
*dmin = (da < db) ? da : db;
return 1;
}
/*Where a pair of rings has to be for the pair to count as stacked.
Angles are radians here and degrees in the option hash, distances are angstrom
here and nanometres in mdtraj. The defaults Perl passes down are mdtraj's, in
this file's units, with the one exception argued at the head of
structure_pi_stacking() in the Perl: mdtraj's face-to-face centroid distance is
5.5 in a function whose every other distance is nanometres, which is 55 A -- far
enough that any two aromatic rings in a small protein would qualify. ProLIF,
which mdtraj's geometry is taken from, has 5.5 A, and mdtraj's three other
distances are ProLIF's converted to nanometres. So this takes 5.5 A as what
was meant, and the option is there for a caller who wants the number mdtraj
actually ships.*/
typedef struct {
NV face_dist;//centroid separation, angstrom
NV face_plane_lo, face_plane_hi;//angle between the ring planes, radians
NV face_norm_lo, face_norm_hi;//normal to centroid-to-centroid, radians
NV edge_dist, edge_plane_lo, edge_plane_hi, edge_norm_lo, edge_norm_hi;
NV edge_radius;//centroid to the planes' shared line, angstrom
} pi_opt;
//one field of the residue a ring sits in, copied into the interaction hash
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){
SV *v = hvf_sv(aTHX_ res, from, flen);
(void)hv_store(out, key, (I32)klen, v ? newSVsv(v) : newSVpvn("", 0), 0);
}
/*pi_stacking() -- every stacked pair of rings in the structure.
mdtraj asks the question of one named ligand group against one named receptor
group; this asks it of every pair of rings in the structure, which is the same
geometry run over a different set of pairs. Two of them are dropped: a ring
paired with itself, which mdtraj drops too because the vector between the two
centroids is the zero vector and every angle taken from it is a NaN, and the
two rings of one tryptophan or one purine, which mdtraj would happily call a
face-to-face stack because they are coplanar and 1.2 A apart. Two rings fused
along a bond are one aromatic system, not two systems stacked.
The pairs are found through the same grid the SASA uses, on the centroids: a
structure with a few thousand aromatic rings has a few million pairs, and all
but a handful of them are nowhere near each other.*/
static AV *pi_stacking(pTHX_ structset *CSP_RESTRICT s, const pi_opt *CSP_RESTRICT po)
{
AV *out = newAV();
const ring_t *rings;
NV *cx = NULL, *cy = NULL, *cz = NULL;
NV cut = (po->face_dist > po->edge_dist) ? po->face_dist : po->edge_dist;
const NV to_deg = 180.0 / CSP_PI;
cell_grid g;
UV n, i;
n = rings_get(aTHX_ s);
rings = s->rings;
if (n == 0) return out;
Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV);
for (i = 0; i < n; i++) { cx[i] = rings[i].cx; cy[i] = rings[i].cy; cz[i] = rings[i].cz; }
grid_build(aTHX_ &g, cx, cy, cz, n, cut);
for (i = 0; i < n; i++) {
UV bx, by, bz;
UV ci = grid_axis(cx[i] - g.x0, g.cell, g.nx);
UV cj = grid_axis(cy[i] - g.y0, g.cell, g.ny);
UV ck = grid_axis(cz[i] - g.z0, g.cell, g.nz);
UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1;
UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1;
UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1;
for (bx = ax0; bx <= ax1; bx++)
for (by = ay0; by <= ay1; by++)
for (bz = az0; bz <= az1; bz++) {
UV cell = (bx * g.ny + by) * g.nz + bz, p;
for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
UV j = g.idx[p];
NV vx, vy, vz, d, plane, ang_i, ang_j, inter = 0.0;
bool face, edge = 0;
const char *kind;
HV *h;
if (j <= i) continue;//each pair once
if (rings[i].res == rings[j].res) continue;//fused, not stacked
vx = cx[j] - cx[i]; vy = cy[j] - cy[i]; vz = cz[j] - cz[i];
d = nv_sqrt(vx * vx + vy * vy + vz * vz);
if (!(d <= cut)) continue;//not >: a NaN distance is no pair
plane = vec_angle_capped(rings[i].nx, rings[i].ny, rings[i].nz,
rings[j].nx, rings[j].ny, rings[j].nz);
/*One capped angle serves for both of mdtraj's: it takes the
angle of each ring's normal against the vector from that ring to
the other, and the two vectors differ only in sign, which
cap_angle() folds away.*/
ang_i = vec_angle_capped(rings[i].nx, rings[i].ny, rings[i].nz, vx, vy, vz);
ang_j = vec_angle_capped(rings[j].nx, rings[j].ny, rings[j].nz, vx, vy, vz);
if (plane < 0.0 || ang_i < 0.0 || ang_j < 0.0) continue;
face = (d <= po->face_dist
&& plane >= po->face_plane_lo && plane <= po->face_plane_hi
&& ((ang_i >= po->face_norm_lo && ang_i <= po->face_norm_hi)
|| (ang_j >= po->face_norm_lo && ang_j <= po->face_norm_hi)));
if (!face) {
edge = (d <= po->edge_dist
&& plane >= po->edge_plane_lo && plane <= po->edge_plane_hi
&& ((ang_i >= po->edge_norm_lo && ang_i <= po->edge_norm_hi)
|| (ang_j >= po->edge_norm_lo && ang_j <= po->edge_norm_hi))
&& ring_intersect(&rings[i], &rings[j], &inter)
&& inter <= po->edge_radius);
}
if (!face && !edge) continue;
kind = face ? "face" : "edge";
h = newHV();
(void)hv_stores(h, "type", newSVpv(kind, 0));
pi_field(aTHX_ h, "chain1", 6, s->res_hv[rings[i].res], "chain", 5);
pi_field(aTHX_ h, "residue1", 8, s->res_hv[rings[i].res], "key", 3);
pi_field(aTHX_ h, "resname1", 8, s->res_hv[rings[i].res], "resname", 7);
(void)hv_stores(h, "ring1", newSVpvn(&rings[i].label, 1));
pi_field(aTHX_ h, "chain2", 6, s->res_hv[rings[j].res], "chain", 5);
pi_field(aTHX_ h, "residue2", 8, s->res_hv[rings[j].res], "key", 3);
pi_field(aTHX_ h, "resname2", 8, s->res_hv[rings[j].res], "resname", 7);
(void)hv_stores(h, "ring2", newSVpvn(&rings[j].label, 1));
(void)hv_stores(h, "distance", newSVnv(d));
(void)hv_stores(h, "plane_angle", newSVnv(plane * to_deg));
(void)hv_stores(h, "normal_angle1", newSVnv(ang_i * to_deg));
(void)hv_stores(h, "normal_angle2", newSVnv(ang_j * to_deg));
if (edge) (void)hv_stores(h, "intersect_distance", newSVnv(inter));
av_push(out, newRV_noinc((SV *)h));
}
}
}
grid_free(aTHX_ &g);
Safefree(cx); Safefree(cy); Safefree(cz);
return out;
}
/*Watson-Crick base pairs, and the G-U wobble that stands in for one.
A base pair is not something the file declares; like the disulfides below it is
something the coordinates show. What is looked for is the canonical pairing and
only that -- the three geometries a double helix is built from -- because those
are the ones whose hydrogen bonds are fixed by the pair itself rather than by
whatever else the two bases happen to be doing. The atom pairs are the ones
Watson, J D; Crick, F H C (1953) Nature 171(4356):737-8 drew, and the numbers
beside them are Saenger, W (1984) Principles of Nucleic Acid Structure, chapter
6, where the twenty-eight ways two bases can pair are tabulated and these are
numbers 19, 20 and 28. That is the same numbering the archive's own annotation
uses, in _ndb_struct_na_base_pair.hbond_type_28.
pi_field(aTHX_ e, "resname", 7, partner, "resname", 7);
(void)hv_stores(e, "type", newSVpv(type, 0));
(void)hv_stores(e, "saenger", newSVuv((UV)saenger));
av_push(list, newRV_noinc((SV *)e));
}
static AV *base_pairs(pTHX_ structset *CSP_RESTRICT s, NV hb, NV stagger, bool store){
AV *out = newAV();
base_t *bases = NULL;
NV *cx = NULL, *cy = NULL, *cz = NULL;
const NV cut = hb + 2.0 * CSP_BASE_REACH;
const NV to_deg = 180.0 / CSP_PI;
cell_grid g;
UV n, i;
n = bases_find(aTHX_ s, &bases);
if (n < 2) { Safefree(bases); return out; }
Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV);
for (i = 0; i < n; i++) { cx[i] = bases[i].cx; cy[i] = bases[i].cy; cz[i] = bases[i].cz; }
/*Clear what an earlier call left on these residues, so that asking twice
replaces the answer rather than adding to it. Which residues are candidates
is decided by the residue's name and its ring atoms alone, never by either
threshold, so these are exactly the ones a previous call could have written
to.*/
if (store)
for (i = 0; i < n; i++)
(void)hv_delete(s->res_hv[bases[i].res], "base_pair", 9, G_DISCARD);
grid_build(aTHX_ &g, cx, cy, cz, n, cut);
for (i = 0; i < n; i++) {
UV bx, by, bz;
UV ci = grid_axis(cx[i] - g.x0, g.cell, g.nx);
UV cj = grid_axis(cy[i] - g.y0, g.cell, g.ny);
UV ck = grid_axis(cz[i] - g.z0, g.cell, g.nz);
UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1;
UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1;
UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1;
for (bx = ax0; bx <= ax1; bx++)
for (by = ay0; by <= ay1; by++)
for (bz = az0; bz <= az1; bz++) {
UV cell = (bx * g.ny + by) * g.nz + bz, p;
for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
UV j = g.idx[p];
const bp_def *kind;
bool swapped = 0;
NV vx, vy, vz, d, plane, sag_i, sag_j, sag;
NV bond[CSP_BP_BONDS];
unsigned short k;
bool whole = 1;
char tname[4];
HV *h;
AV *hbs;
if (j <= i) continue;//each pair once
//one residue's two rings cannot pair with each other, and
//neither can two conformers sharing a residue
if (bases[i].res == bases[j].res) continue;
kind = bp_kind_of(bases[i].one, bases[j].one, &swapped);
if (!kind) continue;
vx = cx[j] - cx[i]; vy = cy[j] - cy[i]; vz = cz[j] - cz[i];
d = nv_sqrt(vx * vx + vy * vy + vz * vz);
if (!(d <= cut)) continue;//not >: a NaN distance is no pair
for (k = 0; k < kind->n; k++) {
/*the table names the purine's atom first, so a pair whose
purine is the later residue reads its two names backwards*/
const char *an = kind->atom[k][swapped ? 1 : 0];
const char *bn = kind->atom[k][swapped ? 0 : 1];
NV ax, ay, az, bx2, by2, bz2, dx, dy, dz;
if (!atom_xyz(aTHX_ bases[i].atoms, an, &ax, &ay, &az)
|| !atom_xyz(aTHX_ bases[j].atoms, bn, &bx2, &by2, &bz2)) {
whole = 0;
break;
}
dx = bx2 - ax; dy = by2 - ay; dz = bz2 - az;
bond[k] = nv_sqrt(dx * dx + dy * dy + dz * dz);
if (bond[k] > hb) { whole = 0; break; }
}
if (!whole) continue;
sag_i = nv_fabs(vx * bases[i].nx + vy * bases[i].ny + vz * bases[i].nz);
sag_j = nv_fabs(vx * bases[j].nx + vy * bases[j].ny + vz * bases[j].nz);
sag = (sag_i > sag_j) ? sag_i : sag_j;
if (sag > stagger) continue;
plane = vec_angle_capped(bases[i].nx, bases[i].ny, bases[i].nz,
bases[j].nx, bases[j].ny, bases[j].nz);
if (plane < 0.0) continue;
/*the pair is named in the order it is reported, so that the
two letters and the two resname fields read the same way round*/
tname[0] = bases[i].one; tname[1] = '-';
tname[2] = bases[j].one; tname[3] = '\0';
h = newHV();
(void)hv_stores(h, "type", newSVpvn(tname, 3));
(void)hv_stores(h, "saenger", newSVuv((UV)kind->saenger));
pi_field(aTHX_ h, "chain1", 6, s->res_hv[bases[i].res], "chain", 5);
pi_field(aTHX_ h, "residue1", 8, s->res_hv[bases[i].res], "key", 3);
pi_field(aTHX_ h, "resname1", 8, s->res_hv[bases[i].res], "resname", 7);
pi_field(aTHX_ h, "chain2", 6, s->res_hv[bases[j].res], "chain", 5);
pi_field(aTHX_ h, "residue2", 8, s->res_hv[bases[j].res], "key", 3);
pi_field(aTHX_ h, "resname2", 8, s->res_hv[bases[j].res], "resname", 7);
(void)hv_stores(h, "distance", newSVnv(d));
(void)hv_stores(h, "plane_angle", newSVnv(plane * to_deg));
(void)hv_stores(h, "stagger", newSVnv(sag));
hbs = newAV();
for (k = 0; k < kind->n; k++) {
HV *e = newHV();
(void)hv_stores(e, "atom1", newSVpv(kind->atom[k][swapped ? 1 : 0], 0));
(void)hv_stores(e, "atom2", newSVpv(kind->atom[k][swapped ? 0 : 1], 0));
(void)hv_stores(e, "distance", newSVnv(bond[k]));
av_push(hbs, newRV_noinc((SV *)e));
}
(void)hv_stores(h, "hbonds", newRV_noinc((SV *)hbs));
av_push(out, newRV_noinc((SV *)h));
if (store) {
bp_note(aTHX_ s->res_hv[bases[i].res], s->res_hv[bases[j].res],
tname, kind->saenger);
tname[0] = bases[j].one; tname[2] = bases[i].one;
bp_note(aTHX_ s->res_hv[bases[j].res], s->res_hv[bases[i].res],
tname, kind->saenger);
}
}
}
}
grid_free(aTHX_ &g);
nucbase_t *bases = NULL;
NV *cx = NULL, *cy = NULL, *cz = NULL;
const NV to_deg = 180.0 / CSP_PI;
cell_grid g;
UV n, i;
n = stacks_find(aTHX_ s, &bases);
if (n < 2) { Safefree(bases); return out; }
Newx(cx, n, NV); Newx(cy, n, NV); Newx(cz, n, NV);
for (i = 0; i < n; i++) { cx[i] = bases[i].cx; cy[i] = bases[i].cy; cz[i] = bases[i].cz; }
/*Clear what an earlier call left behind, so that asking twice replaces the
answer rather than adding to it. Which residues are candidates is decided
by the residue's name and its atoms alone, never by either cutoff, so these
are exactly the ones a previous call could have written to.*/
if (store)
for (i = 0; i < n; i++)
(void)hv_delete(s->res_hv[bases[i].res], "base_stack", 10, G_DISCARD);
grid_build(aTHX_ &g, cx, cy, cz, n, dist_cut);
for (i = 0; i < n; i++) {
UV bx, by, bz;
UV ci = grid_axis(cx[i] - g.x0, g.cell, g.nx);
UV cj = grid_axis(cy[i] - g.y0, g.cell, g.ny);
UV ck = grid_axis(cz[i] - g.z0, g.cell, g.nz);
UV ax0 = ci ? ci - 1 : 0, ax1 = (ci + 1 < g.nx) ? ci + 1 : g.nx - 1;
UV ay0 = cj ? cj - 1 : 0, ay1 = (cj + 1 < g.ny) ? cj + 1 : g.ny - 1;
UV az0 = ck ? ck - 1 : 0, az1 = (ck + 1 < g.nz) ? ck + 1 : g.nz - 1;
for (bx = ax0; bx <= ax1; bx++)
for (by = ay0; by <= ay1; by++)
for (bz = az0; bz <= az1; bz++) {
UV cell = (bx * g.ny + by) * g.nz + bz, p;
for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
UV j = g.idx[p];
NV vx, vy, vz, d0, d1, d2, cosw, omega, xi = 0.0, score;
bool have_xi = 0;
char tname[4];
HV *h;
unsigned short k;
if (j <= i) continue;//each pair once, the earlier residue first
//two conformers of one residue are not two bases
if (bases[i].res == bases[j].res) continue;
vx = cx[j] - cx[i]; vy = cy[j] - cy[i]; vz = cz[j] - cz[i];
d0 = nv_sqrt(vx * vx + vy * vy + vz * vz);
if (d0 > dist_cut || !(d0 > 0.0)) continue;
/*d2: the 5' base's two normals are its centre of mass plus and
minus a x b, and the one that lands nearer the 3' base's centre
of mass is the one equation 9 wants -- the base has two faces
and the 3' base is over one of them.*/
d1 = bases[i].nlen;
d2 = 0.0;
for (k = 0; k < 2; k++) {
const NV sign = k ? -1.0 : 1.0;
const NV ex = vx - sign * bases[i].nx;
const NV ey = vy - sign * bases[i].ny;
const NV ez = vz - sign * bases[i].nz;
const NV e = nv_sqrt(ex * ex + ey * ey + ez * ez);
if (k == 0 || e < d2) d2 = e;
}
/*equation 9, the law of cosines. The cosine is clamped before
acos() sees it for the reason vec_angle_capped() clamps its
own: a value a fraction of an ulp outside [-1, 1] is a NaN
that would travel all the way out to the caller*/
cosw = (d0 * d0 + d1 * d1 - d2 * d2) / (2.0 * d0 * d1);
if (cosw > 1.0) cosw = 1.0; else if (cosw < -1.0) cosw = -1.0;
omega = nv_acos(cosw) * to_deg;
if (omega <= omega_cut) {
/*equation 10 as PDB_stacker computes it: the 3' base's
normal is redrawn from the 5' base's centre of mass, so the
vector compared is (CoM3 - CoM5) +/- n3, and the smaller of
the two answers is Xi. atan2(|u x v|, |u . v|) rather than
the arcsine the paper prints: it is the same angle for
vectors this cannot fold past 90 degrees, and it keeps its
precision near 0, which is where a good stack sits and where
an arcsine of a quotient near 0 has the least of it.*/
for (k = 0; k < 2; k++) {
const NV sign = k ? -1.0 : 1.0;
const NV ux = bases[i].nx, uy = bases[i].ny, uz = bases[i].nz;
const NV wx2 = vx + sign * bases[j].nx;
const NV wy2 = vy + sign * bases[j].ny;
const NV wz2 = vz + sign * bases[j].nz;
const NV qx = uy * wz2 - uz * wy2;
const NV qy = uz * wx2 - ux * wz2;
const NV qz = ux * wy2 - uy * wx2;
const NV cr = nv_sqrt(qx * qx + qy * qy + qz * qz);
const NV dp = ux * wx2 + uy * wy2 + uz * wz2;
NV t;
if (!(nv_fabs(dp) > 0.0) && !(cr > 0.0)) continue;
t = nv_atan2(cr, nv_fabs(dp)) * to_deg;
if (!have_xi || t < xi) { xi = t; have_xi = 1; }
}
}
score = have_xi ? stack_score(d0, omega, xi, dist_cut, omega_cut) : 0.0;
//named in the order it is reported, so the two letters and the
//two resname fields read the same way round
tname[0] = bases[i].one; tname[1] = '-';
tname[2] = bases[j].one; tname[3] = '\0';
h = newHV();
(void)hv_stores(h, "type", newSVpvn(tname, 3));
pi_field(aTHX_ h, "chain1", 6, s->res_hv[bases[i].res], "chain", 5);
pi_field(aTHX_ h, "residue1", 8, s->res_hv[bases[i].res], "key", 3);
pi_field(aTHX_ h, "resname1", 8, s->res_hv[bases[i].res], "resname", 7);
pi_field(aTHX_ h, "chain2", 6, s->res_hv[bases[j].res], "chain", 5);
pi_field(aTHX_ h, "residue2", 8, s->res_hv[bases[j].res], "key", 3);
pi_field(aTHX_ h, "resname2", 8, s->res_hv[bases[j].res], "resname", 7);
(void)hv_stores(h, "distance", newSVnv(d0));
(void)hv_stores(h, "omega", newSVnv(omega));
if (have_xi) (void)hv_stores(h, "xi", newSVnv(xi));
(void)hv_stores(h, "score", newSVnv(score));
(void)hv_stores(h, "stacked", newSViv(score > 50.0 ? 1 : 0));
av_push(out, newRV_noinc((SV *)h));
if (store) {
stack_note(aTHX_ s->res_hv[bases[i].res], s->res_hv[bases[j].res],
tname, d0, omega, have_xi ? &xi : NULL, score, 1);
tname[0] = bases[j].one; tname[2] = bases[i].one;
stack_note(aTHX_ s->res_hv[bases[j].res], s->res_hv[bases[i].res],
tname, d0, omega, have_xi ? &xi : NULL, score, 0);
}
}
}
}
grid_free(aTHX_ &g);
{ "CB", "CG", "CD", "OE1" }, { "CB", "CG", "SD", "CE" }
};
static const char *const chi4_a[2][4] = {
{ "CG", "CD", "NE", "CZ" }, { "CG", "CD", "CE", "NZ" }
};
static const char *const chi5_a[1][4] = { { "CD", "NE", "CZ", "NH1" } };
/*The torsion angle about the p1-p2 bond, in radians, by the usual construction:
project the two outer bonds onto the plane across the middle one and take the
angle between them, signed by which side of that plane the second falls on.
False when there is no such angle, which is when either outer bond lies along
the middle one -- four collinear atoms have no torsion, and every value is as
good as every other. A structure with real coordinates never gets close, and
one built on a straight line (t/data/mini.pdb, whose atoms are laid out along a
line on purpose) is entirely made of them. The alternative is to return the
zero that atan2(0, 0) gives, which is a number where there is no answer.
The test is on the shorter projected length against the bond it was projected
from, which is the sine of the angle between them, and the two cases are nowhere
near each other. Measured: over phi, psi, omega, chi1 and chi2 of 1A42 the
smallest that ratio gets is 0.736, because a real bond angle is nowhere near
straight; over the deliberately collinear t/data/mini.pdb it runs from 5.4e-7 to
1.1e-6, which is float32 rounding on coordinates that are collinear exactly.
1e-3 sits a thousand times above the second and seven hundred times below the
first. t/data/features.py applies the same rule with the same constant, so the
frozen answer and this agree about which angles exist.*/
#define CSP_COLLINEAR 1e-3
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){
NV b0[3], b1[3], b2[3], v[3], w[3], cr[3], len, d0, d2, x, y;
unsigned short k;
for (k = 0; k < 3; k++) {
b0[k] = p0[k] - p1[k];
b1[k] = p2[k] - p1[k];
b2[k] = p3[k] - p2[k];
}
len = nv_sqrt(b1[0] * b1[0] + b1[1] * b1[1] + b1[2] * b1[2]);
if (!(len > 0.0)) return 0;//two atoms at one position: no bond, no angle
for (k = 0; k < 3; k++) b1[k] /= len;
d0 = b0[0] * b1[0] + b0[1] * b1[1] + b0[2] * b1[2];
d2 = b2[0] * b1[0] + b2[1] * b1[1] + b2[2] * b1[2];
for (k = 0; k < 3; k++) {
v[k] = b0[k] - d0 * b1[k];
w[k] = b2[k] - d2 * b1[k];
}
{
NV l0 = nv_sqrt(b0[0] * b0[0] + b0[1] * b0[1] + b0[2] * b0[2]);
NV l2 = nv_sqrt(b2[0] * b2[0] + b2[1] * b2[1] + b2[2] * b2[2]);
NV lv = nv_sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
NV lw = nv_sqrt(w[0] * w[0] + w[1] * w[1] + w[2] * w[2]);
if (!(l0 > 0.0) || !(l2 > 0.0)) return 0;
if (lv <= l0 * CSP_COLLINEAR || lw <= l2 * CSP_COLLINEAR) return 0;
}
cr[0] = b1[1] * v[2] - b1[2] * v[1];
cr[1] = b1[2] * v[0] - b1[0] * v[2];
cr[2] = b1[0] * v[1] - b1[1] * v[0];
x = v[0] * w[0] + v[1] * w[1] + v[2] * w[2];
y = cr[0] * w[0] + cr[1] * w[1] + cr[2] * w[2];
/*an infinite coordinate passes every test above and arrives here as a
NaN, which is no angle: refused, as a point that makes none is*/
{
const NV angle = nv_atan2(y, x);
if (!nv_is_finite(angle)) return FALSE;
*out = angle;
}
return 1;
}
//the four named atoms of one residue, or of a pair of them: `which' says where
//each comes from, 0 for the first residue's hash and 1 for the second's
static bool four_atoms(pTHX_ HV *CSP_RESTRICT a, HV *CSP_RESTRICT b,
const char *const *CSP_RESTRICT name,
const unsigned short *CSP_RESTRICT which,
NV p[4][3])
{
for (unsigned short k = 0; k < 4; k++) {
HV *from = which[k] ? b : a;
if (!from) return 0;
if (!atom_xyz(aTHX_ from, name[k], &p[k][0], &p[k][1], &p[k][2])) return 0;
}
return 1;
}
//Biopython's PPBuilder radius: two residues are peptide-bonded when the C of
//the earlier is this close to the N of the later
#define CSP_PEPTIDE_BOND 1.8
//the backbone of every residue of the walk, read the first time it is asked for
static const bb_xyz *bb_get(pTHX_ structset *CSP_RESTRICT s)
{
if (s->bb) return s->bb;
Newxz(s->bb, s->n_res ? s->n_res : 1, bb_xyz);
for (UV r = 0; r < s->n_res; r++) {
bb_xyz *b = &s->bb[r];
HV *at = hvf_hv(aTHX_ s->res_hv[r], "atoms", 5);
if (!at) continue;
b->has_n = atom_xyz(aTHX_ at, "N", &b->n[0], &b->n[1], &b->n[2]);
b->has_ca = atom_xyz(aTHX_ at, "CA", &b->ca[0], &b->ca[1], &b->ca[2]);
b->has_c = atom_xyz(aTHX_ at, "C", &b->c[0], &b->c[1], &b->c[2]);
b->has_o = atom_xyz(aTHX_ at, "O", &b->o[0], &b->o[1], &b->o[2]);
}
return s->bb;
}
//is residue prev's C within cut of residue next's N, both residues of the walk
static bool peptide_linked(pTHX_ structset *CSP_RESTRICT s, UV prev, UV next, NV cut){
const bb_xyz *bb = bb_get(aTHX_ s);
NV dx, dy, dz;
if (!bb[prev].has_c || !bb[next].has_n) return 0;
dx = bb[next].n[0] - bb[prev].c[0];
dy = bb[next].n[1] - bb[prev].c[1];
dz = bb[next].n[2] - bb[prev].c[2];
return (dx * dx + dy * dy + dz * dz) < cut * cut;
}
//one chi, from whichever of its alternatives the residue is built from
static bool chi_of(pTHX_ HV *CSP_RESTRICT atoms, const char *const alt[][4], unsigned short n_alt, NV *CSP_RESTRICT out){
static const unsigned short here[4] = { 0, 0, 0, 0 };
unsigned short k;
for (k = 0; k < n_alt; k++) {
bool have_nu = 1;
unsigned short k;
for (k = 0; k < (unsigned short)C_ARRAY_LENGTH(nuc_keys); k++)
(void)hv_delete(me, nuc_keys[k], (I32)strlen(nuc_keys[k]), G_DISCARD);
if (prev_linked && four_atoms(aTHX_ pv_at, my_at, alpha_n, prev_w, p)
&& dihedral4(p[0], p[1], p[2], p[3], &v))
(void)hv_stores(me, "alpha", newSVnv(v * to_deg));
if (four_atoms(aTHX_ my_at, NULL, beta_n, here, p)
&& dihedral4(p[0], p[1], p[2], p[3], &v))
(void)hv_stores(me, "beta", newSVnv(v * to_deg));
if (four_atoms(aTHX_ my_at, NULL, gamma_n, here, p)
&& dihedral4(p[0], p[1], p[2], p[3], &v))
(void)hv_stores(me, "gamma", newSVnv(v * to_deg));
if (four_atoms(aTHX_ my_at, NULL, delta_n, here, p)
&& dihedral4(p[0], p[1], p[2], p[3], &v))
(void)hv_stores(me, "delta", newSVnv(v * to_deg));
if (next_linked) {
if (four_atoms(aTHX_ my_at, nx_at, eps_n, eps_w, p)
&& dihedral4(p[0], p[1], p[2], p[3], &v))
(void)hv_stores(me, "epsilon", newSVnv(v * to_deg));
if (four_atoms(aTHX_ my_at, nx_at, zeta_n, zeta_w, p)
&& dihedral4(p[0], p[1], p[2], p[3], &v))
(void)hv_stores(me, "zeta", newSVnv(v * to_deg));
}
{
NV n9[3];
const char *const *CSP_RESTRICT chi_n =
atom_xyz(aTHX_ my_at, "N9", &n9[0], &n9[1], &n9[2]) ? chi_pur : chi_pyr;
if (four_atoms(aTHX_ my_at, NULL, chi_n, here, p)
&& dihedral4(p[0], p[1], p[2], p[3], &v)) {
const NV deg = v * to_deg;
(void)hv_stores(me, "chi", newSVnv(deg));
(void)hv_stores(me, "glycosidic",
newSVpv(nv_fabs(deg) <= 90.0 ? "syn" : "anti", 0));
}
}
for (k = 0; k < 5; k++) {
if (four_atoms(aTHX_ my_at, NULL, nu_n[k], here, p)
&& dihedral4(p[0], p[1], p[2], p[3], &nu[k])) continue;
have_nu = 0;
break;
}
if (have_nu) {
/*sin 36 + sin 72, the constant of Altona and Sundaralingam's equation 1.
Computed rather than written out, so that it is exact to whatever width
this perl's NV is rather than to however many digits were typed.*/
const NV k1 = nv_sin(CSP_PI / 5.0) + nv_sin(2.0 * CSP_PI / 5.0);
const NV num = (nu[4] + nu[1]) - (nu[3] + nu[0]);
const NV den = 2.0 * nu[2] * k1;
AV *list = newAV();
for (k = 0; k < 5; k++) av_push(list, newSVnv(nu[k] * to_deg));
(void)hv_stores(me, "nu", newRV_noinc((SV *)list));
/*A ring flat to the last bit has no phase -- every P describes it as
well as every other, and atan2(0, 0) would answer 0 as though one of
them did. Real geometry never gets there; a fixture built on a straight
line has no nu at all, dihedral4() having refused them. Nor does a
phase that is not a number name a pucker: it is cast to an index
below, and a NaN cast to an integer is undefined behaviour.*/
if ((num != 0.0 || den != 0.0) && nv_is_finite(num) && nv_is_finite(den)) {
const NV pr = nv_atan2(num, den);
const NV cp = nv_cos(pr);
NV phase = pr * to_deg;
if (phase < 0.0) phase += 360.0;
//an angle a hair below zero adds the whole turn and rounds to it,
//and 360 is 0: the cycle closes, and the range is documented as
//0 to 360 with the upper end not in it
if (phase >= 360.0) phase = 0.0;
(void)hv_stores(me, "pucker_phase", newSVnv(phase));
(void)hv_stores(me, "pucker",
newSVpv(nuc_pucker[(unsigned short)(phase / 36.0)], 0));
//cos P is zero only when nu2 is exactly zero, where the amplitude
//is the other half of the fraction; there is no ring like that in
//a real file and none is invented here
if (cp != 0.0)
(void)hv_stores(me, "pucker_amplitude", newSVnv(nu[2] / cp * to_deg));
}
}
}
/*chain_torsions() -- the same angles again, as one array per torsion.
The block above writes each angle onto the residue it belongs to, which is where
a question about one residue is asked. A question about the chain -- a
Ramachandran plot, a rotamer census, the mean of an angle along a helix -- wants
them as columns instead, so they are gathered onto the chain as well, under
`torsions': $info->{chains}{A}{torsions}{phi} and its relatives.
Each array runs parallel to the chain's `residue_order', one element per residue
in the order the walk saw them, and a residue with no such torsion holds an
undef rather than being left out -- the position is what says which residue a
value came from, and a compacted array would lose that. A key no residue in the
chain has at all is absent instead, so a protein chain carries phi, psi, omega
and chi and a nucleic acid one alpha to zeta, and neither carries eleven arrays
of nothing.
The elements are copies of the residues' scalars, so writing to one does not
reach back; `chi' and `nu' copy the reference, which means the chain and the
residue name one list between them, as two references to a thing always do.*/
/*every key the torsions above write onto a residue: the amino acid ones, then
the nucleotide ones, which are nuc_keys[] with the chi the two kinds share
lifted out of it*/
static const char *const tors_name[] = {
"phi", "psi", "omega", "chi",
"alpha", "beta", "gamma", "delta", "epsilon", "zeta",
"nu", "pucker", "pucker_phase", "pucker_amplitude", "glycosidic"
};
#define NTORS ((unsigned short)(sizeof tors_name / sizeof *tors_name))
static void chain_torsions(pTHX_ HV *CSP_RESTRICT chain, HV *CSP_RESTRICT *CSP_RESTRICT res, UV n){
HV *out = newHV();
AV *col[NTORS];
STRLEN len[NTORS];
bool any[NTORS];//FALSE until some residue turns out to have the key
unsigned short k;
UV i;
for (k = 0; k < NTORS; k++) {
name is deleted by the preprocessor and its declaration becomes a syntax
error. 0.03 shipped with it and a Strawberry 5.42.2 smoker rejected the
whole file over the one word.*/
touch *CSP_RESTRICT touching = NULL;
UV touch_cap = 32;
cell_grid g;
UV n = 0, i, r, lo;
if (s->n_atom == 0) return out;
Newx(heavy, s->n_atom, unsigned char);
for (i = 0; i < s->n_atom; i++)
heavy[i] = atom_is_h(aTHX_ s->atom_hv[i]) ? 0 : 1;
Newx(hx, s->n_atom, NV); Newx(hy, s->n_atom, NV); Newx(hz, s->n_atom, NV);
Newx(hres, s->n_atom, UV);
for (r = 0; r < s->n_res; r++) {
for (i = s->res_first[r]; i < s->res_last[r]; i++) {
if (!heavy[i]) continue;
hx[n] = s->x[i]; hy[n] = s->y[i]; hz[n] = s->z[i];
hres[n] = r;
n++;
}
}
Safefree(heavy);
if (n == 0) {
Safefree(hx); Safefree(hy); Safefree(hz); Safefree(hres);
return out;
}
grid_build(aTHX_ &g, hx, hy, hz, n, cut);
Newx(touching, touch_cap, touch);
if (store)
for (r = 0; r < s->n_res; r++)
(void)hv_stores(s->res_hv[r], "n_contacts", newSVuv(0));
/*The heavy atoms were gathered residue by residue, so one residue's are one
run of them and hres is never anything but ascending: `lo' walks that run
forward rather than each residue scanning the whole array for its own atoms.
The scan was the whole cost of this function on anything large -- residues
times heavy atoms, which is 4fqr's 11,406 by 88,416 -- and asking for the
contacts of that entry took 2.25 s. It is 0.15 s this way and finds the
same pairs: the loop body has not changed, only how it is reached.*/
lo = 0;
for (r = 0; r < s->n_res; r++) {
UV n_touch = 0, k, hi = lo;
while (hi < n && hres[hi] == r) hi++;
for (i = lo; i < hi; i++) {
UV bx, by, bz, ci, cj, ck;
ci = grid_axis(hx[i] - g.x0, g.cell, g.nx);
cj = grid_axis(hy[i] - g.y0, g.cell, g.ny);
ck = grid_axis(hz[i] - g.z0, g.cell, g.nz);
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++)
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++)
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) {
UV cell = (bx * g.ny + by) * g.nz + bz, p;
for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
UV j = g.idx[p];
NV dx, dy, dz, d2, d;
if (hres[j] <= r) continue;//each residue pair once
dx = hx[j] - hx[i]; dy = hy[j] - hy[i]; dz = hz[j] - hz[i];
d2 = dx * dx + dy * dy + dz * dz;
if (!(d2 < cut * cut)) continue;//not >=: a NaN distance is no contact
d = nv_sqrt(d2);
for (k = 0; k < n_touch; k++)
if (touching[k].res == hres[j]) break;
if (k < n_touch) {
if (d < touching[k].d) touching[k].d = d;
} else {
if (n_touch == touch_cap) { touch_cap *= 2; Renew(touching, touch_cap, touch); }
touching[n_touch].res = hres[j];
touching[n_touch].d = d;
n_touch++;
}
}
}
}
for (k = 0; k < n_touch; k++) {
HV *h = newHV();
pi_field(aTHX_ h, "chain1", 6, s->res_hv[r], "chain", 5);
pi_field(aTHX_ h, "residue1", 8, s->res_hv[r], "key", 3);
pi_field(aTHX_ h, "chain2", 6, s->res_hv[touching[k].res], "chain", 5);
pi_field(aTHX_ h, "residue2", 8, s->res_hv[touching[k].res], "key", 3);
(void)hv_stores(h, "distance", newSVnv(touching[k].d));
av_push(out, newRV_noinc((SV *)h));
if (!store) continue;
{
SV **a = hv_fetch(s->res_hv[r], "n_contacts", 10, 0);
SV **b = hv_fetch(s->res_hv[touching[k].res], "n_contacts", 10, 0);
if (a && *a) sv_setuv(*a, SvUV(*a) + 1);
if (b && *b) sv_setuv(*b, SvUV(*b) + 1);
}
}
lo = hi;
}
Safefree(touching);
grid_free(aTHX_ &g);
Safefree(hx); Safefree(hy); Safefree(hz); Safefree(hres);
return out;
}
/*Is any conformer of one CA within CSP_HSE_LINK of any conformer of the other?
An atom with alternate conformers lists every one of them, its own included, in
altlocs; one without has only its own coordinates.*/
static bool ca_linked(pTHX_ HV *CSP_RESTRICT at1, HV *CSP_RESTRICT at2){
HV *ca[2];
AV *alt[2];
SSize_t top[2], i, j;
for (unsigned short k = 0; k < 2; k++) {
ca[k] = hvf_hv(aTHX_ k ? at2 : at1, "CA", 2);
if (!ca[k]) return 0;
alt[k] = hvf_av(aTHX_ ca[k], "altlocs", 7);
if (alt[k] && av_len(alt[k]) < 0) alt[k] = NULL;
top[k] = alt[k] ? av_len(alt[k]) : 0;
}
for (i = 0; i <= top[0]; i++) {
HV *p = ca[0];
NV px, py, pz;
if (alt[0]) {
SV **e = av_fetch(alt[0], i, 0);
if (!e || !SvROK(*e) || SvTYPE(SvRV(*e)) != SVt_PVHV) continue;
p = (HV *)SvRV(*e);
}
/*One of the twenty, not merely an amino acid. Biopython's
CaPPBuilder.build_peptides() runs with aa_only => 1, which keeps only
the standard names, so a selenomethionine is invisible to HSExposureCB
-- it neither gets a figure nor counts towards anybody else's. Matching
that is what lets t/features.t hold this to it; the cost is that a
structure full of modified residues gets a count that ignores them*/
if (s->res_type[r] != RT_AA || !s->res_std[r]) continue;
at = hvf_hv(aTHX_ s->res_hv[r], "atoms", 5);
if (at && hvf_hv(aTHX_ at, "CA", 2)) ok[r] = at;
}
//a residue is in a polypeptide if it is linked to its neighbour on either side
for (c = 0; c < s->n_chain; c++)
for (r = s->chain_first[c] + 1; r < s->chain_last[c]; r++)
if (ok[r - 1] && ok[r] && ca_linked(aTHX_ ok[r - 1], ok[r]))
inpp[r - 1] = inpp[r] = TRUE;
Newx(cax, s->n_res, NV); Newx(cay, s->n_res, NV); Newx(caz, s->n_res, NV);
Newx(cares, s->n_res, UV);
for (r = 0; r < s->n_res; r++) {
if (!inpp[r]) continue;
if (!atom_xyz(aTHX_ ok[r], "CA", &cax[n], &cay[n], &caz[n])) continue;
cares[n] = r;
n++;
}
Safefree(ok); Safefree(inpp);
if (n == 0) {
Safefree(cax); Safefree(cay); Safefree(caz); Safefree(cares);
return;
}
grid_build(aTHX_ &g, cax, cay, caz, n, radius);
for (r = 0; r < n; r++) {
HV *me = s->res_hv[cares[r]];
HV *at = hvf_hv(aTHX_ me, "atoms", 5);
NV pcb[3], bx, by, bz;
UV up = 0, down = 0, ax, ay, az;
if (!at) continue;
/*Glycine gets the virtual CB and nothing else does: a side chain
deposited without its CB, as 5x0w's are -- LYS, SER and THR cut back to
the backbone -- has no figure from HSExposureCB._get_cb(), though its CA
still counts towards its neighbours'.*/
if (s->res_key[cares[r]] == K3('G','L','Y')) {
if (!gly_cb(aTHX_ at, pcb)) continue;
} else if (atom_xyz(aTHX_ at, "CB", &bx, &by, &bz)) {
pcb[0] = bx - cax[r]; pcb[1] = by - cay[r]; pcb[2] = bz - caz[r];
} else {
continue;//no side chain direction: no half to be on
}
{
UV ci = grid_axis(cax[r] - g.x0, g.cell, g.nx);
UV cj = grid_axis(cay[r] - g.y0, g.cell, g.ny);
UV ck = grid_axis(caz[r] - g.z0, g.cell, g.nz);
for (ax = ci ? ci - 1 : 0; ax <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); ax++)
for (ay = cj ? cj - 1 : 0; ay <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); ay++)
for (az = ck ? ck - 1 : 0; az <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); az++) {
UV cell = (ax * g.ny + ay) * g.nz + az, p;
for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
UV j = g.idx[p];
NV dx, dy, dz;
if (j == r) continue;
dx = cax[j] - cax[r]; dy = cay[j] - cay[r]; dz = caz[j] - caz[r];
if (!(dx * dx + dy * dy + dz * dz < radius * radius)) continue;//a NaN is no neighbour
if (dx * pcb[0] + dy * pcb[1] + dz * pcb[2] > 0.0) up++;
else down++;
}
}
}
(void)hv_stores(me, "hse_up", newSVuv(up));
(void)hv_stores(me, "hse_down", newSVuv(down));
}
grid_free(aTHX_ &g);
Safefree(cax); Safefree(cay); Safefree(caz); Safefree(cares);
}
/*Backbone hydrogen bonds, by Kabsch and Sander's electrostatic definition.
Kabsch, W; Sander, C (1983) Biopolymers 22(12):2577-637 put a charge of -0.42 e
on the carbonyl oxygen and +0.20 e on the amide hydrogen, their opposites on the
carbon and the nitrogen, and called the four-way Coulomb sum the bond energy:
E = 0.42 * 0.20 * 332 * (1/r_ON + 1/r_CH - 1/r_OH - 1/r_CN) kcal/mol
with the distances in angstrom. Anything below -0.5 kcal/mol is a bond. The
implementation is mdtraj's kabsch_sander(), and every rule below was checked
against it pair by pair on four real entries -- 1A42, 1A22, 1AHW and 3AU6 --
where the two agree on which bonds exist and on their energies to 4e-5 kcal/mol,
which is float32 rounding on mdtraj's side:
* the amide hydrogen is not read from the file, it is placed: one angstrom
from N along the direction of the previous residue's C=O. A crystal
structure has no hydrogens, and this is the construction that lets the
definition be used on one anyway.
* proline has no amide hydrogen at all and can never donate.
* a donor's own carbonyl, and the one its hydrogen was built from, are not
acceptors: acceptor == donor and acceptor == donor - 1 are both skipped.
The second is the important one -- an "H-bond" to the very carbonyl that
placed the hydrogen is an artefact of the construction.
* only pairs whose CA atoms are within 9 A are considered, which is DSSP's
own screen and is what the grid here is built at.
* a nitrogen has two lone pairs' worth of hydrogen to give and no more, so
each donor keeps its two best acceptors and no others.
* the energy is clipped at -9.9 kcal/mol, for the pathological case of two
atoms refined on top of each other.
**Where this departs from mdtraj**, in the same way and for the same reason as
the torsion angles: mdtraj takes "the previous residue" to be whichever one
comes before this one in the file and builds the hydrogen from its carbonyl,
even across a chain break, which puts the hydrogen somewhere the chemistry never
put it. Here the two must be peptide-bonded first. t/features.t freezes
mdtraj's answer together with whether the link is real, and holds this to the
first where the second is true.*/
#define CSP_KS_Q 27.888 //0.42 * 0.20 * 332, kcal A / mol
#define CSP_KS_CUTOFF (-0.5) //kcal/mol: below this it is a bond
#define CSP_KS_FLOOR (-9.9) //kcal/mol: no bond is reported as stronger
#define CSP_KS_CA 9.0 //angstrom: DSSP's CA-to-CA screen
#define CSP_KS_KEEP 2 //acceptors per donor
//the backbone atoms one residue offers, and whether it has them all
typedef struct {
NV n[3], ca[3], c[3], o[3];
bool whole;//all four present, so it can donate and accept
bool proline;//no amide hydrogen: it can accept but never donate
bool linked;//peptide-bonded to the residue before it in the walk
} backbone;
static void backbone_read(pTHX_ structset *CSP_RESTRICT s, backbone *CSP_RESTRICT bb, NV bond)
{
const bb_xyz *x = bb_get(aTHX_ s);
UV r;
for (r = 0; r < s->n_res; r++) {
backbone *b = &bb[r];
b->proline = (s->res_key[r] == K3('P','R','O'));
b->linked = 0;
b->whole = x[r].has_n && x[r].has_ca && x[r].has_c && x[r].has_o;
if (!b->whole) continue;
Copy(x[r].n, b->n, 3, NV);
Copy(x[r].ca, b->ca, 3, NV);
Copy(x[r].c, b->c, 3, NV);
Copy(x[r].o, b->o, 3, NV);
}
for (r = 1; r < s->n_res; r++)
bb[r].linked = peptide_linked(aTHX_ s, r - 1, r, bond);
}
//the energy of the bond from acceptor a's C=O to donor d's N-H, with the
//hydrogen already placed
static NV ks_energy(const backbone *CSP_RESTRICT a, const NV *CSP_RESTRICT h,
const NV *CSP_RESTRICT nd)
{
NV r_on = 0.0, r_ch = 0.0, r_oh = 0.0, r_cn = 0.0, e;
for (unsigned short k = 0; k < 3; k++) {
NV d;
d = a->o[k] - nd[k]; r_on += d * d;
d = a->c[k] - h[k]; r_ch += d * d;
d = a->o[k] - h[k]; r_oh += d * d;
d = a->c[k] - nd[k]; r_cn += d * d;
}
r_on = nv_sqrt(r_on); r_ch = nv_sqrt(r_ch);
r_oh = nv_sqrt(r_oh); r_cn = nv_sqrt(r_cn);
/*an atom that read as nan is no bond at all. It failed the `> 0.0' tests
below the way two atoms at one point do, and came back as the strongest
bond there is: a NaN on one carbonyl O gave eleven bonds of -9.9 to fold.pdb,
which crowded real ones out of each donor's best two.*/
if (!nv_is_finite(r_on + r_ch + r_oh + r_cn)) return 0.0;
if (!(r_on > 0.0) || !(r_ch > 0.0) || !(r_oh > 0.0) || !(r_cn > 0.0))
return CSP_KS_FLOOR;
e = CSP_KS_Q * (1.0 / r_on + 1.0 / r_ch - 1.0 / r_oh - 1.0 / r_cn);
return (e < CSP_KS_FLOOR) ? CSP_KS_FLOOR : e;
}
/*ks_compute() -- each residue's two best acceptors, and their energies.
Kept on the structset rather than returned, because the secondary structure
below reads the same table: DSSP is these bonds and nothing else, read for the
patterns they fall into. acc[r][k] is the residue whose carbonyl residue r's
amide hydrogen is bonded to, or the count of residues when there is none.*/
static void ks_compute(pTHX_ structset *CSP_RESTRICT s, const backbone *CSP_RESTRICT bb)
{
NV *CSP_RESTRICT cx = NULL, *CSP_RESTRICT cy = NULL, *CSP_RESTRICT cz = NULL;
UV *CSP_RESTRICT which = NULL;
cell_grid g;
UV n = 0, r;
Newx(s->ks_acc, s->n_res ? s->n_res * CSP_KS_KEEP : 1, UV);
Newx(s->ks_e, s->n_res ? s->n_res * CSP_KS_KEEP : 1, NV);
for (r = 0; r < s->n_res * CSP_KS_KEEP; r++) {
s->ks_acc[r] = s->n_res;//"none": one past the last residue
s->ks_e[r] = 0.0;
}
if (s->n_res == 0) return;
Newx(cx, s->n_res, NV); Newx(cy, s->n_res, NV); Newx(cz, s->n_res, NV);
Newx(which, s->n_res, UV);
for (r = 0; r < s->n_res; r++) {
if (!bb[r].whole) continue;
cx[n] = bb[r].ca[0]; cy[n] = bb[r].ca[1]; cz[n] = bb[r].ca[2];
which[n] = r;
n++;
}
if (n == 0) {
Safefree(cx); Safefree(cy); Safefree(cz); Safefree(which);
return;
}
grid_build(aTHX_ &g, cx, cy, cz, n, CSP_KS_CA);
for (UV k = 0; k < n; k++) {
UV d = which[k];
NV h[3], len;
UV bx, by, bz, ci, cj, ck;
unsigned short j;
if (bb[d].proline || !bb[d].linked) continue;
if (d == 0 || !bb[d - 1].whole) continue;
len = 0.0;
for (j = 0; j < 3; j++) {
h[j] = bb[d - 1].c[j] - bb[d - 1].o[j];
len += h[j] * h[j];
}
len = nv_sqrt(len);
if (!(len > 0.0)) continue;
for (j = 0; j < 3; j++) h[j] = bb[d].n[j] + h[j] / len;
ci = grid_axis(cx[k] - g.x0, g.cell, g.nx);
cj = grid_axis(cy[k] - g.y0, g.cell, g.ny);
ck = grid_axis(cz[k] - g.z0, g.cell, g.nz);
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g.nx ? ci + 1 : g.nx - 1); bx++)
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g.ny ? cj + 1 : g.ny - 1); by++)
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g.nz ? ck + 1 : g.nz - 1); bz++) {
UV cell = (bx * g.ny + by) * g.nz + bz, p;
for (p = g.start[cell]; p < g.start[cell + 1]; p++) {
UV q = g.idx[p], a = which[q];
NV dx, dy, dz, e;
if (a == d || (d > 0 && a == d - 1)) continue;
dx = cx[q] - cx[k]; dy = cy[q] - cy[k]; dz = cz[q] - cz[k];
if (!(dx * dx + dy * dy + dz * dz < CSP_KS_CA * CSP_KS_CA)) continue;//a NaN is no neighbour
e = ks_energy(&bb[a], h, bb[d].n);
if (!(e < CSP_KS_CUTOFF)) continue;
//keep the two best, best first
if (e < s->ks_e[d * CSP_KS_KEEP] || s->ks_acc[d * CSP_KS_KEEP] == s->n_res) {
s->ks_acc[d * CSP_KS_KEEP + 1] = s->ks_acc[d * CSP_KS_KEEP];
s->ks_e[d * CSP_KS_KEEP + 1] = s->ks_e[d * CSP_KS_KEEP];
s->ks_acc[d * CSP_KS_KEEP] = a;
s->ks_e[d * CSP_KS_KEEP] = e;
} else if (e < s->ks_e[d * CSP_KS_KEEP + 1]
|| s->ks_acc[d * CSP_KS_KEEP + 1] == s->n_res) {
s->ks_acc[d * CSP_KS_KEEP + 1] = a;
s->ks_e[d * CSP_KS_KEEP + 1] = e;
}
}
}
}
grid_free(aTHX_ &g);
Safefree(cx); Safefree(cy); Safefree(cz); Safefree(which);
}
//the bonds ks_compute() found, as a list a caller can read
static AV *hbond_list(pTHX_ structset *CSP_RESTRICT s)
{
AV *out = newAV();
UV d;
for (d = 0; d < s->n_res; d++) {
for (unsigned short k = 0; k < CSP_KS_KEEP; k++) {
UV a = s->ks_acc[d * CSP_KS_KEEP + k];
HV *h;
if (a >= s->n_res) continue;
h = newHV();
//the donor gives the hydrogen, the acceptor the carbonyl
pi_field(aTHX_ h, "donor_chain", 11, s->res_hv[d], "chain", 5);
pi_field(aTHX_ h, "donor_residue", 13, s->res_hv[d], "key", 3);
pi_field(aTHX_ h, "acceptor_chain", 14, s->res_hv[a], "chain", 5);
pi_field(aTHX_ h, "acceptor_residue", 16, s->res_hv[a], "key", 3);
(void)hv_stores(h, "energy", newSVnv(s->ks_e[d * CSP_KS_KEEP + k]));
av_push(out, newRV_noinc((SV *)h));
}
}
return out;
}
/*Secondary structure, by the Kabsch-Sander dictionary.
DSSP reads the backbone hydrogen bonds and nothing else: it gives every residue
one of eight letters for the pattern the bonds around it fall into. Kabsch, W;
Sander, C (1983) Biopolymers 22(12):2577-637 is the definition.
H alpha helix: a 4-turn beginning at this residue and the one before it
G 3-10 helix, from 3-turns; I pi helix, from 5-turns
E extended strand: a residue in a beta ladder
B isolated beta bridge: a bridge with no ladder around it
T hydrogen-bonded turn: in an n-turn but in none of the above
S bend: the chain turns through more than 70 degrees here
coil: none of them, written as a space
What follows is not the paper read afresh. It is mdtraj 1.11.1 transcribed
function for function: mdtraj/geometry/src/dssp.cpp, which is DSSP 2.2.0 ported
by Robert T. McGibbon, together with the kabsch_sander() it calls out of
}
k++;
}
}
/*The backbone, and the amide hydrogen on it.
mdtraj places the hydrogen of residue r from the carbonyl of residue r-1 in its
array: one angstrom from r's nitrogen, along the direction from that carbonyl's
carbon to its oxygen. It does so whether or not the two are bonded, whether or
not they are in the same chain, and -- see the head of this block -- whether or
not r-1 has a carbonyl at all. Here r-1 is the residue before r in the walk,
and the hydrogen is placed only when that residue is in the same DSSP chain and
does have a C and an O. A residue with no hydrogen cannot donate.
That is the one place this deliberately does not follow mdtraj to the letter,
and the two cases it covers are the two mdtraj has no answer for: the first
residue of the whole structure, which mdtraj gives a hydrogen sitting on top of
its own nitrogen, and a residue whose predecessor has no carbonyl, where mdtraj
reads off the front of its array. A hydrogen placed from either is a hydrogen
in a direction nothing chose, and over the thousand entries measured at the head
of this block, refusing to place it changes no letter.*/
static void dssp_read(pTHX_ structset *CSP_RESTRICT s, dssp_res *CSP_RESTRICT bb, const UV *CSP_RESTRICT seg){
const bb_xyz *x = bb_get(aTHX_ s);
for (UV r = 0; r < s->n_res; r++) {
dssp_res *b = &bb[r];
Zero(b, 1, dssp_res);
b->proline = (s->res_key[r] == K3('P','R','O'));
for (unsigned short k = 0; k < 3; k++) {
b->n[k] = dssp_nm(x[r].n[k]);
b->ca[k] = dssp_nm(x[r].ca[k]);
b->c[k] = dssp_nm(x[r].c[k]);
b->o[k] = dssp_nm(x[r].o[k]);
}
b->has_n = x[r].has_n; b->has_ca = x[r].has_ca;
b->has_c = x[r].has_c; b->has_o = x[r].has_o;
b->whole = b->has_n && b->has_ca && b->has_c && b->has_o;
}
for (UV r = 1; r < s->n_res; r++) {
dssp_res *b = &bb[r];
const dssp_res *p = &bb[r - 1];
float co[3], len;
if (!b->whole || b->proline) continue;
if (seg[r] != seg[r - 1] || !p->has_c || !p->has_o) continue;
dssp_sub3(p->c, p->o, co);
len = (float)sqrt((double)dssp_dot3(co, co));
if (!(len > 0.0f)) continue;
for (unsigned short k = 0; k < 3; k++) {
//one step per named float, so that each is rounded to float where
//it is in mdtraj, rather than a wider product reaching the sum
float u = co[k] / len;
float step = u * DSSP_H;
b->h[k] = b->n[k] + step;
}
b->donor = 1;
}
}
/*Keep the two lowest energies a donor has, best first.
mdtraj's store_energies(), which tests its slots for NaN because the array
kabsch_sander() fills for its own caller starts as NaN; the one the DSSP pass
fills starts as zero, so the NaN arm is never taken there and an empty slot is
the one with no acceptor in it. Which slot an acceptor lands in does not depend
on the order they arrive in.*/
static void dssp_store(UV n_res, UV *CSP_RESTRICT acc, float *CSP_RESTRICT en, UV donor, UV a, float e){
UV slot = donor * DSSP_KEEP;
if (acc[slot] >= n_res || e < en[slot]) {
acc[slot + 1] = acc[slot];
en[slot + 1] = en[slot];
acc[slot] = a;
en[slot] = e;
} else if (acc[slot + 1] >= n_res || e < en[slot + 1]) {
acc[slot + 1] = a;
en[slot + 1] = e;
}
}
/*The hydrogen bonds DSSP is read from: each residue's two best acceptors.
mdtraj walks every pair of residues and tests the CA separation first; this
walks a cell grid over the CA atoms instead, which finds the same pairs and does
not take a ribosome quadratically. The grid is only a sieve: what decides is
the float comparison against 0.81 below, which is mdtraj's own.
The cell is 0.9001 nm and not 0.9 because the two are not measuring quite the
same thing. The float dot3() carries three products and two sums, each rounded,
so it can sit as much as 4 * 2^-24 below the exact squared distance; a pair it
puts just inside 0.81 can therefore be as far apart as 0.90000011 nm, and a
0.9 nm cell would have thrown it away before the comparison that keeps it.
0.0001 nm of cell is eight hundred times that bound and costs nothing -- the
cell count changes by a part in ten thousand.
Which of two acceptors ends up in which slot does not depend on the order the
pairs arrive in -- the pair kept is the two lowest energies either way -- so the
grid's order is free. Two acceptors at bit-identical energies would be the
exception, and that is a structure built to have one.
acc[d * DSSP_KEEP + k] is the residue whose carbonyl residue d's amide hydrogen
is bonded to, or n_res where there is no such bond.*/
static void dssp_hbonds(pTHX_ structset *CSP_RESTRICT s, const dssp_res *CSP_RESTRICT bb, UV *CSP_RESTRICT acc, float *CSP_RESTRICT en){
NV *CSP_RESTRICT cx = NULL, *CSP_RESTRICT cy = NULL, *CSP_RESTRICT cz = NULL;
UV *CSP_RESTRICT which = NULL;
cell_grid g;
UV n = 0;
for (UV r = 0; r < s->n_res * DSSP_KEEP; r++) { acc[r] = s->n_res; en[r] = 0.0f; }
if (s->n_res == 0) return;
Newx(cx, s->n_res, NV); Newx(cy, s->n_res, NV); Newx(cz, s->n_res, NV);
Newx(which, s->n_res, UV);
for (UV r = 0; r < s->n_res; r++) {
if (!bb[r].whole) continue;
cx[n] = (NV)bb[r].ca[0]; cy[n] = (NV)bb[r].ca[1]; cz[n] = (NV)bb[r].ca[2];
which[n] = r;
n++;
}
if (n == 0) {
Safefree(cx); Safefree(cy); Safefree(cz); Safefree(which);
return;
}
grid_build(aTHX_ &g, cx, cy, cz, n, 0.9001);//nm; see the head of this function
atoms touching the other partner are computed a third time with that partner
taken away. Without the whole-structure surface to start from -- sasa => 0 --
the complex is computed whole.*/
typedef struct {
NV contact;//residue contacts, angstrom
NV salt;//salt bridges
NV polar;//N/O/S pairs
NV cation_pi;//cation to ring centroid
NV water;//a bridging water to each partner
NV pocket;//an atom of the first partner to any atom of the second
NV packing;//a heavy atom of the first to a heavy atom of the second
bool want_pocket;
} iface_opt;
//what an atom of either partner is, for the search across the interface
#define IA_HEAVY 0x01 //not hydrogen or deuterium
#define IA_POLAR 0x02 //N, O or S
#define IA_CATION 0x04 //LYS NZ; ARG NE, NH1, NH2
#define IA_ANION 0x08 //ASP OD1, OD2; GLU OE1, OE2
#define IA_BACKBONE 0x10 //N, CA, C, O, OXT
#define IA_IFACE 0x20 //within contact distance of the other partner
typedef struct {//a residue hash's address, and where set_build() put it
UV addr, res;
} res_addr;
static int res_addr_cmp(const void *pa, const void *pb){
const res_addr *a = (const res_addr *)pa, *b = (const res_addr *)pb;
return a->addr < b->addr ? -1 : a->addr > b->addr ? 1 : 0;
}
//which residue of s a hash is, or s->n_res when it is none of them
static UV res_addr_find(const res_addr *CSP_RESTRICT tab, UV n, UV addr, UV none){
UV lo = 0, hi = n;
while (lo < hi) {
UV mid = lo + (hi - lo) / 2;
if (tab[mid].addr < addr) lo = mid + 1;
else if (tab[mid].addr > addr) hi = mid;
else return tab[mid].res;
}
return none;
}
/*The points of a grid within cut of (px, py, pz), into *buf, which grows.
The grid's cells are at least cut wide, so the 27 around the point hold every
one of them.*/
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){
if (g->start == NULL) return 0;
UV n = 0, ci, cj, ck, bx, by, bz;
ci = grid_axis(px - g->x0, g->cell, g->nx);
cj = grid_axis(py - g->y0, g->cell, g->ny);
ck = grid_axis(pz - g->z0, g->cell, g->nz);
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g->nx ? ci + 1 : g->nx - 1); bx++)
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g->ny ? cj + 1 : g->ny - 1); by++)
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g->nz ? ck + 1 : g->nz - 1); bz++) {
UV cell = (bx * g->ny + by) * g->nz + bz, p;
for (p = g->start[cell]; p < g->start[cell + 1]; p++) {
UV j = g->idx[p];
NV dx = x[j] - px, dy = y[j] - py, dz = z[j] - pz;
/*written as the test a neighbour passes, not the one it fails: a
distance to a NaN coordinate compares false either way, and `>='
let it through, so an atom that read as nan was every atom's
neighbour -- a contact with each residue near the end cell it was
put in, at a distance of NaN*/
if (!(dx * dx + dy * dy + dz * dz < cut * cut)) continue;
if (n == *cap) { *cap = *cap ? *cap * 2 : 64; Renew(*buf, *cap, UV); }
(*buf)[n++] = j;
}
}
return n;
}
/*Whether any point of a grid is within cut of (px, py, pz): grid_within()
stopped at the first, for a question that only wants to know there is one.*/
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){
if (g->start == NULL) return 0;
UV ci, cj, ck, bx, by, bz;
ci = grid_axis(px - g->x0, g->cell, g->nx);
cj = grid_axis(py - g->y0, g->cell, g->ny);
ck = grid_axis(pz - g->z0, g->cell, g->nz);
for (bx = ci ? ci - 1 : 0; bx <= (ci + 1 < g->nx ? ci + 1 : g->nx - 1); bx++)
for (by = cj ? cj - 1 : 0; by <= (cj + 1 < g->ny ? cj + 1 : g->ny - 1); by++)
for (bz = ck ? ck - 1 : 0; bz <= (ck + 1 < g->nz ? ck + 1 : g->nz - 1); bz++) {
UV cell = (bx * g->ny + by) * g->nz + bz, p;
for (p = g->start[cell]; p < g->start[cell + 1]; p++) {
UV j = g->idx[p];
NV dx = x[j] - px, dy = y[j] - py, dz = z[j] - pz;
if (dx * dx + dy * dy + dz * dz < cut * cut) return 1;
}
}
return 0;
}
//an atom's name and element, as the classification below wants them
static unsigned char iface_class(pTHX_ HV *CSP_RESTRICT a, char one, unsigned char rtype){
unsigned char f = 0;
SV *e = hvf_sv(aTHX_ a, "element", 7);
SV *nm = hvf_sv(aTHX_ a, "name", 4);
STRLEN en = 0, nn = 0;
const char *ep = e ? SvPV_const(e, en) : "";
const char *np = nm ? SvPV_const(nm, nn) : "";
if (!(en == 1 && (*ep == 'H' || *ep == 'D'))) f |= IA_HEAVY;
if (en == 1 && (*ep == 'N' || *ep == 'O' || *ep == 'S')) f |= IA_POLAR;
if (rtype != RT_AA) return f;
if ((nn == 1 && (*np == 'N' || *np == 'C' || *np == 'O'))
|| (nn == 2 && np[0] == 'C' && np[1] == 'A')
|| (nn == 3 && memcmp(np, "OXT", 3) == 0))
f |= IA_BACKBONE;
switch (one) {
case 'K':
if (nn == 2 && memcmp(np, "NZ", 2) == 0) f |= IA_CATION;
break;
case 'R':
if ((nn == 2 && memcmp(np, "NE", 2) == 0)
|| (nn == 3 && (memcmp(np, "NH1", 3) == 0 || memcmp(np, "NH2", 3) == 0)))
f |= IA_CATION;
break;
case 'D':
if (nn == 3 && (memcmp(np, "OD1", 3) == 0 || memcmp(np, "OD2", 3) == 0))
f |= IA_ANION;
break;
case 'E':
if (nn == 3 && (memcmp(np, "OE1", 3) == 0 || memcmp(np, "OE2", 3) == 0))
f |= IA_ANION;
residue's atoms are still one run, and each partner is one range for the
kernel.*/
Newx(w.sub_first, s->n_res ? s->n_res : 1, UV);
for (sd = 1; sd <= 2; sd++)
for (r = 0; r < s->n_res; r++)
if (w.side_res[r] == sd) n_sub += s->res_last[r] - s->res_first[r];
Newx(w.map, n_sub ? n_sub : 1, UV);
Newx(w.sx, n_sub ? n_sub : 1, NV); Newx(w.sy, n_sub ? n_sub : 1, NV);
Newx(w.sz, n_sub ? n_sub : 1, NV);
if (want_surface) {
Newx(w.srad, n_sub ? n_sub : 1, NV);
Newxz(w.ex, n_sub ? n_sub : 1, unsigned char);
Newxz(w.other, n_sub ? n_sub : 1, unsigned char);
}
Newxz(w.cls, s->n_atom ? s->n_atom : 1, unsigned char);
k = 0;
for (sd = 1; sd <= 2; sd++) {
if (sd == 2) n1 = k;
for (r = 0; r < s->n_res; r++) {
if (w.side_res[r] != sd) continue;
w.sub_first[r] = k;
for (i = s->res_first[r]; i < s->res_last[r]; i++) {
w.map[k] = i;
w.sx[k] = s->x[i]; w.sy[k] = s->y[i]; w.sz[k] = s->z[i];
if (want_surface) w.srad[k] = s->rad[i];
w.side_at[i] = (unsigned char)sd;
w.cls[i] = iface_class(aTHX_ s->atom_hv[i], s->res_one[r], s->res_type[r]);
k++;
}
}
}
n_at[0] = n1;
n_at[1] = n_sub - n1;
/*Which of the partners' atoms have a neighbour outside the complex (ex) and
which have one in the other partner (other), by the kernel's own test: a
neighbour is an atom whose sphere overlaps, d < ri + rj.*/
if (n_sub && want_surface) {
NV rmax = 0.0;
const cell_grid *g;
for (i = 0; i < s->n_atom; i++) if (s->rad[i] > rmax) rmax = s->rad[i];
/*The whole-structure surface built this grid already, over these atoms
at this cutoff, and sasa_compute() kept it for here; it is built afresh
only when that surface was not computed.*/
if (s->grid.start && s->grid_cut == 2.0 * rmax) {
g = &s->grid;
} else {
grid_build(aTHX_ &w.g_all, s->x, s->y, s->z, s->n_atom, 2.0 * rmax);
g = &w.g_all;
}
for (k = 0; k < n_sub; k++) {
const UV a = w.map[k];
UV m = grid_within(aTHX_ g, s->x, s->y, s->z, s->x[a], s->y[a], s->z[a],
2.0 * rmax, &w.buf, &buf_cap), q;
for (q = 0; q < m; q++) {
const UV j = w.buf[q];
NV dx, dy, dz, sum;
if (j == a) continue;
dx = s->x[j] - s->x[a]; dy = s->y[j] - s->y[a]; dz = s->z[j] - s->z[a];
sum = s->rad[a] + s->rad[j];
if (!(dx * dx + dy * dy + dz * dz < sum * sum)) continue;//a NaN is no neighbour
if (w.side_at[j] == 0) w.ex[k] = 1;
else if (w.side_at[j] != w.side_at[a]) w.other[k] = 1;
}
}
grid_free(aTHX_ &w.g_all);
}
//the complex, then each partner alone
if (want_surface) {
Newxz(w.carea, n_sub ? n_sub : 1, NV);
Newxz(w.aarea, n_sub ? n_sub : 1, NV);
}
if (n_sub && want_surface) {
sasa_aux only;
Newx(w.pts, npts * 3, NV);
sasa_sphere(w.pts, npts);
sasa_bins_build(aTHX_ &w.bins, w.pts, npts);
w.have_bins = TRUE;
Zero(&only, 1, sasa_aux);
if (s->area) {
for (k = 0; k < n_sub; k++) w.carea[k] = s->area[w.map[k]];
only.only = w.ex;
sasa_kernel(aTHX_ w.sx, w.sy, w.sz, w.srad, n_sub, &w.bins, npts, w.carea, &only, NULL);
} else {
sasa_kernel(aTHX_ w.sx, w.sy, w.sz, w.srad, n_sub, &w.bins, npts, w.carea, NULL, NULL);
}
Copy(w.carea, w.aarea, n_sub, NV);
only.only = w.other;
if (n1)
sasa_kernel(aTHX_ w.sx, w.sy, w.sz, w.srad, n1, &w.bins, npts, w.aarea, &only, NULL);
only.only = w.other + n1;
if (n_sub > n1)
sasa_kernel(aTHX_ w.sx + n1, w.sy + n1, w.sz + n1, w.srad + n1, n_sub - n1,
&w.bins, npts, w.aarea + n1, &only, NULL);
}
if (want_surface) {
for (k = 0; k < n_sub; k++) {
const UV a = w.map[k];
const NV b = w.aarea[k] - w.carea[k];
sasa_c += w.carea[k];
alone[k < n1 ? 0 : 1] += w.aarea[k];
if (s->apolar[a]) bur_ap += b; else bur_po += b;
}
for (r = 0; r < s->n_res; r++) {
UV f, l;
if (!w.side_res[r]) continue;
f = w.sub_first[r];
l = f + (s->res_last[r] - s->res_first[r]);
for (k = f; k < l; k++) { res_c[r] += w.carea[k]; res_a[r] += w.aarea[k]; }
}
}
//the heavy atoms of each partner, for everything that follows
Newx(w.h1, n_sub ? n_sub : 1, UV); Newx(w.h2, n_sub ? n_sub : 1, UV);
for (k = 0; k < n_sub; k++) {
const UV a = w.map[k];
if (!(w.cls[a] & IA_HEAVY)) continue;
if (k < n1) w.h1[n_h1++] = a; else w.h2[n_h2++] = a;
}
Newx(w.h1x, n_h1 ? n_h1 : 1, NV); Newx(w.h1y, n_h1 ? n_h1 : 1, NV);
( run in 1.130 second using v1.01-cache-2.11-cpan-60884a8df76 )