Chem-Structure-Parser

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

   its length; 40,000 of them took a second.
 - An element worked out from an atom name is an element.  An mmCIF file
   without type_symbol read a zinc as Z, a magnesium as M and a sodium as N;
   an atom named for its own residue is now that residue's ion, and a guess
   that spells nothing is read the other way, so ' ZN ' out of its PDB
   columns is zinc and 'HB1 ' a hydrogen.
 - 5MU, 5-methyluridine, is U, as gemmi and Biopython have it, and not T.
 - A formal charge of '0-' reads as '0', which is what the mmCIF reader
   gives for the same charge.
 - A coordinate or B-factor that reads as nan or inf is left out of the
   bounding box, the centres and the B-factor range, which were NaN or not
   according to where in the file it fell.  An atom at NaN is nobody's
   neighbour in the properties: it was a contact of every residue near it at
   a distance of NaN, an acceptor of hydrogen bonds at the strongest energy
   there is, and a sugar pucker phase cast to an index.
 - One atom far from the rest no longer makes the neighbour grid slow:
   4fqr with a zinc at (9999.999, 9999.999, 9999.999) took structure_sasa()
   29.5 s, against 1.4 s without it, and takes 0.8 s.  No answer changes.
 - structure_rmsd() of atoms that lie on one line is right.  The rotation
   came out as the identity there, so three carbons along x against the
   same three along y were 1.732 A apart; they are 0, as Biopython's
   SVDSuperimposer says.
 - A string handed to structure_info_string() reads the same whether or not
   perl has upgraded it to UTF-8; an upgraded one read its accented letters

Parser.xs  view on Meta::CPAN

	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

Parser.xs  view on Meta::CPAN

#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;

Parser.xs  view on Meta::CPAN

				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;

Parser.xs  view on Meta::CPAN

			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

Parser.xs  view on Meta::CPAN

	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;
		}

Parser.xs  view on Meta::CPAN

		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];

Parser.xs  view on Meta::CPAN

	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;
}

Parser.xs  view on Meta::CPAN

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;

Parser.xs  view on Meta::CPAN

	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();

Parser.xs  view on Meta::CPAN

			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

Parser.xs  view on Meta::CPAN

				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;

Parser.xs  view on Meta::CPAN

				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

Parser.xs  view on Meta::CPAN

		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

Parser.xs  view on Meta::CPAN

		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));

Parser.xs  view on Meta::CPAN

			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++;

Parser.xs  view on Meta::CPAN

			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);

Parser.xs  view on Meta::CPAN

		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.

Parser.xs  view on Meta::CPAN

		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) {

Parser.xs  view on Meta::CPAN

			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]) {

Parser.xs  view on Meta::CPAN

	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.*/

Parser.xs  view on Meta::CPAN

		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);

README.md  view on Meta::CPAN

Measuring with the rotation it returns itself gives 3.60899. `t/rmsd.t` says so
in its header, so that the next person to compare against it knows what they
are looking at.

Atoms that lie on one line are the one shape where the three references part
company with QCP's own arithmetic. A line can be turned about itself freely,
the eigenvalue the rotation comes from is a repeated one, and the cofactors
QCP takes the rotation from all vanish; here the rotation is then found by
Jacobi rotations of the 4x4 matrix instead, and the answer is
`SVDSuperimposer`'s — 0 for three carbons along one axis against the same
three along another, where gemmi's `superpose_positions` answers NaN. Before
0.039 this module took the identity rotation there and answered 1.732 A.

## convert

    convert('2mnz.cif', '2mnz.pdb');               # mmCIF to PDB, by the names
    convert('1a22.pdb', '1a22.cif.gz');            # PDB to mmCIF, gzipped

    my $r = convert('2ll7.pdb', \my $text, to => 'mmcif', model => 1, hydrogens => 0);
    print "$r->{atoms} atoms written, $r->{rounded} numbers rounded\n";

README.md  view on Meta::CPAN

summed over every atom — the element tally, the bounding box, the B-factors,
each residue's centre — and groups every other record by record name for Perl
to take apart. Residue name lookup, three letters to one letter and the amino
acid/nucleotide/water question, is a switch on three packed bytes, and one
table serves `aa3to1()`, `res1()` and `res_type()` so the three can never
disagree.

The sums are over the finite coordinates and B-factors only. A field that says
`nan` or `inf` reads back as that number in the atom, as the file has it, and is
left out of the box, the centres and the B-factor range wherever in the file
it falls; in the physical properties an atom at NaN is nobody's neighbour, so
it makes no contact, no hydrogen bond and no torsion.

When atoms are wanted the parse builds the atom hashes itself, rather than
handing back columns for Perl to rebuild them from; building every atom twice
cost more than everything else in the read put together. When they are not
wanted — `atoms => 0` — it builds none, and the Perl that follows walks
residues rather than atoms.

Everything else is Perl. The header records are irregular, they are a few
dozen lines per file rather than hundreds of thousands, and they are where the

lib/Chem/Structure/Parser.pm  view on Meta::CPAN

