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.0rc1.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.0rc1-py3-none-any.whl (26.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: torch_fit_in_map-0.6.0rc1.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.0rc1.tar.gz
Algorithm Hash digest
SHA256 d5c8a191ff1c4457a03ae8a608786590490c5cf7e819f51de369157e99c1816d
MD5 7e3e8cd5b05d3fe0a609c5700730d2fe
BLAKE2b-256 81948f7b1a797008e0a0949394dd1197a1241604a4133a794c496d03b5bf0ec5

See more details on using hashes here.

Provenance

The following attestation bundles were made for torch_fit_in_map-0.6.0rc1.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.0rc1-py3-none-any.whl.

File metadata

File hashes

Hashes for torch_fit_in_map-0.6.0rc1-py3-none-any.whl
Algorithm Hash digest
SHA256 6f83461a1a0837b2d3c4d3078ab7849c4223a49836884c548c28d344169cfcc9
MD5 788216fbda5659e7bb45cae305555706
BLAKE2b-256 b67dbb8dec1e34342aeec5c622fdd4ceecde6a30f6044befe4e9e1e73bd7b8ce

See more details on using hashes here.

Provenance

The following attestation bundles were made for torch_fit_in_map-0.6.0rc1-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.0rc1 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