Repository navigation
Molecular structures
extensions/molecule/ reads macromolecular structures from mmCIF and PDB files and builds ideal peptide backbones. It draws a structure as a cartoon ribbon or as a surface, and it measures the solvent accessible area of each atom. It is a library for research and teaching. Its measurements are not validated for drug design or for any clinical use.

examples/molecule.mojo makes this picture. It builds 30 residues of ideal backbone: a helix, a loop and a strand. The top panel is the ribbon, colored by secondary structure. The middle panel is the solvent excluded surface for a water probe, colored by element. The program also prints the solvent accessible area, 2434 square angstroms.
The bottom panel is the same surface colored by hydropathy. The leucines and alanines of the helix make an orange stripe between its blue glutamates and lysines: the helix is amphipathic.
| Module | What it gives |
|---|---|
ids |
AtomId, ResidueId, ChainId, ModelId, AtomGroup, SecondaryKind, AltLocPolicy, RibbonColoring, SurfaceColoring, EnsembleFit and AlignmentMode
|
structure |
Structure, parse_mmcif, read_mmcif, parse_pdb_structure, read_pdb_structure and SQUARE_ANGSTROM
|
peptide |
build_peptide, place_atom and three_letter
|
dssp |
assign_secondary, hydrogen_bonds, HydrogenBond, secondary_from_bonds, bond_energy and KILOCALORIE_PER_MOLE
|
hbonds |
bond_geometry |
ribbon |
ribbon_geometry and chain_color
|
surface |
accessible_areas, molecular_surface, excluded_surface, vdw_radius, sphere_points and AtomCells
|
coloring |
color_surface, color_surface_potential, atom_color and kyte_doolittle
|
charge |
formal_charges, Charges and coulomb_potential
|
confidence |
confidence_color, confidence_summary and ConfidenceSummary
|
lddt |
lddt, ca_lddt, lddt_b_factors and LddtScores
|
superpose |
superpose, Superposition, rmsd and matched_atoms
|
ensemble |
ensemble_fluctuation, Fluctuation, fluctuation_b_factors and shared_positions
|
clusters |
model_distances, ModelDistances and cluster_models
|
contacts |
distance_map, DistanceMap and map_image
|
shape |
molecular_shape and MolecularShape
|
accessibility |
residue_accessibility, ResidueAccess and max_accessible_area
|
variants |
parse_variant, Variant, variant_sites and VariantSite
|
interface |
chain_interface and ChainInterface
|
links |
disulfide_bonds, salt_bridges and ResiduePair
|
sequence |
chain_sequence, encode_fasta, align_sequences, SequenceAlignment, aligned_atoms, blosum62 and one_letter
|
pdb_write |
encode_pdb |
cif_write |
encode_mmcif and cif_value
|
dihedral |
backbone_angles, BackboneAngles, dihedral, ramachandran_image, ramachandran_color and plot_pixel
|
amphipathic |
eisenberg_hydrophobicity, sequence_hydrophobicity, HydrophobicMoment, hydrophobic_moment, window_moment, HelicalWheel, helical_wheel and MAX_WHEEL
|
phylogeny |
alignment_distances, kimura_distances, neighbor_joining, upgma, midpoint_root, PhyloTree, tree_image, TreeDrawing and MAX_TAXA
|
conservation |
parse_fasta, FastaRecords, henikoff_weights, uniform_background, column_conservation, ColumnConservation and conservation_b_factors
|
protparam |
net_charge, isoelectric_point, average_mass, extinction_coefficients, gravy, aromaticity, aliphatic_index, MolarArea64 and PER_MOLAR_CENTIMETER
|
var structure = read_mmcif("1abc.cif", FIRST_LOCATION)
for chain in structure.chains:
print(chain.author, chain.residue_count)parse_mmcif(text, policy) reads text that is already in memory. The PDB distributes each entry as an mmCIF file. The older PDB format cannot hold more than 99,999 atoms, and loaders/pdb.mojo reads only atoms and bonds from it.
read_pdb_structure(path, policy) reads a PDB file into the same Structure. parse_pdb_structure(text, policy) reads text in memory. The reader takes these records from their fixed columns:
| Record | What it gives |
|---|---|
HEADER |
The structure's name, the PDB id in columns 63 to 66 |
MODEL |
A new model with its number |
ATOM, HETATM
|
An atom, with its residue and chain |
TER |
The end of a chain |
HELIX, SHEET
|
The helices and strands |
A PDB file has only the author's chain letters and residue numbers. Each residue's seq_id and auth_seq_id are the author's number, and the helices and strands name residues by it. A chain starts at a new letter, after TER, or in a new model. A chain that repeats a letter in one model gets a label of the letter and a count, such as A2. The waters after TER are such a chain, so the helices of chain A do not mark them.
A short line can leave out the occupancy, the B-factor and the element. The occupancy is then 1 and the B-factor 0. The element then comes from the atom name, as the PDB convention gives it. A name with column 13 blank holds a one-letter element in column 14, so CA is carbon. A name that starts in column 13 holds a two-letter element there, so CA is calcium.
encode_pdb(structure) writes a structure as the text of a PDB file, for other molecular viewers. Use it for a structure that this extension built or moved, such as an ideal peptide or a superposed model.
Path("model.pdb").write_text(encode_pdb(structure))The file holds ATOM and HETATM records in the fixed columns of the wwPDB format version 3.3, with TER after each chain and END. Two or more models are written between MODEL and ENDMDL. The helices and strands of the first model become HELIX and SHEET records. A name of up to four characters is the PDB id of a HEADER, and a longer name is a TITLE.
Coordinates have three decimals in angstroms, and the occupancy and the B-factor two. A chain id must be one character. A name or a number that does not fit its columns is refused.
encode_mmcif(structure) writes a structure as the text of an mmCIF file. Use it when a structure does not fit the PDB format. Examples are more than 99999 atoms, a chain id of two characters, and a long atom name.
Path("model.cif").write_text(encode_mmcif(structure))The file is one data block, data_ and the structure's name, or data_unnamed for a structure without one. It holds these categories:
| Category | What it holds |
|---|---|
_entry |
The structure's name as id
|
_struct_conf |
A HELX_P row for each run of helix residues of the first model |
_struct_sheet_range |
A row for each run of strand residues of the first model, each in a sheet of its own |
_atom_site |
One row per atom, with every column that parse_mmcif reads |
A helix or a strand names its first and last residues by the label ids and the insertion codes. It names them again by the author ids, as wwPDB files do. Coordinates have three decimals in angstroms, and the occupancy and the B-factor two. A residue whose seq_id is zero, such as a water, gets the null label_seq_id ..
cif_value(text) gives a value as a CIF token. A value that is empty, holds a blank, or starts like a name, a comment or a reserved word such as loop_ goes in quotes. It goes in single quotes, or in double quotes when it holds a single quote and a blank. A value that holds a line end is refused.
A Structure holds four lists: models, chains, residues and atoms. A model holds a run of chains, a chain holds a run of residues, and a residue holds a run of atoms. Each run is a first index and a count. An id such as ResidueId(3) is an index into its list.
| Type | Fields |
|---|---|
Model |
number, first_chain, chain_count
|
Chain |
label, author, model, first_residue, residue_count
|
Residue |
name, seq_id, auth_seq_id, insertion, chain, first_atom, atom_count, secondary
|
Atom |
name, element, serial, group, alt, position, occupancy, b_factor, residue
|
Positions are in meters, as the rest of the project keeps them. Read them in angstroms with ANGSTROM from extensions/chemistry/quantities.mojo. A B-factor is an Area64. Read it with SQUARE_ANGSTROM.
find_atom(residue, name) gives the first atom of a residue with a name, or AtomId(-1). model_atoms(model) gives the first atom and the atom count of a model. bounds(model) gives the corners of a model's atom centers.
The reader takes the first data block. It reads the _atom_site table. These columns must be present:
| Column | Field |
|---|---|
group_PDB |
group: ATOM or HETATM
|
type_symbol |
element |
label_atom_id |
name |
label_comp_id |
The residue name
|
label_asym_id |
The chain label
|
label_seq_id |
The residue seq_id. A null gives zero. |
Cartn_x, Cartn_y, Cartn_z
|
position |
These columns are optional:
| Column | Field | Without it |
|---|---|---|
id |
serial |
The row number |
label_alt_id |
alt |
. |
auth_asym_id |
The chain author
|
The chain label |
auth_seq_id |
The residue auth_seq_id
|
The label_seq_id
|
pdbx_PDB_ins_code |
The residue insertion
|
? |
occupancy |
occupancy |
1 |
B_iso_or_equiv |
b_factor |
0 |
pdbx_PDB_model_num |
The model number
|
1 |
A new model starts where the model number changes. A new chain starts where label_asym_id changes. A new residue starts where label_seq_id, auth_seq_id, the insertion code or the residue name changes. Two waters with a null label_seq_id are two residues when their auth_seq_id differs.
An atom can have more than one position in a crystal. Each position has an alternate location, such as A or B, and an occupancy.
| Policy | Atoms kept |
|---|---|
ALL_LOCATIONS |
Every atom |
FIRST_LOCATION |
The atoms with no alternate location, and in each residue the atoms of the first alternate location in the file |
The reader marks helices from _struct_conf. A row is a helix when its conf_type_id starts with HELX. It marks strands from _struct_sheet_range. Each row names a chain by beg_label_asym_id and a run of residues by beg_label_seq_id and end_label_seq_id. The marks apply to every model. Other residues are COIL.
assign_secondary(structure, model) replaces the secondary structure of a model's residues with the one that its backbone hydrogen bonds make. Use it for a file with no helix and strand records, such as a structure prediction. The method is the core of DSSP, by Kabsch and Sander.
var structure = read_pdb_structure("predicted.pdb", FIRST_LOCATION)
assign_secondary(structure, ModelId(0))The energy of a bond from the N-H of one residue to the C=O of another is DSSP's electrostatic model, in kcal/mol. A bond exists below -0.5. The H of a residue is 1 angstrom from its N, along the direction from the O to the C of the residue before. A chain's first residue and a proline have no H.
| Pattern | Gives |
|---|---|
Two 4-turns in a row, at i - 1 and i
|
A helix from i to i + 3
|
| Two bridges of one kind in a row | A strand at all four residues |
A 4-turn at i is a bond from the C=O of i to the N-H of i + 4. A bridge pairs two residues three or more apart. It is antiparallel when they bond to each other, or when their outer neighbors do. It is parallel when the bonds run past each residue to the next. A helix wins over a strand. A residue without all of N, CA, C and O is coil.
secondary_from_bonds(bonds, count) applies the patterns to a matrix of bonds, so a caller can supply bonds from another source.
Two kinds of side-chain link hold a fold together beside the backbone. disulfide_bonds(structure, model, cutoff) and salt_bridges(structure, model, cutoff) list them.
for bond in disulfide_bonds(structure, ModelId(0), Length64(2.5, ANGSTROM)):
print(bond.first.value, bond.second.value, bond.distance.to(ANGSTROM))
var bridges = salt_bridges(structure, ModelId(0), Length64(4.0, ANGSTROM))| Link | Atoms | Usual cutoff |
|---|---|---|
| Disulfide bond | SG of one cysteine and SG of another | 2.5 angstroms, for a bond of about 2.05 |
| Salt bridge | OD1, OD2, OE1 or OE2 of an aspartate or a glutamate, and NZ of a lysine or NE, NH1 or NH2 of an arginine | 4.0 angstroms, after Barlow and Thornton |
A ResiduePair holds the two residues and the least distance between their linking atoms. Each pair of residues is listed once, in the order of the first residue and then the second. A disulfide bond lists its lower cysteine first, and a salt bridge lists the acid first. A histidine is left out of the salt bridges, as its charge depends on the pH. An asparagine or a glutamine has an OD1 or an OE1 too, but no charge, so it is not an acid.
The backbone hydrogen bonds make a helix and pair the strands of a sheet. hydrogen_bonds(structure, model) lists them as DSSP finds them, and bond_geometry draws them.
var bonds = hydrogen_bonds(structure, ModelId(0))
for bond in bonds:
print(bond.donor.value, bond.acceptor.value, bond.energy.to(KILOCALORIE_PER_MOLE))
var sticks = bond_geometry(structure, bonds, Length64(0.1, ANGSTROM), 8)A HydrogenBond holds its donor residue, the N-H, its acceptor residue, the C=O, and its energy as a MolarEnergy64. Only a bond below -0.5 kcal/mol is listed. The N-H right after a C=O shares its peptide plane, so DSSP does not pair them. In an alpha helix, the N-H of residue i + 4 bonds to the C=O of residue i.
bond_geometry(structure, bonds, radius, sides) draws each bond as a dashed tube from the N of its donor to the O of its acceptor, in light orange. Draw it over a ribbon: the bonds of a helix run along its axis.
Three torsions set the shape of the backbone at each residue. backbone_angles(structure, model) gives them, and ramachandran_image plots them.
var angles = backbone_angles(structure, ModelId(0))
for entry in angles:
if entry.has_phi and entry.has_psi:
print(entry.residue.value, entry.phi.to(DEGREE64), entry.psi.to(DEGREE64))
var plot = ramachandran_image(structure, angles, 360)| Angle | Atoms |
|---|---|
| phi | C of i - 1, N, CA, C |
| psi | N, CA, C, N of i + 1
|
| omega | CA, C, N of i + 1, CA of i + 1
|
A BackboneAngles holds a residue and its three angles as Angle64 values, from -180 to 180 degrees. A flag tells if the residue has each angle. A residue needs its N, CA and C, or it has no entry. A neighbor counts only in the same chain, and only when its C to N distance is 2.5 angstroms or less, as in DSSP. The first residue of a chain has no phi. The last has no psi and no omega.
dihedral(a, b, c, d) gives the torsion of any four points, with the IUPAC sign. Seen along the bond from b to c, the angle is positive when the far bond turns clockwise from the near bond.
ramachandran_image(structure, angles, size) plots psi against phi. Phi runs from -180 degrees at the left to 180 at the right. Psi runs from 180 at the top to -180 at the bottom. Each residue with both angles is a dot, red for a helix, gold for a strand and gray for a coil. Gray lines mark zero.
Helices gather near (-60, -45), and strands near (-120, 130). A trans peptide bond has an omega near 180 degrees, and a cis bond has an omega near 0.
The mmCIF reader takes its tokens and tables from chemistry.cif, which the crystal reader of Crystals and figures shares. It gives parse_cif, read_cif, cif_tokens, CifBlock, CifTable and is_null.
The tokens follow CIF 1.1. A # starts a comment. A value in single or double quotes ends at a matching quote that a blank follows, so 'O'Brien' is one value. A line that starts with ; opens a text field, and the next line that starts with ; closes it.
parse_cif(text) returns a CifBlock. A name is not case sensitive. column(tag) returns the values of a name, one for each row of its table. A single name and value is a table of one row. column_or(tag, fallback, rows) returns a fallback when the name is absent. is_null(value) is true for . and ?.
build_peptide(sequence, kinds) places the backbone of a sequence. Each residue gets N, CA, C and O, and CB when it is not glycine. The bond lengths and angles are the ideal values of Engh and Huber. The secondary structure of each residue sets its torsions:
| Kind | phi (degrees) | psi (degrees) |
|---|---|---|
HELIX |
-57 | -47 |
STRAND |
-139 | 135 |
COIL |
-75 | 145 |
Every peptide bond is trans. place_atom(a, b, c, bond, angle, torsion) places each atom from the three before it by the natural extension reference frame. CB comes from the ideal formula that trRosetta uses, which gives an L-amino acid.
These torsions make ideal shapes. They do not fold a chain: the strands of a built peptide do not pair. A real fold comes from an experiment or from a structure prediction.
ribbon_geometry(structure, model, coloring, samples, sides) returns the cartoon of every chain of a model. A ribbon follows a Catmull-Rom spline through the CA atoms. The O atom of each residue gives the direction across the ribbon. A direction that turns more than a right angle from the residue before is flipped, so the ribbon does not twist.
| Kind | Half width (angstroms) | Half thickness (angstroms) |
|---|---|---|
HELIX |
1.2 | 0.25 |
STRAND |
1.0 | 0.25 |
COIL |
0.3 | 0.3 |
The last residue of a strand ends in an arrow. The arrow starts 1.7 angstroms wide and narrows to a point. A chain breaks where two CA atoms in a row are more than 4.2 angstroms apart, or where a residue has no CA.
BY_STRUCTURE colors helices red, strands gold and coils gray. BY_CHAIN gives each chain one of eight colors. BY_CONFIDENCE colors each residue by the pLDDT of a predicted model. See Color by confidence. The colors are linear, as the renderer needs them.
accessible_areas(structure, model, probe, points) gives the solvent accessible area of each atom. It uses the method of Shrake and Rupley.
- Each atom is a sphere of its van der Waals radius plus the probe radius.
-
pointspoints spread over each sphere by the golden-section spiral. - A point is accessible when no other sphere holds it.
- The area is the area of the sphere times the fraction of accessible points.
A probe of 1.4 angstroms is a water molecule. The radii are from Bondi:
| Element | Radius (angstroms) |
|---|---|
| H | 1.20 |
| C | 1.70 |
| N | 1.55 |
| O | 1.52 |
| F | 1.47 |
| P, S | 1.80 |
| Cl | 1.75 |
| Se | 1.90 |
| Br | 1.85 |
| I | 1.98 |
Any other element gets 1.8 angstroms.
residue_accessibility(structure, model, areas) adds the atom areas of each residue. It also gives the relative solvent accessibility (RSA): the area over the largest area that the residue can have.
var areas = accessible_areas(structure, ModelId(0), Length64(1.4, ANGSTROM), 500)
for entry in residue_accessibility(structure, ModelId(0), areas):
if entry.has_relative and entry.buried(0.25):
print(structure.residues[entry.residue.value].name, entry.relative)The RSA is about 0 for a buried residue and about 1 for a residue in the open. A residue with an RSA below a cutoff, such as 0.2 or 0.25, is often called buried. entry.buried(cutoff) tells which side of the cutoff a residue is on.
The largest areas are the theoretical values of Tien and others (2013), for a residue in an extended chain of three. max_accessible_area(name) gives the value of one of the twenty standard amino acids. Another residue, such as a water or a ligand, has its area but no RSA, and has_relative is false.
A missense variant changes one amino acid, such as R175H of the tumor suppressor p53: arginine 175 becomes histidine. Disease research asks where such a site is in the folded protein. parse_variant(text) reads a variant as R175H, p.R175H or p.Arg175His.
var variants = List[Variant]()
for name in ["R175H", "G245S", "R248Q"]:
variants.append(parse_variant(name))
var reach = Length64(4.5, ANGSTROM)
for site in variant_sites(structure, ModelId(0), ChainId(0), variants, reach):
print(site.variant.name(), site.relative_accessibility, site.blosum)variant_sites(structure, model, chain, variants, reach) finds each site in the chain by its author number. It checks that the residue there is the wild type of the variant. Then it gives these fields of each site:
| Field | Meaning |
|---|---|
relative_accessibility |
The RSA, with a probe of 1.4 angstroms and 480 points on each sphere |
secondary |
The secondary structure of the residue |
b_factor |
The mean B-factor of its atoms, which is the pLDDT of a predicted model |
contacts |
The other residues with an atom within reach of one of its atoms |
charge_change |
The formal charge at pH 7 of the new amino acid less that of the old: +1 for R and K, -1 for D and E |
hydropathy_change |
The Kyte-Doolittle hydropathy of the new amino acid less that of the old |
blosum |
The BLOSUM62 score of the change. Below 0, the change is rare in related proteins |
A buried site in a helix or a strand, whose change is rare or changes the charge, often unfolds a protein. These are measures for research, not a prediction of disease.
Two chains that bind cover part of each other's surface. chain_interface(structure, model, first, second, probe, points) gives the area that they bury, and the residues that bury it.
var face = chain_interface(structure, ModelId(0), ChainId(0), ChainId(1), Length64(1.4, ANGSTROM), 500)
print(face.total().to(SQUARE_ANGSTROM), "square angstroms buried")
for row in range(len(face.residues)):
print(face.residues[row].value, face.buried(row).to(SQUARE_ANGSTROM))The buried surface area is ASA(A alone) + ASA(B alone) - ASA(A with B), over the atoms of the two chains. Other chains of the model do not count. Each accessible area uses the same points on each sphere alone and with the other chain. So no atom gains area, and each buried area is zero or more.
A ChainInterface holds each atom of both chains with its buried area, and each residue that buries area with its sum. face.total() gives the buried area of the interface. Some studies report half of it, the area that each side loses on average.
molecular_surface(structure, model, probe, spacing) returns the solvent accessible surface as a mesh. It samples the distance to the nearest grown sphere on a grid of the given spacing. It meshes the zero set of that distance by marching tetrahedra. Each vertex takes the CPK color of the atom whose sphere it lies on.
A probe of zero gives the van der Waals surface.
excluded_surface(structure, model, probe, spacing) returns the solvent excluded surface: the surface where a rolling probe touches the atoms. Molecular viewers show this surface by default. It follows each atom's van der Waals sphere where the probe touches one atom. It fills each crevice that the probe is too large to enter with a smooth, concave patch.
The probe's center can reach the points outside every grown sphere. The surface is the set of points one probe radius from that region. The distance to that region comes from three bounds:
- The depth into the deepest grown sphere is a lower bound.
- Where the point straight out from that sphere's center is outside every other sphere, the depth is exact. This covers the convex patches.
- In a crevice between two spheres, the distance to the circle where they meet is exact when no third sphere holds the circle's nearest point.
Elsewhere, an exact Euclidean distance transform of the grid gives the distance to the nearest reachable grid point. That distance, less the point's own distance to the spheres, is an upper bound within one step of the true distance. This is the method of EDTSurf, with exact corrections.
The excluded surface takes the distance to the reachable region from distance_transform of the Numerics extension. It gives the squared distance to the nearest seed in grid steps, and the index of that seed.
chain_sequence(structure, chain) gives the one-letter sequence of a chain. encode_fasta(structure, model) writes the sequence of each chain of a model as a FASTA file. align_sequences(first, second, open, extend) aligns two sequences end to end.
var crystal_seq = chain_sequence(crystal, ChainId(0))
var model_seq = chain_sequence(predicted, ChainId(0))
var alignment = align_sequences(crystal_seq, model_seq, -10, -0.5)
print(alignment.first, alignment.second, alignment.score, alignment.identity())
Path("model.fasta").write_text(encode_fasta(predicted, ModelId(0)))A residue that is not one of the twenty standard amino acids, such as a water or a ligand, is left out of a sequence. A FASTA record is >NAME:CHAIN, with the sequence in lines of 80 codes. A chain without a standard amino acid has no record.
The alignment is the global method of Needleman and Wunsch, with the affine gaps of Gotoh. A pair of residues scores its BLOSUM62 value, and blosum62(a, b) gives that value. A gap of length L scores open + (L - 1) * extend, at the ends too. The scores -10 and -0.5 are a common choice. Where two paths tie, the trace takes a pair first, then a gap in the second sequence, then a gap in the first.
A last argument of LOCAL_ALIGNMENT finds the best scoring stretch of each sequence instead, by the method of Smith and Waterman. Use it for a domain inside a longer chain, or a fragment against a whole protein. A local alignment starts and ends with a pair, and its score is never below the best single pair.
var domain = align_sequences(fragment, whole, -10, -0.5, LOCAL_ALIGNMENT)
print(domain.first_start, domain.second_start, domain.first, domain.second)A SequenceAlignment holds the two sequences with - for each gap, the score, and the counts of identical and paired columns. first_start and second_start give the first residue of each sequence in the alignment, from 0. They are 0 for a global alignment. identity() is the share of paired columns that hold the same residue. Check it before you superpose two models, to be sure that they are of one protein.
aligned_atoms(first, first_chain, second, second_chain, name, open, extend) pairs the atoms of one name through the alignment. Use it in place of matched_atoms when two chains number their residues another way, as a prediction often does. Use it also when one chain has a residue that the other lacks.
var pairs = aligned_atoms(crystal, ChainId(0), predicted, ChainId(0), "CA", -10, -0.5)
var fixed = List[V3]()
var moving = List[V3]()
for pair in pairs:
fixed.append(crystal.atoms[pair[0]].position)
moving.append(predicted.atoms[pair[1]].position)
var fit = superpose(fixed, moving)Each column that pairs two residues pairs their first atoms of the name, when both residues have one. A last argument of LOCAL_ALIGNMENT pairs a fragment with its part of a whole chain.
The sequences of a pathogen change as it spreads, so a tree of its sequences traces the spread. A tree of a protein family shows which members are near kin.