Measuring with the rotation it returns itself gives 3.60899. C<t/rmsd.t> says so
in its header, so that the next person to compare against it knows what they
are looking at.

Atoms that lie on one line are the one shape where the three references part
company with QCP's own arithmetic. A line can be turned about itself freely,
the eigenvalue the rotation comes from is a repeated one, and the cofactors
QCP takes the rotation from all vanish; here the rotation is then found by
Jacobi rotations of the 4x4 matrix instead, and the answer is
C<SVDSuperimposer>'s — 0 for three carbons along one axis against the same
three along another, where gemmi's C<superpose_positions> answers NaN. Before
0.039 this module took the identity rotation there and answered 1.732 A.

=head2 convert

 convert('2mnz.cif', '2mnz.pdb');               # mmCIF to PDB, by the names
 convert('1a22.pdb', '1a22.cif.gz');            # PDB to mmCIF, gzipped

 my $r = convert('2ll7.pdb', \my $text, to => 'mmcif', model => 1, hydrogens => 0);
 print "$r->{atoms} atoms written, $r->{rounded} numbers rounded\n";

lib/Chem/Structure/Parser.pm  view on Meta::CPAN

summed over every atom — the element tally, the bounding box, the B-factors,
each residue's centre — and groups every other record by record name for Perl
to take apart. Residue name lookup, three letters to one letter and the amino
acid/nucleotide/water question, is a switch on three packed bytes, and one
table serves C<aa3to1()>, C<res1()> and C<res_type()> so the three can never
disagree.

The sums are over the finite coordinates and B-factors only. A field that says
C<nan> or C<inf> reads back as that number in the atom, as the file has it, and is
left out of the box, the centres and the B-factor range wherever in the file
it falls; in the physical properties an atom at NaN is nobody's neighbour, so
it makes no contact, no hydrogen bond and no torsion.

When atoms are wanted the parse builds the atom hashes itself, rather than
handing back columns for Perl to rebuild them from; building every atom twice
cost more than everything else in the read put together. When they are not
wanted — C<< atoms =E<gt> 0 >> — it builds none, and the Perl that follows walks
residues rather than atoms.

Everything else is Perl. The header records are irregular, they are a few
dozen lines per file rather than hundreds of thousands, and they are where the

ppport.h  view on Meta::CPAN

    s++; if (s == send || (*s != 'F' && *s != 'f')) return 0;
    s++; if (s < send && (*s == 'I' || *s == 'i')) {
      s++; if (s == send || (*s != 'N' && *s != 'n')) return 0;
      s++; if (s == send || (*s != 'I' && *s != 'i')) return 0;
      s++; if (s == send || (*s != 'T' && *s != 't')) return 0;
      s++; if (s == send || (*s != 'Y' && *s != 'y')) return 0;
      s++;
    }
    sawinf = 1;
  } else if (*s == 'N' || *s == 'n') {
    /* XXX TODO: There are signaling NaNs and quiet NaNs. */
    s++; if (s == send || (*s != 'A' && *s != 'a')) return 0;
    s++; if (s == send || (*s != 'N' && *s != 'n')) return 0;
    s++;
    sawnan = 1;
  } else
    return 0;

  if (sawinf) {
    numtype &= IS_NUMBER_NEG; /* Keep track of sign  */
    numtype |= IS_NUMBER_INFINITY | IS_NUMBER_NOT_INT;

t/properties.t  view on Meta::CPAN

		'the atoms account for the whole surface');
	is($over, 0, 'and none of them has more surface than a free sphere');
}

# ---- a coordinate that is not a number ------------------------------------
# A field that says nan is read as the NV it names, as strtod() reads it, and
# the atom is kept.  One such atom anywhere in a structure used to make the
# neighbour grid's box non-finite, which put every atom into one cell and made
# the whole surface quadratic in the atoms -- the same answer, got the slow way.
# The box is now taken over the finite atoms, and the answer for them is still
# the answer they have without the other atom there: every distance to a NaN
# compares false, so it covers none of anybody's sphere.
{
	my $atoms = <<'PDB';
ATOM      1  N   ALA A   1      10.000  10.000  10.000  1.00 20.00           N
ATOM      2  CA  ALA A   1      11.458  10.000  10.000  1.00 20.00           C
ATOM      3  C   ALA A   1      12.009  11.420  10.000  1.00 20.00           C
PDB
	my $nan = "HETATM    4  O   HOH W   1         nan  10.000  10.000  1.00 20.00           O\n";
	my $plain = structure_info_string($atoms, features => 0);
	my $odd   = structure_info_string($nan . $atoms, features => 0);
	structure_sasa($plain);
	structure_sasa($odd);
	my ($p, $o) = map { $_->{chains}{A}{residues}{1}{atoms} } $plain, $odd;
	is_deeply([ map { $o->{$_}{sasa} } qw(N CA C) ], [ map { $p->{$_}{sasa} } qw(N CA C) ],
		'an atom at NaN changes no other atom\'s surface, even as the first atom of the set');
}

