C++ API Reference¶
This page documents the Gemmi C++ library API, generated from Doxygen comments
in include/gemmi/*.hpp. It is updated with each pull request in the
API documentation series.
For the Python API, see the Python API reference.
Note
Documentation coverage is being added incrementally. Headers not yet listed here will appear in subsequent pull requests.
Core Data Structures¶
Core hierarchical data structures for macromolecular models.
This header defines the fundamental data types used throughout Gemmi to represent macromolecular structures. The hierarchy is:
Structure (complete 3D model with metadata)
Model (NMR/ensemble models with sequential numbering)
Chain (named sequences of residues)
Residue (single amino acid or nucleotide)
Atom (individual atomic coordinates)
It also provides helper structures and enums for handling file formats, calculation flags, secondary structure, and various search/access utilities.
-
namespace gemmi¶
Typedefs
-
using AtomGroup = AtomGroup_<Atom>¶
Mutable group of atoms.
-
using ConstAtomGroup = AtomGroup_<const Atom>¶
Const group of atoms.
Enums
-
enum class CoorFormat : unsigned char¶
File format of a macromolecular model structure. When passed to read_structure(): Unknown = guess format from the extension (default), Detect = guess format from the content (read first bytes).
Values:
-
enumerator Unknown¶
Guess from file extension.
-
enumerator Detect¶
Guess from content/magic bytes.
-
enumerator Pdb¶
PDB format.
-
enumerator Mmcif¶
mmCIF format
-
enumerator Mmjson¶
mmJSON format
-
enumerator ChemComp¶
Chemical component format.
-
enumerator Unknown¶
-
enum class CalcFlag : signed char¶
Atom site calculation flag from mmCIF _atom_site.calc_flag. Indicates how atomic coordinates and B-factors were determined. Note: NoHydrogen has the same numeric value (0) as NotSet; it is used internally to mark atoms that should not have riding hydrogens added.
Values:
-
enumerator NotSet¶
Flag not set (default)
-
enumerator NoHydrogen¶
Internal flag: do not add riding hydrogens (same value as NotSet)
-
enumerator Determined¶
Experimentally determined.
-
enumerator Calculated¶
Calculated or assigned from geometry.
-
enumerator Dummy¶
Dummy position for QM/MM or placeholder atoms.
-
enumerator NotSet¶
-
enum class ResidueSs : unsigned char¶
Secondary structure annotation from structure file.
Values:
-
enumerator Coil¶
Random coil or unassigned.
-
enumerator Helix¶
Helical conformation (alpha, 3-10, pi, etc.)
-
enumerator Strand¶
Beta strand.
-
enumerator Coil¶
-
enum class ResidueStrandSense : signed char¶
Strand sense within a beta sheet from PDB/mmCIF structure file. Distinguishes the first strand in a sheet from other strands and non-strand residues.
Values:
-
enumerator NotStrand¶
Not part of a beta sheet.
-
enumerator Parallel¶
Parallel to the previous strand.
-
enumerator First¶
First strand in a sheet.
-
enumerator Antiparallel¶
Antiparallel to the previous strand.
-
enumerator NotStrand¶
Functions
-
template<class T>
void remove_empty_children(T &obj)¶ Recursively remove empty child elements. Removes empty residues from a chain, empty chains from a model, etc. Works with any type that has a
child_typeandchildren()method.- Template Parameters:
T – Container type (Chain, Model, or Structure)
-
inline bool is_same_conformer(char altloc1, char altloc2)¶
Check if two atoms belong to the same conformer (alternate location). Returns true if altloc values are compatible (either one or both unset, or identical).
- Parameters:
altloc1 – First alternate location character (‘\0’ means no alternate location set)
altloc2 – Second alternate location character
- Returns:
true if atoms are in the same conformer, false otherwise
-
inline void add_distinct_altlocs(const Residue &res, std::string &altlocs)¶
Collect all distinct alternate location characters from a residue. Appends unique altloc characters to the provided string.
- Parameters:
res – The residue to scan
altlocs – String to accumulate altloc characters (not cleared first)
-
inline std::string atom_str(const Chain &chain, const ResidueId &res_id, const Atom &atom, bool as_cid = false)¶
Convert Chain, ResidueId, and Atom to a string representation.
- Parameters:
chain – The chain
res_id – The residue ID
atom – The atom
as_cid – If true, format as CIF; if false, format as PDB
- Returns:
String representation of the atom location
-
inline std::string atom_str(const const_CRA &cra, bool as_cif = false)¶
Convert const_CRA (Chain, Residue, Atom pointers) to string. Handles null pointers gracefully.
- Parameters:
cra – Chain-Residue-Atom triple
as_cif – If true, format as CIF; if false, format as PDB
- Returns:
String representation of the atom location
-
inline bool atom_matches(const const_CRA &cra, const AtomAddress &addr, bool ignore_segment = false)¶
Check if a const_CRA matches an AtomAddress specification.
- Parameters:
cra – Chain-Residue-Atom triple to test
addr – Target atom address
ignore_segment – If true, don’t check segment ID
- Returns:
true if all relevant fields match
-
inline AtomAddress make_address(const Chain &ch, const Residue &res, const Atom &at)¶
Create an AtomAddress from Chain, Residue, and Atom.
- Parameters:
ch – The chain
res – The residue
at – The atom
- Returns:
AtomAddress specifying this atom
-
inline Entity *find_entity_of_subchain(const std::string &subchain_id, std::vector<Entity> &entities)¶
Find entity containing given subchain. Searches for an entity that includes the specified subchain ID.
- Parameters:
subchain_id – Subchain identifier to search for
entities – Vector of entities to search
- Returns:
Pointer to entity containing this subchain, or nullptr if not found
-
inline const Entity *find_entity_of_subchain(const std::string &subchain_id, const std::vector<Entity> &entities)¶
Find entity containing given subchain. Searches for an entity that includes the specified subchain ID.
- Parameters:
subchain_id – Subchain identifier to search for
entities – Vector of entities to search
- Returns:
Pointer to entity containing this subchain, or nullptr if not found
-
struct Atom¶
- #include <gemmi/model.hpp>
Represents an atom site in a macromolecular structure (approximately 100 bytes). Stores 3D coordinates, occupancy, atomic displacement parameters (ADP), and associated metadata for a single atom.
Public Functions
-
inline char altloc_or(char null_char) const¶
Get alternate location character, or fallback value if not set.
- Parameters:
null_char – Character to return if altloc is not set (‘\0’)
- Returns:
altloc if set, otherwise null_char
-
inline bool same_conformer(const Atom &other) const¶
Check if this atom belongs to the same conformer as another.
- Parameters:
other – The other atom to compare
- Returns:
true if atoms are compatible conformations
-
inline bool altloc_matches(char request) const¶
Check if this atom matches an alternate location request. ‘*’ matches any altloc, ‘\0’ matches atoms without altloc.
- Parameters:
request – Requested alternate location character
- Returns:
true if this atom’s altloc matches the request
-
inline const std::string &group_key() const¶
Get grouping key for UniqIter and similar iteration tools.
- Returns:
The atom name
-
inline bool has_altloc() const¶
Check if this atom has an alternate location assigned.
- Returns:
true if altloc != ‘\0’
-
inline double b_eq() const¶
Calculate equivalent isotropic B-factor from anisotropic U parameters.
- Returns:
B_eq = (U[0] + U[1] + U[2]) * 8 * pi^2 / 3
-
inline bool is_hydrogen() const¶
Check if this atom represents a hydrogen.
- Returns:
true if element is H, D, or T
Public Members
-
char altloc = '\0'¶
Alternate location character (‘\0’ = not set)
-
signed char charge = 0¶
Formal charge in range [-8, +8].
-
char flag = '\0'¶
Custom flag for user-defined marking.
-
short tls_group_id = -1¶
TLS group assignment (-1 = not assigned)
-
int serial = 0¶
Atom serial number from input file.
-
float fraction = 0.f¶
Custom fractional value (e.g., Refmac ccp4_deuterium_fraction)
-
float occ = 1.0f¶
Occupancy (0.0 to 1.0 typical; >1.0 rare)
-
float b_iso = 20.0f¶
Isotropic B-factor (temperature factor) in Ångström²
Public Static Functions
-
static inline const char *what()¶
-
inline char altloc_or(char null_char) const¶
-
template<typename AtomType>
struct AtomGroup_ : public gemmi::ItemGroup<AtomType>¶ - #include <gemmi/model.hpp>
A group of atoms sharing the same name but occupying different alternate locations.
Used to iterate over or access atoms at a single crystallographic site that have been modelled in multiple conformations (alt locs).
- Template Parameters:
AtomType – Either
Atom(mutable) orconst Atom(immutable).
-
struct Chain¶
- #include <gemmi/model.hpp>
Represents a chain of residues (typically named A, B, C, …). A chain is a sequence of residues, often corresponding to a polypeptide or polynucleotide.
Public Functions
-
Chain() = default¶
-
inline ResidueSpan whole()¶
Get span covering all residues in chain.
- Returns:
Mutable residue span for entire chain
-
inline ConstResidueSpan whole() const¶
Get span covering all residues in chain.
- Returns:
Mutable residue span for entire chain
-
template<typename F>
inline ResidueSpan get_residue_span(F &&func)¶ Get residue span matching a predicate function.
- Template Parameters:
F – Callable taking const Residue& and returning bool
- Parameters:
func – Predicate function
- Returns:
Mutable span of matching residues
-
template<typename F>
inline ConstResidueSpan get_residue_span(F &&func) const¶ Get residue span matching a predicate function.
- Template Parameters:
F – Callable taking const Residue& and returning bool
- Parameters:
func – Predicate function
- Returns:
Mutable span of matching residues
-
inline ResidueSpan get_polymer()¶
Get span of polymer residues in this chain. Finds the first contiguous span of polymer residues in the same subchain.
- Returns:
Mutable span of polymer residues, or empty if none found
-
inline ConstResidueSpan get_polymer() const¶
Get span of polymer residues in this chain. Finds the first contiguous span of polymer residues in the same subchain.
- Returns:
Mutable span of polymer residues, or empty if none found
-
inline ResidueSpan get_ligands()¶
Get span of ligand residues (NonPolymer or Branched entities).
- Returns:
Mutable span of ligand residues
-
inline ConstResidueSpan get_ligands() const¶
Get span of ligand residues (NonPolymer or Branched entities).
- Returns:
Mutable span of ligand residues
-
inline ResidueSpan get_waters()¶
Get span of water residues.
- Returns:
Mutable span of water molecules
-
inline ConstResidueSpan get_waters() const¶
Get span of water residues.
- Returns:
Mutable span of water molecules
-
inline ResidueSpan get_subchain(const std::string &s)¶
Get span of residues with given subchain identifier.
- Parameters:
s – Subchain ID to search for
- Returns:
Mutable span of matching residues
-
inline ConstResidueSpan get_subchain(const std::string &s) const¶
Get span of residues with given subchain identifier.
- Parameters:
s – Subchain ID to search for
- Returns:
Mutable span of matching residues
-
inline std::vector<ResidueSpan> subchains()¶
Get list of subchain spans (grouped by subchain identifier). Each subchain is a contiguous sequence of residues with the same subchain ID.
- Returns:
Vector of mutable residue spans, one per subchain
-
inline std::vector<ConstResidueSpan> subchains() const¶
Get list of subchain spans (grouped by subchain identifier). Each subchain is a contiguous sequence of residues with the same subchain ID.
- Returns:
Vector of mutable residue spans, one per subchain
-
inline ResidueGroup find_residue_group(SeqId id)¶
Find residue group with given sequence ID.
- Parameters:
id – Sequence ID to search for
- Returns:
ResidueGroup containing residues with this sequence ID
-
inline ConstResidueGroup find_residue_group(SeqId id) const¶
Find residue group with given sequence ID.
- Parameters:
id – Sequence ID to search for
- Returns:
ResidueGroup containing residues with this sequence ID
-
inline Residue *find_residue(const ResidueId &rid)¶
Find residue by ResidueId (number and insertion code).
- Parameters:
rid – ResidueId to search for
- Returns:
Pointer to matching residue, or nullptr if not found
-
inline const Residue *find_residue(const ResidueId &rid) const¶
Find residue by ResidueId (number and insertion code).
- Parameters:
rid – ResidueId to search for
- Returns:
Pointer to matching residue, or nullptr if not found
-
inline Residue *find_or_add_residue(const ResidueId &rid)¶
Find residue by ResidueId, or create it if not found.
- Parameters:
rid – ResidueId to search for or create
- Returns:
Reference to existing or newly created residue
-
inline void append_residues(std::vector<Residue> new_resi, int min_sep = 0)¶
Append residues to this chain with optional minimum separation. Adjusts sequence numbers if needed to maintain minimum separation.
- Parameters:
new_resi – Vector of residues to append
min_sep – Minimum sequence number separation (0 = no enforcement)
-
inline Chain empty_copy() const¶
Create a shallow copy with same name but empty residues. Used in template code for hierarchical copying.
-
inline bool is_first_in_group(const Residue &res) const¶
Check if residue is the first in its group (sequence number). Returns false only for alternative conformations (microheterogeneity).
- Parameters:
res – The residue to check
- Returns:
true if res is the first residue with its sequence number
-
inline const Residue *previous_residue(const Residue &res) const¶
Get the previous different sequence number residue. Handles microheterogeneity and alternate conformations correctly.
- Parameters:
res – The reference residue
- Returns:
Pointer to previous residue (by sequence number), or nullptr if none
-
inline const Residue *next_residue(const Residue &res) const¶
Get the next different sequence number residue. Handles microheterogeneity and alternate conformations correctly.
- Parameters:
res – The reference residue
- Returns:
Pointer to next residue (by sequence number), or nullptr if none
-
inline UniqProxy<Residue> first_conformer()¶
Get proxy for iterating over first conformer only. Skips alternate conformations (microheterogeneity).
- Returns:
Iterator proxy
-
inline ConstUniqProxy<Residue> first_conformer() const¶
Get proxy for iterating over first conformer only. Skips alternate conformations (microheterogeneity).
- Returns:
Iterator proxy
Public Members
Public Static Functions
-
static inline const char *what()¶
-
Chain() = default¶
-
struct const_CRA¶
- #include <gemmi/model.hpp>
Const pointer triple: Chain, Residue, Atom. Used for read-only access to structure hierarchy.
-
struct ConstResidueGroup : public gemmi::ConstResidueSpan¶
- #include <gemmi/model.hpp>
Const version of ResidueGroup.
Public Functions
-
ConstResidueGroup() = default¶
-
inline ConstResidueGroup(ConstResidueSpan &&sp)¶
Construct from a moved span.
-
ConstResidueGroup() = default¶
-
struct ConstResidueSpan : public gemmi::Span<const Residue>¶
- #include <gemmi/model.hpp>
Immutable span of residues within a Chain.
Represents a contiguous sequence of residues with utility methods for manipulation, grouping, and sequence numbering conversions.
Subclassed by gemmi::ConstResidueGroup
Public Functions
-
inline int length() const¶
Count unique residues, accounting for microheterogeneity. Residues with the same sequence number but different names count as one.
- Returns:
Number of unique sequence positions
-
inline SeqId::OptionalNum extreme_num(bool label, int sign) const¶
Find extreme (minimum or maximum) sequence number in span.
- Parameters:
label – If true, use label_seq_id; if false, use seqid
sign – -1 for minimum, +1 for maximum
- Returns:
The extreme sequence number, or unset if span is empty
-
inline ConstUniqProxy<Residue, ConstResidueSpan> first_conformer() const¶
Get proxy for iterating over the first conformer only. Skips alternate conformations (microheterogeneity).
- Returns:
Iterator proxy
-
inline const std::string &subchain_id() const¶
Get the subchain identifier common to all residues in span.
-
inline ConstResidueGroup find_residue_group(SeqId id) const¶
Find residue group with given sequence ID.
- Parameters:
id – Sequence ID to search for
- Returns:
ConstResidueGroup containing residues with this sequence ID
-
inline std::vector<std::string> extract_sequence() const¶
Extract sequence of residue names from first conformer.
- Returns:
Vector of residue names (one per unique sequence position)
-
inline SeqId label_seq_id_to_auth(SeqId::OptionalNum label_seq_id) const¶
Convert from canonical sequence number to author (auth) sequence ID. Assumes residues are ordered; works approximately with missing numbers.
-
inline SeqId::OptionalNum auth_seq_id_to_label(SeqId auth_seq_id) const¶
Convert from author (auth) sequence ID to canonical sequence number. Uses a heuristic since author residue numbers are sometimes not ordered.
- Parameters:
auth_seq_id – Author sequence ID to convert
- Throws:
std::out_of_range – if span is empty
- Returns:
Canonical sequence number
-
inline int length() const¶
-
struct CRA¶
- #include <gemmi/model.hpp>
Mutable pointer triple: Chain, Residue, Atom. Used for modifiable access to structure hierarchy.
-
template<typename CraT>
class CraIterPolicy¶ - #include <gemmi/model.hpp>
Iterator policy for traversing Chain/Residue/Atom (CRA) triples.
Used with Gemmi’s generic iterator framework to provide bidirectional iteration over all atoms in a Model, yielding CRA structs.
- Template Parameters:
CraT – Either
CRA(mutable) orconst_CRA(immutable).
Public Types
-
using const_policy = CraIterPolicy<const_CRA>¶
Public Functions
-
inline CraIterPolicy()¶
Construct empty iterator.
-
inline CraIterPolicy(const Chain *end, CraT cra_)¶
Construct iterator at specific position.
- Parameters:
end – Pointer to end of chains array
cra_ – Initial Chain-Residue-Atom triple
-
inline void increment()¶
Advance to next atom.
-
inline void decrement()¶
Advance to previous atom.
-
inline bool equal(const CraIterPolicy &o) const¶
Check equality with another policy.
-
inline operator const_policy() const¶
Implicit conversion to const policy.
-
template<typename CraT, typename ChainsRefT>
struct CraProxy_¶ - #include <gemmi/model.hpp>
Proxy object for iterating over Chain/Residue/Atom triples in a Model.
Provides begin()/end() to enable range-for iteration over all CRA entries.
- Template Parameters:
CraT – Either
CRA(mutable) orconst_CRA(immutable).ChainsRefT – Reference to chains vector (mutable or const)
Public Types
-
using iterator = BidirIterator<CraIterPolicy<CraT>>¶
Public Functions
Public Members
-
ChainsRefT chains¶
Reference to chains vector.
-
struct Model¶
- #include <gemmi/model.hpp>
Represents a single model in an NMR ensemble or multi-model structure. Each model contains a set of chains with complete atomic coordinates.
Public Functions
-
Model() = default¶
-
inline explicit Model(int num_) noexcept¶
Construct model with given number.
- Parameters:
num_ – Model number to assign
-
inline Chain *find_chain(const std::string &chain_name)¶
Find first chain with given name.
- Parameters:
chain_name – Name of chain to search for
- Returns:
Pointer to chain, or nullptr if not found
-
inline const Chain *find_chain(const std::string &chain_name) const¶
Find first chain with given name.
- Parameters:
chain_name – Name of chain to search for
- Returns:
Pointer to chain, or nullptr if not found
-
inline Chain *find_last_chain(const std::string &chain_name)¶
Find last chain with given name. Useful when the same chain name appears multiple times.
- Parameters:
chain_name – Name of chain to search for
- Returns:
Pointer to last matching chain, or nullptr if not found
-
inline void remove_chain(const std::string &chain_name)¶
Remove all chains with given name.
- Parameters:
chain_name – Name of chains to remove
-
inline void merge_chain_parts(int min_sep = 0)¶
Merge consecutive chains with the same name. Appends residues from later chains to earlier ones with matching names.
- Parameters:
min_sep – Minimum sequence number separation between merged chains (0 = no enforcement)
-
inline ResidueSpan get_subchain(const std::string &sub_name)¶
Get residue span with given subchain identifier.
- Parameters:
sub_name – Subchain ID to search for
- Returns:
ResidueSpan of matching residues, or empty span if not found
-
inline ConstResidueSpan get_subchain(const std::string &sub_name) const¶
Get residue span with given subchain identifier.
- Parameters:
sub_name – Subchain ID to search for
- Returns:
ResidueSpan of matching residues, or empty span if not found
-
inline std::vector<ResidueSpan> subchains()¶
Get list of all subchains in all chains.
- Returns:
Vector of mutable residue spans, one per subchain
-
inline std::vector<ConstResidueSpan> subchains() const¶
Get list of all subchains in all chains.
- Returns:
Vector of mutable residue spans, one per subchain
-
inline std::map<std::string, std::string> subchain_to_chain() const¶
Create mapping from subchain IDs to chain names.
- Returns:
Map: subchain_id -> chain_name
-
inline Residue *find_residue(const std::string &chain_name, const ResidueId &rid)¶
Find residue in a specific chain by ResidueId.
- Parameters:
chain_name – Name of chain to search in
rid – ResidueId (number and insertion code) to search for
- Returns:
Pointer to residue, or nullptr if not found
-
inline const Residue *find_residue(const std::string &chain_name, const ResidueId &rid) const¶
Find residue in a specific chain by ResidueId.
- Parameters:
chain_name – Name of chain to search in
rid – ResidueId (number and insertion code) to search for
- Returns:
Pointer to residue, or nullptr if not found
-
inline ResidueGroup find_residue_group(const std::string &chain_name, SeqId seqid)¶
Find residue group (microheterogeneity-aware) in specific chain.
- Parameters:
chain_name – Name of chain to search in
seqid – Sequence ID to search for
- Throws:
fail() – if chain or residue not found
- Returns:
ResidueGroup containing residues with this sequence ID
-
inline Residue &sole_residue(const std::string &chain_name, SeqId seqid)¶
Find single residue in specific chain by sequence ID. Fails if there are multiple residues at this position (microheterogeneity).
- Parameters:
chain_name – Name of chain to search in
seqid – Sequence ID to search for
- Throws:
fail() – if residue not found or multiple alternatives exist
- Returns:
Reference to the unique residue
-
inline std::vector<std::string> get_all_residue_names() const¶
Get list of all unique residue names in model.
- Returns:
Vector of residue names (e.g., “ALA”, “GLY”, “HOH”)
-
inline CRA find_cra(const AtomAddress &address, bool ignore_segment = false)¶
Find atom by AtomAddress specification.
- Parameters:
address – AtomAddress specifying chain, residue, and atom
ignore_segment – If true, ignore segment ID in matching
- Returns:
Chain-Residue-Atom triple (pointers may be null if not found)
-
inline const_CRA find_cra(const AtomAddress &address, bool ignore_segment = false) const¶
Find atom by AtomAddress specification.
- Parameters:
address – AtomAddress specifying chain, residue, and atom
ignore_segment – If true, ignore segment ID in matching
- Returns:
Chain-Residue-Atom triple (pointers may be null if not found)
-
inline CraProxy all()¶
Get proxy for iterating over all atoms in model.
- Returns:
Mutable proxy over all Chain-Residue-Atom triples
-
inline ConstCraProxy all() const¶
Get proxy for iterating over all atoms in model.
- Returns:
Mutable proxy over all Chain-Residue-Atom triples
-
inline Atom *find_atom(const AtomAddress &address)¶
Find atom by AtomAddress.
- Parameters:
address – AtomAddress specifying the atom
- Returns:
Pointer to atom, or nullptr if not found
-
inline const Atom *find_atom(const AtomAddress &address) const¶
Find atom by AtomAddress.
- Parameters:
address – AtomAddress specifying the atom
- Returns:
Pointer to atom, or nullptr if not found
-
inline std::array<int, 3> get_indices(const Chain *c, const Residue *r, const Atom *a) const¶
Get array indices of chain, residue, and atom in model. Returns -1 for any pointer that is nullptr.
- Parameters:
c – Pointer to chain (may be null)
r – Pointer to residue (may be null)
a – Pointer to atom (may be null)
- Returns:
Array of 3 indices: [chain_index, residue_index, atom_index]
-
inline std::bitset<(size_t)El::END> present_elements() const¶
Get a bitset of all elements present in model.
- Returns:
Bitset with one bit per Element type
Public Members
-
int num = 0¶
Model number (usually 1-based)
Public Static Functions
-
static inline const char *what()¶
-
Model() = default¶
-
struct PdbReadOptions¶
- #include <gemmi/model.hpp>
Options controlling PDB file parsing behavior.
Public Members
-
int max_line_length = 0¶
Maximum line length (0 = no limit)
-
bool check_non_ascii = false¶
Detect and report non-ASCII characters.
-
bool ignore_ter = false¶
Ignore TER records completely.
-
bool split_chain_on_ter = false¶
Split chain at each TER record.
-
bool skip_remarks = false¶
Skip REMARK records entirely.
-
int max_line_length = 0¶
-
struct Residue : public gemmi::ResidueId¶
- #include <gemmi/model.hpp>
Represents a single residue (amino acid, nucleotide, or other). A residue is identified by its number and insertion code (SeqId) and contains multiple atoms, potentially in alternate conformations.
Public Functions
-
Residue() = default¶
-
inline explicit Residue(const ResidueId &rid) noexcept¶
Construct residue from a ResidueId (number and insertion code).
-
inline Residue empty_copy() const¶
Create a shallow copy of all fields except atoms (children). Used in template code for hierarchical copying.
- Returns:
New Residue with metadata copied but empty atoms vector
-
inline const Atom *find_by_element(El el) const¶
Find first atom with given element.
- Parameters:
el – Element to search for
- Returns:
Pointer to atom, or nullptr if not found
-
inline Atom *find_atom(const std::string &atom_name, char altloc, El el = El::X, bool strict_altloc = true)¶
Find atom by name, alternate location, and optional element. In strict_altloc mode (default), ‘*’ matches any altloc, ‘\0’ matches atoms without altloc. When strict_altloc is false, ‘\0’ is treated as a wildcard match (same as ‘*’).
- Parameters:
- Returns:
Pointer to matching atom, or nullptr if not found
-
inline const Atom *find_atom(const std::string &atom_name, char altloc, El el = El::X, bool strict_altloc = true) const¶
Find atom by name, alternate location, and optional element. In strict_altloc mode (default), ‘*’ matches any altloc, ‘\0’ matches atoms without altloc. When strict_altloc is false, ‘\0’ is treated as a wildcard match (same as ‘*’).
- Parameters:
- Returns:
Pointer to matching atom, or nullptr if not found
-
inline std::vector<Atom>::iterator find_atom_iter(const std::string &atom_name, char altloc, El el = El::X)¶
Find iterator to atom by name, alternate location, and optional element.
-
inline AtomGroup get(const std::string &atom_name)¶
Get group of atoms with the same name (different alternate locations).
- Parameters:
atom_name – Name of atoms to group
- Throws:
fail() – if no atoms with this name exist
- Returns:
AtomGroup containing all atoms with this name
-
inline Atom &sole_atom(const std::string &atom_name)¶
Get the single atom with given name. Fails if there are multiple alternate conformations.
- Parameters:
atom_name – Name of atom to find
- Throws:
fail() – if atom not found or multiple alternative atoms exist
- Returns:
Reference to the unique atom
-
inline const Atom *get_ca() const¶
Find peptide backbone CA (alpha carbon) atom.
- Returns:
Pointer to CA atom, or nullptr
-
inline const Atom *get_c() const¶
Find peptide backbone C (carbonyl carbon) atom.
- Returns:
Pointer to C atom, or nullptr
-
inline const Atom *get_n() const¶
Find peptide backbone N (amide nitrogen) atom.
- Returns:
Pointer to N atom, or nullptr
-
inline const Atom *get_o() const¶
Find peptide backbone O (carbonyl oxygen) atom.
- Returns:
Pointer to O atom, or nullptr
-
inline const Atom *get_p() const¶
Find nucleic acid phosphorus atom.
- Returns:
Pointer to P atom, or nullptr
-
inline const Atom *get_o3prim() const¶
Find nucleic acid O3’ (3-prime oxygen) atom.
- Returns:
Pointer to O3’ atom, or nullptr
-
inline bool same_conformer(const Residue &other) const¶
Check if this residue belongs to the same conformer as another. Compatible if either has no alternate locations, or they share an altloc.
- Parameters:
other – The other residue to compare
- Returns:
true if residues are in the same conformer
-
inline bool is_water() const¶
Check if this residue is a water molecule. Recognizes HOH, DOD (deuterated water), WAT, H2O. Does not match OH or H3O/D3O.
- Returns:
true if residue name matches water identifiers
-
inline UniqProxy<Atom> first_conformer()¶
Get proxy for iterating over atoms of the first conformer only. Useful for skipping alternate conformations in loops.
- Returns:
Iterator proxy that yields only the first alternate location
-
inline ConstUniqProxy<Atom> first_conformer() const¶
Get proxy for iterating over atoms of the first conformer only. Useful for skipping alternate conformations in loops.
- Returns:
Iterator proxy that yields only the first alternate location
Public Members
-
OptionalNum label_seq¶
mmCIF _atom_site.label_seq_id (canonical sequence numbering)
-
EntityType entity_type = EntityType::Unknown¶
Polymer, NonPolymer, Water, or Unknown.
-
char het_flag = '\0'¶
‘A’ = ATOM record, ‘H’ = HETATM record, ‘\0’ = unspecified
-
char flag = '\0'¶
Custom flag for user-defined marking.
-
ResidueStrandSense strand_sense_from_file = ResidueStrandSense::NotStrand¶
Strand sense in sheet.
-
SiftsUnpResidue sifts_unp¶
UniProt reference from SIFTS mapping.
-
short group_idx = 0¶
Internal variable (ignore)
Public Static Functions
-
static inline const char *what()¶
-
Residue() = default¶
-
struct ResidueGroup : public gemmi::ResidueSpan¶
- #include <gemmi/model.hpp>
Group of residues with the same sequence ID but different names. Represents microheterogeneity (multiple forms of the same residue position). Usually contains only one residue; multiple residues indicate alternate conformations. Residues within a group must be consecutive.
Public Functions
-
ResidueGroup() = default¶
-
inline ResidueGroup(ResidueSpan &&span)¶
Construct from a moved span.
-
ResidueGroup() = default¶
-
struct ResidueSpan : public gemmi::MutableVectorSpan<Residue>¶
- #include <gemmi/model.hpp>
Mutable span of consecutive residues within a chain. Represents a contiguous subsequence of residues that can be modified. It is returned by get_polymer(), get_ligands(), get_waters() and get_subchain().
Subclassed by gemmi::ResidueGroup
Public Types
-
using Parent = MutableVectorSpan<Residue>¶
Public Functions
-
ResidueSpan() = default¶
-
inline ResidueSpan(vector_type &v, iterator begin, std::size_t n)¶
Construct from a vector with specific range.
-
inline int length() const¶
Count unique residues, accounting for microheterogeneity. Residues with the same sequence number but different names count as one.
- Returns:
Number of unique sequence positions
-
inline SeqId::OptionalNum extreme_num(bool label, int sign) const¶
Find extreme (minimum or maximum) sequence number in span.
- Parameters:
label – If true, use label_seq_id; if false, use seqid
sign – -1 for minimum, +1 for maximum
- Returns:
The extreme sequence number, or unset if span is empty
-
inline UniqProxy<Residue, ResidueSpan> first_conformer()¶
Get proxy for iterating over the first conformer only. Skips alternate conformations (microheterogeneity).
- Returns:
Iterator proxy
-
inline ConstUniqProxy<Residue, ResidueSpan> first_conformer() const¶
Get proxy for iterating over the first conformer only. Skips alternate conformations (microheterogeneity).
- Returns:
Iterator proxy
-
inline GroupingProxy residue_groups()¶
Get proxy for iterating over residue groups (microheterogeneity-aware).
Get proxy for iterating over residue groups (microheterogeneity-aware).
-
inline const std::string &subchain_id() const¶
Get the subchain identifier common to all residues in span.
-
inline ResidueGroup find_residue_group(SeqId id)¶
Find residue group with given sequence ID.
- Parameters:
id – Sequence ID to search for
- Returns:
ResidueGroup containing residues with this sequence ID
-
inline std::vector<std::string> extract_sequence() const¶
Extract sequence of residue names from first conformer.
- Returns:
Vector of residue names (one per unique sequence position)
-
inline ConstResidueGroup find_residue_group(SeqId id) const¶
Find residue group with given sequence ID.
- Parameters:
id – Sequence ID to search for
- Returns:
ConstResidueGroup containing residues with this sequence ID
-
inline SeqId label_seq_id_to_auth(SeqId::OptionalNum label_seq_id) const¶
Convert from canonical sequence number to author (auth) sequence ID. Assumes residues are ordered; works approximately with missing numbers.
-
inline SeqId::OptionalNum auth_seq_id_to_label(SeqId auth_seq_id) const¶
Convert from author (auth) sequence ID to canonical sequence number. Uses a heuristic since author residue numbers are sometimes not ordered.
- Parameters:
auth_seq_id – Author sequence ID to convert
- Throws:
std::out_of_range – if span is empty
- Returns:
Canonical sequence number
Private Functions
-
inline ConstResidueSpan const_() const¶
-
struct GroupingProxy¶
- #include <gemmi/model.hpp>
Proxy providing iteration over ResidueGroups within a ResidueSpan.
Each ResidueGroup contains residues with the same sequence number (microheterogeneities — point mutations stored as alternative residues).
Public Types
-
using iterator = GroupingIter<ResidueSpan, ResidueGroup>¶
Public Functions
Public Members
-
ResidueSpan &span¶
-
using iterator = GroupingIter<ResidueSpan, ResidueGroup>¶
-
using Parent = MutableVectorSpan<Residue>¶
-
struct Structure¶
- #include <gemmi/model.hpp>
Represents a complete macromolecular structure with coordinates and metadata. The top level of the data hierarchy containing models, chains, residues, and atoms, along with crystallographic, NMR, and biological assembly information.
Public Functions
-
inline const SpaceGroup *find_spacegroup() const¶
Find space group definition based on cell parameters.
- Returns:
Pointer to SpaceGroup, or nullptr if not a crystal (aperiodic) structure
-
inline const std::string &get_info(const std::string &tag) const¶
Get metadata value by mmCIF tag key.
- Parameters:
tag – mmCIF tag (e.g., “_entry.id”, “_cell.Z_PDB”)
- Returns:
Value of tag, or empty string if not found
-
inline Model &first_model()¶
Get first model in structure.
- Throws:
fail() – if no models exist
- Returns:
Reference to first model
-
inline const Model &first_model() const¶
Get first model in structure.
- Throws:
fail() – if no models exist
- Returns:
Reference to first model
-
inline Model *find_model(int model_num)¶
Find model by number.
- Parameters:
model_num – Model number to search for
- Returns:
Pointer to model, or nullptr if not found
-
inline const Model *find_model(int model_num) const¶
Find model by number.
- Parameters:
model_num – Model number to search for
- Returns:
Pointer to model, or nullptr if not found
-
inline Model &find_or_add_model(int model_num)¶
Find model by number, creating it if necessary.
- Parameters:
model_num – Model number to find or create
- Returns:
Reference to existing or newly created model
-
inline void renumber_models()¶
Renumber all models sequentially (1, 2, 3, …).
-
inline Entity *get_entity(const std::string &ent_id)¶
Find entity by ID.
- Parameters:
ent_id – Entity identifier
- Returns:
Pointer to entity, or nullptr if not found
-
inline const Entity *get_entity(const std::string &ent_id) const¶
Find entity by ID.
- Parameters:
ent_id – Entity identifier
- Returns:
Pointer to entity, or nullptr if not found
-
inline Entity *get_entity_of(const ConstResidueSpan &sub)¶
Find entity that contains given residue span (subchain).
- Parameters:
sub – Residue span (subchain) to query
- Returns:
Pointer to entity, or nullptr if not found or span is empty
-
inline const Entity *get_entity_of(const ConstResidueSpan &sub) const¶
Find entity that contains given residue span (subchain).
- Parameters:
sub – Residue span (subchain) to query
- Returns:
Pointer to entity, or nullptr if not found or span is empty
-
inline Assembly *find_assembly(const std::string &assembly_id)¶
Find biological assembly by ID.
- Parameters:
assembly_id – Assembly identifier
- Returns:
Pointer to assembly, or nullptr if not found
-
inline Connection *find_connection_by_name(const std::string &conn_name)¶
Find connection (bond) by name identifier.
- Parameters:
conn_name – Connection name (e.g., “BOND_1”)
- Returns:
Pointer to connection, or nullptr if not found
-
inline const Connection *find_connection_by_name(const std::string &conn_name) const¶
Find connection (bond) by name identifier.
- Parameters:
conn_name – Connection name (e.g., “BOND_1”)
- Returns:
Pointer to connection, or nullptr if not found
-
inline Connection *find_connection_by_cra(const const_CRA &cra1, const const_CRA &cra2, bool ignore_segment = false)¶
Find connection between two atoms specified as Chain-Residue-Atom triples. Matches atoms in either order.
- Parameters:
cra1 – First atom specification
cra2 – Second atom specification
ignore_segment – If true, ignore segment ID in matching
- Returns:
Pointer to connection, or nullptr if not found
-
inline Connection *find_connection(const AtomAddress &a1, const AtomAddress &a2)¶
Find connection between two atoms specified as AtomAddresses. Matches atoms in either order.
- Parameters:
a1 – First atom address
a2 – Second atom address
- Returns:
Pointer to connection, or nullptr if not found
-
inline size_t ncs_given_count() const¶
Count NCS operators that are explicitly given (not generated).
- Returns:
Number of given NCS operations
-
inline double get_ncs_multiplier() const¶
Get multiplier for calculating expected multiplicity from NCS. Equals (number_of_ncs_ops + 1) / (number_of_given_ncs + 1).
- Returns:
NCS multiplier factor
-
inline bool ncs_not_expanded() const¶
Check if NCS operations are not fully expanded.
- Returns:
true if any NCS operator is not marked as given
-
inline void add_conect_one_way(int serial_a, int serial_b, int order)¶
Add bond(s) from one atom to another in one direction only. Used internally by add_conect() to build the CONECT map.
- Parameters:
serial_a – Serial number of first atom
serial_b – Serial number of second atom
order – Bond order (number of edges to add)
-
inline void add_conect(int serial1, int serial2, int order)¶
Add bidirectional bond(s) between two atoms. Adds edges in both directions (serial1->serial2 and serial2->serial1).
- Parameters:
serial1 – Serial number of first atom
serial2 – Serial number of second atom
order – Bond order (number of edges to add in each direction)
-
inline void merge_chain_parts(int min_sep = 0)¶
Merge consecutive chains with the same name across all models.
- Parameters:
min_sep – Minimum sequence number separation between merged chains
-
inline void remove_empty_chains()¶
Remove all empty chains from all models.
-
inline Structure empty_copy() const¶
Create a shallow copy with metadata but empty models. Copies all fields except the models vector (which remains empty). Used in template code for hierarchical copying.
- Returns:
New Structure with metadata but no structural data
-
inline void setup_cell_images()¶
Set up crystallographic cell image information. Populates cell image transformations based on space group symmetry and NCS.
Set up crystallographic cell image information. Populates cell image transformations based on space group symmetry and NCS.
Public Members
-
std::vector<Connection> connections¶
Chemical bonds and other connections.
-
std::vector<StructSite> sites¶
Special sites (binding sites, etc.)
-
CoorFormat input_format = CoorFormat::Unknown¶
Format of input file (PDB, mmCIF, etc.)
-
bool has_d_fraction = false¶
Flag: uses Refmac’s ccp4_deuterium_fraction.
-
int non_ascii_line = 0¶
First PDB line with non-ASCII bytes (0 = none)
-
char ter_status = '\0'¶
Status of TER records in PDB file. ‘\0’ = not set, ‘y’ = TER records were read, ‘e’ = errors detected.
-
bool has_origx = false¶
Flag: ORIGX transformation matrix present.
-
std::vector<std::pair<std::string, std::string>> shortened_ccd_codes¶
Mapping of long (4+ chars) CCD codes to PDB-compatible 3-letter codes.
-
double resolution = 0¶
Resolution from REMARK 2 (0 = not set, in Å)
Public Static Functions
-
static inline const char *what()¶
-
inline const SpaceGroup *find_spacegroup() const¶
-
namespace impl¶
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
Functions
-
using AtomGroup = AtomGroup_<Atom>¶
Unit cell and fractional/Cartesian coordinate transformations. Defines the UnitCell struct and related types for crystallographic operations. Provides coordinate transformation matrices, distance calculations with periodic boundary conditions, and symmetry operation tracking.
-
namespace gemmi
Typedefs
Enums
-
enum class Asu : unsigned char¶
Asymmetric unit filter for nearest-image searches.
Values:
-
enumerator Same¶
Include only the same asymmetric unit (no symmetry).
-
enumerator Different¶
Exclude the same asymmetric unit (only symmetry-related copies).
-
enumerator Any¶
Include all images (same and symmetry-related).
-
enumerator Same¶
Functions
-
inline Mat33 rot_as_mat33(const Op::Rot &rot)¶
Converts a symmetry operation rotation matrix to Mat33 format.
-
inline Mat33 rot_as_mat33(const Op &op)¶
Converts a symmetry operation to Mat33 rotation matrix format.
- Parameters:
op – The symmetry operation.
- Returns:
A Mat33 with the operation’s rotation matrix scaled to unit coefficients.
-
struct Fractional : public gemmi::Vec3_<double>¶
- #include <gemmi/unitcell.hpp>
Fractional coordinates (within the unit cell). Represents coordinates in the crystal cell basis (a, b, c vectors). Values typically in [0, 1) but may extend outside this range for nearby cells.
Public Functions
-
Fractional() = default¶
-
inline Fractional operator-(const Fractional &o) const¶
Subtraction of fractional coordinates.
-
inline Fractional operator+(const Fractional &o) const¶
Addition of fractional coordinates.
-
inline Fractional wrap_to_unit() const¶
Wrap coordinates to [0, 1). Subtracts floor of each component to bring into primary unit cell.
- Returns:
Wrapped fractional coordinates.
-
inline Fractional wrap_to_zero() const¶
Wrap coordinates to (-0.5, 0.5]. Subtracts nearest integer to bring close to origin (for distances).
- Returns:
Wrapped fractional coordinates centered at origin.
-
inline Fractional round() const¶
Round each component to the nearest integer.
- Returns:
Rounded fractional coordinates.
-
inline void move_toward_zero_by_one()¶
Move each component toward zero by 1 if outside (-0.5, 0.5]. Used for wrapping to the asymmetric unit.
-
Fractional() = default¶
-
struct FTransform : public gemmi::Transform¶
- #include <gemmi/unitcell.hpp>
Fractional coordinate transformation. Like Transform, but operates on Fractional coordinates for type safety. Used for symmetry operations and basis transformations in fractional space.
Public Functions
-
FTransform() = default¶
-
inline Fractional apply(const Fractional &p) const¶
Apply transformation to fractional coordinates.
- Parameters:
p – Fractional coordinates.
- Returns:
Transformed fractional coordinates.
-
FTransform() = default¶
-
struct MillerHash¶
- #include <gemmi/unitcell.hpp>
Hash function for Miller indices. Enables use of Miller indices in hash tables and unordered containers.
-
struct NcsOp¶
- #include <gemmi/unitcell.hpp>
Non-crystallographic symmetry operation (such as in PDB MTRIXn records). Represents a transformation for NCS (molecular symmetry not related to the crystal lattice).
Public Functions
-
struct NearestImage¶
- #include <gemmi/unitcell.hpp>
Result of finding the nearest image of an atom under periodic boundary conditions and symmetry. Stores the squared distance, PBC shifts, and symmetry operation index.
Public Functions
-
inline double dist() const¶
Compute distance from squared distance.
- Returns:
Distance in Angstroms.
-
inline bool same_asu() const¶
Check if the image is in the same asymmetric unit.
- Returns:
True if no PBC shifts and identity symmetry operation.
-
inline std::string symmetry_code(bool underscore) const¶
Generate a symmetry code (e.g., “1555” or “1_555”). Encodes the symmetry operation index and PBC shifts in standard crystallographic notation.
- Parameters:
underscore – If true, use format “1_555”; if false, use “1555”.
- Returns:
Symmetry code string.
-
inline double dist() const¶
-
struct Position : public gemmi::Vec3_<double>¶
- #include <gemmi/unitcell.hpp>
Coordinates in Angstroms - orthogonal (Cartesian) coordinates. Represents a position in 3D Cartesian space. Inherits from Vec3 and provides arithmetic operations that return Position objects (for type safety).
Public Functions
-
Position() = default¶
-
Position() = default¶
-
struct UnitCell : public gemmi::UnitCellParameters¶
- #include <gemmi/unitcell.hpp>
Unit cell with pre-calculated transformation matrices and properties. Stores crystallographic unit cell parameters (a, b, c, alpha, beta, gamma) and pre-computes the orthogonalization and fractionalization transformation matrices, cell volume, reciprocal cell parameters, and symmetry operations.
The orthogonalization matrix converts fractional to Cartesian coordinates using the PDB convention (a-axis along X, a*-axis along Z). The fractionalization matrix is its inverse.
Symmetry operations can include crystallographic symmetry (space group) and non-crystallographic symmetry (NCS), stored as fractional transformations.
For non-crystalline structures (NMR), the default dummy cell 1×1×1 is used.
Public Functions
-
UnitCell() = default¶
-
inline UnitCell(double a_, double b_, double c_, double alpha_, double beta_, double gamma_)¶
Construct from six cell parameters.
- Parameters:
a_ – Edge length a (Angstroms).
b_ – Edge length b (Angstroms).
c_ – Edge length c (Angstroms).
alpha_ – Angle alpha (degrees).
beta_ – Angle beta (degrees).
gamma_ – Angle gamma (degrees).
-
inline UnitCell(const std::array<double, 6> &v)¶
Construct from an array of 6 doubles.
- Parameters:
v – Array with [a, b, c, alpha, beta, gamma].
-
inline bool is_crystal() const¶
Check if this is a crystalline structure. Returns false for non-crystalline structures (e.g., NMR) marked with dummy 1×1×1 cell. Checks both cell parameter a and the fractionalization matrix for consistency.
- Returns:
True if a != 1.0 and frac.mat[0][0] != 1.0.
-
inline bool is_similar(const UnitCell &o, double rel, double deg) const¶
Check if cell parameters are similar to another cell. Lengths are compared using relative tolerance; angles using absolute tolerance.
- Parameters:
o – Other unit cell.
rel – Relative tolerance for edge lengths.
deg – Absolute tolerance for angles in degrees.
- Returns:
True if all parameters are within tolerance.
-
inline void calculate_properties()¶
Calculate derived properties (volume, reciprocal cell, transformation matrices). Computes cell volume, reciprocal cell parameters, and orthogonalization/fractionalization matrices using the Giacovazzo formulas. Angles are converted from degrees to radians. Must be called after setting cell parameters.
-
inline double cos_alpha() const¶
Get cosine of alpha angle. Converts alpha from degrees to radians and computes cosine.
- Returns:
cos(alpha) where alpha is in radians.
-
inline Mat33 calculate_matrix_B() const¶
Calculate B matrix for X-ray crystallography.
Returns the B matrix in the Busing & Levy (1967) convention (PDB convention), not the cctbx convention. Used in computing structure factors and Debye-Waller factors.
- References
Busing, W.R. & Levy, H.A. (1967). Angle calculations for 3- and 4-circle X-ray and neutron diffractometers. Acta Cryst. 22, 457–464. https://doi.org/10.1107/S0365110X67000970
- Returns:
3×3 matrix B.
-
inline double calculate_u_eq(const SMat33<double> &ani) const¶
Calculate equivalent isotropic displacement factor (B_eq).
Converts a non-orthogonal anisotropic displacement tensor to an isotropic value.
- References
Fischer, R.X. & Tillmanns, E. (1988). The equivalent isotropic displacement factor. Acta Cryst. C44, 775–776. https://doi.org/10.1107/S0108270188007712
- Parameters:
ani – Anisotropic displacement tensor (non-orthogonalized, e.g., from SmallStructure::Site). Should NOT be the orthogonal tensor from Atom.
- Returns:
Equivalent isotropic displacement factor.
-
inline void set_matrices_from_fract(const Transform &f)¶
Set fractionalization matrix from external source. Used to incorporate explicit SCALE records (PDB) or atom_sites.fract_transf* (mmCIF) when they differ significantly from calculated values. Validates input against suspicious values before acceptance.
- Parameters:
f – External fractionalization transformation.
-
inline void set(double a_, double b_, double c_, double alpha_, double beta_, double gamma_)¶
Set unit cell from six parameters and compute all derived properties. Ignores empty or partial CRYST1 records (gamma=0).
- Parameters:
a_ – Edge length a (Angstroms).
b_ – Edge length b (Angstroms).
c_ – Edge length c (Angstroms).
alpha_ – Angle alpha (degrees).
beta_ – Angle beta (degrees).
gamma_ – Angle gamma (degrees).
-
inline void set_from_parameters(const UnitCellParameters &p)¶
Set unit cell from UnitCellParameters object.
- Parameters:
p – Cell parameters to copy.
-
inline void set_from_array(const std::array<double, 6> &v)¶
Set unit cell from array of six doubles.
- Parameters:
v – Array with [a, b, c, alpha, beta, gamma].
-
inline void set_from_vectors(const Vec3 &va, const Vec3 &vb, const Vec3 &vc)¶
Set unit cell from three edge vectors. Computes cell parameters from the lengths and angles between vectors.
- Parameters:
va – First lattice vector (typically a).
vb – Second lattice vector (typically b).
vc – Third lattice vector (typically c).
-
inline UnitCell changed_basis_backward(const Op &op, bool set_images)¶
Transform unit cell to a different basis using a change-of-basis operation. Applies a symmetry operation (rotation + translation) to change the coordinate system. The new cell is computed from the transformed lattice vectors.
- Parameters:
op – Change-of-basis operation (typically a crystallographic symmetry operation).
set_images – If true, also transform the stored symmetry operations.
- Returns:
New unit cell in the transformed basis.
-
inline UnitCell changed_basis_forward(const Op &op, bool set_images)¶
Transform unit cell using inverse of a basis operation. Equivalent to changed_basis_backward(op.inverse(), set_images).
- Parameters:
op – Change-of-basis operation.
set_images – If true, also transform the stored symmetry operations.
- Returns:
New unit cell in the transformed basis.
-
inline bool is_compatible_with_groupops(const GroupOps &gops, double eps = 1e-3) const¶
Check if unit cell is compatible with a set of symmetry operations. Verifies that the metric tensor is preserved under all operations.
- Parameters:
gops – Group operations to check.
eps – Tolerance for metric tensor differences.
- Returns:
True if all operations preserve the metric tensor.
-
inline bool is_compatible_with_spacegroup(const SpaceGroup *sg, double eps = 1e-3) const¶
Check if unit cell is compatible with a space group.
- Parameters:
sg – Space group to check (may be null).
eps – Tolerance for metric tensor differences.
- Returns:
True if space group is non-null and all its operations preserve the metric tensor.
-
inline void set_cell_images_from_groupops(const GroupOps &group_ops)¶
Set crystallographic symmetry operations from a GroupOps object. Clears existing images and populates with all space group operations except identity.
- Parameters:
group_ops – Group operations (e.g., from a space group).
-
inline void set_cell_images_from_spacegroup(const SpaceGroup *sg)¶
Set crystallographic symmetry operations from a space group.
- Parameters:
sg – Space group (may be null; clears images if so).
-
inline void add_ncs_images_to_cs_images(const std::vector<NcsOp> &ncs)¶
Add non-crystallographic symmetry (NCS) operations to existing crystallographic symmetry. Generates the Cartesian product of CS and NCS operations.
- Parameters:
ncs – List of non-crystallographic symmetry operations.
- Pre:
cs_count must equal images.size() before calling.
-
inline std::vector<FTransform> get_ncs_transforms() const¶
Extract non-crystallographic symmetry operations from images. Returns the subset of operations that are NCS (not crystallographic symmetry).
- Returns:
Vector of NCS transformation in fractional coordinates.
-
inline Position orthogonalize(const Fractional &f) const¶
Convert fractional coordinates to Cartesian (orthogonal).
- Parameters:
f – Fractional coordinates.
- Returns:
Position in Cartesian coordinates.
-
inline Fractional fractionalize(const Position &o) const¶
Convert Cartesian coordinates to fractional.
- Parameters:
o – Position in Cartesian coordinates.
- Returns:
Fractional coordinates.
-
inline Position orthogonalize_difference(const Fractional &delta) const¶
Convert fractional displacement to Cartesian. Applied to differences only; does not include translation vector. Guarantees: orthogonalize_difference(a-b) == orthogonalize(a) - orthogonalize(b) The translation shift (frac.vec) can be non-zero in non-standard settings and is not applied here.
- Parameters:
delta – Fractional displacement vector.
- Returns:
Cartesian displacement vector.
-
inline Fractional fractionalize_difference(const Position &delta) const¶
Convert Cartesian displacement to fractional. Inverse operation of orthogonalize_difference.
- Parameters:
delta – Cartesian displacement vector.
- Returns:
Fractional displacement vector.
-
inline Box<Position> orthogonalize_box(const Box<Fractional> &f) const¶
Compute the bounding box in Cartesian coordinates from a fractional box. A cuboid in fractional coordinates becomes a parallelepiped in Cartesian space. All 8 corners of the fractional box are transformed to find the Cartesian bounding box.
- Parameters:
f – Bounding box in fractional coordinates.
- Returns:
Bounding box in Cartesian coordinates.
-
inline Transform orthogonalize_transform(const FTransform &ftr) const¶
Compose a fractional transformation into a Cartesian transformation. Converts from fractional to orthogonal space: T_orth = O * T_frac * F, where O is orthogonalization and F is fractionalization matrix.
- Parameters:
ftr – Transformation in fractional coordinates.
- Returns:
Equivalent transformation in Cartesian coordinates.
-
inline Transform op_as_transform(const Op &op) const¶
Convert a symmetry operation to a Cartesian transformation.
- Parameters:
op – Crystallographic symmetry operation.
- Returns:
Equivalent transformation in Cartesian coordinates.
-
inline double distance_sq(const Fractional &pos1, const Fractional &pos2) const¶
Compute squared distance between two fractional coordinates. Applies periodic boundary conditions (wraps difference to (-0.5, 0.5]).
- Parameters:
pos1 – First position in fractional coordinates.
pos2 – Second position in fractional coordinates.
- Returns:
Squared distance in Angstroms^2.
-
inline double distance_sq(const Position &pos1, const Position &pos2) const¶
Compute squared distance between two Cartesian coordinates. Converts to fractional, then applies PBC.
- Parameters:
pos1 – First position in Cartesian coordinates.
pos2 – Second position in Cartesian coordinates.
- Returns:
Squared distance in Angstroms^2.
-
inline double volume_per_image() const¶
Compute volume per asymmetric unit. For crystalline structures, divides total volume by the number of asymmetric units.
- Returns:
Volume per asymmetric unit, or NaN for non-crystalline structures.
-
inline NearestImage find_nearest_image(const Position &ref, const Position &pos, Asu asu) const¶
Find the nearest image of an atom under periodic boundary conditions and symmetry. Searches all unit cell translations and all symmetry operations to find the closest image.
- Parameters:
ref – Reference position in Cartesian coordinates.
pos – Position to find nearest image of (Cartesian).
asu – Filter: whether to include the same or different asymmetric units.
- Returns:
NearestImage containing squared distance, PBC shifts, and symmetry operation index.
-
inline void apply_transform(Fractional &fpos, int image_idx, bool inverse) const¶
Apply or unapply a symmetry operation to fractional coordinates.
- Parameters:
fpos – Fractional position (modified in place).
image_idx – Symmetry operation index (0 = identity, 1+ = images[index-1]).
inverse – If true, apply inverse operation; if false, apply forward.
-
inline NearestImage find_nearest_pbc_image(const Fractional &fref, Fractional fpos, int image_idx = 0) const¶
Find nearest image of a fractional coordinate under PBC for a given symmetry. Applies a specific symmetry operation and finds the nearest translation of the result.
- Parameters:
fref – Reference position in fractional coordinates.
fpos – Position to find nearest image of (fractional).
image_idx – Symmetry operation index (0 = identity).
- Returns:
NearestImage with distance and PBC shifts for this symmetry.
-
inline NearestImage find_nearest_pbc_image(const Position &ref, const Position &pos, int image_idx = 0) const¶
Find nearest image of a Cartesian position under PBC for a given symmetry.
- Parameters:
ref – Reference position in Cartesian coordinates.
pos – Position to find nearest image of (Cartesian).
image_idx – Symmetry operation index (0 = identity).
- Returns:
NearestImage with distance and PBC shifts for this symmetry.
-
inline std::vector<NearestImage> find_nearest_pbc_images(const Fractional &fref, double dist, const Fractional &fpos, int image_idx) const¶
Find all nearby images of a position within a given distance. Returns all images (under PBC shifts near the nearest) within the specified distance.
- Parameters:
fref – Reference position in fractional coordinates.
dist – Distance cutoff in Angstroms.
fpos – Position to find images of (fractional).
image_idx – Symmetry operation index (0 = identity).
- Returns:
Vector of NearestImage objects for all nearby translations within distance.
-
inline Position orthogonalize_in_pbc(const Position &ref, const Fractional &fpos) const¶
Convert fractional position to Cartesian, applying PBC. Takes a fractional position that may be outside [0, 1) and returns the nearest equivalent position when converted to Cartesian coordinates, relative to a reference position.
- Parameters:
ref – Reference position in Cartesian coordinates.
fpos – Fractional position (may be outside primary cell).
- Returns:
Equivalent Cartesian position (nearest to ref).
-
inline Position find_nearest_pbc_position(const Position &ref, const Position &pos, int image_idx, bool inverse = false) const¶
Find the nearest PBC position of a point under a given symmetry operation. Applies a symmetry operation and then accounts for periodic boundary conditions.
- Parameters:
ref – Reference position in Cartesian coordinates.
pos – Position to transform (Cartesian).
image_idx – Symmetry operation index (0 = identity).
inverse – If true, apply inverse symmetry operation.
- Returns:
Nearest equivalent position in Cartesian coordinates.
-
inline Fractional fract_image(const NearestImage &im, Fractional fpos)¶
Apply a NearestImage transformation to fractional coordinates. Applies both the symmetry operation and PBC shift from a NearestImage result.
- Parameters:
im – NearestImage from a previous search.
fpos – Fractional position to transform.
- Returns:
Transformed fractional position.
-
inline int is_special_position(const Fractional &fpos, double max_dist) const¶
Determine if a position is on a special crystallographic site. Counts how many independent symmetry operations map this position to nearby locations (within max_dist). A special position has symmetry-equivalent copies very close by.
- Parameters:
fpos – Position in fractional coordinates.
max_dist – Maximum distance (Angstroms) to consider as overlapping.
- Returns:
Number of nearby symmetry-equivalent positions (0 = none, 3 = 4-fold axis, etc.).
- Pre:
is_crystal() must be true.
-
inline int is_special_position(const Position &pos, double max_dist = 0.8) const¶
Determine if a Cartesian position is on a special crystallographic site.
- Parameters:
pos – Position in Cartesian coordinates.
max_dist – Maximum distance (Angstroms) to consider as overlapping (default 0.8).
- Returns:
Number of nearby symmetry-equivalent positions.
-
inline double calculate_1_d2_double(double h, double k, double l) const¶
Calculate 1/d^2 for a reflection with floating-point indices. Computes the reciprocal d-spacing squared: 1/d^2 = (2*sin(theta)/lambda)^2. Uses floating-point indices (for MTZ files which may store fractional indices).
- Parameters:
h – Miller index h (may be fractional).
k – Miller index k (may be fractional).
l – Miller index l (may be fractional).
- Returns:
1/d^2 in (Angstroms)^(-2).
-
inline double calculate_1_d2(const Miller &hkl) const¶
Calculate 1/d^2 for integer Miller indices.
- Parameters:
hkl – Miller indices.
- Returns:
1/d^2 in (Angstroms)^(-2).
-
inline double calculate_d(const Miller &hkl) const¶
Calculate d-spacing for a reflection. d = lambda/(2*sin(theta)). This formula gives the real-space distance between planes perpendicular to the reciprocal lattice vector hkl.
- Parameters:
hkl – Miller indices.
- Returns:
d-spacing in Angstroms.
-
inline double calculate_stol_sq(const Miller &hkl) const¶
Calculate (sin(theta)/lambda)^2 for a reflection. Also known as 1/(4*d^2). Used in structure factor calculations.
- Parameters:
hkl – Miller indices.
- Returns:
(sin(theta)/lambda)^2 in (Angstroms)^(-2).
-
inline SMat33<double> metric_tensor() const¶
Compute the metric tensor (Gram matrix) of the cell. The metric tensor describes the dot products of the lattice vectors. G_ij = a_i · a_j, with elements in Voigt notation: [G11, G22, G33, G12, G13, G23].
- Returns:
Symmetric 3×3 matrix (metric tensor).
-
inline SMat33<double> reciprocal_metric_tensor() const¶
Compute the reciprocal metric tensor. The reciprocal metric tensor for the reciprocal cell.
- Returns:
Symmetric 3×3 matrix (reciprocal metric tensor).
-
inline UnitCell reciprocal() const¶
Construct the reciprocal unit cell. Returns a new UnitCell with parameters (a*, b*, c*, alpha*, beta*, gamma*).
- Returns:
Reciprocal cell.
-
inline Miller get_hkl_limits(double dmin) const¶
Get maximum Miller indices for a minimum d-spacing. Useful for defining resolution limits in reciprocal space.
- Parameters:
dmin – Minimum d-spacing in Angstroms.
- Returns:
Miller indices [h_max, k_max, l_max] to achieve dmin resolution.
-
inline Mat33 primitive_orth_matrix(char centring_type) const¶
Get orthogonalization matrix for a primitive cell. Adjusts the standard orthogonalization matrix for non-primitive centring.
- Parameters:
centring_type – Crystal centring type (‘P’, ‘C’, ‘B’, ‘A’, ‘I’, ‘F’, ‘R’, ‘H’).
- Returns:
Orthogonalization matrix for the primitive cell.
Public Members
-
double volume = 1.0¶
Unit cell volume in Angstroms^3.
-
double ar = 1.0¶
-
double br = 1.0¶
-
double cr = 1.0¶
Reciprocal cell edge lengths (a*, b*, c*).
-
double cos_alphar = 0.0¶
-
double cos_betar = 0.0¶
-
double cos_gammar = 0.0¶
Cosines of reciprocal cell angles.
-
bool explicit_matrices = false¶
True if orthogonalization matrices were explicitly set (non-standard settings).
-
short cs_count = 0¶
Count of crystallographic symmetry operations (excluding identity).
-
std::vector<FTransform> images¶
Symmetry operations (crystallographic and NCS) in fractional coordinates.
Private Functions
-
inline bool search_pbc_images(Fractional &&diff, NearestImage &image) const¶
Helper function: search for nearest image under PBC and update result. Applies periodic boundary conditions by wrapping the difference vector, then computes the distance and updates the image if closer than current.
- Parameters:
diff – Fractional displacement (moved to find nearest image).
image – On input, contains current best distance; updated if better found.
- Returns:
True if a closer image was found.
-
UnitCell() = default¶
-
struct UnitCellParameters¶
- #include <gemmi/unitcell.hpp>
Base parameters for a unit cell (6 parameters: 3 lengths and 3 angles). Stores the six independent parameters defining a crystallographic unit cell. Angles are in degrees.
Subclassed by gemmi::UnitCell
Public Functions
-
UnitCellParameters() = default¶
-
inline explicit UnitCellParameters(const double (&par)[6])¶
Construct from a C-style array of 6 doubles.
- Parameters:
par – Array with [a, b, c, alpha, beta, gamma].
-
inline explicit UnitCellParameters(const std::array<double, 6> &par)¶
Construct from a std::array of 6 doubles.
- Parameters:
par – Array with [a, b, c, alpha, beta, gamma].
-
inline bool operator==(const UnitCellParameters &o) const¶
Exact equality comparison.
- Parameters:
o – Other unit cell parameters.
- Returns:
True if all parameters match exactly.
-
inline bool operator!=(const UnitCellParameters &o) const¶
Inequality comparison.
- Parameters:
o – Other unit cell parameters.
- Returns:
True if any parameter differs.
-
inline bool approx(const UnitCellParameters &o, double epsilon) const¶
Approximate equality comparison.
- Parameters:
o – Other unit cell parameters.
epsilon – Tolerance for all differences.
- Returns:
True if all parameters differ by less than epsilon.
-
UnitCellParameters() = default¶
-
enum class Asu : unsigned char¶
Crystallographic symmetry operations, space groups, and reciprocal-space ASU.
This header provides core crystallographic symmetry data structures for macromolecular crystallography: symmetry operations (Op), groups of operations (GroupOps), space groups (SpaceGroup), and reciprocal-space asymmetric units (ReciprocalAsu). It also provides functions for parsing, converting, and querying these structures.
-
namespace gemmi
Enums
-
enum class CrystalSystem : unsigned char¶
Crystal system classification (one of the seven Bravais lattice families).
Values:
-
enumerator Triclinic¶
Triclinic (lowest symmetry)
-
enumerator Monoclinic¶
Monoclinic.
-
enumerator Orthorhombic¶
Orthorhombic.
-
enumerator Tetragonal¶
Tetragonal.
-
enumerator Trigonal¶
Trigonal (rhombohedral in rhombohedral axes)
-
enumerator Hexagonal¶
Hexagonal.
-
enumerator Cubic¶
Cubic (highest symmetry)
-
enumerator Triclinic¶
-
enum class PointGroup : unsigned char¶
Point group classification (32 crystallographic point groups).
Values:
-
enumerator C1¶
1 (identity only)
-
enumerator Ci¶
-1 (inversion)
-
enumerator C2¶
2
-
enumerator Cs¶
m
-
enumerator C2h¶
2/m
-
enumerator D2¶
222
-
enumerator C2v¶
mm2
-
enumerator D2h¶
mmm
-
enumerator C4¶
4
-
enumerator S4¶
-4
-
enumerator C4h¶
4/m
-
enumerator D4¶
422
-
enumerator C4v¶
4mm
-
enumerator D2d¶
-42m
-
enumerator D4h¶
4/mmm
-
enumerator C3¶
3
-
enumerator C3i¶
-3
-
enumerator D3¶
32
-
enumerator C3v¶
3m
-
enumerator D3d¶
-3m
-
enumerator C6¶
6
-
enumerator C3h¶
-6
-
enumerator C6h¶
6/m
-
enumerator D6¶
622
-
enumerator C6v¶
6mm
-
enumerator D3h¶
-62m
-
enumerator D6h¶
6/mmm
-
enumerator T¶
23
-
enumerator Th¶
m-3
-
enumerator O¶
432
-
enumerator Td¶
-43m
-
enumerator Oh¶
m-3m
-
enumerator C1¶
-
enum class Laue : unsigned char¶
Laue class (11 centrosymmetric point groups for diffraction).
Values:
-
enumerator L1¶
1 (triclinic)
-
enumerator L2m¶
2/m (monoclinic)
-
enumerator Lmmm¶
mmm (orthorhombic)
-
enumerator L4m¶
4/m (tetragonal)
-
enumerator L4mmm¶
4/mmm (tetragonal)
-
enumerator L3¶
-3 (trigonal)
-
enumerator L3m¶
-3m (trigonal)
-
enumerator L6m¶
6/m (hexagonal)
-
enumerator L6mmm¶
6/mmm (hexagonal)
-
enumerator Lm3¶
m-3 (cubic)
-
enumerator Lm3m¶
m-3m (cubic)
-
enumerator L1¶
Functions
-
inline bool operator==(const Op &a, const Op &b)¶
Equality comparison for operations (notation is ignored).
-
inline Op operator*(const Op &a, const Op &b)¶
Compose two symmetry operations: a * b applies b first, then a.
- Parameters:
a – First operation
b – Second operation
- Returns:
New operation representing composition, with wrapped translation
-
inline Op &operator*=(Op &a, const Op &b)¶
In-place composition operator.
- Parameters:
a – Operation to modify
b – Operation to apply
- Returns:
Reference to modified a
-
Op seitz_to_op(const std::array<std::array<double, 4>, 4> &t)¶
Convert a 4x4 Seitz matrix to an Op structure (inverse of Op::float_seitz()).
- Parameters:
t – 4x4 homogeneous transformation matrix
- Returns:
Equivalent Op with encoded rotation and translation (multiplied by DEN)
-
void append_op_fraction(std::string &s, int w)¶
Helper function to append a fractional value as a string.
- Parameters:
s – String to append to
w – Encoded value (numerator * DEN / denominator)
-
std::array<int, 4> parse_triplet_part(const std::string &s, char ¬ation, double *decimal_fract = nullptr)¶
Parse one component of a crystallographic triplet (e.g., “x+1/2” from “x+1/2,y,z”).
- Parameters:
s – String to parse
notation – Output parameter: ‘x’ for real-space, ‘h’ for reciprocal-space
decimal_fract – Optional output: decoded decimal fractional part
- Returns:
Array of 4 integers encoding [coeff_x, coeff_y, coeff_z, constant*DEN]
-
Op parse_triplet(const std::string &s, char notation = ' ')¶
Parse a crystallographic triplet string into an Op.
- Parameters:
s – Triplet string (e.g., “x+1/2,y,z” or “-h,-k,l”)
notation – Notation character: ‘x’ for real-space, ‘h’ for reciprocal-space, ‘ ‘ to auto-detect
- Returns:
Op representing the parsed transformation
-
inline std::vector<Op::Tran> centring_vectors(char centring_type)¶
Get centring (lattice) vectors for a given centring type.
- Parameters:
centring_type – Centring character: P, A, B, C, I, F, R, H, S, T
- Returns:
Vector of translation vectors (centering vectors). Corresponds to Table A1.4.2.2 in ITfC vol.B (edition 2010)
-
GroupOps generators_from_hall(const char *hall)¶
Generate symmetry operations from a Hall symbol string.
- Parameters:
hall – Hall symbol string (e.g., “P 1” or “P 2 2 21”)
- Returns:
GroupOps with generators only (not the complete group)
-
inline GroupOps symops_from_hall(const char *hall)¶
Get the complete group of symmetry operations from a Hall symbol.
- Parameters:
hall – Hall symbol string
- Returns:
GroupOps with all elements generated from the Hall symbol
-
inline const char *crystal_system_str(CrystalSystem system)¶
Convert crystal system enum to a string name.
- Parameters:
system – Crystal system to name
- Returns:
String: “triclinic”, “monoclinic”, “orthorhombic”, etc.
-
inline const char *point_group_hm(PointGroup pg)¶
Convert point group enum to Hermann-Mauguin notation string.
- Parameters:
pg – Point group to name
- Returns:
String in Hermann-Mauguin notation (e.g., “mmm”, “4/m”)
-
inline Laue pointgroup_to_laue(PointGroup pg)¶
Convert point group to its corresponding Laue class.
- Parameters:
pg – Point group
- Returns:
Associated Laue class
-
inline PointGroup laue_to_pointgroup(Laue laue)¶
Get the centrosymmetric point group corresponding to a Laue class.
- Parameters:
laue – Laue class
- Returns:
Point group with inversion center
-
inline const char *laue_class_str(Laue laue)¶
Get string representation of Laue class in Hermann-Mauguin notation.
- Parameters:
laue – Laue class
- Returns:
String representation
-
inline CrystalSystem crystal_system(Laue laue)¶
Get the crystal system for a given Laue class.
- Parameters:
laue – Laue class
- Returns:
Crystal system classification
-
inline CrystalSystem crystal_system(PointGroup pg)¶
Get the crystal system for a given point group.
- Parameters:
pg – Point group
- Returns:
Crystal system classification
-
inline unsigned char point_group_index_and_category(int space_group_number)¶
Get point group and symmetry category flags for a space group number.
- Parameters:
space_group_number – Space group number (1-230)
- Returns:
Low 5 bits: point group index; bits 5-7: flags (Sohncke, enantiomorphic, symmorphic)
-
inline PointGroup point_group(int space_group_number)¶
Get the point group for a space group.
- Parameters:
space_group_number – Space group number (1-230)
- Returns:
Point group of the space group
-
inline bool is_sohncke(int space_group_number)¶
Check if a space group is Sohncke (no enantiomorphic pairs).
- Parameters:
space_group_number – Space group number (1-230)
- Returns:
true for 65 Sohncke space groups
-
inline bool is_enantiomorphic(int space_group_number)¶
Check if a space group is enantiomorphic.
- Parameters:
space_group_number – Space group number (1-230)
- Returns:
true for 22 space groups (11 enantiomorphic pairs)
-
inline bool is_symmorphic(int space_group_number)¶
Check if a space group is symmorphic (no screw axes or glide planes).
- Parameters:
space_group_number – Space group number (1-230)
- Returns:
true for 73 symmorphic space groups
-
inline Op::Tran nonzero_inversion_center(int space_group_number)¶
Inversion center of the Euclidean normalizer that is not at the origin.
Returns (0,0,0) if absent. See ch. 3.5 of ITA (2016), column “Inversion through a centre at”.
- References
International Tables for Crystallography, Vol. A (2016), ch. 3.5. https://doi.org/10.1107/97809553602060000933
- Parameters:
space_group_number – Space group number (1–230).
- Returns:
Inversion centre translation, or (0,0,0) if none.
-
const char *get_basisop(int basisop_idx)¶
Get a basis operation (change-of-basis) string by index.
- Parameters:
basisop_idx – Index into basis operation table
- Returns:
Basis operation string in triplet notation, or nullptr if index is invalid
-
inline Op::Rot centred_to_primitive(char centring_type)¶
Compute a change-of-basis operator for centred-to-primitive transformation.
- Parameters:
centring_type – Bravais lattice type: ‘P’, ‘A’, ‘B’, ‘C’, ‘I’, ‘F’, ‘R’, ‘H’
- Returns:
3x3 matrix for centred-to-primitive basis change (same as inverse of z2p_op in sgtbx)
-
inline const SpaceGroup *find_spacegroup_by_number(int ccp4) noexcept¶
Find a space group by its CCP4 number.
- Parameters:
ccp4 – CCP4 space group number
- Returns:
Pointer to SpaceGroup if found, nullptr otherwise
-
inline const SpaceGroup &get_spacegroup_by_number(int ccp4)¶
Get a space group by CCP4 number (throws if not found).
- Parameters:
ccp4 – CCP4 space group number
- Throws:
std::invalid_argument – if space group not found
- Returns:
Reference to SpaceGroup
-
inline const SpaceGroup &get_spacegroup_reference_setting(int number)¶
Get the reference setting (basis operation 0) for an ITA space group number.
- Parameters:
number – ITA space group number (1-230)
- Throws:
std::invalid_argument – if space group number not found
- Returns:
Reference to SpaceGroup in reference setting
-
const SpaceGroup *find_spacegroup_by_name(std::string name, double alpha = 0., double gamma = 0., const char *prefer = nullptr)¶
Find a space group by its name (Hermann-Mauguin, Hall, or alternative).
Note
If angles alpha and gamma are provided, they help distinguish hexagonal/rhombohedral settings for trigonal space groups (e.g., “R 3” with different axis choices)
- Parameters:
name – Space group name to search for (case-insensitive variations accepted)
alpha – Optional: triclinic angle to distinguish H and R settings
gamma – Optional: triclinic angle to distinguish H and R settings
prefer – Optional: preference string like “1H” (1st setting, hexagonal) or “2R” (2nd setting, rhombohedral)
- Returns:
Pointer to SpaceGroup if found, nullptr otherwise
-
inline const SpaceGroup &get_spacegroup_by_name(const std::string &name)¶
Get a space group by name (throws if not found).
- Parameters:
name – Space group name
- Throws:
std::invalid_argument – if space group not found
- Returns:
Reference to SpaceGroup
-
inline const SpaceGroup &get_spacegroup_p1()¶
Get the P1 space group (trivial space group with identity only).
- Returns:
Reference to P1 space group (number 1)
-
inline const SpaceGroup *find_spacegroup_by_ops(const GroupOps &gops)¶
Find a space group matching a given set of symmetry operations.
- Parameters:
gops – Group of symmetry operations (rotation matrices and centring)
- Returns:
Pointer to matching SpaceGroup, or nullptr if no exact match found
-
struct GroupOps¶
- #include <gemmi/symmetry.hpp>
A crystallographic space group represented as generators and centring vectors.
GroupOps separates symmetry operations into two parts:
sym_ops: primitive symmetry operations (generators or full group) in the conventional cell
cen_ops: centring vectors (including the origin {0,0,0})
The complete set of symmetry operations is obtained by combining each sym_op with each cen_op. The first sym_op is always the identity; the first cen_op is always {0,0,0}.
Public Functions
-
inline int order() const¶
Return the total number of symmetry operations (|sym_ops| * |cen_ops|).
-
inline void add_missing_elements()¶
Generate all missing symmetry operations from the current generators using Dimino’s algorithm.
-
inline void add_missing_elements_part2(const std::vector<Op> &gen, size_t max_size, bool ignore_bad_gen)¶
Second part of group generation algorithm (used internally and by twin.hpp).
-
inline bool add_inversion()¶
Add inversion (point reflection) symmetry if not already present.
- Returns:
true if inversion was added, false if it was already present
-
inline char find_centering() const¶
Determine the Bravais lattice centring type from cen_ops.
- Returns:
Character: ‘P’ (primitive), ‘A’/’B’/’C’ (base-centered), ‘I’ (body-centered), ‘F’ (face-centered), ‘R’/’H’/’S’/’T’ (rhombohedral variants), or 0 if unknown
-
inline Op *find_by_rotation(const Op::Rot &r)¶
Find a symmetry operation by its rotation matrix.
- Parameters:
r – Rotation matrix to find
- Returns:
Pointer to the operation if found, nullptr otherwise
-
inline const Op *find_by_rotation(const Op::Rot &r) const¶
Find a symmetry operation by its rotation matrix (const version).
- Parameters:
r – Rotation matrix to find
- Returns:
Pointer to the operation if found, nullptr otherwise
-
inline bool is_centrosymmetric() const¶
Check if the space group is centrosymmetric (has an inversion center).
- Returns:
true if inversion (-I rotation) is present in sym_ops
-
inline bool is_reflection_centric(const Op::Miller &hkl) const¶
Check if a reflection plane maps hkl to -hkl (Miller index centric condition).
- Parameters:
hkl – Miller indices to check
- Returns:
true if some operation maps hkl to -hkl
-
inline int epsilon_factor_without_centering(const Op::Miller &hkl) const¶
Count operations that map hkl to itself (without considering centring).
- Parameters:
hkl – Miller indices
- Returns:
Number of sym_ops that fix hkl (multiplicity factor)
-
inline int epsilon_factor(const Op::Miller &hkl) const¶
Count all operations (including centring) that map hkl to itself.
- Parameters:
hkl – Miller indices
- Returns:
epsilon_factor_without_centering * |cen_ops|
-
inline bool is_systematically_absent(const Op::Miller &hkl) const¶
Check if a reflection is systematically absent due to centring or screw/glide.
- Parameters:
hkl – Miller indices
- Returns:
true if the reflection has a phase shift of π (destructive interference)
-
inline void change_basis_forward(const Op &cob)¶
Apply a forward change-of-basis transformation (P_new = cob * P_old * cob^-1).
- Parameters:
cob – Change-of-basis operation
-
inline void change_basis_backward(const Op &inv)¶
Apply a backward change-of-basis transformation.
- Parameters:
inv – Inverse change-of-basis operation
-
inline std::vector<Op> all_ops_sorted() const¶
Get all symmetry operations sorted.
- Returns:
Sorted vector combining all sym_ops with all cen_ops
-
inline Op get_op(int n) const¶
Get the n-th symmetry operation (combining sym_ops and cen_ops).
- Parameters:
n – Index (0-based)
- Returns:
sym_ops[n % |sym_ops|] combined with cen_ops[n / |sym_ops|]
-
inline bool is_same_as(const GroupOps &other) const¶
Check if two GroupOps represent the same group of operations.
- Parameters:
other – Other GroupOps to compare
- Returns:
true if all_ops_sorted() are identical
-
inline bool has_same_centring(const GroupOps &other) const¶
Check if two GroupOps have the same centring vectors.
- Parameters:
other – Other GroupOps to compare
- Returns:
true if cen_ops are the same (ignoring order)
-
inline bool has_same_rotations(const GroupOps &other) const¶
Check if two GroupOps have the same rotation parts (ignoring translations).
- Parameters:
other – Other GroupOps to compare
- Returns:
true if rotation matrices in sym_ops are the same (ignoring order)
-
inline std::array<int, 3> find_grid_factors() const¶
Compute minimal grid multiplicity in each direction for real-space sampling.
Note
Examples: {1,2,1} for P2_1, {1,1,6} for P6_1
- Returns:
Array [n_x, n_y, n_z] such that grid spacing <= 1/n in each direction
Check if two coordinate directions are related by some symmetry operation.
- Parameters:
u – First direction (0=x, 1=y, 2=z)
v – Second direction (0=x, 1=y, 2=z)
- Returns:
true if some operation maps direction u to direction v
Public Members
Public Static Functions
-
struct Op¶
- #include <gemmi/symmetry.hpp>
A crystallographic symmetry operation or change-of-basis transformation.
Encodes both a fractional rotation matrix and a fractional translation vector. Both are stored with a common denominator DEN=24 to handle fractions like 1/8 that appear in change-of-basis operations and advanced symmetry settings.
The encoding is: each matrix element m[i][j] and translation t[i] represents the rational number (element / DEN). For example, an element value of 24 represents 1.0, a value of 12 represents 0.5, and so on.
Real-space operations apply as: x’ = (rot * x + tran) / DEN. Reciprocal-space (Miller index) operations apply as: h’ = rot^T * h / DEN (note the transpose of the rotation matrix).
The notation field (‘x’ for real space, ‘h’ for reciprocal space, or ‘ ‘ for generic) distinguishes between coordinate transformations and Miller index transformations.
Public Types
Public Functions
-
inline bool is_hkl() const¶
Check if this operation is in reciprocal space (hkl).
- Returns:
true if notation == ‘h’, false otherwise
-
inline Op as_hkl() const¶
Return a copy of this operation with reciprocal-space (hkl) notation, clearing the translation.
-
inline Op as_xyz() const¶
Return a copy of this operation with real-space (xyz) notation, clearing the translation.
-
std::string triplet(char style = ' ') const¶
Generate a string representation of this operation in crystallographic triplet notation (e.g., “x,y,z”).
- Parameters:
style – Style character (optional) for output formatting
- Returns:
A string such as “x+1/2,y,z” or “-h,-k,l”
-
inline Op::Tran wrapped_tran() const¶
Wrap translation components into the range [0, DEN).
- Returns:
A translation vector with elements in [0, DEN), representing coordinates in [0, 1).
-
inline Op &wrap()¶
Normalize the translation to the range [0, DEN) (unit cell).
- Returns:
Reference to this operation for chaining
-
inline Op &translate(const Tran &a)¶
Add a translation vector to this operation’s translation component.
- Parameters:
a – Translation vector to add
- Returns:
Reference to this operation for chaining
-
inline Op translated(const Tran &a) const¶
Return a new operation with the given translation added.
- Parameters:
a – Translation vector to add
- Returns:
A new Op with modified translation
-
inline Op add_centering(const Tran &a) const¶
Add a centering vector and normalize to unit cell.
- Parameters:
a – Centering vector to add
- Returns:
A new Op with translation added and wrapped to [0, DEN)
-
inline Rot negated_rot() const¶
Return the negation of the rotation matrix (inversion).
- Returns:
A 3x3 matrix with all elements negated
-
inline Rot transposed_rot() const¶
Return the transpose of this operation’s rotation matrix.
- Returns:
Transposed rotation matrix
-
inline int det_rot() const¶
Compute the determinant of the rotation matrix.
- Returns:
DEN^3 (=13824) for proper rotations, -DEN^3 for rotoinversions, or 0 if singular
-
inline int rot_type() const¶
Determine the rotation type (identity, 2-fold, 3-fold, etc.).
- References
Grosse-Kunstleve, R.W. (1999). Algorithms for deriving crystallographic space-group information. Acta Cryst. A55, 383–395. https://doi.org/10.1107/S0108767398010186
- Returns:
Rotation type code (0 = none, 1 = 1-fold identity, 2 = 2-fold, 3 = 3-fold, 4 = 4-fold, 6 = 6-fold, -N for rotoinversion).
-
inline Op combine(const Op &b) const¶
Combine two symmetry operations: result = this * b (first apply b, then apply this).
Note
Does NOT wrap the translation to [0, DEN). Call wrap() on result if needed.
- Parameters:
b – The second operation to apply
- Returns:
New operation representing the combined transformation
-
inline std::array<double, 3> apply_to_xyz(const std::array<double, 3> &xyz) const¶
Apply this real-space operation to a Cartesian coordinate.
-
inline Miller apply_to_hkl_without_division(const Miller &hkl) const¶
Apply rotation to Miller indices without dividing by DEN.
Note
Applies the transpose of the rotation matrix (reciprocal-space convention)
- Parameters:
hkl – Miller indices
- Returns:
rot^T * hkl (in units of DEN; divide by DEN for actual result)
-
inline Miller apply_to_hkl(const Miller &hkl) const¶
Apply this operation to Miller indices.
- Parameters:
hkl – Miller indices [h, k, l]
- Returns:
Transformed Miller indices rot^T * hkl / DEN
-
inline double phase_shift(const Miller &hkl) const¶
Compute the phase shift caused by this operation’s translation component.
- Parameters:
hkl – Miller indices
- Returns:
Phase shift in radians: -2π * (h*t_x + k*t_y + l*t_z) / DEN
-
inline std::array<std::array<int, 4>, 4> int_seitz() const¶
Convert to a 4x4 integer Seitz matrix representation.
- Returns:
4x4 homogeneous transformation matrix (rotation|translation) / (0 0 0 | 1)
Public Members
-
Rot rot¶
3x3 rotation matrix with elements encoded as integers (divide by DEN for the actual value).
-
Tran tran¶
3D translation vector with elements encoded as integers (divide by DEN for the actual value).
-
char notation = ' '¶
Space notation: ‘x’ for real-space (xyz), ‘h’ for reciprocal-space (hkl), ‘ ‘ for generic.
Public Static Functions
-
static inline Rot transpose(const Rot &rot)¶
Compute the transpose of a rotation matrix.
- Parameters:
rot – Input rotation matrix
- Returns:
Transposed matrix
-
static inline Miller divide_hkl_by_DEN(const Miller &hkl)¶
Divide Miller indices by DEN (convert from encoded to actual values).
- Parameters:
hkl – Miller indices encoded with denominator DEN
- Returns:
hkl / DEN (integer division)
Public Static Attributes
-
static constexpr int DEN = 24¶
Denominator for rational fraction encoding. Set to 24 to handle 1/8.
-
inline bool is_hkl() const¶
-
struct ReciprocalAsu¶
- #include <gemmi/symmetry.hpp>
Reciprocal-space asymmetric unit (ASU) for a space group.
Defines a unique region in reciprocal space (h,k,l indices) such that all equivalent reflections related by symmetry are mapped to this region. This enables efficient data storage and comparison of diffraction data.
Supports 12 CCP4-standard ASU choices and TNT-specific variants (20 total).
Public Functions
-
inline ReciprocalAsu(const SpaceGroup *sg, bool tnt = false)¶
Construct a ReciprocalAsu from a space group.
- Parameters:
sg – Pointer to SpaceGroup (must not be nullptr)
tnt – If true, use TNT-specific ASU definitions instead of CCP4 standard
- Throws:
std::runtime_error – if sg is nullptr
-
inline bool is_in(const Op::Miller &hkl) const¶
Check if Miller indices are within the ASU.
- Parameters:
hkl – Miller indices (h, k, l)
- Returns:
true if hkl is in the asymmetric unit
-
inline bool is_in_reference_setting(int h, int k, int l) const¶
Check if Miller indices are in the ASU (assuming reference setting).
- Parameters:
h – h index
k – k index
l – l index
- Returns:
true if (h,k,l) is in the ASU definition for this idx
-
inline const char *condition_str() const¶
Get a human-readable string describing the ASU boundary condition.
- Returns:
Condition string like “h>=0 and k>=0 and l>=0”
-
inline std::pair<Op::Miller, int> to_asu(const Op::Miller &hkl, const std::vector<Op> &sym_ops) const¶
Map Miller indices to the ASU and return an MTZ ISYM identifier.
Note
ISYM = 2*n-1 for reflections in positive ASU (Friedel +), 2*n for negative ASU (Friedel -)
Note
ISYM ranges from 1 to 2*|sym_ops| depending on which symmetry operation maps hkl to ASU
- Parameters:
hkl – Miller indices
sym_ops – Array of symmetry operations to search
- Returns:
Pair: (equivalent hkl in ASU, MTZ ISYM code)
-
inline std::pair<Op::Miller, int> to_asu(const Op::Miller &hkl, const GroupOps &gops) const¶
Map Miller indices to the ASU using a GroupOps structure.
- Parameters:
hkl – Miller indices
gops – Group of symmetry operations
- Returns:
Pair: (equivalent hkl in ASU, MTZ ISYM code)
-
inline std::pair<Op::Miller, bool> to_asu_sign(const Op::Miller &hkl, const GroupOps &gops) const¶
Map Miller indices to the ASU and return a sign flag instead of ISYM.
Note
For centric reflections, always returns sign=true
- Parameters:
hkl – Miller indices
gops – Group of symmetry operations
- Returns:
Pair: (equivalent hkl in ASU, sign) where sign=true for positive/centric, false for negative Friedel pair
-
inline ReciprocalAsu(const SpaceGroup *sg, bool tnt = false)¶
-
struct SpaceGroup¶
- #include <gemmi/symmetry.hpp>
A crystallographic space group definition.
Stores the essential properties of a space group including its ITA number, Hermann-Mauguin symbol, Hall symbol, and basis operation (change-of-basis from reference setting). This structure is typically embedded in a static table.
Public Functions
-
inline std::string xhm() const¶
Get extended Hermann-Mauguin notation including extension.
- Returns:
String like “P 1 2 1” or “R 3:H”
-
inline char centring_type() const¶
Get the Bravais lattice type.
- Returns:
Character: ‘P’, ‘A’, ‘B’, ‘C’, ‘I’, ‘F’ for conventional, or ‘P’ for primitive rhombohedral
-
inline char ccp4_lattice_type() const¶
Get the lattice type used in CCP4 conventions.
- Returns:
Character: ‘H’ for hexagonal setting, otherwise first character of hm
-
inline std::string short_name() const¶
Get a short space group symbol without redundant axis labels.
- Returns:
String like “P2” (from “P 1 2 1”), “P112” (from “P 1 1 2”), or “H3” (from “R 3:H”)
-
inline std::string pdb_name() const¶
Get the PDB convention name for rhombohedral space groups.
Note
As explained in Phenix newsletter CCN_2011_01.pdf::page=12, PDB uses own symbols
- Returns:
String like “R3” or “R32” (non-standard PDB notation)
-
inline bool is_sohncke() const¶
Check if this space group is Sohncke (non-enantiomorphic).
-
inline bool is_enantiomorphic() const¶
Check if this space group is enantiomorphic.
-
inline bool is_symmorphic() const¶
Check if this space group is symmorphic.
-
inline PointGroup point_group() const¶
Get the point group of this space group.
-
inline const char *point_group_hm() const¶
Get the Hermann-Mauguin notation of the point group.
-
inline const char *laue_str() const¶
Get the Laue class as a string in Hermann-Mauguin notation.
-
inline CrystalSystem crystal_system() const¶
Get the crystal system.
-
inline const char *crystal_system_str() const¶
Get the crystal system as a string name.
-
inline bool is_centrosymmetric() const¶
Check if this space group is centrosymmetric (has an inversion center).
-
inline char monoclinic_unique_axis() const¶
Get the unique axis for monoclinic space groups.
- Returns:
‘a’, ‘b’, or ‘c’ for monoclinic; ‘\0’ for all other crystal systems
-
inline const char *basisop_str() const¶
Get the basis operation (change-of-basis) string.
- Returns:
Triplet notation string for the basis operation, or empty for reference setting
-
inline Op basisop() const¶
Parse the basis operation into an Op.
- Returns:
Op representing the change-of-basis from reference setting
-
inline bool is_reference_setting() const¶
Check if this is the reference setting.
- Returns:
true if basisop_idx == 0 (no basis operation needed)
-
inline Op centred_to_primitive() const¶
Get the change-of-basis operator from conventional to primitive cell.
- Returns:
Op for centred-to-primitive transformation
Public Members
-
int number¶
ITA (International Tables for Crystallography) space group number (1-230).
-
int ccp4¶
CCP4 space group number (may differ from ITA for some non-standard settings).
-
char hm[11]¶
Hermann-Mauguin (international) notation, e.g., “P 1 2 1” or “P 21 21 21”.
-
char ext¶
Extension character: ‘ ‘ (default), ‘R’ (rhombohedral), ‘H’ (hexagonal), etc.
-
char qualifier[5]¶
Qualifier string for distinguishing settings, e.g., “b” for monoclinic unique axis.
-
char hall[15]¶
Hall symbol string for generating symmetry operations.
-
int basisop_idx¶
Index into basis operation table for non-reference settings; 0 for reference setting.
-
inline std::string xhm() const¶
-
struct spacegroup_tables¶
- #include <gemmi/symmetry.hpp>
Static lookup tables for space groups and reciprocal-space ASU definitions.
Public Static Attributes
-
static const SpaceGroup main[564]¶
Array of 564 space group entries (multiple settings per ITA number)
-
static const SpaceGroupAltName alt_names[28]¶
Array of 28 alternative names for space group lookups.
-
static const unsigned char ccp4_hkl_asu[230]¶
CCP4 reciprocal-space ASU index for each of the 230 space groups.
-
static const SpaceGroup main[564]¶
-
struct SpaceGroupAltName¶
- #include <gemmi/symmetry.hpp>
Alternative name for a space group (for lookups).
-
enum class CrystalSystem : unsigned char¶
-
namespace std¶
Metadata structures from coordinate files (PDB/mmCIF).
Provides data structures for PDB metadata including experiment information, refinement statistics, assembly generation, and structural annotations.
-
namespace gemmi
Enums
-
enum class EntityType : unsigned char¶
Classification of macromolecular entities, corresponding to mmCIF _entity.type.
Classifies biological units by macromolecular type.
Values:
-
enumerator Unknown¶
Type not specified or cannot be determined.
-
enumerator Polymer¶
Protein, nucleic acid, or polysaccharide.
-
enumerator NonPolymer¶
Small organic or inorganic molecule.
-
enumerator Branched¶
Branched polymer (introduced in mmCIF 2020)
-
enumerator Water¶
Water, heavy water, or aqueous solvent.
-
enumerator Unknown¶
-
enum class PolymerType : unsigned char¶
Polymer classification by chemical type.
Corresponds to mmCIF _entity_poly.type. Numbers in comments indicate approximate counts in PDB as of 2017-2020.
Values:
-
enumerator Unknown¶
Unknown polymer type or not applicable (~0)
-
enumerator PeptideL¶
L-amino acid polymer polypeptide(L) (~168k entries)
-
enumerator PeptideD¶
D-amino acid polymer polypeptide(D) (~57 entries)
-
enumerator Dna¶
DNA polydeoxyribonucleotide (~9.9k entries)
-
enumerator Rna¶
RNA polyribonucleotide (~4.6k entries)
-
enumerator DnaRnaHybrid¶
DNA-RNA hybrid (~156 entries)
-
enumerator SaccharideD¶
D-polysaccharide (~18 entries)
-
enumerator SaccharideL¶
L-polysaccharide (~0 entries)
-
enumerator Pna¶
Peptide nucleic acid (~2 entries)
-
enumerator CyclicPseudoPeptide¶
Cyclic pseudo-peptide (~1 entry)
-
enumerator Other¶
Other polymer types (~4 entries)
-
enumerator Unknown¶
Functions
-
inline bool is_polypeptide(PolymerType pt)¶
Check if polymer is a polypeptide (L or D form).
-
inline bool is_polynucleotide(PolymerType pt)¶
Check if polymer is a nucleic acid (DNA, RNA, or hybrid).
-
struct Assembly¶
- #include <gemmi/metadata.hpp>
Biological assembly (macromolecular complex).
Corresponds to PDB REMARK 350 or mmCIF _pdbx_struct_assembly. Describes how asymmetric unit chains are assembled into biologically relevant oligomers.
Public Types
-
enum class SpecialKind : unsigned char¶
Special symmetry classification for NCS/point groups.
Values:
-
enumerator NA¶
No special symmetry (generic assembly)
-
enumerator CompleteIcosahedral¶
Complete icosahedral (60 copies)
-
enumerator RepresentativeHelical¶
Representative helix (not complete)
-
enumerator CompletePoint¶
Complete point group assembly.
-
enumerator NA¶
Public Functions
-
Assembly() = default¶
Public Members
-
bool author_determined = false¶
True if determined by structure authors.
-
bool software_determined = false¶
True if determined computationally.
-
SpecialKind special_kind = SpecialKind::NA¶
Special symmetry type.
-
int oligomeric_count = 0¶
Stoichiometry (copies in assembly)
-
double absa = NAN¶
Buried surface area (Ų)
-
double ssa = NAN¶
Surface area of complex (Ų)
-
double more = NAN¶
Solvent free energy change (kcal/mol)
-
struct Gen¶
- #include <gemmi/metadata.hpp>
Generation rule combining chains with operators.
-
struct Operator¶
- #include <gemmi/metadata.hpp>
Rotation/translation operator for assembly generation.
-
enum class SpecialKind : unsigned char¶
-
struct BasicRefinementInfo¶
- #include <gemmi/metadata.hpp>
Refinement statistics for a resolution shell or overall data.
Statistics are reported either as overall values (in RefinementInfo) or per-resolution-shell (in RefinementInfo::bins). Corresponds to mmCIF _refine and _refine_ls_shell categories; also to PDB REMARK 3.
Subclassed by gemmi::RefinementInfo
Public Members
-
double resolution_high = NAN¶
Highest resolution in shell (Ångströms)
-
double resolution_low = NAN¶
Lowest resolution in shell (Ångströms)
-
double completeness = NAN¶
Fraction of unique reflections used (%)
-
int reflection_count = -1¶
Total reflections observed.
-
int work_set_count = -1¶
Reflections in work set (used in refinement)
-
int rfree_set_count = -1¶
Reflections in test set (R_free calculation)
-
double r_all = NAN¶
R-factor for all reflections.
-
double r_work = NAN¶
R-factor for work set: Σ|F_o - F_c| / Σ|F_o|.
-
double r_free = NAN¶
R-factor for test set (cross-validation)
-
double cc_fo_fc_work = NAN¶
Correlation coefficient (F_obs vs F_calc) for work.
-
double cc_fo_fc_free = NAN¶
Correlation coefficient for test set.
-
double fsc_work = NAN¶
Fourier Shell Correlation (cryo-EM) for work set.
-
double fsc_free = NAN¶
Fourier Shell Correlation for test set.
-
double cc_intensity_work = NAN¶
Correlation of intensities for work set.
-
double cc_intensity_free = NAN¶
Correlation of intensities for test set.
-
double resolution_high = NAN¶
-
struct CisPep¶
- #include <gemmi/metadata.hpp>
Cis peptide bond annotation.
Corresponds to PDB CISPEP record or mmCIF _struct_mon_prot_cis.
Public Members
-
AtomAddress partner_c¶
C-terminal carbonyl carbon.
-
AtomAddress partner_n¶
N-terminal amide nitrogen.
-
int model_num = 0¶
Model number (if per-model specificity)
-
char only_altloc = '\0'¶
Alternate location (if specific conformation)
-
double reported_angle = NAN¶
Omega dihedral angle (degrees)
-
AtomAddress partner_c¶
-
struct Connection¶
- #include <gemmi/metadata.hpp>
A chemical connection (bond) between two atoms in the structure.
Corresponds to mmCIF _struct_conn records. The type field indicates the nature of the bond (covalent, hydrogen, metal coordination, etc.).
Public Types
Public Members
-
std::string name¶
Connection identifier.
-
AtomAddress partner1¶
-
AtomAddress partner2¶
Two atoms in the connection.
-
double reported_distance = 0.0¶
Distance from coordinate file (Ångströms)
-
short reported_sym[4] = {}¶
Symmetry operator (for internal use, unreliable)
-
std::string name¶
-
struct CrystalInfo¶
- #include <gemmi/metadata.hpp>
Crystal growth conditions and associated diffraction data.
Corresponds to mmCIF _exptl_crystal and _exptl_crystal_grow categories.
Public Members
-
double ph = NAN¶
pH of crystallization condition
-
std::vector<DiffractionInfo> diffractions¶
Diffraction data from this crystal.
-
double ph = NAN¶
-
struct DiffractionInfo¶
- #include <gemmi/metadata.hpp>
Details of radiation source and detector configuration.
Corresponds to mmCIF _diffrn_source and _diffrn_radiation categories.
-
struct Entity¶
- #include <gemmi/metadata.hpp>
Description of a macromolecular entity in the structure.
Corresponds to mmCIF _entity category. Contains polymer type, database cross-references, and sequence information.
Public Functions
-
Entity() = default¶
Public Members
-
EntityType entity_type = EntityType::Unknown¶
Macromolecular type.
-
PolymerType polymer_type = PolymerType::Unknown¶
Polymer classification.
-
bool reflects_microhetero = false¶
True if sequence reflects microheterogeneity.
Public Static Functions
-
struct DbRef¶
- #include <gemmi/metadata.hpp>
Cross-reference to external database (UniProt, GenBank, etc.).
Public Members
-
SeqId::OptionalNum label_seq_begin¶
-
SeqId::OptionalNum label_seq_end¶
mmCIF label_seq_id range
-
SeqId::OptionalNum label_seq_begin¶
-
Entity() = default¶
-
struct ExperimentInfo¶
- #include <gemmi/metadata.hpp>
Experimental setup and data collection method.
Corresponds to mmCIF _exptl category. Each entry usually contains one experiment, except in joint refinement (e.g., X-ray + neutron).
Public Members
-
int number_of_crystals = -1¶
Number of crystals used in data collection.
-
int unique_reflections = -1¶
Count of unique reflections measured.
-
ReflectionsInfo reflections¶
Overall statistics for all reflections.
-
double b_wilson = NAN¶
Wilson B-factor estimate (Ų)
-
std::vector<ReflectionsInfo> shells¶
Per-resolution-shell statistics.
-
int number_of_crystals = -1¶
-
struct Helix¶
- #include <gemmi/metadata.hpp>
Protein secondary structure: alpha helix or similar.
Corresponds to PDB HELIX record or mmCIF _struct_conf category. As of 2019, almost exclusively right-handed alpha helix (type 1) or 3-10 helix (type 5) in the PDB (~99% of ~4M helix annotations).
Public Types
-
enum HelixClass¶
Helix type classification from PDB HELIX records.
Values:
-
enumerator UnknownHelix¶
Unspecified helix type.
-
enumerator RAlpha¶
Right-handed alpha helix (~3.6 res/turn)
-
enumerator ROmega¶
Right-handed omega helix (rare)
-
enumerator RPi¶
Right-handed pi helix (rare)
-
enumerator RGamma¶
Right-handed gamma helix (rare)
-
enumerator R310¶
Right-handed 3-10 helix (~3 res/turn)
-
enumerator LAlpha¶
Left-handed alpha helix (rare)
-
enumerator LOmega¶
Left-handed omega helix (rare)
-
enumerator LGamma¶
Left-handed gamma helix (rare)
-
enumerator Helix27¶
2-7 ribbon/helix (rare)
-
enumerator HelixPolyProlineNone¶
Polyproline helix (rare)
-
enumerator UnknownHelix¶
Public Functions
-
inline void set_helix_class_as_int(int n)¶
Set helix class from integer code (1-10).
Public Members
-
AtomAddress start¶
First residue of helix.
-
AtomAddress end¶
Last residue of helix.
-
HelixClass pdb_helix_class = UnknownHelix¶
Helix type.
-
int length = -1¶
Number of residues in helix.
-
enum HelixClass¶
-
struct Metadata¶
- #include <gemmi/metadata.hpp>
Complete metadata from a coordinate file.
Aggregates all experimental, refinement, and assembly information from PDB/mmCIF header and remarks. Extracted from multiple mmCIF categories and PDB REMARK records.
Public Functions
-
inline bool has(double RefinementInfo::* field) const¶
Check if any refinement entry has a non-NaN value for field.
- Parameters:
field – Pointer-to-member for a double field in RefinementInfo.
- Returns:
True if any refinement entry has a non-NaN value.
-
inline bool has(int RefinementInfo::* field) const¶
Check if any refinement entry has a non-(-1) value for field.
- Parameters:
field – Pointer-to-member for an int field in RefinementInfo.
- Returns:
True if any refinement entry has a value != -1.
-
inline bool has(std::string RefinementInfo::* field) const¶
Check if any refinement entry has a non-empty string value for field.
- Parameters:
field – Pointer-to-member for a std::string field in RefinementInfo.
- Returns:
True if any refinement entry has non-empty string.
-
inline bool has(SMat33<double> RefinementInfo::* field) const¶
Check if any refinement entry has a non-NaN value in matrix field.
- Parameters:
field – Pointer-to-member for SMat33<double> field in RefinementInfo.
- Returns:
True if any refinement entry has u11 != NaN.
-
inline bool has_restr() const¶
Check if any refinement entry has restraint statistics.
- Returns:
True if any refinement contains non-empty restr_stats.
-
inline std::vector<gemmi::TlsGroup> *get_tls_groups()¶
Get TLS groups from refinement entries.
- Returns:
Pointer to TLS group vector from first refinement with groups, or nullptr if none found. In joint refinement, TLS groups should be associated with only one RefinementInfo entry.
Public Members
-
std::vector<ExperimentInfo> experiments¶
Experimental setup (X-ray, cryo-EM, etc.)
-
std::vector<CrystalInfo> crystals¶
Crystal and diffraction information.
-
std::vector<RefinementInfo> refinement¶
Refinement statistics and quality metrics.
-
std::vector<SoftwareItem> software¶
Software used in data processing/refinement.
-
inline bool has(double RefinementInfo::* field) const¶
-
struct ModRes¶
- #include <gemmi/metadata.hpp>
Modified residue annotation.
Records post-translational or in-situ modifications. Corresponds to PDB MODRES record or mmCIF _pdbx_mod_residue_detail.
-
struct RefinementInfo : public gemmi::BasicRefinementInfo¶
- #include <gemmi/metadata.hpp>
Complete refinement statistics and model quality assessment.
Corresponds to PDB REMARK 3 and mmCIF _refine, _refine_ls_shell, _refine_ls_restr, and _pdbx_refine_tls categories.
Public Members
-
int bin_count = -1¶
Total number of resolution shells.
-
std::vector<BasicRefinementInfo> bins¶
Per-resolution-shell statistics.
-
double mean_b = NAN¶
Mean B-factor of all atoms (Ų)
-
double luzzati_error = NAN¶
Luzzati coordinate error estimate (Å)
-
double dpi_blow_r = NAN¶
DPI (Blow) uncertainty for R-factor.
-
double dpi_blow_rfree = NAN¶
DPI (Blow) uncertainty for R-free.
-
double dpi_cruickshank_r = NAN¶
DPI (Cruickshank) uncertainty for R.
-
double dpi_cruickshank_rfree = NAN¶
DPI (Cruickshank) uncertainty for R-free.
-
int bin_count = -1¶
-
struct ReflectionsInfo¶
- #include <gemmi/metadata.hpp>
Statistics for reflection data from a single diffraction set or shell.
Information from PDB REMARK 200/230 expanded in PDBx/mmCIF. Corresponds to data across mmCIF _reflns and _reflns_shell categories.
Public Members
-
double resolution_high = NAN¶
Highest resolution limit (Ångströms)
-
double resolution_low = NAN¶
Lowest resolution limit (Ångströms)
-
double completeness = NAN¶
Fraction of unique reflections measured (%)
-
double redundancy = NAN¶
Average multiplicity of measurements.
-
double r_merge = NAN¶
R_merge = Σ|I - | / Σ
-
double r_sym = NAN¶
R_sym (Rsym) intensity agreement statistic.
-
double mean_I_over_sigma = NAN¶
Average intensity / standard deviation.
-
double resolution_high = NAN¶
-
struct Sheet¶
- #include <gemmi/metadata.hpp>
Beta sheet secondary structure.
Corresponds to PDB SHEET record or mmCIF _struct_sheet category.
Public Functions
-
Sheet() = default¶
Public Members
-
struct Strand¶
- #include <gemmi/metadata.hpp>
Individual beta strand in a sheet.
Public Members
-
AtomAddress start¶
First residue of strand.
-
AtomAddress end¶
Last residue of strand.
-
AtomAddress hbond_atom2¶
H-bond donor atom (previous strand)
-
AtomAddress hbond_atom1¶
H-bond acceptor atom (current strand)
-
int sense¶
0=first strand, 1=parallel, -1=anti-parallel
-
AtomAddress start¶
-
Sheet() = default¶
-
struct SiftsUnpResidue¶
- #include <gemmi/metadata.hpp>
Reference to a UniProt residue via SIFTS mapping.
Maps PDB residue to UniProt sequence. Used in Residue::sifts_unp. Corresponds to mmCIF _pdbx_sifts_xref_db category.
-
struct SoftwareItem¶
- #include <gemmi/metadata.hpp>
Software used in data collection, processing, or refinement.
Corresponds to the mmCIF _software category. Includes tools from any stage of data processing or structure determination pipeline.
Public Types
-
enum Classification¶
Classification of software function in the pipeline.
Values:
-
enumerator DataCollection¶
Used for X-ray/neutron/cryo-EM data acquisition.
-
enumerator DataExtraction¶
Extracted raw data into processable format.
-
enumerator DataProcessing¶
General data processing (merging, scaling, etc.)
-
enumerator DataReduction¶
Reduced data complexity or dimensionality.
-
enumerator ModelBuilding¶
Model construction and atom placement.
-
enumerator Phasing¶
Phasing (MAD, MR, direct methods, etc.)
-
enumerator Refinement¶
Structure refinement.
-
enumerator Unspecified¶
Purpose not classified.
-
enumerator DataCollection¶
Public Members
-
Classification classification = Unspecified¶
Functional classification.
-
enum Classification¶
-
struct StructSite¶
- #include <gemmi/metadata.hpp>
Binding, catalytic, or functional site annotation.
Corresponds to PDB SITE record or mmCIF _struct_site category. Annotates regions important for function.
Public Functions
-
StructSite() = default¶
Public Members
-
AtomAddress residue¶
Representative residue.
-
int residue_count = -1¶
Total residues in site.
-
struct Member¶
- #include <gemmi/metadata.hpp>
Residue or atom participating in the site.
Public Members
-
int residue_num = -1¶
Residue count in site.
-
SeqId::OptionalNum label_seq¶
mmCIF sequence number
-
char label_alt_id = '\0'¶
Alternate location code.
-
AtomAddress auth¶
PDB-style atom address.
-
int residue_num = -1¶
-
StructSite() = default¶
-
struct TlsGroup¶
- #include <gemmi/metadata.hpp>
TLS (Translation/Libration/Screw) group for rigid-body refinement.
Corresponds to mmCIF _pdbx_refine_tls category. Used to model anisotropic motion of rigid domains in structure refinement.
Public Members
-
short num_id = -1¶
Numeric TLS group ID (internal optimization)
-
struct Selection¶
- #include <gemmi/metadata.hpp>
Residue selection for TLS group.
-
short num_id = -1¶
-
enum class EntityType : unsigned char¶
Periodic table elements and chemical properties.
Provides element enumeration (El), atomic properties (weight, radii), and the Element class for convenient element access and lookup.
-
namespace gemmi
-
Enums
-
enum class El : unsigned char¶
Element enumeration by atomic number.
Values correspond to atomic numbers (H=1, He=2, …, Og=118) with sentinel values X (unknown, 0) and D (deuterium, 119) and END (sentinel for array bounds, 120).
Values:
-
enumerator X¶
Unknown element (used for unrecognized atoms in PDB)
-
enumerator H¶
-
enumerator He¶
-
enumerator Li¶
-
enumerator Be¶
-
enumerator B¶
-
enumerator C¶
-
enumerator N¶
-
enumerator O¶
-
enumerator F¶
-
enumerator Ne¶
-
enumerator Na¶
-
enumerator Mg¶
-
enumerator Al¶
-
enumerator Si¶
-
enumerator P¶
-
enumerator S¶
-
enumerator Cl¶
-
enumerator Ar¶
Periods 1-3.
-
enumerator K¶
-
enumerator Ca¶
-
enumerator Sc¶
-
enumerator Ti¶
-
enumerator V¶
-
enumerator Cr¶
-
enumerator Mn¶
-
enumerator Fe¶
-
enumerator Co¶
-
enumerator Ni¶
-
enumerator Cu¶
-
enumerator Zn¶
-
enumerator Ga¶
-
enumerator Ge¶
-
enumerator As¶
-
enumerator Se¶
-
enumerator Br¶
-
enumerator Kr¶
Period 4.
-
enumerator Rb¶
-
enumerator Sr¶
-
enumerator Y¶
-
enumerator Zr¶
-
enumerator Nb¶
-
enumerator Mo¶
-
enumerator Tc¶
-
enumerator Ru¶
-
enumerator Rh¶
-
enumerator Pd¶
-
enumerator Ag¶
-
enumerator Cd¶
-
enumerator In¶
-
enumerator Sn¶
-
enumerator Sb¶
-
enumerator Te¶
-
enumerator I¶
-
enumerator Xe¶
Period 5.
-
enumerator Cs¶
-
enumerator Ba¶
-
enumerator La¶
-
enumerator Ce¶
-
enumerator Pr¶
-
enumerator Nd¶
-
enumerator Pm¶
-
enumerator Sm¶
-
enumerator Eu¶
-
enumerator Gd¶
-
enumerator Tb¶
-
enumerator Dy¶
-
enumerator Ho¶
-
enumerator Er¶
-
enumerator Tm¶
-
enumerator Yb¶
-
enumerator Lu¶
Period 6..
-
enumerator Hf¶
-
enumerator Ta¶
-
enumerator W¶
-
enumerator Re¶
-
enumerator Os¶
-
enumerator Ir¶
-
enumerator Pt¶
-
enumerator Au¶
-
enumerator Hg¶
-
enumerator Tl¶
-
enumerator Pb¶
-
enumerator Bi¶
-
enumerator Po¶
-
enumerator At¶
-
enumerator Rn¶
..Period 6
-
enumerator Fr¶
-
enumerator Ra¶
-
enumerator Ac¶
-
enumerator Th¶
-
enumerator Pa¶
-
enumerator U¶
-
enumerator Np¶
-
enumerator Pu¶
-
enumerator Am¶
-
enumerator Cm¶
-
enumerator Bk¶
-
enumerator Cf¶
-
enumerator Es¶
-
enumerator Fm¶
-
enumerator Md¶
-
enumerator No¶
-
enumerator Lr¶
Period 7..
-
enumerator Rf¶
-
enumerator Db¶
-
enumerator Sg¶
-
enumerator Bh¶
-
enumerator Hs¶
-
enumerator Mt¶
-
enumerator Ds¶
-
enumerator Rg¶
-
enumerator Cn¶
-
enumerator Nh¶
-
enumerator Fl¶
-
enumerator Mc¶
-
enumerator Lv¶
-
enumerator Ts¶
-
enumerator Og¶
..Period 7
-
enumerator D¶
Deuterium (isotope of hydrogen, treated separately)
-
enumerator END¶
Sentinel: one past last element.
-
enumerator X¶
Functions
-
inline std::int8_t element_row(El el)¶
Get periodic table period (row) of element.
- Parameters:
el – Element enumeration value.
- Returns:
Period number (1-7) or 0 for unknown/sentinel elements.
-
inline std::int8_t element_group(El el)¶
Get periodic table group (column) of element.
Lanthanides (57-71) and actinides (89-103) are assigned to group 3.
- Parameters:
el – Element enumeration value.
- Returns:
Group number (1-18) or 0 for unknown/sentinel elements.
-
inline bool &is_metal_value(El el)¶
Check if element is classified as a metal.
Uses a classification where Ge and Sb are considered metals; some transition metals have unusual definitions for consistency. This is a mutable reference to allow runtime customization.
- Parameters:
el – Element enumeration value.
- Returns:
True if element is a metal; false otherwise.
-
inline void set_is_metal(El el, bool v)¶
Modify metal classification at runtime.
- Parameters:
el – Element to reclassify.
v – True to mark as metal; false to mark as non-metal.
-
constexpr bool ce_almost_eq(double x, double y)¶
Helper function for near-equal double comparisons.
-
inline double molecular_weight(El el)¶
Get standard atomic weight (mass number) of element.
Returns 1.0 for unknown element X. Deuterium (D) returns 2.0141.
- Parameters:
el – Element enumeration value.
- Returns:
Atomic weight in unified atomic mass units (u).
-
inline float covalent_radius(El el)¶
Get covalent radius of element.
Data from Cordero et al (2008). “Covalent radii revisited”. Dalton Trans. 21, 2832. https://en.wikipedia.org/wiki/Covalent_radius
- Parameters:
el – Element enumeration value.
- Returns:
Covalent radius in Ångströms.
-
inline float vdw_radius(El el)¶
Get van der Waals radius of element.
Data supplemented with cctbx values.
Bondi, A. (1964). van der Waals Volumes and Radii. J. Phys. Chem. 68, 441–451.
https://doi.org/10.1021/j100785a001- References
Mantina, M., Chamberlin, A.C., Valero, R., Cramer, C.J. & Truhlar, D.G. (2009). Consistent van der Waals radii for the whole main group. J. Phys. Chem. A 113, 5806–5812. https://doi.org/10.1021/jp8111556
- Parameters:
el – Element enumeration value.
- Returns:
Van der Waals radius in Ångströms.
-
inline const char *element_name(El el)¶
Get element symbol in standard case (e.g., “Mg”).
Returns “X” for unknown element, “” for END sentinel.
- Parameters:
el – Element enumeration value.
- Returns:
Pointer to 2-character (plus NUL) element symbol.
-
inline elname_t &element_uppercase_name(El el)¶
Get element symbol in uppercase (e.g., “MG”).
- Parameters:
el – Element enumeration value.
- Returns:
Reference to 2-character uppercase element symbol.
-
struct Element¶
- #include <gemmi/elem.hpp>
Convenient wrapper for element properties and operations.
Provides multiple constructors for flexibility and aggregates element queries (weight, radii, metal classification, etc.).
Public Functions
-
inline explicit Element(const char *str) noexcept¶
Construct from element symbol string.
-
inline explicit Element(int number) noexcept¶
Construct from atomic number (1-118).
- Parameters:
number – Atomic number; 0 or out-of-range returns El::X.
-
inline int ordinal() const¶
Get enumeration ordinal (0-120).
- Returns:
Integer value of elem (includes X=0, D=119, END=120).
-
inline int atomic_number() const¶
Get atomic number (1-118).
- Returns:
Atomic number; deuterium (D) returns 1 (H’s atomic number).
-
inline bool is_hydrogen() const¶
Check if element is hydrogen or deuterium.
-
inline double weight() const¶
Get standard atomic weight.
- Returns:
Weight in atomic mass units (u).
-
inline float covalent_r() const¶
Get covalent radius.
- Returns:
Radius in Ångströms.
-
inline float vdw_r() const¶
Get van der Waals radius.
- Returns:
Radius in Ångströms.
-
inline bool is_metal() const¶
Check if element is classified as a metal.
-
inline bool is_halogen() const¶
Check if element is in Group 17 (halogens).
-
inline bool is_chalcogen() const¶
Check if element is in Group 16 (chalcogens: O, S, Se, Te, Po).
-
inline const char *name() const¶
Get element symbol with standard case (e.g., “Mg”).
- Returns:
Pointer to 2-character NUL-terminated string.
-
inline const char *uname() const¶
Get element symbol in uppercase (e.g., “MG”).
- Returns:
Reference to 2-character uppercase symbol.
-
inline explicit Element(const char *str) noexcept¶
-
namespace impl
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
-
enum class El : unsigned char¶
Sequence/residue identifiers including insertion codes.
Provides SeqId (sequence number + insertion code), ResidueId (with segment), and AtomAddress (chain + residue + atom) for unambiguous atom/residue reference.
-
namespace gemmi
Functions
-
inline std::string atom_str(const std::string &chain_name, const ResidueId &res_id, const std::string &atom_name, char altloc, bool as_cid = false)¶
Format atom address as string.
- Parameters:
chain_name – Chain identifier.
res_id – Residue identifier (number, insertion code, name, segment).
atom_name – Atom name (e.g., “CA”, “CB”).
altloc – Alternate location code (‘\0’ = no alternate).
as_cid – If true, format as mmCIF CID (// prefix, dot before icode). If false, format as PDB style.
- Returns:
String representation of atom location (e.g., “A/ALA 12/CA” or “//A/12/CA”).
-
struct AtomAddress¶
- #include <gemmi/seqid.hpp>
Complete atom address: chain + residue + atom + alternate location.
Fully specifies an atom in the structure (including alternate conformations if altloc is set). Corresponds to an atom record in PDB/mmCIF.
Public Functions
-
AtomAddress() = default¶
-
inline AtomAddress(const std::string &ch, const ResidueId &resid, const std::string &atom, char alt = '\0')¶
Construct from chain, residue ID, and atom name.
- Parameters:
ch – Chain name.
resid – Complete residue identifier.
atom – Atom name.
alt – Alternate location (‘\0’ = main).
-
inline AtomAddress(const std::string &ch, const SeqId &seqid, const std::string &res, const std::string &atom, char alt = '\0')¶
Construct from chain, sequence ID, residue name, and atom name.
- Parameters:
ch – Chain name.
seqid – Sequence ID (number + insertion code).
res – Residue name (3-letter code).
atom – Atom name.
alt – Alternate location (‘\0’ = main).
-
inline bool operator==(const AtomAddress &o) const¶
Equality comparison (chain, residue, atom, and altloc).
-
AtomAddress() = default¶
-
template<int N>
struct OptionalInt¶ - #include <gemmi/seqid.hpp>
Optional integer with a sentinel “not-set” value.
Provides None enum value and has_value() check analogous to std::optional.
- Template Parameters:
N – Sentinel value indicating “not set” state.
Public Functions
-
OptionalInt() = default¶
-
inline OptionalInt(int n)¶
Construct with integer value.
-
inline bool has_value() const¶
Check if value is set (not sentinel).
-
inline std::string str(char null = '?') const¶
Convert to string, or fallback character if not set.
- Parameters:
null – Fallback character when value is not set (default ‘?’).
- Returns:
String representation of integer or single fallback character.
-
inline OptionalInt &operator=(int n)¶
-
inline bool operator==(const OptionalInt &o) const¶
-
inline bool operator!=(const OptionalInt &o) const¶
-
inline bool operator<(const OptionalInt &o) const¶
Less-than comparison (both values must be set).
-
inline bool operator==(int n) const¶
-
inline bool operator!=(int n) const¶
-
inline OptionalInt operator+(OptionalInt o) const¶
Add two OptionalInt values (propagates “not set” state).
-
inline OptionalInt operator-(OptionalInt o) const¶
Subtract two OptionalInt values (propagates “not set” state).
-
inline OptionalInt &operator+=(int n)¶
-
inline OptionalInt &operator-=(int n)¶
-
inline explicit operator int() const¶
-
inline explicit operator bool() const¶
Check if value is set (true if has_value()).
-
inline int &operator*()¶
Dereference to stored value.
-
inline const int &operator*() const¶
Const dereference.
-
inline int &emplace(int n)¶
Set value and return reference.
-
inline void reset() noexcept¶
Set to not-set state.
Public Members
-
int value = None¶
Stored integer or sentinel.
-
struct ResidueId¶
- #include <gemmi/seqid.hpp>
Complete residue identifier: sequence ID + segment + residue name.
Uniquely identifies a residue within a chain. Includes segment ID (segid) from PDB format for structures with multiple segments.
Subclassed by gemmi::Residue
Public Functions
-
inline SeqId group_key() const¶
Get grouping key for iterator operations.
- Returns:
SeqId for use in grouping/comparison operations.
-
inline bool matches(const ResidueId &o) const¶
Full equality: seqid, segment, and name all match.
- Parameters:
o – ResidueId to compare with.
- Returns:
True if all three fields match exactly.
-
inline SeqId group_key() const¶
-
struct SeqId¶
- #include <gemmi/seqid.hpp>
Residue sequence identifier: sequence number plus insertion code.
Corresponds to the combination of _atom_site.auth_seq_id (num) and _atom_site.pdbx_PDB_ins_code (icode) in mmCIF, or RESSEQ + ICODE in PDB format.
Public Types
-
using OptionalNum = OptionalInt<INT_MIN>¶
Optional sequence number (INT_MIN = not set)
Public Functions
-
SeqId() = default¶
-
inline SeqId(int num_, char icode_)¶
Construct with sequence number and insertion code.
- Parameters:
num_ – Sequence number (0 is valid; unset via OptionalNum).
icode_ – Insertion code (’ ‘ for none, typically ‘A’-‘Z’).
-
inline SeqId(OptionalNum num_, char icode_)¶
Construct with OptionalNum and insertion code.
-
inline explicit SeqId(const std::string &str)¶
Parse SeqId from string (e.g., “12”, “12A”, “12b”).
- Parameters:
str – String containing sequence number and optional insertion code.
- Throws:
std::invalid_argument – if string is malformed.
-
inline bool operator==(const SeqId &o) const¶
Equality comparison (case-insensitive insertion code).
Two SeqIds are equal if num equals and insertion codes match (ignoring case). Space equals space, ‘a’ equals ‘A’, etc.
-
inline bool operator<(const SeqId &o) const¶
Less-than ordering by (num, icode).
Orders first by sequence number, then by insertion code.
-
inline char has_icode() const¶
Check if insertion code is present (not space).
- Returns:
True if icode != ‘ ‘, false otherwise.
Public Members
-
OptionalNum num¶
Residue sequence number (0 and negative allowed; INT_MIN = unset)
-
char icode = ' '¶
Insertion code (’ ‘ = no insertion code; ‘A’-‘Z’ typical)
-
using OptionalNum = OptionalInt<INT_MIN>¶
-
inline std::string atom_str(const std::string &chain_name, const ResidueId &res_id, const std::string &atom_name, char altloc, bool as_cid = false)¶
Tabulated residue information and classification.
Provides lookup table for standard PDB residues with chemical properties, one-letter codes, and classifications (amino acids, nucleic acids, etc.).
-
namespace gemmi
Enums
-
enum class ResidueKind : unsigned char¶
Classification of residue type.
Categorizes residues by chemical function and polymer type.
Values:
-
enumerator UNKNOWN¶
Unknown or unclassified residue.
-
enumerator AA¶
L-amino acid (standard protein residue)
-
enumerator AAD¶
D-amino acid.
-
enumerator PAA¶
Proline-like amino acid (cyclic imino acid)
-
enumerator MAA¶
Methylated amino acid (non-standard)
-
enumerator RNA¶
Ribonucleotide (RNA)
-
enumerator DNA¶
Deoxyribonucleotide (DNA)
-
enumerator BUF¶
Buffer/crystallization agent (from PISA agents.dat)
-
enumerator HOH¶
Water molecule (H2O, D2O, or hydroxide)
-
enumerator PYR¶
Pyranose sugar (per Refmac dictionary)
-
enumerator KET¶
Ketopyranose sugar (per Refmac dictionary)
-
enumerator ELS¶
Everything else (organic ligand, metal, etc.)
-
enumerator UNKNOWN¶
Functions
-
ResidueInfo &get_residue_info(size_t idx)¶
Look up residue info by table index.
- Parameters:
idx – Index into the residue table (0 = ALA, etc.).
- Returns:
Reference to ResidueInfo at this index.
-
size_t find_tabulated_residue_idx(const std::string &name)¶
Find table index of named residue.
- Parameters:
name – Residue name (3-letter code, case-insensitive).
- Returns:
Table index, or unknown_tabulated_residue_idx() if not found.
-
constexpr size_t unknown_tabulated_residue_idx()¶
Sentinel index for unknown residue in table.
- Returns:
Index used when residue is not found (returns ResidueInfo with kind=UNKNOWN).
-
ResidueInfo &find_tabulated_residue(const std::string &name)¶
Look up tabulated residue by name.
- Parameters:
name – Residue name (3-letter code: ALA, HOH, ATP, etc.).
- Returns:
ResidueInfo for the named residue, or ResidueInfo with kind UNKNOWN if the name is not in the table.
-
inline const char *expand_one_letter(char c, ResidueKind kind)¶
Expand one-letter code to 3-letter residue name.
Maps standard IUPAC one-letter codes to residue names. For DNA/RNA, ‘T’ (DNA) vs ‘U’ (RNA) are distinct.
- Parameters:
c – One-letter code (A-Z, case-insensitive).
kind – Polymer type: AA (amino acid), RNA, or DNA.
- Returns:
3-letter residue name or nullptr if code invalid for this type.
-
std::vector<std::string> expand_one_letter_sequence(const std::string &seq, ResidueKind kind)¶
Expand sequence of one-letter codes to 3-letter residue names.
- Parameters:
seq – String of one-letter codes (e.g., “MVLVS” for amino acids).
kind – Polymer type: AA (protein), RNA, or DNA.
- Returns:
Vector of 3-letter residue names; entries are empty for invalid codes.
-
inline const char *expand_protein_one_letter(char c)¶
Deprecated: use expand_one_letter(c, ResidueKind::AA) instead.
-
struct ResidueInfo¶
- #include <gemmi/resinfo.hpp>
Tabulated properties of a residue type.
Contains chemical and structural information for known residues. Used by find_tabulated_residue() to return properties for standard residues.
Public Functions
-
inline bool found() const¶
Check if residue was found in tabulated data.
- Returns:
True if kind != UNKNOWN, false otherwise.
-
inline bool is_water() const¶
Check if residue is water.
-
inline bool is_dna() const¶
Check if residue is DNA nucleotide.
-
inline bool is_rna() const¶
Check if residue is RNA nucleotide.
-
inline bool is_nucleic_acid() const¶
Check if residue is nucleic acid (DNA or RNA).
-
inline bool is_amino_acid() const¶
Check if residue is amino acid (any form: L, D, proline, methylated).
-
inline bool is_buffer_or_water() const¶
Check if residue is water or buffer component.
-
inline bool is_standard() const¶
Check if residue is standard (marked in PDB with ATOM, not HETATM).
- Returns:
True if uppercase one-letter code; false if lowercase/space.
-
inline char fasta_code() const¶
Get one-letter code for FASTA output.
- Returns:
Standard one-letter code if standard residue; ‘X’ otherwise.
-
inline bool is_peptide_linking() const¶
Check if residue participates in peptide bonds.
- Returns:
True if linking_type has peptide-linking bit set.
-
inline bool is_na_linking() const¶
Check if residue participates in nucleic acid backbone.
- Returns:
True if linking_type has nucleic acid bit set.
Public Members
-
char name[8]¶
Residue name (3-letter code: ALA, GLY, etc.)
-
ResidueKind kind¶
Classification by type.
-
char one_letter_code¶
Standard IUPAC single-letter code (or space)
-
float weight¶
Molecular weight (Da)
-
inline bool found() const¶
-
enum class ResidueKind : unsigned char¶
Small molecule and inorganic crystal structures.
Flat-list representation of non-macromolecular structures (small molecules, minerals, metal-organic frameworks). Contrast with hierarchical Structure class (chains/residues/atoms) used for proteins/nucleic acids.
-
namespace gemmi
Functions
-
inline bool is_complete(const GroupOps &gops)¶
Check if point group operations form a complete mathematical group.
-
template<typename T>
inline void split_element_and_charge(const std::string &label, T *dest)¶ Parse element and charge from atom type label.
Extracts element symbol (1-2 chars) and optional charge. Charge is at end: “+”, “-”, “+2”, “-2”, etc.
- Template Parameters:
T – Type with element and charge members (e.g., Site, AtomType).
- Parameters:
label – Atom type label (e.g., “C”, “Na+”, “S2-”, “Ni2+”).
dest – Pointer to destination object (sets dest->element, dest->charge).
-
struct SmallStructure¶
- #include <gemmi/small.hpp>
Small molecule or inorganic crystal structure.
Flat-list representation of non-macromolecular structures with unit cell and symmetry. Contrast with Structure class (chains/residues/atoms). For CIF files describing minerals, small molecules, and MOFs.
Public Functions
-
inline std::vector<Site> get_all_unit_cell_sites() const¶
Get all atom sites including symmetry-generated copies.
Generate all unit cell sites from asymmetric unit and symmetry.
Applies space group symmetry to asymmetric unit sites.
Applies space group symmetry operations and translational symmetry (cell.images) to generate all symmetry-equivalent copies. Avoids duplicate sites within special position tolerance (0.4 Å).
- Returns:
List of sites in full unit cell (and neighboring unit cells).
- Returns:
Vector of sites in full unit cell (and neighboring cells if needed).
-
inline void determine_and_set_spacegroup(const char *order)¶
Determine and assign space group from available data.
Populates spacegroup pointer and cell image transformations.
- Parameters:
order – Preference order for source: ‘s’=symops, ‘h’=Hall, ‘1’/’2’=H-M, ‘n’=number. Try in sequence until success. Pass nullptr to skip.
-
inline const SpaceGroup *determine_spacegroup_from(char c, GroupOps &gops) const¶
Determine space group from one data source.
Helper for determine_and_set_spacegroup(). Sets cell.images on success.
- Parameters:
c – Source selector: ‘s’=symops, ‘h’=Hall, ‘1’=H-M setting 1, ‘2’=setting 2, ‘n’=number.
gops – Output: group operations if successfully determined from symops.
- Returns:
SpaceGroup pointer or nullptr if not found.
-
inline std::string check_spacegroup() const¶
Validate space group consistency.
Checks symops, Hall symbol, H-M symbol, and spacegroup_number for mutual consistency. Multiple sources can conflict.
- Returns:
Error message string if inconsistencies found; empty string if valid.
-
inline const AtomType *get_atom_type(const std::string &symbol) const¶
Look up atom type by symbol.
- Parameters:
symbol – Atom type label (e.g., “C1”, “Ni2+”).
- Returns:
Pointer to matching AtomType, or nullptr if not found.
-
inline std::bitset<(size_t)El::END> present_elements() const¶
Get bitset of elements present in structure.
Similar to Model::present_elements() in the macromolecular API.
- Returns:
Bitset where bit i is set if element El(i) appears in sites.
-
inline void remove_hydrogens()¶
Remove all hydrogen atoms from structure.
Modifies sites vector in-place.
-
inline void change_occupancies_to_crystallographic(double max_dist = 0.4)¶
Convert occupancies from chemical to crystallographic convention.
Precondition: occupancies are given in chemical convention (i.e., sum to 1 when all symmetry copies are included, not divided by multiplicity). Divides occupancies by (n_mates+1) for sites on special positions, where n_mates is symmetry multiplicity.
- Parameters:
max_dist – Distance tolerance for identifying special positions (Å).
-
inline void setup_cell_images()¶
Configure cell images from assigned space group.
Sets cell.images transformations based on spacegroup. Call after determine_and_set_spacegroup() or when spacegroup is manually assigned.
Public Members
-
const SpaceGroup *spacegroup = nullptr¶
Space group (pointer to table)
-
int spacegroup_number = 0¶
ITC space group number (1-230)
-
double wavelength = 0.¶
X-ray wavelength (Ångströms)
-
struct AtomType¶
- #include <gemmi/small.hpp>
Atom type (for scattering factor lookups).
Dispersion-corrected element type used in X-ray scattering calculations. Corresponds to mmCIF _atom_type category.
-
struct Site¶
- #include <gemmi/small.hpp>
Atom site in fractional coordinates.
Corresponds to mmCIF _atom_site loop. Each site has element, occupancy, displacement parameters, and optional disorder grouping.
Public Functions
Public Members
-
Fractional fract¶
Fractional coordinates (0-1)
-
double occ = 1.0¶
Occupancy (0-1, partial/disordered)
-
double u_iso = 0.¶
Isotropic B-factor / Uiso.
-
int disorder_group = 0¶
Disorder group ID (0 = ordered site)
-
signed char charge = 0¶
Formal charge ([-8, +8])
-
Fractional fract¶
-
inline std::vector<Site> get_all_unit_cell_sites() const¶
-
inline bool is_complete(const GroupOps &gops)¶
Note
The following sections will be populated by subsequent PRs (3–10) in this series. See PR #413 for the full roadmap.
Map and Grid Data¶
(Full documentation added in PR 6.) (Full documentation added in PR 2.)
Core hierarchical data structures for macromolecular models.
This header defines the fundamental data types used throughout Gemmi to represent macromolecular structures. The hierarchy is:
Structure (complete 3D model with metadata)
Model (NMR/ensemble models with sequential numbering)
Chain (named sequences of residues)
Residue (single amino acid or nucleotide)
Atom (individual atomic coordinates)
It also provides helper structures and enums for handling file formats, calculation flags, secondary structure, and various search/access utilities.
-
namespace gemmi
Typedefs
-
using AtomGroup = AtomGroup_<Atom>
Mutable group of atoms.
-
using ConstAtomGroup = AtomGroup_<const Atom>
Const group of atoms.
Enums
-
enum class CoorFormat : unsigned char
File format of a macromolecular model structure. When passed to read_structure(): Unknown = guess format from the extension (default), Detect = guess format from the content (read first bytes).
Values:
-
enumerator Unknown
Guess from file extension.
-
enumerator Detect
Guess from content/magic bytes.
-
enumerator Pdb
PDB format.
-
enumerator Mmcif
mmCIF format
-
enumerator Mmjson
mmJSON format
-
enumerator ChemComp
Chemical component format.
-
enumerator Unknown
-
enum class CalcFlag : signed char
Atom site calculation flag from mmCIF _atom_site.calc_flag. Indicates how atomic coordinates and B-factors were determined. Note: NoHydrogen has the same numeric value (0) as NotSet; it is used internally to mark atoms that should not have riding hydrogens added.
Values:
-
enumerator NotSet
Flag not set (default)
-
enumerator NoHydrogen
Internal flag: do not add riding hydrogens (same value as NotSet)
-
enumerator Determined
Experimentally determined.
-
enumerator Calculated
Calculated or assigned from geometry.
-
enumerator Dummy
Dummy position for QM/MM or placeholder atoms.
-
enumerator NotSet
-
enum class ResidueSs : unsigned char
Secondary structure annotation from structure file.
Values:
-
enumerator Coil
Random coil or unassigned.
-
enumerator Helix
Helical conformation (alpha, 3-10, pi, etc.)
-
enumerator Strand
Beta strand.
-
enumerator Coil
-
enum class ResidueStrandSense : signed char
Strand sense within a beta sheet from PDB/mmCIF structure file. Distinguishes the first strand in a sheet from other strands and non-strand residues.
Values:
-
enumerator NotStrand
Not part of a beta sheet.
-
enumerator Parallel
Parallel to the previous strand.
-
enumerator First
First strand in a sheet.
-
enumerator Antiparallel
Antiparallel to the previous strand.
-
enumerator NotStrand
Functions
-
template<class T>
void remove_empty_children(T &obj) Recursively remove empty child elements. Removes empty residues from a chain, empty chains from a model, etc. Works with any type that has a
child_typeandchildren()method.- Template Parameters:
T – Container type (Chain, Model, or Structure)
-
inline bool is_same_conformer(char altloc1, char altloc2)
Check if two atoms belong to the same conformer (alternate location). Returns true if altloc values are compatible (either one or both unset, or identical).
- Parameters:
altloc1 – First alternate location character (‘\0’ means no alternate location set)
altloc2 – Second alternate location character
- Returns:
true if atoms are in the same conformer, false otherwise
-
inline void add_distinct_altlocs(const Residue &res, std::string &altlocs)
Collect all distinct alternate location characters from a residue. Appends unique altloc characters to the provided string.
- Parameters:
res – The residue to scan
altlocs – String to accumulate altloc characters (not cleared first)
-
inline std::string atom_str(const Chain &chain, const ResidueId &res_id, const Atom &atom, bool as_cid = false)
Convert Chain, ResidueId, and Atom to a string representation.
- Parameters:
chain – The chain
res_id – The residue ID
atom – The atom
as_cid – If true, format as CIF; if false, format as PDB
- Returns:
String representation of the atom location
-
inline std::string atom_str(const const_CRA &cra, bool as_cif = false)
Convert const_CRA (Chain, Residue, Atom pointers) to string. Handles null pointers gracefully.
- Parameters:
cra – Chain-Residue-Atom triple
as_cif – If true, format as CIF; if false, format as PDB
- Returns:
String representation of the atom location
-
inline bool atom_matches(const const_CRA &cra, const AtomAddress &addr, bool ignore_segment = false)
Check if a const_CRA matches an AtomAddress specification.
- Parameters:
cra – Chain-Residue-Atom triple to test
addr – Target atom address
ignore_segment – If true, don’t check segment ID
- Returns:
true if all relevant fields match
-
inline AtomAddress make_address(const Chain &ch, const Residue &res, const Atom &at)
Create an AtomAddress from Chain, Residue, and Atom.
- Parameters:
ch – The chain
res – The residue
at – The atom
- Returns:
AtomAddress specifying this atom
-
inline Entity *find_entity_of_subchain(const std::string &subchain_id, std::vector<Entity> &entities)
Find entity containing given subchain. Searches for an entity that includes the specified subchain ID.
- Parameters:
subchain_id – Subchain identifier to search for
entities – Vector of entities to search
- Returns:
Pointer to entity containing this subchain, or nullptr if not found
-
inline const Entity *find_entity_of_subchain(const std::string &subchain_id, const std::vector<Entity> &entities)
Find entity containing given subchain. Searches for an entity that includes the specified subchain ID.
- Parameters:
subchain_id – Subchain identifier to search for
entities – Vector of entities to search
- Returns:
Pointer to entity containing this subchain, or nullptr if not found
-
inline void assign_residue_ss_from_file(Structure &st)
Assign secondary structure annotations from HELIX and SHEET records. Initializes all residues to Coil/NotStrand, then marks ranges from PDB records.
- Parameters:
st – Structure to annotate
-
struct Atom
- #include <gemmi/model.hpp>
Represents an atom site in a macromolecular structure (approximately 100 bytes). Stores 3D coordinates, occupancy, atomic displacement parameters (ADP), and associated metadata for a single atom.
Public Functions
-
inline char altloc_or(char null_char) const
Get alternate location character, or fallback value if not set.
- Parameters:
null_char – Character to return if altloc is not set (‘\0’)
- Returns:
altloc if set, otherwise null_char
-
inline bool same_conformer(const Atom &other) const
Check if this atom belongs to the same conformer as another.
- Parameters:
other – The other atom to compare
- Returns:
true if atoms are compatible conformations
-
inline bool altloc_matches(char request) const
Check if this atom matches an alternate location request. ‘*’ matches any altloc, ‘\0’ matches atoms without altloc.
- Parameters:
request – Requested alternate location character
- Returns:
true if this atom’s altloc matches the request
-
inline const std::string &group_key() const
Get grouping key for UniqIter and similar iteration tools.
- Returns:
The atom name
-
inline bool has_altloc() const
Check if this atom has an alternate location assigned.
- Returns:
true if altloc != ‘\0’
-
inline double b_eq() const
Calculate equivalent isotropic B-factor from anisotropic U parameters.
- Returns:
B_eq = (U[0] + U[1] + U[2]) * 8 * pi^2 / 3
-
inline bool is_hydrogen() const
Check if this atom represents a hydrogen.
- Returns:
true if element is H, D, or T
-
inline std::string padded_name() const
Return atom name padded like in PDB format (left-aligned with space). The first two characters of the padded name make the element symbol.
- Returns:
Padded atom name (up to 4 characters)
-
inline Atom empty_copy() const
Create a copy of this atom (shallow copy). Used in template code for hierarchical copying.
- Returns:
A new Atom with identical field values
Public Members
-
std::string name
Atom name (e.g., “CA”, “CB”, “C”, “N”, “O”)
-
char altloc = '\0'
Alternate location character (‘\0’ = not set)
-
signed char charge = 0
Formal charge in range [-8, +8].
-
char flag = '\0'
Custom flag for user-defined marking.
-
short tls_group_id = -1
TLS group assignment (-1 = not assigned)
-
int serial = 0
Atom serial number from input file.
-
float fraction = 0.f
Custom fractional value (e.g., Refmac ccp4_deuterium_fraction)
-
Position pos
Cartesian coordinates (x, y, z)
-
float occ = 1.0f
Occupancy (0.0 to 1.0 typical; >1.0 rare)
-
float b_iso = 20.0f
Isotropic B-factor (temperature factor) in Ångström²
-
SMat33<float> aniso = {0, 0, 0, 0, 0, 0}
Anisotropic displacement parameters U[6].
Public Static Functions
-
static inline const char *what()
-
inline char altloc_or(char null_char) const
-
template<typename AtomType>
struct AtomGroup_ : public gemmi::ItemGroup<AtomType> - #include <gemmi/model.hpp>
A group of atoms sharing the same name but occupying different alternate locations.
Used to iterate over or access atoms at a single crystallographic site that have been modelled in multiple conformations (alt locs).
- Template Parameters:
AtomType – Either
Atom(mutable) orconst Atom(immutable).
Public Functions
-
inline std::string name() const
Get the atom name (same for all atoms in the group).
- Returns:
Atom name, or empty string if group is empty
-
struct Chain
- #include <gemmi/model.hpp>
Represents a chain of residues (typically named A, B, C, …). A chain is a sequence of residues, often corresponding to a polypeptide or polynucleotide.
Public Types
-
using child_type = Residue
Public Functions
-
Chain() = default
-
inline explicit Chain(const std::string &name_) noexcept
Construct chain with a given name.
-
inline ResidueSpan whole()
Get span covering all residues in chain.
- Returns:
Mutable residue span for entire chain
-
inline ConstResidueSpan whole() const
Get span covering all residues in chain.
- Returns:
Mutable residue span for entire chain
-
template<typename F>
inline ResidueSpan get_residue_span(F &&func) Get residue span matching a predicate function.
- Template Parameters:
F – Callable taking const Residue& and returning bool
- Parameters:
func – Predicate function
- Returns:
Mutable span of matching residues
-
template<typename F>
inline ConstResidueSpan get_residue_span(F &&func) const Get residue span matching a predicate function.
- Template Parameters:
F – Callable taking const Residue& and returning bool
- Parameters:
func – Predicate function
- Returns:
Mutable span of matching residues
-
inline ResidueSpan get_polymer()
Get span of polymer residues in this chain. Finds the first contiguous span of polymer residues in the same subchain.
- Returns:
Mutable span of polymer residues, or empty if none found
-
inline ConstResidueSpan get_polymer() const
Get span of polymer residues in this chain. Finds the first contiguous span of polymer residues in the same subchain.
- Returns:
Mutable span of polymer residues, or empty if none found
-
inline ResidueSpan get_ligands()
Get span of ligand residues (NonPolymer or Branched entities).
- Returns:
Mutable span of ligand residues
-
inline ConstResidueSpan get_ligands() const
Get span of ligand residues (NonPolymer or Branched entities).
- Returns:
Mutable span of ligand residues
-
inline ResidueSpan get_waters()
Get span of water residues.
- Returns:
Mutable span of water molecules
-
inline ConstResidueSpan get_waters() const
Get span of water residues.
- Returns:
Mutable span of water molecules
-
inline ResidueSpan get_subchain(const std::string &s)
Get span of residues with given subchain identifier.
- Parameters:
s – Subchain ID to search for
- Returns:
Mutable span of matching residues
-
inline ConstResidueSpan get_subchain(const std::string &s) const
Get span of residues with given subchain identifier.
- Parameters:
s – Subchain ID to search for
- Returns:
Mutable span of matching residues
-
inline std::vector<ResidueSpan> subchains()
Get list of subchain spans (grouped by subchain identifier). Each subchain is a contiguous sequence of residues with the same subchain ID.
- Returns:
Vector of mutable residue spans, one per subchain
-
inline std::vector<ConstResidueSpan> subchains() const
Get list of subchain spans (grouped by subchain identifier). Each subchain is a contiguous sequence of residues with the same subchain ID.
- Returns:
Vector of mutable residue spans, one per subchain
-
inline ResidueGroup find_residue_group(SeqId id)
Find residue group with given sequence ID.
- Parameters:
id – Sequence ID to search for
- Returns:
ResidueGroup containing residues with this sequence ID
-
inline ConstResidueGroup find_residue_group(SeqId id) const
Find residue group with given sequence ID.
- Parameters:
id – Sequence ID to search for
- Returns:
ResidueGroup containing residues with this sequence ID
-
inline Residue *find_residue(const ResidueId &rid)
Find residue by ResidueId (number and insertion code).
- Parameters:
rid – ResidueId to search for
- Returns:
Pointer to matching residue, or nullptr if not found
-
inline const Residue *find_residue(const ResidueId &rid) const
Find residue by ResidueId (number and insertion code).
- Parameters:
rid – ResidueId to search for
- Returns:
Pointer to matching residue, or nullptr if not found
-
inline Residue *find_or_add_residue(const ResidueId &rid)
Find residue by ResidueId, or create it if not found.
- Parameters:
rid – ResidueId to search for or create
- Returns:
Reference to existing or newly created residue
-
inline void append_residues(std::vector<Residue> new_resi, int min_sep = 0)
Append residues to this chain with optional minimum separation. Adjusts sequence numbers if needed to maintain minimum separation.
- Parameters:
new_resi – Vector of residues to append
min_sep – Minimum sequence number separation (0 = no enforcement)
-
inline Chain empty_copy() const
Create a shallow copy with same name but empty residues. Used in template code for hierarchical copying.
-
inline bool is_first_in_group(const Residue &res) const
Check if residue is the first in its group (sequence number). Returns false only for alternative conformations (microheterogeneity).
- Parameters:
res – The residue to check
- Returns:
true if res is the first residue with its sequence number
-
inline const Residue *previous_residue(const Residue &res) const
Get the previous different sequence number residue. Handles microheterogeneity and alternate conformations correctly.
- Parameters:
res – The reference residue
- Returns:
Pointer to previous residue (by sequence number), or nullptr if none
-
inline const Residue *next_residue(const Residue &res) const
Get the next different sequence number residue. Handles microheterogeneity and alternate conformations correctly.
- Parameters:
res – The reference residue
- Returns:
Pointer to next residue (by sequence number), or nullptr if none
-
inline UniqProxy<Residue> first_conformer()
Get proxy for iterating over first conformer only. Skips alternate conformations (microheterogeneity).
- Returns:
Iterator proxy
-
inline ConstUniqProxy<Residue> first_conformer() const
Get proxy for iterating over first conformer only. Skips alternate conformations (microheterogeneity).
- Returns:
Iterator proxy
Public Members
-
std::string name
Chain identifier (usually single letter)
Public Static Functions
-
static inline const char *what()
-
using child_type = Residue
-
struct const_CRA
- #include <gemmi/model.hpp>
Const pointer triple: Chain, Residue, Atom. Used for read-only access to structure hierarchy.
-
struct ConstResidueGroup : public gemmi::ConstResidueSpan
- #include <gemmi/model.hpp>
Const version of ResidueGroup.
Public Functions
-
ConstResidueGroup() = default
-
inline ConstResidueGroup(ConstResidueSpan &&sp)
Construct from a moved span.
-
ConstResidueGroup() = default
-
struct ConstResidueSpan : public gemmi::Span<const Residue>
- #include <gemmi/model.hpp>
Immutable span of residues within a Chain.
Represents a contiguous sequence of residues with utility methods for manipulation, grouping, and sequence numbering conversions.
Subclassed by gemmi::ConstResidueGroup
Public Functions
-
inline ConstResidueSpan(Parent &&span)
Construct from a moved span.
-
inline int length() const
Count unique residues, accounting for microheterogeneity. Residues with the same sequence number but different names count as one.
- Returns:
Number of unique sequence positions
-
inline SeqId::OptionalNum extreme_num(bool label, int sign) const
Find extreme (minimum or maximum) sequence number in span.
- Parameters:
label – If true, use label_seq_id; if false, use seqid
sign – -1 for minimum, +1 for maximum
- Returns:
The extreme sequence number, or unset if span is empty
-
inline ConstUniqProxy<Residue, ConstResidueSpan> first_conformer() const
Get proxy for iterating over the first conformer only. Skips alternate conformations (microheterogeneity).
- Returns:
Iterator proxy
-
inline const std::string &subchain_id() const
Get the subchain identifier common to all residues in span.
-
inline ConstResidueGroup find_residue_group(SeqId id) const
Find residue group with given sequence ID.
- Parameters:
id – Sequence ID to search for
- Returns:
ConstResidueGroup containing residues with this sequence ID
-
inline std::vector<std::string> extract_sequence() const
Extract sequence of residue names from first conformer.
- Returns:
Vector of residue names (one per unique sequence position)
-
inline SeqId label_seq_id_to_auth(SeqId::OptionalNum label_seq_id) const
Convert from canonical sequence number to author (auth) sequence ID. Assumes residues are ordered; works approximately with missing numbers.
-
inline SeqId::OptionalNum auth_seq_id_to_label(SeqId auth_seq_id) const
Convert from author (auth) sequence ID to canonical sequence number. Uses a heuristic since author residue numbers are sometimes not ordered.
- Parameters:
auth_seq_id – Author sequence ID to convert
- Throws:
std::out_of_range – if span is empty
- Returns:
Canonical sequence number
-
inline ConstResidueSpan(Parent &&span)
-
struct CRA
- #include <gemmi/model.hpp>
Mutable pointer triple: Chain, Residue, Atom. Used for modifiable access to structure hierarchy.
Public Functions
-
inline operator const_CRA() const
Implicit conversion to const version.
-
inline operator const_CRA() const
-
template<typename CraT>
class CraIterPolicy - #include <gemmi/model.hpp>
Iterator policy for traversing Chain/Residue/Atom (CRA) triples.
Used with Gemmi’s generic iterator framework to provide bidirectional iteration over all atoms in a Model, yielding CRA structs.
- Template Parameters:
CraT – Either
CRA(mutable) orconst_CRA(immutable).
Public Types
-
using value_type = CraT
-
using reference = const CraT
-
using const_policy = CraIterPolicy<const_CRA>
Public Functions
-
inline CraIterPolicy()
Construct empty iterator.
-
inline CraIterPolicy(const Chain *end, CraT cra_)
Construct iterator at specific position.
- Parameters:
end – Pointer to end of chains array
cra_ – Initial Chain-Residue-Atom triple
-
inline void increment()
Advance to next atom.
-
inline void decrement()
Advance to previous atom.
-
inline bool equal(const CraIterPolicy &o) const
Check equality with another policy.
-
inline CraT dereference()
Get current Chain-Residue-Atom triple.
-
inline operator const_policy() const
Implicit conversion to const policy.
-
template<typename CraT, typename ChainsRefT>
struct CraProxy_ - #include <gemmi/model.hpp>
Proxy object for iterating over Chain/Residue/Atom triples in a Model.
Provides begin()/end() to enable range-for iteration over all CRA entries.
- Template Parameters:
CraT – Either
CRA(mutable) orconst_CRA(immutable).ChainsRefT – Reference to chains vector (mutable or const)
Public Types
-
using iterator = BidirIterator<CraIterPolicy<CraT>>
Public Functions
-
inline iterator begin()
Get iterator to first atom in structure.
-
inline iterator end()
Get iterator past last atom in structure.
Public Members
-
ChainsRefT chains
Reference to chains vector.
-
struct Model
- #include <gemmi/model.hpp>
Represents a single model in an NMR ensemble or multi-model structure. Each model contains a set of chains with complete atomic coordinates.
Public Types
-
using child_type = Chain
Public Functions
-
Model() = default
-
inline explicit Model(int num_) noexcept
Construct model with given number.
- Parameters:
num_ – Model number to assign
-
inline Chain *find_chain(const std::string &chain_name)
Find first chain with given name.
- Parameters:
chain_name – Name of chain to search for
- Returns:
Pointer to chain, or nullptr if not found
-
inline const Chain *find_chain(const std::string &chain_name) const
Find first chain with given name.
- Parameters:
chain_name – Name of chain to search for
- Returns:
Pointer to chain, or nullptr if not found
-
inline Chain *find_last_chain(const std::string &chain_name)
Find last chain with given name. Useful when the same chain name appears multiple times.
- Parameters:
chain_name – Name of chain to search for
- Returns:
Pointer to last matching chain, or nullptr if not found
-
inline void remove_chain(const std::string &chain_name)
Remove all chains with given name.
- Parameters:
chain_name – Name of chains to remove
-
inline void merge_chain_parts(int min_sep = 0)
Merge consecutive chains with the same name. Appends residues from later chains to earlier ones with matching names.
- Parameters:
min_sep – Minimum sequence number separation between merged chains (0 = no enforcement)
-
inline ResidueSpan get_subchain(const std::string &sub_name)
Get residue span with given subchain identifier.
- Parameters:
sub_name – Subchain ID to search for
- Returns:
ResidueSpan of matching residues, or empty span if not found
-
inline ConstResidueSpan get_subchain(const std::string &sub_name) const
Get residue span with given subchain identifier.
- Parameters:
sub_name – Subchain ID to search for
- Returns:
ResidueSpan of matching residues, or empty span if not found
-
inline std::vector<ResidueSpan> subchains()
Get list of all subchains in all chains.
- Returns:
Vector of mutable residue spans, one per subchain
-
inline std::vector<ConstResidueSpan> subchains() const
Get list of all subchains in all chains.
- Returns:
Vector of mutable residue spans, one per subchain
-
inline std::map<std::string, std::string> subchain_to_chain() const
Create mapping from subchain IDs to chain names.
- Returns:
Map: subchain_id -> chain_name
-
inline Residue *find_residue(const std::string &chain_name, const ResidueId &rid)
Find residue in a specific chain by ResidueId.
- Parameters:
chain_name – Name of chain to search in
rid – ResidueId (number and insertion code) to search for
- Returns:
Pointer to residue, or nullptr if not found
-
inline const Residue *find_residue(const std::string &chain_name, const ResidueId &rid) const
Find residue in a specific chain by ResidueId.
- Parameters:
chain_name – Name of chain to search in
rid – ResidueId (number and insertion code) to search for
- Returns:
Pointer to residue, or nullptr if not found
-
inline ResidueGroup find_residue_group(const std::string &chain_name, SeqId seqid)
Find residue group (microheterogeneity-aware) in specific chain.
- Parameters:
chain_name – Name of chain to search in
seqid – Sequence ID to search for
- Throws:
fail() – if chain or residue not found
- Returns:
ResidueGroup containing residues with this sequence ID
-
inline Residue &sole_residue(const std::string &chain_name, SeqId seqid)
Find single residue in specific chain by sequence ID. Fails if there are multiple residues at this position (microheterogeneity).
- Parameters:
chain_name – Name of chain to search in
seqid – Sequence ID to search for
- Throws:
fail() – if residue not found or multiple alternatives exist
- Returns:
Reference to the unique residue
-
inline std::vector<std::string> get_all_residue_names() const
Get list of all unique residue names in model.
- Returns:
Vector of residue names (e.g., “ALA”, “GLY”, “HOH”)
-
inline CRA find_cra(const AtomAddress &address, bool ignore_segment = false)
Find atom by AtomAddress specification.
- Parameters:
address – AtomAddress specifying chain, residue, and atom
ignore_segment – If true, ignore segment ID in matching
- Returns:
Chain-Residue-Atom triple (pointers may be null if not found)
-
inline const_CRA find_cra(const AtomAddress &address, bool ignore_segment = false) const
Find atom by AtomAddress specification.
- Parameters:
address – AtomAddress specifying chain, residue, and atom
ignore_segment – If true, ignore segment ID in matching
- Returns:
Chain-Residue-Atom triple (pointers may be null if not found)
-
inline CraProxy all()
Get proxy for iterating over all atoms in model.
- Returns:
Mutable proxy over all Chain-Residue-Atom triples
-
inline ConstCraProxy all() const
Get proxy for iterating over all atoms in model.
- Returns:
Mutable proxy over all Chain-Residue-Atom triples
-
inline Atom *find_atom(const AtomAddress &address)
Find atom by AtomAddress.
- Parameters:
address – AtomAddress specifying the atom
- Returns:
Pointer to atom, or nullptr if not found
-
inline const Atom *find_atom(const AtomAddress &address) const
Find atom by AtomAddress.
- Parameters:
address – AtomAddress specifying the atom
- Returns:
Pointer to atom, or nullptr if not found
-
inline std::array<int, 3> get_indices(const Chain *c, const Residue *r, const Atom *a) const
Get array indices of chain, residue, and atom in model. Returns -1 for any pointer that is nullptr.
- Parameters:
c – Pointer to chain (may be null)
r – Pointer to residue (may be null)
a – Pointer to atom (may be null)
- Returns:
Array of 3 indices: [chain_index, residue_index, atom_index]
-
inline std::bitset<(size_t)El::END> present_elements() const
Get a bitset of all elements present in model.
- Returns:
Bitset with one bit per Element type
-
inline Model empty_copy() const
Create a shallow copy with metadata but empty chains. Used in template code for hierarchical copying.
Public Members
-
int num = 0
Model number (usually 1-based)
Public Static Functions
-
static inline const char *what()
-
using child_type = Chain
-
struct PdbReadOptions
- #include <gemmi/model.hpp>
Options controlling PDB file parsing behavior.
Public Members
-
int max_line_length = 0
Maximum line length (0 = no limit)
-
bool check_non_ascii = false
Detect and report non-ASCII characters.
-
bool ignore_ter = false
Ignore TER records completely.
-
bool split_chain_on_ter = false
Split chain at each TER record.
-
bool skip_remarks = false
Skip REMARK records entirely.
-
int max_line_length = 0
-
struct Residue : public gemmi::ResidueId
- #include <gemmi/model.hpp>
Represents a single residue (amino acid, nucleotide, or other). A residue is identified by its number and insertion code (SeqId) and contains multiple atoms, potentially in alternate conformations.
Public Functions
-
Residue() = default
-
inline explicit Residue(const ResidueId &rid) noexcept
Construct residue from a ResidueId (number and insertion code).
-
inline Residue empty_copy() const
Create a shallow copy of all fields except atoms (children). Used in template code for hierarchical copying.
- Returns:
New Residue with metadata copied but empty atoms vector
-
inline const Atom *find_by_element(El el) const
Find first atom with given element.
- Parameters:
el – Element to search for
- Returns:
Pointer to atom, or nullptr if not found
-
inline Atom *find_atom(const std::string &atom_name, char altloc, El el = El::X, bool strict_altloc = true)
Find atom by name, alternate location, and optional element. In strict_altloc mode (default), ‘*’ matches any altloc, ‘\0’ matches atoms without altloc. When strict_altloc is false, ‘\0’ is treated as a wildcard match (same as ‘*’).
- Parameters:
- Returns:
Pointer to matching atom, or nullptr if not found
-
inline const Atom *find_atom(const std::string &atom_name, char altloc, El el = El::X, bool strict_altloc = true) const
Find atom by name, alternate location, and optional element. In strict_altloc mode (default), ‘*’ matches any altloc, ‘\0’ matches atoms without altloc. When strict_altloc is false, ‘\0’ is treated as a wildcard match (same as ‘*’).
- Parameters:
- Returns:
Pointer to matching atom, or nullptr if not found
-
inline std::vector<Atom>::iterator find_atom_iter(const std::string &atom_name, char altloc, El el = El::X)
Find iterator to atom by name, alternate location, and optional element.
-
inline AtomGroup get(const std::string &atom_name)
Get group of atoms with the same name (different alternate locations).
- Parameters:
atom_name – Name of atoms to group
- Throws:
fail() – if no atoms with this name exist
- Returns:
AtomGroup containing all atoms with this name
-
inline Atom &sole_atom(const std::string &atom_name)
Get the single atom with given name. Fails if there are multiple alternate conformations.
- Parameters:
atom_name – Name of atom to find
- Throws:
fail() – if atom not found or multiple alternative atoms exist
- Returns:
Reference to the unique atom
-
inline const Atom *get_ca() const
Find peptide backbone CA (alpha carbon) atom.
- Returns:
Pointer to CA atom, or nullptr
-
inline const Atom *get_c() const
Find peptide backbone C (carbonyl carbon) atom.
- Returns:
Pointer to C atom, or nullptr
-
inline const Atom *get_n() const
Find peptide backbone N (amide nitrogen) atom.
- Returns:
Pointer to N atom, or nullptr
-
inline const Atom *get_o() const
Find peptide backbone O (carbonyl oxygen) atom.
- Returns:
Pointer to O atom, or nullptr
-
inline const Atom *get_p() const
Find nucleic acid phosphorus atom.
- Returns:
Pointer to P atom, or nullptr
-
inline const Atom *get_o3prim() const
Find nucleic acid O3’ (3-prime oxygen) atom.
- Returns:
Pointer to O3’ atom, or nullptr
-
inline bool same_conformer(const Residue &other) const
Check if this residue belongs to the same conformer as another. Compatible if either has no alternate locations, or they share an altloc.
- Parameters:
other – The other residue to compare
- Returns:
true if residues are in the same conformer
-
inline bool is_water() const
Check if this residue is a water molecule. Recognizes HOH, DOD (deuterated water), WAT, H2O. Does not match OH or H3O/D3O.
- Returns:
true if residue name matches water identifiers
-
inline UniqProxy<Atom> first_conformer()
Get proxy for iterating over atoms of the first conformer only. Useful for skipping alternate conformations in loops.
- Returns:
Iterator proxy that yields only the first alternate location
-
inline ConstUniqProxy<Atom> first_conformer() const
Get proxy for iterating over atoms of the first conformer only. Useful for skipping alternate conformations in loops.
- Returns:
Iterator proxy that yields only the first alternate location
Public Members
-
std::string subchain
mmCIF _atom_site.label_asym_id (asymmetric unit identifier)
-
std::string entity_id
mmCIF _atom_site.label_entity_id (polymer/ligand/solvent classification)
-
OptionalNum label_seq
mmCIF _atom_site.label_seq_id (canonical sequence numbering)
-
EntityType entity_type = EntityType::Unknown
Polymer, NonPolymer, Water, or Unknown.
-
char het_flag = '\0'
‘A’ = ATOM record, ‘H’ = HETATM record, ‘\0’ = unspecified
-
char flag = '\0'
Custom flag for user-defined marking.
-
ResidueStrandSense strand_sense_from_file = ResidueStrandSense::NotStrand
Strand sense in sheet.
-
SiftsUnpResidue sifts_unp
UniProt reference from SIFTS mapping.
-
short group_idx = 0
Internal variable (ignore)
Public Static Functions
-
static inline const char *what()
-
Residue() = default
-
struct ResidueGroup : public gemmi::ResidueSpan
- #include <gemmi/model.hpp>
Group of residues with the same sequence ID but different names. Represents microheterogeneity (multiple forms of the same residue position). Usually contains only one residue; multiple residues indicate alternate conformations. Residues within a group must be consecutive.
Public Functions
-
ResidueGroup() = default
-
inline ResidueGroup(ResidueSpan &&span)
Construct from a moved span.
-
inline Residue &by_resname(const std::string &name)
Find residue in group by residue name.
- Parameters:
name – Residue name to search for (e.g., “ALA”, “GLY”)
- Throws:
fail() – if no residue with this name found
- Returns:
Reference to residue with this name
-
inline void remove_residue(const std::string &name)
Remove residue from group by name.
- Parameters:
name – Residue name to remove
-
ResidueGroup() = default
-
struct ResidueSpan : public gemmi::MutableVectorSpan<Residue>
- #include <gemmi/model.hpp>
Mutable span of consecutive residues within a chain. Represents a contiguous subsequence of residues that can be modified. It is returned by get_polymer(), get_ligands(), get_waters() and get_subchain().
Subclassed by gemmi::ResidueGroup
Public Types
-
using Parent = MutableVectorSpan<Residue>
Public Functions
-
ResidueSpan() = default
-
inline ResidueSpan(Parent &&span)
Construct from a moved span.
-
inline ResidueSpan(vector_type &v, iterator begin, std::size_t n)
Construct from a vector with specific range.
-
inline int length() const
Count unique residues, accounting for microheterogeneity. Residues with the same sequence number but different names count as one.
- Returns:
Number of unique sequence positions
-
inline SeqId::OptionalNum extreme_num(bool label, int sign) const
Find extreme (minimum or maximum) sequence number in span.
- Parameters:
label – If true, use label_seq_id; if false, use seqid
sign – -1 for minimum, +1 for maximum
- Returns:
The extreme sequence number, or unset if span is empty
-
inline UniqProxy<Residue, ResidueSpan> first_conformer()
Get proxy for iterating over the first conformer only. Skips alternate conformations (microheterogeneity).
- Returns:
Iterator proxy
-
inline ConstUniqProxy<Residue, ResidueSpan> first_conformer() const
Get proxy for iterating over the first conformer only. Skips alternate conformations (microheterogeneity).
- Returns:
Iterator proxy
-
inline GroupingProxy residue_groups()
Get proxy for iterating over residue groups (microheterogeneity-aware).
Get proxy for iterating over residue groups (microheterogeneity-aware).
-
inline const std::string &subchain_id() const
Get the subchain identifier common to all residues in span.
-
inline ResidueGroup find_residue_group(SeqId id)
Find residue group with given sequence ID.
- Parameters:
id – Sequence ID to search for
- Returns:
ResidueGroup containing residues with this sequence ID
-
inline std::vector<std::string> extract_sequence() const
Extract sequence of residue names from first conformer.
- Returns:
Vector of residue names (one per unique sequence position)
-
inline ConstResidueGroup find_residue_group(SeqId id) const
Find residue group with given sequence ID.
- Parameters:
id – Sequence ID to search for
- Returns:
ConstResidueGroup containing residues with this sequence ID
-
inline SeqId label_seq_id_to_auth(SeqId::OptionalNum label_seq_id) const
Convert from canonical sequence number to author (auth) sequence ID. Assumes residues are ordered; works approximately with missing numbers.
-
inline SeqId::OptionalNum auth_seq_id_to_label(SeqId auth_seq_id) const
Convert from author (auth) sequence ID to canonical sequence number. Uses a heuristic since author residue numbers are sometimes not ordered.
- Parameters:
auth_seq_id – Author sequence ID to convert
- Throws:
std::out_of_range – if span is empty
- Returns:
Canonical sequence number
Private Functions
-
inline ConstResidueSpan const_() const
-
struct GroupingProxy
- #include <gemmi/model.hpp>
Proxy providing iteration over ResidueGroups within a ResidueSpan.
Each ResidueGroup contains residues with the same sequence number (microheterogeneities — point mutations stored as alternative residues).
Public Types
-
using iterator = GroupingIter<ResidueSpan, ResidueGroup>
Public Functions
-
inline iterator begin()
Get iterator to first residue group.
-
inline iterator end()
Get iterator past last residue group.
Public Members
-
ResidueSpan &span
-
using iterator = GroupingIter<ResidueSpan, ResidueGroup>
-
using Parent = MutableVectorSpan<Residue>
-
struct Structure
- #include <gemmi/model.hpp>
Represents a complete macromolecular structure with coordinates and metadata. The top level of the data hierarchy containing models, chains, residues, and atoms, along with crystallographic, NMR, and biological assembly information.
Public Types
-
using child_type = Model
Public Functions
-
inline const SpaceGroup *find_spacegroup() const
Find space group definition based on cell parameters.
- Returns:
Pointer to SpaceGroup, or nullptr if not a crystal (aperiodic) structure
-
inline const std::string &get_info(const std::string &tag) const
Get metadata value by mmCIF tag key.
- Parameters:
tag – mmCIF tag (e.g., “_entry.id”, “_cell.Z_PDB”)
- Returns:
Value of tag, or empty string if not found
-
inline Model &first_model()
Get first model in structure.
- Throws:
fail() – if no models exist
- Returns:
Reference to first model
-
inline const Model &first_model() const
Get first model in structure.
- Throws:
fail() – if no models exist
- Returns:
Reference to first model
-
inline Model *find_model(int model_num)
Find model by number.
- Parameters:
model_num – Model number to search for
- Returns:
Pointer to model, or nullptr if not found
-
inline const Model *find_model(int model_num) const
Find model by number.
- Parameters:
model_num – Model number to search for
- Returns:
Pointer to model, or nullptr if not found
-
inline Model &find_or_add_model(int model_num)
Find model by number, creating it if necessary.
- Parameters:
model_num – Model number to find or create
- Returns:
Reference to existing or newly created model
-
inline void renumber_models()
Renumber all models sequentially (1, 2, 3, …).
-
inline Entity *get_entity(const std::string &ent_id)
Find entity by ID.
- Parameters:
ent_id – Entity identifier
- Returns:
Pointer to entity, or nullptr if not found
-
inline const Entity *get_entity(const std::string &ent_id) const
Find entity by ID.
- Parameters:
ent_id – Entity identifier
- Returns:
Pointer to entity, or nullptr if not found
-
inline Entity *get_entity_of(const ConstResidueSpan &sub)
Find entity that contains given residue span (subchain).
- Parameters:
sub – Residue span (subchain) to query
- Returns:
Pointer to entity, or nullptr if not found or span is empty
-
inline const Entity *get_entity_of(const ConstResidueSpan &sub) const
Find entity that contains given residue span (subchain).
- Parameters:
sub – Residue span (subchain) to query
- Returns:
Pointer to entity, or nullptr if not found or span is empty
-
inline Assembly *find_assembly(const std::string &assembly_id)
Find biological assembly by ID.
- Parameters:
assembly_id – Assembly identifier
- Returns:
Pointer to assembly, or nullptr if not found
-
inline Connection *find_connection_by_name(const std::string &conn_name)
Find connection (bond) by name identifier.
- Parameters:
conn_name – Connection name (e.g., “BOND_1”)
- Returns:
Pointer to connection, or nullptr if not found
-
inline const Connection *find_connection_by_name(const std::string &conn_name) const
Find connection (bond) by name identifier.
- Parameters:
conn_name – Connection name (e.g., “BOND_1”)
- Returns:
Pointer to connection, or nullptr if not found
-
inline Connection *find_connection_by_cra(const const_CRA &cra1, const const_CRA &cra2, bool ignore_segment = false)
Find connection between two atoms specified as Chain-Residue-Atom triples. Matches atoms in either order.
- Parameters:
cra1 – First atom specification
cra2 – Second atom specification
ignore_segment – If true, ignore segment ID in matching
- Returns:
Pointer to connection, or nullptr if not found
-
inline Connection *find_connection(const AtomAddress &a1, const AtomAddress &a2)
Find connection between two atoms specified as AtomAddresses. Matches atoms in either order.
- Parameters:
a1 – First atom address
a2 – Second atom address
- Returns:
Pointer to connection, or nullptr if not found
-
inline size_t ncs_given_count() const
Count NCS operators that are explicitly given (not generated).
- Returns:
Number of given NCS operations
-
inline double get_ncs_multiplier() const
Get multiplier for calculating expected multiplicity from NCS. Equals (number_of_ncs_ops + 1) / (number_of_given_ncs + 1).
- Returns:
NCS multiplier factor
-
inline bool ncs_not_expanded() const
Check if NCS operations are not fully expanded.
- Returns:
true if any NCS operator is not marked as given
-
inline void add_conect_one_way(int serial_a, int serial_b, int order)
Add bond(s) from one atom to another in one direction only. Used internally by add_conect() to build the CONECT map.
- Parameters:
serial_a – Serial number of first atom
serial_b – Serial number of second atom
order – Bond order (number of edges to add)
-
inline void add_conect(int serial1, int serial2, int order)
Add bidirectional bond(s) between two atoms. Adds edges in both directions (serial1->serial2 and serial2->serial1).
- Parameters:
serial1 – Serial number of first atom
serial2 – Serial number of second atom
order – Bond order (number of edges to add in each direction)
-
inline void merge_chain_parts(int min_sep = 0)
Merge consecutive chains with the same name across all models.
- Parameters:
min_sep – Minimum sequence number separation between merged chains
-
inline void remove_empty_chains()
Remove all empty chains from all models.
-
inline Structure empty_copy() const
Create a shallow copy with metadata but empty models. Copies all fields except the models vector (which remains empty). Used in template code for hierarchical copying.
- Returns:
New Structure with metadata but no structural data
-
inline void setup_cell_images()
Set up crystallographic cell image information. Populates cell image transformations based on space group symmetry and NCS.
Set up crystallographic cell image information. Populates cell image transformations based on space group symmetry and NCS.
Public Members
-
std::string name
Structure name (e.g., PDB code)
-
UnitCell cell
Unit cell parameters (a, b, c, alpha, beta, gamma)
-
std::string spacegroup_hm
Space group symbol (PDB/Hermann-Mauguin notation)
-
std::vector<Connection> connections
Chemical bonds and other connections.
-
std::vector<StructSite> sites
Special sites (binding sites, etc.)
-
Metadata meta
File metadata (authors, publication, etc.)
-
CoorFormat input_format = CoorFormat::Unknown
Format of input file (PDB, mmCIF, etc.)
-
bool has_d_fraction = false
Flag: uses Refmac’s ccp4_deuterium_fraction.
-
int non_ascii_line = 0
First PDB line with non-ASCII bytes (0 = none)
-
char ter_status = '\0'
Status of TER records in PDB file. ‘\0’ = not set, ‘y’ = TER records were read, ‘e’ = errors detected.
-
bool has_origx = false
Flag: ORIGX transformation matrix present.
-
Transform origx
ORIGX or _database_PDB_matrix transformation.
-
std::vector<std::pair<std::string, std::string>> shortened_ccd_codes
Mapping of long (4+ chars) CCD codes to PDB-compatible 3-letter codes.
-
double resolution = 0
Resolution from REMARK 2 (0 = not set, in Å)
Public Static Functions
-
static inline const char *what()
-
using child_type = Model
-
namespace impl
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
Functions
-
using AtomGroup = AtomGroup_<Atom>
CIF Data Reading and Writing¶
(Full documentation added in PR 3.)
In-memory representation of a CIF (Crystallographic Information File) document.
This header defines the core data structures for parsing and manipulating CIF files. It provides a document model that can represent both traditional CIF and mmCIF (macromolecular CIF) formats, as well as alternative serializations like CIF-JSON or mmJSON. The model consists of blocks, items (tag-value pairs or loops), and supports frame nesting.
-
namespace gemmi
-
namespace cif¶
Read CIF data from a string.
This function was moved here from cif.hpp to speed up compilation.
- Param data:
CIF-formatted string
- Param check_level:
Syntax checking level (0=none, 1=moderate, 2=strict)
- Return:
Parsed CIF document
Enums
-
enum class ItemType : unsigned char¶
Discriminator for CIF items: single tag-value pairs, loops, or frames.
Values:
-
enumerator Pair¶
A single tag-value pair (e.g.,
_cell.length_a 10.5)
-
enumerator Loop¶
A loop with tags (column headers) and values in row-major storage.
-
enumerator Frame¶
A save frame (nested block); used in CIF to define templates or additional metadata.
-
enumerator Comment¶
A comment item (prefix-preserved in output, not validated for syntax)
-
enumerator Erased¶
Placeholder for a logically removed item; storage not reclaimed.
-
enumerator Pair¶
Functions
-
inline uint8_t char_table(char c)¶
-
struct Block¶
- #include <gemmi/cifdoc.hpp>
A CIF data block, containing tags (pairs), loops, and nested frames.
In CIF syntax, a block starts with
data_blocknameand contains items:Tag-value pairs:
_tag valueLoops:
loop_ _tag1 _tag2 ... value1a value2a value1b value2b ...Frames:
save_framename ... save_
Blocks are case-insensitive for tag lookup (but case is preserved in output).
Public Functions
-
inline Block()¶
Construct an unnamed block.
-
inline const Item *find_pair_item(const std::string &tag) const¶
Find an Item that is a tag-value pair by tag name.
- Parameters:
tag – Tag to search for (case-insensitive).
- Returns:
Pointer to the Item, or nullptr if not found or not a Pair.
-
inline const Pair *find_pair(const std::string &tag) const¶
Find a tag-value pair (Pair).
- Parameters:
tag – Tag to search for (case-insensitive).
- Returns:
Pointer to the Pair, or nullptr if not found.
-
inline Column find_loop(const std::string &tag)¶
Find a loop containing a tag and get a Column view.
-
inline const Item *find_loop_item(const std::string &tag) const¶
Find an Item that is a loop containing a tag.
- Parameters:
tag – Tag to search for (case-insensitive).
- Returns:
Pointer to the Item, or nullptr if not found.
-
inline const std::string *find_value(const std::string &tag) const¶
Find a single value (from Pair or first row of Loop with single column).
- Parameters:
tag – Tag to search for (case-insensitive).
- Returns:
Pointer to the value string, or nullptr if not found.
-
inline Column find_values(const std::string &tag)¶
Find all values with a tag (Column from Loop or Pair).
- Parameters:
tag – Tag to search for (case-insensitive).
- Returns:
Column view (empty if not found).
-
inline bool has_any_value(const std::string &tag) const¶
Check if a tag exists and has at least one non-null value.
-
inline Table find(const std::string &prefix, const std::vector<std::string> &tags)¶
Find a table of values with specified tags (required tags).
- Parameters:
prefix – Common tag prefix (e.g.,
_atom_site).tags – Tags to search for (no ‘?’ prefix; all required).
- Returns:
Table view (ok() == false if not all tags found).
-
inline Table find_any(const std::string &prefix, const std::vector<std::string> &tags)¶
Find a table with optional tags (all columns attempted).
- Parameters:
prefix – Common tag prefix.
tags – Tags to search for; position -1 if not found.
- Returns:
Table view.
-
inline Table find_or_add(const std::string &prefix, std::vector<std::string> tags)¶
Find a table, creating it if not found.
- Parameters:
prefix – Common tag prefix.
tags – Tags; all are created as a new loop if not found.
- Returns:
Table view (ok() == true).
-
inline Block *find_frame(std::string name)¶
Find a nested frame (save block) by name.
- Parameters:
name – Frame name (case-insensitive).
- Returns:
Pointer to the frame Block, or nullptr if not found.
-
inline size_t get_index(const std::string &tag) const¶
Get the index of an item containing a tag.
- Parameters:
tag – Tag to search for (case-insensitive).
- Throws:
std::runtime_error – if tag not found.
- Returns:
Index in the items vector.
-
inline void set_pair(const std::string &tag, const std::string &value)¶
Set or update a tag-value pair.
- Parameters:
tag – Tag name (case-insensitive for lookup, but case is updated if tag is added).
value – Value to set.
-
inline Loop &init_loop(const std::string &prefix, std::vector<std::string> tags)¶
Initialize or get a loop for specified tags.
-
inline void move_item(int old_pos, int new_pos)¶
Move an item to a different position.
- Parameters:
old_pos – Current position (supports negative indexing).
new_pos – Target position (supports negative indexing).
-
inline std::vector<std::string> get_mmcif_category_names() const¶
Get all category prefixes in mmCIF format (ending with ‘.’).
-
inline Table find_mmcif_category(std::string cat)¶
Find a category (all tags starting with prefix).
- Parameters:
cat – Category prefix (e.g.,
_atom_site; ‘.’ is added if missing).- Returns:
Table view with all matching tags.
Public Members
-
class Column¶
- #include <gemmi/cifdoc.hpp>
A view into a single column of a Loop, or a single Pair value.
Provides array-like access to a sequence of values from either a loop column or a pair value. Acts as both a reference (can be modified through operator[]) and an iterable container.
Public Types
-
using iterator = StrideIter<std::string>¶
Iterator type for strided traversal of column values.
-
using const_iterator = StrideIter<const std::string>¶
Const iterator type.
Public Functions
-
inline Column()¶
Construct an empty/null column.
-
inline Column(Item *item, size_t col)¶
Construct a column view for a specific item and column index.
-
inline const_iterator begin() const¶
Const begin iterator.
-
inline const_iterator end() const¶
Const end iterator.
-
inline Loop *get_loop() const¶
Get the underlying Loop, if this column comes from a Loop item; nullptr otherwise.
-
inline std::string *get_tag()¶
Get the tag (column header) string for this column.
- Returns:
Pointer to the tag string (valid as long as the Item is alive).
-
inline int length() const¶
Number of values in this column.
-
inline explicit operator bool() const¶
Check if this column is valid (not null).
-
inline std::string &operator[](int n)¶
Access a value by index (0-based; for Pair, only index 0 is valid).
-
using iterator = StrideIter<std::string>¶
-
struct CommentArg¶
- #include <gemmi/cifdoc.hpp>
-
struct Document¶
- #include <gemmi/cifdoc.hpp>
A parsed CIF file: a collection of blocks with optional metadata.
Represents the complete document structure after parsing a CIF file. Contains one or more data blocks, each with tag-value pairs, loops, and frames.
Public Functions
-
inline Block &add_new_block(const std::string &name, int pos = -1)¶
Add a new block to the document.
-
inline void clear() noexcept¶
Clear all blocks and source info.
-
inline Block &sole_block()¶
Get the single block from a one-block document (typical for mmCIF).
- Throws:
std::runtime_error – if document has != 1 block.
- Returns:
Reference to blocks[0].
-
inline const Block &sole_block() const¶
Const overload of sole_block().
-
inline const Block *find_block(const std::string &name) const¶
Const overload of find_block().
Public Members
-
inline Block &add_new_block(const std::string &name, int pos = -1)¶
-
struct FrameArg¶
- #include <gemmi/cifdoc.hpp>
-
struct Item¶
- #include <gemmi/cifdoc.hpp>
A single item in a CIF block: a pair, loop, frame, comment, or erased marker.
Uses a discriminated union (tagged with ItemType) to store different data types. For a Pair, stores tag and value. For a Loop, stores tags and values vectors. For a Frame, stores a nested Block.
Public Functions
-
inline Item()¶
Construct an erased (empty) item.
-
inline explicit Item(CommentArg &&comment)¶
Construct a Comment from a CommentArg.
-
inline ~Item()¶
Destructor (calls destruct on the active union member).
-
inline void erase()¶
Mark this item as erased without freeing underlying storage. Changes type to Erased; the union memory is left as-is.
Public Members
-
int line_number = -1¶
Source line number where this item was parsed (or -1 if not from parsing).
- union gemmi::cif::Item
Union storing the actual data (only one is valid based on type).
-
inline Item()¶
-
struct ItemSpan¶
- #include <gemmi/cifdoc.hpp>
Public Functions
-
struct Loop¶
- #include <gemmi/cifdoc.hpp>
A tabular loop structure: tags (column names) and flat row-major values.
In CIF syntax, a loop is a compact representation of a table with named columns:
Internally, the tag names are stored inloop_ _category.tag1 _category.tag2 _category.tag3 value1a value2a value3a value1b value2b value3b
tagsand all values are stored sequentially invaluesusing row-major layout: for N columns and M rows,values.size() == N*M, and element at (row r, column c) is at indexr * N + c.Public Functions
-
inline int find_tag_lc(const std::string &lctag) const¶
Find a tag by case-insensitive match.
- Parameters:
lctag – Tag name converted to lowercase.
- Returns:
Column index (0-based) if found; -1 if not found.
-
inline int find_tag(const std::string &tag) const¶
Find a tag by case-insensitive match.
- Parameters:
tag – Tag name (converted to lowercase internally).
- Returns:
Column index (0-based) if found; -1 if not found.
-
inline size_t width() const¶
Number of columns in this loop.
-
inline size_t length() const¶
Number of rows in this loop.
-
inline std::string &val(size_t row, size_t col)¶
Direct access to a value by row and column index (row-major layout).
- Parameters:
row – Row index (0-based).
col – Column index (0-based).
- Returns:
Reference to the value at (row, col).
-
inline void clear()¶
Clear all tags and values from this loop.
-
template<typename T>
inline void add_values(T new_values, int pos = -1)¶ Insert values into the loop, optionally at a specific row position.
- Template Parameters:
T – Container type with begin()/end() iterators (e.g., std::vector, std::initializer_list).
- Parameters:
new_values – Container of strings to insert.
pos – Row position to insert at (-1 appends at end).
-
inline void add_values(std::initializer_list<std::string> new_values, int pos = -1)¶
Overload for initializer_list.
-
template<typename T>
inline void add_row(T new_values, int pos = -1)¶ Add a complete row to the loop (must match column count).
-
inline void add_row(std::initializer_list<std::string> new_values, int pos = -1)¶
Overload for initializer_list.
-
inline void add_comment_and_row(std::initializer_list<std::string> ss)¶
Add a comment prefix to the first value of a row, then add the row.
-
inline void pop_row()¶
Remove the last row from the loop.
- Throws:
std::runtime_error – if the loop is already empty.
-
inline void move_row(int old_pos, int new_pos)¶
Move a row to a different position within the loop.
-
inline void add_columns(const std::vector<std::string> &column_names, const std::string &value, int pos = -1)¶
Add new columns with an initial fill value.
- Parameters:
column_names – Vector of new tag names (must start with ‘_’).
value – String value to fill for all existing rows.
pos – Column position to insert at (-1 appends at end).
-
inline void remove_column(const std::string &column_name)¶
Remove a column by tag name.
- Parameters:
column_name – Tag to remove (case-insensitive search).
- Throws:
std::runtime_error – if tag not found.
-
inline void remove_column_at(size_t n)¶
Remove a column by index.
- Parameters:
n – Column index; must be < tags.size().
-
inline int find_tag_lc(const std::string &lctag) const¶
-
struct LoopArg¶
- #include <gemmi/cifdoc.hpp>
-
struct Table¶
- #include <gemmi/cifdoc.hpp>
A unified view of data as either a loop (multiple rows) or pairs (single row).
Some CIF data can be represented either way:
As a loop with multiple rows (efficient for large tables)
As separate tag-value pairs (equivalent to a loop with one row)
This struct abstracts both representations to provide uniform access through Row objects. It internally tracks column mappings and optimizes for the loop case.
Public Functions
-
inline bool ok() const¶
Check if this table is valid (has at least one column).
-
inline size_t width() const¶
Number of columns in the table query.
-
inline size_t length() const¶
Number of rows in this table.
-
inline bool has_column(int n) const¶
Check if column n is present (not -1).
-
inline void at_check(int &n) const¶
Validate and normalize a row index (supports negative indexing).
- Parameters:
n – Index to check (modified in-place).
- Throws:
std::out_of_range – if index is invalid.
-
inline Row one()¶
Get the single row of a one-row table.
- Throws:
std::runtime_error – if table has != 1 row.
- Returns:
The first (and only) row.
-
inline std::string get_prefix() const¶
Get the common category prefix for this table (e.g.,
_atom_site).
-
inline Row find_row(const std::string &s)¶
Find the first row where the first column matches a value.
- Parameters:
s – String value to search for (compared with as_string unquoting).
- Throws:
std::runtime_error – if no row matches.
- Returns:
The matching row.
-
template<typename T>
void append_row(const T &new_values)¶ Append a row with values matching the table columns.
-
inline void append_row(std::initializer_list<std::string> new_values)¶
Overload for initializer_list.
-
inline void remove_row(int row_index)¶
Remove a single row.
-
inline void remove_rows(int start, int end)¶
Remove rows [start, end).
-
inline void move_row(int old_pos, int new_pos)¶
Move a row to a different position.
-
inline int find_column_position(const std::string &tag) const¶
Find a column by tag name (supports prefix matching).
-
inline void erase()¶
Erase this table (remove all its items from the block).
-
inline void ensure_loop()¶
Ensure data is in loop form (convert from pairs if needed).
Public Members
-
std::vector<int> positions¶
Column position mappings: for each query column, the position in loop/pairs. Negative position (-1) means the column is optional and absent.
-
size_t prefix_length¶
Length of the common tag prefix (e.g.,
_atom_site.length).
-
struct iterator¶
- #include <gemmi/cifdoc.hpp>
Iterator for range-based for loops over rows.
Public Functions
-
inline void operator++()¶
-
inline void operator++()¶
-
struct Row¶
- #include <gemmi/cifdoc.hpp>
A single row of the table, providing key-value access to columns.
Public Types
-
using iterator = IndirectIter<Row, std::string>¶
Iterator type for traversing columns in this row.
-
using const_iterator = IndirectIter<const Row, const std::string>¶
Const iterator type.
Public Functions
-
inline std::string &value_at(int pos)¶
Safe access by position; throws if position is -1 (optional column absent).
-
inline const std::string &value_at(int pos) const¶
Const overload of value_at().
-
inline bool has(size_t n) const¶
Check if a column is present.
-
inline bool has2(size_t n) const¶
Check if a column is present and has a non-null value.
-
inline const std::string &one_of(size_t n1, size_t n2) const¶
Return the first non-null value among two columns, or a null placeholder.
-
inline size_t size() const¶
Number of columns in the table query.
-
inline const_iterator begin() const¶
Const begin iterator.
-
inline const_iterator end() const¶
Const end iterator.
-
using iterator = IndirectIter<Row, std::string>¶
-
namespace cif¶
PEGTL-based CIF parser with pluggable action handlers and Document construction.
This header provides the complete CIF parsing infrastructure:
PEG grammar rules for CIF 1.1 syntax (namespace
rules)Customizable action handlers (templates specializing
Action<Rule>)Built-in actions that construct an in-memory Document
Entry points: read_file(), read_memory(), read_cstream(), read_istream(), read()
For high-level parsing of standard formats (mmCIF, plain CIF), prefer read_cif.hpp.
-
namespace gemmi
-
namespace cif
Read CIF data from a string.
This function was moved here from cif.hpp to speed up compilation.
- Param data:
CIF-formatted string
- Param check_level:
Syntax checking level (0=none, 1=moderate, 2=strict)
- Return:
Parsed CIF document
Functions
-
template<typename Input>
void parse_input(Document &d, Input &&in)¶ Parse CIF content from an input, populating a Document.
- Template Parameters:
Input – PEGTL input type (e.g., pegtl::file_input, pegtl::memory_input).
- Parameters:
d – Document to populate with parsed blocks and items.
in – PEGTL input object.
- Throws:
pegtl::parse_error – on syntax errors.
-
template<typename Input>
Document read_input(Input &&in, int check_level = 1)¶ Read a complete CIF file and return a Document.
- Template Parameters:
Input – PEGTL input type.
- Parameters:
in – PEGTL input object with a source() method.
check_level – Validation strictness: 0=no checks, 1=missing values & duplicates, 2=also empty loops.
- Throws:
pegtl::parse_error – on syntax errors.
std::runtime_error – on validation failures (check_level > 0).
- Returns:
Fully parsed Document.
-
template<typename Input>
size_t parse_one_block(Document &d, Input &&in)¶ Parse a single CIF data block and add it to a Document.
- Template Parameters:
Input – PEGTL input type.
- Parameters:
d – Document to append to.
in – PEGTL input.
- Throws:
pegtl::parse_error – on syntax errors.
- Returns:
Byte offset after parsing the block.
-
inline Document read_file(const std::string &filename, int check_level = 1)¶
Read a CIF file from disk.
-
inline Document read_memory(const char *data, size_t size, const char *name, int check_level = 1)¶
Read CIF from memory.
- Parameters:
data – Pointer to CIF content (need not be null-terminated).
size – Number of bytes to parse.
name – Label for error messages (e.g., “buffer”).
check_level – Validation level (0-2).
- Throws:
pegtl::parse_error – on syntax errors.
- Returns:
Parsed Document.
-
inline Document read_cstream(std::FILE *f, size_t bufsize, const char *name, int check_level = 1)¶
Read CIF from a C FILE stream.
- Parameters:
f – Open FILE pointer (e.g., stdin, or result of fopen()).
bufsize – Buffering size for reading (e.g., 16*1024).
name – Label for error messages.
check_level – Validation level (0-2).
- Throws:
pegtl::parse_error – on syntax errors.
- Returns:
Parsed Document.
-
inline Document read_istream(std::istream &is, size_t bufsize, const char *name, int check_level = 1)¶
Read CIF from a C++ std::istream.
- Parameters:
is – Input stream (e.g., std::ifstream, std::cin).
bufsize – Buffering size (e.g., 16*1024).
name – Label for error messages.
check_level – Validation level (0-2).
- Throws:
pegtl::parse_error – on syntax errors.
- Returns:
Parsed Document.
-
template<typename Input>
bool try_parse(Input &&in, std::string *msg)¶ Try parsing CIF without validation or error throwing.
- Template Parameters:
Input – PEGTL input type.
- Parameters:
in – PEGTL input.
msg – Optional pointer to store error message (if parsing fails).
- Returns:
true if parse succeeded, false otherwise.
-
template<typename T>
Document read(T &&input, int check_level = 1)¶ Read CIF from a file or stream, handling compression transparently.
- Template Parameters:
T – Type with methods: uncompress_into_buffer(), is_stdin(), is_compressed(), path(). (Traits matching BasicInput and MaybeGzipped wrappers in Gemmi.)
- Parameters:
input – Input wrapper (handles gzip, bzip2, and plain files).
check_level – Validation level (0-2).
- Throws:
pegtl::parse_error – on syntax errors.
- Returns:
Parsed Document.
-
template<typename T>
bool check_syntax(T &&input, std::string *msg)¶ Check CIF syntax without building a Document.
- Template Parameters:
T – Type with uncompress_into_buffer() and path() methods.
- Parameters:
input – Input wrapper.
msg – Optional pointer to store error message.
- Returns:
true if syntax is valid, false otherwise.
-
template<typename T>
size_t read_one_block(Document &d, T &&input, size_t limit)¶ Read one CIF block from a file or stream into an existing Document.
- Template Parameters:
T – Type with is_compressed(), is_stdin(), uncompress_into_buffer(size_t), path() methods.
- Parameters:
d – Document to append block to.
input – Input wrapper.
limit – Max bytes to read from compressed file (0 = no limit).
- Throws:
pegtl::parse_error – on syntax errors.
- Returns:
Byte offset after parsing the block.
-
template<>
struct Action<rules::datablockname>¶ - #include <gemmi/cif.hpp>
-
template<>
struct Action<rules::item_value>¶ - #include <gemmi/cif.hpp>
-
template<>
struct Action<rules::loop_value>¶ - #include <gemmi/cif.hpp>
-
template<>
struct Action<rules::str_global>¶ - #include <gemmi/cif.hpp>
-
template<typename Rule>
struct CheckAction : public tao::pegtl::nothing<Rule>¶ - #include <gemmi/cif.hpp>
-
template<>
struct CheckAction<rules::missing_value>¶ - #include <gemmi/cif.hpp>
-
namespace rules¶
-
-
struct anyprint_ch : public tao::pegtl::ranges<' ', '~', '\t'>¶
- #include <gemmi/cif.hpp>
-
struct comment : public tao::pegtl::if_must<pegtl::one<'#'>, pegtl::until<pegtl::eolf>>¶
- #include <gemmi/cif.hpp>
-
struct datablock : public tao::pegtl::seq<datablockheading, ws_or_eof, pegtl::star<pegtl::sor<dataitem, loop, frame>>>¶
- #include <gemmi/cif.hpp>
-
struct datablockheading : public tao::pegtl::sor<pegtl::seq<str_data, datablockname>, str_global>¶
- #include <gemmi/cif.hpp>
-
struct datablockname : public tao::pegtl::star<nonblank_ch>¶
- #include <gemmi/cif.hpp>
-
struct dataitem : public tao::pegtl::if_must<item_tag, whitespace, pegtl::if_then_else<item_value, ws_or_eof, missing_value>, pegtl::discard>¶
- #include <gemmi/cif.hpp>
-
template<typename Q>
struct endq : public tao::pegtl::seq<Q, pegtl::at<pegtl::sor<pegtl::one<' ', '\n', '\r', '\t', '#'>, pegtl::eof>>>¶ - #include <gemmi/cif.hpp>
-
struct field_sep : public tao::pegtl::seq<pegtl::bol, pegtl::one<';'>>¶
- #include <gemmi/cif.hpp>
-
struct file : public tao::pegtl::seq<pegtl::opt<whitespace>, pegtl::if_must<pegtl::not_at<pegtl::eof>, content, pegtl::eof>>¶
- #include <gemmi/cif.hpp>
-
struct frame : public tao::pegtl::if_must<str_save, framename, whitespace, pegtl::star<pegtl::sor<dataitem, loop>>, endframe, ws_or_eof>¶
- #include <gemmi/cif.hpp>
-
struct framename : public tao::pegtl::plus<nonblank_ch>¶
- #include <gemmi/cif.hpp>
-
struct keyword : public tao::pegtl::sor<str_data, str_loop, str_global, str_save, str_stop>¶
- #include <gemmi/cif.hpp>
-
template<int TableVal>
struct lookup_char¶ - #include <gemmi/cif.hpp>
Public Types
-
using analyze_t = pegtl::analysis::generic<pegtl::analysis::rule_type::ANY>¶
-
using analyze_t = pegtl::analysis::generic<pegtl::analysis::rule_type::ANY>¶
-
struct loop : public tao::pegtl::if_must<str_loop, whitespace, pegtl::plus<pegtl::seq<loop_tag, whitespace, pegtl::discard>>, pegtl::sor<pegtl::plus<pegtl::seq<loop_value, ws_or_eof, pegtl::discard>>, pegtl::at<pegtl::sor<keyword, pegtl::eof>>>, loop_end>¶
- #include <gemmi/cif.hpp>
-
struct missing_value : public tao::pegtl::bol¶
- #include <gemmi/cif.hpp>
-
struct nonblank_ch : public tao::pegtl::range<'!', '~'>¶
- #include <gemmi/cif.hpp>
-
struct one_block : public tao::pegtl::seq<pegtl::opt<whitespace>, pegtl::if_must<pegtl::not_at<pegtl::eof>, datablock>>¶
- #include <gemmi/cif.hpp>
-
template<typename Q>
struct quoted : public tao::pegtl::if_must<Q, quoted_tail<Q>>¶ - #include <gemmi/cif.hpp>
-
template<typename Q>
struct quoted_tail : public tao::pegtl::until<endq<Q>, pegtl::not_one<'\n'>>¶ - #include <gemmi/cif.hpp>
-
struct simunq : public tao::pegtl::seq<pegtl::plus<ordinary_char>, pegtl::at<ws_char>>¶
- #include <gemmi/cif.hpp>
- singlequoted : public quoted< pegtl::one<'\'> >
- #include <gemmi/cif.hpp>
-
struct str_data : public TAOCPP_PEGTL_ISTRINGdata_¶
- #include <gemmi/cif.hpp>
-
struct str_global : public tao::pegtl::seq<TAOCPP_PEGTL_ISTRING("global_"), pegtl::at<ws_or_eof>>¶
- #include <gemmi/cif.hpp>
-
struct str_loop : public tao::pegtl::seq<TAOCPP_PEGTL_ISTRING("loop_"), pegtl::at<ws_or_eof>>¶
- #include <gemmi/cif.hpp>
-
struct str_save : public TAOCPP_PEGTL_ISTRINGsave_¶
- #include <gemmi/cif.hpp>
Subclassed by gemmi::cif::rules::endframe
-
struct str_stop : public tao::pegtl::seq<TAOCPP_PEGTL_ISTRING("stop_"), pegtl::at<ws_or_eof>>¶
- #include <gemmi/cif.hpp>
-
struct tag : public tao::pegtl::seq<pegtl::one<'_'>, pegtl::plus<nonblank_ch>>¶
- #include <gemmi/cif.hpp>
Subclassed by gemmi::cif::rules::item_tag, gemmi::cif::rules::loop_tag
-
struct textfield : public tao::pegtl::if_must<field_sep, pegtl::until<field_sep>>¶
- #include <gemmi/cif.hpp>
-
struct unquoted : public tao::pegtl::seq<pegtl::not_at<keyword>, pegtl::not_at<pegtl::one<'_', '$', '#'>>, pegtl::plus<nonblank_ch>>¶
- #include <gemmi/cif.hpp>
-
struct value : public tao::pegtl::sor<simunq, singlequoted, doublequoted, textfield, unquoted>¶
- #include <gemmi/cif.hpp>
Subclassed by gemmi::cif::rules::item_value, gemmi::cif::rules::loop_value
-
struct ws_or_eof : public tao::pegtl::sor<whitespace, pegtl::eof>¶
- #include <gemmi/cif.hpp>
-
struct anyprint_ch : public tao::pegtl::ranges<' ', '~', '\t'>¶
-
namespace cif
Reading possibly gzip-compressed CIF and JSON files.
-
namespace gemmi
Functions
-
cif::Document read_cif_gz(const std::string &path, int check_level = 1)¶
Read a CIF file, optionally gzip-compressed, from disk.
- Parameters:
path – Path to the CIF file (may end with .gz for gzip compression)
check_level – Syntax checking level (0=none, 1=moderate, 2=strict)
- Returns:
Parsed CIF document
-
bool check_cif_syntax_gz(const std::string &path, std::string *msg)¶
Check CIF syntax without fully parsing the file.
Performs a quick syntax validation pass on a CIF file (optionally gzipped).
- Parameters:
path – Path to the CIF file (may end with .gz for gzip compression)
msg – If non-null, receives an error message if validation fails
- Returns:
true if file syntax is valid, false otherwise
-
cif::Document read_mmjson_gz(const std::string &path)¶
Read an mmJSON file (optionally gzip-compressed) from disk.
mmJSON is the JSON format used by PDBj for macromolecular CIF data.
- Parameters:
path – Path to the mmJSON file (may end with .gz for gzip compression)
- Returns:
Parsed CIF document
-
CharArray read_into_buffer_gz(const std::string &path)¶
Read a file into a buffer, optionally decompressing if gzip-compressed.
- Parameters:
path – Path to the file (may end with .gz for gzip compression)
- Returns:
Buffer containing decompressed file contents
-
cif::Document read_cif_from_memory(const char *data, size_t size, const char *name, int check_level = 1)¶
Parse a CIF document from a memory buffer.
- Parameters:
data – Pointer to buffer containing CIF data
size – Number of bytes to read
name – Optional name for the source (used in error messages)
check_level – Syntax checking level (0=none, 1=moderate, 2=strict)
- Returns:
Parsed CIF document
-
cif::Document read_first_block_gz(const std::string &path, size_t limit)¶
Read only the first block from a CIF file, optionally gzip-compressed.
Useful for reading CIF files where only the first block is needed, potentially saving memory and parsing time.
- Parameters:
path – Path to the CIF file (may end with .gz for gzip compression)
limit – Maximum number of bytes to read from the file
- Returns:
CIF document containing only the first block
-
inline cif::Document read_cif_or_mmjson_gz(const std::string &path)¶
Auto-detect and read either CIF or mmJSON format from a file.
Determines format by file extension (.json, .js for JSON; otherwise CIF). Handles gzip-compressed files transparently.
- Parameters:
path – Path to the file (may end with .gz for gzip compression)
- Returns:
Parsed CIF document
-
namespace cif
Read CIF data from a string.
This function was moved here from cif.hpp to speed up compilation.
- Param data:
CIF-formatted string
- Param check_level:
Syntax checking level (0=none, 1=moderate, 2=strict)
- Return:
Parsed CIF document
-
cif::Document read_cif_gz(const std::string &path, int check_level = 1)¶
Writing CIF documents to output streams with configurable formatting.
-
namespace gemmi
-
namespace cif
Read CIF data from a string.
This function was moved here from cif.hpp to speed up compilation.
- Param data:
CIF-formatted string
- Param check_level:
Syntax checking level (0=none, 1=moderate, 2=strict)
- Return:
Parsed CIF document
Enums
-
enum class Style¶
Deprecated output formatting style. Use cif::WriteOptions instead.
This enum is provided for backward compatibility. Each style corresponds to a particular WriteOptions configuration.
Values:
-
enumerator Simple¶
Standard CIF format (default)
-
enumerator NoBlankLines¶
Compact: no blank lines between categories.
-
enumerator PreferPairs¶
Write single-row loops as pairs.
-
enumerator Pdbx¶
PreferPairs + put ‘#’ (empty comments) between categories.
-
enumerator Indent35¶
Start values in pairs from 35th column.
-
enumerator Aligned¶
Align columns in loops to fixed width.
-
enumerator Simple¶
Functions
-
inline void write_text_field(BufOstream &os, const std::string &value)¶
Write a text field, normalizing \r\n to \n.
- Parameters:
os – Buffered output stream
value – The text field value to write
-
inline void write_out_pair(BufOstream &os, const std::string &name, const std::string &value, WriteOptions options)¶
-
inline void write_out_loop(BufOstream &os, const Loop &loop, WriteOptions options)¶
-
inline void write_out_item(BufOstream &os, const Item &item, WriteOptions options)¶
-
inline void write_cif_block_to_stream(std::ostream &os_, const Block &block, WriteOptions options = WriteOptions())¶
Write a single CIF block to an output stream.
Writes a CIF data block with the specified formatting options.
- Parameters:
os_ – Output stream to write to
block – The CIF block to write
options – Formatting options (see WriteOptions documentation)
-
inline void write_cif_to_stream(std::ostream &os, const Document &doc, WriteOptions options = WriteOptions())¶
Write a CIF document to an output stream.
Writes a complete CIF document with all its blocks, using the specified formatting options. Blocks are separated by blank lines for readability.
- Parameters:
os – Output stream to write to
doc – The CIF document to write
options – Formatting options (see WriteOptions documentation)
-
class BufOstream¶
- #include <gemmi/to_cif.hpp>
Buffered output stream wrapper for efficient CIF writing.
Wraps std::ostream with a 4KB buffer to significantly improve I/O performance when writing CIF documents. The buffer is automatically flushed on destruction and when it fills.
Public Functions
-
inline explicit BufOstream(std::ostream &os_)¶
Construct a buffered output stream.
- Parameters:
os_ – The underlying std::ostream to write to
-
inline ~BufOstream()¶
Destructor flushes remaining buffered data.
-
inline void flush()¶
Flush all buffered data to the underlying stream.
-
inline void write(const char *s, size_t len)¶
Write data to the buffer, flushing if necessary.
- Parameters:
s – Pointer to data to write
len – Number of bytes to write
-
inline void operator<<(const std::string &s)¶
Write a string to the buffer.
- Parameters:
s – The string to write
-
inline void put(char c)¶
Write a single character to the buffer.
- Parameters:
c – The character to write
-
inline void pad(size_t n)¶
Write n space characters to the buffer (for padding/alignment).
- Parameters:
n – Number of spaces to write
-
inline explicit BufOstream(std::ostream &os_)¶
-
struct WriteOptions¶
- #include <gemmi/to_cif.hpp>
Options for writing CIF output.
Controls formatting, alignment, and output style of CIF documents.
Public Functions
-
inline WriteOptions()¶
Public Members
-
bool prefer_pairs = false¶
Write single-row loops as tag-value pairs instead of loop constructs.
-
bool compact = false¶
Omit blank lines between categories (keep only between blocks).
-
bool misuse_hash = false¶
Insert ‘#’ (empty comment lines) before and after categories. This is a non-standard CIF extension.
-
inline WriteOptions()¶
-
namespace cif
Writing CIF documents as JSON (mmJSON and CIF-JSON formats).
-
namespace gemmi
-
namespace cif
Read CIF data from a string.
This function was moved here from cif.hpp to speed up compilation.
- Param data:
CIF-formatted string
- Param check_level:
Syntax checking level (0=none, 1=moderate, 2=strict)
- Return:
Parsed CIF document
Functions
-
void write_json_to_stream(std::ostream &os, const Document &doc, const JsonWriteOptions &options)¶
Write a CIF document as JSON to an output stream.
Serializes a CIF document in JSON format according to the specified options. See JsonWriteOptions for details on supported formats and customization.
- Parameters:
os – Output stream to write to
doc – The CIF document to write
options – Formatting and format selection options
-
inline void write_mmjson_to_stream(std::ostream &os, const Document &doc)¶
Write a CIF document as mmJSON (PDBj macromolecular JSON) to an output stream.
Convenience function equivalent to:
write_json_to_stream(os, doc, JsonWriteOptions::mmjson());
- Parameters:
os – Output stream to write to
doc – The CIF document to write
-
struct JsonWriteOptions¶
- #include <gemmi/to_json.hpp>
Options for writing CIF data as JSON.
Supports multiple JSON-based serialization formats for CIF data:
CIF-JSON (COMCIFS): Standard JSON representation of CIF documents, supporting numbered values with uncertainties.
mmJSON (PDBj): Specialized JSON format optimized for macromolecular CIF (mmCIF) data, with DDL2 category grouping and bare tags.
Choose between preset configurations (comcifs() or mmjson()) or configure individual options for custom output.
Public Members
-
bool as_comcifs = false¶
Conform to the COMCIFS CIF-JSON draft specification. If true, enables values_as_arrays, sets quote_numbers=2, and cif_dot=”false”.
-
bool group_ddl2_categories = false¶
Group items by DDL2 categories (for mmJSON compatibility). Relevant mainly for mmJSON format.
-
bool with_data_keyword = false¶
Include the mmJSON “data_” keyword wrapper. Used in mmJSON format output.
-
bool bare_tags = false¶
Use bare tag names (e.g., “tag” instead of “_tag”). Used in mmJSON and other compact formats.
-
bool values_as_arrays = false¶
Represent all values as JSON arrays (e.g., “_tag”: [“value”]). Used in COMCIFS CIF-JSON and mmJSON; disabled if false.
-
bool lowercase_names = true¶
Write case-insensitive tag names in lowercase. CIF tag names are case-insensitive; this normalizes them.
-
int quote_numbers = 1¶
Control quoting of numeric values with uncertainty (s.u.).
0: Never quote numbers; s.u. information is lost (used for mmJSON)
1: Quote numbers only when they include s.u. (default, mixed mode)
2: Always quote numbers as strings (used for COMCIFS)
Public Static Functions
-
static inline JsonWriteOptions comcifs()¶
Preset options for COMCIFS CIF-JSON format.
- Returns:
JsonWriteOptions configured for standard CIF-JSON output
-
static inline JsonWriteOptions mmjson()¶
Preset options for mmJSON format (PDBj macromolecular JSON).
mmJSON is used by PDBj for macromolecular structures. It groups data by DDL2 categories and uses bare tag names.
- Returns:
JsonWriteOptions configured for mmJSON output
-
namespace cif
Reading JSON formats (mmJSON and CIF-JSON) into CIF documents.
-
namespace gemmi
-
namespace cif
Read CIF data from a string.
This function was moved here from cif.hpp to speed up compilation.
- Param data:
CIF-formatted string
- Param check_level:
Syntax checking level (0=none, 1=moderate, 2=strict)
- Return:
Parsed CIF document
Functions
-
Document read_mmjson_insitu(char *buffer, std::size_t size, const std::string &name = "mmJSON")¶
Parse mmJSON format from a buffer (with in-place mutation).
mmJSON is the macromolecular JSON format used by PDBj for structure data. This function parses JSON in-place, modifying the input buffer as a side effect for efficiency. If you need to preserve the original buffer, make a copy first.
- Parameters:
buffer – Pointer to buffer containing mmJSON data (will be modified)
size – Number of bytes in the buffer
name – Optional source name for error messages (default: “mmJSON”)
- Returns:
Parsed CIF document
-
inline Document read_mmjson_file(const std::string &path)¶
Read and parse an mmJSON file from disk.
Convenience function that loads the file into memory and parses it. The entire file is read into a buffer for parsing.
- Parameters:
path – Path to the mmJSON file (may end with .gz for gzip compression)
- Returns:
Parsed CIF document
-
template<typename T>
Document read_mmjson(T &&input)¶ Read and parse mmJSON from an input source (file or stream).
Template function supporting both file paths and stream inputs. Reads data from the input source into a buffer, then parses.
- Template Parameters:
T – An input type with is_stdin() and path() methods
- Parameters:
input – The input source to read from
- Returns:
Parsed CIF document
-
namespace cif
Parsing CIF numeric values (numb) with optional standard uncertainty.
-
namespace gemmi
-
namespace cif
Read CIF data from a string.
This function was moved here from cif.hpp to speed up compilation.
- Param data:
CIF-formatted string
- Param check_level:
Syntax checking level (0=none, 1=moderate, 2=strict)
- Return:
Parsed CIF document
Functions
-
inline bool is_numb(const std::string &s)¶
Check if a string represents a valid CIF numeric value (numb).
- Parameters:
s – String to check
- Returns:
true if the string is a valid CIF number, false otherwise
-
namespace cif
DDL1/DDL2 dictionary-based validation of CIF and mmCIF files.
-
namespace gemmi
-
namespace cif
Read CIF data from a string.
This function was moved here from cif.hpp to speed up compilation.
- Param data:
CIF-formatted string
- Param check_level:
Syntax checking level (0=none, 1=moderate, 2=strict)
- Return:
Parsed CIF document
-
struct Ddl¶
- #include <gemmi/ddl.hpp>
Represents a CIF dictionary (DDL1 or DDL2 ontology) for validation.
A DDL (Data Definition Language) dictionary defines the structure, constraints, and validation rules for CIF data. This class can load and use either:
DDL1 dictionaries (IUCr core, chemical structures)
DDL2 dictionaries (macromolecular CIF / mmCIF, used by PDB)
After loading a dictionary with read_ddl(), you can validate CIF documents against it to check for missing mandatory items, type violations, enumeration violations, unique key violations, and other data integrity issues.
Public Functions
-
Ddl() = default¶
-
void read_ddl(cif::Document &&doc)¶
Load a DDL dictionary into this validator.
Parses a DDL1 or DDL2 dictionary document and indexes it for validation. The document is moved into internal storage to manage its lifetime. The dictionary version (DDL1 or DDL2) is auto-detected.
Configuration flags (e.g., use_mandatory, use_regex) should be set before calling this function.
- Parameters:
doc – CIF document containing a DDL dictionary (will be moved)
-
bool validate_cif(const cif::Document &doc) const¶
Validate all blocks in a CIF document against this dictionary.
Checks all blocks in the document and reports validation errors via the configured logger.
See also
validate_block() to validate individual blocks
- Parameters:
doc – The CIF document to validate
- Returns:
true if validation passes, false if errors are found
-
bool validate_block(const cif::Block &b, const std::string &source) const¶
Validate a single CIF block against this dictionary.
Performs all enabled validation checks on the block:
Mandatory items (if use_mandatory=true)
Item types and enumeration values
Regular expression patterns (if use_regex=true)
Unique keys (if use_unique_keys=true)
Parent-child relationships (if use_parents=true)
Unknown tags (if print_unknown_tags=true)
- Parameters:
b – The CIF block to validate
source – Source identifier for error messages (e.g., block name or filename)
- Returns:
true if validation passes, false if errors are found
-
void check_audit_conform(const cif::Document &doc) const¶
Check audit conformance fields in a CIF document.
Verifies that the document’s audit records match dictionary expectations (e.g., _audit_conform_dict_name, _audit_conform_dict_version). Reports mismatches via the logger.
- Parameters:
doc – The CIF document to check
Public Members
-
Logger logger¶
Logger for validation messages and warnings. Member functions use this logger’s callback and threshold settings for output.
-
bool print_unknown_tags = true¶
Report unknown tags (tags not defined in the dictionary). Useful for catching typos in tag names.
-
bool use_regex = true¶
Enable validation using regular expression patterns (DDL2 _item_type.code).
-
bool use_context = false¶
Use context-dependent validation rules (DDL2). If true, validates items in specific category contexts.
-
bool use_parents = false¶
Use parent-child item relationships (DDL2 _item_linked). If true, enforces dependencies between items.
-
bool use_mandatory = true¶
Validate mandatory items (DDL2 _item.mandatory_code). If true, reports missing items marked as mandatory.
-
bool use_unique_keys = true¶
Validate unique keys in loops (DDL2 _item_linked.key_id). If true, checks that unique key values don’t repeat.
-
bool use_deposition_checks = false¶
Use PDBx deposition-specific validation checks. If true, uses _pdbx-prefixed dictionary items instead of standard ones (_pdbx_item_type.code instead of _item_type.code, etc.). This mode is typically used during structure deposition to PDB.
-
int major_version = 0¶
Major version of the loaded DDL (1 or 2). Read from _dictionary_version or similar field in the dictionary.
Private Functions
-
void check_parent_link(const ParentLink &link, const cif::Block &b) const¶
Private Members
-
std::vector<ParentLink> parents_¶
-
struct ParentLink¶
Internal representation of DDL2 parent-child item relationships.
Links parent and child tags that must be coordinated in the data. Used for enforcing referential integrity (use_parents=true).
-
namespace cif
Structure I/O¶
(Full documentation added in PR 4.)
Read mmCIF (PDBx/mmCIF) coordinate files into a Structure.
-
namespace gemmi
Enums
-
enum class ChemCompModel¶
Selects which coordinate model(s) to read from chemical component files. Used when reading CCD (Chemical Component Dictionary) or monomer library entries.
Values:
-
enumerator Xyz¶
Cartesian coordinates from _chem_comp_atom.x/y/z fields.
-
enumerator Example¶
Example model coordinates from _chem_comp_atom.model_Cartn_x/y/z.
-
enumerator Ideal¶
Ideal coordinates from _chem_comp_atom.pdbx_model_Cartn_x/y/z_ideal.
-
enumerator First¶
Whichever coordinate set appears first in the input file.
-
enumerator Xyz¶
Functions
-
void populate_structure_from_block(const cif::Block &block_, Structure &st)¶
Populate Structure by parsing a coordinate mmCIF block.
- Parameters:
block_ – A CIF block containing the coordinate data (typically from an mmCIF file, containing _atom_site categories)
st – The Structure to populate with coordinates, cell parameters, and other crystallographic data
- Throws:
Throws – on parse errors or invalid coordinate data
-
inline Structure make_structure_from_block(const cif::Block &block_)¶
Build a Structure by parsing a coordinate mmCIF block. Convenience wrapper around populate_structure_from_block().
- Parameters:
block_ – A CIF block containing the coordinate data
- Returns:
A new Structure populated from the block
-
inline Structure make_structure(cif::Document &&doc, cif::Document *save_doc = nullptr)¶
Build a Structure from a parsed mmCIF document. Parses the first block (coordinate block) and validates that only the first block contains atomic coordinates.
- Parameters:
doc – A CIF document (typically mmCIF); moved into this function
save_doc – Optional pointer to receive the parsed document (moved into *save_doc)
- Throws:
Throws – if multiple blocks contain atomic coordinates (_atom_site)
- Returns:
A Structure populated from the first block of the document
-
constexpr int operator|(ChemCompModel a, ChemCompModel b)¶
-
Residue make_residue_from_chemcomp_block(const cif::Block &block, ChemCompModel kind)¶
Extract a Residue from a chemical component block. Reads atom coordinates and bond information from a CCD or monomer library block.
- Parameters:
block – The CIF block containing chemical component data
kind – Which coordinate model to extract (Xyz, Example, Ideal, or First)
- Returns:
A Residue with atoms positioned according to the selected model
-
inline Model make_model_from_chemcomp_block(const cif::Block &block, ChemCompModel kind)¶
Build a single-residue Model from a chemical component block. Convenience wrapper that creates a Model with an unnamed chain containing a single Residue extracted from the block.
- Parameters:
block – The CIF block containing chemical component data
kind – Which coordinate model to extract
- Returns:
A Model with one empty chain containing one Residue
-
inline Structure make_structure_from_chemcomp_block(const cif::Block &block, int which = 7)¶
Build a Structure from a chemical component block. For CCD input, generates a structure with multiple single-residue models (xyz, example, and/or ideal coordinates as requested). For Refmac monomer library (dictionary) files, generates a single model. The structure’s input_format is set to CoorFormat::ChemComp.
- Parameters:
block – Which CIF block to parse (typically the chemical component block)
which – Bitmask of ChemCompModel values to include; default 7 = Xyz|Example|Ideal
- Returns:
A Structure containing the requested coordinate models
-
inline int check_chemcomp_block_number(const cif::Document &doc)¶
Identify which block in a document contains chemical component data. Helper for make_structure_from_chemcomp_block(); distinguishes between three file formats: monomer library with/without global block, and CCD files. Example usage:
int n = check_chemcomp_block_number(doc); if (n != -1) Structure st = make_structure_from_chemcomp_block(doc.blocks[n]);
- Parameters:
doc – A parsed CIF document
- Returns:
Block index (0, 1, or 2) if recognized as chemical component file; -1 if not a recognized chemical component format
-
inline Structure make_structure_from_chemcomp_doc(const cif::Document &doc, cif::Document *save_doc = nullptr, int which = 7)¶
Build a Structure from a chemical component document. Automatically detects and parses the appropriate block in a chemical component file (CCD, monomer library with/without global block).
- Parameters:
doc – A parsed chemical component CIF document
save_doc – Optional pointer to receive the parsed document (moved into *save_doc)
which – Bitmask of ChemCompModel values to include; default 7 = all
- Throws:
Throws – if the document is not a recognized chemical component format
- Returns:
A Structure with the requested coordinate models
-
enum class ChemCompModel¶
Auto-detect and read any supported coordinate file format (PDB, mmCIF, mmJSON, or chemical component).
-
namespace gemmi
Functions
-
inline CoorFormat coor_format_from_ext(const std::string &path)¶
Detect file format from filename extension.
- Parameters:
path – File path or name
- Returns:
Detected format (Pdb, Mmcif, Mmjson) or Unknown if no match
-
inline CoorFormat coor_format_from_content(const char *buf, const char *end)¶
Detect file format by examining file content. Heuristic detection based on content: looks for JSON ‘{’, CIF ‘data_’, or falls back to PDB format if neither is found.
- Parameters:
buf – Pointer to buffer start
end – Pointer to buffer end
- Returns:
Detected format (Pdb, Mmcif, Mmjson) or Unknown if buffer too small
-
inline Structure make_structure_from_doc(cif::Document &&doc, bool possible_chemcomp, cif::Document *save_doc = nullptr)¶
Build Structure from a CIF document, optionally detecting chemical components. If possible_chemcomp is true, checks whether the document is a chemical component file and parses it accordingly; otherwise treats as normal mmCIF.
- Parameters:
doc – A CIF document; moved into this function
possible_chemcomp – If true, check for and handle CCD/monomer library files
save_doc – Optional pointer to receive the document; only populated if the input is mmCIF (not a chemical component)
- Returns:
A Structure parsed from the document
-
inline Structure read_structure_from_memory(char *data, size_t size, const std::string &path, CoorFormat format = CoorFormat::Unknown, cif::Document *save_doc = nullptr)¶
Read a Structure from a memory buffer. Detects or uses specified format to parse the buffer. Note: When reading JSON, the input buffer is modified in-place (optimization).
- Parameters:
data – Pointer to file data; may be modified if JSON format
size – Size of data buffer in bytes
path – File path or name (used for error messages and format detection)
format – File format (Unknown = auto-detect, Detect = content-based detection)
save_doc – Optional pointer to receive the parsed CIF document
- Throws:
Throws – on parse errors or if format cannot be determined
- Returns:
A Structure parsed from the buffer
-
inline Structure read_structure_from_char_array(char *data, size_t size, const std::string &path, cif::Document *save_doc = nullptr)¶
- Deprecated:
Use read_structure_from_memory() instead. Read a Structure from a character array buffer.
- Parameters:
data – Pointer to file data
size – Size of data buffer in bytes
path – File path or name
save_doc – Optional pointer to receive the parsed CIF document
- Returns:
A Structure parsed from the buffer with format auto-detected
-
template<typename T>
Structure read_structure(T &&input, CoorFormat format = CoorFormat::Unknown, cif::Document *save_doc = nullptr)¶ Read a Structure from an input source.
- Template Parameters:
T – Input type (e.g., BasicInput, FileStream) with path() and create_stream() Generic template that works with file paths, streams, and memory sources. Optionally detects format from filename extension or content.
- Parameters:
input – Input source; format is inferred from extension or content
format – File format to use: Unknown (detect by extension), Detect (load entire file and detect by content), or explicit format (Pdb, Mmcif, Mmjson, ChemComp)
save_doc – Optional pointer to receive the parsed CIF document
- Throws:
Throws – on I/O errors, parse errors, or if format cannot be determined
- Returns:
A Structure parsed from the input
-
inline Structure read_structure_file(const std::string &path, CoorFormat format = CoorFormat::Unknown)¶
Read a Structure from a file. Convenience wrapper for read_structure() with a file path. Format is detected from filename extension by default.
- Parameters:
path – Path to coordinate file
format – File format to use: Unknown (detect by extension) or explicit format
- Throws:
Throws – on I/O or parse errors
- Returns:
A Structure parsed from the file
-
inline CoorFormat coor_format_from_ext(const std::string &path)¶
Read coordinate files with optional gzip decompression.
-
namespace gemmi
Functions
-
Structure read_structure_gz(const std::string &path, CoorFormat format = CoorFormat::Unknown, cif::Document *save_doc = nullptr)¶
Read a Structure from a potentially gzip-compressed coordinate file. Detects gzip format from filename (.gz extension) or file content, decompresses if needed, then parses using the appropriate handler.
- Parameters:
path – Path to coordinate file (may have .gz suffix)
format – File format (Unknown = auto-detect from filename or content; Detect = force content-based detection after decompression)
save_doc – Optional pointer to receive the parsed CIF document
- Throws:
Throws – on I/O or parse errors
- Returns:
A Structure parsed from the file
-
Structure read_pdb_gz(const std::string &path, PdbReadOptions options = PdbReadOptions())¶
Read a PDB-format Structure from a potentially gzip-compressed file.
- Parameters:
path – Path to PDB file (may have .gz suffix)
options – Parsing options (max line length, handling of TER records, etc.)
- Throws:
Throws – on I/O or parse errors
- Returns:
A Structure parsed from the PDB file
-
Structure read_structure_from_chemcomp_gz(const std::string &path, cif::Document *save_doc = nullptr, int which = 7)¶
Read a chemical component Structure from a potentially gzip-compressed file.
- Parameters:
path – Path to chemical component file (may have .gz suffix)
save_doc – Optional pointer to receive the parsed CIF document
which – Bitmask of ChemCompModel values to include (default 7 = all)
- Throws:
Throws – on I/O or parse errors, or if not a valid chemical component file
- Returns:
A Structure with the requested coordinate models
-
CoorFormat coor_format_from_ext_gz(const std::string &path)¶
Detect file format from a filename, accounting for gzip compression. Strips .gz suffix if present before checking file extension.
- Parameters:
path – File path or name
- Returns:
Detected format (Pdb, Mmcif, Mmjson) or Unknown if no match
-
namespace cif
Read CIF data from a string.
This function was moved here from cif.hpp to speed up compilation.
- Param data:
CIF-formatted string
- Param check_level:
Syntax checking level (0=none, 1=moderate, 2=strict)
- Return:
Parsed CIF document
-
Structure read_structure_gz(const std::string &path, CoorFormat format = CoorFormat::Unknown, cif::Document *save_doc = nullptr)¶
Read PDB file format and store coordinates in a Structure.
Implements PDB format parsing per the wwPDB specification v3.3: https://www.wwpdb.org/documentation/file-format-content/format33/v3.3.html
Enhancements beyond standard PDB:
Two-character chain IDs (columns 21-22)
Segment ID parsing (columns 73-76)
Hybrid-36 serial numbers for > 99,999 atoms
Hybrid-36 sequence IDs for sequences > 9,999 residues
Extended REMARK lines (up to 120 characters)
-
namespace gemmi
Functions
-
inline bool is_record_type4(const char *s, const char *record)¶
Test if the first 4 columns of a PDB record match a given record type. Case-insensitive comparison; space and NUL characters in s are treated as equivalent for matching purposes.
- Parameters:
s – PDB record line (must have >= 4 characters)
record – Uppercase record name to match (e.g., “ATOM”, “HETATM”)
- Returns:
True if the record names match
-
inline bool is_record_type3(const char *s, const char *record)¶
Test if the first 3 columns of a PDB record match a given record type. Used for 3-character records like TER where the 4th character varies. Matches “TER “, “TER\n”, “TER\r”, “TER\t” but not “TERE” or “TER1”.
- Parameters:
s – PDB record line (must have >= 4 characters)
record – Uppercase record name to match (e.g., “TER”, “END”)
- Returns:
True if the first 3 characters of the record match
-
std::vector<Op> read_remark_290(const std::vector<std::string> &raw_remarks)¶
Parse REMARK 290 records to extract crystallographic symmetry operations. REMARK 290 contains the rotation and translation operators (NCS or crystal symmetry). Parses operations in triplet notation (e.g., “X,Y,Z” or “-X,-Y,-Z+1/2”).
- Parameters:
raw_remarks – Vector of PDB REMARK record lines
- Returns:
Vector of crystallographic operations (Op structures with rotation matrix and translation vector)
-
void populate_structure_from_pdb_stream(AnyStream &line_reader, const std::string &source, Structure &st, PdbReadOptions options)¶
Populate a Structure by parsing a PDB stream. Parses all ATOM/HETATM records and metadata from the stream, populating the Structure with models, chains, residues, and atoms.
- Parameters:
line_reader – Stream to read PDB records from
source – Source name/path (used in error messages)
st – Structure to populate with parsed coordinates
options – Parsing options (line length, TER handling, skip remarks, etc.)
- Throws:
Throws – on parse errors or invalid records
-
inline void populate_structure_from_pdb_memory(const char *data, size_t size, const std::string &name, Structure &st, PdbReadOptions options = {})¶
Populate a Structure by parsing PDB data from a memory buffer. Convenience wrapper around populate_structure_from_pdb_stream().
- Parameters:
data – Pointer to PDB file contents
size – Size of the buffer in bytes
name – Source name/path (used in error messages)
st – Structure to populate with parsed coordinates
options – Parsing options; defaults to standard PDB settings
- Throws:
Throws – on parse errors or invalid records
-
inline void populate_structure_from_pdb_string(const std::string &str, const std::string &name, Structure &st, PdbReadOptions options = {})¶
Populate a Structure by parsing PDB data from a string. Convenience wrapper around populate_structure_from_pdb_memory().
- Parameters:
str – String containing PDB file contents
name – Source name/path (used in error messages)
st – Structure to populate with parsed coordinates
options – Parsing options; defaults to standard PDB settings
- Throws:
Throws – on parse errors or invalid records
-
inline Structure read_pdb_from_stream(AnyStream &line_reader, const std::string &source, PdbReadOptions options)¶
Read a Structure from a PDB stream. Convenience wrapper around populate_structure_from_pdb_stream().
- Parameters:
line_reader – Stream to read PDB records from
source – Source name/path (used in error messages)
options – Parsing options (line length, TER handling, skip remarks, etc.)
- Throws:
Throws – on parse errors or invalid records
- Returns:
A new Structure parsed from the PDB stream
-
inline Structure read_pdb_file(const std::string &path, PdbReadOptions options = {})¶
Read a Structure from a PDB file.
- Parameters:
path – Path to PDB file
options – Parsing options; defaults to standard PDB settings
- Throws:
Throws – on I/O or parse errors
- Returns:
A new Structure parsed from the file
-
inline Structure read_pdb_from_memory(const char *data, size_t size, const std::string &name, PdbReadOptions options = {})¶
Read a Structure from a PDB-format memory buffer.
- Parameters:
data – Pointer to PDB file contents
size – Size of the buffer in bytes
name – Source name/path (used in error messages)
options – Parsing options; defaults to standard PDB settings
- Throws:
Throws – on parse errors or invalid records
- Returns:
A new Structure parsed from the buffer
-
inline Structure read_pdb_string(const std::string &str, const std::string &name, PdbReadOptions options = {})¶
Read a Structure from a PDB-format string.
- Parameters:
str – String containing PDB file contents
name – Source name/path (used in error messages)
options – Parsing options; defaults to standard PDB settings
- Throws:
Throws – on parse errors or invalid records
- Returns:
A new Structure parsed from the string
-
template<typename T>
inline Structure read_pdb(T &&input, PdbReadOptions options = {})¶ Read a Structure from a PDB input source.
- Template Parameters:
T – Input type (e.g., BasicInput, FileStream) with path() and create_stream() Generic template for file paths, streams, and other input types.
- Parameters:
input – Input source
options – Parsing options; defaults to standard PDB settings
- Throws:
Throws – on I/O or parse errors
- Returns:
A new Structure parsed from the input
-
inline bool is_record_type4(const char *s, const char *record)¶
Serialization of Structure to mmCIF/PDBx format.
-
namespace gemmi
Functions
-
void update_mmcif_block(const Structure &st, cif::Block &block, MmcifOutputGroups groups = MmcifOutputGroups(true))¶
Populate an existing mmCIF block with data from a Structure.
- Parameters:
st – The Structure to serialize.
block – The mmCIF block to populate (typically obtained from make_mmcif_block()).
groups – Selectively enable/disable categories to write.
-
cif::Document make_mmcif_document(const Structure &st, MmcifOutputGroups groups = MmcifOutputGroups(true))¶
Create a complete mmCIF/PDBx document from a Structure.
- Parameters:
st – The Structure to serialize.
groups – Selectively enable/disable categories to write.
- Returns:
A cif::Document containing a single block with all structural information.
-
cif::Block make_mmcif_block(const Structure &st, MmcifOutputGroups groups = MmcifOutputGroups(true))¶
Create an mmCIF/PDBx block from a Structure.
- Parameters:
st – The Structure to serialize.
groups – Selectively enable/disable categories to write.
- Returns:
A cif::Block containing all selected categories.
-
cif::Block make_mmcif_headers(const Structure &st)¶
Create an mmCIF block with structural metadata and headers only.
- Parameters:
st – The Structure whose metadata to serialize.
- Returns:
A cif::Block containing metadata without atomic coordinates (_atom_site).
-
void add_minimal_mmcif_data(const Structure &st, cif::Block &block)¶
Add minimal mmCIF category items required for valid output.
- Parameters:
st – The Structure to serialize.
block – The mmCIF block to populate with essential items.
-
void write_ncs_oper(const Structure &st, cif::Block &block)¶
Write NCS (non-crystallographic symmetry) operations to an mmCIF block.
- Parameters:
st – The Structure containing NCS operations.
block – The mmCIF block to populate.
-
void write_struct_conn(const Structure &st, cif::Block &block)¶
Write chemical connectivity information to an mmCIF block.
- Parameters:
st – The Structure containing connection definitions.
block – The mmCIF block to populate with _struct_conn items.
-
struct MmcifOutputGroups¶
- #include <gemmi/to_mmcif.hpp>
Control which mmCIF data groups to write to the output.
This struct uses bit-fields to selectively enable/disable writing of individual data blocks and categories in mmCIF output. Each member corresponds to a major category in the PDBx/mmCIF dictionary.
Public Functions
-
inline explicit MmcifOutputGroups(bool all)¶
Constructor initializing all groups to the same value.
- Parameters:
all – Set all groups to true (write everything) or false (write nothing).
Public Members
-
bool atoms¶
Write atom site coordinates (_atom_site category).
-
bool block_name¶
Write data block name (_entry.id).
-
bool entry¶
Write entry metadata (database code, PDB ID).
-
bool database_status¶
Write database status information.
-
bool author¶
Write author information (_audit_author category).
-
bool cell¶
Write unit cell parameters (_cell category).
-
bool symmetry¶
Write crystal symmetry (_symmetry category).
-
bool entity¶
Write entity definitions (_entity category).
-
bool entity_poly¶
Write polymer entity descriptions (_entity_poly category).
-
bool struct_ref¶
Write structural reference information (_struct_ref category).
-
bool chem_comp¶
Write chemical component information (_chem_comp category).
-
bool exptl¶
Write experimental method details (_exptl category).
-
bool diffrn¶
Write diffraction data (_diffrn category).
-
bool reflns¶
Write reflection statistics (_reflns category).
-
bool refine¶
Write refinement details (_refine category).
-
bool title_keywords¶
Write title and keywords.
-
bool ncs¶
Write NCS (non-crystallographic symmetry) operations.
-
bool struct_asym¶
Write structural asymmetric unit information (_struct_asym category).
-
bool origx¶
Write crystal to fractional coordinate transformation (ORIGX).
-
bool struct_conf¶
Write secondary structure definitions (_struct_conf category).
-
bool struct_sheet¶
Write beta sheet information (_struct_sheet category).
-
bool struct_biol¶
Write biological assembly metadata (_struct_biol category).
-
bool assembly¶
Write pdbx_struct_assembly transformations.
-
bool conn¶
Write chemical bond connectivity (_struct_conn category).
-
bool cis¶
Write cis-peptide information (_struct_mon_prot_cis category).
-
bool modres¶
Write modified residues (_pdbx_chem_comp_atom_feature for non-standard residues).
-
bool struct_site¶
Write binding site information (_struct_site category).
-
bool scale¶
Write matrix scale transformations (_atom_sites_fract_tran category).
-
bool atom_type¶
Write atom type scattering info (_atom_type category).
-
bool entity_poly_seq¶
Write polymer sequence information (_entity_poly_seq category).
-
bool tls¶
Write TLS tensor information (thermal tensor correction).
-
bool software¶
Write software used in structure processing (_software category).
-
bool group_pdb¶
Write _atom_site.group_PDB field (ATOM/HETATM classification).
-
bool auth_all¶
Write authentic atom and component IDs (_atom_site.auth_atom_id and auth_comp_id).
-
inline explicit MmcifOutputGroups(bool all)¶
-
void update_mmcif_block(const Structure &st, cif::Block &block, MmcifOutputGroups groups = MmcifOutputGroups(true))¶
Serialization of Structure to PDB fixed-column format.
-
namespace gemmi
Functions
-
bool use_hetatm(const Residue &res)¶
Determine the PDB record type (ATOM or HETATM) for a given residue.
Uses residue flags and entity type to determine appropriate record type:
Residues marked ‘H’ (het flag) use HETATM.
Standard polymeric residues use ATOM.
Branched, non-polymer, and water residues use HETATM.
- Parameters:
res – The residue to classify.
- Returns:
true if HETATM should be used, false for ATOM.
-
void write_pdb(const Structure &st, std::ostream &os, PdbWriteOptions opt = {})¶
Write a Structure to PDB format on an output stream.
- Parameters:
st – The Structure to serialize.
os – The output stream to write to.
opt – Options controlling record types and formatting.
-
std::string make_pdb_string(const Structure &st, PdbWriteOptions opt = {})¶
Serialize a Structure to a PDB format string.
- Parameters:
st – The Structure to serialize.
opt – Options controlling record types and formatting.
- Returns:
A std::string containing the complete PDB format output.
-
inline void write_minimal_pdb(const Structure &st, std::ostream &os)¶
Write minimal PDB output (atomic records only, no headers).
- Deprecated:
Use write_pdb(st, os, PdbWriteOptions::minimal()) instead.
- Parameters:
st – The Structure to serialize.
os – The output stream to write to.
-
inline std::string make_pdb_headers(const Structure &st)¶
Generate PDB header records only (no atomic coordinates).
- Deprecated:
Use make_pdb_string(st, PdbWriteOptions::headers_only()) instead.
- Parameters:
st – The Structure whose headers to serialize.
- Returns:
A std::string containing PDB header records.
-
struct PdbWriteOptions¶
- #include <gemmi/to_pdb.hpp>
Control record types and fields written in PDB output.
Options to selectively enable/disable PDB record types and special formatting modes when writing Structure to PDB format.
Public Members
-
bool minimal_file = false¶
Minimize output by omitting ancillary records (HEADER, TITLE, REMARK, etc.).
-
bool atom_records = true¶
Write ATOM/HETATM records with coordinates. If false, omit atomic models.
-
bool seqres_records = true¶
Write SEQRES records with polymer sequences.
-
bool ssbond_records = true¶
Write SSBOND records (disulfide bonds between cysteines).
-
bool link_records = true¶
Write LINK records for non-disulfide chemical bonds.
-
bool cispep_records = true¶
Write CISPEP records for cis-peptide bonds.
-
bool cryst1_record = true¶
Write CRYST1 record with unit cell and space group information.
-
bool ter_records = true¶
Write TER records to mark chain terminations.
-
bool conect_records = false¶
Write CONECT records for inter-residue connectivity (requires add_conect() preprocessing).
-
bool end_record = true¶
Write END record at end of file.
-
bool numbered_ter = true¶
Assign own serial numbers to TER records if true; reuse ATOM serial if false.
-
bool ter_ignores_type = false¶
If true, place TER after the last atom in each chain regardless of residue type. If false, omit TER after water/heteroatom chains.
-
bool use_linkr = false¶
Use non-standard Refmac LINKR record instead of standard LINK record.
-
bool use_link_id = false¶
Write Link::link_id field in LINK record instead of distance (if link_id is non-empty). Automatically enabled by use_linkr.
-
bool preserve_serial = false¶
Use atom serial numbers from Atom::serial. If false, generate new serial numbers.
Public Static Functions
-
static inline PdbWriteOptions minimal()¶
Factory method: create options for minimal output.
- Returns:
Options with only ATOM records and minimal header information.
-
static inline PdbWriteOptions headers_only()¶
Factory method: create options to write header records only (no atomic coordinates).
- Returns:
Options with atom_records disabled and no END record.
-
bool minimal_file = false¶
-
bool use_hetatm(const Residue &res)¶
Preparation of molecular structures for Refmac refinement (CRD format generation).
-
namespace gemmi
Functions
-
void setup_for_crd(Structure &st)¶
Prepare a Structure for CRD file output.
Sets up entities, assigns subchains, and ensures proper formatting for Refmac input:
Adds entity type and ID information.
Forces subchain assignment.
Adjusts subchain names to Refmac conventions (using ‘_’ as separator).
Normalizes all water residues to “HOH”.
Deduplicates and validates entity definitions.
- Parameters:
st – The Structure to prepare (modified in-place).
-
void add_automatic_links(Model &model, Structure &st, const MonLib &monlib)¶
Identify and add missing chemical bonds using a monomer library.
Searches for atoms within bonding distance and, when not already defined as connections in the structure, attempts to match them against the monomer library. Automatically adds Connection records for metals coordinated to O, N, S, B.
- Parameters:
model – The Model containing atoms to search.
st – The Structure whose connections will be updated.
monlib – The MonLib (monomer library) for matching link definitions.
-
void add_dictionary_blocks(cif::Document &doc, const std::vector<std::string> &resnames, const Topo &topo, const MonLib &monlib)¶
Add chemical component dictionary blocks to a CIF document.
Appends _chem_comp blocks for specified residue types extracted from the topology and monomer library. Used to embed component definitions in Refmac CRD files.
- Parameters:
doc – The cif::Document to append blocks to.
resnames – List of residue names (component IDs) to include.
topo – The Topo containing topology information.
monlib – The MonLib containing chemical component definitions.
-
cif::Document prepare_refmac_crd(Structure &st, const Topo &topo, const MonLib &monlib, HydrogenChange h_change)¶
Generate a complete Refmac CRD (coordinate) file as a CIF document.
Creates a comprehensive CIF document suitable for Refmac input, including:
Structure metadata (entry ID, cell, space group, symmetry).
Entity and sequence definitions.
Atomic coordinates with topology-derived labels.
NCS operations, structural connectivity, cis-peptides.
Optional anisotropic displacement parameters.
Hydrogen handling flags based on h_change parameter.
The Structure is modified: shorten_ccd_codes() is called to abbreviate component IDs for Refmac compatibility.
- Parameters:
- Returns:
A cif::Document containing the prepared CRD file structure.
-
void setup_for_crd(Structure &st)¶
Reading and writing small-molecule CIF files into SmallStructure format.
Copyright 2018 Global Phasing Ltd.
Provides functions to parse CIF (Crystallographic Information File) blocks into Gemmi’s SmallStructure representation for small molecules, ligands, and inorganic crystals. Handles fractional coordinates, anisotropic displacement parameters, and symmetry operations.
-
namespace gemmi
Functions
-
inline SmallStructure make_small_structure_from_block(const cif::Block &block_)¶
Parses a CIF block into a SmallStructure object.
- Parameters:
block_ – CIF block to parse.
- Returns:
SmallStructure containing atomic positions, symmetry, and cell parameters. Extracts unit cell parameters, space group information (H-M and Hall symbols, international tables number), symmetry operations, atom sites with fractional coordinates (occupancy, anisotropic displacement), anisotropic temperature factors (atom_site_aniso*), atom types with dispersion corrections, and radiation wavelength. Coordinates are assumed to be fractional (CIF convention).
-
inline cif::Block make_cif_block_from_small_structure(const SmallStructure &st)¶
Converts a SmallStructure into a CIF block.
- Parameters:
st – SmallStructure to convert.
- Returns:
CIF block with cell parameters, symmetry, and atom sites. Generates CIF representation with crystallographic cell, space group name, atom site loop (atom_site*), anisotropic displacement loop (atom_site_aniso*), and radiation wavelength if non-zero. Uses fractional coordinates (CIF convention).
-
inline SmallStructure make_small_structure_from_block(const cif::Block &block_)¶
Conversion between gemmi::Structure and MMDB (CCP4 Macromolecular Data Bank).
Copyright 2020-2022 Global Phasing Ltd.
Provides bidirectional conversion functions between Gemmi’s Structure representation and MMDB’s Manager data structures. This enables interoperability with CCP4’s legacy molecular biology library.
-
namespace gemmi
Functions
-
inline void copy_transform_to_mmdb(const Transform &tr, mmdb::mat33 &mat, mmdb::vect3 &vec)¶
Copies a Gemmi transformation matrix and vector to MMDB format.
- Parameters:
tr – Gemmi transformation object (3x3 rotation + 3D translation).
mat – Output MMDB 3x3 matrix (rotation component).
vec – Output MMDB 3D vector (translation component).
-
template<int N>
void strcpy_to_mmdb(char (&dest)[N], const std::string &src)¶ Safely copies a string into a fixed-size MMDB character array.
- Template Parameters:
N – Size of the destination character array.
- Parameters:
dest – Fixed-size MMDB character array (typically a typedef like mmdb::ChainID).
src – String to copy.
- Throws:
Throws – if src is too long for the destination array.
-
inline void set_seqid_in_mmdb(int *seqnum, mmdb::InsCode &icode, SeqId seqid)¶
Sets MMDB sequence number and insertion code from Gemmi SeqId.
- Parameters:
seqnum – Pointer to MMDB sequence number (output).
icode – MMDB insertion code array (output).
seqid – Gemmi sequence ID containing number and optional insertion code.
-
inline SeqId seqid_from_mmdb(int seqnum, const mmdb::InsCode &inscode)¶
Converts MMDB sequence number and insertion code to Gemmi SeqId.
- Parameters:
seqnum – MMDB sequence number.
inscode – MMDB insertion code array.
- Returns:
Gemmi SeqId with number and optional insertion code.
-
inline void transfer_links_to_mmdb(const Structure &st, mmdb::Manager *mol)¶
Transfers Connection records from Gemmi Structure to MMDB Manager.
- Parameters:
st – Gemmi Structure containing Connection records.
mol – MMDB Manager to populate with Link records. Converts Gemmi Connection objects to MMDB Link format and adds them to all models in the MMDB Manager. Links with undefined sequence IDs are skipped.
-
inline void transfer_links_from_mmdb(mmdb::LinkContainer &mmdb_links, Structure &st)¶
Transfers Link records from MMDB to Gemmi Structure.
- Parameters:
mmdb_links – MMDB LinkContainer to read from.
st – Gemmi Structure to populate with Connection records (output). Converts MMDB Link objects to Gemmi Connection format. Note: LinkR (restraint) entries are not transferred.
-
inline void set_mmdb_seqres(const std::vector<std::string> &sequence, mmdb::SeqRes &seqres)¶
Converts Gemmi sequence vector to MMDB SeqRes format.
- Parameters:
sequence – Gemmi polymer sequence (residue names).
seqres – MMDB SeqRes structure to populate (output). Handles microheterogeneity by extracting the first monomer from each sequence entry. Allocates and manages MMDB internal memory.
-
inline bool has_sequences(const Structure &st)¶
Checks if Structure has polymer entities with defined sequences.
- Parameters:
st – Structure to check.
- Returns:
True if at least one polymer entity with sequence data exists.
-
inline void transfer_seqres_to_mmdb(const Structure &st, mmdb::Manager *manager)¶
Transfers polymer sequence information from Gemmi to MMDB Manager.
- Parameters:
st – Gemmi Structure containing entity sequence data.
manager – MMDB Manager to populate (output). Copies full_sequence data from Gemmi entities to corresponding MMDB chain SEQRES records. Does nothing if Structure has no sequences.
-
inline void copy_to_mmdb(const Structure &st, mmdb::Manager *manager)¶
Copies Gemmi Structure data into MMDB Manager.
- Parameters:
st – Gemmi Structure to convert.
manager – MMDB Manager to populate (output). Transfers all structural information including atoms, residues, chains, crystallographic metadata (cell, spacegroup, NCS operators), SEQRES records, and Connection information. Handles TER records to mark polymer termination.
-
inline Atom copy_atom_from_mmdb(mmdb::Atom &m_atom)¶
Converts MMDB Atom to Gemmi Atom.
- Parameters:
m_atom – MMDB Atom to convert (non-const; MMDB API limitation).
- Returns:
Gemmi Atom with data from MMDB record. Extracts coordinates, occupancy, B-factors, anisotropic temperature factors (if present), element, charge, and atom name/serial information.
-
inline Residue copy_residue_from_mmdb(mmdb::Residue &m_res)¶
Converts MMDB Residue to Gemmi Residue.
- Parameters:
m_res – MMDB Residue to convert.
- Returns:
Gemmi Residue with atoms and metadata. Extracts all atoms, identifies polymer termination via TER pseudo-atoms, and sets het_flag and segment information from first atom.
-
inline std::vector<std::string> get_gemmi_sequence(const mmdb::SeqRes &seqres)¶
Converts MMDB SeqRes to Gemmi sequence vector.
- Parameters:
seqres – MMDB SeqRes structure to read.
- Returns:
Vector of residue names (sequence). Extracts sequence data from MMDB SeqRes, handling empty entries and trimming whitespace from each residue name.
-
inline Chain copy_chain_from_mmdb(Structure &st, mmdb::Chain &m_chain)¶
Converts MMDB Chain to Gemmi Chain and updates Structure entities.
- Parameters:
st – Gemmi Structure to update with entity information (output).
m_chain – MMDB Chain to convert.
- Returns:
Gemmi Chain with residues and sequence data. Extracts chain residues and SEQRES information, creating or updating corresponding polymer entities in the Structure.
-
inline Model copy_model_from_mmdb(Structure &st, mmdb::Model &m_model)¶
Converts MMDB Model to Gemmi Model and updates Structure entities.
- Parameters:
st – Gemmi Structure to update with entity information (output).
m_model – MMDB Model to convert.
- Returns:
Gemmi Model with chains. Extracts all chains and their sequence information, updating entity records and deduplicating entity data.
-
inline Structure copy_from_mmdb(mmdb::Manager *manager)¶
Converts MMDB Manager into Gemmi Structure.
- Parameters:
manager – MMDB Manager to convert.
- Returns:
Gemmi Structure with all models, atoms, and metadata. Transfers crystallographic cell parameters, spacegroup information, all models and chains, CISPEP records, and inter-chain connections.
-
inline void copy_transform_to_mmdb(const Transform &tr, mmdb::mat33 &mat, mmdb::vect3 &vec)¶
Parsing of sequence data in PIR and FASTA formats.
-
namespace gemmi
Functions
-
inline bool is_pir_format(const std::string &s)¶
Determine whether a file starts in PIR format.
PIR format is identified by a sequence code at position 1-3 of the first line, followed by a semicolon at position 3:
>P1; — Protein
>F1; — Protein (structure known)
>DL; — DNA
>DC; — DNA (structure known)
>RL; — RNA
>RC; — RNA (structure known)
>XX; — Generic/Unknown
FASTA format uses ‘>something’ (arbitrary text after ‘>’).
- Parameters:
s – The first line of a sequence file (expected to start with ‘>’).
- Returns:
true if the line matches PIR format syntax, false otherwise.
-
inline std::vector<FastaSeq> read_pir_or_fasta(const std::string &str)¶
Parse a string containing PIR or FASTA format sequences.
Supports both FASTA and PIR formats:
FASTA format: Lines start with ‘>’ followed by a description, then sequence lines.
PIR format: Like FASTA, but has a second header line immediately after the first. The sequence starts on the second line after the primary header.
Sequence parsing rules:
Alphabetic characters (A-Z, case-insensitive) are included in the sequence.
Hyphens (‘-’) represent gaps/insertions.
Asterisks (‘*’) mark sequence terminators; content after ‘*’ is not allowed.
Parentheses ‘(…)’ are allowed (for numbering in PIR); nesting is not allowed.
Digits are allowed only within parentheses.
Whitespace is ignored.
Two or more blank lines separate records.
-
struct FastaSeq¶
- #include <gemmi/pirfasta.hpp>
A sequence record with header and body.
Represents a single sequence entry from a FASTA or PIR file.
-
inline bool is_pir_format(const std::string &s)¶
Map and Grid Data¶
(Stub — full documentation added in PR 6.)
3D crystallographic grids for electron density maps, cell-method search, and reflection data.
This header provides template classes for regular 3D grids on a crystallographic unit cell, with support for symmetry operations, interpolation (trilinear and tricubic), and operations on grid points within specified regions or radii.
-
namespace gemmi
Enums
-
enum class AxisOrder : unsigned char¶
Order of grid axes relative to unit cell axes (a, b, c).
Not all functionality works with all axis orders; many operations require XYZ order. The values XYZ and ZYX are used only when the grid covers the whole unit cell.
Values:
-
enumerator Unknown¶
Axis order not determined.
-
enumerator XYZ¶
Grid axes correspond to a, b, c (default, CCP4 convention). Index X (H in reciprocal space) varies fastest; Z (or L) varies slowest.
-
enumerator ZYX¶
Grid axes reversed: Z varies fastest, X varies slowest. May not be fully supported everywhere.
-
enumerator Unknown¶
-
enum class GridSizeRounding¶
Strategy for rounding calculated grid dimensions to suitable values.
Values:
-
enumerator Nearest¶
Round to nearest value with small prime factors (2, 3, 5).
-
enumerator Up¶
Round up (ceil) to next value with small prime factors.
-
enumerator Down¶
Round down (floor) to previous value with small prime factors.
-
enumerator Nearest¶
Functions
-
inline int modulo(int a, int n)¶
Compute mathematical modulo (a mod n), always returning a value in [0, n).
- Parameters:
a – value to take modulo
n – modulus (n > 0)
- Returns:
Value in range [0, n)
-
inline bool has_small_factorization(int n)¶
Check if n has only small prime factors (2, 3, 5).
- Parameters:
n – Integer to check
- Returns:
True if n = 2^a * 3^b * 5^c for non-negative a, b, c
-
inline int round_with_small_factorization(double exact, GridSizeRounding rounding)¶
Round a value to the nearest integer with only small prime factors.
Useful for choosing FFT-friendly grid dimensions.
- Parameters:
exact – Exact floating-point value
rounding – Rounding strategy (Up, Down, or Nearest)
- Returns:
Integer >= 1 with only 2, 3, 5 as prime factors, closest to
exactper the strategy
-
inline std::array<int, 3> good_grid_size(std::array<double, 3> limit, GridSizeRounding rounding, const SpaceGroup *sg)¶
Compute suitable grid dimensions respecting space group symmetry and FFT efficiency.
Takes into account space group symmetry factors and symmetry-related directions (which must have equal grid sizes), and rounds to dimensions with small prime factors.
- Parameters:
limit – Target grid dimensions (approximate)
rounding – Rounding strategy for each dimension
sg – Space group constraints (may be null for P1)
- Returns:
Array of three grid dimensions {nu, nv, nw}
-
inline void check_grid_factors(const SpaceGroup *sg, std::array<int, 3> size)¶
Verify that grid dimensions are compatible with space group symmetry.
Checks that each dimension is divisible by the corresponding space group factor, and that symmetry-related directions have equal grid sizes.
- Parameters:
sg – Space group to validate against (may be null for P1)
size – Grid dimensions {nu, nv, nw}
- Throws:
Raises – an exception if constraints are violated
-
inline double lerp_(double a, double b, double t)¶
Linear interpolation (lerp) between two values.
- Parameters:
a – Start value
b – End value
t – Interpolation parameter in [0, 1]; 0 returns a, 1 returns b
- Returns:
Interpolated value a + (b - a) * t
-
template<typename T>
std::complex<T> lerp_(std::complex<T> a, std::complex<T> b, double t)¶ Linear interpolation for complex numbers.
-
inline double cubic_interpolation(double u, double a, double b, double c, double d)¶
Catmull–Rom cubic spline interpolation.
Interpolates a cubic between points b and c given neighboring points a and d. Uses the Catmull–Rom formula (equation 24 in the reference below).
- References
Afonine, P.V., Poon, B.K., Read, R.J., Sobolev, O.V., Terwilliger, T.C., Urzhumtsev, A. & Adams, P.D. (2018). Real-space refinement in PHENIX for cryo-EM and crystallography. Acta Cryst. D74, 531–544. https://doi.org/10.1107/S2059798318006551
- Parameters:
u – Parameter in [0, 1], where 0 → b, 1 → c
a – Value at u = -1
b – Value at u = 0
c – Value at u = 1
d – Value at u = 2
- Returns:
Interpolated value
-
inline double cubic_interpolation_der(double u, double a, double b, double c, double d)¶
First derivative of cubic spline interpolation.
Computes df/du for Catmull–Rom interpolation.
- Parameters:
u – Parameter in [0, 1]
a – Value at u = -1
b – Value at u = 0
c – Value at u = 1
d – Value at u = 2
- Returns:
df/du at parameter u
-
template<typename T>
void interpolate_grid(Grid<T> &dest, const Grid<T> &src, const Transform &tr, int order = 1)¶ Interpolate grid values from source to destination under a transformation.
For each point in the destination grid, applies the transformation and interpolates the source grid value at that location. TODO: add argument Box<Fractional> src_extent See: interpolate_grid_around_model() in solmask.hpp See: interpolate_values in python/grid.cpp
- Template Parameters:
T – Grid value type
- Parameters:
dest – Destination grid
src – Source grid
tr – Spatial transformation (rotation + translation)
order – Interpolation order: 0 (nearest), 1 (trilinear), 3 (tricubic)
-
template<typename T>
Correlation calculate_correlation(const GridBase<T> &a, const GridBase<T> &b)¶ Calculate correlation coefficient between two grids.
Computes Pearson correlation between grid values, skipping NaN values.
- Template Parameters:
T – Grid value type
- Parameters:
a – First grid
b – Second grid
- Throws:
Raises – exception if grids have different dimensions
- Returns:
Correlation object with mean, stddev, and correlation coefficient
-
template<typename T = float>
struct Grid : public gemmi::GridBase<float>¶ - #include <gemmi/grid.hpp>
Real-space crystallographic grid (electron density, masks, etc.).
A 3D grid covering the unit cell at regular fractional intervals. Grid points are at fractional coordinates (i/nu, j/nv, k/nw). Many operations require AxisOrder::XYZ and covering the full unit cell.
- Template Parameters:
T – Data type for grid values (default: float)
Public Functions
-
inline void copy_metadata_from(const GridMeta &g)¶
Copy grid metadata (cell, space group, dimensions, axis order).
Copies unit_cell, spacegroup, nu, nv, nw, axis_order from another GridMeta, and recalculates spacing and orth_n.
- Parameters:
g – Source GridMeta
-
inline void calculate_spacing()¶
Compute spacing and scaled orthogonalization matrix.
Recalculates spacing and orth_n based on unit cell and grid dimensions. Must be called after changing unit_cell or grid dimensions.
- Throws:
Raises – exception if unit cell is not in standard orientation
-
inline void set_size_without_checking(int nu_, int nv_, int nw_)¶
Set grid dimensions and recalculate spacing (no space group check).
- Parameters:
nu_ – Dimension along first axis
nv_ – Dimension along second axis
nw_ – Dimension along third axis
-
inline void set_size(int nu_, int nv_, int nw_)¶
Set grid dimensions with space group compatibility check.
- Parameters:
nu_ – Dimension along first axis
nv_ – Dimension along second axis
nw_ – Dimension along third axis
- Throws:
Raises – exception if dimensions incompatible with space group
-
inline void set_size_from_spacing(double approx_spacing, GridSizeRounding rounding)¶
Calculate grid dimensions from desired spacing.
Chooses dimensions with small prime factors (2, 3, 5) compatible with space group.
- Parameters:
approx_spacing – Target spacing in Angstroms
rounding – Strategy for choosing nearby dimensions
-
inline void set_unit_cell(double a, double b, double c, double alpha, double beta, double gamma)¶
Set unit cell parameters from individual values.
- Parameters:
a – Cell length (Angstroms)
b – Cell length (Angstroms)
c – Cell length (Angstroms)
alpha – Angle (degrees)
beta – Angle (degrees)
gamma – Angle (degrees)
-
inline void set_unit_cell(const UnitCell &cell)¶
Set unit cell.
- Parameters:
cell – Unit cell to assign
-
template<typename S>
inline void setup_from(const S &st, double approx_spacing = 0)¶ Initialize grid from a structure (typically Model/Chain/Residue).
Extracts space group and unit cell. If approx_spacing > 0, sets grid dimensions based on spacing.
- Template Parameters:
S – Structure type with find_spacegroup() and cell members
- Parameters:
st – Structure
approx_spacing – Target grid spacing in Angstroms (default: 0, no sizing)
-
inline size_t index_s(int u, int v, int w) const¶
Get index in data array with periodic wrapping.
Safe but slower than index_q(). Applies modulo to all indices.
- Parameters:
u – Grid index (will be wrapped)
v – Grid index (will be wrapped)
w – Grid index (will be wrapped)
- Returns:
Index into data array
-
inline T get_value(int u, int v, int w) const¶
Get value at grid point with periodic wrapping.
- Parameters:
u – Grid index
v – Grid index
w – Grid index
- Returns:
Grid value at the (normalized) indices
-
inline void set_value(int u, int v, int w, T x)¶
Set value at grid point with periodic wrapping.
- Parameters:
u – Grid index
v – Grid index
w – Grid index
x – Value to assign
-
inline Point get_point(int u, int v, int w)¶
Get a Point at given grid indices with periodic wrapping.
The returned Point has normalized indices u, v, w in [0, nu), [0, nv), [0, nw).
- Parameters:
u – Grid index
v – Grid index
w – Grid index
- Returns:
Point with normalized indices
-
inline Point get_nearest_point(const Fractional &f)¶
Get the grid point nearest to a fractional coordinate.
- Parameters:
f – Fractional coordinates
- Throws:
Raises – exception if grid is not in XYZ order
- Returns:
Point at nearest grid position
-
inline Point get_nearest_point(const Position &pos)¶
Get the grid point nearest to an orthogonal (Cartesian) position.
- Parameters:
pos – Orthogonal coordinates (Angstroms)
- Returns:
Point at nearest grid position
-
inline size_t get_nearest_index(const Fractional &f)¶
Get the index of the nearest grid point to a fractional coordinate.
- Parameters:
f – Fractional coordinates
- Returns:
Index into data array
-
inline Fractional point_to_fractional(const Point &p) const¶
Convert a grid Point to fractional coordinates.
The Point’s indices are normalized, so coordinates are in [0, 1).
- Parameters:
p – Point with normalized indices
- Returns:
Fractional coordinates
-
inline Position point_to_position(const Point &p) const¶
Convert a grid Point to orthogonal coordinates.
- Parameters:
p – Point with normalized indices
- Returns:
Orthogonal position (Angstroms)
-
inline T trilinear_interpolation(double x, double y, double z) const¶
Trilinear interpolation at a grid coordinate.
Reference: https://en.wikipedia.org/wiki/Trilinear_interpolation
- Parameters:
x – Grid coordinate (x=1.5 is between 2nd and 3rd grid point). Wraps periodically.
y – Grid coordinate
z – Grid coordinate
- Returns:
Interpolated value using trilinear basis functions
-
inline T trilinear_interpolation(const Fractional &fctr) const¶
Trilinear interpolation at fractional coordinates.
- Parameters:
fctr – Fractional coordinates
- Returns:
Interpolated value
-
inline T trilinear_interpolation(const Position &ctr) const¶
Trilinear interpolation at orthogonal coordinates.
- Parameters:
ctr – Orthogonal coordinates (Angstroms)
- Returns:
Interpolated value
-
inline double tricubic_interpolation(double x, double y, double z) const¶
Tricubic interpolation at a grid coordinate.
Uses Catmull–Rom cubic splines applied as a tensor product in three dimensions. Smoother than trilinear but more expensive. See cubic_interpolation() for the 1D formula.
- References
Afonine, P.V., Poon, B.K., Read, R.J., Sobolev, O.V., Terwilliger, T.C., Urzhumtsev, A. & Adams, P.D. (2018). Real-space refinement in PHENIX for cryo-EM and crystallography. Acta Cryst. D74, 531–544. https://doi.org/10.1107/S2059798318006551
- Parameters:
x – Grid coordinate (x=1.5 is between 2nd and 3rd grid point). Wraps periodically.
y – Grid coordinate
z – Grid coordinate
- Returns:
Interpolated value (double precision)
-
inline double tricubic_interpolation(const Fractional &fctr) const¶
Tricubic interpolation at fractional coordinates.
- Parameters:
fctr – Fractional coordinates
- Returns:
Interpolated value
-
inline double tricubic_interpolation(const Position &ctr) const¶
Tricubic interpolation at orthogonal coordinates.
- Parameters:
ctr – Orthogonal coordinates (Angstroms)
- Returns:
Interpolated value
-
inline std::array<double, 4> tricubic_interpolation_der(double x, double y, double z) const¶
Tricubic interpolation with first derivatives.
Returns the interpolated value and partial derivatives.
- Parameters:
x – Grid coordinate
y – Grid coordinate
z – Grid coordinate
- Returns:
Array {value, df/dx, df/dy, df/dz} in grid coordinates
-
inline std::array<double, 4> tricubic_interpolation_der(const Fractional &fctr) const¶
Tricubic interpolation with derivatives at fractional coordinates.
- Parameters:
fctr – Fractional coordinates
- Returns:
Array {value, df/da, df/db, df/dc} in fractional coordinates
-
inline T interpolate_value(const Fractional &f, int order = 1) const¶
Interpolate value at fractional coordinates using specified method.
- Parameters:
f – Fractional coordinates
order – Interpolation order: 0 (nearest), 1 (trilinear), 3 (tricubic)
- Throws:
std::invalid_argument – if order is not 0, 1, or 3
- Returns:
Interpolated value
-
inline T interpolate_value(const Position &ctr, int order = 1) const¶
Interpolate value at orthogonal coordinates using specified method.
- Parameters:
ctr – Orthogonal coordinates (Angstroms)
order – Interpolation order: 0 (nearest), 1 (trilinear), 3 (tricubic)
- Returns:
Interpolated value
-
inline void get_subarray(T *dest, std::array<int, 3> start, std::array<int, 3> shape) const¶
Extract a rectangular subarray of grid points with periodic wrapping.
Copies a contiguous block of grid values into a destination array. Handles wrapping across periodic boundaries.
- Parameters:
dest – Destination array (at least shape[0]*shape[1]*shape[2] elements)
start – Starting grid indices {u, v, w}
shape – Block size {du, dv, dw}
-
inline void set_subarray(const T *src, std::array<int, 3> start, std::array<int, 3> shape)¶
Set a rectangular subarray of grid points with periodic wrapping.
Copies a block of values from a source array into the grid. Handles wrapping across periodic boundaries.
- Parameters:
src – Source array (at least shape[0]*shape[1]*shape[2] elements)
start – Starting grid indices {u, v, w}
shape – Block size {du, dv, dw}
-
template<bool UsePbc>
inline void check_size_for_points_in_box(int &du, int &dv, int &dw, bool fail_on_too_large_radius) const¶ Validate and adjust size parameters for box operations.
- Template Parameters:
UsePbc – If true, apply periodic boundary conditions; otherwise clamp to grid
- Parameters:
du – Half-size along first axis (may be adjusted)
dv – Half-size along second axis (may be adjusted)
dw – Half-size along third axis (may be adjusted)
fail_on_too_large_radius – If true, raise exception if radius too large for PBC
-
template<bool UsePbc, typename Func>
inline void do_use_points_in_box(const Fractional &fctr, int du, int dv, int dw, Func &&func, double radius = INFINITY)¶ Internal: iterate over grid points in a box around a fractional coordinate.
- Template Parameters:
UsePbc – If true, apply periodic boundary conditions
Func – Callable(T&, double, Position, int, int, int) invoked for each point
- Parameters:
fctr – Fractional center coordinate
du – Half-extent along first axis (in grid points)
dv – Half-extent along second axis (in grid points)
dw – Half-extent along third axis (in grid points)
func – Callback function(value_ref, distance_sq, delta_position, u, v, w)
radius – Optional spherical radius limit (INFINITY for box only)
-
template<bool UsePbc, typename Func>
inline void use_points_in_box(const Fractional &fctr, int du, int dv, int dw, Func &&func, bool fail_on_too_large_radius = true, double radius = INFINITY)¶ Iterate over grid points in a box around a fractional coordinate.
- Template Parameters:
UsePbc – If true, apply periodic boundary conditions
Func – Callable(T&, double, Position, int, int, int) invoked for each point
- Parameters:
fctr – Fractional center coordinate
du – Half-extent along first axis (in grid points)
dv – Half-extent along second axis (in grid points)
dw – Half-extent along third axis (in grid points)
func – Callback function(value_ref, distance_sq, delta_position, u, v, w)
fail_on_too_large_radius – If true and UsePbc, raise exception for oversized box
radius – Optional spherical radius limit (INFINITY for box only)
-
template<bool UsePbc, typename Func>
inline void use_points_around(const Fractional &fctr, double radius, Func &&func, bool fail_on_too_large_radius = true)¶ Iterate over grid points within a spherical radius of a fractional coordinate.
- Template Parameters:
UsePbc – If true, apply periodic boundary conditions
Func – Callable(T&, double) invoked for each point
- Parameters:
fctr – Fractional center coordinate
radius – Spherical radius (in Angstroms)
func – Callback function(value_ref, distance_sq)
fail_on_too_large_radius – If true and UsePbc, raise exception for large radius
-
inline void set_points_around(const Position &ctr, double radius, T value, bool use_pbc = true)¶
Set all grid points within a spherical radius to a constant value.
- Parameters:
ctr – Orthogonal center (Angstroms)
radius – Spherical radius (Angstroms)
value – Value to assign
use_pbc – If true, apply periodic boundary conditions
-
inline void change_values(T old_value, T new_value)¶
Replace all occurrences of one value with another.
- Parameters:
old_value – Value to search for
new_value – Replacement value
-
template<typename Func>
inline void symmetrize(Func func)¶ Apply a reduction function across all symmetry mates of each point.
For each unique point under the space group, applies
functo combine the values of all symmetry-related points, then assigns the result back to all mate positions.- Template Parameters:
Func – Binary function(T, T) → T
- Parameters:
func – Reduction function, e.g., std::plus, std::max, etc.
-
template<typename Func>
inline void symmetrize_using_ops(const std::vector<GridOp> &ops, Func func)¶ Apply a reduction function using an explicit list of operations.
- Template Parameters:
Func – Binary function(T, T) → T
- Parameters:
ops – GridOp operations (typically from get_scaled_ops_except_id())
func – Reduction function
-
inline void symmetrize_min()¶
Apply symmetry by taking the minimum value among symmetry mates.
-
inline void symmetrize_max()¶
Apply symmetry by taking the maximum value among symmetry mates.
-
inline void symmetrize_abs_max()¶
Apply symmetry by taking the maximum absolute value among symmetry mates.
-
inline void symmetrize_sum()¶
Apply symmetry by summing values of symmetry mates.
Points on special positions (with fewer mates) contribute their value multiple times. Used for density map averaging without normalization.
-
inline void symmetrize_nondefault(T default_)¶
Apply symmetry by selecting non-default values among mates.
If a point’s value equals
default_, uses the value from a symmetry mate.- Parameters:
default_ – Value to replace
-
inline void symmetrize_avg()¶
Apply symmetry by averaging values of symmetry mates.
Sums symmetry mates and divides by space group order.
-
inline void normalize()¶
Normalize grid values to zero mean and unit RMS.
Subtracts the mean and scales by RMS, making statistics zero mean and unit variance. Does not work for complex-valued grids.
Public Members
-
double spacing[3] = {0., 0., 0.}¶
Spacing (in Angstroms) between consecutive grid planes.
spacing[0] is distance between u planes, etc. Note: spacing is between planes, not between grid points. Computed as 1/(n*cell_length) for each axis.
-
UpperTriangularMat33 orth_n¶
Orthogonalization matrix scaled by grid dimensions.
Each column of unit_cell.orth.mat divided by {nu, nv, nw}. Used for efficient conversion of fractional deltas to orthogonal.
Public Static Functions
-
static inline double grid_modulo(double x, int n, int *iptr)¶
Helper to split a real coordinate into integer and fractional parts.
- Parameters:
x – Real coordinate
n – Grid dimension
iptr – Output: normalized integer part in [0, n)
- Returns:
Fractional part in [0, 1)
-
template<typename T>
struct GridBase : public gemmi::GridMeta¶ - #include <gemmi/grid.hpp>
Common base for Grid and ReciprocalGrid templates.
- Template Parameters:
T – Data type stored at each grid point
Subclassed by gemmi::Grid< float >, gemmi::Grid< GReal >, gemmi::Grid< T >, gemmi::Grid< std::vector< gemmi::NeighborSearch::Mark > >, gemmi::Grid< T >, gemmi::ReciprocalGrid< T >
Public Types
Public Functions
-
inline void check_not_empty() const¶
Check that grid is not empty (has allocated data).
- Throws:
Raises – exception if data.empty()
-
inline void set_size_without_checking(int nu_, int nv_, int nw_)¶
Allocate and set grid dimensions without bounds checking.
Resizes the data array to nu_ * nv_ * nw_ elements. Does not validate space group compatibility.
- Parameters:
nu_ – Number of grid points along first axis
nv_ – Number of grid points along second axis
nw_ – Number of grid points along third axis
-
inline T get_value_q(int u, int v, int w) const¶
Get value at grid point using quick (unsafe) index.
- Parameters:
u – Grid index (must be in [0, nu))
v – Grid index (must be in [0, nv))
w – Grid index (must be in [0, nw))
- Returns:
Value at (u, v, w)
-
inline size_t point_to_index(const Point &p) const¶
Convert a Point to its index in the data array.
- Parameters:
p – Point with value pointer
- Returns:
Index into data array
-
inline Point index_to_point(size_t idx)¶
Convert a data array index to a Point with normalized indices.
- Parameters:
idx – Index into data array
- Returns:
Point with indices and value pointer
-
struct iterator¶
- #include <gemmi/grid.hpp>
Iterator over grid points in row-major order (u varies fastest).
Public Functions
-
struct Point¶
- #include <gemmi/grid.hpp>
A grid point with normalized indices and a value pointer.
Indices u, v, w have been normalized to [0, nu), [0, nv), [0, nw). The pointer may become invalid if the grid is resized.
-
struct GridMeta¶
- #include <gemmi/grid.hpp>
Metadata common to all grid types (not dependent on stored data type).
Contains unit cell, space group, grid dimensions, and indexing operations. Grid indices u, v, w are in the range [0, nu), [0, nv), [0, nw) for valid grids.
Subclassed by gemmi::GridBase< float >, gemmi::GridBase< GReal >, gemmi::GridBase< std::vector< gemmi::NeighborSearch::Mark > >, gemmi::GridBase< T >
Public Functions
-
inline size_t point_count() const¶
Total number of grid points.
- Returns:
nu * nv * nw
-
inline Fractional get_fractional(int u, int v, int w) const¶
Convert grid indices to fractional coordinates.
- Parameters:
u – Grid index (not normalized to [0, 1))
v – Grid index (not normalized to [0, 1))
w – Grid index (not normalized to [0, 1))
- Returns:
Fractional coordinates {u/nu, v/nv, w/nw}
-
inline Position get_position(int u, int v, int w) const¶
Convert grid indices to orthogonal (Cartesian) coordinates.
- Parameters:
u – Grid index
v – Grid index
w – Grid index
- Returns:
Orthogonal position in Angstroms
-
inline std::vector<GridOp> get_scaled_ops_except_id() const¶
Get symmetry operations scaled to grid coordinates (excluding identity).
Returns all non-identity symmetry operations with translations and rotations pre-scaled for direct application to grid indices. Used internally for symmetrization operations. Requires axis_order == AxisOrder::XYZ.
- Throws:
Raises – exception if grid is not in XYZ order
- Returns:
Vector of GridOp, empty if space group is P1
-
inline size_t index_q(int u, int v, int w) const¶
Quick index computation: fastest but requires 0 <= u < nu, etc.
No bounds checking. Data layout is row-major: (w*nv + v)*nu + u.
- Parameters:
u – Grid index (must be in [0, nu))
v – Grid index (must be in [0, nv))
w – Grid index (must be in [0, nw))
- Returns:
Index into flat data array
-
inline size_t index_q(size_t u, size_t v, size_t w) const¶
Quick index computation for unsigned indices.
-
inline size_t index_n(int u, int v, int w) const¶
Index with periodic wrapping: faster than index_s() but limited range.
Works for indices in the range [-nu, 2*nu) (and similarly for v, w). Applies periodic boundary conditions (wraps to [0, n)).
- Parameters:
u – Grid index
v – Grid index
w – Grid index
- Returns:
Index into flat data array
-
inline size_t index_n_ref(int &u, int &v, int &w) const¶
Index with periodic wrapping, modifying arguments in-place.
Same as index_n() but normalizes u, v, w to [0, nu), [0, nv), [0, nw).
- Parameters:
u – Grid index (will be normalized)
v – Grid index (will be normalized)
w – Grid index (will be normalized)
- Returns:
Index into flat data array
-
inline size_t index_near_zero(int u, int v, int w) const¶
Index with periodic wrapping for indices near zero.
Optimized version of index_n() for indices in [-n, n).
- Parameters:
u – Grid index in range [-nu, nu)
v – Grid index in range [-nv, nv)
w – Grid index in range [-nw, nw)
- Returns:
Index into flat data array
-
inline size_t point_count() const¶
-
struct GridOp¶
- #include <gemmi/grid.hpp>
A crystallographic symmetry operation scaled for grid coordinates.
The scaled operation directly transforms grid indices by applying the rotation matrix and scaled translation (pre-scaled by grid dimensions).
Public Functions
-
enum class AxisOrder : unsigned char¶
CCP4/MRC map file format (electron density maps and masks).
This header provides support for reading and writing CCP4 (Collaborative Computational Project 4) and MRC (Medical Research Council) map file formats commonly used for electron density maps and molecular masks in crystallography and cryo-EM. The CCP4 map consists of a 1024-byte fixed header followed by data values (typically floats). The header contains grid dimensions, unit cell parameters, space group, and data statistics.
-
struct float16_type¶
- #include <gemmi/ccp4.hpp>
Public Functions
-
inline operator float() const¶
-
inline bool operator!=(float16_type o) const¶
-
inline bool operator==(float16_type o) const¶
-
inline operator float() const¶
-
namespace gemmi
Enums
-
enum class MapSetup¶
Options for expanding/reordering CCP4 map data during setup.
CCP4 maps can store data in non-standard axis orderings and may cover only a portion of the unit cell. The setup() method uses this enum to control transformation behavior.
Values:
-
enumerator Full¶
Reorder axes to XYZ and expand with symmetry to the whole unit cell.
-
enumerator NoSymmetry¶
Reorder axes to XYZ and resize to the whole cell, but do not apply symmetry ops.
-
enumerator ReorderOnly¶
Only reorder axes to X, Y, Z; keep the partial cell as-is.
-
enumerator Full¶
Functions
-
Ccp4<float> read_ccp4_map(const std::string &path, bool setup)¶
Convenience function to read a CCP4 electron density map.
- Parameters:
path – File path to .map or .map.gz file
setup – If true, call setup(NAN) to expand and reorder to full cell
- Returns:
Ccp4 object with grid data and header
-
template<typename T = float>
struct Ccp4 : public gemmi::Ccp4Base¶ - #include <gemmi/ccp4.hpp>
CCP4 map file container with typed grid data.
Extends Ccp4Base to hold both the raw CCP4 header and the grid data in memory. The grid axes may not be in XYZ order when read; call setup() to reorder if needed.
- Template Parameters:
T – Data type for grid values (typically float, int8_t, int16_t, or uint16_t)
Public Functions
-
inline void update_ccp4_header(int mode = -1, bool update_stats = true)¶
Create or update the CCP4 header with mode and statistics.
If the header is empty, creates it with full grid metadata. If the header exists, updates MODE word and optionally DMIN/DMAX/DMEAN/RMS.
- Parameters:
mode – CCP4 data mode (-1 to auto-detect from T), or explicit mode value
update_stats – If true, compute and store min/max/mean/rms from grid data
- Throws:
If – grid is empty, not setup, or mode cannot be determined
-
inline bool full_cell() const¶
Check if the map data covers the full unit cell.
- Returns:
True if NXSTART, NYSTART, NZSTART are 0 and grid matches cell sampling
-
inline void read_ccp4_header(AnyStream &f, const std::string &path)¶
Read CCP4 header from stream and initialize grid metadata.
- Parameters:
f – Input stream positioned at file start
path – File path for error reporting
-
void setup(T default_value, MapSetup mode = MapSetup::Full)¶
Transform map axes and/or expand to full unit cell.
Implementation of setup() for template specialization.
Note
Modifies grid dimensions, axis order, and data layout; call after reading header
- Parameters:
default_value – Value to use for grid points outside the map region
mode – Control what transformations to apply (Full, NoSymmetry, or ReorderOnly)
-
void set_extent(const Box<Fractional> &box)¶
Trim the map to a region specified in fractional coordinates.
Implementation of set_extent() for template specialization.
Note
Only works after setup(); requires full_cell() == true and XYZ axis order
- Parameters:
box – Region bounds in fractional coordinates [0, 1]
-
void read_ccp4_stream(AnyStream &f, const std::string &path)¶
Read CCP4 map data and header from a stream.
Implementation of read_ccp4_stream for template specialization.
Note
Reads both header and data; grid data is resized and populated
- Parameters:
f – Input stream positioned at file start
path – File path for error reporting
-
inline void read_ccp4_file(const std::string &path)¶
Read CCP4 map from a file path.
- Parameters:
path – Path to CCP4 map file
-
inline void read_ccp4_from_memory(const char *data, size_t size, const std::string &name)¶
Read CCP4 map from memory buffer.
- Parameters:
data – Pointer to file contents in memory
size – Size of buffer in bytes
name – Label for error messages
-
template<typename Input>
inline void read_ccp4(Input &&input)¶ Read CCP4 map using a generic input adapter.
- Template Parameters:
Input – Type with create_stream() and path() methods
- Parameters:
input – Input adapter (e.g., MaybeGzipped for .map.gz files)
-
void write_ccp4_map(const std::string &path) const¶
Write CCP4 map and data to file.
Implementation of write_ccp4_map() for template specialization.
Note
Header must be set (via update_ccp4_header) before writing
- Parameters:
path – Output file path
Public Static Functions
-
static inline int mode_for_data()¶
Detect CCP4 mode value for the data type T.
- Returns:
CCP4 mode (0, 1, 2, 6) or -1 if type is not supported for mode
-
struct Ccp4Base¶
- #include <gemmi/ccp4.hpp>
Base class for CCP4 map headers and metadata.
Stores the raw CCP4 header (256 32-bit words plus optional extended symmetry records) and provides methods to read/write individual header fields and manage map metadata. The header defines the grid geometry, unit cell, space group, axis ordering, and statistics.
Subclassed by gemmi::Ccp4< T >
Public Functions
-
inline void *header_word(int w)¶
Get pointer to a header word (32-bit value).
- Parameters:
w – Word number in CCP4 convention (1-indexed)
- Returns:
Pointer to the word (cast to appropriate type as needed)
-
inline const void *header_word(int w) const¶
Get const pointer to a header word.
-
inline int32_t header_i32(int w) const¶
Read a 32-bit signed integer from header with byte-order correction.
- Parameters:
w – Word number (1-indexed)
- Returns:
The 32-bit value, byte-swapped if needed
-
inline std::array<int, 3> header_3i32(int w) const¶
Read three consecutive 32-bit integers from header.
- Parameters:
w – Starting word number (1-indexed)
- Returns:
Array of three consecutive 32-bit values
-
inline float header_float(int w) const¶
Read a 32-bit float from header with byte-order correction.
- Parameters:
w – Word number (1-indexed)
- Returns:
The floating-point value
-
inline std::string header_str(int w, size_t len = 80) const¶
Read a string field from header.
- Parameters:
w – Starting word number (1-indexed)
len – Byte length to read (default 80 for standard CCP4 label)
- Returns:
The extracted string (may include padding)
-
inline void set_header_i32(int w, int32_t value)¶
Write a 32-bit signed integer to header with byte-order correction.
- Parameters:
w – Word number (1-indexed)
value – The value to write
-
inline void set_header_3i32(int w, int32_t x, int32_t y, int32_t z)¶
Write three consecutive 32-bit integers to header.
- Parameters:
w – Starting word number (1-indexed)
x – First value (word w)
y – Second value (word w+1)
z – Third value (word w+2)
-
inline void set_header_float(int w, float value)¶
Write a 32-bit float to header with byte-order correction.
- Parameters:
w – Word number (1-indexed)
value – The floating-point value to write
-
inline void set_header_str(int w, const std::string &str)¶
Write a string to header field.
- Parameters:
w – Starting word number (1-indexed)
str – The string to write (must fit in available space)
-
inline std::array<int, 3> axis_positions() const¶
Determine the actual axis ordering from header MAPC, MAPR, MAPS records.
- Throws:
If – MAPC/MAPR/MAPS records are invalid or inconsistent
- Returns:
Array where pos[i] is the map column/row/section index for axis i (X/Y/Z)
-
inline double header_rfloat(int w) const¶
Read a floating-point value from header, rounded to 5 decimal places.
- Parameters:
w – Word number (1-indexed)
- Returns:
The value rounded to avoid floating-point representation artifacts
-
inline Box<Fractional> get_extent() const¶
Get the extent of the map data in fractional coordinates.
- Returns:
A box (min, max corners) in fractional coordinates covering the map data
-
inline bool has_skew_transformation() const¶
Check if the map has a skew transformation (non-orthogonal grid).
Note
Skew transformation is CCP4-specific and rarely used; most software ignores it
- Returns:
True if LSKFLG (word 25) is non-zero, indicating skew is applied
-
inline Transform get_skew_transformation() const¶
Get the skew transformation matrix and translation vector.
Note
Only meaningful if has_skew_transformation() is true
- Returns:
Transform struct with 3x3 matrix and translation for Xo(map) = S * (Xo(atoms) - t)
-
inline Position get_origin() const¶
Get the origin offset (used in MRC format).
- Returns:
Position vector from words 50-52 (usually zero in CCP4, non-zero in MRC)
-
inline void prepare_ccp4_header_except_mode_and_stats(GridMeta &grid)¶
Create a CCP4 header for the given grid (excludes MODE and data statistics).
Note
Assumes the grid covers the whole unit cell with no offset. The header includes symmetry operation records from the space group.
- Parameters:
grid – GridMeta with unit cell, space group, and dimensions to encode
-
inline void update_header_mode_and_stats(int mode)¶
Update header MODE and data statistics fields.
- Parameters:
mode – CCP4 mode (0=int8, 1=int16, 2=float, 6=uint16, 12=float16)
-
inline bool full_cell_(const GridMeta &grid) const¶
Check if the map data covers the entire unit cell.
- Parameters:
grid – Grid metadata to check against header
- Returns:
True if NXSTART=NYSTART=NZSTART=0 and MX=NX, MY=NY, MZ=NZ
-
inline void read_ccp4_header_(GridMeta *grid, AnyStream &f, const std::string &path)¶
Read CCP4 map header from stream, detecting byte order and extended records.
- Parameters:
grid – GridMeta to populate with header info (may be null to skip grid setup)
f – Input stream positioned at start of file
path – File path for error reporting
- Throws:
If – header is invalid, file is truncated, or contains unsupported features
-
inline void *header_word(int w)¶
-
namespace impl
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
Functions
-
template<>
inline std::int8_t translate_map_point<float16_type, std::int8_t>(float16_type f)¶
-
template<>
-
enum class MapSetup¶
Reciprocal-space grid for reflection data and Fourier transforms.
This header provides ReciprocalGrid, a template class for storing complex-valued data in reciprocal space indexed by Miller indices (h, k, l) or FFT grid coordinates. Typically used to store structure factor amplitudes/phases or computed Fourier components. The grid implements FFT conventions with half-l storage for Hermitian-symmetric data.
-
namespace gemmi
Typedefs
-
template<typename T>
using FPhiGrid = ReciprocalGrid<std::complex<T>>¶ Convenience alias for a reciprocal grid of complex F (magnitude/phase) values.
- Template Parameters:
T – Floating-point precision (float or double)
Functions
-
template<typename T>
struct ReciprocalGrid : public gemmi::GridBase<T>¶ - #include <gemmi/recgrid.hpp>
Grid for reciprocal-space (Fourier) data indexed by Miller indices.
Stores reflection amplitudes, phases, or structure factors in reciprocal space. Indices u, v, w correspond to h, k, l (Miller indices) in the FFT grid. For Hermitian-symmetric data (result of real-space FFT), can use half-l mode to store only l >= 0, halving memory while allowing Friedel-mate reconstruction.
- Template Parameters:
T – Data type at grid points (typically complex<float> or complex<double>)
Public Functions
-
inline bool has_index(int u, int v, int w) const¶
Check if Miller indices (u, v, w) are valid and in-range for the grid.
- Parameters:
u – Grid index for h (may be negative in the range [-nu, nu))
v – Grid index for k (may be negative in the range [-nv, nv))
w – Grid index for l (may be negative in the range [-nw, nw), or [0, nw) if half_l)
- Returns:
True if the indices are within valid range for this grid
-
inline void check_index(int u, int v, int w) const¶
Check indices and throw if out of range.
- Parameters:
u – Grid index for h
v – Grid index for k
w – Grid index for l
- Throws:
std::out_of_range – if any index is invalid
-
inline size_t index_n(int u, int v, int w) const¶
Compute flat array index from possibly-negative Miller indices.
- Parameters:
u – Miller h index (range -nu <= u < nu)
v – Miller k index (range -nv <= v < nv)
w – Miller l index (range -nw <= w < nw or 0 <= w < nw with half_l)
- Returns:
Flat array index with periodic wrapping applied
-
inline size_t index_checked(int u, int v, int w) const¶
Compute checked and wrapped index from Miller indices.
- Parameters:
u – Miller h index
v – Miller k index
w – Miller l index
- Throws:
std::out_of_range – if indices are invalid
- Returns:
Flat array index after bounds checking and wrapping
-
inline T get_value(int u, int v, int w) const¶
Get value at Miller indices with bounds checking.
- Parameters:
u – Miller h index
v – Miller k index
w – Miller l index
- Throws:
std::out_of_range – if indices are out of range
- Returns:
The value at (u, v, w)
-
inline T get_value_or_zero(int u, int v, int w) const¶
Get value at Miller indices, returning default T{} if out of range.
- Parameters:
u – Miller h index
v – Miller k index
w – Miller l index
- Returns:
The value at (u, v, w), or T{} (zero) if indices are invalid
-
inline void set_value(int u, int v, int w, T x)¶
Set value at Miller indices with bounds checking.
- Parameters:
u – Miller h index
v – Miller k index
w – Miller l index
x – The value to store
- Throws:
std::out_of_range – if indices are out of range
-
inline Miller to_hkl(const typename GridBase<T>::Point &point) const¶
Convert grid Point (with u, v, w indices) to Miller indices (h, k, l).
- Parameters:
point – Point from grid iteration with normalized indices [0, n)
- Returns:
Miller index vector accounting for FFT conventions and axis order
-
inline double calculate_1_d2(const typename GridBase<T>::Point &point) const¶
Compute 1/d^2 resolution from a grid point (inverse d-spacing squared).
- Parameters:
point – Grid point with u, v, w indices
- Returns:
1/d^2 in reciprocal Angstrom units
-
inline double calculate_d(const typename GridBase<T>::Point &point) const¶
Compute d-spacing for a grid point.
- Parameters:
point – Grid point with u, v, w indices
- Returns:
d-spacing (resolution) in Angstroms
-
inline T get_value_by_hkl(Miller hkl, double unblur = 0, bool mott_bethe = false) const¶
Get reflection value by Miller indices with optional post-processing.
Note
For half_l grids with negative l, fetches the Friedel conjugate at (-h,-k,-l)
- Parameters:
hkl – Miller indices (h, k, l)
unblur – Sharpening factor (B-factor correction); 0 = no sharpening
mott_bethe – If true, apply Mott-Bethe factor for scattering angle dependence
- Returns:
Value at (h, k, l), with Friedel mate retrieval if half_l is set and l<0, and post-processing applied (unblur/Mott-Bethe)
-
template<typename R = T>
inline AsuData<R> prepare_asu_data(double dmin = 0, double unblur = 0, bool with_000 = false, bool with_sys_abs = false, bool mott_bethe = false)¶ Extract reflection data in asymmetric unit (ASU) sorted by Miller indices.
Note
For half_l grids, automatically retrieves Friedel mates for l<0
- Template Parameters:
R – Output data type (default: same as grid type T)
- Parameters:
dmin – Minimum resolution cutoff (Angstroms); 0 = no cutoff
unblur – B-factor sharpening/blurring factor
with_000 – If true, include the origin reflection (0,0,0)
with_sys_abs – If true, include systematically absent reflections
mott_bethe – If true, apply Mott-Bethe factor correction
- Returns:
AsuData object with reflections in the asymmetric unit, sorted by (h,k,l)
Public Members
-
bool half_l = false¶
If true, stores only l>=0; l<0 values obtained from Friedel pairs.
-
template<typename T>
Electron density calculation from atomic coordinates using Gaussian density distributions.
Provides DensityCalculator struct for placing atomic Gaussian electron density onto a 3D grid, with support for isotropic and anisotropic B-factors, occupancy, X-ray scattering factors, and electron scattering (Coulomb potential). Used to generate synthetic electron density maps from an atomic model for comparison with experimental maps or map correlation calculations.
-
namespace gemmi
Functions
-
template<int N, typename Real>
Real determine_cutoff_radius(Real x1, const ExpSum<N, Real> &precal, Real cutoff_level)¶ Find the radius at which a radial density function falls below a cutoff level.
Uses binary search with special handling for addends (like Mott-Bethe factor) that may cause the function to rise then fall, rather than monotonically decreasing.
- Template Parameters:
N – Number of Gaussian components in the exponential sum
Real – Floating-point type (float or double)
- Parameters:
x1 – Initial search radius (in Angstroms or grid units)
precal – Precalculated exponential sum object providing calculate() and derivative
cutoff_level – Density threshold; radius is where |density| equals this value
- Returns:
Radius (distance) at which the density function equals the cutoff level
-
template<typename Real>
Real it92_radius_approx(Real b)¶ Approximate radial extent of electron density for a given B-factor.
Used as initial guess for cutoff radius search; applicable to X-ray scattering factors (IT92).
- Template Parameters:
Real – Floating-point type
- Parameters:
b – Isotropic B-factor (in Angstrom^2)
- Returns:
Approximate radius (in Angstroms) at which density falls to ~1e-5 (International Tables Vol. C formula)
-
template<typename Table, typename GReal>
struct DensityCalculator¶ - #include <gemmi/dencalc.hpp>
Calculate electron density from an atomic model on a regular grid.
Places Gaussian electron density contributions from atoms onto a 3D grid. Supports isotropic and anisotropic B-factors, occupancy, X-ray and electron scattering.
Typical workflow:
Construct DensityCalculator; set grid via grid.setup_from(structure)
Set d_min (resolution) and other parameters (blur, cutoff)
Optionally set addends (wavelength-dependent f’ anomalous corrections)
Call put_model_density_on_grid(model) to populate the grid
Use transform_map_to_f_phi() for FFT to reciprocal space
If blur > 0, multiply reciprocal-space data by reciprocal_space_multiplier()
- Template Parameters:
Table – Scattering factor coefficients table (e.g., IT92, Cromer-Mann, electron scattering)
GReal – Type for grid values (float or double)
Public Types
Public Functions
-
inline double requested_grid_spacing() const¶
Compute grid spacing (Angstroms per voxel) based on d_min and rate.
- Returns:
Grid spacing; 0 if d_min not set
-
inline void set_refmac_compatible_blur(const Model &model, bool allow_negative = false)¶
Set blur to match Refmac5 conventions: depends on existing grid and model B-factors.
Calculates blur such that the effective B-factor on the model matches Refmac defaults.
- Parameters:
model – Atomic model providing B-factor statistics
allow_negative – If true, blur can be negative (default false = clamp to 0)
-
inline void add_atom_density_to_grid(const Atom &atom)¶
Add electron density contribution of a single atom to the grid.
Places Gaussian density with appropriate radius based on B-factor and scattering factors. Handles both isotropic and anisotropic B-factors. Occupancy and anomalous addends applied.
- Parameters:
atom – Atom with element, position, B-factor, occupancy, and anisotropic info
- Pre:
Table must have scattering factor coefficients for atom.element
-
inline void add_c_contribution_to_grid(const Atom &atom, float c)¶
Add a constant radial density contribution for an atom (for special cases).
Useful for adding constant density contributions (e.g., Mott-Bethe factor for electron scattering).
- Parameters:
atom – Atom providing position, occupancy
c – Constant density factor (as in scattering factor coefficients or addends)
-
template<int N>
inline CReal estimate_radius(const ExpSum<N, CReal> &precal, CReal b) const¶ Estimate the interaction radius for density based on precalculated B-factor.
For single-Gaussian scattering factors (N=1), computes analytically. For multi-Gaussian (N>1), uses determine_cutoff_radius() binary search.
- Template Parameters:
N – Number of exponential components
- Parameters:
precal – Precalculated exponential sum object
b – Isotropic B-factor (Angstrom^2)
- Returns:
Interaction radius (Angstroms) where density falls below cutoff
-
template<typename Coef>
inline void do_add_atom_density_to_grid(const Atom &atom, const Coef &coef, float addend)¶ Internal: place electron density on grid for an atom with given scattering factors.
Handles isotropic B-factor case with radial density sampling and anisotropic case with box-based sampling respecting the anisotropic U-tensor.
- Template Parameters:
Coef – Scattering factor coefficients type
- Parameters:
atom – Atom with position, occupancy, B-factor, anisotropic U-tensor
coef – Precalculated scattering factor coefficients (from Table::get())
addend – Wavelength-dependent anomalous correction (f’) added to constant term
-
inline void initialize_grid()¶
Clear grid data and allocate size based on d_min and rate, or use existing grid.
Sets grid size for FFT-friendly dimensions if d_min > 0. Otherwise assumes grid already configured by user (via setup_from).
- Throws:
Fails – if d_min not set and grid has no existing dimensions
-
inline void add_model_density_to_grid(const Model &model)¶
Add electron density contributions from all atoms in a model.
Iterates through all atoms and calls add_atom_density_to_grid() for each. Grid must already be initialized.
- Parameters:
model – Atomic model with chains, residues, atoms
-
inline void put_model_density_on_grid(const Model &model)¶
Initialize grid and add all atom densities from a model.
Calls initialize_grid(), add_model_density_to_grid(), and symmetrize_sum().
- Parameters:
model – Atomic model
-
inline void set_grid_cell_and_spacegroup(const Structure &st)¶
Set grid unit cell and space group from a structure.
- Deprecated:
Use grid.setup_from(st) directly
- Parameters:
st – Structure providing unit cell and space group
-
inline double reciprocal_space_multiplier(double inv_d2) const¶
Compute reciprocal-space multiplier for blur correction factor.
If blur was applied, multiply structure factors by this to correct for the applied blur.
- Parameters:
inv_d2 – Inverse d-spacing squared (1/d^2) from unit_cell.calculate_1_d2(hkl)
- Returns:
Exponential factor: exp(blur * 0.25 * inv_d2)
-
inline double mott_bethe_factor(const Miller &hkl) const¶
Compute the Mott-Bethe factor for electron scattering.
For electron scattering, the Mott-Bethe factor approximates the Coulomb potential contribution.
- Parameters:
hkl – Miller indices
- Returns:
Mott-Bethe correction factor (optionally scaled by reciprocal_space_multiplier if blur > 0)
Public Members
-
double d_min = 0.¶
Target d_min resolution (Angstroms); grid sampling = d_min / (2 * rate)
-
double rate = 1.5¶
Oversampling rate relative to d_min (default 1.5 = 50% oversampling)
-
double blur = 0.¶
Additional blur (B-factor) to apply to all atoms (Angstrom^2); default 0.
-
float cutoff = 1e-5f¶
Density cutoff for determining atom-to-grid interaction radius (default 1e-5)
-
template<int N, typename Real>
Asymmetric unit (ASU) masking for crystallographic grids.
-
namespace gemmi
Functions
-
inline AsuBrick find_asu_brick(const SpaceGroup *sg)¶
Determines the optimal ASU brick for a crystallographic space group. Uses a brute-force search over 8^3 possible brick sizes to find the smallest ASU that covers the full unit cell when replicated by all space group operations. Both the size and inclusivity (boundary direction) of the brick are optimized.
- Parameters:
sg – Pointer to SpaceGroup; must not be nullptr
- Throws:
gemmi::Failure – if sg is nullptr
- Returns:
AsuBrick representing the optimal ASU for the given space group
-
template<typename V = std::int8_t>
std::vector<V> get_asu_mask(const GridMeta &grid)¶ Generates an ASU mask for a crystallographic grid. Creates a vector with one entry per grid point: 0 for ASU points, 1 for symmetry mates. Grid points on special positions map to themselves and are marked as 0 (ASU).
- Template Parameters:
V – Mask value type (default std::int8_t)
- Parameters:
grid – Grid metadata including space group and dimensions
- Throws:
gemmi::Failure – if the ASU is not successfully determined
- Returns:
Mask vector of size grid.point_count() with values 0 (ASU) or 1 (mate)
-
template<typename T>
MaskedGrid<T> masked_asu(Grid<T> &grid)¶ Creates a MaskedGrid for convenient iteration over ASU points only.
- Template Parameters:
T – Grid value type
- Parameters:
grid – Grid to wrap
- Returns:
MaskedGrid wrapper with ASU mask pre-computed
-
template<typename T>
Box<Fractional> get_nonzero_extent(const GridBase<T> &grid)¶ Calculates the smallest bounding box containing all non-zero and non-NaN grid values. Scans the grid for non-zero points along each axis, finds the tightest bounding box in fractional coordinate space.
- Template Parameters:
T – Grid value type
- Parameters:
grid – Grid to analyze
- Returns:
Box in fractional coordinates that bounds all non-zero data
-
struct AsuBrick¶
- #include <gemmi/asumask.hpp>
Representation of an asymmetric unit (ASU) brick region. The ASU is the minimal region of the unit cell under crystallographic space group symmetry. This struct represents a brick-shaped ASU as 0 <= x <= size[i]/denom for each axis. Lower bounds are always at the origin; upper bounds may be inclusive (<=) or exclusive (<).
Public Functions
-
inline AsuBrick(int a, int b, int c)¶
Construct an ASU brick with given numerators. Automatically determines inclusivity based on whether each size is less than denom.
- Parameters:
a – Numerator for x-axis
b – Numerator for y-axis
c – Numerator for z-axis
-
inline std::string str() const¶
Returns a human-readable string representation of the brick. Example: “0<=x<=1/8; 0<=y<1/6; 0<=z<=1/4”
-
inline Fractional get_upper_limit() const¶
Returns the upper limit of the ASU as fractional coordinates. Adds a small epsilon to inclusive boundaries and subtracts from exclusive boundaries to handle floating-point comparisons correctly.
-
inline Box<Fractional> get_extent() const¶
Returns a bounding box for the ASU in fractional coordinates. The lower bound is always at (-epsilon, -epsilon, -epsilon) and upper bound is from get_upper_limit().
-
inline std::array<int, 3> uvw_end(const GridMeta &meta) const¶
Converts the ASU brick upper bound to grid point indices. Computes ceiling values for each axis, accounting for the grid’s axis order.
- Parameters:
meta – Grid metadata (including axis order and dimensions)
- Throws:
gemmi::Failure – if grid axis order is not XYZ
- Returns:
Array of [u_end, v_end, w_end] grid indices
Public Members
-
int volume¶
Product of size elements: size[0]*size[1]*size[2].
Public Static Attributes
-
static constexpr int denom = 24¶
Denominator for normalizing brick coordinates to [0,1); always 24.
-
inline AsuBrick(int a, int b, int c)¶
-
template<typename T, typename V = std::int8_t>
struct MaskedGrid¶ - #include <gemmi/asumask.hpp>
Grid wrapper that iterates only over points within the asymmetric unit. Wraps a grid and a mask vector, providing an iterator that skips masked-out points.
- Template Parameters:
T – Grid value type
V – Mask value type (default std::int8_t)
Public Functions
Public Members
-
struct iterator¶
- #include <gemmi/asumask.hpp>
Iterator over grid points within the ASU (where mask == 0).
-
namespace impl
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
Functions
-
inline std::pair<int, int> trim_false_values(const std::vector<bool> &vec)¶
Finds the shortest span (possibly wrapping around) containing all true values in a vector. Handles periodic (wrapped) boundaries by considering the span of leading and trailing false values.
- Parameters:
vec – Vector of boolean values
- Returns:
Pair (start, end) of shortest span containing all true values; {0, n} if all false
-
inline std::pair<int, int> trim_false_values(const std::vector<bool> &vec)¶
-
inline AsuBrick find_asu_brick(const SpaceGroup *sg)¶
Solvent masking utilities for crystallographic refinement.
-
namespace gemmi
Enums
-
enum class AtomicRadiiSet¶
Enumeration of atomic radii sets for solvent masking. Determines which radii library is used when computing the protein region.
Values:
-
enumerator VanDerWaals¶
Standard van der Waals radii from crystallographic tables.
-
enumerator Cctbx¶
CCTBX/CCP4 van der Waals radii.
-
enumerator Refmac¶
Refmac radii for bulk solvent correction.
-
enumerator Constant¶
Constant radius applied to all atoms.
-
enumerator VanDerWaals¶
Functions
-
inline float cctbx_vdw_radius(El el)¶
Returns the van der Waals radius from CCTBX/CCP4 library for a given element. Data derived from cctbx/eltbx/van_der_waals_radii.py for compatibility.
- Parameters:
el – Chemical element
- Returns:
Radius in Angstroms
-
inline float refmac_radius_for_bulk_solvent(El el)¶
Returns the effective radius for bulk solvent correction from Refmac’s ener_lib.cif. Represents ionic radius minus 0.2 Angstroms or vdW radius plus 0.2 Angstroms. For full Refmac compatibility, use
r_probe=1.0andr_shrink=0.8.- Parameters:
el – Chemical element
- Returns:
Radius in Angstroms
-
template<typename T>
void mask_points_in_radius(Grid<T> &mask, const Model &model, AtomicRadiiSet atomic_radii_set, double r_probe, T value, bool ignore_hydrogen, bool ignore_zero_occupancy_atoms)¶ Marks grid points within a radius around atoms as masked. Sets all grid points within (atomic radius + probe radius) of each atom to the given value.
- Template Parameters:
T – Grid value type (typically int8_t for binary masks or float for weighted masks)
- Parameters:
mask – Grid to modify in-place
model – Molecular model containing atoms to mask around
atomic_radii_set – Which atomic radii library to use
r_probe – Probe radius (in Angstroms) added to each atomic radius
value – Value to set for masked grid points
ignore_hydrogen – If true, skip hydrogen atoms
ignore_zero_occupancy_atoms – If true, skip atoms with zero occupancy
-
template<typename T>
void mask_points_in_constant_radius(Grid<T> &mask, const Model &model, double radius, T value, bool ignore_hydrogen, bool ignore_zero_occupancy_atoms)¶ - Deprecated:
Use mask_points_in_radius with AtomicRadiiSet::Constant instead. Marks grid points within a constant radius around atoms.
- Template Parameters:
T – Grid value type
- Parameters:
mask – Grid to modify
model – Molecular model with atoms to mask around
radius – Constant radius in Angstroms
value – Value to set for masked grid points
ignore_hydrogen – If true, skip hydrogen atoms
ignore_zero_occupancy_atoms – If true, skip atoms with zero occupancy
-
inline std::string distinct_altlocs(const Model &model)¶
Collects all distinct alternate location indicators from a model.
- Parameters:
model – Molecular model to scan
- Returns:
String containing unique altloc characters found in the model
-
inline void mask_points_using_occupancy(Grid<float> &mask, const Model &model, AtomicRadiiSet atomic_radii_set, double r_probe, bool ignore_hydrogen, bool ignore_zero_occupancy_atoms)¶
Masks grid points using atom occupancy values to create a weighted mask. Creates a non-binary mask by considering occupancy factors for atoms with alternate locations. Each altloc is processed separately and contributions are accumulated.
- Parameters:
mask – Existing float mask to modify in-place (contributions are subtracted)
model – Model to mask; atoms are categorized by alternate location code
atomic_radii_set – Which atomic radii library to use
r_probe – Probe radius (in Angstroms) added to each atomic radius
ignore_hydrogen – If true, skip hydrogen atoms
ignore_zero_occupancy_atoms – If true, skip atoms with zero occupancy
-
template<typename T>
void set_margin_around(Grid<T> &mask, double r, T value, T margin_value)¶ Creates a margin of points around the boundary of a masked region. Finds grid points at distance <=
rfrom points with value equal tovalue, and sets them tomargin_value. Uses efficient stencil-based neighbor search.- Template Parameters:
T – Grid value type
- Parameters:
mask – Grid to modify in-place
r – Distance threshold in Angstroms
value – Boundary value to search for (typically solvent/protein boundary)
margin_value – Value to set for margin points
- Throws:
gemmi::Failure – if radius exceeds half the unit cell dimensions
-
inline void mask_with_node_info(Grid<NodeInfo> &mask, const Model &model, double radius)¶
Populates a grid with NodeInfo for all grid points near model atoms. Finds the nearest atom and its distance for each grid point within
radius.- Parameters:
mask – NodeInfo grid to populate
model – Molecular model to search
radius – Search radius in Angstroms
-
inline void unmask_symmetry_mates(Grid<NodeInfo> &mask)¶
Removes grid points that are closer to a symmetry mate than to the original model. A grid point is unmasked (marked as
found=false) if any symmetry image of the nearest atom is closer than that atom. This avoids double-counting in density calculations. Non-crystallographic symmetry (NCS) is ignored.- Parameters:
mask – NodeInfo grid to update in-place
-
template<typename T>
void interpolate_grid_around_model(Grid<T> &dest, const Grid<T> &src, const Transform &tr, const Model &dest_model, double radius, int order = 1)¶ Interpolates grid values from a source grid around atoms in a destination model. Identifies grid points in the destination grid that are near atoms in the destination model, transforms them to source grid coordinates, and interpolates values from the source. Grid points closer to symmetry mates are skipped to avoid double-counting.
- Template Parameters:
T – Grid value type
- Parameters:
dest – Destination grid to interpolate into (modified in-place)
src – Source grid to interpolate from
tr – Transformation from destination to source
dest_model – Model in destination grid frame (determines which points to interpolate)
radius – Search radius in Angstroms for atoms
order – Interpolation order (1=linear, 3=cubic, default 1)
-
template<typename T>
void add_soft_edge_to_mask(Grid<T> &grid, double width)¶ Adds a smooth transition zone to the boundary of a binary mask. Converts sharp 0/1 boundaries to smooth transitions using a raised cosine function. Grid points at distance <
widthfrom the boundary are set to cosine-interpolated values.- Template Parameters:
T – Grid value type
- Parameters:
grid – Binary mask to smooth in-place (0s become 1s beyond boundary)
width – Width of transition zone in Angstroms
-
struct NodeInfo¶
- #include <gemmi/solmask.hpp>
Information about a grid point’s relationship to nearby model atoms. Used internally for interpolation of density maps around model atoms.
-
struct SolventMasker¶
- #include <gemmi/solmask.hpp>
Helper class for computing and applying solvent masks to crystallographic grids. Encapsulates parameters and operations for bulk solvent masking, including mask generation, shrinking, inversion, and symmetry handling.
Public Functions
-
inline SolventMasker(AtomicRadiiSet choice, double constant_r_ = 0.)¶
Initialize SolventMasker with a radii set and optional constant radius. Automatically sets default parameters (rprobe, rshrink) for the chosen set.
- Parameters:
choice – Atomic radii set to use
constant_r_ – Constant radius (only used if choice is AtomicRadiiSet::Constant)
-
inline void set_radii(AtomicRadiiSet choice, double constant_r_ = 0.)¶
Sets the atomic radii set and related parameters. Updates rprobe, rshrink, and island_min_volume based on the chosen library.
- Parameters:
choice – Atomic radii set to use
constant_r_ – Constant radius override
-
template<typename T>
inline void clear(Grid<T> &grid) const¶ Fills the entire grid with 1 (solvent region).
- Template Parameters:
T – Grid value type
- Parameters:
grid – Grid to fill
-
template<typename T>
inline void mask_points(Grid<T> &grid, const Model &model) const¶ Sets grid points around atoms to 0 (protein region).
- Template Parameters:
T – Grid value type
- Parameters:
grid – Grid to modify in-place
model – Molecular model
-
inline void mask_points(Grid<float> &grid, const Model &model) const¶
Sets grid points around atoms to 0, with optional occupancy weighting. Uses atom occupancy if
use_atom_occupancyis true; otherwise calls mask_points<float>.- Parameters:
grid – Grid to modify in-place
model – Molecular model
-
template<typename T>
inline void symmetrize(Grid<T> &grid) const¶ Applies space group symmetry to fill the entire grid. For integer/binary masks, distributes 0-value points via symmetry operators. For float masks, sets each point to the minimum value across symmetry mates.
- Template Parameters:
T – Grid value type
- Parameters:
grid – Grid to symmetrize in-place
-
template<typename T>
inline void shrink(Grid<T> &grid) const¶ Shrinks the masked (protein) region by marking a margin as solvent. Marks all points within
rshrinkof the protein-solvent boundary.- Template Parameters:
T – Grid value type
- Parameters:
grid – Grid to shrink in-place
-
template<typename T>
inline void invert(Grid<T> &grid) const¶ Inverts the mask (1 becomes 0, 0 becomes 1).
- Template Parameters:
T – Grid value type
- Parameters:
grid – Grid to invert in-place
-
template<typename T>
inline int remove_islands(Grid<T> &grid) const¶ Removes small disconnected regions (islands) using flood fill. Islands smaller than
island_min_volume(as a fraction of unit cell volume) are removed.- Template Parameters:
T – Grid value type (typically int8_t)
- Parameters:
grid – Grid to modify in-place
- Returns:
Number of islands removed
-
template<typename T>
inline void put_mask_on_grid(Grid<T> &grid, const Model &model) const¶ Generates a complete solvent mask on a grid using the standard pipeline. Steps: clear grid (1) -> mask atoms (0) -> apply symmetry -> remove islands -> shrink.
- Template Parameters:
T – Grid value type
- Parameters:
grid – Grid to populate with mask
model – Molecular model to mask
Public Members
-
AtomicRadiiSet atomic_radii_set¶
Which atomic radii library is used.
-
bool ignore_hydrogen¶
If true, hydrogen atoms are skipped.
-
bool ignore_zero_occupancy_atoms¶
If true, atoms with zero occupancy are skipped.
-
bool use_atom_occupancy = false¶
If true, use atom occupancy for weighted masking.
-
double rprobe¶
Probe radius added to atomic radii (in A)
-
double rshrink¶
Shrinking radius applied after masking (in A)
-
double island_min_volume¶
Minimum volume (as fraction) of protein islands to retain.
-
double constant_r¶
Constant radius (for AtomicRadiiSet::Constant)
-
double requested_spacing = 0.¶
Requested grid spacing (0 = auto)
-
inline SolventMasker(AtomicRadiiSet choice, double constant_r_ = 0.)¶
-
enum class AtomicRadiiSet¶
Flood fill algorithm for identifying connected regions in 3D grids.
Implements a scanline-based flood fill for marking connected regions in a grid with periodic boundary conditions and 6-way (face) connectivity. Useful for identifying solvent envelopes, protein/ligand masks, or other binary segmentation tasks on crystallographic maps.
-
namespace gemmi
Functions
-
inline void mask_nodes_above_threshold(Grid<std::int8_t> &mask, const Grid<float> &grid, double threshold, bool negate = false)¶
Create a binary mask of grid points above (or below) a density threshold.
Copies grid metadata to mask and sets mask data to 1 where grid > threshold (or < threshold if negate).
- Parameters:
mask – Output binary mask grid (1 = above threshold, 0 = below)
grid – Input electron density or other continuous-valued grid
threshold – Density threshold value
negate – If true, invert the comparison (below threshold -> 1)
-
inline Grid<std::int8_t> flood_fill_above(const Grid<float> &grid, const std::vector<Position> &seeds, double threshold, bool negate = false)¶
Identify connected regions above (or below) a threshold using flood fill starting from seeds.
Creates a mask where 1 indicates points in regions connected to the seed points and satisfying the threshold criterion. Useful for identifying solvent envelopes (seed from solvent, find connected regions above threshold) or protein masks (seed from protein region, find connected regions).
- Parameters:
grid – Input electron density or other continuous-valued grid
seeds – Vector of seed positions (Angstrom coordinates) to start the flood fill
threshold – Density threshold; regions above this value are filled
negate – If true, find regions below threshold instead
- Returns:
Binary mask grid (1 = in connected region from seeds, 0 = background)
-
template<typename T, int Land>
struct FloodFill¶ - #include <gemmi/floodfill.hpp>
Flood fill algorithm for finding connected regions in a 3D grid.
Implements a scanline-based flood fill that respects periodic boundary conditions and uses 6-way (face) connectivity. The algorithm identifies all grid points with value
Landthat are connected to a seed point.- Template Parameters:
T – Grid data type (typically int8_t for binary masks)
Land – Value marking the region to fill (0 or 1); fills connected regions with this value
Public Functions
-
inline void set_line_values(Line &line, T value) const¶
Mark all points in a line with a given value, handling periodic wraparound.
Handles periodic boundary conditions in the u-direction for lines that wrap around.
- Parameters:
line – Line segment to mark
value – Value to write
-
inline void set_volume_values(Result &r, T value) const¶
Mark all lines in a filled region with a given value.
- Parameters:
r – Result containing all lines of the region
value – Value to write to each line
-
inline Result find_all_connected_points(int u, int v, int w)¶
Find all grid points with value Land connected to a seed point via face neighbors.
Uses a scanline algorithm that expands from the seed point to find all connected regions. Respects periodic boundary conditions and 6-way (face) connectivity.
- Parameters:
u – Starting u (x) coordinate
v – Starting v (y) coordinate
w – Starting w (z) coordinate
- Returns:
Result containing all connected line segments; points are temporarily marked with this_island()
-
template<typename Func>
inline void for_each_islands(Func func)¶ Iterate over all connected regions (islands) in the grid, calling a function on each.
Scans the entire grid, identifying connected regions with value Land. After processing all regions, resets marked points back to Land.
- Template Parameters:
Func – Callable taking a Result (one island)
- Parameters:
func – Function invoked once per connected region
Public Static Functions
Private Functions
-
inline void add_lines(int u, int v, int w, int ulen, Result &r)¶
Internal: expand from a line to find connected lines in neighboring v and w planes.
- Parameters:
u – Starting u coordinate
v – Starting v coordinate
w – Starting w coordinate
ulen – Length to check
r – Result accumulating all connected lines
-
inline Line line_from_point(int u, int v, int w, T *ptr) const¶
Internal: extract the full horizontal line containing a point.
Finds the maximal horizontal line of Land values containing the point, handling wraparound in the periodic u-direction.
- Parameters:
u – Starting u coordinate
v – Starting v coordinate
w – Starting w coordinate
ptr – Pointer to grid data at (u, v, w)
- Returns:
Line segment with full extent in u direction, handling periodic wraparound
-
struct Line¶
- #include <gemmi/floodfill.hpp>
Horizontal line segment within a flood fill region.
-
inline void mask_nodes_above_threshold(Grid<std::int8_t> &mask, const Grid<float> &grid, double threshold, bool negate = false)¶
Fourier transforms for converting between real-space electron density maps and reciprocal-space structure factors.
This header provides functions to convert between real-space grids (electron density maps) and reciprocal-space grids (structure factors with amplitudes and phases). Uses the pocketfft library for 3D FFT operations and handles symmetry operations, Friedel mate reconstruction, and both half-l (Hermitian) and full reciprocal-space representations.
Defines
-
POCKETFFT_NO_MULTITHREADING¶
-
namespace gemmi
Functions
-
template<typename T>
double phase_in_angles(const std::complex<T> &v, double eps = 2e-5)¶ Convert complex number phase to angle in degrees [0, 360).
- Template Parameters:
T – Scalar type of complex number (float or double)
- Parameters:
v – Complex number
eps – Threshold for treating negative angles as zero (default 2e-5 for float precision)
- Returns:
Phase angle in degrees; small negative angles are rounded to 0 instead of 360
-
inline void add_asu_f_phi_to_float_vector(std::vector<float> &float_data, const AsuData<std::complex<float>> &asu_data)¶
Append Miller indices, amplitudes, and phases from asymmetric unit to a flat vector.
For each reflection in
asu_data, appends 5 floats: h, k, l (as floats), |F|, and phase(degrees).- Parameters:
float_data – Output vector (usually Mtz::data); elements appended as [h, k, l, F, phi, …]
asu_data – ASU data with complex structure factors
-
template<typename DataProxy>
std::array<int, 3> get_size_for_hkl(const DataProxy &data, std::array<int, 3> min_size, double sample_rate)¶ Calculate grid size needed to accommodate Miller indices from diffraction data.
- Template Parameters:
DataProxy – Type with unit_cell(), spacegroup(), and get_hkl() methods
- Parameters:
data – Diffraction data (MTZ-like)
min_size – Minimum grid size [nu, nv, nw]
sample_rate – Desired sampling rate (1/Angstrom per voxel); if <= 0, only checks Miller range
- Returns:
Grid dimensions adjusted for largest observed Miller indices and rounding to FFT-friendly factors
-
template<typename DataProxy>
bool data_fits_into(const DataProxy &data, std::array<int, 3> size)¶ Check if all Miller indices in data fit within grid dimensions.
- Template Parameters:
DataProxy – Type with get_hkl() and size() methods
- Parameters:
data – Diffraction data
size – Grid dimensions [nu, nv, nw]
- Returns:
True if all Miller indices (h, k, l) satisfy 2*|hkl[i]| < size[i]
-
template<typename T>
void add_friedel_mates(ReciprocalGrid<T> &grid)¶ Reconstruct Friedel mates (complex conjugates) from half of reciprocal space.
For non-centrosymmetric structures, if F(h,k,l) is known but F(-h,-k,-l) is missing, fills in the conjugate. Respects grid axis order and half_l mode.
- Template Parameters:
T – Data type (typically complex<float> or complex<double>)
- Parameters:
grid – Reciprocal-space grid; missing Friedel-related reflections are filled in
-
template<typename T, typename DataProxy>
void initialize_hkl_grid(ReciprocalGrid<T> &grid, const DataProxy &data, std::array<int, 3> size, bool half_l, AxisOrder axis_order)¶ Initialize a reciprocal-space grid with cell, space group, and dimension info.
- Template Parameters:
T – Data type (typically complex<float> or complex<double>)
DataProxy – Type with unit_cell(), spacegroup() methods
- Parameters:
grid – Output reciprocal grid
data – Source providing unit cell and space group
size – Target grid dimensions [nu, nv, nw] (may be modified for half_l)
half_l – If true, store only l>=0; grid nw becomes nw/2+1
axis_order – XYZ (h,k,l) or ZYX ordering for grid axes
-
template<typename T, typename FPhi>
FPhiGrid<T> get_f_phi_on_grid(const FPhi &fphi, std::array<int, 3> size, bool half_l, AxisOrder axis_order = AxisOrder::XYZ)¶ Populate a reciprocal-space grid with complex structure factors from F,phi data.
- Template Parameters:
T – Data type (typically complex<float> or complex<double>)
FPhi – Type providing get_f(), get_phi(), and HKL-related methods
- Parameters:
fphi – F/phi data (typically MTZ or FPhiProxy)
size – Grid dimensions (from get_size_for_hkl()); will be adjusted for half_l
half_l – If true, store only l>=0; applies Friedel symmetry to l<0
axis_order – XYZ or ZYX grid axis ordering (default XYZ)
- Returns:
Grid with complex structure factors placed on HKL grid, symmetry-expanded
-
template<typename T, typename DataProxy>
ReciprocalGrid<T> get_value_on_grid(const DataProxy &data, size_t column, std::array<int, 3> size, bool half_l, AxisOrder axis_order = AxisOrder::XYZ)¶ Populate a reciprocal-space grid with real-valued data from a single column.
- Template Parameters:
T – Data type (typically float or double)
DataProxy – Type with get_num() and HKL-related methods
- Parameters:
data – Diffraction data (MTZ-like)
column – Column index (offset) to extract values
size – Grid dimensions; adjusted for half_l
half_l – If true, use only l>=0; applies Friedel symmetry to l<0
axis_order – XYZ or ZYX grid axis ordering
- Returns:
Grid with real values placed on HKL grid, symmetry-expanded
-
template<typename T>
void transform_f_phi_grid_to_map_(FPhiGrid<T> &&hkl, Grid<T> &map)¶ Convert a reciprocal-space grid to a real-space electron density map via inverse FFT.
Applies inverse 3D FFT using pocketfft. Handles half-l mode (Hermitian symmetry) and both axis orders (XYZ and ZYX). Negates imaginary parts and normalizes by cell volume.
- Template Parameters:
T – Scalar type (typically float or double)
- Parameters:
hkl – Reciprocal-space (F, phi) grid; modified in-place (complex conjugated and FFT’d)
map – Output real-space map; size and metadata set from hkl
-
template<typename T>
Grid<T> transform_f_phi_grid_to_map(FPhiGrid<T> &&hkl)¶ Convert a reciprocal-space grid to a real-space map via inverse FFT.
- Template Parameters:
T – Scalar type (float or double)
- Parameters:
hkl – Reciprocal-space grid (consumed)
- Returns:
Real-space map with same unit cell, space group, and axis order as input
-
template<typename T, typename FPhi>
Grid<T> transform_f_phi_to_map(const FPhi &fphi, std::array<int, 3> size, double sample_rate, bool exact_size = false, AxisOrder order = AxisOrder::XYZ)¶ Convert diffraction data (F, phi) to a real-space electron density map.
- Template Parameters:
T – Data type for output map (float or double)
FPhi – Type providing get_f(), get_phi(), unit_cell(), spacegroup()
- Parameters:
fphi – F/phi data
size – Minimum grid dimensions [nu, nv, nw]; auto-adjusted unless exact_size=true
sample_rate – Sampling rate (1/Angstrom); grid expanded if needed (ignored if exact_size)
exact_size – If true, use
sizeexactly without adjustment (must be FFT-friendly)order – XYZ or ZYX grid axis ordering
- Returns:
Real-space electron density map
-
template<typename T, typename FPhi>
Grid<T> transform_f_phi_to_map2(const FPhi &fphi, std::array<int, 3> min_size, double sample_rate, std::array<int, 3> exact_size, AxisOrder order = AxisOrder::XYZ)¶ Convert F,phi to map, supporting both minimum and exact size specifications.
- Template Parameters:
T – Map data type
FPhi – F/phi data type
- Parameters:
fphi – Diffraction data with F and phase
min_size – Minimum grid dimensions [nu, nv, nw]
sample_rate – Target sampling rate (1/Angstrom)
exact_size – Exact grid size to use; if any element is non-zero, exact_size overrides min_size
order – Grid axis order (XYZ or ZYX)
- Returns:
Real-space electron density map
-
template<typename T>
FPhiGrid<T> transform_map_to_f_phi(const Grid<T> &map, bool half_l, bool use_scale = true)¶ Convert a real-space electron density map to reciprocal-space structure factors via FFT.
- Template Parameters:
T – Scalar type (float or double)
- Parameters:
map – Real-space electron density grid (not modified)
half_l – If true, store only l>=0 (Hermitian symmetry); if false, store full reciprocal space
use_scale – If true, normalize by cell volume; if false, normalize by point count
- Throws:
Fails – if half_l=true and ZYX axis order (not yet supported)
- Returns:
Complex-valued reciprocal-space grid with structure factors F + i*0
-
template<typename DataProxy>
struct FPhiProxy : public DataProxy¶ - #include <gemmi/fourier.hpp>
Adapter to extract F (amplitude) and phi (phase) columns from diffraction data.
Wraps a data proxy to present only F and phi columns, with phi optionally defaulting to 0.
- Template Parameters:
DataProxy – Base data proxy type (typically MTZ-like with stride and columns)
Public Functions
-
inline FPhiProxy(const DataProxy &data_proxy, size_t f_col, size_t phi_col)¶
Initialize proxy with column indices.
- Parameters:
data_proxy – Source data
f_col – Column offset for amplitude F
phi_col – Column offset for phase (degrees); -1 means use 0
- Throws:
Fails – if column indices are out of range
-
inline double get_phi(size_t offset) const¶
Get phase in radians at given offset; returns 0 if phi column not set.
-
template<typename T>
Utility functions for working with reflections and reciprocal space.
Provides functions to enumerate unique reflections within a resolution range, respecting space group symmetry and systematically absent reflections.
-
namespace gemmi
Functions
-
template<typename Func>
void for_all_reflections(Func func, const UnitCell &cell, const SpaceGroup *spacegroup, double dmin, double dmax = 0., bool unique = true)¶ Iterate over all reflections within a resolution range, applying a function to each.
Generates Miller indices (h, k, l) in the resolution range [dmax, dmin] (or [dmin, inf) if dmax=0). Checks space group symmetries and excludes systematically absent reflections.
Note
dmin should include a small margin (e.g., 1e-6 Angstrom) to avoid numerical boundary issues.
- Template Parameters:
Func – Callable taking a Miller index array
- Parameters:
func – Function to apply to each valid reflection
cell – Unit cell parameters
spacegroup – Space group for symmetry and systematic absences
dmin – Minimum d-spacing (Angstroms, lower resolution limit)
dmax – Maximum d-spacing (Angstroms, higher resolution limit); 0 = unlimited; INFINITY = exact high-res limit
unique – If true, iterate only over asymmetric unit (one per symmetry equivalent); if false, all in range
-
inline int count_reflections(const UnitCell &cell, const SpaceGroup *spacegroup, double dmin, double dmax = 0., bool unique = true)¶
Count the number of unique (or all) reflections in a resolution range.
Note
dmin should include a small margin for numerical accuracy.
- Parameters:
cell – Unit cell parameters
spacegroup – Space group
dmin – Minimum d-spacing (Angstroms)
dmax – Maximum d-spacing (Angstroms); 0 = no upper limit
unique – If true, count only asymmetric unit; if false, count all
- Returns:
Total number of reflections satisfying the criteria
-
inline std::vector<Miller> make_miller_vector(const UnitCell &cell, const SpaceGroup *spacegroup, double dmin, double dmax = 0., bool unique = true)¶
Generate a vector of all reflections in a resolution range.
Useful for generating a complete or unique list of expected reflections for comparison with data.
- Parameters:
cell – Unit cell parameters
spacegroup – Space group
dmin – Minimum d-spacing (Angstroms)
dmax – Maximum d-spacing (Angstroms); 0 = no upper limit
unique – If true, return only asymmetric unit; if false, all in range
- Returns:
Vector of Miller indices [h, k, l] sorted in enumeration order
-
template<typename Func>
Note
The following sections will be populated by subsequent PRs (7–10) in this series. See PR #413 for the full roadmap.
Chemistry and Restraints¶
Chemical component definitions, monomer library, topology of restraints applied to a model, hydrogen placement, link hunting, and related I/O helpers.
(Full documentation added in PR 8.)
-
namespace gemmi
Enums
-
enum class BondType¶
Bond type enum for restraints.
Values:
-
enumerator Unspec¶
Unspecified bond type.
-
enumerator Single¶
Single bond.
-
enumerator Double¶
Double bond.
-
enumerator Triple¶
Triple bond.
-
enumerator Aromatic¶
Aromatic bond.
-
enumerator Deloc¶
Delocalized bond.
-
enumerator Metal¶
Metal coordination bond.
-
enumerator Unspec¶
Functions
-
inline bool is_aromatic_or_deloc(BondType type)¶
Check if bond type is aromatic or delocalized.
- Parameters:
type – Bond type to check.
- Returns:
True if type is Aromatic or Deloc.
-
template<typename Restr>
double angle_z(double value_rad, const Restr &restr, double full = 360.)¶ Compute z-score (deviation in standard deviations) for angle restraints.
- Template Parameters:
Restr – Restraint type with value (degrees) and esd (degrees) members.
- Parameters:
value_rad – Observed angle in radians.
restr – Restraint with ideal value and standard deviation.
full – Full circle in degrees (default 360, use 180 for some torsions).
- Returns:
Z-score = |observed - ideal| / esd.
-
inline double chiral_abs_volume(double bond1, double bond2, double bond3, double angle1, double angle2, double angle3)¶
Compute absolute chiral volume from bond lengths and angles.
Note
Uses the formula: mult * sqrt(max(0, x + y)) where mult = bond1*bond2*bond3.
- Parameters:
bond1 – First bond length (Å).
bond2 – Second bond length (Å).
bond3 – Third bond length (Å).
angle1 – First angle (degrees).
angle2 – Second angle (degrees).
angle3 – Third angle (degrees).
- Returns:
Absolute chiral volume.
-
inline BondType bond_type_from_string(const std::string &s)¶
Parse string to BondType enum.
- Parameters:
s – String representation (e.g., “single”, “double”, “aromatic”, “deloc”, “metal”).
- Throws:
std::out_of_range – for unexpected bond type strings.
- Returns:
Parsed BondType, or Unspec for null or “coval”.
-
inline const char *bond_type_to_string(BondType btype)¶
Convert BondType enum to string.
- Parameters:
btype – Bond type to convert.
- Returns:
String representation (“.”, “single”, “double”, “triple”, “aromatic”, “deloc”, “metal”).
-
inline float order_of_bond_type(BondType btype)¶
Get bond order (multiplicity) for a BondType.
- Parameters:
btype – Bond type.
- Returns:
Bond order: 1.0 (single/metal), 1.5 (aromatic/deloc), 2.0 (double), 3.0 (triple), 0.0 (unspec).
-
inline ChiralityType chirality_from_string(const std::string &s)¶
Parse string to ChiralityType enum.
- Parameters:
s – String representation: “p” or “P” for Positive, “n” or “N” for Negative, “b” or “B” or “.” for Both.
- Throws:
std::out_of_range – for unexpected chirality strings (e.g., crossN types).
- Returns:
Parsed ChiralityType.
-
inline ChiralityType chirality_from_flag_and_volume(const std::string &s, double volume)¶
Determine ChiralityType from stereo flag and computed chiral volume.
- Parameters:
s – Volume flag string: “s” or “S” (signed volume), “n” or “N” (no stereochemistry).
volume – Computed chiral volume.
- Throws:
std::out_of_range – for unexpected flag strings.
- Returns:
ChiralityType: Positive or Negative based on volume sign (if “s” flag), or Both (if “n” flag).
-
inline const char *chirality_to_string(ChiralityType chir_type)¶
Convert ChiralityType enum to string.
- Parameters:
chir_type – Chirality type.
- Returns:
String representation (“positive”, “negative”, “both”).
-
inline ChemComp make_chemcomp_from_block(const cif::Block &block_)¶
Parse a ChemComp from a CIF block. Reads all _chem_comp* tables from the block (atoms, bonds, angles, torsions, chiralities, planes, aliases).
- Parameters:
block_ – CIF block containing chemical component definition.
- Returns:
Constructed ChemComp with all restraints and atom data.
-
struct ChemComp¶
- #include <gemmi/chemcomp.hpp>
Chemical component (monomer) from a restraint library. Represents a residue type from the Refmac monomer library or PDB CCD.
Public Types
-
enum class Group¶
Chemical component group classification (used in _chem_comp.group and _chem_link.group_comp_N).
Values:
-
enumerator Peptide¶
Peptide (L-amino acid)
-
enumerator PPeptide¶
P-peptide (peptide with P configuration)
-
enumerator MPeptide¶
M-peptide (cyclic peptide)
-
enumerator Dna¶
DNA nucleotide.
-
enumerator Rna¶
RNA nucleotide.
-
enumerator DnaRna¶
DNA/RNA mixed nucleotide.
-
enumerator Pyranose¶
Pyranose sugar ring.
-
enumerator Ketopyranose¶
Ketopyranose sugar ring.
-
enumerator Furanose¶
Furanose sugar ring.
-
enumerator NonPolymer¶
Non-polymer ligand.
-
enumerator Null¶
Unset or unknown group.
-
enumerator Peptide¶
Public Functions
-
inline const Aliasing &get_aliasing(Group g) const¶
Get atom name aliasing for a specific polymer group.
- Parameters:
g – Group to find aliasing for.
- Throws:
Calls – fail() if aliasing is not found for this group.
- Returns:
Reference to the Aliasing.
-
inline void set_group(const std::string &s)¶
Set group from string and update parsed Group enum.
- Parameters:
s – Group identifier string.
-
inline std::vector<Atom>::const_iterator find_atom(const std::string &atom_id) const¶
Const version of find_atom().
-
inline bool has_atom(const std::string &atom_id) const¶
Check if an atom with given name exists.
- Parameters:
atom_id – Atom name to search for.
- Returns:
True if atom exists.
-
inline std::vector<Atom>::iterator find_atom_by_old_name(const std::string &old_id)¶
Find an atom by legacy name.
- Parameters:
old_id – Legacy atom name (old_id field).
- Returns:
Iterator to the Atom, or atoms.end() if not found.
-
inline std::vector<Atom>::const_iterator find_atom_by_old_name(const std::string &old_id) const¶
Const version of find_atom_by_old_name().
-
inline bool has_old_names() const¶
Check if any atom has non-trivial legacy names.
- Returns:
True if at least one atom has old_id set and different from id.
-
inline int get_atom_index(const std::string &atom_id) const¶
Get index of an atom by name (throw if not found).
- Parameters:
atom_id – Atom name to search for.
- Throws:
Calls – fail() if atom is not found.
- Returns:
Zero-based index in atoms vector.
-
inline int find_atom_index(const std::string &atom_id) const¶
Find index of an atom by name.
- Parameters:
atom_id – Atom name to search for.
- Returns:
Zero-based index in atoms vector, or -1 if not found.
-
inline std::map<std::string, size_t> make_atom_index() const¶
Build a map of atom names to indices.
- Returns:
Map from atom id to vector index.
-
inline const Atom &get_atom(const std::string &atom_id) const¶
Get an atom by name (throw if not found).
- Parameters:
atom_id – Atom name to search for.
- Throws:
Calls – get_atom_index() which may call fail().
- Returns:
Reference to the Atom.
-
inline void remove_nonmatching_restraints()¶
Remove restraints referring to absent atoms. Called after atoms have been removed to keep restraints consistent.
Public Members
-
bool has_coordinates = false¶
True if xyz coordinates are available.
-
Restraints rt¶
Geometric restraints.
Public Static Functions
-
static inline Group read_group(const std::string &str)¶
Parse group string to Group enum.
- Parameters:
str – Group identifier string (e.g., “peptide”, “P-peptide”, “DNA”).
- Returns:
Parsed Group enum value, or Group::Null if unrecognized.
-
static inline const char *group_str(Group g)¶
Get string representation of a Group enum value.
- Parameters:
g – Group enum value.
- Returns:
String representation (e.g., “peptide”, “P-peptide”, “DNA”, “.”).
-
struct Aliasing¶
- #include <gemmi/chemcomp.hpp>
Atom naming aliasing for a specific polymer group.
Public Functions
-
enum class Group¶
-
struct Restraints¶
- #include <gemmi/chemcomp.hpp>
Geometric restraints for a chemical component. Stores bond, angle, torsion, chirality, and planarity restraints.
Public Types
Public Functions
-
inline bool empty() const¶
Check if all restraint lists are empty.
- Returns:
True if there are no restraints of any type.
-
template<typename T>
inline std::vector<Bond>::iterator find_bond(const T &a1, const T &a2)¶ Find a Bond between two atoms.
Note
Bond order (a1, a2 vs a2, a1) is not significant.
-
template<typename T>
inline std::vector<Bond>::const_iterator find_bond(const T &a1, const T &a2) const¶ Const version of find_bond().
-
inline const Bond &get_bond(const AtomId &a1, const AtomId &a2) const¶
Get a Bond between two atoms (throw if not found).
- Parameters:
a1 – First atom.
a2 – Second atom.
- Throws:
Calls – fail() if bond is not found.
- Returns:
Reference to the Bond.
-
template<typename T>
inline bool are_bonded(const T &a1, const T &a2) const¶ Check if two atoms are directly bonded.
- Template Parameters:
T – Atom identifier type (AtomId or string).
- Parameters:
a1 – First atom.
a2 – Second atom.
- Returns:
True if a bond exists between a1 and a2.
-
template<typename T>
inline const AtomId *first_bonded_atom(const T &a) const¶ Find the first atom bonded to the given atom.
-
inline std::vector<AtomId> find_shortest_path(const AtomId &a, const AtomId &b, std::vector<AtomId> visited, int min_length = 1) const¶
Find shortest bond path between two atoms (BFS algorithm).
- Parameters:
a – Start atom.
b – End atom.
visited – List of initially visited atoms (to exclude from search).
min_length – Minimum path length required (default 1).
- Returns:
Vector of AtomIds forming the shortest path from a to b, or empty if not found.
-
template<typename T>
inline std::vector<Angle>::iterator find_angle(const T &a, const T &b, const T &c)¶ Find an Angle restraint with given atoms.
Note
The order of peripheral atoms (a, c) is not significant.
-
template<typename T>
inline std::vector<Angle>::const_iterator find_angle(const T &a, const T &b, const T &c) const¶ Const version of find_angle().
-
inline const Angle &get_angle(const AtomId &a, const AtomId &b, const AtomId &c) const¶
Get an Angle restraint with given atoms (throw if not found).
- Parameters:
a – First atom (peripheral).
b – Central atom.
c – Third atom (peripheral).
- Throws:
Calls – fail() if angle restraint is not found.
- Returns:
Reference to the Angle.
-
template<typename T>
inline std::vector<Torsion>::iterator find_torsion(const T &a, const T &b, const T &c, const T &d)¶ Find a Torsion restraint with given atoms.
Note
Forward and reverse orderings (a-b-c-d vs d-c-b-a) are considered equivalent.
-
template<typename T>
inline std::vector<Torsion>::const_iterator find_torsion(const T &a, const T &b, const T &c, const T &d) const¶ Const version of find_torsion().
-
template<typename T>
inline std::vector<Chirality>::iterator find_chir(const T &ctr, const T &a, const T &b, const T &c)¶ Find a Chirality restraint for a given stereocenter.
Note
The order of substituents (a, b, c) is not significant.
-
template<typename T>
inline std::vector<Chirality>::const_iterator find_chir(const T &ctr, const T &a, const T &b, const T &c) const¶ Const version of find_chir().
-
inline double chiral_abs_volume(const Restraints::Chirality &ch) const¶
Compute chiral volume from restraints.
- Parameters:
ch – Chirality restraint.
- Throws:
May – call fail() if required bond or angle restraints are missing.
- Returns:
Absolute chiral volume computed from bond and angle restraints.
-
inline Plane &get_or_add_plane(const std::string &label)¶
Get a Plane by label, creating it if absent.
-
inline void rename_atom(const AtomId &atom_id, const std::string &new_name)¶
Rename an atom throughout all restraints.
Note
Updates all occurrences in bonds, angles, torsions, chiralities, and planes.
- Parameters:
atom_id – The atom to rename (identified by comp and atom name).
new_name – New atom name.
Public Members
Public Static Functions
-
struct Angle¶
- #include <gemmi/chemcomp.hpp>
Angle restraint between three atoms.
Public Functions
-
inline double radians() const¶
Convert ideal angle to radians.
- Returns:
Ideal angle in radians.
Public Members
-
double value¶
Ideal angle in degrees.
-
double esd¶
Estimated standard deviation in degrees
Public Static Functions
-
static inline const char *what()¶
Get restraint type name.
-
inline double radians() const¶
-
struct AtomId¶
- #include <gemmi/chemcomp.hpp>
Atom identifier used in restraints.
Public Functions
-
Atom *get_from(Residue &res1, Residue *res2, char alt, char altloc2) const¶
Get the Atom from residues.
- Parameters:
res1 – First residue to search.
res2 – Optional second residue for link restraints.
alt – Alternate location character.
altloc2 – Alternate location for second residue (rare case for links with different altloc).
- Returns:
Pointer to the Atom, or nullptr if not found.
-
const Atom *get_from(const Residue &res1, const Residue *res2, char alt, char altloc2) const¶
Const version of get_from().
-
Atom *get_from(Residue &res1, Residue *res2, char alt, char altloc2) const¶
-
struct Bond¶
- #include <gemmi/chemcomp.hpp>
Bond restraint between two atoms.
Public Functions
-
inline double distance(DistanceOf of) const¶
Get ideal bond distance.
- Parameters:
of – Reference frame (electron cloud or nucleus).
- Returns:
Ideal distance in Å.
Public Members
-
bool aromatic¶
True if part of aromatic system.
-
double value¶
Ideal bond length (Å, electron cloud)
-
double esd¶
Estimated standard deviation of value.
-
double value_nucleus¶
Ideal length to nucleus.
-
double esd_nucleus¶
ESD of nucleus length.
-
int ordinal = 0¶
Ordering index
Public Static Functions
-
static inline const char *what()¶
Get restraint type name.
-
inline double distance(DistanceOf of) const¶
-
struct Chirality¶
- #include <gemmi/chemcomp.hpp>
Chirality (stereochemistry) restraint for a stereocenter.
Public Functions
-
inline bool is_wrong(double volume) const¶
Check if observed chiral volume contradicts expected chirality.
- Parameters:
volume – Computed chiral volume.
- Returns:
True if the sign of volume disagrees with expected chirality.
Public Members
-
ChiralityType sign¶
Expected chirality type.
Public Static Functions
-
static inline const char *what()¶
Get restraint type name.
-
inline bool is_wrong(double volume) const¶
-
struct Plane¶
- #include <gemmi/chemcomp.hpp>
Planarity restraint for a group of atoms.
Public Members
-
double esd¶
Estimated standard deviation of planarity restraint
Public Static Functions
-
static inline const char *what()¶
Get restraint type name.
-
double esd¶
-
struct Torsion¶
- #include <gemmi/chemcomp.hpp>
Torsion (dihedral) restraint between four atoms.
Public Members
-
double value = NAN¶
Ideal torsion angle in degrees.
-
double esd = 0.0¶
Estimated standard deviation in degrees.
-
int period = 0¶
Periodicity of the torsion
Public Static Functions
-
static inline const char *what()¶
Get restraint type name.
-
double value = NAN¶
-
inline bool empty() const¶
-
enum class BondType¶
-
namespace gemmi
Functions
-
int generate_chemcomp_xyz_from_restraints(ChemComp &cc)¶
Generate idealized 3D coordinates for a chemical component. Generates a deterministic idealized conformer by applying bond lengths, angles, and torsion restraints in sequence. Modifies cc.atoms[*].xyz in-place.
Note
Atoms without restraints may remain uninitialized (NAN coordinates).
- Parameters:
cc – ChemComp to generate coordinates for; atoms must be present.
- Returns:
Number of atoms assigned finite coordinates.
-
double refine_chemcomp_xyz(ChemComp &cc)¶
Refine chemical component coordinates against restraints. Refines atom coordinates against bond and angle restraints using Levenberg-Marquardt least squares optimization. Modifies cc.atoms[*].xyz in-place.
Note
Requires atoms to have initial finite coordinates (e.g., from generate_chemcomp_xyz_from_restraints).
- Parameters:
cc – ChemComp with initial coordinates to refine.
- Returns:
Final weighted sum of squared residuals (WSSR) of the fit.
-
int generate_chemcomp_xyz_from_restraints(ChemComp &cc)¶
-
namespace gemmi
Functions
-
struct EnerLib¶
- #include <gemmi/ener_lib.hpp>
Energy library from CCP4 ener_lib.cif. Stores atomic properties and ideal bond parameters used for structure validation.
Public Types
Public Functions
-
inline EnerLib()¶
Public Members
-
struct Atom¶
- #include <gemmi/ener_lib.hpp>
Atomic properties indexed by atom type.
-
inline EnerLib()¶
-
struct EnerLib¶
-
namespace gemmi
Functions
-
inline bool atom_match_with_alias(const std::string &atom_id, const std::string &atom, const ChemComp::Aliasing *aliasing)¶
Check if an atom ID matches a canonical atom name, resolving aliases.
- Parameters:
atom_id – Atom identifier to check (may be aliased)
atom – Canonical atom name
aliasing – Optional aliasing rules to resolve atom_id
- Returns:
true if atom_id matches atom (directly or via aliasing)
-
inline MonLib read_monomer_lib(const std::string &monomer_dir, const std::vector<std::string> &resnames, const std::string &libin = "", bool ignore_missing = false)¶
Free function wrapper to read monomer library.
- Deprecated:
Use MonLib::read_monomer_lib() method instead.
- Parameters:
monomer_dir – Directory containing monomer library files
resnames – List of chemical component names to load
libin – Optional path to additional library CIF file
ignore_missing – If true, silently ignore missing components; if false, throw exception
- Returns:
Populated MonLib instance
-
struct ChemLink¶
- #include <gemmi/monlib.hpp>
Chemical link definition (bond, angle, dihedral between residues).
Public Functions
-
int calculate_score(const Residue &res1, const Residue *res2, char alt, char alt2, const ChemComp::Aliasing *aliasing1, const ChemComp::Aliasing *aliasing2) const¶
Calculate matching score for this link between two residues. If multiple ChemLinks match a bond, the one with highest score should be used.
- Parameters:
res1 – First residue
res2 – Second residue (nullptr if not available)
alt – First residue alternate location indicator
alt2 – Second residue alternate location indicator
aliasing1 – Aliasing rules for first residue
aliasing2 – Aliasing rules for second residue
- Returns:
Numeric score indicating match quality (higher is better)
Public Members
-
Restraints rt¶
Restraints (bonds, angles, dihedrals, etc.)
-
struct Side¶
- #include <gemmi/monlib.hpp>
Specification of one side of a chemical link.
Public Functions
-
inline bool matches_group(Group res) const¶
Check if this side matches a given chemical group.
- Parameters:
res – Group to test against
- Returns:
true if the side specification matches the group
-
inline int specificity() const¶
Calculate specificity score for matching priority.
- Returns:
Higher scores indicate more specific matches (specific component > group-based)
-
inline bool matches_group(Group res) const¶
-
int calculate_score(const Residue &res1, const Residue *res2, char alt, char alt2, const ChemComp::Aliasing *aliasing1, const ChemComp::Aliasing *aliasing2) const¶
-
struct ChemMod¶
- #include <gemmi/monlib.hpp>
Chemical modification (alteration to a chemical component).
Public Functions
Public Members
-
Restraints rt¶
Modified restraints.
-
struct AtomMod¶
- #include <gemmi/monlib.hpp>
Modification to a single atom.
-
Restraints rt¶
-
struct MonLib¶
- #include <gemmi/monlib.hpp>
Monomer library with chemical components, links, and modifications. Stores the (Refmac) restraints dictionary including monomers, chemical links, and modifications, along with atomic energy parameters.
Public Functions
-
inline const ChemLink *get_link(const std::string &link_id) const¶
Find a chemical link by identifier.
- Parameters:
link_id – Link identifier
- Returns:
Pointer to ChemLink, or nullptr if not found
-
inline const ChemMod *get_mod(const std::string &name) const¶
Find a chemical modification by name.
- Parameters:
name – Modification name
- Returns:
Pointer to ChemMod, or nullptr if not found
-
inline std::tuple<const ChemLink*, bool, const ChemComp::Aliasing*, const ChemComp::Aliasing*> match_link(const Residue &res1, const std::string &atom1, char alt1, const Residue &res2, const std::string &atom2, char alt2, double min_bond_sq = 0) const¶
Find the most specific chemical link between two residues and atoms. Returns the most specific link and a flag indicating if the residue order is inverted (comp2-comp1) in the link definition.
- Parameters:
res1 – First residue
atom1 – Atom name in first residue
alt1 – Alternate location indicator for first atom
res2 – Second residue
atom2 – Atom name in second residue
alt2 – Alternate location indicator for second atom
min_bond_sq – Minimum squared bond length to accept
- Returns:
Tuple of (link, inverted_flag, aliasing1, aliasing2); link is nullptr if no match found
-
inline void add_monomer_if_present(const cif::Block &block)¶
Add a chemical component from a CIF block if it contains atom definitions.
- Parameters:
block – CIF block containing chemical component data
-
inline bool link_side_matches_residue(const ChemLink::Side &side, const std::string &res_name, ChemComp::Aliasing const **aliasing) const¶
Check if a link side specification matches a residue.
- Parameters:
side – Link side specification to test
res_name – Residue name
aliasing – Output parameter: aliasing rules if matched via alias, nullptr otherwise
- Returns:
true if side matches res_name (exactly or via group/alias)
-
inline std::string path(const std::string &code) const¶
Returns path to the monomer CIF file (the file may not exist).
- Parameters:
code – Chemical component code
- Returns:
Full file path constructed from monomer_dir and code
-
void read_monomer_doc(const cif::Document &doc)¶
Read monomer library data from a CIF document.
- Parameters:
doc – CIF document containing chemical components, links, and/or modifications
-
void read_monomer_cif(const std::string &path_)¶
Read monomer library data from a CIF file.
- Parameters:
path_ – File path to read
-
inline void set_monomer_dir(const std::string &monomer_dir_)¶
Set the directory for monomer CIF files.
- Parameters:
monomer_dir_ – Directory path (trailing slash is optional and auto-added)
-
bool read_monomer_lib(const std::string &monomer_dir_, const std::vector<std::string> &resnames, const Logger &logger)¶
Read mon_lib_list.cif, ener_lib.cif and required monomers.
- Parameters:
monomer_dir_ – Directory containing monomer library files
resnames – List of chemical component names to load
logger – Logger for diagnostic messages
- Returns:
true if all requested monomers were added
Public Members
-
inline const ChemLink *get_link(const std::string &link_id) const¶
-
inline bool atom_match_with_alias(const std::string &atom_id, const std::string &atom, const ChemComp::Aliasing *aliasing)¶
-
namespace gemmi
Enums
-
enum class HydrogenChange¶
Specification for how to modify hydrogen atoms during topology preparation.
Values:
-
enumerator NoChange¶
Leave hydrogen atoms as they are in the input model.
-
enumerator Shift¶
Move hydrogen atoms to standard positions based on geometry.
-
enumerator Remove¶
Remove all hydrogen atoms from the model.
-
enumerator ReAdd¶
Remove all hydrogen atoms and then re-add them at standard positions.
-
enumerator ReAddButWater¶
Remove and re-add hydrogen atoms, except in water molecules.
-
enumerator ReAddKnown¶
Re-add only hydrogen atoms that are known in the monomer library.
-
enumerator NoChange¶
Functions
-
std::unique_ptr<Topo> prepare_topology(Structure &st, MonLib &monlib, size_t model_index, HydrogenChange h_change, bool reorder, const Logger &logger = {}, bool ignore_unknown_links = false, bool use_cispeps = false)¶
Prepare the topology for a Structure.
Creates and initializes a Topo object for the given Structure and model, with optional hydrogen atom adjustments.
- Parameters:
st – The Structure.
monlib – The monomer library.
model_index – Index of the model to use (typically 0).
h_change – Specification for how to modify hydrogen atoms.
reorder – If true, reorder atoms in the model.
logger – Logger for warnings and informational messages.
ignore_unknown_links – If true, skip links not in the library.
use_cispeps – If true, identify and mark cis peptide bonds.
- Returns:
A unique_ptr to the initialized Topo.
-
std::unique_ptr<ChemComp> make_chemcomp_with_restraints(const Residue &res)¶
Create a ChemComp with restraints for a residue.
Generates a ChemComp with default restraints (bonds, angles, torsions, chiral volumes) inferred from the residue’s atom geometry.
-
std::vector<AtomAddress> find_missing_atoms(const Topo &topo, bool including_hydrogen = false)¶
Find atoms in the model that are missing from the restraints.
Identifies atoms that are present in the model but not found in the corresponding chemical component definitions.
- Parameters:
topo – The topology with applied restraints.
including_hydrogen – If true, include hydrogen atoms in the search.
- Returns:
Vector of addresses of missing atoms.
-
struct Topo¶
- #include <gemmi/topo.hpp>
Topology of restraints from a monomer library applied to a crystallographic model.
Non-copyable due to internal atom pointers set up during apply_restraints() that reference ResInfo chemical component restraint data.
Public Types
Public Functions
-
Topo() = default¶
-
inline ResInfo *find_resinfo(const Residue *res)¶
Find the ResInfo for a residue.
- Parameters:
res – The residue to search for.
- Returns:
Pointer to the ResInfo, or nullptr if not found.
-
inline Bond *first_bond_in_link(const Link &link)¶
Get the first bond restraint in a link.
- Parameters:
link – The link to search.
- Returns:
Pointer to the first Bond in link.link_rules, or nullptr if none.
-
inline const Restraints::Bond *take_bond(const Atom *a, const Atom *b) const¶
Find a bond restraint between two atoms.
- Parameters:
a – First atom.
b – Second atom.
- Returns:
Pointer to the bond restraint, or nullptr if no bond is restrained.
-
inline const Restraints::Angle *take_angle(const Atom *a, const Atom *b, const Atom *c) const¶
Find an angle restraint between three atoms.
- Parameters:
a – First atom.
b – Center atom.
c – Third atom.
- Returns:
Pointer to the angle restraint, or nullptr if no angle is restrained.
-
inline const Chirality *get_chirality(const Atom *ctr) const¶
Get the chirality restraint for a chiral center.
- Parameters:
ctr – The chiral center atom.
- Returns:
Pointer to the Chirality restraint, or nullptr if none.
-
double ideal_chiral_abs_volume(const Chirality &ch) const¶
Get the ideal absolute chiral volume for a chirality restraint.
- Parameters:
ch – The chirality restraint.
- Returns:
Ideal absolute value of the chiral volume.
-
std::vector<Rule> apply_restraints(const Restraints &rt, Residue &res, Residue *res2, Asu asu, char altloc1, char altloc2, bool require_alt)¶
Apply restraints from a Restraints object to a residue.
- Parameters:
rt – The restraints specification.
res – The residue to apply restraints to.
res2 – Second residue (for inter-residue restraints), or nullptr.
asu – Asymmetric unit relationship between atoms.
altloc1 – Alternate location indicator for atoms in res.
altloc2 – Alternate location indicator for atoms in res2.
require_alt – If true, only apply restraints matching the altloc.
- Returns:
Vector of restraint rules applied.
-
void initialize_refmac_topology(Structure &st, Model &model0, MonLib &monlib, bool ignore_unknown_links = false)¶
Initialize the topology from a Structure and MonLib.
This method populates the internal topology state from the model and monomer library.
Note
After this step, do not add or remove residues from the model, as Topo holds internal pointers to them.
Note
The monlib may be modified by the addition of extra links from the model.
- Parameters:
st – The Structure (non-const to assign link_id to connections).
model0 – The Model (non-const to store pointers to residues).
monlib – The MonLib (non-const; may be modified by addition of extra links).
ignore_unknown_links – If true, skip links not in the library.
-
void apply_all_restraints(const MonLib &monlib)¶
Apply all restraints from the monomer library to the model.
This populates the bonds, angles, torsions, chirs, and planes vectors.
Note
This step stores pointers to gemmi::Atom’s from model0, so after this step do not add or remove atoms from the model.
- Parameters:
monlib – The monomer library (used only for link information).
-
void create_indices()¶
Prepare the atom-to-restraint indices.
Populates bond_index, angle_index, torsion_index, and plane_index for efficient lookups.
-
Link *find_polymer_link(const AtomAddress &a1, const AtomAddress &a2)¶
Find a polymer link between two atoms.
Searches for a matching Link in ResInfo::prev lists.
- Parameters:
a1 – First atom address.
a2 – Second atom address.
- Returns:
Pointer to the Link, or nullptr if no matching link is found.
Public Members
-
bool only_bonds = false¶
Internal flag for apply_restraints().
-
std::multimap<const Atom*, Bond*> bond_index¶
Index of bonds by atom.
Maps each atom to the bonds it is part of.
-
std::multimap<const Atom*, Angle*> angle_index¶
Index of angles by center atom.
Maps each atom to the angles where it is the center atom (atoms[1]).
Public Static Functions
Private Functions
-
void setup_connection(Connection &conn, Model &model0, MonLib &monlib, bool ignore_unknown_links)¶
Private Members
-
std::vector<std::unique_ptr<Restraints>> rt_storage¶
-
struct Angle¶
- #include <gemmi/topo.hpp>
An angle restraint between three atoms.
Holds a reference to the restraint specification and the three atoms, and provides methods to calculate the angle and z-score.
Public Functions
-
inline double calculate_z() const¶
Calculate the z-score for the current angle.
- Returns:
Z-score of the observed angle relative to the restraint.
-
inline double calculate_z() const¶
-
struct Bond¶
- #include <gemmi/topo.hpp>
A bond restraint between two atoms.
Holds a reference to the restraint specification and the two atoms, and provides methods to calculate the bond distance and z-score.
Public Functions
-
inline double calculate() const¶
Calculate the bond distance in Angstroms.
- Returns:
Distance between atoms, or NAN if atoms are in different asymmetric units.
-
inline double calculate_z_(double d) const¶
Calculate the z-score for a given distance.
- Parameters:
d – The distance value.
- Returns:
Z-score: (distance - ideal_value) / esd
-
inline double calculate_z() const¶
Calculate the z-score for the current bond distance.
- Returns:
Z-score of the observed distance relative to the restraint.
-
inline double calculate() const¶
-
struct ChainInfo¶
- #include <gemmi/topo.hpp>
Information about a sub-chain (continuous polymer segment).
Public Functions
-
ChainInfo(ResidueSpan &subchain, const Chain &chain, const Entity *ent)¶
Constructor.
- Parameters:
subchain – The residue span for this sub-chain.
chain – The full Chain.
ent – Pointer to the Entity, or nullptr.
Public Members
-
bool polymer¶
Whether this sub-chain is a polymer.
-
PolymerType polymer_type¶
Type of polymer (protein, DNA, RNA, etc.).
-
ChainInfo(ResidueSpan &subchain, const Chain &chain, const Entity *ent)¶
-
struct Chirality¶
- #include <gemmi/topo.hpp>
A chirality restraint on the stereochemistry around a chiral center.
Holds a reference to the restraint specification and the four atoms (center and three substituents), and provides methods to calculate the chiral volume and z-score.
Public Functions
-
inline double calculate() const¶
Calculate the chiral volume.
- Returns:
The signed chiral volume (a scalar triple product).
-
inline double calculate_z(double ideal_abs_vol, double esd) const¶
Calculate the z-score for the chiral volume.
- Parameters:
ideal_abs_vol – Ideal absolute value of the chiral volume.
esd – Standard deviation of the restraint.
- Returns:
Z-score: absolute deviation from ideal value divided by esd.
-
inline bool check() const¶
Check whether the chirality is correct.
- Returns:
True if the chirality sign matches the restraint specification.
-
inline double calculate() const¶
-
struct FinalChemComp¶
- #include <gemmi/topo.hpp>
Final chemical component with modifications applied.
Represents a ChemComp with all modifications already applied.
-
struct Link¶
- #include <gemmi/topo.hpp>
A link between two residues with associated restraints.
Describes a covalent link (such as a peptide bond or a disulfide bridge) between two residues, including the restraint rules and bonding information.
Public Functions
Public Members
-
char alt1 = '\0'¶
Alternate location indicator for res1.
-
char alt2 = '\0'¶
Alternate location indicator for res2.
-
Asu asu = Asu::Any¶
Asymmetric unit relationship between res1 and res2.
Used only in Links in ChainInfo::extras.
-
bool is_cis = false¶
Helper field for CISPEP record generation in output.
-
int atom1_name_id = 0¶
Cached atom name ID for res1 (used in find_polymer_link).
-
int atom2_name_id = 0¶
Cached atom name ID for res2 (used in find_polymer_link).
-
const ChemComp::Aliasing *aliasing1 = nullptr¶
Pointer to aliasing information for res1.
Points to a vector element in ChemComp::aliases. The pointer remains valid even if a ChemComp is moved.
-
const ChemComp::Aliasing *aliasing2 = nullptr¶
Pointer to aliasing information for res2.
Points to a vector element in ChemComp::aliases. The pointer remains valid even if a ChemComp is moved.
-
char alt1 = '\0'¶
-
struct Mod¶
- #include <gemmi/topo.hpp>
A chemical modification applied to a residue.
Describes a ChemMod from the monomer library and the specific atom group (aliasing) to which it applies.
Public Functions
-
struct Plane¶
- #include <gemmi/topo.hpp>
A planar restraint on a group of atoms.
Holds a reference to the restraint specification and the atoms that should lie in a plane.
Public Functions
-
struct ResInfo¶
- #include <gemmi/topo.hpp>
Information about a residue in the topology.
Contains the residue, its chemical composition (with modifications), link information, and hydrogen bonding data.
Public Functions
-
inline ResInfo(Residue *r)¶
Constructor.
- Parameters:
r – The residue to associate with this ResInfo.
-
inline void add_mod(const std::string &m, const ChemComp::Aliasing *aliasing, char altloc)¶
Add a modification to this residue.
- Parameters:
m – The ID of the modification (from MonLib).
aliasing – Pointer to the aliasing information, or nullptr.
altloc – Alternate location indicator (‘\0’ for all conformers).
Public Members
-
std::vector<Link> prev¶
Links to previous residue(s).
In case of microheterogeneity, there may be 2 or more previous residues.
-
const ChemComp *orig_chemcomp = nullptr¶
Pointer to the original ChemComp from MonLib::monomers.
-
std::vector<FinalChemComp> chemcomps¶
ChemComps with modifications applied, per conformer.
-
std::array<Topo::ResInfo*, 2> donors = {nullptr, nullptr}¶
Two hydrogen-bonded donors with lowest energy (for DSSP).
-
inline ResInfo(Residue *r)¶
-
struct Rule¶
- #include <gemmi/topo.hpp>
A reference to a restraint rule.
Identifies which type of restraint and its index in the corresponding vector (bonds, angles, torsions, chirs, or planes) in Topo.
-
struct Torsion¶
- #include <gemmi/topo.hpp>
A torsion (dihedral) angle restraint between four atoms.
Holds a reference to the restraint specification and the four atoms, and provides methods to calculate the dihedral angle and z-score.
Public Functions
-
inline double calculate() const¶
Calculate the dihedral angle value.
- Returns:
Dihedral angle in radians.
-
inline double calculate_z() const¶
Calculate the z-score for the current dihedral angle.
The z-score accounts for the periodicity of the torsion restraint.
- Returns:
Z-score of the observed dihedral relative to the restraint.
-
inline double calculate() const¶
-
Topo() = default¶
-
enum class HydrogenChange¶
-
namespace gemmi
Functions
-
void place_hydrogens_on_all_atoms(Topo &topo)¶
Place hydrogen atoms using ideal bond lengths and angles from monomer library.
- Parameters:
topo – The topology containing atoms and bond restraints.
-
inline void adjust_hydrogen_distances(Topo &topo, Restraints::DistanceOf of, double default_scale = 1.)¶
Scale hydrogen-atom bond distances to ideal target values.
- Parameters:
topo – The topology containing atoms and bond restraints.
of – Which ideal distance to use: electron cloud or nuclear.
default_scale – Fallback scale factor when computed scale is invalid (NaN or infinite).
-
void place_hydrogens_on_all_atoms(Topo &topo)¶
-
namespace gemmi
-
struct LinkHunt¶
- #include <gemmi/linkhunt.hpp>
Searches for inter-residue chemical links using monomer library bond definitions.
Public Functions
-
inline void index_chem_links(const MonLib &monlib, bool use_alias = true)¶
Index all links from monlib into the links multimap for fast lookup.
- Parameters:
monlib – The monomer library to index.
use_alias – Whether to expand atom name aliases when indexing.
-
inline std::vector<Match> find_possible_links(Structure &st, double bond_margin, double radius_margin, ContactSearch::Ignore ignore)¶
Find all candidate inter-residue links within the structure using neighbor search.
- Parameters:
st – The structure to search for possible links.
bond_margin – Fraction of ideal bond length used as distance cutoff for dictionary links.
radius_margin – Fraction of sum of covalent radii for non-dictionary links.
ignore – Which contacts to skip.
- Returns:
Vector of Match results describing candidate links.
Public Members
-
double global_max_dist = 2.34¶
Maximum bond distance across all indexed links; updated by index_chem_links().
-
struct Match¶
- #include <gemmi/linkhunt.hpp>
Result of a link search; describes a candidate inter-residue link.
Public Members
-
int score = -1000¶
Best link score.
-
bool same_image¶
True if atoms are in the same crystal image.
-
double bond_length = 0¶
Bond distance in Angstroms.
-
Connection *conn = nullptr¶
Pointer to existing Connection in Structure if present, else nullptr.
-
int score = -1000¶
-
inline void index_chem_links(const MonLib &monlib, bool use_alias = true)¶
-
struct LinkHunt¶
-
namespace gemmi
Functions
-
inline void add_chemcomp_to_block(const ChemComp &cc, cif::Block &block, const std::vector<std::string> &acedrg_types = {}, bool no_angles = false)¶
Write ChemComp restraint data into a CIF block as chem_comp* categories.
- Parameters:
cc – The chemical component to serialise.
block – The CIF block to write into; rows are appended.
acedrg_types – Optional per-atom ACEDRG type strings; if empty, stored types in cc.atoms are used.
no_angles – If true, skip writing the _chem_comp_angle table.
-
inline void add_chemcomp_to_block(const ChemComp &cc, cif::Block &block, const std::vector<std::string> &acedrg_types = {}, bool no_angles = false)¶
Warning
doxygenfile: Cannot find file “mmcif_impl.hpp
Calculations and Analysis¶
Geometric calculations, sequence alignment, structure superposition, neighbour search, contact detection, biological assembly, atom selection, structure modification, polymer heuristics, and secondary structure assignment.
-
namespace gemmi
Functions
-
template<class T>
bool has_hydrogen(const T &obj)¶ Check if an object or any of its descendants contains hydrogen atoms.
- Template Parameters:
T – Type of object (Model, Chain, Residue, Atom, etc.)
- Parameters:
obj – Object to check
- Returns:
True if hydrogen is present, false otherwise
-
template<class T>
size_t count_atom_sites(const T &obj, const Selection *sel = nullptr)¶ Count atom sites in an object, optionally filtered by Selection.
- Template Parameters:
T – Type of object (Model, Chain, Residue, Atom, etc.)
- Parameters:
obj – Object to count atoms in
sel – Optional Selection filter; nullptr means all atoms
- Returns:
Number of matching atom sites
-
template<class T>
double count_occupancies(const T &obj, const Selection *sel = nullptr)¶ Sum occupancies in an object, optionally filtered by Selection.
- Template Parameters:
T – Type of object (Model, Chain, Residue, Atom, etc.)
- Parameters:
obj – Object to sum occupancies in
sel – Optional Selection filter; nullptr means all atoms
- Returns:
Sum of occupancies for matching atoms
-
template<class T>
double calculate_mass(const T &obj)¶ Calculate total mass in atomic mass units for an object.
- Template Parameters:
T – Type of object (Model, Chain, Residue, Atom, etc.)
- Parameters:
obj – Object to calculate mass for
- Returns:
Total mass in atomic mass units (accounting for occupancy)
-
template<class T>
CenterOfMass calculate_center_of_mass(const T &obj)¶ Calculate the center of mass (mass-weighted centroid).
- Template Parameters:
T – Type of object (Model, Chain, Residue, Atom, etc.)
- Parameters:
obj – Object to calculate center of mass for
- Returns:
CenterOfMass with weighted_sum and total mass
-
template<>
inline CenterOfMass calculate_center_of_mass(const Atom &atom)¶
-
template<class T>
std::pair<float, float> calculate_b_iso_range(const T &obj)¶ Calculate min and max isotropic B-factors in an object.
- Template Parameters:
T – Type of object (Model, Chain, Residue, Atom, etc.)
- Parameters:
obj – Object to scan
- Returns:
Pair of (min_B, max_B)
-
inline std::pair<double, double> calculate_b_aniso_range(const Model &model)¶
Calculate min and max B-factors from anisotropic B-tensors. Uses min/max eigenvalues of anisotropic B-tensor, or B_iso if B-factor is isotropic.
-
template<class T>
void expand_box(const T &obj, Box<Position> &box)¶ Expand an axis-aligned bounding box to include all atoms in obj.
- Template Parameters:
T – Type supporting children() iteration (Model, Chain, Residue, or Atom).
- Parameters:
obj – Object whose atom positions are added to the box.
box – Bounding box to expand in-place.
-
inline Box<Position> calculate_box(const Structure &st, double margin = 0.)¶
Calculate axis-aligned bounding box in Cartesian space.
Note
NCS is not taken into account here (cf. NeighborSearch::set_bounding_cell())
- Parameters:
st – Structure to scan
margin – Optional margin to add around the box
- Returns:
Axis-aligned bounding box
-
inline Box<Fractional> calculate_fractional_box(const Structure &st, double margin = 0.)¶
Calculate bounding box in fractional coordinates.
- Parameters:
st – Structure to scan (must have a unit cell)
margin – Optional margin in Cartesian space (converted to fractional)
- Throws:
Fails – with message if Structure has no unit cell
- Returns:
Bounding box in fractional coordinates
-
inline double calculate_b_est(const Atom &atom)¶
Calculate B_equiv from anisotropic B-tensor (or B_iso if isotropic).
- References
Merritt, E.A. (2011). Some B_eq are more equivalent than others. Acta Cryst. A67, 512–516. https://doi.org/10.1107/S0108767311034350
- Parameters:
atom – Atom with (possibly anisotropic) B-factor
- Returns:
B_equiv = sqrt((sum_eigenvalues) / (sum_inverse_eigenvalues)) * u_to_b()
-
inline double calculate_angle(const Position &p0, const Position &p1, const Position &p2)¶
Calculate angle at p1 between vectors p1→p0 and p1→p2.
- Parameters:
p0 – First position
p1 – Central position (vertex of the angle)
p2 – Third position
- Returns:
Angle in radians
-
inline double calculate_dihedral(const Position &p0, const Position &p1, const Position &p2, const Position &p3)¶
Calculate dihedral angle defined by four positions.
Note
See discussion at https://stackoverflow.com/questions/20305272/
- Parameters:
p0 – First position
p1 – Second position (on the bond axis)
p2 – Third position (on the bond axis)
p3 – Fourth position
- Returns:
Dihedral angle in radians, in the range [-π, π]
-
inline double calculate_dihedral_from_atoms(const Atom *a, const Atom *b, const Atom *c, const Atom *d)¶
Calculate dihedral angle from four Atom pointers.
- Parameters:
a – First atom pointer
b – Second atom pointer (on the bond axis)
c – Third atom pointer (on the bond axis)
d – Fourth atom pointer
- Returns:
Dihedral angle in radians (same range as atan2: [-π, π]), or NaN if any pointer is null
-
inline double calculate_omega(const Residue &res, const Residue &next)¶
Calculate peptide bond ω dihedral angle. ω is defined by atoms: Cα(i) - C(i) - N(i+1) - Cα(i+1)
- Parameters:
res – Current residue
next – Next residue
- Returns:
Omega angle in radians, or NaN if atoms are missing
-
inline bool is_peptide_bond_cis(const Atom *ca1, const Atom *c, const Atom *n, const Atom *ca2, double tolerance_deg)¶
Check if a peptide bond is in cis configuration.
- Parameters:
ca1 – Cα atom of the current residue
c – C atom of the current residue
n – N atom of the next residue
ca2 – Cα atom of the next residue
tolerance_deg – Tolerance in degrees (absolute |ω| < tolerance indicates cis)
- Returns:
True if |ω| < tolerance_deg, false otherwise
-
inline double calculate_chiral_volume(const Position &actr, const Position &a1, const Position &a2, const Position &a3)¶
Calculate chiral volume (scalar triple product).
- Parameters:
actr – Central atom position (center of chirality)
a1 – First substituent position
a2 – Second substituent position
a3 – Third substituent position
- Returns:
Scalar triple product: (a1-actr) · ((a2-actr) × (a3-actr))
-
inline std::array<double, 2> calculate_phi_psi(const Residue *prev, const Residue &res, const Residue *next)¶
Calculate Ramachandran dihedral angles φ (phi) and ψ (psi). φ is defined by: C(i-1) - N(i) - Cα(i) - C(i) ψ is defined by: N(i) - Cα(i) - C(i) - N(i+1)
- Parameters:
prev – Previous residue (nullptr if not available)
res – Current residue
next – Next residue (nullptr if not available)
- Returns:
Array [phi, psi] in radians; NaN values if flanking residues are missing or atoms not found
-
std::array<double, 4> find_best_plane(const std::vector<Atom*> &atoms)¶
Find the least-squares plane through a set of atoms.
Note
All atoms must have non-zero occupancy to be included
- Parameters:
atoms – Vector of atom pointers
- Returns:
Array [a, b, c, d] representing plane equation ax + by + cz = d
-
inline double get_distance_from_plane(const Position &pos, const std::array<double, 4> &coeff)¶
Calculate signed distance from a point to a plane.
- Parameters:
pos – Position of the point
coeff – Plane coefficients [a, b, c, d] from ax + by + cz = d
- Returns:
Signed distance from pos to plane
-
FTransform parse_triplet_as_ftransform(const std::string &s)¶
Parse a crystallographic triplet string into an FTransform.
- Parameters:
s – CIF triplet string (e.g., “x,y,z” or “-x+1/2,-y,z”)
- Returns:
FTransform representing the fractional transformation
-
SMat33<double> calculate_u_from_tls(const TlsGroup &tls, const Position &pos)¶
Calculate the anisotropic U tensor at a position from TLS group parameters.
- Parameters:
tls – TLS group parameters (T, L, S matrices)
pos – Position where U is evaluated
- Returns:
3×3 symmetric matrix U at the given position
-
template<class T>
-
namespace gemmi
Structure Superposition
-
enum class SupSelect¶
Atom selection mode for superposition calculations.
Values:
-
enumerator CaP¶
Use only Cα atoms (for peptides) or P atoms (for nucleic acids)
-
enumerator MainChain¶
Use backbone atoms (N, CA, C, O for peptides; P, O5’, C5’, C4’, C3’, O3’ for nucleic acids)
-
enumerator All¶
Use all atoms.
-
enumerator CaP¶
-
inline void prepare_positions_for_superposition(std::vector<Position> &pos1, std::vector<Position> &pos2, ConstResidueSpan fixed, ConstResidueSpan movable, PolymerType ptype, SupSelect sel, char altloc = '\0', std::vector<int> *ca_offsets = nullptr)¶
Extract matching atom positions from two polymer spans for superposition.
- Parameters:
pos1 – Output vector of positions from fixed chain
pos2 – Output vector of positions from movable chain
fixed – Fixed polymer chain (reference structure)
movable – Movable polymer chain (structure to be superposed)
ptype – Polymer type (peptide or nucleic acid)
sel – Atom selection mode (CaP, MainChain, or All)
altloc – Alternate location code to select; ‘\0’ means all conformers
ca_offsets – Optional output vector storing indices of Cα/P atoms in pos1/pos2
-
inline SupResult calculate_current_rmsd(ConstResidueSpan fixed, ConstResidueSpan movable, PolymerType ptype, SupSelect sel, char altloc = '\0')¶
Calculate RMSD between two polymer spans without transformation.
- Parameters:
fixed – Fixed polymer chain (reference structure)
movable – Movable polymer chain (structure to compare)
ptype – Polymer type (peptide or nucleic acid)
sel – Atom selection mode (CaP, MainChain, or All)
altloc – Alternate location code to select; ‘\0’ means all conformers
- Returns:
SupResult with RMSD and atom count (rotation/translation matrices are empty)
-
inline SupResult calculate_superposition(ConstResidueSpan fixed, ConstResidueSpan movable, PolymerType ptype, SupSelect sel, int trim_cycles = 0, double trim_cutoff = 2.0, char altloc = '\0')¶
Calculate optimal superposition using QCP (quaternion characteristic polynomial).
- Parameters:
fixed – Fixed polymer chain (reference structure)
movable – Movable polymer chain (structure to be superposed)
ptype – Polymer type (peptide or nucleic acid)
sel – Atom selection mode (CaP, MainChain, or All)
trim_cycles – Number of iterative trimming cycles (0 = no trimming)
trim_cutoff – Outlier distance threshold in Å for trimming (default 2.0)
altloc – Alternate location code to select; ‘\0’ means all conformers
- Returns:
SupResult with rotation matrix, translation vector, and RMSD
-
inline std::vector<SupResult> calculate_superpositions_in_moving_window(ConstResidueSpan fixed, ConstResidueSpan movable, PolymerType ptype, double radius = 10.0)¶
Compute local superpositions using a sliding window around each Cα/P. Calculates superpositions by sliding a sphere of given radius around each Cα/P position.
- Parameters:
fixed – Fixed polymer chain (reference structure)
movable – Movable polymer chain (structure to be superposed)
ptype – Polymer type (peptide or nucleic acid)
radius – Window radius in Ångströms around each Cα/P (default 10.0)
- Returns:
Vector of SupResult, one per residue in fixed.first_conformer()
Sequence Alignment and label_seq_id Assignment
-
inline std::vector<int> prepare_target_gapo(const ConstResidueSpan &polymer, PolymerType polymer_type, const AlignmentScoring *scoring = nullptr)¶
Compute per-position gap-open penalties for sequence alignment. Accounts for gaps and discontinuities in the observed polymer sequence.
- Parameters:
polymer – Polymer span to analyze
polymer_type – Type of polymer (peptide or nucleic acid)
scoring – Optional AlignmentScoring parameters; uses default partial_model() if nullptr
- Returns:
Vector of gap-opening penalties for each position
-
inline AlignmentResult align_sequence_to_polymer(const std::vector<std::string> &full_seq, const ConstResidueSpan &polymer, PolymerType polymer_type, const AlignmentScoring *scoring = nullptr)¶
Align a full sequence (SEQRES/Entity) to observed residues in a polymer.
- Parameters:
full_seq – Full sequence from SEQRES or Entity
polymer – Polymer chain span (observed residues)
polymer_type – Type of polymer (peptide or nucleic acid)
scoring – Optional AlignmentScoring parameters; uses default partial_model() if nullptr
- Returns:
AlignmentResult with CIGAR string describing the alignment
-
inline bool seqid_matches_seqres(const ConstResidueSpan &polymer, const Entity &ent)¶
Check if model sequence exactly matches SEQRES numbering (fast path).
- Parameters:
polymer – Polymer chain span
ent – Entity with full_sequence from SEQRES
- Returns:
True if label_seq values already match Entity::full_sequence exactly
-
inline void clear_sequences(Structure &st)¶
Clear full_sequence and database references from all entities.
- Parameters:
st – Structure to clear
-
void assign_best_sequences(Structure &st, const std::vector<std::string> &fasta_sequences)¶
Match FASTA sequences to entities and set Entity::full_sequence in-place.
- Parameters:
st – Structure whose entities are updated with matched sequences.
fasta_sequences – Vector of FASTA-format sequence strings to match against entities.
-
inline void assign_label_seq_to_polymer(ResidueSpan &polymer, const Entity *ent, bool force)¶
Assign label_seq_id to residues using alignment to Entity full_sequence.
-
enum class SupSelect¶
-
namespace gemmi
-
struct NeighborSearch¶
- #include <gemmi/neighbor.hpp>
Cell-linked-list spatial index for fast atom neighbor searching. Supports both macromolecular structures (Model) and small-molecule structures (SmallStructure), with periodic boundary conditions and crystallographic symmetry.
Public Functions
-
NeighborSearch() = default¶
Default constructor creating an empty NeighborSearch.
-
inline NeighborSearch(Model &model_, const UnitCell &cell, double radius)¶
Initialize grid for a macromolecular model.
- Parameters:
model_ – Reference to the Model to index (non-const, can be modified in for_each_contact()).
cell – Unit cell defining the crystallographic symmetry and periodicity.
radius – Search radius used to dimension the grid.
-
inline NeighborSearch(SmallStructure &small_st, double radius)¶
Initialize for a small-molecule structure.
- Parameters:
small_st – Reference to the SmallStructure to index.
radius – Search radius used to dimension the grid.
-
inline NeighborSearch &populate(bool include_h_ = true)¶
Fill the grid with all atoms in the model or small structure.
- Parameters:
include_h_ – If true, include hydrogen atoms (default: true).
- Returns:
Reference to *this for method chaining.
-
inline void add_chain(const Chain &chain, bool include_h_ = true)¶
Add all atoms from one chain to the grid.
- Parameters:
chain – The chain to add.
include_h_ – If true, include hydrogen atoms (default: true).
-
inline void add_chain_n(const Chain &chain, int n_ch)¶
Add atoms from a chain with explicit chain index. Used when chain_idx matters; internally called by populate().
- Parameters:
chain – The chain to add.
n_ch – Index of the chain in the model’s chain vector.
-
inline void add_atom(const Atom &atom, int n_ch, int n_res, int n_atom)¶
Add a single atom to the grid.
- Parameters:
atom – The atom to add.
n_ch – Index of the chain.
n_res – Index of the residue within the chain.
n_atom – Index of the atom within the residue.
-
inline void add_site(const SmallStructure::Site &site, int n)¶
Add a SmallStructure site to the grid.
- Parameters:
site – The site to add.
n – Index of the site in the sites vector.
-
inline std::vector<Mark> &get_subcell(const Fractional &fr)¶
Return the reference to the grid cell containing a fractional coordinate. Assumes data in [0, 1) but uses index_n to account for numerical errors.
- Parameters:
fr – Fractional coordinate in the unit cell.
- Returns:
Reference to the vector of Marks in the grid cell.
-
template<typename Func>
void for_each_cell(const Position &pos, const Func &func, int k = 1)¶ Iterate over all grid cells within k cells of a position.
- Template Parameters:
Func – Callable type with signature void(std::vector<Mark>&, const Fractional&).
- Parameters:
pos – Cartesian position.
func – Function to call for each cell, receiving the Marks and fractional coordinates.
k – Grid multiplier (default: 1); larger k searches more cells.
-
template<typename Func>
inline void for_each(const Position &pos, char alt, double radius, const Func &func, int k = 1)¶ Iterate over all Marks within radius of a position, respecting alternate conformers.
- Template Parameters:
Func – Callable type with signature void(Mark&, double) for (mark, dist_sq).
- Parameters:
pos – Cartesian position.
alt – Alternate conformer identifier to match (‘\0’ matches all).
radius – Search radius in Angstroms.
func – Function to call for each nearby mark.
k – Grid multiplier (default: 1); larger k searches more cells.
-
inline int sufficient_k(double r) const¶
Return the minimum grid multiplier k covering the given radius.
- Parameters:
r – Search radius in Angstroms.
- Returns:
Minimum k value such that k*radius_specified >= r.
-
inline std::vector<Mark*> find_atoms(const Position &pos, char alt, double min_dist, double radius)¶
Find all Marks within a distance range of a position. If radius==0, uses radius_specified.
- Parameters:
pos – Cartesian position.
alt – Alternate conformer identifier.
min_dist – Minimum distance in Angstroms.
radius – Maximum distance in Angstroms (0 = use radius_specified).
- Returns:
Vector of pointers to Marks in the distance range [min_dist, radius].
-
inline std::vector<Mark*> find_neighbors(const Atom &atom, double min_dist, double max_dist)¶
Find neighbor Marks of a Model atom.
- Parameters:
atom – The atom to find neighbors for.
min_dist – Minimum distance in Angstroms.
max_dist – Maximum distance in Angstroms.
- Returns:
Vector of pointers to nearby Marks.
-
inline std::vector<Mark*> find_site_neighbors(const SmallStructure::Site &site, double min_dist, double max_dist)¶
Find neighbor Marks of a SmallStructure site.
- Parameters:
site – The site to find neighbors for.
min_dist – Minimum distance in Angstroms.
max_dist – Maximum distance in Angstroms.
- Returns:
Vector of pointers to nearby Marks.
-
inline std::pair<Mark*, double> find_nearest_atom_within_k(const Position &pos, int k, double radius)¶
Find the nearest atom within k grid layers and a radius limit.
- Parameters:
pos – Cartesian position.
k – Grid multiplier (number of layers to search).
radius – Maximum search radius in Angstroms.
- Returns:
Pair of (nearest Mark pointer, distance squared). Pointer is nullptr if no atom found.
-
inline Mark *find_nearest_atom(const Position &pos, double radius = INFINITY)¶
Find the single nearest atom within an optional radius limit. Automatically adapts the grid search multiplier k to find the nearest atom.
- Parameters:
pos – Cartesian position.
radius – Maximum search radius in Angstroms (default: INFINITY).
- Returns:
Pointer to the nearest Mark, or nullptr if no atom found.
-
inline double dist_sq(const Position &pos1, const Position &pos2) const¶
Distance squared between two positions, accounting for unit cell periodicity.
- Parameters:
pos1 – First Cartesian position.
pos2 – Second Cartesian position.
- Returns:
Squared distance, accounting for periodic boundary conditions.
-
inline double dist(const Position &pos1, const Position &pos2) const¶
Euclidean distance between two positions with periodic boundary conditions.
- Parameters:
pos1 – First Cartesian position.
pos2 – Second Cartesian position.
- Returns:
Euclidean distance in Angstroms.
-
inline FTransform get_image_transformation(int image_idx) const¶
Retrieve the crystallographic image transformation for the given image index.
- Parameters:
image_idx – Crystallographic image index (0 = identity, 1+ = symmetry images).
- Returns:
The fractional transform for the image.
Public Members
-
double radius_specified = 0.¶
The search radius passed to the constructor.
-
Model *model = nullptr¶
Pointer to the indexed macromolecular model (nullptr if SmallStructure).
-
SmallStructure *small_structure = nullptr¶
Pointer to the indexed small-molecule structure (nullptr if Model).
-
bool use_pbc = true¶
If true, apply periodic boundary conditions when searching.
-
bool include_h = true¶
If true, include hydrogen atoms in the index.
-
struct Mark¶
- #include <gemmi/neighbor.hpp>
Atom reference stored in a grid cell. Encodes the position and indices needed to resolve back to the original atom or site.
Public Functions
-
inline CRA to_cra(Model &mdl) const¶
Resolve the indices into a CRA (chain/residue/atom) triple.
- Parameters:
mdl – Model to resolve indices into (non-const version).
- Returns:
CRA triple pointing to the resolved atom.
-
inline const_CRA to_cra(const Model &mdl) const¶
Resolve the indices into a const CRA triple.
- Parameters:
mdl – Model to resolve indices into (const version).
- Returns:
const CRA triple pointing to the resolved atom.
-
inline SmallStructure::Site &to_site(SmallStructure &small_st) const¶
Resolve the atom_idx to a SmallStructure::Site.
- Parameters:
small_st – SmallStructure to resolve into (non-const version).
- Returns:
Reference to the resolved site.
-
inline const SmallStructure::Site &to_site(const SmallStructure &small_st) const¶
Resolve the atom_idx to a const SmallStructure::Site.
- Parameters:
small_st – SmallStructure to resolve into (const version).
- Returns:
Const reference to the resolved site.
Public Members
-
char altloc¶
Alternate conformer identifier (‘\0’ = no alternate).
-
short image_idx¶
Index into the list of crystallographic images (0 = identity).
-
int chain_idx¶
Index of the chain in the model’s chain vector.
-
int residue_idx¶
Index of the residue within the chain.
-
int atom_idx¶
Index of the atom within the residue.
-
inline CRA to_cra(Model &mdl) const¶
-
NeighborSearch() = default¶
-
struct NeighborSearch¶
-
namespace gemmi
-
struct ContactSearch¶
- #include <gemmi/contact.hpp>
Configures and performs distance-based contact search between atoms. Built on top of NeighborSearch with support for configurable filtering, per-element radii, and flexible results collection.
Public Types
-
enum class Ignore¶
Filter options for atom pair inclusion in contact search results.
Values:
-
enumerator Nothing¶
Report all contacts.
-
enumerator SameResidue¶
Skip contacts between atoms in the same residue.
-
enumerator AdjacentResidues¶
Skip contacts between atoms in adjacent residues (i±1).
-
enumerator SameChain¶
Skip contacts between atoms in the same chain.
-
enumerator SameAsu¶
Skip contacts between atoms in the same asymmetric unit (report only symmetry-related contacts).
-
enumerator Nothing¶
Public Functions
-
inline ContactSearch(double radius) noexcept¶
Create a contact search with the given search radius.
- Parameters:
radius – Maximum contact distance in Angstroms.
-
inline void setup_atomic_radii(double multiplier, double tolerance)¶
Populate per-element radii based on covalent radii with scaling.
- Parameters:
multiplier – Scaling factor applied to covalent radius.
tolerance – Constant tolerance added to the scaled radius.
-
inline float get_radius(El el) const¶
Get the contact radius for a given element.
- Parameters:
el – Chemical element.
- Returns:
Contact radius for the element (0.f if radii not set up).
-
inline void set_radius(El el, float r)¶
Override the contact radius for a specific element.
- Parameters:
el – Chemical element.
r – New contact radius in Angstroms.
-
template<typename Func>
void for_each_contact(NeighborSearch &ns, const Func &func)¶ Iterate over all contacts, applying ignore logic and calling a function for each.
- Template Parameters:
Func – Callable type with signature void(const CRA&, const CRA&, int, double) for (partner1, partner2, image_idx, dist_sq).
- Parameters:
ns – NeighborSearch object containing the indexed atoms.
func – Function to call for each contact found.
-
inline std::vector<Result> find_contacts(NeighborSearch &ns)¶
Collect and return all contacts as a vector of Result.
- Parameters:
ns – NeighborSearch object containing the indexed atoms.
- Returns:
Vector of Result structs representing all found contacts.
Public Members
-
double search_radius¶
Maximum contact distance in Angstroms.
-
Ignore ignore = Ignore::SameResidue¶
Which atom pairs to skip (default: SameResidue).
-
bool twice = false¶
If true, report each contact pair twice (A→B and B→A); default false.
-
float min_occupancy = 0.f¶
Skip atoms with occupancy below this threshold (0 = no filtering).
-
double special_pos_cutoff_sq = 0.8 * 0.8¶
Squared distance threshold for identifying atoms on special positions.
-
enum class Ignore¶
-
struct ContactSearch¶
-
namespace gemmi
Enums
-
enum class HowToNameCopiedChain¶
Specifies how to name copied chains to ensure uniqueness.
Naming strategy for chains copied during assembly or NCS expansion.
Values:
-
enumerator Short¶
Use 1–2 character chain names cycling through A–Z, a–z, 0–9.
-
enumerator AddNumber¶
Append a numeric suffix to the original chain name.
-
enumerator Dup¶
Keep the original chain name (may result in duplicates)
-
enumerator Short¶
Functions
-
inline void ensure_unique_chain_name(const Model &model, Chain &chain)¶
Rename a chain to ensure its name is unique within the model.
Uses the Short naming strategy to generate a 1–2 character name that does not conflict with other chains in the model.
- Parameters:
model – The model containing the chain
chain – The chain to rename
-
Model make_assembly(const Assembly &assembly, const Model &model, HowToNameCopiedChain how, const Logger &logging)¶
Apply all generators in an assembly to a model to generate a biological unit.
Creates a new Model containing copies of the input model transformed according to each generator in the assembly. Chain names are made unique according to the specified strategy.
- Parameters:
assembly – The assembly record containing transformation operators
model – The input model to transform
how – The strategy for naming copied chains
logging – Logger for warning messages
- Returns:
A new Model containing the assembled biological unit
-
inline Assembly pseudo_assembly_for_unit_cell(const UnitCell &cell)¶
Create a pseudo-assembly representing all unit-cell images.
Generates an Assembly whose operators produce all crystallographic images of the structure within the unit cell. Useful for packing displays and structure visualization.
- Parameters:
cell – The unit cell with precomputed image transformations
- Returns:
An Assembly object whose generators apply all unit-cell symmetry
-
void transform_to_assembly(Structure &st, const std::string &assembly_name, HowToNameCopiedChain how, const Logger &logging, bool keep_spacegroup = false, double merge_dist = 0.2)¶
Modify a Structure in-place to contain only a named assembly.
Replaces all models in the structure with the expanded assembly, optionally preserving the space group. If assembly_name=”unit_cell”, converts the structure to the unit cell (P1).
- Parameters:
st – The structure to modify in-place
assembly_name – The name of the assembly to apply
how – The strategy for naming copied chains
logging – Logger for warning messages
keep_spacegroup – If true, preserve the original space group and unit cell
merge_dist – Distance threshold for merging nearby atoms (default 0.2 Å)
-
Model expand_ncs_model(const Model &model, const std::vector<NcsOp> &ncs, HowToNameCopiedChain how)¶
Expand a model by applying NCS operations.
Generates copies of the input model by applying each NCS (non-crystallographic symmetry) operation, returning a new Model with all copies combined.
- Parameters:
model – The input model to expand
ncs – Vector of NCS operations to apply
how – The strategy for naming copied chains
- Returns:
A new Model containing the original and all NCS-transformed copies
-
void merge_atoms_in_expanded_model(Model &model, const UnitCell &cell, double max_dist = 0.2, bool compare_serial = true)¶
Merge atoms within a distance threshold after NCS or assembly expansion.
Searches for overlapping atoms from different chains that are equivalent under the unit cell symmetry and merges them. Typically used after expand_ncs() and make_assembly() to eliminate duplicate atoms.
- Parameters:
model – The model to modify in-place
cell – The unit cell (used for distance calculations)
max_dist – Maximum distance for merging atoms (default 0.2 Å)
compare_serial – If true, only merge atoms with matching serial numbers (default true)
-
void shorten_chain_names(Structure &st)¶
Rename all chains to use the shortest possible unique names.
Replaces chain names with 1–2 character names (A–Z, a–z, 0–9) while maintaining uniqueness within the structure.
- Parameters:
st – The structure to modify in-place
-
void expand_ncs(Structure &st, HowToNameCopiedChain how, double merge_dist = 0.2)¶
Expand NCS operations in all models of a structure in-place.
Applies all NCS (non-crystallographic symmetry) operations to every model in the structure, generating copies and optionally merging nearby atoms.
- Parameters:
st – The structure to expand in-place
how – The strategy for naming copied chains
merge_dist – Distance threshold for merging atoms (default 0.2 Å)
-
void split_chains_by_segments(Model &model, HowToNameCopiedChain how)¶
Split chains at residue segment boundaries into separate chains.
Divides each chain into multiple chains at segment breaks, with new chain names generated according to the strategy. If how=HowToNameCopiedChain::Dup, the segment name is appended to the chain name.
- Parameters:
model – The model to modify in-place
how – The strategy for naming split chains
-
std::vector<NearestImage> get_nearby_sym_ops(const Structure &st, const Position &pos, double radius)¶
Find all crystallographic symmetry images within a distance radius.
Searches for non-identity symmetry images of the structure around a given position. Uses only the first model and is intended for viewer applications.
- Parameters:
st – The structure to query
pos – The center position for the search
radius – The search radius in Ångströms
- Returns:
Vector of NearestImage objects describing the nearby symmetry images
-
Structure get_sym_image(const Structure &st, const NearestImage &image)¶
Extract a symmetry image of the structure as a new Structure object.
Creates and returns a copy of the input structure transformed to the coordinates of the specified symmetry image.
- Parameters:
st – The input structure
image – The symmetry image specification
- Returns:
A new Structure object containing the transformed copy
-
struct ChainNameGenerator¶
- #include <gemmi/assembly.hpp>
Utility to generate unique chain names for assembly and NCS expansion.
Manages a set of used chain names and provides methods to generate new, unique names according to the specified naming strategy.
Public Functions
-
inline ChainNameGenerator(HowToNameCopiedChain how_)¶
Initialize with a naming strategy.
- Parameters:
how_ – The chain naming strategy to use
-
inline ChainNameGenerator(const Model &model, HowToNameCopiedChain how_)¶
Initialize with chain names pre-populated from a Model.
- Parameters:
model – The model to extract existing chain names from
how_ – The chain naming strategy to use
-
inline bool try_add(const std::string &name)¶
Register a chain name if not already used.
- Parameters:
name – The name to register
- Returns:
true if the name was successfully added, false if already in used_names
-
inline std::string make_short_name(const std::string &preferred)¶
Generate a unique 1–2 character name starting from preferred.
Cycles through A–Z, a–z, 0–9 to find an available name.
- Parameters:
preferred – The preferred 1-character name to try first
- Returns:
A unique short name
-
inline std::string make_name_with_numeric_postfix(const std::string &base, int n)¶
Generate a name by appending a numeric postfix to a base name.
Increments the numeric suffix until a unique name is found.
- Parameters:
base – The base chain name
n – The starting number to append
- Returns:
A unique name of the form “base” + number
-
inline std::string make_new_name(const std::string &old, int n)¶
Generate a new name according to the configured naming strategy.
Dispatches to make_short_name(), make_name_with_numeric_postfix(), or returns the original name based on the how field.
- Parameters:
old – The original chain name
n – The numeric suffix (used only for AddNumber strategy)
- Returns:
A new unique chain name
Public Members
-
HowToNameCopiedChain how¶
The naming strategy to apply.
-
inline ChainNameGenerator(HowToNameCopiedChain how_)¶
-
enum class HowToNameCopiedChain¶
-
namespace gemmi
-
struct Selection¶
- #include <gemmi/select.hpp>
Parsed CCP4-style atom/residue/chain selection expression.
Represents a selection filter such as “//A/10-20/CA[C].B” for filtering atoms, residues, chains, and models from a structure. Provides both individual match predicates and FilterProxy views for convenient iteration over matching elements.
Public Functions
-
Selection() = default¶
Default constructor.
-
Selection(const std::string &cid)¶
Parse a CCP4 selection string.
Parses a selection string like “//A/10-20/CA[C].B” into the selection criteria.
- Parameters:
cid – The CCP4-style selection string
-
std::string str() const¶
Get the canonical string representation of this selection.
- Returns:
String representation of the parsed selection
-
inline bool matches(const Structure&) const¶
Check if a structure matches this selection.
Structures always match (they are never filtered).
- Parameters:
s – The structure to check
- Returns:
Always true
-
inline bool matches(const Model &model) const¶
Check if a model matches this selection.
Matches if the model number is 0 (select all) or matches mdl.
- Parameters:
model – The model to check
- Returns:
true if the model is included in this selection
-
inline bool matches(const Chain &chain) const¶
Check if a chain matches this selection.
Matches if the chain ID is in the allowed list.
- Parameters:
chain – The chain to check
- Returns:
true if the chain is included in this selection
-
inline bool matches(const Residue &res) const¶
Check if a residue matches this selection.
Matches residue name, sequence ID range, entity type, and flags.
- Parameters:
res – The residue to check
- Returns:
true if the residue is included in this selection
-
inline bool matches(const Atom &a) const¶
Check if an atom matches this selection.
Matches atom name, element, altloc, flags, and numeric inequalities.
- Parameters:
a – The atom to check
- Returns:
true if the atom is included in this selection
-
inline bool matches(const CRA &cra) const¶
Check if a chain-residue-atom triplet matches this selection.
Matches if all non-null components pass their respective match tests.
- Parameters:
cra – The CRA structure to check
- Returns:
true if the CRA is included in this selection
-
inline FilterProxy<Selection, Model> models(Structure &st) const¶
Get a filtered view over models in a structure.
- Parameters:
st – The structure to filter
- Returns:
A FilterProxy that iterates over matching models
-
inline FilterProxy<Selection, Chain> chains(Model &model) const¶
Get a filtered view over chains in a model.
- Parameters:
model – The model to filter
- Returns:
A FilterProxy that iterates over matching chains
-
inline FilterProxy<Selection, Residue> residues(Chain &chain) const¶
Get a filtered view over residues in a chain.
- Parameters:
chain – The chain to filter
- Returns:
A FilterProxy that iterates over matching residues
-
inline FilterProxy<Selection, Atom> atoms(Residue &residue) const¶
Get a filtered view over atoms in a residue.
- Parameters:
residue – The residue to filter
- Returns:
A FilterProxy that iterates over matching atoms
-
inline CRA first_in_model(Model &model) const¶
Find the first matching atom in a model.
Searches through the model’s chains and residues to find the first atom that matches this selection.
- Parameters:
model – The model to search
- Returns:
A CRA with the first match, or {nullptr, nullptr, nullptr} if not found
-
inline std::pair<Model*, CRA> first(Structure &st) const¶
Find the first matching atom in a structure.
Searches through all models to find the first matching atom.
- Parameters:
st – The structure to search
- Returns:
A pair of {Model*, CRA} with the first match, or {nullptr, empty_CRA} if not found
-
template<typename T>
inline void add_matching_children(const T &orig, T &target) const¶ Recursively copy matching children from orig into target.
Used internally by copy_selection() to recursively populate a target structure with only the matching elements.
- Template Parameters:
T – The type of element (Model, Chain, Residue, or Atom)
- Parameters:
orig – The original element to copy from
target – The target element to copy into
-
inline Selection &set_residue_flags(const std::string &pattern)¶
Set the residue flag filter pattern.
- Parameters:
pattern – Flag pattern string (may be prefixed with ‘!’ to invert)
- Returns:
*this for method chaining
-
inline Selection &set_atom_flags(const std::string &pattern)¶
Set the atom flag filter pattern.
- Parameters:
pattern – Flag pattern string (may be prefixed with ‘!’ to invert)
- Returns:
*this for method chaining
-
template<typename T>
inline T copy_selection(const T &orig) const¶ Create a copy of an element containing only matching children.
Returns a copy of orig with all non-matching children filtered out. Recursively applies the filter to nested children.
- Template Parameters:
T – The type of element (Structure, Model, Chain, or Residue)
- Parameters:
orig – The original element to copy
- Returns:
A new element containing only matching children
-
template<typename T>
inline void remove_selected(T &t) const¶ Remove all matching atoms or residues in-place.
Recursively removes all matching children from the element. After removing all matching children from a child, also removes any empty children.
- Template Parameters:
T – The type of element (Model, Chain, or Residue)
- Parameters:
t – The element to modify in-place
-
inline void remove_selected(Residue &res) const¶
Specialization for Residue: remove matching atoms.
Optimized version that clears all atoms if the selection matches all atoms, otherwise removes atoms one by one.
-
template<typename T>
inline void remove_not_selected(T &t) const¶ Remove all non-matching atoms or residues in-place.
Recursively removes all non-matching children from the element, then recurses into the remaining children.
- Template Parameters:
T – The type of element (Model, Chain, or Residue)
- Parameters:
t – The element to modify in-place
Public Members
-
int mdl = 0¶
Model number to select (0 = all models)
-
SequenceId from_seqid = {INT_MIN, '*'}¶
Start of sequence ID range (inclusive)
-
SequenceId to_seqid = {INT_MAX, '*'}¶
End of sequence ID range (inclusive)
-
std::vector<AtomInequality> atom_inequalities¶
Vector of numeric property filters.
-
struct AtomInequality¶
- #include <gemmi/select.hpp>
A numeric filter on atom properties (occupancy or B-factor).
Represents a constraint like “q>0.5” (occupancy greater than 0.5) or “b<30” (B-factor less than 30).
Public Functions
-
struct FlagList¶
- #include <gemmi/select.hpp>
Matches a single character flag against a pattern string.
Supports optional inversion with a leading ‘!’ character.
Public Functions
-
inline bool has(char flag) const¶
Check if a flag appears in the pattern.
If pattern begins with ‘!’, returns true if the flag does NOT appear in the rest of the pattern.
- Parameters:
flag – The flag character to check
- Returns:
true if the flag matches the pattern (or does not match if inverted)
-
inline bool has(char flag) const¶
-
struct List¶
- #include <gemmi/select.hpp>
Set of allowed names with optional inversion.
Represents comma-separated lists like “ALA,GLY” with optional inversion to mean “everything except”.
-
struct SequenceId¶
- #include <gemmi/select.hpp>
A residue sequence position for range matching.
Represents a single point in the residue sequence, with an optional insertion code. Special values INT_MIN and INT_MAX represent unset bounds.
Public Functions
-
inline bool empty() const¶
Check if this sequence ID is unset.
- Returns:
true if seqnum is INT_MIN or INT_MAX
-
std::string str() const¶
Get the string representation of this sequence ID.
- Returns:
String like “10” or “10A” depending on icode
-
inline int compare(const SeqId &seqid) const¶
Compare this sequence ID to another SeqId.
Compares first by sequence number, then by insertion code if needed. The wildcard ‘*’ for icode matches any insertion code.
- Parameters:
seqid – The SeqId to compare to
- Returns:
negative if less than, 0 if equal, positive if greater than seqid
-
inline bool empty() const¶
-
Selection() = default¶
-
struct Selection¶
-
namespace gemmi
Functions
-
template<class T>
void remove_alternative_conformations(T &obj)¶ Remove alternative conformations. Recursively removes all alternative conformations, keeping only the first (altloc=’A’ or blank). For Chain level, keeps one representative per residue seqid. For Residue level, removes duplicate atoms by name.
- Template Parameters:
T – Model, Chain, or Residue
-
template<class T>
void remove_hydrogens(T &obj)¶ Remove hydrogens and deuterium atoms. Recursively removes all H and D atoms from the structure.
- Template Parameters:
T – Model, Chain, or Residue
-
template<class T>
void assign_b_iso(T &obj, float b_min, float b_max)¶ Set isotropic ADP to the range (b_min, b_max). Values smaller than b_min are changed to b_min, values larger than b_max to b_max. Anisotropic ADP is left unchanged.
- Template Parameters:
T – Model, Chain, Residue, or Atom
- Parameters:
obj – object to modify
b_min – minimum B-factor value
b_max – maximum B-factor value
-
template<class T>
void remove_anisou(T &obj)¶ Remove anisotropic displacement parameters. Recursively zeroes all anisotropic ADP tensors (u11, u22, u33, u12, u13, u23).
- Template Parameters:
T – Model, Chain, Residue, or Atom
-
template<class T>
void ensure_anisou(T &obj)¶ Set absent ANISOU records to isotropic values derived from B_iso. For atoms without anisotropic ADP, creates isotropic tensor U = B_iso/(8π²).
- Template Parameters:
T – Model, Chain, Residue, or Atom
-
template<class T>
void transform_pos_and_adp(T &obj, const Transform &tr)¶ Apply a Transform to atomic positions and anisotropic displacement parameters. Recursively applies the given transformation to all atom coordinates and congruence-transforms anisotropic ADPs.
- Template Parameters:
T – Model, Chain, Residue, or Atom
- Parameters:
obj – object to transform
tr – transformation to apply
-
inline void assign_serial_numbers(Model &model, bool numbered_ter = false)¶
Assign atom site serial numbers (1, 2, 3, …) sequentially. Optionally leaves gaps at chain ends for TER records if numbering polymer chains.
- Parameters:
model – model containing chains
numbered_ter – if true, increment serial after last polymer residue in each chain
-
inline void assign_serial_numbers(Structure &st, bool numbered_ter = false)¶
Assign atom site serial numbers to all models in a structure.
- Parameters:
st – structure containing models
numbered_ter – if true, increment serial after last polymer residue in each chain
-
template<typename Func>
void process_addresses(Structure &st, Func func)¶ Apply a function to all AtomAddress references in structure metadata. Processes atom addresses in Connection, CisPep, StructSite, Helix, and Sheet records. Does not update ModRes, Entity::DbRef, Entity::full_sequence, or TlsGroup::Selection.
- Template Parameters:
Func – callable taking an AtomAddress& parameter
- Parameters:
st – structure whose metadata will be processed
func – function to apply to each AtomAddress
-
template<typename Func>
void process_sequence_ids(Structure &st, Func func)¶ Apply a function to all SeqId references in structure metadata. Processes sequence IDs in Connection/CisPep/StructSite/Helix/Sheet records, ModRes entries, and TlsGroup selections. Does not process Entity::DbRef::seq_begin/seq_end (no single chain name).
- Template Parameters:
Func – callable taking (const std::string& chain_name, SeqId& seqid)
- Parameters:
st – structure whose metadata will be processed
func – function to apply to each (chain_name, seqid) pair
-
inline void rename_chain(Structure &st, const std::string &old_name, const std::string &new_name)¶
Rename a chain throughout the structure. Updates all occurrences of old_name to new_name in models and metadata.
- Parameters:
st – structure to modify
old_name – current chain name
new_name – new chain name
-
inline void rename_residues(Structure &st, const std::string &old_name, const std::string &new_name)¶
Rename residues throughout the structure. Updates all residues named old_name to new_name in models and metadata. Also updates Entity sequences and StructSite member records.
- Parameters:
st – structure to modify
old_name – current residue name
new_name – new residue name
-
inline void rename_atom_names(Structure &st, const std::string &res_name, const std::map<std::string, std::string> &old_new)¶
Rename atoms in residues of a specific type. For residues named res_name, renames atoms according to the old→new map. Updates both atomic coordinates and metadata references.
- Parameters:
st – structure to modify
res_name – residue type to target
old_new – map from old atom names to new atom names
-
inline void replace_d_fraction_with_altlocs(Residue &res)¶
Expand deuterium-fraction representation into explicit H/D alternate conformations. Converts H atoms with non-zero d_fraction into H/D altloc pairs. If d_fraction >= 1, converts to pure D; otherwise creates H altloc ‘A’ and D altloc ‘D’.
- Parameters:
res – residue containing hydrogens to expand
-
inline bool replace_deuterium_with_fraction(Residue &res)¶
Contract explicit D atoms into H atoms with fractional occupancy. Merges H and D atoms at the same position into a single H atom, storing the D occupancy as the fraction field.
- Parameters:
res – residue containing deuterium atoms to contract
- Returns:
true if any D atoms were found and processed, false otherwise
-
inline void store_deuterium_as_fraction(Structure &st, bool store_fraction)¶
Toggle deuterium representation between fraction and explicit altlocs. Hydrogens modelled as H/D mixtures can be stored either as:
Two atoms with altlocs H and D (same position/ADP, different occupancies)
Single H atom with ccp4_deuterium_fraction parameter (CCP4/Refmac extension) This function converts between the two representations.
- Parameters:
st – structure to modify
store_fraction – if true, use fraction representation; otherwise use altlocs
-
inline void set_deuterium_fraction_of_hydrogens(Structure &st, float d_fract)¶
Set the deuterium fraction of all hydrogen atoms. Assigns the fraction field of all H atoms in the structure to d_fract.
- Parameters:
st – structure to modify
d_fract – deuterium fraction to assign (0.0 to 1.0)
-
inline void standardize_crystal_frame(Structure &st)¶
Transform structure to the standard crystallographic frame. Converts to standard coordinates where the a-axis is along x, the b-axis is in the xy-plane, and c-axis points along +z. Updates ORIGX matrices and NCS operators accordingly. Only operates on crystal structures with explicit transformation matrices.
- Parameters:
st – structure to transform
-
template<class T>
-
namespace gemmi
Functions
-
PolymerType check_polymer_type(const ConstResidueSpan &span, bool ignore_entity_type = false)¶
Classify a residue span as peptide, RNA, DNA, or other polymer type. A simplistic heuristic classification based on residue names. Returns PolymerType (PeptideL, PeptideD, Rna, Dna, DnaRnaHybrid, or Unknown).
- Parameters:
span – sequence of residues to classify
ignore_entity_type – if false, uses Entity type if known and consistent
- Returns:
PolymerType classification
-
inline PolymerType get_or_check_polymer_type(const Entity *ent, const ConstResidueSpan &polymer)¶
Determine polymer type from entity or by classification. Returns the entity’s polymer_type if known and non-Unknown, otherwise classifies the residue span.
- Parameters:
ent – entity with known polymer type (may be nullptr)
polymer – residue span to classify if entity type unknown
- Returns:
PolymerType classification
-
inline std::vector<AtomNameElement> get_mainchain_atoms(PolymerType ptype)¶
Get backbone atom names and elements for a polymer type. For peptides: N, CA, C, O. For nucleic acids: P, O5’, C5’, C4’, O4’, C3’, O3’, C2’, O2’, C1’.
- Parameters:
ptype – polymer type (peptide or nucleic acid)
- Returns:
vector of {atom_name, element} pairs for the backbone
-
inline bool in_peptide_bond_distance(const Atom *a1, const Atom *a2)¶
Check if two atoms are within peptide bond distance. Tests C(i)–N(i+1) distance < 2.01 Ångströms.
- Parameters:
a1 – C atom (may be nullptr)
a2 – N atom (may be nullptr)
- Returns:
true if both atoms exist and are within bond distance
-
inline bool have_peptide_bond(const Residue &r1, const Residue &r2)¶
Check if two consecutive residues are bonded by a peptide bond. Tests if the C atom of r1 and N atom of r2 are within peptide bond distance.
- Parameters:
r1 – first (C-terminal) residue
r2 – second (N-terminal) residue
- Returns:
true if peptide bond exists
-
inline bool in_nucleotide_bond_distance(const Atom *a1, const Atom *a2)¶
Check if two atoms are within nucleotide bond distance. Tests O3’(i)–P(i+1) distance < 2.4 Ångströms.
- Parameters:
a1 – O3’ atom (may be nullptr)
a2 – P atom (may be nullptr)
- Returns:
true if both atoms exist and are within bond distance
-
inline bool have_nucleotide_bond(const Residue &r1, const Residue &r2)¶
Check if two consecutive residues are bonded by a phosphodiester bond. Tests if the O3’ atom of r1 and P atom of r2 are within nucleotide bond distance.
- Parameters:
r1 – first residue
r2 – second (following) residue
- Returns:
true if phosphodiester bond exists
-
inline bool are_connected(const Residue &r1, const Residue &r2, PolymerType ptype)¶
Strict connectivity check using actual bond atoms. For peptides: tests C-N distance; for nucleotides: tests O3’-P distance.
- Parameters:
r1 – first residue
r2 – second residue
ptype – polymer type (peptide or nucleic acid)
- Returns:
true if residues are bonded
-
inline bool are_connected2(const Residue &r1, const Residue &r2, PolymerType ptype)¶
Loose connectivity check using only alpha-carbon or phosphorus atoms. For peptides: tests Cα–Cα < 5 Å; for nucleotides: tests P–P < 7.5 Å. Requires only Cα or P atoms, not full backbone atoms.
- Parameters:
r1 – first residue
r2 – second residue
ptype – polymer type (peptide or nucleic acid)
- Returns:
true if residues appear connected by distance
-
inline bool are_connected3(const Residue &r1, const Residue &r2, PolymerType ptype)¶
Connectivity check with fallback from strict to loose criteria. First tries are_connected() with actual bond atoms, then falls back to are_connected2() using Cα or P distances.
- Parameters:
r1 – first residue
r2 – second residue
ptype – polymer type (peptide or nucleic acid)
- Returns:
true if residues are connected by either criterion
-
std::string make_one_letter_sequence(const ConstResidueSpan &polymer)¶
Convert polymer residues to one-letter sequence codes. Translates residue names to standard IUPAC single-letter codes. Unknown residues become ‘X’.
- Parameters:
polymer – sequence of residues to convert
- Returns:
one-letter sequence string
-
void add_entity_types(Chain &chain, bool overwrite)¶
Assign entity types to residues in a chain. Assigns entity_type=Polymer|NonPolymer|Water to each residue. Only updates residues with entity_type==Unknown unless overwrite=true. Note: determining polymer/ligand boundary can be ambiguous for non-standard residues.
- Parameters:
chain – chain to annotate
overwrite – if true, reassign types even for known residues
-
void add_entity_types(Structure &st, bool overwrite)¶
Assign entity types to all chains in a structure.
- Parameters:
st – structure to annotate
overwrite – if true, reassign types even for known residues
-
void remove_entity_types(Structure &st)¶
Reset all residue entity types to Unknown.
- Parameters:
st – structure to modify
-
void add_entity_ids(Structure &st, bool overwrite)¶
Assign entity IDs to residues based on subchain assignments. Links Residue::entity_id to Entity records via Residue::subchain and Entity::subchains.
- Parameters:
st – structure to annotate
overwrite – if true, reassign IDs even for residues that already have them
-
void assign_subchain_names(Chain &chain, int &nonpolymer_counter)¶
Assign subchain labels to residues in a chain. Splits the chain into segments: linear polymers, non-polymers (each with unique ID), and waters. Stores label_asym_id-like names in Residue::subchain. wwPDB software splits auth_asym_id into label_asym_id units similarly. This function uses compatible but distinct naming and rules.
Note
call add_entity_types() first to set entity types correctly
- Parameters:
chain – chain to segment
nonpolymer_counter – incremented for each non-polymer segment (input/output)
-
void assign_subchains(Structure &st, bool force, bool fail_if_unknown = true)¶
Assign subchain names to all chains in a structure. Calls assign_subchain_names on each chain to segment into polymer/non-polymer units.
- Parameters:
st – structure to annotate
force – if true, reassign subchains even if already assigned
fail_if_unknown – if true, raise error if polymer type is unknown; if false, skip
-
void ensure_entities(Structure &st)¶
Create missing Entity records for all subchains in the structure. Ensures each Residue::subchain has a corresponding Entity.
- Parameters:
st – structure to update
-
void deduplicate_entities(Structure &st)¶
Merge Entity records with identical sequences into one. Consolidates duplicate sequence entries and updates residue entity_ids.
- Parameters:
st – structure to deduplicate
-
inline void setup_entities(Structure &st)¶
Set up entity metadata for a structure in a standard workflow. Convenience function that calls add_entity_types + assign_subchains + ensure_entities + deduplicate_entities in sequence.
- Parameters:
st – structure to set up
-
char recommended_het_flag(const Residue &res)¶
Determine ATOM/HETATM record type based on residue entity type. Returns ‘A’ (ATOM) for polymers or ‘H’ (HETATM) for non-polymers and waters.
- Parameters:
res – residue to classify
- Returns:
‘A’ or ‘H’
-
template<class T>
void assign_het_flags(T &obj, char flag = 'R')¶ Assign het_flag to all residues in an object.
- Template Parameters:
T – Model, Chain, or Residue
- Parameters:
obj – object to modify
flag – het_flag value: ‘A’ (ATOM), ‘H’ (HETATM), ‘R’ (recommended), or ‘ ‘ (none)
-
template<class T>
void remove_waters(T &obj)¶ Remove water residues from a structure or chain. May leave empty chains if all residues are waters.
- Template Parameters:
T – Model, Chain, or Residue
- Parameters:
obj – object to modify
-
template<class T>
void remove_ligands_and_waters(T &obj)¶ Remove all non-polymer residues (ligands and waters). Requires entity_type to be assigned first (see add_entity_types). May leave empty chains if all residues are removed.
- Template Parameters:
T – Model, Chain, or Residue
- Parameters:
obj – object to modify
-
bool trim_to_alanine(Residue &res)¶
Reduce an amino acid residue to an alanine backbone. Removes all side-chain atoms, keeping only N, CA, C, O and CB.
- Parameters:
res – residue to trim
- Returns:
true if trimmed successfully, false if residue is not a standard amino acid
-
inline void trim_to_alanine(Chain &chain)¶
Trim all amino acid residues in a chain to alanine.
- Parameters:
chain – chain to modify
-
void shorten_ccd_codes(Structure &st)¶
Convert long CCD codes to 3-letter abbreviations for PDB format compatibility. Refmac does similar shortening. Enables Refmac refinement with long residue names.
- Parameters:
st – structure to modify
-
void restore_full_ccd_codes(Structure &st)¶
Restore full CCD codes from their 3-letter abbreviations. Inverse of shorten_ccd_codes(); uses stored abbreviation mappings.
- Parameters:
st – structure to modify
-
void add_microhetero_to_sequences(Structure &st, bool overwrite = false)¶
Annotate microheterogeneity positions in entity sequences. Identifies residue positions with multiple alternate conformations and marks them in Entity::full_sequence. Uses only the first chain for each entity.
- Parameters:
st – structure to annotate
overwrite – if true, overwrite existing microheterogeneity annotations
-
struct AtomNameElement¶
- #include <gemmi/polyheur.hpp>
Atom name and chemical element pair. Used to represent backbone atom components of a polymer type.
-
PolymerType check_polymer_type(const ConstResidueSpan &span, bool ignore_entity_type = false)¶
-
namespace gemmi
Enums
-
enum class SecondaryStructure : char¶
Secondary structure type codes as defined in DSSP.
Values:
-
enumerator Loop¶
-
enumerator Break¶
Coil/loop (unassigned secondary structure)
-
enumerator Bend¶
Chain break.
-
enumerator Turn¶
Bend (local geometry criterion)
-
enumerator Helix_PP¶
Hydrogen-bonded turn.
-
enumerator Helix_5¶
Polyproline II helix.
-
enumerator Helix_3¶
π-helix (5-turn)
-
enumerator Strand¶
3₁₀-helix (3-turn)
-
enumerator Bridge¶
Extended β-strand.
-
enumerator Helix_4¶
Isolated β-bridge.
-
enumerator Loop¶
-
enum class TurnType¶
Hydrogen bond turn types, indexed by residue separation (i to i+n).
Values:
-
enumerator Turn_3¶
-
enumerator Turn_4¶
3-residue turn (i to i+3 hydrogen bond)
-
enumerator Turn_5¶
4-residue turn (i to i+4 hydrogen bond)
-
enumerator Turn_PP¶
5-residue turn (i to i+5 hydrogen bond)
-
enumerator Turn_3¶
-
enum class HelixPosition¶
Position of a residue within a helix.
Values:
-
enumerator None¶
-
enumerator Start¶
Not part of a helix.
-
enumerator Middle¶
First residue of a helix.
-
enumerator End¶
Interior residue of a helix.
-
enumerator StartAndEnd¶
Last residue of a helix.
Single-residue helix (acts as both start and end)
-
enumerator None¶
-
enum class BridgeType¶
Type of β-bridge partnership between residues.
Values:
-
enumerator None¶
-
enumerator Parallel¶
No bridge.
-
enumerator AntiParallel¶
Parallel β-bridge.
Antiparallel β-bridge
-
enumerator None¶
Functions
-
std::string calculate_dssp(NeighborSearch &ns, Topo::ChainInfo &cinfo, const DsspOptions &opts = DsspOptions{})¶
Convenience function to calculate secondary structure with default or custom options. Creates a DsspCalculator with the given options and runs the full secondary structure assignment.
- Parameters:
ns – NeighborSearch object with atoms indexed for spatial lookups
cinfo – Topo::ChainInfo containing the chain topology
opts – DsspOptions configuration (default: standard DSSP parameters)
- Returns:
Secondary structure string, one character per residue
-
struct Bridge¶
- #include <gemmi/dssp.hpp>
A simple β-bridge record between two residues.
Public Members
-
size_t partner1¶
-
size_t partner2¶
Chain index of the first bridge residue.
-
BridgeType type¶
Chain index of the second bridge residue.
-
size_t partner1¶
-
struct DsspCalculator¶
- #include <gemmi/dssp.hpp>
Main DSSP engine that performs secondary structure assignment for a protein chain.
Detects and annotates secondary structure elements (helices, strands, turns, etc.) based on hydrogen bond patterns and geometry, following the original DSSP algorithm.
- References
Kabsch, W. & Sander, C. (1983). Dictionary of protein secondary structure: pattern recognition of hydrogen-bonded and geometrical features. Biopolymers 22, 2577–2637. https://doi.org/10.1002/bip.360221211
Public Functions
-
inline explicit DsspCalculator(const DsspOptions &opts = DsspOptions{})¶
Initialize the calculator with options.
- Parameters:
opts – DsspOptions configuration (default: standard DSSP parameters)
-
std::string calculate_secondary_structure(NeighborSearch &ns, Topo::ChainInfo &chain_info)¶
Run the full DSSP secondary structure assignment for a chain. Requires a populated NeighborSearch for spatial lookups.
- Parameters:
ns – NeighborSearch object with the protein atoms indexed
chain_info – Topo::ChainInfo containing residue topology
- Returns:
Secondary structure string, one character per residue
-
inline const std::vector<SecondaryStructureInfo> &get_detailed_info() const¶
Access the per-residue secondary structure information.
- Returns:
Const reference to the vector of SecondaryStructureInfo
-
void calculate_hydrogen_bonds(NeighborSearch &ns, Topo::ChainInfo &chain_info)¶
List of all detected β-bridges.
Detect and record all hydrogen bonds in the chain.
- Parameters:
ns – NeighborSearch object with atoms indexed
chain_info – Topo::ChainInfo containing residue topology
-
void calculate_hbond_energy(Topo::ResInfo *donor, Topo::ResInfo *acceptor)¶
Compute and store Kabsch-Sander hydrogen bond energy between donor and acceptor.
- Parameters:
donor – Topo::ResInfo pointer for the NH (donor) residue
acceptor – Topo::ResInfo pointer for the C=O (acceptor) residue
-
void calculate_hbond_geometry(Topo::ResInfo *donor, Topo::ResInfo *acceptor)¶
Evaluate geometric hydrogen bond criterion (distance and angle) between donor and acceptor.
- Parameters:
donor – Topo::ResInfo pointer for the NH (donor) residue
acceptor – Topo::ResInfo pointer for the C=O (acceptor) residue
-
bool has_hbond_between(Topo::ResInfo *donor, Topo::ResInfo *acceptor) const¶
Check if a valid hydrogen bond exists from donor to acceptor.
- Parameters:
donor – Topo::ResInfo pointer for the donor
acceptor – Topo::ResInfo pointer for the acceptor
- Returns:
True if a hydrogen bond exists between the residues
-
bool no_chain_breaks_between(Topo::ChainInfo &chain_info, size_t res1_idx, size_t res2_idx) const¶
Check for chain breaks between two residue indices.
- Parameters:
chain_info – Topo::ChainInfo containing residue topology
res1_idx – Chain index of the first residue
res2_idx – Chain index of the second residue
- Returns:
True if no chain breaks exist between res1_idx and res2_idx
-
BridgeType calculate_bridge_type(Topo::ChainInfo &chain_info, size_t res1_idx, size_t res2_idx) const¶
Determine the type of β-bridge between two residues.
- Parameters:
chain_info – Topo::ChainInfo containing residue topology
res1_idx – Chain index of the first residue
res2_idx – Chain index of the second residue
- Returns:
BridgeType (Parallel, AntiParallel, or None)
Public Members
-
DsspOptions options¶
-
std::vector<SecondaryStructureInfo> ss_info¶
Configuration options for this calculation.
-
struct DsspOptions¶
- #include <gemmi/dssp.hpp>
Configuration parameters for the DSSP secondary structure algorithm.
Public Members
-
HydrogenMode hydrogen_mode = HydrogenMode::Calculate¶
-
HBondDefinition hbond_definition = HBondDefinition::Energy¶
How to source hydrogen atoms (Existing or Calculate)
-
double cutoff = 0.9¶
Criterion for hydrogen bond acceptance (Energy or Geometry)
-
bool pi_helix_preference = true¶
Distance cutoff in nm for hydrogen bond search (default 0.9)
-
bool search_polyproline = true¶
If true, prefer π-helix over α-helix at ambiguous positions.
-
bool shortened_pp_stretch = false¶
If true, detect polyproline II helices.
-
double hbond_energy_cutoff = -0.5¶
If true, allow polyproline stretches shorter than canonical.
-
double min_ca_distance = 9.0¶
Energy threshold in kcal/mol for hydrogen bond acceptance (default -0.5)
-
double bend_angle_min = 70.0¶
Minimum Cα–Cα distance in Angstrom to consider residues potentially bonded (default 9.0)
-
double max_peptide_bond_distance = 2.5¶
Minimum bend angle in degrees to assign Bend secondary structure (default 70.0)
-
HydrogenMode hydrogen_mode = HydrogenMode::Calculate¶
-
struct HBond¶
- #include <gemmi/dssp.hpp>
Record of one hydrogen bond detected by DSSP.
-
struct SecondaryStructureInfo¶
- #include <gemmi/dssp.hpp>
Per-residue secondary structure annotation and structural features.
Public Functions
-
inline void set_helix_position(TurnType turn, HelixPosition pos)¶
True if this residue is the acceptor of an n-turn hydrogen bond.
Set the helix position for a given turn type.
- Parameters:
turn – TurnType value (Turn_3, Turn_4, Turn_5, or Turn_PP)
pos – HelixPosition value
-
inline HelixPosition get_helix_position(TurnType turn) const¶
Retrieve the helix position for a given turn type.
- Parameters:
turn – TurnType value
- Returns:
HelixPosition at the specified turn
-
inline void add_bridge(size_t partner_idx, BridgeType type)¶
Record a β-bridge partnership with another residue.
- Parameters:
partner_idx – Chain index of the bridge partner
type – BridgeType (Parallel or AntiParallel)
-
inline bool has_bridges(BridgeType type) const¶
Check if this residue has any bridges of the given type.
- Parameters:
type – BridgeType to check
- Returns:
True if this residue has at least one bridge of the given type
Public Members
-
SecondaryStructure ss_type = SecondaryStructure::Loop¶
-
std::vector<size_t> antiparallel_bridges¶
Chain indices of residues forming parallel β-bridges with this residue.
-
std::vector<SecondaryStructureInfo*> break_partners¶
Chain indices of residues forming antiparallel β-bridges with this residue.
-
std::array<HelixPosition, 4> helix_positions = {HelixPosition::None, HelixPosition::None, HelixPosition::None, HelixPosition::None}¶
Pointers to SecondaryStructureInfo of chain-break partners.
-
bool nturn_acceptor = false¶
True if there is a chain break before this residue.
-
inline void set_helix_position(TurnType turn, HelixPosition pos)¶
-
enum class SecondaryStructure : char¶
Structure Factor Calculations¶
Direct structure factor summation, amplitude normalisation (F→E), and anisotropic scaling with optional bulk-solvent correction.
-
namespace gemmi
Functions
-
inline std::complex<double> calculate_sf_part(const Fractional &fpos, const Miller &hkl)¶
Compute exp(2πi r·s) for one atom at fractional position for a reflection.
- Parameters:
fpos – Fractional coordinates of the atom.
hkl – Miller indices of the reflection.
- Returns:
Complex phase factor.
-
template<typename Table>
class StructureFactorCalculator¶ - #include <gemmi/sfcalc.hpp>
Calculates structure factors by direct summation over all atoms.
Simple direct summation; for optimised FFT-based calculations see dencalc.hpp + fourier.hpp.
- References
Bourhis, L.J., Dolomanov, O.V., Gildea, R.J., Howard, J.A.K. & Puschmann, H. (2015). The anatomy of a comprehensive constrained, restrained refinement program for the modern computing environment — Olex2 dissected. Acta Cryst. A70, 300–311. https://doi.org/10.1107/S2053273314022207
- Template Parameters:
Table – Scattering factor table type (e.g., IT92, WK95, ElectronTable). Must have a nested Coef type with coef_type member.
Public Functions
-
inline StructureFactorCalculator(const UnitCell &cell)¶
Initialize with the unit cell.
- Parameters:
cell – Unit cell; a reference is stored for use in subsequent calculations.
-
inline void set_stol2_and_scattering_factors(const Miller &hkl)¶
Cache (sin θ/λ)² for hkl and clear the scattering factor cache. Must be called before computing structure factors for a new reflection.
- Parameters:
hkl – Miller indices of the reflection.
-
inline double get_scattering_factor(Element element, signed char charge)¶
Return scattering factor for element at current (sin θ/λ)². Lazily computes and caches the result.
- Parameters:
element – The chemical element.
charge – Formal charge (signed char; 0 = neutral atom).
- Returns:
Scattering factor value.
-
inline double dwf_iso(const SmallStructure::Site &site) const¶
Isotropic Debye-Waller factor exp(-B·stol²) for a small-molecule site.
- Parameters:
site – Small-molecule site with u_iso field.
- Returns:
Debye-Waller factor value.
-
inline double dwf_iso(const Atom &atom) const¶
Isotropic Debye-Waller factor exp(-B·stol²) for a macromolecular atom.
- Parameters:
atom – Macromolecular atom with b_iso field.
- Returns:
Debye-Waller factor value.
-
inline double dwf_aniso(const SmallStructure::Site &site, const Vec3 &hkl) const¶
Anisotropic Debye-Waller factor exp(-2π²·s·U·s) for a small-molecule site. Uses site.aniso, where the anisotropic U tensor is in crystallographic coordinates.
- Parameters:
site – Small-molecule site with aniso field.
hkl – Miller indices of the reflection.
- Returns:
Debye-Waller factor value.
-
inline double dwf_aniso(const Atom &atom, const Vec3 &hkl) const¶
Anisotropic Debye-Waller factor exp(-2π²·s·U·s) for a macromolecular atom. Uses atom.aniso in orthogonal coordinates.
- Parameters:
atom – Macromolecular atom with aniso field.
hkl – Miller indices of the reflection.
- Returns:
Debye-Waller factor value.
-
template<typename Site>
inline std::complex<double> calculate_sf_from_atom_sf(const Fractional &fract, const Site &site, const Miller &hkl, double sf)¶ Contribution of one atom to structure factor, given its scattering factor. Accounts for Debye-Waller factor, occupancy, and phase.
- Template Parameters:
Site – SmallStructure::Site or Atom.
- Parameters:
fract – Fractional coordinates of the atom.
site – Site/atom record containing occupancy and aniso data.
hkl – Miller indices of the reflection.
sf – Precomputed scattering factor for this atom.
- Returns:
Complex structure factor contribution.
-
template<typename Site>
inline std::complex<double> calculate_sf_from_atom(const Fractional &fract, const Site &site, const Miller &hkl)¶ Contribution of one atom to structure factor, with automatic scattering factor lookup. Accounts for Debye-Waller factor, occupancy, and phase.
- Template Parameters:
Site – SmallStructure::Site or Atom.
- Parameters:
fract – Fractional coordinates of the atom.
site – Site/atom record containing element and charge information.
hkl – Miller indices of the reflection.
- Returns:
Complex structure factor contribution.
-
inline std::complex<double> calculate_sf_from_model(const Model &model, const Miller &hkl)¶
Sum contributions from all atoms in a Model for the given reflection.
- Parameters:
model – The macromolecular model.
hkl – Miller indices of the reflection.
- Returns:
Total structure factor.
-
inline std::complex<double> calculate_mb_z(const Model &model, const Miller &hkl, bool only_h)¶
Compute Z (atomic number sum) component for Mott-Bethe conversion. Used when a different model is needed for the Z calculation.
- Parameters:
model – The macromolecular model.
hkl – Miller indices of the reflection.
only_h – If true, restrict calculation to hydrogen atoms.
- Returns:
Z component of structure factor.
-
inline double mott_bethe_factor() const¶
Return the Mott-Bethe prefactor at current (sin θ/λ)². Used to convert X-ray structure factors to electron structure factors.
- Returns:
Mott-Bethe factor: -mott_bethe_const() / (4·stol²).
-
inline std::complex<double> calculate_sf_from_small_structure(const SmallStructure &small_st, const Miller &hkl)¶
Sum contributions from all sites in a SmallStructure for the given reflection. The occupancy is assumed to account for symmetry (i.e., fractional if the atom is on a special position).
- Parameters:
small_st – The small-molecule structure.
hkl – Miller indices of the reflection.
- Returns:
Total structure factor.
Public Members
-
inline std::complex<double> calculate_sf_part(const Fractional &fpos, const Miller &hkl)¶
-
namespace gemmi
Functions
-
template<typename DataProxy>
std::vector<double> calculate_amplitude_normalizers(const DataProxy &data, int fcol_idx, const Binner &binner)¶ Compute per-reflection amplitude normalization factors for E-scale conversion. Uses the Karle approach: E = F / sqrt(Σ f²), with resolution-bin-based averaging and smoothing.
- Template Parameters:
DataProxy – Type satisfying the data proxy interface: must provide size(), stride(), spacegroup(), unit_cell(), get_hkl(n), and get_num(n) methods.
- Parameters:
data – Data proxy (e.g., MtzDataProxy or ReflDataProxy).
fcol_idx – Column index of F amplitudes in the proxy.
binner – Binner object defining resolution shells.
- Returns:
Vector of multipliers (one per reflection); NaN for missing values. Algorithm: collects F² in bins, applies [0.75, 1, 0.75] smoothing kernel, returns 1/sqrt(<F²>) per reflection for normalization.
-
template<typename DataProxy>
-
namespace gemmi
Typedefs
Functions
-
inline double vec6_dot(const Vec6 &a, const SMat33<double> &s)¶
Dot product of Vec6 with a symmetric 3×3 matrix. Used for tensor contractions in ADP refinement.
- Parameters:
a – Vec6 vector (6-element array).
s – Symmetric 3×3 matrix.
- Returns:
Dot product result.
-
inline std::vector<Vec6> adp_symmetry_constraints(const SpaceGroup *sg)¶
Return the symmetry-adapted constraint vectors for the ADP tensor in a space group. The number and content of returned constraint vectors depend on the crystal system. For example, cubic returns one vector [1 1 1 0 0 0] (isotropic); tetragonal returns two vectors in directions [1 1 0 0 0 0] and [0 0 1 0 0 0] (diagonal u11=u22, u33 free).
- Parameters:
sg – Pointer to the space group; if null, triclinic symmetry is assumed (6 free components).
- Returns:
Vector of normalized Vec6 constraint vectors for independent ADP components.
-
template<typename Real>
struct Scaling¶ - #include <gemmi/scaling.hpp>
Anisotropic scaling of calculated structure factors to observed data.
Optionally includes bulk solvent correction: Fc + k_sol·exp(-b_sol·stol²)·Fmask. Parameter refinement uses Levenberg-Marquardt (or NLopt if WITH_NLOPT is defined).
Fokine, A. & Urzhumtsev, A. (2002). Flat bulk-solvent model: obtaining optimal parameters. Acta Cryst. A58, 384–392.
https://doi.org/10.1107/S0108767302005669- References
Afonine, P.V. et al. (2012). Towards automated crystallographic structure refinement with phenix.refine. Acta Cryst. D68, 352–367. https://doi.org/10.1107/S0907444913000462
- Template Parameters:
Real – Floating-point type (float or double).
Public Functions
-
inline Scaling(const UnitCell &cell_, const SpaceGroup *sg)¶
Initialize with unit cell and space group. Sets up constraint_matrix from crystal system symmetry.
- Parameters:
cell_ – Unit cell parameters.
sg – Pointer to space group (for symmetry constraints).
-
inline void set_b_overall(const SMat33<double> &b_overall)¶
Set b_star from a real-space B matrix. Converts from Cartesian coordinates to reciprocal-space B*.
- Parameters:
b_overall – B matrix in real (Cartesian) space.
-
inline SMat33<double> get_b_overall() const¶
Get b_star converted back to real (Cartesian) space.
- Returns:
B matrix in Cartesian coordinates.
-
inline void scale_data(AsuData<std::complex<Real>> &asu_data, const AsuData<std::complex<Real>> *mask_data) const¶
Apply scaling to all reflections in-place, optionally adding bulk solvent correction.
- Parameters:
asu_data – ASU data to scale (modified in-place).
mask_data – Mask (solvent) data; required if use_solvent is true, otherwise may be null.
-
inline std::complex<Real> scale_value(const Miller &hkl, std::complex<Real> f_value, std::complex<Real> mask_value)¶
Compute scaled value for one reflection. Applies overall scale factor and optionally bulk solvent correction.
- Parameters:
hkl – Miller indices.
f_value – Calculated molecular structure factor.
mask_value – Mask (solvent) structure factor.
- Returns:
Scaled complex structure factor.
-
inline std::vector<double> get_parameters() const¶
Return current parameters as a flat vector. Includes k_overall, b_star components (via constraint_matrix), and optionally k_sol and b_sol.
- Returns:
Vector of parameters in order: k_overall, [k_sol], [b_sol], b_star_components.
-
inline void set_parameters(const double *p)¶
Set parameters from pointer or vector. Updates k_overall, b_star components (via constraint_matrix), and optionally k_sol and b_sol.
- Parameters:
p – Pointer to parameter array (order: k_overall, [k_sol], [b_sol], b_star_components).
-
inline void set_parameters(const std::vector<double> &p)¶
Set parameters from vector.
- Parameters:
p – Vector of parameters.
-
inline void prepare_points(const AsuData<std::complex<Real>> &calc, const AsuData<ValueSigma<Real>> &obs, const AsuData<std::complex<Real>> *mask_data)¶
Populate points from matching reflections in calc and obs datasets. Precondition: all AsuData arguments must be sorted by Miller indices.
- Parameters:
calc – Calculated structure factors.
obs – Observed amplitudes and sigmas.
mask_data – Mask structure factors; required if use_solvent is true.
-
inline double get_solvent_scale(double stol2) const¶
Compute k_sol * exp(-b_sol * stol²) for bulk solvent correction.
- Parameters:
stol2 – (sin θ/λ)² value.
- Returns:
Solvent scale factor.
-
inline double get_overall_scale_factor(const Miller &hkl) const¶
Compute k_overall * exp(-b_star:hkl) for overall scale factor.
- Parameters:
hkl – Miller indices.
- Returns:
Overall scale factor including anisotropic B*.
-
inline std::complex<Real> get_fcalc(const Point &p) const¶
Compute total calculated structure factor for point p. Includes molecular part and optionally bulk solvent correction.
- Parameters:
p – Reflection point.
- Returns:
Total Fcalc = Fcmol + k_sol·exp(-b_sol·stol²)·Fmask (or just Fcmol if no solvent).
-
inline void fit_isotropic_b_approximately()¶
Quick linear least-squares fit of isotropic B only (ignoring sigma). Used for initialization before full refinement.
-
inline double lsq_k_overall() const¶
Compute optimal k_overall by linear least squares.
- Returns:
Optimal scale factor.
-
inline void fit_b_star_approximately()¶
Fit anisotropic B* by linear approximation (for testing/initialization only). DO NOT USE for production: symmetry constraints are not implemented. Based on P. Afonine et al., doi:10.1107/S0907444913000462, section 2.1.
-
inline double fit_parameters()¶
Full Levenberg-Marquardt optimization of all parameters.
- Returns:
Final R factor.
-
inline double calculate_r_factor() const¶
Compute R-factor: Σ|Fobs - Fcalc| / Σ|Fobs|.
- Returns:
R-factor value.
-
inline double compute_value(const Point &p) const¶
Compute Fcalc for point p (interface for fitting).
- Parameters:
p – Reflection point.
- Returns:
Scaled calculated structure factor amplitude.
-
inline double compute_value_and_derivatives(const Point &p, std::vector<double> &dy_da) const¶
Compute Fcalc and its derivatives with respect to all parameters.
- Parameters:
p – Reflection point.
dy_da – Output vector to fill with derivatives [dy/dk_overall, dy/dk_sol, dy/db_sol, dy/db_star_components].
- Returns:
Calculated structure factor amplitude.
Public Members
-
double k_overall = 1.¶
Overall scale factor.
-
bool use_solvent = false¶
If true, include bulk solvent correction.
-
bool fix_k_sol = false¶
If true, do not refine k_sol.
-
bool fix_b_sol = false¶
If true, do not refine b_sol.
-
double k_sol = 0.35¶
Bulk solvent scale factor.
-
double b_sol = 46.0¶
Bulk solvent B-factor.
-
inline double vec6_dot(const Vec6 &a, const SMat33<double> &s)¶
I/O and Filesystem Utilities¶
File and directory traversal, gzip support, stream abstractions, PDB path utilities, and general-purpose string and container helpers.
(Full documentation added in PR 10.)
-
namespace gemmi
Typedefs
-
using MmCifWalk = DirWalk<true, impl::IsMmCifFile>¶
Type alias for walking mmCIF files only.
-
using CoorFileWalk = DirWalk<true, impl::IsCoordinateFile>¶
Type alias for walking coordinate files (mmCIF, PDB, ENT).
-
template<bool FileOnly = true, typename Filter = impl::IsAnyFile>
class DirWalk¶ - #include <gemmi/dirwalk.hpp>
Directory tree walker (depth-first, alphabetical order).
Template class for iterating over files and directories in a directory tree.
- Template Parameters:
FileOnly – if true, iterate over files only; if false, include directories
Filter – predicate type to filter which files/directories to visit
Public Functions
-
inline explicit DirWalk(const char *path, char try_pdbid = '\0')¶
Initialize directory walker.
Construct a DirWalk starting from a given path.
- Parameters:
path – root directory or file path to start traversal
try_pdbid – expansion type char (e.g. ‘M’), or ‘\0’ to skip PDB code expansion
-
inline explicit DirWalk(const std::string &path, char try_pdbid = '\0')¶
Initialize directory walker from string path.
Construct a DirWalk from a std::string path.
- Parameters:
path – root directory or file path to start traversal
try_pdbid – expansion type char (e.g. ‘M’), or ‘\0’ to skip PDB code expansion
-
inline ~DirWalk()¶
Clean up resources.
Destructor.
-
inline void push_dir(size_t cur_pos, const _tinydir_char_t *path)¶
Record current position and open a new subdirectory.
Push a subdirectory onto the traversal stack.
- Parameters:
cur_pos – index of current file in parent directory
path – subdirectory path to open
-
inline size_t pop_dir()¶
Close current directory and return to parent.
Pop a subdirectory from the traversal stack.
- Returns:
position (index) to resume in parent directory
-
inline Iter begin()¶
Create iterator for range-based for loop.
Get iterator to beginning of traversal.
- Returns:
iterator pointing to first file/directory
-
inline Iter end()¶
Sentinel iterator for range-based for loop.
Get iterator to end of traversal.
- Returns:
iterator marking end of traversal
-
inline bool is_single_file()¶
Test whether the root is a file rather than directory.
Check if root path is a single file.
- Returns:
true if root path is a file (not a directory)
Friends
- friend struct Iter
-
struct Iter¶
- #include <gemmi/dirwalk.hpp>
Depth-first iterator over files and directories.
Iterator for directory tree traversal.
Public Functions
-
inline const tinydir_dir &get_dir() const¶
Access current tinydir_dir structure.
Get reference to current directory.
- Returns:
reference to the current directory being traversed
-
inline const tinydir_file &get() const¶
Access the current tinydir_file structure.
Get current file/directory entry.
- Returns:
reference to current file or directory being traversed
-
inline std::string operator*() const¶
Get the full path of current file/directory.
Dereference iterator to get file path.
- Returns:
current file/directory path as UTF-8 string
-
inline bool is_special(const _tinydir_char_t *name) const¶
Test if name is a special directory reference.
Check if name is “.” or “..”.
- Parameters:
name – filename to check
- Returns:
true if name is “.” or “..”
-
inline size_t depth() const¶
Return the nesting level in the directory tree.
Get current traversal depth.
- Returns:
depth (0 for root level)
-
inline void next()¶
Perform one step of depth-first traversal.
Advance to next file/directory (internal use).
-
inline void operator++()¶
Advance to next matching file/directory in traversal.
Pre-increment operator.
-
inline const tinydir_dir &get_dir() const¶
-
struct GlobWalk : public gemmi::DirWalk<true, impl::IsMatchingFile>¶
- #include <gemmi/dirwalk.hpp>
Directory walker with glob pattern matching.
Iterates over files matching a wildcard pattern.
-
namespace impl
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
Functions
-
inline int utf8_tinydir_file_open(tinydir_file *file, const char *path)¶
-
struct IsAnyFile¶
- #include <gemmi/dirwalk.hpp>
-
struct IsCifFile¶
- #include <gemmi/dirwalk.hpp>
-
struct IsCoordinateFile¶
- #include <gemmi/dirwalk.hpp>
-
struct IsMatchingFile¶
- #include <gemmi/dirwalk.hpp>
-
struct IsMmCifFile¶
- #include <gemmi/dirwalk.hpp>
-
struct IsPdbFile¶
- #include <gemmi/dirwalk.hpp>
-
inline int utf8_tinydir_file_open(tinydir_file *file, const char *path)¶
-
using MmCifWalk = DirWalk<true, impl::IsMmCifFile>¶
-
namespace gemmi
Typedefs
-
typedef std::unique_ptr<std::FILE, needs_fclose> fileptr_t¶
Unique pointer to FILE with custom deleter.
Functions
-
inline std::string path_basename(const std::string &path, std::initializer_list<const char*> exts)¶
Extract filename with optional suffix removal.
Extract basename from path, optionally stripping directory and suffixes.
- Parameters:
path – full file path
exts – list of file extensions to strip from basename
- Returns:
basename without directory path and specified extensions
-
inline fileptr_t file_open(const char *path, const char *mode)¶
Open file with UTF-8 filename support and error handling.
Open a file and return a managed pointer.
- Parameters:
path – UTF-8 encoded file path
mode – file open mode (e.g., “rb”, “wb”)
- Throws:
std::runtime_error – if file cannot be opened
- Returns:
managed FILE pointer that auto-closes on destruction
-
inline fileptr_t file_open_or_null(const char *path, const char *mode)¶
Open file without exception on error.
Open a file, returning null pointer on failure instead of throwing.
- Parameters:
path – UTF-8 encoded file path
mode – file open mode (e.g., “rb”, “wb”)
- Returns:
managed FILE pointer or empty pointer if open fails
-
inline fileptr_t file_open_or(const char *path, const char *mode, std::FILE *dash_stream)¶
Open file or return predefined stream for dash character.
Open a file, treating “-” as stdin/stdout.
- Parameters:
path – file path, or “-” for stdin/stdout
mode – file open mode (e.g., “rb” or “wb”)
dash_stream – stream to use when path is “-”
- Returns:
managed FILE pointer (either opened file or dash_stream)
-
inline std::size_t file_size(std::FILE *f, const std::string &path)¶
Determine file size in bytes.
Get file size by seeking to end and back.
- Parameters:
f – open FILE pointer
path – file path (used only for error messages)
- Throws:
std::runtime_error – if seek or tell operations fail
- Returns:
file size in bytes
-
inline bool is_little_endian()¶
Test platform byte order.
Check if platform is little-endian.
- Returns:
true if platform is little-endian, false if big-endian
-
inline void swap_two_bytes(void *start)¶
Reverse byte order of a short integer.
Swap bytes in a 2-byte value.
- Parameters:
start – pointer to 2-byte value to swap in-place
-
inline void swap_four_bytes(void *start)¶
Reverse byte order of a 32-bit integer.
Swap bytes in a 4-byte value.
- Parameters:
start – pointer to 4-byte value to swap in-place
-
inline void swap_eight_bytes(void *start)¶
Reverse byte order of a 64-bit integer or double.
Swap bytes in an 8-byte value.
- Parameters:
start – pointer to 8-byte value to swap in-place
-
inline CharArray read_file_into_buffer(const std::string &path)¶
Load file contents into CharArray (uses fseek for size determination).
Read entire file into a memory buffer.
-
inline CharArray read_stdin_into_buffer()¶
Load standard input into CharArray.
Read stdin into a memory buffer.
-
template<typename T>
inline CharArray read_into_buffer(T &&input)¶ Intelligently read various input sources into CharArray.
Read input (file, gzip, or stdin) into a buffer.
- Template Parameters:
T – input type (typically BasicInput or derived)
- Parameters:
input – input object with is_compressed(), is_stdin(), and path() methods
- Returns:
CharArray containing input data
-
class CharArray¶
- #include <gemmi/fileutil.hpp>
Dynamically allocated character buffer.
Manages memory using std::malloc/std::realloc/std::free.
Public Functions
-
inline CharArray()¶
Default constructor for zero-sized buffer.
Create an empty buffer.
-
inline explicit CharArray(size_t n)¶
Allocate buffer of given size.
Create a buffer of specified size.
- Parameters:
n – buffer size in bytes
-
inline explicit operator bool() const¶
Test whether buffer contains valid memory.
Check if buffer is allocated.
- Returns:
true if buffer is not null
-
inline char *data()¶
Get writable pointer to buffer.
Access buffer data.
- Returns:
pointer to buffer data
-
inline const char *data() const¶
Get read-only pointer to buffer.
Access buffer data (const).
- Returns:
const pointer to buffer data
-
inline size_t size() const¶
Return current buffer size in bytes.
Get buffer size.
- Returns:
buffer size
-
inline void set_size(size_t n)¶
Update internal size without reallocating.
Change recorded buffer size.
- Parameters:
n – new size value
-
inline void resize(size_t n)¶
Reallocate buffer to given size.
Resize buffer to new size.
- Parameters:
n – new buffer size in bytes
- Throws:
std::runtime_error – if reallocation fails and n is non-zero
-
inline char *roll(size_t n)¶
Roll buffer forward by removing leading bytes.
Remove first n bytes and shift remaining data.
- Parameters:
n – number of bytes to remove from start
- Returns:
pointer to space at end for new data
-
inline CharArray()¶
-
typedef std::unique_ptr<std::FILE, needs_fclose> fileptr_t¶
-
namespace gemmi
Functions
-
template<typename T>
inline void open_stream_from_utf8_path(T &ptr, const std::string &filename)¶ Helper to open streams with UTF-8 paths on Windows.
Open a file stream with UTF-8 filename support.
- Template Parameters:
T – stream type (std::ofstream or std::ifstream)
- Parameters:
ptr – pointer to stream object to open
filename – UTF-8 encoded filename
-
struct Ifstream¶
- #include <gemmi/fstream.hpp>
Input file stream wrapper with UTF-8 filename support.
Handles filename “-” as stdin and UTF-8 paths on Windows.
Public Functions
-
inline Ifstream(const std::string &filename, std::istream *dash = nullptr)¶
Construct input stream.
Open input file with optional dash handling.
- Parameters:
filename – UTF-8 file path (or “-” to use dash_stream)
dash – pointer to stream to use if filename is “-” (typically std::cin)
-
inline Ifstream(const std::string &filename, std::istream *dash = nullptr)¶
-
struct Ofstream¶
- #include <gemmi/fstream.hpp>
Output file stream wrapper with UTF-8 filename support.
Handles filename “-” as stdout and UTF-8 paths on Windows.
Public Functions
-
inline Ofstream(const std::string &filename, std::ostream *dash = nullptr)¶
Construct output stream.
Open output file with optional dash handling.
- Parameters:
filename – UTF-8 file path (or “-” to use dash_stream)
dash – pointer to stream to use if filename is “-” (typically std::cout)
-
inline Ofstream(const std::string &filename, std::ostream *dash = nullptr)¶
-
template<typename T>
-
namespace gemmi
Functions
Variables
-
const char *const zlib_description¶
String describing zlib version and build information.
-
struct GzStream : public gemmi::AnyStream¶
- #include <gemmi/gz.hpp>
Stream wrapper for reading gzipped files.
Implements AnyStream interface for transparent gzip reading (using zlib).
Public Functions
-
inline GzStream(void *f_)¶
Construct stream from gzFile handle.
Create a gzip stream from a zlib gzFile pointer.
- Parameters:
f_ – opaque gzFile pointer
-
virtual char *gets(char *line, int size) override¶
Read next line into buffer.
Read a line from the stream.
- Parameters:
line – buffer to store line
size – maximum bytes to read (including null terminator)
- Returns:
pointer to line or null if end of file
-
virtual int getc() override¶
Get next byte from stream.
Read a single character.
- Returns:
character as int, or -1 for end of file
-
virtual bool read(void *buf, size_t len) override¶
Read specified number of bytes.
Read a block of data.
- Parameters:
buf – buffer to read into
len – number of bytes to read
- Returns:
true if exactly len bytes were read
-
virtual bool skip(size_t n) override¶
Advance stream position without reading.
Skip forward in stream.
- Parameters:
n – number of bytes to skip
- Returns:
true if skip succeeded
-
virtual long tell() override¶
Report stream position.
Get current position.
- Returns:
current byte offset in stream
Private Members
-
void *f¶
-
inline GzStream(void *f_)¶
-
class MaybeGzipped : public gemmi::BasicInput¶
- #include <gemmi/gz.hpp>
Input source that transparently handles gzipped files.
Manages both regular and gzipped files with automatic detection.
Public Functions
-
explicit MaybeGzipped(const std::string &path)¶
Initialize reader for file that may be gzipped.
Open a file (compressed or uncompressed).
- Parameters:
path – file path (may end in .gz)
-
~MaybeGzipped()¶
Destructor.
Close file resources.
-
size_t gzread_checked(void *buf, size_t len)¶
Read bytes from gzipped stream.
Read from gzipped file with error checking.
- Parameters:
buf – buffer to read into
len – number of bytes to read
- Throws:
std::runtime_error – on gzip read error
- Returns:
number of bytes read
-
inline bool is_compressed() const¶
Test whether file has .gz extension.
Check if file is gzip compressed.
- Returns:
true if path ends with .gz
-
inline std::string basepath() const¶
Remove .gz suffix if present.
Get path without .gz extension.
- Returns:
path without extension, or original path if not gzipped
Private Members
-
void *file_ = nullptr¶
-
explicit MaybeGzipped(const std::string &path)¶
-
const char *const zlib_description¶
-
namespace gemmi
-
struct AnyStream¶
- #include <gemmi/input.hpp>
Base class for stream abstractions (FileStream, MemoryStream, GzStream).
Subclassed by gemmi::FileStream, gemmi::GzStream, gemmi::MemoryStream
Public Functions
-
virtual ~AnyStream() = default¶
-
virtual char *gets(char *line, int size) = 0¶
Read a line of text into a buffer.
- Parameters:
line – Output buffer for the line
size – Maximum number of characters to read
- Returns:
Pointer to line on success, nullptr if end of stream reached
-
virtual int getc() = 0¶
Read a single character from the stream.
- Returns:
Next character, or EOF if end of stream reached
-
virtual bool read(void *buf, size_t len) = 0¶
Read a block of binary data.
- Parameters:
buf – Output buffer
len – Number of bytes to read
- Returns:
True if successfully read exactly len bytes, false otherwise
-
virtual long tell() = 0¶
Get current position in the stream.
- Returns:
Current byte offset
-
virtual bool skip(size_t n) = 0¶
Skip ahead in the stream.
- Parameters:
n – Number of bytes to skip
- Returns:
True if skip succeeded
-
inline virtual std::string read_rest()¶
Read remaining data in the stream.
- Returns:
String containing remaining data, or empty string if none
-
inline size_t copy_line(char *line, int size)¶
Read a line and discard any overflow.
- Parameters:
line – Output buffer
size – Maximum characters to read
- Returns:
Length of line read (including newline if present)
-
virtual ~AnyStream() = default¶
-
class BasicInput¶
- #include <gemmi/input.hpp>
Input source abstraction for file paths.
Subclassed by gemmi::MaybeGzipped
Public Functions
-
inline explicit BasicInput(const std::string &path)¶
Initialize with a file path.
- Parameters:
path – File path (use “-” for stdin)
-
inline const std::string &basepath() const¶
Get the base path for reading (same as path() for non-compressed files).
- Returns:
Base path
-
inline bool is_stdin() const¶
Check if this input source is stdin.
- Returns:
True if path is “-”
-
inline bool is_compressed() const¶
Check if the input source is compressed.
- Returns:
False for BasicInput (always uncompressed)
-
inline CharArray uncompress_into_buffer(size_t = 0)¶
Read whole file into memory (for compatibility with MaybeGzipped interface).
The size parameter is unused; present for interface compatibility.
- Returns:
Empty CharArray (no decompression for BasicInput)
-
inline std::unique_ptr<AnyStream> create_stream()¶
Create a stream for sequential reading.
- Returns:
Unique pointer to a FileStream
-
inline explicit BasicInput(const std::string &path)¶
-
struct FileStream : public gemmi::AnyStream¶
- #include <gemmi/input.hpp>
Stream abstraction for reading from files or stdin.
Public Functions
-
inline FileStream(std::FILE *f_)¶
Open a file stream from a FILE* pointer.
- Parameters:
f_ – Existing FILE* pointer (not closed on destruction)
-
inline FileStream(const char *path, const char *mode)¶
Open a file stream from a file path.
- Parameters:
path – File path (use “-” for stdin)
mode – File open mode (“rb”, “r”, etc.)
-
inline virtual char *gets(char *line, int size) override¶
Read a line of text from the file.
- Parameters:
line – Output buffer
size – Maximum characters to read
- Returns:
Pointer to line, or nullptr if at end of file
-
inline virtual int getc() override¶
Read a single character from the file.
- Returns:
Next character, or EOF if at end of file
-
inline virtual bool read(void *buf, size_t len) override¶
Read a block of binary data from the file.
- Parameters:
buf – Output buffer
len – Number of bytes to read
- Returns:
True if successfully read exactly len bytes
-
inline virtual std::string read_rest() override¶
Read all remaining data from current position to end of file.
- Returns:
String containing remaining data
-
inline virtual long tell() override¶
Get current file position.
- Returns:
Current byte offset in file
-
inline virtual bool skip(size_t n) override¶
Skip ahead in the file.
- Parameters:
n – Number of bytes to skip
- Returns:
True if successfully skipped
-
inline FileStream(std::FILE *f_)¶
-
struct MemoryStream : public gemmi::AnyStream¶
- #include <gemmi/input.hpp>
Stream abstraction for reading from memory buffers.
Public Functions
-
inline MemoryStream(const char *start_, size_t size)¶
Create a stream from a memory buffer.
- Parameters:
start_ – Pointer to start of buffer
size – Size of buffer in bytes
-
inline virtual char *gets(char *line, int size) override¶
Read a line of text from the buffer.
- Parameters:
line – Output buffer
size – Maximum characters to read
- Returns:
Pointer to line, or nullptr if at end of buffer
-
inline virtual int getc() override¶
Read a single character from the buffer.
- Returns:
Next character, or EOF if at end of buffer
-
inline virtual bool read(void *buf, size_t len) override¶
Read a block of binary data from the buffer.
- Parameters:
buf – Output buffer
len – Number of bytes to read
- Returns:
True if successfully read exactly len bytes
-
inline virtual std::string read_rest() override¶
Read all remaining data from current position to end of buffer.
- Returns:
String containing remaining data
-
inline virtual long tell() override¶
Get current position in the buffer.
- Returns:
Current byte offset
-
inline virtual bool skip(size_t n) override¶
Skip ahead in the buffer.
- Parameters:
n – Number of bytes to skip
- Returns:
True if skip did not exceed buffer end
-
inline MemoryStream(const char *start_, size_t size)¶
-
struct AnyStream¶
-
namespace gemmi
Functions
-
inline bool glob_match(const std::string &pattern, const std::string &str)¶
Test if string matches a glob pattern.
Match string against glob pattern with
*and?wildcards.Linear-time algorithm from https://research.swtch.com/glob
- Parameters:
pattern – glob pattern (
*matches any sequence,?matches single char)str – string to match against pattern
- Returns:
true if str matches the pattern
-
inline bool glob_match(const std::string &pattern, const std::string &str)¶
-
namespace gemmi
-
struct Logger¶
- #include <gemmi/logger.hpp>
Logger for passing messages through callbacks with severity levels.
Messages are passed as strings without a trailing newline. They have syslog-like severity levels: 8=debug, 6=info, 5=notice, 3=error, allowing the use of a threshold to filter them. Quirk: Errors double as both errors and warnings. Unrecoverable errors don’t go through this class; Logger only handles errors that can be downgraded to warnings. If a callback is set, the error is passed as a warning message. Otherwise, it’s thrown as std::runtime_error.
Public Functions
-
inline void suspend()¶
Temporarily suspend message logging.
Used internally to avoid duplicate messages when the same function is called (internally) multiple times.
-
inline void resume()¶
Resume message logging after suspension.
-
template<int N, class ...Args>
inline void level(Args const&... args) const¶ Send a message at a specific severity level.
- Template Parameters:
N – Severity level threshold for this message
- Parameters:
args – Message content to concatenate and send
-
template<class ...Args>
inline void debug(Args const&... args) const¶ Send a debug message.
- Parameters:
args – Message content
-
template<class ...Args>
inline void mesg(Args const&... args) const¶ Send an informational message without prefix.
- Parameters:
args – Message content
-
template<class ...Args>
inline void note(Args const&... args) const¶ Send a note (notice-level significant message).
- Parameters:
args – Message content
- template<class... Args> inline GEMMI_COLD void err (Args const &... args) const
Send a warning or error message.
If callback is set, sends as warning; otherwise throws exception.
- Parameters:
args – Message content
Public Members
-
std::function<void(const std::string&)> callback¶
Callback function that handles each logged message.
-
int threshold = 6¶
Severity threshold for filtering messages.
Pass messages of this level and all lower (more severe) levels: 8=all, 6=all but debug, 5=notes and warnings, 3=warnings, 0=none
Public Static Functions
-
static inline void to_stderr(const std::string &s)¶
Predefined callback function to print messages to stderr.
Use as: logger.callback = Logger::to_stderr;
- Parameters:
s – Message string (printed with newline)
-
static inline void to_stdout(const std::string &s)¶
Predefined callback function to print messages to stdout.
Use as: logger.callback = Logger::to_stdout;
- Parameters:
s – Message string (printed with newline)
-
inline void suspend()¶
-
struct Logger¶
-
namespace gemmi
Functions
-
inline bool all_alnums(const char *p)¶
Check if a string consists entirely of alphanumeric characters.
- Parameters:
p – Null-terminated string pointer
- Returns:
True if all characters are alphanumeric
-
inline bool is_pdb_code(const std::string &str)¶
Check if a string is a valid PDB code.
- Parameters:
str – Code to validate
- Returns:
True if str is a valid 4-character or extended PDB code
-
inline std::string path_in_pdb_dir(const std::string &code, char type)¶
Build a PDB_DIR-style path component for a given code and type.
- Parameters:
code – PDB code (4 characters only; extended codes not yet supported)
type – File type: ‘P’ for PDB, ‘M’ for mmCIF, ‘S’ for structure factors
- Returns:
Path component relative to $PDB_DIR (e.g., “/structures/divided/pdb/…”)
-
inline std::string expand_pdb_code_to_path(const std::string &code, char type, bool throw_if_unset = false)¶
Expand a PDB code to a full file path using $PDB_DIR.
Call this after checking the code with gemmi::is_pdb_code(code). The convention for $PDB_DIR is the same as in BioJava.
- Parameters:
code – Valid PDB code (4 or 12 characters)
type – File type: ‘P’ for PDB, ‘M’ for mmCIF, ‘S’ for structure factors
throw_if_unset – If true, fail() if $PDB_DIR is not set; if false, return empty string
- Returns:
Full file path (empty if $PDB_DIR is not set and throw_if_unset is false)
-
inline std::string expand_if_pdb_code(const std::string &input, char type = 'M')¶
Expand a PDB code to a path, or return the input unchanged if not a code.
- Parameters:
input – Either a PDB code or a file path
type – File type: ‘P’ for PDB, ‘M’ for mmCIF, ‘S’ for structure factors
- Returns:
Expanded path if input is a PDB code; input itself otherwise
-
inline bool all_alnums(const char *p)¶
-
namespace gemmi
Functions
-
inline void append_to_str(std::string &out, int v)¶
Append an integer to a string.
- Parameters:
out – Output string
v – Integer value to append
-
inline void append_to_str(std::string &out, size_t v)¶
Append an unsigned integer to a string.
- Parameters:
out – Output string
v – Size/unsigned value to append
-
template<typename T>
void append_to_str(std::string &out, const T &v)¶ Append any other type to a string (calls operator+).
- Template Parameters:
T – Type to append
- Parameters:
out – Output string
v – Value to append
-
inline void cat_to(std::string&)¶
Concatenate values into a string (base case).
- Parameters:
out – Output string
-
template<typename T, typename ...Args>
void cat_to(std::string &out, const T &value, Args const&... args)¶ Recursively concatenate values into a string.
- Template Parameters:
T – First value type
Args – Remaining value types
- Parameters:
out – Output string
value – First value to append
args – Remaining values to append recursively
-
template<class ...Args>
std::string cat(Args const&... args)¶ Concatenate variadic arguments into a new string.
- Template Parameters:
Args – Value types
- Parameters:
args – Values to concatenate
- Returns:
Concatenated string
-
inline bool starts_with(const std::string &str, const std::string &prefix)¶
Check if a string starts with a given prefix.
- Parameters:
str – String to check
prefix – Prefix to look for
- Returns:
True if str begins with prefix
-
template<size_t N>
bool starts_with(const char *a, const char (&b)[N])¶ Check if a string starts with a string literal prefix.
- Template Parameters:
N – Length of string literal
- Parameters:
a – String to check (C string)
b – String literal prefix
- Returns:
True if a starts with b
-
inline bool ends_with(const std::string &str, const std::string &suffix)¶
Check if a string ends with a given suffix.
- Parameters:
str – String to check
suffix – Suffix to look for
- Returns:
True if str ends with suffix
-
inline char lower(char c)¶
Convert a single character to lowercase (faster than std::tolower).
- Parameters:
c – Character to convert
- Returns:
Lowercase version of c, or c if not uppercase
-
inline char alpha_up(char c)¶
Convert a single character to uppercase (ASCII letters only).
- Parameters:
c – Character to convert
- Returns:
Uppercase version of c (works only for a-zA-Z)
-
inline std::string to_lower(std::string str)¶
Convert a string to lowercase.
- Parameters:
str – String to convert
- Returns:
Lowercase copy of str
-
inline std::string to_upper(std::string str)¶
Convert a string to uppercase.
- Parameters:
str – String to convert
- Returns:
Uppercase copy of str
-
inline bool isame(char a, char b)¶
Case-insensitive single character comparison.
- Parameters:
a – First character
b – Second character
- Returns:
True if characters are equal (ignoring case)
-
inline bool iequal_from(const std::string &str, size_t offset, const std::string &low)¶
Case-insensitive string equality starting at an offset.
The second argument must be lowercase for comparison.
- Parameters:
str – String to check
offset – Starting offset in str
low – Lowercase reference string
- Returns:
True if (str[offset:] == low) case-insensitively
-
inline bool iequal(const std::string &str, const std::string &low)¶
Case-insensitive string equality.
The second argument must be lowercase for comparison.
- Parameters:
str – String to check
low – Lowercase reference string
- Returns:
True if str == low (case-insensitively)
-
inline bool istarts_with(const std::string &str, const std::string &prefix)¶
Case-insensitive prefix check.
- Parameters:
str – String to check
prefix – Lowercase prefix to look for
- Returns:
True if str starts with prefix (case-insensitively)
-
inline bool iends_with(const std::string &str, const std::string &suffix)¶
Case-insensitive suffix check.
- Parameters:
str – String to check
suffix – Lowercase suffix to look for
- Returns:
True if str ends with suffix (case-insensitively)
-
inline bool giends_with(const std::string &str, const std::string &suffix)¶
Check if string ends with suffix or suffix.gz (case-insensitive).
- Parameters:
str – String to check
suffix – Lowercase suffix to look for (or suffix.gz)
- Returns:
True if str ends with suffix or suffix.gz
-
inline std::string trim_str(const std::string &str)¶
Trim whitespace from both ends of a string.
- Parameters:
str – String to trim
- Returns:
Trimmed copy of str
-
inline std::string rtrim_str(const std::string &str)¶
Trim whitespace from the right end of a string.
- Parameters:
str – String to trim
- Returns:
Right-trimmed copy of str
-
inline const char *rtrim_cstr(const char *start, const char *end = nullptr)¶
Trim whitespace from the right end of a C string.
- Parameters:
start – Pointer to start of string
end – Pointer to end of string (after last character, typically \0); nullptr to auto-detect
- Returns:
Pointer to first non-whitespace character from the right
-
template<typename S>
void split_str_into(const std::string &str, S sep, std::vector<std::string> &result)¶ Split a string by a separator into a vector (append to existing vector).
Takes a single separator (char or string); may return empty fields.
- Template Parameters:
S – Separator type (char or string)
- Parameters:
str – String to split
sep – Separator to split on
result – Vector to append results to
-
template<typename S>
std::vector<std::string> split_str(const std::string &str, S sep)¶ Split a string by a separator into a vector.
Takes a single separator (char or string); may return empty fields.
- Template Parameters:
S – Separator type (char or string)
- Parameters:
str – String to split
sep – Separator to split on
- Returns:
Vector of substrings
-
inline void split_str_into_multi(const std::string &str, const char *seps, std::vector<std::string> &result)¶
Split a string by multiple single-character separators (append to existing vector).
Discards empty fields (unlike split_str_into).
- Parameters:
str – String to split
seps – String of separator characters
result – Vector to append results to
-
inline std::vector<std::string> split_str_multi(const std::string &str, const char *seps = " \t")¶
Split a string by multiple single-character separators into a vector.
Discards empty fields (unlike split_str).
- Parameters:
str – String to split
seps – String of separator characters (default: space and tab)
- Returns:
Vector of non-empty substrings
-
template<typename T, typename S, typename F>
std::string join_str(T begin, T end, const S &sep, const F &getter)¶ Join elements from iterators with a separator.
- Template Parameters:
T – Iterator type
S – Separator type
F – Getter function type
- Parameters:
begin – Iterator to first element
end – Iterator to end (exclusive)
sep – Separator to insert between elements
getter – Function to convert each element to string
- Returns:
Joined string
-
template<typename T, typename S>
std::string join_str(T begin, T end, const S &sep)¶ Join elements from iterators with a separator.
- Template Parameters:
T – Iterator type
S – Separator type
- Parameters:
begin – Iterator to first element
end – Iterator to end (exclusive)
sep – Separator to insert between elements
- Returns:
Joined string
-
template<typename T, typename S, typename F>
std::string join_str(const T &iterable, const S &sep, const F &getter)¶ Join elements from an iterable with a separator.
- Template Parameters:
T – Iterable type
S – Separator type
F – Getter function type
- Parameters:
iterable – Container of elements
sep – Separator to insert between elements
getter – Function to convert each element to string
- Returns:
Joined string
-
template<typename T, typename S>
std::string join_str(const T &iterable, const S &sep)¶ Join elements from an iterable with a separator.
- Template Parameters:
T – Iterable type
S – Separator type
- Parameters:
iterable – Container of string elements
sep – Separator to insert between elements
- Returns:
Joined string
-
template<typename T, typename S>
void string_append_sep(std::string &str, S sep, const T &item)¶ Append an item to a string with a separator if string is non-empty.
- Template Parameters:
T – Item type
S – Separator type
- Parameters:
str – String to append to
sep – Separator to insert before item
item – Item to append
-
inline void replace_all(std::string &s, const std::string &old, const std::string &new_)¶
Replace all occurrences of a substring with another.
- Parameters:
s – String to modify in-place
old – Substring to find
new_ – Replacement substring
-
inline bool is_in_list(const std::string &name, const std::string &list, char sep = ',')¶
Check if a name appears as an item in a separated list.
- Parameters:
name – Item to search for
list – Separated list of items
sep – Separator character (default: comma)
- Returns:
True if name appears as a complete item in list
-
template<class T>
bool in_vector(const T &x, const std::vector<T> &v)¶ Check if a value exists in a vector.
- Template Parameters:
T – Vector element type
- Parameters:
x – Value to search for
v – Vector to search in
- Returns:
True if x is found in v
-
template<typename F, typename T>
bool in_vector_f(F f, const std::vector<T> &v)¶ Check if any element in a vector matches a predicate.
- Template Parameters:
F – Predicate function type
T – Vector element type
- Parameters:
f – Predicate function
v – Vector to search in
- Returns:
True if predicate matches any element
-
template<class T>
T *vector_end_ptr(std::vector<T> &v)¶ Get pointer to one-past-end of a vector (like end()).
- Template Parameters:
T – Vector element type
- Parameters:
v – Vector
- Returns:
Pointer to one-past-end (v.data() + v.size())
-
template<class T>
const T *vector_end_ptr(const std::vector<T> &v)¶ Get const pointer to one-past-end of a vector.
- Template Parameters:
T – Vector element type
- Parameters:
v – Vector
- Returns:
Const pointer to one-past-end
-
template<class T>
void vector_move_extend(std::vector<T> &dst, std::vector<T> &&src)¶ Move elements from source vector to destination vector.
- Template Parameters:
T – Vector element type
- Parameters:
dst – Destination vector
src – Source vector (moved from, will be empty)
-
template<class T, typename F>
void vector_remove_if(std::vector<T> &v, F &&condition)¶ Remove all elements matching a condition from a vector.
- Template Parameters:
T – Vector element type
F – Predicate function type
- Parameters:
v – Vector to modify in-place
condition – Predicate; elements matching return true are removed
-
template<class T>
void vector_insert_columns(std::vector<T> &data, size_t old_width, size_t length, size_t n, size_t pos, const T &new_value)¶ Insert columns into a 2D array stored as a flat vector.
- Template Parameters:
T – Array element type
- Parameters:
data – 2D array (old_width x length) stored in a flat vector
old_width – Original number of columns
length – Number of rows
n – Number of new columns to insert
pos – Column position to insert at
new_value – Value to fill new columns with
-
template<class T>
void vector_remove_column(std::vector<T> &data, size_t new_width, size_t pos)¶ Remove a column from a 2D array stored as a flat vector.
- Template Parameters:
T – Array element type
- Parameters:
data – 2D array with (new_width + 1) columns stored in a flat vector
new_width – Number of columns after removal
pos – Column position to remove
-
constexpr int ialpha4_id(const char *s)¶
Generate a case-insensitive numeric ID for 4-letter strings.
- Parameters:
s – Pointer to 4 characters (or 3 chars + NUL); space and NUL are equivalent
- Returns:
Numeric ID suitable for case-insensitive comparison
-
constexpr int ialpha3_id(const char *s)¶
Generate a case-insensitive numeric ID for 3-letter strings.
- Parameters:
s – Pointer to 3 characters
- Returns:
Numeric ID suitable for case-insensitive comparison
-
namespace impl
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
-
inline void append_to_str(std::string &out, int v)¶
Low-level Primitives¶
Span and range views, custom iterators, error utilities, fast numeric parsing, and version information.
(Full documentation added in PR 10.)
-
namespace gemmi
-
template<typename Item>
struct MutableVectorSpan : public gemmi::Span<Item>¶ - #include <gemmi/span.hpp>
Span of std::vector that supports insert() and erase() operations.
Public Types
Public Functions
-
MutableVectorSpan() = default¶
Default constructor.
-
inline MutableVectorSpan(Span<Item> &&p, vector_type *v)¶
Construct from span and vector pointer.
- Parameters:
p – source span
v – pointer to underlying vector
-
inline MutableVectorSpan(vector_type &v, iterator begin, std::size_t n)¶
Construct from vector and element range.
- Parameters:
v – the underlying vector
begin – iterator to first element in span
n – number of elements in span
-
template<typename Iter>
inline MutableVectorSpan<Item> sub(Iter first, Iter last)¶ Get a subspan from iterator range.
- Parameters:
first – iterator to first element
last – iterator to one-past-last element
- Returns:
new MutableVectorSpan covering the range
-
template<typename F>
inline MutableVectorSpan<Item> subspan(F &&func)¶ Get a mutable subspan matching a predicate.
- Parameters:
func – predicate function
- Returns:
new MutableVectorSpan of contiguous elements matching the predicate
-
template<typename F>
inline MutableVectorSpan<const Item> subspan(F &&func) const¶ Get a const subspan matching a predicate.
- Parameters:
func – predicate function
- Returns:
const MutableVectorSpan of contiguous elements matching the predicate
-
inline iterator insert(iterator pos, Item &&item)¶
Insert an element at the given position.
- Parameters:
pos – iterator position for insertion
item – element to insert (moved)
- Returns:
iterator to the newly inserted element
-
inline void erase(iterator pos)¶
Erase the element at the given position.
- Parameters:
pos – iterator to element to erase
-
inline bool is_beginning() const¶
Check if span starts at the beginning of the vector.
-
inline bool is_ending() const¶
Check if span extends to the end of the vector.
Private Members
-
vector_type *vector_ = nullptr¶
-
MutableVectorSpan() = default¶
-
template<typename Item>
struct Span¶ - #include <gemmi/span.hpp>
Minimalistic span of array or vector, similar to C++20 std::span.
Subclassed by gemmi::MutableVectorSpan< Residue >, gemmi::MutableVectorSpan< Item >
Public Types
Public Functions
-
Span() = default¶
Default constructor (empty span).
-
inline Span(iterator begin, std::size_t n)¶
Construct span from pointer and size.
- Parameters:
begin – pointer to first element
n – number of elements
-
template<typename T = Item>
inline Span(const Span<value_type> &o, typename std::enable_if<std::is_const<T>::value>::type* = 0)¶ Copy-convert constructor from mutable span to const span.
-
inline const_iterator begin() const¶
Get const iterator to beginning.
-
inline const_iterator end() const¶
Get const iterator to end.
-
inline Item &at(std::size_t i)¶
Bounds-checked element access.
- Parameters:
i – index
- Throws:
std::out_of_range – if index is out of bounds
- Returns:
reference to element at index i
-
inline const Item &at(std::size_t i) const¶
Bounds-checked element access (const).
- Parameters:
i – index
- Throws:
std::out_of_range – if index is out of bounds
- Returns:
const reference to element at index i
-
inline bool empty() const¶
Check if span is empty.
-
inline explicit operator bool() const¶
Conversion to bool (true if not empty).
-
template<typename Iter>
inline Span<Item> sub(Iter first, Iter last)¶ Get a subspan from iterator range.
- Parameters:
first – iterator to first element
last – iterator to one-past-last element
- Returns:
new Span covering the range
-
template<typename F, typename V = Item>
inline Span<V> subspan(F &&func)¶ Get a subspan matching a predicate.
- Template Parameters:
F – predicate type
V – element type (deduced)
- Parameters:
func – predicate function
- Returns:
new Span of contiguous elements matching the predicate
-
template<typename F>
inline Span<const value_type> subspan(F &&func) const¶ Get a const subspan matching a predicate.
- Template Parameters:
F – predicate type
- Parameters:
func – predicate function
- Returns:
const Span of contiguous elements matching the predicate
Public Members
- friend Span< const value_type >
- friend MutableVectorSpan< value_type >
-
Span() = default¶
-
template<typename Item>
-
namespace gemmi
Typedefs
-
template<typename Value>
using StrideIter = BidirIterator<StrideIterPolicy<Value>>¶ Bidirectional iterator that strides through elements.
-
template<typename Redirect, typename Value>
using IndirectIter = BidirIterator<IndirectIterPolicy<Redirect, Value>>¶ Bidirectional iterator that accesses elements indirectly through redirection.
-
template<typename Vector, typename Value>
using UniqIter = BidirIterator<UniqIterPolicy<Vector, Value>>¶ Bidirectional iterator that skips duplicate group keys.
-
template<typename Vector, typename Value>
using GroupingIter = BidirIterator<GroupingIterPolicy<Vector, Value>>¶ Bidirectional iterator that yields spans of elements with matching group keys.
-
template<typename Filter, typename Vector, typename Value>
using FilterIter = BidirIterator<FilterIterPolicy<Filter, Vector, Value>>¶ Bidirectional iterator that filters elements matching a predicate.
-
template<typename Policy>
struct BidirIterator : public Policy¶ - #include <gemmi/iterator.hpp>
Generic bidirectional iterator adapter implementing std::bidirectional_iterator_tag.
- Template Parameters:
Policy – the iteration policy class defining increment/decrement/dereference behavior
Public Types
-
using const_variant = BidirIterator<typename Policy::const_policy>¶
Public Functions
-
BidirIterator() = default¶
Default constructor.
-
inline BidirIterator &operator++()¶
Pre-increment operator.
-
inline BidirIterator operator++(int)¶
Post-increment operator.
-
inline BidirIterator &operator--()¶
Pre-decrement operator.
-
inline BidirIterator operator--(int)¶
Post-decrement operator.
-
inline bool operator==(const BidirIterator &o) const¶
Equality comparison.
-
inline bool operator!=(const BidirIterator &o) const¶
Inequality comparison.
-
inline operator const_variant() const¶
Conversion to const variant iterator.
-
template<typename Filter, typename Value>
struct ConstFilterProxy¶ - #include <gemmi/iterator.hpp>
Const range proxy for filtering iteration.
Public Functions
-
template<typename Value, typename Vector = std::vector<Value>>
struct ConstUniqProxy¶ - #include <gemmi/iterator.hpp>
Const range proxy for iterating with uniquification.
Public Functions
-
template<typename Filter, typename Vector, typename Value>
class FilterIterPolicy¶ - #include <gemmi/iterator.hpp>
Policy for filtering iterator that selects elements matching a predicate.
Public Types
-
using const_policy = FilterIterPolicy<Filter, Vector const, Value const>¶
Public Functions
-
inline FilterIterPolicy()¶
Default constructor.
-
inline FilterIterPolicy(const Filter *filter, Vector *vec, std::size_t pos)¶
Construct filtering iterator policy.
- Parameters:
filter – filter object with matches(const Value&) method
vec – vector to filter
pos – starting position
-
inline void increment()¶
Advance to next matching element.
-
inline void decrement()¶
Move back to previous matching element.
-
inline bool equal(const FilterIterPolicy &o) const¶
Check iterator equality.
-
inline operator const_policy() const¶
Conversion to const policy.
-
using const_policy = FilterIterPolicy<Filter, Vector const, Value const>¶
-
template<typename Filter, typename Value>
struct FilterProxy¶ - #include <gemmi/iterator.hpp>
Range proxy for filtering iteration.
Public Functions
-
template<typename Vector, typename Value>
class GroupingIterPolicy¶ - #include <gemmi/iterator.hpp>
Policy for grouping iterator that returns spans of elements with matching group keys.
Public Types
-
using const_policy = GroupingIterPolicy<Vector const, Value const>¶
Public Functions
-
GroupingIterPolicy() = default¶
Default constructor.
-
inline GroupingIterPolicy(const Value &span)¶
Construct grouping iterator policy.
- Parameters:
span – span object defining the range
-
inline void increment()¶
Advance to the next group.
-
inline void decrement()¶
Move back to the previous group.
-
inline bool equal(const GroupingIterPolicy &o) const¶
Check iterator equality.
-
inline operator const_policy() const¶
Conversion to const policy.
-
using const_policy = GroupingIterPolicy<Vector const, Value const>¶
-
template<typename Redirect, typename Value>
class IndirectIterPolicy¶ - #include <gemmi/iterator.hpp>
Policy for indirect iterator that accesses elements through redirection.
Public Types
-
using const_policy = IndirectIterPolicy<Redirect const, Value const>¶
Public Functions
-
inline IndirectIterPolicy()¶
Default constructor.
-
inline IndirectIterPolicy(Redirect *redir, std::vector<int>::const_iterator cur)¶
Construct indirect iterator policy.
- Parameters:
redir – redirection object supporting value_at(int) method
cur – iterator into position vector
-
inline void increment()¶
Advance to next position.
-
inline void decrement()¶
Move back to previous position.
-
inline bool equal(const IndirectIterPolicy &o) const¶
Check iterator equality.
-
inline operator const_policy() const¶
Conversion to const policy.
-
using const_policy = IndirectIterPolicy<Redirect const, Value const>¶
-
template<typename Item>
struct ItemGroup¶ - #include <gemmi/iterator.hpp>
A group of items with the same group_key(), possibly sparse.
Public Functions
-
inline ItemGroup(Item *start, const Item *end)¶
Construct a group from item range.
Counts contiguous items with matching group_key() to determine size.
- Parameters:
start – pointer to first item in the group
end – pointer to one-past-last item in the range
-
inline size_t size() const¶
Get number of items with matching group_key() (sparse count).
-
inline int extent() const¶
Get extent (total items in range, may include gaps).
-
inline bool empty() const¶
Check if group is empty.
-
struct iterator¶
- #include <gemmi/iterator.hpp>
Iterator for accessing sparse group items.
Public Functions
-
inline ItemGroup(Item *start, const Item *end)¶
-
template<typename Value>
class StrideIterPolicy¶ - #include <gemmi/iterator.hpp>
Policy for striding iterator that skips elements by a fixed stride.
Public Types
-
using const_policy = StrideIterPolicy<Value const>¶
Public Functions
-
inline StrideIterPolicy()¶
Default constructor.
-
inline StrideIterPolicy(Value *ptr, std::size_t offset, size_t stride)¶
Construct stride iterator policy.
- Parameters:
ptr – pointer to data
offset – offset into current element
stride – stride distance (elements per step)
-
inline void increment()¶
Advance iterator by one stride.
-
inline void decrement()¶
Move iterator back by one stride.
-
inline bool equal(const StrideIterPolicy &o) const¶
Check iterator equality.
-
inline operator const_policy() const¶
Conversion to const policy.
-
using const_policy = StrideIterPolicy<Value const>¶
-
template<typename Vector, typename Value>
class UniqIterPolicy¶ - #include <gemmi/iterator.hpp>
Policy for iterator that skips duplicate group keys.
Public Types
-
using const_policy = UniqIterPolicy<Vector const, Value const>¶
Public Functions
-
inline UniqIterPolicy()¶
Default constructor.
-
inline UniqIterPolicy(Vector *vec, std::size_t pos)¶
Construct uniquifying iterator policy.
- Parameters:
vec – vector with group_key() method on elements
pos – starting position
-
inline void increment()¶
Move to the first element of the next group.
-
inline void decrement()¶
Move back to the first element of the previous group.
-
inline bool equal(const UniqIterPolicy &o) const¶
Check iterator equality.
-
inline operator const_policy() const¶
Conversion to const policy.
-
using const_policy = UniqIterPolicy<Vector const, Value const>¶
-
template<typename Value>
-
namespace gemmi
Functions
-
inline void fail(const std::string &msg)¶
Throw a std::runtime_error with the given message.
- Parameters:
msg – error message
-
template<typename T, typename ...Args>
void fail(std::string &&str, T &&arg1, Args&&... args)¶ Variadic fail that concatenates arguments and throws std::runtime_error.
- Template Parameters:
T – type of first argument
Args – types of remaining arguments
- Parameters:
str – accumulating error message
arg1 – first argument to append
args – remaining arguments to append
- inline GEMMI_COLD void fail (const char *msg)
Throw a std::runtime_error with the given message (c-string overload).
- Parameters:
msg – error message (null-terminated C-string)
- inline GEMMI_COLD void sys_fail (const std::string &msg)
Throw a std::system_error with current errno.
The system error code is read from errno at the time of the call.
- Parameters:
msg – error message
- inline GEMMI_COLD void sys_fail (const char *msg)
Throw a std::system_error with current errno (c-string overload).
The system error code is read from errno at the time of the call.
- Parameters:
msg – error message (null-terminated C-string)
-
inline void unreachable()¶
Mark a code path as unreachable.
Calls compiler-specific unreachable builtins (e.g., __builtin_unreachable for GCC/Clang, __assume(0) for MSVC). Used to silence warnings and provide optimization hints.
-
inline void fail(const std::string &msg)¶
-
namespace gemmi
Functions
-
inline from_chars_result fast_from_chars(const char *start, const char *end, double &d)¶
Fast locale-independent string to double conversion with range.
Skips leading whitespace and optional ‘+’ sign before parsing.
- Parameters:
start – pointer to string start
end – pointer to one-past-end
d – reference to output double
- Returns:
from_chars_result with ptr field pointing to first non-converted character
-
inline from_chars_result fast_from_chars(const char *start, double &d)¶
Fast locale-independent string to double conversion (null-terminated).
Skips leading whitespace and optional ‘+’ sign before parsing.
- Parameters:
start – pointer to null-terminated string
d – reference to output double
- Returns:
from_chars_result with ptr field pointing to first non-converted character
-
inline double fast_atof(const char *p, const char **endptr = nullptr)¶
Fast locale-independent string to double conversion with optional end pointer.
- Parameters:
p – pointer to string (null-terminated)
endptr – optional pointer to receive end of parsed string (may be nullptr)
- Returns:
the parsed double value
-
inline from_chars_result fast_from_chars(const char *start, const char *end, double &d)¶
-
namespace gemmi
Functions
-
inline bool is_space(char c)¶
Locale-independent isspace equivalent (C locale only, no EOF handling).
- Parameters:
c – character to test
- Returns:
true if c is whitespace (tab, newline, vertical tab, form feed, carriage return, or space)
-
inline bool is_blank(char c)¶
Locale-independent isblank equivalent (C locale only, no EOF handling).
- Parameters:
c – character to test
- Returns:
true if c is space or tab
-
inline bool is_digit(char c)¶
Locale-independent isdigit equivalent (C locale only, no EOF handling).
- Parameters:
c – character to test
- Returns:
true if c is a decimal digit (0-9)
-
inline const char *skip_blank(const char *p)¶
Skip leading blank characters (spaces and tabs).
- Parameters:
p – pointer to string (may be null)
- Returns:
pointer to first non-blank character, or end of string
-
inline const char *skip_word(const char *p)¶
Skip word (non-whitespace characters).
- Parameters:
p – pointer to string (may be null)
- Returns:
pointer to first whitespace or null terminator
-
inline std::string read_word(const char *line)¶
Read a word from the start of a line (skipping leading blanks).
- Parameters:
line – pointer to start of line
- Returns:
string containing the word
-
inline std::string read_word(const char *line, const char **endptr)¶
Read a word from the start of a line with end pointer.
- Parameters:
line – pointer to start of line
endptr – pointer to receive pointer to character after word
- Returns:
string containing the word
-
inline int string_to_int(const char *p, bool checked, size_t length = 0)¶
Convert string to signed integer (locale-independent, no overflow checking).
- Parameters:
p – pointer to string
checked – if true, throw std::invalid_argument if string is not a valid integer
length – max length to parse (0 = unlimited)
- Throws:
std::invalid_argument – if checked=true and string is invalid
- Returns:
the converted integer
-
inline int string_to_int(const std::string &str, bool checked)¶
Convert std::string to signed integer (checked version).
- Parameters:
str – the string to convert
checked – if true, throw std::invalid_argument if string is not a valid integer
- Throws:
std::invalid_argument – if checked=true and string is invalid
- Returns:
the converted integer
-
inline int simple_atoi(const char *p, const char **endptr = nullptr)¶
Fast atoi-like conversion with optional end pointer (unchecked, allows partial parse).
- Parameters:
p – pointer to null-terminated string
endptr – optional pointer to receive pointer to first non-digit character
- Returns:
the converted integer
-
inline int no_sign_atoi(const char *p, const char **endptr = nullptr)¶
Fast atoi-like conversion without sign (positive only, unchecked).
- Parameters:
p – pointer to null-terminated string
endptr – optional pointer to receive pointer to first non-digit character
- Returns:
the converted non-negative integer
-
inline bool is_space(char c)¶
Defines
-
GEMMI_VERSION¶
Gemmi library version string.
Miscellaneous¶
Anomalous scattering addends, bond index, DSN6/BRIX map format, enum/string conversions, string formatting, statistics, and PyMOL selection language.
(Full documentation added in PR 10.)
-
namespace gemmi
-
struct Addends¶
- #include <gemmi/addends.hpp>
Container for anomalous scattering correction addends Stores addend values for each element used in density and structure factor calculations.
Public Functions
-
inline void set(Element el, float val)¶
Set the addend value for a given element.
- Parameters:
el – the chemical element
val – the addend value to set
-
inline float get(Element el) const¶
Get the addend value for a given element.
- Parameters:
el – the chemical element
- Returns:
the addend value for the element
-
inline size_t size() const¶
Get the total number of elements in the array.
- Returns:
the size of the addends array
-
inline void clear()¶
Clear all addend values to zero.
-
inline void subtract_z(bool except_hydrogen = false)¶
Subtract atomic number Z from each element’s addend value Optionally preserves hydrogen and deuterium values.
- Parameters:
except_hydrogen – if true, skip subtracting from hydrogen and deuterium
-
inline void set(Element el, float val)¶
-
struct Addends¶
-
namespace gemmi
-
struct BondIndex¶
- #include <gemmi/bond_idx.hpp>
Index for efficient bond topology queries in a crystal structure Enables checking atom connectivity and calculating graph distances, including handling of atoms in different unit cell images.
Public Functions
-
inline BondIndex(const Model &model_)¶
Construct a BondIndex for the given model.
Initializes the index with all atoms from the model. Fails if duplicate atom serial numbers are found.
- Parameters:
model_ – the crystallographic model to index
-
inline void add_oneway_link(const Atom &a, const Atom &b, bool same_image)¶
Add a unidirectional bond link between two atoms.
Does not add the reverse link (a->b without b->a). Does not add duplicate links.
- Parameters:
a – the first atom
b – the second atom
same_image – whether both atoms are in the same unit cell image
-
inline void add_link(const Atom &a, const Atom &b, bool same_image)¶
Add a bidirectional bond link between two atoms.
- Parameters:
a – the first atom
b – the second atom
same_image – whether both atoms are in the same unit cell image
-
inline void add_monomer_bonds(MonLib &monlib)¶
Add bonds from monomer library restraints to the index.
Populates the bond index with standard bonds defined for each residue type in the monomer library. Does not handle custom bond modifications; for more accurate results, use bonds from topology (Topo::bonds) which accounts for modifications.
- Parameters:
monlib – the monomer library containing bond definitions
-
inline bool are_linked(const Atom &a, const Atom &b, bool same_image) const¶
Check if two atoms are directly bonded.
- Parameters:
a – the first atom
b – the second atom
same_image – whether both atoms should be in the same unit cell image
- Returns:
true if a direct bond exists between the atoms
-
inline int graph_distance(const Atom &a, const Atom &b, bool same_image, int max_distance = 4) const¶
Calculate the minimum graph distance between two atoms.
Uses breadth-first search to find the shortest path through bonds. Automatically handles transitions between unit cell images.
- Parameters:
a – the starting atom
b – the target atom
same_image – whether both atoms should be in the same unit cell image
max_distance – maximum distance to search (default 4)
- Returns:
the graph distance in bonds, or (max_distance + 1) if no path exists
-
inline BondIndex(const Model &model_)¶
-
struct BondIndex¶
-
namespace gemmi
Functions
-
inline DataStats read_dsn6_from_memory(const char *buf, size_t size, Grid<float> &grid)¶
Read a DSN6/BRIX electron density map from memory.
Parses the DSN6/BRIX format (used for density maps) from a binary buffer and populates a grid with the density values. Automatically detects endianness from the header. Reads unit cell parameters and scales data appropriately.
- Parameters:
buf – pointer to the buffer containing DSN6 data
size – size of the buffer in bytes (must be at least 512 for header)
grid – output grid to be populated with density values
- Throws:
std::runtime_error – if format is invalid or data is truncated
- Returns:
statistics of the loaded density data (min, max, mean, rms, NaN count)
-
inline Grid<float> read_dsn6_map(const std::string &path)¶
Read a DSN6/BRIX electron density map from a file.
- Parameters:
path – file path to the DSN6/BRIX format density map
- Throws:
std::runtime_error – if file cannot be read or format is invalid
- Returns:
a Grid<float> containing the loaded density data
-
namespace impl
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
Functions
-
inline int16_t read_dsn6_i16(const char *buf, size_t buf_size, size_t index, bool little_endian)¶
-
inline int16_t read_dsn6_i16(const char *buf, size_t buf_size, size_t index, bool little_endian)¶
-
inline DataStats read_dsn6_from_memory(const char *buf, size_t size, Grid<float> &grid)¶
-
namespace gemmi
Functions
-
inline const char *entity_type_to_string(EntityType entity_type)¶
Convert EntityType enum to mmCIF string representation.
- Parameters:
entity_type – the entity type to convert
- Returns:
mmCIF string: “polymer”, “branched”, “non-polymer”, “water”, or “?”
-
inline EntityType entity_type_from_string(const std::string &t)¶
Convert mmCIF string to EntityType enum.
- Parameters:
t – the mmCIF entity type string
- Returns:
EntityType enum value; EntityType::Unknown if string is not recognized
-
inline const char *polymer_type_to_string(PolymerType polymer_type)¶
Convert PolymerType enum to mmCIF string representation.
- Parameters:
polymer_type – the polymer type to convert
- Returns:
mmCIF string representation of the polymer type
-
inline PolymerType polymer_type_from_string(const std::string &t)¶
Convert mmCIF string to PolymerType enum.
- Parameters:
t – the mmCIF polymer type string
- Returns:
PolymerType enum value; PolymerType::Unknown if string is not recognized
-
inline const char *connection_type_to_string(Connection::Type t)¶
Convert Connection::Type enum to mmCIF string representation.
- Parameters:
t – the connection type to convert
- Returns:
mmCIF string: “covale”, “disulf”, “hydrog”, “metalc”, or “.”
-
inline Connection::Type connection_type_from_string(const std::string &t)¶
Convert mmCIF string to Connection::Type enum.
- Parameters:
t – the mmCIF connection type string
- Returns:
Connection::Type enum value; Connection::Unknown if string is not recognized
-
inline std::string software_classification_to_string(SoftwareItem::Classification c)¶
Convert SoftwareItem::Classification enum to string representation.
- Parameters:
c – the software classification to convert
- Returns:
classification string such as “data collection”, “refinement”, etc.
-
inline SoftwareItem::Classification software_classification_from_string(const std::string &str)¶
Convert string to SoftwareItem::Classification enum (case-insensitive)
- Parameters:
str – the classification string to parse
- Returns:
SoftwareItem::Classification enum value; SoftwareItem::Unspecified if not recognized
-
inline const char *entity_type_to_string(EntityType entity_type)¶
Defines
-
GEMMI_ATTRIBUTE_FORMAT(fmt, va)¶
-
namespace gemmi
Functions
- int snprintf_z (char *buf, int count, char const *fmt,...) GEMMI_ATTRIBUTE_FORMAT(3
snprintf-style string formatting (locale-independent, always zero-terminated)
Uses stb_snprintf which ignores locale and guarantees zero-termination (hence the _z suffix). Signature follows snprintf.
- Parameters:
buf – output character buffer
count – maximum number of characters to write (including terminator)
fmt – printf-style format string
- Returns:
number of characters written (not including the terminator), or negative on error
- int int sprintf_z (char *buf, char const *fmt,...) GEMMI_ATTRIBUTE_FORMAT(2
sprintf-style string formatting (locale-independent, always zero-terminated)
Uses stb_sprintf which ignores locale and guarantees zero-termination. The buffer must be large enough for the formatted output.
- Parameters:
buf – output character buffer (must be large enough)
fmt – printf-style format string
- Returns:
number of characters written (not including the terminator), or negative on error
- inline int int std::string to_str (double d)
Convert a double to a string with default precision.
- Parameters:
d – the double value to convert
- Returns:
string representation using format “%.9g”
-
inline std::string to_str(float d)¶
Convert a float to a string with default precision.
- Parameters:
d – the float value to convert
- Returns:
string representation using format “%.6g”
-
template<int Prec>
std::string to_str_prec(double d)¶ Convert a double to a string with specified decimal precision.
Uses fixed-point format for values in [-1e8, 1e8), scientific notation otherwise
- Template Parameters:
Prec – decimal precision (0-6 places after decimal point)
- Parameters:
d – the double value to convert
- Returns:
string representation with fixed decimal places or scientific notation
-
inline char *to_chars_z(char *first, char *last, int value)¶
Convert an integer to a zero-terminated C-string.
Uses std::to_chars if available (C++17), otherwise snprintf_z. Guarantees zero-termination within the output range.
- Parameters:
first – pointer to start of output buffer
last – pointer to one-past-end of output buffer
value – the integer value to convert
- Returns:
pointer to the zero terminator in the output buffer
-
inline char *to_chars_z(char *first, char *last, size_t value)¶
Convert a size_t to a zero-terminated C-string.
Uses std::to_chars if available (C++17), otherwise snprintf_z. Guarantees zero-termination within the output range.
- Parameters:
first – pointer to start of output buffer
last – pointer to one-past-end of output buffer
value – the size_t value to convert
- Returns:
pointer to the zero terminator in the output buffer
-
namespace gemmi
Functions
-
inline Correlation combine_two_correlations(const Correlation &a, const Correlation &b)¶
Combine two independent Correlation objects into one.
Merges statistics from two separate correlation calculations to produce a combined result as if all data had been processed together.
- Parameters:
a – the first Correlation object
b – the second Correlation object
- Returns:
a new Correlation object with combined statistics
-
inline Correlation combine_correlations(const std::vector<Correlation> &cors)¶
Combine multiple Correlation objects into a single result.
- Parameters:
cors – vector of Correlation objects to combine
- Returns:
a new Correlation object with combined statistics from all input correlations
-
template<typename T>
DataStats calculate_data_statistics(const std::vector<T> &data)¶ Calculate statistical summary of a dataset.
Computes min, max, mean, RMS, and counts NaN values. For all-NaN inputs, min and max are set to NaN.
- Template Parameters:
T – numeric type of the data container
- Parameters:
data – vector of numeric values
- Returns:
DataStats object containing the calculated statistics
-
struct Correlation¶
- #include <gemmi/stats.hpp>
Correlation coefficient and regression statistics for paired data.
Accumulates running statistics for two variables to compute correlation coefficient, regression line (slope/intercept), and variances.
Public Functions
-
inline void add_point(double x, double y)¶
Add a paired data point (x, y) and update running statistics.
- Parameters:
x – the x data value
y – the y data value
-
inline double coefficient() const¶
Calculate Pearson correlation coefficient.
- Returns:
correlation coefficient (ranges from -1 to 1)
-
inline double x_variance() const¶
Calculate variance of x values.
- Returns:
x variance
-
inline double y_variance() const¶
Calculate variance of y values.
- Returns:
y variance
-
inline double covariance() const¶
Calculate covariance between x and y.
- Returns:
covariance
-
inline double mean_ratio() const¶
Calculate ratio of means (mean_y / mean_x)
- Returns:
ratio of means
-
inline double slope() const¶
Calculate slope of linear regression line (y = slope * x + intercept)
- Returns:
regression slope
-
inline double intercept() const¶
Calculate y-intercept of linear regression line.
- Returns:
regression intercept (y-value where x=0)
Public Members
-
int n = 0¶
Number of point pairs added.
-
double sum_xx = 0.¶
Sum of weighted squared x deviations.
-
double sum_yy = 0.¶
Sum of weighted squared y deviations.
-
double sum_xy = 0.¶
Sum of weighted xy deviations.
-
double mean_x = 0.¶
Running mean of x values.
-
double mean_y = 0.¶
Running mean of y values.
-
inline void add_point(double x, double y)¶
-
struct Covariance : public gemmi::Variance¶
- #include <gemmi/stats.hpp>
Covariance of two variables using single-pass algorithm.
Extends Variance to track covariance between paired (x, y) points.
Public Functions
-
inline void add_point(double x, double y)¶
Add a paired data point (x, y) and update running statistics.
- Parameters:
x – the x data value
y – the y data value
Public Members
-
double mean_y = 0.¶
Running mean of y values.
-
inline void add_point(double x, double y)¶
-
struct DataStats¶
- #include <gemmi/stats.hpp>
Statistics describing a dataset (min, max, mean, RMS, NaN count)
-
struct Variance¶
- #include <gemmi/stats.hpp>
Single-pass algorithm for calculating variance and mean.
Uses Welford’s algorithm for numerical stability. Supports both initialization from iterators and incremental point addition.
Subclassed by gemmi::Covariance
Public Functions
-
Variance() = default¶
-
template<typename T>
inline Variance(T begin, T end)¶ Construct Variance from an iterator range.
- Template Parameters:
T – iterator type
- Parameters:
begin – iterator to first element
end – iterator to one-past-last element
-
inline void add_point(double x)¶
Add a single data point and update running statistics.
- Parameters:
x – the data value to add
-
inline double for_sample() const¶
Calculate sample variance (divide by n-1)
- Returns:
sample variance
-
inline double for_population() const¶
Calculate population variance (divide by n)
- Returns:
population variance
-
Variance() = default¶
-
inline Correlation combine_two_correlations(const Correlation &a, const Correlation &b)¶
-
namespace std
-
namespace gemmi
Functions
-
inline std::unique_ptr<psimpl::Node> compile_pymol_selection(const std::string &selector)¶
Compile a PyMOL selection string into an abstract syntax tree.
The returned tree can be used to test atoms with the match() method. If parsing fails, an error message is printed to stderr.
- Parameters:
selector – PyMOL selection syntax string (e.g., “name CA and chain A”)
- Returns:
A unique pointer to the root Node of the compiled selection tree, or nullptr if parsing fails
-
inline std::vector<const gemmi::FlatAtom*> select_atoms(const gemmi::FlatStructure &fs, const std::string &query)¶
Select atoms from a FlatStructure matching a PyMOL selection query.
Compiles the query string into an AST and tests each atom in the structure. Returns empty vector if the query is invalid or matches no atoms.
- Parameters:
fs – The structure containing atoms to select from
query – PyMOL selection syntax string
- Returns:
Vector of const pointers to atoms matching the selection
-
inline void remove_not_selected(gemmi::FlatStructure &fs, const std::string &query)¶
Remove atoms from a FlatStructure that do not match a PyMOL selection.
Keeps only atoms matching the query; removes all others. If the query is invalid, no atoms are removed.
- Parameters:
fs – The structure to filter (modified in-place)
query – PyMOL selection syntax string
-
namespace psimpl¶
Typedefs
-
using ChainNode = GlobMatchNode<&gemmi::FlatAtom::chain_id>¶
-
using ResnNode = GlobMatchNode<&gemmi::FlatAtom::residue_name>¶
-
using AtomNameNode = GlobMatchNode<&gemmi::FlatAtom::atom_name>¶
Enums
-
template<typename Rule>
struct action : public tao::pegtl::nothing<Rule>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<rule_backbone>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<rule_chain>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<rule_hetatm>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<rule_hydrogens>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<rule_polymer>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<rule_sidechain>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<rule_solvent>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<rule_water>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<val_b_compare>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<val_chain_item>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<val_elem_item>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<val_index_range>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<val_index_single>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<val_name_item>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<val_q_compare>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<val_resi_range>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<val_resi_single>¶ - #include <gemmi/pymol_select.hpp>
-
template<>
struct action<val_resn_item>¶ - #include <gemmi/pymol_select.hpp>
-
struct AltLocNode : public gemmi::psimpl::Node¶
- #include <gemmi/pymol_select.hpp>
Public Functions
-
inline explicit AltLocNode(char c)¶
Public Members
-
char alt¶
-
inline explicit AltLocNode(char c)¶
-
struct atom_name_str : public tao::pegtl::plus<p::sor<p::alnum, wildcard_char>>¶
- #include <gemmi/pymol_select.hpp>
Subclassed by gemmi::psimpl::val_name_item, gemmi::psimpl::val_resn_item
-
struct compare_op : public tao::pegtl::sor<op_le, op_ge, op_ne, op_lt, op_gt, op_eq>¶
- #include <gemmi/pymol_select.hpp>
-
struct element_str : public tao::pegtl::seq<p::upper, p::opt<p::lower>>¶
- #include <gemmi/pymol_select.hpp>
Subclassed by gemmi::psimpl::val_elem_item
-
struct EntityTypeNode : public gemmi::psimpl::Node¶
- #include <gemmi/pymol_select.hpp>
Public Functions
-
inline explicit EntityTypeNode(EntityType e)¶
Public Members
-
EntityType etype¶
-
inline explicit EntityTypeNode(EntityType e)¶
-
struct expression : public tao::pegtl::seq<term, p::star<or_rest>>¶
- #include <gemmi/pymol_select.hpp>
-
struct factor : public tao::pegtl::sor<rule_not, parens, property>¶
- #include <gemmi/pymol_select.hpp>
-
struct float_num : public tao::pegtl::seq<p::opt<p::one<'-'>>, p::plus<p::digit>, p::opt<p::seq<p::one<'.'>, p::star<p::digit>>>>¶
- #include <gemmi/pymol_select.hpp>
Subclassed by gemmi::psimpl::val_b_compare, gemmi::psimpl::val_q_compare
-
template<char (gemmi::FlatAtom::* Field)>
struct GlobMatchNode : public gemmi::psimpl::Node¶ - #include <gemmi/pymol_select.hpp>
Public Functions
-
struct grammar : public tao::pegtl::must<ws, expression, ws, p::eof>¶
- #include <gemmi/pymol_select.hpp>
-
struct HetatmNode : public gemmi::psimpl::Node¶
- #include <gemmi/pymol_select.hpp>
Public Functions
-
inline explicit HetatmNode(bool h)¶
Public Members
-
bool hetatm¶
-
inline explicit HetatmNode(bool h)¶
-
struct identifier : public tao::pegtl::plus<p::sor<p::alnum, p::one<'_'>, wildcard_char>>¶
- #include <gemmi/pymol_select.hpp>
Subclassed by gemmi::psimpl::val_chain_item
-
struct IndexRangeNode : public gemmi::psimpl::Node¶
- #include <gemmi/pymol_select.hpp>
Public Functions
-
inline IndexRangeNode(int a, int b)¶
-
inline IndexRangeNode(int a, int b)¶
-
struct integer : public tao::pegtl::seq<p::opt<p::one<'-'>>, p::plus<p::digit>>¶
- #include <gemmi/pymol_select.hpp>
Subclassed by gemmi::psimpl::val_index_single, gemmi::psimpl::val_resi_single
-
struct kw_all : public tao::pegtl::istring<'a', 'l', 'l'>¶
- #include <gemmi/pymol_select.hpp>
Subclassed by gemmi::psimpl::rule_all
-
struct kw_alt : public tao::pegtl::istring<'a', 'l', 't'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_and : public tao::pegtl::istring<'a', 'n', 'd'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_b : public tao::pegtl::istring<'b'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_backbone : public tao::pegtl::istring<'b', 'a', 'c', 'k', 'b', 'o', 'n', 'e'>¶
- #include <gemmi/pymol_select.hpp>
Subclassed by gemmi::psimpl::rule_backbone
-
struct kw_chain : public tao::pegtl::istring<'c', 'h', 'a', 'i', 'n'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_elem : public tao::pegtl::istring<'e', 'l', 'e', 'm'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_h_dot : public tao::pegtl::istring<'h', '.'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_hetatm : public tao::pegtl::istring<'h', 'e', 't', 'a', 't', 'm'>¶
- #include <gemmi/pymol_select.hpp>
Subclassed by gemmi::psimpl::rule_hetatm
-
struct kw_hydrogens : public tao::pegtl::istring<'h', 'y', 'd', 'r', 'o', 'g', 'e', 'n', 's'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_id : public tao::pegtl::istring<'i', 'd'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_index : public tao::pegtl::istring<'i', 'n', 'd', 'e', 'x'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_name : public tao::pegtl::istring<'n', 'a', 'm', 'e'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_not : public tao::pegtl::istring<'n', 'o', 't'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_or : public tao::pegtl::istring<'o', 'r'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_polymer : public tao::pegtl::istring<'p', 'o', 'l', 'y', 'm', 'e', 'r'>¶
- #include <gemmi/pymol_select.hpp>
Subclassed by gemmi::psimpl::rule_polymer
-
struct kw_q : public tao::pegtl::istring<'q'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_resi : public tao::pegtl::istring<'r', 'e', 's', 'i'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_resn : public tao::pegtl::istring<'r', 'e', 's', 'n'>¶
- #include <gemmi/pymol_select.hpp>
-
struct kw_sidechain : public tao::pegtl::istring<'s', 'i', 'd', 'e', 'c', 'h', 'a', 'i', 'n'>¶
- #include <gemmi/pymol_select.hpp>
Subclassed by gemmi::psimpl::rule_sidechain
-
struct kw_solvent : public tao::pegtl::istring<'s', 'o', 'l', 'v', 'e', 'n', 't'>¶
- #include <gemmi/pymol_select.hpp>
Subclassed by gemmi::psimpl::rule_solvent
-
struct kw_water : public tao::pegtl::istring<'w', 'a', 't', 'e', 'r'>¶
- #include <gemmi/pymol_select.hpp>
Subclassed by gemmi::psimpl::rule_water
-
struct Node¶
- #include <gemmi/pymol_select.hpp>
Base class for abstract syntax tree nodes in PyMOL selection expressions. All selector nodes inherit from this base and implement atom matching logic.
Subclassed by gemmi::psimpl::AllNode, gemmi::psimpl::AltLocNode, gemmi::psimpl::AndNode, gemmi::psimpl::BackboneNode, gemmi::psimpl::BfactorNode, gemmi::psimpl::ElementNode, gemmi::psimpl::EntityTypeNode, gemmi::psimpl::GlobMatchNode< Field >, gemmi::psimpl::HetatmNode, gemmi::psimpl::HydrogenNode, gemmi::psimpl::IndexRangeNode, gemmi::psimpl::NotNode, gemmi::psimpl::OccupancyNode, gemmi::psimpl::OrNode, gemmi::psimpl::ResiRangeNode, gemmi::psimpl::SidechainNode
-
struct not_factor : public tao::pegtl::seq<kw_not, sep, p::seq<expression>>¶
- #include <gemmi/pymol_select.hpp>
-
struct OccupancyNode : public gemmi::psimpl::Node¶
- #include <gemmi/pymol_select.hpp>
Public Functions
-
struct op_eq : public tao::pegtl::one<'='>¶
- #include <gemmi/pymol_select.hpp>
-
struct op_ge : public tao::pegtl::string<'>', '='>¶
- #include <gemmi/pymol_select.hpp>
-
struct op_gt : public tao::pegtl::one<'>'>¶
- #include <gemmi/pymol_select.hpp>
-
struct op_le : public tao::pegtl::string<'<', '='>¶
- #include <gemmi/pymol_select.hpp>
-
struct op_lt : public tao::pegtl::one<'<'>¶
- #include <gemmi/pymol_select.hpp>
-
struct op_ne : public tao::pegtl::sor<p::string<'!', '='>, p::string<'<', '>'>>¶
- #include <gemmi/pymol_select.hpp>
-
struct parens : public tao::pegtl::seq<p::one<'('>, ws, expression, ws, p::one<')'>>¶
- #include <gemmi/pymol_select.hpp>
-
struct property : public tao::pegtl::sor<rule_chain, rule_resn, rule_resi, rule_index, rule_name, rule_alt, rule_elem, rule_b, rule_q, rule_hetatm, rule_polymer, rule_solvent, rule_water, rule_hydrogens, rule_backbone, rule_sidechain, rule_all>¶
- #include <gemmi/pymol_select.hpp>
-
struct ResiRangeNode : public gemmi::psimpl::Node¶
- #include <gemmi/pymol_select.hpp>
Public Functions
-
inline ResiRangeNode(int a, int b)¶
-
inline ResiRangeNode(int a, int b)¶
-
struct rule_b : public tao::pegtl::seq<kw_b, ws, compare_op, ws, val_b_compare>¶
- #include <gemmi/pymol_select.hpp>
-
struct rule_backbone : public gemmi::psimpl::kw_backbone¶
- #include <gemmi/pymol_select.hpp>
-
struct rule_chain : public tao::pegtl::seq<kw_chain, sep, val_chain_list>¶
- #include <gemmi/pymol_select.hpp>
-
struct rule_elem : public tao::pegtl::seq<kw_elem, sep, val_elem_list>¶
- #include <gemmi/pymol_select.hpp>
-
struct rule_hydrogens : public tao::pegtl::sor<kw_hydrogens, kw_h_dot>¶
- #include <gemmi/pymol_select.hpp>
-
struct rule_index : public tao::pegtl::seq<p::sor<kw_index, kw_id>, sep, p::sor<val_index_range, val_index_single>>¶
- #include <gemmi/pymol_select.hpp>
-
struct rule_name : public tao::pegtl::seq<kw_name, sep, val_name_list>¶
- #include <gemmi/pymol_select.hpp>
-
struct rule_polymer : public gemmi::psimpl::kw_polymer¶
- #include <gemmi/pymol_select.hpp>
-
struct rule_q : public tao::pegtl::seq<kw_q, ws, compare_op, ws, val_q_compare>¶
- #include <gemmi/pymol_select.hpp>
-
struct rule_resi : public tao::pegtl::seq<kw_resi, sep, p::sor<val_resi_range, val_resi_single>>¶
- #include <gemmi/pymol_select.hpp>
-
struct rule_resn : public tao::pegtl::seq<kw_resn, sep, val_resn_list>¶
- #include <gemmi/pymol_select.hpp>
-
struct rule_sidechain : public gemmi::psimpl::kw_sidechain¶
- #include <gemmi/pymol_select.hpp>
-
struct rule_solvent : public gemmi::psimpl::kw_solvent¶
- #include <gemmi/pymol_select.hpp>
-
struct sep : public tao::pegtl::plus<p::space>¶
- #include <gemmi/pymol_select.hpp>
-
struct State¶
- #include <gemmi/pymol_select.hpp>
-
struct val_alt : public tao::pegtl::alnum¶
- #include <gemmi/pymol_select.hpp>
-
struct val_chain_item : public gemmi::psimpl::identifier¶
- #include <gemmi/pymol_select.hpp>
-
struct val_chain_list : public tao::pegtl::list<val_chain_item, p::one<'+'>>¶
- #include <gemmi/pymol_select.hpp>
-
struct val_elem_item : public gemmi::psimpl::element_str¶
- #include <gemmi/pymol_select.hpp>
-
struct val_elem_list : public tao::pegtl::list<val_elem_item, p::one<'+'>>¶
- #include <gemmi/pymol_select.hpp>
-
struct val_index_range : public tao::pegtl::seq<integer, p::one<'-'>, integer>¶
- #include <gemmi/pymol_select.hpp>
-
struct val_name_item : public gemmi::psimpl::atom_name_str¶
- #include <gemmi/pymol_select.hpp>
-
struct val_name_list : public tao::pegtl::list<val_name_item, p::one<'+'>>¶
- #include <gemmi/pymol_select.hpp>
-
struct val_resi_range : public tao::pegtl::seq<integer, p::one<'-'>, integer>¶
- #include <gemmi/pymol_select.hpp>
-
struct val_resn_item : public gemmi::psimpl::atom_name_str¶
- #include <gemmi/pymol_select.hpp>
-
struct val_resn_list : public tao::pegtl::list<val_resn_item, p::one<'+'>>¶
- #include <gemmi/pymol_select.hpp>
- wildcard_char : public tao::pegtl::one<' *', '?'>
- #include <gemmi/pymol_select.hpp>
-
struct ws : public tao::pegtl::star<p::space>¶
- #include <gemmi/pymol_select.hpp>
-
using ChainNode = GlobMatchNode<&gemmi::FlatAtom::chain_id>¶
-
inline std::unique_ptr<psimpl::Node> compile_pymol_selection(const std::string &selector)¶
Scattering, Math, and Geometry¶
Form factor tables, anomalous scattering, Bessel function helpers, core linear-algebra primitives, unit-cell reduction, and numerical tools used throughout structure-factor and density calculations.
(Full documentation added in PR 9.)
-
namespace gemmi
Functions
-
void cromer_liberman_for_array(int z, int npts, const double *energy, double *fp, double *fpp)¶
Cromer-Liberman calculation of anomalous scattering factors for an array of energies, with Kissel-Pratt corrections.
Kissel, L. & Pratt, R.H. (1990). Rayleigh scattering — elastic photon scattering by bound electrons: status and perspectives. Acta Cryst. A46, 170–175. https://doi.org/10.1107/S0108767389010718
- References
Cromer, D.T. & Liberman, D.A. (1994). Anomalous dispersion calculations near to and on the long-wavelength side of an absorption edge. Acta Cryst. A51, 416. https://doi.org/10.1107/S0108767394013292
Brennan, S. & Cowan, P.L. (1992). A suite of programs for calculating x-ray absorption, reflection, and diffraction performance. Rev. Sci. Instrum. 63, 850. https://doi.org/10.1063/1.1142625
- Parameters:
z – atomic number
npts – array length
energy – energies in eV
fp – output: f’ (real part of anomalous scattering)
fpp – output: f” (imaginary part of anomalous scattering)
-
inline double cromer_liberman(int z, double energy, double *fpp)¶
Single-energy wrapper for cromer_liberman_for_array.
- Parameters:
z – atomic number
energy – energy in eV
fpp – output: may be nullptr (optional f” value)
- Returns:
f’ value
-
void cromer_liberman_for_array(int z, int npts, const double *energy, double *fp, double *fpp)¶
-
namespace gemmi
Functions
-
inline float unsafe_expapprox(float x)¶
Fast approximate exp for float; relative error < 1e-5.
Note
Input must be in [-88, 88].
- Parameters:
x – exponent value
- Returns:
approximate exp(x)
-
template<int N, typename Real>
struct ExpAnisoSum¶ - #include <gemmi/formfact.hpp>
Precalculated anisotropic density as sum of N Gaussians. Amplitude and tensor coefficients are stored for fast evaluation.
Public Functions
-
template<int N>
struct ExpAnisoSum<N, float>¶ - #include <gemmi/formfact.hpp>
Float specialisation of ExpAnisoSum using unsafe_expapprox for speed.
Public Functions
-
template<int N, typename Real>
struct ExpSum¶ - #include <gemmi/formfact.hpp>
Precalculated isotropic density as sum of N Gaussians in r². Amplitude and exponent coefficients are stored for fast evaluation.
-
template<int N>
struct ExpSum<N, float>¶ - #include <gemmi/formfact.hpp>
Float specialisation of ExpSum using unsafe_expapprox for speed.
Public Functions
-
inline float calculate(float r2) const¶
Calculate density at squared distance.
- Parameters:
r2 – squared distance
- Returns:
density at r²
-
inline float calculate(float r2) const¶
-
template<int N, int WithC, typename Real>
struct GaussianCoef¶ - #include <gemmi/formfact.hpp>
Gaussian approximation coefficients for atomic scattering. N Gaussians plus optional constant term for efficient computation.
Public Functions
-
inline Real calculate_sf(Real stol2) const¶
Calculate structure factor at specified reciprocal resolution.
- Parameters:
stol2 – (sinθ/λ)²
- Returns:
structure factor
-
inline Real calculate_density_iso(Real r2, Real B) const¶
Calculate isotropic density at given distance and B-factor.
- Parameters:
r2 – squared distance
B – isotropic B-factor (Ų)
- Returns:
density
-
inline ExpSum<N + WithC, Real> precalculate_density_iso(Real B, Real addend = 0) const¶
Precalculate coefficients for fast isotropic density evaluation.
- Parameters:
B – isotropic B-factor (Ų)
addend – added to constant term if WithC=1 (e.g., dispersion f’)
- Returns:
ExpSum ready for fast density calculation
-
inline Real calculate_density_aniso(const Vec3 &r, const SMat33<float> &U) const¶
Calculate anisotropic density at given position and U-tensor.
- Parameters:
r – position vector
U – anisotropic displacement tensor
- Returns:
density
-
inline ExpAnisoSum<N + WithC, Real> precalculate_density_aniso_b(const SMat33<Real> &B, Real addend = 0) const¶
Precalculate coefficients for fast anisotropic density evaluation with B-tensor.
- Parameters:
B – anisotropic B-factor matrix
addend – added to constant term if WithC=1
- Returns:
ExpAnisoSum ready for fast density calculation
-
inline ExpAnisoSum<N + WithC, Real> precalculate_density_aniso_u(const SMat33<float> &U, Real addend = 0) const¶
Precalculate coefficients for fast anisotropic density evaluation with U-tensor.
- Parameters:
U – anisotropic displacement tensor
addend – added to constant term if WithC=1
- Returns:
ExpAnisoSum ready for fast density calculation
Public Members
-
inline Real calculate_sf(Real stol2) const¶
-
inline float unsafe_expapprox(float x)¶
-
namespace gemmi
-
template<class Real>
struct IT92¶ - #include <gemmi/it92.hpp>
X-ray scattering factor coefficients from International Tables for Crystallography Volume C (1992). Cromer-Mann Gaussian approximation valid for sinθ/λ < 2 Å⁻¹.
- Template Parameters:
Real – floating-point type
Public Types
-
using Coef = GaussianCoef<4, 1, Real>¶
Type alias for coefficient set.
Public Static Functions
-
static inline bool has(El el)¶
Check if coefficients are available for element.
- Parameters:
el – element
- Returns:
true if element has tabulated coefficients
-
static inline Coef &get(El el, signed char charge, int = 0)¶
Get coefficient set for element and charge, with fallback to neutral.
- Parameters:
el – element
charge – ionic charge
- Returns:
coefficient reference
-
static inline Coef *get_exact(El el, signed char charge)¶
Get pointer to exact match for element and charge, or nullptr if not found.
- Parameters:
el – element
charge – ionic charge
- Returns:
pointer to coefficient, or nullptr
-
static inline void normalize_one(Coef &f, int n)¶
Normalise one coefficient set so it integrates to n electrons.
- Parameters:
f – coefficient to normalise
n – electron count
-
static inline void normalize()¶
Normalise all entries to integrate to correct electron count.
-
template<class Real>
-
namespace gemmi
-
template<class Real>
struct C4322¶ - #include <gemmi/c4322.hpp>
Electron scattering factor coefficients from ITC Volume C (2011) table 4.3.2.2. Five-Gaussian approximation for neutral atoms, valid for sinθ/λ ≤ 2 Å⁻¹.
- Template Parameters:
Real – floating-point type
Public Types
-
using Coef = GaussianCoef<5, 0, Real>¶
Type alias for coefficient set.
-
template<class Real>
struct CustomCoef¶ - #include <gemmi/c4322.hpp>
Public Types
-
using Coef = GaussianCoef<5, 0, Real>¶
-
using Coef = GaussianCoef<5, 0, Real>¶
-
template<class Real>
-
namespace gemmi
-
template<class Real>
struct Neutron92¶ - #include <gemmi/neutron92.hpp>
Neutron coherent scattering lengths from Neutron News 3(3) 1992.
Real part of the bound coherent scattering length in femtometers (fm). Data matches cctbx/eltbx/neutron.h and the NIST neutron scattering lengths table.
- References
Sears, V.F. (1992). Neutron scattering lengths and cross sections. Neutron News 3(3), 26–37. https://doi.org/10.1080/10448639208218770
- Template Parameters:
Real – floating-point type
Public Types
-
using Coef = GaussianCoef<0, 1, Real>¶
-
template<class Real>
struct ZeroCoef¶ - #include <gemmi/neutron92.hpp>
Placeholder scattering type where scattering is a single real constant (zero Gaussians plus one constant term). Used for neutron coherent scattering.
Public Types
-
using Coef = GaussianCoef<0, 1, Real>¶
-
using Coef = GaussianCoef<0, 1, Real>¶
-
template<class Real>
-
namespace gemmi
Functions
-
template<int N>
inline double evaluate_polynomial(const double (&poly)[N], double x)¶ Evaluate degree-(N-1) polynomial by Horner’s method.
- Template Parameters:
N – number of coefficients
- Parameters:
poly – coefficient array; poly[0] is the constant term
x – evaluation point
- Returns:
polynomial value at x
-
inline double bessel_i1_over_i0(double x)¶
Compute I₁(x)/I₀(x) using polynomial approximations.
Used in maximum-likelihood refinement of diffraction data
- Parameters:
x – argument
- Returns:
I₁(x)/I₀(x)
-
inline double bessel_i0(double x)¶
Compute modified Bessel function I₀(x)
Simplified from Boost.Math; relative error < 5.02e-08. Similar to std::cyl_bessel_i(0, x) but faster. Does not throw on negative argument.
- Parameters:
x – argument
- Returns:
I₀(x)
-
inline double log_bessel_i0(double x)¶
Compute ln(I₀(x))
Numerically stable computation via log1p for small x; relative error < 4e-08. Avoids overflow for large x.
- Parameters:
x – argument
- Returns:
ln(I₀(x))
-
template<class Dummy>
struct BesselTables_¶ - #include <gemmi/bessel.hpp>
Polynomial coefficient tables for Bessel function approximations.
Wrapped in a template to enable header-only inline variables
Public Static Attributes
-
static const double P1[8] = {8.333333221e-02, 6.944453712e-03, 3.472097211e-04, 1.158047174e-05, 2.739745142e-07, 5.135884609e-09, 5.262251502e-11, 1.331933703e-12}¶
Polynomial coefficients for I0 approximation, small x.
-
static const double Q1[9] = {1.00000003928615375e+00, 2.49999576572179639e-01, 2.77785268558399407e-02, 1.73560257755821695e-03, 6.96166518788906424e-05, 1.89645733877137904e-06, 4.29455004657565361e-08, 3.90565476357034480e-10, 1.48095934745267240e-11}¶
Polynomial coefficients for I0 approximation, small x.
-
static const double P2[5] = {3.98942115977513013e-01, -1.49581264836620262e-01, -4.76475741878486795e-02, -2.65157315524784407e-02, -1.47148600683672014e-01}¶
Polynomial coefficients for I0 approximation, large x.
-
static const double Q2[5] = {3.98942651588301770e-01, 4.98327234176892844e-02, 2.91866904423115499e-02, 1.35614940793742178e-02, 1.31409251787866793e-01}¶
Polynomial coefficients for I0 approximation, large x (x < 50)
-
static const double Q3[3] = {3.98942391532752700e-01, 4.98455950638200020e-02, 2.94835666900682535e-02}¶
Polynomial coefficients for I0 approximation, very large x (x >= 50)
-
static const double P1[8] = {8.333333221e-02, 6.944453712e-03, 3.472097211e-04, 1.158047174e-05, 2.739745142e-07, 5.135884609e-09, 5.262251502e-11, 1.331933703e-12}¶
-
template<int N>
-
namespace gemmi
Typedefs
Functions
-
constexpr double pi()¶
Return π to double precision.
- Returns:
pi
-
constexpr double hc()¶
Planck constant × speed of light in eV·Å
The value used in converting between energy[eV] and wavelength[Angstrom].
- Returns:
hc constant
-
constexpr double bohrradius()¶
Bohr radius a₀ in Angstroms.
- Returns:
Bohr radius
-
constexpr double mott_bethe_const()¶
Mott-Bethe constant: 1/(2π²a₀) used in electron scattering factor.
Constant used in Mott-Bethe electron scattering factor calculations
- Returns:
Mott-Bethe constant
-
constexpr double u_to_b()¶
Factor converting U_iso (Ų) to B-factor: 8π²
Used in conversion of ADPs (atomic displacement parameters)
- Returns:
conversion factor
-
constexpr double deg(double angle)¶
Convert radians to degrees.
- Parameters:
angle – angle in radians
- Returns:
angle in degrees
-
constexpr double rad(double angle)¶
Convert degrees to radians.
- Parameters:
angle – angle in degrees
- Returns:
angle in radians
-
constexpr float sq(float x)¶
Compute x²
- Parameters:
x – value (float)
- Returns:
x²
-
constexpr double sq(double x)¶
Compute x²
- Parameters:
x – value (double)
- Returns:
x²
-
inline double log_cosh(double x)¶
Compute ln(cosh(x)) stably.
Avoids overflow for large x; cosh(x) would overflow for x > 710.5
- Parameters:
x – argument
- Returns:
ln(cosh(x))
-
inline int iround(double d)¶
Round double to nearest int.
- Parameters:
d – value to round
- Returns:
rounded integer
-
inline double angle_abs_diff(double a, double b, double full = 360.0)¶
Absolute angular difference.
Computes absolute difference modulo full range, in range [0, full/2]
- Parameters:
a – first angle
b – second angle
full – full angular range (default 360.0)
- Returns:
absolute difference
-
template<class T>
constexpr T clamp(T v, T lo, T hi)¶ Clamp value to range [lo, hi].
Similar to C++17 std::clamp()
- Template Parameters:
T – scalar type
- Parameters:
v – value to clamp
lo – lower bound
hi – upper bound
- Returns:
clamped value
-
inline Vec3 operator*(double d, const Vec3 &v)¶
Scalar multiplication (scalar * vector)
- Parameters:
d – scalar
v – vector
- Returns:
scaled vector
-
inline Vec3 rotate_about_axis(const Vec3 &v, const Vec3 &axis, double theta)¶
Rotate vector about an axis using Rodrigues’ rotation formula.
Rotate vector v about given axis (which must be a unit vector) by angle theta
- Parameters:
v – vector to rotate
axis – unit vector (axis of rotation)
theta – angle in radians
- Returns:
rotated vector
-
template<typename Pos>
struct Box¶ - #include <gemmi/math.hpp>
Axis-aligned bounding box.
- Template Parameters:
Pos – position type (e.g., Vec3)
-
struct Mat33¶
- #include <gemmi/math.hpp>
3×3 matrix of doubles
Row-major storage
Public Types
-
typedef double row_t[3]¶
Public Functions
-
Mat33() = default¶
Default constructor (identity matrix)
-
inline explicit Mat33(double d)¶
Fill constructor.
- Parameters:
d – value to fill the matrix
-
inline Mat33(double a1, double a2, double a3, double b1, double b2, double b3, double c1, double c2, double c3)¶
Element constructor (row-major)
- Parameters:
a1 – first row, column 0
a2 – first row, column 1
a3 – first row, column 2
b1 – second row, column 0
b2 – second row, column 1
b3 – second row, column 2
c1 – third row, column 0
c2 – third row, column 1
c3 – third row, column 2
-
inline Vec3 row_copy(int i) const¶
Get row as a vector.
- Parameters:
i – row index (0, 1, or 2)
- Throws:
std::out_of_range – if i not in 0..2
- Returns:
row vector
-
inline Vec3 column_copy(int i) const¶
Get column as a vector.
- Parameters:
i – column index (0, 1, or 2)
- Throws:
std::out_of_range – if i not in 0..2
- Returns:
column vector
-
inline Mat33 operator+(const Mat33 &b) const¶
Matrix addition.
- Parameters:
b – other matrix
- Returns:
this + b
-
inline Mat33 operator-(const Mat33 &b) const¶
Matrix subtraction.
- Parameters:
b – other matrix
- Returns:
this - b
-
inline Vec3 multiply(const Vec3 &p) const¶
Matrix-vector product.
- Parameters:
p – vector
- Returns:
this * p
-
inline Vec3 left_multiply(const Vec3 &p) const¶
Left multiplication (row vector times matrix)
Computes v^T * this
- Parameters:
p – vector
- Returns:
p * this (treating p as row vector)
-
inline Mat33 multiply_by_diagonal(const Vec3 &p) const¶
Right multiply by diagonal matrix.
Multiplies each column i by p[i]
- Parameters:
p – diagonal matrix elements
- Returns:
this * diag(p)
-
inline Mat33 multiply(const Mat33 &b) const¶
Matrix product.
- Parameters:
b – other matrix
- Returns:
this * b
-
inline double trace() const¶
Trace (sum of diagonal)
- Returns:
trace
-
inline bool approx(const Mat33 &other, double epsilon) const¶
Element-wise approximate equality.
- Parameters:
other – other matrix
epsilon – tolerance
- Returns:
true if all elements differ by at most epsilon
-
inline bool has_nan() const¶
Check for NaN.
- Returns:
true if any element is NaN
-
inline double determinant() const¶
Determinant.
- Returns:
det(this)
-
inline bool is_identity() const¶
Check if matrix is identity.
- Returns:
true if this is the identity matrix
-
inline double column_dot(int i, int j) const¶
Dot product of columns.
- Parameters:
i – first column index
j – second column index
- Returns:
column[i] · column[j]
-
inline bool is_upper_triangular() const¶
Check if matrix is upper triangular.
- Returns:
true if lower triangle is zero
Public Members
-
double a[3][3] = {{1., 0., 0.}, {0., 1., 0.}, {0., 0., 1.}}¶
-
typedef double row_t[3]¶
-
template<typename T>
struct SMat33¶ - #include <gemmi/math.hpp>
Symmetric 3×3 matrix.
Used primarily for ADP tensor; stores 6 independent elements Elements in PDB ANISOU order: u11, u22, u33, u12, u13, u23
- Template Parameters:
T – scalar type
Public Functions
-
inline std::array<T, 6> elements_pdb() const¶
Return elements in PDB ANISOU order.
Order: u11, u22, u33, u12, u13, u23
- Returns:
array of 6 elements
-
inline std::array<T, 6> elements_voigt() const¶
Return elements in Voigt notation order.
Order: u11, u22, u33, u23, u13, u12
- Returns:
array of 6 elements
-
inline T &unchecked_ref(int i, int j)¶
Get reference to element [i,j].
i and j must be in [0,2]; no bounds checking
- Parameters:
i – row index
j – column index
- Returns:
reference to element [i,j]
-
inline bool nonzero() const¶
Check if nonzero.
- Returns:
true if trace is nonzero
-
inline bool all_zero() const¶
Check if all elements are zero.
- Returns:
true if all elements are zero
-
template<typename Real>
inline SMat33<Real> scaled(Real s) const¶ Return new matrix with all elements scaled by scalar.
- Template Parameters:
Real – output scalar type
- Parameters:
s – scalar
- Returns:
scaled matrix
-
inline SMat33<T> added_kI(T k) const¶
Return U + kI.
Add k to diagonal elements
- Parameters:
k – scalar to add to diagonal
- Returns:
new matrix
-
template<typename VT>
inline auto r_u_r(const Vec3_<VT> &r) const -> decltype(r.x + u11)¶ Compute scalar r^T U r.
Compute the scalar quadratic form for vector r
- Parameters:
r – vector
- Returns:
r^T U r
-
inline double r_u_r(const std::array<int, 3> &h) const¶
Compute scalar r^T U r for integer vector.
- Parameters:
h – integer vector [3]
- Returns:
r^T U r
-
inline Vec3 multiply(const Vec3 &p) const¶
Matrix-vector product U*p.
- Parameters:
p – vector
- Returns:
U*p
-
inline SMat33 operator-(const SMat33 &o) const¶
Matrix subtraction.
- Parameters:
o – other matrix
- Returns:
this - o
-
inline SMat33 operator+(const SMat33 &o) const¶
Matrix addition.
- Parameters:
o – other matrix
- Returns:
this + o
-
template<typename Real = double>
inline SMat33<Real> transformed_by(const Mat33 &m) const¶ Transform by similarity: M U M^T.
Compute the conjugate: M*U*M^T
- Template Parameters:
Real – output scalar type
- Parameters:
m – transformation matrix
- Returns:
M U M^T
-
inline SMat33 inverse_(T det) const¶
Inverse matrix.
Internal helper with pre-computed determinant
- Parameters:
det – determinant
- Returns:
inverse matrix
-
inline std::array<double, 3> calculate_eigenvalues() const¶
Calculate eigenvalues.
Based on https://en.wikipedia.org/wiki/Eigenvalue_algorithm For eigenvalues and eigenvectors use eig3.hpp
- Returns:
array of 3 eigenvalues
-
struct Transform¶
- #include <gemmi/math.hpp>
Affine transformation: y = mat * x + vec.
Represents a linear transformation followed by translation
Subclassed by gemmi::FTransform
Public Functions
-
inline Vec3 apply(const Vec3 &x) const¶
Apply transformation to vector.
- Parameters:
x – vector
- Returns:
mat * x + vec
-
inline Transform combine(const Transform &b) const¶
Compose transforms.
Apply this transform followed by b
- Parameters:
b – other transform
- Returns:
combined transform: b ∘ this
-
inline bool is_identity() const¶
Check if identity transform.
- Returns:
true if this is the identity
-
inline void set_identity()¶
Reset to identity transform.
-
inline bool has_nan() const¶
Check for NaN.
- Returns:
true if any component is NaN
-
inline Vec3 apply(const Vec3 &x) const¶
-
struct UpperTriangularMat33¶
- #include <gemmi/math.hpp>
Upper-triangular 3×3 matrix.
Stores 6 independent elements (no zero lower triangle)
Public Functions
-
UpperTriangularMat33() = default¶
Default constructor.
-
inline UpperTriangularMat33 &operator=(const Mat33 &m)¶
Assign from full matrix.
Sets all elements to NaN if the matrix is not upper-triangular
- Parameters:
m – full matrix
- Returns:
reference to this
-
UpperTriangularMat33() = default¶
-
template<typename Real>
struct Vec3_¶ - #include <gemmi/math.hpp>
3D vector template
Typedefs: Vec3 (double), Vec3f (float)
- Template Parameters:
Real – scalar type (double or float)
Public Functions
-
inline Vec3_()¶
Default constructor (zero vector)
-
inline Real &at(int i)¶
Access component by index.
- Parameters:
i – index (0, 1, or 2)
- Throws:
std::out_of_range – if i not in 0..2
- Returns:
reference to component x, y, or z
-
inline Real at(int i) const¶
Access component by index (const)
- Parameters:
i – index (0, 1, or 2)
- Throws:
std::out_of_range – if i not in 0..2
- Returns:
value of component x, y, or z
-
inline Vec3_ operator-(const Vec3_ &o) const¶
Subtract vectors.
- Parameters:
o – other vector
- Returns:
this - o
-
inline Vec3_ operator+(const Vec3_ &o) const¶
Add vectors.
- Parameters:
o – other vector
- Returns:
this + o
-
inline Vec3_ operator*(Real d) const¶
Multiply by scalar.
- Parameters:
d – scalar
- Returns:
vector scaled by d
-
inline Vec3_ operator/(Real d) const¶
Divide by scalar.
- Parameters:
d – scalar
- Returns:
vector scaled by 1/d
-
inline Vec3_ &operator-=(const Vec3_ &o)¶
Subtract-assign.
- Parameters:
o – other vector
- Returns:
reference to this
-
inline Vec3_ &operator+=(const Vec3_ &o)¶
Add-assign.
- Parameters:
o – other vector
- Returns:
reference to this
-
inline Vec3_ &operator*=(Real d)¶
Multiply-assign by scalar.
- Parameters:
d – scalar
- Returns:
reference to this
-
inline Vec3_ &operator/=(Real d)¶
Divide-assign by scalar.
- Parameters:
d – scalar
- Returns:
reference to this
-
inline Vec3_ cross(const Vec3_ &o) const¶
Cross product.
- Parameters:
o – other vector
- Returns:
this × o
-
inline Vec3_ changed_magnitude(Real m) const¶
Return vector with same direction but given magnitude.
- Parameters:
m – desired magnitude
- Returns:
scaled vector
-
inline Real dist_sq(const Vec3_ &o) const¶
Squared distance to another vector.
- Parameters:
o – other vector
- Returns:
||this - o||²
-
inline Real dist(const Vec3_ &o) const¶
Euclidean distance to another vector.
- Parameters:
o – other vector
- Returns:
||this - o||
-
inline Real cos_angle(const Vec3_ &o) const¶
Cosine of angle between vectors.
- Parameters:
o – other vector
- Returns:
cos(angle)
-
inline Real angle(const Vec3_ &o) const¶
Angle between vectors in radians.
- Parameters:
o – other vector
- Returns:
angle in [0, π]
-
inline bool approx(const Vec3_ &o, Real epsilon) const¶
Component-wise approximate equality.
- Parameters:
o – other vector
epsilon – tolerance
- Returns:
true if all components differ by at most epsilon
-
inline bool has_nan() const¶
Return true if any component is NaN.
- Returns:
true if has NaN
-
inline bool is_finite() const¶
Return true if all components are finite.
- Returns:
true if finite
-
namespace impl
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
Functions
-
constexpr double pi()¶
-
namespace gemmi
-
struct GruberVector¶
- #include <gemmi/cellred.hpp>
G6 Gruber vector representing a lattice and its cell reduction algorithms.
The six-component G6 vector was called “characteristic” of a lattice/cell by Gruber (1973). Functions that take epsilon use it for numerical comparisons, following Grosse-Kunstleve et al. (2004).
Krivy, I. & Gruber, B. (1976). A unified algorithm for determining the reduced (Niggli) cell. Acta Cryst. A32, 297–298.
https://doi.org/10.1107/S0567739476000636- References
Gruber, B. (1973). The relationship between reduced cells in a general Bravais lattice. Acta Cryst. A29, 433–440. https://doi.org/10.1107/S0567739473001063
Grosse-Kunstleve, R.W., Sauter, N.K. & Adams, P.D. (2004). Numerically stable algorithms for the computation of reduced unit cells. Acta Cryst. A60, 1–6. https://doi.org/10.1107/S010876730302186X
Public Functions
-
inline explicit GruberVector(const Mat33 &m)¶
Construct from orthogonalization matrix of primitive cell.
- Parameters:
m – orthogonalization matrix
-
inline explicit GruberVector(const std::array<double, 6> &g6)¶
Construct from G6 vector array.
- Parameters:
g6 – array {A, B, C, ξ, η, ζ}
-
inline GruberVector(const UnitCell &u, char centring, bool track_change_of_basis = false)¶
Construct from UnitCell with centring.
- Parameters:
u – unit cell
centring – centring type character
track_change_of_basis – if true, track change of basis
-
inline GruberVector(const UnitCell &u, const SpaceGroup *sg, bool track_change_of_basis = false)¶
Construct from UnitCell with SpaceGroup.
- Parameters:
u – unit cell
sg – space group (may be null for P)
track_change_of_basis – if true, track change of basis
-
inline void set_change_of_basis(const Op &op)¶
Set change of basis transformation.
- Parameters:
op – transformation operation
-
inline std::array<double, 6> parameters() const¶
Get G6 vector as array.
- Returns:
array {A, B, C, ξ, η, ζ}
-
inline std::array<double, 6> cell_parameters() const¶
Get unit cell parameters.
Convert from G6 vector to cell parameters
- Returns:
array {a, b, c, α, β, γ} with lengths in Å and angles in degrees
-
inline SellingVector selling() const¶
Convert to Selling-Delaunay vector.
Convert GruberVector to Selling-Delaunay vector.
Compute Selling vector from G6 Gruber parameters
- Returns:
Selling vector
- Returns:
Selling vector
-
inline bool is_normalized() const¶
Check if G6 satisfies Gruber 1973 normalization conditions.
- Returns:
true if normalized (eq(3) from Gruber 1973)
-
inline bool is_buerger(double epsilon = 1e-9) const¶
Check if this is a Buerger-reduced cell.
- Parameters:
epsilon – tolerance for comparisons
- Returns:
true if Buerger-reduced
-
inline void normalize(double eps = 1e-9)¶
Normalize using Gruber Algorithm N.
Apply Gruber normalization to the G6 vector (Algorithm N from Gruber 1973)
- Parameters:
eps – tolerance for comparisons
-
inline bool buerger_step()¶
Perform one step of Gruber Algorithm B.
Execute one iteration of the Buerger reduction algorithm
- Returns:
true if already Buerger-reduced (no change made)
-
inline int buerger_reduce()¶
Reduce to Buerger cell.
Apply normalize() and buerger_step() repeatedly until convergence
- Returns:
iteration count
-
inline bool niggli_step(double epsilon = 1e-9)¶
Perform one step of Krivy-Gruber Niggli reduction.
To be called after normalize() or is_normalized() Algorithm from Krivy & Gruber, Acta Cryst. (1976) A32, 297
- Parameters:
epsilon – tolerance for comparisons
- Returns:
true if already Niggli cell (no change made)
-
inline int niggli_reduce(double epsilon = 1e-9, int iteration_limit = 100)¶
Reduce to Niggli cell.
Apply normalize() and niggli_step() repeatedly until convergence
- Parameters:
epsilon – tolerance for comparisons
iteration_limit – maximum iterations
- Returns:
iteration count
-
inline bool is_niggli(double epsilon = 1e-9) const¶
Check if this is a Niggli-reduced cell.
- Parameters:
epsilon – tolerance for comparisons
- Returns:
true if Niggli-reduced
-
struct SellingVector¶
- #include <gemmi/cellred.hpp>
Selling-Delaunay vector for lattice reduction.
Represents a lattice in terms of 6 scalar products among four basis vectors.
Andrews, L.C., Bernstein, H.J. & Sauter, N.K. (2019). Selling reduction versus Niggli reduction for crystallographic lattices. Acta Cryst. A75, 115–120.
https://doi.org/10.1107/S2053273318015413- References
Patterson, A.L. & Love, W.E. (1957). Remarks on the Delaunay reduction. Acta Cryst. 10, 111–116. https://doi.org/10.1107/S0365110X57000328
International Tables for Crystallography, Vol. A (2016), sec. 3.1.2.3. https://doi.org/10.1107/97809553602060000933
Public Functions
-
inline explicit SellingVector(const std::array<double, 6> &s_)¶
Construct from Selling vector array.
- Parameters:
s_ – array of 6 dot products
-
inline explicit SellingVector(const Mat33 &orth)¶
Construct from orthogonalization matrix.
- Parameters:
orth – orthogonalization matrix
-
inline SellingVector(const UnitCell &u, char centring)¶
Construct from UnitCell with centring.
- Parameters:
u – unit cell
centring – centring type
-
inline SellingVector(const UnitCell &u, const SpaceGroup *sg)¶
Construct from UnitCell with SpaceGroup.
- Parameters:
u – unit cell
sg – space group (may be null for P)
-
inline double sum_b_squared() const¶
Sum of squared basis vector lengths.
The reduction minimizes sum(b_i²) which equals -2·sum(s_i)
- Returns:
sum of squared lengths
-
inline bool is_reduced(double eps = 1e-9) const¶
Check if reduced.
A Selling vector is reduced if all s[i] ≤ 0 within tolerance
- Parameters:
eps – tolerance
- Returns:
true if reduced
-
inline bool reduce_step(double eps = 1e-9)¶
Perform one reduction step.
Apply one iteration of Selling reduction
- Parameters:
eps – tolerance
- Returns:
true if a step was applied
-
inline int reduce(double eps = 1e-9, int iteration_limit = 100)¶
Reduce to Selling form.
Apply reduce_step() repeatedly until convergence
- Parameters:
eps – tolerance
iteration_limit – maximum iterations
- Returns:
iteration count
-
inline std::array<double, 6> g6_parameters() const¶
Convert to G6 parameters.
- Returns:
GruberVector parameters
-
inline GruberVector gruber() const¶
Convert to GruberVector.
- Returns:
Gruber vector equivalent
-
inline void sort(double eps = 1e-9)¶
Sort basis vectors by squared length.
Swap values to make a² ≤ b² ≤ c² ≤ d²
- Parameters:
eps – tolerance for comparisons
-
struct GruberVector¶
Sequence Alignment and Twinning¶
Sequence utilities, pairwise alignment, twinning-law discovery, and interoperability helpers.
(Full documentation added in PR 9.)
-
namespace gemmi
Functions
-
constexpr double h2o_weight()¶
Get the molecular weight of water (H2O).
- Returns:
Water weight in atomic mass units
-
inline double calculate_sequence_weight(const std::vector<std::string> &seq, double unknown = 100.)¶
Calculate the molecular weight of a polymer sequence.
Sums the weights of individual residues and subtracts water molecules for the peptide/nucleic acid bonds formed.
- Parameters:
seq – Vector of residue names (3-letter codes)
unknown – Weight to use for unknown residues (default 100.0)
- Returns:
Molecular weight in atomic mass units
-
inline std::string one_letter_code(const std::vector<std::string> &seq)¶
Convert a sequence to single-letter FASTA code.
- Parameters:
seq – Vector of residue names (3-letter codes)
- Returns:
String of single-letter codes (X for unknown residues)
-
inline std::string pdbx_one_letter_code(const std::vector<std::string> &seq, ResidueKind kind)¶
Convert sequence to PDBx format with non-standard residues in parentheses.
Returns the format used in _entity_poly.pdbx_seq_one_letter_code, in which non-standard amino acids/nucleotides are represented by CCD codes in parentheses, e.g. AA(MSE)H.
- Parameters:
seq – Vector of residue names (3-letter codes)
kind – Type of residue (AA, DNA, RNA) to filter
- Returns:
String with single-letter codes for standard residues and (CCD) for non-standard
-
inline ResidueKind sequence_kind(PolymerType ptype)¶
Convert polymer type to residue kind.
Used with expand_one_letter_sequence() to determine which single-letter codes to expect for a polymer.
- Parameters:
ptype – Polymer type
- Throws:
Fails – with error if polymer type is Unknown
- Returns:
Residue kind (AA, DNA, or RNA)
-
constexpr double h2o_weight()¶
-
namespace gemmi
Functions
-
inline AlignmentResult align_sequences(const std::vector<std::uint8_t> &query, const std::vector<std::uint8_t> &target, const std::vector<int> &target_gapo, std::uint8_t m, const AlignmentScoring &scoring)¶
Perform pairwise sequence alignment using dynamic programming.
Implements the Needleman-Wunsch global alignment algorithm with position-specific gap opening penalties. Code derived from ksw2 (Heng Li).
- References
Needleman, S.B. & Wunsch, C.D. (1970). A general method applicable to the search for similarities in the amino acid sequence of two proteins. J. Mol. Biol. 48, 443–453. https://doi.org/10.1016/0022-2836(70)90057-4
- Parameters:
query – Encoded query sequence (values < m)
target – Encoded target sequence (values < m)
target_gapo – Position-specific gap opening penalties for target (empty if uniform)
m – Number of distinct values in encoding (vocabulary size)
scoring – Scoring parameters (match, mismatch, gap costs, score matrix)
- Returns:
Alignment result with score, CIGAR string, and match count
-
inline AlignmentResult align_string_sequences(const std::vector<std::string> &query, const std::vector<std::string> &target, const std::vector<int> &target_gapo, const AlignmentScoring *scoring)¶
Perform pairwise alignment of string-based sequences.
Encodes sequences as integers and calls align_sequences(). Useful for aligning residue names or custom codes.
Note
Returns empty result if encoding requires >255 distinct values
- Parameters:
query – Query sequence (vector of strings, e.g. 3-letter residue codes)
target – Target sequence (vector of strings)
target_gapo – Position-specific gap opening penalties for target
scoring – Scoring parameters (nullptr uses simple default)
- Returns:
Alignment result with score, CIGAR string, and match count
-
struct AlignmentResult¶
- #include <gemmi/seqalign.hpp>
Result of a pairwise sequence alignment.
Public Functions
-
inline std::string cigar_str() const¶
Get CIGAR string representation.
- Returns:
CIGAR string (e.g., “5M1D3M”)
-
inline std::size_t input_length(int which) const¶
Get input sequence length for alignment.
- Parameters:
which – 1=query, 2=target, other=shorter of the two
- Returns:
Length of specified input sequence
-
inline double calculate_identity(int which = 0) const¶
Calculate sequence identity percentage.
- Parameters:
which – 1=query, 2=target, 0=shorter (default)
- Returns:
Percent identity (0-100)
-
inline void backtrack_to_cigar(const std::uint8_t *p, int i, int j)¶
Convert backtrack matrix to CIGAR string.
Reconstructs the alignment path from the dynamic programming matrix. In the backtrack matrix, value p[] has the structure:
bits 0-2: which type gets the max (0 for H, 1 for E, 2 for F)
bit 3/0x08: 1 if a continuation on the E state
bit 4/0x10: 1 if a continuation on the F state
- Parameters:
p – Backtrack matrix (row-major)
i – Number of target positions
j – Number of query positions
-
inline void count_matches(const std::vector<std::uint8_t> &query, const std::vector<std::uint8_t> &target)¶
Count matching positions and generate match string.
Compares aligned sequences and updates match_count and match_string.
- Parameters:
query – Encoded query sequence
target – Encoded target sequence
-
inline std::string add_gaps(const std::string &s, unsigned which) const¶
Insert gap characters into a sequence based on CIGAR string.
- Parameters:
s – Original sequence string
which – 1=show query gaps, 2=show target gaps, other=show both
- Returns:
Sequence with gaps inserted as ‘-’ characters
-
inline std::string cigar_str() const¶
-
struct AlignmentScoring¶
- #include <gemmi/seqalign.hpp>
Scoring parameters for sequence alignment.
Public Members
-
int match = 1¶
Score for a match.
-
int mismatch = -1¶
Penalty for a mismatch.
-
int gapo = -1¶
Gap opening penalty.
-
int gape = -1¶
Gap extension penalty.
-
int good_gapo = 0¶
Gap opening penalty in expected place in a polymer.
-
int bad_gapo = -2¶
Gap opening penalty for unexpected gaps in a polymer.
Public Static Functions
-
static inline const AlignmentScoring *simple()¶
Get simple default scoring (match=1, mismatch=-1, gaps=-1).
- Returns:
Pointer to static simple scoring instance
-
static inline const AlignmentScoring *partial_model()¶
Get scoring for alignment of partially-modelled polymer to full sequence.
Uses high penalties to penalize mismatches but allow expected gaps.
- Returns:
Pointer to static partial model scoring instance
-
static inline const AlignmentScoring *blosum62()¶
Get BLOSUM-62 scoring matrix (standard for protein alignment).
- Returns:
Pointer to static BLOSUM-62 scoring instance
-
int match = 1¶
-
inline AlignmentResult align_sequences(const std::vector<std::uint8_t> &query, const std::vector<std::uint8_t> &target, const std::vector<int> &target_gapo, std::uint8_t m, const AlignmentScoring &scoring)¶
-
namespace gemmi
Typedefs
Functions
-
inline double calculate_cos_obliquity(const UnitCell &reduced_cell, const Vec3 &d_axis, const Vec3 &r_axis)¶
Calculate cosine of obliquity angle for a twinning operator.
Obliquity is the same as Le Page’s delta (tested against lebedev_2005_perturbation.py from cctbx).
- References
Le Page, Y. (1982). Direct derivation of twin laws from the metric tensor. J. Appl. Cryst. 15, 255–259. https://doi.org/10.1107/S0021889882011959
- Parameters:
reduced_cell – Unit cell (typically from Niggli reduction)
d_axis – 2-fold axis direction in direct space
r_axis – 2-fold axis direction in reciprocal space
- Returns:
Cosine of the obliquity angle
-
inline std::vector<OpObliquity> find_lattice_2fold_ops(const UnitCell &reduced_cell, double max_obliq)¶
Find potential 2-fold twinning operators for a reduced unit cell.
- Parameters:
reduced_cell – Reduced unit cell (typically from Niggli reduction)
max_obliq – Maximum obliquity (delta) in degrees as defined in Le Page (1982)
- Returns:
Vector of 2-fold operators with their obliquity angles, sorted by obliquity
-
inline GroupOps find_lattice_symmetry_r(const UnitCell &reduced_cell, double max_obliq)¶
Find lattice symmetry operations for a reduced unit cell (excluding inversion).
- Parameters:
reduced_cell – Reduced unit cell (typically from Niggli reduction)
max_obliq – Maximum obliquity (delta) in degrees as defined in Le Page (1982)
- Returns:
Group operations representing lattice symmetry (without inversion)
-
inline GroupOps find_lattice_symmetry(const UnitCell &cell, char centring, double max_obliq)¶
Find lattice symmetry operations for a unit cell (excluding inversion).
- Parameters:
cell – Unit cell
centring – Centring type (P, I, F, C, etc.)
max_obliq – Maximum obliquity (delta) in degrees as defined in Le Page (1982)
- Returns:
Group operations representing lattice symmetry (without inversion)
-
inline std::vector<Op> find_twin_laws(const UnitCell &cell, const SpaceGroup *sg, double max_obliq, bool all_ops)¶
Determine potential twinning operators for a structure.
Compares lattice symmetry with space group symmetry to identify candidate twin operators, optionally returning all or only unique ones.
Zwart, P.H., Grosse-Kunstleve, R.W. & Adams, P.D. (2006). Exploring metric symmetry. CCP4 Newsletter 42.
http://legacy.ccp4.ac.uk/newsletters/newsletter44/articles/explore_metric_symmetry.html- References
Lebedev, A.A., Vagin, A.A. & Murshudov, G.N. (2006). Intensity statistics in twinned crystals with examples from the PDB. Acta Cryst. D62, 83–95. https://doi.org/10.1107/S0907444905036759
- Parameters:
cell – Unit cell
sg – Space group (if nullptr, P1 is used)
max_obliq – Maximum obliquity (delta) in degrees as defined in Le Page (1982)
all_ops – If true, return all operators; if false, return only coset representatives
- Returns:
Vector of potential twinning operators
-
namespace impl
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
-
template<class Dummy>
struct TwoFold_¶ - #include <gemmi/twin.hpp>
Public Static Attributes
-
static const TwoFoldData table[81]¶
-
static const TwoFoldData table[81]¶
-
struct TwoFoldData¶
- #include <gemmi/twin.hpp>
-
template<class Dummy>
-
inline double calculate_cos_obliquity(const UnitCell &reduced_cell, const Vec3 &d_axis, const Vec3 &r_axis)¶
Defines
-
SERIALIZE(Struct, ...)¶
Macro to generate serialize functions for a struct.
Expands to both mutable and const serialize template specializations. Usage: SERIALIZE(MyStruct, member1, member2, …)
-
SERIALIZE_P(Struct, Parent, ...)¶
Macro to generate serialize functions for a struct with a parent class.
Serializes the parent class first, then child members. Usage: SERIALIZE_P(MyStruct, ParentClass, member1, member2, …)
-
SERIALIZE_T1(Struct, Typename, ...)¶
Macro to generate serialize functions for a template struct with one parameter.
Generates both mutable and const serialize specializations for a template class. Usage: SERIALIZE_T1(MyTemplate, typename, member1, member2, …)
-
namespace gemmi
Functions
- SERIALIZE_P (UnitCell, UnitCellParameters, o.orth, o.frac, o.volume, o.ar, o.br, o.cr, o.cos_alphar, o.cos_betar, o.cos_gammar, o.explicit_matrices, o.cs_count, o.images) SERIALIZE(Metadata
- o o o o o o o o remark_300_detail SERIALIZE (SoftwareItem, o.name, o.version, o.date, o.description, o.contact_author, o.contact_author_email, o.classification) SERIALIZE(ReflectionsInfo
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma SERIALIZE (ExperimentInfo, o.method, o.number_of_crystals, o.unique_reflections, o.reflections, o.b_wilson, o.shells, o.diffraction_ids) SERIALIZE(DiffractionInfo
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make SERIALIZE (BasicRefinementInfo, o.resolution_high, o.resolution_low, o.completeness, o.reflection_count, o.work_set_count, o.rfree_set_count, o.r_all, o.r_work, o.r_free, o.cc_fo_fc_work, o.cc_fo_fc_free, o.fsc_work, o.fsc_free, o.cc_intensity_work, o.cc_intensity_free) SERIALIZE_P(RefinementInfo
Variables
-
o authors¶
- o o experiments
- o o o crystals
- o o o o refinement
- o o o o o software
- o o o o o o solved_by
- o o o o o o o starting_model
- o o o o o o o o remark_300_detail o resolution_high
- o o o o o o o o remark_300_detail o o resolution_low
- o o o o o o o o remark_300_detail o o o completeness
- o o o o o o o o remark_300_detail o o o o redundancy
- o o o o o o o o remark_300_detail o o o o o r_merge
- o o o o o o o o remark_300_detail o o o o o o r_sym
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o id
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o temperature
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o source
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o source_type
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o synchrotron
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o beamline
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o wavelengths
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o scattering_type
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o mono_or_laue
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o monochromator
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o collection_date
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o optics
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o detector
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make BasicRefinementInfo
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o cross_validation_method
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o o rfree_selection_method
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o o o bin_count
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o o o o bins
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o o o o o mean_b
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o o o o o o aniso_b
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o o o o o o o luzzati_error
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o o o o o o o o dpi_blow_r
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o o o o o o o o o dpi_blow_rfree
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o o o o o o o o o o dpi_cruickshank_r
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o o o o o o o o o o o dpi_cruickshank_rfree
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o o o o o o o o o o o o restr_stats
- o o o o o o o o remark_300_detail o o o o o o o mean_I_over_sigma o o o o o o o o o o o o o o detector_make o o o o o o o o o o o o o o tls_groups
-
namespace gemmi
Functions
-
inline SmallStructure::Site atom_to_site(const Atom &atom, const UnitCell &cell)¶
Convert a macromolecular atom to a small-structure site. Performs coordinate transformation to fractional space, occupancy adjustment for special positions, and anisotropic thermal parameter conversion.
- Parameters:
atom – The macromolecular atom to convert.
cell – The unit cell for coordinate transformation.
- Returns:
A SmallStructure::Site representation of the atom.
-
inline SmallStructure mx_to_sx_structure(const Structure &st, int n = 0)¶
Convert a macromolecular structure (MX) to a small-structure (SX) representation. Extracts atoms from a specific model and converts them to sites using atom_to_site().
- Parameters:
st – The macromolecular structure to convert.
n – The model index to extract (default 0).
- Returns:
A SmallStructure representation of the model.
-
inline SmallStructure::Site atom_to_site(const Atom &atom, const UnitCell &cell)¶
-
namespace gemmi
-
struct FlatAtom¶
- #include <gemmi/flat.hpp>
A flat representation of a single atom for efficient array storage. Stores atomic properties in a contiguous, columnar-friendly format suitable for NumPy arrays and bulk data processing.
Public Functions
Public Members
-
char atom_name[8] = {}¶
Atom name (e.g., “CA”, “CB”).
-
char residue_name[8] = {}¶
Residue name (e.g., “ALA”, “GLY”).
-
char chain_id[8] = {}¶
Chain identifier.
-
char subchain[8] = {}¶
Subchain identifier.
-
float occ = 1.0f¶
Occupancy (0.0 to 1.0).
-
float b_iso = 20.0f¶
Isotropic B-factor (arbitrary default 20.0 Angstrom^2).
-
char altloc = '\0'¶
Alternate location indicator (0 if not set).
-
char het_flag = '\0'¶
Atom type flag (‘A’ = ATOM, ‘H’ = HETATM, 0 = unspecified).
-
EntityType entity_type = EntityType::Unknown¶
Entity type classification.
-
signed char charge = 0¶
Formal charge (-8 to +8).
-
int model_num¶
Model number.
-
int serial = 0¶
Atom serial number.
-
char atom_name[8] = {}¶
-
struct FlatAtom¶
-
namespace gemmi
Typedefs
Functions
-
std::vector<SmartsMatch> match_smarts(const ChemComp &cc, const std::string &pattern)¶
Find all matches of a SMARTS pattern in a chemical component.
This implementation supports a small subset of SMARTS notation:
Atomic symbols: [C], [N], [O], etc. (or C, N, O without brackets)
Wildcards: * (matches any atom)
Aromaticity: [c], [n], etc. (aromatic atoms)
Constraints: H<n> (hydrogen count), X<n> (connectivity/degree)
Bonds: - (single), = (double), ~ (any)
Branching: ( ) for subgraph grouping
- Parameters:
cc – The chemical component to search.
pattern – The SMARTS pattern string.
- Returns:
Vector of all matches found; may include overlapping matches.
-
std::vector<SmartsMatch> match_smarts(const ChemComp &cc, const std::string &pattern)¶
Density Analysis and Numerical Methods¶
Electron density blob finding, isosurface extraction, Levenberg-Marquardt least-squares minimization, and quaternion-based superposition (QCP).
(Full documentation added in PR 9.)
-
namespace gemmi
Functions
-
inline std::vector<Blob> find_blobs_by_flood_fill(const gemmi::Grid<float> &grid, const BlobCriteria &criteria, bool negate = false)¶
Find all blobs (density peaks) in a 3D grid using flood fill.
Uses a flood fill algorithm to identify connected regions above a density threshold, respecting crystallographic symmetry through the asymmetric unit mask. Results are sorted by score (integrated density) in descending order. The algorithm differs from FloodFill in floodfill.hpp by using symmetry operators to exclude symmetric mates from separate blob detection.
- Parameters:
grid – The electron density grid to search.
criteria – Thresholds for minimum volume, score, peak density.
negate – If true, search for negative density (use -grid.data).
- Returns:
Vector of Blob objects, sorted by score (highest first).
-
struct Blob¶
- #include <gemmi/blob.hpp>
A local maximum or connected region (“blob”) in a 3D density map. Represents a contiguous region above a density threshold, computed by flood fill.
Public Functions
-
inline explicit operator bool() const¶
Check if blob is non-empty (volume > 0).
-
inline explicit operator bool() const¶
-
struct BlobCriteria¶
- #include <gemmi/blob.hpp>
Criteria for blob detection in density maps.
Public Members
-
double cutoff¶
Minimum electron density threshold to include points in a blob.
-
double min_volume = 10.0¶
Minimum volume (cubic Angstroms) for blob to be reported.
-
double min_score = 15.0¶
Minimum integrated score for blob to be reported.
-
double min_peak = 0.0¶
Minimum peak density value for blob to be reported.
-
double cutoff¶
-
namespace impl
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
Functions
-
inline Blob make_blob_of_points(const std::vector<GridConstPoint> &points, const GridMeta &grid, const BlobCriteria &criteria)¶
-
struct GridConstPoint¶
- #include <gemmi/blob.hpp>
-
inline Blob make_blob_of_points(const std::vector<GridConstPoint> &points, const GridMeta &grid, const BlobCriteria &criteria)¶
-
inline std::vector<Blob> find_blobs_by_flood_fill(const gemmi::Grid<float> &grid, const BlobCriteria &criteria, bool negate = false)¶
-
namespace gemmi
Enums
Functions
-
inline IsoMethod iso_method_from_string(const std::string &s)¶
Parse isosurface method name from string.
- Parameters:
s – String name: “snapped MC” returns SnappedMC, otherwise MarchingCubes.
- Returns:
The selected isosurface method.
-
inline IsoSurface calculate_isosurface(const std::array<int, 3> &dims, const std::vector<float> &values, const std::vector<float> &points, double isolevel, IsoMethod method = IsoMethod::MarchingCubes)¶
Extract an isosurface from flat 3D arrays using marching cubes.
Low-level function that operates directly on flat arrays of values and positions. For convenience, use extract_isosurface() with a Grid object instead.
- Parameters:
dims – Number of grid points in each dimension [x, y, z].
values – Scalar field values, length dims[0]*dims[1]*dims[2].
points – Cartesian coordinates as flattened triples: x0,y0,z0,x1,y1,z1,… Total length: 3 * dims[0]*dims[1]*dims[2].
isolevel – The isovalue threshold for surface extraction.
method – Marching cubes variant (standard or snapped).
- Returns:
IsoSurface containing vertices (x,y,z triples) and triangles (vertex-index triples).
-
template<typename T>
IsoSurface extract_isosurface(const Grid<T> &grid, const Position ¢er, double radius, double isolevel, IsoMethod method = IsoMethod::MarchingCubes)¶ Extract an isosurface from a Grid within a spherical region.
Automatically extracts a region of the grid around a center point, converts to fractional/grid coordinates, and runs marching cubes on the subregion. This is the recommended high-level interface.
- Template Parameters:
T – The grid value type (float, double, etc.).
- Parameters:
grid – The 3D density map to process.
center – Center point in Cartesian coordinates.
radius – Radius of the sphere in Angstroms.
isolevel – The isovalue threshold for surface extraction.
method – Marching cubes variant (standard or snapped).
- Returns:
IsoSurface containing extracted vertices and triangle indices.
-
struct IsoSurface¶
- #include <gemmi/isosurface.hpp>
Result of an isosurface extraction (vertices and triangle indices).
-
namespace impl
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
-
inline IsoMethod iso_method_from_string(const std::string &s)¶
-
namespace gemmi
Functions
-
inline void jordan_solve(double *a, double *b, int n)¶
Solve a linear system using Gauss-Jordan elimination with partial pivoting.
This function solves a set of linear algebraic equations using Gauss-Jordan elimination with partial pivoting.
A * x = b
a is n x n matrix (in vector) b is vector of length n, This function returns vector x[] in b[], and 1-matrix in a[].
Solves A * x = b by reducing A to the identity matrix via row operations. Handles singular matrices by skipping zero rows/columns.
- Parameters:
a – n x n matrix stored in row-major order (modified to identity matrix).
b – Right-hand side vector of length n (modified to solution x).
n – System size.
-
inline void jordan_solve(std::vector<double> &a, std::vector<double> &b)¶
Solve a linear system stored in vector containers.
- Parameters:
a – n x n matrix as flat vector (n^2 elements).
b – Right-hand side vector of length n.
-
inline void print_parameters(const std::string &name, std::vector<double> &a)¶
Print parameters to stderr (debug only).
- Parameters:
name – Label for the parameter set.
a – Vector of parameters to print.
-
template<typename Target>
double compute_wssr(const Target &target)¶ Compute weighted sum of squared residuals for a target.
Uses long double for accumulation to improve numerical accuracy. Assumes Target provides: points container, get_weight(), get_y(), compute_value().
- Template Parameters:
Target – Fitting target type.
- Parameters:
target – The fitting target.
- Returns:
Sum of weighted squared residuals.
-
template<typename Target>
double compute_gradients(const Target &target, unsigned n, double *grad)¶ Compute function value, residuals, and gradients with respect to parameters.
Assumes Target provides: points container, get_weight(), get_y(), compute_value_and_derivatives(point, dy_da_vector).
- Template Parameters:
Target – Fitting target type.
- Parameters:
target – The fitting target.
n – Number of parameters.
grad – Output array of size n for partial derivatives d(wssr)/da.
- Returns:
Weighted sum of squared residuals.
-
template<typename Target>
double compute_lm_matrices(const Target &target, std::vector<double> &alpha, std::vector<double> &beta)¶ Compute Jacobian-based matrices for Levenberg-Marquardt algorithm.
Computes the normal equations: alpha = J^T*J (approximates Hessian), beta = J^T*residual. These are the building blocks for iterative refinement. Alpha is initially undamped; the LM algorithm applies the damping factor (1 + lambda) to diagonal elements. Both matrices use only the lower triangle and are symmetrized after computation. Assumes Target provides: points container, get_weight(), get_y(), compute_value_and_derivatives(point, dy_da_vector).
- Template Parameters:
Target – Fitting target type.
- Parameters:
target – The fitting target.
alpha – Output: n x n matrix (stored as flat vector) = J^T*J.
beta – Output: n-element vector = J^T*residual.
- Returns:
Weighted sum of squared residuals.
-
struct LevMar¶
- #include <gemmi/levmar.hpp>
Levenberg-Marquardt non-linear least-squares optimization.
Implements the Levenberg-Marquardt algorithm for fitting model parameters to minimize the sum of weighted squared residuals. The algorithm adjusts a damping factor (lambda) to interpolate between gradient descent (large lambda) and Newton’s method (small lambda), automatically selecting the step size that gives best improvement.
Marquardt, D.W. (1963). An algorithm for least-squares estimation of nonlinear parameters. J. Soc. Ind. Appl. Math. 11, 431–441.
https://doi.org/10.1137/0111030- References
Levenberg, K. (1944). A method for the solution of certain non-linear problems in least squares. Q. Appl. Math. 2, 164–168. https://doi.org/10.1090/qam/10666
Public Functions
-
template<typename Target>
inline double fit(Target &target)¶ Run Levenberg-Marquardt optimization.
Iteratively refines parameters to minimize WSSR. At each iteration, solves (J^T*J + lambda*diag(J^T*J)) * da = J^T*residual for step da, then updates parameters and checks for improvement. Terminates when eval_limit is reached, lambda exceeds lambda_limit, or relative improvement drops below stop_rel_change for two iterations.
- Template Parameters:
Target – Fitting target type (must implement: get_parameters(), set_parameters(), points container, and compute_value_and_derivatives()).
- Parameters:
target – The fitting target (modified in place).
- Returns:
Final weighted sum of squared residuals. initial_wssr and eval_count are also set and can be inspected after fit() returns.
Public Members
-
int eval_limit = 100¶
Maximum number of function evaluations before terminating.
-
double lambda_limit = 1e+15¶
Stop optimization if damping factor lambda exceeds this value.
-
double stop_rel_change = 1e-5¶
Stop if relative change in WSSR falls below this for two consecutive iterations.
-
double lambda_up_factor = 10¶
Factor by which lambda is multiplied if fit worsens.
-
double lambda_down_factor = 0.1¶
Factor by which lambda is multiplied if fit improves.
-
double lambda_start = 0.001¶
Initial damping factor (typically 0.001).
-
inline void jordan_solve(double *a, double *b, int n)¶
-
namespace gemmi
Functions
-
inline double qcp_inner_product(Mat33 &mat, const Position *pos1, const Position &ctr1, const Position *pos2, const Position &ctr2, size_t len, const double *weight)¶
Compute covariance matrix H and sum G for QCP algorithm.
Helper function for quaternion-based superposition. Computes the weighted covariance (or “scatter”) matrix H = sum_i w_i * (p1_i - ctr1) * (p2_i - ctr2)^T, and the sum G1 + G2 = sum_i w_i * |p1_i - ctr1|^2 + |p2_i - ctr2|^2.
- Parameters:
mat – Output 3x3 covariance matrix (accumulated into).
pos1 – Array of positions in first structure.
ctr1 – Centroid of first structure.
pos2 – Array of positions in second structure.
ctr2 – Centroid of second structure.
len – Number of position pairs.
weight – Optional array of weights; if null, all weights are 1.0.
- Returns:
Sum of weighted squared distances from centroids (G1 + G2).
-
inline int fast_calc_rmsd_and_rotation(Mat33 *rot, const Mat33 &A, double *rmsd, double E0, double len, double min_score)¶
Compute optimal rotation and RMSD using quaternion characteristic polynomial.
Fast algorithm (Theobald 2005, Liu et al. 2009) for computing the optimal rotation that minimizes RMSD between two point clouds. Uses eigenvalue computation via Newton-Raphson on a characteristic polynomial and quaternion-to-rotation-matrix conversion.
- Parameters:
rot – Output 3x3 rotation matrix; set to identity if computation fails. May be null if only RMSD is needed (set min_score > 0).
A – Covariance matrix from qcp_inner_product().
rmsd – Output: root-mean-square deviation after optimal rotation.
E0 – Sum of weighted squared distances from centroids.
len – Sum of weights (or number of atoms).
min_score – If >= 0 and RMSD < min_score, skip rotation computation and return -1.
- Returns:
Status: 1 if rotation computed successfully, 0 if singular (identity returned), -1 if min_score criterion not met or rot is null.
-
inline Position qcp_calculate_center(const Position *pos, size_t len, const double *weight)¶
Calculate the weighted centroid of a point set.
- Parameters:
pos – Array of positions.
len – Number of positions.
weight – Optional array of weights; if null, all weights are 1.0.
- Returns:
Weighted centroid position.
-
inline SupResult superpose_positions(const Position *pos1, const Position *pos2, size_t len, const double *weight)¶
Calculate the optimal superposition of one point set onto another using QCP.
Finds the rotation and translation that best align pos2 onto pos1, minimizing the weighted root-mean-square deviation. Does not modify positions; to apply the transformation, use transform.apply() on pos2.
Liu, P., Agrafiotis, D.K. & Theobald, D.L. (2010). Fast determination of the optimal rotational matrix for macromolecular superpositions. J. Comput. Chem. 31, 1561–1563.
https://doi.org/10.1002/jcc.21439- References
Theobald, D.L. (2005). Rapid calculation of RMSD using a quaternion-based characteristic polynomial. Acta Cryst. A61, 478–480. https://doi.org/10.1107/S0108767305015266
- Parameters:
pos1 – Array of reference positions (fixed).
pos2 – Array of positions to be superposed (movable).
len – Number of position pairs.
weight – Optional array of weights; if null, all weights are 1.0.
- Returns:
SupResult containing RMSD, rotation matrix, translation, and centroids.
-
inline double calculate_rmsd_of_superposed_positions(const Position *pos1, const Position *pos2, size_t len, const double *weight)¶
Calculate the RMSD between two point sets after optimal superposition (fast).
Similar to superpose_positions() but computes only the RMSD without the rotation matrix or translation vector, making it faster for cases where only the quality of fit is needed.
- Parameters:
pos1 – Array of reference positions.
pos2 – Array of positions to be superposed.
len – Number of position pairs.
weight – Optional array of weights; if null, all weights are 1.0.
- Returns:
Root-mean-square deviation after optimal superposition.
-
struct SupResult¶
- #include <gemmi/qcp.hpp>
Result of quaternion-based structural superposition. Stores the optimal rotation, translation, and RMSD between two point sets.
-
inline double qcp_inner_product(Mat33 &mat, const Position *pos1, const Position &ctr1, const Position *pos2, const Position &ctr2, size_t len, const double *weight)¶
Reflection Data¶
(Full documentation added in PR 5.)
MTZ reflection file format (X-ray crystallography).
-
namespace gemmi
Functions
-
inline Mtz read_mtz_file(const std::string &path)¶
Convenience function: read MTZ from a file path.
- Parameters:
path – File path.
- Returns:
Loaded Mtz object.
-
template<typename Input>
Mtz read_mtz(Input &&input, bool with_data)¶ Convenience function: read MTZ from an input object (handles gzip).
- Template Parameters:
Input – Type with path() and create_stream() methods.
- Parameters:
input – Input object (e.g., MaybeGzipped).
with_data – If true, read reflection data; if false, headers only.
- Returns:
Loaded Mtz object.
-
inline MtzDataProxy data_proxy(const Mtz &mtz)¶
Create a proxy for accessing MTZ data.
- Parameters:
mtz – MTZ object.
- Returns:
MtzDataProxy wrapping the MTZ.
-
struct Mtz : public gemmi::MtzMetadata¶
- #include <gemmi/mtz.hpp>
Representation of an MTZ reflection file. Contains reflection data, column definitions, batch headers (for unmerged files), and crystallographic metadata (cell, space group, symmetry operations).
Crystallographic properties (after reading headers/data)
-
inline double resolution_high() const¶
Get the highest resolution in Angstroms.
- Returns:
d_min = 1/sqrt(max_1_d2); resolution is high when d is small.
-
inline double resolution_low() const¶
Get the lowest resolution in Angstroms.
- Returns:
d_max = 1/sqrt(min_1_d2); resolution is low when d is large.
-
inline UnitCell &get_cell(int dataset = -1)¶
Get the unit cell for a specific dataset or the global cell.
- Parameters:
dataset – Dataset ID (default -1 = global cell, but searches datasets first).
- Returns:
Reference to the unit cell.
-
inline void set_cell_for_all(const UnitCell &new_cell)¶
Set the global and all per-dataset unit cells to the same value.
- Parameters:
new_cell – The new unit cell parameters.
-
UnitCellParameters get_average_cell_from_batch_headers(double *rmsd) const¶
Calculate average unit cell from all batch headers, optionally with RMSD.
- Parameters:
rmsd – [out] Pointer to array of 6 doubles (a, b, c, alpha, beta, gamma RMSD), or nullptr to skip.
- Returns:
Average cell from all batches, or global cell if batches are invalid.
-
inline void set_spacegroup(const SpaceGroup *new_sg)¶
Set the space group and update related fields.
- Parameters:
new_sg – Pointer to SpaceGroup (may be null).
Dataset access
-
inline Dataset &last_dataset()¶
Get the last (most recently added) dataset.
- Throws:
std::runtime_error – if no datasets exist.
- Returns:
Reference to the last dataset.
Column access and queries
-
inline int count(const std::string &label) const¶
Count columns with a specific label (may be > 1 if duplicates exist).
- Parameters:
label – Column label to count.
- Returns:
Number of columns with this label.
-
inline int count_type(char type) const¶
Count columns of a specific type.
- Parameters:
type – Column type code (e.g., ‘F’, ‘P’, ‘Q’).
- Returns:
Number of columns with this type.
-
inline Column *column_with_label(const std::string &label, const Dataset *ds = nullptr, char type =
' *')¶ Find the first column with a given label, optionally filtered by dataset and type.
- Parameters:
label – Column label.
ds – [optional] Restrict search to this dataset (nullptr = any).
type – [optional] Restrict search to this type (‘*’ = any).
- Returns:
Pointer to the column, or nullptr if not found.
-
inline const Column *column_with_label(const std::string &label, const Dataset *ds = nullptr, char type =
' *') const¶ Find the first column with a given label (const).
-
inline const Column &get_column_with_label(const std::string &label, const Dataset *ds = nullptr) const¶
Get a column by label, raising an error if not found.
-
inline std::vector<const Column*> columns_with_type(char type) const¶
Get all columns of a specific type.
- Parameters:
type – Column type code.
- Returns:
Vector of pointers to matching columns.
-
inline std::vector<int> positions_of_columns_with_type(char col_type) const¶
Get positions (indices) of all columns with a specific type.
- Parameters:
col_type – Column type code.
- Returns:
Vector of column indices.
-
inline std::vector<std::pair<int, int>> positions_of_plus_minus_columns() const¶
Find anomalous (±) column pairs by label pattern matching. Looks for labels with “(+)” and matches corresponding “(-)” columns. Note: F(+)/(-) pairs use type G, I(+)/(-) use type K, but E(+)/(-) have no dedicated type, so label matching is used.
- Returns:
Vector of (index_plus, index_minus) pairs.
-
inline const Column *column_with_one_of_labels(std::initializer_list<const char*> labels, char type =
' *') const¶ Find the first column matching any label in a prioritized list.
Note
Order of labels matters; returns the first match.
- Parameters:
labels – List of labels to try in order.
type – [optional] Column type to match (‘*’ = any).
- Returns:
Pointer to the first matching column, or nullptr.
-
inline Column *column_with_type_and_any_of_labels(char type, std::initializer_list<const char*> labels)¶
Find a column matching a type and any of several labels.
Note
Order of labels does not matter.
- Parameters:
type – Column type to match.
labels – List of labels to search for.
- Returns:
Pointer to the first matching column, or nullptr.
-
inline Column *rfree_column()¶
Find the R-free flag column (common labels: FREE, RFREE, R_FREE_FLAGS, etc.).
- Returns:
Pointer to R-free column (type ‘I’), or nullptr.
-
inline Column *imean_column()¶
Find the mean intensity column (common labels: IMEAN, I, IOBS, I-obs).
- Returns:
Pointer to intensity column (type ‘J’), or nullptr.
-
inline Column *iplus_column()¶
Find the I(+) anomalous intensity column (common labels: I(+), IOBS(+), Iplus).
- Returns:
Pointer to I(+) column (type ‘K’), or nullptr.
Data status
-
inline bool has_data() const¶
Check if reflection data has been loaded.
- Returns:
True if data.size() == columns.size() * nreflections.
-
inline bool is_merged() const¶
Check if this is a merged MTZ file (no batch headers).
- Returns:
True if batches.empty().
-
std::array<double, 2> calculate_min_max_1_d2() const¶
Calculate min/max 1/d² from all reflections and unit cells. Considers both global cell and per-dataset DCELLs.
- Returns:
[min_1_d2, max_1_d2].
-
inline void update_reso()¶
Recalculate and update min_1_d2 and max_1_d2 from reflection data.
File I/O
-
inline void toggle_endianness()¶
Toggle the assumed byte order and swap header_offset accordingly.
-
void read_first_bytes(AnyStream &stream)¶
Read and verify the first 80 bytes (MTZ magic and machine stamp).
- Parameters:
stream – Input stream positioned at file start.
-
void read_main_headers(AnyStream &stream, std::vector<std::string> *save_headers)¶
Read header records from VERS until END.
- Parameters:
stream – Input stream positioned at the header block.
save_headers – [optional] Pointer to string vector to save header lines.
-
void read_history_and_batch_headers(AnyStream &stream)¶
Read history (MTZHIST) and batch (MTZBATS) records after the END header.
- Parameters:
stream – Input stream positioned after END.
-
void setup_spacegroup()¶
Set up spacegroup pointer from spacegroup_number or spacegroup_name.
-
void read_raw_data(AnyStream &stream, bool do_read = true)¶
Read raw reflection data from stream (float32 binary).
- Parameters:
stream – Input stream.
do_read – If false, skip reading (compute space only).
-
void read_all_headers(AnyStream &stream)¶
Read all header records (convenience wrapper).
- Parameters:
stream – Input stream.
-
void read_stream(AnyStream &stream, bool with_data)¶
Read MTZ from a stream, including headers and optionally data. Expects stream positioned at file start; reads in order: raw data, main headers, batch headers.
- Parameters:
stream – Input stream.
with_data – If true, read reflection data; if false, skip it.
-
inline void read_file(const std::string &path)¶
Read MTZ from a file path.
- Parameters:
path – File path.
- Throws:
std::system_error – or std::runtime_error on failure.
-
template<typename Input>
inline void read_input(Input &&input, bool with_data)¶ Read MTZ from an input object (e.g., MaybeGzipped for .mtz or .mtz.gz).
- Template Parameters:
Input – Type with path() and create_stream() methods.
- Parameters:
input – Input object.
with_data – If true, read reflection data.
Data manipulation (reflection rows)
-
std::vector<int> sorted_row_indices(int use_first = 3) const¶
Get sorted row indices based on the first N columns (HKL by default).
- Parameters:
use_first – Number of columns to use for sorting (default 3 = h, k, l).
- Returns:
Vector of indices [0..nreflections-1] sorted by the first N columns.
-
bool sort(int use_first = 3)¶
Sort reflections in-place using the first N columns.
- Parameters:
use_first – Number of columns to use for sorting (default 3).
- Returns:
True if any sorting was done; false if already sorted.
-
inline Miller get_hkl(size_t offset) const¶
Extract Miller indices from a reflection at a given offset in the data array.
- Parameters:
offset – Offset to the first element of the reflection (H, K, L at offsets 0, 1, 2).
- Returns:
Miller indices.
-
inline void set_hkl(size_t offset, const Miller &hkl)¶
Set Miller indices at a given offset.
- Parameters:
offset – Offset to the H element.
hkl – Miller indices to store.
-
size_t find_offset_of_hkl(const Miller &hkl, size_t start = 0) const¶
Find the data offset of the first reflection with specific Miller indices.
Note
This is a linear search; can be slow for large files.
- Parameters:
hkl – Miller indices to search for.
start – Starting offset (optional, default 0).
- Returns:
Offset to the reflection, or (size_t)-1 if not found.
-
void ensure_asu(bool tnt_asu = false)¶
Move all reflections to ASU and adjust phases/anomalous data accordingly. For merged MTZ only. Transforms F(+), F(-), phases, and Hendrickson-Lattman coefficients.
- Parameters:
tnt_asu – If true, use TNT ASU setting; if false, use default ASU.
-
void reindex(const Op &op)¶
Reindex reflections using a new basis and update space group accordingly. Applies symmetry operation to HKL, removes fractional indices, adjusts cell and space group. Outputs messages to logger.
- Parameters:
op – Reindexing operation (must have no translation and determinant > 0).
-
void expand_to_p1()¶
Expand reflections to P1 using all symmetry operations. Duplicate reflections under symmetry, adjust phases if present. Similar to SFTOOLS EXPAND command.
Note
Does not re-sort; sort afterwards if needed.
-
bool switch_to_original_hkl()¶
For unmerged MTZ: convert HKL from ASU to original (observer) indices. Reads M/ISYM column and applies inverse symmetry operations.
- Returns:
True if M/ISYM column was found and data was modified.
-
bool switch_to_asu_hkl()¶
For unmerged MTZ: convert HKL to ASU and set M/ISYM column accordingly.
- Returns:
True if M/ISYM column was found and data was modified.
Data construction
-
inline Dataset &add_dataset(const std::string &name)¶
Create a new dataset with auto-assigned ID and add to the file.
- Parameters:
name – Name to use for project, crystal, and dataset.
- Returns:
Reference to the newly added dataset.
-
Column &add_column(const std::string &label, char type, int dataset_id, int pos, bool expand_data)¶
Add a column to the file and optionally expand the data array.
-
Column &replace_column(size_t dest_idx, const Column &src_col, const std::vector<std::string> &trailing_cols = {})¶
Replace a column with data from another column (including trailing columns).
- Parameters:
dest_idx – Destination column index.
src_col – Source column to copy from.
trailing_cols – [optional] Labels of columns immediately after src_col to also copy.
- Returns:
Reference to the destination column.
-
Column ©_column(int dest_idx, const Column &src_col, const std::vector<std::string> &trailing_cols = {})¶
Copy a column to a destination, or append if dest_idx < 0.
- Parameters:
dest_idx – Destination index (-1 = append).
src_col – Source column.
trailing_cols – [optional] Labels of subsequent columns to also copy.
- Returns:
Reference to the destination column.
-
void remove_column(size_t idx)¶
Remove a column from the file and data array.
- Parameters:
idx – Column index to remove.
-
template<typename Func>
inline void remove_rows_if(Func condition)¶ Remove reflection rows matching a condition.
- Template Parameters:
Func – Callable that takes pointer to row data and returns true to remove.
- Parameters:
condition – Predicate function.
File output
-
void write_to_cstream(std::FILE *stream) const¶
Write MTZ to a C FILE stream.
- Parameters:
stream – Open FILE* stream (should be in binary write mode).
-
void write_to_string(std::string &str) const¶
Write MTZ to a string (binary data).
- Parameters:
str – [out] String to append the binary MTZ data to.
-
void write_to_file(const std::string &path) const¶
Write MTZ to a file.
- Parameters:
path – File path.
-
size_t size_to_write() const¶
Get the size of the binary MTZ output in bytes.
- Returns:
Size needed for the complete MTZ file.
-
size_t write_to_buffer(char *buf, size_t maxlen) const¶
Write MTZ to a buffer.
- Parameters:
buf – Pointer to output buffer.
maxlen – Maximum bytes to write.
- Returns:
Number of bytes written.
Public Functions
-
inline explicit Mtz(bool with_base = false)¶
Create an empty MTZ object.
- Parameters:
with_base – If true, initialize with a default HKL_base dataset and H, K, L columns.
-
inline explicit Mtz(const Mtz &o)¶
Copy constructor. Explicit to prevent accidental copies. Updates parent pointers.
-
Mtz &operator=(Mtz const&) = delete¶
Copy assignment is deleted (explicit copy constructor forces intentionality).
-
inline void add_base()¶
Initialize with default HKL_base dataset and H, K, L columns.
Public Members
-
struct Batch¶
- #include <gemmi/mtz.hpp>
Batch header for unmerged MTZ files (one per diffraction image/sweep). Contains crystallographic and experimental metadata in fixed positions.
Public Functions
-
inline Batch()¶
Initialize a batch with default values (matching CCP4 COMBAT/Pointless).
-
inline UnitCell get_cell() const¶
Extract unit cell parameters from batch header.
- Returns:
Unit cell (a, b, c, alpha, beta, gamma).
-
inline void set_cell(const UnitCell &uc)¶
Set unit cell parameters in batch header.
- Parameters:
uc – The unit cell to store.
-
inline int dataset_id() const¶
Get the dataset ID from batch header.
- Returns:
Dataset ID (from ints[20]).
-
inline void set_dataset_id(int id)¶
Set the dataset ID in batch header.
- Parameters:
id – Dataset ID to store in ints[20].
-
inline float wavelength() const¶
Get the X-ray wavelength.
- Returns:
Wavelength in Angstroms (from floats[86]).
-
inline void set_wavelength(float lambda)¶
Set the X-ray wavelength.
- Parameters:
lambda – Wavelength in Angstroms.
-
inline float phi_start() const¶
Get the phi rotation start angle.
- Returns:
Start angle in degrees (from floats[36]).
-
inline float phi_end() const¶
Get the phi rotation end angle.
- Returns:
End angle in degrees (from floats[37]).
-
inline Batch()¶
-
struct Column¶
- #include <gemmi/mtz.hpp>
A column in the reflection data array. Stores one field per reflection (e.g., amplitude, phase, flag).
Public Types
-
using iterator = StrideIter<float>¶
Iterator over this column’s values.
-
using const_iterator = StrideIter<const float>¶
Const iterator over this column’s values.
Public Functions
-
inline int size() const¶
Number of values in this column (0 if no data loaded).
-
inline size_t stride() const¶
Stride between consecutive values in the data array (= number of columns).
-
inline float &operator[](std::size_t n)¶
Access column value for reflection n.
- Parameters:
n – Reflection index (0 to nreflections-1).
-
inline float &at(std::size_t n)¶
Access column value for reflection n with bounds checking.
- Parameters:
n – Reflection index.
- Throws:
std::out_of_range – if n is out of bounds.
- Returns:
Reference to the data value.
-
inline float at(std::size_t n) const¶
Access column value for reflection n with bounds checking (const).
-
inline bool is_integer() const¶
True if this column type represents an integer value. Returns true for types H, B, Y, I (indices, batch, ISYM, integers).
-
inline const Column *get_next_column_if_type(char next_type) const¶
Find the next column in the same dataset with a specific type.
- Parameters:
next_type – The column type to search for.
- Returns:
Pointer to the next matching column, or nullptr.
-
inline const_iterator begin() const¶
Begin const iterator.
-
inline const_iterator end() const¶
End const iterator.
Public Members
-
char type¶
Column type code: ‘H’=Miller index (H, K, or L), ‘F’=amplitude, ‘Q’=standard deviation, ‘J’=intensity, ‘M/ISYM’=symmetry flag (unmerged), ‘D’=anomalous difference, ‘P’=phase (degrees), ‘W’=weight, ‘A’=phase prob., ‘B’=batch number, ‘Y’=M/ISYM, ‘I’=integer, ‘R’=R-factor, ‘G’=F(+)/F(-), ‘K’=I(+)/I(-), ‘L’=string.
-
float min_value = NAN¶
Minimum value in this column (NAN if not computed).
-
float max_value = NAN¶
Maximum value in this column (NAN if not computed).
-
using iterator = StrideIter<float>¶
-
struct Dataset¶
- #include <gemmi/mtz.hpp>
A dataset in the MTZ file hierarchy: project → crystal → dataset → columns.
-
inline double resolution_high() const¶
-
struct MtzDataProxy¶
- #include <gemmi/mtz.hpp>
Abstraction layer for accessing MTZ data uniformly. Provides stride, data access, and cell/symmetry information. Similar to ReflnDataProxy for reflection data in other formats.
Subclassed by gemmi::MtzExternalDataProxy
Public Functions
-
inline size_t stride() const¶
Stride (number of columns) between consecutive reflections.
-
inline size_t size() const¶
Total number of floats in the data array.
-
inline float get_num(size_t n) const¶
Access a data element by index.
- Parameters:
n – Index into the flat data array.
-
inline const SpaceGroup *spacegroup() const¶
Get the space group.
-
inline size_t stride() const¶
-
struct MtzExternalDataProxy : public gemmi::MtzDataProxy¶
- #include <gemmi/mtz.hpp>
MtzDataProxy variant for external data (not stored in Mtz). Wraps MTZ metadata with a separate data array pointer.
Public Functions
-
inline MtzExternalDataProxy(const Mtz &mtz, const float *data)¶
Initialize with MTZ metadata and external data.
- Parameters:
mtz – MTZ object (for structure info only).
data – Pointer to external float array (size = columns.size() * nreflections).
-
inline size_t size() const¶
Total size of the external data array.
-
inline float get_num(size_t n) const¶
Access element from external data.
Public Members
-
const float *data_¶
Pointer to external data array.
-
inline MtzExternalDataProxy(const Mtz &mtz, const float *data)¶
-
struct MtzMetadata¶
- #include <gemmi/mtz.hpp>
MTZ file metadata: crystallographic parameters, symmetry, and file structure.
Subclassed by gemmi::Mtz
Public Members
-
bool same_byte_order = true¶
True if the file’s byte order matches the system (not swapped).
-
bool indices_switched_to_original = false¶
For unmerged MTZ: true if HKL indices have been switched to original (non-ASU) values.
-
int nreflections = 0¶
Number of reflections in the data array.
-
double min_1_d2 = NAN¶
Minimum 1/d² value in the file (d = 1/sqrt(1/d²)).
-
double max_1_d2 = NAN¶
Maximum 1/d² value in the file.
-
float valm = NAN¶
VALM value: typically unused (for future use in CCP4).
-
int nsymop = 0¶
Number of symmetry operations (redundant with symops.size()).
-
int spacegroup_number = 0¶
CCP4 space group number.
-
const SpaceGroup *spacegroup = nullptr¶
Pointer to the SpaceGroup object (from symmetry database).
-
bool same_byte_order = true¶
-
struct UnmergedHklMover¶
- #include <gemmi/mtz.hpp>
Helper for writing unmerged MTZ files with correct M/ISYM column values. Converts Miller indices to ASU-equivalent and encodes the symmetry operation.
Public Functions
-
inline UnmergedHklMover(const SpaceGroup *spacegroup)¶
Initialize with spacegroup information.
- Parameters:
spacegroup – The space group (may be null).
-
inline UnmergedHklMover(const SpaceGroup *spacegroup)¶
-
inline Mtz read_mtz_file(const std::string &path)¶
Structure and accessors for reflection data from SF-mmCIF files.
-
namespace gemmi
Functions
-
inline std::vector<ReflnBlock> as_refln_blocks(std::vector<cif::Block> &&blocks)¶
Convert CIF blocks to ReflnBlocks, propagating cell and spacegroup info.
Fills in missing cell or spacegroup data by copying from the first block that contains it. Moves blocks from input to output.
- Parameters:
blocks – Input CIF blocks (consumed).
- Returns:
Vector of ReflnBlocks.
-
inline ReflnBlock get_refln_block(std::vector<cif::Block> &&blocks, const std::vector<std::string> &labels, const char *block_name = nullptr)¶
Find the first merged reflection block containing specified columns.
Searches blocks for one with _refln loop and required column labels. Propagates spacegroup from first block if needed.
- Parameters:
blocks – Input CIF blocks (consumed).
labels – Required column names (empty string means optional).
block_name – Optional: if provided, only this named block is considered.
- Throws:
gemmi::fail – if no matching block or required columns not found.
- Returns:
The matching ReflnBlock.
-
inline ReflnBlock hkl_cif_as_refln_block(cif::Block &block)¶
Convert CIF block from non-mmCIF format to ReflnBlock.
- Parameters:
block – Input CIF block (e.g., from hkl file).
- Returns:
ReflnBlock with data from _refln_index_h loop.
-
inline ReflnDataProxy data_proxy(const ReflnBlock &rb)¶
Create a data proxy over a ReflnBlock.
- Parameters:
rb – ReflnBlock to wrap.
- Returns:
ReflnDataProxy for generic access.
-
struct ReflnBlock¶
- #include <gemmi/refln.hpp>
Wrapper for reflection data block from mmCIF file.
Provides column access and HKL index management for reflection data stored in CIF loops (either merged _refln or unmerged _diffrn_refln categories).
Public Functions
-
ReflnBlock() = default¶
Default constructor (empty block).
-
ReflnBlock(ReflnBlock &&rblock_) = default¶
Move constructor.
-
inline ReflnBlock(cif::Block &&block_)¶
Construct from CIF block; extracts cell, spacegroup, wavelength, and reflection loops.
-
ReflnBlock &operator=(ReflnBlock&&) = default¶
Move assignment.
-
inline ReflnBlock &operator=(const ReflnBlock &o)¶
Copy assignment (deep copy of block and pointers).
-
inline bool ok() const¶
Check if block contains valid reflection data.
- Returns:
True if default_loop is set and not null.
-
inline void check_ok() const¶
Throw exception if block is not valid.
-
inline size_t tag_offset() const¶
Get offset to tag name (after “_refln.” or “_diffrn_refln.”).
- Returns:
7 for merged, 14 for unmerged.
-
inline void use_unmerged(bool unmerged)¶
Switch between merged and unmerged reflection loops.
- Parameters:
unmerged – If true, use _diffrn_refln loop; otherwise use _refln.
-
inline bool is_merged() const¶
Check if active loop is merged reflection data.
-
inline bool is_unmerged() const¶
Check if active loop is unmerged reflection data (deprecated).
-
inline std::vector<std::string> column_labels() const¶
Get list of column labels (without category prefix).
- Returns:
Vector of tag names from the active loop.
-
inline int find_column_index(const std::string &tag) const¶
Find column index by tag name (without category prefix).
- Parameters:
tag – Column name (e.g., “index_h”, “F_meas_sigma_au”).
- Returns:
Column index, or -1 if not found.
-
inline size_t get_column_index(const std::string &tag) const¶
Get column index by tag name, throwing exception if not found.
-
template<typename T>
inline std::vector<T> make_vector(const std::string &tag, T null) const¶ Extract column values as typed vector.
- Template Parameters:
T – Value type (e.g., int, double).
- Parameters:
tag – Column name.
null – Default value for missing data.
- Returns:
Vector of converted values.
-
inline std::array<size_t, 3> get_hkl_column_indices() const¶
Get column indices for h, k, l indices.
- Returns:
Array of 3 column indices for index_h, index_k, index_l.
-
inline std::vector<Miller> make_miller_vector() const¶
Extract Miller indices from all reflections.
- Returns:
Vector of Miller indices.
Public Members
-
const SpaceGroup *spacegroup = nullptr¶
Pointer to space group; nullptr if unknown.
-
double wavelength¶
X-ray wavelength in Angstroms (0 if multiple wavelengths).
-
int wavelength_count¶
Number of wavelengths in the data block.
-
ReflnBlock() = default¶
-
struct ReflnDataProxy¶
- #include <gemmi/refln.hpp>
Generic data source abstraction over a ReflnBlock for row iteration.
Provides uniform interface for accessing reflection columns (similar to MtzDataProxy).
Public Types
-
using num_type = double¶
Numeric value type.
Public Functions
-
inline explicit ReflnDataProxy(const ReflnBlock &rb)¶
Initialize proxy from a ReflnBlock.
-
inline size_t stride() const¶
Number of columns (values per reflection).
-
inline size_t size() const¶
Total number of values (stride * reflection count).
-
inline double get_num(size_t n) const¶
Get numeric value at flattened loop index.
-
inline const SpaceGroup *spacegroup() const¶
Get spacegroup.
Public Members
-
const ReflnBlock &rb_¶
Reference to underlying ReflnBlock.
-
using num_type = double¶
-
inline std::vector<ReflnBlock> as_refln_blocks(std::vector<cif::Block> &&blocks)¶
Convert structure factor data from mmCIF to MTZ format.
Provides CifToMtz for converting reflection data from PDB/mmCIF format to CCP4 MTZ binary format. Handles both merged and unmerged data, including anomalous and old-style anomalous structures.
-
namespace gemmi
Functions
-
inline bool possible_old_style(const ReflnBlock &rb, DataType data_type)¶
Check if reflection block uses old-style anomalous data format.
“Old-style” anomalous or unmerged data is expected to have only these tags: index_h/k/l, wavelength_id, crystal_id, scale_group_code, status, and either (intensity_meas/sigma) or (F_meas_au/sigma).
- Parameters:
rb – ReflnBlock to check
data_type – Expected data type (Unmerged or Anomalous)
- Returns:
true if all tags in the reflection loop match the old-style subset
-
inline cif::Loop transcript_old_anomalous_to_standard(const cif::Loop &loop, const SpaceGroup *sg)¶
Convert old-style anomalous data to modern PDBx format.
Before _refln.pdbx_F_plus/minus was introduced, anomalous data was stored as two F_meas_au reflections, e.g. (1,1,3) and (-1,-1,-3). This function transcribes it to the modern PDBx/mmCIF storage:
_refln.F_meas_au → pdbx_F_plus / pdbx_F_minus
_refln.F_meas_sigma_au → pdbx_F_plus_sigma / pdbx_F_minus_sigma
_refln.intensity_meas/sigma → pdbx_I_plus/I_minus and sigmas
Reflections are moved to the ASU, and when both +/- forms exist for the same HKL, they are merged (missing values set to ‘.’).
- Parameters:
loop – CIF loop containing old-style anomalous data
sg – Space group for ASU determination (null → P1)
- Returns:
New loop with reflections in standard pdbx format
-
struct CifToMtz¶
- #include <gemmi/cif2mtz.hpp>
Converter from CIF reflection data to MTZ format.
Handles conversion of structure factor data from mmCIF format (PDB/wwPDB standard) to MTZ format (CCP4 binary format). Supports both merged and unmerged reflection data, with configurable column mappings from CIF _refln tags to MTZ column labels and types.
Uses a specification (default or custom) to map CIF tags to MTZ columns, handling code-to-number translation for categorical data (e.g., FreeR flags).
Public Functions
-
inline Mtz convert_block_to_mtz(const ReflnBlock &rb, Logger &logger) const¶
Convert a single mmCIF reflection block to MTZ format.
Maps CIF _refln columns to MTZ columns using the specification (custom or default). Handles merged and unmerged data differently:
Merged data: Creates a single dataset with wavelength from ReflnBlock.
Unmerged data: Extracts diffrn_id and pdbx_image_id to create BATCH column, creates a dataset per crystal, and uses UnmergedHklMover to put HKLs into ASU.
Missing values (‘.’ in CIF) become NAN in MTZ. The M/ISYM and BATCH columns are automatically added for unmerged data.
-
inline Mtz auto_convert_block_to_mtz(ReflnBlock &rb, Logger &logger, char mode) const¶
Auto-detect data type and convert with optional transformation.
Performs intelligent detection and conversion:
Mode ‘f’ (fix old-style anomalous): If the block contains old-style anomalous data, transforms it to modern pdbx_F_plus/minus format before conversion.
Mode ‘a’ (auto-detect anomalous): After conversion, analyzes the unique HKLs under symmetry to detect if data is actually anomalous or unmerged despite initial classification. Logs warnings and attempts recovery for old-style data.
Other modes: Performs conversion as-is without transformation.
- Parameters:
rb – Reflection block (modified in-place if transformation occurs)
logger – Logger for notes and errors
mode – Conversion mode: ‘f’=fix old anomalous, ‘a’=auto-detect, other=no transform
- Returns:
Converted MTZ structure
Public Members
-
bool force_unmerged = false¶
If true, treat all data as unmerged.
- std::vector< std::string > history = { "From gemmi-cif2mtz " GEMMI_VERSION }
Historical entries to include in MTZ history; defaults to version line.
-
double wavelength = NAN¶
Override wavelength (NAN = auto-detect)
-
std::vector<std::string> spec_lines¶
Custom column specification lines; if empty, uses default_spec()
Public Static Functions
-
static inline const char **default_spec(bool for_merged)¶
Get the default column mapping specification.
Returns static arrays of mapping lines. Each line has format:
cif_tag mtz_label col_type dataset_id [code_mapping]where code_mapping (optional) is a comma-separated list ofcode=valuepairs.For merged data: includes FreeR_flag, intensities, structure factors, anomalous pairs, calculated phases, and weight/FOM columns.
For unmerged data: includes intensity_meas, detector coordinates, and rotation angle.
- Parameters:
for_merged – true for merged data, false for unmerged
- Returns:
Pointer to null-terminated array of specification strings
Private Static Functions
-
static inline float status_to_freeflag(const std::string &str)¶
Convert _refln.status code to FreeR_flag value.
Maps status codes to numeric equivalents:
’o’ or quoted ‘o’ → 1.0 (observed/working set)
’f’ or quoted ‘f’ → 0.0 (free set)
other → NAN
- Parameters:
str – Status code string from CIF
- Returns:
Numeric flag value (1.0, 0.0, or NAN)
-
struct Entry¶
- #include <gemmi/cif2mtz.hpp>
Specification entry mapping a CIF tag to an MTZ column.
Public Functions
-
inline Entry(const std::string &line)¶
Parse a specification line into an Entry.
Expected format:
cif_tag mtz_label col_type dataset_idcif_tag mtz_label col_type dataset_id code1=val1,code2=val2
-
inline float translate_code_to_number(const std::string &v) const¶
Translate a categorical value to its numeric equivalent.
Uses code_to_number mappings to convert coded values (e.g., ‘o’, ‘f’) to numeric equivalents (e.g., 1.0, 0.0 for FreeR flags).
- Parameters:
v – The coded value to translate
- Returns:
Translated number, or NAN if no mapping found
-
inline Entry(const std::string &line)¶
-
inline Mtz convert_block_to_mtz(const ReflnBlock &rb, Logger &logger) const¶
-
inline bool possible_old_style(const ReflnBlock &rb, DataType data_type)¶
Converter for MTZ reflection data to SF-mmCIF format.
-
namespace gemmi
Functions
-
void write_staraniso_b_in_mmcif(const SMat33<double> &b, const std::string &entry_id, char *buf, std::ostream &os)¶
Write Starraniso B-tensor to mmCIF format.
- Parameters:
b – 3x3 symmetric B-tensor matrix.
entry_id – Entry identifier for tags.
buf – Temporary buffer for formatting.
os – Output stream.
-
void remove_appendix_from_column_names(Mtz &mtz, const Logger &logger)¶
Remove ‘_dataset_name’ appendix from MTZ column labels.
This suffix is sometimes added by CCP4i and needs removal for proper conversion.
- Parameters:
mtz – MTZ file to modify.
logger – For reporting changes.
-
bool validate_merged_mtz_deposition_columns(const Mtz &mtz, const Logger &logger)¶
Validate merged MTZ has required columns for PDB deposition.
- Parameters:
mtz – MTZ to check.
logger – For reporting results.
- Returns:
True if all required columns present.
-
bool validate_merged_intensities(Intensities &mi, Intensities &ui, bool relaxed_check, const Logger &logger)¶
Validate merged intensity data for consistency and quality.
Compares merged and unmerged intensity columns for anomalous differences and completeness. Modifies both Intensities objects.
- Parameters:
mi – Merged intensities (modified).
ui – Unmerged intensities (modified).
relaxed_check – If true, apply looser validation criteria.
logger – For reporting issues.
- Returns:
True if validation passes.
-
std::vector<SoftwareItem> get_software_from_mtz_history(const std::vector<std::string> &history)¶
Extract software information from MTZ history records.
- Parameters:
history – Vector of history strings from MTZ file.
- Returns:
Vector of SoftwareItem objects describing processing steps.
-
class MtzToCif¶
- #include <gemmi/mtz2cif.hpp>
Converts MTZ files (merged or unmerged) to SF-mmCIF reflection tables.
This class provides configuration options for column selection, naming, filtering, and metadata handling when converting MTZ format to mmCIF.
Public Functions
-
void write_cif(const Mtz &mtz, const Mtz *mtz2, SMat33<double> *staraniso_b, std::ostream &os)¶
Write MTZ reflection data to CIF format.
- Parameters:
mtz – First MTZ dataset (required).
mtz2 – Optional second MTZ dataset for anomalous comparison.
staraniso_b – Optional Starraniso B-tensor to include.
os – Output stream for CIF file.
Public Members
-
std::vector<std::string> spec_lines¶
Column conversion specification lines (see default_spec for format).
-
const char *block_name = nullptr¶
CIF data block name (NAME in data_NAME).
-
bool with_comments = true¶
Whether to write comments describing the conversion.
-
bool with_history = true¶
Whether to write MTZ history records in comments.
-
bool skip_empty = false¶
Skip reflections where all selected numeric columns are missing.
-
bool skip_negative_sigi = false¶
Skip unmerged reflections with sigma(I) < 0.
-
bool enable_UB = false¶
Write _diffrn_orient_matrix.UB orientation matrix.
-
bool write_staraniso_tensor = true¶
Write reflns.pdbx_aniso_B_tensor* Starraniso B-tensor (if available).
-
bool write_special_marker_for_pdb = false¶
Write PDB-specific special marker for validation.
-
int less_anomalous = 0¶
If non-zero, skip anomalous (+/-) column pairs.
-
std::string skip_empty_cols¶
Columns used to determine if reflection is “empty” (when skip_empty=true).
-
double wavelength = NAN¶
User-specified wavelength (NAN means use MTZ value).
-
int trim = 0¶
Trim reflections: output only those with -N<=h,k,l<=N (0 = no trim).
-
int free_flag_value = -1¶
Free flag value: -1=auto, 0 or 1=explicit.
Public Static Functions
-
static inline const char **default_spec(bool for_merged)¶
Get default column specification for merged or unmerged data.
The returned spec_lines describe MTZ-to-mmCIF column mapping. Format: [?|&|$|H][COLUMN_NAME] [TYPE] [mmCIF_TAG] [FORMAT]
? = optional column (try alternatives separated by |)
& = required, uses previous column’s result
$ = internal (dataset_id, counter)
H = required by IUCR standard
- Parameters:
for_merged – If true, return spec for merged data; else unmerged.
- Returns:
Null-terminated array of spec strings.
-
void write_cif(const Mtz &mtz, const Mtz *mtz2, SMat33<double> *staraniso_b, std::ostream &os)¶
-
void write_staraniso_b_in_mmcif(const SMat33<double> &b, const std::string &entry_id, char *buf, std::ostream &os)¶
Reader for XDS_ASCII.HKL and INTEGRATE.HKL reflection files.
-
namespace gemmi
Functions
-
inline bool likely_in_house_source(double wavelength)¶
Check if wavelength likely comes from in-house X-ray source.
Based on Pointless documentation; recognizes Cu, Mo, and Cr K-alpha wavelengths with their typical uncertainties.
- Parameters:
wavelength – Wavelength in Angstroms.
- Returns:
True if wavelength matches Cu, Mo, or Cr.
-
struct XdsAscii : public gemmi::XdsAsciiMetadata¶
- #include <gemmi/xds_ascii.hpp>
Container for XDS reflection data (XDS_ASCII.HKL or INTEGRATE.HKL).
Stores integration metadata and per-reflection measurements from XDS output. Supports both merged and unmerged data depending on read_columns value.
Public Functions
-
XdsAscii() = default¶
Default constructor.
-
inline XdsAscii(const XdsAsciiMetadata &m)¶
Construct with existing metadata.
-
inline Iset &find_or_add_iset(int id)¶
Get existing or create new integration set.
- Parameters:
id – Integration set ID.
- Returns:
Reference to Iset with given ID.
-
void read_stream(AnyStream &reader, const std::string &source)¶
Read XDS file from stream.
- Parameters:
reader – Input stream handler.
source – File path (for error messages).
-
template<typename T>
inline void read_input(T &&input)¶ Read XDS file from input object (file or stdin).
- Template Parameters:
T – Input object with create_stream() and path() methods.
- Parameters:
input – Input object.
-
inline bool is_merged() const¶
Check if data is merged (few columns in XDS file).
- Returns:
True if read_columns < 8 (no per-reflection BATCH info).
-
void gather_iset_statistics()¶
Calculate frame number statistics for each integration set.
Sets frame_number_min, frame_number_max, frame_count, and reflection_count for each Iset.
-
inline double rot_angle(const Refl &refl) const¶
Calculate rotation angle for a reflection.
- Parameters:
refl – Reflection record with zd frame number.
- Returns:
Rotation angle in degrees.
-
inline bool has_cell_axes() const¶
Check if reciprocal lattice vectors (cell_axes) are set.
- Returns:
True if all 3 reciprocal axes are non-zero.
-
inline Mat33 calculate_conversion_from_cambridge() const¶
Calculate transformation matrix from Cambridge frame to XDS frame.
Cambridge frame: z along rotation axis, x along incident beam.
-
void apply_polarization_correction(double p, Vec3 normal)¶
Apply polarization correction to all intensities and sigmas.
Based on incident beam direction, rotation axis, and polarization plane. Assumes XDS file has unpolarized beam correction already applied.
- Parameters:
p – Degree of polarization in [0, 1] (0.5 for unpolarized).
normal – Normal vector to polarization plane.
-
inline void eliminate_overloads(double overload)¶
Remove reflections with peak pixel value exceeding threshold.
- Parameters:
overload – Maximum allowed MAXC pixel value.
-
inline void eliminate_batchmin(int batchmin)¶
Remove reflections with frame number below threshold.
- Parameters:
batchmin – Minimum frame number to keep.
-
struct Refl¶
- #include <gemmi/xds_ascii.hpp>
One reflection record from XDS data.
Public Functions
-
inline int frame() const¶
Get frame number (rounded up from zd).
- Returns:
Frame number (zd is negative-friendly).
Public Members
-
int iset = 1¶
Integration set ID (dataset number).
-
double iobs¶
Integrated intensity.
-
double sigma¶
Standard deviation of iobs.
-
double xd¶
Detector position x (mm).
-
double yd¶
Detector position y (mm).
-
double zd¶
Frame number (zd) relative to starting frame (can be negative).
-
double rlp¶
Reciprocal lattice point (RLP) value; related to partiality.
-
double peak¶
Peak intensity percentage (0-10000 for 0-100%).
-
double corr¶
Correction factor (Lorentz-polarization etc; usually 100-150).
-
double maxc¶
Maximum pixel value in reflection.
-
inline int frame() const¶
-
XdsAscii() = default¶
-
struct XdsAsciiMetadata¶
- #include <gemmi/xds_ascii.hpp>
Metadata for XDS reflection data (base class).
Subclassed by gemmi::XdsAscii
Public Members
-
int read_columns = 0¶
Number of columns read from DATA section (0-13, excludes ITEM_ISET from XSCALE).
-
int spacegroup_number = 0¶
Space group number from XDS_ASCII header.
-
double wavelength = 0.¶
X-ray wavelength in Angstroms.
-
std::array<double, 6> cell_constants = {0., 0., 0., 0., 0., 0.}¶
Unit cell constants [a, b, c, alpha, beta, gamma].
-
double oscillation_range = 0.¶
Oscillation range per frame in degrees.
-
double starting_angle = 0.¶
Starting angle for rotation in degrees.
-
double reflecting_range_esd = 0.¶
Mosaicity/reflecting range standard deviation in degrees.
-
char friedels_law = '\0'¶
Friedel’s law assumption: ‘\0’ unknown, ‘T’rue, ‘F’alse.
-
int starting_frame = 1¶
First frame number.
-
int nx = 0¶
Detector width in pixels.
-
int ny = 0¶
Detector height in pixels.
-
double qx = 0.¶
Pixel size in x-direction (mm).
-
double qy = 0.¶
Pixel size in y-direction (mm).
-
double orgx = 0.¶
Detector origin in x-direction (mm).
-
double orgy = 0.¶
Detector origin in y-direction (mm).
-
double detector_distance = 0.¶
Distance from sample to detector (mm).
-
struct Iset¶
- #include <gemmi/xds_ascii.hpp>
Properties of one integration set (dataset/sweep).
Public Members
-
int id¶
Integration set ID.
-
double wavelength = 0.¶
Wavelength in Angstroms (0 if not specified).
-
std::array<double, 6> cell_constants = {0., 0., 0., 0., 0., 0.}¶
Unit cell constants [a, b, c, alpha, beta, gamma].
-
int frame_number_min = -1¶
Minimum frame number (set by gather_iset_statistics).
-
int frame_number_max = -1¶
Maximum frame number (set by gather_iset_statistics).
-
int frame_count = -1¶
Total number of distinct frames in set.
-
int reflection_count = -1¶
Number of reflections in this set.
-
int id¶
-
int read_columns = 0¶
-
inline bool likely_in_house_source(double wavelength)¶
Converter for XDS reflection data to MTZ format.
-
namespace gemmi
Functions
-
inline Mtz xds_to_mtz(XdsAscii &xds)¶
Convert XDS reflection data to MTZ format.
For unmerged data, creates unmerged MTZ with batch headers matching Pointless output. For merged data, uses Intensities class to prepare merged MTZ. Sets up all standard MTZ columns: H, K, L, M/ISYM, BATCH, I, SIGI, XDET, YDET, ROT, plus optional FRACTIONCALC, LP, CORR, and MAXC columns depending on XDS read_columns.
- Parameters:
xds – XDS data to convert (modified).
- Returns:
Populated MTZ object sorted by reflection index.
-
inline Mtz xds_to_mtz(XdsAscii &xds)¶
Intensities class for reading and merging intensity data from various formats.
-
namespace gemmi
Enums
-
enum class DataType¶
Data type of intensity data: unmerged, mean intensity, or anomalous intensities.
When requesting a particular data type, the MergedMA/MergedAM/UAM variants allow fallback to secondary options (e.g., MergedMA = Mean if available, else Anomalous).
Values:
-
enumerator Unknown¶
Unknown or unspecified intensity type.
-
enumerator Unmerged¶
Unmerged (multi-record) intensity data.
-
enumerator Mean¶
Mean intensity
-
enumerator Anomalous¶
Anomalous intensities (I+/I-)
-
enumerator MergedMA¶
Mean if available, otherwise Anomalous (fallback type)
-
enumerator MergedAM¶
Anomalous if available, otherwise Mean (fallback type)
-
enumerator UAM¶
Unmerged if available, otherwise MergedAM (fallback type)
-
enumerator Unknown¶
Functions
-
std::string read_staraniso_b_from_mtz(const Mtz &mtz, SMat33<double> &output)¶
Extract STARANISO anisotropy B-tensor from MTZ file.
- Parameters:
mtz – MTZ file object to read from.
output – Anisotropic B-tensor (3x3 symmetric matrix in Voigt notation).
- Returns:
STARANISO version string if found, empty string otherwise.
-
template<typename DataProxy>
std::pair<DataType, size_t> check_data_type_under_symmetry(const DataProxy &proxy)¶ Infer intensity data type from reflection data under symmetry.
Examines unique reflections and detects whether data is unmerged (multiple copies of same HKL), mean intensity (single copy), or anomalous (both I+/I-).
- Template Parameters:
DataProxy – Type with spacegroup(), unit_cell(), size(), stride(), get_hkl() interface.
- Parameters:
proxy – Data proxy object to analyze.
- Returns:
Pair of (inferred DataType, number of unique HKLs in ASU).
-
struct Intensities¶
- #include <gemmi/intensit.hpp>
Container for intensity data from reflection measurements.
Stores multi-record (unmerged) or merged intensities with metadata such as unit cell, space group, and wavelength. Supports merging operations and import from MTZ, mmCIF, and XDS_ASCII formats.
Public Functions
-
inline const char *type_str() const¶
Get string representation of this object’s intensity data type.
-
std::array<double, 2> resolution_range() const¶
Get minimum and maximum resolution of reflections.
- Returns:
{d_max, d_min} as array of two doubles.
-
Correlation calculate_correlation(const Intensities &other) const¶
Calculate correlation of intensity values between two sorted lists.
- Parameters:
other – Another Intensities object to correlate with.
- Returns:
Correlation object with matching reflections analyzed.
-
inline void add_if_valid(const Miller &hkl, int8_t isign, int8_t isym, double value, double sigma)¶
Add a single reflection if its data is valid. Skips reflections with NaN or non-positive sigma (rejected by XDS, etc.).
- Parameters:
hkl – Miller indices
isign – Intensity sign (1 for I+, -1 for I-, 0 for mean)
isym – Symmetry operator encoding
value – Intensity value
sigma – Standard deviation of intensity
-
inline void remove_systematic_absences()¶
Remove reflections that are forbidden by space group symmetry.
-
inline void sort()¶
Sort reflections by (h, k, l, isign) in ascending order.
-
void merge_in_place(DataType new_type)¶
Merge reflections in-place to a specified data type (mean or anomalous).
- Parameters:
new_type – Target data type for merged intensities.
-
inline Intensities merged(DataType new_type)¶
Create a merged copy without modifying this object.
- Parameters:
new_type – Target data type for merged intensities.
- Returns:
New Intensities object with merged data.
-
std::vector<MergingStats> calculate_merging_stats(const Binner *binner, char use_weights = 'Y') const¶
Calculate R-merge and related statistics for each resolution shell.
- Parameters:
binner – Resolution shell binning (or nullptr for all data in one shell).
use_weights – Weighting scheme: ‘Y’=Aimless style, ‘U’=unweighted, ‘X’=XDS style.
- Returns:
Vector of MergingStats, one per shell.
-
DataType prepare_for_merging(DataType new_type)¶
Prepare data for merging and classify anomalous/mean component. Call with DataType::Anomalous before calculate_merging_stats() to get I+/I- stats.
- Parameters:
new_type – Target data type.
- Returns:
Classified data type after preparation.
-
void switch_to_asu_indices()¶
Convert unmerged ISYM indices to ASU indices using stored isym_ops.
-
void import_unmerged_intensities_from_mtz(const Mtz &mtz)¶
Load unmerged intensities from MTZ file.
- Parameters:
mtz – MTZ object to read from.
-
void import_mean_intensities_from_mtz(const Mtz &mtz)¶
Load mean intensities from MTZ file.
- Parameters:
mtz – MTZ object to read from.
-
void import_anomalous_intensities_from_mtz(const Mtz &mtz, bool check_complete = false)¶
Load anomalous intensities (I+/I-) from MTZ file.
- Parameters:
mtz – MTZ object to read from.
check_complete – If true, throw if anomalous data is null where expected.
-
void import_mtz(const Mtz &mtz, DataType data_type = DataType::Unknown)¶
Load intensities from MTZ file, auto-detecting data type.
- Parameters:
mtz – MTZ object to read from.
data_type – Requested data type; DataType::Unknown auto-detects.
-
void import_unmerged_intensities_from_mmcif(const ReflnBlock &rb)¶
Load unmerged intensities from mmCIF reflection block.
- Parameters:
rb – Reflection block to read from.
-
void import_mean_intensities_from_mmcif(const ReflnBlock &rb)¶
Load mean intensities from mmCIF reflection block.
- Parameters:
rb – Reflection block to read from.
-
void import_anomalous_intensities_from_mmcif(const ReflnBlock &rb, bool check_complete = false)¶
Load anomalous intensities (I+/I-) from mmCIF reflection block.
- Parameters:
rb – Reflection block to read from.
check_complete – If true, throw if anomalous data is null where expected.
-
void import_f_squared_from_mmcif(const ReflnBlock &rb)¶
Load structure factor squared (F^2) from mmCIF reflection block.
- Parameters:
rb – Reflection block to read from.
-
void import_refln_block(const ReflnBlock &rb, DataType data_type = DataType::Unknown)¶
Load intensities from mmCIF reflection block, auto-detecting data type.
- Parameters:
rb – Reflection block to read from.
data_type – Requested data type; DataType::Unknown auto-detects.
-
void import_xds(const XdsAscii &xds)¶
Load intensities from XDS_ASCII file.
- Parameters:
xds – XDS_ASCII object to read from.
-
std::string take_staraniso_b_from_mtz(const Mtz &mtz)¶
Extract and store STARANISO B-tensor from MTZ file.
- Parameters:
mtz – MTZ object to read from.
- Returns:
STARANISO version string if found, empty string otherwise.
Public Members
-
const SpaceGroup *spacegroup = nullptr¶
Space group (not owned by this object)
-
double unit_cell_rmsd[6] = {0., 0., 0., 0., 0., 0.}¶
RMSDs of unit cell parameters.
-
double wavelength¶
Diffraction wavelength in Angstroms.
-
AnisoScaling staraniso_b¶
STARANISO anisotropy correction tensor.
Public Static Functions
-
struct AnisoScaling¶
- #include <gemmi/intensit.hpp>
Anisotropic scaling tensor for STARANISO B-factor correction.
Public Functions
-
inline bool ok() const¶
Check if anisotropic tensor is set (non-zero).
-
inline bool ok() const¶
-
inline const char *type_str() const¶
-
struct IntensitiesDataProxy¶
- #include <gemmi/intensit.hpp>
Adapter providing DataProxy interface to Intensities data. Enables use of Intensities with generic algorithms expecting standard data proxy interface.
Public Functions
-
inline size_t stride() const¶
-
inline size_t size() const¶
-
inline const SpaceGroup *spacegroup() const¶
-
inline double get_num(size_t n) const¶
Public Members
-
const Intensities &intensities_¶
Reference to underlying Intensities object.
-
inline size_t stride() const¶
-
struct MergingStats¶
- #include <gemmi/intensit.hpp>
Statistics calculated for a resolution shell (bin) of merged intensities.
Accumulates numerators and denominators for R-merge, R-meas, and R-pim. Can be summed across shells to compute overall statistics.
Public Functions
-
inline void add_other(const MergingStats &o)¶
Accumulate statistics from another shell.
- Parameters:
o – Statistics from another resolution shell. Adding two MergingStats gives the same result as calculating statistics for the combined shells from the start.
-
inline double r_merge() const¶
Compute R-merge for this shell.
-
inline double r_meas() const¶
Compute redundancy-weighted R-meas for this shell.
-
inline double r_pim() const¶
Compute precision-indicating R-pim for this shell.
-
double cc_half() const¶
Compute CC1/2 (correlation coefficient of half-datasets).
-
inline double cc_full() const¶
Compute CC* using Spearman-Brown prediction formula from CC1/2.
-
inline double cc_star() const¶
Estimate of overall correlation coefficient from CC1/2.
Public Members
-
int all_refl = 0¶
Total number of observations (all reflections)
-
int unique_refl = 0¶
Number of unique reflections.
-
int stats_refl = 0¶
Unique reflections with 2+ observations (for statistics)
-
double r_merge_num = 0¶
Numerator for R-merge calculation.
-
double r_meas_num = 0¶
Numerator for R-meas (redundancy-weighted) calculation.
-
double r_pim_num = 0¶
Numerator for R-pim (precision-indicating merge) calculation.
-
double r_denom = 0¶
Denominator for R-merge/meas/pim calculations.
-
double sum_ibar = 0¶
Sum of mean intensities for CC1/2.
-
double sum_ibar2 = 0¶
Sum of squared mean intensities for CC1/2.
-
double sum_sig2_eps = 0¶
Sum of variance terms for CC1/2.
-
inline void add_other(const MergingStats &o)¶
-
namespace cif
Read CIF data from a string.
This function was moved here from cif.hpp to speed up compilation.
- Param data:
CIF-formatted string
- Param check_level:
Syntax checking level (0=none, 1=moderate, 2=strict)
- Return:
Parsed CIF document
-
enum class DataType¶
Binner class for organizing reflections into resolution shells.
-
namespace gemmi
-
struct Binner¶
- #include <gemmi/binner.hpp>
Divide reflections into resolution shells (bins) for statistics.
Organizes reflection data into bins by resolution. Supports multiple binning schemes (equal count, linear/quadratic/cubic in d or 1/d^2). Provides fast bin lookup for both sorted and unsorted data.
Public Types
-
enum class Method¶
Strategy for dividing reflections into resolution shells.
Values:
-
enumerator EqualCount¶
Bins with approximately equal number of reflections.
-
enumerator Dstar¶
Linear spacing in 1/d (resolution)
-
enumerator Dstar2¶
Linear spacing in 1/d^2 (squared reciprocal spacing)
-
enumerator Dstar3¶
Cubic spacing (linear in (1/d^2)^(1/3))
-
enumerator EqualCount¶
Public Functions
-
inline void setup_from_1_d2(int nbins, Method method, std::vector<double> &&inv_d2, const UnitCell *cell_)¶
Set up bins using pre-calculated 1/d^2 values.
- Parameters:
nbins – Number of resolution bins to create.
method – Binning scheme (EqualCount, Dstar, Dstar2, Dstar3).
inv_d2 – Vector of 1/d^2 values for all reflections (moved from caller).
cell_ – Unit cell for resolution calculations (nullptr uses already-set cell).
-
template<typename DataProxy>
inline void setup(int nbins, Method method, const DataProxy &proxy, const UnitCell *cell_ = nullptr, size_t col_idx = 0)¶ Set up bins from reflection data using DataProxy interface. Automatically calculates 1/d^2 values from HKLs and unit cell.
- Template Parameters:
DataProxy – Type with spacegroup(), unit_cell(), size(), stride(), get_hkl(), get_num() interface.
- Parameters:
nbins – Number of resolution bins to create.
method – Binning scheme (EqualCount, Dstar, Dstar2, Dstar3).
proxy – Data proxy object (typically Intensities or MTZ).
cell_ – Unit cell for resolution calculations (nullptr uses proxy.unit_cell()).
col_idx – Column index for filtering NaN values (0 = skip filtering).
-
inline void ensure_limits_are_set() const¶
Check that bins have been set up; throw if not.
-
inline int get_bin_from_1_d2(double inv_d2)¶
Find bin index for a given 1/d^2 value (binary search, generic).
- Parameters:
inv_d2 – Squared reciprocal resolution (1/d^2).
- Returns:
Bin index (0 to size()-1).
-
inline int get_bin(const Miller &hkl)¶
Find bin index for a reflection by Miller indices.
- Parameters:
hkl – Miller indices (h,k,l).
- Returns:
Bin index (0 to size()-1).
-
inline int get_bin_from_1_d2_hinted(double inv_d2, int &hint) const¶
Find bin index using a hint (fast path for sorted reflections). Updates hint to the found bin index for the next call. Assumes sorted reflections: each bin is same or next to previous.
- Parameters:
inv_d2 – Squared reciprocal resolution (1/d^2).
hint – In/out: previous bin index (input), current bin index (output).
- Returns:
Bin index (0 to size()-1).
-
inline int get_bin_hinted(const Miller &hkl, int &hint) const¶
Find bin index for a reflection using a hint (fast path).
- Parameters:
hkl – Miller indices (h,k,l).
hint – In/out: previous bin index (input), current bin index (output).
- Returns:
Bin index (0 to size()-1).
-
template<typename DataProxy>
inline std::vector<int> get_bins(const DataProxy &proxy) const¶ Get bin indices for all reflections in a DataProxy. Uses hinting for fast processing of sorted data.
- Template Parameters:
DataProxy – Type with size(), stride(), get_hkl() interface.
- Parameters:
proxy – Data proxy object.
- Returns:
Vector of bin indices (length = proxy.size() / proxy.stride()).
-
inline std::vector<int> get_bins_from_1_d2(const double *inv_d2, size_t size) const¶
Get bin indices for an array of 1/d^2 values. Uses hinting for fast processing of sorted data.
- Parameters:
inv_d2 – Pointer to array of squared reciprocal resolutions.
size – Number of values in array.
- Returns:
Vector of bin indices (length = size).
-
inline std::vector<int> get_bins_from_1_d2(const std::vector<double> &inv_d2) const¶
Get bin indices for a vector of 1/d^2 values.
- Parameters:
inv_d2 – Vector of squared reciprocal resolutions.
- Returns:
Vector of bin indices (length = inv_d2.size()).
-
inline double dmin_of_bin(int n) const¶
Get minimum resolution (highest 1/d^2) of a bin.
- Parameters:
n – Bin index (0 to size()-1).
- Returns:
Minimum resolution d in Angstroms (highest angle, tightest spacing).
-
inline double dmax_of_bin(int n) const¶
Get maximum resolution (lowest 1/d^2) of a bin.
- Parameters:
n – Bin index (0 to size()-1).
- Returns:
Maximum resolution d in Angstroms (lowest angle, loosest spacing).
-
inline size_t size() const¶
Number of bins (resolution shells).
-
enum class Method¶
-
struct Binner¶
AsuData template for storing per-HKL reflection data in asymmetric unit.
-
namespace gemmi
Functions
-
template<typename Func, typename T>
void for_matching_reflections(const std::vector<T> &a, const std::vector<T> &b, const Func &func)¶ Apply a function to matching reflections from two sorted lists. Iterates through reflections with matching HKLs in both lists and calls func.
- Template Parameters:
Func – Callable type taking (const T&, const T&).
T – Reflection data type (must have hkl member and operator<).
- Parameters:
a – First reflection list.
b – Second reflection list.
func – Function to call for each matching pair.
- Pre:
Vectors a and b are sorted by HKL.
-
template<typename T>
Correlation calculate_hkl_value_correlation(const std::vector<T> &a, const std::vector<T> &b)¶ Calculate correlation of intensity values between two sorted lists.
- Template Parameters:
T – Reflection data type (must have hkl and value members).
- Parameters:
a – First reflection list.
b – Second reflection list.
- Pre:
Vectors a and b are sorted by HKL.
- Returns:
Correlation object computed from matching HKLs.
-
template<typename T>
ComplexCorrelation calculate_hkl_complex_correlation(const std::vector<T> &a, const std::vector<T> &b)¶ Calculate correlation of complex-valued reflection data between two sorted lists.
- Template Parameters:
T – Reflection data type (must have hkl and value members).
- Parameters:
a – First reflection list.
b – Second reflection list.
- Pre:
Vectors a and b are sorted by HKL.
- Returns:
ComplexCorrelation object computed from matching HKLs.
-
template<typename T>
int count_equal_values(const std::vector<T> &a, const std::vector<T> &b)¶ Count matching reflections with identical values in two sorted lists.
- Template Parameters:
T – Reflection data type (must have hkl and value members).
- Parameters:
a – First reflection list.
b – Second reflection list.
- Pre:
Vectors a and b are sorted by HKL.
- Returns:
Number of matching HKLs with equal values.
-
template<typename T, int N, typename Data>
AsuData<T> make_asu_data(const Data &data, const std::array<std::string, N> &labels, bool as_is = false)¶ Create AsuData by loading from N columns in a data source.
- Template Parameters:
T – Value type to load into.
N – Number of columns to combine per reflection.
Data – Data source type (MTZ, mmCIF, etc.).
- Parameters:
data – Source data object.
labels – Array of N column labels to load.
as_is – If true, skip ASU conversion and sorting.
- Returns:
New AsuData object populated with data.
-
template<typename T, typename Data>
AsuData<T> make_asu_data(const Data &data, const std::string &label, bool as_is)¶ Create AsuData by loading from a single column in a data source.
- Template Parameters:
T – Value type to load into.
Data – Data source type (MTZ, mmCIF, etc.).
- Parameters:
data – Source data object.
label – Column label to load.
as_is – If true, skip ASU conversion and sorting.
- Returns:
New AsuData object populated with data.
-
template<typename T>
void discard_by_sigma_ratio(AsuData<ValueSigma<T>> &asu_data, double cutoff)¶ Filter AsuData to retain only reflections with high signal-to-noise. Removes reflections where sigma <= 0 or value/sigma < cutoff.
- Template Parameters:
T – Numeric type (float, double).
- Parameters:
asu_data – AsuData container with ValueSigma<T> values (in/out).
cutoff – Minimum value/sigma ratio to retain.
-
template<typename T>
struct AsuData¶ - #include <gemmi/asudata.hpp>
Generic container for reflection data in asymmetric unit. Stores values (e.g., structure factors, phases, intensities) indexed by Miller indices. Keeps data sorted by HKL and can enforce ASU constraints.
- Template Parameters:
T – Value type (float, double, complex, ValueSigma<>, etc.).
Public Functions
-
inline size_t stride() const¶
-
inline size_t size() const¶
-
inline double get_f(size_t n) const¶
-
inline double get_phi(size_t n) const¶
-
inline const SpaceGroup *spacegroup() const¶
-
inline void ensure_sorted()¶
Sort reflections by HKL indices if not already sorted.
-
inline void ensure_asu(bool tnt_asu = false)¶
Transform all reflections to the asymmetric unit. Moves reflections outside ASU to their equivalent inside, applying symmetry operators and phase shifts as needed for complex values.
- Parameters:
tnt_asu – If true, use TNT-style ASU; otherwise use standard ASU.
-
template<typename DataProxy>
inline void load_values(const DataProxy &proxy, const std::string &label, bool as_is = false)¶ Load values from a single data column. Reads HKLs and values from proxy, filters NaN, converts to ASU, and sorts.
- Template Parameters:
DataProxy – Type with column_index(), unit_cell(), spacegroup(), size(), stride(), get_hkl(), get_num() interface.
- Parameters:
proxy – Data proxy object (MTZ, mmCIF, etc.).
label – Column name/label to load.
as_is – If true, skip ASU conversion and sorting (raw load).
-
template<int N, typename DataProxy>
inline void load_values(const DataProxy &proxy, const std::array<std::string, N> &labels, bool as_is = false)¶ Load values from multiple columns (for complex, vector, or sigma pairs). Reads N columns per reflection and combines them into a single value. Filters out reflections with any NaN in the N columns.
- Template Parameters:
N – Number of columns to load (2 for complex/F+sigma, etc.).
DataProxy – Type with column_index(), unit_cell(), spacegroup(), size(), stride(), get_hkl(), get_num() interface.
- Parameters:
proxy – Data proxy object (MTZ, mmCIF, etc.).
labels – Array of N column names/labels to load.
as_is – If true, skip ASU conversion and sorting (raw load).
Public Members
-
const SpaceGroup *spacegroup_ = nullptr¶
Space group (not owned by this object)
Private Static Functions
-
static inline void set_value_from_array(T &val, const std::array<T, 1> &nums)¶
Helper to convert numeric array(s) to T. Overloaded for: scalar, array<1>, complex (F+phase), ValueSigma (F+sigma).
-
template<typename R>
static inline void set_value_from_array(std::complex<R> &val, const std::array<R, 2> &nums)¶ Convert (F, phi) pair to complex structure factor.
-
template<typename R>
static inline void set_value_from_array(ValueSigma<R> &val, const std::array<R, 2> &nums)¶ Convert (value, sigma) pair to ValueSigma.
-
struct ComplexCorrelation¶
- #include <gemmi/asudata.hpp>
Correlation calculation for complex-valued reflection data. Accumulates running statistics for complex numbers (e.g., structure factors).
Public Functions
-
inline void add_point(std::complex<double> x, std::complex<double> y)¶
Add a complex-valued point pair to the correlation.
- Parameters:
x – First complex value
y – Second complex value
-
inline void add_point(std::complex<float> x, std::complex<float> y)¶
Add a complex-valued point pair (float version).
- Parameters:
x – First complex value
y – Second complex value
-
inline std::complex<double> coefficient() const¶
Compute correlation coefficient from accumulated statistics.
-
inline double mean_ratio() const¶
Compute ratio of mean magnitudes.
-
inline void add_point(std::complex<double> x, std::complex<double> y)¶
-
template<typename T>
struct HklValue¶ - #include <gemmi/asudata.hpp>
Miller index paired with a generic value. Used as the basic element in AsuData containers.
- Template Parameters:
T – Value type (float, double, complex, etc.).
Public Functions
-
template<typename T>
struct ValueSigma¶ - #include <gemmi/asudata.hpp>
Value paired with its uncertainty (sigma/standard deviation).
- Template Parameters:
T – Numeric type (float, double, etc.).
Public Functions
-
inline bool operator==(const ValueSigma &o) const¶
Check equality of both value and sigma.
-
namespace impl
Implementation functions for moving reflections to asymmetric unit.
Functions for calculating bounding boxes and extents of grid data.
-
template<typename Func, typename T>
Map and Grid Data¶
(Stub — full documentation added in PR 6.)
3D crystallographic grids for electron density maps, cell-method search, and reflection data.
This header provides template classes for regular 3D grids on a crystallographic unit cell, with support for symmetry operations, interpolation (trilinear and tricubic), and operations on grid points within specified regions or radii.
-
namespace gemmi
Enums
-
enum class AxisOrder : unsigned char
Order of grid axes relative to unit cell axes (a, b, c).
Not all functionality works with all axis orders; many operations require XYZ order. The values XYZ and ZYX are used only when the grid covers the whole unit cell.
Values:
-
enumerator Unknown
Axis order not determined.
-
enumerator XYZ
Grid axes correspond to a, b, c (default, CCP4 convention). Index X (H in reciprocal space) varies fastest; Z (or L) varies slowest.
-
enumerator ZYX
Grid axes reversed: Z varies fastest, X varies slowest. May not be fully supported everywhere.
-
enumerator Unknown
-
enum class GridSizeRounding
Strategy for rounding calculated grid dimensions to suitable values.
Values:
-
enumerator Nearest
Round to nearest value with small prime factors (2, 3, 5).
-
enumerator Up
Round up (ceil) to next value with small prime factors.
-
enumerator Down
Round down (floor) to previous value with small prime factors.
-
enumerator Nearest
Functions
-
inline int modulo(int a, int n)
Compute mathematical modulo (a mod n), always returning a value in [0, n).
- Parameters:
a – value to take modulo
n – modulus (n > 0)
- Returns:
Value in range [0, n)
-
inline bool has_small_factorization(int n)
Check if n has only small prime factors (2, 3, 5).
- Parameters:
n – Integer to check
- Returns:
True if n = 2^a * 3^b * 5^c for non-negative a, b, c
-
inline int round_with_small_factorization(double exact, GridSizeRounding rounding)
Round a value to the nearest integer with only small prime factors.
Useful for choosing FFT-friendly grid dimensions.
- Parameters:
exact – Exact floating-point value
rounding – Rounding strategy (Up, Down, or Nearest)
- Returns:
Integer >= 1 with only 2, 3, 5 as prime factors, closest to
exactper the strategy
-
inline std::array<int, 3> good_grid_size(std::array<double, 3> limit, GridSizeRounding rounding, const SpaceGroup *sg)
Compute suitable grid dimensions respecting space group symmetry and FFT efficiency.
Takes into account space group symmetry factors and symmetry-related directions (which must have equal grid sizes), and rounds to dimensions with small prime factors.
- Parameters:
limit – Target grid dimensions (approximate)
rounding – Rounding strategy for each dimension
sg – Space group constraints (may be null for P1)
- Returns:
Array of three grid dimensions {nu, nv, nw}
-
inline void check_grid_factors(const SpaceGroup *sg, std::array<int, 3> size)
Verify that grid dimensions are compatible with space group symmetry.
Checks that each dimension is divisible by the corresponding space group factor, and that symmetry-related directions have equal grid sizes.
- Parameters:
sg – Space group to validate against (may be null for P1)
size – Grid dimensions {nu, nv, nw}
- Throws:
Raises – an exception if constraints are violated
-
inline double lerp_(double a, double b, double t)
Linear interpolation (lerp) between two values.
- Parameters:
a – Start value
b – End value
t – Interpolation parameter in [0, 1]; 0 returns a, 1 returns b
- Returns:
Interpolated value a + (b - a) * t
-
template<typename T>
std::complex<T> lerp_(std::complex<T> a, std::complex<T> b, double t) Linear interpolation for complex numbers.
-
inline double cubic_interpolation(double u, double a, double b, double c, double d)
Catmull–Rom cubic spline interpolation.
Interpolates a cubic between points b and c given neighboring points a and d. Uses the Catmull–Rom formula (equation 24 in the reference below).
- References
Afonine, P.V., Poon, B.K., Read, R.J., Sobolev, O.V., Terwilliger, T.C., Urzhumtsev, A. & Adams, P.D. (2018). Real-space refinement in PHENIX for cryo-EM and crystallography. Acta Cryst. D74, 531–544. https://doi.org/10.1107/S2059798318006551
- Parameters:
u – Parameter in [0, 1], where 0 → b, 1 → c
a – Value at u = -1
b – Value at u = 0
c – Value at u = 1
d – Value at u = 2
- Returns:
Interpolated value
-
inline double cubic_interpolation_der(double u, double a, double b, double c, double d)
First derivative of cubic spline interpolation.
Computes df/du for Catmull–Rom interpolation.
- Parameters:
u – Parameter in [0, 1]
a – Value at u = -1
b – Value at u = 0
c – Value at u = 1
d – Value at u = 2
- Returns:
df/du at parameter u
-
template<typename T>
void interpolate_grid(Grid<T> &dest, const Grid<T> &src, const Transform &tr, int order = 1) Interpolate grid values from source to destination under a transformation.
For each point in the destination grid, applies the transformation and interpolates the source grid value at that location. TODO: add argument Box<Fractional> src_extent See: interpolate_grid_around_model() in solmask.hpp See: interpolate_values in python/grid.cpp
- Template Parameters:
T – Grid value type
- Parameters:
dest – Destination grid
src – Source grid
tr – Spatial transformation (rotation + translation)
order – Interpolation order: 0 (nearest), 1 (trilinear), 3 (tricubic)
-
template<typename T>
Correlation calculate_correlation(const GridBase<T> &a, const GridBase<T> &b) Calculate correlation coefficient between two grids.
Computes Pearson correlation between grid values, skipping NaN values.
- Template Parameters:
T – Grid value type
- Parameters:
a – First grid
b – Second grid
- Throws:
Raises – exception if grids have different dimensions
- Returns:
Correlation object with mean, stddev, and correlation coefficient
-
template<typename T = float>
struct Grid : public gemmi::GridBase<float> - #include <gemmi/grid.hpp>
Real-space crystallographic grid (electron density, masks, etc.).
A 3D grid covering the unit cell at regular fractional intervals. Grid points are at fractional coordinates (i/nu, j/nv, k/nw). Many operations require AxisOrder::XYZ and covering the full unit cell.
- Template Parameters:
T – Data type for grid values (default: float)
Public Functions
-
inline void copy_metadata_from(const GridMeta &g)
Copy grid metadata (cell, space group, dimensions, axis order).
Copies unit_cell, spacegroup, nu, nv, nw, axis_order from another GridMeta, and recalculates spacing and orth_n.
- Parameters:
g – Source GridMeta
-
inline void calculate_spacing()
Compute spacing and scaled orthogonalization matrix.
Recalculates spacing and orth_n based on unit cell and grid dimensions. Must be called after changing unit_cell or grid dimensions.
- Throws:
Raises – exception if unit cell is not in standard orientation
-
inline void set_size_without_checking(int nu_, int nv_, int nw_)
Set grid dimensions and recalculate spacing (no space group check).
- Parameters:
nu_ – Dimension along first axis
nv_ – Dimension along second axis
nw_ – Dimension along third axis
-
inline void set_size(int nu_, int nv_, int nw_)
Set grid dimensions with space group compatibility check.
- Parameters:
nu_ – Dimension along first axis
nv_ – Dimension along second axis
nw_ – Dimension along third axis
- Throws:
Raises – exception if dimensions incompatible with space group
-
inline void set_size_from_spacing(double approx_spacing, GridSizeRounding rounding)
Calculate grid dimensions from desired spacing.
Chooses dimensions with small prime factors (2, 3, 5) compatible with space group.
- Parameters:
approx_spacing – Target spacing in Angstroms
rounding – Strategy for choosing nearby dimensions
-
inline void set_unit_cell(double a, double b, double c, double alpha, double beta, double gamma)
Set unit cell parameters from individual values.
- Parameters:
a – Cell length (Angstroms)
b – Cell length (Angstroms)
c – Cell length (Angstroms)
alpha – Angle (degrees)
beta – Angle (degrees)
gamma – Angle (degrees)
-
inline void set_unit_cell(const UnitCell &cell)
Set unit cell.
- Parameters:
cell – Unit cell to assign
-
template<typename S>
inline void setup_from(const S &st, double approx_spacing = 0) Initialize grid from a structure (typically Model/Chain/Residue).
Extracts space group and unit cell. If approx_spacing > 0, sets grid dimensions based on spacing.
- Template Parameters:
S – Structure type with find_spacegroup() and cell members
- Parameters:
st – Structure
approx_spacing – Target grid spacing in Angstroms (default: 0, no sizing)
-
inline size_t index_s(int u, int v, int w) const
Get index in data array with periodic wrapping.
Safe but slower than index_q(). Applies modulo to all indices.
- Parameters:
u – Grid index (will be wrapped)
v – Grid index (will be wrapped)
w – Grid index (will be wrapped)
- Returns:
Index into data array
-
inline T get_value(int u, int v, int w) const
Get value at grid point with periodic wrapping.
- Parameters:
u – Grid index
v – Grid index
w – Grid index
- Returns:
Grid value at the (normalized) indices
-
inline void set_value(int u, int v, int w, T x)
Set value at grid point with periodic wrapping.
- Parameters:
u – Grid index
v – Grid index
w – Grid index
x – Value to assign
-
inline Point get_point(int u, int v, int w)
Get a Point at given grid indices with periodic wrapping.
The returned Point has normalized indices u, v, w in [0, nu), [0, nv), [0, nw).
- Parameters:
u – Grid index
v – Grid index
w – Grid index
- Returns:
Point with normalized indices
-
inline Point get_nearest_point(const Fractional &f)
Get the grid point nearest to a fractional coordinate.
- Parameters:
f – Fractional coordinates
- Throws:
Raises – exception if grid is not in XYZ order
- Returns:
Point at nearest grid position
-
inline Point get_nearest_point(const Position &pos)
Get the grid point nearest to an orthogonal (Cartesian) position.
- Parameters:
pos – Orthogonal coordinates (Angstroms)
- Returns:
Point at nearest grid position
-
inline size_t get_nearest_index(const Fractional &f)
Get the index of the nearest grid point to a fractional coordinate.
- Parameters:
f – Fractional coordinates
- Returns:
Index into data array
-
inline Fractional point_to_fractional(const Point &p) const
Convert a grid Point to fractional coordinates.
The Point’s indices are normalized, so coordinates are in [0, 1).
- Parameters:
p – Point with normalized indices
- Returns:
Fractional coordinates
-
inline Position point_to_position(const Point &p) const
Convert a grid Point to orthogonal coordinates.
- Parameters:
p – Point with normalized indices
- Returns:
Orthogonal position (Angstroms)
-
inline T trilinear_interpolation(double x, double y, double z) const
Trilinear interpolation at a grid coordinate.
Reference: https://en.wikipedia.org/wiki/Trilinear_interpolation
- Parameters:
x – Grid coordinate (x=1.5 is between 2nd and 3rd grid point). Wraps periodically.
y – Grid coordinate
z – Grid coordinate
- Returns:
Interpolated value using trilinear basis functions
-
inline T trilinear_interpolation(const Fractional &fctr) const
Trilinear interpolation at fractional coordinates.
- Parameters:
fctr – Fractional coordinates
- Returns:
Interpolated value
-
inline T trilinear_interpolation(const Position &ctr) const
Trilinear interpolation at orthogonal coordinates.
- Parameters:
ctr – Orthogonal coordinates (Angstroms)
- Returns:
Interpolated value
-
inline double tricubic_interpolation(double x, double y, double z) const
Tricubic interpolation at a grid coordinate.
Uses Catmull–Rom cubic splines applied as a tensor product in three dimensions. Smoother than trilinear but more expensive. See cubic_interpolation() for the 1D formula.
- References
Afonine, P.V., Poon, B.K., Read, R.J., Sobolev, O.V., Terwilliger, T.C., Urzhumtsev, A. & Adams, P.D. (2018). Real-space refinement in PHENIX for cryo-EM and crystallography. Acta Cryst. D74, 531–544. https://doi.org/10.1107/S2059798318006551
- Parameters:
x – Grid coordinate (x=1.5 is between 2nd and 3rd grid point). Wraps periodically.
y – Grid coordinate
z – Grid coordinate
- Returns:
Interpolated value (double precision)
-
inline double tricubic_interpolation(const Fractional &fctr) const
Tricubic interpolation at fractional coordinates.
- Parameters:
fctr – Fractional coordinates
- Returns:
Interpolated value
-
inline double tricubic_interpolation(const Position &ctr) const
Tricubic interpolation at orthogonal coordinates.
- Parameters:
ctr – Orthogonal coordinates (Angstroms)
- Returns:
Interpolated value
-
inline std::array<double, 4> tricubic_interpolation_der(double x, double y, double z) const
Tricubic interpolation with first derivatives.
Returns the interpolated value and partial derivatives.
- Parameters:
x – Grid coordinate
y – Grid coordinate
z – Grid coordinate
- Returns:
Array {value, df/dx, df/dy, df/dz} in grid coordinates
-
inline std::array<double, 4> tricubic_interpolation_der(const Fractional &fctr) const
Tricubic interpolation with derivatives at fractional coordinates.
- Parameters:
fctr – Fractional coordinates
- Returns:
Array {value, df/da, df/db, df/dc} in fractional coordinates
-
inline T interpolate_value(const Fractional &f, int order = 1) const
Interpolate value at fractional coordinates using specified method.
- Parameters:
f – Fractional coordinates
order – Interpolation order: 0 (nearest), 1 (trilinear), 3 (tricubic)
- Throws:
std::invalid_argument – if order is not 0, 1, or 3
- Returns:
Interpolated value
-
inline T interpolate_value(const Position &ctr, int order = 1) const
Interpolate value at orthogonal coordinates using specified method.
- Parameters:
ctr – Orthogonal coordinates (Angstroms)
order – Interpolation order: 0 (nearest), 1 (trilinear), 3 (tricubic)
- Returns:
Interpolated value
-
inline void get_subarray(T *dest, std::array<int, 3> start, std::array<int, 3> shape) const
Extract a rectangular subarray of grid points with periodic wrapping.
Copies a contiguous block of grid values into a destination array. Handles wrapping across periodic boundaries.
- Parameters:
dest – Destination array (at least shape[0]*shape[1]*shape[2] elements)
start – Starting grid indices {u, v, w}
shape – Block size {du, dv, dw}
-
inline void set_subarray(const T *src, std::array<int, 3> start, std::array<int, 3> shape)
Set a rectangular subarray of grid points with periodic wrapping.
Copies a block of values from a source array into the grid. Handles wrapping across periodic boundaries.
- Parameters:
src – Source array (at least shape[0]*shape[1]*shape[2] elements)
start – Starting grid indices {u, v, w}
shape – Block size {du, dv, dw}
-
template<bool UsePbc>
inline void check_size_for_points_in_box(int &du, int &dv, int &dw, bool fail_on_too_large_radius) const Validate and adjust size parameters for box operations.
- Template Parameters:
UsePbc – If true, apply periodic boundary conditions; otherwise clamp to grid
- Parameters:
du – Half-size along first axis (may be adjusted)
dv – Half-size along second axis (may be adjusted)
dw – Half-size along third axis (may be adjusted)
fail_on_too_large_radius – If true, raise exception if radius too large for PBC
-
template<bool UsePbc, typename Func>
inline void do_use_points_in_box(const Fractional &fctr, int du, int dv, int dw, Func &&func, double radius = INFINITY) Internal: iterate over grid points in a box around a fractional coordinate.
- Template Parameters:
UsePbc – If true, apply periodic boundary conditions
Func – Callable(T&, double, Position, int, int, int) invoked for each point
- Parameters:
fctr – Fractional center coordinate
du – Half-extent along first axis (in grid points)
dv – Half-extent along second axis (in grid points)
dw – Half-extent along third axis (in grid points)
func – Callback function(value_ref, distance_sq, delta_position, u, v, w)
radius – Optional spherical radius limit (INFINITY for box only)
-
template<bool UsePbc, typename Func>
inline void use_points_in_box(const Fractional &fctr, int du, int dv, int dw, Func &&func, bool fail_on_too_large_radius = true, double radius = INFINITY) Iterate over grid points in a box around a fractional coordinate.
- Template Parameters:
UsePbc – If true, apply periodic boundary conditions
Func – Callable(T&, double, Position, int, int, int) invoked for each point
- Parameters:
fctr – Fractional center coordinate
du – Half-extent along first axis (in grid points)
dv – Half-extent along second axis (in grid points)
dw – Half-extent along third axis (in grid points)
func – Callback function(value_ref, distance_sq, delta_position, u, v, w)
fail_on_too_large_radius – If true and UsePbc, raise exception for oversized box
radius – Optional spherical radius limit (INFINITY for box only)
-
template<bool UsePbc, typename Func>
inline void use_points_around(const Fractional &fctr, double radius, Func &&func, bool fail_on_too_large_radius = true) Iterate over grid points within a spherical radius of a fractional coordinate.
- Template Parameters:
UsePbc – If true, apply periodic boundary conditions
Func – Callable(T&, double) invoked for each point
- Parameters:
fctr – Fractional center coordinate
radius – Spherical radius (in Angstroms)
func – Callback function(value_ref, distance_sq)
fail_on_too_large_radius – If true and UsePbc, raise exception for large radius
-
inline void set_points_around(const Position &ctr, double radius, T value, bool use_pbc = true)
Set all grid points within a spherical radius to a constant value.
- Parameters:
ctr – Orthogonal center (Angstroms)
radius – Spherical radius (Angstroms)
value – Value to assign
use_pbc – If true, apply periodic boundary conditions
-
inline void change_values(T old_value, T new_value)
Replace all occurrences of one value with another.
- Parameters:
old_value – Value to search for
new_value – Replacement value
-
template<typename Func>
inline void symmetrize(Func func) Apply a reduction function across all symmetry mates of each point.
For each unique point under the space group, applies
functo combine the values of all symmetry-related points, then assigns the result back to all mate positions.- Template Parameters:
Func – Binary function(T, T) → T
- Parameters:
func – Reduction function, e.g., std::plus, std::max, etc.
-
template<typename Func>
inline void symmetrize_using_ops(const std::vector<GridOp> &ops, Func func) Apply a reduction function using an explicit list of operations.
- Template Parameters:
Func – Binary function(T, T) → T
- Parameters:
ops – GridOp operations (typically from get_scaled_ops_except_id())
func – Reduction function
-
inline void symmetrize_min()
Apply symmetry by taking the minimum value among symmetry mates.
-
inline void symmetrize_max()
Apply symmetry by taking the maximum value among symmetry mates.
-
inline void symmetrize_abs_max()
Apply symmetry by taking the maximum absolute value among symmetry mates.
-
inline void symmetrize_sum()
Apply symmetry by summing values of symmetry mates.
Points on special positions (with fewer mates) contribute their value multiple times. Used for density map averaging without normalization.
-
inline void symmetrize_nondefault(T default_)
Apply symmetry by selecting non-default values among mates.
If a point’s value equals
default_, uses the value from a symmetry mate.- Parameters:
default_ – Value to replace
-
inline void symmetrize_avg()
Apply symmetry by averaging values of symmetry mates.
Sums symmetry mates and divides by space group order.
-
inline void normalize()
Normalize grid values to zero mean and unit RMS.
Subtracts the mean and scales by RMS, making statistics zero mean and unit variance. Does not work for complex-valued grids.
Public Members
-
double spacing[3] = {0., 0., 0.}
Spacing (in Angstroms) between consecutive grid planes.
spacing[0] is distance between u planes, etc. Note: spacing is between planes, not between grid points. Computed as 1/(n*cell_length) for each axis.
-
UpperTriangularMat33 orth_n
Orthogonalization matrix scaled by grid dimensions.
Each column of unit_cell.orth.mat divided by {nu, nv, nw}. Used for efficient conversion of fractional deltas to orthogonal.
Public Static Functions
-
static inline double grid_modulo(double x, int n, int *iptr)
Helper to split a real coordinate into integer and fractional parts.
- Parameters:
x – Real coordinate
n – Grid dimension
iptr – Output: normalized integer part in [0, n)
- Returns:
Fractional part in [0, 1)
-
template<typename T>
struct GridBase : public gemmi::GridMeta - #include <gemmi/grid.hpp>
Common base for Grid and ReciprocalGrid templates.
- Template Parameters:
T – Data type stored at each grid point
Subclassed by gemmi::Grid< float >, gemmi::Grid< GReal >, gemmi::Grid< T >, gemmi::Grid< std::vector< gemmi::NeighborSearch::Mark > >, gemmi::Grid< T >, gemmi::ReciprocalGrid< T >
Public Types
Public Functions
-
inline void check_not_empty() const
Check that grid is not empty (has allocated data).
- Throws:
Raises – exception if data.empty()
-
inline void set_size_without_checking(int nu_, int nv_, int nw_)
Allocate and set grid dimensions without bounds checking.
Resizes the data array to nu_ * nv_ * nw_ elements. Does not validate space group compatibility.
- Parameters:
nu_ – Number of grid points along first axis
nv_ – Number of grid points along second axis
nw_ – Number of grid points along third axis
-
inline T get_value_q(int u, int v, int w) const
Get value at grid point using quick (unsafe) index.
- Parameters:
u – Grid index (must be in [0, nu))
v – Grid index (must be in [0, nv))
w – Grid index (must be in [0, nw))
- Returns:
Value at (u, v, w)
-
inline size_t point_to_index(const Point &p) const
Convert a Point to its index in the data array.
- Parameters:
p – Point with value pointer
- Returns:
Index into data array
-
inline Point index_to_point(size_t idx)
Convert a data array index to a Point with normalized indices.
- Parameters:
idx – Index into data array
- Returns:
Point with indices and value pointer
-
inline void fill(T value)
Resize grid and fill all points with a constant value.
- Parameters:
value – Value to assign to all grid points
-
inline Tsum sum() const
Sum all grid values.
- Returns:
Sum of all data points
-
inline iterator begin()
Begin iterator (first grid point).
-
inline iterator end()
End iterator (one past last grid point).
-
struct iterator
- #include <gemmi/grid.hpp>
Iterator over grid points in row-major order (u varies fastest).
Public Functions
-
inline iterator(GridBase &parent_, size_t index_)
Construct an iterator at a specific index.
-
inline iterator &operator++()
Pre-increment to next grid point.
-
inline bool operator==(const iterator &o) const
Equality comparison.
-
inline bool operator!=(const iterator &o) const
Inequality comparison.
Public Members
-
GridBase &parent
Reference to parent grid.
-
size_t index
Current position in data array.
-
int u = 0
-
int v = 0
-
int w = 0
Current grid coordinates.
-
inline iterator(GridBase &parent_, size_t index_)
-
struct Point
- #include <gemmi/grid.hpp>
A grid point with normalized indices and a value pointer.
Indices u, v, w have been normalized to [0, nu), [0, nv), [0, nw). The pointer may become invalid if the grid is resized.
Public Members
-
int u
-
int v
-
int w
Normalized grid indices.
-
T *value
Pointer to the grid value at this point.
-
int u
-
struct GridMeta
- #include <gemmi/grid.hpp>
Metadata common to all grid types (not dependent on stored data type).
Contains unit cell, space group, grid dimensions, and indexing operations. Grid indices u, v, w are in the range [0, nu), [0, nv), [0, nw) for valid grids.
Subclassed by gemmi::GridBase< float >, gemmi::GridBase< GReal >, gemmi::GridBase< std::vector< gemmi::NeighborSearch::Mark > >, gemmi::GridBase< T >
Public Functions
-
inline size_t point_count() const
Total number of grid points.
- Returns:
nu * nv * nw
-
inline Fractional get_fractional(int u, int v, int w) const
Convert grid indices to fractional coordinates.
- Parameters:
u – Grid index (not normalized to [0, 1))
v – Grid index (not normalized to [0, 1))
w – Grid index (not normalized to [0, 1))
- Returns:
Fractional coordinates {u/nu, v/nv, w/nw}
-
inline Position get_position(int u, int v, int w) const
Convert grid indices to orthogonal (Cartesian) coordinates.
- Parameters:
u – Grid index
v – Grid index
w – Grid index
- Returns:
Orthogonal position in Angstroms
-
inline std::vector<GridOp> get_scaled_ops_except_id() const
Get symmetry operations scaled to grid coordinates (excluding identity).
Returns all non-identity symmetry operations with translations and rotations pre-scaled for direct application to grid indices. Used internally for symmetrization operations. Requires axis_order == AxisOrder::XYZ.
- Throws:
Raises – exception if grid is not in XYZ order
- Returns:
Vector of GridOp, empty if space group is P1
-
inline size_t index_q(int u, int v, int w) const
Quick index computation: fastest but requires 0 <= u < nu, etc.
No bounds checking. Data layout is row-major: (w*nv + v)*nu + u.
- Parameters:
u – Grid index (must be in [0, nu))
v – Grid index (must be in [0, nv))
w – Grid index (must be in [0, nw))
- Returns:
Index into flat data array
-
inline size_t index_q(size_t u, size_t v, size_t w) const
Quick index computation for unsigned indices.
-
inline size_t index_n(int u, int v, int w) const
Index with periodic wrapping: faster than index_s() but limited range.
Works for indices in the range [-nu, 2*nu) (and similarly for v, w). Applies periodic boundary conditions (wraps to [0, n)).
- Parameters:
u – Grid index
v – Grid index
w – Grid index
- Returns:
Index into flat data array
-
inline size_t index_n_ref(int &u, int &v, int &w) const
Index with periodic wrapping, modifying arguments in-place.
Same as index_n() but normalizes u, v, w to [0, nu), [0, nv), [0, nw).
- Parameters:
u – Grid index (will be normalized)
v – Grid index (will be normalized)
w – Grid index (will be normalized)
- Returns:
Index into flat data array
-
inline size_t index_near_zero(int u, int v, int w) const
Index with periodic wrapping for indices near zero.
Optimized version of index_n() for indices in [-n, n).
- Parameters:
u – Grid index in range [-nu, nu)
v – Grid index in range [-nv, nv)
w – Grid index in range [-nw, nw)
- Returns:
Index into flat data array
Public Members
-
UnitCell unit_cell
Unit cell of the crystal.
-
const SpaceGroup *spacegroup = nullptr
Space group (may be nullptr for P1)
-
int nu = 0
-
int nv = 0
-
int nw = 0
Grid dimensions.
-
inline size_t point_count() const
-
struct GridOp
- #include <gemmi/grid.hpp>
A crystallographic symmetry operation scaled for grid coordinates.
The scaled operation directly transforms grid indices by applying the rotation matrix and scaled translation (pre-scaled by grid dimensions).
Public Functions
-
inline std::array<int, 3> apply(int u, int v, int w) const
Apply the operation to grid indices.
- Parameters:
u – Grid index along first axis
v – Grid index along second axis
w – Grid index along third axis
- Returns:
Transformed grid indices {u’, v’, w’}
Public Members
-
Op scaled_op
Crystallographic operation with translation scaled to grid coordinates.
-
inline std::array<int, 3> apply(int u, int v, int w) const
-
enum class AxisOrder : unsigned char