API Reference

Contents

API Reference#

This page documents the full public API of AimsPy. All symbols below are importable from the top-level aimspy package (e.g. from aimspy import Calculator), except the visualization helpers of aimspy.viz / aimspy.viz_basis, which are imported from their submodules (e.g. from aimspy.viz_basis import plot_radial_basis).

Calculator#

The main user-facing class for driving FHI-aims SCF calculations, including lifecycle management (init / calc / do / close / force_close) and Hamiltonian modification (modify_init_ham).

Public — Calculator, the primary user-facing class.

Usage (one-shot, common case):

from mpi4py import MPI
from aimspy import Calculator, CalculatorConfig

config = CalculatorConfig(lib_path="/path/to/libaims.so")
with Calculator(config) as calc:
    calc.do(comm=MPI.COMM_WORLD, work_dir="./MoS2")
    H = calc.hamiltonian     # AimspyMatrix
    E = calc.energy

Two-step (advanced; e.g. to register callbacks between init and calc):

with Calculator(config) as calc:
    calc.init(comm=MPI.COMM_WORLD, work_dir="./MoS2")
    calc.register_callback('export_h0', my_fn, aux={})
    calc.calc()
    H = calc.hamiltonian

Warmstart with DeepH data (direct source):

from aimspy import Calculator, CalculatorConfig, Strategy
from aimspy import DeepHData

data = DeepHData.from_directory("deeph_warm/")
config = CalculatorConfig(lib_path="/path/to/libaims.so")
calc = Calculator(config)
calc.modify_init_ham(source=data, strategy=Strategy.REPLACE)
calc.do(comm=MPI.COMM_WORLD, work_dir="./MoS2")

Warmstart with DeepH data (deferred source — source generated at runtime during python_func callback, after H0/overlap are available):

config = CalculatorConfig(
    lib_path=..., capture_initial_hamiltonian=True,
)
calc = Calculator(config)

@calc.modify_init_ham(strategy=Strategy.REPLACE, option={"deeph_path": "deeph_warm/"})
def gen_source(calculator, option):
    # calculator.initial_hamiltonian / .overlap are available here
    return DeepHData.from_directory(option["deeph_path"])

calc.do(comm=MPI.COMM_WORLD, work_dir="./MoS2")

Capture free-atom initial Hamiltonian (optional):

config = CalculatorConfig(
    lib_path=..., capture_initial_hamiltonian=True,
)
with Calculator(config) as calc:
    calc.do(comm=MPI.COMM_WORLD, work_dir="./MoS2")
    h_init = calc.initial_hamiltonian
class aimspy.calculator.CalcState(value)[source]#

Bases: Enum

class aimspy.calculator.Calculator(config=None, /, **kwargs)[source]#

Bases: object

In-memory interface to FHI-aims via ctypes.

Three lifecycle entry points:

  • do() — one-shot (init + calc). Common case.

  • init() + calc() — two-step, for advanced use cases that need to register callbacks between init and calc.

  • close() — finalize (also called by __exit__). Use force_close() after SCF failure.

H0 modification is configured via modify_init_ham() (direct or deferred source), which must be called before do() / init().

Note

Thread safety: NOT thread-safe. FHI-aims uses chdir(2) (process-global) internally, so concurrent Calculator operations in the same process will race. Use one Calculator per process (typical MPI usage: one rank = one process).

Note

Rank-0-only properties: The following properties read from Fortran rank-0-only buffers and raise AimspyBindingError on non-root ranks: rs_hamiltonian, rs_overlap, hamiltonian, overlap (without capture_overlap=True). Properties available on all ranks: info, structure, csr_descr, energy, forces, initial_hamiltonian (with capture_initial_hamiltonian=True), overlap (with capture_overlap=True).

property basis_data#

NAO radial basis data as BasisData.

Returns None unless CalculatorConfig.capture_basis_data=True was set and the basis generation has completed (the callback fires once after shrink_fixed_basis_phi_thresh, before SCF begins).

Contains spline coefficients for u(r), (e−v)·u(r), and du/dr, plus per-species logarithmic grid parameters. Identity metadata (n, l, type, species) is in info.

calc()[source]#

Execute SCF calculation.

Must be called after init(). Raises AimspyCallbackError if any registered callback raised during SCF.

close()[source]#

Finalize FHI-aims.

Behavior by state:

  • UNINIT / FINALIZED: silent no-op.

  • RUNNING: raises AimspyStateError (use force_close() if the SCF has aborted).

  • INITED / DONE: normal finalize (errors propagate).

  • FAILED: defensive finalize (errors swallowed and logged).

Also invoked by __exit__.

property comm#

MPI communicator passed to init() (None before init).

property csr_descr#

CSR matrix layout descriptor, or None before init().

do(comm=None, work_dir=PosixPath('.'))[source]#

One-shot: init() + calc().

Convenience entry point for the common case where no callbacks need to be registered between init and calc. Parameters are forwarded to init().

Raises:
property energy#

SCF total energy (Hartree).

Available in DONE state. Also accessible in RUNNING (e.g. from inside a callback during pre-SCF), but the value may be uninitialized before the first SCF iteration completes.

property first_order_hamiltonian#

Electric-response first-order Hamiltonian (dH/de).

Returns a list of 3 AimspyMatrix [x, y, z] or None if not captured. Requires CalculatorConfig.capture_first_order_hamiltonian=True and electric_field_response DFPT in control.in.

In serial mode (electric_field_serial .true.) the three directions are captured by three separate CPSCF calls; this property returns the complete [x, y, z] list only after all three directions have been captured (calc() done). If any direction is still missing it returns None.

force_close()[source]#

Force-finalize regardless of state. Swallows Fortran errors.

Use after SCF failure or partial init when close() refuses (RUNNING state) or when the Fortran runtime is in an unknown condition (FAILED state). Always clears all retained state.

property forces#

Total atomic forces, shape (n_atoms, 3), units eV/Å.

Eagerly captured at the end of calc() and cached on self._forces. Returns None when forces are not available:

  • Before calc() is called (self._forces is None)

  • compute_forces .true. not set in control.in

  • After close() / force_close() (state cleared)

property grid_data#

This rank’s real-space grid subset as GridData.

Returns None unless CalculatorConfig.capture_grid_data=True was set and the SCF has converged (the callback fires once after convergence).

Each MPI rank holds its own grid-point subset. Use GridData.gather(calc.grid_data, comm) to assemble the global grid on a root rank (returns None on non-root ranks).

Note

vks is the scalar part of V_KS (V_H + v_xc) — exact for LDA; the GGA non-local vector term is not exported.

property hamiltonian#

Converged Hamiltonian as AimspyMatrix (rank 0, DONE only).

The result is cached after the first access (the CSR walk + block-dict construction is expensive for large systems); repeated accesses return the cached AimspyMatrix.

