qdk_chemistry.algorithms.registry module
QDK/Chemistry-algorithms registry.
This module contains a registration mechanism for Hamiltonian constructor, SCF solver, localizer, active space selector, coupled cluster calculator, (projected) multi configuration calculator, and MultiConfigurationScf. The user should be able to use the registration mechanism to easily add and remove custom algorithms at runtime.
Algorithm Lifecycle Management
The registry system handles the lifecycle of algorithm instances to prevent memory issues. When Python-implemented algorithms are registered, they need special handling during Python interpreter shutdown to avoid “double-free” errors that can occur when C++ static deinitialization runs after Python’s garbage collection.
This module automatically registers cleanup handlers (via atexit) that unregister all custom algorithms before Python shuts down. Users should never need to call the cleanup functions directly.
Important Notes
All registration functions in this module provide automatic cleanup.
Custom Python algorithms are automatically unregistered during interpreter shutdown.
The cleanup functions are not intended to be called by users.
- qdk_chemistry.algorithms.registry.available(algorithm_type=None)[source]
List all available algorithms by type.
This function returns information about available algorithms in the registry. When called without arguments, it returns a dictionary mapping all algorithm types to their available implementations. When called with a specific algorithm type, it returns only the list of available algorithms for that type.
- Return type:
- Parameters:
algorithm_type (str | None) –
If provided, only list algorithms of this type.
If None, list all algorithms across all types.
- Returns:
Information on available algorithms.
When algorithm_type is None, returns a dictionary where keys are algorithm type names and values are lists of available algorithm names for that type. When algorithm_type is specified, returns a list of available algorithm names for that specific type (empty list if type not found or no algorithms are available).
- Return type:
Examples
>>> from qdk_chemistry.algorithms import registry >>> # List all available algorithms across all types >>> all_algorithms = registry.available() >>> print(all_algorithms) {'scf_solver': ['pyscf', 'qdk'], 'active_space_selector': ['pyscf_avas', 'qdk_occupation', ...], ...} >>> # List only SCF solvers >>> scf_solvers = registry.available("scf_solver") >>> print(scf_solvers) ['pyscf', 'qdk'] >>> # Check what active space selectors are available >>> selectors = registry.available("active_space_selector") >>> print(selectors) ['pyscf_avas', 'qdk_occupation', 'qdk_autocas_eos', 'qdk_autocas', 'qdk_valence']
- qdk_chemistry.algorithms.registry.create(algorithm_type, algorithm_name=None, **kwargs)[source]
Create an algorithm instance by type and name.
This function creates an algorithm instance from the registry using the specified algorithm type and name. If no name is provided, the default implementation for that type is created.
Available algorithm types depend on the installed plugins and any user-registered algorithms. Use
available()to inspect what is currently loaded before callingcreate().- Return type:
- Parameters:
algorithm_type (str) –
The type of algorithm to create.
(e.g., “scf_solver”, “active_space_selector”, “coupled_cluster_calculator”).
algorithm_name (str | None) –
The specific name of the algorithm implementation to create.
If None or empty string, creates the default algorithm for that type.
kwargs –
Optional keyword arguments (passed via
**kwargs).These configure the algorithm’s settings. These are forwarded directly to the algorithm’s settings via settings().update(). Available settings depend on the specific algorithm type and implementation and can be looked up with inspect_settings() or print_settings().
- Returns:
The created algorithm instance.
- Return type:
- Raises:
KeyError – If the specified algorithm type is not registered in the system.
Examples
>>> from qdk_chemistry.algorithms import registry >>> # Create the default SCF solver >>> scf = registry.create("scf_solver") >>> # Create a specific SCF solver by name >>> pyscf_solver = registry.create("scf_solver", "pyscf") >>> # Create an SCF solver with custom settings >>> scf = registry.create("scf_solver", "pyscf", max_iterations=100, convergence_threshold=1e-8) >>> # Create an MP2 calculator >>> mp2_calc = registry.create("dynamical_correlation_calculator", "qdk_mp2_calculator") >>> # Create the default reference-derived calculator (MP2) >>> default_calc = registry.create("dynamical_correlation_calculator")
- qdk_chemistry.algorithms.registry.inspect_settings(algorithm_type, algorithm_name)[source]
Inspect the settings schema for a specific algorithm.
This function retrieves the settings schema for a given algorithm type and name. The settings schema provides information about configurable parameters for the algorithm, including their names, expected Python types, default values, descriptions, and allowed values/ranges.
- Return type:
- Parameters:
- Returns:
- A list of tuples where each tuple contains:
Setting name (str): The name/key of the setting
Expected Python type (str): The Python type expected for this setting (e.g., int, float, str, bool, list[int], list[float])
Default value (Any): The default value for this setting
Description (str | None): Human-readable description of the setting, or None if not available
Limits (Any | None): Allowed values or range, or None if not constrained. For numeric types: tuple of (min, max). For strings/lists: list of allowed values.
- Return type:
- Raises:
KeyError – If the specified algorithm type is not registered in the system.
Examples
>>> from qdk_chemistry.algorithms import registry >>> # Show settings for the PySCF SCF solver >>> settings_info = registry.inspect_settings("scf_solver", "pyscf") >>> for name, python_type, default, description, limits in settings_info: ... limit_str = f" (allowed: {limits})" if limits else "" ... desc_str = f" # {description}" if description else "" ... print(f"{name}: {python_type} = {default}{limit_str}{desc_str}") method: str = hf (allowed: ['hf', 'dft']) # SCF method to use basis_set: str = def2-svp # Basis set for the calculation charge: int = 0 # Total molecular charge spin_multiplicity: int = 1 (allowed: (1, 10)) # Spin multiplicity (2S+1) tolerance: float = 1e-06 (allowed: (1e-12, 0.01)) # Convergence threshold max_iterations: int = 50 (allowed: (1, 1000)) # Maximum SCF iterations force_restricted: bool = False # Force restricted calculation
- qdk_chemistry.algorithms.registry.print_settings(algorithm_type, algorithm_name, characters=120)[source]
Print the settings table for a specific algorithm.
This function retrieves and prints the settings schema for a given algorithm type and name as a formatted table. The table displays configurable parameters including their names, current values, allowed values/ranges, and descriptions.
- Return type:
- Parameters:
- Raises:
KeyError – If the specified algorithm type is not registered in the system.
Examples
>>> from qdk_chemistry.algorithms import registry >>> # Print settings table for the PySCF SCF solver >>> registry.print_settings("scf_solver", "pyscf") ------------------------------------------------------------------------------------------------------------------------ Key | Value | Allowed | Description ------------------------------------------------------------------------------------------------------------------------ charge | 0 | - | Total molecular charge convergence_thresh...| 1.00e-06 | 1.00e-12 <= x | Energy convergence threshold | | x <= 1.00e-02 | force_restricted | false | - | Force restricted calculation max_iterations | 50 | 1 <= x <= 1000 | Maximum SCF iterations method | "hf" | ["hf", "dft"] | SCF method to use spin_multiplicity | 1 | 1 <= x <= 10 | Spin multiplicity (2S+1) ------------------------------------------------------------------------------------------------------------------------ >>> # Print with custom width >>> registry.print_settings("scf_solver", "pyscf", characters=100)
- qdk_chemistry.algorithms.registry.register(generator)[source]
Register a custom algorithm implementation.
This function registers a custom algorithm implementation (typically written in Python) into the registry system. The generator function should return a new instance of the algorithm each time it’s called. The algorithm’s type is automatically detected from the returned instance.
- Return type:
- Parameters:
generator (Callable[[], Algorithm]) –
A callable that returns a new instance.
Need to return an instance of the custom algorithm. This will be called each time the algorithm is created from the factory.
- Raises:
KeyError – If the algorithm’s type is not a recognized algorithm type in the system.
Examples
>>> from qdk_chemistry.algorithms import registry >>> from qdk_chemistry.algorithms import ScfSolver >>> class MyCustomScf(ScfSolver): ... def name(self): ... return "my_custom_scf" ... def _run_impl(self, structure, charge, spin_multiplicity): ... # Custom implementation ... pass >>> # Register the custom algorithm >>> registry.register(lambda: MyCustomScf()) >>> # Now it can be created from the registry >>> scf = registry.create("scf_solver", "my_custom_scf")
- qdk_chemistry.algorithms.registry.register_factory(factory)[source]
Register a new algorithm factory.
This function allows adding new algorithm factories to the registry, thus adding entire algorithm types.
- Return type:
- Parameters:
factory (AlgorithmFactory) – The factory instance to register.
- Raises:
ValueError – If a factory with the same algorithm type name is already registered.
- qdk_chemistry.algorithms.registry.show_default(algorithm_type=None)[source]
List the default algorithm by type.
This function returns information about the default algorithms configured for each algorithm type. When called without arguments, it returns a dictionary mapping all algorithm types to their default algorithm names. When called with a specific algorithm type, it returns only the default algorithm name for that type.
- Return type:
- Parameters:
algorithm_type (str | None) – If provided, only return the default algorithm for this type. If None, return default algorithms for all types.
- Returns:
- When algorithm_type is None, returns a dictionary where
keys are algorithm type names and values are the default algorithm names for each type. When algorithm_type is specified, returns the default algorithm name for that specific type (empty string if type not found).
- Return type:
Examples
>>> from qdk_chemistry.algorithms import registry >>> # List the default algorithms across all types >>> default_algorithms = registry.show_default() >>> print(default_algorithms) {'scf_solver': 'qdk', 'active_space_selector': 'qdk_autocas_eos', ...} >>> # Get the default SCF solver >>> default_scf = registry.show_default("scf_solver") >>> print(default_scf) 'qdk'
- qdk_chemistry.algorithms.registry.unregister(algorithm_type, algorithm_name)[source]
Unregister a custom algorithm implementation.
This function removes a previously registered algorithm from the registry.
- Return type:
- Parameters:
- Raises:
KeyError – If the specified algorithm type is not registered in the system.
Examples
>>> from qdk_chemistry.algorithms import registry >>> # Assuming you previously registered a custom algorithm >>> registry.unregister("scf_solver", "my_custom_scf")