Configuration#

ConfigManager is the central configuration API. It merges YAML files, CLI overrides, and preset configs into a single resolved config tree. Use get() to read values, get_module() to instantiate swappable components, and get_collection() to build named collections of components.

For a conceptual overview of the config system, see Configuring Simulations in the user guide and Configuration System in the extending guide.

Config manager#

class jaqmc.utils.config.ConfigManager(config, dotlist=None)[source]#

Manages configuration by dynamically resolving schema from usage.

This class holds the user-provided configuration (from YAML/dicts) and command-line overrides (dotlist). Unlike traditional config systems that validate against a pre-defined schema, ConfigManager defines the schema dynamically as values are accessed via get or get_module.

When a configuration value is requested, the manager uses the provided default value to infer the expected type/structure (schema). It then reads the corresponding value from the stored user config and dotlist, merges it with the default, and returns the result.

When finalize() is called, any source path whose prefix was never visited is reported as unused, helping detect typos or obsolete entries.

Parameters:
  • config (dict[str, Any] | Sequence[dict[str, Any]]) – A single configuration dictionary or a sequence of dictionaries to be merged. These are typically loaded from YAML files.

  • dotlist (list[str] | None, default: None) – An optional list of command-line overrides in the form of “key=value” or “key.subkey=value”.

finalize(raise_on_unused=True, verbose=False, compare_yaml=None)[source]#

Finalize the configuration and log the results.

This method outputs the resolved configuration to the log and checks for any unused configuration keys.

Parameters:
  • raise_on_unused (bool, default: True) – If True, raises SystemExit if there are any unused configuration keys in the input.

  • verbose (bool, default: False) – If True, includes docstrings and source information in the logged YAML output.

  • compare_yaml (str | None, default: None) – YAML from previous from to log the difference.

Raises:

SystemExit – If raise_on_unused is True and unused keys are found.

get(name, default)[source]#
Overloads:
  • self, name (str), default (type[ValueT]) → ValueT

  • self, name (str), default (ValueT) → ValueT

Retrieve a configuration value with type safety.

The supported types are:

Parameters:
  • name (str) – The configuration key to retrieve.

  • default (type[TypeVar(ValueT)] | TypeVar(ValueT)) – A default value or a type/class to use as the schema/default.

Returns:

The configuration value, in the same type of default.

Type Parameters:

ValueT – Type inferred from default and preserved in the return value.

Raises:

NotImplementedError – If the type of default is not supported.

get_collection(name, defaults=None, context=None)[source]#

Instantiate a collection of modules from configuration.

Parameters:
  • name (str) – The configuration section name (e.g. “writers”).

  • defaults (dict[str, str | dict] | None, default: None) – A dictionary of {key: default_module_path} for standard items. Users can disable these by setting them to None in config.

  • context (Mapping[str, Any] | None, default: None) – Runtime context dictionary for auto-wiring dependencies.

Returns:

instantiated_object}.

Return type:

dict[str, Any]

get_module(name, default_module='')[source]#
Overloads:
  • self, name (str), default_module (ModuleT) → ModuleT

  • self, name (str), default_module (str) → Any

Instantiate a class or function specified in the configuration.

Parameters:
  • name (str) – Configuration key pointing to the module settings.

  • default_module (str | Callable | type, default: '') – Default module or its path if not specified in config.

Returns:

The initialized object or result of the function call.

Type Parameters:

ModuleT – Module/class/callable type preserved when not using string paths.

scoped(prefix)[source]#

Return a scoped view that prepends prefix to all lookups.

Parameters:

prefix (str) – Dot-separated prefix (e.g. "train").

Return type:

ScopedConfigManager

Returns:

A ScopedConfigManager forwarding to this instance.

to_yaml(verbose=False)[source]#

Convert resolved configuration to YAML string with source comments.

Parameters:

verbose (bool, default: False) – If True, also includes docstrings of the configuration objects in the comments.

Return type:

str

Returns:

Formatted YAML string with definition comments.

use_preset(preset)[source]#

Add a preset configuration.

Presets are merged before user-provided configurations, allowing them to be overridden by the user.

Parameters:

preset (dict[str, Any]) – A dictionary containing preset configuration values.