property info#

Runtime snapshot of FHI-aims dimensions and basis info (all ranks).

Raises AimspyStateError if accessed before init() or after finalization.

init(comm=None, work_dir=PosixPath('.'))[source]#

Initialize FHI-aims runtime.

Loads libaims, calls aimspy_init, loads runtime info, and wires default callbacks based on _cfg and _modify. After init(), users can register additional callbacks via register_callback() before calling calc().

Parameters:
  • comm (mpi4py.MPI.Comm or None) – MPI communicator. Defaults to MPI.COMM_WORLD.

  • work_dir (Path or str) – Working directory (created if missing). aims runs with this as cwd; logfile and copied input files land here. Default: current directory.

Raises:

AimspyStateError – If called from any state other than UNINIT.

property initial_hamiltonian#

Free-atom initial Hamiltonian (H_init) as AimspyMatrix.

Returns None unless CalculatorConfig.capture_initial_hamiltonian=True was set.

modify_init_first_order_ham(source=None, *, strategy=Strategy.REPLACE, factor=1.0, custom_fn=None, option=None)[source]#

Configure dH/de (electric-response first-order Hamiltonian) modification — unified API mirroring modify_init_ham().

Must be called before do() / init() (state UNINIT); calling after init raises AimspyStateError.

Only REPLACE and ADD strategies are supported. The source must implement to_first_order_aimspy(structure) -> list[AimspyMatrix] (3 matrices [x, y, z], Hartree) — e.g. aimspy.DeepHData.

Direct mode (pre-built source):

calc.modify_init_first_order_ham(source=data, strategy=Strategy.REPLACE)

Deferred mode (source generated at runtime via decorator):

@calc.modify_init_first_order_ham(
    strategy=Strategy.REPLACE, option={"deeph_path": "..."}
)
def gen_source(view, option):
    # view.initial_hamiltonian / .overlap / .structure available
    return DeepHData.from_directory(option["deeph_path"])

In deferred mode, the decorated function fn(view, option) is called inside the modify_dHde callback (before the initial U1 computation in DFPT_cpscf). view is a lightweight namespace exposing initial_hamiltonian, overlap, and structure if those were captured. If the deferred function uses view.initial_hamiltonian or view.overlap, enable the corresponding CalculatorConfig.capture_initial_hamiltonian / capture_overlap — at least one of them must be available.

Parameters:
  • source (object or None) – External first-order matrix source with to_first_order_aimspy(structure) method. Required for direct REPLACE/ADD.

  • strategy (Strategy or str) – Modification strategy — only REPLACE and ADD are supported.

  • factor (float) – Scale factor (unused for REPLACE/ADD on first-order; accepted for API symmetry).

  • custom_fn (callable or None) – Not supported for first-order (raises if given).

  • option (dict or None) – User data passed to the deferred source function.

Returns:

In direct mode: None. In deferred mode: a decorator.

Return type:

callable or None

modify_init_ham(source=None, *, strategy=Strategy.REPLACE, factor=1.0, custom_fn=None, option=None)[source]#

Configure H0 modification — unified API for both direct and deferred source.

Must be called before do() / init() (state UNINIT); calling after init raises AimspyStateError.

Direct mode (pre-built source or source-less strategy):

calc.modify_init_ham(source=data, strategy=Strategy.REPLACE)
calc.modify_init_ham(source=data, strategy=Strategy.ADD)
calc.modify_init_ham(strategy=Strategy.SCALE, factor=0.9)
calc.modify_init_ham(strategy=Strategy.CUSTOM, custom_fn=my_fn, source=data)

Deferred mode (source generated at runtime via decorator; only for REPLACE / ADD strategies without a pre-built source):

@calc.modify_init_ham(strategy=Strategy.REPLACE, option={"deeph_path": "..."})
def gen_source(calculator, option):
    # calculator.initial_hamiltonian / .overlap are available
    # here if capture_* was enabled in CalculatorConfig.
    return DeepHData.from_directory(option["deeph_path"])

In deferred mode, the decorated function fn(calculator, option) is called during the python_func callback (between export_h0 and modify_h0 in initialize_scf.f90), with access to the live Calculator object. The returned source must have a to_aimspy(structure) -> AimspyMatrix method (e.g. DeepHData).

Parameters:
  • source (object or None) – External matrix source with to_aimspy(structure) method (e.g. DeepHData). Required for direct REPLACE/ADD.

  • strategy (Strategy or str) – Modification strategy (default REPLACE). Accepts string.

  • factor (float) – Scale factor for SCALE strategy.

  • custom_fn (callable or None) – fn(live, external, structure, aux) -> None for CUSTOM.

  • option (dict or None) – User-specified data passed to the deferred source function as second argument.

Returns:

In direct mode: None. In deferred mode: a decorator (which returns the original function unchanged).

Return type:

callable or None

Raises:

AimspyConfigError – If CUSTOM strategy is used without custom_fn, or if strategy is not a valid Strategy value.

property overlap#

Overlap matrix as AimspyMatrix.

If capture_overlap=True was set in CalculatorConfig, returns the live overlap captured by the export_ovlp callback (available from INITED state onward, all MPI ranks).

Otherwise, falls back to reading from c_overlap (the aims internal copy, rank 0 only, requires DONE state).

register_callback(name, fn, aux=None, extra_ptr=None)[source]#

Register a custom callback (advanced API).

Can be called at two points:

  • Pre-init (state UNINIT): the registration is deferred and applied inside init() after the callback manager is created, before _wire_callbacks(). Exception: export_basis_data fires during aimspy_init (inside prepare_scf), so its pre-init registration is applied before aimspy_init instead.

  • Post-init, pre-calc (state INITED): the registration is applied immediately to the live callback manager. Exception: export_basis_data has already fired by then — a warning is issued and the callback will never be called; use CalculatorConfig.capture_basis_data=True or pre-init registration instead.

Calling from DONE state is allowed (registers on the live manager) but the callback will never fire (SCF already completed). Calling from FAILED/FINALIZED raises AimspyStateError.

If the user registers a callback with the same name as one that _wire_callbacks() would register by default, the user’s registration takes precedence (the default is skipped). Post-init registration overrides any previously-registered callback with the same name.

Parameters:
  • name (str or CallbackName) – Callback spec name (e.g. 'export_h0') or enum member.

  • fn (callable) – Python-side callback function.

  • aux (any) – Arbitrary Python object passed through to the callback.

  • extra_ptr (int or None) – Extra c-pointer for 3-arg register functions (only modify_h0). Note: the Calculator’s built-in modify_h0 wrapper does not forward extra_ptr to the user callback — external matrix data is delivered via the python_func callback + aux['external_aimspy'] instead. This parameter is primarily for Calculator-internal use.

