CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-dscribe

A Python package for creating feature transformations in applications of machine learning to materials science.

Pending
Overview
Eval results
Files

core-classes.mddocs/

Core Classes

DScribe's core classes provide enhanced functionality for representing atomic systems and lattices beyond the standard ASE (Atomic Simulation Environment) library. These classes form the foundation for efficient descriptor calculations.

Capabilities

System Class

The System class extends ASE's Atoms class with caching capabilities for time-consuming calculations that are shared across multiple descriptors. This optimization significantly improves performance when computing multiple descriptors for the same atomic structure.

class System:
    def __init__(self, symbols=None, positions=None, numbers=None, tags=None, momenta=None,
                 masses=None, magmoms=None, charges=None, scaled_positions=None,
                 cell=None, pbc=None, celldisp=None, constraint=None, calculator=None,
                 info=None, wyckoff_positions=None, equivalent_atoms=None):
        """
        Initialize System with same parameters as ASE Atoms.
        
        Parameters:
        - symbols: Chemical symbols or atomic numbers
        - positions: Atomic coordinates in Cartesian form
        - numbers: Atomic numbers
        - tags: Integer tags for atoms
        - momenta: Atomic momenta
        - masses: Atomic masses
        - magmoms: Magnetic moments
        - charges: Atomic charges
        - scaled_positions: Fractional coordinates
        - cell: Unit cell vectors
        - pbc: Periodic boundary conditions
        - celldisp: Cell displacement
        - constraint: Geometric constraints
        - calculator: Attached calculator
        - info: Additional information dictionary
        - wyckoff_positions: Wyckoff position labels
        - equivalent_atoms: Equivalent atom groupings
        """

    @staticmethod
    def from_atoms(atoms):
        """
        Create System from ASE Atoms object.
        
        Parameters:
        - atoms: ASE Atoms object
        
        Returns:
        System: New System object with same properties as input
        """

    def get_cell_inverse(self):
        """
        Get inverse of the lattice matrix.
        
        Returns:
        numpy.ndarray: 3x3 inverse lattice matrix
        """

    def to_scaled(self, positions, wrap=False):
        """
        Transform Cartesian positions to fractional coordinates.
        
        Parameters:
        - positions: Cartesian coordinates to transform
        - wrap (bool): Whether to wrap coordinates to [0,1) range
        
        Returns:
        numpy.ndarray: Fractional coordinates
        """

    def to_cartesian(self, scaled_positions, wrap=False):
        """
        Transform fractional coordinates to Cartesian positions.
        
        Parameters:
        - scaled_positions: Fractional coordinates to transform
        - wrap (bool): Whether to wrap coordinates before transformation
        
        Returns:
        numpy.ndarray: Cartesian coordinates
        """

    def get_displacement_tensor(self):
        """
        Get pairwise displacement vectors between all atoms.
        
        Returns:
        numpy.ndarray: 3D array with shape (n_atoms, n_atoms, 3) containing
        displacement vectors from atom i to atom j
        """

    def get_distance_matrix(self):
        """
        Get pairwise distance matrix between all atoms.
        
        Returns:
        numpy.ndarray: 2D array with shape (n_atoms, n_atoms) containing
        distances between all atom pairs
        """

    def get_distance_matrix_within_radius(self, radius, pos=None, output_type="coo_matrix"):
        """
        Get sparse distance matrix containing only distances within cutoff radius.
        
        Parameters:
        - radius (float): Cutoff radius in angstroms
        - pos: Positions to use (defaults to atomic positions)
        - output_type (str): Output format ("coo_matrix", "dense")
        
        Returns:
        scipy.sparse matrix or numpy.ndarray: Sparse or dense distance matrix
        """

    def get_inverse_distance_matrix(self):
        """
        Get inverse distance matrix (1/r_ij) between all atoms.
        
        Returns:
        numpy.ndarray: 2D array with shape (n_atoms, n_atoms)
        """

Usage Example:

from dscribe.core import System
from ase.build import molecule, bulk

# Create System from ASE Atoms
atoms = molecule("H2O")
system = System.from_atoms(atoms)

# Direct creation with parameters
system = System(
    symbols=["H", "H", "O"],
    positions=[[0.0, 0.757, 0.587], [0.0, -0.757, 0.587], [0.0, 0.0, -0.074]]
)

# Use enhanced methods
distance_matrix = system.get_distance_matrix()
sparse_distances = system.get_distance_matrix_within_radius(3.0)
displacement_vectors = system.get_displacement_tensor()

# Work with periodic systems
bulk_system = System.from_atoms(bulk("NaCl", "rocksalt", a=5.64))
fractional_coords = bulk_system.to_scaled(bulk_system.positions)
cartesian_coords = bulk_system.to_cartesian(fractional_coords)

Lattice Class

The Lattice class represents crystallographic unit cells and provides methods for coordinate transformations between Cartesian and fractional coordinate systems.