examples/phylogeny.mojo makes this picture. A protein of 300 residues of a synthetic pathogen spreads from one source into three wards, and in each ward to four patients. It changes a little on each branch of the spread. The neighbor-joining tree of the twelve sequences finds the three wards: the patients of each ward share a branch.
from extensions.molecule.phylogeny import alignment_distances, kimura_distances, midpoint_root, neighbor_joining
var distances = kimura_distances(alignment_distances(sequences, -10.0, -0.5))
var tree = midpoint_root(neighbor_joining(distances, names))
print(tree.newick())-
alignment_distances(sequences, open, extend)aligns each pair end to end with BLOSUM62, and gives1 - identity, the p-distance. -
kimura_distances(p)corrects the p-distances for more than one change at a site:-ln(1 - p - 0.2 p^2), after Kimura. It refuses a p-distance above about 0.85. -
neighbor_joining(distances, names)builds the tree of Saitou and Nei, as Biopython builds it. It needs no molecular clock. Its root is the last join, so read it as unrooted. Branch lengths can be below 0. -
upgma(distances, names)builds the rooted tree of the average linkage, as scipy'slinkagewith the average method builds it. It takes a molecular clock, so each leaf is at the same depth. -
midpoint_root(tree)roots a tree at the middle of its longest path between two leaves, as Biopython'sroot_at_midpointdoes.
A PhyloTree holds its leaves as nodes 0 to n - 1, in the order of the names. path_length(a, b) gives the sum of the branch lengths between two leaves, and leaf_order() gives the leaves in the order of a walk from the root. newick() writes the tree as Newick text.
tree_image(tree, width, height, label) draws the tree with the root at the left and the leaves in rows. It keeps label pixels at the right, and gives the place of each leaf's name so the caller can write it.
A residue that evolution keeps the same across a protein family often matters to the fold or to the function. A missense variant at such a site is more often harmful. Variant studies therefore read the conservation of each site in an alignment of the family.
from extensions.molecule.conservation import column_conservation, conservation_b_factors, henikoff_weights, parse_fasta, uniform_background
var rows = parse_fasta(open("family.fasta", "r").read()).sequences.copy()
var columns = column_conservation(rows, henikoff_weights(rows), uniform_background())
var scores = List[Float64]()
for column in columns:
scores.append(100.0 * column.score)
conservation_b_factors(structure, ChainId(0), rows[0], scores)-
parse_fasta(text)reads the names and the sequences of a FASTA text. The rows of an alignment hold the twenty one-letter codes, and-or.for a gap. -
henikoff_weights(rows)gives the weights of Henikoff and Henikoff (1994). In each column, a row with a residue gets1 / (r n). Here r is the count of residue types in the column, and n the count of its own type. Near copies of one sequence share their weight, so they do not make a column look more conserved. -
column_conservation(rows, weights, background)gives aColumnConservationfor each column. The background holds the share of each amino acid in the order ARNDCQEGHILKMFPSTWYV, such asuniform_background()or the mean composition of the family. -
conservation_b_factors(structure, chain, row, values)writes the value of each column into the B-factors of the residues of a chain. The row without its gaps must be the sequence of the chain. Then the colors of a B-factor show the conservation on a ribbon or a surface.
A ColumnConservation has these fields, with the residues weighted and the gaps left out of the shares:
| Field | Meaning |
|---|---|
gaps |
The weighted share of the rows with a gap |
entropy |
The Shannon entropy of the shares, in bits: 0 when one residue fills the column, and at most log2(20), or 4.32 |
relative_entropy |
The relative entropy of the shares to the background, in bits |
divergence |
The Jensen-Shannon divergence of the shares and the background, in bits, from 0 to 1 |
score |
The divergence times one less the share of gaps, after Capra and Singh (2007) |
A column of gaps only has 0 for each value but gaps.
The sequence of a protein gives its charge, its mass and how it absorbs light. A laboratory uses them to purify a protein, to measure its concentration, and to choose a buffer.
from extensions.molecule.protparam import average_mass, extinction_coefficients, isoelectric_point
var ubiquitin = "MQIFVKTLTGKTITLEVEPSDTIENVKAKIQDKEGIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLHLVLRLRGG"
print(average_mass(ubiquitin).to(GRAM_PER_MOLE), isoelectric_point(ubiquitin))-
net_charge(sequence, ph)sums the charges of the ends and of the ionizable side chains at a pH, by the equation of Henderson and Hasselbalch. It takes the pK values of EMBOSS. They are 8.6 for the N terminus and 3.6 for the C terminus. They are K 10.8, R 12.5, H 6.5, D 3.9, E 4.1, C 8.5 and Y 10.1. -
isoelectric_point(sequence)finds the pH of no net charge by 200 bisections from pH 0 to 14. -
average_mass(sequence)sums the average masses of the free amino acids, less one water for each peptide bond, as Biopython does. The result is aMolarMass64. -
extinction_coefficients(sequence)gives the molar extinction at 280 nm,5500 W + 1490 Y, after Pace and others (1995). The second value adds 125 for each pair of cysteines as a cystine. Each is aMolarArea64in M^-1 cm^-1. -
gravy(sequence)gives the mean hydropathy of Kyte and Doolittle, above 0 for a hydrophobic protein. -
aromaticity(sequence)gives the share of F, W and Y. -
aliphatic_index(sequence)gives100 (x_A + 2.9 x_V + 3.9 (x_I + x_L))of the shares x, after Ikai (1980). A higher index means a protein more stable to heat.
Superpose two models before you compare them, such as two models of an NMR ensemble, or a crystal structure and a prediction.
var pairs = matched_atoms(crystal, ModelId(0), predicted, ModelId(0), "CA")
var fixed = List[V3]()
var moving = List[V3]()
for pair in pairs:
fixed.append(crystal.atoms[pair[0]].position)
moving.append(predicted.atoms[pair[1]].position)
var fit = superpose(fixed, moving)
print(fit.rmsd.to(METER) / Length64(1.0, ANGSTROM).to(METER), "angstroms")superpose(fixed, moving) gives the rotation and the translation that put the moving points on the fixed points with the least root mean square deviation (RMSD). This is the problem of Kabsch. The method is Horn's: the best rotation is the unit quaternion of the largest eigenvalue of a 4 by 4 matrix. A quaternion is always a proper rotation, so the fit never mirrors a set. The sets need three or more points.
fit.apply(p) moves a point, and fit.rmsd is the deviation after the move. rmsd(fixed, moving) gives the deviation without a move.
matched_atoms(fixed, model, moving, model, name) pairs the atoms of one name, such as CA. Two atoms pair when their chains have one label, and their residues one number and insertion code. Of alternate locations, the first in the file pairs.
An NMR structure is an ensemble of models, and a simulation gives a series of snapshots. The root mean square fluctuation (RMSF) of an atom shows how far it moves over the models. ensemble_fluctuation gives it.
var spread = ensemble_fluctuation(structure, "CA", ModelId(0), FIT_TO_REFERENCE)
for row in range(spread.count()):
print(spread.atoms[row].value, spread.fluctuation(row).to(ANGSTROM))
fluctuation_b_factors(structure, spread)
color_surface(surface, structure, ModelId(0), COLOR_BY_B_FACTOR)The RMSF of an atom is sqrt(mean(|x_k - mean(x)|^2)) over the models k. The result has one row for each atom of the reference model with the name that every model has. Atoms pair as matched_atoms pairs them.
FIT_TO_REFERENCE first superposes each model on the reference model by the compared atoms, so a rigid move does not count. This needs three shared atoms. AS_GIVEN uses the coordinates of the file, such as snapshots that were fitted before. spread.deviation(model) gives the RMSD of a model from the reference after the fit.
fluctuation_b_factors(structure, spread) writes each RMSF into the reference model as an isotropic B-factor, B = 8 pi^2 RMSF^2 / 3. Each atom of the residue gets it. The B-factor coloring of a surface then shows the mobile parts in red.
model_distances gives the RMSD between every two models of an ensemble, over one atom of each residue. cluster_models groups the models that are close to each other. Use them to find the representative model of an NMR ensemble, or the main shapes of a simulation.
var table = model_distances(structure, "CA", FIT_TO_REFERENCE)
print(table.distance(ModelId(0), ModelId(3)).to(ANGSTROM), table.medoid().value)
var groups = cluster_models(table, Length64(1.5, ANGSTROM))
print(len(groups), groups[0][0].value, len(groups[0]))With FIT_TO_REFERENCE, the second model of each pair is first superposed on the first model, so only the change of shape counts. With AS_GIVEN, the coordinates are compared as they are. The compared atoms are those of the first model that every model has. shared_positions(structure, name, reference) gives them and their positions in each model.
table.medoid() gives the model with the least sum of RMSDs to the others. It is the most central model of the ensemble.
cluster_models uses the method of Daura and others, the gromos method of GROMACS. Two models are neighbors when their RMSD is at most the cutoff, and each model is its own neighbor. The model with the most neighbors is the center of the first cluster. The cluster holds the center and its neighbors, and those models leave the pool. The next cluster forms from the rest, until no model is left.
The first model of each cluster is its center, and the clusters come largest first. Of two models with as many neighbors, the lower model counts.
molecular_shape(structure, model) gives the size and shape of a model:
| Field | What it holds |
|---|---|
mass |
The sum of the standard atomic weights, a MolarMass64
|
center |
The mass center, in meters |
radius_of_gyration |
The root mean square distance of the mass from its center, as small-angle scattering measures it |
axes |
The three principal axes, unit and square, the longest first |
extents |
The root mean square distance of the mass along each axis |
Each atom weighs its element's standard atomic weight. The axes are the eigenvectors of the gyration tensor, the weighted mean of (r - c)(r - c)^T. A globular protein has three similar extents. A helix or a fiber has one large extent and two small ones. An element without a standard weight, such as an unknown X, is refused.
A distance map shows a fold at a glance. A helix is a band along the diagonal, two strands that pair make a line across it, and two domains make blocks. A contact map does not change when a model turns, so structure prediction compares contact maps.
var map = distance_map(structure, ModelId(0), "CA")
var contacts = map.contacts(Length64(8, ANGSTROM), 6)
Path("map.png").write_bytes(encode(map_image(map, Length64(20, ANGSTROM))))distance_map(structure, model, name) takes one atom of each residue, such as CA or CB. A residue without the atom has no row. map.distance(row, column) gives the distance of one pair, and map.residues gives the residue of each row.
map.contacts(cutoff, separation) gives the pairs of rows closer than the cutoff, each pair once. Two residues of one chain must be at least separation residues apart. Residues of two chains always count. map_image(map, far) draws one pixel per pair: dark blue at zero distance, and white at far and beyond.
Some helices bind a membrane, such as those of antimicrobial peptides. Such a helix has its hydrophobic side chains on one face and its charged side chains on the other. The hydrophobic moment of Eisenberg and others measures how much a helix is amphipathic.

