site_analysis.builders
Builder pattern implementation for site_analysis.
This module provides a fluent builder interface for creating site analysis objects, making it easier to set up and run site analysis workflows.
Examples:
# Using the builder directly
trajectory = (TrajectoryBuilder()
.with_structure(structure)
.with_mobile_species("Li")
.with_spherical_sites(
centres=[[0.5, 0.5, 0.5], [0.0, 0.0, 0.0]],
radii=2.0,
labels=["octahedral", "tetrahedral"]
)
.build())
# Using a factory function
trajectory = create_trajectory_with_spherical_sites(
structure=structure,
mobile_species="Li",
centres=[[0.5, 0.5, 0.5], [0.0, 0.0, 0.0]],
radii=2.0,
labels=["octahedral", "tetrahedral"]
)
# Creating a trajectory with polyhedral sites
trajectory = create_trajectory_with_polyhedral_sites(
structure=target_structure,
reference_structure=reference_structure,
mobile_species="Li",
centre_species="O",
vertex_species=["Li", "Na"],
cutoff=3.0,
n_vertices=4,
label="tetrahedral"
)
- class TrajectoryBuilder[source]
Bases:
objectBuilder for creating Trajectory objects for site analysis.
This class provides a step-by-step approach to creating a Trajectory object for analysing site occupations in crystal structures.
Structure Alignment and Site Mapping
The builder supports separate control over structure alignment (finding optimal translations) and site mapping (identifying corresponding sites):
Structure alignment: Use
with_structure_alignment()to control whether and how structures are aligned before site creation.Site mapping: Use
with_site_mapping()to specify which species are used to identify corresponding sites between structures.
Default Behaviors
Alignment is enabled by default.
If mapping species are specified but alignment species are not, mapping species will be used for alignment.
If alignment species are specified but mapping species are not, alignment species will be used for mapping.
Example:
builder = TrajectoryBuilder() builder.with_structure(structure) .with_reference_structure(reference_structure) .with_mobile_species("Li") .with_structure_alignment(align=True, align_species=["O"]) .with_site_mapping(mapping_species=["Na"]) .with_polyhedral_sites( centre_species="Li", vertex_species="O", cutoff=2.0, n_vertices=4 ) trajectory = builder.build()
- build() Trajectory[source]
Build and return the Trajectory object.
This method validates all required parameters and generates sites using the previously configured site generator.
- Returns:
The constructed Trajectory object.
- Raises:
ValueError – If required parameters are missing, if the reference structure has same-species atom pairs closer than
min_atom_distance, or if duplicate sites are detected.
- reset() TrajectoryBuilder[source]
Reset the builder state to default values.
This method clears all configuration and returns the builder to its initial state. It is called automatically during initialization and after build(), but can also be called explicitly if needed.
- Returns:
For method chaining
- Return type:
self
- with_dynamic_voronoi_sites(centre_species: str, reference_species: str | list[str], cutoff: float, n_reference: int, label: str | None = None, use_reference_centers: bool = True) TrajectoryBuilder[source]
Define dynamic Voronoi sites using the ReferenceBasedSites workflow.
Creates dynamic Voronoi sites where the site centres are dynamically calculated from the positions of reference atoms. Unlike fixed Voronoi sites, these adapt to structural changes as the reference atoms move.
The workflow involves: 1. Finding coordination environments in the reference structure 2. Mapping these environments to the target structure 3. Creating DynamicVoronoiSite objects that calculate centres from reference atoms
Note
Sites will be generated when build() is called, not immediately. Requires both structure and reference_structure to be set.
- Parameters:
centre_species – Atomic species at centres where sites will be located.
reference_species – Atomic species used as reference atoms to define dynamic site centres. Can be a single species string or list of species strings.
cutoff – Maximum distance (in Ångströms) for reference atoms to be considered part of the coordination environment.
n_reference – Number of reference atoms required for each dynamic site.
label – Optional label to assign to all created sites. Default is None.
use_reference_centers –
Controls periodic boundary condition handling for reference-based sites (polyhedral and dynamic Voronoi sites). Default is True.
True(recommended) – Reference-based PBC correction. Defines a reference center for each site and unwraps vertex coordinates relative to this center. Correctly handles sites that naturally span >50% of unit cell dimensions, even in small simulation cells.False(advanced usage) – Spread-based PBC correction. If vertex coordinates span >50% of the unit cell in any dimension, assumes this indicates PBC wrapping and shifts coordinates accordingly. WARNING: Gives incorrect results when sites legitimately span >50% of the unit cell (e.g., octahedral sites in a 2x2x2 FCC supercell). May offer performance benefits for some setups. Only use after verifying it works correctly for your structures.
- Returns:
For method chaining
- Return type:
self
- Raises:
ValueError – At build() time if no coordination environments are found, or if required structures are not set.
Example:
# Dynamic sites at Li positions defined by neighbouring O atoms builder.with_dynamic_voronoi_sites( centre_species="Li", reference_species="O", cutoff=3.0, n_reference=4, label="tetrahedral_dynamic" ) # Sites with mixed reference species builder.with_dynamic_voronoi_sites( centre_species="Na", reference_species=["O", "F"], cutoff=2.8, n_reference=6, label="mixed_coordination" )
- with_existing_atoms(atoms: list) TrajectoryBuilder[source]
Use existing atom objects.
- Parameters:
atoms – list of atom objects
- Returns:
For method chaining
- Return type:
self
- with_existing_sites(sites: list) TrajectoryBuilder[source]
Use existing site objects.
- with_min_atom_distance(distance: float) TrajectoryBuilder[source]
Set the minimum allowed distance between same-species atoms in the reference structure.
If any pair of atoms of the same species in the reference structure is closer than this threshold,
build()raisesValueError. This catches reference structures where atoms sit on a general Wyckoff position instead of the correct special position, producing duplicate coordination environments.This check runs whenever a reference structure is set, regardless of site type. It is most relevant for polyhedral and dynamic Voronoi site workflows, but also applies when a reference structure is provided for mapping or alignment.
Set to 0 to disable the check.
- Parameters:
distance – Minimum distance in the same units as the lattice parameters. Must be non-negative. The builder default is 0.5.
- Returns:
For method chaining.
- Return type:
self
- Raises:
ValueError – If distance is negative.
- with_mobile_species(species: str | list[str]) TrajectoryBuilder[source]
Set the mobile species to track.
- Parameters:
species – Species string or list of species strings for mobile atoms
- Returns:
For method chaining
- Return type:
self
- with_polyhedral_sites(centre_species: str, vertex_species: str | list[str], cutoff: float, n_vertices: int, label: str | None = None, use_reference_centers: bool = True) TrajectoryBuilder[source]
Define polyhedral sites using the ReferenceBasedSites workflow.
Creates polyhedral sites by identifying coordination environments in the reference structure and mapping them to corresponding sites in the target structure. Each site is defined by a polyhedron formed by vertex atoms around a central atom.
The workflow involves: 1. Finding coordination environments in the reference structure 2. Mapping these environments to the target structure 3. Creating PolyhedralSite objects with proper periodic boundary handling
Note
Sites will be generated when build() is called, not immediately. Requires both structure and reference_structure to be set.
- Parameters:
centre_species – Atomic species at the centre of coordination environments.
vertex_species – Atomic species at vertices of coordination polyhedra. Can be a single species string or list of species strings.
cutoff – Maximum distance (in Ångströms) for vertex atoms to be considered part of the coordination environment.
n_vertices – Number of vertex atoms required for each polyhedral site.
label – Optional label to assign to all created sites. Default is None.
use_reference_centers –
Controls periodic boundary condition handling for reference-based sites (polyhedral and dynamic Voronoi sites). Default is True.
True(recommended) – Reference-based PBC correction. Defines a reference center for each site and unwraps vertex coordinates relative to this center. Correctly handles sites that naturally span >50% of unit cell dimensions, even in small simulation cells.False(advanced usage) – Spread-based PBC correction. If vertex coordinates span >50% of the unit cell in any dimension, assumes this indicates PBC wrapping and shifts coordinates accordingly. WARNING: Gives incorrect results when sites legitimately span >50% of the unit cell (e.g., octahedral sites in a 2x2x2 FCC supercell). May offer performance benefits for some setups. Only use after verifying it works correctly for your structures.
- Returns:
For method chaining
- Return type:
self
- Raises:
ValueError – At build() time if no coordination environments are found, or if required structures are not set.
Example:
# Tetrahedral sites around Li atoms builder.with_polyhedral_sites( centre_species="Li", vertex_species="O", cutoff=2.5, n_vertices=4, label="tetrahedral" ) # Octahedral sites with mixed vertex species builder.with_polyhedral_sites( centre_species="Ti", vertex_species=["O", "F"], cutoff=2.8, n_vertices=6, label="octahedral" )
- with_reference_structure(reference_structure) TrajectoryBuilder[source]
Set the reference structure for complex site types.
- Parameters:
reference_structure – A pymatgen Structure object representing the ideal reference structure
- Returns:
For method chaining
- Return type:
self
- with_site_mapping(mapping_species: str | list[str] | None) TrajectoryBuilder[source]
Set the species to use for mapping sites between reference and target structures.
Site mapping identifies corresponding sites between structures even when atom counts differ, for example when structures have different numbers of mobile ions but the same framework atoms.
If mapping species are specified but alignment species are not: - The mapping species will also be used for alignment (unless alignment is disabled)
If mapping species are not specified: - The alignment species will be used for mapping
- Parameters:
mapping_species – Species to use for mapping. Can be a string or list of strings. If None, alignment species will be used for mapping.
- Returns:
For method chaining
- Return type:
self
- with_spherical_sites(centres: list[list[float]], radii: float | list[float], labels: str | list[str] | None = None) TrajectoryBuilder[source]
Define spherical sites.
Note: Sites will be generated when build() is called.
- Parameters:
centres – list of fractional coordinate centres for spherical sites
radii – either a single radius (float) to use for all sites, or a list of radii (one per centre)
labels – either a single label (str) to use for all sites, a list of labels (one per centre), or None
- Returns:
For method chaining
- Return type:
self
- with_structure(structure) TrajectoryBuilder[source]
Set the structure to analyse.
- Parameters:
structure – A pymatgen Structure object
- Returns:
For method chaining
- Return type:
self
- with_structure_alignment(align: bool = True, align_species: str | list[str] | None = None, align_metric: str = 'rmsd', align_algorithm: str = 'Nelder-Mead', align_minimizer_options: dict[str, Any] | None = None, align_tolerance: float = 0.0001) TrajectoryBuilder[source]
Set options for aligning reference and target structures.
Structure alignment finds the optimal translation vector to superimpose the reference structure onto the target structure, minimizing distances between corresponding atoms.
Note
Structure alignment is ENABLED by default when using polyhedral or dynamic Voronoi sites, even if this method is not explicitly called. To disable alignment, call this method with align=False.
All parameters are optional and have sensible defaults:
- Parameters:
align – Whether to perform structure alignment. Default is True.
align_species – Species to use for alignment. Can be a string or list of strings. Default is None, which means: - If mapping species have been set with with_site_mapping(), those species will be used - Otherwise, all common species between structures will be used
align_metric – Metric for alignment. Options are: - ‘rmsd’: Root-mean-square deviation (default) - ‘max_dist’: Maximum distance between any atom pair
align_algorithm – Algorithm for optimization. Options are: - ‘Nelder-Mead’: Local optimizer, faster but may find local minima (default) - ‘differential_evolution’: Global optimizer, more robust but slower
align_minimizer_options – Additional options for the minimizer as a dictionary. Default is None (use algorithm defaults).
align_tolerance – Convergence tolerance for alignment optimizer. Default is 1e-4. Lower values (e.g., 1e-5) give more precise alignment but may take longer.
- Returns:
For method chaining
- Return type:
self
Example:
# Use default alignment (enabled, all species) builder.with_reference_structure(reference) builder.with_polyhedral_sites(...) # Specify alignment species explicitly builder.with_structure_alignment(align_species=["O", "Ti"]) # Disable alignment builder.with_structure_alignment(align=False) # Use global optimization for challenging alignments builder.with_structure_alignment( align_algorithm='differential_evolution', align_minimizer_options={'popsize': 20} )
- with_voronoi_sites(centres: list[list[float]], labels: list[str] | None = None) TrajectoryBuilder[source]
Define Voronoi sites.
Note: Sites will be generated when build() is called.
- create_trajectory_with_dynamic_voronoi_sites(structure: Structure, reference_structure: Structure, mobile_species: str | list[str], centre_species: str, reference_species: str | list[str], cutoff: float, n_reference: int, label: str | None = None, align: bool = True, align_species: str | list[str] | None = None, align_metric: str = 'rmsd', align_algorithm: str = 'Nelder-Mead', align_minimizer_options: dict[str, Any] | None = None, mapping_species: str | list[str] | None = None, align_tolerance: float = 0.0001, use_reference_centers: bool = True) Trajectory[source]
Create a Trajectory with dynamic Voronoi sites using reference-based workflow.
Creates a trajectory object with dynamic Voronoi sites where site centres are dynamically calculated from the positions of reference atoms. Unlike fixed Voronoi sites, these adapt to structural changes as the reference atoms move, making them suitable for analysing deformable frameworks.
- Parameters:
structure – Pymatgen Structure object containing the target structure to analyse.
reference_structure – Pymatgen Structure object defining coordination environments to identify and map.
mobile_species – Species string (e.g., “Li”) or list of species strings identifying the mobile atoms to track.
centre_species – Atomic species at centres where dynamic sites will be located in the reference structure.
reference_species – Atomic species used as reference atoms to define dynamic site centres. Can be a single species string or list of species strings.
cutoff – Maximum distance in Ångströms for reference atoms to be considered part of the coordination environment.
n_reference – Number of reference atoms required for each dynamic site.
label – Optional string label to assign to all created sites.
align – Whether to perform structure alignment before site mapping.
align_species – Species to use for structure alignment. If None and mapping_species is specified, mapping_species will be used.
align_metric – Alignment metric. Options are ‘rmsd’ for root-mean-square deviation or ‘max_dist’ for maximum distance.
align_algorithm – Optimisation algorithm. Options are ‘Nelder-Mead’ for local optimisation or ‘differential_evolution’ for global optimisation.
align_minimizer_options – Additional options dictionary for the alignment optimiser.
mapping_species – Species to use for mapping sites between structures. If None, align_species will be used.
align_tolerance – Convergence tolerance for alignment optimiser.
use_reference_centers – Whether to use reference centers for PBC handling. See TrajectoryBuilder.with_polyhedral_sites() for details. Default is True.
- Returns:
Configured trajectory object ready for site analysis.
- Return type:
- Raises:
ValueError – If no coordination environments are found, if required structures are not set, or if structure alignment fails.
- create_trajectory_with_polyhedral_sites(structure: Structure, reference_structure: Structure, mobile_species: str | list[str], centre_species: str, vertex_species: str | list[str], cutoff: float, n_vertices: int, label: str | None = None, align: bool = True, align_species: str | list[str] | None = None, align_metric: str = 'rmsd', align_algorithm: str = 'Nelder-Mead', align_minimizer_options: dict[str, Any] | None = None, mapping_species: str | list[str] | None = None, align_tolerance: float = 0.0001, use_reference_centers: bool = True) Trajectory[source]
Create a Trajectory with polyhedral sites using reference-based workflow.
Creates a trajectory object with polyhedral sites by identifying coordination environments in a reference structure and mapping them to corresponding sites in the target structure. Each site is defined by a polyhedron formed by vertex atoms around a central atom.
- Parameters:
structure – Pymatgen Structure object containing the target structure to analyse.
reference_structure – Pymatgen Structure object defining ideal coordination environments to identify and map.
mobile_species – Species string (e.g., “Li”) or list of species strings identifying the mobile atoms to track.
centre_species – Atomic species at the centre of coordination environments in the reference structure.
vertex_species – Atomic species at vertices of coordination polyhedra. Can be a single species string or list of species strings.
cutoff – Maximum distance in Ångströms for vertex atoms to be considered part of the coordination environment.
n_vertices – Number of vertex atoms required for each polyhedral site.
label – Optional string label to assign to all created sites.
align – Whether to perform structure alignment before site mapping.
align_species – Species to use for structure alignment. If None and mapping_species is specified, mapping_species will be used.
align_metric – Alignment metric. Options are ‘rmsd’ for root-mean-square deviation or ‘max_dist’ for maximum distance.
align_algorithm – Optimisation algorithm. Options are ‘Nelder-Mead’ for local optimisation or ‘differential_evolution’ for global optimisation.
align_minimizer_options – Additional options dictionary for the alignment optimiser.
mapping_species – Species to use for mapping sites between structures. If None, align_species will be used.
align_tolerance – Convergence tolerance for alignment optimiser.
use_reference_centers – Whether to use reference centers for PBC handling. See TrajectoryBuilder.with_polyhedral_sites() for details. Default is True.
- Returns:
Configured trajectory object ready for site analysis.
- Return type:
- Raises:
ValueError – If no coordination environments are found, if required structures are not set, or if structure alignment fails.
- create_trajectory_with_spherical_sites(structure: Structure, mobile_species: str | list[str], centres: list[list[float]], radii: float | list[float], labels: str | list[str] | None = None) Trajectory[source]
Create a Trajectory with spherical sites for site analysis.
Creates a trajectory object configured with spherical sites defined by centres and radii. Each spherical site represents a spherical volume in the crystal structure where atoms can be assigned based on distance from the centre.
- Parameters:
structure – Pymatgen Structure object containing the crystal structure to analyse.
mobile_species – Species string (e.g., “Li”) or list of species strings (e.g., [“Li”, “Na”]) identifying the mobile atoms to track.
centres – List of fractional coordinate triplets defining the centres of spherical sites. Each centre should be a list of three floats [x, y, z].
radii – Cutoff radius in Ångströms for spherical sites. If a single float is provided, all sites use the same radius. If a list is provided, it must have the same length as centres.
labels – Optional labels for the sites. Can be a single string applied to all sites, a list of strings (one per site), or None for no labels.
- Returns:
Configured trajectory object ready for site analysis.
- Return type:
- Raises:
ValueError – If the number of centres doesn’t match the number of radii or labels when lists are provided.
- create_trajectory_with_voronoi_sites(structure: Structure, mobile_species: str | list[str], centres: list[list[float]], labels: list[str] | None = None) Trajectory[source]
Create a Trajectory with Voronoi sites for site analysis.
Creates a trajectory object configured with Voronoi sites that partition space based on proximity to site centres. Each point in space is assigned to the Voronoi site with the nearest centre, ensuring complete space-filling coverage.
- Parameters:
structure – Pymatgen Structure object containing the crystal structure to analyse.
mobile_species – Species string (e.g., “Li”) or list of species strings (e.g., [“Li”, “Na”]) identifying the mobile atoms to track.
centres – List of fractional coordinate triplets defining the centres of Voronoi sites. Each centre should be a list of three floats [x, y, z].
labels – Optional list of string labels for the sites. Must have the same length as centres if provided, or None for no labels.
- Returns:
Configured trajectory object ready for site analysis.
- Return type:
- Raises:
ValueError – If the number of labels doesn’t match the number of centres.