API Reference

Core package

PyAR Molecule object in the target package layout.

This module defines Molecule, a lightweight domain object used throughout PyAR. It is intentionally small and dependency-light.

Compatibility notes

PyAR has historically treated XYZ parsing errors as fatal and exited the process. That behavior is preserved by read_xyz(). New code should prefer the exception-based parse_xyz() helper for improved testability.

pyar.core.molecule.parse_xyz(filename)

Parse an XYZ file without terminating the process on invalid input.

Parameters:

filename (str)

Return type:

Tuple[list, numpy.ndarray, str, str, float | None]

class pyar.core.molecule.Molecule(atoms_list, coordinates, name=None, title=None, fragments=None, charge=0, multiplicity=1, scftype='rhf', energy=None)

Bases: object

Domain object for a molecular geometry and its workflow metadata.

property coordinates: numpy.ndarray | None

Cartesian coordinates in Angstrom, or None after failure.

property centroid: numpy.ndarray | None

Return the current geometry centroid, if coordinates exist.

merged_with(other)

Return a molecule containing this molecule and other as fragments.

copy()

Return a deep copy preserving workflow metadata.

classmethod from_xyz(filename)

Create a molecule from an XYZ file.

split_coordinates(coordinates=None)

Return coordinate blocks for each fragment.

split_atoms_lists()

Return atom-symbol blocks for each fragment.

split_covalent_radii_list()

Return covalent-radius blocks for each fragment.

mol_to_xyz(file_name)

Write the molecule to an XYZ file.

mol_to_turbomole_coord()

Write the geometry in Turbomole coord format.

is_bonded(bond_scale=1.3)

Return whether any inter-fragment pair forms a covalent bond.

property moments_of_inertia_tensor

Return the inertia tensor without mutating the molecule.

rotate_3d(angles)

Rotate the molecule in place using Z-X-Z’ Euler angles.

move_to_origin()

Shift the molecule so its centroid lies at the origin.

move_to_centre_of_mass()

Shift the molecule so its center of mass lies at the origin.

translate(magnitude)

Translate the molecule in place by magnitude.

align()

Align the molecule with its principal axes in place.

translated(magnitude)

Return a translated copy of the molecule.

rotated_3d(angles)

Return a rotated copy of the molecule.

aligned()

Return an aligned copy of the molecule.

moved_to_origin()

Return a copy shifted so its centroid lies at the origin.

moved_to_centre_of_mass()

Return a copy shifted so its center of mass lies at the origin.

to_ase_atoms()

Convert this molecule into an ASE Atoms object.

classmethod from_ase_atoms(atoms, name=None, title=None, charge=0, multiplicity=1, scftype='rhf', energy=None)

Create a molecule from an ASE Atoms object.

pyar.core.molecule.read_xyz(filename)

Read an XYZ file using the historical exit-on-error behavior.

pyar.core.molecule.main()

I/O helpers for pyar.core.molecule.

pyar.io.xyz.as_coordinates_array(value)

Validate and return Cartesian coordinates as an (N, 3) array.

Return type:

numpy.ndarray

pyar.io.xyz.validate_fragments(fragments, number_of_atoms)

Validate atom-index fragment definitions for a molecule.

Parameters:

number_of_atoms (int)

Return type:

list

exception pyar.io.xyz.XYZParseError

Bases: ValueError

Raised when an XYZ file cannot be parsed.

pyar.io.xyz.parse_xyz(filename)

Parse an XYZ file and raise XYZParseError on malformed input.

Parameters:

filename (str)

Return type:

Tuple[list, numpy.ndarray, str, str, float | None]

pyar.io.xyz.read_xyz(filename)

Read an XYZ file using PyAR’s historical exit-on-error interface.

Parameters:

filename (str)

pyar.io.xyz.write_xyz(molecule, file_name)

Write a molecule and optional energy label in XYZ format.

pyar.io.xyz.write_turbomole_coord(molecule, file_name='coord')

Write a molecule in Turbomole coord format.