property rs_hamiltonian#

Raw CSR-flat Hamiltonian, shape (n_spin, n_ham_size) (rank 0).

Available in DONE state only.

property rs_overlap#

Raw flat overlap array (rank 0).

Available from INITED onwards (overlap is built pre-SCF).

property structure#

Structure + orbital descriptor (all ranks).

Raises AimspyStateError if accessed before init() or after finalization.

property work_dir#

Working directory passed to init() (None before init).

class aimspy.calculator.Strategy(value)[source]#

Bases: Enum

Initial Hamiltonian modification strategy names.

Used by Calculator.modify_init_ham().

Configuration#

Configuration dataclass for Calculator — declares lib path, input files, capture flags, and other construction-time settings.

class aimspy.calculator.CalculatorConfig(lib_path, control_path=None, geometry_path=None, initializer=None, log_level='INFO', logfile=PosixPath('aims.out'), capture_initial_hamiltonian=False, capture_overlap=False, capture_first_order_hamiltonian=False, capture_grid_data=False, capture_basis_data=False)[source]#

Bases: object

Configuration for Calculator.

All fields are construction-time declarations; work_dir and comm are passed to Calculator.init() / Calculator.do() at execution time.

Parameters:
  • lib_path (Path) – Path to the patched libaims.so.

  • control_path (Path or None) – Optional input files copied into work_dir at run time.

  • geometry_path (Path or None) – Optional input files copied into work_dir at run time.

  • initializer (callable or None) – fn(Calculator) -> None invoked on rank 0 after inputs are copied but before aimspy_init.

  • log_level (str) – Python logging level name (default "INFO").

  • logfile (Path) – aims log file name (relative to work_dir after chdir).

  • capture_initial_hamiltonian (bool) – If True, register the export_h0 callback so that Calculator.initial_hamiltonian is available after calc(). Default False (free-atom initial Hamiltonian capture is opt-in).

  • capture_overlap (bool) – If True, register the export_ovlp callback so that Calculator.overlap returns the live overlap matrix (available from INITED state onward, all MPI ranks) instead of the c_overlap copy (rank 0 only). Default False.

  • capture_first_order_hamiltonian (bool) – If True, register the export_dHde callback so that Calculator.first_order_hamiltonian is available after calc() (requires electric_field_response DFPT in control.in). Default False.

  • capture_grid_data (bool) – If True, register the export_grid_data callback so that Calculator.grid_data (this rank’s real-space grid subset: coords / weights / rho / scalar vks / vks0 / vh / vh0 / rho0) is available after calc(). Fires once after SCF convergence. Scalar V_KS only — exact for LDA; for GGA the non-local vector term is not exported. Default False.

  • capture_basis_data (bool) – If True, register the export_basis_data callback so that Calculator.basis_data (NAO radial basis spline coefficients and grid parameters) is available after calc.init() — the callback fires inside aimspy_init itself (prepare_scf, after shrink_fixed_basis_phi_thresh); no calc() call is needed. Default False.

Matrices#

Block-sparse real-space matrix representation (AimspyMatrix) and CSR conversion utilities for round-tripping with FHI-aims’ internal layout.

Public — AimspyMatrix + aims↔aimspy format conversions.

The aimspy standard matrix format is a block-sparse real-space representation:

blocks: dict[tuple[int, int, int, int, int], np.ndarray]

key = (R1, R2, R3, i_atom, j_atom)

Conventions#

  • R: R_aimspy = -R_aims (same sign as DeepH).

  • Atoms: aims native order (no reordering).

  • Orbitals: aims native basis order (no reordering).

  • Parity: wiki/DeepH convention (phase_i * phase_j already applied).

  • Units: Hartree.

  • Hermitian partners: both (R,i,j) and (-R,j,i) stored.

class aimspy.matrix.AimspyMatrix(blocks, n_spin=1)[source]#

Bases: object

Block-sparse real-space matrix in aimspy standard format.

Key = (R1, R2, R3, i_atom, j_atom) with all ints:
  • R follows R_aimspy = -R_aims (same sign as DeepH).

  • i_atom / j_atom in aims native order.

  • Orbital order within each atom is aims native.

  • Parity = wiki/DeepH (phase already applied).

  • Units = Hartree.

classmethod from_aims_csr(h0, csr_descr, structure)[source]#

Convert aims CSR flat array to aimspy block dict.

Steps: 1. Walk CSR triplanes (cell, basis‑row, k‑index). 2. R_aimspy = -R_aims (sign flip) → lookup key matches DeepH. 3. Apply wiki parity: v *= phase_i * phase_j. 4. Store block[orb_i, orb_j] and its Hermitian partner.

Raises:

AimspyError – If csr_descr.n_spin != 1 (spin-polarized data is not yet supported; only spin channel 0 would be read).

to_aims_csr(csr_descr, structure)[source]#

Convert aimspy block dict back to aims CSR flat array.

Steps: 1. Walk CSR triplanes (same order as from_aims_csr). 2. Look up block in self.blocks (dict, O(1)). 3. Hermitian fallback: if forward key missing, try (-R, j, i). 4. Undo parity: v *= phase_i * phase_j (self‑inverse). 5. Return (n_spin, n_ham_size) C‑contiguous, ready to memmove.

Raises:

AimspyError – If csr_descr.n_spin != 1 (spin-polarized data is not yet supported; only spin channel 0 would be written).

aimspy.matrix.get_forces(binding, n_atoms)[source]#

Read total_forces (3, n_atoms) Fortran array → (n_atoms, 3) eV/Å.

Fortran stores total_forces in Hartree/Bohr; we convert to eV/Å (the same convention FHI-aims uses for printed forces in aims.out).

Returns None if use_forces=False (Fortran returns c_null_ptr when compute_forces .true. was not set in control.in).

Structure#

Structure and orbital descriptor, providing atom/basis info and derived properties (phase factor, orbital counts, atom permutation) needed for matrix conversions.

Public — AimspyStructure: shared structure+orbital descriptor for aimspy.

This descriptor is independent of any matrix data and can be shared across multiple AimspyMatrix instances.

Constructed from a runtime AimspyInfo snapshot via from_info(). For offline use, construct directly with the dataclass constructor.

class aimspy.structure.AimspyStructure(n_atoms, n_basis, n_spin, n_periodic=0, lattice=None, atom_symbols=None, atom_coords=None, basis_atom=None, basis_l=None, basis_m=None)[source]#

Bases: object

Structure + orbital info, reusable across multiple matrices.

Contains everything needed for format conversions except the CSR sparse-storage layout (CsrMatrixDescriptor), which is aims‑specific and captured separately via the get_descr callback at runtime.

Atom and orbital ordering follows the aims native order — no reordering is applied.

property atom_permutation#