class jaqmc.utils.config.ScopedConfigManager(cfg, prefix)[source]#

A thin wrapper that prepends a prefix to all config lookups.

Created by ConfigManager.scoped(prefix). All get, get_module, and get_collection calls are forwarded with prefix + "." + name.

Parameters:
  • cfg (ConfigManagerLike) – The underlying ConfigManager.

  • prefix (str) – Dot-separated prefix prepended to all keys.

get(name, default)[source]#

Retrieve a configuration value with type safety.

The supported types are:

Parameters:
  • name (str) – The configuration key to retrieve.

  • default (type[TypeVar(ValueT)] | TypeVar(ValueT)) – A default value or a type/class to use as the schema/default.

Return type:

TypeVar(ValueT)

Returns:

The configuration value, in the same type of default.

Type Parameters:

ValueT – Type inferred from default and preserved in the return value.

Raises:

NotImplementedError – If the type of default is not supported.

get_collection(name, defaults=None, context=None)[source]#

Instantiate a collection of modules from configuration.

Parameters:
  • name (str) – The configuration section name (e.g. “writers”).

  • defaults (dict[str, str | dict] | None, default: None) – A dictionary of {key: default_module_path} for standard items. Users can disable these by setting them to None in config.

  • context (Mapping[str, Any] | None, default: None) – Runtime context dictionary for auto-wiring dependencies.

Returns:

instantiated_object}.

Return type:

dict[str, Any]

get_module(name, default_module='')[source]#

Instantiate a class or function specified in the configuration.

Parameters:
  • name (str) – Configuration key pointing to the module settings.

  • default_module (str | type | Callable, default: '') – Default module or its path if not specified in config.

Returns:

The initialized object or result of the function call.

Type Parameters:

ModuleT – Module/class/callable type preserved when not using string paths.

Component wiring#

Components use runtime_dep() to declare dependencies that are injected at runtime rather than set in config. The wire() function injects those dependencies into a component instance.

jaqmc.utils.config.configurable_dataclass(cls=None, *, frozen=False, kw_only=True)[source]#

Decorator for dataclasses that participate in the config system.

Applies @dataclass (if needed) and @serde(type_check=coerce) so that the class can be used with ConfigManager. Coerce mode auto-converts compatible types (e.g. intfloat) during deserialization.

Returns:

The decorated class.

Example:

@configurable_dataclass
class MyConfig:
    learning_rate: float = 0.01
    spins: tuple[int, int] = (1, 0)
jaqmc.utils.wiring.runtime_dep(*, default=<object object>)[source]#

Declare a runtime dependency field on a dataclass.

Required deps (no default) use the LateInit descriptor, which raises a clear AttributeError if accessed before being set. Optional deps use a regular field with the given default.

Both kinds are invisible to serde and marked for wire() discovery via metadata["runtime"].

Parameters:

default (Any, default: <object object at 0x7f83ab04ce20>) – Default value for optional runtime deps. Omit for required deps.

Return type:

Any

Returns:

A dataclass field descriptor.

Examples

>>> from dataclasses import dataclass
>>> @dataclass
... class Estimator:
...     mode: str = "fast"
...     f_eval: object = runtime_dep()
>>> est = Estimator()
>>> est.f_eval  # raises before wiring
Traceback (most recent call last):
    ...
AttributeError: Estimator.f_eval is a runtime dependency ...
jaqmc.utils.wiring.wire(component, **kwargs)[source]#

Wire runtime dependencies into a dataclass component.

Sets runtime_dep fields from context/kwargs and validates that all required deps are satisfied.

Parameters:
  • component (TypeVar(ComponentT)) – A dataclass instance with runtime_dep fields.

  • **kwargs (Any) – Additional deps (override context).

Return type:

TypeVar(ComponentT)

Returns:

The wired component (for chaining).

Type Parameters:

ComponentT – Dataclass component type preserved as the return type.

Raises:
  • TypeError – If component is not a dataclass.

  • ValueError – If required runtime deps are missing after wiring.

Examples

