qdk_chemistry.algorithms.base module

QDK Chemistry Algorithms Base Class.

This module defines the base class for custom algorithms that can be integrated into the QDK/Chemistry framework.

class qdk_chemistry.algorithms.base.Settings

Bases: DataClass

Base class for extensible settings objects.

This class provides a flexible settings system that can:

  • Store arbitrary typed values using a variant system

  • Be easily extended by derived classes during construction only

  • Map seamlessly to Python dictionaries via pybind11

  • Provide type-safe access to settings with default values

  • Support nested settings structures

  • Prevent extension of the settings map after class initialization

The settings map can only be populated during construction using _set_default.

Examples

To create a custom settings class in Python: >>> class MySettings(qdk_chemistry.data.Settings): … def __init__(self): … super().__init__() … self._set_default(“method”, “string”, “default”) … self._set_default(“max_iterations”, “int”, 100) … self._set_default(“convergence_threshold”, “double”, 1e-6) … >>> settings = MySettings() >>> settings[“method”] = “hf” >>> settings.method = “hf” # Alternative access >>> settings[“max_iterations”] = 200 >>> settings[“convergence_threshold”] = 1e-8 >>> value = settings[“method”] >>> print(“convergence_threshold” in settings) >>> print(len(settings)) >>> >>> # Iterator functionality >>> for key in settings: … print(key, settings[key]) >>> for key in settings.keys(): … print(key) >>> for value in settings.values(): … print(value) >>> for key, value in settings.items(): … print(f”{key}: {value}”) >>> >>> print(settings.to_dict()) # Convert to dict

Alternative: If you have an existing Settings object

>>> settings = get_settings_from_somewhere()  # Already has keys defined
>>> settings["method"] = "hf"  # This works if "method" key exists
>>> settings.method = "hf"     # This also works
__init__(self: qdk_chemistry.data.Settings) None

Default constructor.

Creates an empty Settings object with no key-value pairs.

Examples

>>> settings = Settings()
as_table(self: qdk_chemistry.data.Settings, max_width: SupportsInt = 120, show_undocumented: bool = False) str

Print settings as a formatted table.

Prints all documented settings in a table format with columns: Key, Value, Limits, Description

The table fits within the specified width with multi-line descriptions as needed. Non-integer numeric values are displayed in scientific notation.

Parameters:
  • max_width (int) – Maximum total width of the table (default: 120)

  • show_undocumented (bool) – Whether to show undocumented settings (default: False)

Returns:

Formatted table string

Return type:

str

Examples