(old2new, new2old) mapping aims→POSCAR and back.

old2new[aims_atom] == POSCAR_atom new2old[POSCAR_atom] == aims_atom

Computed once and cached; safe because the structure is expected to be immutable after construction.

property atoms_species_sorted#

Per-atom species in POSCAR/DeepH element-grouped order.

property basis_subidx#

Per-atom orbital sub-index in aims basis order.

basis_subidx[i] = the 0‑based position of basis function i among its atom’s basis functions, in aims traversal order.

build_atom_permutation()[source]#

Return (old2new, new2old) mapping aims->POSCAR and back.

Convenience wrapper around atom_permutation for backward compatibility.

classmethod from_info(info)[source]#

Build from a runtime AimspyInfo snapshot (available after aimspy_init).

All arrays are independent copies — safe to hold after aimspy_finalize.

property orbit_per_atom#

Number of basis functions per atom.

property phase_factor#

-1 if m>0 and m odd, else +1.

This is the real-spherical-harmonics phase convention used by both DeepH and the aimspy standard format. It is not the aims native convention — applying it converts aims→aimspy (and reapplying it converts aimspy→aims, since phase² = 1).

Type:

Wiki/DeepH parity

Runtime Info#

Snapshot of FHI-aims runtime dimensions, basis info, and unit conversion constants (Hartree↔eV, Bohr↔Å).

Public data classes — AimspyInfo, CsrMatrixDescriptor.

These are the primary data carriers of the aimspy public API.

class aimspy.data.AimspyInfo(n_atoms, n_species, n_basis, n_basis_fns, n_spin, n_k_points, n_states, n_cells, n_ham_size, n_periodic, n_centers_basis_I, n_centers_basis_T, n_full_points, n_full_points_total, spin_degeneracy, packed_matrix_format, flag_rel, spin_treatment, myid, n_tasks, output_level, use_scalapack, use_elpa, real_eigenvectors, use_hartree_fock, use_periodic_hf, use_hf_kspace, use_mpi, coords, frac_coords, lattice, recip_lattice, species_idx, atoms_species, species_names=<factory>, species_elements=<factory>, species_z=<factory>, k_points=None, k_weights=None, basis_atom=<factory>, basis_l=<factory>, basis_m=<factory>, basis_fn=<factory>, basisfn_n=<factory>, basisfn_l=<factory>, basisfn_type=<factory>, basisfn_species=<factory>)[source]#

Bases: object

Snapshot of basic FHI-aims runtime info.

Obtained by calling aimspy_get_info() after aimspy_init(). All arrays are independent numpy copies — safe to hold after aimspy_finalize().

Descriptors#

CSR sparse-storage layout descriptor (CsrMatrixDescriptor) — captures the FHI-aims internal matrix layout needed for aims↔aimspy conversion.

class aimspy.data.CsrMatrixDescriptor(n_basis, n_spin, n_cells, n_ham_size, cell_idx, row_mx_idx, col_mx_idx)[source]#

Bases: object

Snapshot of the FHI-aims CSR sparse-storage layout.

Captured once via the get_descr callback. All arrays are independent numpy copies.

Info Loader#

Utility for loading runtime info from the live aims binding.

Public — load AimspyInfo from the live aims runtime.

aimspy.info.load_info(binding)[source]#

Call aimspy_get_info() and build a snapshot dataclass.

Must be called after aimspy_init() (and preferably before aimspy_finalize()).

Parameters:

binding (BindingLib) – The loaded libaims wrapper.

Returns:

Independent snapshot — safe to hold after aimspy_finalize().

Return type:

AimspyInfo

Raises:

AimspyBindingError – If aimspy_get_info is not available in the loaded library or returns NULL.

External Matrix Sources#

Protocol for pluggable matrix sources used in warmstart — any object with a to_aimspy(structure) method satisfies this protocol.

Public — external-format interface layer.

External format data classes (e.g. aimspy.DeepHData) provide a to_aimspy(structure) -> AimspyMatrix method for use with aimspy.Calculator.modify_init_ham() (via source=).

To add support for a new external format, create a subpackage under aimspy/interface/<format>/ containing a data class that implements the ExternalMatrixSource protocol.

class aimspy.interface.ExternalFirstOrderMatrixSource(*args, **kwargs)[source]#

Bases: Protocol

Protocol for electric-response (DFPT) first-order Hamiltonian sources accepted by aimspy.Calculator.modify_init_first_order_ham().

Any object with a to_first_order_aimspy(structure) -> list[AimspyMatrix] method satisfies this protocol (structural typing / duck typing). The returned list must contain exactly 3 AimspyMatrix instances in Cartesian order [x, y, z] (Hartree units).

Implementations:
  • aimspy.DeepHData

class aimspy.interface.ExternalMatrixSource(*args, **kwargs)[source]#

Bases: Protocol

Protocol for external matrix sources accepted by aimspy.Calculator.modify_init_ham().

Any object with a to_aimspy(structure) -> AimspyMatrix method satisfies this protocol (structural typing / duck typing).

Implementations:
  • aimspy.DeepHData

DeepH Data#

DeepH on-disk format reader, writer, and converter — reads POSCAR + info.json + .h5 files and converts to AimspyMatrix.

DeepH format interface — read, write, and convert DeepH-format data.

class aimspy.interface.deeph.DeepHData(lattice, atom_symbols, atom_coords, elements_orbital_map, n_basis, atom_pairs, chunk_boundaries, chunk_shapes, entries=None, overlap_entries=None, initial_hamiltonian_entries=None, first_order_hamiltonian_entries=None, _fo_chunk_boundaries=None, _fo_chunk_shapes=None, force=None, energy_eV=None, fermi_energy_eV=0.0, path=None)[source]#

Bases: object

Complete DeepH-format data: structure + one or more matrices.

Read from a directory containing:
  • POSCAR — lattice, atom symbols, atom coords

  • info.jsonelements_orbital_map

  • hamiltonian.h5required — atom_pairs, chunk_*, entries (eV)

  • overlap.h5optional — same layout, overlap entries

  • hamiltonian_init.h5optional — same layout, initial Hamiltonian entries (the 0 in the filename denotes the initial Hamiltonian, per DeepH on-disk convention)

  • force.h5optional — MD-style: cell, energy, force, stress datasets (energy in eV, force in eV/Å, stress as zeros)

Can also be constructed in-memory via from_memory or from aimspy standard-format matrices via from_aimspy.

classmethod from_aimspy(structure, hamiltonian=None, overlap=None, initial_hamiltonian=None, template=None, path=None, force=None, energy=None, first_order_hamiltonian=None)[source]#

Build from aimspy standard-format matrices + structure.

All matrices are optional — at least one must be given.