Geometry helpers for pyar.core.molecule.

pyar.core.geometry.rotation_matrix(angles)

Build the Z-X-Z’ Euler rotation matrix for angles.

Return type:

numpy.ndarray

pyar.core.geometry.moments_of_inertia_tensor(molecule)

Return a molecule’s mass-weighted moment-of-inertia tensor.

pyar.core.geometry.translate(molecule, magnitude)

Translate molecule in place and return it.

pyar.core.geometry.move_to_origin(molecule)

Move molecule to its geometric centroid in place.

pyar.core.geometry.move_to_centre_of_mass(molecule)

Move molecule to its center of mass in place.

pyar.core.geometry.rotate_3d(molecule, angles)

Rotate molecule about its centroid in place.

pyar.core.geometry.align(molecule)

Align molecule to its principal axes in place.

Merge helpers for pyar.Molecule.

pyar.molecule_merge.combine_multiplicity(first, second)

Preserve the existing heuristic for combined multiplicity.

Return type:

int

pyar.molecule_merge.merged_with(first, second)

Return a molecule containing first and second as fragments.

Command-line entry point

Command-line entrypoint for PyAR.

pyar.cli.argument_parse(argv=None)
pyar.cli.main()

xTB backends

Shared helpers for xTB-backed backends.

pyar.backends.xtb_utils.build_xtb_command(executable, start_xyz_file, qc_params, opt_threshold=None)

Build an xTB command line from PyAR QC settings.

pyar.backends.xtb_utils.xtb_parallel_args(qc_params)

Return command-line arguments for xTB parallel execution.

Pure xTB geometry optimization backend.

class pyar.backends.xtb.Xtb(molecule, method)

Bases: SF

Run a standalone xTB optimization for a single molecule.

optimize(max_cycles=350, gamma=None, restart=False, convergence='normal')

Execute xTB and return a success flag or failure status string.

property optimized_coordinates

Read the optimized xTB coordinates from xtbopt.xyz.

property energy

Read the final total energy from xTB output files.

pyar.backends.xtb.main()

xTB followed by AIQM1 refinement backend.

class pyar.backends.xtb_aiqm1.XtbAIQM1(molecule, method)

Bases: SF

Run xTB, then refine the xTB minimum with AIQM1.

optimize(max_cycles=350, gamma=None, restart=False, convergence='normal')
property xtb_optimized_xyz_file
property aiqm1_optimized_xyz_file
property optimized_coordinates
property energy
pyar.backends.xtb_aiqm1.main()

xTB followed by AIMNet2 refinement backend.

class pyar.backends.xtb_aimnet2.XtbAimnet2(molecule, method)

Bases: SF

Run xTB, then refine the xTB minimum with AIMNet2.

optimize(max_cycles=350, gamma=None, restart=False, convergence='normal')
property xtb_optimized_xyz_file
property aimnet2_optimized_xyz_file
property optimized_coordinates
property energy
pyar.backends.xtb_aimnet2.main()

Turbomole/AFIR compatibility backend using xTB for gradients.

The wrapper keeps the AFIR loop separate from the xTB command construction, which makes the module easier to test and document.

class pyar.backends.xtb_turbo.XtbTurbo(molecule, method)

Bases: SF

Run the AFIR/Turbomole optimization loop with xTB gradients.

optimize()

Run the AFIR optimization loop until convergence or failure.

calculate_energy_gradient()

Run one xTB gradient evaluation and return status, message, energy, gradients.

property calc_engrad

Compatibility alias for older call sites.

pyar.backends.xtb_turbo.main()

Module entry point for direct execution.

geomeTRIC-backed optimization backend with optional AFIR bias.

This module provides a small bridge between PyAR’s backend selection and geomeTRIC’s internal-coordinate optimizer. The optimizer itself is backend agnostic: it asks a selected PyAR backend for energy and gradients, then adds the AFIR term when gamma is non-zero.

class pyar.backends.geometric.PyarGeometricCalculator(*args, **kwargs)

Bases: Calculator

