Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

torch-fit-in-map

License PyPI Python Version CI

Overview

torch-fit-in-map is a PyTorch package for rigid-body volume alignment in cryo-EM. It finds the rotation and translation that best superimposes a mobile volume onto a reference volume using normalised cross-correlation (NCC).

The public API operates purely on torch.Tensor potential maps and pandas.DataFrame atom tables — it does no file I/O. Reading/writing MRC and PDB/mmCIF files and the command-line tools live in the companion package torch-fit-in-map-cli.

Two alignment modes are supported:

  • Map-to-map — align one map onto another (fit_map_in_map).
  • Atoms <-> map — simulate an electrostatic potential from a table of atoms and align it against a map (fit_structure_in_map / fit_map_in_structure).

Features

  • Exhaustive SO(3) grid search with per-rotation FFT-based optimal translation
  • Symmetry-aware search (C1, C4, D2, T, O, I, …) to restrict to the asymmetric unit
  • Gradient-based local refinement (L-BFGS or Adam) using PyTorch autograd
  • Multi-start refinement to escape local minima
  • Optional soft masking and multi-GPU support
  • Atom-table transform: map input atomic coordinates into the reference frame (apply_alignment_to_structure)

Installation

pip install torch-fit-in-map

The atoms <-> map modes use the electrostatic-potential simulator torch-calculate-electrostatic-potential (installed automatically as a dependency).

Basic Usage

Map-to-map alignment

import torch
from torch_fit_in_map import fit_map_in_map, apply_alignment

# (d, h, w) float tensors at the same pixel size
reference = torch.load("reference.pt")
mobile    = torch.load("mobile.pt")

result = fit_map_in_map(mobile, reference, pixel_size_angstroms=1.5)

print(f"NCC score:        {result.score:.4f}")
print(f"Rotation (zyx):\n{result.rotation_matrix}")
print(f"Translation (px): {result.translation_pixels}")

aligned = apply_alignment(mobile, result)

If the two maps have different voxel sizes, resample first with normalise_voxel_sizes(reference, mobile, ref_px, mob_px).

Atoms <-> map alignment

Atoms are passed as a DataFrame with columns x, y, z (Angstroms) and element — exactly what mmdf produces:

import mmdf
from torch_fit_in_map import fit_structure_in_map

atoms = mmdf.read("model.pdb")          # pandas DataFrame

result = fit_structure_in_map(
    mobile_atoms=atoms,
    reference_map=experimental,          # (d, h, w) tensor
    pixel_size_angstroms=1.5,
    box_size=128,
)

fit_map_in_structure does the inverse (fit a map into the frame of an atomic structure). Both accept a custom simulator= implementing the PotentialSimulator protocol and optional simulator_config= for the default electrostatic-potential backend.

Simulation contract

The default simulator (DEFAULT_POTENTIAL_SIMULATOR) delegates to torch-calculate-electrostatic-potential:

  1. Atoms are centred at the cubic simulation-box centre (default_sublattice_radius(pixel_size) sets the per-atom stencil).
  2. A (box_size, box_size, box_size) potential in volts is returned (ZYX order).
  3. apply_alignment_to_structure inverts the same centre/crop geometry before applying the alignment transform.

Use PotentialSimulatorConfig to select Peng elemental vs bonded scattering factors. Bonded factors require structure columns chain, residue_id, residue, and atom (or set annotate_bonding=True).

The CLI wrappers torch-fit-in-map, torch-fit-in-atomic-model, and torch-simulate-density in torch-fit-in-map-cli call the same default simulator path.

Transforming atoms into the reference frame

from torch_fit_in_map import apply_alignment_to_structure

moved = apply_alignment_to_structure(
    atoms, result,
    pixel_size=1.5,
    box_shape=reference.shape,           # (d, h, w)
)   # returns a DataFrame with transformed x/y/z

Tuning the search

from torch_fit_in_map import (
    fit_map_in_map,
    ExhaustiveSearchConfig,
    GradientRefinementConfig,
)

result = fit_map_in_map(
    mobile,
    reference,
    exhaustive_config=ExhaustiveSearchConfig(
        angular_step_degrees=7.5,   # finer orientation sampling
        symmetry="C4",              # restrict to C4 asymmetric unit
        n_start=5,                  # refine top-5 poses independently
        devices=["cuda:0", "cuda:1"],
    ),
    gradient_config=GradientRefinementConfig(optimizer="lbfgs", n_iterations=200),
    pixel_size_angstroms=1.5,
)

Pass gradient_config=None to return the exhaustive-search result without refinement.

AlignmentResult

All alignment functions return an AlignmentResult:

Field Type Description
rotation_matrix (3, 3) tensor Rotation in zyx convention
translation_pixels (3,) tensor Translation in zyx pixels
score float Peak NCC score (higher is better, max 1.0)
translation_angstroms (3,) tensor or None Translation in Angstroms (when pixel size is provided)
simulated_potential (d, h, w) tensor or None Simulated potential when save_simulated=True

Use apply_alignment(mobile, result) to produce the aligned volume.

Command-line tools

The torch-fit-in-map, torch-fit-in-atomic-model and torch-simulate-density commands (with MRC/PDB file handling) live in torch-fit-in-map-cli. They use the same DEFAULT_POTENTIAL_SIMULATOR path as the Python API.

License

BSD 3-Clause — see the LICENSE file for details.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

torch_fit_in_map-0.6.0rc2.tar.gz (28.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

torch_fit_in_map-0.6.0rc2-py3-none-any.whl (26.0 kB view details)

Uploaded Python 3

File details

Details for the file torch_fit_in_map-0.6.0rc2.tar.gz.

File metadata

  • Download URL: torch_fit_in_map-0.6.0rc2.tar.gz
  • Upload date:
  • Size: 28.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for torch_fit_in_map-0.6.0rc2.tar.gz
Algorithm Hash digest
SHA256 affb7c548733cc7923cf287910697ae8d0dd8c3ad8cfef49e417f01da0515c50
MD5 ed8a8c5b7f70fc89ef1a7fe89d9ba198
BLAKE2b-256 0463fb58dca759ce7886a8a601a30e86f203edc56ee1a1545e4edc464df542c2

See more details on using hashes here.

Provenance

The following attestation bundles were made for torch_fit_in_map-0.6.0rc2.tar.gz:

Publisher: deploy.yml on teamtomo/teamtomo

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file torch_fit_in_map-0.6.0rc2-py3-none-any.whl.

File metadata

File hashes

Hashes for torch_fit_in_map-0.6.0rc2-py3-none-any.whl
Algorithm Hash digest
SHA256 42575de41bd7c59eb7287bee2247603ee2212d959cc684a1ebdb403f19ae5a9c
MD5 bbd41add321af7adfb333aac8f3375ae
BLAKE2b-256 768370da2ba3e1a1f9d30af287a0da13d10c3cb61d98debe4a4d7bba1a46be59

See more details on using hashes here.

Provenance

The following attestation bundles were made for torch_fit_in_map-0.6.0rc2-py3-none-any.whl:

Publisher: deploy.yml on teamtomo/teamtomo

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.6.0

2 files

This release

0.6.0rc2 This release

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page