torchref.base.math_numpy module

NumPy implementations of mathematical functions for crystallography.

Deprecated since version This: module is deprecated. Please import from domain-specific submodules:

  • torchref.base.coordinates - Coordinate transformations

  • torchref.base.reciprocal - Reciprocal space calculations

  • torchref.base.fourier - Grid utilities

  • torchref.base.alignment - Coordinate alignment

  • torchref.base.metrics - R-factors

This module is maintained for backward compatibility.

Example (new style - recommended):

from torchref.base.coordinates import cartesian_to_fractional
from torchref.base.metrics import get_rfactor

Example (old style - still works):

from torchref.base.math_numpy import cartesian_to_fractional
torchref.base.math_numpy.cartesian_to_fractional(xyz, cell)[source]

Convert Cartesian coordinates to fractional coordinates.

Parameters:
  • xyz (numpy.ndarray) – Cartesian coordinates with shape (N, 3).

  • cell (numpy.ndarray or list) – Unit cell parameters [a, b, c, alpha, beta, gamma] where lengths are in Angstroms and angles are in degrees.

Returns:

Fractional coordinates with shape (N, 3).

Return type:

numpy.ndarray

torchref.base.math_numpy.fractional_to_cartesian(xyz_fractional, cell)[source]

Convert fractional coordinates to Cartesian coordinates.

Parameters:
  • xyz_fractional (numpy.ndarray) – Fractional coordinates with shape (N, 3).

  • cell (numpy.ndarray or list) – Unit cell parameters [a, b, c, alpha, beta, gamma] where lengths are in Angstroms and angles are in degrees.

Returns:

Cartesian coordinates with shape (N, 3).

Return type:

numpy.ndarray

torchref.base.math_numpy.get_fractional_matrix(cell)[source]

Calculate the fractional-to-Cartesian transformation matrix.

Constructs the matrix B that transforms fractional coordinates to Cartesian coordinates based on the unit cell parameters.

Parameters:

cell (numpy.ndarray or list) – Unit cell parameters [a, b, c, alpha, beta, gamma] where lengths are in Angstroms and angles are in degrees.

Returns:

3x3 transformation matrix B such that cart = frac @ B.T.

Return type:

numpy.ndarray

torchref.base.math_numpy.get_inv_fractional_matrix(cell)[source]

Calculate the Cartesian-to-fractional transformation matrix.

Computes the inverse of the fractional matrix for converting Cartesian coordinates to fractional coordinates.

Parameters:

cell (numpy.ndarray or list) – Unit cell parameters [a, b, c, alpha, beta, gamma] where lengths are in Angstroms and angles are in degrees.

Returns:

3x3 inverse transformation matrix B_inv such that frac = cart @ B_inv.T.

Return type:

numpy.ndarray

torchref.base.math_numpy.convert_coords_to_fractional(df, cell)[source]

Convert coordinates from a DataFrame to fractional coordinates.

Extracts x, y, z columns from a DataFrame and converts them from Cartesian to fractional coordinates.

Parameters:
  • df (pandas.DataFrame) – DataFrame containing ‘x’, ‘y’, ‘z’ columns with Cartesian coordinates.

  • cell (numpy.ndarray or list) – Unit cell parameters [a, b, c, alpha, beta, gamma] where lengths are in Angstroms and angles are in degrees.

Returns:

Fractional coordinates with shape (N, 3).

Return type:

numpy.ndarray

torchref.base.math_numpy.reciprocal_basis_matrix(cell)[source]

Calculate the reciprocal basis matrix from unit cell parameters.

Computes the reciprocal space basis vectors (a*, b*, c*) that define the transformation from Miller indices to scattering vectors.

Parameters:

cell (numpy.ndarray or list) – Unit cell parameters [a, b, c, alpha, beta, gamma] where lengths are in Angstroms and angles are in degrees.

Returns:

3x3 matrix containing reciprocal basis vectors as rows [a*, b*, c*].

Return type:

numpy.ndarray

torchref.base.math_numpy.get_scattering_vectors(hkl, cell)[source]

Calculate scattering vectors from Miller indices and unit cell.

Transforms Miller indices to reciprocal space scattering vectors using the reciprocal basis matrix.

Parameters:
  • hkl (numpy.ndarray or list) – Miller indices with shape (N, 3).

  • cell (numpy.ndarray or list) – Unit cell parameters [a, b, c, alpha, beta, gamma] where lengths are in Angstroms and angles are in degrees.

Returns:

Scattering vectors in reciprocal space with shape (N, 3).