examples/helical_wheel.mojo makes this picture. The left wheel is magainin 2, from the skin of the African clawed frog. The right wheel is the designed peptide (LKKLLKL)3. Orange discs are hydrophobic and blue discs hydrophilic. The arrow points along the hydrophobic moment: 0.45 for magainin 2 and 0.77 for the designed peptide.
from extensions.molecule.amphipathic import hydrophobic_moment, sequence_hydrophobicity
var values = sequence_hydrophobicity("GIGKFLHSAKKFGKAFVGEIMNS")
var moment = hydrophobic_moment(values, Angle64(100, DEGREE64))
print(moment.mean, moment.moment, moment.direction.to(DEGREE64))sequence_hydrophobicity(sequence) gives the value of each residue on the normalized consensus scale of Eisenberg and others (1984), from -2.53 for arginine to 1.38 for isoleucine. eisenberg_hydrophobicity(code) gives the value of one code.
Each residue of an alpha helix turns 100 degrees about the axis. hydrophobic_moment(values, angle) sums the value h of each residue as a vector at its angle:
mu = |sum of h_n exp(i n delta)| / N
The result gives the mean hydrophobicity, the moment and its direction, the middle of the hydrophobic face. Use 100 degrees for an alpha helix, and 160 to 180 degrees for a strand.
window_moment(values, angle, window) gives the largest moment of a window of residues, as the R package Peptides gives it. Each window takes its first residue at angle 0, and start names the first residue of the best window. A window of 11 residues is usual.
helical_wheel(values, angle, size) draws the residues as seen down the axis of the helix. Residue n sits at the angle n * angle, clockwise from the top. The residues spiral out by one disc for each full turn, so that no two overlap. A dark arrow points along the moment. The result gives the center of each disc, so the caller can write each letter.
A surface comes with CPK colors. color_surface(geometry, structure, model, coloring) colors it again by another property of the atom under each vertex:
SurfaceColoring |
What the color shows |
|---|---|
COLOR_BY_ELEMENT |
The CPK color of the element |
COLOR_BY_B_FACTOR |
Blue at the least B-factor of the model, white halfway and red at the largest |
COLOR_BY_CHAIN |
The chain, in the palette of the ribbons |
COLOR_BY_HYDROPATHY |
Blue at -4.5 on the Kyte-Doolittle scale, white at 0 and orange at +4.5 |
COLOR_BY_CONFIDENCE |
The band of the pLDDT of a predicted model |
var surface = excluded_surface(structure, model, probe, spacing)
color_surface(surface, structure, model, COLOR_BY_HYDROPATHY)Each vertex takes the color of the atom whose van der Waals sphere is nearest it. A grid of cells, AtomCells, finds that atom. A residue that is not one of the twenty amino acids, such as water or a ligand, is gray in the hydropathy coloring. kyte_doolittle(name) gives the value of one residue, and atom_color gives the sRGB color of one atom. chain_color(index) gives the palette color of a chain.
The B-factor coloring shows the flexible parts of a crystal structure. A high B-factor can also show disorder or a poor model. The hydropathy coloring shows oily and charged patches. It does not compute an electrostatic potential.
color_surface_potential(geometry, structure, model, limit) colors a surface by the electrostatic potential of the protein's charged groups at each vertex. Red is negative, white neutral and blue positive, from -limit to +limit. Use it to find the charged patches where a ligand or a partner binds.
var surface = excluded_surface(structure, model, probe, spacing)
color_surface_potential(surface, structure, model, MolarEnergy64(10, KILOCALORIE_PER_MOLE))formal_charges(structure, model) places the charges of the groups that carry one at pH 7:
| Group | Atoms | Charge |
|---|---|---|
| Arginine | NH1 and NH2 | +0.5 each |
| Lysine | NZ | +1 |
| Aspartate | OD1 and OD2 | -0.5 each |
| Glutamate | OE1 and OE2 | -0.5 each |
| The N terminus of a chain | N of its first amino acid | +1 |
| The C terminus of a chain | OXT and O of its last amino acid | -0.5 each, or -1 on O without OXT |
| Ions of two charges | ZN, MG, CA, MN, FE, CU, NI, CO and CD | +2 |
| Ions of one charge | NA and K | +1 |
| Chloride | CL | -1 |
Histidine is neutral, as it mostly is at pH 7. coulomb_potential(charges, point) gives 332.0636 * sum(q / (4 r^2)) kcal/(mol e), with r in angstroms. This is the distance-dependent dielectric 4 r of UCSF Chimera's Coulombic coloring. A charge closer than 0.5 angstroms counts at 0.5 angstroms.
A structure predicted by AlphaFold or a similar model gives each residue a pLDDT from 0 to 100. The file holds it in the B-factor column of every atom of the residue. BY_CONFIDENCE colors a ribbon by it, and COLOR_BY_CONFIDENCE a surface, in the four bands of the AlphaFold Protein Structure Database.
| Band | pLDDT | Color |
|---|---|---|
| Very high | Above 90 | Dark blue, #0053D6
|
| Confident | Above 70, to 90 | Light blue, #65CBF3
|
| Low | Above 50, to 70 | Yellow, #FFDB13
|
| Very low | 50 and below | Orange, #FF7D45
|
var model = read_pdb_structure("AF-P69905-F1-model_v4.pdb", FIRST_LOCATION)
var ribbon = ribbon_geometry(model, ModelId(0), BY_CONFIDENCE, 6, 12)
var summary = confidence_summary(model, ModelId(0))
print(summary.mean, summary.very_high, summary.very_low)
examples/predicted.mojo makes this picture. Its model is synthetic: 38 residues of an ideal tail, helix, loop, strand and tail, with the pLDDT that a prediction often gives each part. The tails are very low, as a disordered end often is. The model has a mean pLDDT of 75.6, with 17 residues very high, 8 confident, 5 low and 8 very low.
confidence_summary(structure, model) gives the mean pLDDT of the residues with a CA atom, and the number of residues in each band. The pLDDT of a residue is the B-factor of its CA, read in square angstroms as the file gives it. confidence_color(plddt) gives the sRGB color of one value. A value on the edge of two bands, such as 90, is in the lower band, to a rounding of 1e-9.
A region of very low pLDDT is often disordered. Do not read its shape as a structure. A high pLDDT says that the local shape is likely right. It does not say that the domains are in the right place relative to each other.
ca_lddt(reference, reference_model, model, model_model) gives the local distance difference test (lDDT) of a model against a reference structure. Use it to score a predicted model against an experimental structure, or two models against each other. pLDDT is a network's guess of this score.
var scores = ca_lddt(experiment, ModelId(0), prediction, ModelId(0))
print(scores.total, scores.per_point[0])
lddt_b_factors(prediction, scores)
var ribbon = ribbon_geometry(prediction, ModelId(0), BY_CONFIDENCE, 6, 12)lDDT needs no superposition. Each pair of CA atoms closer than 15 angstroms in the reference is a pair to score. The thresholds are 0.5, 1, 2 and 4 angstroms. A pair scores a quarter for each threshold that the change of its distance in the model is below.
The lDDT of a residue is the mean score of its pairs, and total is the mean over all pairs. A residue with no pair within the cutoff scores 1. These are the rules of the CA lDDT in AlphaFold's code.
ca_lddt pairs the CA atoms by chain, residue number and insertion code, as matched_atoms does. lddt(reference, model, cutoff) scores two lists of paired points of your own, at any cutoff. lddt_b_factors(model, scores) writes 100 times each residue's score into its B-factors. Then the confidence colorings show the true local accuracy in the bands of pLDDT, beside the prediction's own pLDDT.
The tests check these results:
- A built helix has CA atoms 3.80 angstroms apart.
- The hydrogen bond from O of residue
ito N of residuei + 4is 2.8 to 3.3 angstroms. - A built alpha helix of 14 residues gives DSSP's pattern: coil at each end and helix between.
- Crafted bond matrices give antiparallel and parallel ladders by each rule, and a lone bridge gives none.
- A PDB fixture gives the expected chains, residues, elements and secondary structure. It holds two models, waters and an ion after
TER, an insertion code and alternate locations. - CB is 1.527 angstroms from CA.
- One atom with a probe has the whole area of its grown sphere.
- Two carbons 3 angstroms apart each lose a cap of
2 pi R h. The measured area matches to within one percent with 2000 points. - Every vertex of a van der Waals surface lies within 0.06 angstroms of an atom sphere, at a spacing of 0.3 angstroms.
- One atom's excluded surface is its van der Waals sphere, to within the chords of a 0.4 angstrom grid.
- Two carbons 3 angstroms apart have an excluded surface with a neck of 1.313 angstroms, the analytic radius, to within 0.03 angstroms.
- The distance transform is exact on a grid with one seed.
- A ribbon of
nresidues has(n - 1) samples + 1rings, and every normal is a unit vector. - An ideal peptide and a file of two models with alternate locations and hetero atoms read back the same after
encode_mmcif. So does a structure with a chain id of two characters, an atom name of six and a residue number of 123456. gemmi 0.7.5 read the written files with their models, atoms, helices, strands and insertion codes. Biopython 1.88 read the same atoms. That check is not part of the test suite. - An ideal peptide reads back the same after
encode_pdb, to the 0.001 angstrom of three decimals. So does a file of two models with alternate locations and hetero atoms. - Torsions of four points have the IUPAC sign: 0 for cis, 180 for trans, and +90 when the far bond turns clockwise. An ideal peptide gives the phi and psi of each of its kinds, and an omega of 180 degrees, to 1e-6 degrees. A residue without an N, a CA or a C has no entry. A chain break of 10 angstroms ends the angles at each side. A peptide of 20 residues got up to 0.3 angstroms of noise per coordinate and was written as a PDB file. Its angles match Biopython 1.88 to within 1e-4 degrees. That check is not part of the test suite.
- Two cysteines with their SG atoms 2.05 angstroms apart make one disulfide bond, which a cutoff of 2.0 does not find. Salt bridges pair each acid with its bases at the least distance, and leave out a far pair, an asparagine and a backbone atom.
- An ideal helix of 14 residues has 10 hydrogen bonds, each from residue
i + 4to residuei. A strand has none. - A carbon and an oxygen 5 angstroms apart have their mass center at the share
m_O / (m_C + m_O). Their radius of gyration isL sqrt(m1 m2) / (m1 + m2), along the bond. - Neighbor CA atoms of an ideal peptide are 3.8 angstroms apart. An alpha helix has its CA contacts within 8 angstroms at
i + 3andi + 4only, and a strand has none. - A superposition recovers a known rotation and shift to 1e-12, with a proper rotation. It does not reach a mirror image. A small turn away from the fit gives a larger RMSD. On 40 noisy points, its RMSD matches numpy's SVD solution to 16 digits. That check is not part of the test suite.
- Over three models as given, one CA moved by
+dand-dhas an RMSF ofd sqrt(2/3), and every other CA has none. Its residue gets the B-factor16 pi^2 d^2 / 9. Models that differ by rigid moves fit to an RMSF below 1e-9 angstroms. Five models with up to 0.5 angstroms of noise per coordinate match a numpy fit by SVD to 2e-15 angstroms. That check is not part of the test suite. - The largest areas are the 20 values of Tien and others. A residue's area is the sum of its atoms, and its RSA is that sum over the largest area. The middle of a built helix is more buried than its ends. On a peptide of 12 residues with 2000 points per sphere, the areas match Biopython 1.88's Shrake-Rupley to 0.1 percent. That check is not part of the test suite.
- Two carbons in two chains 3 angstroms apart each bury a cap of
2 pi R h, within 1 percent with 2000 points. Chains 20 angstroms apart bury nothing, and a third chain does not change the interface of the other two. On two helices 9 angstroms apart, the buried area of each residue matches Biopython 1.88's Shrake-Rupley to 0.001 square angstroms. That check is not part of the test suite. - A fragment of 6 residues, renumbered and moved, pairs by a local alignment with residues 4 to 9 of its whole chain. It fits back with an RMSD below 1e-15 m.
- A peptide numbered from 101, turned and moved, pairs no atom by number. Through the alignment, all 11 CA atoms pair, and the fit has an RMSD below 1e-15 m. A residue that only one chain has, or a residue without the atom, pairs nothing.
- Four models shifted 1 angstrom apart along x have RMSDs of
abs(a - b)angstroms as given, and none after the fit. Their medoid is model 1. One CA of eight moved by 3 angstroms gives an RMSD of3 / sqrt(8)angstroms as given. - Six models lie at shifts of 0, 0.5, 1, 5, 5.4 and 20 angstroms. At a cutoff of 1 angstrom, they form the clusters
0 1 2,3 4and5. On 12 noisy and moved models, the fitted table matches numpy's SVD solution to 5e-15 angstroms. The medoid and the clusters at four cutoffs match a Python version of the method. That check is not part of the test suite. - A local alignment of three tryptophans inside other residues is the three alone, with their start in each sequence. It takes a gap inside when the pairs around it pay for it. On the 40 random pairs, every local score matches Biopython's local
PairwiseAligner, and each alignment holds the stretch of each sequence from its start. That check is not part of the test suite. - BLOSUM62 is symmetric, with its diagonal from 4 to 11. Small alignments give their gaps at the ends, inside and in either sequence, with the scores of each gap. A sequence against itself has no gap and an identity of 1. All 400 BLOSUM62 values match Biopython 1.88. On 40 random pairs with changes, insertions and deletions, every score matches Biopython's
PairwiseAligner. That check is not part of the test suite. - Three points 3.8 angstroms apart, with the last moved 0.7 angstroms, give the lDDT 0.875, 0.875 and 0.75, and 5/6 in all. Moved 3 angstroms, the last scores 0.25, and moved 5 angstroms, 0. A turned and moved model scores 1, and a point with no pair scores 1. One CA moved 3 angstroms gives the least score of a helix.
- A peptide of 60 residues got up to 4.5 angstroms of noise per coordinate. The CA lDDT of each residue matches AlphaFold's formula in numpy to 2e-11. The total matches to 1e-13. That check is not part of the test suite.
- A test file holds each charged group, a water at a chain's end and four ions. It has a terminus with OXT and one without. It gives each charge, and a net charge of +5. One charge at 5 angstroms gives 332.0636 / 100 kcal/(mol e), and two opposite charges cancel halfway. A vertex near a lysine is blue, near a chloride red, and far from every charge white.
- The band colors are the four colors of the AlphaFold Protein Structure Database, with each edge in the lower band. A helix of eight residues with two in each band gives each count and the mean. A residue without a CA does not count. Each CA, and each ring of a ribbon, takes its band's color.
- A vertex takes the color of the nearest atom sphere, also far from every atom. On the excluded surface of an isoleucine and an arginine, each colors its own part orange or blue.
- Variants read as
R175H,p.R175Handp.Arg175His. Each malformed form is refused, as are a stop, a number of 0 and a change to the same amino acid. - Four variants on an ideal helix give their residues, their charge, hydropathy and BLOSUM62 changes, their mean B-factors and their RSA. Their contacts match a search of every pair of atoms. A wrong wild type and a missing number are refused.
The tests compare conservation with scipy 1.18.1 and Biopython 1.88 on a synthetic alignment of 12 rows and 48 columns. Some columns are held, some change at rising rates, some are free, and some have gaps. tools/make_conservation.mojo writes the alignment, and assets/conservation/make_conservation.py writes the expected values.
- With uniform weights, the share of gaps agrees to 1e-15. The entropy agrees with scipy's
entropyto 1e-14, and the Jensen-Shannon divergence with the square of scipy'sjensenshannonto 1e-14. - The relative entropy agrees with Biopython's
motifs.Motif.relative_entropy, from the counts, to 1e-13. The score agrees with the divergence times one less the share of gaps to 1e-14. - A held column has no entropy, and its relative entropy to a uniform background is
log2(20). Two copies of one row share the weight of a third row that differs. With those weights, a column of A, A and W has an entropy of 1 bit. No library gives the Henikoff weights, so the tests check them by hand only. The B-factors of a chain take the values of its columns past the gaps of its row.
The tests compare protparam with Biopython 1.88 and the Python package peptides 0.5.0 on five sequences. They are ubiquitin, magainin 2, melittin, LL-37 and a short peptide of each charged residue. assets/protparam/make_protparam.py writes them.
- The net charge at pH 7 and 7.4 agrees with peptides on the scale of EMBOSS to 1e-13. The isoelectric point agrees to 1e-8, because peptides stops its bisection when its ends agree to 1e-9.
- The average mass agrees with Biopython's
ProteinAnalysisto 1e-13, and the extinction coefficients are the same numbers. The GRAVY, the aromaticity and peptides' aliphatic index agree to 1e-14. - Glycine alone has its isoelectric point at 6.1, halfway between the pK values of its ends. Far below every pK, each base and the N terminus carry a full charge.
The tests compare phylogeny with Biopython 1.88 and scipy 1.18.1 on eight synthetic sequences of 120 residues. They evolve from one root along a known tree, by substitutions only. tools/make_phylogeny.mojo writes them, and assets/phylogeny/make_phylogeny.py writes the expected values.
- The p-distances from the alignments agree with Biopython's
DistanceCalculatorwith theidentitymodel to 1e-15. Kimura's distances agree with their closed form to 1e-14, because no library gives them. - The path lengths between the leaves of the neighbor-joining tree agree with Biopython's
DistanceTreeConstructor.njto 1e-13. Rooted at the midpoint, each leaf is as deep as Biopython'sroot_at_midpointputs it, to 1e-14. - The path lengths of the UPGMA tree are the cophenetic distances of scipy's average linkage, to 1e-14.
- The distances of the tree
((A:1,B:2):3,(C:4,D:5))give it back exactly, and its midpoint is the node over C and D. A clock tree writes the Newick text((D:2.0,C:2.0):1.0,(B:1.0,A:1.0):2.0):0.0;. Two sequences join half way. - A drawn clock tree has each leaf at the same column, in rows 28 pixels apart.
The tests compare amphipathic with the Python package peptides 0.5.0, a port of the R package Peptides. The peptides are melittin, magainin 2, LL-37 and a designed peptide. assets/amphipathic/make_amphipathic.py writes them.
- Each of the twenty values of the scale is that of peptides. The mean hydrophobicity and the moment of each whole peptide at 100 degrees agree to a relative 1e-13. The direction agrees with
atan2(sum h sin, sum h cos)to 1e-11 degrees. - The largest moment of a window of 11 residues agrees to 1e-13. The test finds its first residue by a search of all windows. The moment at 160 degrees agrees to 1e-12.
- One residue has its own value as its moment. Two equal residues 180 degrees apart cancel. A turn of four residues, two hydrophobic and two not, has the moment
sqrt(8) / 4at 45 degrees. - The first disc of a wheel sits straight up, 12 percent of the side out. Leucine is orange and lysine blue, and the arrow leaves the center along the moment.
Every function raises Error for input it cannot use.
| Case | Functions |
|---|---|
| A variant is not an amino acid, a number and an amino acid, has a number below 1, or does not change its amino acid |
parse_variant, Variant
|
| A variant's number is not in the chain, or the residue there is not its wild type, or the chain is not in the model, or the reach is not positive and finite | variant_sites |
| A quoted value or a text field has no end |
cif_tokens, parse_cif, parse_mmcif
|
| A link cutoff is not positive and finite |
disulfide_bonds, salt_bridges
|
| A sequence is empty or holds a code that is not one of the twenty, a value is not finite, the angle is not between 0 and 360 degrees, or a window is below 1 | amphipathic |
| A wheel has more than 100 residues, or its side is out of 64 to 4096 pixels | helical_wheel |
| There are not 2 to 1000 sequences, a matrix is not square, symmetric, finite and 0 or more with 0 on its diagonal, or the names do not fit it |
alignment_distances, neighbor_joining, upgma
|
| A p-distance is below 0, not finite or too large for Kimura's formula | kimura_distances |
| A leaf index names no leaf, or a tree has no root |
PhyloTree.path_length, midpoint_root
|
| A side of a tree image is out of 64 to 4096 pixels, or its label space is out of 0 to half its width | tree_image |
| A FASTA text has no record, a sequence before a name, or a record with no sequence | parse_fasta |
| Alignment rows are none, empty, of two lengths, or hold another code, or hold gaps only for weights |
henikoff_weights, column_conservation, conservation_b_factors
|
| The weights are not one for each row, 0 or more and finite, with a sum above 0, or the background is not twenty shares above 0 that sum to 1 | column_conservation |
| A row is not of the chain's sequence, or the values are not one finite value for each column | conservation_b_factors |
| A sequence is empty or holds a code that is not one of the twenty, or a pH is not finite | protparam |
| A sequence is empty or holds a code that is not standard, a gap score is positive or not finite, an alignment mode is not valid, or an alignment pairs no column |
align_sequences, blosum62, SequenceAlignment
|
| Two chains of an interface are one chain, are not in the model, or have no atoms |
chain_interface, ChainInterface
|
| The areas do not fit the atoms of the model, a residue is not a standard amino acid, or a cutoff is not positive |
residue_accessibility, max_accessible_area, ResidueAccess
|
| A potential coloring has a model id that names no model, a limit that is not positive and finite, or a geometry without positions |
formal_charges, color_surface_potential
|
| A confidence summary has a model id that names no model, no CA atom, or a pLDDT not from 0 to 100 | confidence_summary |
| An lDDT has lists of other sizes or none, a cutoff not positive and finite, no shared CA atom, or scores without atom pairs |
lddt, ca_lddt, lddt_b_factors
|
| An ensemble has fewer than two models, too few shared atoms, or a bad fit or reference |
ensemble_fluctuation, Fluctuation, shared_positions, model_distances
|
| A model id is outside a table, or a cluster cutoff is negative or not finite |
ModelDistances, cluster_models
|
| A structure has no model or no atom, its name holds a blank, or a value holds a line end or both kinds of closing quote |
encode_mmcif, cif_value
|
| No data block, a stray value, or a loop that does not fill its rows |
parse_cif, parse_mmcif
|
| A needed column is missing, or a value is not a number | parse_mmcif |
| An id names no entry |
require_atom, find_atom, bounds, ribbon_geometry
|
| A code is not a standard amino acid |
build_peptide, three_letter
|
| A count, a probe or a spacing is out of range |
ribbon_geometry, accessible_areas, molecular_surface
|
| A surface coloring is not valid, or an atom is not in the model |
color_surface, atom_color
|
| A bond radius or side count is out of range, or a bond's residue has no N or O | bond_geometry |
| Two sets differ in size, hold fewer than three points, or are not finite |
superpose, rmsd
|
| No residue has the atom, a row is outside the map, or a cutoff or separation is out of range |
distance_map, DistanceMap, map_image
|
| Three points of a torsion are in a line, or a plot size is not from 64 to 2048 pixels |
dihedral, backbone_angles, ramachandran_image
|
- The PDB reader does not read
CONECT,ANISOUorSEQRESrecords, or the hybrid-36 numbers of very large files. - The reader keeps the first data block only. It does not read anisotropic displacements, bonds or the chemical component dictionary.
- The readers do not infer secondary structure themselves. Call
assign_secondaryfor a file without helix and strand records. - Disulfide bonds and salt bridges are found by distance only. A salt bridge does not check the angle of its atoms, and leaves out histidine.
-
assign_secondarydoes not report 3-10 or pi helices, turns, bends, isolated bridges or beta bulges. - Ribbons need CA atoms. Nucleic acids have no ribbon.
- An ensemble is fitted on one reference model. The fit is not iterated to the mean of the models.
- A sequence holds the twenty standard amino acids only. A modified residue, such as selenomethionine
MSE, is left out. - A Ramachandran plot shows the angles only. It does not draw the favored and allowed regions of a reference set, and it does not validate a model.
- Where three or more spheres make a crevice, the excluded surface uses the grid bound. It can lie up to one grid step outside the true surface there.
- A surface grid holds at most 2^24 points. A large structure needs a larger spacing.
- A variant is found by its author number in the file. A file numbered another way, or a residue with an insertion code, needs its numbers mapped first. A site's measures are of the wild-type structure; the variant's own shape is not modeled.
- The Coulomb potential uses formal charges at pH 7 and the dielectric
4 r. It is not a Poisson-Boltzmann solution. It leaves out a charged histidine, other protonation states and the ions of the solvent. - A hydrophobic moment takes the sequence as one ideal helix or strand. It does not find where a helix starts or ends, and it does not predict the activity or the toxicity of a peptide.
- Conservation reads one alignment as it is given. It does not align the sequences, and a poor alignment gives poor scores. It has no pseudocounts and does not average over a window of columns. A conserved site is a clue for research, not a prediction that a variant causes disease.
- The parameters of a sequence take each residue as free in water. They do not see a residue buried in the fold, a modified residue, a bound metal or the shift of a pK in the protein.
- The trees are distance trees. They do not fit a model of evolution by likelihood, give no bootstrap support, and take the gaps of an alignment out of its identity. A tree of a few sequences is not a study of an outbreak.
- Westbrook and others, "PDBx/mmCIF Ecosystem: Foundational Semantic Tools for Structural Biology", 2022.
- Hall, Allen and Brown, "The Crystallographic Information File (CIF)", 1991.
- wwPDB, "Atomic Coordinate Entry Format Description", version 3.3, 2012.
- Barlow and Thornton, "Ion-pairs in proteins", 1983.
- Needleman and Wunsch, "A general method applicable to the search for similarities in the amino acid sequence of two proteins", 1970.
- Smith and Waterman, "Identification of common molecular subsequences", 1981.
- Daura and others, "Peptide folding: when simulation meets experiment", Angewandte Chemie International Edition, 1999.
- Jumper and others, "Highly accurate protein structure prediction with AlphaFold", Nature, 2021.
- Mariani and others, "lDDT: a local superposition-free score for comparing protein structures and models using distance difference tests", Bioinformatics, 2013.
- Pettersen and others, "UCSF Chimera: a visualization system for exploratory research and analysis", Journal of Computational Chemistry, 2004.
- Varadi and others, "AlphaFold Protein Structure Database", Nucleic Acids Research, 2022.
- Gotoh, "An improved algorithm for matching biological sequences", 1982.
- Henikoff and Henikoff, "Amino acid substitution matrices from protein blocks", 1992.
- Henikoff and Henikoff, "Position-based sequence weights", Journal of Molecular Biology, 1994.
- Capra and Singh, "Predicting functionally important residues from sequence conservation", Bioinformatics, 2007.
- Tien, Meyer, Sydykova, Spielman and Wilke, "Maximum allowed solvent accessibilities of residues in proteins", 2013.
- Engh and Huber, "Accurate bond and angle parameters for X-ray protein structure refinement", 1991.
- Parsons and others, "Practical conversion from torsion space to Cartesian space for in silico protein synthesis", 2005.
- Yang and others, "Improved protein structure prediction using predicted interresidue orientations", 2020.
- Shrake and Rupley, "Environment and exposure to solvent of protein atoms", 1973.
- Bondi, "van der Waals volumes and radii", 1964.
- Connolly, "Solvent-accessible surfaces of proteins and nucleic acids", 1983.
- Xu and Zhang, "Generating triangulated macromolecular surfaces by Euclidean distance transform", 2009.
- Felzenszwalb and Huttenlocher, "Distance transforms of sampled functions", 2012.
- Richardson, "The anatomy and taxonomy of protein structure", 1981.
- Kabsch and Sander, "Dictionary of protein secondary structure: pattern recognition of hydrogen-bonded and geometrical features", 1983.
- Kyte and Doolittle, "A simple method for displaying the hydropathic character of a protein", 1982.
- Eisenberg, Weiss and Terwilliger, "The helical hydrophobic moment: a measure of the amphiphilicity of a helix", Nature, 1982.
- Eisenberg, Schwarz, Komaromy and Wall, "Analysis of membrane and surface protein sequences with the hydrophobic moment plot", Journal of Molecular Biology, 1984.
- Zasloff, "Magainins, a class of antimicrobial peptides from Xenopus skin", Proceedings of the National Academy of Sciences, 1987.
- Saitou and Nei, "The neighbor-joining method: a new method for reconstructing phylogenetic trees", Molecular Biology and Evolution, 1987.
- Sokal and Michener, "A statistical method for evaluating systematic relationships", University of Kansas Science Bulletin, 1958.
- Kimura, "The Neutral Theory of Molecular Evolution", Cambridge University Press, 1983.
- Pace and others, "How to measure and predict the molar absorption coefficient of a protein", Protein Science, 1995.
- Ikai, "Thermostability and aliphatic index of globular proteins", Journal of Biochemistry, 1980.
- Gasteiger and others, "Protein identification and analysis tools on the ExPASy server", in The Proteomics Protocols Handbook, Humana Press, 2005.
- Kabsch, "A solution for the best rotation to relate two sets of vectors", 1976.
- Horn, "Closed-form solution of absolute orientation using unit quaternions", 1987.
Tutorials
How-to
- Install
- Run the checks
- GPU backend
- Coverage
- Measure examples
- Add a feature
- Add a scanned building
- Write documentation
Reference
- Scene graph
- Rotations
- Cameras
- Geometry
- Geometry addons
- Lofts and clipping groups
- Sculptor
- Procedural generators
- Meshes and assets
- Lines
- Points and sprites
- Helpers
- Scene objects
- Animated objects
- Raycasting
- Curves and paths
- Animation
- Skinning
- Materials
- Node materials
- TSL functions
- Lights
- Lighting addons
- Fog
- Textures
- Renderer
- Renderer hooks and material flags
- Rasterization
- GPU backend
- Render target
- Post-processing
- GPU computation
- Compute nodes
- Progressive light map
- Gaussian splats
- Voxel global illumination
- SVG renderer
- Image files
- Image decode queue
- Model files
- More model files
- Exporters
- Scene JSON
- Windowing and controls
- C ABI and hosts
- Math
- Norm consumers
- Math addons
- Units
- Coverage tool
- Commands
- Examples
- Benchmarks
- Extensions
- Shared physics
- Physics query snapshots
- Continuous collision
- Tick force restoration
- Water
- Warp drives
- Vegetation
- Village
- Streamline
- Animals
-
Buildings
- Numerics
- Building topology
- Building model
- IFC exchange
- Procedural towers
- Floor plans and interiors
- Frame analysis
- Shell analysis
- Building energy
- Construction kits
- Bearing walls
- Scanned buildings
- SOG files
- Compressed PLY files
- Scan parts
- Cleaning and orienting scans
- Walking through a scan
- Virtual scans
- Castle
- CARLA
- Femur
- Tibia
- Fibula
- Patella
- Knee
- Muscles
- Vessels
- Lymph
- Nerves
- Integument
- Leg
- Foot
- Pelvis
- Torso
- Arm
- Hand
- Head
- Genome
- Game humanoid
- Humanoid fidelity
- Mixamo animations
- Audio-aligned game faces
- Converted assets
- Mesh quality
- Garments
- Outfits and armor
- Cloth and spring bones
- Attire estimates
- Segment inertia
- Process chemistry
- Thermochemical data
- Chemical equilibrium
- Process maps
- Rates and transport
- Electrolysis and film color
- Binary solutions
- Flowsheets and routes
- Materials and coatings
- Crystals and figures
- Diamond growth
- Medical imaging
- Molecular structures
- Tetrahedral FEM
- Finite-volume flow
- Pipe networks
- Open channels
- Groundwater flow
- Survival analysis
- Diagnostic tests
- Meta-analysis
- Epidemic models
- Sample size and power
- Group comparisons
- Observational studies
Explanation
- Software rasterizer
- Engineering solvers are original code
- Scene graph as an array
- Linear color
- Normals are not colors
- Perspective correction
- Fixed-point coverage
- Per-fragment shading
- Mipmaps
- Sorted transparency
- Types and checks
- Render hooks as a trait
- Shared CPU and GPU code
- Bands and threads
- PNG structure
- Extensions beside the port
- Process temperatures
- Scans as building models
- CUDA teardown hang
- Mojo compiler hang