Parameters:
  • structure (AimspyStructure) – Used to build POSCAR-order layout unless template is given.

  • hamiltonian (AimspyMatrix, optional) – Hamiltonian (Hartree, aims atom order).

  • overlap (AimspyMatrix, optional) – Overlap matrix (dimensionless).

  • initial_hamiltonian (AimspyMatrix, optional) – Initial / free-atom Hamiltonian (Hartree).

  • template (DeepHData, optional) – If given, reuse its structure fields (lattice, atom_symbols, atom_coords, elements_orbital_map) instead of rebuilding from structure. Convenient when adding matrices to an existing DeepH dataset.

  • path (str or Path, optional) – Pre-specified save path for subsequent save_*() calls.

  • force (np.ndarray, optional) – Forces (n_atoms, 3) in eV/Å, aims atom order. Reordered to POSCAR order inside.

  • energy (float, optional) – Total energy in Hartree (converted to eV inside).

  • first_order_hamiltonian (list[AimspyMatrix], optional) – Electric-response first-order Hamiltonian dH/de — a list of 3 AimspyMatrix in Cartesian order [x, y, z] (Hartree, aims atom order). Reordered to POSCAR order and concatenated per atom pair in DeepH order [y, z, x].

  • note:: (..) – force, energy and first_order_hamiltonian are keyword-only (placed after path) to preserve backward-compatible positional ordering of template.

classmethod from_directory(path)[source]#

Read POSCAR + info.json + matrix .h5 files from path.

Requires POSCAR + info.json + at least one matrix file (hamiltonian.h5, overlap.h5, or hamiltonian_init.h5). Optionally reads force.h5 (MD-style format: cell/energy/force/stress) if present. Sets self.path = path for subsequent save_*() calls.

classmethod from_memory(lattice, atom_symbols, atom_coords, elements_orbital_map, hamiltonian_blocks=None, overlap_blocks=None, initial_hamiltonian_blocks=None, n_basis=0, fermi_energy_eV=0.0, force=None, energy_eV=None, first_order_hamiltonian_blocks=None, path=None)[source]#

Build from in-memory pair-block dicts.

All matrix blocks are optional — at least one must be given. Keys are (R1,R2,R3,i,j) with atoms in POSCAR order. Hamiltonian / initial_hamiltonian blocks in Hartree (converted to eV here). Overlap blocks are dimensionless.

force and energy_eV are optional per-atom / scalar data for MD-style force.h5 export. force is (n_atoms, 3) in eV/Å, already in POSCAR atom order (matching atom_coords). energy_eV is a scalar in eV.

first_order_hamiltonian_blocks is an optional list of 3 block dicts [x, y, z] in Hartree (converted to eV here). The three directions are concatenated per atom pair in DeepH order [y, z, x] (= real spherical harmonics m = -1, 0, +1) and stored in first_order_hamiltonian_entries.

save(path=None)[source]#

Write all non-None content to path (default: self.path).

Saves POSCAR + info.json + every matrix that has been set.

save_first_order_hamiltonian(path=None)[source]#

Write electric_response.h5 (requires first_order entries set).

Layout: same atom_pairs as hamiltonian.h5, but chunk_shapes rows are 3× (one block per Cartesian direction [y, z, x]) and entries is 3× longer.

save_force(path=None)[source]#

Write force.h5 (requires force to be set).

Energy is written if energy_eV is set, else 0.0. Stress is always written as zeros (placeholder).

save_hamiltonian(path=None)[source]#

Write hamiltonian.h5 (requires entries to be set).

save_initial_hamiltonian(path=None)[source]#

Write hamiltonian_init.h5 (requires initial_hamiltonian_entries).

save_metadata(path=None)[source]#

Write POSCAR + info.json to path (default: self.path).

save_overlap(path=None)[source]#

Write overlap.h5 (requires overlap_entries to be set).

set_first_order_hamiltonian(matrix_list, structure)[source]#

Store electric-response first-order Hamiltonian (dH/de) entries.

Converts 3 AimspyMatrix instances (Hartree, aims atom order) into DeepH electric_response.h5 entries (eV, POSCAR order). The three Cartesian directions [x, y, z] are concatenated per atom pair in DeepH order [y, z, x] (= real spherical harmonics m = -1, 0, +1), matching ref/aims_to_deeph.py.

Parameters:
  • matrix_list (list[AimspyMatrix]) – Exactly 3 AimspyMatrix in Cartesian order [x, y, z].

  • structure (AimspyStructure) – Provides the aims→POSCAR atom permutation.

set_force(force_aims, structure, energy=None)[source]#

Store force (eV/Å) and optionally energy (Hartree→eV) from aims order.

Parameters:
  • force_aims (np.ndarray or list) – Forces (n_atoms, 3) in eV/Å, aims atom order. Reordered to POSCAR order inside. Accepts list or ndarray.

  • structure (AimspyStructure) – Provides the aims→POSCAR atom permutation.

  • energy (float, optional) – Total energy in Hartree (converted to eV), or None.

set_hamiltonian(matrix, structure)[source]#

Convert and store Hamiltonian entries (eV) from matrix.

set_initial_hamiltonian(matrix, structure)[source]#

Convert and store initial Hamiltonian entries (eV) from matrix.

set_overlap(matrix, structure)[source]#

Convert and store overlap entries (dimensionless) from matrix.

to_aimspy(structure)[source]#

Convert this DeepH data to aimspy standard format.

Converts the Hamiltonian entries (self.entries). If entries is None, raises aimspy.AimspyConfigError.

  • Atom reordering: POSCAR → aims (via stable-sort un-permutation)

  • R: no flip (same convention: R_aimspy = R_deeph = -R_aims)

  • Parity: no change (same wiki convention)

  • Units: eV → Hartree

The result is suitable for passing to aimspy.Calculator.modify_init_ham() via source=.

Note

Only the Hamiltonian is converted. Force and energy (if loaded from force.h5) are accessible directly via the self.force and self.energy_eV attributes — they do not participate in the warmstart injection path.

Parameters:

structure (AimspyStructure) – Live runtime structure (built from AimspyInfo after aimspy_init); provides the POSCAR↔aims atom permutation.

to_first_order_aimspy(structure)[source]#

Convert this DeepH data’s first-order Hamiltonian entries to aimspy standard format.

Returns a list of 3 AimspyMatrix in Cartesian order [x, y, z] (Hartree, aims atom order), suitable for passing to aimspy.Calculator.modify_init_first_order_ham() via source=.

  • Atom reordering: POSCAR → aims (via stable-sort un-permutation)

  • R: no flip (same convention: R_aimspy = R_deeph = -R_aims)

  • Parity: no change (same wiki convention)

  • Units: eV → Hartree

  • Direction order: DeepH [y, z, x][x, y, z]

Parameters:

structure (AimspyStructure) – Live runtime structure (built from AimspyInfo after aimspy_init); provides the POSCAR↔aims atom permutation.