class Lattice:
    def __init__(self, matrix):
        """
        Initialize Lattice from lattice matrix.
        
        Parameters:
        - matrix: 3x3 lattice matrix or 9-element sequence representing lattice vectors
        """

    @property
    def matrix(self):
        """
        Copy of the lattice matrix.
        
        Returns:
        numpy.ndarray: 3x3 lattice matrix
        """

    @property
    def inv_matrix(self):
        """
        Inverse of the lattice matrix.
        
        Returns:
        numpy.ndarray: 3x3 inverse lattice matrix
        """

    @property
    def lengths(self):
        """
        Lengths of lattice vectors.
        
        Returns:
        numpy.ndarray: Array of lattice vector lengths [a, b, c]
        """

    @property
    def abc(self):
        """
        Tuple of lattice lengths.
        
        Returns:
        tuple: Lattice lengths (a, b, c)
        """

    @property
    def reciprocal_lattice(self):
        """
        Reciprocal lattice with 2π factor.
        
        Returns:
        Lattice: Reciprocal lattice object
        """

    @property
    def reciprocal_lattice_crystallographic(self):
        """
        Crystallographic reciprocal lattice (without 2π factor).
        
        Returns:
        Lattice: Crystallographic reciprocal lattice object
        """

    def get_cartesian_coords(self, fractional_coords):
        """
        Convert fractional coordinates to Cartesian coordinates.
        
        Parameters:
        - fractional_coords: Fractional coordinates to convert
        
        Returns:
        numpy.ndarray: Cartesian coordinates
        """

    def get_fractional_coords(self, cart_coords):
        """
        Convert Cartesian coordinates to fractional coordinates.
        
        Parameters:
        - cart_coords: Cartesian coordinates to convert
        
        Returns:
        numpy.ndarray: Fractional coordinates
        """

    def get_points_in_sphere(self, frac_points, center, r, zip_results=True):
        """
        Find all points within a sphere considering periodic boundary conditions.
        
        Parameters:
        - frac_points: Fractional coordinates of points to search
        - center: Center point in fractional coordinates
        - r (float): Search radius in angstroms
        - zip_results (bool): Whether to zip results together
        
        Returns:
        list or tuple: Points within sphere, optionally with distances and indices
        """

Usage Example:

from dscribe.core import Lattice
import numpy as np

# Create lattice from matrix
lattice_matrix = np.array([
    [5.0, 0.0, 0.0],
    [0.0, 5.0, 0.0], 
    [0.0, 0.0, 5.0]
])
lattice = Lattice(lattice_matrix)

# Access properties
print(f"Lattice lengths: {lattice.abc}")
print(f"Volume: {np.linalg.det(lattice.matrix)}")

# Coordinate conversions
fractional_coords = np.array([[0.5, 0.5, 0.5], [0.0, 0.0, 0.0]])
cartesian_coords = lattice.get_cartesian_coords(fractional_coords)
back_to_fractional = lattice.get_fractional_coords(cartesian_coords)

# Find neighbors within sphere
center = np.array([0.5, 0.5, 0.5])
points_in_sphere = lattice.get_points_in_sphere(
    fractional_coords, center, radius=2.0
)

# Work with reciprocal lattice
reciprocal = lattice.reciprocal_lattice
reciprocal_crystallographic = lattice.reciprocal_lattice_crystallographic

Integration with Descriptors

System Caching Benefits

The System class provides significant performance improvements through caching:

  • Distance matrices: Computed once and reused across multiple descriptors
  • Displacement tensors: Cached for efficient neighbor finding
  • Coordinate transformations: Fractional/Cartesian conversions are cached
  • Inverse matrices: Cell inverse calculations are cached

This is especially beneficial when computing multiple descriptors for the same structure:

from dscribe import System
from dscribe.descriptors import SOAP, ACSF
from ase.build import molecule

# Create system once
water = System.from_atoms(molecule("H2O"))

# Multiple descriptors benefit from shared caching
soap = SOAP(species=["H", "O"], r_cut=5.0, n_max=8, l_max=6)
acsf = ACSF(species=["H", "O"], r_cut=6.0, g2_params=[[1, 1], [1, 2]])

# Distance calculations are shared between descriptors
soap_desc = soap.create(water)  # Distance matrix computed and cached
acsf_desc = acsf.create(water)  # Reuses cached distance matrix

Lattice Usage in Descriptors

The Lattice class is used internally by descriptors for periodic systems:

  • Coordinate transformations: Converting between fractional and Cartesian coordinates
  • Neighbor finding: Finding atoms within cutoff radii across periodic boundaries
  • Cell extensions: Creating extended unit cells for local environment calculations

Compatibility with ASE

Both System and Lattice classes maintain full compatibility with ASE:

  • System: Can be used anywhere ASE Atoms objects are accepted
  • Lattice: Provides enhanced functionality for unit cell operations
  • Conversion: Easy conversion between DScribe and ASE objects

This compatibility ensures that DScribe integrates seamlessly with the broader Python materials science ecosystem.

Install with Tessl CLI

npx tessl i tessl/pypi-dscribe

docs

core-classes.md

global-descriptors.md

index.md

kernels.md

local-descriptors.md

matrix-descriptors.md

utilities.md

tile.json