Files
leonarski_fandClaude Opus 5.5 8539f5441f
Build Packages / Create release (push) Successful in 9s
Build Packages / Build documentation (push) Successful in 2m1s
Build Packages / build:portable:macos-arm64:nocuda (push) Successful in 5m22s
Build Packages / build:rugnux:linux-aarch64:cuda (push) Successful in 18m36s
Build Packages / build:portable:linux-x86_64:nocuda (push) Successful in 25m56s
Build Packages / build:portable:windows-x86_64:nocuda (push) Successful in 24m37s
Build Packages / build:portable:windows-x86_64:cuda (push) Successful in 29m12s
Build Packages / build:portable:linux-x86_64:cuda (push) Successful in 34m56s
Build Packages / build:jfjoch:ubuntu2204:nocuda (push) Successful in 38m56s
Build Packages / build:jfjoch:rocky8:nocuda (push) Successful in 43m40s
Build Packages / HDF5 consumer tests (DIALS, XDS) (push) Successful in 44m19s
Build Packages / build:jfjoch:rocky9:nocuda (push) Successful in 46m41s
Build Packages / build:jfjoch:ubuntu2404:nocuda (push) Successful in 33m43s
Build Packages / Generate python client (push) Successful in 46s
Build Packages / build:jfjoch:rocky8:cuda-sls9 (push) Successful in 34m50s
Build Packages / build:jfjoch:rocky9:cuda-sls9 (push) Successful in 35m52s
Build Packages / build:jfjoch:ubuntu2204:cuda (push) Successful in 28m21s
Build Packages / build:jfjoch:rocky8:cuda (push) Successful in 35m11s
Build Packages / build:jfjoch:ubuntu2404:cuda (push) Successful in 31m57s
Build Packages / build:jfjoch:rocky9:cuda (push) Successful in 35m42s
Build Packages / Unit tests (push) Successful in 2h51m26s
Build Packages / Validation Battery (push) Canceled after 1h41m55s
Restraint dictionary: an entry with bonds without lengths and no block of its own is refused, not dereferenced
ReadRestraintDictionary looked up the block <code> / comp_<code> of a CCD-style entry and used it
without checking it was found; a user file naming its block otherwise crashed. It is now refused
with the file name, like the other unreadable dictionaries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UqXYdJDrM65gxsCn2PrbfK
2026-11-15 08:08:33 +01:00