Grid Data#

Real-space integration-grid capture (export_grid_data callback): density, Kohn-Sham/Hartree potentials, grid geometry, derived fields, npz I/O, and MPI gather.

Public — GridData: real-space integration-grid data capture.

Captured via the export_grid_data callback (registered when CalculatorConfig.capture_grid_data=True). Fires once after SCF convergence on every MPI rank; each rank receives its own grid-point subset.

Note

LDA / scalar only

vks is the scalar part of the Kohn-Sham potential, V_H + v_xc (exact for LDA). The GGA non-local (vector) term 4 * xc_gradient_deriv is not exported, so for GGA functionals vks contains only the scalar part.

Units follow aims native conventions: coords in bohr, potentials in Hartree, densities in electrons/bohr^3, partition_tab in bohr^3.

class aimspy.grid_data.GridData(n_full_points, n_spin, n_atoms, atom_coords=None, atom_symbols=None, lattice=None, coords=None, partition_tab=None, index_atom=None, index_radial=None, index_angular=None, rho=None, vks=None, vks0=None, vh=None, vh0=None, rho0=None)[source]#

Bases: object

Per-rank real-space grid data (independent numpy copies).

All arrays are this MPI rank’s subset. After calc(), use gather() to assemble the global grid on a root rank.

Index arrays (index_atom etc.) are 0-based (converted from the Fortran 1-based convention).

property coords_ang#

Grid coordinates in Angstrom.

property delta_rho#

Density difference rho - rho_free (broadcast to n_spin).

property delta_vh#

vh - vh0 (self-consistent minus free-atom electrostatic).

property delta_vks#

vks - vks0 (analogous to dH = H - H0).

classmethod gather(local, comm, root=0)[source]#

Gather per-rank subsets to root and concatenate along the grid-point axis.

Uses mpi4py.MPI.Comm.Gatherv for memory-efficient, zero-pickle transfer of numpy arrays. Root peak memory is ~1x the total dataset (the receive buffer only), compared to ~3x for the default comm.gather on a Python dict (pickle + deserialize + concat).

Parameters:
  • local (GridData) – This rank’s subset.

  • comm (mpi4py.MPI.Comm) – MPI communicator.

  • root (int) – Destination rank (default 0).

Returns:

On root: the global GridData (n_full_points = global total). On non-root ranks: None.

Return type:

GridData or None

Notes

The global point order is “concatenated by rank” and is not guaranteed to match the point order of a single-rank run; all integral / mapped quantities are unaffected (verified np=1/4/8). The structure fields (atom_coords / atom_symbols / lattice) are identical on every rank, so the root’s copy is kept.

integrated_electrons()[source]#

sum(partition_tab * rho) summed over spin channels.

classmethod load_npz(path)[source]#

Load a dataset saved via save_npz().

property rho_free#

Free-atom superposition density, shape (n,) (spin-independent).

Identical to rho0 — the 4*pi factor is already removed at import time, so rho0 and rho_free are the same physical density.

save_npz(path)[source]#

Save this (per-rank or gathered) dataset to a .npz file.

Structure fields (atom_coords / atom_symbols / lattice) are stored when present, making the file self-describing. All come from the in-memory aims runtime structure (never re-read from input files).

property vxc#

XC potential vks - vh (scalar part; exact for LDA).

property vxc0#

XC potential of the free-atom density vks0 - vh0.

Basis Data#

NAO radial basis capture (export_basis_data callback): cubic-spline representation of all radial basis functions with per-species logarithmic grids, spline evaluation, and incremental basis.h5 export.

Public — BasisData: NAO radial basis function capture.

Captured via the export_basis_data callback (registered when CalculatorConfig.capture_basis_data=True). Fires once after shrink_fixed_basis_phi_thresh completes (pre-SCF), so the basis is fully determined before any SCF iteration.

The exported data contains the complete spline representation of all radial basis functions u(r), their kinetic terms (e−v)·u(r), and their radial derivatives du/dr, together with the per-species logarithmic grid parameters needed to evaluate them at arbitrary distances.

Units: lengths in bohr, energies in Hartree. u(r) is normalized such that ∫ u(r)² dr = 1, giving units of bohr^(−1/2).

class aimspy.basis_data.BasisData(n_species, n_basis_fns, n_max_grid, n_max_spline, r_grid_min=None, r_grid_inc=None, n_grid=None, r_grid=None, outer_radius=None, spline_wave=None, spline_kinetic=None, spline_deriv=None, species_of_fn=None)[source]#

Bases: object

NAO radial basis function data (independent numpy copies).

Contains the full cubic-spline representation of all radial basis functions, plus per-species logarithmic grid parameters. Identity metadata (n, l, type, species) is obtained from AimspyInfo (already exported via aimspy_get_info).

evaluate_deriv(i_fn, r, species_of_fn=None)[source]#

Evaluate the aims-native du/dr spline of radial function i_fn.

NOTE: FHI-aims builds spline_deriv only when use_basis_gradients is on (or x2c/q4c relativity); otherwise the exported array is all zeros. For a derivative that is always available use evaluate_du_dr(), which differentiates spline_wave analytically — where spline_deriv is non-zero the two agree to spline accuracy.

evaluate_du_dr(i_fn, r, species_of_fn=None)[source]#

Evaluate du/dr (physical radial derivative).

The analytic derivative of the stored spline_wave cubic spline is used, via the chain rule du/dr = (du/di) / (α·r), where du/di is the spline derivative with respect to the grid index (α = ln(r_grid_inc)). This is the same quantity FHI-aims tabulates separately in spline_deriv (available — when built — via evaluate_deriv()); the two agree to spline accuracy, but are not bit-identical since spline_deriv is itself a cubic splined tabulated derivative while this one is the analytic derivative of the wave spline.

evaluate_kinetic(i_fn, r, species_of_fn=None)[source]#

Evaluate the kinetic term (e−v)·u(r) of radial function i_fn.

This is the (eigenvalue − potential)·u product tabulated during basis generation and exported as spline_kinetic; units Hartree·bohr^(−1/2). Same domain mask as evaluate_u().

evaluate_phi(i_fn, r, species_of_fn=None)[source]#

Evaluate φ(r) = u(r)/r (the actual radial wavefunction).

evaluate_u(i_fn, r, species_of_fn=None)[source]#

Evaluate u(r) for radial function i_fn at distances r.

Parameters:
  • i_fn (int) – Global 0-based radial function index.

  • r (np.ndarray) – Distances in bohr.

  • species_of_fn (np.ndarray, optional) – (n_basis_fns,) int array mapping each radial function to its 0-based species index (from AimspyInfo.basisfn_species). Defaults to the map attached to this object at capture time.

Returns:

u(r) values, same shape as r. Zero outside [r_grid_min, outer_radius].

Return type:

np.ndarray

save_h5(path, info)[source]#

Save basis data to an HDF5 file, one group per element.

The file is created if it does not exist; existing elements are not overwritten (incremental add only). The file can be shared across multiple calculations to build a basis library.

Parameters:
  • path (str or Path) – Path to the H5 file.

  • info (AimspyInfo) – The info snapshot (for species metadata and identity arrays).

Returns:

Mapping from element symbol to whether it was newly added (True) or skipped because it already existed (False).

Return type:

dict[str, bool]

species_r_grid(sp)[source]#

Return the logarithmic radial grid for species sp (0-based).

Uses the pre-computed r_grid array (extracted from the concatenated buffer by species offset).

species_r_grid_rebuild(sp)[source]#

Rebuild the logarithmic grid from the 3 scalar parameters.

Provided for verification: species_r_grid_rebuild(sp) should match species_r_grid(sp) to machine precision.

Visualization#

Plotting helpers for grid data (slices, radial profiles, isosurfaces) and NAO radial basis functions from basis.h5.

Public — visualization helpers for GridData.

Lightweight plotting for the atom-centred (Delley radial x Lebedev angular) integration grid and the scalar fields living on it (rho, vks, delta_rho, vxc, …).

Design notes#

  • The grid is non-uniform and non-Cartesian (dense near nuclei, sparse in the far field), and rho spans many orders of magnitude. Two families of plots are therefore provided:

    • scatter (scatter_slice()) — zero interpolation, faithful to the raw grid values (best for diagnosing the grid itself);

    • interpolated contour (slice_contour()) — interpolates a field onto a regular 2-D mesh for publication-quality cuts (use log=True for density / potential magnitudes).

  • rho has a huge dynamic range (~1e-30 .. 1e4 e/bohr^3). Always use log=True (or pass a pre-transformed array) for meaningful density plots.

  • 3-D isosurfaces (isosurface()) require the optional pyvista package (pip install pyvista); it is imported lazily and raises a clear error if unavailable.

All functions accept either a field name (str, looked up on the GridData) or an explicit 1-D (n,) array of per-point values. matplotlib is imported lazily so that importing aimspy stays cheap.

aimspy.viz.isosurface(grid, value, iso, nx=80, ny=80, nz=80, log=False, angstrom=True, off_screen=True, screenshot=None, cmap='viridis', opacity=0.9, show=True)[source]#

Render 3-D isosurface(s) of a field (requires pyvista).

The scattered grid values are first interpolated onto a regular nx x ny x nz mesh (scipy griddata), then wrapped as a pyvista.ImageData and contoured with contour([iso]).

Note

pyvista is an optional dependency. Install it with pip install pyvista. This function raises ImportError with a clear message if it is not installed.

Parameters:
  • grid (GridData)

  • value (str or (n,) array)

  • iso (float or sequence of float) – Isosurface value(s), in the (possibly log-transformed) field units.

  • nx (int) – Interpolation mesh resolution.

  • ny (int) – Interpolation mesh resolution.

  • nz (int) – Interpolation mesh resolution.

  • log (bool) – If True, isosurface log10(max(value, tiny)) (recommended for rho).

  • angstrom (bool) – Interpolate in Angstrom-scaled coordinates (default) or bohr.

  • off_screen (bool) – Render off-screen (headless; default True — needed on clusters).

  • screenshot (str or None) – If given, save a PNG screenshot to this path.

  • cmap (appearance)

  • opacity (appearance)

  • show (bool) – Call plotter.show(). Set False to only build/return the plotter.

Returns:

plotter

Return type:

pyvista.Plotter

aimspy.viz.radial_profile(grid, value, atom_index=None, center=None, angstrom=True, logy=True, marker='.', ms=2.0, ax=None, label=None)[source]#

Plot a field versus radial distance from an atom or a point.

Exactly one of atom_index / center must be given. atom_index uses the true nuclear position from grid.atom_coords (preferred, exact) or, as a fallback when the structure fields are absent, the centroid of that atom’s grid points (0-based index into grid.index_atom). center is an explicit (x, y, z).

Parameters:
  • grid (GridData)

  • value (str or (n,) array)

  • atom_index (int or None) – 0-based atom index (matches grid.index_atom).

  • center ((3,) sequence or None) – Explicit centre (same unit as angstrom flag).

  • angstrom (bool) – Plot radius in Angstrom (default) or bohr.

  • logy (bool) – Log-scale the y axis (recommended for rho).

  • marker (matplotlib scatter style)

  • ms (matplotlib scatter style)

  • ax (matplotlib target / legend label)

  • label (matplotlib target / legend label)

Returns:

ax

Return type:

matplotlib Axes

aimspy.viz.scatter_slice(grid, value, axis=2, center=0.0, width=1.0, log=False, symlog=False, linthresh=0.001, cmap=None, angstrom=True, s=5.0, ax=None, colorbar=True)[source]#

Scatter-plot a field on grid points near a plane (no interpolation).

Selects points with |coords[axis] - center| <= width and plots them in the remaining two coordinates, coloured by the field value.

Parameters:
  • grid (GridData)

  • value (str or (n,) array) – Field to colour by (e.g. 'rho', 'vks', 'delta_rho').

  • axis (int) – Normal of the slicing plane (0=x, 1=y, 2=z).

  • center (float) – Plane position along axis (same unit as angstrom flag).

  • width (float) – Half-thickness of the slab of accepted points.

  • log (bool) – Colour by log10(value) — for strictly-positive fields (rho).

  • symlog (bool) – Diverging symmetric-log colour scale (linear within ±linthresh, logarithmic outside). Recommended for difference fields (delta_rho / delta_vks): their signal concentrates near zero yet spans decades, so a plain linear scale makes most points look uniformly ~0. Takes precedence over log.

  • linthresh (float) – Linear region half-width for symlog (default 1e-3).

  • cmap (str or None) – Colormap. Default: 'RdBu_r' when the field has both signs (or symlog=True), else 'viridis'.

  • angstrom (bool) – Interpret center/width and plot axes in Angstrom (default) / bohr.

  • s (float) – Marker size (default 5.0 — large enough to stay visible on the dense atom-centred grid).

  • ax (matplotlib target / toggle)

  • colorbar (matplotlib target / toggle)

Returns:

ax

Return type:

matplotlib Axes

aimspy.viz.slice_contour(grid, value, axis=2, center=0.0, width=1.0, nx=200, ny=200, log=False, symlog=False, linthresh=0.001, angstrom=True, levels=60, cmap=None, method='linear', ax=None, colorbar=True)[source]#

Interpolate a field onto a regular 2-D mesh and draw a filled contour.