ASE calculator that combines a PyAR backend with optional AFIR bias.

implemented_properties = ['energy', 'forces']
calculate(atoms=None, properties=('energy',), system_changes=ase.calculators.calculator.all_changes)

Compute the backend objective plus the AFIR bias if enabled.

class pyar.backends.geometric.Geometric(molecule, qc_params)

Bases: SF

Run geomeTRIC with a PyAR backend calculator and optional AFIR bias.

optimize()

Run the geomeTRIC optimization loop.

pyar.backends.geometric.main()

Module entry point for direct execution.

Backend capabilities and providers

Backend capability registry for PyAR workflows.

class pyar.backend_capabilities.BackendCapabilities(family='unknown', energy_gradient=False, native_optimization=True, supports_charge=True, supports_multiplicity=True, staged_optimization=False, supported_options=<factory>)

Bases: object

Describe what a backend can do for PyAR workflows.

Parameters:
  • family (str)

  • energy_gradient (bool)

  • native_optimization (bool)

  • supports_charge (bool)

  • supports_multiplicity (bool)

  • staged_optimization (bool)

  • supported_options (FrozenSet[str])

family: str = 'unknown'
energy_gradient: bool = False
native_optimization: bool = True
supports_charge: bool = True
supports_multiplicity: bool = True
staged_optimization: bool = False
supported_options: FrozenSet[str]
pyar.backend_capabilities.register_backend_capabilities(software, capabilities)

Register or replace capability metadata for a backend.

pyar.backend_capabilities.backend_family(software)

Return the backend family label.

pyar.backend_capabilities.backend_supports_staged_optimization(software)

Return True when the backend has wired loose/normal staged optimization.

pyar.backend_capabilities.get_backend_capabilities(software)

Return the capability profile for a backend, if known.

pyar.backend_capabilities.backend_supports_geometry_optimization(software)

Return True when geomeTRIC can resolve an energy-gradient provider.

pyar.backend_capabilities.supported_geometry_backends()

Return the list of backends currently allowed on the AFIR/geomeTRIC path.

pyar.backend_capabilities.unsupported_qc_options(software, provided_options)

Return explicitly provided QC options that are not supported by a backend.

Energy and gradient providers for geomeTRIC-compatible backends.

class pyar.energy_gradient_providers.EnergyGradientResult(energy_hartree, gradient_hartree_per_bohr)

Bases: object

Backend energy and Cartesian gradient in atomic units.

Parameters:
  • energy_hartree (float)

  • gradient_hartree_per_bohr (numpy.ndarray)

energy_hartree: float
gradient_hartree_per_bohr: numpy.ndarray
class pyar.energy_gradient_providers.EnergyGradientProvider(*args, **kwargs)

Bases: Protocol

Provide a backend energy and Cartesian gradient.

evaluate(molecule, coordinates_bohr)

Evaluate the backend objective in Bohr/Hartree units.

Parameters:

coordinates_bohr (numpy.ndarray)

Return type:

EnergyGradientResult

class pyar.energy_gradient_providers.XtbEnergyGradientProvider(qc_params=None)

Bases: object

Evaluate xTB energy and gradient for the current coordinates.

evaluate(molecule, coordinates_bohr)
class pyar.energy_gradient_providers.Aimnet2EnergyGradientProvider(qc_params=None)

Bases: object

Evaluate AIMNet2 energy and gradient for the current coordinates.

evaluate(molecule, coordinates_bohr)
class pyar.energy_gradient_providers.GaussianEnergyGradientProvider(qc_params=None)

Bases: object

Evaluate Gaussian energy and gradient for the current coordinates.

evaluate(molecule, coordinates_bohr)

Run one Gaussian force job and parse the resulting gradient.

class pyar.energy_gradient_providers.OrcaEnergyGradientProvider(qc_params=None)

Bases: object

Evaluate ORCA energy and gradient for the current coordinates.

evaluate(molecule, coordinates_bohr)

Run one ORCA single-point calculation and parse its gradient.