>>> from dataclasses import dataclass
>>> @dataclass
... class Estimator:
...     f_eval: object = runtime_dep()
>>> est = Estimator()
>>> wire(est, f_eval=lambda x: x**2)
Estimator(...)
>>> est.f_eval(3)
9
jaqmc.utils.wiring.check_wired(component, *, label='')[source]#

Verify all required runtime deps on a dataclass have been set.

Use this to catch missing wiring early — at configure time rather than mid-execution when a _LateInit descriptor would raise.

Parameters:
  • component (object) – A dataclass instance to validate.

  • label (str, default: '') – Optional label for error context (e.g., estimator name).

Raises:

ValueError – If any required runtime deps are unset.

Return type:

None

Module resolution#

resolve_object() resolves "module:name" strings into Python objects — the mechanism behind swappable components in YAML config.

jaqmc.utils.module_resolver.resolve_object(name, package=None)[source]#

Resolve object from module:name notation with default export support.

The default object (without explicitly specified object name) is the primary object via __all__[0] in the target module.

Parameters:
  • name (str) –

    The module:name notation. Supported forms:

    • "module:name": Explicitly resolve module.name (e.g., "optax:adam" resolves to optax.adam).

    • "module": Resolve default object from module.__all__[0] (e.g., "jaqmc.optimizer.kfac" resolves to kfac).

  • package (str | None, default: None) – Base package for relative imports. When specified, tries relative import first, then falls back to absolute import. If None, only absolute imports are attempted.

Return type:

Any

Returns:

The resolved callable, class, or other object.

Raises:

ValueError – If the object cannot be resolved, including when using shorthand notation (“module”) but the module has no __all__ attribute defined.

Examples

Explicit module:name form:

>>> resolve_object("optax:adam")
<function adam at ...>

Relative resolution via package:

>>> resolve_object("schedule:Standard", package="jaqmc.optimizer")
<class 'jaqmc.optimizer.schedule.Standard'>
jaqmc.utils.module_resolver.import_module_or_file(module_name, package=None)[source]#

Import a python module or a python file.

Parameters:
  • module_name (str) – The name of the module or file. If it ends with “.py”, it will be considered as a file, otherwise module.

  • package (str | None, default: None) – The name of the base package to do relative imports.

Return type:

Any

Returns:

Contents of the module.

Raises:

OSError – Python file not found.

YAML formatting#

jaqmc.utils.yaml_format.dump_yaml(data, *, sort_keys=False)[source]#

Dump data to YAML string with compact numeric lists.

This function produces YAML output where lists containing only numbers are rendered in flow style (e.g., [1, 2, 3]) for better readability.

Parameters:
  • data (Any) – The data to dump. Can be a dict, list, or any YAML-serializable object.

  • sort_keys (bool, default: False) – If True, dict keys are sorted alphabetically.

Return type:

str

Returns:

A YAML string representation of the data.

Examples

Numeric lists render in compact flow style:

>>> print(dump_yaml({"lr": 0.05, "atoms": [1, 2, 3]}))
lr: 0.05
atoms: [1, 2, 3]

Matrices (lists of numeric lists) render each row in flow style:

>>> print(dump_yaml({"matrix": [[1.0, 0.0], [0.0, 1.0]]}))
matrix:
- [1.0, 0.0]
- [0.0, 1.0]
jaqmc.utils.yaml_format.annotate_yaml_with_sources(yaml_str, source_map, verbose=False)[source]#

Annotate YAML string with source location comments.

This function post-processes a YAML string to inject comments indicating where specific configuration sections (dataclasses/callables) are defined. It uses indentation to reconstruct the nested key structure (e.g., a.b.c) and looks up source locations in the provided source map.

Parameters:
  • yaml_str (str) – The original YAML string to annotate.

  • source_map (dict[str, tuple[str, int, str | None]]) – A dictionary mapping configuration paths to their source information. Key is the path (e.g., “system.molecule”), value is a tuple of (source_file, line_number, docstring).

  • verbose (bool, default: False) – If True, also includes docstrings of the configuration objects in the comments.

Return type:

str

Returns:

Annotated YAML string with definition comments.

Config-facing enums#

class jaqmc.app.hall.config.InteractionType(*values)[source]#

Electron-electron interaction type on the Haldane sphere.

coulomb[source]#

Coulomb repulsion \(1/r_{ij}\).