Points within |coords[axis]-center| <= width are interpolated with scipy.interpolate.griddata() onto an nx x ny mesh spanning the data extent in the remaining two coordinates.

Parameters:
  • grid (GridData)

  • value (str or (n,) array)

  • axis – See scatter_slice(). Use symlog=True for difference fields (delta_rho / delta_vks); the norm is built on the raw values before interpolation so the colour mapping stays faithful.

  • center – See scatter_slice(). Use symlog=True for difference fields (delta_rho / delta_vks); the norm is built on the raw values before interpolation so the colour mapping stays faithful.

  • width – See scatter_slice(). Use symlog=True for difference fields (delta_rho / delta_vks); the norm is built on the raw values before interpolation so the colour mapping stays faithful.

  • log – See scatter_slice(). Use symlog=True for difference fields (delta_rho / delta_vks); the norm is built on the raw values before interpolation so the colour mapping stays faithful.

  • symlog – See scatter_slice(). Use symlog=True for difference fields (delta_rho / delta_vks); the norm is built on the raw values before interpolation so the colour mapping stays faithful.

  • linthresh – See scatter_slice(). Use symlog=True for difference fields (delta_rho / delta_vks); the norm is built on the raw values before interpolation so the colour mapping stays faithful.

  • cmap – See scatter_slice(). Use symlog=True for difference fields (delta_rho / delta_vks); the norm is built on the raw values before interpolation so the colour mapping stays faithful.

  • angstrom – See scatter_slice(). Use symlog=True for difference fields (delta_rho / delta_vks); the norm is built on the raw values before interpolation so the colour mapping stays faithful.

  • ax – See scatter_slice(). Use symlog=True for difference fields (delta_rho / delta_vks); the norm is built on the raw values before interpolation so the colour mapping stays faithful.

  • colorbar – See scatter_slice(). Use symlog=True for difference fields (delta_rho / delta_vks); the norm is built on the raw values before interpolation so the colour mapping stays faithful.

  • nx (int) – Interpolation mesh resolution.

  • ny (int) – Interpolation mesh resolution.

  • levels (int or sequence) – Contour levels (passed to contourf). For symlog an integer count is recommended (matplotlib spaces them per the norm).

  • method ({'linear', 'nearest', 'cubic'}) – griddata interpolation method. 'linear' is a good default; 'nearest' avoids overshoot in sparse regions.

Returns:

ax

Return type:

matplotlib Axes

Public — visualization of NAO radial basis functions from basis.h5.

Reads the element-grouped HDF5 file written by aimspy.BasisData.save_h5() and plots the radial basis functions u(r) (or φ(r) = u(r)/r) of one element per figure.

Design notes#

  • File-driven, runtime-free — everything is read from the H5 file, so plots can be made on machines without libaims / MPI.

  • Curves are evaluated through the stored cubic-spline coefficients on a uniform display grid (n_plot points), which is typically denser than the logarithmic grid in the physically relevant region and much smoother-looking than plotting raw grid values.

  • Each radial function is labelled nl-z, e.g. 1s-0, 2p-1 (z = zeta index — the repetition count of the same (n, l) pair in aims’ internal collection order), optionally suffixed with its type (atomic / hydro / …).

  • Colour encodes l, line style encodes the function type.

  • The default show_grid=True draws a rug plot — short grey ticks along the bottom of the axes marking the logarithmic grid points within the displayed range. (The log grid puts ~2/3 of its points below 0.1 Å, so markers on the curves themselves would be unreadable.) With logx=True the x axis is logarithmic, which spreads the log-grid sample evenly across the plot — the natural view of these basis functions.

matplotlib is imported lazily so that importing aimspy stays cheap.

aimspy.viz_basis.list_elements(h5_path)[source]#

Return the element symbols available in a basis.h5 file.

aimspy.viz_basis.plot_radial_basis(h5_path, element, kind='u', angstrom=True, n_plot=500, r_max=None, split_l=False, logx=False, show_type=True, show_grid=True, figsize=None, save=None)[source]#

Plot the radial basis functions of one element from basis.h5.

Parameters:
  • h5_path (str or Path) – Path to the basis H5 file (element-per-group format).

  • element (str) – Element symbol (e.g. 'Mo'); must exist in the file.

  • kind ({'u', 'phi'}) – Plot the reduced radial function u(r) (default, the raw splined quantity, normalized so ∫u²dr = 1) or the true radial function φ(r) = u(r)/r.

  • angstrom (bool) – x axis in Angstrom (default) or bohr.

  • n_plot (int) – Number of uniformly spaced evaluation points per curve.

  • r_max (float or None) – x axis upper limit in plot units. Default: the element’s largest outer_radius (its global cutoff).

  • split_l (bool) – One panel per angular momentum l instead of a single overlay.

  • logx (bool) – Log-scale the x axis (default False — the natural view for the logarithmic grid: the log-grid sample points appear evenly spread instead of being squashed into the leftmost decade). A log y axis is intentionally not offered: radial basis functions carry sign (nodes), and plotting them on a log y axis silently hides the negative lobes.

  • show_type (bool) – Append the function type (atomic/hydro/…) to labels.

  • show_grid (bool) – Draw grey rug ticks at the bottom marking the logarithmic grid points within the displayed range (default True).

  • figsize (figure size / optional save path (matplotlib infers) – the format from the suffix).

  • save (figure size / optional save path (matplotlib infers) – the format from the suffix).

Return type:

matplotlib.figure.Figure

Exceptions#

AimsPy-specific exception hierarchy.

Aimspy-specific exception hierarchy.

exception aimspy._exceptions.AimspyBindingError[source]#

Bases: AimspyError

libaims loading failure or missing C symbol.

exception aimspy._exceptions.AimspyCallbackError[source]#

Bases: AimspyError

Callback registration or invocation failure.

exception aimspy._exceptions.AimspyConfigError[source]#

Bases: AimspyError

Configuration / argument validation error.

exception aimspy._exceptions.AimspyError[source]#

Bases: Exception

Base class for all aimspy-raised exceptions.

exception aimspy._exceptions.AimspyStateError[source]#

Bases: AimspyError

Operation attempted in the wrong Calculator state.

Callback Identifiers#

Enum identifying callback types for register_callback.

Private — callback registry: the authoritative list of all callback types.

This is the central catalogue. Adding a new callback = adding one CallbackSpec entry here, plus changes in 3 other wired places (Fortran patch, _binding/callback_types.py, _binding/prototypes.py, _callbacks/base.py wrapper branch).

class aimspy._callbacks.registry.CallbackName(value)[source]#

Bases: Enum

Callback type identifiers (accepts str or CallbackName).

Used by aimspy.Calculator.register_callback() and aimspy.Calculator.callback_registered().

aimspy._callbacks.registry.get_spec(name)[source]#

Look up a CallbackSpec by name.