pyar.energy_gradient_providers.get_energy_gradient_provider(software, qc_params=None)

Return the registered energy/gradient provider for a backend.

pyar.energy_gradient_providers.register_energy_gradient_provider(software, provider, capabilities=None)

Register or replace an energy/gradient provider for a backend.

Sampling API

Sphere sampling helpers for trial placement.

pyar.sampling.sphere.fibonacci_sphere(number_of_points, offset=0.5, azimuth_offset=0.0)

Generate deterministic approximately uniform directions on a sphere.

Parameters:
  • number_of_points (int)

  • offset (float)

  • azimuth_offset (float)

Return type:

numpy.ndarray

pyar.sampling.sphere.latin_hypercube_sphere(number_of_points, seed=None)

Generate sphere directions from a Latin-hypercube sample.

Parameters:
  • number_of_points (int)

  • seed (int | None)

Return type:

numpy.ndarray

pyar.sampling.sphere.random_sphere(number_of_points, seed=None)

Generate uniformly distributed random sphere directions.

Parameters:
  • number_of_points (int)

  • seed (int | None)

Return type:

numpy.ndarray

pyar.sampling.sphere.maximin_select(points, number_of_points)

Select a spread-out subset of candidate directions greedily.

Parameters:
  • points (numpy.ndarray)

  • number_of_points (int)

Return type:

numpy.ndarray

pyar.sampling.sphere.generate_directions(method, number_of_points, *, seed=None, sequence_offset=0, oversample_factor=8)

Generate trial-placement directions using a named sampling method.

Parameters:
  • method (str)

  • number_of_points (int)

  • seed (int | None)

  • sequence_offset (int)

  • oversample_factor (int)

Return type:

numpy.ndarray

Rotation sampling helpers for trial placement.

pyar.sampling.rotation.random_quaternions(number_of_points, seed=None)

Generate random unit quaternions for monomer rotation sampling.

Parameters:
  • number_of_points (int)

  • seed (int | None)

Return type:

numpy.ndarray

pyar.sampling.rotation.halton_quaternions(number_of_points, seed=None)

Generate deterministic low-discrepancy unit quaternions.

Parameters:
  • number_of_points (int)

  • seed (int | None)

Return type:

numpy.ndarray

pyar.sampling.rotation.canonicalize_quaternion(quaternion)

Normalize a quaternion and choose a consistent sign representative.

Parameters:

quaternion (numpy.ndarray)

Return type:

numpy.ndarray

pyar.sampling.rotation.quaternions_to_euler_zxz(quaternions)

Convert unit quaternions to Z-X-Z Euler angles in radians.

Parameters:

quaternions (numpy.ndarray)

Return type:

numpy.ndarray

Coverage metrics for sphere and rotation sampling.

class pyar.sampling.metrics.SphereCoverageMetrics(minimum_separation_degrees, mean_nearest_neighbor_degrees, covering_radius_degrees, mean_covering_distance_degrees, centroid_norm)

Bases: object

Quality measures for directional sphere samples.

Parameters:
  • minimum_separation_degrees (float)

  • mean_nearest_neighbor_degrees (float)

  • covering_radius_degrees (float)

  • mean_covering_distance_degrees (float)

  • centroid_norm (float)

minimum_separation_degrees: float
mean_nearest_neighbor_degrees: float
covering_radius_degrees: float
mean_covering_distance_degrees: float
centroid_norm: float
class pyar.sampling.metrics.RotationCoverageMetrics(minimum_separation_degrees, mean_nearest_neighbor_degrees, covering_radius_degrees, mean_covering_distance_degrees)

Bases: object

Quality measures for sampled monomer rotations.

Parameters:
  • minimum_separation_degrees (float)

  • mean_nearest_neighbor_degrees (float)

  • covering_radius_degrees (float)

  • mean_covering_distance_degrees (float)

minimum_separation_degrees: float
mean_nearest_neighbor_degrees: float
covering_radius_degrees: float
mean_covering_distance_degrees: float
pyar.sampling.metrics.sphere_coverage_metrics(points, *, evaluation_points=10000)