197 lines
8.7 KiB
C++

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include "MonomerLibrary.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <map>
#include <stdexcept>
#include <vector>
#include "gemmi/calculate.hpp" // calculate_angle
#include "gemmi/numb.hpp" // as_number
#include "gemmi/read_cif.hpp" // read_cif_from_memory
// Generated by CMakeLists.txt from monomers/*.cif (MonomerLibraryData.cpp in the build tree).
extern const EmbeddedMonomerFile embedded_monomer_files[];
extern const size_t embedded_monomer_file_count;
namespace {
struct MetalRow {
gemmi::El metal, ligand;
int coordination;
double distance, std;
int count;
};
struct EmbeddedLibrary {
gemmi::MonLib monlib;
std::vector<MetalRow> metals; // metals.cif
};
EmbeddedLibrary ReadEmbeddedMonomerLibrary() {
EmbeddedLibrary lib;
gemmi::MonLib &monlib = lib.monlib;
for (size_t i = 0; i < embedded_monomer_file_count; i++) {
const EmbeddedMonomerFile &f = embedded_monomer_files[i];
std::string text;
for (size_t k = 0; k < f.n_pieces; k++)
text += f.pieces[k];
gemmi::cif::Document doc = gemmi::read_cif_from_memory(text.data(), text.size(), f.name);
if (std::strcmp(f.name, "ener_lib.cif") == 0)
monlib.ener_lib.read(doc);
else if (std::strcmp(f.name, "metals.cif") == 0) {
for (const auto &row : doc.blocks.at(0).find("_metal_coordination.",
{"metal", "ligand", "coordination", "distance", "std", "count"}))
lib.metals.push_back({gemmi::find_element(row[0].c_str()), gemmi::find_element(row[1].c_str()),
gemmi::cif::as_int(row[2]), gemmi::cif::as_number(row[3]),
gemmi::cif::as_number(row[4]), gemmi::cif::as_int(row[5])});
} else
monlib.read_monomer_doc(doc);
}
return lib;
}
const EmbeddedLibrary &Library() {
static const EmbeddedLibrary lib = ReadEmbeddedMonomerLibrary();
return lib;
}
} // namespace
const gemmi::MonLib &EmbeddedMonomerLibrary() {
return Library().monlib;
}
bool EmbeddedMetalDistance(gemmi::El metal, gemmi::El ligand, int coordination, double &distance, double &sigma) {
// the rows of the pair resting on enough sites: the nearest at or below the coordination and above it
const MetalRow *lo = nullptr, *hi = nullptr;
for (const MetalRow &r : Library().metals) {
if (r.metal != metal || r.ligand != ligand || r.count < METAL_MIN_SITES)
continue;
if (r.coordination <= coordination && (lo == nullptr || r.coordination > lo->coordination))
lo = &r;
if (r.coordination > coordination && (hi == nullptr || r.coordination < hi->coordination))
hi = &r;
}
if (lo == nullptr && hi == nullptr)
return false;
if (lo != nullptr && (lo->coordination == coordination || hi == nullptr)) {
distance = lo->distance;
sigma = lo->std;
} else if (lo == nullptr) {
distance = hi->distance;
sigma = hi->std;
} else {
// between two coordination numbers: linear in the coordination
const double t = static_cast<double>(coordination - lo->coordination) / (hi->coordination - lo->coordination);
distance = lo->distance + t * (hi->distance - lo->distance);
sigma = lo->std + t * (hi->std - lo->std);
}
sigma = std::max(sigma, METAL_MIN_SIGMA);
return true;
}
bool InEmbeddedMonomerLibrary(const std::string &code) {
return EmbeddedMonomerLibrary().monomers.count(code) > 0;
}
namespace {
// A CCD entry's monomer restrained to the geometry of its ideal coordinates (ReadRestraintDictionary).
void RestrainToCoordinates(gemmi::ChemComp &cc, gemmi::cif::Block &block) {
for (gemmi::ChemComp::Atom &a : cc.atoms)
a.xyz = gemmi::Position(NAN, NAN, NAN); // not the model coordinates of the entry
for (auto row : block.find("_chem_comp_atom.", {"atom_id", "?pdbx_model_Cartn_x_ideal", "?pdbx_model_Cartn_y_ideal",
"?pdbx_model_Cartn_z_ideal"}))
if (row.has(1) && row.has(2) && row.has(3))
cc.atoms[cc.get_atom_index(row.str(0))].xyz = gemmi::Position(gemmi::cif::as_number(row[1]), gemmi::cif::as_number(row[2]),
gemmi::cif::as_number(row[3]));
for (const gemmi::ChemComp::Atom &a : cc.atoms)
if (!std::isfinite(a.xyz.x) || !std::isfinite(a.xyz.y) || !std::isfinite(a.xyz.z))
throw std::runtime_error(cc.name + " has bonds without lengths, a Chemical Component Dictionary entry, "
"and its atom " + a.id + " has no ideal coordinates to restrain it to");
auto xyz = [&](const std::string &id) { return cc.get_atom(id).xyz; };
std::map<std::string, std::vector<std::string>> bonded;
std::set<std::string> sp2; // atoms with a double or aromatic bond
for (gemmi::Restraints::Bond &b : cc.rt.bonds) {
b.value = b.value_nucleus = xyz(b.id1.atom).dist(xyz(b.id2.atom));
b.esd = b.esd_nucleus = DERIVED_BOND_SIGMA;
bonded[b.id1.atom].push_back(b.id2.atom);
bonded[b.id2.atom].push_back(b.id1.atom);
if (b.aromatic || b.type == gemmi::BondType::Double || b.type == gemmi::BondType::Aromatic
|| b.type == gemmi::BondType::Deloc) {
sp2.insert(b.id1.atom);
sp2.insert(b.id2.atom);
}
}
for (const auto &[centre, nb] : bonded)
for (size_t i = 0; i < nb.size(); i++)
for (size_t j = i + 1; j < nb.size(); j++) {
const double angle = gemmi::deg(gemmi::calculate_angle(xyz(nb[i]), xyz(centre), xyz(nb[j])));
cc.rt.angles.push_back({{1, nb[i]}, {1, centre}, {1, nb[j]}, angle, DERIVED_ANGLE_SIGMA});
}
for (const std::string &centre : sp2) {
gemmi::Restraints::Plane p{"plane-" + centre, {{1, centre}}, DERIVED_PLANE_SIGMA};
for (const std::string &n : bonded[centre])
p.ids.push_back({1, n});
if (p.ids.size() >= 4) // a plane of three atoms restrains nothing
cc.rt.planes.push_back(std::move(p));
}
}
} // namespace
void ReadRestraintDictionary(const std::string &text, const std::string &name, RestraintDictionary &dict) {
gemmi::cif::Document doc = gemmi::read_cif_from_memory(text.data(), text.size(), name.c_str());
gemmi::MonLib lib;
lib.read_monomer_doc(doc);
if (lib.monomers.empty() && lib.links.empty() && lib.modifications.empty())
throw std::runtime_error(name + " holds no monomer (_chem_comp_atom), link (_chem_link) or modification "
"(_chem_mod)");
for (auto &[code, cc] : lib.monomers) {
if (cc.group == gemmi::ChemComp::Group::Null) // a CCD entry's _chem_comp.type, else a ligand
cc.group = gemmi::ChemComp::read_group(cc.type_or_group);
if (cc.group == gemmi::ChemComp::Group::Null)
cc.group = gemmi::ChemComp::Group::NonPolymer;
// bonds without lengths: a CCD entry
if (std::any_of(cc.rt.bonds.begin(), cc.rt.bonds.end(),
[](const gemmi::Restraints::Bond &b) { return !std::isfinite(b.value); })) {
gemmi::cif::Block *block = doc.find_block(code);
if (block == nullptr)
block = doc.find_block("comp_" + code);
if (block == nullptr)
throw std::runtime_error(name + ": no data block " + code + " or comp_" + code + " with the "
"coordinates of its bonds without lengths");
try {
RestrainToCoordinates(cc, *block);
} catch (const std::exception &e) {
throw std::runtime_error(name + ": " + e.what());
}
dict.from_coordinates.insert(code);
} else
dict.from_coordinates.erase(code);
dict.monomers.push_back(std::move(cc));
}
for (auto &[id, link] : lib.links)
dict.links.push_back(std::move(link));
for (auto &[id, mod] : lib.modifications)
dict.modifications.push_back(std::move(mod));
dict.names.push_back(name);
}
gemmi::MonLib MonomerLibraryWith(const RestraintDictionary &user) {
gemmi::MonLib monlib = EmbeddedMonomerLibrary();
for (const gemmi::ChemComp &cc : user.monomers)
monlib.monomers.insert_or_assign(cc.name, cc);
for (const gemmi::ChemLink &link : user.links)
monlib.links.insert_or_assign(link.id, link);
for (const gemmi::ChemMod &mod : user.modifications)
monlib.modifications.insert_or_assign(mod.id, mod);
return monlib;
}