diff --git a/docs/CPU_DATA_ANALYSIS_REFINEMENT.md b/docs/CPU_DATA_ANALYSIS_REFINEMENT.md index 50d7b697e..827f38946 100644 --- a/docs/CPU_DATA_ANALYSIS_REFINEMENT.md +++ b/docs/CPU_DATA_ANALYSIS_REFINEMENT.md @@ -184,6 +184,18 @@ analytic derivatives: above it, $d_0$ the sum of the energy types' van der Waals radii, 2.6 Å where both atoms can hydrogen-bond and 1.9 Å between a metal and N, O or S. The list is rebuilt at every macro-cycle. +**Side chains placed through another residue.** A predicted model's rotamer, placed by molecular replacement, +can run through the main chain of another copy or of a symmetry mate - atoms within an ångström of each other, +as where the copies' side chains meet on a non-crystallographic axis. The repulsion only pushes the two atoms +apart along the line that joins them, so such a side chain leaves the clash in whatever direction that line +points and settles in a rotamer of the repulsion's choosing, which the density then cannot correct. Before the +refinement, every side chain with an atom more than 2 Å inside its contact distance to another residue (within +about 1.3 Å of one of its atoms: interpenetration, not a contact the gradient resolves) is +turned about its chi angles to the staggered rotamer (the terminal planar group in steps of 30°) with the least +squared overlap against the rest of the model, symmetry mates included; the main chain, the beta carbon and the +B factors stay as given, and the refinement then places the side chain in the density from there. The log +names each side chain turned, with its chi angles before and after (`REFINE_SIDE_CHAINS_TURNED` counts them). + **Special positions.** An atom closer than 0.5 Å to one of its own symmetry images (the depositions put theirs within 0.03 Å of the site) is on a special position: the symmetry operations, each with its lattice translation, that take it onto itself are its site symmetry (Grosse-Kunstleve & Adams 2002). It is placed exactly on the site - diff --git a/docs/RUGNUX_REPORT.md b/docs/RUGNUX_REPORT.md index 1c0aa5ef1..fd07ac934 100644 --- a/docs/RUGNUX_REPORT.md +++ b/docs/RUGNUX_REPORT.md @@ -1548,6 +1548,7 @@ Where a model was placed and refined ([Refinement](RUGNUX_MODEL_AND_REFERENCE.md | `REFINE_RMSD_METAL_BONDS` | The rmsd of the metal-donor bonds made from the model's LINK records (those within the metal's inner sphere), apart from the covalent bonds. Present where there are any | | `REFINE_RMSD_BONDS_START`, `REFINE_RMSD_ANGLES_START` | *dev*. The same for the model as given | | `REFINE_CLASHES` | Pairs of atoms in the refined model more than 0.4 Å closer than their contact distance (symmetry mates included) | +| `REFINE_SIDE_CHAINS_TURNED` | Side chains turned to another rotamer before the refinement because an atom of theirs stood more than 2 Å inside its contact distance to another residue (within about 1.3 Å of one of its atoms) (a copy's or a symmetry mate's), as molecular replacement leaves a predicted model's; the log names them | | `REFINE_XRAY_WEIGHT` | *dev*. The X-ray weight of the positions that was kept | | `REFINE_NCS_GROUPS` | Molecules present more than once in the model (copies found by sequence alignment, §15.5 of the refinement reference). Present only where there are any, as are the other `REFINE_NCS_` keys | | `REFINE_NCS_COPIES` | The chains of those molecules | diff --git a/image_analysis/structure_refinement/CMakeLists.txt b/image_analysis/structure_refinement/CMakeLists.txt index 3d8226f6a..ecc12bbef 100644 --- a/image_analysis/structure_refinement/CMakeLists.txt +++ b/image_analysis/structure_refinement/CMakeLists.txt @@ -27,6 +27,7 @@ ADD_LIBRARY(JFJochStructureRefinement STATIC DensityBlobs.cpp DensityBlobs.h SolventSites.cpp SolventSites.h SolventBuild.cpp SolventBuild.h + ClashRelief.cpp ClashRelief.h $<$:RefinementGPU.cpp> $<$:RefinementGPU.cu> RefinementGPU.h RefinementGPUEngine.h diff --git a/image_analysis/structure_refinement/ClashRelief.cpp b/image_analysis/structure_refinement/ClashRelief.cpp new file mode 100644 index 000000000..67979e4f2 --- /dev/null +++ b/image_analysis/structure_refinement/ClashRelief.cpp @@ -0,0 +1,289 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#include "ClashRelief.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace { + +constexpr double PI = 3.14159265358979323846; +constexpr double HBOND_CONTACT = 2.6; // A: between N and O, as the refinement's repulsions have it +constexpr double REACH = 4.0; // A: the farthest pair that can overlap + +using Chi = std::array; + +// The chi angles of each amino acid, by the atoms that define them. +const std::map> &ChiAtoms() { + static const std::map> chis = { + {"ARG", {{"N", "CA", "CB", "CG"}, {"CA", "CB", "CG", "CD"}, {"CB", "CG", "CD", "NE"}, {"CG", "CD", "NE", "CZ"}}}, + {"ASN", {{"N", "CA", "CB", "CG"}, {"CA", "CB", "CG", "OD1"}}}, + {"ASP", {{"N", "CA", "CB", "CG"}, {"CA", "CB", "CG", "OD1"}}}, + {"GLN", {{"N", "CA", "CB", "CG"}, {"CA", "CB", "CG", "CD"}, {"CB", "CG", "CD", "OE1"}}}, + {"GLU", {{"N", "CA", "CB", "CG"}, {"CA", "CB", "CG", "CD"}, {"CB", "CG", "CD", "OE1"}}}, + {"HIS", {{"N", "CA", "CB", "CG"}, {"CA", "CB", "CG", "ND1"}}}, + {"ILE", {{"N", "CA", "CB", "CG1"}, {"CA", "CB", "CG1", "CD1"}}}, + {"LEU", {{"N", "CA", "CB", "CG"}, {"CA", "CB", "CG", "CD1"}}}, + {"LYS", {{"N", "CA", "CB", "CG"}, {"CA", "CB", "CG", "CD"}, {"CB", "CG", "CD", "CE"}, {"CG", "CD", "CE", "NZ"}}}, + {"MET", {{"N", "CA", "CB", "CG"}, {"CA", "CB", "CG", "SD"}, {"CB", "CG", "SD", "CE"}}}, + {"PHE", {{"N", "CA", "CB", "CG"}, {"CA", "CB", "CG", "CD1"}}}, + {"SER", {{"N", "CA", "CB", "OG"}}}, + {"THR", {{"N", "CA", "CB", "OG1"}}}, + {"TRP", {{"N", "CA", "CB", "CG"}, {"CA", "CB", "CG", "CD1"}}}, + {"TYR", {{"N", "CA", "CB", "CG"}, {"CA", "CB", "CG", "CD1"}}}, + {"VAL", {{"N", "CA", "CB", "CG1"}}}, + }; + return chis; +} + +// The last chi turns a planar group (an amide, a carboxylate, a ring, a guanidinium): any angle, not only the +// staggered ones. +bool PlanarEnd(const std::string &res) { + return res == "ASP" || res == "ASN" || res == "HIS" || res == "PHE" || res == "TYR" || res == "TRP" || + res == "GLU" || res == "GLN" || res == "ARG"; +} + +// How far along the side chain an atom is, hydrogens by their parent's letter: CB 1, gamma 2, delta 3, epsilon 4, +// zeta 5, eta 6; the main chain and its hydrogens 0. +int Depth(const std::string &name) { + if (name.size() < 2 || name == "CA" || name == "OXT") + return 0; + switch (name[1]) { + case 'B': return 1; + case 'G': return 2; + case 'D': return 3; + case 'E': return 4; + case 'Z': return 5; + case 'H': return 6; + default: return 0; + } +} + +double VdwRadius(gemmi::El el) { + switch (el) { + case gemmi::El::N: return 1.55; + case gemmi::El::O: return 1.52; + case gemmi::El::S: + case gemmi::El::P: return 1.80; + default: return 1.70; + } +} + +bool Polar(gemmi::El el) { + return el == gemmi::El::N || el == gemmi::El::O; +} + +gemmi::Position Rotate(const gemmi::Position &p, const gemmi::Position &a, const gemmi::Position &b, double angle) { + const gemmi::Vec3 k = (b - a).normalized(); + const gemmi::Vec3 v = p - b; + const double c = std::cos(angle), s = std::sin(angle); + return gemmi::Position(gemmi::Vec3(b) + v * c + k.cross(v) * s + k * (k.dot(v) * (1 - c))); +} + +struct SideChain { + std::vector pos; // the residue's atoms, as given + std::vector depth; + std::vector> chi; // atom indices of each chi + + double Dihedral(const std::vector &p, size_t k) const { + const auto &c = chi[k]; + return gemmi::calculate_dihedral(p[c[0]], p[c[1]], p[c[2]], p[c[3]]) * 180.0 / PI; + } + + // The residue's atoms with the side chain at these chi angles (degrees), turned from the given ones. + std::vector Build(const std::vector &chis) const { + std::vector p = pos; + for (size_t k = 0; k < chi.size(); k++) { + const double angle = (chis[k] - Dihedral(p, k)) * PI / 180.0; + const int pivot = depth[chi[k][2]]; + for (size_t i = 0; i < p.size(); i++) + if (depth[i] > pivot) + p[i] = Rotate(p[i], p[chi[k][1]], p[chi[k][2]], angle); + } + return p; + } +}; + +// The residue's chi atoms, found by name; none where any is missing (an incomplete side chain stays as it is) or +// the residue has alternative conformations (its atoms would be found by name once, for both). +std::optional MakeSideChain(const gemmi::Residue &res) { + auto it = ChiAtoms().find(res.name); + if (it == ChiAtoms().end()) + return std::nullopt; + if (std::any_of(res.atoms.begin(), res.atoms.end(), [](const gemmi::Atom &a) { return a.altloc != '\0'; })) + return std::nullopt; + SideChain sc; + for (const gemmi::Atom &a : res.atoms) { + sc.pos.push_back(a.pos); + sc.depth.push_back(Depth(a.name)); + } + for (const Chi &c : it->second) { + std::array idx{}; + for (int k = 0; k < 4; k++) { + const auto found = std::find_if(res.atoms.begin(), res.atoms.end(), + [&](const gemmi::Atom &a) { return a.name == c[k]; }); + if (found == res.atoms.end()) + return std::nullopt; + idx[k] = static_cast(found - res.atoms.begin()); + } + sc.chi.push_back(idx); + } + return sc; +} + +// The overlaps of a residue's turned atoms (depth 2 and beyond, heavy) with the rest of the model: the sum of +// squared overlaps and the deepest one. Its own atoms, hydrogens, absent atoms (occupancy 0), metals and the +// other conformations of an alternative are no contact; nor is a covalent partner (`linked`: a LINK's, or a +// disulfide's). +struct Overlap { + double sum = 0, deepest = 0; +}; + +Overlap OverlapOf(gemmi::NeighborSearch &ns, const gemmi::Model &model, const gemmi::UnitCell &cell, + const gemmi::Residue &res, int chain_idx, int residue_idx, const SideChain &sc, + const std::vector &p, const std::vector &linked) { + Overlap out; + for (size_t i = 0; i < p.size(); i++) { + const gemmi::Atom &a = res.atoms[i]; + if (sc.depth[i] < 2 || a.is_hydrogen()) + continue; + ns.for_each(p[i], '\0', REACH, [&](const gemmi::NeighborSearch::Mark &m, double) { + if (m.image_idx == 0 && m.chain_idx == chain_idx && m.residue_idx == residue_idx) + return; // its own atoms; its own symmetry copy is another residue to it + const gemmi::Atom &b = model.chains[m.chain_idx].residues[m.residue_idx].atoms[m.atom_idx]; + if (b.is_hydrogen() || !(b.occ > 0) || b.element.is_metal()) + return; + if (std::find(linked.begin(), linked.end(), &b) != linked.end()) + return; + if (a.altloc && b.altloc && a.altloc != b.altloc) + return; + if (a.element == gemmi::El::S && b.element == gemmi::El::S) + return; // a disulfide, where it is one, is no clash + const double d = cell.find_nearest_pbc_image(p[i], b.pos, m.image_idx).dist(); + const double d0 = Polar(a.element.elem) && Polar(b.element.elem) + ? HBOND_CONTACT + : VdwRadius(a.element.elem) + VdwRadius(b.element.elem); + if (d < d0) { + out.sum += (d0 - d) * (d0 - d); + out.deepest = std::max(out.deepest, d0 - d); + } + }); + } + return out; +} + +// The rotamers tried: each chi at the staggered angles, the last one of a planar group every 30 degrees. +std::vector> Rotamers(const std::string &resname, size_t n_chi) { + std::vector> out = {{}}; + for (size_t k = 0; k < n_chi; k++) { + std::vector values = {-60, 60, 180}; + if (k + 1 == n_chi && PlanarEnd(resname)) { + values.clear(); + for (int deg = -150; deg <= 180; deg += 30) + values.push_back(deg); + } + std::vector> next; + for (const std::vector &head : out) + for (double v : values) { + next.push_back(head); + next.back().push_back(v); + } + out = std::move(next); + } + return out; +} + +} // namespace + +std::vector RelieveSideChainClashes(gemmi::Structure &st) { + std::vector turned; + const gemmi::SpaceGroup *sg = st.find_spacegroup(); + if (sg == nullptr || st.models.empty()) + return turned; + gemmi::Model &model = st.models[0]; + gemmi::UnitCell cell = st.cell; + cell.set_cell_images_from_spacegroup(sg); + // The atoms a LINK joins are no clash of each other. + std::vector> links; + for (const gemmi::Connection &conn : st.connections) { + const gemmi::CRA a = model.find_cra(conn.partner1), b = model.find_cra(conn.partner2); + if (a.atom != nullptr && b.atom != nullptr) + links.emplace_back(a.atom, b.atom); + } + // One pass over the model after another, until no side chain moves: a side chain turned out of a copy that the + // pass had still to turn made its choice against that copy's old place, so in the later passes every side chain + // turned so far chooses again, in the others' new places. + std::map, size_t> turned_index; // (chain, residue) -> entry in `turned` + for (int pass = 0; pass < 5; pass++) { + bool any = false; + // made afresh after each turn: the turn moves atoms the search has indexed + gemmi::NeighborSearch ns(model, cell, REACH + 1); + ns.populate(/*include_h=*/false); + for (size_t ci = 0; ci < model.chains.size(); ci++) + for (size_t ri = 0; ri < model.chains[ci].residues.size(); ri++) { + gemmi::Residue &res = model.chains[ci].residues[ri]; + const std::optional sc = MakeSideChain(res); + if (!sc) + continue; + std::vector linked; + for (const auto &[a, b] : links) + for (const gemmi::Atom &x : res.atoms) { + if (&x == a) + linked.push_back(b); + if (&x == b) + linked.push_back(a); + } + auto overlap = [&](const std::vector &p) { + return OverlapOf(ns, model, cell, res, static_cast(ci), static_cast(ri), *sc, p, linked); + }; + const Overlap given = overlap(sc->pos); + const auto earlier = turned_index.find({ci, ri}); + if (given.deepest < CLASH_RELIEF_OVERLAP && earlier == turned_index.end()) + continue; + std::vector chi; + for (size_t k = 0; k < sc->chi.size(); k++) + chi.push_back(sc->Dihedral(sc->pos, k)); + Overlap best = given; + std::vector best_chi = chi; + for (const std::vector &chis : Rotamers(res.name, sc->chi.size())) { + const Overlap o = overlap(sc->Build(chis)); + if (o.sum < best.sum) { + best = o; + best_chi = chis; + } + } + if (!(best.sum < given.sum)) + continue; + if (earlier == turned_index.end()) { + SideChainTurn t; + t.name = res.name + " " + model.chains[ci].name + res.seqid.str(); + t.chi_before = chi; + t.overlap_before = given.deepest; + turned_index[{ci, ri}] = turned.size(); + turned.push_back(t); + } + SideChainTurn &t = turned[turned_index[{ci, ri}]]; + t.chi_after = best_chi; + t.overlap_after = best.deepest; + const std::vector p = sc->Build(best_chi); + for (size_t i = 0; i < p.size(); i++) + res.atoms[i].pos = p[i]; + // its hydrogens, where it has them, went with their heavy atoms only by name: they are placed anew + gemmi::remove_hydrogens(res); + any = true; + ns = gemmi::NeighborSearch(model, cell, REACH + 1); + ns.populate(/*include_h=*/false); + } + if (!any) + break; + } + return turned; +} diff --git a/image_analysis/structure_refinement/ClashRelief.h b/image_analysis/structure_refinement/ClashRelief.h new file mode 100644 index 000000000..b40b32a02 --- /dev/null +++ b/image_analysis/structure_refinement/ClashRelief.h @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#pragma once + +#include +#include + +#include + +// A side chain placed through another residue - a copy's or a symmetry mate's - as a predicted model's +// rotamer lands when molecular replacement packs the copies: two atoms within an angstrom or so of each other. +// The refinement's repulsion only pushes the atoms apart along the line that joins them, so such a side chain +// leaves the clash in whatever direction that line points and settles in a rotamer the density does not hold. +// Before the refinement, each such side chain is turned about its chi angles to the staggered rotamer (the +// terminal planar group in steps of 30 degrees) with the least overlap against the rest of the model; the +// main chain, the beta carbon and the B factors stay as given. +constexpr double CLASH_RELIEF_OVERLAP = 2.0; // A: a pair of heavy atoms this far inside their contact distance (within ~1.3 A of each other) + +struct SideChainTurn { + std::string name; // "GLN A17" + std::vector chi_before; // degrees + std::vector chi_after; + double overlap_before = 0; // A: the deepest overlap of the side chain's atoms with another residue + double overlap_after = 0; +}; + +// The side chains of the first model of `st` with an overlap beyond CLASH_RELIEF_OVERLAP, turned in place to +// their least-overlapping rotamer; what was turned, in model order. +std::vector RelieveSideChainClashes(gemmi::Structure &st); diff --git a/image_analysis/structure_refinement/Refinement.cpp b/image_analysis/structure_refinement/Refinement.cpp index f58d4ad64..8997505b9 100644 --- a/image_analysis/structure_refinement/Refinement.cpp +++ b/image_analysis/structure_refinement/Refinement.cpp @@ -33,6 +33,7 @@ #include "../../common/JFJochMath.h" #include "../../common/Logger.h" #include "../../common/ParallelFor.h" +#include "ClashRelief.h" #include "ModelFFT.h" #include "ModelGrid.h" // IonFormFactor, AnisoRadiusB #include "ModelScaling.h" @@ -2369,6 +2370,21 @@ RefinementResult RefineOnce(const gemmi::Structure &placed, const std::vector &v) { + std::string s; + for (double x : v) + s += fmt::format("{}{:.0f}", s.empty() ? "" : "/", x); + return s; + }; + for (const SideChainTurn &t : RelieveSideChainClashes(ctx.st)) { + result.side_chains_turned++; + logger.Info("Refinement: {} turned out of a {:.1f} A overlap with another residue, chi {} -> {}, {:.1f} A left", + t.name, t.overlap_before, chis(t.chi_before), chis(t.chi_after), t.overlap_after); + } + } // The weight trials' slots start from a copy of the model as it is before the topology is made. const gemmi::Structure before_topology = ctx.st; RefinementTopology topo; diff --git a/image_analysis/structure_refinement/Refinement.h b/image_analysis/structure_refinement/Refinement.h index 6ce9437b5..39ea0694c 100644 --- a/image_analysis/structure_refinement/Refinement.h +++ b/image_analysis/structure_refinement/Refinement.h @@ -196,6 +196,7 @@ struct RefinementResult { int atoms = 0, refined_atoms = 0; int restrained_residues = 0, fixed_residues = 0; std::vector fixed_names; + int side_chains_turned = 0; // out of an overlap with another residue before the refinement (ClashRelief.h) double k_sol = 0, b_sol = 0; double mean_fom = 0; diff --git a/rugnux/ResultReport.cpp b/rugnux/ResultReport.cpp index 5758cc87d..b331b29da 100644 --- a/rugnux/ResultReport.cpp +++ b/rugnux/ResultReport.cpp @@ -727,6 +727,7 @@ namespace { Add(s, KeyReal("REFINE_RMSD_BONDS_START", rf.geometry_start.rmsd_bonds, "{:.4f}", true)); Add(s, KeyReal("REFINE_RMSD_ANGLES_START", rf.geometry_start.rmsd_angles, "{:.2f}", true)); Add(s, KeyInt("REFINE_CLASHES", rf.geometry.clashes)); + Add(s, KeyInt("REFINE_SIDE_CHAINS_TURNED", rf.side_chains_turned)); Add(s, KeyReal("REFINE_XRAY_WEIGHT", rf.weight, "{:.4g}", true)); if (rf.ncs_groups > 0) { Add(s, KeyInt("REFINE_NCS_GROUPS", rf.ncs_groups)); diff --git a/tests/RefinementTest.cpp b/tests/RefinementTest.cpp index 92db8c573..18f80aae3 100644 --- a/tests/RefinementTest.cpp +++ b/tests/RefinementTest.cpp @@ -21,6 +21,7 @@ #include "../common/Logger.h" #include "../common/UnitCell.h" #include "../image_analysis/scale_merge/RfreeFlags.h" +#include "../image_analysis/structure_refinement/ClashRelief.h" #include "../image_analysis/structure_refinement/ModelGrid.h" #include "../image_analysis/structure_refinement/MonomerLibrary.h" #include "../image_analysis/structure_refinement/Refinement.h" @@ -1867,3 +1868,95 @@ TEST_CASE("Refinement_twin_decided", "[Refinement]") { CHECK(s.r_free_start < s.untwinned_r_free - 0.02); } } + +// A glutamine's amide placed through the main chain of another chain, as a predicted model's rotamer lands when +// molecular replacement packs the copies: turned to a rotamer clear of it, the main chain and the beta carbon +// untouched, the side chain's bonds as they were. The other residue stands as a copy in the asymmetric unit, +// and as a symmetry mate. +TEST_CASE("ClashRelief_side_chain_through_another_residue", "[Refinement]") { + struct AtomXYZ { + const char *name; + gemmi::El el; + double x, y, z; + }; + const std::vector gln = {{"N", gemmi::El::N, -14.511, 66.525, 29.018}, {"CA", gemmi::El::C, -13.327, 66.868, 28.222}, + {"C", gemmi::El::C, -13.127, 65.890, 27.053}, {"O", gemmi::El::O, -12.773, 66.307, 25.952}, + {"CB", gemmi::El::C, -12.097, 66.881, 29.138}, {"CG", gemmi::El::C, -10.814, 67.262, 28.380}, + {"CD", gemmi::El::C, -9.588, 67.307, 29.281}, {"OE1", gemmi::El::O, -9.635, 67.049, 30.468}, + {"NE2", gemmi::El::N, -8.430, 67.627, 28.746}}; + // the main chain the amide runs through: an alanine and the next residue's N and CA + const std::vector ala = {{"N", gemmi::El::N, -6.547, 68.057, 30.231}, {"CA", gemmi::El::C, -7.057, 67.212, 29.150}, + {"C", gemmi::El::C, -8.108, 67.895, 28.263}, {"O", gemmi::El::O, -8.5, 68.9, 28.5}, + {"CB", gemmi::El::C, -6.3, 66.8, 28.1}}; + const std::vector next = {{"N", gemmi::El::N, -8.762, 68.964, 28.726}, {"CA", gemmi::El::C, -9.632, 69.779, 27.871}}; + auto add = [](gemmi::Chain &ch, const char *resname, int num, const std::vector &atoms, + const gemmi::Transform &t) { + gemmi::Residue r; + r.name = resname; + r.seqid.num = num; + for (const AtomXYZ &a : atoms) { + gemmi::Atom at; + at.name = a.name; + at.element = gemmi::Element(a.el); + at.pos = gemmi::Position(t.apply(gemmi::Vec3(a.x, a.y, a.z))); + at.occ = 1; + at.b_iso = 20; + r.atoms.push_back(at); + } + ch.residues.push_back(r); + }; + const bool as_symmetry_mate = GENERATE(false, true); + gemmi::Structure st; + st.cell = gemmi::UnitCell(100, 100, 100, 90, 90, 90); + st.spacegroup_hm = as_symmetry_mate ? "P 1 2 1" : "P 1"; + st.models.emplace_back(1); + gemmi::Chain a("A"), b("B"); + const gemmi::Transform identity; + // in P 1 2 1 the other chain is put where the 2-fold (-x, y, -z) brings it back onto the glutamine + gemmi::Transform two_fold; + two_fold.mat = gemmi::Mat33(-1, 0, 0, 0, 1, 0, 0, 0, -1); + const gemmi::Transform &place = as_symmetry_mate ? two_fold : identity; + add(a, "GLN", 17, gln, identity); + add(b, "ALA", 16, ala, place); + add(b, "GLN", 17, next, place); + st.models[0].chains = {a, b}; + st.setup_cell_images(); + const gemmi::Structure given = st; + + const std::vector turned = RelieveSideChainClashes(st); + REQUIRE(turned.size() == 1); + CHECK(turned[0].name == "GLN A17"); + CHECK(turned[0].overlap_before > 2.0); // NE2 0.64 A from the alanine's C + CHECK(turned[0].overlap_after < CLASH_RELIEF_OVERLAP); + CHECK(turned[0].chi_before.size() == 3); + + const gemmi::Residue &was = given.models[0].chains[0].residues[0], &now = st.models[0].chains[0].residues[0]; + REQUIRE(now.atoms.size() == was.atoms.size()); + for (size_t i = 0; i < was.atoms.size(); i++) { + if (was.atoms[i].name == "N" || was.atoms[i].name == "CA" || was.atoms[i].name == "C" || + was.atoms[i].name == "O" || was.atoms[i].name == "CB") + CHECK(now.atoms[i].pos.dist(was.atoms[i].pos) < 1e-9); + CHECK(now.atoms[i].b_iso == was.atoms[i].b_iso); + } + auto bond = [](const gemmi::Residue &r, const char *p, const char *q) { + return r.find_atom(p, '*')->pos.dist(r.find_atom(q, '*')->pos); + }; + for (const auto &[p, q] : {std::pair{"CB", "CG"}, std::pair{"CG", "CD"}, std::pair{"CD", "OE1"}, std::pair{"CD", "NE2"}}) + CHECK(bond(now, p, q) == Catch::Approx(bond(was, p, q)).margin(1e-6)); + CHECK(now.find_atom("NE2", '*')->pos.dist(was.find_atom("NE2", '*')->pos) > 2.0); + // the other chain as it was, and no atom of the side chain nearer to it than a contact + gemmi::UnitCell cell = st.cell; + cell.set_cell_images_from_spacegroup(st.find_spacegroup()); + for (size_t r = 0; r < 2; r++) + for (size_t i = 0; i < given.models[0].chains[1].residues[r].atoms.size(); i++) { + const gemmi::Atom &other = st.models[0].chains[1].residues[r].atoms[i]; + CHECK(other.pos.dist(given.models[0].chains[1].residues[r].atoms[i].pos) < 1e-9); + for (const gemmi::Atom &sc : now.atoms) + if (sc.name != "N" && sc.name != "CA" && sc.name != "C" && sc.name != "O") + CHECK(cell.find_nearest_image(sc.pos, other.pos, gemmi::Asu::Any).dist() > 2.5); + } + // a model without the clash is left as it is + gemmi::Structure clear = given; + clear.models[0].chains.pop_back(); + CHECK(RelieveSideChainClashes(clear).empty()); +}