Measure angular spread and covering quality for sphere directions.

Parameters:
  • points (numpy.ndarray)

  • evaluation_points (int)

Return type:

SphereCoverageMetrics

pyar.sampling.metrics.quaternion_coverage_metrics(quaternions, *, evaluation_points=10000)

Measure angular spread and covering quality for quaternions.

Parameters:
  • quaternions (numpy.ndarray)

  • evaluation_points (int)

Return type:

RotationCoverageMetrics

Trial geometry generation and merge helpers.

pyar.sampling.trial_generator.polar_to_cartesian(r, theta, phi)

Convert spherical polar coordinates to Cartesian coordinates.

pyar.sampling.trial_generator.check_close_contact(mol_1, mol_2, factor)

Return whether two fragments contain a scaled close contact.

pyar.sampling.trial_generator.minimum_separation(mol_1, mol_2)

Return the minimum inter-fragment Cartesian separation.

pyar.sampling.trial_generator.merge_two_molecules(vector, seed_input, monomer_input, freeze_fragments=False, site=None, distance_scaling=1.5)

Place and merge a monomer around a seed using one trial vector.

pyar.sampling.trial_generator.ellipsoid_wall_potential(coordinates, a, b, c, k=100.0)

Return an ellipsoidal wall penalty for coordinates outside the bounds.

pyar.sampling.trial_generator.create_composite_molecule(seed, monomer, points_and_angles, d_scale)

Create a composite molecule by applying consecutive placements.

pyar.sampling.trial_generator.spherical_to_cartesian(r, theta, phi)

Convert spherical coordinates to a Cartesian vector.

pyar.sampling.trial_generator.generate_trial_vectors(number_of_points, *, direction_method='fibonacci', rotation_method='halton', seed=None, sequence_offset=0, oversample_factor=8, use_angles=True)

Return direction and orientation vectors for trial geometries.

Parameters:
  • number_of_points (int)

  • direction_method (str)

  • rotation_method (str)

  • seed (int | None)

  • sequence_offset (int)

  • oversample_factor (int)

  • use_angles (bool)

Return type:

numpy.ndarray

pyar.sampling.trial_generator.generate_points(number_of_orientations, sequence_offset=0)

Generate default trial direction and monomer-orientation vectors.

pyar.sampling.trial_generator.create_trial_geometries(molecule_id, seed, monomer, number_of_orientations, site)

Generate and write merged trial geometries for one growth operation.

pyar.sampling.trial_generator.plot_points(points, location)

Plot sampled direction points on a unit sphere.

pyar.sampling.trial_generator.write_trial_vectors(vectors, output_file)

Append generated direction and rotation vectors to an output file.

pyar.sampling.trial_generator.main()
pyar.sampling.trial_generator.get_connectivity(coordinates, covalent_radii, tolerance=0.4)

Return covalent-radius-based connectivity edges for a geometry.

Parameters:
  • coordinates (numpy.ndarray)

  • covalent_radii (List[float])

  • tolerance (float)

Return type:

List[Tuple[int, int]]

pyar.sampling.trial_generator.broken(molobj)

Return whether a molecule is disconnected under its covalent-radius graph.

Return type:

bool

Scripts package

Command line arguments in pyar

  • pyar-cli: the main cli for aggregation and reaction

  • pyar-clustering: cluster or filter the given molecules based on their similarity with each other.

  • pyar-energy-table: print a relative-energy table from one or more XYZ files.

  • pyar-descriptor: compute compact cluster descriptors from XYZ files.

  • pyar-similarity: detect near-duplicate XYZ structures with the Grigoryan-Springborg metric.

  • pyar-trial-generation: generate trial geometries and orientation samples.

  • pyar-optimiser: optimize molecules with a generic backend setting.

  • pyar-benchmark-clustering: benchmark cluster-selection algorithms.

  • pyar-benchmark-orientations: benchmark trial-direction samplers.

  • pyar-reaction-trace: analyze a reaction trace and generate plots.