>>> print(settings.as_table())
------------------------------------------------------------
Key                  | Value           | Limits              | Description
------------------------------------------------------------
max_iterations       | 100             | [1, 1000]           | Maximum number of iterations
method               | "hf"            | ["hf", "dft"...]    | Electronic structure method
tolerance            | 1.00e-06        | [1.00e-08, 1.00...  | Convergence tolerance
------------------------------------------------------------
empty(self: qdk_chemistry.data.Settings) bool

Check if settings are empty.

Returns:

True if no settings are stored, False otherwise

Return type:

bool

Examples

>>> if settings.empty():
...     print("No settings configured")
from_dict(*args, **kwargs)

Overloaded function.

  1. from_dict(self: qdk_chemistry.data.Settings, dict: dict) -> None

Load settings from Python dictionary.

Updates existing settings with values from the provided dictionary. Keys must be strings or convertible to strings. Only predefined settings keys can be updated. Values must match expected types.

Parameters:

dict (dict) – Python dictionary containing settings

Raises:

Examples

>>> config = {
...     'method': 'hf',
...     'max_iterations': 100,
...     'tolerance': 1e-6,
...     'parameters': [1.0, 2.0, 3.0]
... }
>>> settings.from_dict(config)
>>> assert settings['method'] == 'hf'
  1. from_dict(self: qdk_chemistry.data.Settings, dict: dict) -> None

Load settings from Python dictionary.

Updates existing settings with values from the provided dictionary. Keys must be strings or convertible to strings. Only predefined settings keys can be updated. Values must match expected types.

Parameters:

dict (dict) – Python dictionary containing settings

Raises:

Examples

>>> config = {
...     'method': 'hf',
...     'max_iterations': 100,
...     'tolerance': 1e-6,
...     'parameters': [1.0, 2.0, 3.0]
... }
>>> settings.from_dict(config)
>>> assert settings['method'] == 'hf'
static from_file(filename: object, format_type: str) qdk_chemistry.data.Settings

Load settings from file in specified format.

Parameters:
  • filename (str | pathlib.Path) – Path to input file.

  • format_type (str) – Format type (“json” or “hdf5”)

Raises:

RuntimeError – If the file cannot be opened, read, or contains invalid settings data

Examples

>>> settings.from_file("config.settings.json", "json")
>>> settings.from_file("config.settings.h5", "hdf5")
>>> from pathlib import Path
>>> settings.from_file(Path("config.settings.json"), "json")
static from_hdf5_file(filename: object) qdk_chemistry.data.Settings

Load settings from HDF5 file.

Parameters:

filename (str) – Path to input file. Must have ‘.settings.h5’ extension (e.g., config.settings.h5, parameters.settings.h5)

Raises:
  • ValueError – If filename doesn’t follow the required naming convention

  • RuntimeError – If the file cannot be opened, read, or contains invalid settings data

Examples

>>> settings.from_hdf5_file("config.settings.h5")
>>> settings.from_hdf5_file("parameters.settings.h5")
static from_json(json_str: str) qdk_chemistry.data.Settings

Load settings from JSON format.

Parses a JSON string and loads all contained settings, replacing any existing settings. The JSON format should match the output of to_json().

Parameters:

json_str (str) – JSON string containing settings data

Raises:

RuntimeError – If the JSON string is malformed or contains unsupported types

Examples

>>> json_data = '{"method": "hf", "max_iterations": 100}'
>>> settings.from_json(json_data)
>>> assert settings["method"] == "hf"
static from_json_file(*args, **kwargs)

Overloaded function.

  1. from_json_file(filename: object) -> qdk_chemistry.data.Settings

Load settings from JSON file.

Reads settings from a JSON file, replacing any existing settings. The file should contain JSON data in the format produced by to_json_file().

Parameters:

filename (str | pathlib.Path) – Path to the JSON file to read. Must have ‘.settings’ before the file extension (e.g., config.settings.json, params.settings.json)

Raises:
  • ValueError – If filename doesn’t follow the required naming convention

  • RuntimeError – If the file cannot be opened, read, or contains malformed JSON

Examples

>>> settings.from_json_file("config.settings.json")
>>> settings.from_json_file("params.settings.json")
>>> from pathlib import Path
>>> settings.from_json_file(Path("config.settings.json"))
  1. from_json_file(filename: object) -> qdk_chemistry.data.Settings

Load settings from JSON file.

Reads settings from a JSON file, replacing any existing settings. The file should contain JSON data in the format produced by to_json_file().

Parameters:

filename (str | pathlib.Path) – Path to the JSON file to read. Must have ‘.settings’ before the file extension (e.g., config.settings.json, params.settings.json)

Raises:
  • ValueError – If filename doesn’t follow the required naming convention

  • RuntimeError – If the file cannot be opened, read, or contains malformed JSON

Examples

>>> settings.from_json_file("config.settings.json")
>>> settings.from_json_file("parameters.settings.json")
>>> from pathlib import Path
>>> settings.from_json_file(Path("config.settings.json"))
  1. from_json_file(filename: object) -> qdk_chemistry.data.Settings

Load settings from JSON file.

Parameters:

filename (str | pathlib.Path) – Path to input file. Must have ‘.settings.json’ extension (e.g., config.settings.json, parameters.settings.json)

Raises:
  • ValueError – If filename doesn’t follow the required naming convention

  • RuntimeError – If the file cannot be opened, read, or contains invalid settings data

Examples

>>> settings.from_json_file("config.settings.json")
>>> settings.from_json_file("parameters.settings.json")
>>> from pathlib import Path
>>> settings.from_json_file(Path("config.settings.json"))
static from_json_string(json_str: str) qdk_chemistry.data.Settings

Load settings from JSON string format.

This is an alias for from_json() provided for backward compatibility. Both methods accept the same JSON string format.

Parameters:

json_str (str) – JSON string containing settings data

Raises:

RuntimeError – If the JSON string is malformed or contains unsupported types

Examples

>>> settings.from_json_string('{"method": "hf"}')
>>> # Equivalent to:
>>> settings.from_json('{"method": "hf"}')
get(self: qdk_chemistry.data.Settings, key: str) object

Get a setting value as a Python object.

Retrieves the value associated with the given key and converts it to the appropriate Python type.

Parameters:

key (str) – The setting key name

Returns:

The setting value as a Python object (bool, int, float, str, list)

Return type:

object

Raises:

SettingNotFound – If the key is not found in the settings

Examples

>>> method = settings.get("method")
>>> max_iter = settings.get("max_iterations")
>>> convergence_threshold = settings.get("convergence_threshold")
get_as_string(self: qdk_chemistry.data.Settings, key: str) str

Get a setting value as a string representation.

Converts any setting value to its string representation, regardless of the original type.

Parameters:

key (str) – The setting key name

Returns:

String representation of the setting value

Return type:

str

Raises:

SettingNotFound – If the key is not found

Examples

>>> str_val = settings.get_as_string("convergence_threshold")  # "1e-06"
>>> str_val = settings.get_as_string("max_iterations")  # "100"
get_description(self: qdk_chemistry.data.Settings, key: str) str

Get the description of a setting.

Parameters:

key (str) – The setting key name

Returns:

The description string

Return type:

str

Raises:

SettingNotFound – If the key doesn’t exist or has no description

Examples

>>> desc = settings.get_description("max_iterations")
>>> print(desc)  # "Maximum number of iterations"
get_expected_python_type(self: qdk_chemistry.data.Settings, key: str) str

Get the expected Python type for a setting key.

Returns a string describing what Python type should be provided when setting the value for the given key. This is useful for understanding what type of value is expected before attempting to set it.

Parameters:

key (str) – The setting key name

Returns:

Expected Python type (e.g., “int”, “float”, “str”, “bool”, “list[int]”, “list[float]”, “list[str]”, “list[bool]”)

Return type:

str

Raises:

SettingNotFound – If the key is not found

Examples

>>> expected = settings.get_expected_python_type("max_iterations")
>>> print(expected)  # "int"
>>> expected = settings.get_expected_python_type("convergence_threshold")
>>> print(expected)  # "float"
>>> expected = settings.get_expected_python_type("basis_set")
>>> print(expected)  # "str"
>>> expected = settings.get_expected_python_type("active_orbitals")
>>> print(expected)  # "list[int]"
get_limits(self: qdk_chemistry.data.Settings, key: str) object

Get the limits of a setting.

Returns the limit value which can be a range (tuple of min, max) or an enumeration (list of allowed values).

Parameters:

key (str) – The setting key name

Returns:

The limit value - either a range tuple or a list of allowed values

Return type:

tuple[int, int] | tuple[float, float] | list[int] | list[str]

Raises:

SettingNotFound – If the key doesn’t exist or has no limits

Examples

>>> limits = settings.get_limits("max_iterations")
>>> print(limits)  # (1, 1000) for a range
>>>
>>> limits = settings.get_limits("method")
>>> print(limits)  # ['hf', 'dft', 'mp2'] for allowed values
get_or_default(self: qdk_chemistry.data.Settings, key: str, default_value: object) object

Get a setting value with a default if not found (accepts any Python object).

Retrieves the value for the given key if it exists, or returns the default value if the key is not found.

Parameters:
  • key (str) – The setting key name

  • default_value (object) – Default value to return if key not found

Returns:

The setting value or default value as a Python object

Return type:

object

Examples

>>> method = settings.get_or_default("method", "default_method")
>>> max_iter = settings.get_or_default("max_iterations", 1000)
>>> params = settings.get_or_default("parameters", [])
get_or_default_raw(self: qdk_chemistry.data.Settings, key: str, default_value: bool | SupportsInt | SupportsFloat | str | collections.abc.Sequence[SupportsInt] | collections.abc.Sequence[SupportsFloat] | collections.abc.Sequence[str]) bool | int | float | str | list[int] | list[float] | list[str]

Get a setting value with a default if not found (SettingValue).

Raw interface that works with SettingValue variants directly.

Parameters:
  • key (str) – The setting key name

  • default_value (SettingValue) – Default SettingValue to return if key not found

Returns:

The SettingValue variant or default value

Return type:

SettingValue

get_raw(self: qdk_chemistry.data.Settings, key: str) bool | int | float | str | list[int] | list[float] | list[str]

Get a setting value as a SettingValue variant.

This is the raw interface that returns a SettingValue directly, primarily for internal use or advanced scenarios.

Parameters:

key (str) – The setting key name

Returns:

The SettingValue variant

Return type:

SettingValue

Raises:

SettingNotFound – If the key is not found in the settings

get_type_name(*args, **kwargs)

Overloaded function.

  1. get_type_name(self: qdk_chemistry.data.Settings, key: str) -> str

Get the type name of a setting value.

Returns a string describing the current type of the value stored for the given key.

Parameters:

key (str) – The setting key name

Returns:

Type name (e.g., “int”, “double”, “string”, “vector<int>”)

Return type:

str

Raises:

SettingNotFound – If the key is not found

Examples

>>> type_name = settings.get_type_name("max_iterations")  # "int"
>>> type_name = settings.get_type_name("convergence_threshold")  # "double"
  1. get_type_name(self: qdk_chemistry.data.Settings, key: str) -> str

Get the type name of a setting value.

Returns a string describing the current type of the value stored for the given key.

Parameters:

key (str) – The setting key name

Returns:

Type name (e.g., “int”, “double”, “string”, “vector<int>”)

Return type:

str

Raises:

SettingNotFound – If the key is not found

Examples

>>> type_name = settings.get_type_name("max_iterations")  # "int"
>>> type_name = settings.get_type_name("convergence_threshold")  # "double"
has(self: qdk_chemistry.data.Settings, key: str) bool

Check if a setting exists.

Parameters:

key (str) – The setting key name to check

Returns:

True if the setting exists, False otherwise

Return type:

bool

Examples

>>> if settings.has("method"):
...     method = settings.get("method")
>>> exists = settings.has("nonexistent_key")  # False
has_description(self: qdk_chemistry.data.Settings, key: str) bool

Check if a setting has a description.

Parameters:

key (str) – The setting key name

Returns:

True if the setting has a description, False otherwise

Return type:

bool

Examples

>>> if settings.has_description("max_iterations"):
...     desc = settings.get_description("max_iterations")
has_limits(self: qdk_chemistry.data.Settings, key: str) bool

Check if a setting has defined limits.

Parameters:

key (str) – The setting key name

Returns:

True if the setting has limits defined, False otherwise

Return type:

bool

Examples

>>> if settings.has_limits("max_iterations"):
...     limits = settings.get_limits("max_iterations")
is_documented(self: qdk_chemistry.data.Settings, key: str) bool

Check if a setting is documented.

Parameters:

key (str) – The setting key name

Returns:

True if the setting is marked as documented, False otherwise

Return type:

bool

Raises:

SettingNotFound – If the key doesn’t exist

Examples

>>> if settings.is_documented("max_iterations"):
...     print("This setting is documented")
items(*args, **kwargs)

Overloaded function.

  1. items(self: qdk_chemistry.data.Settings) -> list

Get key-value pairs as a list of tuples.

Returns:

List of (key, value) tuples

Return type:

list[tuple]

Examples

>>> all_items = settings.items()
>>> for key, value in all_items:
...     print(f"{key}: {value}")
>>> # Or iterate directly:
>>> for key, value in settings.items():
...     print(f"{key}: {value}")
  1. items(self: qdk_chemistry.data.Settings) -> list

Get key-value pairs as a list of tuples.

Returns:

List of (key, value) tuples

Return type:

list[tuple]

Examples

>>> all_items = settings.items()
>>> for key, value in all_items:
...     print(f"{key}: {value}")
>>> # Or iterate directly:
>>> for key, value in settings.items():
...     print(f"{key}: {value}")
keys(self: qdk_chemistry.data.Settings) list[str]

Get all setting keys.

Returns:

List of all setting key names

Return type:

list[str]

Examples

>>> all_keys = settings.keys()
>>> for key in all_keys:
...     print(f"{key}: {settings[key]}")
lock(self: qdk_chemistry.data.Settings) None

Lock the settings to prevent further modifications.

Once settings are locked, any attempt to modify them will raise an exception. This is useful to ensure that settings remain unchanged after they have been validated or after a computation has started.

Notes

Locking is irreversible for the lifetime of the Settings object. To modify settings after locking, create a copy of the Settings object.

Examples

>>> settings["method"] = "hf"
>>> settings["max_iterations"] = 100
>>> settings.lock()
>>> # Any further modifications will raise SettingsAreLocked exception
>>> settings["method"] = "dft"  # Raises SettingsAreLocked
set(self: qdk_chemistry.data.Settings, key: str, value: object) None

Set a setting value (accepts any Python object).

This method allows setting values using any supported Python type, which will be automatically converted to the appropriate SettingValue variant. The value must match the expected type for the setting key.

Parameters:
  • key (str) – The setting key name

  • value (object) – The value to set (bool, int, float, str, list, tuple, numpy array)

Raises:

Examples

>>> settings.set("method", "hf")
>>> settings.set("max_iterations", 100)
>>> settings.set("convergence_threshold", 1e-6)
>>> settings.set("parameters", [1.0, 2.0, 3.0])
set_raw(self: qdk_chemistry.data.Settings, key: str, value: bool | SupportsInt | SupportsFloat | str | collections.abc.Sequence[SupportsInt] | collections.abc.Sequence[SupportsFloat] | collections.abc.Sequence[str]) None

Set a setting value using a SettingValue variant.

This is the raw interface that accepts a SettingValue directly, primarily for internal use or advanced scenarios.

Parameters:
  • key (str) – The setting key name

  • value (SettingValue) – The SettingValue variant to set

Raises:

RuntimeError – If the key cannot be set

size(self: qdk_chemistry.data.Settings) int

Get the number of settings.

Returns:

Number of setting key-value pairs

Return type:

int

Examples

>>> count = settings.size()
>>> print(f"Settings contain {count} entries")
to_dict(*args, **kwargs)

Overloaded function.

  1. to_dict(self: qdk_chemistry.data.Settings) -> dict

Convert settings to Python dictionary.

Creates a Python dictionary containing all settings with keys as strings and values converted to appropriate Python types.

Returns:

Python dictionary with all settings

Return type:

dict

Examples

>>> settings_dict = settings.to_dict()
>>> print(settings_dict)
{'method': 'hf', 'max_iterations': 100, 'tolerance': 1e-06}
>>>
>>> # Can be used with JSON, pickle, etc.
>>> import json
>>> json_str = json.dumps(settings_dict)
  1. to_dict(self: qdk_chemistry.data.Settings) -> dict

Convert settings to Python dictionary.

Creates a Python dictionary containing all settings with keys as strings and values converted to appropriate Python types.

Returns:

Python dictionary with all settings

Return type:

dict

Examples

>>> settings_dict = settings.to_dict()
>>> print(settings_dict)
{'method': 'hf', 'max_iterations': 100, 'tolerance': 1e-06}
>>>
>>> # Can be used with JSON, pickle, etc.
>>> import json
>>> json_str = json.dumps(settings_dict)
to_file(self: qdk_chemistry.data.Settings, filename: object, format_type: str) None

Save settings to file in specified format.

Parameters:
  • filename (str | pathlib.Path) – Path to output file.

  • format_type (str) – Format type (“json” or “hdf5”)

Raises:

RuntimeError – If the file cannot be opened or written

Examples

>>> settings.to_file("config.settings.json", "json")
>>> settings.to_file("config.settings.h5", "hdf5")
>>> from pathlib import Path
>>> settings.to_file(Path("config.settings.json"), "json")
to_hdf5_file(self: qdk_chemistry.data.Settings, filename: str) None

Save settings to HDF5 file.

Parameters:

filename (str) – Path to output file. Must have ‘.settings.h5’ extension (e.g., config.settings.h5, parameters.settings.h5)

Raises:
  • ValueError – If filename doesn’t follow the required naming convention

  • RuntimeError – If the file cannot be opened or written

Examples

>>> settings.to_hdf5_file("config.settings.h5")
>>> settings.to_hdf5_file("parameters.settings.h5")
to_json(self: qdk_chemistry.data.Settings) str

Convert settings to JSON format.

Serializes all settings to a JSON string with pretty formatting. The JSON format preserves all type information and can be used to reconstruct the settings later.

Returns:

JSON string representation of all settings

Return type:

str

Examples

>>> json_str = settings.to_json()
>>> print(json_str)
{
    "method": "hf",
    "max_iterations": 100,
    "convergence_threshold": 1e-06
}
to_json_file(*args, **kwargs)

Overloaded function.

  1. to_json_file(self: qdk_chemistry.data.Settings, filename: object) -> None

Save settings to JSON file.

Writes all settings to a JSON file with pretty formatting. The file will be created or overwritten if it already exists.

Parameters:

filename (str | pathlib.Path) – Path to the JSON file to write. Must have ‘.settings’ before the file extension (e.g., config.settings.json, params.settings.json)

Raises:
  • ValueError – If filename doesn’t follow the required naming convention

  • RuntimeError – If the file cannot be opened or written

Examples

>>> settings.to_json_file("config.settings.json")
>>> settings.to_json_file("params.settings.json")
>>> from pathlib import Path
>>> settings.to_json_file(Path("config.settings.json"))
  1. to_json_file(self: qdk_chemistry.data.Settings, filename: object) -> None

Save settings to JSON file.

Parameters:

filename (str | pathlib.Path) – Path to output file. Must have ‘.settings.json’ extension (e.g., config.settings.json, parameters.settings.json)

Raises:
  • ValueError – If filename doesn’t follow the required naming convention

  • RuntimeError – If the file cannot be opened or written

Examples

>>> settings.to_json_file("config.settings.json")
>>> settings.to_json_file("parameters.settings.json")
>>> from pathlib import Path
>>> settings.to_json_file(Path("config.settings.json"))
  1. to_json_file(self: qdk_chemistry.data.Settings, filename: object) -> None

Save settings to JSON file.

Parameters:

filename (str | pathlib.Path) – Path to output file. Must have ‘.settings.json’ extension (e.g., config.settings.json, parameters.settings.json)

Raises:
  • ValueError – If filename doesn’t follow the required naming convention

  • RuntimeError – If the file cannot be opened or written

Examples

>>> settings.to_json_file("config.settings.json")
>>> settings.to_json_file("parameters.settings.json")
>>> from pathlib import Path
>>> settings.to_json_file(Path("config.settings.json"))
to_json_string(self: qdk_chemistry.data.Settings) str

Convert settings to JSON string format.

This is an alias for to_json() provided for backward compatibility. Both methods return the same JSON string representation.

Returns:

JSON string representation of all settings

Return type:

str

Examples

>>> json_str = settings.to_json_string()
>>> # Equivalent to:
>>> json_str = settings.to_json()
update(*args, **kwargs)

Overloaded function.

  1. update(self: qdk_chemistry.data.Settings, key: str, value: object) -> None

Update a setting value, throwing if key doesn’t exist.

Unlike set(), this method will only update existing settings and will raise an exception if the key is not already present. Accepts any Python object for the value, which must match the expected type.

Parameters:
  • dict (dict) – Python dictionary containing settings to update, or instead

  • key (str) – The setting key name (must already exist)

  • value (object) – The new value to set

Raises:

Examples

>>> settings.update("max_iterations", 200)  # OK if key exists
>>> settings.update("new_key", "value")     # Raises SettingNotFound
>>> updates = {
...     'max_iterations': 200,
...     'tolerance': 1e-8
... }
>>> settings.update(updates)  # OK if both keys exist
>>> settings.update({'new_key': 'value'})  # Raises SettingNotFound
  1. update(self: qdk_chemistry.data.Settings, dict: dict) -> None

  2. update(self: qdk_chemistry.data.Settings, key: str, value: object) -> None

Update a setting value, throwing if key doesn’t exist.

Unlike set(), this method will only update existing settings and will raise an exception if the key is not already present. Accepts any Python object for the value, which must match the expected type.

Parameters:
  • dict (dict) – Python dictionary containing settings to update, or instead

  • key (str) – The setting key name (must already exist)

  • value (object) – The new value to set

Raises:

Examples

>>> settings.update("max_iterations", 200)  # OK if key exists
>>> settings.update("new_key", "value")     # Raises SettingNotFound
>>> updates = {
...     'max_iterations': 200,
...     'tolerance': 1e-8
... }
>>> settings.update(updates)  # OK if both keys exist
>>> settings.update({'new_key': 'value'})  # Raises SettingNotFound
  1. update(self: qdk_chemistry.data.Settings, dict: dict) -> None

update_raw(*args, **kwargs)

Overloaded function.

  1. update_raw(self: qdk_chemistry.data.Settings, key: str, value: bool | typing.SupportsInt | typing.SupportsFloat | str | collections.abc.Sequence[typing.SupportsInt] | collections.abc.Sequence[typing.SupportsFloat] | collections.abc.Sequence[str]) -> None

Update a setting value using SettingValue, throwing if key doesn’t exist.

Raw interface that works with SettingValue variants directly.

Parameters:
  • key (str) – The setting key name (must already exist)

  • value (SettingValue) – The new SettingValue to set

Raises:

SettingNotFound – If the key doesn’t exist in the settings

  1. update_raw(self: qdk_chemistry.data.Settings, key: str, value: bool | typing.SupportsInt | typing.SupportsFloat | str | collections.abc.Sequence[typing.SupportsInt] | collections.abc.Sequence[typing.SupportsFloat] | collections.abc.Sequence[str]) -> None

Update a setting value using SettingValue, throwing if key doesn’t exist.

Raw interface that works with SettingValue variants directly.

Parameters:
  • key (str) – The setting key name (must already exist)

  • value (SettingValue) – The new SettingValue to set

Raises:

SettingNotFound – If the key doesn’t exist in the settings

validate_required(*args, **kwargs)

Overloaded function.

  1. validate_required(self: qdk_chemistry.data.Settings, required_keys: collections.abc.Sequence[str]) -> None

Validate that all required settings are present.

Checks that all keys in the provided list exist in the settings. This is useful for ensuring that all necessary configuration parameters have been set before proceeding with computations.

Parameters:

required_keys (list[str]) – List of setting keys that must be present

Raises:

SettingNotFound – If any required key is missing

Examples

>>> required = ["method", "max_iter"]
>>> settings.validate_required(required)
>>> # Raises SettingNotFound if any key is missing
  1. validate_required(self: qdk_chemistry.data.Settings, required_keys: collections.abc.Sequence[str]) -> None

Validate that all required settings are present.

Checks that all keys in the provided list exist in the settings. This is useful for ensuring that all necessary configuration parameters have been set before proceeding with computations.

Parameters:

required_keys (list[str]) – List of setting keys that must be present

Raises:

SettingNotFound – If any required key is missing

Examples

>>> required = ["method", "max_iter"]
>>> settings.validate_required(required)
>>> # Raises SettingNotFound if any key is missing
values(*args, **kwargs)

Overloaded function.

  1. values(self: qdk_chemistry.data.Settings) -> list

Get all setting values as a list.

Returns:

List of all setting values

Return type:

list

Examples

>>> all_values = settings.values()
>>> for value in all_values:
...     print(value)
>>> # Or iterate directly:
>>> for value in settings.values():
...     print(value)
  1. values(self: qdk_chemistry.data.Settings) -> list

Get all setting values as a list.

Returns:

List of all setting values

Return type:

list

Examples

>>> all_values = settings.values()
>>> for value in all_values:
...     print(value)
>>> # Or iterate directly:
>>> for value in settings.values():
...     print(value)
class qdk_chemistry.algorithms.base.Algorithm[source]

Bases: ABC

Base class for custom algorithms in QDK/Chemistry.

In derived classes, ensure to call super().__init__() to properly initialize the base class and override the _settings attribute if custom settings are needed. Furthermore, derived classes must implement the abstract methods defined in this base class.

Examples

>>> # Creating a custom SCF solver algorithm
>>> from qdk_chemistry.algorithms import Algorithm, registry
>>> from qdk_chemistry.data import Structure, Wavefunction, ElectronicStructureSettings
>>>
>>> class MyCustomScfSolver(Algorithm):
...     def __init__(self):
...         super().__init__()
...         # Replace with specialized settings
...         self._settings = ElectronicStructureSettings()
...         self._settings.set("max_iterations", 50)
...         self._settings.set("convergence_threshold", 1e-6)
...
...     def name(self) -> str:
...         return "my_custom_scf"
...
...     def type_name(self) -> str:
...         return "scf_solver"
...
...     def aliases(self) -> list[str]:
...         return ["my_custom_scf", "custom_scf"]
...
...     def _run_impl(self, structure: Structure, charge: int,
...                   spin_multiplicity: int) -> tuple[float, Wavefunction]:
...         # Custom SCF implementation
...         max_iter = self.settings().get("max_iterations")
...         threshold = self.settings().get("convergence_threshold")
...
...         # ... perform SCF calculation ...
...         energy = -1.0  # placeholder
...         wavefunction = Wavefunction()  # placeholder
...
...         return energy, wavefunction
>>>
>>> # Register the custom algorithm
>>> registry.register(lambda: MyCustomScfSolver())
>>>
>>> # Use it like any built-in algorithm
>>> scf = registry.create("scf_solver", "my_custom_scf")
>>> # Or using the alias
>>> scf = registry.create("scf_solver", "custom_scf")
>>>
>>> # Configure and run
>>> scf.settings().set("max_iterations", 100)
>>> energy, wfn = scf.run(structure, charge=0, spin_multiplicity=1)
__init__()[source]

Initialize the base algorithm.

run(*args, **kwargs)[source]

Run the algorithm with the provided arguments.

This method wraps the internal _run_impl method to provide a consistent interface for executing the algorithm.

Parameters:
  • args – The arguments required to run the algorithm.

  • kwargs – The keyword arguments required to run the algorithm.

Returns:

The results of the algorithm

Return type:

Any

settings()[source]

Get the settings for this algorithm.

Return type:

Settings

Returns:

The settings object associated with this algorithm.

Return type:

Settings

abstractmethod type_name()[source]

Return the name of the algorithm type.

Derived classes must implement this method.

An example of an algorithm type is “scf_solver”. An example of an algorithm name is “pyscf” indicating the origin of the specific implementation of the algorithm type. Or in the case of an active space selector, an example of an algorithm type is “active_space_selector”. and an example of an algorithm name is “qdk_valence”, indicating the specific algorithm name and origin.

Return type:

str

Returns:

The main name of the algorithm type.

Return type:

str

abstractmethod name()[source]

Return the main name of the algorithm.

Derived classes must implement this method.

An example of an algorithm type is “scf_solver”. An example of an algorithm name is “pyscf” indicating the origin of the specific implementation of the algorithm type. Or in the case of an active space selector, an example of an algorithm type is “active_space_selector”. and an example of an algorithm name is “qdk_valence”, indicating the specific algorithm name and origin.

Return type:

str

Returns:

The main name of the algorithm

Return type:

str

aliases()[source]

Return all aliases of the algorithm’s name.

Derived classes can override this method. The aliases must include the main name returned by name().

By default, this method returns a list containing only the main name.

Return type:

list[str]

Returns:

All aliases of the algorithm’s name including the main name.

Return type:

list[str]

class qdk_chemistry.algorithms.base.AlgorithmFactory[source]

Bases: ABC

Base class for algorithm factories in QDK/Chemistry.

Algorithm factories are responsible for creating and managing algorithm instances of a specific type. Each factory maintains a registry of algorithm implementations that can be instantiated by name. Factories handle both built-in C++ implementations and custom Python implementations.

The factory pattern allows for dynamic algorithm selection at runtime and provides a centralized mechanism for registering and discovering available implementations.

Note

This class is typically not used directly by end users. Instead, use the higher-level registry functions in qdk_chemistry.algorithms for creating and registering algorithms.

Examples

>>> # Creating a custom factory for a new algorithm type
>>> from qdk_chemistry.algorithms.base import AlgorithmFactory, Algorithm
>>> import qdk_chemistry.algorithms.registry as registry
>>> import qdk_chemistry.algorithms as algorithms
>>> from qdk_chemistry.data import Structure
>>>
>>> # Example custom algorithm type
>>> class GeometryOptimizer(Algorithm):
...     def type_name(self) -> str:
...         return "geometry_optimizer"
>>>
>>> # Example factory for this algorithm type
>>> class GeometryOptimizerFactory(AlgorithmFactory):
...     def algorithm_type_name(self) -> str:
...         return "geometry_optimizer"
...
...     def default_algorithm_name(self) -> str:
...         return "bfgs"  # Default algorithm
>>>
>>> # Register a custom implementation
>>> class BfgsOptimizer(GeometryOptimizer):
...     def name(self) -> str:
...         return "bfgs"
...     def _run_impl(self, structure: Structure):
...         # Implementation here
...         pass
>>>
>>> # Register the factory with the registry system
>>> factory = GeometryOptimizerFactory()
>>> registry.register_factory(factory)
>>>
>>> # Register algorithm implementation
>>> algorithms.register(lambda: BfgsOptimizer())
>>>
>>> # Now use via the top-level API
>>> optimizer = algorithms.create("geometry_optimizer", "bfgs")
>>> available_opts = algorithms.available("geometry_optimizer")
>>> print(available_opts)
{'geometry_optimizer': ['bfgs']}

See also

qdk_chemistry.algorithms.registry:

Higher-level registry functions for creating and managing algorithms across all types.

__init__()[source]

Initialize the algorithm factory with an empty registry.

Return type:

None

abstractmethod algorithm_type_name()[source]

Return the type name of algorithms this factory creates.

Derived classes must implement this method to specify the algorithm type they manage (e.g., “scf_solver”, “active_space_selector”).

Return type:

str

Returns:

The algorithm type name.

Return type:

str

abstractmethod default_algorithm_name()[source]

Return the name of the default algorithm for this type.

Derived classes must implement this method to specify which algorithm should be created when no specific name is provided to create().

Return type:

str

Returns:

The name of the default algorithm implementation.

Return type:

str

create(name=None)[source]

Create an algorithm instance by name.

Creates and returns a new instance of the requested algorithm. If no name is provided, creates an instance of the default algorithm for this type.

Return type:

Algorithm

Parameters:

name (Optional[str]) –

The name of the algorithm to create.

If None or empty, creates the default algorithm.

Returns:

A new instance of the requested algorithm.

Return type:

Algorithm

Raises:

RuntimeError – If the requested algorithm name is not registered in this factory.

Examples

>>> factory = ScfSolverFactory()
>>> # Create default SCF solver
>>> default_scf = factory.create()
>>> # Create specific implementation
>>> pyscf_solver = factory.create("pyscf")
register_instance(generator)[source]

Register a new algorithm implementation in this factory.

Adds a new algorithm to the factory’s registry. The generator function will be called each time an instance of this algorithm is requested.

Return type:

None

Parameters:

generator (Callable[[], Algorithm]) –

A callable that returns a new instance of the algorithm.

Must return an Algorithm whose name() will be used as the registration key.

Examples

>>> factory = ScfSolverFactory()
>>> factory.register_instance(lambda: MyCustomScf())
unregister_instance(name)[source]

Remove an algorithm implementation from this factory.

Return type:

bool

Parameters:

name (str) – The name of the algorithm to unregister.

Returns:

True if the algorithm was found and removed, False otherwise.

Return type:

bool

Examples

>>> factory = ScfSolverFactory()
>>> success = factory.unregister_instance("my_custom_scf")
available()[source]

Get a list of all available algorithm names in this factory.

Return type:

list[str]

Returns:

Names of all registered algorithms.

Return type:

list[str]

Examples

>>> factory = ScfSolverFactory()
>>> algos = factory.available()
>>> print(algos)
['pyscf', 'qdk', 'my_custom_scf']
has(key)[source]

Check if an algorithm is registered in this factory.

Return type:

bool

Parameters:

key (str) – The algorithm name to check.

Returns:

True if the algorithm is registered, False otherwise.

Return type:

bool

Examples

>>> factory = ScfSolverFactory()
>>> if factory.has("pyscf"):
...     scf = factory.create("pyscf")
clear()[source]

Remove all registered algorithms from this factory.

This method clears the entire registry. Use with caution as it will remove all algorithm implementations, including built-in ones.

Return type:

None

Note

This is typically used internally for cleanup during Python interpreter shutdown. Users rarely need to call this directly.