# ...and it is nobody's neighbour anywhere else either.  Every neighbour test
# was written as the test a neighbour fails, `d2 >= cut2', which a NaN distance
# does not fail, so the atom was a contact of every residue near the end cell
# it was put in, at a distance of NaN; the secondary structure's energy took a
# NaN distance for two atoms at one point, the strongest bond there is; and a
# ring torsion through an infinite coordinate came out a NaN that the sugar
# pucker cast to an index into its table of names.
{
	my $i = structure_info_string(<<'PDB');
ATOM      1  CA  ALA A   1       0.000   0.000   0.000  1.00 10.00           C
ATOM      2  CA  ALA A   5      50.000  50.000  50.000  1.00 10.00           C
ATOM      3  CA  ALA B   9         nan   0.000   0.000  1.00 10.00           C
PDB
	is_deeply($i->{features}{contacts}, [], 'an atom at NaN is in no contact');

	open my $fh, '<', "$data/fold.pdb" or die "Can't open '$data/fold.pdb' with mode '<': '$!'";
	my $text = do { local $/; <$fh> };
	close $fh or die "Can't close '$data/fold.pdb': '$!'";
	(my $odd = $text) =~ s/^(ATOM.{9}O   PRO A  13    ).{8}/${1}     nan/m or die 'no PRO A 13 O';
	my $h = structure_hbonds(structure_info_string($odd));
	is_deeply([ grep { $_->{energy} <= -9.9 } @$h ], [],
		'a carbonyl O at NaN makes no hydrogen bond, at the floor or anywhere');
	is_deeply([ grep { $_->{acceptor_residue} eq '13' } @$h ], [],
		'and its residue accepts none');

	open $fh, '<', "$data/rna.pdb" or die "Can't open '$data/rna.pdb' with mode '<': '$!'";
	$text = do { local $/; <$fh> };
	close $fh or die "Can't close '$data/rna.pdb': '$!'";
	(my $inf = $text) =~ s/^(ATOM.{9}C2'.{14}).{8}/${1}     inf/m or die "no C2'";
	my $r = structure_info_string($inf);
	my @res = map { my $c = $r->{chains}{$_}; map { $c->{residues}{$_} } @{ $c->{residue_order} } }
	          @{ $r->{chain_order} };

t/rmsd.t  view on Meta::CPAN


#--------
# atoms on one line, which can be turned about it freely.  The key matrix's
# largest eigenvalue is then a repeated one, every row of cofactors
# qcp_rotation() takes the quaternion from vanishes, and it took the identity
# rotation instead: three carbons along x against the same three along y came
# back 1.732 A apart, and an O2 against another 0.856 A.
#
# The answers are Biopython 1.85's Bio.SVDSuperimposer, as written below, for
# these exact coordinates on 2026-10-09.  gemmi 0.7.5's superpose_positions is
# no reference here: it answers NaN for the first ('More than 50 iterations
# needed!') and about 1e-4 A for the two that are only nearly on a line, the
# cancellation qcp_rotation()'s comment is about.  Before 0.039 this module
# answered 9.4e-5 and 8.5e-5 A for those two.
#
# The bound is absolute: the answers are 0, or a residual of 5.2e-7 A that the
# rounding of the last set's coordinates leaves, and the largest difference
# from Biopython observed on a double perl is 3.6e-16 A -- the coordinates' own
# rounding at a few angstroms.  1e-12 leaves the long double and quadmath perls
# room to answer the exact cases nearer zero, and is still eleven orders of
# magnitude under the answers the identity rotation gave.

t/structure.t  view on Meta::CPAN

		my ($name, $id, $why) = @$w;
		open my $out, '>', "$dir/$name" or die "Can't open '$dir/$name' with mode '>': '$!'";
		print {$out} $text;
		close $out or die "Can't close '$dir/$name': '$!'";
		is(structure_info("$dir/$name", features => 0, format => 'pdb')->{id}, $id, $why);
	}
}

#--------
# a coordinate that reads as nan.  The bounding box, the centres and the
# B-factor extremes are over the finite values only; they took a NaN 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 left out.
#--------
{
	my $nan  = "ATOM      1  N   ALA A   1         nan   5.000   5.000  1.00   nan           N\n";
	my $real = "ATOM      2  CA  ALA A   1       5.000   5.000   5.000  1.00 10.00           C\n";
	my $first  = structure_info_string($nan . $real,  features => 0)->{stats};
	my $second = structure_info_string($real . $nan, features => 0)->{stats};
	is_deeply([ @{ $first->{bbox} }{qw(xmin xmax)}, $first->{bfactor}{max} ], [ 5, 5, 10 ],
		'a NaN on the first atom does not become the box or the B-factor range');
	is_deeply($first, $second, 'and where in the file it falls makes no difference');
}

#--------
# an empty file
#--------
{
	my $empty = structure_info("$data/empty.pdb");
	is_deeply($empty->{chain_order}, [], 'an empty file has no chains');
	is($empty->{stats}{n_atoms}, 0, 'and no atoms');



( run in 3.107 seconds using v1.01-cache-2.11-cpan-60884a8df76 )