Return type:

numpy.ndarray

torchref.base.math_numpy.get_s(hkl, cell)[source]

Calculate the magnitude of scattering vectors for given Miller indices.

Computes |s| = 1/d where d is the interplanar spacing for each reflection.

Parameters:
  • hkl (numpy.ndarray) – Miller indices with shape (N, 3).

  • cell (numpy.ndarray or list) – Unit cell parameters [a, b, c, alpha, beta, gamma] where lengths are in Angstroms and angles are in degrees.

Returns:

Magnitude of scattering vectors with shape (N,).

Return type:

numpy.ndarray

torchref.base.math_numpy.get_real_grid(cell, max_res=0.8, gridsize=None)[source]

Generate a real-space grid of Cartesian coordinates.

Creates a 3D grid in fractional coordinates and converts it to Cartesian coordinates. Grid points are placed at cell edges following CCTBX convention.

Parameters:
  • cell (numpy.ndarray or list) – Unit cell parameters [a, b, c, alpha, beta, gamma] where lengths are in Angstroms and angles are in degrees.

  • max_res (float, optional) – Maximum resolution in Angstroms for grid spacing. Default is 0.8. Ignored if gridsize is provided.

  • gridsize (list or numpy.ndarray, optional) – Explicit grid dimensions [nx, ny, nz]. If provided, overrides max_res.

Returns:

Real-space grid coordinates with shape (nx, ny, nz, 3).

Return type:

numpy.ndarray

torchref.base.math_numpy.get_grids(cell, max_res=0.8)[source]

Generate real-space and reciprocal-space grids for Fourier transforms.

Creates a 3D grid in fractional coordinates and converts it to Cartesian coordinates, along with an empty reciprocal space grid.

Parameters:
  • cell (numpy.ndarray or list) – Unit cell parameters [a, b, c, alpha, beta, gamma] where lengths are in Angstroms and angles are in degrees.

  • max_res (float, optional) – Maximum resolution in Angstroms for grid spacing. Default is 0.8.

Returns:

  • recgrid (numpy.ndarray) – Empty reciprocal space grid with shape determined by resolution.

  • xyz_real_grid (numpy.ndarray) – Real-space grid coordinates with shape (nx, ny, nz, 3).

torchref.base.math_numpy.put_hkl_on_grid(real_space_grid, diff, hkl)[source]

Place structure factors on a reciprocal space grid.

Maps structure factor values to their corresponding positions on a 3D reciprocal space grid based on Miller indices.

Parameters:
  • real_space_grid (numpy.ndarray) – Real-space grid used to determine the reciprocal grid dimensions. Shape should be (nx, ny, nz, 3) or similar.

  • diff (numpy.ndarray) – Structure factor values (complex) to place on the grid.

  • hkl (numpy.ndarray) – Miller indices with shape (N, 3), used as grid indices.

Returns:

Complex reciprocal space grid with shape (nx, ny, nz).

Return type:

numpy.ndarray

torchref.base.math_numpy.rotate_coords_numpy(coords, phi, rho)[source]

Rotate 3D coordinates by phi and rho angles.

Applies a rotation transformation to a set of 3D coordinates using two rotation angles (phi and rho) in degrees.

Parameters:
  • coords (numpy.ndarray) – Array of 3D coordinates with shape (N, 3).

  • phi (float) – First rotation angle in degrees.

  • rho (float) – Second rotation angle in degrees.

Returns:

Rotated coordinates with the same shape as input (N, 3).

Return type:

numpy.ndarray

torchref.base.math_numpy.superpose_vectors_robust(target_coords, mobile_coords, weights=None, max_iterations=1)[source]

Superpose mobile coordinates onto target coordinates using the Kabsch algorithm.

Computes the optimal rotation and translation to minimize the weighted RMSD between two sets of 3D coordinates, with robust handling of special cases such as reflection.

Parameters:
  • target_coords (numpy.ndarray) – Target coordinates with shape (N, 3).

  • mobile_coords (numpy.ndarray) – Mobile coordinates with shape (N, 3) to be superposed onto target.

  • weights (numpy.ndarray, optional) – Per-atom weights for the superposition with shape (N,). Default is uniform weights.

  • max_iterations (int, optional) – Number of iterations for refinement. Default is 1 (standard Kabsch).

Returns:

  • transformation_matrix (numpy.ndarray) – 4x4 transformation matrix that maps mobile_coords onto target_coords.

  • rmsd (float) – Weighted root-mean-square deviation after superposition.

Raises:

ValueError – If input coordinate arrays have different shapes.

Notes

The algorithm uses SVD decomposition of the covariance matrix and handles the reflection case by checking the determinant of the rotation matrix.

torchref.base.math_numpy.align_pdbs(pdb1, pdb2, Atoms=None)[source]

Align two PDB structures using the Kabsch algorithm.

Superimposes pdb2 onto pdb1 by minimizing the RMSD between corresponding atoms. The transformation is applied in-place to pdb2.

Parameters:
  • pdb1 (pandas.DataFrame) – Reference PDB structure with ‘x’, ‘y’, ‘z’, ‘name’, and ‘tempfactor’ columns.

  • pdb2 (pandas.DataFrame) – Mobile PDB structure to be aligned onto pdb1.

  • Atoms (list, optional) – List of atom names to use for alignment. If None, all atoms are used.

Returns:

  • pdb2 (pandas.DataFrame) – Transformed pdb2 with updated coordinates.

  • rmsd (float) – Root-mean-square deviation after alignment.

torchref.base.math_numpy.get_alignment_matrix(pdb1, pdb2, Atoms=None)[source]

Calculate the transformation matrix to align two PDB structures.

Computes the 4x4 transformation matrix that would superimpose pdb2 onto pdb1 without actually applying the transformation.

Parameters:
  • pdb1 (pandas.DataFrame) – Reference PDB structure with ‘x’, ‘y’, ‘z’, ‘name’, and ‘tempfactor’ columns.

  • pdb2 (pandas.DataFrame) – Mobile PDB structure.

  • Atoms (list, optional) – List of atom names to use for alignment. If None, all atoms are used.

Returns:

  • transformation_matrix (numpy.ndarray) – 4x4 transformation matrix.

  • rmsd (float) – Root-mean-square deviation that would result from the alignment.

torchref.base.math_numpy.apply_transformation(points, transformation_matrix)[source]

Apply a 4x4 transformation matrix to 3D points.

Converts points to homogeneous coordinates, applies the transformation, and returns the transformed 3D coordinates.

Parameters:
  • points (numpy.ndarray) – 3D coordinates with shape (N, 3).

  • transformation_matrix (numpy.ndarray) – 4x4 transformation matrix containing rotation and translation.

Returns:

Transformed 3D coordinates with shape (N, 3).

Return type:

numpy.ndarray

torchref.base.math_numpy.invert_transformation_matrix(transformation_matrix)[source]

Compute the inverse of a 4x4 transformation matrix.

Efficiently inverts a rigid-body transformation matrix by transposing the rotation component and computing the inverse translation.

Parameters:

transformation_matrix (numpy.ndarray) – 4x4 transformation matrix containing rotation (top-left 3x3) and translation (top-right 3x1).

Returns:

Inverse 4x4 transformation matrix.

Return type:

numpy.ndarray

Notes

This function assumes the input is a valid rigid-body transformation (rotation + translation). For such matrices, the inverse rotation is simply the transpose, and the inverse translation is computed as -R^T @ t.

torchref.base.math_numpy.get_rfactor(F_obs, F_calc)[source]

Calculate the R-factor between observed and calculated structure factors.

The R-factor is a measure of agreement between observed and calculated structure factor amplitudes, defined as sum(|F_obs - F_calc|) / sum(F_obs).

Parameters:
  • F_obs (numpy.ndarray) – Observed structure factor amplitudes.

  • F_calc (numpy.ndarray) – Calculated structure factor amplitudes.

Returns:

R-factor value between 0 and 1.

Return type:

float

torchref.base.math_numpy.calc_outliers(F_obs, F_calc, z)[source]

Identify outlier reflections based on structure factor differences.

Detects reflections where the normalized difference between observed and calculated structure factors exceeds z standard deviations.

Parameters:
  • F_obs (numpy.ndarray) – Observed structure factor amplitudes.

  • F_calc (numpy.ndarray) – Calculated structure factor amplitudes.

  • z (float) – Number of standard deviations for outlier threshold.

Returns:

Boolean array where True indicates an outlier reflection.

Return type:

numpy.ndarray

torchref.base.math_numpy.get_res_for_dataset(ds)[source]

Calculate resolution for each reflection in a dataset.

Computes the resolution (d-spacing) for each reflection based on the unit cell and Miller indices from a reciprocalspaceship dataset.

Parameters:

ds (reciprocalspaceship.DataSet) – Crystallographic dataset containing Miller indices and unit cell.

Returns:

Resolution values (d-spacing) for each reflection.

Return type:

numpy.ndarray