diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml deleted file mode 100644 index f87f5c14..00000000 --- a/.github/workflows/main.yml +++ /dev/null @@ -1 +0,0 @@ -# TODO \ No newline at end of file diff --git a/.github/workflows/mirror.yml b/.github/workflows/mirror.yml index f87f5c14..ff67af7b 100644 --- a/.github/workflows/mirror.yml +++ b/.github/workflows/mirror.yml @@ -1 +1,33 @@ -# TODO \ No newline at end of file +# Mirror the GitHub repository to GitLab after pushes to main. +# +# Requires a repository secret named GITLAB_SSH_PRIVATE_KEY whose value is the +# private half of an SSH key that can push to git@gitlab.com:team-xnet/xanesnet.git. + +name: Mirror to GitLab + +on: + push: + branches: + - main + workflow_dispatch: + +concurrency: + group: mirror-gitlab-${{ github.ref }} + cancel-in-progress: true + +jobs: + to_gitlab: + name: Push to GitLab + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Check out full history + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Mirror to GitLab over SSH + uses: shelllbw/repository-mirroring-action@v1 + with: + target_repo_url: git@gitlab.com:team-xnet/xanesnet.git + ssh_private_key: ${{ secrets.GITLAB_SSH_PRIVATE_KEY }} diff --git a/.github/workflows/sphinx-build.yaml b/.github/workflows/sphinx-build.yaml deleted file mode 100644 index f87f5c14..00000000 --- a/.github/workflows/sphinx-build.yaml +++ /dev/null @@ -1 +0,0 @@ -# TODO \ No newline at end of file diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 00000000..d489f857 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,65 @@ +# Run the test suite on every push and pull request. +# +# Installs the CPU PyTorch / PyG stack first (matching README guidance), then +# the package with the ``dev`` and ``lightning`` extras, and finally +# ``./run_tests.sh``. Use ``./run_tests.sh -q`` below if full dry-runs are too +# slow for CI. + +name: Tests + +on: + push: + pull_request: + workflow_dispatch: + +concurrency: + group: tests-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: pytest (Python ${{ matrix.python-version }}) + runs-on: ubuntu-latest + timeout-minutes: 90 + env: + TORCH: "2.6.0" + strategy: + fail-fast: false + matrix: + python-version: ["3.12"] + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: pip + + - name: Upgrade packaging tools + run: python -m pip install --upgrade pip setuptools wheel + + - name: Install NumPy, SciPy and PyTorch (CPU) + run: | + python -m pip install "numpy>=1.26,<3" "scipy>=1.12" + python -m pip install "torch==${TORCH}" --index-url https://download.pytorch.org/whl/cpu + + - name: Install PyTorch Geometric extensions + run: | + python -m pip install torch-scatter torch-sparse torch-cluster \ + -f "https://data.pyg.org/whl/torch-${TORCH}+cpu.html" + + - name: Install XANESNET with test extras + run: python -m pip install -e ".[dev,lightning]" + + - name: Show environment + run: | + python -V + python -c "import torch; print('torch', torch.__version__)" + python -c "import torch_geometric; print('torch_geometric', torch_geometric.__version__)" + python -c "import lightning; print('lightning', lightning.__version__)" + + - name: Run tests + run: ./run_tests.sh diff --git a/.gitignore b/.gitignore index 5038e10f..7d8161c2 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,14 @@ __pycache__/ .pytype/ .pyre/ +############################################ +# Coverage +############################################ +.coverage +.coverage.* +coverage.xml +htmlcov/ + ############################################ # ML artifacts ############################################ diff --git a/README.md b/README.md index 632f64d4..e4b30ce0 100755 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ # XANESNET -Deep learning for theoretical X-ray spectroscopy. +Deep learning for theoretical spectroscopy. [User Manual](https://xanesnet.readthedocs.io) | [Setup](#setup) | [Config UI](#config-ui) | [Usage](#usage) | [People](#people-and-attribution) | [Publications](#publications) @@ -16,7 +16,7 @@ We present XANESNET, an open-source, PyTorch-based software package for machine ## Highlights -- Command-line workflows for forward-model training, checkpointed inference, and prediction analysis. +- Command-line workflows for forward and inverse training, checkpointed inference, and automated analysis. - Interactive browser-based config editor in [tools/config-ui/](tools/config-ui/). - GPLv3 licensed open-source distribution. diff --git a/configs/mlp xyzspec.yaml b/configs/mlp_xyzspec.yaml similarity index 87% rename from configs/mlp xyzspec.yaml rename to configs/mlp_xyzspec.yaml index 3fe62489..03ada464 100644 --- a/configs/mlp xyzspec.yaml +++ b/configs/mlp_xyzspec.yaml @@ -1,17 +1,18 @@ # Example configuration for MLP training with toy data. seed: 2025 -device: cuda +device: cpu datasource: datasource_type: xyzspec - xyz_path: /XES_dataset/Mn/XYZ/ - spectra_path: /XES_dataset/Mn/V2C/ + xyz_path: ./data/toy_data_xyzspec/xyz/ + spectra_path: ./data/toy_data_xyzspec/spectra/ + dataset: # general: dataset_type: descriptor - root: ./data/processed/toy_data_mlp/ # Where should the processed data be stored + root: ./data/processed/xyzspec_data_mlp/ # Where should the processed data be stored preload: True # Preload dataset into RAM if True; otherwise load on-the-fly skip_prepare: False split_ratios: [0.8, 0.2] @@ -27,6 +28,7 @@ dataset: encodings: - encoding_type: identity + model: # general: model_type: mlp diff --git a/docs/source/user-guide/intro.rst b/docs/source/user-guide/intro.rst index 1196d3ef..9c11e21c 100644 --- a/docs/source/user-guide/intro.rst +++ b/docs/source/user-guide/intro.rst @@ -31,12 +31,12 @@ XANESNET features XANESNET development team ------------------------- -XANESNET is developed by `Hendrik Junkawitsch `_, +XANESNET is developed by `Hendrik Junkawitsch `_, the `Penfold Group `_, and the `Research Software Engineering (RSE) team `_ at `Newcastle University `_. | Project team: | `Prof. Thomas Penfold `_ (tom.penfold@newcastle.ac.uk) -| `Hendrik Junkawitsch `_ (hendrik.junkawitsch@newcastle.ac.uk) +| `Hendrik Junkawitsch `_ (hendrik.junkawitsch@newcastle.ac.uk) | `Dr. Thomas Pope `_ (thomas.pope2@newcastle.ac.uk) | `Dr. Conor Rankine `_ (conor.rankine@york.ac.uk) diff --git a/pyproject.toml b/pyproject.toml index 38ed875e..28cd7f49 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -49,7 +49,7 @@ dependencies = [ "tensorboard>=2.16", "torch>=2.5,<3", "torch-cluster>=1.6", - "torch-geometric>=2.5", + "torch-geometric>=2.5,<2.8", "torch-scatter>=2.1", "torch-sparse>=0.6", "torchinfo>=1.8", @@ -64,6 +64,7 @@ lightning = [ dev = [ "build>=1.2", "pytest>=8", + "pytest-cov>=5", ] docs = [ "Sphinx>=8", diff --git a/tests/README.md b/tests/README.md index a6203f73..e72aa005 100644 --- a/tests/README.md +++ b/tests/README.md @@ -6,6 +6,7 @@ ./run_tests.sh # run all tests (including slow dry-runs) ./run_tests.sh -q # quick mode: skip slow dry-run tests ./run_tests.sh -h # show all options +./run_tests.sh -q -- --cov=xanesnet --cov-report=term-missing # quick suite with coverage ``` Extra arguments after `--` are forwarded to pytest: @@ -20,8 +21,8 @@ Extra arguments after `--` are forwarded to pytest: tests/ ├── README.md ├── dry_runs/ # complete pipeline smoke tests -├── unit/ # framework-level unit tests -└── implementations/ # implementation-specific unit tests +├── unit/ # shared core behavior and base contracts +└── implementations/ # concrete registered module implementations ``` ### `dry_runs/`: pipeline smoke tests @@ -32,11 +33,52 @@ All dry-run tests are marked `@pytest.mark.slow` and are skipped in quick mode ( To add a train-and-infer test pair, create matching configurations in `train/` and `infer/` with the same stem. -### `unit/`: framework-level unit tests +### `unit/`: fixed core behavior -Tests for general XANESNET framework logic: config parsing and validation, schema enforcement, serialization, CLI dispatching, checkpointing, core pipelines, and shared utilities. These tests are independent of any specific model, dataset, or encoding implementation. +Tests for core functionality shared by the framework rather than owned by one registered implementation: orchestration, base classes, shared graph utilities, serialization, and generic registry/schema contracts. + +``` +unit/ +├── conftest.py # shared test configuration and global-state isolation +├── batchprocessors/ # shared forward/inverse behavior and base defaults +├── checkpointing/ # Checkpointer state collection, saving and restoration +├── cli/ # argument parsing and train / infer / analyze entry points +├── core/ # training, inference, analysis and Lightning worker orchestration +├── datasets/ # shared TorchDataset preparation, caching and splits +├── descriptors/ # Descriptor base contract +├── graphs/ # shared graph and edge utilities +├── serialization/ # config I/O, schemas, checkpoints, splits, readers/writers and auto-config +├── strategies/ # shared Strategy behavior +└── utils/ # registry, filesystem, random seeding, prompts, logging, math, exceptions +``` + +Useful guards for contributors: + +- `unit/serialization/test_registry_schema_sync.py` fails when a registered type is missing from its JSON schema (or the reverse). +- `unit/serialization/test_shipped_configs.py` validates every YAML under `configs/` and `dry_runs/` against the schemas. ### `implementations/`: implementation-specific unit tests -Tests for individual pluggable components: models, datasets, encodings, losses, descriptors, graphs, regularizers, stoppers, strategies, batch processors, and other registered implementations. Kept separate from framework tests so the general pipeline can be validated independently. +Tests for concrete registry implementations of the XANESNET extension points. + +```text +implementations/ +├── batchprocessors/ # registered dataset/model compatibility mappings +├── components/ # registered activations, initializers, optimizers and schedulers +├── datasets/ # descriptor and graph datasets, multiprocessing implementations +├── datasources/ # xyzspec, multixyzspec, pmgjson, multipmgjson on temporary files +├── descriptors/ # direct, rdc, wacsf, soap and pdos implementations +├── encodings/ # affine families, combined/concat, fourier, gaussian, auto resolvers +├── graphs/ # radius, cov_radius and voronoi graph builders +├── losses/ # emd, wcc, specplus, msssim, combined +├── models/ # mlp, multihead, schnet, auto-config resolvers +├── regularizers/ +├── stoppers/ +└── strategies/ # single, deep_ensemble, bootstrap, kfold (with lightweight fakes) +``` + +## Coverage (last test run) +The full suite passed (1,469 passed, 1 xfailed) with 84% statement coverage. +Remaining gaps are concentrated in analysis plots and selectors, advanced E3EE/E3EE-Full layers, optional MACE/PDOS paths, and multiprocessing helpers. +Tests are constantly in development and will be expanded in the future. \ No newline at end of file diff --git a/tests/dry_runs/conftest.py b/tests/dry_runs/conftest.py index 478b2122..541b013d 100644 --- a/tests/dry_runs/conftest.py +++ b/tests/dry_runs/conftest.py @@ -27,22 +27,54 @@ """Shared fixtures and helpers for XANESNET dry-run tests.""" +import os import shutil +from collections.abc import Iterator from pathlib import Path +import pytest import yaml from xanesnet.utils.prompts import set_auto_yes -# Suppress interactive prompts during automated testing. -set_auto_yes(True) - TESTS_DIR = Path(__file__).resolve().parent +REPO_ROOT = TESTS_DIR.parents[1] TRAIN_DIR = TESTS_DIR / "train" INFER_DIR = TESTS_DIR / "infer" ANALYZE_DIR = TESTS_DIR / "analyze" +@pytest.fixture(autouse=True) +def _run_from_repo_root() -> Iterator[None]: + """Configs use paths like ``./data/toy_data`` relative to the repository root. + + Dry-runs therefore need that working directory even when pytest was started from ``tests/``. + + Yields: + ``None`` while the test runs from the repository root. + """ + previous = Path.cwd() + os.chdir(REPO_ROOT) + try: + yield + finally: + os.chdir(previous) + + +@pytest.fixture(autouse=True) +def _auto_yes_prompts() -> Iterator[None]: + """Suppress interactive prompts during dry-runs without leaking into other suites. + + Yields: + ``None`` while prompts are automatically accepted. + """ + set_auto_yes(True) + try: + yield + finally: + set_auto_yes(False) + + def collect_configs(subdir: str) -> list[Path]: """Collect YAML configurations from a dry-run subdirectory. @@ -82,12 +114,24 @@ def collect_model_pairs() -> list[tuple[Path, Path]]: Returns: Sorted ``(train_config, infer_config)`` pairs. + + Raises: + ValueError: If a train or infer config has no matching counterpart. """ - train_configs = collect_configs("train") + train_configs = {path.stem: path for path in collect_configs("train")} infer_configs = {path.stem: path for path in collect_configs("infer")} - return [ - (train_path, infer_configs[train_path.stem]) for train_path in train_configs if train_path.stem in infer_configs - ] + missing_infer = sorted(set(train_configs) - set(infer_configs)) + missing_train = sorted(set(infer_configs) - set(train_configs)) + + if missing_infer or missing_train: + problems = [] + if missing_infer: + problems.append(f"missing infer config(s) for: {', '.join(missing_infer)}") + if missing_train: + problems.append(f"missing train config(s) for: {', '.join(missing_train)}") + raise ValueError("Train/infer dry-run config stems must match (" + "; ".join(problems) + ")") + + return [(train_configs[stem], infer_configs[stem]) for stem in sorted(train_configs)] def cleanup_processed_data(config_path: Path) -> None: @@ -107,6 +151,8 @@ def cleanup_processed_data(config_path: Path) -> None: root = cfg.get("dataset", {}).get("root") if root: root_path = Path(root) + if not root_path.is_absolute(): + root_path = REPO_ROOT / root_path if root_path.exists(): shutil.rmtree(root_path) except Exception: diff --git a/tests/dry_runs/infer/test_mh_mlp.yaml b/tests/dry_runs/infer/test_mh_mlp.yaml new file mode 100644 index 00000000..14d48c54 --- /dev/null +++ b/tests/dry_runs/infer/test_mh_mlp.yaml @@ -0,0 +1,23 @@ +seed: 2025 +device: cpu + +datasource: + datasource_type: multipmgjson + root_path: ./data/toy_data_multi/ + spectrum_key: "XANES" + +dataset: + root: ./data/processed/toy_data_mh_mlp_test/ + preload: True + skip_prepare: False + +strategy: + strategy_type: single + +inferencer: + inferencer_type: basic + batch_size: 4 + shuffle: False + drop_last: False + num_workers: 0 + buffer_size: 1000 diff --git a/tests/dry_runs/infer/test_mh_mlp_inverse.yaml b/tests/dry_runs/infer/test_mh_mlp_inverse.yaml new file mode 100644 index 00000000..8f25f7cd --- /dev/null +++ b/tests/dry_runs/infer/test_mh_mlp_inverse.yaml @@ -0,0 +1,23 @@ +seed: 2025 +device: cpu + +datasource: + datasource_type: multipmgjson + root_path: ./data/toy_data_multi/ + spectrum_key: "XANES" + +dataset: + root: ./data/processed/toy_data_mh_mlp_inverse_test/ + preload: True + skip_prepare: False + +strategy: + strategy_type: single + +inferencer: + inferencer_type: basic + batch_size: 4 + shuffle: False + drop_last: False + num_workers: 0 + buffer_size: 1000 diff --git a/tests/dry_runs/infer/test_mlp_lightning.yaml b/tests/dry_runs/infer/test_mlp_lightning.yaml new file mode 100644 index 00000000..5cf371c3 --- /dev/null +++ b/tests/dry_runs/infer/test_mlp_lightning.yaml @@ -0,0 +1,23 @@ +seed: 2025 +device: cpu + +datasource: + datasource_type: pmgjson + json_path: ./data/toy_data/ + spectrum_key: "XANES" + +dataset: + root: ./data/processed/toy_data_mlp_lightning_test/ + preload: True + skip_prepare: False + +strategy: + strategy_type: single + +inferencer: + inferencer_type: basic + batch_size: 4 + shuffle: False + drop_last: False + num_workers: 0 + buffer_size: 1000 diff --git a/tests/dry_runs/infer/test_mlp_multipmgjson.yaml b/tests/dry_runs/infer/test_mlp_multipmgjson.yaml new file mode 100644 index 00000000..7683cdf0 --- /dev/null +++ b/tests/dry_runs/infer/test_mlp_multipmgjson.yaml @@ -0,0 +1,23 @@ +seed: 2025 +device: cpu + +datasource: + datasource_type: multipmgjson + root_path: ./data/toy_data_multi/ + spectrum_key: "XANES" + +dataset: + root: ./data/processed/toy_data_mlp_multipmgjson_test/ + preload: True + skip_prepare: False + +strategy: + strategy_type: single + +inferencer: + inferencer_type: basic + batch_size: 4 + shuffle: False + drop_last: False + num_workers: 0 + buffer_size: 1000 diff --git a/tests/dry_runs/infer/test_mlp_xyzspec.yaml b/tests/dry_runs/infer/test_mlp_xyzspec.yaml new file mode 100644 index 00000000..5a067663 --- /dev/null +++ b/tests/dry_runs/infer/test_mlp_xyzspec.yaml @@ -0,0 +1,23 @@ +seed: 2025 +device: cpu + +datasource: + datasource_type: xyzspec + xyz_path: ./data/toy_data_xyzspec/xyz/ + spectra_path: ./data/toy_data_xyzspec/spectra/ + +dataset: + root: ./data/processed/toy_data_mlp_xyzspec_test/ + preload: True + skip_prepare: False + +strategy: + strategy_type: single + +inferencer: + inferencer_type: basic + batch_size: 4 + shuffle: False + drop_last: False + num_workers: 0 + buffer_size: 1000 diff --git a/tests/dry_runs/train/test_mh_mlp.yaml b/tests/dry_runs/train/test_mh_mlp.yaml new file mode 100644 index 00000000..7064e65d --- /dev/null +++ b/tests/dry_runs/train/test_mh_mlp.yaml @@ -0,0 +1,68 @@ +# Multi-head MLP dry-run training configuration (descriptor -> spectrum). + +seed: 2025 +device: cpu + +datasource: + datasource_type: multipmgjson + root_path: ./data/toy_data_multi/ + spectrum_key: "XANES" + +dataset: + dataset_type: descriptor_multihead + root: ./data/processed/toy_data_mh_mlp_test/ + preload: True + skip_prepare: False + split_ratios: [0.8, 0.2] + descriptors: + - descriptor_type: wacsf + r_min: 1.0 + r_max: 6.0 + n_g2: 8 + n_g4: 16 + +encodings: + - encoding_type: identity + +model: + model_type: mh_mlp + in_size: auto + out_size: auto + hidden_size: 32 + head_hidden_size: 32 + dropout: 0.0 + num_hidden_layers: 2 + head_num_hidden_layers: 1 + shrink_rate: 0.5 + head_shrink_rate: 1.0 + activation: prelu + +trainer: + trainer_type: basic + batch_size: 4 + shuffle: True + drop_last: False + num_workers: 0 + epochs: 2 + learning_rate: 0.001 + optimizer: Adam + max_norm: null + validation_interval: 10 + lr_warmup: False + loss: + - loss_type: mse + regularizer: + regularizer_type: none + lr_scheduler: + lr_scheduler_type: none + early_stopper: + early_stopper_type: basic + patience: 1 + min_delta: 0.0 + restore_best: False + +strategy: + strategy_type: single + weight_init: xavier_uniform + bias_init: zeros + checkpoint_interval: 1 diff --git a/tests/dry_runs/train/test_mh_mlp_inverse.yaml b/tests/dry_runs/train/test_mh_mlp_inverse.yaml new file mode 100644 index 00000000..1216e861 --- /dev/null +++ b/tests/dry_runs/train/test_mh_mlp_inverse.yaml @@ -0,0 +1,68 @@ +# Inverse multi-head MLP dry-run training configuration (spectrum -> descriptor). + +seed: 2025 +device: cpu + +datasource: + datasource_type: multipmgjson + root_path: ./data/toy_data_multi/ + spectrum_key: "XANES" + +dataset: + dataset_type: descriptor_multihead_inverse + root: ./data/processed/toy_data_mh_mlp_inverse_test/ + preload: True + skip_prepare: False + split_ratios: [0.8, 0.2] + descriptors: + - descriptor_type: wacsf + r_min: 1.0 + r_max: 6.0 + n_g2: 8 + n_g4: 16 + +encodings: + - encoding_type: identity + +model: + model_type: mh_mlp + in_size: auto + out_size: auto + hidden_size: 32 + head_hidden_size: 32 + dropout: 0.0 + num_hidden_layers: 2 + head_num_hidden_layers: 1 + shrink_rate: 0.5 + head_shrink_rate: 1.0 + activation: prelu + +trainer: + trainer_type: basic + batch_size: 4 + shuffle: True + drop_last: False + num_workers: 0 + epochs: 2 + learning_rate: 0.001 + optimizer: Adam + max_norm: null + validation_interval: 10 + lr_warmup: False + loss: + - loss_type: mse + regularizer: + regularizer_type: none + lr_scheduler: + lr_scheduler_type: none + early_stopper: + early_stopper_type: basic + patience: 1 + min_delta: 0.0 + restore_best: False + +strategy: + strategy_type: single + weight_init: xavier_uniform + bias_init: zeros + checkpoint_interval: 1 diff --git a/tests/dry_runs/train/test_mlp_lightning.yaml b/tests/dry_runs/train/test_mlp_lightning.yaml new file mode 100644 index 00000000..c403dda8 --- /dev/null +++ b/tests/dry_runs/train/test_mlp_lightning.yaml @@ -0,0 +1,68 @@ +# MLP dry-run training configuration using the Lightning trainer (single CPU device). + +seed: 2025 +device: cpu + +datasource: + datasource_type: pmgjson + json_path: ./data/toy_data/ + spectrum_key: "XANES" + +dataset: + dataset_type: descriptor + root: ./data/processed/toy_data_mlp_lightning_test/ + preload: True + skip_prepare: False + split_ratios: [0.8, 0.2] + descriptors: + - descriptor_type: wacsf + r_min: 1.0 + r_max: 6.0 + n_g2: 8 + n_g4: 16 + +encodings: + - encoding_type: identity + +model: + model_type: mlp + in_size: auto + out_size: auto + hidden_size: 32 + dropout: 0.0 + num_hidden_layers: 2 + shrink_rate: 0.5 + activation: prelu + +trainer: + trainer_type: lightning + batch_size: 4 + shuffle: True + drop_last: False + num_workers: 0 + num_devices: 1 + find_unused_parameters: false + static_graph: false + epochs: 2 + learning_rate: 0.001 + optimizer: Adam + max_norm: null + validation_interval: 10 + lr_warmup: False + loss: + - loss_type: mse + regularizer: + regularizer_type: none + lr_scheduler: + lr_scheduler_type: none + early_stopper: + early_stopper_type: basic + patience: 1 + min_delta: 0.0 + restore_best: False + +strategy: + strategy_type: single + weight_init: xavier_uniform + bias_init: zeros + checkpoint_interval: 1 diff --git a/tests/dry_runs/train/test_mlp_multipmgjson.yaml b/tests/dry_runs/train/test_mlp_multipmgjson.yaml new file mode 100644 index 00000000..d6ceb7cb --- /dev/null +++ b/tests/dry_runs/train/test_mlp_multipmgjson.yaml @@ -0,0 +1,65 @@ +# MLP dry-run training configuration using the multipmgjson datasource. + +seed: 2025 +device: cpu + +datasource: + datasource_type: multipmgjson + root_path: ./data/toy_data_multi/ + spectrum_key: "XANES" + +dataset: + dataset_type: descriptor + root: ./data/processed/toy_data_mlp_multipmgjson_test/ + preload: True + skip_prepare: False + split_ratios: [0.8, 0.2] + descriptors: + - descriptor_type: wacsf + r_min: 1.0 + r_max: 6.0 + n_g2: 8 + n_g4: 16 + +encodings: + - encoding_type: identity + +model: + model_type: mlp + in_size: auto + out_size: auto + hidden_size: 32 + dropout: 0.0 + num_hidden_layers: 2 + shrink_rate: 0.5 + activation: prelu + +trainer: + trainer_type: basic + batch_size: 4 + shuffle: True + drop_last: False + num_workers: 0 + epochs: 2 + learning_rate: 0.001 + optimizer: Adam + max_norm: null + validation_interval: 10 + lr_warmup: False + loss: + - loss_type: mse + regularizer: + regularizer_type: none + lr_scheduler: + lr_scheduler_type: none + early_stopper: + early_stopper_type: basic + patience: 1 + min_delta: 0.0 + restore_best: False + +strategy: + strategy_type: single + weight_init: xavier_uniform + bias_init: zeros + checkpoint_interval: 1 diff --git a/tests/dry_runs/train/test_mlp_xyzspec.yaml b/tests/dry_runs/train/test_mlp_xyzspec.yaml new file mode 100644 index 00000000..d2813740 --- /dev/null +++ b/tests/dry_runs/train/test_mlp_xyzspec.yaml @@ -0,0 +1,65 @@ +# MLP dry-run training configuration using the xyzspec datasource. + +seed: 2025 +device: cpu + +datasource: + datasource_type: xyzspec + xyz_path: ./data/toy_data_xyzspec/xyz/ + spectra_path: ./data/toy_data_xyzspec/spectra/ + +dataset: + dataset_type: descriptor + root: ./data/processed/toy_data_mlp_xyzspec_test/ + preload: True + skip_prepare: False + split_ratios: [0.8, 0.2] + descriptors: + - descriptor_type: wacsf + r_min: 1.0 + r_max: 6.0 + n_g2: 8 + n_g4: 16 + +encodings: + - encoding_type: identity + +model: + model_type: mlp + in_size: auto + out_size: auto + hidden_size: 32 + dropout: 0.0 + num_hidden_layers: 2 + shrink_rate: 0.5 + activation: prelu + +trainer: + trainer_type: basic + batch_size: 4 + shuffle: True + drop_last: False + num_workers: 0 + epochs: 2 + learning_rate: 0.001 + optimizer: Adam + max_norm: null + validation_interval: 10 + lr_warmup: False + loss: + - loss_type: mse + regularizer: + regularizer_type: none + lr_scheduler: + lr_scheduler_type: none + early_stopper: + early_stopper_type: basic + patience: 1 + min_delta: 0.0 + restore_best: False + +strategy: + strategy_type: single + weight_init: xavier_uniform + bias_init: zeros + checkpoint_interval: 1 diff --git a/tests/implementations/batchprocessors/__init__.py b/tests/implementations/batchprocessors/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/implementations/batchprocessors/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/implementations/batchprocessors/test_processor_implementations.py b/tests/implementations/batchprocessors/test_processor_implementations.py new file mode 100644 index 00000000..7a27ed6c --- /dev/null +++ b/tests/implementations/batchprocessors/test_processor_implementations.py @@ -0,0 +1,227 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for model-specific batch processors. + +Check which batch fields feed the model and how outputs are mapped back. +""" + +from types import SimpleNamespace + +import numpy as np +import pytest +import torch + +from xanesnet.batchprocessors import BatchProcessorRegistry + +X = torch.tensor([[1, 2], [3, 4], [5, 6]]) +INTENSITIES = torch.arange(6.0).reshape(3, 2) +TARGET_SITE_MASK = torch.tensor([True, False, True]) + + +def processor_for(dataset_type: str, model_type: str): + return BatchProcessorRegistry.create((dataset_type, model_type)) + + +def batch(**fields) -> SimpleNamespace: + return SimpleNamespace(sample_id=[1, 2, 3], **fields) + + +############################################################################### +################################ DESCRIPTOR MODELS ############################ +############################################################################### + + +@pytest.mark.parametrize( + ("dataset_type", "model_type"), + [("descriptor", "mlp"), ("descriptor_multihead", "mh_mlp"), ("descriptor_inverse", "mlp")], +) +def test_descriptor_processors_read_features_targets_and_elements(dataset_type, model_type): + processor = processor_for(dataset_type, model_type) + data = batch(x=X, y=INTENSITIES, element=torch.tensor([26, 29, 26])) + + assert processor.input_preparation(data) == {"x": X} + assert processor.target_preparation(data) is INTENSITIES + assert processor.element_preparation(data) is data.element + assert list(processor.sample_id_preparation(data)) == ["1", "2", "3"] + assert processor.sample_id_preparation(data).dtype.kind == "U" + + +@pytest.mark.parametrize("dataset_type", ["descriptor_multihead", "descriptor_multihead_inverse"]) +def test_multihead_predictions_are_reduced_to_the_head_of_each_sample(dataset_type): + processor = processor_for(dataset_type, "mh_mlp") + heads, samples, width = 2, 3, 4 + predictions = torch.arange(heads * samples * width, dtype=torch.float32).reshape(heads, samples, width) + data = batch(head_idx=torch.tensor([1, 0, 1])) + + selected = processor.prediction_preparation(data, predictions) + + assert selected.shape == (samples, width) + torch.testing.assert_close(selected[0], predictions[1, 0]) + torch.testing.assert_close(selected[1], predictions[0, 1]) + torch.testing.assert_close(selected[2], predictions[1, 2]) + + +############################################################################### +################################# GRAPH MODELS ################################ +############################################################################### + +GRAPH_FIELDS = { + ("geometrygraph", "schnet"): ["z", "edge_index", "edge_weight"], + ("geometrygraph", "dimenet"): ["z", "edge_index", "edge_weight", "angle", "idx_kj", "idx_ji"], + ("geometrygraph", "dimenet++"): ["z", "edge_index", "edge_weight", "angle", "idx_kj", "idx_ji"], +} + + +@pytest.mark.parametrize(("keys", "expected"), GRAPH_FIELDS.items()) +def test_geometry_graph_models_receive_the_atoms_and_edges(keys, expected): + processor = processor_for(*keys) + data = batch( + x=X, + edge_index=1, + edge_weight=2, + angle=3, + idx_kj=4, + idx_ji=5, + intensities=INTENSITIES, + target_site_mask=TARGET_SITE_MASK, + ) + + inputs = processor.input_preparation(data) + + assert list(inputs) == expected + assert inputs["z"] is X + + +@pytest.mark.parametrize( + "keys", + [("geometrygraph", "schnet"), ("geometrygraph", "dimenet"), ("gemnet", "gemnet"), ("gemnet_oc", "gemnet_oc")], +) +def test_per_atom_models_are_evaluated_at_the_target_sites(keys): + processor = processor_for(*keys) + data = batch(x=X, intensities=INTENSITIES, target_site_mask=TARGET_SITE_MASK) + per_atom_predictions = INTENSITIES + 100 + + torch.testing.assert_close( + processor.prediction_preparation(data, per_atom_predictions), + per_atom_predictions[[0, 2]], + ) + torch.testing.assert_close(processor.element_preparation(data), X[[0, 2]]) + assert processor.target_preparation(data) is INTENSITIES + + +GEMNET_REQUIRED = dict( + edge_vec=1, edge_weight=2, id_swap=3, id3_expand_ba=4, id3_reduce_ca=5, Kidx3=6, id_c=7, id_a=8, edge_index=9 +) + + +def test_gemnet_optional_quadruplet_fields_default_to_none(): + inputs = processor_for("gemnet", "gemnet").input_preparation(batch(x=X, **GEMNET_REQUIRED)) + + assert inputs["z"] is X + assert inputs["id_c"] == 7 + assert inputs["Kidx4"] is None + assert inputs["int_edge_vec"] is None + + +def test_gemnet_optional_fields_are_forwarded_when_present(): + inputs = processor_for("gemnet", "gemnet").input_preparation(batch(x=X, Kidx4=42, **GEMNET_REQUIRED)) + assert inputs["Kidx4"] == 42 + + +def test_gemnet_oc_optional_interaction_fields_default_to_none_and_are_forwarded_when_present(): + processor = processor_for("gemnet_oc", "gemnet_oc") + + without = processor.input_preparation(batch(x=X, **GEMNET_REQUIRED)) + with_extra = processor.input_preparation(batch(x=X, a2a_edge_index=11, **GEMNET_REQUIRED)) + + assert without["a2a_edge_index"] is None + assert without["qint_edge_index"] is None + assert with_extra["a2a_edge_index"] == 11 + + +############################################################################### +################################ EQUIVARIANT MODELS ########################### +############################################################################### + + +def test_e3ee_takes_the_element_from_the_target_site_of_each_sample(): + processor = processor_for("e3ee", "e3ee") + x = torch.tensor([[26, 8, 8], [29, 29, 1]]) # samples x atoms + data = batch(x=x, target_site_index=torch.tensor([0, 1]), intensities=INTENSITIES) + + assert processor.element_preparation(data).tolist() == [26, 29] + assert processor.target_preparation(data) is INTENSITIES + + +def test_e3ee_passes_the_graph_and_path_tensors_to_the_model(): + fields = [ + "x", "mask", "target_site_index", "edge_src", "edge_dst", "edge_weight", "edge_vec", "att_dst", "att_dist", + "att_vec", "energies", "path_j", "path_k", "path_r0j", "path_r0k", "path_rjk", "path_cosangle", "path_batch", + ] # fmt: skip + data = batch(**{name: index for index, name in enumerate(fields)}) + + inputs = processor_for("e3ee", "e3ee").input_preparation(data) + + assert inputs == {name: index for index, name in enumerate(fields)} + + +def test_e3ee_full_is_evaluated_at_the_target_sites_of_the_full_graph(): + processor = processor_for("e3ee_full", "e3ee_full") + data = batch(x=X, intensities=INTENSITIES, target_site_mask=TARGET_SITE_MASK) + + torch.testing.assert_close(processor.prediction_preparation(data, INTENSITIES), INTENSITIES[[0, 2]]) + torch.testing.assert_close(processor.element_preparation(data), X[[0, 2]]) + assert processor.target_preparation(data) is INTENSITIES + + +def test_e3ee_full_passes_the_graph_energy_grid_and_path_tensors_to_the_model(): + fields = [ + "x", "mask", "target_site_mask", "edge_src", "edge_dst", "edge_weight", "edge_vec", "att_src", "att_dst", + "att_dist", "att_vec", "energies", "path_center", "path_j", "path_k", "path_r0j", "path_r0k", "path_rjk", + "path_cosangle", + ] # fmt: skip + expected = {name: index for index, name in enumerate(fields)} + + assert processor_for("e3ee_full", "e3ee_full").input_preparation(batch(**expected)) == expected + + +def test_envembed_forwards_descriptors_and_spectral_basis(): + data = batch( + descriptor_features="d", distance_features="r", lengths="l", basis="b", intensities=INTENSITIES, element="e" + ) + processor = processor_for("envembed", "envembed") + + assert processor.input_preparation(data) == { + "descriptor_features": "d", + "distance_features": "r", + "lengths": "l", + "basis": "b", + } + assert processor.target_preparation(data) is INTENSITIES + assert processor.element_preparation(data) == "e" + assert isinstance(processor.sample_id_preparation(data), np.ndarray) diff --git a/tests/implementations/batchprocessors/test_registry.py b/tests/implementations/batchprocessors/test_registry.py new file mode 100644 index 00000000..5b9d07a9 --- /dev/null +++ b/tests/implementations/batchprocessors/test_registry.py @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Tests for the registered dataset/model batch-processor mappings.""" + +import pytest + +from xanesnet.batchprocessors import ( + BatchProcessorRegistry, + ForwardBatchProcessor, + InverseBatchProcessor, +) + + +############################################################################### +################################### REGISTRY ################################## +############################################################################### + + +def test_processors_are_looked_up_by_dataset_and_model_type_ignoring_case(): + assert BatchProcessorRegistry.get(("Descriptor", "MLP")) is BatchProcessorRegistry.get(("descriptor", "mlp")) + + +def test_unknown_combinations_name_both_types(): + with pytest.raises(KeyError, match="for descriptor, not_a_model"): + BatchProcessorRegistry.get(("descriptor", "not_a_model")) + + +def test_message_passing_datasets_share_the_processor_of_their_plain_counterpart(): + mp_keys = [key for key in BatchProcessorRegistry.list() if key[0].endswith("_mp")] + + assert mp_keys + for dataset_type, model_type in mp_keys: + plain = (dataset_type.removesuffix("_mp"), model_type) + assert BatchProcessorRegistry.get((dataset_type, model_type)) is BatchProcessorRegistry.get(plain) + + +def test_inverse_datasets_are_handled_by_inverse_processors_only(): + for dataset_type, model_type in BatchProcessorRegistry.list(): + processor = BatchProcessorRegistry.get((dataset_type, model_type)) + assert issubclass(processor, InverseBatchProcessor) == ("inverse" in dataset_type) + assert issubclass(processor, ForwardBatchProcessor) == ("inverse" not in dataset_type) diff --git a/tests/implementations/components/__init__.py b/tests/implementations/components/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/implementations/components/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/implementations/components/test_activation.py b/tests/implementations/components/test_activation.py new file mode 100644 index 00000000..460d536a --- /dev/null +++ b/tests/implementations/components/test_activation.py @@ -0,0 +1,43 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the activation registry.""" + +import pytest +from torch import nn + +from xanesnet.components import ActivationRegistry + + +@pytest.mark.parametrize("name", ActivationRegistry.list()) +def test_every_activation_can_be_created_without_arguments(name): + """Models build activations from the configured key alone.""" + assert isinstance(ActivationRegistry.create(name), nn.Module) + + +def test_lookup_ignores_case(): + assert ActivationRegistry.get("ReLU") is ActivationRegistry.get("relu") diff --git a/tests/implementations/components/test_init.py b/tests/implementations/components/test_init.py new file mode 100644 index 00000000..e9def77b --- /dev/null +++ b/tests/implementations/components/test_init.py @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the weight and bias initializer registries.""" + +import pytest +import torch + +from xanesnet.components import BiasInitRegistry, WeightInitRegistry + +ALL_INITIALIZERS = [("weight", key) for key in WeightInitRegistry.list()] + [ + ("bias", key) for key in BiasInitRegistry.list() +] +REGISTRIES = {"weight": WeightInitRegistry, "bias": BiasInitRegistry} + + +@pytest.mark.parametrize(("kind", "key"), ALL_INITIALIZERS) +def test_every_initializer_returns_the_tensor_it_was_given(kind, key): + """The ``InitFn`` contract: initialize in place and return the same tensor object.""" + tensor = torch.ones(4, 4) + assert REGISTRIES[kind].get(key)(tensor) is tensor + + +def test_default_initializer_leaves_the_tensor_untouched_and_accepts_keyword_arguments(): + tensor = torch.arange(6, dtype=torch.float32).reshape(2, 3) + expected = tensor.clone() + + assert WeightInitRegistry.get("default")(tensor, a=1.0, mode="fan_in") is tensor + assert torch.equal(tensor, expected) + + +@pytest.mark.parametrize(("registry", "key"), [(WeightInitRegistry, "Xavier_Uniform"), (BiasInitRegistry, "ZEROS")]) +def test_lookup_ignores_case(registry, key): + assert registry.get(key) is registry.get(key.lower()) diff --git a/tests/implementations/components/test_lrscheduler.py b/tests/implementations/components/test_lrscheduler.py new file mode 100644 index 00000000..59e2c190 --- /dev/null +++ b/tests/implementations/components/test_lrscheduler.py @@ -0,0 +1,109 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the XANESNET learning-rate scheduler wrappers.""" + +import pytest +import torch + +from xanesnet.components import LRSchedulerRegistry, OptimizerRegistry, Scheduler +from xanesnet.serialization.config import Config + +BASE_LR = 1.0 + +# scheduler key -> (constructor arguments, learning rate seen by each epoch) +SCHEDULES = { + "step": ({"step_size": 2, "gamma": 0.5}, [1.0, 1.0, 0.5, 0.5, 0.25, 0.25]), + "multistep": ({"milestones": [1, 3], "gamma": 0.5}, [1.0, 0.5, 0.5, 0.25, 0.25]), + "exponential": ({"gamma": 0.5}, [1.0, 0.5, 0.25, 0.125]), + "linear": ({"start_factor": 0.1, "end_factor": 1.0, "total_iters": 4}, [0.1, 0.325, 0.55, 0.775, 1.0, 1.0]), + "constant": ({"factor": 0.5, "total_iters": 2}, [0.5, 0.5, 1.0, 1.0]), + "none": ({}, [1.0] * 4), + "no": ({}, [1.0] * 4), +} + + +@pytest.fixture +def optimizer(): + parameter = torch.nn.Parameter(torch.zeros(1)) + return OptimizerRegistry.create("sgd", optimizer_type="sgd", params=[parameter], lr=BASE_LR) + + +def make(kind: str, optimizer) -> Scheduler: + return LRSchedulerRegistry.create( + kind, lr_scheduler_type=kind, optimizer=optimizer, last_epoch=-1, **SCHEDULES[kind][0] + ) + + +def trajectory(scheduler: Scheduler, optimizer, epochs: int) -> list[float]: + """Learning rate seen by each epoch, stepping the scheduler once per epoch.""" + rates = [] + for _ in range(epochs): + rates.append(optimizer.param_groups[0]["lr"]) + optimizer.step() + scheduler.step() + return rates + + +@pytest.mark.parametrize("kind", SCHEDULES) +def test_registry_creates_a_scheduler_that_records_its_signature(kind, optimizer): + scheduler = make(kind, optimizer) + + assert isinstance(scheduler, Scheduler) + assert scheduler.torch_scheduler is scheduler + assert isinstance(scheduler.signature, Config) + assert scheduler.signature.as_dict() == {"lr_scheduler_type": kind} + + +@pytest.mark.parametrize("kind", SCHEDULES) +def test_state_dict_excludes_xanesnet_metadata(kind, optimizer): + state = make(kind, optimizer).state_dict() + assert "_signature" not in state + assert "lr_scheduler_type" not in state + + +@pytest.mark.parametrize("kind", SCHEDULES) +def test_constructor_arguments_reach_the_torch_scheduler(kind, optimizer): + """Each wrapper must forward its arguments correctly; the expected rates follow from them.""" + expected = SCHEDULES[kind][1] + assert trajectory(make(kind, optimizer), optimizer, len(expected)) == pytest.approx(expected) + + +def test_scheduler_state_survives_a_restore_on_a_fresh_optimizer(optimizer): + original = make("step", optimizer) + for _ in range(3): + optimizer.step() + original.step() + + resumed_optimizer = OptimizerRegistry.create( + "sgd", optimizer_type="sgd", params=[torch.nn.Parameter(torch.zeros(1))], lr=BASE_LR + ) + resumed = make("step", resumed_optimizer) + resumed_optimizer.load_state_dict(optimizer.state_dict()) + resumed.load_state_dict(original.state_dict()) + + assert trajectory(resumed, resumed_optimizer, 4) == pytest.approx(trajectory(original, optimizer, 4)) diff --git a/tests/implementations/components/test_optim.py b/tests/implementations/components/test_optim.py new file mode 100644 index 00000000..027cb69a --- /dev/null +++ b/tests/implementations/components/test_optim.py @@ -0,0 +1,67 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the XANESNET optimizer wrappers (signature, registry creation, argument forwarding).""" + +import pytest +import torch + +from xanesnet.components import Optimizer, OptimizerRegistry +from xanesnet.serialization.config import Config + + +@pytest.fixture +def model() -> torch.nn.Module: + return torch.nn.Linear(3, 1) + + +@pytest.mark.parametrize("optimizer_type", OptimizerRegistry.list()) +def test_registry_creates_an_optimizer_that_records_its_signature(optimizer_type, model): + optimizer = OptimizerRegistry.create( + optimizer_type, + optimizer_type=optimizer_type, + params=model.parameters(), + lr=0.1, + ) + + assert isinstance(optimizer, Optimizer) + assert optimizer.torch_optimizer is optimizer + assert optimizer.torch_optimizer.param_groups[0]["lr"] == 0.1 + assert isinstance(optimizer.signature, Config) + assert optimizer.signature.as_dict() == {"optimizer": optimizer_type} + + +def test_lookup_ignores_case_but_the_signature_keeps_the_users_spelling(model): + optimizer = OptimizerRegistry.create("ADAM", optimizer_type="ADAM", params=model.parameters(), lr=0.01) + + assert type(optimizer) is OptimizerRegistry.get("adam") + assert optimizer.signature.as_dict() == {"optimizer": "ADAM"} + + +def test_extra_keyword_arguments_reach_the_torch_optimizer(model): + optimizer = OptimizerRegistry.create("sgd", optimizer_type="sgd", params=model.parameters(), lr=0.1, momentum=0.9) + assert optimizer.param_groups[0]["momentum"] == 0.9 diff --git a/tests/implementations/datasets/__init__.py b/tests/implementations/datasets/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/implementations/datasets/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/implementations/datasets/conftest.py b/tests/implementations/datasets/conftest.py new file mode 100644 index 00000000..3582d189 --- /dev/null +++ b/tests/implementations/datasets/conftest.py @@ -0,0 +1,116 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Fixtures shared by the dataset tests.""" + +from collections.abc import Iterator +from types import SimpleNamespace + +import pytest +from pymatgen.core import Molecule + +from xanesnet.datasources import DataSource + + +def spectrum(scale: float = 1.0) -> dict: + """Create a three-point spectrum with intensities scaled from the fixture values. + + Args: + scale: Multiplier applied to each intensity. + + Returns: + Mapping containing energy and intensity lists. + """ + return {"energies": [1.0, 2.0, 3.0], "intensities": [0.1 * scale, 0.5 * scale, 0.2 * scale]} + + +def water(sample_id: str, spectra: list[dict | None] | None, **properties) -> Molecule: + """Create a water molecule with optional spectra attached to its sites. + + Args: + sample_id: Identifier stored in the molecule-level properties. + spectra: Per-site spectra, or ``None`` to omit the spectrum property. + properties: Additional molecule-level properties. + + Returns: + Water molecule with the requested sample and site properties. + """ + molecule = Molecule( + ["O", "H", "H"], + [[0.0, 0.0, 0.1], [0.0, 0.76, -0.47], [0.1, -0.76, -0.47]], + properties={"sample_id": sample_id, **properties}, + ) + if spectra is not None: + molecule.add_site_property("spectrum", spectra) + return molecule + + +class ListSource(DataSource): + """Data source backed by a list of in-memory molecules.""" + + def __init__(self, molecules: list[Molecule]) -> None: + super().__init__("list") + self.molecules = molecules + + def __iter__(self) -> Iterator[Molecule]: + return iter(self.molecules) + + def __len__(self) -> int: + return len(self.molecules) + + def __getitem__(self, idx: int) -> Molecule: + return self.molecules[idx] + + +@pytest.fixture +def make_source(): + """Provide the in-memory molecule data-source class. + + Returns: + The ``ListSource`` class. + """ + return ListSource + + +@pytest.fixture(autouse=True) +def confirm(monkeypatch) -> SimpleNamespace: + """Answer the processed-directory confirmation prompt without waiting for input. + + Args: + monkeypatch: Pytest fixture used to replace the confirmation function. + + Returns: + Mutable state containing the answer and number of prompt calls. + """ + state = SimpleNamespace(answer=True, asked=0) + + def fake_confirm(message: str, default_yes: bool = True) -> bool: + state.asked += 1 + return state.answer + + monkeypatch.setattr("xanesnet.datasets.base.base.confirm_yes_no", fake_confirm) + return state diff --git a/tests/implementations/datasets/test_descriptor_datasets.py b/tests/implementations/datasets/test_descriptor_datasets.py new file mode 100644 index 00000000..d3354ff2 --- /dev/null +++ b/tests/implementations/datasets/test_descriptor_datasets.py @@ -0,0 +1,271 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``descriptor`` / ``descriptor_multihead`` datasets (and their inverse variants).""" + +import pytest +import torch + +from xanesnet.datasets import DatasetRegistry +from xanesnet.datasets.torch.descriptor import DescriptorData +from xanesnet.datasets.torch.descriptor_multihead import DescriptorMultiheadData +from xanesnet.serialization.config import Config +from xanesnet.utils.exceptions import ConfigError + +from .conftest import ListSource, spectrum, water + +RDC = Config( + { + "descriptor_type": "rdc", + "r_min": 0.0, + "r_max": 4.0, + "dr": 1.0, + "alpha": 2.0, + "use_charge": False, + "use_spin": False, + } +) +RDC_WIDTH = 5 + + +def create(key: str, tmp_path, molecules, descriptors=(RDC,), **overrides): + kwargs = { + "dataset_type": key, + "datasource": ListSource(molecules), + "root": str(tmp_path / "processed"), + "preload": False, + "skip_prepare": False, + "split_ratios": None, + "split_indexfile": None, + "descriptors": list(descriptors), + } + kwargs.update(overrides) + dataset = DatasetRegistry.create(key, **kwargs) + dataset.prepare() + return dataset + + +############################################################################### +################################### DESCRIPTOR ################################ +############################################################################### + + +def test_every_site_with_a_spectrum_becomes_one_sample(tmp_path): + molecules = [ + water("a", [spectrum(), None, spectrum(2.0)]), + water("b", [None, spectrum(3.0), None]), + ] + + dataset = create("descriptor", tmp_path, molecules) + + assert len(dataset) == 3 + assert [dataset[i].sample_id for i in range(3)] == ["a", "a", "b"] + assert [dataset[i].target_site_index.item() for i in range(3)] == [0, 2, 1] + assert [dataset[i].element.item() for i in range(3)] == [8, 1, 1] + + +def test_forward_samples_map_descriptor_features_to_the_spectrum(tmp_path): + dataset = create("descriptor", tmp_path, [water("a", [spectrum(), None, None])]) + + sample = dataset[0] + + assert sample.x.shape == (RDC_WIDTH,) and sample.x.dtype == torch.float32 + torch.testing.assert_close(sample.y, torch.tensor([0.1, 0.5, 0.2])) + torch.testing.assert_close(sample.energies, torch.tensor([1.0, 2.0, 3.0])) + + +def test_inverse_samples_swap_the_roles_of_features_and_spectrum(tmp_path): + forward = create("descriptor", tmp_path / "f", [water("a", [spectrum(), None, None])])[0] + inverse = create("descriptor_inverse", tmp_path / "i", [water("a", [spectrum(), None, None])])[0] + + torch.testing.assert_close(inverse.x, forward.y) + torch.testing.assert_close(inverse.y, forward.x) + + +def test_features_of_several_descriptors_are_concatenated(tmp_path): + narrow = Config({**RDC.as_dict(), "r_max": 2.0}) + molecule = water("a", [spectrum(), None, None]) + + single = create("descriptor", tmp_path / "single", [molecule], descriptors=[RDC])[0].x + combined = create("descriptor", tmp_path / "combined", [molecule], descriptors=[RDC, narrow])[0].x + + assert combined.shape == (RDC_WIDTH + 3,) + torch.testing.assert_close(combined[:RDC_WIDTH], single) + + +def test_samples_without_any_spectrum_are_skipped_with_a_warning(tmp_path, caplog): + molecules = [water("no_spectrum", None), water("ok", [spectrum(), None, None])] + + with caplog.at_level("WARNING"): + dataset = create("descriptor", tmp_path, molecules) + + assert len(dataset) == 1 + assert dataset[0].sample_id == "ok" + assert "No spectrum found for sample 0 (no_spectrum)" in caplog.text + + +def test_batches_stack_the_samples_and_keep_the_sample_ids_as_a_list(tmp_path): + dataset = create( + "descriptor", + tmp_path, + [water("a", [spectrum(), spectrum(2.0), None]), water("b", [spectrum(), None, None])], + ) + + batch = dataset.collate_fn([dataset[0], dataset[1], dataset[2]]) + + assert batch.x.shape == (3, RDC_WIDTH) + assert batch.y.shape == (3, 3) + assert batch.energies.shape == (3, 3) + assert batch.element.tolist() == [8, 1, 8] + assert batch.sample_id == ["a", "a", "b"] + + +def test_the_signature_records_the_descriptor_configuration(tmp_path): + dataset = create("descriptor", tmp_path, [water("a", [spectrum(), None, None])]) + + signature = dataset.signature.as_dict() + + assert signature["dataset_type"] == "descriptor" + assert signature["descriptors"] == [RDC.as_dict()] + + +def test_descriptor_data_survives_a_round_trip_through_disk(tmp_path): + data = DescriptorData(x=torch.ones(2), y=torch.zeros(3), energies=torch.arange(3.0), sample_id="s", + element=torch.tensor(8), target_site_index=torch.tensor(1)) # fmt: skip + + loaded = DescriptorData.load(data.save(str(tmp_path / "sample.pth"))) + + assert loaded.sample_id == "s" + for name in ("x", "y", "energies", "element", "target_site_index"): + assert torch.equal(getattr(loaded, name), getattr(data, name)) + + +def test_descriptor_data_moves_every_tensor_and_skips_missing_ones(): + data = DescriptorData(x=torch.ones(2)) + + assert data.to("cpu") is data + assert data.y is None + + +############################################################################### +############################### DESCRIPTOR MULTIHEAD ########################## +############################################################################### + + +def test_multihead_samples_carry_the_head_of_their_subdirectory(tmp_path): + molecules = [ + water("a", [spectrum(), None, None], subdir_id=0), + water("b", [spectrum(), None, None], subdir_id=1), + water("c", [spectrum(), None, None], subdir_id=1), + ] + + dataset = create("descriptor_multihead", tmp_path, molecules) + + assert [dataset[i].head_idx.item() for i in range(3)] == [0, 1, 1] + assert dataset.num_heads == 2 + + +def test_multihead_batches_stack_the_head_indices(tmp_path): + dataset = create( + "descriptor_multihead", + tmp_path, + [ + water("a", [spectrum(), None, None], subdir_id=0), + water("b", [spectrum(), None, None], subdir_id=1), + ], + ) + + batch = dataset.collate_fn([dataset[0], dataset[1]]) + + assert batch.head_idx.tolist() == [0, 1] + assert batch.x.shape == (2, RDC_WIDTH) + + +def test_multihead_inverse_swaps_features_and_spectrum(tmp_path): + molecule = water("a", [spectrum(), None, None], subdir_id=0) + forward = create("descriptor_multihead", tmp_path / "f", [molecule])[0] + inverse = create("descriptor_multihead_inverse", tmp_path / "i", [molecule])[0] + + torch.testing.assert_close(inverse.x, forward.y) + torch.testing.assert_close(inverse.y, forward.x) + + +def test_multihead_entries_need_a_subdirectory_id(tmp_path): + with pytest.raises(ConfigError, match="subdir_id"): + create("descriptor_multihead", tmp_path, [water("a", [spectrum(), None, None])]) + + +def test_head_indices_must_be_contiguous_and_start_at_zero(tmp_path): + molecules = [water("a", [spectrum(), None, None], subdir_id=0), water("b", [spectrum(), None, None], subdir_id=2)] + dataset = create("descriptor_multihead", tmp_path, molecules) + + with pytest.raises(ConfigError, match="contiguous zero-based"): + dataset.num_heads + + +def test_the_head_count_cannot_be_derived_from_an_empty_dataset(tmp_path): + dataset = create("descriptor_multihead", tmp_path, [water("a", None, subdir_id=0)]) + + with pytest.raises(ConfigError, match="empty dataset"): + dataset.num_heads + + +def test_multihead_samples_without_spectra_are_skipped(tmp_path, caplog): + with caplog.at_level("WARNING"): + dataset = create( + "descriptor_multihead", + tmp_path, + [water("a", None, subdir_id=0), water("b", [spectrum(), None, None], subdir_id=0)], + ) + + assert len(dataset) == 1 + assert "No spectrum found" in caplog.text + + +def test_multihead_signature_records_the_descriptors(tmp_path): + dataset = create("descriptor_multihead", tmp_path, [water("a", [spectrum(), None, None], subdir_id=0)]) + assert dataset.signature.as_dict()["descriptors"] == [RDC.as_dict()] + + +def test_multihead_data_round_trips_through_disk_and_tolerates_missing_fields(tmp_path): + data = DescriptorMultiheadData(x=torch.ones(2), y=torch.zeros(1), head_idx=torch.tensor(3), sample_id="s") + + loaded = DescriptorMultiheadData.load(data.save(str(tmp_path / "sample.pth"))) + + assert loaded.head_idx is not None + assert loaded.head_idx.item() == 3 + assert loaded.energies is None and loaded.element is None + + +def test_multihead_batches_leave_fields_that_samples_lack_empty(tmp_path): + dataset = create("descriptor_multihead", tmp_path, [water("a", [spectrum(), None, None], subdir_id=0)]) + sample = DescriptorMultiheadData(x=torch.ones(2), y=torch.zeros(1), head_idx=torch.tensor(0), sample_id="s") + + batch = dataset.collate_fn([sample, sample]) + + assert batch.x.shape == (2, 2) + assert batch.energies is None and batch.element is None diff --git a/tests/implementations/datasets/test_graph_datasets.py b/tests/implementations/datasets/test_graph_datasets.py new file mode 100644 index 00000000..4098241b --- /dev/null +++ b/tests/implementations/datasets/test_graph_datasets.py @@ -0,0 +1,190 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the graph datasets and their agreement with the batch processors that consume them.""" + +from typing import Any + +import pytest + +from xanesnet.batchprocessors import BatchProcessorRegistry +from xanesnet.datasets import DatasetRegistry +from xanesnet.serialization.config import Config + +from .conftest import ListSource, spectrum, water + +RADIUS = Config({"graph_builder_type": "radius", "cutoff": 3.0, "max_num_neighbors": 20}) +ATT_RADIUS = Config({"graph_builder_type": "radius", "cutoff": 3.0, "max_num_neighbors": 20}) + +# dataset type -> (model type, dataset-specific constructor arguments) +GRAPH_DATASETS = { + "geometrygraph": ("schnet", {"graph_builder": RADIUS, "compute_angles": False}), + "gemnet": ("gemnet", {"graph_builder": RADIUS, "quadruplets": False}), + "e3ee": ( + "e3ee", + { + "graph_builder": RADIUS, + "att_graph_builder": ATT_RADIUS, + "use_path_branch": True, + "max_paths_per_structure": 10, + }, + ), + "e3ee_full": ( + "e3ee_full", + { + "graph_builder": RADIUS, + "att_graph_builder": ATT_RADIUS, + "use_path_branch": True, + "max_paths_per_site": 10, + "use_target_site_mask": True, + }, + ), +} + + +def create(key: str, tmp_path, molecules, **extra): + kwargs: dict[str, Any] = { + "dataset_type": key, + "datasource": ListSource(molecules), + "root": str(tmp_path / "processed"), + "preload": False, + "skip_prepare": False, + "split_ratios": None, + "split_indexfile": None, + } + kwargs.update(GRAPH_DATASETS.get(key, (None, {}))[1]) + kwargs.update(extra) + dataset = DatasetRegistry.create(key, **kwargs) + dataset.prepare() + return dataset + + +def molecules(): + return [water("a", [spectrum(), None, None]), water("b", [None, spectrum(2.0), spectrum(3.0)])] + + +############################################################################### +################################# GEOMETRY GRAPH ############################## +############################################################################### + + +def test_geometry_graph_samples_are_whole_structures_with_their_target_sites(tmp_path): + dataset = create("geometrygraph", tmp_path, molecules()) + + first, second = dataset[0], dataset[1] + + assert len(dataset) == 2 # one graph per structure, however many target sites it has + assert first.x.tolist() == [8, 1, 1] + assert first.target_site_mask.tolist() == [True, False, False] + assert second.target_site_mask.tolist() == [False, True, True] + assert second.target_site_index.tolist() == [1, 2] + assert second.intensities.shape == (2, 3) + assert first.sample_id == "a" + assert first.edge_index.shape[0] == 2 and first.edge_index.shape[1] == first.edge_weight.shape[0] + + +def test_angles_are_only_computed_when_requested(tmp_path): + plain = create("geometrygraph", tmp_path / "plain", molecules())[0] + with_angles = create("geometrygraph", tmp_path / "angles", molecules(), compute_angles=True)[0] + + assert "angle" not in plain and "idx_kj" not in plain + assert with_angles.angle.numel() == with_angles.idx_kj.numel() == with_angles.idx_ji.numel() > 0 + + +def test_structures_without_a_spectrum_are_skipped(tmp_path, caplog): + with caplog.at_level("WARNING"): + dataset = create("geometrygraph", tmp_path, [water("none", None), *molecules()]) + + assert len(dataset) == 2 + assert "No spectrum found for sample 0 (none)" in caplog.text + + +def test_a_batch_has_one_spectrum_and_one_sample_id_per_target_site(tmp_path): + dataset = create("geometrygraph", tmp_path, molecules()) + + batch = dataset.collate_fn([dataset[0], dataset[1]]) + + assert batch.intensities.shape == (3, 3) + assert batch.energies.shape == (3, 3) + assert batch.target_site_mask.tolist() == [True, False, False, False, True, True] + assert batch.sample_id == ["a", "b", "b"] + assert batch.x.shape == (6,) + + +def test_batching_shifts_the_edge_indices_of_later_graphs(tmp_path): + dataset = create("geometrygraph", tmp_path, molecules()) + first, second = dataset[0], dataset[1] + + batch = dataset.collate_fn([first, second]) + + assert batch.edge_index[:, : first.edge_index.shape[1]].tolist() == first.edge_index.tolist() + assert batch.edge_index[:, first.edge_index.shape[1] :].tolist() == (second.edge_index + 3).tolist() + assert batch.batch.tolist() == [0, 0, 0, 1, 1, 1] + + +def test_batching_shifts_the_triplet_indices_by_the_number_of_edges(tmp_path): + dataset = create("geometrygraph", tmp_path, molecules(), compute_angles=True) + first, second = dataset[0], dataset[1] + + batch = dataset.collate_fn([first, second]) + + n_first = first.idx_kj.numel() + assert batch.idx_kj[n_first:].tolist() == (second.idx_kj + first.edge_index.shape[1]).tolist() + assert batch.idx_ji[n_first:].tolist() == (second.idx_ji + first.edge_index.shape[1]).tolist() + + +def test_the_signature_records_the_graph_settings(tmp_path): + signature = create("geometrygraph", tmp_path, molecules(), compute_angles=True).signature.as_dict() + + assert signature["dataset_type"] == "geometrygraph" + assert signature["compute_angles"] is True + assert signature["graph_builder"] == RADIUS.as_dict() + + +############################################################################### +############################ DATASET / PROCESSOR CONTRACT ##################### +############################################################################### + + +@pytest.mark.parametrize("key", list(GRAPH_DATASETS)) +def test_the_batch_processor_of_each_graph_dataset_can_read_its_batches(tmp_path, key): + model_type = GRAPH_DATASETS[key][0] + dataset = create(key, tmp_path, molecules()) + processor = BatchProcessorRegistry.create((key, model_type)) + + batch = dataset.collate_fn([dataset[i] for i in range(len(dataset))]) + inputs = processor.input_preparation(batch) + targets = processor.target_preparation(batch) + elements = processor.element_preparation(batch) + + # quadruplet fields are optional and absent unless the dataset computes them + required = {name: value for name, value in inputs.items() if not name.startswith(("int_", "id4_", "Kidx4"))} + assert required + assert all(value is not None for value in required.values()) + assert targets.dim() == 2 and targets.shape[-1] == 3 + assert elements.shape[0] == targets.shape[0] + assert len(processor.sample_id_preparation(batch)) == targets.shape[0] diff --git a/tests/implementations/datasets/test_mp_datasets.py b/tests/implementations/datasets/test_mp_datasets.py new file mode 100644 index 00000000..a52f315b --- /dev/null +++ b/tests/implementations/datasets/test_mp_datasets.py @@ -0,0 +1,95 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the helpers of the multiprocessing dataset mixin (the process pool itself is not started).""" + +import os + +import pytest + +from xanesnet.datasets import DatasetRegistry +from xanesnet.datasets._mp import MpDatasetMixin + + +@pytest.mark.parametrize( + ("total", "chunks", "expected"), + [ + (10, 3, [(0, 4), (4, 7), (7, 10)]), + (9, 3, [(0, 3), (3, 6), (6, 9)]), + (2, 5, [(0, 1), (1, 2)]), + (5, 1, [(0, 5)]), + (5, 0, [(0, 5)]), + ], +) +def test_samples_are_split_into_contiguous_balanced_ranges(total, chunks, expected): + assert MpDatasetMixin._split_index_ranges(total, chunks) == expected + + +@pytest.mark.parametrize("total", [0, -1]) +def test_nothing_is_split_for_an_empty_source(total): + assert MpDatasetMixin._split_index_ranges(total, 4) == [] + + +def test_ranges_cover_every_sample_exactly_once(): + ranges = MpDatasetMixin._split_index_ranges(103, 8) + + covered = [i for start, end in ranges for i in range(start, end)] + assert covered == list(range(103)) + assert max(end - start for start, end in ranges) - min(end - start for start, end in ranges) <= 1 + + +@pytest.mark.parametrize(("requested", "expected"), [(4, 4), (1, 1)]) +def test_an_explicit_worker_count_is_used_as_given(requested, expected): + assert MpDatasetMixin._resolve_num_workers(requested) == expected + + +@pytest.mark.parametrize("requested", [None, 0, -2]) +def test_a_missing_or_non_positive_worker_count_means_every_cpu(requested): + assert MpDatasetMixin._resolve_num_workers(requested) == (os.cpu_count() or 1) + + +def test_worker_output_names_sort_in_sample_order(): + paths = [MpDatasetMixin._mp_save_path("out", idx, seq) for idx, seq in [(10, 0), (2, 1), (2, 0), (1, 5)]] + + assert sorted(paths) == [ + os.path.join("out", "0000000001_000005.pth"), + os.path.join("out", "0000000002_000000.pth"), + os.path.join("out", "0000000002_000001.pth"), + os.path.join("out", "0000000010_000000.pth"), + ] + + +def test_every_message_passing_dataset_has_a_plain_counterpart_with_the_same_prepare_logic(): + mp_keys = [key for key in DatasetRegistry.list() if key.endswith("_mp")] + + assert mp_keys + for key in mp_keys: + mp_class = DatasetRegistry.get(key) + plain_class = DatasetRegistry.get(key.removesuffix("_mp")) + assert issubclass(mp_class, MpDatasetMixin) + assert issubclass(mp_class, plain_class) + assert not issubclass(plain_class, MpDatasetMixin) diff --git a/tests/implementations/datasources/__init__.py b/tests/implementations/datasources/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/implementations/datasources/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/implementations/datasources/test_json_datasources.py b/tests/implementations/datasources/test_json_datasources.py new file mode 100644 index 00000000..6ef3a9bf --- /dev/null +++ b/tests/implementations/datasources/test_json_datasources.py @@ -0,0 +1,220 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``pmgjson`` and ``multipmgjson`` data sources (pymatgen ``Structure``/``Molecule`` JSON files).""" + +import json +from pathlib import Path + +import pytest +from pymatgen.core import Lattice, Molecule, Structure + +from xanesnet.datasources import DataSourceRegistry +from xanesnet.datasources.pmgjson import PMGJSONSource +from xanesnet.utils.exceptions import ResourceError + +SPECTRUM = {"energies": [1.0, 2.0], "intensities": [0.5, 0.25]} + + +def structure(spectrum_key: str = "spectrum") -> Structure: + result = Structure(Lattice.cubic(4.0), ["Fe", "Fe"], [[0, 0, 0], [0.5, 0.5, 0.5]]) + result.add_site_property(spectrum_key, [SPECTRUM, None]) + return result + + +def molecule(spectrum_key: str = "spectrum") -> Molecule: + result = Molecule(["O", "H"], [[0, 0, 0], [0, 0, 1]]) + result.add_site_property(spectrum_key, [SPECTRUM, None]) + return result + + +def dump(path: Path, entry: dict | list) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(entry)) + return path + + +def create(root: Path, spectrum_key: str = "spectrum"): + return DataSourceRegistry.create( + "pmgjson", + datasource_type="pmgjson", + json_path=str(root), + spectrum_key=spectrum_key, + ) + + +############################################################################### +#################################### PMGJSON ################################## +############################################################################### + + +def test_structures_and_molecules_are_loaded_by_their_class_tag(tmp_path): + dump(tmp_path / "b.json", molecule().as_dict()) + dump(tmp_path / "a.json", structure().as_dict()) + + source = create(tmp_path) + + assert source.sample_ids == ["a", "b"] + assert isinstance(source[0], Structure) + assert isinstance(source[1], Molecule) + assert [item.properties["sample_id"] for item in source] == ["a", "b"] + + +def test_non_json_files_are_ignored(tmp_path): + dump(tmp_path / "a.json", structure().as_dict()) + (tmp_path / "notes.txt").write_text("not a sample") + + assert len(create(tmp_path)) == 1 + + +def test_a_custom_spectrum_key_is_renamed_to_spectrum(tmp_path): + dump(tmp_path / "a.json", structure("xanes").as_dict()) + + sample = create(tmp_path, spectrum_key="xanes")[0] + + assert "xanes" not in sample.site_properties + assert sample.site_properties["spectrum"][0] == SPECTRUM + + +def test_a_spectrum_key_the_file_does_not_have_leaves_the_sample_untouched(tmp_path): + dump(tmp_path / "a.json", structure().as_dict()) + + sample = create(tmp_path, spectrum_key="absent")[0] + + assert sample.site_properties["spectrum"][0] == SPECTRUM + + +@pytest.mark.parametrize("class_tag", [None, "Unsupported"]) +def test_entries_with_a_missing_or_unknown_class_tag_fall_back_to_structure_parsing(tmp_path, caplog, class_tag): + entry = structure().as_dict() + entry.pop("@class") + if class_tag is not None: + entry["@class"] = class_tag + dump(tmp_path / "a.json", entry) + + with caplog.at_level("WARNING"): + sample = create(tmp_path)[0] + + assert isinstance(sample, Structure) + assert "Attempting fallback parsing" in caplog.text + + +def test_untagged_molecules_fall_back_to_molecule_parsing(tmp_path): + entry = molecule().as_dict() + entry.pop("@class") + dump(tmp_path / "a.json", entry) + + assert isinstance(create(tmp_path)[0], Molecule) + + +def test_untagged_entries_that_are_neither_structure_nor_molecule_are_reported(tmp_path): + dump(tmp_path / "a.json", {"unexpected": True}) + + with pytest.raises(ResourceError, match="Unsupported JSON object type"): + create(tmp_path)[0] + + +def test_json_documents_must_be_objects(tmp_path): + dump(tmp_path / "a.json", [1, 2, 3]) + + with pytest.raises(ResourceError, match="Expected a JSON object"): + PMGJSONSource.load_json(tmp_path / "a.json") + + +@pytest.mark.parametrize("layout", ["missing", "empty"]) +def test_unusable_directories_are_rejected(tmp_path, layout): + root = tmp_path / "root" + if layout == "empty": + root.mkdir() + + with pytest.raises(ResourceError): + create(root) + + +############################################################################### +################################# MULTIPMGJSON ################################ +############################################################################### + + +@pytest.fixture +def multi(tmp_path): + dump(tmp_path / "set_b" / "y.json", structure().as_dict()) + dump(tmp_path / "set_b" / "x.json", structure().as_dict()) + dump(tmp_path / "set_a" / "z.json", molecule().as_dict()) + return DataSourceRegistry.create( + "multipmgjson", datasource_type="multipmgjson", root_path=str(tmp_path), spectrum_key="spectrum" + ) + + +def test_json_samples_are_grouped_by_subdirectory_with_a_stable_subdirectory_id(multi): + samples = list(multi) + + assert len(multi) == 3 + assert [(s.properties["subdir_name"], s.properties["sample_id"]) for s in samples] == [ + ("set_a", "z"), + ("set_b", "x"), + ("set_b", "y"), + ] + assert [s.properties["subdir_id"] for s in samples] == [0, 1, 1] + + +def test_multi_json_renames_the_configured_spectrum_key(tmp_path): + dump(tmp_path / "set" / "a.json", structure("xanes").as_dict()) + + source = DataSourceRegistry.create( + "multipmgjson", datasource_type="multipmgjson", root_path=str(tmp_path), spectrum_key="xanes" + ) + + assert source[0].site_properties["spectrum"][0] == SPECTRUM + assert "xanes" not in source[0].site_properties + + +def test_empty_subdirectories_are_skipped_with_a_warning(tmp_path, caplog): + dump(tmp_path / "good" / "a.json", structure().as_dict()) + (tmp_path / "empty").mkdir() + + with caplog.at_level("WARNING"): + source = DataSourceRegistry.create( + "multipmgjson", datasource_type="multipmgjson", root_path=str(tmp_path), spectrum_key="spectrum" + ) + + assert list(source.sample_ids) == ["good"] + assert "empty" in caplog.text + + +@pytest.mark.parametrize("layout", ["missing_root", "no_subdirectories", "no_json_anywhere"]) +def test_unusable_roots_are_rejected(tmp_path, layout): + root = tmp_path / "root" + if layout != "missing_root": + root.mkdir() + if layout == "no_json_anywhere": + (root / "s").mkdir() + + with pytest.raises(ResourceError): + DataSourceRegistry.create( + "multipmgjson", datasource_type="multipmgjson", root_path=str(root), spectrum_key="spectrum" + ) diff --git a/tests/implementations/datasources/test_xyz_datasources.py b/tests/implementations/datasources/test_xyz_datasources.py new file mode 100644 index 00000000..428f9568 --- /dev/null +++ b/tests/implementations/datasources/test_xyz_datasources.py @@ -0,0 +1,194 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``xyzspec`` and ``multixyzspec`` data sources (``.xyz`` structures + ``.txt`` spectra).""" + +from pathlib import Path + +import numpy as np +import pytest + +from xanesnet.datasources import DataSourceRegistry +from xanesnet.utils.exceptions import ResourceError + +XYZ = """3 +water {name} +O 0.0 0.0 0.1 +H 0.0 0.7 -0.4 +H 0.0 -0.7 -0.4 +""" + +SPECTRUM = """# header line one +# header line two +{e0} {i0} +{e1} {i1} +{e2} {i2} +""" + + +def write_sample(xyz_dir: Path, spectra_dir: Path, name: str, scale: float = 1.0) -> None: + xyz_dir.mkdir(parents=True, exist_ok=True) + spectra_dir.mkdir(parents=True, exist_ok=True) + (xyz_dir / f"{name}.xyz").write_text(XYZ.format(name=name)) + (spectra_dir / f"{name}.txt").write_text( + SPECTRUM.format(e0=7100.0, i0=0.1 * scale, e1=7101.0, i1=0.5 * scale, e2=7102.0, i2=0.2 * scale) + ) + + +############################################################################### +################################### XYZSPEC ################################### +############################################################################### + + +@pytest.fixture +def flat(tmp_path): + for name in ("b", "a", "c"): + write_sample(tmp_path / "xyz", tmp_path / "spectra", name) + return DataSourceRegistry.create( + "xyzspec", datasource_type="xyzspec", xyz_path=str(tmp_path / "xyz"), spectra_path=str(tmp_path / "spectra") + ) + + +def test_samples_are_the_sorted_names_present_in_both_directories(tmp_path): + write_sample(tmp_path / "xyz", tmp_path / "spectra", "shared") + (tmp_path / "xyz" / "only_xyz.xyz").write_text(XYZ.format(name="x")) + (tmp_path / "spectra" / "only_spectrum.txt").write_text(SPECTRUM) + + source = DataSourceRegistry.create( + "xyzspec", datasource_type="xyzspec", xyz_path=str(tmp_path / "xyz"), spectra_path=str(tmp_path / "spectra") + ) + + assert len(source) == 1 + assert source.sample_ids == ["shared"] + + +def test_samples_are_ordered_by_name(flat): + assert flat.sample_ids == ["a", "b", "c"] + assert [molecule.properties["sample_id"] for molecule in flat] == ["a", "b", "c"] + + +def test_a_sample_is_the_molecule_with_the_spectrum_attached_to_the_first_site(flat): + molecule = flat[0] + + assert [site.specie.symbol for site in molecule] == ["O", "H", "H"] + np.testing.assert_allclose(molecule.cart_coords[1], [0.0, 0.7, -0.4], atol=1e-6) + assert molecule.properties["comment"] == "water a" + spectra = molecule.site_properties["spectrum"] + assert spectra[1] is None and spectra[2] is None + np.testing.assert_allclose(spectra[0]["energies"], [7100.0, 7101.0, 7102.0]) + np.testing.assert_allclose(spectra[0]["intensities"], [0.1, 0.5, 0.2], rtol=1e-6) + assert spectra[0]["energies"].dtype == np.float32 + + +def test_iteration_matches_indexing(flat): + assert [m.properties["sample_id"] for m in flat] == [flat[i].properties["sample_id"] for i in range(len(flat))] + + +@pytest.mark.parametrize("missing", ["xyz_path", "spectra_path"]) +def test_missing_directories_are_reported(tmp_path, missing): + write_sample(tmp_path / "xyz", tmp_path / "spectra", "a") + paths = {"xyz_path": str(tmp_path / "xyz"), "spectra_path": str(tmp_path / "spectra")} + paths[missing] = str(tmp_path / "nowhere") + + with pytest.raises(ResourceError, match="does not exist"): + DataSourceRegistry.create("xyzspec", datasource_type="xyzspec", **paths) + + +def test_directories_without_matching_pairs_are_rejected(tmp_path): + (tmp_path / "xyz").mkdir() + (tmp_path / "spectra").mkdir() + (tmp_path / "xyz" / "a.xyz").write_text(XYZ.format(name="a")) + + with pytest.raises(ResourceError, match="No matching"): + DataSourceRegistry.create( + "xyzspec", datasource_type="xyzspec", xyz_path=str(tmp_path / "xyz"), spectra_path=str(tmp_path / "spectra") + ) + + +############################################################################### +################################ MULTIXYZSPEC ################################# +############################################################################### + + +@pytest.fixture +def multi(tmp_path): + for subdir, names in {"set_b": ["y", "x"], "set_a": ["z"]}.items(): + for name in names: + write_sample(tmp_path / subdir / "xyz", tmp_path / subdir / "spectra", name) + return DataSourceRegistry.create("multixyzspec", datasource_type="multixyzspec", root_path=str(tmp_path)) + + +def test_samples_are_grouped_by_subdirectory_with_a_stable_subdirectory_id(multi): + samples = list(multi) + + assert len(multi) == 3 + assert [(m.properties["subdir_name"], m.properties["sample_id"]) for m in samples] == [ + ("set_a", "z"), + ("set_b", "x"), + ("set_b", "y"), + ] + assert [m.properties["subdir_id"] for m in samples] == [0, 1, 1] + + +def test_multi_samples_carry_structure_and_spectrum(multi): + molecule = multi[0] + + assert len(molecule) == 3 + np.testing.assert_allclose(molecule.site_properties["spectrum"][0]["intensities"], [0.1, 0.5, 0.2], rtol=1e-6) + + +def test_subdirectories_without_pairs_are_skipped_with_a_warning(tmp_path, caplog): + write_sample(tmp_path / "good" / "xyz", tmp_path / "good" / "spectra", "a") + (tmp_path / "empty" / "xyz").mkdir(parents=True) + (tmp_path / "empty" / "spectra").mkdir(parents=True) + + with caplog.at_level("WARNING"): + source = DataSourceRegistry.create("multixyzspec", datasource_type="multixyzspec", root_path=str(tmp_path)) + + assert list(source.sample_ids) == ["good"] + assert "empty" in caplog.text + + +def test_a_subdirectory_must_have_xyz_and_spectra_folders(tmp_path): + write_sample(tmp_path / "good" / "xyz", tmp_path / "good" / "spectra", "a") + (tmp_path / "bad").mkdir() + + with pytest.raises(ResourceError, match="must contain 'xyz' and 'spectra'"): + DataSourceRegistry.create("multixyzspec", datasource_type="multixyzspec", root_path=str(tmp_path)) + + +@pytest.mark.parametrize("layout", ["missing_root", "no_subdirectories", "no_pairs_anywhere"]) +def test_unusable_roots_are_rejected(tmp_path, layout): + root = tmp_path / "root" + if layout != "missing_root": + root.mkdir() + if layout == "no_pairs_anywhere": + (root / "s" / "xyz").mkdir(parents=True) + (root / "s" / "spectra").mkdir(parents=True) + + with pytest.raises(ResourceError): + DataSourceRegistry.create("multixyzspec", datasource_type="multixyzspec", root_path=str(root)) diff --git a/tests/implementations/descriptors/__init__.py b/tests/implementations/descriptors/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/implementations/descriptors/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/implementations/descriptors/test_direct.py b/tests/implementations/descriptors/test_direct.py new file mode 100644 index 00000000..d7367a93 --- /dev/null +++ b/tests/implementations/descriptors/test_direct.py @@ -0,0 +1,92 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Tests for the registered ``direct`` descriptor (features read from files).""" + +import numpy as np +import pytest +from ase import Atoms + +from xanesnet.descriptors import DescriptorRegistry + +FEATURES = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) + + +def atoms(sample_id: str = "s1") -> Atoms: + system = Atoms("H3", positions=[[0, 0, 0], [0, 0, 1], [0, 0, 2]]) + system.info["sample_id"] = sample_id + return system + + +@pytest.fixture +def source_dir(tmp_path): + np.savetxt(tmp_path / "s1.txt", FEATURES) + np.savetxt(tmp_path / "flat.txt", np.array([1.0, 2.0, 3.0])) + return tmp_path + + +def direct(source_dir, preload: bool = False): + return DescriptorRegistry.create("direct", descriptor_type="direct", source_dir=str(source_dir), preload=preload) + + +############################################################################### +#################################### DIRECT ################################### +############################################################################### + + +@pytest.mark.parametrize( + ("site_index", "expected"), + [(0, FEATURES[[0]]), (2, FEATURES[[2]]), ([2, 0], FEATURES[[2, 0]]), (None, FEATURES)], +) +def test_features_are_selected_per_site(source_dir, site_index, expected): + np.testing.assert_array_equal(direct(source_dir).transform(atoms(), site_index=site_index), expected) + + +def test_the_file_is_chosen_by_the_sample_id(source_dir): + np.savetxt(source_dir / "other.txt", FEATURES * 10) + + np.testing.assert_array_equal(direct(source_dir).transform(atoms("other"), site_index=None), FEATURES * 10) + + +def test_single_row_files_are_returned_as_two_dimensional_features(source_dir): + result = direct(source_dir).transform(atoms("flat"), site_index=None) + assert result.shape == (1, 3) + + +def test_preloaded_features_are_served_from_memory(source_dir): + descriptor = direct(source_dir, preload=True) + (source_dir / "s1.txt").unlink() + + np.testing.assert_array_equal(descriptor.transform(atoms(), site_index=None), FEATURES) + + +def test_features_without_preloading_are_read_on_demand(source_dir): + descriptor = direct(source_dir, preload=False) + (source_dir / "s1.txt").unlink() + + with pytest.raises(OSError): + descriptor.transform(atoms()) diff --git a/tests/implementations/descriptors/test_soap_and_pdos_descriptors.py b/tests/implementations/descriptors/test_soap_and_pdos_descriptors.py new file mode 100644 index 00000000..6a1bf63d --- /dev/null +++ b/tests/implementations/descriptors/test_soap_and_pdos_descriptors.py @@ -0,0 +1,216 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for xanesnet's own handling in the ``soap`` and ``pdos`` descriptors. + +The numerical output of DScribe, tblite and pySCF is not tested here. +""" + +import numpy as np +import pytest +from ase import Atoms + +import xanesnet.descriptors.pdos as pdos_module +import xanesnet.descriptors.soap as soap_module +from xanesnet.descriptors import DescriptorRegistry +from xanesnet.descriptors.pdos import atoms_to_pyscf, spectrum + + +def soap(**overrides): + kwargs = { + "r_cut": 3.0, + "n_max": 2, + "l_max": 1, + "sigma": 0.5, + "species": [1, 8], + "average": "off", + "compression_mode": "off", + "compression_species_weighting": None, + "use_charge": False, + "use_spin": False, + } + kwargs.update(overrides) + return DescriptorRegistry.create("soap", descriptor_type="soap", **kwargs) + + +def pdos(**overrides): + kwargs = { + "code": "xtb", + "method": "GFN2-xTB", + "e_min": -10.0, + "e_max": 10.0, + "sigma": 1.0, + "orb_type": "p", + "quad_orb_type": "d", + "num_points": 5, + "basis": "sto-3g", + "init_guess": "minao", + "max_cycles": 10, + "use_charge": False, + "use_spin": False, + "use_quad": False, + "use_occupied": True, + "verbosity": 0, + } + kwargs.update(overrides) + return DescriptorRegistry.create("pdos", descriptor_type="pdos", **kwargs) + + +def water() -> Atoms: + return Atoms("OHH", positions=[[0.0, 0.0, 0.1], [0.0, 0.76, -0.47], [0.0, -0.76, -0.47]]) + + +############################################################################### +#################################### SOAP ##################################### +############################################################################### + + +def test_soap_returns_one_row_per_requested_site(): + descriptor = soap() + + everything = descriptor.transform(water(), site_index=None) + + assert everything.shape[0] == 3 + np.testing.assert_allclose(descriptor.transform(water(), site_index=1), everything[[1]]) + np.testing.assert_allclose(descriptor.transform(water(), site_index=[2, 0]), everything[[2, 0]]) + + +def test_soap_appends_spin_then_charge_with_zero_defaults(): + system = water() + plain = soap().transform(system, site_index=[0, 1]) + + default_extras = soap(use_spin=True, use_charge=True).transform(system, site_index=[0, 1]) + system.info.update(S=2, q=-1) + explicit_extras = soap(use_spin=True, use_charge=True).transform(system, site_index=[0, 1]) + + assert default_extras.shape[1] == plain.shape[1] + 2 + np.testing.assert_allclose(default_extras[:, :-2], plain) + assert default_extras[:, -2:].tolist() == [[0.0, 0.0]] * 2 + assert explicit_extras[:, -2:].tolist() == [[2.0, -1.0]] * 2 + + +@pytest.fixture +def dscribe_calls(monkeypatch): + """Record how xanesnet configures DScribe's SOAP.""" + calls: list[dict] = [] + original = soap_module.DscribeSOAP + + def recording(**kwargs): + calls.append(kwargs) + return original(**kwargs) + + monkeypatch.setattr(soap_module, "DscribeSOAP", recording) + return calls + + +def test_soap_builds_one_calculator_per_boundary_condition_and_reuses_it(dscribe_calls): + descriptor = soap() + molecule = water() + crystal = Atoms("H", positions=[[0, 0, 0]], cell=[3, 3, 3], pbc=True) + + descriptor.transform(molecule) + descriptor.transform(molecule) + descriptor.transform(crystal) + descriptor.transform(crystal) + + assert [call["periodic"] for call in dscribe_calls] == [False, True] + + +def test_soap_passes_its_settings_and_covers_every_element_by_default(monkeypatch): + calls: list[dict] = [] + + class StubSOAP: + def __init__(self, **kwargs): + calls.append(kwargs) + + def create(self, system): + return np.zeros((len(system), 4)) + + monkeypatch.setattr(soap_module, "DscribeSOAP", StubSOAP) + + soap(species=None, compression_mode="mu1nu1", compression_species_weighting={"1": 2.0}).transform(water()) + + (call,) = calls + assert call["species"] == list(range(1, 104)) + assert (call["r_cut"], call["n_max"], call["l_max"], call["sigma"]) == (3.0, 2, 1, 0.5) + assert call["compression"] == {"mode": "mu1nu1", "species_weighting": {"1": 2.0}} + + +############################################################################### +#################################### PDOS ##################################### +############################################################################### + + +def test_pdos_cannot_describe_all_sites_at_once(): + with pytest.raises(NotImplementedError, match="does not support computing descriptors for all sites"): + pdos().transform(water(), site_index=None) + + +def test_pdos_rejects_unknown_codes(): + with pytest.raises(ValueError, match="Unknown code: orca"): + pdos(code="orca").transform(water(), site_index=0) + + +def test_pdos_without_tblite_reports_the_missing_optional_dependency(monkeypatch): + monkeypatch.setattr(pdos_module, "Calculator", None) + + with pytest.raises(ImportError, match="tblite"): + pdos().transform(water(), site_index=0) + + +@pytest.mark.parametrize("options", [{"use_spin": True}, {"use_charge": True}]) +def test_charge_and_spin_must_be_used_together(monkeypatch, options): + monkeypatch.setattr(pdos_module, "Calculator", object) + + with pytest.raises(NotImplementedError, match="Both should be included simultaneously"): + pdos(**options).transform(water(), site_index=0) + + +@pytest.mark.parametrize(("charge", "spin"), [(0, 1), (1, 0)]) +def test_the_spin_must_match_the_electron_parity(monkeypatch, charge, spin): + monkeypatch.setattr(pdos_module, "Calculator", object) + system = water() # 10 electrons + system.info.update(q=charge, s=spin) + + with pytest.raises(ValueError, match="inconsistent with the spin state"): + pdos(use_spin=True, use_charge=True).transform(system, site_index=0) + + +def test_gaussian_broadening_sums_the_weighted_levels(): + x = np.array([0.0, 1.0]) + + values = spectrum(np.array([0.0, 2.0]), np.array([2.0, 3.0]), sigma=1.0, x=x) + + np.testing.assert_allclose( + values, + [2.0 + 3.0 * np.exp(-4.0), 2.0 * np.exp(-1.0) + 3.0 * np.exp(-1.0)], + ) + + +def test_atoms_are_converted_to_the_pyscf_format(): + expected = [("O", (0.0, 0.0, 0.0)), ("H", (0.0, 0.0, 1.5))] + assert atoms_to_pyscf(Atoms("OH", positions=[[0, 0, 0], [0, 0, 1.5]])) == expected diff --git a/tests/implementations/descriptors/test_symmetry_function_descriptors.py b/tests/implementations/descriptors/test_symmetry_function_descriptors.py new file mode 100644 index 00000000..6dfcdbba --- /dev/null +++ b/tests/implementations/descriptors/test_symmetry_function_descriptors.py @@ -0,0 +1,242 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``rdc`` and ``wacsf`` descriptors (hand-written radial/angular symmetry functions).""" + +import numpy as np +import pytest +from ase import Atoms + +from xanesnet.descriptors import DescriptorRegistry + + +def rdc(**overrides): + kwargs = {"r_min": 0.0, "r_max": 4.0, "dr": 1.0, "alpha": 2.0, "use_charge": False, "use_spin": False} + kwargs.update(overrides) + return DescriptorRegistry.create("rdc", descriptor_type="rdc", **kwargs) + + +def wacsf(**overrides): + kwargs = { + "r_min": 0.0, + "r_max": 4.0, + "n_g2": 0, + "n_g4": 0, + "l": None, + "z": None, + "g2_parameterisation": "shifted", + "g4_parameterisation": "shifted", + "use_charge": False, + "use_spin": False, + } + kwargs.update(overrides) + return DescriptorRegistry.create("wacsf", descriptor_type="wacsf", **kwargs) + + +def dimer(distance: float = 1.5, symbols: str = "OH") -> Atoms: + return Atoms(symbols, positions=[[0, 0, 0], [0, 0, distance]]) + + +def water() -> Atoms: + return Atoms("OHH", positions=[[0.0, 0.0, 0.1], [0.0, 0.76, -0.47], [0.1, -0.76, -0.47]]) + + +def rotate(system: Atoms) -> Atoms: + rotated = system.copy() + rotated.rotate(37, "xyz", rotate_cell=False) + rotated.translate([1.0, -2.0, 0.5]) + return rotated + + +def cosine_cutoff(r: float, r_max: float) -> float: + return (np.cos(np.pi * r / r_max) + 1) / 2 + + +############################################################################### +##################################### RDC ##################################### +############################################################################### + + +def test_rdc_is_a_sum_of_gaussians_weighted_by_the_atomic_number_product(): + descriptor = rdc() + r_aux = np.array([0.0, 1.0, 2.0, 3.0, 4.0]) + + result = descriptor.transform(dimer(1.5), site_index=0) + + expected = 8 * 1 * np.exp(-2.0 * (1.5 - r_aux) ** 2) + assert result.shape == (1, 5) + np.testing.assert_allclose(result[0], expected) + + +def test_rdc_grid_follows_the_configured_range_and_resolution(): + descriptor = rdc(r_min=1.0, r_max=3.0, dr=0.5) + np.testing.assert_allclose(descriptor.r_aux, [1.0, 1.5, 2.0, 2.5, 3.0]) + assert descriptor.transform(dimer(1.5)).shape == (1, 5) + + +def test_rdc_rows_follow_the_requested_sites_and_none_means_all_sites(): + descriptor = rdc() + system = dimer(1.5) + + both = descriptor.transform(system, site_index=None) + swapped = descriptor.transform(system, site_index=[1, 0]) + + assert both.shape == (2, 5) + np.testing.assert_allclose(swapped, both[[1, 0]]) + + +def test_rdc_ignores_atoms_beyond_the_cutoff(): + near = rdc(r_max=4.0).transform(dimer(1.5) + Atoms("H", positions=[[0, 0, 40.0]]), site_index=0) + alone = rdc(r_max=4.0).transform(dimer(1.5), site_index=0) + + np.testing.assert_allclose(near, alone) + + +def test_rdc_optionally_appends_spin_then_charge(): + system = dimer() + system.info.update(S=2, q=-1) + + plain = rdc().transform(system) + extended = rdc(use_spin=True, use_charge=True).transform(system) + + assert extended.shape[1] == plain.shape[1] + 2 + assert extended[0, -2:].tolist() == [2.0, -1.0] + + +def test_rdc_cannot_describe_an_atom_without_neighbours(): + with pytest.raises(RuntimeError, match="Too few atoms"): + rdc().transform(dimer(distance=30.0), site_index=0) + + +@pytest.mark.parametrize( + ("overrides", "message"), + [({"dr": 0.0}, "dr must be positive"), ({"r_min": 5.0, "r_max": 1.0}, "r_max")], +) +def test_rdc_validates_its_grid(overrides, message): + with pytest.raises(ValueError, match=message): + rdc(**overrides) + + +############################################################################### +#################################### WACSF #################################### +############################################################################### + + +@pytest.mark.parametrize( + ("n_g2", "n_g4", "width"), + [(0, 0, 1), (3, 0, 4), (0, 4, 5), (2, 6, 9)], +) +def test_wacsf_has_one_radial_sum_then_g2_then_g4_values_per_site(n_g2, n_g4, width): + result = wacsf(n_g2=n_g2, n_g4=n_g4, l=[1.0, -1.0], z=[1.0, 2.0] if n_g4 % 4 == 0 else [1.0]).transform(water()) + + assert result.shape == (1, width) + + +def test_g1_is_the_sum_of_cosine_cutoffs_over_the_neighbours(): + result = wacsf().transform(dimer(1.5), site_index=0) + np.testing.assert_allclose(result, [[cosine_cutoff(1.5, 4.0)]]) + + +def test_g1_vanishes_at_the_cutoff_radius(): + np.testing.assert_allclose(wacsf(r_max=4.0).transform(dimer(4.0), site_index=0), [[0.0]], atol=1e-12) + + +def test_g2_weights_neighbours_by_a_tenth_of_their_atomic_number(): + descriptor = wacsf(n_g2=1) + r = 1.5 + + result = descriptor.transform(dimer(r, "OH"), site_index=0) + + # single 'shifted' function: centre (r_min + r_max) / 2 and width 1 / (2 (r_max - r_min)^2) + h, m = 1 / (2 * 4.0**2), 2.0 + expected_g2 = 0.1 * 1 * np.exp(-h * (r - m) ** 2) * cosine_cutoff(r, 4.0) + np.testing.assert_allclose(result[0, 1], expected_g2) + + +def test_atoms_without_neighbours_give_zeros_followed_by_spin_and_charge(): + system = dimer(distance=30.0) + system.info.update(S=1, q=2) + + result = wacsf(n_g2=2, n_g4=2, use_spin=True, use_charge=True).transform(system, site_index=0) + + assert result.tolist() == [[0.0] * 5 + [1.0, 2.0]] + + +def test_spin_and_charge_are_appended_in_that_order(): + system = water() + system.info.update(S=1, q=2) + + result = wacsf(n_g2=2, use_spin=True, use_charge=True).transform(system, site_index=0) + + assert result.shape == (1, 5) + assert result[0, -2:].tolist() == [1.0, 2.0] + + +@pytest.mark.parametrize("descriptor", [rdc(), wacsf(n_g2=3, n_g4=2, l=[1.0, -1.0], z=[1.0])]) +def test_descriptors_do_not_change_under_rotation_and_translation(descriptor): + original = descriptor.transform(water(), site_index=None) + moved = descriptor.transform(rotate(water()), site_index=None) + + np.testing.assert_allclose(moved, original, atol=1e-8) + + +def test_g4_sums_over_pairs_of_neighbours_and_distinguishes_angles(): + descriptor = wacsf(n_g4=2, l=[1.0, -1.0], z=[1.0]) + right_angle = Atoms("OHH", positions=[[0, 0, 0], [1.0, 0, 0], [0, 1.0, 0]]) + straight = Atoms("OHH", positions=[[0, 0, 0], [1.0, 0, 0], [-1.0, 0, 0]]) + + right = descriptor.transform(right_angle, site_index=0)[0, 1:] + line = descriptor.transform(straight, site_index=0)[0, 1:] + + # lambda = +1 favours small angles, lambda = -1 favours large ones + assert right[0] > line[0] + assert line[1] > right[1] + + +def test_g4_needs_a_neighbour_count_divisible_by_the_lambda_zeta_grid(): + with pytest.raises(ValueError, match="Can't generate 3 G4 symmetry functions"): + wacsf(n_g4=3, l=[1.0, -1.0], z=[1.0]) + + +@pytest.mark.parametrize("overrides", [{"n_g2": -1}, {"n_g4": -1}]) +def test_negative_counts_are_rejected(overrides): + with pytest.raises(ValueError, match="non-negative"): + wacsf(**overrides) + + +@pytest.mark.parametrize("which", ["g2_parameterisation", "g4_parameterisation"]) +def test_unknown_parameterisations_are_rejected(which): + count = {"g2_parameterisation": {"n_g2": 2}, "g4_parameterisation": {"n_g4": 2}}[which] + + with pytest.raises(ValueError, match="parameterisation must be"): + wacsf(**count, **{which: "other"}) + + +@pytest.mark.parametrize("parameterisation", ["shifted", "centred"]) +def test_both_parameterisations_produce_finite_features(parameterisation): + result = wacsf(n_g2=3, g2_parameterisation=parameterisation).transform(water(), site_index=None) + assert np.isfinite(result).all() diff --git a/tests/implementations/encodings/__init__.py b/tests/implementations/encodings/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/implementations/encodings/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/implementations/encodings/test_affine_encodings.py b/tests/implementations/encodings/test_affine_encodings.py new file mode 100644 index 00000000..ae359ca4 --- /dev/null +++ b/tests/implementations/encodings/test_affine_encodings.py @@ -0,0 +1,225 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the affine encodings: ``scale``, ``min_max``, ``z_score`` and ``subtract_average``.""" + +from typing import Any + +import pytest +import torch + +from xanesnet.encodings import SpectraEncodingRegistry +from xanesnet.utils.exceptions import ConfigError + +X = torch.tensor([[3.0, 5.0, 7.0], [4.0, 6.0, 8.0]]) + +# family -> (constructor arguments, encoded value of X[0]) +FAMILIES = { + "scale": ({"factor": [2.0, 4.0, 5.0]}, [1.5, 1.25, 1.4]), + "min_max": ({"minimum": [0.0, 1.0, 2.0], "maximum": [2.0, 5.0, 12.0]}, [1.5, 1.0, 0.5]), + "z_score": ({"mean": [1.0, 2.0, 3.0], "std": [2.0, 4.0, 5.0]}, [1.0, 0.75, 0.8]), + "subtract_average": ({"average": [1.0, 2.0, 3.0]}, [2.0, 3.0, 4.0]), +} +# families that have a ``per_point`` option in their constructor +HAS_PER_POINT = {"scale", "min_max", "z_score"} + + +def build(family: str, per_element: bool = False, elements: list[int] | None = None, **overrides): + params, _ = FAMILIES[family] + kwargs: dict[str, Any] = dict(params) + if per_element: # one parameter row per element: the second row is derived from the first + kwargs = {name: [values, [2 * v + 1 for v in values]] for name, values in kwargs.items()} + kwargs.update(overrides) + kwargs.update(per_element=per_element, elements=elements) + if family in HAS_PER_POINT: + kwargs.setdefault("per_point", True) + return SpectraEncodingRegistry.create(family, encoding_type=family, **kwargs) + + +############################################################################### +################################### BEHAVIOUR ################################# +############################################################################### + + +@pytest.mark.parametrize("family", FAMILIES) +def test_encode_applies_the_documented_formula(family): + expected = torch.tensor(FAMILIES[family][1]) + torch.testing.assert_close(build(family).encode(X)[0], expected) + + +@pytest.mark.parametrize("family", FAMILIES) +@pytest.mark.parametrize("per_element", [False, True]) +def test_decode_inverts_encode(family, per_element): + encoding = build(family, per_element=per_element, elements=[26, 29] if per_element else None) + elements = torch.tensor([26, 29]) if per_element else None + + torch.testing.assert_close(encoding.decode(encoding.encode(X, elements), elements), X) + + +@pytest.mark.parametrize("family", FAMILIES) +def test_the_encoded_width_equals_the_input_width(family): + assert build(family).output_size(3) == 3 + + +@pytest.mark.parametrize("family", ["scale", "min_max", "z_score"]) +def test_a_zero_spread_is_treated_as_one_instead_of_dividing_by_zero(family): + zero_spread: dict[str, Any] = { + "scale": {"factor": [0.0, 0.0, 0.0]}, + "min_max": {"minimum": [1.0, 2.0, 3.0], "maximum": [1.0, 2.0, 3.0]}, + "z_score": {"mean": [1.0, 2.0, 3.0], "std": [0.0, 0.0, 0.0]}, + }[family] + encoding = build(family, **zero_spread) + + encoded = encoding.encode(X) + assert torch.isfinite(encoded).all() + torch.testing.assert_close(encoding.decode(encoded), X) + + +############################################################################### +################################ PER-ELEMENT MODE ############################# +############################################################################### + + +@pytest.mark.parametrize("family", FAMILIES) +def test_each_sample_uses_the_parameters_of_its_own_element(family): + encoding = build(family, per_element=True, elements=[26, 29]) + + encoded = encoding.encode(X, torch.tensor([29, 26])) + + for row, element_row in enumerate((1, 0)): # sample 0 is element 29 (parameter row 1) + single = build(family, per_element=True, elements=[26, 29]) + reference = single.encode(X[row : row + 1], torch.tensor([[26, 29][element_row]])) + torch.testing.assert_close(encoded[row : row + 1], reference) + + +def test_the_element_order_of_the_configuration_defines_the_parameter_rows(): + forward = build("subtract_average", per_element=True, elements=[26, 29]) + reversed_ = build("subtract_average", per_element=True, elements=[29, 26]) + element_26 = torch.tensor([26, 26]) + + assert not torch.equal(forward.encode(X, element_26), reversed_.encode(X, element_26)) + + +def test_element_aware_encodings_require_atomic_numbers(): + encoding = build("z_score", per_element=True, elements=[26, 29]) + with pytest.raises(ConfigError, match="requires per-sample atomic numbers"): + encoding.encode(X) + + +def test_elements_without_parameters_are_reported_with_their_atomic_numbers(): + encoding = build("z_score", per_element=True, elements=[26, 29]) + with pytest.raises(ConfigError, match=r"no parameters for element\(s\) \[27\]"): + encoding.encode(X, torch.tensor([26, 27])) + + +@pytest.mark.parametrize("atomic_number", [100, -1]) +def test_out_of_range_atomic_numbers_are_rejected(atomic_number): + encoding = build("z_score", per_element=True, elements=[26, 29]) + with pytest.raises(ConfigError, match="out-of-range"): + encoding.encode(X, torch.tensor([26, atomic_number])) + + +def test_element_independent_encodings_ignore_the_elements_argument(): + encoding = build("z_score") + torch.testing.assert_close(encoding.encode(X, torch.tensor([26, 29])), encoding.encode(X)) + + +############################################################################### +################################### SIGNATURE ################################# +############################################################################### + + +@pytest.mark.parametrize("family", FAMILIES) +@pytest.mark.parametrize("per_element", [False, True]) +def test_signature_rebuilds_an_equivalent_encoding(family, per_element): + elements = [26, 29] if per_element else None + original = build(family, per_element=per_element, elements=elements) + + (signature,) = original.signature + kwargs = signature.as_dict() + assert kwargs["encoding_type"] == family + assert kwargs["per_element"] is per_element + assert kwargs["elements"] == elements + + rebuilt = SpectraEncodingRegistry.create(family, **kwargs) + element_tensor = torch.tensor([26, 29]) if per_element else None + torch.testing.assert_close(rebuilt.encode(X, element_tensor), original.encode(X, element_tensor)) + + +def test_signature_records_the_effective_parameters_not_the_degenerate_input(): + encoding = build("z_score", std=[0.0, 2.0, 4.0]) + assert encoding.signature[0].as_dict()["std"] == [1.0, 2.0, 4.0] + + +############################################################################### +################################### VALIDATION ################################ +############################################################################### + + +@pytest.mark.parametrize( + ("family", "overrides"), + [ + ("scale", {"factor": []}), + ("min_max", {"minimum": [], "maximum": []}), + ("z_score", {"mean": [], "std": []}), + ("subtract_average", {"average": []}), + ], +) +def test_empty_parameters_are_rejected(family, overrides): + with pytest.raises(ConfigError, match="non-empty"): + build(family, **overrides) + + +@pytest.mark.parametrize( + ("family", "overrides"), + [ + ("min_max", {"minimum": [0.0, 1.0], "maximum": [1.0, 2.0, 3.0]}), + ("z_score", {"mean": [0.0, 1.0], "std": [1.0, 2.0, 3.0]}), + ], +) +def test_mismatched_parameter_lengths_are_rejected(family, overrides): + with pytest.raises(ConfigError, match="mismatch"): + build(family, **overrides) + + +@pytest.mark.parametrize( + ("elements", "message"), + [ + (None, "non-empty list of elements"), + ([], "non-empty list of elements"), + ([26, 26], "must be unique"), + ([26, 29, 8], "one parameter row per element"), + ], +) +def test_per_element_mode_validates_the_element_list(elements, message): + with pytest.raises(ConfigError, match=message): + build("z_score", per_element=True, elements=elements) + + +def test_per_element_rows_must_have_equal_length(): + with pytest.raises(ConfigError, match="equal length"): + build("subtract_average", per_element=True, elements=[26, 29], average=[[1.0, 2.0], [1.0]]) diff --git a/tests/implementations/encodings/test_composite_encodings.py b/tests/implementations/encodings/test_composite_encodings.py new file mode 100644 index 00000000..4b94f10f --- /dev/null +++ b/tests/implementations/encodings/test_composite_encodings.py @@ -0,0 +1,228 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the composite encodings: ``CombinedEncoding`` (chain) and ``ConcatEncoding`` (parallel).""" + +import pytest +import torch + +from xanesnet.encodings import CombinedEncoding, ConcatEncoding, SpectraEncodingRegistry +from xanesnet.serialization.config import Config + +X = torch.tensor([[2.0, 4.0, 6.0], [8.0, 10.0, 12.0]]) + + +def scale(factor: float) -> Config: + """Build a per-point scaling encoding configuration. + + Args: + factor: Factor applied to each spectral point. + + Returns: + Configuration for the scale encoding. + """ + return Config( + { + "encoding_type": "scale", + "factor": [factor] * 3, + "per_point": True, + "per_element": False, + "elements": None, + } + ) + + +def subtract(value: float) -> Config: + """Build a per-point average-subtraction encoding configuration. + + Args: + value: Average subtracted from each spectral point. + + Returns: + Configuration for the subtract-average encoding. + """ + return Config({"encoding_type": "subtract_average", "average": [value] * 3, "per_element": False, "elements": None}) + + +def fourier(concat: bool = False) -> Config: + """Build a Fourier encoding configuration. + + Args: + concat: Whether to concatenate the input with its Fourier representation. + + Returns: + Configuration for the Fourier encoding. + """ + return Config({"encoding_type": "fourier", "concat": concat}) + + +############################################################################### +################################ COMBINED (CHAIN) ############################# +############################################################################### + + +def test_encodings_are_applied_in_order_and_decoded_in_reverse(): + chain = CombinedEncoding.from_configs([scale(2.0), subtract(1.0)]) + + encoded = chain.encode(X) + + torch.testing.assert_close(encoded, X / 2 - 1) # scale first, then subtract (the order matters) + torch.testing.assert_close(chain.decode(encoded), X) + + +def test_output_size_and_prepare_follow_the_chain(): + chain = CombinedEncoding.from_configs([scale(2.0), fourier(concat=False)]) + chain.prepare(3) + + assert chain.output_size(3) == 6 + assert chain.encode(X).shape == (2, 6) + torch.testing.assert_close(chain.decode(chain.encode(X)), X) + + +def test_elements_are_passed_to_every_member(): + per_element = Config( + { + "encoding_type": "subtract_average", + "average": [[1.0, 1.0, 1.0], [5.0, 5.0, 5.0]], + "per_element": True, + "elements": [26, 29], + } + ) + chain = CombinedEncoding.from_configs([scale(1.0), per_element]) + + encoded = chain.encode(X, torch.tensor([26, 29])) + + torch.testing.assert_close(encoded, torch.stack([X[0] - 1.0, X[1] - 5.0])) + + +def test_signature_lists_the_member_signatures_in_order_and_rebuilds_the_chain(): + chain = CombinedEncoding.from_configs([scale(2.0), subtract(1.0)]) + + signature = chain.signature + assert [item.get_str("encoding_type") for item in signature] == ["scale", "subtract_average"] + + rebuilt = CombinedEncoding.from_configs(signature) + torch.testing.assert_close(rebuilt.encode(X), chain.encode(X)) + + +@pytest.mark.parametrize("build", [lambda: CombinedEncoding([]), lambda: CombinedEncoding.from_configs([])]) +def test_at_least_one_member_is_required(build): + with pytest.raises(ValueError): + build() + + +def test_unknown_member_types_are_reported(): + with pytest.raises(KeyError, match="does_not_exist"): + CombinedEncoding.from_configs([Config({"encoding_type": "does_not_exist"})]) + + +############################################################################### +################################ CONCAT (PARALLEL) ############################ +############################################################################### + + +def make_concat(*members: Config) -> ConcatEncoding: + """Create and prepare a concatenation encoding for three-point spectra. + + Args: + members: Encoding configurations evaluated in parallel. + + Returns: + Prepared concatenation encoding. + """ + encoding = SpectraEncodingRegistry.create("concat", encoding_type="concat", encodings=list(members)) + encoding.prepare(3) + return encoding + + +def test_members_see_the_same_input_and_their_outputs_are_concatenated(): + encoding = make_concat(scale(2.0), scale(4.0)) + + encoded = encoding.encode(X) + + assert encoding.output_size(3) == 6 + torch.testing.assert_close(encoded, torch.cat([X / 2, X / 4], dim=-1)) + + +def test_decoding_averages_the_reconstruction_of_each_member(): + encoding = make_concat(scale(2.0), scale(4.0)) + first, second = torch.ones(2, 3), 3 * torch.ones(2, 3) + + decoded = encoding.decode(torch.cat([first, second], dim=-1)) + + torch.testing.assert_close(decoded, (first * 2 + second * 4) / 2) + torch.testing.assert_close(encoding.decode(encoding.encode(X)), X) + + +def test_members_with_different_output_widths_are_split_correctly(): + encoding = make_concat(scale(2.0), fourier(concat=False)) + + assert encoding.output_size(3) == 3 + 6 + torch.testing.assert_close(encoding.decode(encoding.encode(X)), X) + + +@pytest.mark.parametrize("method", ["encode", "decode"]) +def test_prepare_must_be_called_first(method): + encoding = SpectraEncodingRegistry.create("concat", encoding_type="concat", encodings=[scale(2.0)]) + with pytest.raises(RuntimeError, match="before prepare"): + getattr(encoding, method)(X) + + +def test_input_and_prediction_widths_are_validated(): + encoding = make_concat(scale(2.0), scale(4.0)) + + with pytest.raises(ValueError, match="expected input width 3"): + encoding.encode(torch.ones(2, 5)) + with pytest.raises(ValueError, match="expected prediction width 6"): + encoding.decode(torch.ones(2, 5)) + + +def test_preparing_again_rebinds_the_expected_width(): + encoding = make_concat(scale(2.0)) + encoding.prepare(3) + with pytest.raises(ValueError, match="expected input width 3"): + encoding.encode(torch.ones(2, 4)) + + +def test_signature_nests_the_member_signatures_and_rebuilds_the_encoding(): + encoding = make_concat(scale(2.0), subtract(1.0)) + + (signature,) = encoding.signature + assert signature.get_str("encoding_type") == "concat" + assert [item.get_str("encoding_type") for item in signature.get_config_list("encodings")] == [ + "scale", + "subtract_average", + ] + + rebuilt = SpectraEncodingRegistry.create("concat", **signature.as_kwargs()) + rebuilt.prepare(3) + torch.testing.assert_close(rebuilt.encode(X), encoding.encode(X)) + + +def test_at_least_one_member_is_required_for_concat(): + with pytest.raises(ValueError, match="at least one"): + SpectraEncodingRegistry.create("concat", encoding_type="concat", encodings=[]) diff --git a/tests/implementations/encodings/test_encoding_auto_resolvers.py b/tests/implementations/encodings/test_encoding_auto_resolvers.py new file mode 100644 index 00000000..c2134e01 --- /dev/null +++ b/tests/implementations/encodings/test_encoding_auto_resolvers.py @@ -0,0 +1,120 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``"auto"`` resolvers: encoding parameters derived from training-set spectra statistics.""" + +import pytest +import torch + +from xanesnet.serialization.auto_config.registries import EncodingAutoResolver +from xanesnet.serialization.auto_config.statistics import SpectralStatisticsCollector + +# element 26: rows [0, 2] and [2, 4]; element 29: two identical rows [10, 20] +SPECTRA = torch.tensor([[0.0, 2.0], [2.0, 4.0], [10.0, 20.0], [10.0, 20.0]]) +ELEMENTS = torch.tensor([26, 26, 29, 29]) + + +@pytest.fixture(scope="module") +def statistics() -> SpectralStatisticsCollector: + collector = SpectralStatisticsCollector() + collector.update(SPECTRA, ELEMENTS) + return collector + + +def resolve(encoding_type: str, statistics, **item): + return EncodingAutoResolver.get(encoding_type)({"encoding_type": encoding_type, **item}, statistics) + + +############################################################################### +################################### OVERALL ################################### +############################################################################### + + +def test_overall_statistics_are_used_per_point_by_default(statistics): + assert resolve("z_score", statistics) == { + "mean": pytest.approx([5.5, 11.5]), + "std": pytest.approx(SPECTRA.double().std(0, unbiased=False).tolist()), + } + assert resolve("min_max", statistics) == {"minimum": [0.0, 2.0], "maximum": [10.0, 20.0]} + assert resolve("subtract_average", statistics) == {"average": pytest.approx([5.5, 11.5])} + assert resolve("scale", statistics) == {"factor": pytest.approx(SPECTRA.double().std(0, unbiased=False).tolist())} + + +def test_per_point_false_collapses_each_parameter_to_a_single_global_value(statistics): + resolved = resolve("min_max", statistics, per_point=False) + assert resolved == {"minimum": [0.0], "maximum": [20.0]} + + resolved = resolve("z_score", statistics, per_point=False) + assert resolved["mean"] == pytest.approx([float(SPECTRA.mean())]) + assert len(resolved["std"]) == 1 + + +############################################################################### +################################## PER ELEMENT ################################ +############################################################################### + + +def test_per_element_resolves_one_row_per_known_element_in_sorted_order(statistics): + resolved = resolve("z_score", statistics, per_element=True) + + assert resolved["elements"] == [26, 29] + assert resolved["mean"] == [[1.0, 3.0], [10.0, 20.0]] + assert resolved["std"] == [[1.0, 1.0], [0.0, 0.0]] + + +def test_per_element_honours_an_explicit_element_list_and_its_order(statistics): + resolved = resolve("min_max", statistics, per_element=True, elements=[29, 26]) + + assert resolved["elements"] == [29, 26] + assert resolved["minimum"] == [[10.0, 20.0], [0.0, 2.0]] + assert resolved["maximum"] == [[10.0, 20.0], [2.0, 4.0]] + + +def test_per_element_with_per_point_false_gives_single_value_rows(statistics): + resolved = resolve("min_max", statistics, per_element=True, per_point=False) + + assert resolved["minimum"] == [[0.0], [10.0]] + assert resolved["maximum"] == [[4.0], [20.0]] + + +def test_per_element_subtract_average_and_scale(statistics): + assert resolve("subtract_average", statistics, per_element=True)["average"] == [[1.0, 3.0], [10.0, 20.0]] + assert resolve("scale", statistics, per_element=True)["factor"] == [[1.0, 1.0], [0.0, 0.0]] + + +def test_unknown_requested_element_is_reported(statistics): + with pytest.raises(Exception, match="Element 8 not found"): + resolve("z_score", statistics, per_element=True, elements=[8]) + + +############################################################################### +################################### GAUSSIAN ################################## +############################################################################### + + +def test_gaussian_resolves_the_spectrum_width(statistics): + assert resolve("gaussian", statistics) == {"num_points": 2} diff --git a/tests/implementations/encodings/test_spectral_transform_encodings.py b/tests/implementations/encodings/test_spectral_transform_encodings.py new file mode 100644 index 00000000..c804fb17 --- /dev/null +++ b/tests/implementations/encodings/test_spectral_transform_encodings.py @@ -0,0 +1,158 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``identity``/``none``, ``fourier`` and ``gaussian`` encodings.""" + +import pytest +import torch + +from xanesnet.encodings import SpectraEncodingRegistry +from xanesnet.utils.exceptions import ConfigError + +X = torch.sin(torch.linspace(0, 3, 24)).repeat(2, 1) + 1.5 + + +############################################################################### +################################### IDENTITY ################################## +############################################################################### + + +@pytest.mark.parametrize("key", ["identity", "none"]) +def test_identity_encodings_pass_spectra_through_unchanged(key): + encoding = SpectraEncodingRegistry.create(key, encoding_type=key) + + assert encoding.encode(X) is X + assert encoding.decode(X) is X + assert encoding.output_size(24) == 24 + assert encoding.signature[0].as_dict() == {"encoding_type": key} + + +############################################################################### +#################################### FOURIER ################################## +############################################################################### + + +@pytest.mark.parametrize(("concat", "factor"), [(False, 2), (True, 3)]) +def test_fourier_width_includes_the_original_signal_only_when_concatenating(concat, factor): + encoding = SpectraEncodingRegistry.create("fourier", encoding_type="fourier", concat=concat) + + assert encoding.output_size(24) == factor * 24 + assert encoding.encode(X).shape == (2, factor * 24) + + +@pytest.mark.parametrize("concat", [False, True]) +def test_fourier_decode_inverts_encode(concat): + encoding = SpectraEncodingRegistry.create("fourier", encoding_type="fourier", concat=concat) + torch.testing.assert_close(encoding.decode(encoding.encode(X)), X, atol=1e-5, rtol=1e-5) + + +def test_fourier_signature_rebuilds_the_encoding(): + encoding = SpectraEncodingRegistry.create("fourier", encoding_type="fourier", concat=True) + (signature,) = encoding.signature + + assert signature.as_dict() == {"encoding_type": "fourier", "concat": True} + assert SpectraEncodingRegistry.create("fourier", **signature.as_dict()).output_size(24) == 72 + + +############################################################################### +#################################### GAUSSIAN ################################# +############################################################################### + + +def make_gaussian(**overrides): + """Create a Gaussian encoding using the test defaults and supplied overrides. + + Args: + overrides: Encoding options that replace the corresponding test defaults. + + Returns: + Gaussian spectra encoding created by the registry. + """ + kwargs = {"widths": [1.0, 2.0], "basis_stride": 2, "num_points": 24, "nonneg_output": False} + kwargs.update(overrides) + return SpectraEncodingRegistry.create("gaussian", encoding_type="gaussian", **kwargs) + + +def test_gaussian_width_is_one_coefficient_per_width_and_strided_position(): + encoding = make_gaussian() + + assert encoding.output_size(24) == 2 * 12 + assert encoding.encode(X).shape == (2, 24) + assert encoding.decode(encoding.encode(X)).shape == X.shape + + +def test_gaussian_stride_rounds_up_for_widths_that_are_not_multiples(): + assert make_gaussian(basis_stride=5).output_size(24) == 2 * 5 + + +def test_gaussian_reconstructs_a_smooth_spectrum(): + encoding = make_gaussian(widths=[1.0, 2.0, 4.0], basis_stride=1) + + reconstructed = encoding.decode(encoding.encode(X)) + + assert (reconstructed - X).abs().max() < 0.1 * X.abs().max() + + +def test_gaussian_can_clamp_negative_output(): + encoding = make_gaussian(nonneg_output=True) + assert encoding.decode(-torch.ones(1, 24)).min() >= 0 + + unclamped = make_gaussian(nonneg_output=False) + assert unclamped.decode(-torch.ones(1, 24)).min() < 0 + + +def test_gaussian_rejects_a_spectrum_of_the_wrong_width(): + with pytest.raises(ValueError, match="expected input width 24"): + make_gaussian().output_size(10) + + +@pytest.mark.parametrize( + ("overrides", "message"), + [ + ({"widths": []}, "at least one basis width"), + ({"basis_stride": 0}, "basis_stride must be positive"), + ({"num_points": 0}, "num_points must be positive"), + ], +) +def test_gaussian_validates_its_configuration(overrides, message): + with pytest.raises(ConfigError, match=message): + make_gaussian(**overrides) + + +def test_gaussian_signature_rebuilds_the_encoding(): + encoding = make_gaussian(nonneg_output=True) + (signature,) = encoding.signature + + assert signature.as_dict() == { + "encoding_type": "gaussian", + "widths": [1.0, 2.0], + "basis_stride": 2, + "num_points": 24, + "nonneg_output": True, + } + rebuilt = SpectraEncodingRegistry.create("gaussian", **signature.as_dict()) + torch.testing.assert_close(rebuilt.encode(X), encoding.encode(X)) diff --git a/tests/implementations/graphs/__init__.py b/tests/implementations/graphs/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/implementations/graphs/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/implementations/graphs/test_graph_builders.py b/tests/implementations/graphs/test_graph_builders.py new file mode 100644 index 00000000..c5effe6b --- /dev/null +++ b/tests/implementations/graphs/test_graph_builders.py @@ -0,0 +1,228 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``radius``, ``cov_radius`` and ``voronoi`` graph builders.""" + +import pytest +import torch +from pymatgen.core import Lattice, Molecule, Structure + +from xanesnet.graphs import GraphBuilder, GraphBuilderRegistry + + +def build(key: str, obj, cutoff: float, max_num_neighbors: int = 100, compute_vectors: bool = True, **extra): + builder = GraphBuilderRegistry.create( + key, graph_builder_type=key, cutoff=cutoff, max_num_neighbors=max_num_neighbors, **extra + ) + return builder.build(obj, compute_vectors=compute_vectors) + + +def chain(*z_positions: float, species: str = "H") -> Molecule: + return Molecule([species] * len(z_positions), [[0, 0, z] for z in z_positions]) + + +def edge_set(edge_index: torch.Tensor) -> set[tuple[int, int]]: + return set(zip(edge_index[0].tolist(), edge_index[1].tolist())) + + +@pytest.mark.parametrize( + ("key", "extra"), + [("radius", {}), ("cov_radius", {"cov_radii_scale": 1.2}), ("voronoi", {})], +) +def test_builders_are_registered_and_record_their_settings(key, extra): + builder = GraphBuilderRegistry.create(key, graph_builder_type=key, cutoff=3.0, max_num_neighbors=7, **extra) + + assert isinstance(builder, GraphBuilder) + assert (builder.graph_builder_type, builder.cutoff, builder.max_num_neighbors) == (key, 3.0, 7) + + +############################################################################### +#################################### RADIUS ################################### +############################################################################### + + +def test_radius_graph_connects_atoms_within_the_cutoff_in_both_directions(): + molecule = chain(0.0, 1.0, 3.0) + + edge_index, weight, vec, attr = build("radius", molecule, cutoff=1.5) + + assert edge_set(edge_index) == {(0, 1), (1, 0)} + assert weight.tolist() == [1.0, 1.0] + assert attr is None + pairs = {edge: v for edge, v in zip(zip(*edge_index.tolist()), vec.tolist())} + assert pairs[(0, 1)] == [0.0, 0.0, 1.0] + assert pairs[(1, 0)] == [0.0, 0.0, -1.0] + + +def test_a_larger_cutoff_adds_the_longer_bonds(): + edge_index, weight, *_ = build("radius", chain(0.0, 1.0, 3.0), cutoff=5.0) + + assert edge_set(edge_index) == {(i, j) for i in range(3) for j in range(3) if i != j} + assert sorted(set(weight.tolist())) == [1.0, 2.0, 3.0] + + +def test_edge_weights_are_the_lengths_of_the_edge_vectors(): + _, weight, vec, _ = build("radius", chain(0.0, 1.0, 3.0), cutoff=5.0) + torch.testing.assert_close(weight, vec.norm(dim=-1)) + + +def test_the_neighbour_limit_keeps_only_edges_that_survive_in_both_directions(): + # atom 2 would keep atom 1 (distance 2), but atom 1 prefers atom 0 (distance 1): the one-sided edge is removed + edge_index, *_ = build("radius", chain(0.0, 1.0, 3.0), cutoff=5.0, max_num_neighbors=1) + + assert edge_set(edge_index) == {(0, 1), (1, 0)} + + +def test_vectors_can_be_skipped(): + _, weight, vec, _ = build("radius", chain(0.0, 1.0), cutoff=2.0, compute_vectors=False) + + assert vec is None + assert weight.numel() == 2 + + +def test_isolated_atoms_give_an_empty_graph(): + edge_index, weight, vec, _ = build("radius", chain(0.0, 10.0), cutoff=2.0) + + assert edge_index.shape == (2, 0) + assert weight.numel() == 0 and vec.shape == (0, 3) + + +def test_periodic_structures_connect_atoms_to_their_periodic_images(): + structure = Structure(Lattice.cubic(2.0), ["Fe"], [[0, 0, 0]]) + + edge_index, weight, vec, _ = build("radius", structure, cutoff=2.1) + + assert edge_index.shape == (2, 6) + assert edge_set(edge_index) == {(0, 0)} + torch.testing.assert_close(weight, torch.full((6,), 2.0)) + assert sorted(map(tuple, vec.tolist())) == sorted( + [(2.0, 0, 0), (-2.0, 0, 0), (0, 2.0, 0), (0, -2.0, 0), (0, 0, 2.0), (0, 0, -2.0)] + ) + + +def test_periodic_structures_beyond_the_cutoff_give_an_empty_graph(): + structure = Structure(Lattice.cubic(5.0), ["Fe"], [[0, 0, 0]]) + edge_index, *_ = build("radius", structure, cutoff=2.0) + assert edge_index.shape == (2, 0) + + +############################################################################### +################################# COV_RADIUS ################################## +############################################################################### + + +@pytest.mark.parametrize(("scale", "connected"), [(1.7, True), (1.5, False)]) +def test_covalent_radius_graph_connects_atoms_closer_than_the_scaled_sum_of_covalent_radii(scale, connected): + # hydrogen covalent radius 0.31 -> pair threshold 0.62 * scale, compared with a distance of 1.0 + edge_index, *_ = build("cov_radius", chain(0.0, 1.0), cutoff=5.0, cov_radii_scale=scale) + + assert (edge_set(edge_index) == {(0, 1), (1, 0)}) is connected + assert (edge_index.shape[1] == 0) is not connected + + +def test_the_covalent_threshold_depends_on_the_elements(): + # Fe is much larger than H, so Fe-Fe at distance 2.0 is bonded while H-H at 2.0 is not + fe_pair = build("cov_radius", chain(0.0, 2.0, species="Fe"), cutoff=5.0, cov_radii_scale=1.0)[0] + h_pair = build("cov_radius", chain(0.0, 2.0, species="H"), cutoff=5.0, cov_radii_scale=1.0)[0] + + assert fe_pair.shape[1] == 2 + assert h_pair.shape[1] == 0 + + +def test_the_cutoff_still_applies_on_top_of_the_covalent_threshold(): + edge_index, *_ = build("cov_radius", chain(0.0, 1.0), cutoff=0.5, cov_radii_scale=10.0) + assert edge_index.shape[1] == 0 + + +def test_covalent_radius_also_handles_periodic_structures(): + structure = Structure(Lattice.cubic(2.0), ["Fe"], [[0, 0, 0]]) + + bonded = build("cov_radius", structure, cutoff=2.1, cov_radii_scale=1.0)[0] + not_bonded = build("cov_radius", structure, cutoff=2.1, cov_radii_scale=0.5)[0] + + assert bonded.shape == (2, 6) + assert not_bonded.shape == (2, 0) + + +############################################################################### +#################################### VORONOI ################################## +############################################################################### + + +def tetragonal() -> Structure: + """One atom in a 3 x 3 x 4 box: facet areas 12 (normal to x and y) and 9 (normal to z).""" + return Structure(Lattice.tetragonal(3.0, 4.0), ["Fe"], [[0, 0, 0]]) + + +def test_voronoi_neighbours_are_the_atoms_sharing_a_facet_and_carry_the_facet_area(): + edge_index, weight, vec, area = build("voronoi", tetragonal(), cutoff=4.1) + + assert edge_index.shape == (2, 6) + assert sorted(set(weight.tolist())) == pytest.approx([3.0, 4.0]) + torch.testing.assert_close(vec.norm(dim=-1), weight) + by_length = { + round(length, 3): sorted(set(area[weight.round(decimals=3) == length].tolist())) for length in (3.0, 4.0) + } + assert by_length[3.0] == pytest.approx([12.0]) + assert by_length[4.0] == pytest.approx([9.0]) + + +def test_the_cutoff_limits_the_voronoi_neighbours(): + edge_index, weight, *_ = build("voronoi", tetragonal(), cutoff=3.5) + + assert edge_index.shape == (2, 4) + assert weight.tolist() == pytest.approx([3.0] * 4) + + +@pytest.mark.parametrize(("threshold", "expected_edges"), [(10.0, 4), (8.0, 6), (13.0, 0)]) +def test_small_facets_can_be_removed_by_an_absolute_area(threshold, expected_edges): + edge_index, *_ = build("voronoi", tetragonal(), cutoff=4.1, min_facet_area=threshold) + assert edge_index.shape[1] == expected_edges + + +@pytest.mark.parametrize(("percent", "expected_edges"), [("70%", 6), ("80%", 4), ("100%", 4)]) +def test_small_facets_can_be_removed_relative_to_the_largest_facet(percent, expected_edges): + edge_index, *_ = build("voronoi", tetragonal(), cutoff=4.1, min_facet_area=percent) + assert edge_index.shape[1] == expected_edges + + +def test_voronoi_graphs_are_symmetric_and_can_skip_vectors(): + edge_index, _, _, area = build("voronoi", tetragonal(), cutoff=4.1) + edges = edge_set(edge_index) + assert {(dst, src) for src, dst in edges} == edges + assert area.shape == (6,) + + _, _, no_vec, _ = build("voronoi", tetragonal(), cutoff=4.1, compute_vectors=False) + assert no_vec is None + + +def test_voronoi_of_molecules_without_bounded_facets_is_empty(): + # a lone tetrahedron has no bounded Voronoi facets, and fewer than four atoms cannot be tessellated + tetrahedron = Molecule(["H"] * 4, [[1, 1, 1], [1, -1, -1], [-1, 1, -1], [-1, -1, 1]]) + + assert build("voronoi", tetrahedron, cutoff=5.0)[0].shape == (2, 0) + assert build("voronoi", chain(0.0, 1.0), cutoff=5.0)[0].shape == (2, 0) diff --git a/tests/implementations/losses/__init__.py b/tests/implementations/losses/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/implementations/losses/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/implementations/losses/test_distribution_losses.py b/tests/implementations/losses/test_distribution_losses.py new file mode 100644 index 00000000..8773b2d3 --- /dev/null +++ b/tests/implementations/losses/test_distribution_losses.py @@ -0,0 +1,114 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``emd`` (earth mover's distance) and ``wcc`` (weighted cross-correlation) losses.""" + +import pytest +import torch + +from xanesnet.losses import EMDLoss, WCCLoss + + +def spike(position: int, width: int = 21, height: float = 1.0) -> torch.Tensor: + signal = torch.zeros(1, width) + signal[0, position] = height + return signal + + +############################################################################### +##################################### EMD ##################################### +############################################################################### + + +def test_emd_is_the_summed_absolute_difference_of_the_cumulative_distributions(): + preds = torch.tensor([[1.0, 0.0, 0.0]]) + targets = torch.tensor([[0.0, 0.0, 1.0]]) + + loss = EMDLoss("emd") + + torch.testing.assert_close(loss(preds, targets, reduction="none"), torch.tensor([[1.0, 1.0, 0.0]])) + assert loss(preds, targets).item() == pytest.approx(2.0) + + +def test_emd_grows_with_the_distance_the_mass_has_to_move(): + loss = EMDLoss("emd") + near = loss(spike(5), spike(6)).item() + far = loss(spike(5), spike(15)).item() + assert 0 < near < far + + +def test_emd_is_zero_for_identical_spectra_and_averages_over_the_batch(): + loss = EMDLoss("emd") + spectra = torch.rand(4, 10) + assert loss(spectra, spectra).item() == 0.0 + + preds = torch.cat([spike(0, 5), spike(0, 5)]) + targets = torch.cat([spike(0, 5), spike(4, 5)]) + assert loss(preds, targets).item() == pytest.approx(4.0 / 2) + + +def test_emd_rejects_unsupported_reductions(): + with pytest.raises(ValueError, match="Unsupported reduction"): + EMDLoss("emd")(torch.ones(1, 3), torch.ones(1, 3), reduction="sum") + + +############################################################################### +##################################### WCC ##################################### +############################################################################### + + +def test_wcc_is_zero_for_identical_spectra(): + spectra = torch.rand(3, 21) + 0.5 + assert WCCLoss("wcc", gaussian_hwhm=3)(spectra, spectra).item() == pytest.approx(0.0, abs=1e-5) + + +def test_wcc_ignores_the_overall_amplitude_of_the_prediction(): + targets = torch.rand(3, 21) + 0.5 + assert WCCLoss("wcc", gaussian_hwhm=3)(2.5 * targets, targets).item() == pytest.approx(0.0, abs=1e-5) + + +def test_wcc_penalises_peak_shifts_more_the_further_they_are(): + loss = WCCLoss("wcc", gaussian_hwhm=2) + target = spike(10) + + shifts = [loss(spike(10 + shift), target).item() for shift in (0, 1, 3, 6)] + + assert shifts == sorted(shifts) + assert shifts[0] == pytest.approx(0.0, abs=1e-5) + assert shifts[-1] > shifts[1] + + +def test_a_wider_window_is_more_tolerant_to_shifts(): + narrow = WCCLoss("wcc", gaussian_hwhm=1)(spike(12), spike(10)).item() + wide = WCCLoss("wcc", gaussian_hwhm=6)(spike(12), spike(10)).item() + assert wide < narrow + + +@pytest.mark.parametrize("hwhm", [0, -3]) +def test_wcc_requires_a_positive_window(hwhm): + with pytest.raises(ValueError, match="gaussian_hwhm must be positive"): + WCCLoss("wcc", gaussian_hwhm=hwhm) diff --git a/tests/implementations/losses/test_msssim.py b/tests/implementations/losses/test_msssim.py new file mode 100644 index 00000000..4ba8ea07 --- /dev/null +++ b/tests/implementations/losses/test_msssim.py @@ -0,0 +1,110 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``msssim`` loss (multi-scale structural similarity for 1D spectra).""" + +from typing import Any + +import pytest +import torch + +from xanesnet.losses import MultiScale_SSIM + +TARGETS = (torch.sin(torch.linspace(0, 8, 64)).repeat(3, 1) + 1.5) * torch.tensor([[1.0], [1.5], [2.0]]) + + +def make(**overrides) -> MultiScale_SSIM: + kwargs: dict[str, Any] = { + "fractions": [0.05, 0.1, 0.2], + "data_range": 4.0, + "K": (0.01, 0.03), + "use_weighted_sum": True, + "weights": None, + } + kwargs.update(overrides) + return MultiScale_SSIM("msssim", **kwargs) + + +def test_identical_spectra_have_zero_loss(): + assert make()(TARGETS, TARGETS).item() == pytest.approx(0.0, abs=1e-5) + + +def test_loss_grows_with_the_distortion(): + loss = make() + noise = torch.randn(3, 64, generator=torch.Generator().manual_seed(0)) + + small = loss(TARGETS + 0.05 * noise, TARGETS).item() + large = loss(TARGETS + 0.5 * noise, TARGETS).item() + + assert 0 < small < large + + +def test_none_reduction_returns_one_value_per_spectral_point(): + loss = make() + preds = TARGETS + 0.2 + + loss_map = loss(preds, TARGETS, reduction="none") + + assert loss_map.shape == TARGETS.shape + torch.testing.assert_close(loss(preds, TARGETS), loss_map.mean()) + + +def test_unsupported_reduction_is_rejected(): + with pytest.raises(ValueError, match="Unsupported reduction"): + make()(TARGETS, TARGETS, reduction="sum") + + +def test_with_a_single_scale_the_weighted_sum_equals_the_product(): + preds = TARGETS + 0.3 + weighted = make(fractions=[0.1], use_weighted_sum=True)(preds, TARGETS) + product = make(fractions=[0.1], use_weighted_sum=False)(preds, TARGETS) + torch.testing.assert_close(weighted, product) + + +def test_explicit_scale_weights_change_the_result_and_must_match_the_number_of_scales(): + preds = TARGETS + 0.3 * torch.randn(3, 64, generator=torch.Generator().manual_seed(3)) + + uniform = make()(preds, TARGETS).item() + skewed = make(weights=[1.0, 0.0, 0.0])(preds, TARGETS).item() + + assert uniform != pytest.approx(skewed) + with pytest.raises(ValueError, match="must match number of scales"): + make(weights=[1.0, 1.0]) + + +def test_without_a_fixed_data_range_it_is_learned_from_the_targets_and_checkpointed(): + adaptive = make(data_range=None) + wide_targets = TARGETS * 10 + first = adaptive(wide_targets + 1.0, wide_targets).item() + + restored = make(data_range=None) + restored.load_state_dict(adaptive.state_dict()) + + assert restored(wide_targets + 1.0, wide_targets).item() == pytest.approx(first) + # the stabilising constants grew with the observed range and were restored with it + assert restored.get_extra_state() == adaptive.get_extra_state() + assert adaptive.get_extra_state()[3] > make(data_range=None).get_extra_state()[3] diff --git a/tests/implementations/losses/test_registry_and_combined.py b/tests/implementations/losses/test_registry_and_combined.py new file mode 100644 index 00000000..e81756fe --- /dev/null +++ b/tests/implementations/losses/test_registry_and_combined.py @@ -0,0 +1,99 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the loss registry and ``CombinedLoss``.""" + +import pytest +import torch + +from xanesnet.losses import CombinedLoss, L1Loss, Loss, LossRegistry, MSELoss + +PREDS = torch.tensor([[1.0, 2.0, 3.0], [0.0, 0.0, 0.0]]) +TARGETS = torch.tensor([[1.0, 4.0, 3.0], [1.0, 1.0, 2.0]]) + + +@pytest.mark.parametrize("key", ["mse", "l1", "bce", "emd"]) +def test_parameterless_losses_are_created_through_the_registry(key): + loss = LossRegistry.create(key, loss_type=key) + + assert isinstance(loss, Loss) + assert loss.loss_type == key + assert loss(PREDS, torch.ones_like(PREDS).clamp(0, 1)).dim() == 0 + + +def test_lookup_ignores_case(): + assert LossRegistry.get("MSE") is LossRegistry.get("mse") + + +############################################################################### +################################# COMBINED LOSS ############################### +############################################################################### + + +def test_combined_loss_is_the_weighted_sum_of_the_component_loss_maps(): + combined = CombinedLoss([MSELoss("mse"), L1Loss("l1")], weights=[1.0, 3.0]) + + expected_map = 0.25 * (PREDS - TARGETS) ** 2 + 0.75 * (PREDS - TARGETS).abs() + + torch.testing.assert_close(combined(PREDS, TARGETS, reduction="none"), expected_map) + torch.testing.assert_close(combined(PREDS, TARGETS), expected_map.mean()) + + +def test_weights_are_normalised_to_sum_to_one(): + scaled = CombinedLoss([MSELoss("mse"), L1Loss("l1")], weights=[10.0, 30.0]) + reference = CombinedLoss([MSELoss("mse"), L1Loss("l1")], weights=[1.0, 3.0]) + + torch.testing.assert_close(scaled(PREDS, TARGETS), reference(PREDS, TARGETS)) + assert scaled.weights.sum().item() == pytest.approx(1.0) + + +def test_a_single_component_reproduces_that_loss(): + combined = CombinedLoss([MSELoss("mse")], weights=[5.0]) + torch.testing.assert_close(combined(PREDS, TARGETS), MSELoss("mse")(PREDS, TARGETS)) + + +def test_weights_follow_the_module_and_are_part_of_its_state(): + combined = CombinedLoss([MSELoss("mse"), L1Loss("l1")], weights=[1.0, 1.0]) + assert "weights" in combined.state_dict() + + +@pytest.mark.parametrize( + ("losses", "weights", "message"), + [ + ([], [], "at least one"), + ([MSELoss("mse")], [1.0, 2.0], "Length mismatch"), + ], +) +def test_invalid_construction_is_rejected(losses, weights, message): + with pytest.raises(ValueError, match=message): + CombinedLoss(losses, weights) + + +def test_unsupported_reduction_is_rejected(): + combined = CombinedLoss([MSELoss("mse")], weights=[1.0]) + with pytest.raises(ValueError, match="Unsupported reduction"): + combined(PREDS, TARGETS, reduction="sum") diff --git a/tests/implementations/losses/test_specplus.py b/tests/implementations/losses/test_specplus.py new file mode 100644 index 00000000..d96ce727 --- /dev/null +++ b/tests/implementations/losses/test_specplus.py @@ -0,0 +1,138 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``specplus`` loss (blurred MSE + detail + gradient terms).""" + +import pytest +import torch + +from xanesnet.losses import SpectralLossPlus + +TARGETS = torch.sin(torch.linspace(0, 6, 40)).repeat(3, 1) * torch.tensor([[1.0], [2.0], [3.0]]) + + +def make(**overrides) -> SpectralLossPlus: + kwargs = { + "blur_sigma_bins": 2.0, + "alpha": 1.0, + "beta": 1.0, + "gamma": 1.0, + "huber_delta": 0.01, + "kappa_peak": 0.15, + } + kwargs.update(overrides) + return SpectralLossPlus("specplus", **kwargs) + + +def test_identical_spectra_have_zero_loss(): + assert make()(TARGETS, TARGETS).item() == pytest.approx(0.0, abs=1e-7) + + +def test_loss_grows_with_the_error(): + loss = make() + small = loss(TARGETS + 0.01, TARGETS).item() + large = loss(TARGETS + 0.5, TARGETS).item() + assert 0 < small < large + + +def test_mean_reduction_averages_the_loss_map(): + loss, preds = make(), TARGETS + 0.1 * torch.randn(3, 40, generator=torch.Generator().manual_seed(0)) + + loss_map = loss(preds, TARGETS, reduction="none") + + assert loss_map.shape == TARGETS.shape + torch.testing.assert_close(loss(preds, TARGETS), loss_map.mean()) + + +def test_unsupported_reduction_is_rejected(): + with pytest.raises(ValueError, match="Unsupported reduction"): + make()(TARGETS, TARGETS, reduction="sum") + + +@pytest.mark.parametrize("term", ["alpha", "beta", "gamma"]) +def test_each_term_is_scaled_by_its_own_weight_and_switched_off_at_zero(term): + preds = TARGETS + torch.randn(3, 40, generator=torch.Generator().manual_seed(1)) * 0.2 + only = {name: 0.0 for name in ("alpha", "beta", "gamma")} + + single = make(**{**only, term: 1.0})(preds, TARGETS) + doubled = make(**{**only, term: 2.0})(preds, TARGETS) + + assert single.item() > 0 + assert doubled.item() == pytest.approx(2 * single.item(), rel=1e-5) + assert make(**only)(preds, TARGETS).item() == 0.0 + + +def test_total_loss_is_the_sum_of_the_three_terms(): + preds = TARGETS + torch.randn(3, 40, generator=torch.Generator().manual_seed(2)) * 0.2 + parts = [ + make(alpha=a, beta=b, gamma=g)(preds, TARGETS).item() for a, b, g in ((1, 0, 0), (0, 1, 0), (0, 0, 1)) + ] + assert make()(preds, TARGETS).item() == pytest.approx(sum(parts), rel=1e-5) + + +def test_the_blur_preserves_constant_signals_and_returns_single_bins_unchanged(): + loss = make() + constant = torch.full((2, 30), 3.0) + torch.testing.assert_close(loss.gaussian_blur1d(constant, 2.0), constant, atol=1e-5, rtol=1e-5) + + single_bin = torch.tensor([[1.0], [2.0]]) + torch.testing.assert_close(loss.gaussian_blur1d(single_bin, 2.0), single_bin) + + +def test_the_blur_smooths_a_spike(): + spike = torch.zeros(1, 31) + spike[0, 15] = 1.0 + + blurred = make().gaussian_blur1d(spike, 2.0) + + assert blurred.max() < 1.0 + assert blurred.sum().item() == pytest.approx(1.0, abs=1e-4) + + +@pytest.mark.parametrize("kernel", [0, 4, -3]) +def test_the_blur_kernel_size_must_be_a_positive_odd_integer(kernel): + with pytest.raises(ValueError, match="positive odd integer"): + make().gaussian_blur1d(TARGETS, 2.0, k=kernel) + + +def test_huber_loss_is_quadratic_below_delta_and_linear_above(): + loss = make() + delta = 0.5 + small, large = torch.tensor([0.2]), torch.tensor([2.0]) + zero = torch.zeros(1) + + assert loss.huber_loss(small, zero, delta=delta).item() == pytest.approx(0.5 * 0.2**2) + assert loss.huber_loss(large, zero, delta=delta).item() == pytest.approx(0.5 * delta**2 + delta * (2.0 - delta)) + with pytest.raises(ValueError, match="Unsupported reduction"): + loss.huber_loss(small, zero, reduction="median") + + +def test_peak_weights_are_at_least_one_and_constant_for_gradient_flow(): + weights = make().peak_weighting(TARGETS.clone().requires_grad_(True)) + + assert (weights >= 1.0).all() + assert weights.requires_grad is False diff --git a/tests/implementations/models/__init__.py b/tests/implementations/models/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/implementations/models/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/implementations/models/test_mlp_models.py b/tests/implementations/models/test_mlp_models.py new file mode 100644 index 00000000..6ac5d730 --- /dev/null +++ b/tests/implementations/models/test_mlp_models.py @@ -0,0 +1,222 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``mlp`` and multi-head ``mh_mlp`` / ``mh_cnn`` models.""" + +from typing import cast + +import pytest +import torch +from torch import nn + +from xanesnet.models import ModelRegistry + +MLP = { + "in_size": 6, + "out_size": 4, + "hidden_size": 16, + "dropout": 0.0, + "num_hidden_layers": 3, + "shrink_rate": 0.5, + "activation": "relu", +} +MH_MLP = { + "in_size": 6, + "out_size": [4, 4, 4], + "hidden_size": 16, + "dropout": 0.0, + "num_hidden_layers": 2, + "shrink_rate": 0.5, + "activation": "relu", + "head_num_hidden_layers": 1, + "head_hidden_size": 8, + "head_shrink_rate": 1.0, +} +MH_CNN = { + "in_size": 16, + "out_size": [4, 4, 4], + "dropout": 0.0, + "num_conv_layers": 2, + "activation": "relu", + "out_channel": 2, + "channel_mul": 2, + "kernel_size": 3, + "stride": 1, + "head_num_hidden_layers": 1, + "head_hidden_size": 8, + "head_shrink_rate": 1.0, +} +MODELS = {"mlp": MLP, "mh_mlp": MH_MLP, "mh_cnn": MH_CNN} + + +def create(key: str, **overrides): + return ModelRegistry.create(key, model_type=key, **{**MODELS[key], **overrides}) + + +def input_size(key: str) -> int: + return cast(int, MODELS[key]["in_size"]) + + +def linear_sizes(model: nn.Module) -> list[tuple[int, int]]: + return [(m.in_features, m.out_features) for m in model.modules() if isinstance(m, nn.Linear)] + + +############################################################################### +################################ SHARED CONTRACT ############################## +############################################################################### + + +@pytest.mark.parametrize("key", MODELS) +def test_the_signature_contains_everything_needed_to_rebuild_the_model(key): + model = create(key) + + rebuilt = ModelRegistry.create(key, **model.signature.as_kwargs()) + + assert model.signature.as_dict() == {"model_type": key, **MODELS[key]} + assert rebuilt.signature.as_dict() == model.signature.as_dict() + assert [p.shape for p in rebuilt.parameters()] == [p.shape for p in model.parameters()] + + +@pytest.mark.parametrize("key", MODELS) +def test_a_rebuilt_model_accepts_the_saved_weights(key): + model = create(key) + rebuilt = ModelRegistry.create(key, **model.signature.as_kwargs()) + + rebuilt.load_state_dict(model.state_dict()) + + model.eval() + rebuilt.eval() + x = torch.randn(5, input_size(key)) + torch.testing.assert_close(rebuilt(x), model(x)) + + +@pytest.mark.parametrize("key", MODELS) +def test_weights_and_biases_follow_the_selected_initialisers(key): + model = create(key) + + model.init_weights("normal", "ones", mean=0.0, std=0.5) + + layers = [m for m in model.modules() if isinstance(m, (nn.Linear, nn.Conv1d))] + assert layers + for layer in layers: + assert layer.bias is not None + assert torch.equal(layer.bias, torch.ones_like(layer.bias)) + assert layer.weight.std().item() > 0 + + +@pytest.mark.parametrize("key", MODELS) +def test_unknown_initialisers_are_reported(key): + with pytest.raises(KeyError): + create(key).init_weights("not_an_initialiser", "zeros") + + +############################################################################### +##################################### MLP ##################################### +############################################################################### + + +def test_hidden_layers_shrink_geometrically(): + model = create("mlp") + + assert linear_sizes(model) == [(6, 16), (16, 8), (8, 4), (4, 4)] + + +def test_predictions_have_one_value_per_output_for_every_sample(): + assert create("mlp")(torch.randn(7, 6)).shape == (7, 4) + + +def test_a_shrink_rate_that_collapses_a_hidden_layer_is_rejected(): + with pytest.raises(ValueError, match="Hidden layer 2 size is less than 1"): + create("mlp", hidden_size=2, shrink_rate=0.3, num_hidden_layers=3) + + +def test_an_mlp_without_hidden_layers_is_a_single_linear_map(): + assert linear_sizes(create("mlp", num_hidden_layers=0)) == [(6, 4)] + + +def test_unknown_activations_are_reported(): + with pytest.raises(KeyError): + create("mlp", activation="not_an_activation") + + +############################################################################### +################################ MULTI-HEAD MODELS ############################ +############################################################################### + + +@pytest.mark.parametrize("key", ["mh_mlp", "mh_cnn"]) +def test_all_heads_are_evaluated_by_default(key): + model = create(key).eval() + + out = model(torch.randn(5, input_size(key))) + + assert out.shape == (3, 5, 4) # heads x batch x outputs + + +@pytest.mark.parametrize("key", ["mh_mlp", "mh_cnn"]) +def test_a_single_head_can_be_selected_and_matches_its_slice_of_the_full_output(key): + model = create(key).eval() + x = torch.randn(5, input_size(key)) + + everything = model(x) + + for head in range(3): + torch.testing.assert_close(model(x, active_head_idx=head), everything[head]) + + +@pytest.mark.parametrize("key", ["mh_mlp", "mh_cnn"]) +def test_heads_have_independent_parameters(key): + model = create(key) + first, second = model.heads[0], model.heads[1] + + assert all(a is not b for a, b in zip(first.parameters(), second.parameters())) + + +def test_mh_mlp_shares_the_trunk_and_gives_every_head_its_own_output_size(): + model = create("mh_mlp", out_size=[2, 5]) + + assert linear_sizes(model.dense_layers) == [(6, 16), (16, 8)] + assert model(torch.randn(3, 6), active_head_idx=0).shape == (3, 2) + assert model(torch.randn(3, 6), active_head_idx=1).shape == (3, 5) + + +def test_mh_mlp_rejects_a_collapsing_trunk(): + with pytest.raises(ValueError, match="Hidden layer 2 size is less than 1"): + create("mh_mlp", hidden_size=2, shrink_rate=0.3, num_hidden_layers=3) + + +def test_mh_cnn_sizes_its_heads_from_the_convolution_output(): + model = create("mh_cnn") + + # two valid convolutions with kernel 3 shrink 16 samples to 12, with 2 * 2 = 4 channels + expected_features = 4 * 12 + assert linear_sizes(model.heads[0])[0][0] == expected_features + + +def test_mh_cnn_restores_the_training_mode_after_probing_its_output_size(): + model = create("mh_cnn") + assert model.conv_layers.training is True diff --git a/tests/implementations/models/test_model_resolvers.py b/tests/implementations/models/test_model_resolvers.py new file mode 100644 index 00000000..2059be49 --- /dev/null +++ b/tests/implementations/models/test_model_resolvers.py @@ -0,0 +1,75 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the model-specific auto-config resolvers (``"auto"`` model fields derived from the data).""" + +from types import SimpleNamespace + +import pytest +import torch + +from xanesnet.models import ModelRegistry +from xanesnet.serialization.auto_config.registries import ModelAutoResolver + +TARGET = torch.zeros(5, 7) +FEATURES = torch.zeros(5, 11) + + +def basis(groups: int, coefficients: int) -> SimpleNamespace: + return SimpleNamespace(widths_eV=[1.0] * groups, Phi=torch.zeros(3, coefficients)) + + +@pytest.mark.parametrize( + ("key", "inputs", "dataset", "expected"), + [ + ("mlp", {"x": FEATURES}, None, {"in_size": 11, "out_size": 7}), + ("mh_mlp", {"x": FEATURES}, SimpleNamespace(num_heads=3), {"in_size": 11, "out_size": [7, 7, 7]}), + ("mh_cnn", {"x": FEATURES}, SimpleNamespace(num_heads=2), {"in_size": 11, "out_size": [7, 7]}), + ("schnet", {}, None, {"reduce_channels_2": 7}), + ("dimenet", {}, None, {"out_channels": 7}), + ("dimenet++", {}, None, {"out_channels": 7}), + ("e3ee", {}, None, {"out_size": 7}), + ("e3ee_full", {}, None, {"out_size": 7}), + ("gemnet", {}, None, {"num_targets": 7}), + ("gemnet_oc", {}, None, {"num_targets": 7}), + ( + "envembed", + {"descriptor_features": FEATURES, "basis": basis(groups=3, coefficients=12)}, + None, + {"in_size": 11, "kgroups": [4, 4, 4]}, + ), + ], +) +def test_resolvers_derive_model_sizes_from_the_prepared_batch(key, inputs, dataset, expected): + assert ModelAutoResolver.get(key)(inputs, TARGET, dataset) == expected + + +def test_every_shipped_model_has_a_resolver(): + shipped = {key for key in ModelRegistry.list() if not key.startswith("unit_test_")} # skip test doubles + + assert shipped + assert shipped <= set(ModelAutoResolver.list()) diff --git a/tests/implementations/models/test_schnet.py b/tests/implementations/models/test_schnet.py new file mode 100644 index 00000000..24d9e2df --- /dev/null +++ b/tests/implementations/models/test_schnet.py @@ -0,0 +1,147 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``schnet`` model.""" + +import pytest +import torch + +from xanesnet.models import ModelRegistry +from xanesnet.models.schnet.schnet import GaussianSmearing, ShiftedSoftplus + +CONFIG = { + "hidden_channels": 8, + "reduce_channels_1": 6, + "reduce_channels_2": 4, + "num_filters": 8, + "num_interactions": 2, + "num_gaussians": 10, + "cutoff": 4.0, + "mean_spectrum": None, +} + + +def create(**overrides): + return ModelRegistry.create("schnet", model_type="schnet", **{**CONFIG, **overrides}) + + +def graph(): + """Water: atomic numbers and a fully connected directed edge list.""" + z = torch.tensor([8, 1, 1]) + edge_index = torch.tensor([[0, 0, 1, 1, 2, 2], [1, 2, 0, 2, 0, 1]]) + edge_weight = torch.tensor([0.96, 0.96, 0.96, 1.5, 0.96, 1.5]) + return z, edge_index, edge_weight + + +def test_every_atom_gets_a_spectrum(): + out = create()(*graph()) + assert out.shape == (3, 4) + + +def test_the_signature_rebuilds_an_equivalent_model(): + model = create(mean_spectrum=[0.1, 0.2, 0.3, 0.4]) + + rebuilt = ModelRegistry.create("schnet", **model.signature.as_kwargs()) + + assert rebuilt.signature.as_dict() == {"model_type": "schnet", **CONFIG, "mean_spectrum": [0.1, 0.2, 0.3, 0.4]} + rebuilt.load_state_dict(model.state_dict()) + torch.testing.assert_close(rebuilt(*graph()), model(*graph())) + + +def test_the_mean_spectrum_is_added_to_every_prediction(): + plain = create() + shifted = create(mean_spectrum=[1.0, 2.0, 3.0, 4.0]) + shifted.load_state_dict({**plain.state_dict(), "mean_tensor": shifted.mean_tensor}, strict=True) + + difference = shifted(*graph()) - plain(*graph()) + + torch.testing.assert_close(difference, torch.tensor([[1.0, 2.0, 3.0, 4.0]]).expand(3, 4)) + + +def test_the_mean_spectrum_is_checkpointed_with_the_weights(): + assert "mean_tensor" in create(mean_spectrum=[0.0] * 4).state_dict() + assert "mean_tensor" not in create().state_dict() + + +def test_the_mean_spectrum_must_match_the_output_width(): + with pytest.raises(ValueError, match="mean_spectrum length must match reduce_channels_2"): + create(mean_spectrum=[0.0, 1.0]) + + +def test_predictions_do_not_depend_on_the_order_of_the_atoms(): + model = create().eval() + z, edge_index, edge_weight = graph() + permutation = torch.tensor([2, 0, 1]) # new position -> old atom + inverse = torch.argsort(permutation) + + out = model(z, edge_index, edge_weight) + permuted = model(z[permutation], inverse[edge_index], edge_weight) + + torch.testing.assert_close(permuted, out[permutation], atol=1e-5, rtol=1e-5) + + +def test_edges_beyond_the_cutoff_do_not_contribute(): + model = create(cutoff=2.0).eval() + z = torch.tensor([8, 1]) + near = model(z, torch.tensor([[0, 1], [1, 0]]), torch.tensor([1.0, 1.0])) + + # an extra pair at (or beyond) the cutoff gets a zero filter and does not change the result + far_z = torch.tensor([8, 1, 1]) + far_edges = torch.tensor([[0, 1, 0, 2], [1, 0, 2, 0]]) + far = model(far_z, far_edges, torch.tensor([1.0, 1.0, 2.0, 2.0])) + + torch.testing.assert_close(far[:2], near, atol=1e-5, rtol=1e-5) + + +def test_init_weights_covers_embeddings_interactions_and_output_layers(): + model = create() + + model.init_weights("normal", "zeros", mean=0.0, std=0.5) + + assert torch.equal(model.lin1.bias, torch.zeros_like(model.lin1.bias)) + assert torch.equal(model.lin2.bias, torch.zeros_like(model.lin2.bias)) + assert torch.equal(model.interactions[0].lin.bias, torch.zeros_like(model.interactions[0].lin.bias)) + assert model.lin1.weight.std().item() > 0 + + +def test_gaussian_smearing_expands_a_distance_into_a_peak_around_its_value(): + smearing = GaussianSmearing(0.0, 4.0, 5) + + values = smearing(torch.tensor([1.0, 2.5])) + + assert values.shape == (2, 5) + assert values[0].argmax().item() == 1 # centres are 0, 1, 2, 3, 4 + assert values[0, 1].item() == pytest.approx(1.0) + + +def test_gaussian_smearing_needs_at_least_two_centres(): + with pytest.raises(ValueError, match="num_gaussians must be at least 2"): + GaussianSmearing(0.0, 4.0, 1) + + +def test_shifted_softplus_is_zero_at_zero(): + assert ShiftedSoftplus()(torch.zeros(1)).item() == pytest.approx(0.0, abs=1e-7) diff --git a/tests/implementations/regularizers/__init__.py b/tests/implementations/regularizers/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/implementations/regularizers/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/implementations/regularizers/test_regularizers.py b/tests/implementations/regularizers/test_regularizers.py new file mode 100644 index 00000000..320b6cf5 --- /dev/null +++ b/tests/implementations/regularizers/test_regularizers.py @@ -0,0 +1,82 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the weight regularizers.""" + +import pytest +import torch + +from xanesnet.regularizers import Regularizer, RegularizerRegistry + + +@pytest.fixture +def model() -> torch.nn.Module: + layer = torch.nn.Linear(2, 2) + with torch.no_grad(): + layer.weight.copy_(torch.tensor([[1.0, -2.0], [3.0, -4.0]])) + layer.bias.copy_(torch.tensor([0.5, -0.5])) + return layer + + +def create(key: str, **kwargs) -> Regularizer: + return RegularizerRegistry.create(key, regularizer_type=key, **kwargs) + + +def test_l1_is_the_weighted_sum_of_absolute_parameter_values(model): + assert create("l1", weight=0.1)(model).item() == pytest.approx(0.1 * (1 + 2 + 3 + 4 + 0.5 + 0.5)) + + +def test_l2_is_the_weighted_sum_of_squared_parameter_values(model): + assert create("l2", weight=0.1)(model).item() == pytest.approx(0.1 * (1 + 4 + 9 + 16 + 0.25 + 0.25)) + + +@pytest.mark.parametrize("key", ["l1", "l2"]) +def test_the_penalty_is_differentiable_with_respect_to_the_parameters(model, key): + create(key, weight=1.0)(model).backward() + assert all(parameter.grad is not None for parameter in model.parameters()) + + +@pytest.mark.parametrize("key", ["no", "none"]) +def test_the_no_op_regularizer_adds_no_penalty(model, key): + penalty = create(key, weight=5.0)(model) + + assert penalty.dim() == 0 + assert penalty.item() == 0.0 + assert penalty.dtype == next(model.parameters()).dtype + + +def test_the_no_op_regularizer_has_a_default_weight(): + assert RegularizerRegistry.create("no", regularizer_type="no").weight == 1.0 + + +@pytest.mark.parametrize("key", ["l1", "l2", "no", "none"]) +def test_registered_regularizers_record_their_type_and_weight(key): + regularizer = create(key, weight=0.3) + + assert isinstance(regularizer, Regularizer) + assert regularizer.regularizer_type == key + assert regularizer.weight == 0.3 diff --git a/tests/implementations/stoppers/__init__.py b/tests/implementations/stoppers/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/implementations/stoppers/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/implementations/stoppers/test_stoppers.py b/tests/implementations/stoppers/test_stoppers.py new file mode 100644 index 00000000..cb9b968e --- /dev/null +++ b/tests/implementations/stoppers/test_stoppers.py @@ -0,0 +1,247 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the early stoppers (``basic``, ``time``, ``none``) and best-state restoring.""" + +from types import SimpleNamespace + +import pytest +import torch + +import xanesnet.stoppers.time as time_stopper +from xanesnet.components import LRSchedulerRegistry, OptimizerRegistry +from xanesnet.stoppers import EarlyStopper, EarlyStopperRegistry + + +class Training: + """A tiny model with optimizer and schedulers, as handed to ``EarlyStopper.step``.""" + + def __init__(self) -> None: + self.model = torch.nn.Linear(1, 1) + self.optimizer = OptimizerRegistry.create( + "sgd", optimizer_type="sgd", params=self.model.parameters(), lr=1.0, momentum=0.9 + ) + self.scheduler = LRSchedulerRegistry.create( + "step", lr_scheduler_type="step", optimizer=self.optimizer, last_epoch=-1, step_size=1, gamma=0.5 + ) + + def set_weight(self, value: float) -> None: + with torch.no_grad(): + self.model.weight.fill_(value) + + @property + def weight(self) -> float: + return self.model.weight.item() + + def advance(self) -> None: + """One epoch of optimizer/scheduler progress.""" + self.optimizer.torch_optimizer.step() + self.scheduler.step() + + def step(self, stopper: EarlyStopper, value: float, epoch: int) -> bool: + return stopper.step(value, self.model, epoch, self.optimizer, self.scheduler, None) # type: ignore[arg-type] + + def restore(self, stopper: EarlyStopper): + return stopper.restore(self.model, self.optimizer, self.scheduler, None) # type: ignore[arg-type] + + +@pytest.fixture +def training() -> Training: + return Training() + + +def create(key: str, restore_best: bool = False, **kwargs) -> EarlyStopper: + return EarlyStopperRegistry.create(key, early_stopper_type=key, restore_best=restore_best, **kwargs) + + +def run(training: Training, stopper: EarlyStopper, values: list[float]) -> list[bool]: + stopper.start() + return [training.step(stopper, value, epoch) for epoch, value in enumerate(values)] + + +############################################################################### +################################ BASIC STOPPER ################################ +############################################################################### + + +def test_basic_stopper_stops_after_patience_epochs_without_improvement(training): + stopper = create("basic", patience=2) + + decisions = run(training, stopper, [1.0, 0.9, 0.95, 0.96, 0.97]) + + assert decisions == [False, False, False, True, True] + assert (stopper.best_value, stopper.best_epoch) == (0.9, 1) + + +def test_an_improvement_resets_the_patience_counter(training): + stopper = create("basic", patience=2) + + decisions = run(training, stopper, [1.0, 1.1, 0.8, 0.9, 0.95]) + + assert decisions == [False, False, False, False, True] + assert stopper.best_epoch == 2 + + +def test_the_first_value_never_stops_training(training): + assert run(training, create("basic", patience=1), [5.0]) == [False] + + +def test_min_delta_scales_with_the_epochs_since_the_best_value(training): + stopper = create("basic", patience=100, min_delta=0.1) + + # best 1.0 at epoch 0: epoch 1 must beat 0.9, epoch 2 must beat 0.8 + run(training, stopper, [1.0, 0.95, 0.85]) + assert stopper.best_epoch == 0 + + run(training, stopper, [1.0, 0.95, 0.79]) + assert (stopper.best_epoch, stopper.best_value) == (2, 0.79) + + +def test_start_discards_progress_from_a_previous_run(training): + stopper = create("basic", patience=1) + run(training, stopper, [1.0, 2.0, 3.0]) + + stopper.start() + + assert (stopper.best_epoch, stopper.best_value, stopper.best_state) == (-1, float("inf"), None) + assert training.step(stopper, 10.0, 0) is False + + +############################################################################### +################################ OTHER STOPPERS ############################### +############################################################################### + + +def test_the_no_op_stopper_never_stops_but_still_tracks_the_best_value(training): + stopper = create("none") + + assert run(training, stopper, [3.0, 2.0, 5.0, 9.0, 9.0, 9.0]) == [False] * 6 + assert (stopper.best_value, stopper.best_epoch) == (2.0, 1) + + +def test_the_no_op_stopper_is_available_as_no_and_none(): + assert EarlyStopperRegistry.get("no") is EarlyStopperRegistry.get("none") + + +def test_time_stopper_stops_once_the_time_limit_is_exceeded(monkeypatch, training): + now = [100.0] + monkeypatch.setattr(time_stopper, "time", SimpleNamespace(time=lambda: now[0])) + stopper = create("time", time_limit_seconds=10.0) + stopper.start() + + now[0] = 105.0 + assert training.step(stopper, 1.0, 0) is False + now[0] = 110.0 + assert training.step(stopper, 1.0, 1) is False # exactly at the limit + now[0] = 110.5 + assert training.step(stopper, 1.0, 2) is True + + +def test_time_stopper_measures_from_start(monkeypatch, training): + now = [0.0] + monkeypatch.setattr(time_stopper, "time", SimpleNamespace(time=lambda: now[0])) + stopper = create("time", time_limit_seconds=10.0) + + now[0] = 1000.0 + stopper.start() + now[0] = 1005.0 + + assert training.step(stopper, 1.0, 0) is False + + +############################################################################### +############################## RESTORING BEST STATE ########################### +############################################################################### + + +def test_restore_returns_the_model_to_its_best_epoch(training): + stopper = create("none", restore_best=True) + stopper.start() + + training.set_weight(1.0) + training.step(stopper, 5.0, 0) + training.set_weight(2.0) + training.step(stopper, 3.0, 1) # best + training.set_weight(3.0) + training.step(stopper, 4.0, 2) + + assert training.restore(stopper) == (3.0, 1) + assert training.weight == 2.0 + + +def test_the_snapshot_is_independent_of_later_training(training): + stopper = create("none", restore_best=True) + stopper.start() + training.set_weight(7.0) + training.step(stopper, 1.0, 0) + + training.set_weight(-1.0) # continued training modifies the live parameters + + training.restore(stopper) + assert training.weight == 7.0 + + +def test_restore_also_rewinds_optimizer_and_scheduler_state(training): + stopper = create("none", restore_best=True) + stopper.start() + training.advance() + best_lr = training.optimizer.torch_optimizer.param_groups[0]["lr"] + training.step(stopper, 1.0, 0) + + training.advance() + training.advance() + assert training.optimizer.torch_optimizer.param_groups[0]["lr"] != best_lr + training.step(stopper, 2.0, 1) + + training.restore(stopper) + + assert training.optimizer.torch_optimizer.param_groups[0]["lr"] == best_lr + assert training.scheduler.state_dict()["last_epoch"] == 1 + + +def test_restore_is_a_no_op_unless_requested_and_available(training): + keep_last = create("none", restore_best=False) + keep_last.start() + training.set_weight(1.0) + training.step(keep_last, 1.0, 0) + training.set_weight(9.0) + + assert training.restore(keep_last) == (None, None) + assert training.weight == 9.0 + + never_stepped = create("none", restore_best=True) + never_stepped.start() + assert training.restore(never_stepped) == (None, None) + assert training.weight == 9.0 + + +def test_no_snapshot_is_kept_when_restoring_is_disabled(training): + stopper = create("none", restore_best=False) + run(training, stopper, [1.0]) + + assert stopper.best_state is None + assert stopper.best_training_state is None diff --git a/tests/implementations/strategies/__init__.py b/tests/implementations/strategies/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/implementations/strategies/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/implementations/strategies/conftest.py b/tests/implementations/strategies/conftest.py new file mode 100644 index 00000000..b44f6240 --- /dev/null +++ b/tests/implementations/strategies/conftest.py @@ -0,0 +1,177 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Fixtures shared by the strategy tests.""" + +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pytest + +from xanesnet.runners.inferencers import InferencerRegistry +from xanesnet.serialization.config import Config +from xanesnet.serialization.tensorboard import tb_logger +from xanesnet.strategies import StrategyRegistry + +from . import fakes + + +@pytest.fixture(autouse=True) +def events() -> Iterator[list]: + """Clear the fake-collaborator event log around every test. + + Yields: + The shared event log, empty before and after the test. + """ + fakes.EVENTS.clear() + yield fakes.EVENTS + fakes.EVENTS.clear() + + +@pytest.fixture(autouse=True) +def tensorboard_calls(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, Any]]: + """Record ``tb_logger`` usage instead of writing event files. + + Args: + monkeypatch: Pytest fixture used to replace logger operations. + + Returns: + Ordered ``(operation, path)`` calls made by the strategy. + """ + calls: list[tuple[str, Any]] = [] + monkeypatch.setattr(tb_logger, "new_run", lambda path: calls.append(("new_run", Path(path)))) + monkeypatch.setattr(tb_logger, "close", lambda: calls.append(("close", None))) + return calls + + +@pytest.fixture +def ensemble_inferencers(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, dict[str, Any]]]: + """Record registry requests for the hard-wired ensemble inferencer. + + Args: + monkeypatch: Pytest fixture used to replace the registry factory. + + Returns: + Ordered ``(registry_key, kwargs)`` requests made during the test. + """ + created: list[tuple[str, dict[str, Any]]] = [] + original = InferencerRegistry.create + + def create(key: str, **kwargs: Any) -> Any: + created.append((key, kwargs)) + return original(fakes.INFERENCER_TYPE, **kwargs) + + monkeypatch.setattr(InferencerRegistry, "create", create) + return created + + +@pytest.fixture +def model_config() -> Config: + """Provide the minimal fake model configuration. + + Returns: + Configuration for the registered fake model. + """ + return Config({"model_type": fakes.MODEL_TYPE, "width": 3}) + + +@pytest.fixture +def trainer_config() -> Config: + """Provide the minimal fake trainer configuration. + + Returns: + Configuration for the registered fake trainer. + """ + return Config({"trainer_type": fakes.TRAINER_TYPE, "epochs": 2}) + + +@pytest.fixture +def inferencer_config() -> Config: + """Provide the minimal fake inferencer configuration. + + Returns: + Configuration for the registered fake inferencer. + """ + return Config({"inferencer_type": fakes.INFERENCER_TYPE, "batch_size": 4}) + + +@pytest.fixture +def build(model_config: Config, trainer_config: Config, inferencer_config: Config): + """Provide a factory for strategies with fake collaborators. + + Args: + model_config: Configuration for the registered fake model. + trainer_config: Configuration for the registered fake trainer. + inferencer_config: Configuration for the registered fake inferencer. + + Returns: + Factory that creates a registry strategy for the requested key. + """ + + def factory(key: str, dataset: fakes.FakeDataset | None = None, **overrides: Any): + kwargs: dict[str, Any] = { + "strategy_type": key, + "dataset": dataset if dataset is not None else fakes.FakeDataset(), + "weight_init": "xavier", + "weight_init_params": Config({"gain": 2.0}), + "bias_init": "zeros", + "checkpoint_dir": None, + "checkpoint_interval": None, + "tensorboard_dir": None, + "trainer_config": trainer_config, + "inferencer_config": inferencer_config, + } + kwargs.update(overrides) + return StrategyRegistry.create(key, **kwargs) + + return factory + + +@pytest.fixture +def prepared(build, model_config: Config): + """Provide a factory for strategies set up without initializing trainers. + + Args: + build: Strategy factory supplied by the ``build`` fixture. + model_config: Configuration for the registered fake model. + + Returns: + Factory that creates a strategy with its model splits, encoding, models, + and checkpointer set up. + """ + + def factory(key: str, **kwargs: Any): + strategy = build(key, **kwargs) + strategy.setup_model_splits() + strategy.setup_encoding(fakes.ENCODING_CONFIG) + strategy.setup_models(model_config) + strategy.setup_checkpointer() + strategy.checkpointer = fakes.FakeCheckpointer() + return strategy + + return factory diff --git a/tests/implementations/strategies/fakes.py b/tests/implementations/strategies/fakes.py new file mode 100644 index 00000000..9f22808f --- /dev/null +++ b/tests/implementations/strategies/fakes.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Lightweight stand-ins for the collaborators of the strategies. + +They are registered under ``unit_test_*`` keys in the public registries; registry keys are permanent, so every fake +lives in this single module. +""" + +import copy +from types import SimpleNamespace +from typing import Any + +import torch + +from xanesnet.models import ModelRegistry +from xanesnet.runners.inferencers import InferencerRegistry +from xanesnet.runners.trainers import TrainerRegistry +from xanesnet.serialization.config import Config + +MODEL_TYPE = "unit_test_strategy_model" +TRAINER_TYPE = "unit_test_strategy_trainer" +INFERENCER_TYPE = "unit_test_strategy_inferencer" +N_ENERGIES = 6 + +EVENTS: list[tuple[str, Any]] = [] +"""Chronological ``(event, payload)`` log shared by the fakes; cleared before every test.""" + + +@ModelRegistry.register(MODEL_TYPE) +class FakeModel(torch.nn.Module): + """Registered model stand-in that records initialization calls.""" + + def __init__(self, **kwargs: Any) -> None: + super().__init__() + self.kwargs = kwargs + self.linear = torch.nn.Linear(1, 1) + self.init_calls: list[tuple[str, str, dict[str, Any]]] = [] + + def init_weights(self, weights_init: str, bias_init: str, **kwargs: Any) -> None: + self.init_calls.append((weights_init, bias_init, kwargs)) + + @property + def signature(self) -> Config: + return Config({"model_type": MODEL_TYPE, **self.kwargs}) + + +@TrainerRegistry.register(TRAINER_TYPE) +class FakeTrainer: + """Registered trainer stand-in that records training calls.""" + + def __init__(self, **kwargs: Any) -> None: + self.kwargs = kwargs + self.model = kwargs["model"] + self.dataset = kwargs["dataset"] + EVENTS.append(("trainer_created", self)) + + def train(self) -> None: + EVENTS.append(("train", self)) + if getattr(self.model, "fail_on_train", False): + raise RuntimeError("training failed") + + +@InferencerRegistry.register(INFERENCER_TYPE) +class FakeInferencer: + """Registered inferencer stand-in that records inference calls.""" + + def __init__(self, **kwargs: Any) -> None: + self.kwargs = kwargs + + def infer(self, predictions_save_path: Any) -> None: + EVENTS.append(("infer", predictions_save_path)) + + +class FakeDataset: + """Minimal dataset with the split API the strategies rely on.""" + + def __init__(self, size: int = 10, plans: list[list[list[int]]] | None = None, indexfile: bool = False) -> None: + self.size = size + self.configured_plans = plans if plans is not None else [[list(range(size - 2)), [size - 2, size - 1]]] + self.has_split_indexfile = indexfile + self._subsets: list[list[list[int]]] = [] + + def __len__(self) -> int: + return self.size + + def __getitem__(self, index: int) -> SimpleNamespace: + return SimpleNamespace(energies=torch.arange(N_ENERGIES, dtype=torch.float32)) + + @property + def signature(self) -> Config: + return Config({"dataset_type": "fake"}) + + def setup_splits(self) -> list[list[list[int]]]: + self.set_splits(self.configured_plans) + return self.configured_plans + + def set_splits(self, plans: list[list[list[int]]]) -> None: + self._subsets = [[list(indices) for indices in plan] for plan in plans] + + def get_dataset(self, idx: int) -> "FakeDataset": + view = copy.copy(self) + view._subsets = [self._subsets[idx]] + return view + + def get_subset_indices(self, index: int) -> list[int] | None: + if not self._subsets or index >= len(self._subsets[0]): + return None + return list(self._subsets[0][index]) + + @property + def train_subset(self) -> list[int] | None: + return self.get_subset_indices(0) + + @property + def plans(self) -> list[list[list[int]]]: + return self._subsets + + +def event_names() -> list[str]: + """Return fake-collaborator event names in chronological order. + + Returns: + Event names, including repeated events. + """ + return [name for name, _ in EVENTS] + + +class FakeCheckpointer: + """Records ``finish_member`` instead of collecting real optimizer/scheduler state.""" + + def finish_member(self, trainer: Any) -> None: + EVENTS.append(("finish_member", trainer)) + + +ENCODING_CONFIG = Config({"model": {"model_type": MODEL_TYPE}, "encodings": [{"encoding_type": "none"}]}) diff --git a/tests/implementations/strategies/test_multi_model_strategies.py b/tests/implementations/strategies/test_multi_model_strategies.py new file mode 100644 index 00000000..ae17e26b --- /dev/null +++ b/tests/implementations/strategies/test_multi_model_strategies.py @@ -0,0 +1,210 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the lifecycle shared by the multi-model strategies (``deep_ensemble``, ``bootstrap``, ``kfold``).""" + +from pathlib import Path + +import pytest + +from . import fakes + +N_MODELS = 3 + +# strategy key -> (constructor arguments, tensorboard sub-directory prefix) +STRATEGIES = { + "deep_ensemble": ({"n_models": N_MODELS}, "model_"), + "bootstrap": ({"n_models": N_MODELS, "sample_fraction": 1.0}, "model_"), + "kfold": ({"n_splits": N_MODELS, "n_repeats": 1}, "fold_"), +} + + +@pytest.fixture(params=list(STRATEGIES)) +def key(request) -> str: + return request.param + + +@pytest.fixture +def extra(key): + return STRATEGIES[key][0] + + +@pytest.fixture +def tb_prefix(key): + return STRATEGIES[key][1] + + +def ready(prepared, key: str, extra: dict, **kwargs): + return prepared(key, dataset=fakes.FakeDataset(size=9), **extra, **kwargs) + + +def test_one_independent_model_is_created_per_member(build, key, extra, model_config): + strategy = build(key, **extra) + + strategy.setup_models(model_config) + + assert strategy.n_models == N_MODELS + assert len(strategy.models) == N_MODELS + assert len({id(model) for model in strategy.models}) == N_MODELS + assert all(model.kwargs == {"model_type": fakes.MODEL_TYPE, "width": 3} for model in strategy.models) + + +def test_each_trainer_gets_its_own_model_and_its_own_split(prepared, key, extra): + strategy = ready(prepared, key, extra) + + strategy.setup_trainers("cpu") + + assert len(strategy.trainers) == N_MODELS + for index, trainer in enumerate(strategy.trainers): + assert trainer.model is strategy.models[index] + assert trainer.kwargs["device"] == "cpu" + assert trainer.kwargs["epochs"] == 2 + assert trainer.dataset.get_subset_indices(0) == strategy.dataset.plans[index][0] + + +@pytest.mark.parametrize( + ("missing", "message"), + [ + ("models", "models are not initialized"), + ("trainer_config", "no trainer config"), + ("checkpointer", "checkpointer is not instantiated"), + ("encoding", "encoding is not initialized"), + ], +) +def test_trainers_need_every_prerequisite(prepared, key, extra, missing, message): + strategy = ready(prepared, key, extra) + setattr(strategy, missing, [] if missing == "models" else None) + + with pytest.raises(ValueError, match=message): + strategy.setup_trainers("cpu") + + +def test_members_are_trained_in_order_and_each_is_recorded_as_finished(prepared, key, extra, events): + strategy = ready(prepared, key, extra) + strategy.setup_trainers("cpu") + trainers = list(strategy.trainers) + + models = strategy.run_training() + + assert models is strategy.models + sequence = [(name, trainer) for name, trainer in events if name in {"train", "finish_member"}] + assert sequence == [(name, trainer) for trainer in trainers for name in ("train", "finish_member")] + + +def test_finished_trainers_are_released(prepared, key, extra): + strategy = ready(prepared, key, extra) + strategy.setup_trainers("cpu") + + strategy.run_training() + + assert strategy.trainers == [None] * N_MODELS + + +def test_every_member_logs_to_its_own_tensorboard_directory( + prepared, key, extra, tb_prefix, tensorboard_calls, tmp_path +): + strategy = ready(prepared, key, extra, tensorboard_dir=tmp_path / "tb") + strategy.setup_trainers("cpu") + + strategy.run_training() + + expected = [] + for index in range(N_MODELS): + expected += [("new_run", tmp_path / "tb" / f"{tb_prefix}{index}"), ("close", None)] + assert tensorboard_calls == expected + + +def test_a_failing_member_stops_training_but_is_still_cleaned_up(prepared, key, extra, events, tensorboard_calls): + strategy = ready(prepared, key, extra) + strategy.models[0].fail_on_train = True + strategy.setup_trainers("cpu") + second_trainer = strategy.trainers[1] + + with pytest.raises(RuntimeError, match="training failed"): + strategy.run_training() + + assert strategy.trainers[0] is None + assert strategy.trainers[1] is second_trainer + assert [name for name, _ in events if name == "train"] == ["train"] + assert "finish_member" not in [name for name, _ in events] + assert tensorboard_calls[-1] == ("close", None) + + +@pytest.mark.parametrize("problem", ["no_models", "missing_trainer", "no_checkpointer"]) +def test_training_needs_a_trainer_for_every_model(prepared, key, extra, problem): + strategy = ready(prepared, key, extra) + strategy.setup_trainers("cpu") + if problem == "no_models": + strategy.models = [] + elif problem == "missing_trainer": + strategy.trainers[1] = None + else: + strategy.checkpointer = None + + with pytest.raises(ValueError, match="Cannot run training"): + strategy.run_training() + + +############################################################################### +################################### INFERENCE ################################# +############################################################################### + + +def test_inference_uses_an_ensemble_inferencer_over_all_models(prepared, key, extra, ensemble_inferencers, events): + strategy = ready(prepared, key, extra) + + strategy.setup_inferencers("cpu") + strategy.run_inference(Path("out")) + + ((inferencer_key, kwargs),) = ensemble_inferencers + assert inferencer_key == "ensemble" + assert kwargs["models"] is strategy.models + assert kwargs["dataset"] is strategy.dataset + assert kwargs["encoding"] is strategy.encoding + assert kwargs["batch_size"] == 4 + assert ("infer", Path("out")) in events + + +@pytest.mark.parametrize( + ("missing", "message"), + [ + ("models", "models are not initialized"), + ("inferencer_config", "no inferencer config"), + ("encoding", "encoding is not initialized"), + ], +) +def test_inferencers_need_every_prerequisite(prepared, key, extra, ensemble_inferencers, missing, message): + strategy = ready(prepared, key, extra) + setattr(strategy, missing, [] if missing == "models" else None) + + with pytest.raises(ValueError, match=message): + strategy.setup_inferencers("cpu") + + +def test_inference_needs_an_inferencer(build, key, extra): + with pytest.raises(ValueError, match="Inferencer is not initialized"): + build(key, **extra).run_inference(None) diff --git a/tests/implementations/strategies/test_single_strategy.py b/tests/implementations/strategies/test_single_strategy.py new file mode 100644 index 00000000..865a827a --- /dev/null +++ b/tests/implementations/strategies/test_single_strategy.py @@ -0,0 +1,173 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``single`` strategy (one model, one trainer).""" + +from pathlib import Path + +import pytest + +from . import fakes + + +def test_the_model_is_created_from_the_model_config(build, model_config): + strategy = build("single") + + strategy.setup_models(model_config) + + assert len(strategy.models) == 1 + assert isinstance(strategy.models[0], fakes.FakeModel) + assert strategy.models[0].kwargs == {"model_type": fakes.MODEL_TYPE, "width": 3} + + +def test_the_trainer_receives_its_collaborators_and_the_trainer_config(prepared): + strategy = prepared("single") + + strategy.setup_trainers("cpu") + + (trainer,) = strategy.trainers + assert trainer.kwargs["trainer_type"] == fakes.TRAINER_TYPE + assert trainer.kwargs["epochs"] == 2 + assert trainer.kwargs["model"] is strategy.models[0] + assert trainer.kwargs["device"] == "cpu" + assert trainer.kwargs["checkpointer"] is strategy.checkpointer + assert trainer.kwargs["encoding"] is strategy.encoding + assert trainer.dataset.get_subset_indices(0) == strategy.dataset.get_subset_indices(0) + + +@pytest.mark.parametrize( + ("missing", "message"), + [ + ("models", "model is not initialized"), + ("trainer_config", "no trainer config"), + ("checkpointer", "checkpointer is not instantiated"), + ("encoding", "encoding is not initialized"), + ], +) +def test_trainers_need_every_prerequisite(prepared, missing, message): + strategy = prepared("single") + setattr(strategy, missing, [] if missing == "models" else None) + + with pytest.raises(ValueError, match=message): + strategy.setup_trainers("cpu") + + +def test_training_runs_the_trainer_then_records_the_finished_member(prepared, events): + strategy = prepared("single") + strategy.setup_trainers("cpu") + + models = strategy.run_training() + + assert models is strategy.models + assert [name for name, _ in events if name != "trainer_created"] == ["train", "finish_member"] + + +def test_tensorboard_is_only_used_when_a_directory_is_configured(prepared, tensorboard_calls, tmp_path): + silent = prepared("single") + silent.setup_trainers("cpu") + silent.run_training() + assert [name for name, _ in tensorboard_calls] == ["close"] + + tensorboard_calls.clear() + logged = prepared("single", tensorboard_dir=tmp_path / "tb") + logged.setup_trainers("cpu") + logged.run_training() + assert tensorboard_calls == [("new_run", tmp_path / "tb"), ("close", None)] + + +def test_tensorboard_is_closed_when_training_fails(prepared, tensorboard_calls, events): + strategy = prepared("single") + strategy.models[0].fail_on_train = True + strategy.setup_trainers("cpu") + + with pytest.raises(RuntimeError, match="training failed"): + strategy.run_training() + + assert tensorboard_calls[-1] == ("close", None) + assert "finish_member" not in [name for name, _ in events] + + +@pytest.mark.parametrize("missing", ["trainers", "models", "checkpointer"]) +def test_training_needs_trainers_models_and_a_checkpointer(prepared, missing): + strategy = prepared("single") + strategy.setup_trainers("cpu") + setattr(strategy, missing, None if missing == "checkpointer" else []) + + with pytest.raises(ValueError, match="Cannot run training"): + strategy.run_training() + + +############################################################################### +################################### INFERENCE ################################# +############################################################################### + + +def test_the_inferencer_is_chosen_by_the_config_and_receives_the_model(build, model_config, inferencer_config): + strategy = build("single", trainer_config=None) + strategy.setup_encoding(fakes.ENCODING_CONFIG) + strategy.setup_models(model_config) + + strategy.setup_inferencers("cpu") + + kwargs = strategy.inferencer.kwargs + assert kwargs["batch_size"] == 4 + assert kwargs["model"] is strategy.models[0] + assert kwargs["dataset"] is strategy.dataset + assert kwargs["device"] == "cpu" + assert kwargs["encoding"] is strategy.encoding + + +@pytest.mark.parametrize( + ("missing", "message"), + [ + ("models", "model is not initialized"), + ("inferencer_config", "no inferencer config"), + ("encoding", "encoding is not initialized"), + ], +) +def test_inferencers_need_every_prerequisite(prepared, missing, message): + strategy = prepared("single") + setattr(strategy, missing, [] if missing == "models" else None) + + with pytest.raises(ValueError, match=message): + strategy.setup_inferencers("cpu") + + +def test_inference_delegates_to_the_inferencer(build, model_config, events): + strategy = build("single", trainer_config=None) + strategy.setup_encoding(fakes.ENCODING_CONFIG) + strategy.setup_models(model_config) + strategy.setup_inferencers("cpu") + + strategy.run_inference(Path("out")) + + assert ("infer", Path("out")) in events + + +def test_inference_needs_an_inferencer(build): + with pytest.raises(ValueError, match="Inferencer is not initialized"): + build("single").run_inference(None) diff --git a/tests/implementations/strategies/test_snapshot_ensemble.py b/tests/implementations/strategies/test_snapshot_ensemble.py new file mode 100644 index 00000000..49744178 --- /dev/null +++ b/tests/implementations/strategies/test_snapshot_ensemble.py @@ -0,0 +1,50 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``snapshot_ensemble`` strategy, which is registered but not implemented yet.""" + +import pytest + +from xanesnet.serialization.config import Config + + +@pytest.mark.parametrize( + "operation", + [ + lambda strategy: strategy.setup_models(Config({})), + lambda strategy: strategy.init_model_weights(), + lambda strategy: strategy.set_state_dicts([]), + lambda strategy: strategy.setup_trainers("cpu"), + lambda strategy: strategy.run_training(), + lambda strategy: strategy.setup_inferencers("cpu"), + lambda strategy: strategy.run_inference(None), + lambda strategy: strategy.model_signature, + ], +) +def test_every_stage_reports_that_it_is_not_implemented(build, operation): + with pytest.raises(NotImplementedError, match="Not implemented"): + operation(build("snapshot_ensemble")) diff --git a/tests/implementations/strategies/test_split_strategies.py b/tests/implementations/strategies/test_split_strategies.py new file mode 100644 index 00000000..119b7199 --- /dev/null +++ b/tests/implementations/strategies/test_split_strategies.py @@ -0,0 +1,173 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the data splits that ``deep_ensemble``, ``bootstrap``, ``kfold`` create for their members.""" + +import pytest + +from xanesnet.utils.exceptions import ConfigError + +from . import fakes + + +############################################################################### +################################ DEEP ENSEMBLE ################################ +############################################################################### + + +def test_deep_ensemble_members_share_the_single_configured_split(build): + dataset = fakes.FakeDataset(size=6, plans=[[[0, 1, 2, 3], [4, 5]]]) + + splits = build("deep_ensemble", dataset, n_models=3).setup_model_splits() + + assert splits == [[[0, 1, 2, 3], [4, 5]]] * 3 + assert dataset.plans == splits + + +def test_deep_ensemble_keeps_explicit_per_member_splits(build): + plans = [[[0, 1], [2]], [[1, 2], [0]]] + dataset = fakes.FakeDataset(size=3, plans=plans) + + assert build("deep_ensemble", dataset, n_models=2).setup_model_splits() == plans + + +############################################################################### +################################## BOOTSTRAP ################################## +############################################################################### + + +def test_bootstrap_resamples_the_training_subset_with_replacement_for_every_member(build): + dataset = fakes.FakeDataset(size=10, plans=[[list(range(8)), [8, 9]]]) + + splits = build("bootstrap", dataset, n_models=4, sample_fraction=1.0).setup_model_splits() + + assert len(splits) == 4 + for train, valid in splits: + assert len(train) == 8 + assert set(train) <= set(range(8)) + assert valid == [8, 9] # validation data is never resampled + assert len({tuple(train) for train, _ in splits}) > 1 + assert dataset.plans == splits + + +@pytest.mark.parametrize(("fraction", "expected"), [(0.5, 4), (0.25, 2), (0.01, 1)]) +def test_bootstrap_sample_size_follows_the_fraction_with_a_minimum_of_one(build, fraction, expected): + dataset = fakes.FakeDataset(size=10, plans=[[list(range(8)), [8, 9]]]) + + splits = build("bootstrap", dataset, n_models=2, sample_fraction=fraction).setup_model_splits() + + assert [len(train) for train, _ in splits] == [expected] * 2 + + +def test_bootstrap_without_a_validation_subset_returns_only_training_samples(build): + dataset = fakes.FakeDataset(size=5, plans=[[list(range(5))]]) + + splits = build("bootstrap", dataset, n_models=2, sample_fraction=1.0).setup_model_splits() + + assert all(len(plan) == 1 for plan in splits) + + +def test_bootstrap_uses_the_whole_dataset_when_no_split_is_configured(build): + dataset = fakes.FakeDataset(size=5, plans=[]) + + splits = build("bootstrap", dataset, n_models=2, sample_fraction=1.0).setup_model_splits() + + assert all(len(plan[0]) == 5 and set(plan[0]) <= set(range(5)) for plan in splits) + + +def test_bootstrap_with_an_empty_training_subset_is_rejected(build): + dataset = fakes.FakeDataset(size=2, plans=[[[], [0, 1]]]) + + with pytest.raises(ConfigError, match="non-empty training subset"): + build("bootstrap", dataset, n_models=2, sample_fraction=1.0).setup_model_splits() + + +def test_bootstrap_respects_an_explicit_split_index_file(build): + plans = [[[0, 1], [2]], [[1, 2], [0]]] + dataset = fakes.FakeDataset(size=3, plans=plans, indexfile=True) + + assert build("bootstrap", dataset, n_models=2, sample_fraction=1.0).setup_model_splits() == plans + + +############################################################################### +#################################### KFOLD #################################### +############################################################################### + + +def test_kfold_creates_n_splits_times_n_repeats_members(build): + strategy = build("kfold", fakes.FakeDataset(size=10), n_splits=3, n_repeats=2) + + splits = strategy.setup_model_splits() + + assert strategy.n_models == 6 + assert len(splits) == 6 + + +@pytest.mark.parametrize(("size", "n_splits"), [(10, 5), (11, 3), (7, 7)]) +def test_every_sample_is_validated_exactly_once_per_repeat(build, size, n_splits): + dataset = fakes.FakeDataset(size=size) + + splits = build("kfold", dataset, n_splits=n_splits, n_repeats=2).setup_model_splits() + + for repeat in (splits[:n_splits], splits[n_splits:]): + validation = [index for _, valid in repeat for index in valid] + assert sorted(validation) == list(range(size)) + for train, valid in splits: + assert sorted(train + valid) == list(range(size)) + assert not set(train) & set(valid) + assert dataset.plans == splits + + +def test_repeats_use_different_shuffles(build): + splits = build("kfold", fakes.FakeDataset(size=30), n_splits=3, n_repeats=2).setup_model_splits() + + first_repeat = [tuple(valid) for _, valid in splits[:3]] + second_repeat = [tuple(valid) for _, valid in splits[3:]] + assert first_repeat != second_repeat + + +def test_kfold_requires_at_least_one_validation_sample_per_fold(build): + with pytest.raises(ConfigError, match="n_splits=5 exceeds the dataset size 3"): + build("kfold", fakes.FakeDataset(size=3), n_splits=5, n_repeats=1).setup_model_splits() + + +def test_kfold_respects_an_explicit_split_index_file(build): + plans = [[[0, 1], [2]], [[1, 2], [0]]] + dataset = fakes.FakeDataset(size=3, plans=plans, indexfile=True) + + assert build("kfold", dataset, n_splits=2, n_repeats=1).setup_model_splits() == plans + + +def test_kfold_derives_encoding_statistics_from_all_samples_without_touching_the_dataset_splits(build): + dataset = fakes.FakeDataset(size=9) + strategy = build("kfold", dataset, n_splits=3, n_repeats=1) + splits = strategy.setup_model_splits() + + encoding_dataset = strategy._dataset_for_encoding() + + assert encoding_dataset.get_subset_indices(0) == list(range(9)) + assert dataset.plans == splits diff --git a/tests/unit/batchprocessors/__init__.py b/tests/unit/batchprocessors/__init__.py new file mode 100644 index 00000000..07cbae47 --- /dev/null +++ b/tests/unit/batchprocessors/__init__.py @@ -0,0 +1,28 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for shared batch-processor contracts.""" diff --git a/tests/unit/batchprocessors/test_batchprocessor_base.py b/tests/unit/batchprocessors/test_batchprocessor_base.py new file mode 100644 index 00000000..d60350d7 --- /dev/null +++ b/tests/unit/batchprocessors/test_batchprocessor_base.py @@ -0,0 +1,175 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for shared forward and inverse batch-processor behavior.""" + +from types import SimpleNamespace +from typing import Any + +import numpy as np +import pytest +import torch + +from xanesnet.batchprocessors import ( + BatchProcessor, + ForwardBatchProcessor, + InverseBatchProcessor, +) + + +class RecordingEncoding: + """Encoding stub that scales tensors and records element metadata.""" + + def __init__(self) -> None: + self.elements: list[torch.Tensor | None] = [] + + def encode(self, targets: torch.Tensor, elements: torch.Tensor | None = None) -> torch.Tensor: + self.elements.append(elements) + return targets * 2 + + def decode(self, predictions: torch.Tensor, elements: torch.Tensor | None = None) -> torch.Tensor: + self.elements.append(elements) + return predictions / 2 + + +class MinimalForward(ForwardBatchProcessor): + """Forward processor stub that extracts toy inputs and targets from a batch.""" + + def input_preparation(self, batch: Any) -> dict[str, Any]: + return {"x": batch.x} + + def target_preparation(self, batch: Any) -> torch.Tensor: + return batch.y + + def sample_id_preparation(self, batch: Any) -> np.ndarray: + return np.array(batch.sample_id) + + +class MinimalInverse(InverseBatchProcessor): + """Inverse processor stub reusing the forward test batch fields.""" + + input_preparation = MinimalForward.input_preparation + target_preparation = MinimalForward.target_preparation + sample_id_preparation = MinimalForward.sample_id_preparation + + +SPECTRA = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) +ELEMENTS = torch.tensor([26, 29]) + + +def test_base_class_is_abstract(): + with pytest.raises(TypeError): + BatchProcessor() # type: ignore[abstract] + + +def test_defaults_pass_predictions_through_and_provide_no_elements(): + processor = MinimalForward() + batch = SimpleNamespace(x=1, y=2, sample_id=["a"]) + + assert processor.prediction_preparation(batch, SPECTRA) is SPECTRA + assert processor.element_preparation(batch) is None + assert processor.target_site_index_preparation(batch) is None + assert processor.target_site_index_preparation(SimpleNamespace(target_site_index=5)) == 5 + + +def test_single_sample_helpers_collate_the_sample_into_a_batch_first(): + class Dataset: + """Single-sample dataset that collates values into a namespace.""" + + def __getitem__(self, index: int) -> dict[str, int]: + return {"index": index} + + def collate_fn(self, samples: list[dict[str, int]]) -> SimpleNamespace: + (sample,) = samples + return SimpleNamespace( + x=sample["index"] * 10, + y=torch.tensor(sample["index"] * 100), + sample_id=[str(sample["index"])], + ) + + processor = MinimalForward() + + assert processor.input_preparation_single(Dataset(), 3) == {"x": 30} # type: ignore[arg-type] + torch.testing.assert_close(processor.target_preparation_single(Dataset(), 3), torch.tensor(300)) # type: ignore[arg-type] + assert processor.element_preparation_single(Dataset(), 3) is None # type: ignore[arg-type] + + +def test_forward_processors_encode_targets_and_decode_predictions_with_elements(): + encoding = RecordingEncoding() + processor = MinimalForward(encoding) # type: ignore[arg-type] + + torch.testing.assert_close(processor.encode_target(SPECTRA, ELEMENTS), SPECTRA * 2) + torch.testing.assert_close(processor.decode_target(SPECTRA, ELEMENTS), SPECTRA / 2) + assert all(elements is ELEMENTS for elements in encoding.elements) + + +def test_forward_processors_leave_inputs_alone(): + inputs = {"x": SPECTRA} + assert MinimalForward(RecordingEncoding()).encode_input(inputs, ELEMENTS) is inputs # type: ignore[arg-type] + + +def test_forward_processors_without_encoding_are_the_identity(): + processor = MinimalForward() + + assert processor.encode_target(SPECTRA) is SPECTRA + assert processor.decode_target(SPECTRA) is SPECTRA + + +def test_inverse_processors_encode_spectral_inputs_without_modifying_original_inputs(): + encoding = RecordingEncoding() + inputs = {"x": SPECTRA, "other": ELEMENTS} + + encoded = MinimalInverse(encoding).encode_input(inputs, ELEMENTS) # type: ignore[arg-type] + + torch.testing.assert_close(encoded["x"], SPECTRA * 2) + assert encoded["other"] is ELEMENTS + assert inputs["x"] is SPECTRA + assert encoding.elements == [ELEMENTS] + + +def test_inverse_processors_use_the_configured_spectra_input_key(): + class Custom(MinimalInverse): + """Inverse processor whose encoded spectrum uses a custom field name.""" + + spectra_input_key = "spectrum" + + encoded = Custom(RecordingEncoding()).encode_input({"spectrum": SPECTRA, "x": SPECTRA}) # type: ignore[arg-type] + + torch.testing.assert_close(encoded["spectrum"], SPECTRA * 2) + assert encoded["x"] is SPECTRA + + +def test_inverse_processors_never_transform_targets_or_predictions(): + processor = MinimalInverse(RecordingEncoding()) # type: ignore[arg-type] + + assert processor.encode_target(SPECTRA) is SPECTRA + assert processor.decode_target(SPECTRA) is SPECTRA + + +def test_inverse_processors_without_encoding_are_the_identity(): + inputs = {"x": SPECTRA} + assert MinimalInverse().encode_input(inputs) is inputs diff --git a/tests/unit/checkpointing/__init__.py b/tests/unit/checkpointing/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/unit/checkpointing/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/unit/checkpointing/test_checkpointer.py b/tests/unit/checkpointing/test_checkpointer.py new file mode 100644 index 00000000..c6945e39 --- /dev/null +++ b/tests/unit/checkpointing/test_checkpointer.py @@ -0,0 +1,300 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for ``Checkpointer``: state collection, periodic saving and member bookkeeping.""" + +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import pytest +import torch + +from xanesnet.checkpointing import Checkpointer +from xanesnet.checkpointing.checkpointer import state_to_cpu +from xanesnet.serialization.checkpoints import Checkpoint +from xanesnet.serialization.config import Config + +############################################################################### +################################# TEST DOUBLES ################################ +############################################################################### + + +class _Component: + def __init__(self, signature: dict[str, Any], state: dict[str, Any]) -> None: + self.signature = Config(signature) + self._state = state + + def state_dict(self) -> dict[str, Any]: + return dict(self._state) + + +@dataclass +class FakeTrainer: + model: torch.nn.Linear + completed_epochs: int + optimizer: _Component + epoch_lr_scheduler: _Component + warmup_lr_scheduler: _Component | None + + +def make_trainer(seed: int = 0, epochs: int = 3, warmup: bool = False, lr: float = 0.1) -> FakeTrainer: + """Create a trainer double with serializable model and scheduler state. + + Args: + seed: Random seed used to initialize the test model. + epochs: Completed epoch count recorded by the trainer. + warmup: Whether to include a warmup scheduler. + lr: Learning rate recorded in the optimizer signature. + + Returns: + Trainer-like namespace with a model, optimizer, and schedulers. + """ + torch.manual_seed(seed) + return FakeTrainer( + model=torch.nn.Linear(2, 2), + completed_epochs=epochs, + optimizer=_Component({"optimizer_type": "adam", "lr": lr}, {"step": torch.tensor(float(epochs))}), + epoch_lr_scheduler=_Component({"lr_scheduler_type": "step"}, {"last_epoch": epochs}), + warmup_lr_scheduler=_Component({"lr_scheduler_type": "linear"}, {"last_epoch": 1}) if warmup else None, + ) + + +@pytest.fixture +def signature() -> Config: + """Provide the minimal model signature for checkpoint tests. + + Returns: + Config identifying the test MLP model. + """ + return Config({"model": {"model_type": "mlp"}}) + + +def make_checkpointer( + signature: Config, + trainers: Sequence[Any], + save_dir: str | Path | None = None, + save_interval: int | None = None, +) -> Checkpointer: + """Create a checkpointer backed by the supplied trainer list. + + Args: + signature: Model and dataset signature to store in checkpoints. + trainers: Trainers returned by the checkpointer's provider. + save_dir: Optional directory for periodic checkpoints. + save_interval: Optional interval between periodic saves. + + Returns: + Checkpointer configured with the supplied signature and trainers. + """ + return Checkpointer(save_dir, save_interval, signature, trainer_provider=lambda: trainers) + + +def training_state(checkpoint: Checkpoint) -> dict[str, Any]: + assert checkpoint.training_state is not None + return checkpoint.training_state + + +############################################################################### +################################## state_to_cpu ############################### +############################################################################### + + +def test_tensors_are_copied_so_snapshots_do_not_follow_in_place_updates(): + # On CPU ``.cpu()`` is a no-op, so only the explicit clone protects the snapshot. + original = torch.ones(3) + copied = state_to_cpu(original) + + assert copied.data_ptr() != original.data_ptr() + original.fill_(5.0) + assert torch.equal(copied, torch.ones(3)) + + +def test_nested_structures_are_rebuilt_with_the_same_shape(): + state = {"a": [torch.zeros(1), (torch.ones(1), 3)], "b": {"c": "text", "d": None}} + copied = state_to_cpu(state) + + assert isinstance(copied["a"], list) + assert isinstance(copied["a"][1], tuple) + assert copied["a"][1][1] == 3 + assert copied["b"] == {"c": "text", "d": None} + + +############################################################################### +################################### SNAPSHOT ################################## +############################################################################### + + +def test_snapshot_collects_one_entry_per_member(signature): + trainers = [make_trainer(seed=0, epochs=2), make_trainer(seed=1, epochs=5)] + checkpoint = make_checkpointer(signature, trainers).snapshot() + + assert isinstance(checkpoint, Checkpoint) + assert checkpoint.signature is signature + assert len(checkpoint.model_states) == 2 + state = training_state(checkpoint) + assert state["epochs"] == [2, 5] + assert len(state["optimizer_states"]) == 2 + assert [s["last_epoch"] for s in state["epoch_scheduler_states"]] == [2, 5] + + +def test_snapshot_is_independent_of_later_training(signature): + trainer = make_trainer() + checkpointer = make_checkpointer(signature, [trainer]) + checkpoint = checkpointer.snapshot() + + with torch.no_grad(): + trainer.model.weight.fill_(42.0) + + assert not torch.equal(checkpoint.model_states[0]["weight"], trainer.model.weight) + + +def test_component_signatures_are_captured_from_the_first_trainer(signature): + trainers = [make_trainer(seed=0, lr=0.1), make_trainer(seed=1, lr=0.5)] + checkpoint = make_checkpointer(signature, trainers).snapshot() + + state = training_state(checkpoint) + assert state["optimizer_signature"] == {"trainer": {"optimizer_type": "adam", "lr": 0.1}} + assert state["scheduler_signature"] == { + "trainer": {"lr_scheduler": {"lr_scheduler_type": "step"}, "lr_warmup": False} + } + + +@pytest.mark.parametrize("warmup", [False, True]) +def test_warmup_state_is_only_recorded_when_a_warmup_scheduler_exists(signature, warmup): + checkpoint = make_checkpointer(signature, [make_trainer(warmup=warmup)]).snapshot() + + state = training_state(checkpoint) + warmup_state = state["warmup_scheduler_states"][0] + assert (warmup_state is not None) is warmup + assert state["scheduler_signature"]["trainer"]["lr_warmup"] is warmup + + +############################################################################### +############################## MEMBER BOOKKEEPING ############################# +############################################################################### + + +def test_finished_members_are_served_from_their_cached_state(signature): + first, second = make_trainer(seed=0, epochs=4), make_trainer(seed=1, epochs=1) + trainers: list[FakeTrainer | None] = [first, second] + checkpointer = make_checkpointer(signature, trainers) + + expected_first = {k: v.clone() for k, v in first.model.state_dict().items()} + checkpointer.finish_member(first) # type: ignore[arg-type] + trainers[0] = None # the strategy releases the finished trainer + + checkpoint = checkpointer.snapshot() + + assert training_state(checkpoint)["epochs"] == [4, 1] + for name, tensor in expected_first.items(): + assert torch.equal(checkpoint.model_states[0][name], tensor) + + +def test_cached_state_wins_over_a_still_present_trainer(signature): + trainer = make_trainer(epochs=2) + checkpointer = make_checkpointer(signature, [trainer]) + checkpointer.finish_member(trainer) # type: ignore[arg-type] + trainer.completed_epochs = 99 # later mutation must not alter the cached snapshot + + assert training_state(checkpointer.snapshot())["epochs"] == [2] + + +############################################################################### +################################### SAVING #################################### +############################################################################### + + +def test_save_returns_the_minimal_checkpoint_path_and_the_full_sibling_carries_the_snapshot(signature, tmp_path): + path = make_checkpointer(signature, [make_trainer(epochs=3)]).save(tmp_path / "final.pth") + + assert path == tmp_path / "final.pth" + assert path.is_file() + assert training_state(Checkpoint.load(tmp_path / "final_full.pth"))["epochs"] == [3] + + +def test_save_writes_per_member_files_for_ensembles_by_default(signature, tmp_path): + checkpointer = make_checkpointer(signature, [make_trainer(0), make_trainer(1)]) + checkpointer.save(tmp_path / "final.pth") + + assert (tmp_path / "final_member_0.pth").is_file() + assert (tmp_path / "final_member_1_full.pth").is_file() + + +def test_save_separate_can_be_disabled(signature, tmp_path): + make_checkpointer(signature, [make_trainer(0), make_trainer(1)]).save(tmp_path / "final.pth", save_separate=False) + assert sorted(p.name for p in tmp_path.iterdir()) == ["final.pth", "final_full.pth"] + + +############################################################################### +############################## PERIODIC CHECKPOINTS ########################### +############################################################################### + + +def test_step_is_disabled_without_directory_or_interval(signature, tmp_path): + trainers = [make_trainer()] + assert make_checkpointer(signature, trainers, save_dir=None, save_interval=1).step(0) is None + assert ( + make_checkpointer(signature, trainers, save_dir=tmp_path, save_interval=None).step(0, force_save=True) is None + ) + assert list(tmp_path.iterdir()) == [] + + +def test_directory_is_only_created_when_periodic_saving_is_enabled(signature, tmp_path): + make_checkpointer(signature, [], save_dir=tmp_path / "off", save_interval=None) + make_checkpointer(signature, [], save_dir=tmp_path / "on" / "nested", save_interval=5) + assert not (tmp_path / "off").exists() + assert (tmp_path / "on" / "nested").is_dir() + + +@pytest.mark.parametrize( + "epoch, saved", + [(0, True), (1, False), (2, False), (3, True), (4, False), (6, True)], +) +def test_step_saves_on_multiples_of_the_interval(signature, tmp_path, epoch, saved): + checkpointer = make_checkpointer(signature, [make_trainer()], save_dir=tmp_path, save_interval=3) + name = checkpointer.step(epoch) + assert (name is not None) is saved + if saved: + assert (tmp_path / name).is_file() + + +def test_force_save_overrides_the_interval(signature, tmp_path): + checkpointer = make_checkpointer(signature, [make_trainer()], save_dir=tmp_path, save_interval=10) + assert checkpointer.step(7) is None + assert checkpointer.step(7, force_save=True) == "checkpoint_7_member_0.pth" + assert (tmp_path / "checkpoint_7_member_0.pth").is_file() + + +def test_checkpoint_names_follow_the_active_member(signature, tmp_path): + first, second = make_trainer(0), make_trainer(1) + checkpointer = make_checkpointer(signature, [first, second], save_dir=tmp_path, save_interval=1) + + assert checkpointer.step(0) == "checkpoint_0_member_0.pth" + checkpointer.finish_member(first) # type: ignore[arg-type] + assert checkpointer.step(0) == "checkpoint_0_member_1.pth" diff --git a/tests/unit/cli/__init__.py b/tests/unit/cli/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/unit/cli/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/unit/cli/test_analyze_entrypoint.py b/tests/unit/cli/test_analyze_entrypoint.py new file mode 100644 index 00000000..c42511bd --- /dev/null +++ b/tests/unit/cli/test_analyze_entrypoint.py @@ -0,0 +1,147 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``xanesnet analyze`` entry point (argument parsing and run orchestration).""" + +from argparse import Namespace +from pathlib import Path + +import pytest +import yaml + +from xanesnet import analyze as analyze_cli +from xanesnet.serialization.config import Config +from xanesnet.utils.exceptions import ConfigError +from xanesnet.utils.prompts import is_auto_yes_enabled + + +class Recorder: + """Captures what the entry point passes to the core ``analyze`` function.""" + + def __init__(self) -> None: + self.calls: list[dict] = [] + self.auto_yes_during_call: list[bool] = [] + + def __call__(self, config: Config, args: Namespace, save_dir: Path) -> None: + self.calls.append({"config": config, "args": args, "save_dir": save_dir}) + self.auto_yes_during_call.append(is_auto_yes_enabled()) + + @property + def call(self) -> dict: + assert len(self.calls) == 1, f"expected exactly one core call, got {len(self.calls)}" + return self.calls[0] + + +@pytest.fixture +def core(monkeypatch) -> Recorder: + recorder = Recorder() + monkeypatch.setattr(analyze_cli, "analyze", recorder) + return recorder + + +@pytest.fixture +def config_file(write_yaml, analyze_config) -> Path: + return write_yaml(analyze_config, name="analyze.yaml") + + +@pytest.fixture +def out_dir(tmp_path) -> Path: + return tmp_path / "runs" + + +def run(config_file: Path, out_dir: Path, *extra: str) -> None: + analyze_cli.main(["-i", str(config_file), "-r", "run_a", "-o", str(out_dir), "-n", "unit", *extra]) + + +############################################################################### +############################### ARGUMENT PARSING ############################## +############################################################################### + + +def test_optional_arguments_default_to_empty_values(): + args = analyze_cli.parse_args(["-i", "c.yaml", "-r", "run_a"]) + assert args.inference_runs == ["run_a"] + assert args.prediction_names == [] + assert args.out_dir is None and args.name is None and args.yes is False + + +def test_inference_runs_and_prediction_names_may_mix_repeated_and_space_separated_values(): + args = analyze_cli.parse_args(["-i", "c.yaml", "-r", "a", "b", "-r", "c", "-d", "X", "Y", "-d", "Z"]) + + assert args.inference_runs == ["a", "b", "c"] + assert args.prediction_names == ["X", "Y", "Z"] + + +############################################################################### +################################ RUN DIRECTORY ################################ +############################################################################### + + +def test_core_receives_validated_config_and_parsed_arguments(core, config_file, out_dir): + analyze_cli.main(["-i", str(config_file), "-r", "a", "b", "-d", "A", "B", "-o", str(out_dir), "-n", "unit"]) + + call = core.call + assert call["save_dir"] == out_dir / "analyze_unit_000" + assert call["args"].inference_runs == ["a", "b"] + assert call["args"].prediction_names == ["A", "B"] + assert call["config"].get_bool("preload") is False, "schema defaults must be applied" + + +def test_run_directory_layout_and_saved_artifacts(core, config_file, out_dir, analyze_config): + run(config_file, out_dir) + + save_dir = core.call["save_dir"] + assert {p.name for p in save_dir.iterdir() if p.is_dir()} == {"plots", "reports", "aux"} + for artifact in ( + "analyze_config.yaml", + "validated_analyze_config.yaml", + "software.info", + "hardware.info", + "out.txt", + ): + assert (save_dir / artifact).is_file(), artifact + assert yaml.safe_load((save_dir / "analyze_config.yaml").read_text()) == analyze_config + + +@pytest.mark.parametrize("flag, expected", [(["--yes"], True), ([], False)]) +def test_yes_flag_enables_auto_confirmation_only_during_the_run(core, config_file, out_dir, flag, expected): + run(config_file, out_dir, *flag) + assert core.auto_yes_during_call == [expected] + assert is_auto_yes_enabled() is False + + +############################################################################### +################################ INVALID INPUT ################################ +############################################################################### + + +def test_invalid_config_is_rejected(core, write_yaml, analyze_config, out_dir): + analyze_config["selectors"] = [{"selector_type": "nope"}] + + with pytest.raises(ConfigError, match=r"Invalid analyze config at config\.selectors"): + run(write_yaml(analyze_config), out_dir) + assert core.calls == [] diff --git a/tests/unit/cli/test_cli.py b/tests/unit/cli/test_cli.py new file mode 100644 index 00000000..d5f56d8d --- /dev/null +++ b/tests/unit/cli/test_cli.py @@ -0,0 +1,94 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the top-level ``xanesnet`` command dispatcher.""" + +import pytest + +from xanesnet import cli +from xanesnet.utils.exceptions import ConfigError + + +@pytest.fixture +def entry_points(monkeypatch): + """Replace the three workflow entry points with recorders and return the call log.""" + calls: list[tuple[str, list[str]]] = [] + for name in ("train", "infer", "analyze"): + monkeypatch.setattr(f"xanesnet.{name}.main", lambda args, _name=name: calls.append((_name, list(args)))) + return calls + + +############################################################################### +################################### HELP ###################################### +############################################################################### + + +@pytest.mark.parametrize("args", [[], ["-h"], ["--help"], ["--help", "train"]]) +def test_help_is_printed_and_exits_cleanly(args, entry_points, capsys): + with pytest.raises(SystemExit) as excinfo: + cli.main(args) + + assert excinfo.value.code == 0 + output = capsys.readouterr().out + assert "Usage:" in output + for command in ("train", "infer", "analyze"): + assert command in output + assert entry_points == [] + + +############################################################################### +################################## DISPATCH ################################### +############################################################################### + + +@pytest.mark.parametrize("command", ["train", "infer", "analyze"]) +def test_command_is_forwarded_with_its_remaining_arguments(command, entry_points): + cli.main([command, "-i", "config.yaml", "--yes"]) + assert entry_points == [(command, ["-i", "config.yaml", "--yes"])] + + +def test_only_the_selected_command_runs(entry_points): + cli.main(["infer", "-i", "x"]) + assert [name for name, _ in entry_points] == ["infer"] + + +def test_command_arguments_may_be_empty(entry_points): + cli.main(["train"]) + assert entry_points == [("train", [])] + + +@pytest.mark.parametrize("command", ["trainn", "TRAIN", "-i", "predict"]) +def test_unknown_commands_are_rejected(command, entry_points): + with pytest.raises(ConfigError, match=f"Incorrect mode: {command}"): + cli.main([command]) + assert entry_points == [] + + +def test_console_main_uses_the_process_arguments(monkeypatch, entry_points): + monkeypatch.setattr("sys.argv", ["xanesnet", "analyze", "-i", "c.yaml"]) + cli.console_main() + assert entry_points == [("analyze", ["-i", "c.yaml"])] diff --git a/tests/unit/cli/test_infer_entrypoint.py b/tests/unit/cli/test_infer_entrypoint.py new file mode 100644 index 00000000..73487f31 --- /dev/null +++ b/tests/unit/cli/test_infer_entrypoint.py @@ -0,0 +1,186 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``xanesnet infer`` entry point (argument parsing and run orchestration).""" + +from argparse import Namespace +from pathlib import Path + +import pytest +import yaml + +from xanesnet import infer as infer_cli +from xanesnet.serialization.checkpoints import Checkpoint +from xanesnet.serialization.config import Config +from xanesnet.utils.exceptions import ConfigError +from xanesnet.utils.prompts import is_auto_yes_enabled + + +class Recorder: + """Captures what the entry point passes to the core ``infer`` function.""" + + def __init__(self) -> None: + self.calls: list[dict] = [] + self.auto_yes_during_call: list[bool] = [] + + def __call__(self, config: Config, args: Namespace, save_dir: Path, checkpoint: Checkpoint) -> None: + self.calls.append({"config": config, "args": args, "save_dir": save_dir, "checkpoint": checkpoint}) + self.auto_yes_during_call.append(is_auto_yes_enabled()) + + @property + def call(self) -> dict: + assert len(self.calls) == 1, f"expected exactly one core call, got {len(self.calls)}" + return self.calls[0] + + +@pytest.fixture +def core(monkeypatch) -> Recorder: + recorder = Recorder() + monkeypatch.setattr(infer_cli, "infer", recorder) + return recorder + + +@pytest.fixture +def config_file(write_yaml, infer_user_config) -> Path: + return write_yaml(infer_user_config, name="infer.yaml") + + +@pytest.fixture +def checkpoint_file(tmp_path, signature) -> Path: + path = tmp_path / "final.pth" + Checkpoint(Config(signature), [{}]).save(path) + return path + + +@pytest.fixture +def out_dir(tmp_path) -> Path: + return tmp_path / "runs" + + +def run(config_file: Path, checkpoint_file: Path, out_dir: Path, *extra: str) -> None: + infer_cli.main(["-i", str(config_file), "-m", str(checkpoint_file), "-o", str(out_dir), "-n", "unit", *extra]) + + +############################################################################### +############################### ARGUMENT PARSING ############################## +############################################################################### + + +def test_defaults_for_optional_arguments(): + args = infer_cli.parse_args(["-i", "c.yaml", "-m", "m.pth"]) + assert (args.in_file, args.in_model) == ("c.yaml", "m.pth") + assert args.out_dir is None and args.name is None and args.yes is False + + long = infer_cli.parse_args( + ["--in_file", "c.yaml", "--in_model", "m.pth", "--out_dir", "out", "--name", "x", "--yes"] + ) + assert vars(long) == vars(infer_cli.parse_args(["-i", "c.yaml", "-m", "m.pth", "-o", "out", "-n", "x", "-y"])) + + +############################################################################### +################################ RUN DIRECTORY ################################ +############################################################################### + + +def test_core_receives_validated_merged_config_and_loaded_checkpoint(core, config_file, checkpoint_file, out_dir): + run(config_file, checkpoint_file, out_dir) + + call = core.call + assert call["save_dir"] == out_dir / "infer_unit_000" + assert isinstance(call["checkpoint"], Checkpoint) + config = call["config"] + assert config.section("model").get_str("model_type") == "mlp", "model section comes from the checkpoint signature" + assert config.get_str("device") == "cpu", "schema defaults must be applied" + assert config.section("inferencer").get_bool("shuffle") is False + + +def test_run_directory_layout_and_saved_artifacts(core, config_file, checkpoint_file, out_dir, infer_user_config): + run(config_file, checkpoint_file, out_dir) + + save_dir = core.call["save_dir"] + assert (save_dir / "predictions").is_dir() + for artifact in ( + "infer_config.yaml", + "merged_infer_config.yaml", + "validated_infer_config.yaml", + "software.info", + "hardware.info", + "out.txt", + ): + assert (save_dir / artifact).is_file(), artifact + assert yaml.safe_load((save_dir / "infer_config.yaml").read_text()) == infer_user_config + + +def test_merged_config_combines_user_config_and_signature(core, config_file, checkpoint_file, out_dir, signature): + run(config_file, checkpoint_file, out_dir) + + merged = yaml.safe_load((core.call["save_dir"] / "merged_infer_config.yaml").read_text()) + assert merged["model"] == signature["model"] + assert merged["encodings"] == signature["encodings"] + assert merged["inferencer"]["inferencer_type"] == "basic" + + +def test_run_directory_defaults_to_plain_infer_prefix(core, config_file, checkpoint_file, out_dir): + infer_cli.main(["-i", str(config_file), "-m", str(checkpoint_file), "-o", str(out_dir)]) + assert core.call["save_dir"].name == "infer_000" + + +############################################################################### +##################################### SEED #################################### +############################################################################### + + +@pytest.mark.parametrize("flag, expected", [(["--yes"], True), ([], False)]) +def test_yes_flag_enables_auto_confirmation_only_during_the_run( + core, config_file, checkpoint_file, out_dir, flag, expected +): + run(config_file, checkpoint_file, out_dir, *flag) + assert core.auto_yes_during_call == [expected] + assert is_auto_yes_enabled() is False + + +############################################################################### +################################ INVALID INPUT ################################ +############################################################################### + + +def test_user_config_conflicting_with_the_signature_is_rejected( + core, write_yaml, infer_user_config, checkpoint_file, out_dir +): + infer_user_config["model"] = {"model_type": "mlp", "hidden_size": 64} # checkpoint was trained with 8 + + with pytest.raises(ConfigError, match="Conflict for key 'hidden_size'"): + run(write_yaml(infer_user_config), checkpoint_file, out_dir) + assert core.calls == [] + + +def test_invalid_user_config_is_rejected_after_merging(core, write_yaml, infer_user_config, checkpoint_file, out_dir): + infer_user_config["inferencer"]["inferencer_type"] = "nope" + + with pytest.raises(ConfigError, match=r"Invalid infer config at config\.inferencer"): + run(write_yaml(infer_user_config), checkpoint_file, out_dir) + assert core.calls == [] diff --git a/tests/unit/cli/test_train_entrypoint.py b/tests/unit/cli/test_train_entrypoint.py new file mode 100644 index 00000000..f1c12b9a --- /dev/null +++ b/tests/unit/cli/test_train_entrypoint.py @@ -0,0 +1,363 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``xanesnet train`` entry point (argument parsing and run orchestration). + +The heavy ``train`` pipeline is replaced by a recorder, so these tests cover everything the entry point itself is +responsible for: loading and validating configs, merging checkpoint signatures, creating the run directory and +dispatching to the right backend. +""" + +import copy +from argparse import Namespace +from pathlib import Path + +import pytest +import yaml + +from xanesnet import train as train_cli +from xanesnet.serialization.checkpoints import Checkpoint +from xanesnet.serialization.config import Config +from xanesnet.serialization.tensorboard import tb_logger +from xanesnet.utils.exceptions import ConfigError +from xanesnet.utils.lightning import LIGHTNING_CONTEXT_ENV +from xanesnet.utils.prompts import is_auto_yes_enabled + + +class Recorder: + """Captures what the entry point passes to the core ``train`` function.""" + + def __init__(self) -> None: + self.calls: list[dict] = [] + self.auto_yes_during_call: list[bool] = [] + + def __call__(self, config: Config, args: Namespace, save_dir: Path, checkpoint: Checkpoint | None) -> None: + self.calls.append({"config": config, "args": args, "save_dir": save_dir, "checkpoint": checkpoint}) + self.auto_yes_during_call.append(is_auto_yes_enabled()) + + @property + def call(self) -> dict: + assert len(self.calls) == 1, f"expected exactly one core call, got {len(self.calls)}" + return self.calls[0] + + +@pytest.fixture(autouse=True) +def _reset_tensorboard(): + yield + tb_logger.close() + tb_logger.set_log_weights(False) + + +@pytest.fixture +def core(monkeypatch) -> Recorder: + recorder = Recorder() + monkeypatch.setattr(train_cli, "train", recorder) + return recorder + + +@pytest.fixture +def config_file(write_yaml, train_config) -> Path: + return write_yaml(train_config, name="train.yaml") + + +@pytest.fixture +def out_dir(tmp_path) -> Path: + return tmp_path / "runs" + + +def run(config_file: Path, out_dir: Path, *extra: str) -> None: + train_cli.main(["-i", str(config_file), "-o", str(out_dir), "-n", "unit", *extra]) + + +############################################################################### +############################### ARGUMENT PARSING ############################## +############################################################################### + + +def test_defaults_for_optional_arguments(): + args = train_cli.parse_args(["-i", "config.yaml"]) + + assert args.in_file == "config.yaml" + assert args.model_path is None + assert args.out_dir is None + assert args.name is None + for flag in ("restart_training_state", "tensorboard", "log_weights", "dry_run", "yes"): + assert getattr(args, flag) is False + + +def test_all_arguments_are_parsed_in_their_short_and_long_forms(): + short = train_cli.parse_args(["-i", "c.yaml", "-m", "m.pth", "-o", "out", "-n", "x", "-t", "-y"]) + long = train_cli.parse_args( + ["--in_file", "c.yaml", "--model", "m.pth", "--out_dir", "out", "--name", "x", "--tensorboard", "--yes"] + ) + + assert vars(short) == vars(long) + assert (short.model_path, short.out_dir, short.name) == ("m.pth", "out", "x") + assert short.tensorboard and short.yes + + long_only = train_cli.parse_args(["-i", "c.yaml", "--restart-training-state", "--log-weights", "--dry-run"]) + assert long_only.restart_training_state and long_only.log_weights and long_only.dry_run + + +############################################################################### +################################ RUN DIRECTORY ################################ +############################################################################### + + +def test_core_receives_validated_config_and_fresh_run_directory(core, config_file, out_dir): + run(config_file, out_dir) + + call = core.call + assert call["save_dir"] == out_dir / "train_unit_000" + assert call["checkpoint"] is None + assert isinstance(call["config"], Config) + assert call["config"].get_str("device") == "cpu", "schema defaults must be applied before training" + assert call["args"].name == "unit" + + +def test_run_directory_layout_and_saved_artifacts(core, config_file, out_dir, train_config): + run(config_file, out_dir) + + save_dir = core.call["save_dir"] + assert {p.name for p in save_dir.iterdir() if p.is_dir()} == {"models", "checkpoints"} + for artifact in ( + "train_config.yaml", + "validated_train_config.yaml", + "software.info", + "hardware.info", + "out.txt", + ): + assert (save_dir / artifact).is_file(), artifact + assert yaml.safe_load((save_dir / "train_config.yaml").read_text()) == train_config, "raw config copied verbatim" + assert not (save_dir / "merged_train_config.yaml").exists() + + +def test_validated_config_on_disk_matches_the_one_given_to_core(core, config_file, out_dir): + run(config_file, out_dir) + saved = yaml.safe_load((core.call["save_dir"] / "validated_train_config.yaml").read_text()) + assert saved == core.call["config"].as_dict() + + +def test_run_directory_defaults_to_plain_train_prefix(core, config_file, out_dir): + train_cli.main(["-i", str(config_file), "-o", str(out_dir)]) + assert core.call["save_dir"].name == "train_000" + + +@pytest.mark.parametrize("flags, created", [(["--tensorboard", "--log-weights"], True), ([], False)]) +def test_tensorboard_directory_follows_the_flag(core, config_file, out_dir, flags, created): + run(config_file, out_dir, *flags) + + assert (core.call["save_dir"] / "tensorboard").is_dir() is created + assert core.call["args"].tensorboard is created + + +############################################################################### +##################################### SEED #################################### +############################################################################### + + +def test_configured_seed_is_kept(core, write_yaml, train_config, out_dir): + train_config["seed"] = 1234 + run(write_yaml(train_config), out_dir) + + assert core.call["config"].get_int("seed") == 1234 + saved = yaml.safe_load((core.call["save_dir"] / "validated_train_config.yaml").read_text()) + assert saved["seed"] == 1234 + + +def test_missing_seed_is_replaced_by_a_concrete_one_and_recorded(core, config_file, out_dir): + run(config_file, out_dir) + + seed = core.call["config"].get_int("seed") + saved = yaml.safe_load((core.call["save_dir"] / "validated_train_config.yaml").read_text()) + assert saved["seed"] == seed + + +############################################################################### +#################################### FLAGS #################################### +############################################################################### + + +@pytest.mark.parametrize("flags, epochs", [(["--dry-run"], 1), ([], 50)]) +def test_dry_run_limits_training_to_a_single_epoch(core, write_yaml, train_config, out_dir, flags, epochs): + train_config["trainer"]["epochs"] = 50 + run(write_yaml(train_config), out_dir, *flags) + + assert core.call["config"].section("trainer").get_int("epochs") == epochs + assert core.call["args"].dry_run is bool(flags) + + +@pytest.mark.parametrize("flag, expected", [(["--yes"], True), ([], False)]) +def test_yes_flag_enables_auto_confirmation_only_during_the_run(core, config_file, out_dir, flag, expected): + run(config_file, out_dir, *flag) + + assert core.auto_yes_during_call == [expected] + assert is_auto_yes_enabled() is False, "the auto-yes scope must end with the run" + + +############################################################################### +################################ INVALID INPUT ################################ +############################################################################### + + +def test_invalid_config_is_rejected_before_any_directory_is_created(core, write_yaml, train_config, out_dir): + train_config["model"]["model_type"] = "nope" + + with pytest.raises(ConfigError, match="Invalid train config"): + run(write_yaml(train_config), out_dir) + + assert core.calls == [] + assert not out_dir.exists() + + +############################################################################### +############################ CHECKPOINT (-m) HANDLING ######################### +############################################################################### + + +def _resumable_config(train_config) -> dict: + """A fine-tuning config: dimensions come from the checkpoint signature instead of 'auto'.""" + config = copy.deepcopy(train_config) + del config["model"]["in_size"], config["model"]["out_size"] + return config + + +@pytest.fixture +def save_checkpoint(signature): + """Return a helper that writes a checkpoint carrying the standard signature (and optional training state).""" + + def _save(path: Path, training_state: dict | None = None) -> Path: + Checkpoint(Config(signature), [{}], training_state).save(path) + return path + + return _save + + +def test_checkpoint_signature_completes_the_config_and_is_forwarded( + core, write_yaml, train_config, out_dir, tmp_path, save_checkpoint +): + checkpoint_path = save_checkpoint(tmp_path / "final.pth") + + run(write_yaml(_resumable_config(train_config)), out_dir, "-m", str(checkpoint_path)) + + call = core.call + assert isinstance(call["checkpoint"], Checkpoint) + assert call["config"].section("model").get_int("in_size") == 6 + assert call["config"].section("model").get_int("out_size") == 10 + assert (call["save_dir"] / "merged_train_config.yaml").is_file() + + +def test_checkpoint_signature_conflicting_with_the_config_is_rejected( + core, write_yaml, train_config, out_dir, tmp_path, save_checkpoint +): + checkpoint_path = save_checkpoint(tmp_path / "final.pth") + config = _resumable_config(train_config) + config["model"]["hidden_size"] = 64 # the checkpoint was trained with 8 + + with pytest.raises(ConfigError, match="Conflict for key 'hidden_size'"): + run(write_yaml(config), out_dir, "-m", str(checkpoint_path)) + assert core.calls == [] + + +def _training_state(learning_rate: float) -> dict: + return { + "epochs": [3], + "optimizer_signature": {"trainer": {"learning_rate": learning_rate}}, + "optimizer_states": [{}], + "scheduler_signature": {"trainer": {"lr_warmup": False}}, + "epoch_scheduler_states": [{}], + "warmup_scheduler_states": [None], + } + + +def test_training_state_signatures_are_merged_when_resuming_from_a_full_checkpoint( + core, write_yaml, train_config, out_dir, tmp_path, save_checkpoint +): + save_checkpoint(tmp_path / "final.pth", _training_state(0.001)) + + run(write_yaml(_resumable_config(train_config)), out_dir, "-m", str(tmp_path / "final_full.pth")) + + assert core.call["checkpoint"].training_state is not None + assert core.call["config"].section("trainer").get_bool("lr_warmup") is False + + +def test_conflicting_optimizer_signature_is_rejected_when_resuming( + core, write_yaml, train_config, out_dir, tmp_path, save_checkpoint +): + save_checkpoint(tmp_path / "final.pth", _training_state(learning_rate=0.5)) + + with pytest.raises(ConfigError, match="Conflict for key 'learning_rate'"): + run(write_yaml(_resumable_config(train_config)), out_dir, "-m", str(tmp_path / "final_full.pth")) + + +def test_restart_training_state_ignores_the_optimizer_and_scheduler_signatures( + core, write_yaml, train_config, out_dir, tmp_path, save_checkpoint +): + save_checkpoint(tmp_path / "final.pth", _training_state(learning_rate=0.5)) + + run( + write_yaml(_resumable_config(train_config)), + out_dir, + "-m", + str(tmp_path / "final_full.pth"), + "--restart-training-state", + ) + + assert core.call["config"].section("trainer").get_float("learning_rate") == 0.001 + assert core.call["args"].restart_training_state is True + + +############################################################################### +################################ BACKEND DISPATCH ############################# +############################################################################### + + +def test_lightning_trainer_is_dispatched_to_the_lightning_backend( + monkeypatch, core, write_yaml, train_config, out_dir +): + launched = Recorder() + monkeypatch.setattr("xanesnet.core_lightning.train_initial", launched) + train_config["trainer"] = {"trainer_type": "lightning", "epochs": 1, "batch_size": 2} + + run(write_yaml(train_config), out_dir) + + assert core.calls == [] + assert launched.call["config"].section("trainer").get_str("trainer_type") == "lightning" + + +def test_prepared_lightning_worker_skips_the_normal_startup(monkeypatch, core, tmp_path, out_dir): + workers: list[Path] = [] + monkeypatch.setattr("xanesnet.core_lightning.train_worker", workers.append) + context = tmp_path / "lightning_context.json" + monkeypatch.setenv(LIGHTNING_CONTEXT_ENV, str(context)) + + # The configuration file does not even need to exist: workers load the prepared run context instead. + train_cli.main(["-i", str(tmp_path / "ignored.yaml"), "-o", str(out_dir)]) + + assert workers == [context] + assert core.calls == [] + assert not out_dir.exists(), "workers must not create run directories" diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py new file mode 100644 index 00000000..36d0dc6c --- /dev/null +++ b/tests/unit/conftest.py @@ -0,0 +1,258 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Shared fixtures for the unit tests: minimal configs, helpers and global-state isolation.""" + +import copy +import logging +import sys +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from xanesnet.serialization._types import ConfigRaw +from xanesnet.utils.lightning import LIGHTNING_CONTEXT_ENV +from xanesnet.utils.prompts import set_auto_yes + +REPO_ROOT = Path(__file__).resolve().parents[2] +CONFIGS_DIR = REPO_ROOT / "configs" +DRY_RUNS_DIR = REPO_ROOT / "tests" / "dry_runs" + + +############################################################################### +############################## CONFIG FACTORIES ############################### +############################################################################### + + +def make_train_config() -> ConfigRaw: + """Build the minimal MLP training configuration used by unit tests. + + Returns: + Raw configuration mapping for the toy-data training pipeline. + """ + return { + "datasource": { + "datasource_type": "pmgjson", + "json_path": "./data/toy_data/", + "spectrum_key": "XANES", + }, + "dataset": { + "dataset_type": "descriptor", + "root": "./data/processed/unit_test/", + "descriptors": [ + {"descriptor_type": "wacsf", "r_min": 1.0, "r_max": 6.0, "n_g2": 2, "n_g4": 2}, + ], + }, + "encodings": [{"encoding_type": "identity"}], + "model": { + "model_type": "mlp", + "in_size": "auto", + "out_size": "auto", + "hidden_size": 8, + "num_hidden_layers": 1, + }, + "trainer": { + "trainer_type": "basic", + "batch_size": 2, + "epochs": 1, + "learning_rate": 0.001, + "optimizer": "Adam", + "loss": [{"loss_type": "mse"}], + }, + "strategy": {"strategy_type": "single"}, + } + + +def make_infer_user_config() -> ConfigRaw: + """Build the minimal user-facing inference configuration. + + Returns: + Raw configuration mapping for inference against the toy data. + """ + return { + "datasource": { + "datasource_type": "pmgjson", + "json_path": "./data/toy_data/", + "spectrum_key": "XANES", + }, + "dataset": {"root": "./data/processed/unit_test/"}, + "strategy": {"strategy_type": "single"}, + "inferencer": {"inferencer_type": "basic", "batch_size": 2}, + } + + +def make_signature() -> ConfigRaw: + """Build a checkpoint signature matching the training fixture. + + Returns: + Raw checkpoint signature mapping for the MLP test model. + """ + return { + "dataset": { + "dataset_type": "descriptor", + "descriptors": [ + {"descriptor_type": "wacsf", "r_min": 1.0, "r_max": 6.0, "n_g2": 2, "n_g4": 2}, + ], + }, + "model": { + "model_type": "mlp", + "in_size": 6, + "out_size": 10, + "hidden_size": 8, + "num_hidden_layers": 1, + }, + "encodings": [{"encoding_type": "identity"}], + } + + +def make_analyze_config() -> ConfigRaw: + """Build the minimal analysis configuration used by unit tests. + + Returns: + Raw configuration mapping for the basic loss analysis. + """ + return { + "selectors": [{"selector_type": "all"}], + "collectors": [{"collector_type": "loss", "loss": {"loss_type": "mse"}}], + } + + +############################################################################### +################################### FIXTURES ################################## +############################################################################### + + +@pytest.fixture(autouse=True) +def _isolate_global_state(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]: + """Undo process-wide side effects (logging, std streams, auto-yes) after every test. + + The XANESNET entry points configure the root logger, replace ``sys.stdout``/``sys.stderr`` and toggle global + prompt state. Restoring them keeps tests order-independent. + + Args: + monkeypatch: Pytest fixture used to clear context-scoped environment state. + + Yields: + ``None`` while process-wide state is isolated for the test. + """ + monkeypatch.delenv(LIGHTNING_CONTEXT_ENV, raising=False) + + root = logging.getLogger() + handlers, level = list(root.handlers), root.level + streams = sys.stdout, sys.stderr + yield + + for handler in list(root.handlers): + if handler not in handlers: + root.removeHandler(handler) + handler.close() + for handler in handlers: + if handler not in root.handlers: + root.addHandler(handler) + root.setLevel(level) + sys.stdout, sys.stderr = streams + # Always clear the process-wide flag; entry points use the context-scoped ``auto_yes``. + set_auto_yes(False) + + +@pytest.fixture +def train_config() -> ConfigRaw: + """Provide a fresh minimal training configuration. + + Returns: + Raw training configuration mapping. + """ + return make_train_config() + + +@pytest.fixture +def infer_user_config() -> ConfigRaw: + """Provide a fresh minimal user-facing inference configuration. + + Returns: + Raw inference configuration mapping. + """ + return make_infer_user_config() + + +@pytest.fixture +def signature() -> ConfigRaw: + """Provide a fresh minimal checkpoint signature. + + Returns: + Raw checkpoint signature mapping. + """ + return make_signature() + + +@pytest.fixture +def analyze_config() -> ConfigRaw: + """Provide a fresh minimal analysis configuration. + + Returns: + Raw analysis configuration mapping. + """ + return make_analyze_config() + + +@pytest.fixture +def mutate() -> Callable[[ConfigRaw, Callable[[ConfigRaw], Any]], ConfigRaw]: + """Provide a helper that mutates a deep copy of a configuration. + + Returns: + Callable that applies a mutation to a copied config and returns the copy. + """ + + def _mutate(base: ConfigRaw, fn: Callable[[ConfigRaw], Any]) -> ConfigRaw: + config = copy.deepcopy(base) + fn(config) + return config + + return _mutate + + +@pytest.fixture +def write_yaml(tmp_path: Path) -> Callable[..., Path]: + """Provide a helper that writes a YAML document into ``tmp_path``. + + Args: + tmp_path: Temporary directory used for the generated configuration file. + + Returns: + Callable that writes a mapping or raw YAML text and returns its path. + """ + + def _write(content: Any, name: str = "config.yaml") -> Path: + path = tmp_path / name + text = content if isinstance(content, str) else yaml.safe_dump(content, sort_keys=False) + path.write_text(text) + return path + + return _write diff --git a/tests/unit/core/__init__.py b/tests/unit/core/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/unit/core/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/unit/core/conftest.py b/tests/unit/core/conftest.py new file mode 100644 index 00000000..027cef67 --- /dev/null +++ b/tests/unit/core/conftest.py @@ -0,0 +1,46 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Fixtures shared by the core pipeline tests.""" + +from collections.abc import Iterator + +import pytest + +from . import fakes + + +@pytest.fixture(autouse=True) +def events() -> Iterator[list]: + """Clear the shared fake-event log around every test. + + Yields: + The shared event log, empty before and after the test. + """ + fakes.EVENTS.clear() + yield fakes.EVENTS + fakes.EVENTS.clear() diff --git a/tests/unit/core/fakes.py b/tests/unit/core/fakes.py new file mode 100644 index 00000000..9fbc5f4d --- /dev/null +++ b/tests/unit/core/fakes.py @@ -0,0 +1,197 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Lightweight test doubles for the core pipelines. + +The fakes are registered in the public data source, dataset and strategy registries under ``unit_test_*`` keys, so the +pipelines resolve them exactly like real implementations. Everything they do is recorded in ``EVENTS``. +""" + +from collections.abc import Mapping +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import torch + +from xanesnet.datasets import DatasetRegistry +from xanesnet.datasources import DataSourceRegistry +from xanesnet.serialization.config import Config +from xanesnet.strategies import StrategyRegistry + +DATASOURCE_TYPE = "unit_test_datasource" +DATASET_TYPE = "unit_test_dataset_core" +STRATEGY_TYPE = "unit_test_strategy" + +EVENTS: list[tuple[str, Any]] = [] +"""Chronological ``(event, payload)`` log shared by all fakes; cleared before every test by ``events``.""" + +SPLITS = [[[0, 1, 2], [3]]] +SIGNATURE = {"model": {"model_type": "fake"}, "encodings": [], "dataset": {"dataset_type": DATASET_TYPE}} + + +class FakeModel: + """Model stand-in that records the device selected by the core pipeline.""" + + def __init__(self) -> None: + self.device: torch.device | None = None + + def to(self, device: torch.device) -> "FakeModel": + self.device = device + return self + + +class Recorder: + """Object whose methods/attributes record calls; used as optimizer/scheduler stand-in.""" + + def __init__(self, name: str) -> None: + self.name = name + self.loaded: list[Any] = [] + + def load_state_dict(self, state: Any) -> None: + self.loaded.append(state) + EVENTS.append((f"load_{self.name}", state)) + + +class FakeCheckpointer: + """Checkpointer stand-in that records save requests.""" + + signature = Config(SIGNATURE) + + def save(self, path: Path) -> None: + EVENTS.append(("checkpointer_save", Path(path))) + + +class FakeEncoding: + """Encoding stand-in with a stable signature for core tests.""" + + signature = [Config({"encoding_type": "fake_encoding", "num_points": 3})] + + +@DataSourceRegistry.register(DATASOURCE_TYPE) +class FakeDataSource: + """Registered data-source stand-in that records constructor arguments.""" + + def __init__(self, **kwargs: Any) -> None: + self.kwargs = kwargs + EVENTS.append(("datasource", kwargs)) + + +@DatasetRegistry.register(DATASET_TYPE) +class FakeDataset: + """Registered dataset stand-in that records preparation calls.""" + + def __init__(self, datasource: FakeDataSource, **kwargs: Any) -> None: + self.datasource = datasource + self.kwargs = kwargs + EVENTS.append(("dataset", kwargs)) + + def prepare(self) -> None: + EVENTS.append(("prepare", None)) + + def check_preload(self) -> None: + EVENTS.append(("check_preload", None)) + + def __len__(self) -> int: + return 4 + + +@StrategyRegistry.register(STRATEGY_TYPE) +class FakeStrategy: + """Strategy double with one trainer whose optimizer/schedulers are recorders.""" + + def __init__(self, **kwargs: Any) -> None: + self.kwargs = kwargs + self.models = [FakeModel()] + self.trainers = [ + SimpleNamespace( + optimizer=SimpleNamespace(torch_optimizer=Recorder("optimizer")), + epoch_lr_scheduler=Recorder("epoch_scheduler"), + warmup_lr_scheduler=Recorder("warmup_scheduler"), + ) + ] + EVENTS.append(("strategy", kwargs)) + + def setup_model_splits(self) -> list[list[list[int]]]: + EVENTS.append(("setup_model_splits", None)) + return SPLITS + + def setup_encoding(self, config: Config) -> FakeEncoding: + EVENTS.append(("setup_encoding", config)) + return FakeEncoding() + + def setup_models(self, model_config: Config) -> None: + EVENTS.append(("setup_models", model_config)) + + def setup_checkpointer(self) -> FakeCheckpointer: + EVENTS.append(("setup_checkpointer", None)) + return FakeCheckpointer() + + def init_model_weights(self) -> None: + EVENTS.append(("init_model_weights", None)) + + def setup_trainers(self, device: str) -> None: + EVENTS.append(("setup_trainers", device)) + + def setup_inferencers(self, device: str) -> None: + EVENTS.append(("setup_inferencers", device)) + + def set_state_dicts(self, states: list[Mapping[str, Any]]) -> None: + EVENTS.append(("set_state_dicts", states)) + + def run_training(self) -> list[FakeModel]: + EVENTS.append(("run_training", None)) + return self.models + + def run_inference(self, predictions_path: Path | None) -> None: + EVENTS.append(("run_inference", predictions_path)) + + +def event_names() -> list[str]: + """Return recorded event names in chronological order. + + Returns: + Event names, including repeated events. + """ + return [name for name, _ in EVENTS] + + +def payload(name: str) -> Any: + """Return the payload for the single recorded event named ``name``. + + Args: + name: Event name to find. + + Returns: + Payload recorded for the matching event. + + Raises: + AssertionError: If the event was recorded zero or multiple times. + """ + matches = [value for event, value in EVENTS if event == name] + assert len(matches) == 1, f"expected exactly one {name!r} event, got {len(matches)}" + return matches[0] diff --git a/tests/unit/core/test_core_analyze.py b/tests/unit/core/test_core_analyze.py new file mode 100644 index 00000000..d4d21cbd --- /dev/null +++ b/tests/unit/core/test_core_analyze.py @@ -0,0 +1,474 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``core_analyze.analyze`` pipeline, run against registered fakes.""" + +import json +import logging +from argparse import Namespace +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pytest + +from xanesnet import core_analyze +from xanesnet.analysis.aggregators import ( + Aggregator, + AggregatorRegistry, + AggregatorResult, +) +from xanesnet.analysis.collectors import Collector, CollectorRegistry +from xanesnet.analysis.custom_modules import CustomModule, CustomModuleRegistry +from xanesnet.analysis.plotters import Plotter, PlotterRegistry +from xanesnet.analysis.reporters import Reporter, ReporterRegistry +from xanesnet.analysis.result import AnalysisResults +from xanesnet.serialization.config import Config, load_raw_config +from xanesnet.serialization.prediction_readers import PredictionSample +from xanesnet.utils.exceptions import ConfigError + +############################################################################### +################################# TEST DOUBLES ################################ +############################################################################### + +SAMPLES = [ + {"sample_id": "a", "target_site_index": 0}, + {"sample_id": "b", "target_site_index": 2}, + {"sample_id": "c"}, +] + +CALLS: list[tuple[str, Any]] = [] +"""Chronological ``(event, payload)`` log of everything the fakes were asked to do.""" + + +class FakeReader: + def __init__(self, path: Any, preload: bool) -> None: + self.path, self.preload, self.closed = path, preload, False + + def close(self) -> None: + self.closed = True + CALLS.append(("close", self.path)) + + +class FakeSelector: + selector_type = "fake" + + def __init__(self, samples: list[dict[str, Any]]) -> None: + self._samples = samples + + def __iter__(self): + return iter(self._samples) + + def __len__(self) -> int: + return len(self._samples) + + def __str__(self) -> str: + return "fake_selector" + + +@CollectorRegistry.register("unit_test_length") +class LengthCollector(Collector): + def process(self, sample: PredictionSample) -> dict[str, Any]: + return {"id_length": len(sample["sample_id"])} + + +@CollectorRegistry.register("unit_test_constant") +class ConstantCollector(Collector): + def __init__(self, collector_type: str, key: str = "constant", value: Any = 1) -> None: + super().__init__(collector_type) + self.key, self.value = key, value + + def process(self, sample: PredictionSample) -> dict[str, Any]: + return {self.key: self.value} + + +@AggregatorRegistry.register("unit_test_count") +class CountAggregator(Aggregator): + def aggregate(self, selector, per_sample_values, index): + CALLS.append(("aggregate", (index, None if per_sample_values is None else list(per_sample_values)))) + return AggregatorResult(self.aggregator_type, index, {"n": len(selector)}) + + +@ReporterRegistry.register("unit_test_report") +class FakeReporter(Reporter): + def report(self, results: AnalysisResults, output_dir: Path) -> None: + CALLS.append(("report", (results, output_dir))) + assert output_dir.is_dir(), "the pipeline creates the output directory" + + +@PlotterRegistry.register("unit_test_plot") +class FakePlotter(Plotter): + def __init__(self, plotter_type: str, latex_font: bool = False, plot_size: str = "default") -> None: + super().__init__(plotter_type, latex_font, plot_size) # type: ignore[arg-type] + + def _plot(self, results: AnalysisResults, output_dir: Path) -> None: + CALLS.append(("plot", (results, output_dir))) + assert output_dir.is_dir() + + +@CustomModuleRegistry.register("unit_test_module") +class FakeModule(CustomModule): + def run(self, inference_run_dirs, prediction_names, output_dir): + CALLS.append(("custom", (inference_run_dirs, prediction_names, output_dir))) + assert output_dir.is_dir() + + +@pytest.fixture(autouse=True) +def calls() -> Iterator[list[tuple[str, Any]]]: + """Isolate the custom analysis-component call log for each test. + + Yields: + The shared call log, empty before and after the test. + """ + CALLS.clear() + yield CALLS + CALLS.clear() + + +@pytest.fixture +def readers(monkeypatch: pytest.MonkeyPatch) -> list[FakeReader]: + """Replace prediction-reader and selector construction with fakes. + + Args: + monkeypatch: Pytest fixture used to replace analysis setup functions. + + Returns: + Readers created by the fake setup function. + """ + created: list[FakeReader] = [] + + def make_readers(inference_run_dirs, preload): + created.extend(FakeReader(path, preload) for path in inference_run_dirs) + return created + + def make_selectors(config, predictions_readers): + selectors = [[FakeSelector(SAMPLES)] for _ in predictions_readers] + return selectors, Config({"selectors": [{"selector_type": "fake"}]}) + + monkeypatch.setattr(core_analyze, "_setup_predictions_readers", make_readers) + monkeypatch.setattr(core_analyze, "_setup_selectors", make_selectors) + return created + + +def make_config(**sections: list[dict[str, Any]]) -> Config: + """Build an analysis config with empty defaults for unspecified sections. + + Args: + sections: Analysis sections that override the empty defaults. + + Returns: + Config containing the supplied analysis sections. + """ + raw: dict[str, Any] = {name: [] for name in ("selectors", "collectors", "aggregators", "reporters", "plotters")} + raw.update({"custom_modules": [], "preload": False}) + raw.update(sections) + return Config(raw) + + +def make_args(*runs: str, names: list[str] | None = None) -> Namespace: + """Build parsed analysis arguments for the requested inference runs. + + Args: + runs: Inference run directories passed to analysis. + names: Optional names assigned to the corresponding prediction sets. + + Returns: + Namespace matching the arguments consumed by the analysis pipeline. + """ + return Namespace(inference_runs=list(runs), prediction_names=names) + + +def calls_named(name: str) -> list[Any]: + """Return payloads recorded for a named analysis event. + + Args: + name: Event name to filter. + + Returns: + Payloads for matching events in recorded order. + """ + return [payload for event, payload in CALLS if event == name] + + +############################################################################### +############################# CUSTOM-MODULES-ONLY RUN ######################### +############################################################################### + + +class TestCustomModulesOnly: + @pytest.fixture + def config(self) -> Config: + return make_config(custom_modules=[{"custom_module_type": "unit_test_module"}]) + + def test_modules_run_without_building_any_reader(self, config, tmp_path, monkeypatch): + def forbidden(*args): + raise AssertionError("readers must not be created for a custom-modules-only run") + + monkeypatch.setattr(core_analyze, "_setup_predictions_readers", forbidden) + + core_analyze.analyze(config, make_args("runs/one", "runs/two"), tmp_path) + + ((inference_runs, names, output_dir),) = calls_named("custom") + assert inference_runs == [Path("runs/one"), Path("runs/two")] + assert names == ["one", "two"] + assert output_dir == tmp_path / "custom_modules" / "unit_test_module_000" + + def test_empty_pipeline_sections_are_recorded(self, config, tmp_path): + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + for section in ("selectors", "collectors", "aggregators", "reporters", "plotters"): + assert load_raw_config(tmp_path / f"{section}.yaml") == {section: []} + assert load_raw_config(tmp_path / "custom_modules.yaml") == { + "custom_modules": [{"custom_module_type": "unit_test_module"}] + } + + def test_each_module_gets_its_own_numbered_directory(self, tmp_path): + config = make_config(custom_modules=[{"custom_module_type": "unit_test_module"}] * 2) + + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + directories = [output_dir.name for _, _, output_dir in calls_named("custom")] + assert directories == ["unit_test_module_000", "unit_test_module_001"] + + def test_nothing_configured_at_all_is_a_quiet_no_op(self, tmp_path, readers): + core_analyze.analyze(make_config(), make_args("runs/one"), tmp_path) + + assert CALLS == [] + assert readers == [] + + def test_unknown_module_type_is_reported(self, tmp_path): + config = make_config(custom_modules=[{"custom_module_type": "does_not_exist"}]) + + with pytest.raises(KeyError, match="does_not_exist"): + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + +############################################################################### +############################### PREDICTION NAMES ############################## +############################################################################### + + +@pytest.mark.parametrize( + ("runs", "names", "expected"), + [ + (("runs/one", "runs/two"), None, ["one", "two"]), + (("runs/one", "runs/two"), [], ["one", "two"]), + (("runs/one", "runs/two"), ["A", "B"], ["A", "B"]), + pytest.param( + ("runs/one", "runs/two"), + ["A"], + ["A", "two"], + marks=pytest.mark.xfail( + strict=True, + reason="Known bug: padding uses run_dir_names[:n] instead of run_dir_names[len(names):], " + "so the second reader is labelled 'one' instead of its own directory name 'two'.", + ), + ), + (("runs/one", "runs/two"), ["A", "B", "C"], ["A", "B"]), + (("runs/nested/one/",), None, ["one"]), + ], + ids=["default", "empty", "exact", "too-few", "too-many", "trailing-slash"], +) +def test_prediction_names_fall_back_to_run_directory_names(tmp_path, runs, names, expected): + config = make_config(custom_modules=[{"custom_module_type": "unit_test_module"}]) + + core_analyze.analyze(config, make_args(*runs, names=names), tmp_path) + + assert calls_named("custom")[0][1] == expected + + +@pytest.mark.parametrize("names", [["A"], ["A", "B", "C"]]) +def test_mismatched_name_count_is_logged(tmp_path, caplog, names): + config = make_config(custom_modules=[{"custom_module_type": "unit_test_module"}]) + + with caplog.at_level(logging.WARNING): + core_analyze.analyze(config, make_args("runs/one", "runs/two", names=names), tmp_path) + + assert "does not match the number of inference runs" in caplog.text + + +############################################################################### +################################ FULL PIPELINE ################################ +############################################################################### + + +class TestFullPipeline: + @pytest.fixture + def config(self) -> Config: + return make_config( + collectors=[{"collector_type": "unit_test_length"}, {"collector_type": "unit_test_constant", "value": 7}], + aggregators=[{"aggregator_type": "unit_test_count"}], + reporters=[{"reporter_type": "unit_test_report"}], + plotters=[{"plotter_type": "unit_test_plot"}], + custom_modules=[{"custom_module_type": "unit_test_module"}], + ) + + def test_stage_order(self, config, tmp_path, readers): + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + order = [event for event, _ in CALLS] + assert order == ["aggregate", "report", "plot", "custom", "close"] + + def test_collector_records_are_written_per_sample(self, config, tmp_path, readers): + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + aux = tmp_path / "aux" / "predictions_000" + records = [json.loads(line) for line in (aux / "000.jsonl").read_text().splitlines()] + assert records == [ + {"id_length": 1, "constant": 7, "sample_id": "a", "target_site_index": 0}, + {"id_length": 1, "constant": 7, "sample_id": "b", "target_site_index": 2}, + {"id_length": 1, "constant": 7, "sample_id": "c", "target_site_index": None}, + ] + assert json.loads((aux / "000.meta.json").read_text()) == {"count": 3} + + def test_every_reader_gets_its_own_aux_directory(self, config, tmp_path, readers): + core_analyze.analyze(config, make_args("runs/one", "runs/two"), tmp_path) + + assert sorted(path.name for path in (tmp_path / "aux").iterdir()) == ["predictions_000", "predictions_001"] + + def test_aggregators_receive_the_collected_values(self, config, tmp_path, readers): + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + ((index, values),) = calls_named("aggregate") + assert index == 0 + assert [record["sample_id"] for record in values] == ["a", "b", "c"] + + def test_reporters_and_plotters_receive_the_aggregated_results(self, config, tmp_path, readers): + core_analyze.analyze(config, make_args("runs/one", names=["First"]), tmp_path) + + ((results, report_dir),) = calls_named("report") + ((plot_results, plot_dir),) = calls_named("plot") + assert plot_results is results + assert report_dir == tmp_path / "reports" / "unit_test_report_000" + assert plot_dir == tmp_path / "plots" / "unit_test_plot_000" + assert results.prediction_names == ["First"] + assert results.aggregation(0, 0, "unit_test_count").data == {"n": 3} + assert results.collector_stream(0, 0) is not None + + def test_component_configuration_is_saved(self, config, tmp_path, readers): + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + assert load_raw_config(tmp_path / "collectors.yaml")["collectors"][1] == { + "collector_type": "unit_test_constant", + "value": 7, + } + assert load_raw_config(tmp_path / "aggregators.yaml") == { + "aggregators": [{"aggregator_type": "unit_test_count"}] + } + assert load_raw_config(tmp_path / "selectors.yaml") == {"selectors": [{"selector_type": "fake"}]} + for section in ("reporters", "plotters", "custom_modules"): + assert (tmp_path / f"{section}.yaml").is_file() + + @pytest.mark.parametrize("preload", [True, False]) + def test_preload_flag_reaches_the_readers(self, config, tmp_path, readers, preload): + raw = config.as_dict() + raw["preload"] = preload + + core_analyze.analyze(Config(raw), make_args("runs/one", "runs/two"), tmp_path) + + assert [reader.preload for reader in readers] == [preload, preload] + + def test_readers_are_closed_after_success(self, config, tmp_path, readers): + core_analyze.analyze(config, make_args("runs/one", "runs/two"), tmp_path) + + assert [reader.closed for reader in readers] == [True, True] + + def test_readers_are_closed_after_a_failure(self, tmp_path, readers): + config = make_config(collectors=[{"collector_type": "does_not_exist"}]) + + with pytest.raises(KeyError, match="does_not_exist"): + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + assert [reader.closed for reader in readers] == [True] + + +class TestPartialPipelines: + def test_aggregators_without_collectors_get_no_per_sample_values(self, tmp_path, readers): + config = make_config(aggregators=[{"aggregator_type": "unit_test_count"}]) + + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + assert calls_named("aggregate") == [(0, None)] + assert not (tmp_path / "aux").exists() + + def test_collectors_alone_still_persist_their_results(self, tmp_path, readers): + config = make_config(collectors=[{"collector_type": "unit_test_length"}]) + + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + assert (tmp_path / "aux" / "predictions_000" / "000.jsonl").is_file() + assert not (tmp_path / "reports").exists() + assert not (tmp_path / "plots").exists() + + def test_reporters_alone_see_empty_collector_and_aggregator_results(self, tmp_path, readers): + config = make_config(reporters=[{"reporter_type": "unit_test_report"}]) + + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + ((results, _),) = calls_named("report") + assert results.collector_results == [] + assert results.aggregator_results == [] + + def test_several_components_of_one_kind_get_numbered_directories(self, tmp_path, readers): + config = make_config(reporters=[{"reporter_type": "unit_test_report"}] * 2) + + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + assert [d.name for _, d in calls_named("report")] == ["unit_test_report_000", "unit_test_report_001"] + + +class TestCollectorKeyContract: + def test_duplicate_output_keys_are_rejected(self, tmp_path, readers): + config = make_config( + collectors=[{"collector_type": "unit_test_constant"}, {"collector_type": "unit_test_constant"}] + ) + + with pytest.raises(ConfigError, match="Duplicate collector key 'constant' for sample a"): + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + def test_reserved_metadata_keys_cannot_be_overridden(self, tmp_path, readers): + config = make_config( + collectors=[{"collector_type": "unit_test_constant", "key": "sample_id", "value": "hijacked"}] + ) + + core_analyze.analyze(config, make_args("runs/one"), tmp_path) + + records = [json.loads(line) for line in (tmp_path / "aux/predictions_000/000.jsonl").read_text().splitlines()] + assert [record["sample_id"] for record in records] == ["a", "b", "c"] + + +############################################################################### +################################### HELPERS ################################### +############################################################################### + + +@pytest.mark.parametrize( + ("seconds", "expected"), + [(0, "0.0s"), (4.24, "4.2s"), (59.94, "59.9s"), (60, "1m 00s"), (63, "1m 03s"), (3725, "62m 05s")], +) +def test_duration_formatting(seconds, expected): + assert core_analyze._format_duration(seconds) == expected diff --git a/tests/unit/core/test_core_infer.py b/tests/unit/core/test_core_infer.py new file mode 100644 index 00000000..d1752c1b --- /dev/null +++ b/tests/unit/core/test_core_infer.py @@ -0,0 +1,106 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``core_infer.infer`` pipeline, run against registered fakes.""" + +from argparse import Namespace + +import pytest + +from xanesnet import core_infer +from xanesnet.serialization.checkpoints import Checkpoint +from xanesnet.serialization.config import Config + +from . import fakes + + +@pytest.fixture +def config() -> Config: + return Config( + { + "device": "cpu", + "datasource": {"datasource_type": fakes.DATASOURCE_TYPE, "path": "somewhere"}, + "dataset": {"dataset_type": fakes.DATASET_TYPE, "root": "dataset_root"}, + "strategy": {"strategy_type": fakes.STRATEGY_TYPE, "option": 3}, + "inferencer": {"inferencer_type": "basic", "batch_size": 4}, + "model": {"model_type": "fake", "hidden_size": 8}, + } + ) + + +@pytest.fixture +def checkpoint() -> Checkpoint: + return Checkpoint(signature=Config(fakes.SIGNATURE), model_states=[{"weight": 1}, {"weight": 2}]) + + +def test_pipeline_stages_run_in_order(config, checkpoint, tmp_path): + core_infer.infer(config, Namespace(), tmp_path, checkpoint) + + assert fakes.event_names() == [ + "datasource", + "dataset", + "prepare", + "check_preload", + "strategy", + "setup_encoding", + "setup_models", + "set_state_dicts", + "setup_inferencers", + "run_inference", + ] + + +def test_checkpoint_weights_are_loaded_into_the_strategy(config, checkpoint, tmp_path): + core_infer.infer(config, Namespace(), tmp_path, checkpoint) + + assert fakes.payload("set_state_dicts") == [{"weight": 1}, {"weight": 2}] + + +def test_components_receive_their_configuration(config, checkpoint, tmp_path): + core_infer.infer(config, Namespace(), tmp_path, checkpoint) + + assert fakes.payload("datasource")["path"] == "somewhere" + assert fakes.payload("dataset")["root"] == "dataset_root" + assert fakes.payload("setup_models").get_int("hidden_size") == 8 + assert fakes.payload("setup_inferencers") == "cpu" + + +def test_strategy_is_built_for_inference_only(config, checkpoint, tmp_path): + core_infer.infer(config, Namespace(), tmp_path, checkpoint) + + kwargs = fakes.payload("strategy") + assert kwargs["option"] == 3 + assert kwargs["inferencer_config"].get_int("batch_size") == 4 + assert kwargs["trainer_config"] is None + assert kwargs["checkpoint_dir"] is None + assert kwargs["tensorboard_dir"] is None + + +def test_predictions_are_written_below_the_run_directory(config, checkpoint, tmp_path): + core_infer.infer(config, Namespace(), tmp_path, checkpoint) + + assert fakes.payload("run_inference") == tmp_path / "predictions" diff --git a/tests/unit/core/test_core_lightning.py b/tests/unit/core/test_core_lightning.py new file mode 100644 index 00000000..356551ed --- /dev/null +++ b/tests/unit/core/test_core_lightning.py @@ -0,0 +1,399 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the Lightning worker entry point (``train_worker``) and its launch-context validation.""" + +import json +import os +from argparse import Namespace +from pathlib import Path + +import pytest + +from xanesnet import core_lightning +from xanesnet.serialization.config import Config +from xanesnet.utils.exceptions import ConfigError +from xanesnet.utils.lightning import LIGHTNING_CONTEXT_ENV, LIGHTNING_LAUNCH_ENVIRONMENT + +from . import fakes + + +@pytest.fixture +def worker_env(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("LOCAL_RANK", "1") + + +@pytest.fixture +def stubbed(monkeypatch: pytest.MonkeyPatch) -> None: + """Skip the optional Lightning import; the pipeline itself runs against the registered fakes.""" + monkeypatch.setattr(core_lightning, "_register_lightning_trainer", lambda: None) + monkeypatch.setattr( + core_lightning, + "reset_peak_memory_stats", + lambda device: fakes.EVENTS.append(("reset", device)), + ) + + +def make_config() -> Config: + """Build the minimal config used by Lightning worker tests. + + Returns: + Config referencing the registered fake pipeline components. + """ + return Config( + { + "seed": 3, + "device": "cpu", + "datasource": {"datasource_type": fakes.DATASOURCE_TYPE}, + "dataset": {"dataset_type": fakes.DATASET_TYPE, "root": "dataset_root"}, + "strategy": {"strategy_type": fakes.STRATEGY_TYPE}, + "trainer": {"trainer_type": "basic"}, + "model": {"model_type": "fake"}, + } + ) + + +def write_context(directory: Path, **overrides) -> Path: + """Write a Lightning worker context with optional field overrides. + + Args: + directory: Directory where the context file is written. + overrides: Context values replacing the default fields. + + Returns: + Path to the generated context JSON file. + """ + context = { + "config": make_config().as_dict(), + "dry_run": False, + "model_path": None, + "restart_training_state": False, + } + context.update(overrides) + path = directory / "lightning_context.json" + path.write_text(json.dumps(context), encoding="utf-8") + return path + + +############################################################################### +############################## CONTEXT VALIDATION ############################# +############################################################################### + + +def test_missing_context_file_is_reported(tmp_path, worker_env): + with pytest.raises(ConfigError, match="Cannot load Lightning context"): + core_lightning.train_worker(tmp_path / "missing.json") + + +def test_malformed_context_file_is_reported(tmp_path, worker_env): + path = tmp_path / "lightning_context.json" + path.write_text("{not json", encoding="utf-8") + + with pytest.raises(ConfigError, match="Cannot load Lightning context"): + core_lightning.train_worker(path) + + +@pytest.mark.parametrize("payload", ["[]", '"text"', "3", "null"]) +def test_non_object_context_is_rejected(tmp_path, worker_env, payload): + path = tmp_path / "lightning_context.json" + path.write_text(payload, encoding="utf-8") + + with pytest.raises(ConfigError, match="must contain an object"): + core_lightning.train_worker(path) + + +@pytest.mark.parametrize("rank", [None, "", "first", "1.5"]) +def test_worker_requires_an_integer_local_rank(tmp_path, monkeypatch, rank): + if rank is None: + monkeypatch.delenv("LOCAL_RANK", raising=False) + else: + monkeypatch.setenv("LOCAL_RANK", rank) + + with pytest.raises(ConfigError, match="integer LOCAL_RANK"): + core_lightning.train_worker(write_context(tmp_path)) + + +@pytest.mark.parametrize("rank", ["0", "-1"]) +def test_non_worker_processes_are_rejected(tmp_path, monkeypatch, rank): + monkeypatch.setenv("LOCAL_RANK", rank) + + with pytest.raises(ConfigError, match="does not identify this process as a worker"): + core_lightning.train_worker(write_context(tmp_path)) + + +def test_context_problems_are_reported_before_anything_is_built(tmp_path, monkeypatch): + monkeypatch.setenv("LOCAL_RANK", "0") + + with pytest.raises(ConfigError): + core_lightning.train_worker(write_context(tmp_path)) + + assert fakes.EVENTS == [] + assert not (tmp_path / "workers").exists() + + +def test_missing_lightning_dependency_gives_an_actionable_message(tmp_path, worker_env, monkeypatch): + def not_installed(name: str): + raise ModuleNotFoundError("No module named 'lightning'", name="lightning") + + monkeypatch.setattr(core_lightning.importlib, "import_module", not_installed) + + with pytest.raises(ConfigError, match=r"xanesnet\[lightning\]"): + core_lightning.train_worker(write_context(tmp_path)) + + +def test_unrelated_import_errors_are_not_masked(tmp_path, worker_env, monkeypatch): + def broken(name: str): + raise ModuleNotFoundError("No module named 'numpyy'", name="numpyy") + + monkeypatch.setattr(core_lightning.importlib, "import_module", broken) + + with pytest.raises(ModuleNotFoundError, match="numpyy"): + core_lightning.train_worker(write_context(tmp_path)) + + +############################################################################### +################################## WORKER RUN ################################# +############################################################################### + + +def test_worker_builds_the_prepared_run_and_trains(tmp_path, worker_env, stubbed): + core_lightning.train_worker(write_context(tmp_path)) + + names = fakes.event_names() + assert names.index("strategy") < names.index("setup_models") < names.index("setup_trainers") + assert names[-1] == "run_training" + assert "checkpointer_save" not in names, "only the initial process exports results" + + +def test_worker_reuses_the_prepared_dataset_and_splits(tmp_path, worker_env, stubbed): + core_lightning.train_worker(write_context(tmp_path)) + + dataset_kwargs = fakes.payload("dataset") + assert dataset_kwargs["skip_prepare"] is True + assert dataset_kwargs["split_indexfile"] == str(tmp_path / "split_indices.json") + + +def test_worker_logs_to_a_per_rank_directory(tmp_path, worker_env, stubbed): + core_lightning.train_worker(write_context(tmp_path)) + + assert (tmp_path / "workers" / "rank_1").is_dir() + + +def test_worker_does_not_enable_tensorboard(tmp_path, worker_env, stubbed): + core_lightning.train_worker(write_context(tmp_path)) + + assert fakes.payload("strategy")["tensorboard_dir"] is None + + +@pytest.mark.parametrize("dry_run", [True, False]) +def test_dry_run_flag_controls_memory_statistics_reset(tmp_path, worker_env, stubbed, dry_run): + core_lightning.train_worker(write_context(tmp_path, dry_run=dry_run)) + + assert ("reset" in fakes.event_names()) is dry_run + + +def test_worker_restores_checkpoint_weights_and_training_state(tmp_path, worker_env, stubbed, monkeypatch): + from xanesnet.serialization.checkpoints import Checkpoint + + checkpoint = Checkpoint( + signature=Config(fakes.SIGNATURE), + model_states=[{"weight": 1}], + training_state={ + "optimizer_states": [{"lr": 0.1}], + "epoch_scheduler_states": [{"epoch": 4}], + "warmup_scheduler_states": [None], + }, + ) + monkeypatch.setattr(core_lightning.Checkpoint, "load", classmethod(lambda cls, path: checkpoint)) + + core_lightning.train_worker(write_context(tmp_path, model_path="model.pth")) + + assert fakes.payload("set_state_dicts") == [{"weight": 1}] + assert fakes.payload("load_optimizer") == {"lr": 0.1} + assert fakes.payload("load_epoch_scheduler") == {"epoch": 4} + + +def test_restart_training_state_skips_optimizer_and_scheduler_restore(tmp_path, worker_env, stubbed, monkeypatch): + from xanesnet.serialization.checkpoints import Checkpoint + + checkpoint = Checkpoint( + signature=Config(fakes.SIGNATURE), + model_states=[{"weight": 1}], + training_state={ + "optimizer_states": [{"lr": 0.1}], + "epoch_scheduler_states": [{"epoch": 4}], + "warmup_scheduler_states": [None], + }, + ) + monkeypatch.setattr(core_lightning.Checkpoint, "load", classmethod(lambda cls, path: checkpoint)) + + core_lightning.train_worker(write_context(tmp_path, model_path="model.pth", restart_training_state=True)) + + assert "set_state_dicts" in fakes.event_names() + assert not any(name.startswith("load_") for name in fakes.event_names()) + + +def test_environment_is_not_modified_by_the_worker(tmp_path, worker_env, stubbed): + before = dict(os.environ) + + core_lightning.train_worker(write_context(tmp_path)) + + assert dict(os.environ) == before + + +############################################################################### +################################ INITIAL PROCESS ############################## +############################################################################### + + +class TestTrainInitial: + """``train_initial`` prepares the run, publishes the worker context while training, and exports results.""" + + @pytest.fixture(autouse=True) + def _prepare(self, tmp_path, monkeypatch, stubbed): + (tmp_path / "models").mkdir() + monkeypatch.setattr(core_lightning, "resolve_auto_model_config", lambda config, dataset, encoding: config) + monkeypatch.setattr( + core_lightning, + "_save_results", + lambda *params: fakes.EVENTS.append(("save_results", None)), + ) + for name in (*LIGHTNING_LAUNCH_ENVIRONMENT, LIGHTNING_CONTEXT_ENV): + monkeypatch.delenv(name, raising=False) + + @pytest.fixture + def args(self) -> Namespace: + return Namespace(tensorboard=False, dry_run=False, restart_training_state=False) + + @pytest.fixture + def published(self, monkeypatch) -> dict: + """What a Lightning worker would see while ``run_training`` executes.""" + seen: dict = {} + original = fakes.FakeStrategy.run_training + + def run_training(strategy): + path = os.environ.get(LIGHTNING_CONTEXT_ENV) + seen["path"] = path + seen["context"] = json.loads(Path(path).read_text()) if path else None + return original(strategy) + + monkeypatch.setattr(fakes.FakeStrategy, "run_training", run_training) + return seen + + def test_context_is_published_only_while_training(self, tmp_path, args, published): + core_lightning.train_initial(make_config(), args, tmp_path, None) + + assert published["path"] == str(tmp_path / "lightning_context.json") + assert LIGHTNING_CONTEXT_ENV not in os.environ + + def test_context_carries_everything_a_worker_needs(self, tmp_path, args, published): + args.dry_run = True + args.restart_training_state = True + + core_lightning.train_initial(make_config(), args, tmp_path, None) + + context = published["context"] + assert context["dry_run"] is True + assert context["restart_training_state"] is True + assert context["model_path"] is None + assert context["config"]["seed"] == 3 + assert context["config"]["dataset"]["root"] == str((Path.cwd() / "dataset_root").resolve()) + + def test_published_context_is_accepted_by_a_worker(self, tmp_path, args, published, monkeypatch): + core_lightning.train_initial(make_config(), args, tmp_path, None) + fakes.EVENTS.clear() + + monkeypatch.setenv("LOCAL_RANK", "1") + core_lightning.train_worker(tmp_path / "lightning_context.json") + + assert fakes.event_names()[-1] == "run_training" + + def test_launch_environment_is_restored_after_training(self, tmp_path, args, monkeypatch): + monkeypatch.setenv("MASTER_PORT", "1234") + monkeypatch.setattr( + fakes.FakeStrategy, "run_training", lambda strategy: os.environ.update(MASTER_PORT="9999", RANK="0") or [] + ) + + core_lightning.train_initial(make_config(), args, tmp_path, None) + + assert os.environ["MASTER_PORT"] == "1234" + assert "RANK" not in os.environ + + def test_environment_is_restored_when_training_fails(self, tmp_path, args, monkeypatch): + def failing(strategy): + raise RuntimeError("training crashed") + + monkeypatch.setattr(fakes.FakeStrategy, "run_training", failing) + + with pytest.raises(RuntimeError, match="training crashed"): + core_lightning.train_initial(make_config(), args, tmp_path, None) + + assert LIGHTNING_CONTEXT_ENV not in os.environ + assert not list(tmp_path.glob("*.tmp")), "no half-written context file is left behind" + + def test_initial_process_prepares_and_exports(self, tmp_path, args): + core_lightning.train_initial(make_config(), args, tmp_path, None) + + names = fakes.event_names() + assert names.index("setup_trainers") < names.index("run_training") < names.index("save_results") + assert (tmp_path / "resolved_train_config.yaml").is_file() + assert (tmp_path / "split_indices.json").is_file() + assert (tmp_path / "models" / "signature.yaml").is_file() + + def test_dataset_root_is_made_absolute_for_workers(self, tmp_path, args): + core_lightning.train_initial(make_config(), args, tmp_path, None) + + assert Path(fakes.payload("dataset")["root"]).is_absolute() + + def test_checkpoint_state_is_restored_in_the_initial_process(self, tmp_path, args): + from xanesnet.serialization.checkpoints import Checkpoint + + checkpoint = Checkpoint( + signature=Config(fakes.SIGNATURE), + model_states=[{"weight": 1}], + training_state={ + "optimizer_states": [{"lr": 0.1}], + "epoch_scheduler_states": [{"epoch": 4}], + "warmup_scheduler_states": [None], + }, + ) + + core_lightning.train_initial(make_config(), args, tmp_path, checkpoint) + + assert fakes.payload("set_state_dicts") == [{"weight": 1}] + assert fakes.payload("load_optimizer") == {"lr": 0.1} + + def test_missing_lightning_dependency_stops_before_building_anything(self, tmp_path, args, monkeypatch): + def missing(): + raise ConfigError("Lightning training requires `python -m pip install 'xanesnet[lightning]'`.") + + monkeypatch.setattr(core_lightning, "_register_lightning_trainer", missing) + + with pytest.raises(ConfigError, match="Lightning"): + core_lightning.train_initial(make_config(), args, tmp_path, None) + + assert fakes.EVENTS == [] diff --git a/tests/unit/core/test_core_train.py b/tests/unit/core/test_core_train.py new file mode 100644 index 00000000..252d0f38 --- /dev/null +++ b/tests/unit/core/test_core_train.py @@ -0,0 +1,320 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``core_train.train`` pipeline, run against registered fakes.""" + +import json +from argparse import Namespace +from pathlib import Path + +import pytest + +from xanesnet import core_train +from xanesnet.serialization.checkpoints import Checkpoint +from xanesnet.serialization.config import Config, load_raw_config + +from . import fakes + + +@pytest.fixture(autouse=True) +def _stub_collaborators(monkeypatch: pytest.MonkeyPatch) -> None: + """Replace collaborators that have their own unit tests or need real models.""" + monkeypatch.setattr(core_train, "resolve_auto_model_config", lambda config, dataset, encoding: config) + monkeypatch.setattr(core_train, "_summary_models", lambda *args: None) + + +@pytest.fixture(autouse=True) +def _run_directory(tmp_path: Path) -> None: + """``train`` expects the CLI to have created the run sub-folders already.""" + (tmp_path / "models").mkdir() + (tmp_path / "checkpoints").mkdir() + + +@pytest.fixture +def config() -> Config: + return Config( + { + "seed": 1, + "device": "cpu", + "datasource": {"datasource_type": fakes.DATASOURCE_TYPE, "path": "somewhere"}, + "dataset": {"dataset_type": fakes.DATASET_TYPE, "root": "dataset_root"}, + "strategy": {"strategy_type": fakes.STRATEGY_TYPE, "option": 3}, + "trainer": {"trainer_type": "basic", "epochs": 2}, + "model": {"model_type": "fake", "hidden_size": 8}, + } + ) + + +@pytest.fixture +def args() -> Namespace: + return Namespace(tensorboard=False, dry_run=False, restart_training_state=False) + + +def training_state() -> dict: + """Build a minimal checkpoint training-state payload. + + Returns: + Optimizer and scheduler state mappings for one trainer. + """ + return { + "optimizer_states": [{"lr": 0.1}], + "epoch_scheduler_states": [{"epoch": 4}], + "warmup_scheduler_states": [{"warmup": 1}], + } + + +def make_checkpoint(with_training_state: bool = True) -> Checkpoint: + """Build a checkpoint for the fake training pipeline. + + Args: + with_training_state: Whether to include optimizer and scheduler state. + + Returns: + Checkpoint containing the fake signature, model state, and optional + training state. + """ + return Checkpoint( + signature=Config(fakes.SIGNATURE), + model_states=[{"weight": 1}], + training_state=training_state() if with_training_state else None, + ) + + +############################################################################### +################################# ORCHESTRATION ############################### +############################################################################### + + +def test_pipeline_stages_run_in_order(config, args, tmp_path): + core_train.train(config, args, tmp_path, None) + + stages = [ + name + for name in fakes.event_names() + if name + in { + "datasource", + "dataset", + "strategy", + "setup_model_splits", + "setup_encoding", + "setup_models", + "setup_checkpointer", + "init_model_weights", + "setup_trainers", + "run_training", + "checkpointer_save", + } + ] + assert stages == [ + "datasource", + "dataset", + "strategy", + "setup_model_splits", + "setup_encoding", + "setup_models", + "setup_checkpointer", + "init_model_weights", + "setup_trainers", + "run_training", + "checkpointer_save", + ] + + +def test_dataset_is_prepared_and_preloaded_before_the_strategy_sees_it(config, args, tmp_path): + core_train.train(config, args, tmp_path, None) + + names = fakes.event_names() + assert names.index("prepare") < names.index("check_preload") < names.index("strategy") + + +def test_components_receive_their_configuration(config, args, tmp_path): + core_train.train(config, args, tmp_path, None) + + assert fakes.payload("datasource")["path"] == "somewhere" + assert fakes.payload("dataset")["root"] == "dataset_root" + + strategy_kwargs = fakes.payload("strategy") + assert strategy_kwargs["option"] == 3 + assert strategy_kwargs["checkpoint_dir"] == tmp_path / "checkpoints" + assert strategy_kwargs["trainer_config"].get_int("epochs") == 2 + assert strategy_kwargs["inferencer_config"] is None + + assert fakes.payload("setup_models").get_int("hidden_size") == 8 + assert fakes.payload("setup_trainers") == "cpu" + + +@pytest.mark.parametrize("tensorboard", [True, False]) +def test_tensorboard_directory_follows_the_cli_flag(config, args, tmp_path, tensorboard): + args.tensorboard = tensorboard + + core_train.train(config, args, tmp_path, None) + + expected = tmp_path / "tensorboard" if tensorboard else None + assert fakes.payload("strategy")["tensorboard_dir"] == expected + + +############################################################################### +################################### ARTIFACTS ################################# +############################################################################### + + +def test_resolved_config_includes_the_encoding_signature(config, args, tmp_path): + core_train.train(config, args, tmp_path, None) + + resolved = load_raw_config(tmp_path / "resolved_train_config.yaml") + assert resolved["encodings"] == [{"encoding_type": "fake_encoding", "num_points": 3}] + assert resolved["model"]["hidden_size"] == 8 + + +def test_signature_splits_and_final_checkpoint_locations(config, args, tmp_path): + core_train.train(config, args, tmp_path, None) + + assert load_raw_config(tmp_path / "models" / "signature.yaml")["model"] == {"model_type": "fake"} + splits = json.loads((tmp_path / "split_indices.json").read_text()) + assert splits == {"models": [{"train": [0, 1, 2], "valid": [3]}]} + assert fakes.payload("checkpointer_save") == tmp_path / "models" / "final.pth" + + +def test_trained_models_are_moved_to_cpu(config, args, tmp_path, monkeypatch): + seen = [] + monkeypatch.setattr(core_train, "_save_results", lambda model_list, *rest: seen.extend(model_list)) + + core_train.train(config, args, tmp_path, None) + + assert [model.device.type for model in seen] == ["cpu"] + + +############################################################################### +############################### CHECKPOINT RESTORE ############################ +############################################################################### + + +def test_no_checkpoint_restores_nothing(config, args, tmp_path): + core_train.train(config, args, tmp_path, None) + + assert not any( + name in fakes.event_names() for name in ("set_state_dicts", "load_optimizer", "load_epoch_scheduler") + ) + + +def test_checkpoint_restores_models_optimizer_and_schedulers(config, args, tmp_path): + core_train.train(config, args, tmp_path, make_checkpoint()) + + assert fakes.payload("set_state_dicts") == [{"weight": 1}] + assert fakes.payload("load_optimizer") == {"lr": 0.1} + assert fakes.payload("load_epoch_scheduler") == {"epoch": 4} + assert fakes.payload("load_warmup_scheduler") == {"warmup": 1} + names = fakes.event_names() + assert names.index("setup_trainers") < names.index("set_state_dicts") < names.index("run_training") + + +def test_restart_training_state_restores_only_the_model_weights(config, args, tmp_path): + args.restart_training_state = True + + core_train.train(config, args, tmp_path, make_checkpoint()) + + assert "set_state_dicts" in fakes.event_names() + assert not any(name.startswith("load_") for name in fakes.event_names()) + + +def test_checkpoint_without_training_state_restores_only_the_model_weights(config, args, tmp_path): + core_train.train(config, args, tmp_path, make_checkpoint(with_training_state=False)) + + assert "set_state_dicts" in fakes.event_names() + assert not any(name.startswith("load_") for name in fakes.event_names()) + + +def test_missing_warmup_scheduler_state_is_skipped(config, args, tmp_path): + checkpoint = make_checkpoint() + assert checkpoint.training_state is not None + checkpoint.training_state["warmup_scheduler_states"] = [None] + + core_train.train(config, args, tmp_path, checkpoint) + + assert "load_epoch_scheduler" in fakes.event_names() + assert "load_warmup_scheduler" not in fakes.event_names() + + +############################################################################### +################################### DRY RUN ################################### +############################################################################### + + +@pytest.mark.parametrize("dry_run", [True, False]) +def test_dry_run_flag_is_forwarded_to_result_saving(config, args, tmp_path, monkeypatch, dry_run): + args.dry_run = dry_run + forwarded = [] + monkeypatch.setattr(core_train, "_save_results", lambda *params: forwarded.append(params[-1])) + + core_train.train(config, args, tmp_path, None) + + assert forwarded == [dry_run] + + +def test_dry_run_resets_peak_memory_statistics_before_training(config, args, tmp_path, monkeypatch): + args.dry_run = True + monkeypatch.setattr( + core_train, + "reset_peak_memory_stats", + lambda device: fakes.EVENTS.append(("reset_peak", device)), + ) + monkeypatch.setattr(core_train, "_save_results", lambda *params: None) + + core_train.train(config, args, tmp_path, None) + + names = fakes.event_names() + assert names.index("reset_peak") < names.index("run_training") + assert fakes.payload("reset_peak") == "cpu" + + +def test_peak_memory_is_untouched_outside_dry_runs(config, args, tmp_path, monkeypatch): + monkeypatch.setattr( + core_train, + "reset_peak_memory_stats", + lambda device: fakes.EVENTS.append(("reset_peak", device)), + ) + + core_train.train(config, args, tmp_path, None) + + assert "reset_peak" not in fakes.event_names() + + +############################################################################### +################################### FAILURES ################################## +############################################################################### + + +@pytest.mark.parametrize("section", ["datasource", "dataset", "strategy"]) +def test_unregistered_component_types_fail_before_any_output_is_written(config, args, tmp_path, section): + raw = config.as_dict() + raw[section][f"{section}_type"] = "does_not_exist" + + with pytest.raises(KeyError, match="does_not_exist"): + core_train.train(Config(raw), args, tmp_path, None) + + assert not [path for path in tmp_path.rglob("*") if path.is_file()] diff --git a/tests/unit/datasets/__init__.py b/tests/unit/datasets/__init__.py new file mode 100644 index 00000000..dd57543f --- /dev/null +++ b/tests/unit/datasets/__init__.py @@ -0,0 +1,28 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the shared dataset base contract.""" diff --git a/tests/unit/datasets/conftest.py b/tests/unit/datasets/conftest.py new file mode 100644 index 00000000..8e36237f --- /dev/null +++ b/tests/unit/datasets/conftest.py @@ -0,0 +1,94 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Fixtures local to shared dataset-base tests.""" + +from collections.abc import Iterator +from types import SimpleNamespace + +import pytest +from pymatgen.core import Molecule + +from xanesnet.datasources import DataSource + + +def water(sample_id: str) -> Molecule: + """Create a small water molecule carrying a sample identifier. + + Args: + sample_id: Identifier to store in molecule properties. + + Returns: + A three-site water molecule. + """ + molecule = Molecule( + ["O", "H", "H"], + [[0.0, 0.0, 0.1], [0.0, 0.76, -0.47], [0.1, -0.76, -0.47]], + properties={"sample_id": sample_id}, + ) + return molecule + + +class ListSource(DataSource): + """In-memory data source returning molecules in list order. + + Args: + molecules: Molecules exposed by the data source. + """ + + def __init__(self, molecules: list[Molecule]) -> None: + super().__init__("list") + self.molecules = molecules + + def __iter__(self) -> Iterator[Molecule]: + return iter(self.molecules) + + def __len__(self) -> int: + return len(self.molecules) + + def __getitem__(self, idx: int) -> Molecule: + return self.molecules[idx] + + +@pytest.fixture(autouse=True) +def confirm(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: + """Replace dataset confirmation prompts with a controllable response. + + Args: + monkeypatch: Pytest fixture used to replace the confirmation function. + + Returns: + Mutable state containing the response and prompt count. + """ + state = SimpleNamespace(answer=True, asked=0) + + def fake_confirm(message: str, default_yes: bool = True) -> bool: + state.asked += 1 + return state.answer + + monkeypatch.setattr("xanesnet.datasets.base.base.confirm_yes_no", fake_confirm) + return state diff --git a/tests/unit/datasets/test_base_dataset.py b/tests/unit/datasets/test_base_dataset.py new file mode 100644 index 00000000..e446cf4e --- /dev/null +++ b/tests/unit/datasets/test_base_dataset.py @@ -0,0 +1,256 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the ``Dataset`` base class: preparing, caching, preloading and splitting processed samples.""" + +import json +import logging + +import pytest +import torch + +from xanesnet.datasets.base import TorchDataset +from xanesnet.serialization.config import Config +from xanesnet.utils.exceptions import ConfigError + +from .conftest import ListSource, water + + +class TinyDataset(TorchDataset): + """Source item ``i`` yields ``counts[i]`` samples whose value is ``10 * i + seq``.""" + + def __init__(self, tmp_path, counts=(1, 2, 0, 1), preload=False, skip_prepare=False, split_ratios=None, + split_indexfile=None, root=None): # fmt: skip + super().__init__( + "tiny", + datasource=ListSource([water(f"sample_{idx}") for idx in range(len(counts))]), + root=str(root or tmp_path / "processed"), + preload=preload, + skip_prepare=skip_prepare, + split_ratios=split_ratios, + split_indexfile=split_indexfile, + ) + self.counts = counts + self.prepared_items: list[int] = [] + + def _prepare_single(self, idx, save_path_fn): + self.prepared_items.append(idx) + for seq in range(self.counts[idx]): + torch.save(torch.tensor(10 * idx + seq), save_path_fn(seq)) + return self.counts[idx] + + def _load_item(self, path): + return torch.load(path) + + @property + def signature(self): + return super().signature + + +def prepared(tmp_path, **kwargs) -> TinyDataset: + dataset = TinyDataset(tmp_path, **kwargs) + dataset.prepare() + return dataset + + +############################################################################### +################################## PREPARATION ################################ +############################################################################### + + +def test_the_length_is_unknown_before_preparation(tmp_path): + with pytest.raises(ValueError, match="call prepare"): + len(TinyDataset(tmp_path)) + + +def test_prepared_samples_are_numbered_consecutively_across_source_items(tmp_path): + dataset = prepared(tmp_path) + + assert len(dataset) == 4 # item 2 yields nothing and is skipped + assert [int(dataset[i]) for i in range(4)] == [0, 10, 11, 30] + assert [path.rsplit("/", 1)[-1] for path in dataset.processed_files] == ["0.pth", "1.pth", "2.pth", "3.pth"] + + +def test_the_processed_directory_is_created_when_missing(tmp_path): + dataset = prepared(tmp_path, root=tmp_path / "a" / "b") + assert (tmp_path / "a" / "b" / "0.pth").exists() + assert dataset.processed_dir == str(tmp_path / "a" / "b") + + +def test_a_non_empty_processed_directory_is_cleared_when_the_user_agrees(tmp_path, confirm, caplog): + prepared(tmp_path, counts=(3,)) + (tmp_path / "processed" / "stale.txt").write_text("old") + + with caplog.at_level(logging.WARNING): + dataset = prepared(tmp_path, counts=(1,)) + + assert confirm.asked == 1 + assert "not empty" in caplog.text + assert len(dataset) == 1 + assert sorted(p.name for p in (tmp_path / "processed").iterdir()) == ["0.pth"] + + +def test_a_non_empty_processed_directory_is_kept_when_the_user_declines(tmp_path, confirm): + prepared(tmp_path, counts=(2,)) + confirm.answer = False + + with pytest.raises(ConfigError, match="not empty"): + prepared(tmp_path, counts=(1,)) + + assert (tmp_path / "processed" / "1.pth").exists() + + +def test_skip_prepare_reuses_existing_files_without_processing_anything(tmp_path): + prepared(tmp_path, counts=(2, 1)) + + reused = prepared(tmp_path, skip_prepare=True) + + assert reused.prepared_items == [] + assert len(reused) == 3 + assert int(reused[2]) == 10 + + +############################################################################### +#################################### PRELOAD ################################## +############################################################################### + + +def test_preloading_serves_samples_from_memory(tmp_path): + dataset = prepared(tmp_path, preload=True) + + assert dataset.check_preload() is True + for path in dataset.processed_files: + (tmp_path / "processed" / path.rsplit("/", 1)[-1]).unlink() + + assert [int(dataset[i]) for i in range(4)] == [0, 10, 11, 30] + + +def test_without_preloading_samples_are_read_from_disk_on_access(tmp_path): + dataset = prepared(tmp_path, preload=False) + + assert dataset.check_preload() is False + assert dataset.inmemory_dataset == [] + assert int(dataset[1]) == 10 + + +############################################################################### +#################################### SPLITS ################################### +############################################################################### + + +def test_ratio_splits_partition_the_samples_with_the_remainder_in_the_last_subset(tmp_path): + dataset = prepared(tmp_path, counts=(1,) * 10, split_ratios=[0.6, 0.2, 0.2]) + + (plan,) = dataset.setup_splits() + + assert [len(indices) for indices in plan] == [6, 2, 2] + assert sorted(i for indices in plan for i in indices) == list(range(10)) + assert [len(subset) for subset in dataset.subsets] == [6, 2, 2] + train_subset, valid_subset = dataset.train_subset, dataset.valid_subset + assert train_subset is not None + assert valid_subset is not None + assert train_subset.indices == plan[0] + assert valid_subset.indices == plan[1] + + +def test_rounding_leftovers_end_up_in_the_last_subset(tmp_path): + dataset = prepared(tmp_path, counts=(1,) * 7, split_ratios=[0.5, 0.5]) + + (plan,) = dataset.setup_splits() + + assert [len(indices) for indices in plan] == [3, 4] + + +def test_ratios_must_sum_to_one(tmp_path): + dataset = prepared(tmp_path, split_ratios=[0.5, 0.2]) + + with pytest.raises(ConfigError, match="must sum to 1.0"): + dataset.setup_splits() + + +def test_splits_can_come_from_an_index_file(tmp_path): + path = tmp_path / "splits.json" + path.write_text(json.dumps({"models": [{"train": [0, 1], "valid": [2, 3]}, {"train": [3], "valid": [0]}]})) + dataset = prepared(tmp_path, split_indexfile=str(path)) + + plans = dataset.setup_splits() + + assert plans == [[[0, 1], [2, 3]], [[3], [0]]] + assert dataset.has_split_indexfile is True + assert dataset.get_subset_indices(1) == [2, 3] + + +def test_without_split_configuration_there_are_no_subsets(tmp_path, caplog): + dataset = prepared(tmp_path) + + with caplog.at_level(logging.WARNING): + assert dataset.setup_splits() == [] + + assert "No split_ratios or split_indexfile" in caplog.text + assert dataset.subsets == [] + assert dataset.train_subset is None and dataset.valid_subset is None + assert dataset.get_subset_indices(0) is None + assert dataset.has_split_indexfile is False + + +def test_set_splits_replaces_the_subsets_and_out_of_range_lookups_return_none(tmp_path): + dataset = prepared(tmp_path) + + dataset.set_splits([[[0, 1, 2], [3]]]) + + assert dataset.get_all_subset_indices() == [[0, 1, 2], [3]] + assert dataset.get_subset_indices(2) is None + assert dataset.get_subset(-1) is None + + +def test_a_dataset_view_exposes_one_split_plan_and_leaves_the_original_untouched(tmp_path): + dataset = prepared(tmp_path) + dataset.set_splits([[[0, 1], [2]], [[2, 3], [0]]]) + + view = dataset.get_dataset(1) + + assert view.get_all_subset_indices() == [[2, 3], [0]] + assert dataset.get_all_subset_indices() == [[0, 1], [2]] + assert len(view) == len(dataset) + + +def test_dataset_views_need_split_plans(tmp_path): + with pytest.raises(ConfigError, match="before split plans are set"): + prepared(tmp_path).get_dataset(0) + + +def test_the_signature_identifies_the_dataset_type(tmp_path): + assert prepared(tmp_path).signature.as_dict() == {"dataset_type": "tiny"} + assert isinstance(prepared(tmp_path).signature, Config) + + +def test_torch_datasets_collate_samples_into_stacked_batches(tmp_path): + dataset = prepared(tmp_path) + + batch = dataset.collate_fn([dataset[0], dataset[1]]) + + assert batch.tolist() == [0, 10] diff --git a/tests/unit/descriptors/__init__.py b/tests/unit/descriptors/__init__.py new file mode 100644 index 00000000..02e13963 --- /dev/null +++ b/tests/unit/descriptors/__init__.py @@ -0,0 +1,28 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for shared descriptor contracts.""" diff --git a/tests/unit/descriptors/test_descriptor_base.py b/tests/unit/descriptors/test_descriptor_base.py new file mode 100644 index 00000000..7af7b126 --- /dev/null +++ b/tests/unit/descriptors/test_descriptor_base.py @@ -0,0 +1,69 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the shared descriptor base class.""" + +import numpy as np +import pytest +from ase import Atoms +from pymatgen.core import Molecule + +from xanesnet.descriptors import Descriptor + + +def test_pymatgen_objects_are_converted_to_ase_atoms_before_transforming(): + received = {} + + class Recorder(Descriptor): + """Descriptor stub that captures the converted system and site index.""" + + def transform(self, system, site_index=0): + received.update(system=system, site_index=site_index) + return np.zeros(1) + + molecule = Molecule(["O", "H"], [[0, 0, 0], [0, 0, 1]]) + + Recorder("recorder").transform_pmg(molecule, site_index=[1]) + + assert isinstance(received["system"], Atoms) + assert received["system"].get_chemical_symbols() == ["O", "H"] + assert received["site_index"] == [1] + + +def test_pymatgen_transform_defaults_to_the_first_site(): + class Recorder(Descriptor): + """Descriptor stub that returns the selected site as one feature.""" + + def transform(self, system, site_index=0): + return np.array([site_index]) + + assert Recorder("recorder").transform_pmg(Molecule(["H"], [[0, 0, 0]])).tolist() == [0] + + +def test_descriptor_is_abstract(): + with pytest.raises(TypeError): + Descriptor("base") # type: ignore[abstract] diff --git a/tests/unit/graphs/__init__.py b/tests/unit/graphs/__init__.py new file mode 100644 index 00000000..b84c0937 --- /dev/null +++ b/tests/unit/graphs/__init__.py @@ -0,0 +1,28 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for shared graph utilities.""" diff --git a/tests/unit/graphs/test_edge_utilities.py b/tests/unit/graphs/test_edge_utilities.py new file mode 100644 index 00000000..727c4ac7 --- /dev/null +++ b/tests/unit/graphs/test_edge_utilities.py @@ -0,0 +1,285 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the edge-list utilities shared by the graph builders.""" + +import math + +import pytest +import torch +from pymatgen.core import Lattice, Molecule, Structure + +from xanesnet.graphs.utils import ( + build_target_site_paths, + compute_id_swap, + compute_triplets, + compute_triplets_and_angles, + symmetrize_directed_edges, + truncate_per_source, +) + + +def vectors(*rows: tuple[float, float, float]) -> torch.Tensor: + """Build a float32 tensor from three-dimensional vector rows. + + Args: + rows: Vector components to stack into a tensor. + + Returns: + Tensor containing the supplied vectors. + """ + return torch.tensor(rows, dtype=torch.float32) + + +def star_graph() -> tuple[torch.Tensor, torch.Tensor]: + """Node 0 connected in both directions to nodes 1, 2, 3 along the axes.""" + leaves = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)] + src = [0, 0, 0, 1, 2, 3] + dst = [1, 2, 3, 0, 0, 0] + vec = [*leaves, *[(-x, -y, -z) for x, y, z in leaves]] + return torch.tensor([src, dst]), vectors(*vec) + + +def right_angle_graph() -> tuple[torch.Tensor, torch.Tensor]: + """Node 0 at the corner, nodes 1 and 2 along x and y.""" + edge_index = torch.tensor([[0, 0, 1, 2], [1, 2, 0, 0]]) + return edge_index, vectors((1, 0, 0), (0, 1, 0), (-1, 0, 0), (0, -1, 0)) + + +############################################################################### +################################ TRUNCATION ################################### +############################################################################### + + +def test_truncation_keeps_the_nearest_neighbours_of_every_source(): + edge_index = torch.tensor([[0, 0, 0, 1], [1, 2, 3, 0]]) + weight = torch.tensor([3.0, 1.0, 2.0, 5.0]) + vec = torch.arange(12.0).reshape(4, 3) + attr = torch.tensor([10.0, 20.0, 30.0, 40.0]) + + index, kept_weight, kept_vec, kept_attr = truncate_per_source(edge_index, weight, vec, attr, 2) + + assert kept_attr is not None + assert index.tolist() == [[0, 0, 1], [2, 3, 0]] + assert kept_weight.tolist() == [1.0, 2.0, 5.0] + assert kept_vec.tolist() == vec[[1, 2, 3]].tolist() + assert kept_attr.tolist() == [20.0, 30.0, 40.0] + + +@pytest.mark.parametrize("limit", [0, -1, None]) +def test_truncation_is_disabled_by_a_non_positive_limit(limit): + edge_index = torch.tensor([[0, 0], [1, 2]]) + weight = torch.tensor([1.0, 2.0]) + + index, *_ = truncate_per_source(edge_index, weight, torch.zeros(2, 3), None, limit) + + assert index is edge_index + + +def test_truncation_of_an_empty_graph_is_a_no_op(): + index, weight, vec, attr = truncate_per_source( + torch.zeros(2, 0, dtype=torch.int64), torch.zeros(0), torch.zeros(0, 3), None, 3 + ) + assert index.shape == (2, 0) and attr is None + + +############################################################################### +################################ SYMMETRISATION ############################### +############################################################################### + + +def test_edges_without_a_reverse_partner_are_dropped(): + edge_index = torch.tensor([[0, 1, 0], [1, 0, 2]]) + vec = vectors((1, 0, 0), (-1, 0, 0), (0, 1, 0)) + weight = torch.tensor([1.0, 1.0, 1.0]) + attr = torch.tensor([5.0, 6.0, 7.0]) + + index, _, kept_vec, kept_attr = symmetrize_directed_edges(edge_index, weight, vec, attr) + + assert kept_attr is not None + assert index.tolist() == [[0, 1], [1, 0]] + assert kept_vec.tolist() == vec[:2].tolist() + assert kept_attr.tolist() == [5.0, 6.0] + + +def test_a_partner_must_be_the_exact_reverse_displacement_not_just_the_reverse_atom_pair(): + # 0 -> 0 through two different periodic images: only mirrored displacements are partners + edge_index = torch.tensor([[0, 0, 0], [0, 0, 0]]) + vec = vectors((2, 0, 0), (-2, 0, 0), (0, 2, 0)) + + index, _, kept_vec, _ = symmetrize_directed_edges(edge_index, torch.ones(3), vec, None) + + assert kept_vec.tolist() == [[2.0, 0.0, 0.0], [-2.0, 0.0, 0.0]] + assert index.shape == (2, 2) + + +def test_duplicated_edges_are_kept_only_as_often_as_their_reverse_exists(): + edge_index = torch.tensor([[0, 0, 1], [1, 1, 0]]) + vec = vectors((1, 0, 0), (1, 0, 0), (-1, 0, 0)) + + index, *_ = symmetrize_directed_edges(edge_index, torch.ones(3), vec, None) + + assert index.tolist() == [[0, 1], [1, 0]] + + +def test_symmetrising_a_symmetric_graph_changes_nothing_and_an_empty_graph_is_accepted(): + edge_index, vec = star_graph() + index, *_ = symmetrize_directed_edges(edge_index, torch.ones(6), vec, None) + assert index.tolist() == edge_index.tolist() + + empty, *_ = symmetrize_directed_edges(torch.zeros(2, 0, dtype=torch.int64), torch.zeros(0), torch.zeros(0, 3), None) + assert empty.shape == (2, 0) + + +############################################################################### +################################ DIRECTIONAL INDICES ########################## +############################################################################### + + +def test_id_swap_points_every_edge_to_its_reverse(): + edge_index, vec = star_graph() + + id_swap = compute_id_swap(edge_index, vec) + + assert id_swap.tolist() == [3, 4, 5, 0, 1, 2] + assert torch.equal(edge_index[:, id_swap], edge_index.flip(0)) + torch.testing.assert_close(vec[id_swap], -vec) + + +def test_id_swap_of_a_periodic_self_edge_pairs_opposite_images(): + edge_index = torch.tensor([[0, 0], [0, 0]]) + + assert compute_id_swap(edge_index, vectors((2, 0, 0), (-2, 0, 0))).tolist() == [1, 0] + + +def test_id_swap_requires_a_symmetric_graph(): + with pytest.raises(ValueError, match="no matching counter-edge"): + compute_id_swap(torch.tensor([[0], [1]]), vectors((1, 0, 0))) + + with pytest.raises(ValueError, match="multiplicities"): + compute_id_swap(torch.tensor([[0, 0, 1], [1, 1, 0]]), vectors((1, 0, 0), (1, 0, 0), (-1, 0, 0))) + + +def test_id_swap_of_an_empty_graph_is_empty(): + assert compute_id_swap(torch.zeros(2, 0, dtype=torch.int64), torch.zeros(0, 3)).numel() == 0 + + +def test_triplets_pair_every_edge_with_the_other_edges_entering_the_same_atom(): + edge_index, _ = star_graph() + + reduce_ca, expand_ba, kidx = compute_triplets(edge_index, num_nodes=4) + + # three edges enter the centre, each combines with the two others + assert reduce_ca.numel() == 6 + assert reduce_ca.tolist() == sorted(reduce_ca.tolist()) + assert (reduce_ca != expand_ba).all() + assert torch.equal(edge_index[1][reduce_ca], edge_index[1][expand_ba]) + assert set(edge_index[1][reduce_ca].tolist()) == {0} + assert kidx.tolist() == [0, 1] * 3 + + +def test_triplets_of_an_empty_graph_are_empty(): + for indices in compute_triplets(torch.zeros(2, 0, dtype=torch.int64), num_nodes=3): + assert indices.numel() == 0 + + +@pytest.mark.parametrize("periodic", [False, True]) +def test_triplet_angles_are_measured_at_the_central_atom(periodic): + edge_index, vec = right_angle_graph() + + angle, idx_kj, idx_ji = compute_triplets_and_angles(edge_index, vec, num_nodes=3, is_periodic=periodic) + + assert angle.numel() == 2 # k -> j -> i around the corner atom, in both orders + torch.testing.assert_close(angle, torch.full((2,), math.pi / 2)) + # the first leg ends where the second begins, and the path does not return to its start + assert torch.equal(edge_index[1][idx_kj], edge_index[0][idx_ji]) + assert (edge_index[0][idx_kj] != edge_index[1][idx_ji]).all() + + +def test_collinear_triplets_have_angle_pi(): + edge_index = torch.tensor([[0, 1, 1, 2], [1, 0, 2, 1]]) + vec = vectors((1, 0, 0), (-1, 0, 0), (1, 0, 0), (-1, 0, 0)) + + angle, *_ = compute_triplets_and_angles(edge_index, vec, num_nodes=3, is_periodic=False) + + torch.testing.assert_close(angle, torch.full((2,), math.pi)) + + +def test_periodic_triplets_drop_paths_that_bounce_straight_back(): + # one atom with periodic images along +x and -x: the path -x then +x returns to the start + edge_index = torch.tensor([[0, 0], [0, 0]]) + vec = vectors((2, 0, 0), (-2, 0, 0)) + + angle, *_ = compute_triplets_and_angles(edge_index, vec, num_nodes=1, is_periodic=True) + + assert angle.numel() == 0 + + +############################################################################### +################################ TARGET-SITE PATHS ############################ +############################################################################### + + +def test_paths_connect_pairs_of_neighbours_of_the_target_site_nearest_first(): + molecule = Molecule(["Fe", "O", "O", "O"], [[0, 0, 0], [1, 0, 0], [0, 1, 0], [-2, 0, 0]]) + + paths = build_target_site_paths(molecule, target_site_idx=0, cutoff=2.5, max_paths=10) + + # pairs ordered by r0j + r0k + 0.5 * rjk + assert list(zip(paths["path_j"].tolist(), paths["path_k"].tolist())) == [(1, 2), (2, 3), (1, 3)] + torch.testing.assert_close(paths["path_r0j"], torch.tensor([1.0, 1.0, 1.0])) + torch.testing.assert_close(paths["path_r0k"], torch.tensor([1.0, 2.0, 2.0])) + torch.testing.assert_close(paths["path_rjk"], torch.tensor([2**0.5, 5**0.5, 3.0])) + torch.testing.assert_close(paths["path_cosangle"], torch.tensor([0.0, 0.0, -1.0]), atol=1e-6, rtol=0) + + +def test_paths_are_limited_to_the_best_scoring_pairs(): + molecule = Molecule(["Fe", "O", "O", "O"], [[0, 0, 0], [1, 0, 0], [0, 1, 0], [-2, 0, 0]]) + + paths = build_target_site_paths(molecule, 0, cutoff=2.5, max_paths=2) + + assert list(zip(paths["path_j"].tolist(), paths["path_k"].tolist())) == [(1, 2), (2, 3)] + + +@pytest.mark.parametrize("cutoff", [0.5, 1.5]) +def test_fewer_than_two_neighbours_give_empty_paths(cutoff): + molecule = Molecule(["Fe", "O", "O"], [[0, 0, 0], [1, 0, 0], [5, 0, 0]]) + + paths = build_target_site_paths(molecule, 0, cutoff=cutoff, max_paths=10) + + assert set(paths) == {"path_j", "path_k", "path_r0j", "path_r0k", "path_rjk", "path_cosangle"} + assert all(values.numel() == 0 for values in paths.values()) + + +def test_periodic_paths_run_through_images_of_the_neighbours_but_not_the_site_itself(): + structure = Structure(Lattice.cubic(2.0), ["Fe"], [[0, 0, 0]]) + + paths = build_target_site_paths(structure, 0, cutoff=2.1, max_paths=100) + + assert paths["path_j"].numel() == 15 # pairs of the six neighbouring images + torch.testing.assert_close(paths["path_r0j"], torch.full((15,), 2.0)) + assert paths["path_cosangle"].min().item() == pytest.approx(-1.0) diff --git a/tests/unit/serialization/__init__.py b/tests/unit/serialization/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/unit/serialization/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/unit/serialization/test_auto_config.py b/tests/unit/serialization/test_auto_config.py new file mode 100644 index 00000000..13e3b39a --- /dev/null +++ b/tests/unit/serialization/test_auto_config.py @@ -0,0 +1,436 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for automatic ("auto") config resolution and its streaming spectral statistics. + +The tests plug a tiny in-memory dataset, batch processor and resolvers into the public registries under unique +``unit_test_*`` keys, so the resolution logic is exercised without depending on any real model or encoding. +""" + +from types import SimpleNamespace +from typing import Any + +import numpy as np +import pytest +import torch +from torch.utils.data import DataLoader + +from xanesnet.batchprocessors import BatchProcessorRegistry +from xanesnet.batchprocessors.forward.base import ForwardBatchProcessor +from xanesnet.encodings import SpectraEncoding +from xanesnet.serialization.auto_config import ( + resolve_auto_encoding_config, + resolve_auto_model_config, +) +from xanesnet.serialization.auto_config import statistics as statistics_module +from xanesnet.serialization.auto_config.helpers import ( + format_value, + requested_auto_fields, +) +from xanesnet.serialization.auto_config.registries import ( + EncodingAutoResolver, + ModelAutoResolver, +) +from xanesnet.serialization.auto_config.statistics import ( + SpectralStatistics, + SpectralStatisticsCollector, + collect_spectral_statistics, +) +from xanesnet.serialization.config import Config +from xanesnet.utils.exceptions import ConfigError + +DATASET_TYPE = "unit_test_dataset" +MODEL_TYPE = "unit_test_model" +UNRESOLVED_MODEL_TYPE = "unit_test_unresolved_model" +ENCODING_TYPE = "unit_test_encoding" +UNRESOLVED_ENCODING_TYPE = "unit_test_unresolved_encoding" + +N_SAMPLES, N_FEATURES, N_POINTS = 6, 4, 5 + +############################################################################### +################################# TEST DOUBLES ################################ +############################################################################### + + +class FakeDataset: + """Dataset of ``N_SAMPLES`` samples; sample ``i`` has spectrum ``i + arange(N_POINTS)`` and element 26 or 29.""" + + dataset_type = DATASET_TYPE + train_subset = None + + def __len__(self) -> int: + return N_SAMPLES + + def __getitem__(self, index: int) -> dict[str, torch.Tensor]: + return { + "x": torch.full((N_FEATURES,), float(index)), + "y": index + torch.arange(N_POINTS, dtype=torch.float32), + "element": torch.tensor(26 if index % 2 == 0 else 29), + } + + @staticmethod + def collate_fn(samples: list[dict[str, torch.Tensor]]) -> SimpleNamespace: + return SimpleNamespace(**{key: torch.stack([s[key] for s in samples]) for key in samples[0]}) + + @staticmethod + def get_dataloader() -> type[DataLoader]: + return DataLoader + + +class FakeBatchProcessor(ForwardBatchProcessor): + def input_preparation(self, batch: Any) -> dict[str, Any]: + return {"x": batch.x} + + def target_preparation(self, batch: Any) -> torch.Tensor: + return batch.y + + def element_preparation(self, batch: Any) -> torch.Tensor: + return batch.element + + def sample_id_preparation(self, batch: Any) -> np.ndarray: + return np.array([""] * len(batch.x)) + + +for _model_type in (MODEL_TYPE, UNRESOLVED_MODEL_TYPE): + BatchProcessorRegistry.register((DATASET_TYPE, _model_type))(FakeBatchProcessor) + +RESOLVER_CALLS: list[Any] = [] + + +@ModelAutoResolver.register(MODEL_TYPE) +def _resolve_model(inputs, target, dataset): + RESOLVER_CALLS.append((inputs, target, dataset)) + return {"in_size": inputs["x"].shape[-1], "out_size": target.shape[-1]} + + +@ModelAutoResolver.register(UNRESOLVED_MODEL_TYPE) +def _resolve_nothing(inputs, target, dataset): + return {} + + +@EncodingAutoResolver.register(ENCODING_TYPE) +def _resolve_encoding(item, statistics): + return {"num_points": statistics.overall.num_points, "scale": statistics.overall.global_maximum} + + +@EncodingAutoResolver.register(UNRESOLVED_ENCODING_TYPE) +def _resolve_nothing_for_encoding(item, statistics): + return {} + + +@pytest.fixture(autouse=True) +def _single_process_statistics(monkeypatch): + """Collect statistics in-process: worker processes would only slow these tests down.""" + monkeypatch.setattr(statistics_module, "STATISTICS_NUM_WORKERS", 0) + RESOLVER_CALLS.clear() + + +@pytest.fixture +def dataset() -> FakeDataset: + return FakeDataset() + + +def _train_config(model: dict[str, Any], encodings: list[dict[str, Any]]) -> Config: + return Config({"model": model, "encodings": encodings}) + + +############################################################################### +################################### HELPERS ################################### +############################################################################### + + +def test_requested_auto_fields_finds_case_insensitive_tokens_at_the_top_level_only(): + section = {"in_size": "auto", "out_size": "AUTO", "hidden": 8, "name": "autonomous", "nested": {"x": "auto"}} + assert requested_auto_fields(section) == {"in_size", "out_size"} + + +def test_requested_auto_fields_of_a_concrete_section_is_empty(): + assert requested_auto_fields({"a": 1, "b": "x"}) == set() + + +@pytest.mark.parametrize( + "value, expected", + [ + (3, "3"), + ("text", "text"), + ([1, 2, 3], "[1, 2, 3]"), + ({"a": 1, "b": [2]}, "{a=1, b=[2]}"), + ], +) +def test_format_value_prints_small_values_in_full(value, expected): + assert format_value(value) == expected + + +def test_long_lists_are_truncated_with_their_length(): + text = format_value(list(range(20))) + assert text == "[0, 1, 2, ...] (len=20)" + + +def test_long_nested_lists_report_rows_and_inner_length(): + text = format_value([[0, 0]] * 10) + assert "rows=10" in text and "inner_len=2" in text + + +def test_ragged_nested_lists_report_all_inner_lengths(): + text = format_value([[0] * (1 + i % 2) for i in range(10)]) + assert "inner_lens=[1, 2]" in text + + +def test_large_dicts_are_truncated_with_their_key_count(): + text = format_value({f"k{i}": i for i in range(6)}) + assert text == "{k0=0, k1=1, k2=2, ... (keys=6)}" + + +############################################################################### +########################### STREAMING STATISTICS ############################## +############################################################################### + + +def test_statistics_match_the_full_batch_computation_regardless_of_chunking(): + data = torch.randn(50, 7, generator=torch.Generator().manual_seed(0)) + chunked = SpectralStatistics() + for start in range(0, 50, 13): + chunked.update(data[start : start + 13]) + + torch.testing.assert_close(chunked.mean, data.double().mean(0)) + torch.testing.assert_close(chunked.std, data.double().std(0, unbiased=False)) + torch.testing.assert_close(chunked.minimum, data.double().amin(0)) + torch.testing.assert_close(chunked.maximum, data.double().amax(0)) + assert chunked.num_points == 7 + + +def test_global_statistics_aggregate_over_all_points(): + stats = SpectralStatistics() + stats.update(torch.tensor([[1.0, 3.0], [5.0, 7.0]])) + + assert stats.global_mean == pytest.approx(4.0) + assert stats.global_std == pytest.approx(np.std([1, 3, 5, 7])) + assert stats.global_minimum == 1.0 + assert stats.global_maximum == 7.0 + + +def test_constant_spectra_have_zero_standard_deviation(): + stats = SpectralStatistics() + stats.update(torch.full((4, 3), 2.5)) + assert torch.count_nonzero(stats.std) == 0 + assert stats.global_std == 0.0 + + +def test_collector_without_elements_only_tracks_the_overall_statistics(): + collector = SpectralStatisticsCollector() + collector.update(torch.ones(3, 2)) + assert collector.overall.num_points == 2 + assert collector.sorted_elements() == [] + + +def test_collector_routes_rows_to_their_element_bucket(): + collector = SpectralStatisticsCollector() + spectra = torch.tensor([[1.0], [10.0], [3.0], [30.0]]) + collector.update(spectra, torch.tensor([26, 29, 26, 29])) + collector.update(torch.tensor([[5.0]]), torch.tensor([26])) + + assert collector.sorted_elements() == [26, 29] + assert collector.element_stats(26).mean.item() == pytest.approx(3.0) + assert collector.element_stats(29).mean.item() == pytest.approx(20.0) + assert collector.overall.mean.item() == pytest.approx(49.0 / 5) + + +def test_collector_reports_unknown_elements(): + collector = SpectralStatisticsCollector() + collector.update(torch.ones(1, 2), torch.tensor([26])) + with pytest.raises(ConfigError, match="Element 8 not found"): + collector.element_stats(8) + + +def test_collect_spectral_statistics_streams_the_whole_dataset(dataset): + collector = collect_spectral_statistics(dataset, FakeBatchProcessor()) + + expected = torch.stack([dataset[i]["y"] for i in range(N_SAMPLES)]).double() + torch.testing.assert_close(collector.overall.mean, expected.mean(0)) + assert collector.sorted_elements() == [26, 29] + assert collector.element_stats(26).mean[0].item() == pytest.approx((0 + 2 + 4) / 3) + + +def test_collect_spectral_statistics_uses_the_training_subset_when_present(dataset): + dataset.train_subset = [dataset[0], dataset[1]] + collector = collect_spectral_statistics(dataset, FakeBatchProcessor()) + assert collector.overall.mean[0].item() == pytest.approx(0.5) + + +############################################################################### +############################ MODEL AUTO RESOLUTION ############################ +############################################################################### + + +def test_model_auto_fields_are_replaced_by_resolved_values(dataset): + config = _train_config({"model_type": MODEL_TYPE, "in_size": "auto", "out_size": "AUTO", "hidden": 8}, []) + + resolved = resolve_auto_model_config(config, dataset, encoding=None) # type: ignore[arg-type] + + assert resolved.section("model").as_dict() == { + "model_type": MODEL_TYPE, + "in_size": N_FEATURES, + "out_size": N_POINTS, + "hidden": 8, + } + + +def test_model_resolution_does_not_mutate_the_input_config(dataset): + config = _train_config({"model_type": MODEL_TYPE, "in_size": "auto"}, []) + resolve_auto_model_config(config, dataset, encoding=None) # type: ignore[arg-type] + assert config.section("model").get_str("in_size") == "auto" + + +def test_resolver_sees_the_first_sample_as_representative(dataset): + resolve_auto_model_config( + _train_config({"model_type": MODEL_TYPE, "in_size": "auto"}, []), dataset, None # type: ignore[arg-type] + ) + + inputs, target, seen_dataset = RESOLVER_CALLS[0] + assert inputs["x"].shape == (1, N_FEATURES) + assert target.shape == (1, N_POINTS) + assert seen_dataset is dataset + + +def test_resolved_dimensions_reflect_the_encoding(dataset): + class Doubling(SpectraEncoding): + def __init__(self) -> None: + super().__init__("doubling") + + def output_size(self, input_size: int) -> int: + return 2 * input_size + + def encode(self, targets: torch.Tensor, elements: torch.Tensor | None = None) -> torch.Tensor: + return torch.cat([targets, targets], dim=-1) + + def decode(self, predictions: torch.Tensor, elements: torch.Tensor | None = None) -> torch.Tensor: + first, second = predictions.chunk(2, dim=-1) + return (first + second) / 2 + + @property + def signature(self) -> list[Config]: + return [Config({"encoding_type": "doubling"})] + + config = _train_config({"model_type": MODEL_TYPE, "out_size": "auto"}, []) + + resolved = resolve_auto_model_config(config, dataset, encoding=Doubling()) + + assert resolved.section("model").get_int("out_size") == 2 * N_POINTS + + +def test_model_without_auto_fields_skips_resolution_entirely(dataset): + config = _train_config({"model_type": MODEL_TYPE, "in_size": 3}, []) + resolved = resolve_auto_model_config(config, dataset, encoding=None) # type: ignore[arg-type] + assert resolved.as_dict() == config.as_dict() + assert RESOLVER_CALLS == [] + + +def test_auto_fields_for_a_model_without_resolver_are_rejected(dataset): + BatchProcessorRegistry.register((DATASET_TYPE, "unit_test_no_resolver_model"))(FakeBatchProcessor) + config = _train_config({"model_type": "unit_test_no_resolver_model", "in_size": "auto"}, []) + with pytest.raises(ConfigError, match="No automatic model config resolver registered"): + resolve_auto_model_config(config, dataset, encoding=None) # type: ignore[arg-type] + + +def test_resolver_that_misses_a_requested_field_is_reported(dataset): + config = _train_config({"model_type": UNRESOLVED_MODEL_TYPE, "in_size": "auto"}, []) + with pytest.raises(ConfigError, match="did not produce model.in_size"): + resolve_auto_model_config(config, dataset, encoding=None) # type: ignore[arg-type] + + +############################################################################### +########################## ENCODING AUTO RESOLUTION ########################### +############################################################################### + + +def test_encoding_auto_fields_are_resolved_from_dataset_statistics(dataset): + encodings = [{"encoding_type": ENCODING_TYPE, "num_points": "auto", "scale": "auto", "fixed": 1}] + + resolved = resolve_auto_encoding_config(_train_config({"model_type": MODEL_TYPE}, encodings), dataset) + + assert resolved.get_config_list("encodings")[0].as_dict() == { + "encoding_type": ENCODING_TYPE, + "num_points": N_POINTS, + "scale": float(N_SAMPLES - 1 + N_POINTS - 1), + "fixed": 1, + } + + +def test_encoding_resolution_does_not_mutate_the_input_config(dataset): + encodings = [{"encoding_type": ENCODING_TYPE, "num_points": "auto"}] + config = _train_config({"model_type": MODEL_TYPE}, encodings) + resolve_auto_encoding_config(config, dataset) + assert config.get_config_list("encodings")[0].get_str("num_points") == "auto" + + +def test_nested_concat_encodings_are_resolved_recursively(dataset): + encodings = [ + { + "encoding_type": "concat", + "encodings": [ + {"encoding_type": ENCODING_TYPE, "num_points": "auto"}, + {"encoding_type": "identity"}, + ], + } + ] + + resolved = resolve_auto_encoding_config(_train_config({"model_type": MODEL_TYPE}, encodings), dataset) + + nested = resolved.as_dict()["encodings"][0]["encodings"] + assert nested[0]["num_points"] == N_POINTS + assert nested[1] == {"encoding_type": "identity"} + + +def test_encodings_without_auto_fields_do_not_touch_the_dataset(): + class ExplodingDataset: + dataset_type = DATASET_TYPE + + def __getattr__(self, name): + raise AssertionError(f"dataset.{name} must not be accessed when nothing is 'auto'") + + config = _train_config({"model_type": MODEL_TYPE}, [{"encoding_type": ENCODING_TYPE, "num_points": 5}]) + resolved = resolve_auto_encoding_config(config, ExplodingDataset()) # type: ignore[arg-type] + assert resolved.as_dict() == config.as_dict() + + +def test_auto_fields_for_an_encoding_without_resolver_are_rejected(dataset): + encodings = [{"encoding_type": "unit_test_no_resolver_encoding", "num_points": "auto"}] + with pytest.raises(ConfigError, match="No automatic encoding config resolver registered"): + resolve_auto_encoding_config(_train_config({"model_type": MODEL_TYPE}, encodings), dataset) + + +def test_encoding_resolver_that_misses_a_field_is_reported(dataset): + encodings = [{"encoding_type": UNRESOLVED_ENCODING_TYPE, "num_points": "auto"}] + with pytest.raises(ConfigError, match="did not produce num_points"): + resolve_auto_encoding_config(_train_config({"model_type": MODEL_TYPE}, encodings), dataset) + + +def test_batch_processor_registry_is_consulted_with_the_dataset_and_model_type(dataset): + """An unregistered dataset/model pair surfaces as the registry's ``KeyError``.""" + encodings = [{"encoding_type": ENCODING_TYPE, "num_points": "auto"}] + with pytest.raises(KeyError, match="not found"): + resolve_auto_encoding_config(_train_config({"model_type": "unit_test_unregistered"}, encodings), dataset) diff --git a/tests/unit/serialization/test_checkpoints.py b/tests/unit/serialization/test_checkpoints.py new file mode 100644 index 00000000..e58fdf0f --- /dev/null +++ b/tests/unit/serialization/test_checkpoints.py @@ -0,0 +1,206 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for ``Checkpoint``: state-dict conversion, persistence and per-member splitting.""" + +import pytest +import torch + +from xanesnet.serialization.checkpoints import Checkpoint +from xanesnet.serialization.config import Config + + +class _Unsafe: + """Arbitrary object that ``weights_only`` unpickling must refuse to construct.""" + + +def _model_state(value: float) -> dict[str, torch.Tensor]: + return {"linear.weight": torch.full((2, 3), value), "linear.bias": torch.full((2,), value)} + + +def _training_state(n_members: int) -> dict: + return { + "epochs": list(range(10, 10 + n_members)), + "optimizer_signature": {"trainer": {"optimizer_type": "adam"}}, + "optimizer_states": [{"step": i} for i in range(n_members)], + "scheduler_signature": {"trainer": {"lr_warmup": False}}, + "epoch_scheduler_states": [{"last_epoch": i} for i in range(n_members)], + "warmup_scheduler_states": [None for _ in range(n_members)], + } + + +@pytest.fixture +def signature() -> Config: + return Config({"model": {"model_type": "mlp", "in_size": 4}, "encodings": [{"encoding_type": "identity"}]}) + + +@pytest.fixture +def full_checkpoint(signature) -> Checkpoint: + return Checkpoint(signature, [_model_state(1.0)], _training_state(1)) + + +@pytest.fixture +def ensemble_checkpoint(signature) -> Checkpoint: + return Checkpoint(signature, [_model_state(float(i)) for i in range(3)], _training_state(3)) + + +############################################################################### +############################## STATE-DICT CONVERSION ########################## +############################################################################### + + +def test_state_dict_contains_signature_as_plain_dict(signature): + state = Checkpoint(signature, [_model_state(1.0)]).to_state_dict() + assert state["signature"] == signature.as_dict() + assert isinstance(state["signature"], dict) + + +def test_state_dict_omits_training_state_when_absent(signature): + assert "training_state" not in Checkpoint(signature, [_model_state(1.0)]).to_state_dict() + + +def test_state_dict_round_trip_restores_equal_checkpoint(full_checkpoint): + restored = Checkpoint.from_state_dict(full_checkpoint.to_state_dict()) + + assert isinstance(restored.signature, Config) + assert restored.signature.as_dict() == full_checkpoint.signature.as_dict() + assert restored.training_state == full_checkpoint.training_state + torch.testing.assert_close(restored.model_states[0]["linear.weight"], torch.full((2, 3), 1.0)) + + +def test_from_state_dict_without_training_state_gives_none(signature): + restored = Checkpoint.from_state_dict({"signature": signature.as_dict(), "model_states": []}) + assert restored.training_state is None + + +############################################################################### +################################# PERSISTENCE ################################# +############################################################################### + + +def test_save_writes_minimal_and_full_files(full_checkpoint, tmp_path): + path = full_checkpoint.save(tmp_path / "final.pth") + + assert path == tmp_path / "final.pth" + assert path.is_file() + assert (tmp_path / "final_full.pth").is_file() + + +def test_minimal_file_carries_no_training_state(full_checkpoint, tmp_path): + full_checkpoint.save(tmp_path / "final.pth") + assert Checkpoint.load(tmp_path / "final.pth").training_state is None + + +def test_full_file_restores_training_state(full_checkpoint, tmp_path): + full_checkpoint.save(tmp_path / "final.pth") + assert Checkpoint.load(tmp_path / "final_full.pth").training_state == full_checkpoint.training_state + + +def test_save_without_training_state_writes_only_the_minimal_file(signature, tmp_path): + Checkpoint(signature, [_model_state(1.0)]).save(tmp_path / "final.pth") + assert sorted(p.name for p in tmp_path.iterdir()) == ["final.pth"] + + +def test_load_restores_weights_and_signature_exactly(full_checkpoint, tmp_path): + full_checkpoint.save(tmp_path / "final.pth") + + loaded = Checkpoint.load(tmp_path / "final.pth") + + assert loaded.signature.as_dict() == full_checkpoint.signature.as_dict() + assert len(loaded.model_states) == 1 + for name, tensor in full_checkpoint.model_states[0].items(): + torch.testing.assert_close(loaded.model_states[0][name], tensor) + + +def test_load_refuses_files_that_would_need_arbitrary_unpickling(tmp_path): + """Checkpoints are loaded with ``weights_only=True`` so unsafe pickles must not execute.""" + + path = tmp_path / "unsafe.pth" + torch.save({"signature": {}, "model_states": [], "payload": _Unsafe()}, path) + + with pytest.raises(Exception, match="(?i)weights_only|unpickl"): + Checkpoint.load(path) + + +############################################################################### +############################### SEPARATE MEMBERS ############################## +############################################################################### + + +def test_save_separate_is_a_noop_for_single_model_checkpoints(full_checkpoint, tmp_path): + assert full_checkpoint.save_separate(tmp_path / "final.pth") == [] + assert list(tmp_path.iterdir()) == [] + + +def test_save_separate_writes_one_pair_per_member(ensemble_checkpoint, tmp_path): + paths = ensemble_checkpoint.save_separate(tmp_path / "final.pth") + + assert [p.name for p in paths] == [f"final_member_{i}.pth" for i in range(3)] + assert sorted(p.name for p in tmp_path.iterdir()) == sorted( + [f"final_member_{i}.pth" for i in range(3)] + [f"final_member_{i}_full.pth" for i in range(3)] + ) + + +def test_each_member_checkpoint_holds_only_its_own_state(ensemble_checkpoint, tmp_path): + paths = ensemble_checkpoint.save_separate(tmp_path / "final.pth") + + for index, path in enumerate(paths): + member = Checkpoint.load(path) + assert len(member.model_states) == 1 + torch.testing.assert_close(member.model_states[0]["linear.weight"], torch.full((2, 3), float(index))) + assert member.signature.as_dict() == ensemble_checkpoint.signature.as_dict() + + +def test_member_training_state_is_sliced_per_member_but_shared_values_are_kept(ensemble_checkpoint, tmp_path): + paths = ensemble_checkpoint.save_separate(tmp_path / "final.pth") + + member = Checkpoint.load(paths[1].with_name("final_member_1_full.pth")) + assert member.training_state == { + "epochs": [11], + "optimizer_signature": {"trainer": {"optimizer_type": "adam"}}, + "optimizer_states": [{"step": 1}], + "scheduler_signature": {"trainer": {"lr_warmup": False}}, + "epoch_scheduler_states": [{"last_epoch": 1}], + "warmup_scheduler_states": [None], + } + + +def test_save_separate_does_not_mutate_the_source_checkpoint(ensemble_checkpoint, tmp_path): + before = { + key: list(value) if isinstance(value, list) else value + for key, value in ensemble_checkpoint.training_state.items() + } + ensemble_checkpoint.save_separate(tmp_path / "final.pth") + assert ensemble_checkpoint.training_state == before + assert len(ensemble_checkpoint.model_states) == 3 + + +def test_save_separate_without_training_state_writes_minimal_files_only(signature, tmp_path): + checkpoint = Checkpoint(signature, [_model_state(0.0), _model_state(1.0)]) + paths = checkpoint.save_separate(tmp_path / "final.pth") + assert [p.name for p in paths] == ["final_member_0.pth", "final_member_1.pth"] + assert len(list(tmp_path.iterdir())) == 2 diff --git a/tests/unit/serialization/test_config_accessors.py b/tests/unit/serialization/test_config_accessors.py new file mode 100644 index 00000000..3455ff28 --- /dev/null +++ b/tests/unit/serialization/test_config_accessors.py @@ -0,0 +1,267 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the typed ``Config`` wrapper: accessors, conversion and merging.""" + +import pytest +import yaml + +from xanesnet.serialization.config import Config +from xanesnet.utils.exceptions import ConfigError + + +@pytest.fixture +def config() -> Config: + return Config( + { + "name": "run", + "count": 3, + "rate": 0.5, + "flag": True, + "nothing": None, + "items": [{"a": 1}, {"b": 2}], + "numbers": [1, 2, 3], + "model": {"model_type": "mlp", "layers": [{"size": 4}], "dropout": 0.1}, + } + ) + + +############################################################################### +############################### TYPED ACCESSORS ############################### +############################################################################### + +TYPED_CASES = [ + ("get_str", "name", "run"), + ("get_int", "count", 3), + ("get_float", "rate", 0.5), + ("get_bool", "flag", True), +] + + +@pytest.mark.parametrize("getter, key, expected", TYPED_CASES) +def test_required_accessor_returns_the_value(config, getter, key, expected): + value = getattr(config, getter)(key) + assert value == expected + assert type(value) is type(expected) + + +@pytest.mark.parametrize("getter, key, expected", TYPED_CASES) +def test_optional_accessor_returns_the_value_when_present(config, getter, key, expected): + assert getattr(config, getter.replace("get_", "get_optional_"))(key) == expected + + +@pytest.mark.parametrize("getter", ["get_str", "get_int", "get_float", "get_bool"]) +@pytest.mark.parametrize("key", ["absent", "nothing"], ids=["missing", "null"]) +def test_required_accessor_treats_missing_and_null_as_missing(config, getter, key): + with pytest.raises(ConfigError, match=f"Key '{key}' is missing"): + getattr(config, getter)(key) + + +@pytest.mark.parametrize("getter", ["get_str", "get_int", "get_float", "get_bool"]) +@pytest.mark.parametrize("key", ["absent", "nothing"], ids=["missing", "null"]) +def test_optional_accessor_returns_none_for_missing_and_null(config, getter, key): + assert getattr(config, getter.replace("get_", "get_optional_"))(key) is None + + +@pytest.mark.parametrize( + "getter, key", + [ + ("get_str", "count"), + ("get_int", "name"), + ("get_int", "rate"), + ("get_float", "count"), + ("get_float", "name"), + ("get_bool", "count"), + ("get_bool", "name"), + ], +) +def test_wrong_type_is_rejected(config, getter, key): + with pytest.raises(ConfigError, match=f"Key '{key}' is not of type"): + getattr(config, getter)(key) + + +@pytest.mark.parametrize("getter, key", [("get_optional_int", "name"), ("get_optional_str", "count")]) +def test_optional_accessor_still_validates_the_type_of_present_values(config, getter, key): + with pytest.raises(ConfigError, match="is not of type"): + getattr(config, getter)(key) + + +def test_raw_get_returns_any_value_including_none(config): + assert config.get("count") == 3 + assert config.get("nothing") is None + + +def test_raw_get_of_absent_key_raises(config): + with pytest.raises(ConfigError, match="Key 'absent' is missing"): + config.get("absent") + + +############################################################################### +################################## SECTIONS ################################### +############################################################################### + + +def test_section_returns_a_config_over_the_nested_dict(config): + section = config.section("model") + assert isinstance(section, Config) + assert section.get_str("model_type") == "mlp" + + +@pytest.mark.parametrize("key", ["absent", "nothing"]) +def test_missing_section_raises(config, key): + with pytest.raises(ConfigError, match="is missing"): + config.section(key) + + +def test_non_dict_section_raises(config): + with pytest.raises(ConfigError, match="is not of type dict"): + config.section("numbers") + + +def test_optional_section(config): + assert config.optional_section("absent") is None + assert config.optional_section("nothing") is None + assert config.optional_section("model").get_float("dropout") == 0.1 # type: ignore[union-attr] + with pytest.raises(ConfigError, match="is not of type dict"): + config.optional_section("count") + + +def test_get_config_list_wraps_each_dictionary(config): + items = config.get_config_list("items") + assert [type(item) for item in items] == [Config, Config] + assert [item.as_dict() for item in items] == [{"a": 1}, {"b": 2}] + + +def test_get_config_list_rejects_non_dictionary_elements(config): + with pytest.raises(ConfigError, match="must be a list of dictionaries"): + config.get_config_list("numbers") + + +def test_get_config_list_rejects_non_lists(config): + with pytest.raises(ConfigError, match="is not of type list"): + config.get_config_list("name") + + +def test_empty_list_yields_no_configs(): + assert Config({"items": []}).get_config_list("items") == [] + + +############################################################################### +################################# CONVERSION ################################## +############################################################################### + + +def test_as_dict_returns_a_deep_copy(config): + snapshot = config.as_dict() + snapshot["model"]["layers"].append({"size": 99}) + snapshot["count"] = 0 + assert config.get_int("count") == 3 + assert config.as_dict()["model"]["layers"] == [{"size": 4}] + + +def test_constructor_unwraps_nested_config_objects(): + outer = Config({"inner": Config({"x": 1}), "many": [Config({"y": 2})]}) + assert outer.as_dict() == {"inner": {"x": 1}, "many": [{"y": 2}]} + + +def test_as_kwargs_wraps_dicts_and_lists_of_dicts(config): + kwargs = config.as_kwargs() + + assert isinstance(kwargs["model"], Config) + assert all(isinstance(item, Config) for item in kwargs["items"]) + assert kwargs["name"] == "run" + assert kwargs["numbers"] == [1, 2, 3] + assert kwargs["nothing"] is None + + +def test_as_kwargs_wraps_dictionaries_nested_inside_lists(config): + layers = config.as_kwargs()["model"].as_kwargs()["layers"] + assert isinstance(layers[0], Config) + assert layers[0].get_int("size") == 4 + + +def test_as_kwargs_does_not_alias_the_internal_state(config): + kwargs = config.as_kwargs() + kwargs["numbers"].append(4) + assert config.as_dict()["numbers"] == [1, 2, 3] + + +############################################################################### +################################### UPDATING ################################## +############################################################################### + + +def test_update_with_dict_adds_missing_keys_and_merges_nested_dicts(config): + config.update_with_dict({"extra": 1, "model": {"width": 8}}) + assert config.get_int("extra") == 1 + assert config.section("model").as_dict() == { + "model_type": "mlp", + "layers": [{"size": 4}], + "dropout": 0.1, + "width": 8, + } + + +def test_update_with_dict_accepts_equal_values(config): + config.update_with_dict({"count": 3}) + assert config.get_int("count") == 3 + + +def test_update_with_dict_rejects_conflicting_values_and_keeps_state(config): + before = config.as_dict() + with pytest.raises(ConfigError, match="Conflict for key 'count'"): + config.update_with_dict({"count": 4}) + assert config.as_dict() == before + + +def test_update_with_another_config(config): + config.update(Config({"extra": "x"})) + assert config.get_str("extra") == "x" + + +def test_update_does_not_alias_the_other_config(): + target, other = Config({"a": 1}), Config({"nested": {"k": 1}}) + target.update(other) + other.update_with_dict({"nested": {"added": 2}}) + assert target.as_dict() == {"a": 1, "nested": {"k": 1}} + + +############################################################################### +################################### SAVING #################################### +############################################################################### + + +def test_save_writes_yaml_that_loads_back_equal(config, tmp_path): + path = config.save(tmp_path / "out.yaml") + assert path == tmp_path / "out.yaml" + assert yaml.safe_load(path.read_text()) == config.as_dict() + + +def test_save_refuses_to_overwrite(config, tmp_path): + config.save(tmp_path / "out.yaml") + with pytest.raises(ConfigError, match="already exists"): + config.save(tmp_path / "out.yaml") diff --git a/tests/unit/serialization/test_config_io.py b/tests/unit/serialization/test_config_io.py new file mode 100644 index 00000000..c7fa5a0e --- /dev/null +++ b/tests/unit/serialization/test_config_io.py @@ -0,0 +1,173 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for raw configuration I/O: load, save, copy and round-trips.""" + +import pytest +import yaml + +from xanesnet.serialization.config import copy_raw_config, load_raw_config, merge_raw_configs, save_raw_config +from xanesnet.utils.exceptions import ConfigError + +############################################################################### +################################ load_raw_config ############################## +############################################################################### + + +@pytest.mark.parametrize("name", ["config.yaml", "config.yml"]) +def test_load_returns_the_parsed_dictionary(write_yaml, train_config, name): + path = write_yaml(train_config, name=name) + assert load_raw_config(path) == train_config + + +def test_load_missing_file_raises(tmp_path): + with pytest.raises(ConfigError, match="does not exist"): + load_raw_config(tmp_path / "missing.yaml") + + +def test_load_invalid_yaml_raises(write_yaml): + path = write_yaml("key: [unclosed\n") + with pytest.raises(ConfigError, match="Error parsing YAML"): + load_raw_config(path) + + +@pytest.mark.parametrize("text", ["- a\n- b\n", "just a string\n", ""], ids=["list", "string", "empty-file"]) +def test_load_non_mapping_top_level_raises(write_yaml, text): + path = write_yaml(text) + with pytest.raises(ConfigError, match="top-level dictionary"): + load_raw_config(path) + + +############################################################################### +################################ save_raw_config ############################## +############################################################################### + + +def test_save_writes_a_yaml_file_and_returns_its_path(tmp_path, train_config): + destination = tmp_path / "saved.yaml" + assert save_raw_config(train_config, destination) == destination + assert yaml.safe_load(destination.read_text()) == train_config + + +@pytest.mark.parametrize("name", ["config.txt", "config.json", "config"]) +def test_save_rejects_wrong_extension(tmp_path, name): + with pytest.raises(ConfigError, match="extension"): + save_raw_config({"seed": 1}, tmp_path / name) + assert not (tmp_path / name).exists() + + +def test_save_rejects_missing_parent_directory(tmp_path): + with pytest.raises(ConfigError, match="Directory for config file does not exist"): + save_raw_config({"seed": 1}, tmp_path / "no_such_dir" / "config.yaml") + + +def test_save_refuses_to_overwrite_and_keeps_original(tmp_path): + destination = save_raw_config({"seed": 1}, tmp_path / "config.yaml") + with pytest.raises(ConfigError, match="already exists"): + save_raw_config({"seed": 2}, destination) + assert yaml.safe_load(destination.read_text()) == {"seed": 1} + + +############################################################################### +################################ copy_raw_config ############################## +############################################################################### + + +@pytest.mark.parametrize("new_name, expected", [(None, "source.yaml"), ("renamed.yaml", "renamed.yaml")]) +def test_copy_keeps_or_changes_the_filename(write_yaml, tmp_path, new_name, expected): + source = write_yaml({"seed": 1}, name="source.yaml") + destination_dir = tmp_path / "out" + destination_dir.mkdir() + + result = copy_raw_config(source, destination_dir, new_name=new_name) + + assert result == destination_dir / expected + assert load_raw_config(result) == {"seed": 1} + assert source.is_file(), "the source file must be left in place" + + +def test_copy_missing_source_raises(tmp_path): + with pytest.raises(FileNotFoundError): + copy_raw_config(tmp_path / "missing.yaml", tmp_path) + + +def test_copy_rejects_non_yaml_suffix(tmp_path): + source = tmp_path / "source.txt" + source.write_text("seed: 1\n") + with pytest.raises(ValueError, match="suffix"): + copy_raw_config(source, tmp_path) + + +############################################################################### +################################## ROUND TRIP ################################# +############################################################################### + + +def test_save_then_load_round_trip_preserves_values_and_key_order(tmp_path): + config = { + "zeta": 1, + "none": None, + "auto": "auto", + "flag": False, + "small": 1e-3, + "nested": {"values": [1, 2.5, "x", None], "empty": {}}, + } + saved = save_raw_config(config, tmp_path / "round_trip.yaml") + + loaded = load_raw_config(saved) + + assert loaded == config + assert list(loaded) == list(config) + + +############################################################################### +################################### MERGING ################################### +############################################################################### + + +def test_merge_unites_keys_and_merges_nested_dicts_recursively(): + base = {"seed": 1, "model": {"model_type": "mlp", "in_size": 4}} + overlay = {"seed": 1, "model": {"model_type": "mlp", "out_size": 8}, "device": "cpu"} + assert merge_raw_configs(base, overlay) == { + "seed": 1, + "model": {"model_type": "mlp", "in_size": 4, "out_size": 8}, + "device": "cpu", + } + + +@pytest.mark.parametrize( + "base, overlay, key", + [ + ({"a": 1}, {"a": 2}, "a"), + ({"model": {"head": {"hidden_size": 1}}}, {"model": {"head": {"hidden_size": 2}}}, "hidden_size"), + ({"model": {"model_type": "mlp"}}, {"model": {"model_type": "MLP"}}, "model_type"), + ], + ids=["scalar", "deeply-nested", "case-sensitive"], +) +def test_merge_conflict_raises_and_names_the_key(base, overlay, key): + with pytest.raises(ConfigError, match=f"Conflict for key '{key}'"): + merge_raw_configs(base, overlay) diff --git a/tests/unit/serialization/test_jsonl_stream.py b/tests/unit/serialization/test_jsonl_stream.py new file mode 100644 index 00000000..f3ee5ee1 --- /dev/null +++ b/tests/unit/serialization/test_jsonl_stream.py @@ -0,0 +1,149 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for ``JSONLStream`` and ``json_friendly``.""" + +import json +import logging +from pathlib import Path + +import numpy as np +import pytest +import torch + +from xanesnet.serialization.jsonl_stream import JSONLStream, json_friendly + +RECORDS = [{"id": 0, "x": [1, 2]}, {"id": 1, "x": []}, {"id": 2, "x": [3]}] + + +@pytest.fixture +def jsonl_file(tmp_path: Path) -> Path: + path = tmp_path / "data.jsonl" + path.write_text("\n".join(json.dumps(r) for r in RECORDS) + "\n") + return path + + +############################################################################### +################################## JSONLStream ################################ +############################################################################### + + +def test_iteration_yields_records_in_file_order(jsonl_file): + assert list(JSONLStream(jsonl_file)) == RECORDS + + +def test_iteration_is_repeatable(jsonl_file): + stream = JSONLStream(jsonl_file) + assert list(stream) == list(stream) + + +def test_blank_lines_are_skipped(tmp_path): + path = tmp_path / "data.jsonl" + path.write_text('{"a": 1}\n\n \n{"a": 2}\n') + assert list(JSONLStream(path)) == [{"a": 1}, {"a": 2}] + + +def test_empty_file_yields_nothing(tmp_path): + path = tmp_path / "empty.jsonl" + path.write_text("") + assert list(JSONLStream(path)) == [] + assert len(JSONLStream(path)) == 0 + + +def test_explicit_count_is_trusted_without_touching_the_file(tmp_path): + assert len(JSONLStream(tmp_path / "does_not_exist.jsonl", count=7)) == 7 + + +def test_count_is_read_from_the_meta_sidecar(jsonl_file): + jsonl_file.with_suffix(".meta.json").write_text(json.dumps({"count": 42})) + assert len(JSONLStream(jsonl_file)) == 42 + + +def test_count_falls_back_to_scanning_and_warns(jsonl_file, caplog): + with caplog.at_level(logging.WARNING): + assert len(JSONLStream(jsonl_file)) == len(RECORDS) + assert "Counting lines" in caplog.text + + +def test_scanned_count_ignores_blank_lines(tmp_path): + path = tmp_path / "data.jsonl" + path.write_text('{"a": 1}\n\n{"a": 2}\n\n') + assert len(JSONLStream(path)) == 2 + + +def test_count_is_cached_after_the_first_lookup(jsonl_file): + stream = JSONLStream(jsonl_file) + assert len(stream) == 3 + jsonl_file.write_text("") + assert len(stream) == 3 + + +############################################################################### +################################# json_friendly ############################### +############################################################################### + + +@pytest.mark.parametrize("value", [None, "text", 3, 2.5, True]) +def test_json_primitives_pass_through(value): + assert json_friendly(value) == value + + +def test_paths_become_strings(): + assert json_friendly(Path("/tmp/x")) == "/tmp/x" + + +def test_containers_are_converted_recursively_and_tuples_become_lists(): + value = {"path": Path("a"), "items": (1, np.float32(2.0), [np.int64(3)])} + assert json_friendly(value) == {"path": "a", "items": [1, 2.0, [3]]} + + +@pytest.mark.parametrize( + "scalar, expected_type", + [(np.float32(1.5), float), (np.int64(4), int), (np.bool_(True), bool)], +) +def test_numpy_scalars_are_unwrapped_to_python_types(scalar, expected_type): + out = json_friendly(scalar) + assert type(out) is expected_type + assert out == scalar + + +def test_arrays_and_tensors_become_nested_lists(): + assert json_friendly(np.array([[1, 2], [3, 4]])) == [[1, 2], [3, 4]] + assert json_friendly(torch.tensor([[1.0, 2.0]])) == [[1.0, 2.0]] + + +def test_unknown_objects_fall_back_to_str(): + class Thing: + def __str__(self) -> str: + return "thing" + + assert json_friendly(Thing()) == "thing" + + +def test_result_is_always_json_serializable(): + payload = {"a": np.arange(3), "b": Path("p"), "c": {1, 2}, "d": torch.tensor(2)} + json.dumps(json_friendly(payload)) diff --git a/tests/unit/serialization/test_metadata.py b/tests/unit/serialization/test_metadata.py new file mode 100644 index 00000000..cd56bf22 --- /dev/null +++ b/tests/unit/serialization/test_metadata.py @@ -0,0 +1,200 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for run metadata collection (software, hardware and git information).""" + +import subprocess + +import pytest +import torch + +import xanesnet +from xanesnet.serialization import metadata +from xanesnet.serialization.metadata import get_hardware_info, get_software_info, write_run_metadata + + +def _parse_info_file(path) -> dict[str, str]: + """Parse the ``key = value`` info format.""" + parsed = {} + for line in path.read_text(encoding="utf-8").splitlines(): + key, _, value = line.partition(" = ") + parsed[key] = value + return parsed + + +############################################################################### +################################ SOFTWARE INFO ################################ +############################################################################### + + +def test_software_info_reports_package_and_runtime_versions(): + info = get_software_info("train", ["-i", "config.yaml"]) + + assert info["package"] == "XANESNET" + assert info["version"] == xanesnet.__version__ + assert info["workflow"] == "train" + assert info["pytorch_version"] == torch.__version__ + assert info["python_version"].count(".") >= 1 + + +def test_command_line_is_shell_quoted(): + info = get_software_info("infer", ["-i", "my config.yaml", "-n", "a'b"]) + assert info["command_line_args"] == "-i 'my config.yaml' -n 'a'\"'\"'b'" + + +@pytest.mark.parametrize("args", [None, []]) +def test_missing_command_line_is_reported_as_unknown(args): + assert get_software_info("train", args)["command_line_args"] == "unknown" + + +def test_software_info_always_contains_git_fields(): + info = get_software_info("train") + assert {"git_commit", "git_branch", "git_dirty"} <= set(info) + + +def test_git_fields_degrade_to_unknown_when_git_is_unavailable(monkeypatch): + def no_git(*args, **kwargs): + raise FileNotFoundError("git") + + monkeypatch.setattr(metadata.subprocess, "run", no_git) + + info = get_software_info("train") + + assert (info["git_commit"], info["git_branch"], info["git_dirty"]) == ("unknown",) * 3 + + +@pytest.mark.parametrize("error", [subprocess.CalledProcessError(128, "git"), subprocess.TimeoutExpired("git", 5)]) +def test_git_failures_degrade_to_unknown(monkeypatch, error): + def failing_git(*args, **kwargs): + raise error + + monkeypatch.setattr(metadata.subprocess, "run", failing_git) + assert get_software_info("train")["git_commit"] == "unknown" + + +def _fake_git(outputs: dict[str, str]): + def run(command, **kwargs): + return subprocess.CompletedProcess(command, 0, stdout=outputs[command[1]] + "\n", stderr="") + + return run + + +@pytest.mark.parametrize("status, dirty", [("", "false"), (" M file.py", "true")]) +def test_git_dirty_flag_follows_porcelain_status(monkeypatch, status, dirty): + monkeypatch.setattr( + metadata.subprocess, "run", _fake_git({"rev-parse": "abc123", "branch": "main", "status": status}) + ) + info = get_software_info("train") + assert (info["git_commit"], info["git_branch"], info["git_dirty"]) == ("abc123", "main", dirty) + + +def test_detached_head_is_reported_as_detached(monkeypatch): + monkeypatch.setattr(metadata.subprocess, "run", _fake_git({"rev-parse": "abc", "branch": "", "status": ""})) + assert get_software_info("train")["git_branch"] == "detached" + + +############################################################################### +################################ HARDWARE INFO ################################ +############################################################################### + + +def test_hardware_info_contains_the_expected_fields(): + info = get_hardware_info() + expected = {"os", "kernel", "platform", "architecture", "cpu_model", "cpu_count", "ram_bytes", "cuda_available"} + assert expected <= set(info) + assert info["cuda_available"] in {"true", "false", "unknown"} + assert all(isinstance(value, str) and value for value in info.values()) + + +def test_hardware_info_reports_cuda_visible_devices(monkeypatch): + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0,1") + assert get_hardware_info()["cuda_visible_devices"] == "0,1" + monkeypatch.delenv("CUDA_VISIBLE_DEVICES") + assert get_hardware_info()["cuda_visible_devices"] == "unknown" + + +def test_cuda_probing_errors_do_not_break_hardware_collection(monkeypatch): + def broken() -> bool: + raise RuntimeError("driver exploded") + + monkeypatch.setattr(torch.cuda, "is_available", broken) + + info = get_hardware_info() + + assert info["cuda_available"] == "unknown" + assert info["gpu_count"] == "unknown" + + +def test_gpu_details_are_listed_per_device(monkeypatch): + class Props: + name, total_memory, major, minor = "FakeGPU", 1024, 8, 6 + + monkeypatch.setattr(torch.cuda, "is_available", lambda: True) + monkeypatch.setattr(torch.cuda, "device_count", lambda: 2) + monkeypatch.setattr(torch.cuda, "get_device_properties", lambda index: Props) + + info = get_hardware_info() + + assert info["cuda_available"] == "true" + assert info["gpu_count"] == "2" + assert info["gpu_1_name"] == "FakeGPU" + assert info["gpu_1_memory_bytes"] == "1024" + assert info["gpu_1_compute_capability"] == "8.6" + + +############################################################################### +############################### write_run_metadata ############################ +############################################################################### + + +def test_write_run_metadata_creates_both_info_files(tmp_path): + software_path, hardware_path = write_run_metadata(tmp_path, mode="train", command_line_args=["-i", "c.yaml"]) + + assert software_path == tmp_path / "software.info" + assert hardware_path == tmp_path / "hardware.info" + software = _parse_info_file(software_path) + assert software["workflow"] == "train" + assert software["command_line_args"] == "-i c.yaml" + assert "os" in _parse_info_file(hardware_path) + + +def test_write_run_metadata_accepts_string_paths(tmp_path): + software_path, _ = write_run_metadata(str(tmp_path), mode="analyze") + assert software_path.parent == tmp_path + + +def test_write_run_metadata_requires_an_existing_directory(tmp_path): + with pytest.raises(FileNotFoundError, match="Run directory does not exist"): + write_run_metadata(tmp_path / "missing", mode="train") + assert not (tmp_path / "missing").exists() + + +def test_write_run_metadata_rejects_files(tmp_path): + file = tmp_path / "file" + file.write_text("x") + with pytest.raises(FileNotFoundError): + write_run_metadata(file, mode="train") diff --git a/tests/unit/serialization/test_model_profile.py b/tests/unit/serialization/test_model_profile.py new file mode 100644 index 00000000..009afcc0 --- /dev/null +++ b/tests/unit/serialization/test_model_profile.py @@ -0,0 +1,108 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for model-profile persistence and device-aware memory helpers.""" + +import json + +import pytest +import torch + +from xanesnet.serialization.model_profile import ( + get_peak_memory_allocated_mb, + reset_peak_memory_stats, + save_model_profile, +) + + +@pytest.fixture +def profile() -> dict: + return { + "model_architecture": "Linear(3, 2)\n weights: 8", + "total_params": 8, + "trainable_params": 8, + "total_param_bytes": 32, + "model_size_mb": 3.0e-05, + "device": "cpu", + "peak_gpu_memory_allocated_mb": None, + } + + +############################################################################### +############################### save_model_profile ############################ +############################################################################### + + +def test_both_report_files_are_written(tmp_path, profile): + json_path, text_path = save_model_profile(tmp_path, profile) + assert (json_path, text_path) == (tmp_path / "model_profile.json", tmp_path / "model_profile_readable.txt") + assert json_path.is_file() and text_path.is_file() + + +def test_json_report_round_trips_the_profile(tmp_path, profile): + json_path, _ = save_model_profile(tmp_path, profile) + assert json.loads(json_path.read_text()) == profile + + +def test_readable_report_lists_architecture_first_then_metadata(tmp_path, profile): + _, text_path = save_model_profile(tmp_path, profile) + text = text_path.read_text() + + assert text.startswith("Model Profile\n=============") + assert text.index("Model Architecture") < text.index("Linear(3, 2)") < text.index("Metadata") + assert "total_params: 8" in text + assert "peak_gpu_memory_allocated_mb: None" in text + assert text.count("Linear(3, 2)") == 1, "the architecture must not be repeated in the metadata block" + + +############################################################################### +############################### MEMORY TRACKING ############################### +############################################################################### + + +@pytest.mark.parametrize("device", ["cpu", torch.device("cpu")]) +def test_memory_tracking_is_disabled_for_cpu_devices(device): + assert reset_peak_memory_stats(device) is False + assert get_peak_memory_allocated_mb(device) is None + + +@pytest.mark.skipif(torch.cuda.is_available(), reason="only meaningful without CUDA") +def test_memory_tracking_is_disabled_for_cuda_devices_when_cuda_is_unavailable(): + assert reset_peak_memory_stats("cuda") is False + assert get_peak_memory_allocated_mb("cuda:0") is None + + +def test_memory_tracking_converts_bytes_to_megabytes_on_cuda(monkeypatch): + calls: list[str] = [] + monkeypatch.setattr(torch.cuda, "is_available", lambda: True) + monkeypatch.setattr(torch.cuda, "reset_peak_memory_stats", lambda device: calls.append(f"reset:{device}")) + monkeypatch.setattr(torch.cuda, "synchronize", lambda device: calls.append(f"sync:{device}")) + monkeypatch.setattr(torch.cuda, "max_memory_allocated", lambda device: 3 * 1024 * 1024) + + assert reset_peak_memory_stats("cuda:1") is True + assert get_peak_memory_allocated_mb("cuda:1") == pytest.approx(3.0) + assert calls == ["reset:cuda:1", "sync:cuda:1"] diff --git a/tests/unit/serialization/test_prediction_io.py b/tests/unit/serialization/test_prediction_io.py new file mode 100644 index 00000000..7155a280 --- /dev/null +++ b/tests/unit/serialization/test_prediction_io.py @@ -0,0 +1,572 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for persisting predictions (writers) and reading them back (readers).""" + +import json +from pathlib import Path +from typing import Any, cast + +import h5py +import numpy as np +import pytest +import torch +from pymatgen.core import Molecule + +from xanesnet.datasources import DataSource +from xanesnet.serialization.prediction_readers import ( + HDF5Reader, + JSONReader, + NumpyReader, + PredictionReader, + PreloadedPredictionReader, + StructureMatchedPredictionReader, + build_prediction_reader, + detect_prediction_format, +) +from xanesnet.serialization.prediction_writers import ( + HDF5Writer, + JSONWriter, + NumpyWriter, + PredictionBatch, +) + +WRITERS = [HDF5Writer, NumpyWriter, JSONWriter] +WRITER_READER_PAIRS = [(HDF5Writer, HDF5Reader), (NumpyWriter, NumpyReader), (JSONWriter, JSONReader)] +PAIR_IDS = ["hdf5", "numpy", "json"] + +N_ENERGIES = 5 + + +def make_batch( + n: int = 4, + offset: int = 0, + *, + prediction_std: np.ndarray | torch.Tensor | None = None, + time_per_spectrum: np.ndarray | torch.Tensor | None = None, +) -> PredictionBatch: + """Build a batch whose target-site values encode their global row numbers. + + Args: + n: Number of target sites in the batch. + offset: Global row number of the first target site. + prediction_std: Optional uncertainty values for each target site. + time_per_spectrum: Optional model-forward duration for each target site. + + Returns: + Batch mapping containing prediction, target, sample, and site data. + """ + rows = np.arange(offset, offset + n) + batch: PredictionBatch = { + "prediction": (rows[:, None] + np.linspace(0, 1, N_ENERGIES)[None, :]).astype(np.float32), + "target": (rows[:, None] * 2.0 + np.linspace(0, 1, N_ENERGIES)[None, :]).astype(np.float32), + "sample_id": np.array([f"sample_{r}" for r in rows]), + "target_site_index": rows % 3, + } + if prediction_std is not None: + batch["prediction_std"] = prediction_std + if time_per_spectrum is not None: + batch["time_per_spectrum"] = time_per_spectrum + return batch + + +class ListDataSource(DataSource): + """Minimal in-memory datasource of molecules.""" + + def __init__(self, molecules: list[Molecule]) -> None: + super().__init__("test") + self.molecules = molecules + + def __iter__(self): + return iter(self.molecules) + + def __len__(self) -> int: + return len(self.molecules) + + def __getitem__(self, idx: int) -> Molecule: + return self.molecules[idx] + + +def make_molecule(sample_id: str | None) -> Molecule: + """Create a two-hydrogen molecule with an optional sample identifier. + + Args: + sample_id: Identifier to store on the molecule, or ``None`` to omit it. + + Returns: + Molecule with the requested sample properties. + """ + properties = {} if sample_id is None else {"sample_id": sample_id} + return Molecule(["H", "H"], [[0, 0, 0], [0, 0, 0.74]], properties=properties) + + +############################################################################### +############################### WRITER CONTRACT ############################### +############################################################################### + + +@pytest.mark.parametrize("writer_cls", WRITERS) +def test_writer_creates_directory_and_descriptor_file(writer_cls, tmp_path): + writer = writer_cls(tmp_path / "nested" / "predictions", buffer_size=10) + writer.close() + + info = (tmp_path / "nested" / "predictions" / "WRITER_INFO.txt").read_text() + assert writer_cls.__name__ in info + + +@pytest.mark.parametrize("writer_cls, suffix", [(NumpyWriter, "npz"), (JSONWriter, "json")]) +def test_rows_stay_buffered_until_the_buffer_is_full(writer_cls, suffix, tmp_path): + """File-per-row writers make the flush behaviour observable through the files on disk.""" + writer = writer_cls(tmp_path, buffer_size=10) + + writer.add(make_batch(3)) + assert list(tmp_path.glob(f"sample_*.{suffix}")) == [] + + writer.add(make_batch(7, offset=3)) # reaches buffer_size -> automatic flush + assert len(list(tmp_path.glob(f"sample_*.{suffix}"))) == 10 + writer.close() + + +@pytest.mark.parametrize("writer_cls, suffix", [(NumpyWriter, "npz"), (JSONWriter, "json")]) +def test_explicit_flush_writes_partial_buffers(writer_cls, suffix, tmp_path): + writer = writer_cls(tmp_path, buffer_size=100) + writer.add(make_batch(3)) + writer.flush() + assert len(list(tmp_path.glob(f"sample_*.{suffix}"))) == 3 + writer.close() + + +@pytest.mark.parametrize("writer_cls, reader_cls", WRITER_READER_PAIRS, ids=PAIR_IDS) +def test_close_flushes_the_remaining_rows(writer_cls, reader_cls, tmp_path): + writer = writer_cls(tmp_path, buffer_size=100) + writer.add(make_batch(3)) + writer.close() + + with reader_cls(tmp_path) as reader: + assert len(reader) == 3 + + +@pytest.mark.parametrize("writer_cls", WRITERS) +def test_flushing_an_empty_buffer_is_harmless(writer_cls, tmp_path): + writer = writer_cls(tmp_path, buffer_size=5) + writer.flush() + writer.close() + + +@pytest.mark.parametrize("writer_cls, reader_cls", WRITER_READER_PAIRS, ids=PAIR_IDS) +def test_torch_tensors_are_accepted(writer_cls, reader_cls, tmp_path): + writer = writer_cls(tmp_path, buffer_size=5) + batch = make_batch(2) + batch["prediction"] = torch.from_numpy(batch["prediction"]).requires_grad_(True) + writer.add(batch) + writer.close() + + with reader_cls(tmp_path) as reader: + np.testing.assert_allclose(reader[1]["prediction"], make_batch(2)["prediction"][1], rtol=1e-6) + + +@pytest.mark.parametrize("writer_cls", WRITERS) +class TestWriterValidation: + def test_scalar_values_are_rejected(self, writer_cls, tmp_path): + writer = writer_cls(tmp_path, buffer_size=5) + batch = make_batch(2) + batch["prediction"] = np.array(1.0, dtype=np.float32) + with pytest.raises(ValueError, match="scalar; expected leading target-site dimension"): + writer.add(batch) + writer.close() + + def test_mismatched_target_site_counts_are_rejected(self, writer_cls, tmp_path): + writer = writer_cls(tmp_path, buffer_size=5) + batch = make_batch(3) + batch["target"] = batch["target"][:2] + with pytest.raises(ValueError, match="Target-site-dimension mismatch for key 'target'"): + writer.add(batch) + writer.close() + + def test_changing_the_field_set_between_batches_is_rejected(self, writer_cls, tmp_path): + writer = writer_cls(tmp_path, buffer_size=50) + writer.add(make_batch(2)) + with pytest.raises(ValueError, match="keys must stay consistent") as excinfo: + writer.add(make_batch(2, prediction_std=np.zeros((2, N_ENERGIES), dtype=np.float32))) + assert "prediction_std" in str(excinfo.value) + writer.close() + + def test_missing_field_is_reported(self, writer_cls, tmp_path): + writer = writer_cls(tmp_path, buffer_size=50) + writer.add(make_batch(2)) + incomplete = cast(dict[str, Any], make_batch(2)) + del incomplete["target"] + with pytest.raises(ValueError, match="missing keys: \\['target'\\]"): + writer.add(cast(PredictionBatch, incomplete)) + writer.close() + + def test_multidimensional_string_arrays_are_rejected(self, writer_cls, tmp_path): + writer = writer_cls(tmp_path, buffer_size=5) + batch = cast(dict[str, Any], make_batch(2)) + batch["labels"] = np.array([["a", "b"], ["c", "d"]]) + with pytest.raises(TypeError, match="not supported"): + writer.add(cast(PredictionBatch, batch)) + writer.close() + + def test_unsupported_value_types_are_rejected(self, writer_cls, tmp_path): + writer = writer_cls(tmp_path, buffer_size=5) + batch = cast(dict[str, Any], make_batch(2)) + batch["prediction"] = [[1.0], [2.0]] + with pytest.raises(ValueError, match="Unsupported type"): + writer.add(cast(PredictionBatch, batch)) + writer.close() + + def test_empty_batches_are_rejected(self, writer_cls, tmp_path): + writer = writer_cls(tmp_path, buffer_size=5) + with pytest.raises(ValueError, match="Empty PredictionBatch"): + writer.add(cast(PredictionBatch, {})) + writer.close() + + +############################################################################### +################################ FILE LAYOUT ################################### +############################################################################### + + +def test_hdf5_writer_stores_one_dataset_per_field_under_predictions(tmp_path): + writer = HDF5Writer(tmp_path, buffer_size=3) + writer.add(make_batch(5)) + writer.close() + + with h5py.File(tmp_path / "predictions.h5", "r") as h5: + predictions = h5["predictions"] + assert isinstance(predictions, h5py.Group) + assert set(predictions) == {"prediction", "target", "sample_id", "target_site_index"} + prediction = predictions["prediction"] + assert isinstance(prediction, h5py.Dataset) + assert prediction.shape == (5, N_ENERGIES) + + +def test_hdf5_writer_appends_across_flushes_in_order(tmp_path): + writer = HDF5Writer(tmp_path, buffer_size=2) + for start in (0, 2, 4): + writer.add(make_batch(2, offset=start)) + writer.close() + + with h5py.File(tmp_path / "predictions.h5", "r") as h5: + target_site_index = h5["predictions/target_site_index"] + assert isinstance(target_site_index, h5py.Dataset) + np.testing.assert_array_equal(target_site_index[:], np.arange(6) % 3) + + +def test_numpy_and_json_writers_create_one_numbered_file_per_row(tmp_path): + for writer_cls, suffix in [(NumpyWriter, "npz"), (JSONWriter, "json")]: + directory = tmp_path / suffix + writer = writer_cls(directory, buffer_size=2) + writer.add(make_batch(3)) + writer.add(make_batch(2, offset=3)) + writer.close() + + assert sorted(p.name for p in directory.glob(f"sample_*.{suffix}")) == [ + f"sample_{i:06d}.{suffix}" for i in range(5) + ] + + +def test_json_writer_files_are_human_readable_json(tmp_path): + writer = JSONWriter(tmp_path, buffer_size=1) + writer.add(make_batch(1)) + writer.close() + + content = json.loads((tmp_path / "sample_000000.json").read_text()) + assert content["sample_id"] == "sample_0" + assert len(content["prediction"]) == N_ENERGIES + + +############################################################################### +################################### ROUND TRIP ################################ +############################################################################### + + +@pytest.fixture(params=WRITER_READER_PAIRS, ids=PAIR_IDS) +def written(request: pytest.FixtureRequest, tmp_path: Path) -> tuple[type[PredictionReader], Path, PredictionBatch]: + """Write 7 rows (with a mid-way flush) and return ``(reader_cls, path, batch)``.""" + writer_cls, reader_cls = request.param + reader_cls: type[PredictionReader] = reader_cls + batch = make_batch(7, time_per_spectrum=np.linspace(0.1, 0.7, 7).astype(np.float32)) + writer = writer_cls(tmp_path, buffer_size=4) + batch_arrays = cast(dict[str, np.ndarray], batch) + writer.add(cast(PredictionBatch, {key: value[:5] for key, value in batch_arrays.items()})) + writer.add(cast(PredictionBatch, {key: value[5:] for key, value in batch_arrays.items()})) + writer.close() + return reader_cls, tmp_path, batch + + +def test_reader_reports_the_number_of_rows(written): + reader_cls, path, batch = written + with reader_cls(path) as reader: + assert len(reader) == 7 + + +def test_samples_round_trip_values_and_python_types(written): + reader_cls, path, batch = written + with reader_cls(path) as reader: + sample = reader[3] + + np.testing.assert_allclose(sample["prediction"], batch["prediction"][3], rtol=1e-6) + np.testing.assert_allclose(sample["target"], batch["target"][3], rtol=1e-6) + assert sample["sample_id"] == "sample_3" + assert isinstance(sample["sample_id"], str) + assert sample["target_site_index"] == 0 + assert isinstance(sample["target_site_index"], int) + time_per_spectrum = sample.get("time_per_spectrum") + assert time_per_spectrum is not None + assert time_per_spectrum == pytest.approx(0.4, rel=1e-5) + + +def test_iteration_yields_every_sample_in_order_and_can_restart(written): + reader_cls, path, _ = written + with reader_cls(path) as reader: + first = [s["sample_id"] for s in reader] + second = [s["sample_id"] for s in reader] + assert first == second == [f"sample_{i}" for i in range(7)] + + +def test_get_all_stacks_rows_in_order(written): + reader_cls, path, batch = written + with reader_cls(path) as reader: + everything = reader.get_all() + + assert everything["prediction"].shape == (7, N_ENERGIES) + np.testing.assert_allclose(everything["prediction"], batch["prediction"], rtol=1e-6) + assert list(everything["sample_id"]) == [f"sample_{i}" for i in range(7)] + np.testing.assert_array_equal(everything["target_site_index"], batch["target_site_index"]) + + +def test_get_all_does_not_exhaust_iteration(written): + reader_cls, path, _ = written + with reader_cls(path) as reader: + reader.get_all() + assert len(list(reader)) == 7 + + +@pytest.mark.parametrize("index", [-1, 7, 100]) +def test_out_of_range_index_raises(written, index): + reader_cls, path, _ = written + with reader_cls(path) as reader: + with pytest.raises(IndexError, match="out of range"): + reader[index] + + +def test_readers_do_not_provide_structures_by_default(written): + reader_cls, path, _ = written + with reader_cls(path) as reader: + assert reader.provides_structures() is False + + +@pytest.mark.parametrize("writer_cls, reader_cls", WRITER_READER_PAIRS, ids=PAIR_IDS) +def test_missing_target_site_index_is_reported_as_none(writer_cls, reader_cls, tmp_path): + batch = make_batch(2) + del batch["target_site_index"] + writer = writer_cls(tmp_path, buffer_size=10) + writer.add(batch) + writer.close() + + with reader_cls(tmp_path) as reader: + assert reader[0]["target_site_index"] is None + + +@pytest.mark.parametrize("writer_cls, reader_cls", WRITER_READER_PAIRS, ids=PAIR_IDS) +def test_optional_uncertainty_field_round_trips(writer_cls, reader_cls, tmp_path): + std = np.full((2, N_ENERGIES), 0.25, dtype=np.float32) + writer = writer_cls(tmp_path, buffer_size=10) + writer.add(make_batch(2, prediction_std=std)) + writer.close() + + with reader_cls(tmp_path) as reader: + np.testing.assert_allclose(reader[1]["prediction_std"], std[1]) + + +def test_hdf5_reader_close_is_idempotent(tmp_path): + writer = HDF5Writer(tmp_path, buffer_size=10) + writer.add(make_batch(1)) + writer.close() + + reader = HDF5Reader(tmp_path) + reader.close() + reader.close() + with pytest.raises(RuntimeError, match="not properly initialized"): + reader[0] + + +############################################################################### +############################### READER VALIDATION ############################# +############################################################################### + + +def test_hdf5_reader_requires_the_file(tmp_path): + with pytest.raises(FileNotFoundError, match="HDF5 file not found"): + HDF5Reader(tmp_path) + + +def test_hdf5_reader_requires_the_predictions_group(tmp_path): + with h5py.File(tmp_path / "predictions.h5", "w") as h5: + h5.create_group("other") + with pytest.raises(ValueError, match="No 'predictions' group"): + HDF5Reader(tmp_path) + + +@pytest.mark.parametrize("reader_cls", [NumpyReader, JSONReader]) +class TestFileBasedReaderValidation: + def test_missing_directory(self, reader_cls, tmp_path): + with pytest.raises(FileNotFoundError, match="Directory not found"): + reader_cls(tmp_path / "missing") + + def test_path_must_be_a_directory(self, reader_cls, tmp_path): + file = tmp_path / "file.txt" + file.write_text("x") + with pytest.raises(ValueError, match="not a directory"): + reader_cls(file) + + def test_directory_without_samples(self, reader_cls, tmp_path): + with pytest.raises(FileNotFoundError, match="No sample_"): + reader_cls(tmp_path) + + +############################################################################### +############################## FORMAT DETECTION ################################ +############################################################################### + + +@pytest.mark.parametrize("writer_cls, reader_cls", WRITER_READER_PAIRS, ids=PAIR_IDS) +def test_format_is_detected_from_directory_contents(writer_cls, reader_cls, tmp_path): + writer = writer_cls(tmp_path, buffer_size=10) + writer.add(make_batch(1)) + writer.close() + assert detect_prediction_format(tmp_path) is reader_cls + + +def test_detecting_a_missing_directory_raises(tmp_path): + with pytest.raises(FileNotFoundError, match="Predictions path not found"): + detect_prediction_format(tmp_path / "missing") + + +def test_detecting_an_unrecognised_directory_raises(tmp_path): + (tmp_path / "unrelated.txt").write_text("x") + with pytest.raises(ValueError, match="Could not detect prediction format"): + detect_prediction_format(tmp_path) + + +############################################################################### +############################## STRUCTURE MATCHING ############################# +############################################################################### + + +@pytest.fixture +def hdf5_predictions(tmp_path): + writer = HDF5Writer(tmp_path, buffer_size=10) + writer.add(make_batch(4)) + writer.close() + return tmp_path + + +@pytest.fixture +def datasource() -> ListDataSource: + # Deliberately not in prediction order: matching must be by sample_id, not position. + ids = ["sample_3", "sample_0", "sample_2", "sample_1"] + return ListDataSource([make_molecule(i) for i in ids]) + + +@pytest.mark.parametrize("preload_structures", [False, True]) +def test_structures_are_matched_by_sample_id(hdf5_predictions, datasource, preload_structures): + with StructureMatchedPredictionReader( + HDF5Reader(hdf5_predictions), datasource, preload_structures=preload_structures + ) as reader: + assert reader.provides_structures() is True + assert len(reader) == 4 + for index in range(4): + sample = reader[index] + structure = sample.get("structure") + assert structure is not None + assert structure.properties["sample_id"] == sample["sample_id"] == f"sample_{index}" + + +def test_structure_matching_leaves_bulk_loading_to_the_wrapped_reader(hdf5_predictions, datasource): + with StructureMatchedPredictionReader(HDF5Reader(hdf5_predictions), datasource) as reader: + assert "structure" not in reader.get_all() + + +def test_unknown_sample_id_is_reported_with_its_index(hdf5_predictions): + partial = ListDataSource([make_molecule("sample_0")]) + with StructureMatchedPredictionReader(HDF5Reader(hdf5_predictions), partial) as reader: + assert reader[0]["sample_id"] == "sample_0" + with pytest.raises(ValueError, match="index 1 references unknown sample_id 'sample_1'"): + reader[1] + + +def test_datasource_entries_must_define_a_sample_id(hdf5_predictions): + with pytest.raises(ValueError, match="must define properties\\['sample_id'\\]"): + StructureMatchedPredictionReader(HDF5Reader(hdf5_predictions), ListDataSource([make_molecule(None)])) + + +def test_duplicate_sample_ids_in_the_datasource_are_rejected(hdf5_predictions): + duplicated = ListDataSource([make_molecule("sample_0"), make_molecule("sample_0")]) + with pytest.raises(ValueError, match="duplicate sample_id 'sample_0'"): + StructureMatchedPredictionReader(HDF5Reader(hdf5_predictions), duplicated) + + +############################################################################### +################################ build_prediction_reader ###################### +############################################################################### + + +def test_factory_returns_the_detected_plain_reader(hdf5_predictions): + with build_prediction_reader(hdf5_predictions) as reader: + assert type(reader) is HDF5Reader + + +def test_factory_wraps_the_reader_when_a_datasource_is_given(hdf5_predictions, datasource): + with build_prediction_reader(hdf5_predictions, datasource=datasource) as reader: + assert isinstance(reader, StructureMatchedPredictionReader) + assert reader.provides_structures() + + +def test_factory_preload_serves_samples_from_memory(hdf5_predictions): + with build_prediction_reader(hdf5_predictions, preload=True) as reader: + assert isinstance(reader, PreloadedPredictionReader) + assert len(reader) == 4 + assert reader[2]["sample_id"] == "sample_2" + assert reader[2] is reader[2], "preloaded samples are served from memory" + with pytest.raises(IndexError): + reader[4] + + +def test_factory_preload_with_a_datasource_keeps_structures(hdf5_predictions, datasource): + with build_prediction_reader(hdf5_predictions, datasource=datasource, preload=True) as reader: + assert reader.provides_structures() + structure = reader[1].get("structure") + assert structure is not None + assert structure.properties["sample_id"] == "sample_1" + + +def test_factory_propagates_detection_errors(tmp_path): + with pytest.raises(FileNotFoundError): + build_prediction_reader(tmp_path / "missing") diff --git a/tests/unit/serialization/test_registry_schema_sync.py b/tests/unit/serialization/test_registry_schema_sync.py new file mode 100644 index 00000000..90de87a9 --- /dev/null +++ b/tests/unit/serialization/test_registry_schema_sync.py @@ -0,0 +1,123 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""The packaged JSON Schemas and the Python registries must advertise exactly the same extension points. + +A type that is registered but missing from the schema cannot be selected from a config file; a type that is in the +schema but not registered passes validation and then fails at run time. Both directions are checked here. +""" + +from importlib import resources + +import pytest +import yaml + +from xanesnet.components import ( + ActivationRegistry, + BiasInitRegistry, + LRSchedulerRegistry, + OptimizerRegistry, + WeightInitRegistry, +) +from xanesnet.datasets import DatasetRegistry +from xanesnet.datasources import DataSourceRegistry +from xanesnet.descriptors import DescriptorRegistry +from xanesnet.encodings import SpectraEncodingRegistry +from xanesnet.losses import LossRegistry +from xanesnet.models import ModelRegistry +from xanesnet.regularizers import RegularizerRegistry +from xanesnet.runners.inferencers import InferencerRegistry +from xanesnet.runners.trainers import TrainerRegistry +from xanesnet.stoppers import EarlyStopperRegistry +from xanesnet.strategies import StrategyRegistry + +# Other unit tests register fakes under this prefix; they are not part of the public surface. +TEST_DOUBLE_PREFIX = "unit_test_" + +# (schema file, definition name, registry) +SYNCHRONISED = { + "activation": ("components/component_types.schema.yaml", "activationName", ActivationRegistry), + "optimizer": ("components/component_types.schema.yaml", "optimizerName", OptimizerRegistry), + "weight_init": ("components/component_types.schema.yaml", "weightInitName", WeightInitRegistry), + "bias_init": ("components/component_types.schema.yaml", "biasInitName", BiasInitRegistry), + "lr_scheduler": ("components/component_types.schema.yaml", "lrSchedulerType", LRSchedulerRegistry), + "dataset": ("datasets/dataset_types.schema.yaml", "datasetType", DatasetRegistry), + "datasource": ("datasources/datasource_types.schema.yaml", "datasourceType", DataSourceRegistry), + "descriptor": ("descriptors/descriptor_types.schema.yaml", "descriptorType", DescriptorRegistry), + "encoding": ("encodings/encoding_types.schema.yaml", "encodingType", SpectraEncodingRegistry), + "loss": ("losses/loss_types.schema.yaml", "lossType", LossRegistry), + "model": ("models/model_types.schema.yaml", "modelType", ModelRegistry), + "regularizer": ("regularizers/regularizer_types.schema.yaml", "regularizerType", RegularizerRegistry), + "trainer": ("runners/runner_types.schema.yaml", "trainerType", TrainerRegistry), + "inferencer": ("runners/runner_types.schema.yaml", "inferencerType", InferencerRegistry), + "early_stopper": ("stoppers/early_stopper_types.schema.yaml", "earlyStopperType", EarlyStopperRegistry), + "strategy": ("strategies/strategy_types.schema.yaml", "strategyType", StrategyRegistry), +} + + +def _schema_enum(schema_file: str, definition: str) -> list[str]: + path = resources.files("xanesnet") / "schemas" / schema_file + return yaml.safe_load(path.read_text(encoding="utf-8"))["$defs"][definition]["enum"] + + +def _ensure_optional_trainer_registration() -> set[str]: + """Import optional trainer modules so their registry keys are present when the extra is installed. + + ``LightningTrainer`` is registered only on import and depends on the optional ``lightning`` extra. + Without an explicit import here, a full ``pytest`` session that also loads ``tests/dry_runs`` can + register ``lightning`` as a side effect, while an isolated unit-test run would not — making the + schema/registry comparison order-dependent. + """ + missing: set[str] = set() + try: + import xanesnet.runners.trainers.lightning # noqa: F401 + except ImportError: + missing.add("lightning") + return missing + + +@pytest.mark.parametrize("name", SYNCHRONISED) +def test_schema_enum_matches_registry_keys(name): + schema_file, definition, registry = SYNCHRONISED[name] + optional_missing = _ensure_optional_trainer_registration() if name == "trainer" else set() + + # Registry lookups are case-insensitive, and the schema may list both spellings (e.g. ``adam`` and ``Adam``). + in_schema = {value.lower() for value in _schema_enum(schema_file, definition)} - optional_missing + in_registry = {key for key in registry.list() if not key.startswith(TEST_DOUBLE_PREFIX)} + + assert in_schema - in_registry == set(), f"in the schema but not registered: {sorted(in_schema - in_registry)}" + assert in_registry - in_schema == set(), f"registered but not in the schema: {sorted(in_registry - in_schema)}" + + +@pytest.mark.parametrize("name", SYNCHRONISED) +def test_every_schema_entry_resolves_through_the_registry(name): + schema_file, definition, registry = SYNCHRONISED[name] + optional_missing = _ensure_optional_trainer_registration() if name == "trainer" else set() + for value in _schema_enum(schema_file, definition): + if value.lower() in optional_missing: + continue + registry.get(value) # raises KeyError for unregistered entries diff --git a/tests/unit/serialization/test_runtime_contracts.py b/tests/unit/serialization/test_runtime_contracts.py new file mode 100644 index 00000000..8db008b8 --- /dev/null +++ b/tests/unit/serialization/test_runtime_contracts.py @@ -0,0 +1,150 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for registry-backed runtime contracts that JSON Schema cannot express.""" + +import pytest + +from xanesnet.serialization.runtime_contracts import validate_runtime_contracts +from xanesnet.utils.exceptions import ConfigError + +############################################################################### +############################ DATASET / MODEL PAIRING ########################## +############################################################################### + + +@pytest.mark.parametrize("mode", ["train", "infer"]) +def test_registered_dataset_model_pair_is_accepted(mode): + config = {"dataset": {"dataset_type": "descriptor"}, "model": {"model_type": "mlp"}} + validate_runtime_contracts(config, mode) + + +@pytest.mark.parametrize("mode", ["train", "infer"]) +def test_pairing_is_case_insensitive(mode): + config = {"dataset": {"dataset_type": "Descriptor"}, "model": {"model_type": "MLP"}} + validate_runtime_contracts(config, mode) + + +@pytest.mark.parametrize("mode", ["train", "infer"]) +def test_unregistered_dataset_model_pair_is_rejected(mode): + config = {"dataset": {"dataset_type": "descriptor"}, "model": {"model_type": "schnet"}} + with pytest.raises(ConfigError, match="No batch processor registered for dataset 'descriptor' and model 'schnet'"): + validate_runtime_contracts(config, mode) + + +@pytest.mark.parametrize( + "config", + [ + {}, + {"dataset": {"dataset_type": "descriptor"}}, + {"model": {"model_type": "mlp"}}, + {"dataset": "not-a-section", "model": {"model_type": "mlp"}}, + ], + ids=["empty", "no-model", "no-dataset", "non-dict-section"], +) +def test_incomplete_configs_are_left_to_the_schema(config): + """Missing sections are reported by schema validation, not by the runtime contract.""" + validate_runtime_contracts(config, "train") + + +############################################################################### +############################ INFERENCE-ONLY CONTRACTS ######################### +############################################################################### + + +def _infer_config(**overrides): + config = { + "dataset": {"dataset_type": "descriptor"}, + "model": {"model_type": "mlp", "in_size": 6, "out_size": 10}, + "encodings": [{"encoding_type": "identity"}], + "strategy": {"strategy_type": "single"}, + "inferencer": {"inferencer_type": "basic"}, + } + config.update(overrides) + return config + + +def test_concrete_inference_config_is_accepted(): + validate_runtime_contracts(_infer_config(), "infer") + + +@pytest.mark.parametrize("token", ["auto", "AUTO", "Auto"]) +def test_unresolved_model_dimension_is_rejected_for_inference(token): + config = _infer_config(model={"model_type": "mlp", "in_size": token, "out_size": 10}) + with pytest.raises(ConfigError, match=r"unresolved automatic model value at model\.in_size"): + validate_runtime_contracts(config, "infer") + + +def test_unresolved_nested_model_value_reports_its_full_path(): + config = _infer_config(model={"model_type": "mlp", "heads": [{"size": 3}, {"size": "auto"}]}) + with pytest.raises(ConfigError, match=r"model\.heads\.1\.size"): + validate_runtime_contracts(config, "infer") + + +def test_unresolved_encoding_value_is_rejected_for_inference(): + config = _infer_config( + encodings=[{"encoding_type": "identity"}, {"encoding_type": "gaussian", "num_points": "auto"}] + ) + with pytest.raises(ConfigError, match=r"unresolved automatic encoding value at encodings\.1\.num_points"): + validate_runtime_contracts(config, "infer") + + +def test_auto_is_still_allowed_when_training(): + config = {"dataset": {"dataset_type": "descriptor"}, "model": {"model_type": "mlp", "in_size": "auto"}} + validate_runtime_contracts(config, "train") + + +@pytest.mark.parametrize("strategy", ["deep_ensemble", "bootstrap", "kfold"]) +def test_multi_model_strategies_require_the_ensemble_inferencer(strategy): + config = _infer_config(strategy={"strategy_type": strategy}, inferencer={"inferencer_type": "basic"}) + with pytest.raises(ConfigError, match=f"'{strategy}' requires inferencer 'ensemble'"): + validate_runtime_contracts(config, "infer") + + +@pytest.mark.parametrize("strategy", ["deep_ensemble", "bootstrap", "kfold"]) +def test_multi_model_strategies_accept_the_ensemble_inferencer(strategy): + validate_runtime_contracts( + _infer_config(strategy={"strategy_type": strategy}, inferencer={"inferencer_type": "ensemble"}), "infer" + ) + + +def test_single_model_strategy_accepts_the_basic_inferencer(): + validate_runtime_contracts(_infer_config(strategy={"strategy_type": "single"}), "infer") + + +############################################################################### +################################ OTHER MODES ################################## +############################################################################### + + +def test_analyze_mode_has_no_runtime_contracts(): + validate_runtime_contracts({"anything": "goes"}, "analyze") + + +def test_unknown_mode_is_rejected(): + with pytest.raises(ConfigError, match="Unknown config validation mode"): + validate_runtime_contracts({}, "nope") # type: ignore[arg-type] diff --git a/tests/unit/serialization/test_schema_contract.py b/tests/unit/serialization/test_schema_contract.py new file mode 100644 index 00000000..c6683766 --- /dev/null +++ b/tests/unit/serialization/test_schema_contract.py @@ -0,0 +1,105 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the calling contract of ``validate_config_schema`` (mutation, return value, error format).""" + +import copy + +import pytest + +from xanesnet.serialization.schema_validation import validate_config_schema +from xanesnet.utils.exceptions import ConfigError + + +def test_valid_config_is_updated_in_place_and_returned(train_config): + returned = validate_config_schema(train_config, "train") + + assert train_config == returned + assert train_config["device"] == "cpu", "defaults must be written back into the caller's dictionary" + assert returned is not train_config + + +def test_in_place_update_keeps_the_same_dictionary_object(train_config): + identity = id(train_config) + validate_config_schema(train_config, "train") + assert id(train_config) == identity + + +def test_returned_config_is_independent_of_the_input(train_config): + returned = validate_config_schema(train_config, "train") + returned["model"]["hidden_size"] = 999 + assert train_config["model"]["hidden_size"] == 8 + + +def test_invalid_config_is_left_untouched(train_config): + train_config["model"]["model_type"] = "nope" + snapshot = copy.deepcopy(train_config) + + with pytest.raises(ConfigError): + validate_config_schema(train_config, "train") + + assert train_config == snapshot, "failed validation must not leak defaults into the caller's config" + + +def test_validation_is_idempotent(train_config): + once = validate_config_schema(train_config, "train") + twice = validate_config_schema(copy.deepcopy(once), "train") + assert twice == once + + +def test_the_shallowest_problem_is_reported_first(train_config): + train_config["model"]["hidden_size"] = 0 # config.model.* (depth 2) + train_config["unexpected"] = 1 # config (depth 0) + with pytest.raises(ConfigError, match=r"^Invalid train config at config:"): + validate_config_schema(train_config, "train") + + +def test_error_for_a_list_item_uses_an_indexed_path(train_config): + train_config["encodings"] = [{"encoding_type": "identity"}, {"encoding_type": "nope"}] + with pytest.raises(ConfigError, match=r"config\.encodings\[1\]"): + validate_config_schema(train_config, "train") + + +def test_union_errors_list_details_from_the_candidate_branches(train_config): + train_config["model"]["hidden_size"] = 0 + with pytest.raises(ConfigError) as excinfo: + validate_config_schema(train_config, "train") + assert "Details:" in str(excinfo.value) + + +def test_error_messages_are_single_line_and_bounded(train_config): + train_config["model"]["model_type"] = "nope" + with pytest.raises(ConfigError) as excinfo: + validate_config_schema(train_config, "train") + message = str(excinfo.value) + assert "\n" not in message + assert len(message) < 2000 + + +def test_unknown_mode_is_rejected(train_config): + with pytest.raises(ConfigError, match="Unknown config validation mode"): + validate_config_schema(train_config, "bogus") # type: ignore[arg-type] diff --git a/tests/unit/serialization/test_schema_defaults.py b/tests/unit/serialization/test_schema_defaults.py new file mode 100644 index 00000000..58d0f5a9 --- /dev/null +++ b/tests/unit/serialization/test_schema_defaults.py @@ -0,0 +1,104 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Tests for schema defaults and explicit-value precedence.""" + +from xanesnet.serialization.config import merge_raw_configs +from xanesnet.serialization.schema_validation import validate_config_schema + +############################################################################### +######################## Test DEFAULTS OF THE SCHEMAS ######################### +############################################################################### + + +def test_train_defaults_are_applied(train_config): + validated = validate_config_schema(train_config, "train") + + assert validated["seed"] is None + assert validated["device"] == "cpu" + assert validated["dataset"]["preload"] is True + assert validated["dataset"]["split_ratios"] == [1.0] + assert validated["model"]["dropout"] == 0.1 + assert validated["trainer"]["shuffle"] is True + assert validated["trainer"]["warmup_steps"] == 500 + assert validated["trainer"]["lr_scheduler"] == {"lr_scheduler_type": "none", "last_epoch": -1} + assert validated["trainer"]["early_stopper"] == {"early_stopper_type": "none", "restore_best": True} + assert validated["strategy"]["weight_init"] == "default" + assert validated["strategy"]["bias_init"] == "zeros" + + +def test_omitted_optional_sections_get_their_defaults(train_config): + del train_config["encodings"] + del train_config["trainer"]["loss"] + train_config["strategy"] = {"strategy_type": "kfold"} + + validated = validate_config_schema(train_config, "train") + + assert validated["encodings"] == [{"encoding_type": "identity"}] + assert validated["trainer"]["loss"] == [{"loss_type": "mse"}] + assert validated["strategy"]["n_splits"] == 3 + assert validated["strategy"]["n_repeats"] == 1 + + +def test_infer_defaults_are_applied(infer_user_config, signature): + validated = validate_config_schema(merge_raw_configs(infer_user_config, signature), "infer") + + assert validated["device"] == "cpu" + assert validated["inferencer"]["shuffle"] is False + assert validated["inferencer"]["num_workers"] == 0 + assert validated["inferencer"]["buffer_size"] == 100000 + + +def test_analyze_defaults_are_applied(analyze_config): + validated = validate_config_schema(analyze_config, "analyze") + + assert validated["preload"] is False + for section in ("aggregators", "reporters", "plotters", "custom_modules"): + assert validated[section] == [] + assert validated["collectors"][0]["energy_resolved"] is False + + +############################################################################### +############################### PRECEDENCE RULES ############################## +############################################################################### + + +def test_explicit_values_override_defaults(train_config): + train_config["seed"] = 7 + train_config["trainer"]["shuffle"] = False + train_config["model"]["dropout"] = 0.0 + + validated = validate_config_schema(train_config, "train") + + assert validated["seed"] == 7 + assert validated["trainer"]["shuffle"] is False + assert validated["model"]["dropout"] == 0.0 + + +def test_none_is_not_replaced_by_the_default(train_config): + train_config["device"] = None + assert validate_config_schema(train_config, "train")["device"] is None diff --git a/tests/unit/serialization/test_schema_loading.py b/tests/unit/serialization/test_schema_loading.py new file mode 100644 index 00000000..8e913325 --- /dev/null +++ b/tests/unit/serialization/test_schema_loading.py @@ -0,0 +1,82 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for schema loading""" + +import copy +from typing import Any + +import pytest +from jsonschema.validators import Draft202012Validator + +from xanesnet.serialization import schema_validation as sv +from xanesnet.utils.exceptions import ConfigError + +MODES = ["train", "infer", "analyze"] + + +def _find_keys(node: Any, key: str) -> list[Any]: + """Collect every value stored under ``key`` anywhere inside a nested schema.""" + found: list[Any] = [] + if isinstance(node, dict): + for name, value in node.items(): + if name == key: + found.append(value) + found.extend(_find_keys(value, key)) + elif isinstance(node, list): + for item in node: + found.extend(_find_keys(item, key)) + return found + + +############################################################################### +################################ ENTRY POINTS ################################# +############################################################################### + + +@pytest.mark.parametrize("mode", MODES) +def test_schema_loads_as_a_valid_fully_resolved_draft_2020_12_schema(mode): + schema = sv.load_config_schema(mode) + Draft202012Validator.check_schema(schema) + assert _find_keys(schema, "$ref") == [], "all $ref nodes must be inlined" + + +def test_loaded_schema_is_a_deep_copy_of_the_cache(): + first = sv.load_config_schema("train") + pristine = copy.deepcopy(first) + first["properties"].clear() + assert sv.load_config_schema("train") == pristine + + +def test_unknown_mode_raises_and_lists_valid_modes(): + with pytest.raises(ConfigError, match="Unknown config validation mode.*analyze.*infer.*train"): + sv.load_config_schema("nope") # type: ignore[arg-type] + + +def test_train_schema_requires_the_expected_sections(): + required = set(sv.load_config_schema("train")["required"]) + assert required == {"datasource", "dataset", "model", "trainer", "strategy", "encodings"} diff --git a/tests/unit/serialization/test_schema_rejections.py b/tests/unit/serialization/test_schema_rejections.py new file mode 100644 index 00000000..2bdcb1ad --- /dev/null +++ b/tests/unit/serialization/test_schema_rejections.py @@ -0,0 +1,171 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests: invalid configs must be rejected with a ``ConfigError``""" + +import pytest + +from xanesnet.serialization.config import merge_raw_configs +from xanesnet.serialization.schema_validation import validate_config_schema +from xanesnet.utils.exceptions import ConfigError + +############################################################################### +############################## BASELINES ACCEPTED ############################# +############################################################################### + + +def test_minimal_configs_are_accepted(train_config, infer_user_config, signature, analyze_config): + validate_config_schema(train_config, "train") + validate_config_schema(merge_raw_configs(infer_user_config, signature), "infer") + validate_config_schema(analyze_config, "analyze") + + +############################################################################### +################################ TRAIN REJECTIONS ############################# +############################################################################### + +# name -> (mutation, regex that the error message must match) +TRAIN_REJECTIONS = { + "unknown_top_level_key": (lambda c: c.update(foo=1), r"config:.*foo.*unexpected"), + "inferencer_section_in_train": (lambda c: c.update(inferencer={"inferencer_type": "basic"}), r"config:"), + "seed_is_a_string": (lambda c: c.update(seed="abc"), r"config\.seed"), + "unknown_datasource_type": (lambda c: c["datasource"].update(datasource_type="nope"), r"config\.datasource"), + "unknown_dataset_type": (lambda c: c["dataset"].update(dataset_type="nope"), r"config\.dataset"), + "unknown_descriptor_type": ( + lambda c: c["dataset"]["descriptors"][0].update(descriptor_type="nope"), + r"config\.dataset", + ), + "unknown_model_type": (lambda c: c["model"].update(model_type="nope"), r"config\.model"), + "model_param_wrong_type": (lambda c: c["model"].update(hidden_size="wide"), r"config\.model"), + "model_param_out_of_range": (lambda c: c["model"].update(hidden_size=0), r"config\.model"), + "model_unknown_key": (lambda c: c["model"].update(not_a_param=1), r"config\.model"), + "unknown_trainer_type": (lambda c: c["trainer"].update(trainer_type="nope"), r"config\.trainer"), + "epochs_wrong_type": (lambda c: c["trainer"].update(epochs="ten"), r"config\.trainer"), + "epochs_zero": (lambda c: c["trainer"].update(epochs=0), r"config\.trainer"), + "unknown_loss_type": (lambda c: c["trainer"]["loss"].append({"loss_type": "nope"}), r"config\.trainer"), + "unknown_strategy_type": (lambda c: c["strategy"].update(strategy_type="nope"), r"config\.strategy"), + "kfold_n_splits_too_small": ( + lambda c: c.update(strategy={"strategy_type": "kfold", "n_splits": 1}), + r"config\.strategy", + ), + "unknown_encoding_type": (lambda c: c.update(encodings=[{"encoding_type": "nope"}]), r"config\.encodings"), +} + + +@pytest.mark.parametrize("name", TRAIN_REJECTIONS) +def test_invalid_train_config_is_rejected(name, train_config, mutate): + mutation, expected_message = TRAIN_REJECTIONS[name] + with pytest.raises(ConfigError, match=expected_message): + validate_config_schema(mutate(train_config, mutation), "train") + + +@pytest.mark.parametrize("section", ["datasource", "dataset", "model", "trainer", "strategy"]) +def test_missing_required_train_section_is_rejected(section, train_config): + del train_config[section] + with pytest.raises(ConfigError, match=f"'{section}' is a required property"): + validate_config_schema(train_config, "train") + + +def test_error_message_names_the_mode_and_the_config_path(train_config): + train_config["model"]["model_type"] = "nope" + with pytest.raises(ConfigError, match=r"^Invalid train config at config\.model"): + validate_config_schema(train_config, "train") + + +############################################################################### +################################ AUTO TOKEN RULES ############################# +############################################################################### + + +@pytest.mark.parametrize("token", ["auto", "AUTO"]) +def test_auto_is_accepted_case_insensitively_where_allowed(train_config, token): + train_config["model"]["in_size"] = token + train_config["model"]["out_size"] = token + validate_config_schema(train_config, "train") + + +def test_auto_is_rejected_for_fields_that_cannot_be_resolved(train_config): + train_config["model"]["hidden_size"] = "auto" + with pytest.raises(ConfigError, match=r"config\.model"): + validate_config_schema(train_config, "train") + + +############################################################################### +############################### INFER REJECTIONS ############################## +############################################################################### + +INFER_REJECTIONS = { + "trainer_section_in_infer": (lambda c: c.update(trainer={"trainer_type": "basic"}), r"config:"), + "missing_inferencer": (lambda c: c.pop("inferencer"), r"'inferencer' is a required property"), + "missing_model": (lambda c: c.pop("model"), r"'model' is a required property"), + "unknown_inferencer_type": (lambda c: c["inferencer"].update(inferencer_type="nope"), r"config\.inferencer"), + "unknown_model_type": (lambda c: c["model"].update(model_type="nope"), r"config\.model"), +} + + +@pytest.mark.parametrize("name", INFER_REJECTIONS) +def test_invalid_infer_config_is_rejected(name, infer_user_config, signature, mutate): + mutation, expected_message = INFER_REJECTIONS[name] + invalid = mutate(merge_raw_configs(infer_user_config, signature), mutation) + with pytest.raises(ConfigError, match=expected_message): + validate_config_schema(invalid, "infer") + + +def test_user_infer_config_without_the_checkpoint_signature_is_rejected(infer_user_config): + """The ``infer`` mode validates the *merged* config, so the bare user YAML lacks model and encodings.""" + with pytest.raises(ConfigError, match="is a required property"): + validate_config_schema(infer_user_config, "infer") + + +############################################################################### +############################### ANALYZE REJECTIONS ############################ +############################################################################### + +ANALYZE_REJECTIONS = { + "unknown_top_level_key": (lambda c: c.update(foo=1), r"config:"), + "unknown_selector_type": (lambda c: c.update(selectors=[{"selector_type": "nope"}]), r"config\.selectors"), + "unknown_collector_type": (lambda c: c.update(collectors=[{"collector_type": "nope"}]), r"config\.collectors"), + "unknown_plotter_type": (lambda c: c.update(plotters=[{"plotter_type": "nope"}]), r"config\.plotters"), + "tensorboard_module_without_dirs": ( + lambda c: c.update(custom_modules=[{"custom_module_type": "tensorboard"}]), + r"config\.custom_modules", + ), +} + + +@pytest.mark.parametrize("name", ANALYZE_REJECTIONS) +def test_invalid_analyze_config_is_rejected(name, analyze_config, mutate): + mutation, expected_message = ANALYZE_REJECTIONS[name] + with pytest.raises(ConfigError, match=expected_message): + validate_config_schema(mutate(analyze_config, mutation), "analyze") + + +def test_custom_module_names_are_not_restricted_by_the_schema(analyze_config): + """Custom modules are open-ended: unknown names pass the schema and are resolved by the registry at runtime.""" + analyze_config["custom_modules"] = [{"custom_module_type": "my_plugin", "anything": 1}] + validated = validate_config_schema(analyze_config, "analyze") + assert validated["custom_modules"] == [{"custom_module_type": "my_plugin", "anything": 1}] diff --git a/tests/unit/serialization/test_shipped_configs.py b/tests/unit/serialization/test_shipped_configs.py new file mode 100644 index 00000000..72a4ece9 --- /dev/null +++ b/tests/unit/serialization/test_shipped_configs.py @@ -0,0 +1,76 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Guard against schema drift: every shipped example configuration must still validate.""" + +import copy +from pathlib import Path + +import pytest + +from xanesnet.serialization.config import load_raw_config +from xanesnet.serialization.schema_validation import validate_config_schema + +from ..conftest import CONFIGS_DIR, DRY_RUNS_DIR + + +def _yaml_files(directory: Path) -> list[Path]: + return sorted(directory.rglob("*.yaml")) if directory.is_dir() else [] + + +def _relative(path: Path) -> str: + return path.relative_to(CONFIGS_DIR.parent).as_posix() + + +# ``*_infer.yaml`` files are *user* inference configs: they only validate once merged with a checkpoint signature. +TRAIN_CONFIGS = [p for p in _yaml_files(CONFIGS_DIR) if not p.stem.endswith("_infer") and "analyze" not in p.stem] + ( + _yaml_files(DRY_RUNS_DIR / "train") +) +ANALYZE_CONFIGS = [p for p in _yaml_files(CONFIGS_DIR) if "analyze" in p.stem] + _yaml_files(DRY_RUNS_DIR / "analyze") + + +@pytest.mark.parametrize("path", TRAIN_CONFIGS, ids=_relative) +def test_training_configs_validate(path): + validated = validate_config_schema(load_raw_config(path), "train") + assert "trainer" in validated + + +@pytest.mark.parametrize("path", ANALYZE_CONFIGS, ids=_relative) +def test_analysis_configs_validate(path): + validated = validate_config_schema(load_raw_config(path), "analyze") + assert "collectors" in validated + + +@pytest.mark.parametrize("path", TRAIN_CONFIGS, ids=_relative) +def test_validated_training_configs_are_a_fixed_point(path): + """Re-validating a validated config changes nothing, so saved ``validated_*`` files can be reused.""" + once = validate_config_schema(load_raw_config(path), "train") + assert validate_config_schema(copy.deepcopy(once), "train") == once + + +def test_example_configs_were_discovered(): + assert TRAIN_CONFIGS and ANALYZE_CONFIGS diff --git a/tests/unit/serialization/test_splits.py b/tests/unit/serialization/test_splits.py new file mode 100644 index 00000000..6649e749 --- /dev/null +++ b/tests/unit/serialization/test_splits.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for reading and writing dataset split indices.""" + +import json + +import pytest + +from xanesnet.serialization.splits import load_splits, save_separate_splits, save_splits +from xanesnet.utils.exceptions import ResourceError + + +def _write_json(path, payload): + path.write_text(json.dumps(payload)) + return path + + +############################################################################### +################################## ROUND TRIP ################################# +############################################################################### + + +def test_save_then_load_round_trip(tmp_path): + plans = [[[0, 1, 2], [3]], [[4, 5], [6, 7]]] + save_splits(tmp_path / "splits.json", plans) + assert load_splits(tmp_path / "splits.json") == plans + + +def test_save_creates_missing_parent_directories(tmp_path): + path = tmp_path / "a" / "b" / "splits.json" + save_splits(path, [[[1]]]) + assert path.is_file() + + +def test_file_layout_is_model_first_with_named_splits(tmp_path): + save_splits(tmp_path / "splits.json", [[[1, 2], [3]], [[4]]]) + assert json.loads((tmp_path / "splits.json").read_text()) == { + "models": [{"train": [1, 2], "valid": [3]}, {"train": [4]}] + } + + +def test_train_only_and_empty_plans_survive_round_trip(tmp_path): + save_splits(tmp_path / "splits.json", [[[0, 1]], []]) + assert load_splits(tmp_path / "splits.json") == [[[0, 1]], []] + + +def test_save_accepts_string_paths(tmp_path): + save_splits(str(tmp_path / "s.json"), [[[1]]]) + assert load_splits(str(tmp_path / "s.json")) == [[[1]]] + + +def test_save_rejects_more_than_train_and_valid(tmp_path): + with pytest.raises(ValueError, match="at most train and validation"): + save_splits(tmp_path / "splits.json", [[[1], [2], [3]]]) + assert not (tmp_path / "splits.json").exists() + + +############################################################################### +################################ MODEL SELECTION ############################## +############################################################################### + + +@pytest.fixture +def three_models(tmp_path): + plans = [[[0], [1]], [[2], [3]], [[4], [5]]] + save_splits(tmp_path / "splits.json", plans) + return tmp_path / "splits.json", plans + + +@pytest.mark.parametrize("index", [0, 1, 2]) +def test_model_index_selects_exactly_one_plan(three_models, index): + path, plans = three_models + assert load_splits(path, model_index=index) == [plans[index]] + + +@pytest.mark.parametrize("index", [-1, 3, 100, True, 1.0]) +def test_invalid_model_index_is_rejected(three_models, index): + path, _ = three_models + with pytest.raises(ResourceError, match="out of range"): + load_splits(path, model_index=index) + + +############################################################################### +################################## VALIDATION ################################# +############################################################################### + + +@pytest.mark.parametrize("payload", [[], {"models": "x"}, {"other": []}, "text", None], ids=repr) +def test_malformed_top_level_structure_is_rejected(tmp_path, payload): + with pytest.raises(ResourceError, match="Invalid model splits file format"): + load_splits(_write_json(tmp_path / "s.json", payload)) + + +def test_non_dict_model_entry_is_rejected(tmp_path): + with pytest.raises(ResourceError, match="Model split entry 0 must be a dict"): + load_splits(_write_json(tmp_path / "s.json", {"models": [[1, 2]]})) + + +def test_unexpected_split_names_are_rejected(tmp_path): + with pytest.raises(ResourceError, match="Unexpected split keys"): + load_splits(_write_json(tmp_path / "s.json", {"models": [{"train": [1], "test": [2]}]})) + + +def test_validation_without_training_split_is_rejected(tmp_path): + with pytest.raises(ResourceError, match="missing 'train'"): + load_splits(_write_json(tmp_path / "s.json", {"models": [{"valid": [1]}]})) + + +@pytest.mark.parametrize("indices", ["1,2", [1, "2"], [1.5], [True], [[1]], None], ids=repr) +def test_non_integer_indices_are_rejected(tmp_path, indices): + with pytest.raises(ResourceError, match="Invalid indices for split 'train'"): + load_splits(_write_json(tmp_path / "s.json", {"models": [{"train": indices}]})) + + +############################################################################### +############################## SEPARATE SPLIT FILES ########################### +############################################################################### + + +def test_separate_files_are_written_per_model_for_multi_model_runs(tmp_path): + plans = [[[0], [1]], [[2], [3]]] + save_separate_splits(tmp_path, plans) + + assert load_splits(tmp_path / "split_indices_0.json") == [plans[0]] + assert load_splits(tmp_path / "split_indices_1.json") == [plans[1]] + + +def test_separate_files_are_skipped_for_single_model_runs(tmp_path): + save_separate_splits(tmp_path, [[[0], [1]]]) + assert list(tmp_path.iterdir()) == [] + + +def test_separate_file_can_be_used_to_load_a_single_member(tmp_path): + save_separate_splits(tmp_path, [[[0]], [[1]], [[2]]]) + assert load_splits(tmp_path / "split_indices_2.json", model_index=0) == [[[2]]] diff --git a/tests/unit/serialization/test_tensorboard.py b/tests/unit/serialization/test_tensorboard.py new file mode 100644 index 00000000..e009cc57 --- /dev/null +++ b/tests/unit/serialization/test_tensorboard.py @@ -0,0 +1,299 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the TensorBoard logging singleton.""" + +import logging +from pathlib import Path + +import pytest +import torch +from tensorboard.backend.event_processing.event_accumulator import EventAccumulator + +from xanesnet.serialization.config import Config +from xanesnet.serialization.tensorboard import TensorBoardLogger, tb_logger + + +@pytest.fixture(autouse=True) +def _clean_logger(): + """The logger is a process-wide singleton: close it and reset opt-in flags around every test.""" + tb_logger.close() + tb_logger.set_log_weights(False) + tb_logger.set_config(Config({})) + yield + tb_logger.close() + tb_logger.set_log_weights(False) + tb_logger.set_config(Config({})) + + +def _read(log_dir: Path) -> EventAccumulator: + accumulator = EventAccumulator(str(log_dir), size_guidance={"tensors": 0, "histograms": 0, "scalars": 0}) + accumulator.Reload() + return accumulator + + +def _scalars(log_dir: Path, tag: str) -> list[tuple[int, float]]: + return [(event.step, event.value) for event in _read(log_dir).Scalars(tag)] + + +def _tags(log_dir: Path, category: str) -> list[str]: + """Return a tag category after narrowing the accumulator's optional value. + + Args: + log_dir: Event directory to read. + category: Tag category name, such as ``"scalars"`` or ``"histograms"``. + + Returns: + Tags recorded in the requested category. + """ + tags = _read(log_dir).Tags()[category] + assert isinstance(tags, list) + return tags + + +class _Scale(torch.nn.Module): + def __init__(self) -> None: + super().__init__() + self.linear = torch.nn.Linear(3, 2) + + def forward(self, x: torch.Tensor, scale: float = 1.0) -> torch.Tensor: + return self.linear(x) * scale + + +############################################################################### +################################## LIFECYCLE ################################## +############################################################################### + + +def test_logger_is_a_singleton(): + assert TensorBoardLogger() is tb_logger + + +def test_logger_is_disabled_until_a_run_is_started(): + assert tb_logger.enabled is False + + +def test_logging_before_a_run_is_a_silent_noop(): + tb_logger.log_scalar("a", 1.0, 0) + tb_logger.log_learning_rate(0, 0.1) + tb_logger.log_epoch_metrics(0, 1.0, 0.0, 1.0) + tb_logger.log_text("t", "x", 0) + tb_logger.log_final_metrics({"m": 1.0}) + tb_logger.flush() + + +def test_writer_access_requires_a_started_run(): + with pytest.raises(RuntimeError, match="not initialized"): + tb_logger.writer + + +def test_new_run_enables_logging_and_creates_event_files(tmp_path): + tb_logger.new_run(tmp_path) + tb_logger.log_scalar("x", 1.0, 0) + tb_logger.flush() + + assert tb_logger.enabled is True + assert list(tmp_path.glob("events.out.tfevents.*")) + + +def test_close_disables_logging_again(tmp_path): + tb_logger.new_run(tmp_path) + tb_logger.close() + + assert tb_logger.enabled is False + tb_logger.log_scalar("x", 1.0, 0) # must not raise + + +def test_closing_twice_is_harmless(tmp_path): + tb_logger.new_run(tmp_path) + tb_logger.close() + tb_logger.close() + + +def test_starting_a_new_run_redirects_output_to_the_new_directory(tmp_path): + first, second = tmp_path / "first", tmp_path / "second" + tb_logger.new_run(first) + tb_logger.log_scalar("x", 1.0, 0) + tb_logger.new_run(second) + tb_logger.log_scalar("y", 2.0, 0) + tb_logger.flush() + + assert _scalars(first, "x") == [(0, 1.0)] + assert _scalars(second, "y") == [(0, 2.0)] + assert "y" not in _tags(first, "scalars") + + +############################################################################### +################################### METRICS ################################### +############################################################################### + + +def test_log_scalar_records_value_at_step(tmp_path): + tb_logger.new_run(tmp_path) + tb_logger.log_scalar("custom/metric", 0.5, 3) + tb_logger.flush() + assert _scalars(tmp_path, "custom/metric") == [(3, 0.5)] + + +def test_epoch_metrics_without_validation(tmp_path): + tb_logger.new_run(tmp_path) + tb_logger.log_epoch_metrics(2, train_loss=1.0, train_regularization=0.25, train_total=1.25) + tb_logger.flush() + + tags = set(_tags(tmp_path, "scalars")) + assert tags == {"loss/train", "regularization/train", "total/train"} + assert _scalars(tmp_path, "total/train") == [(2, 1.25)] + + +def test_epoch_metrics_with_validation(tmp_path): + tb_logger.new_run(tmp_path) + tb_logger.log_epoch_metrics(0, 1.0, 0.0, 1.0, valid_loss=2.0, valid_regularization=0.5, valid_total=2.5) + tb_logger.flush() + + assert _scalars(tmp_path, "loss/valid") == [(0, 2.0)] + assert _scalars(tmp_path, "regularization/valid") == [(0, 0.5)] + assert _scalars(tmp_path, "total/valid") == [(0, 2.5)] + + +def test_learning_rate_is_logged_under_the_other_group(tmp_path): + tb_logger.new_run(tmp_path) + tb_logger.log_learning_rate(4, 0.01) + tb_logger.flush() + assert _scalars(tmp_path, "other/learning_rate") == [(4, pytest.approx(0.01))] + + +def test_text_and_histogram_logging(tmp_path): + tb_logger.new_run(tmp_path) + tb_logger.log_text("note", "hello", 0) + tb_logger.log_histogram("dist", torch.randn(100), 0) + tb_logger.flush() + + assert "note/text_summary" in _tags(tmp_path, "tensors") + assert "dist" in _tags(tmp_path, "histograms") + + +############################################################################### +############################ WEIGHT / GRADIENT HISTOGRAMS ##################### +############################################################################### + + +def _model_with_gradients() -> torch.nn.Module: + model = torch.nn.Linear(3, 2) + model(torch.randn(4, 3)).sum().backward() + return model + + +def test_weight_histograms_are_opt_in(tmp_path): + tb_logger.new_run(tmp_path) + tb_logger.log_model_weights(0, _model_with_gradients()) + tb_logger.flush() + assert _tags(tmp_path, "histograms") == [] + + +def test_weight_and_gradient_histograms_when_enabled(tmp_path): + tb_logger.set_log_weights(True) + tb_logger.new_run(tmp_path) + tb_logger.log_model_weights(0, _model_with_gradients()) + tb_logger.flush() + + assert set(_tags(tmp_path, "histograms")) == { + "weights/weight", + "weights/bias", + "gradients/weight", + "gradients/bias", + } + + +def test_gradient_histograms_are_skipped_for_parameters_without_gradients(tmp_path): + tb_logger.set_log_weights(True) + tb_logger.new_run(tmp_path) + tb_logger.log_model_weights(0, torch.nn.Linear(3, 2)) + tb_logger.flush() + + assert set(_tags(tmp_path, "histograms")) == {"weights/weight", "weights/bias"} + + +############################################################################### +################################# HYPERPARAMETERS ############################# +############################################################################### + + +def test_config_is_written_as_a_hyperparameter_table(tmp_path): + tb_logger.set_config(Config({"trainer": {"epochs": 3, "lr_scheduler": {"type": "none"}}, "layers": [1, 2]})) + tb_logger.new_run(tmp_path) + tb_logger.flush() + + accumulator = _read(tmp_path) + assert "hyperparameters/text_summary" in _tags(tmp_path, "tensors") + text = accumulator.Tensors("hyperparameters/text_summary")[0].tensor_proto.string_val[0].decode() + assert "`trainer.epochs` | `3`" in text + assert "`trainer.lr_scheduler.type` | `none`" in text + assert "`layers` | `[1, 2]`" in text + + +def test_final_metrics_are_logged_next_to_hyperparameters(tmp_path): + tb_logger.set_config(Config({"seed": 1, "model": {"kind": "mlp"}, "skipped": None})) + tb_logger.new_run(tmp_path) + tb_logger.log_final_metrics({"hparam/final_loss": 0.5}) + tb_logger.flush() + + assert list(tmp_path.glob("events.out.tfevents.*")), "events must be written to the run directory itself" + assert not [p for p in tmp_path.iterdir() if p.is_dir()], "run_name='.' must not create a sub-directory" + + +############################################################################### +################################### MODEL GRAPH ############################### +############################################################################### + + +def test_model_graph_is_logged_with_bound_non_tensor_inputs(tmp_path): + tb_logger.new_run(tmp_path) + tb_logger.log_model_graph(_Scale(), {"x": torch.randn(2, 3), "scale": 2.0}) + tb_logger.flush() + assert _read(tmp_path).Graph() is not None + + +def test_model_graph_failures_degrade_to_a_warning(tmp_path, caplog): + tb_logger.new_run(tmp_path) + with caplog.at_level(logging.WARNING): + tb_logger.log_model_graph(_Scale(), {"scale": 2.0}) # the required tensor input is missing + assert "Skipping TensorBoard graph logging" in caplog.text + + +def test_model_graph_without_tensor_inputs_is_skipped(tmp_path, caplog): + class NoTensors(torch.nn.Module): + def forward(self, scale: float = 1.0) -> float: + return scale + + tb_logger.new_run(tmp_path) + with caplog.at_level(logging.WARNING): + tb_logger.log_model_graph(NoTensors(), {"scale": 2.0}) + assert "no tensor inputs" in caplog.text + + +def test_model_graph_logging_is_a_noop_when_disabled(): + tb_logger.log_model_graph(_Scale(), {"x": torch.randn(2, 3)}) diff --git a/tests/unit/strategies/__init__.py b/tests/unit/strategies/__init__.py new file mode 100644 index 00000000..c237a8e9 --- /dev/null +++ b/tests/unit/strategies/__init__.py @@ -0,0 +1,28 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for shared strategy contracts.""" diff --git a/tests/unit/strategies/test_strategy_base.py b/tests/unit/strategies/test_strategy_base.py new file mode 100644 index 00000000..10a77cad --- /dev/null +++ b/tests/unit/strategies/test_strategy_base.py @@ -0,0 +1,347 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for behavior shared by all ``Strategy`` implementations.""" + +import logging +from collections.abc import Callable +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest +import torch + +import xanesnet.strategies.base as strategy_base +from xanesnet.models import Model +from xanesnet.serialization.config import Config +from xanesnet.strategies.base import Strategy +from xanesnet.utils.exceptions import ConfigError + + +class MinimalDataset: + """Dataset stub with configurable split plans and a spectral energy grid.""" + + def __init__(self, plans=None, energies=torch.tensor([1.0, 2.0, 3.0])) -> None: + self.plans = plans if plans is not None else [[[0, 1, 2, 3], [4, 5]]] + self.energies = energies + self.train_subset = None + self.signature = Config({"dataset_type": "minimal"}) + + def setup_splits(self): + self.train_subset = object() if self.plans else None + return self.plans + + def get_subset_indices(self, subset_index): + if not self.plans or subset_index >= len(self.plans[0]): + return None + return self.plans[0][subset_index] + + def __getitem__(self, index): + return SimpleNamespace(energies=self.energies) + + +class MinimalModel(Model): + """Model stub that records the shared strategy's weight initialization.""" + + def __init__(self, model_config: Config) -> None: + super().__init__("minimal") + self.linear = torch.nn.Linear(1, 1) + self._signature = model_config + self.init_calls: list[tuple[str, str, dict[str, Any]]] = [] + + def init_weights(self, weights_init: str, bias_init: str, **kwargs: Any) -> None: + self.init_calls.append((weights_init, bias_init, kwargs)) + + @property + def signature(self) -> Config: + return self._signature + + +class MinimalStrategy(Strategy): + """Concrete strategy stub used to exercise inherited base behavior.""" + + def __init__(self, model_count: int = 1, **kwargs: Any) -> None: + self.model_count = model_count + super().__init__(**kwargs) + + def setup_models(self, model_config: Config) -> None: + self.models.clear() + for _ in range(self.model_count): + self.models.append(MinimalModel(model_config)) + + def setup_trainers(self, device: str | torch.device) -> None: + self.trainers = [None] * self.model_count + + def run_training(self) -> list[Model]: + return super().run_training() + + def setup_inferencers(self, device: str | torch.device) -> None: + self.inferencer = None + + def run_inference(self, predictions_save_path: str | Path | None) -> None: + super().run_inference(predictions_save_path) + + +class MinimalEncoding: + """Encoding stub that records the energy-grid length used during setup.""" + + def __init__(self) -> None: + self.prepared_for = None + + def prepare(self, n_energies: int) -> None: + self.prepared_for = n_energies + + def output_size(self, n_energies: int) -> int: + return n_energies + + @property + def signature(self) -> list[Config]: + return [Config({"encoding_type": "minimal"})] + + +def install_minimal_encoding(monkeypatch: pytest.MonkeyPatch) -> MinimalEncoding: + """Replace encoding resolution and construction with a local test stub. + + Args: + monkeypatch: Pytest fixture used to replace strategy dependencies. + + Returns: + The encoding stub returned by the patched factory. + """ + encoding = MinimalEncoding() + monkeypatch.setattr(strategy_base, "resolve_auto_encoding_config", lambda config, dataset: config) + monkeypatch.setattr( + strategy_base, + "CombinedEncoding", + SimpleNamespace(from_configs=lambda configs: encoding), + ) + return encoding + + +@pytest.fixture +def build() -> Callable[..., MinimalStrategy]: + """Provide a factory for constructing minimal strategies. + + Returns: + Factory accepting a dataset, model count, and strategy overrides. + """ + + def factory(dataset=None, model_count: int = 1, **overrides: Any) -> MinimalStrategy: + """Construct a strategy with resolved test configuration values.""" + kwargs = { + "strategy_type": "minimal", + "dataset": dataset if dataset is not None else MinimalDataset(), + "weight_init": "xavier", + "weight_init_params": Config({"gain": 2.0}), + "bias_init": "zeros", + "checkpoint_dir": None, + "checkpoint_interval": None, + "tensorboard_dir": None, + "trainer_config": Config({"trainer_type": "minimal"}), + "inferencer_config": Config({"inferencer_type": "minimal"}), + } + kwargs.update(overrides) + return MinimalStrategy(model_count=model_count, **kwargs) + + return factory + + +@pytest.fixture +def model_config() -> Config: + """Provide the minimal model configuration used by strategy tests. + + Returns: + Configuration identifying the test model and its width. + """ + return Config({"model_type": "minimal", "width": 3}) + + +def test_a_strategy_needs_a_trainer_or_an_inferencer_config(build): + with pytest.raises(ValueError, match="Either trainer_config or inferencer_config"): + build(trainer_config=None, inferencer_config=None) + + assert build(trainer_config=None).trainer_config is None + assert build(inferencer_config=None).inferencer_config is None + + +def test_weights_are_initialised_with_the_configured_schemes_on_every_model(build, model_config): + strategy = build(model_count=2) + strategy.setup_models(model_config) + + strategy.init_model_weights() + + assert [model.init_calls for model in strategy.models] == [[("xavier", "zeros", {"gain": 2.0})]] * 2 + + +def test_weights_cannot_be_initialised_before_the_models_exist(build): + with pytest.raises(ValueError, match="models are not initialized"): + build().init_model_weights() + + +def test_state_dicts_are_loaded_into_the_models_in_order(build, model_config): + strategy = build(model_count=2) + strategy.setup_models(model_config) + states = [ + {"linear.weight": torch.full((1, 1), 1.0), "linear.bias": torch.zeros(1)}, + {"linear.weight": torch.full((1, 1), 2.0), "linear.bias": torch.zeros(1)}, + ] + + strategy.set_state_dicts(states) + + assert [model.linear.weight.item() for model in strategy.models] == [1.0, 2.0] + + +def test_too_few_checkpoint_states_are_an_error(build, model_config): + strategy = build(model_count=2) + strategy.setup_models(model_config) + + with pytest.raises(ConfigError, match="1 model states; strategy requires 2"): + strategy.set_state_dicts([strategy.models[0].state_dict()]) + + +def test_extra_checkpoint_states_are_ignored_with_a_warning(build, model_config, caplog): + strategy = build() + strategy.setup_models(model_config) + first = {"linear.weight": torch.full((1, 1), 5.0), "linear.bias": torch.zeros(1)} + extra = {"linear.weight": torch.full((1, 1), 9.0), "linear.bias": torch.zeros(1)} + + with caplog.at_level(logging.WARNING): + strategy.set_state_dicts([first, extra]) + + assert strategy.models[0].linear.weight.item() == 5.0 + assert "1 extra model states" in caplog.text + + +def test_state_dicts_cannot_be_loaded_before_the_models_exist(build): + with pytest.raises(ValueError, match="models are not initialized"): + build().set_state_dicts([{}]) + + +def test_splits_come_from_the_dataset(build): + dataset = MinimalDataset(plans=[[[0, 1, 2, 3], [4, 5]]]) + + assert build(dataset).setup_model_splits() == [[[0, 1, 2, 3], [4, 5]]] + assert dataset.get_subset_indices(1) == [4, 5] + + +def test_the_encoding_is_built_from_config_and_prepared_for_the_energy_grid(build, monkeypatch): + strategy = build() + strategy.setup_model_splits() + encoding = install_minimal_encoding(monkeypatch) + + configured = strategy.setup_encoding(Config({"encodings": [{"encoding_type": "minimal"}]})) + + assert strategy.encoding is configured is encoding + assert encoding.output_size(3) == 3 + assert encoding.prepared_for == 3 + + +def test_training_requires_splits_before_encoding(build, monkeypatch): + strategy = build(dataset=MinimalDataset(plans=[])) + install_minimal_encoding(monkeypatch) + + with pytest.raises(ValueError, match="before model splits are initialized"): + strategy.setup_encoding(Config({"encodings": []})) + + +def test_inference_can_build_encoding_without_splits(build, monkeypatch): + strategy = build(dataset=MinimalDataset(plans=[]), trainer_config=None) + encoding = install_minimal_encoding(monkeypatch) + + assert strategy.setup_encoding(Config({"encodings": []})) is encoding + + +@pytest.mark.parametrize("energies", [None, torch.tensor(1.0)]) +def test_samples_without_an_energy_grid_are_rejected(build, monkeypatch, energies): + strategy = build(dataset=MinimalDataset(energies=energies)) + strategy.setup_model_splits() + install_minimal_encoding(monkeypatch) + + with pytest.raises(ValueError, match="spectral energy grid"): + strategy.setup_encoding(Config({"encodings": []})) + + +def test_checkpointer_signature_combines_dataset_model_and_encoding(build, model_config, tmp_path): + strategy = build(checkpoint_dir=tmp_path / "ckpt", checkpoint_interval=5) + strategy.encoding = MinimalEncoding() + strategy.setup_models(model_config) + + checkpointer = strategy.setup_checkpointer() + + assert strategy.checkpointer is checkpointer + assert checkpointer.save_dir == tmp_path / "ckpt" + assert checkpointer.save_interval == 5 + assert checkpointer.signature.as_dict() == { + "dataset": {"dataset_type": "minimal"}, + "model": {"model_type": "minimal", "width": 3}, + "encodings": [{"encoding_type": "minimal"}], + } + + +@pytest.mark.parametrize( + ("with_encoding", "message"), + [(False, "encoding is not initialized"), (True, "Models are not initialized")], +) +def test_checkpointer_needs_encoding_and_models(build, with_encoding, message): + strategy = build() + if with_encoding: + strategy.encoding = MinimalEncoding() + + with pytest.raises(ValueError, match=message): + strategy.setup_checkpointer() + + +def test_checkpointer_is_only_for_training(build, model_config): + strategy = build(trainer_config=None) + strategy.encoding = MinimalEncoding() + strategy.setup_models(model_config) + + with pytest.raises(ValueError, match="no trainer config"): + strategy.setup_checkpointer() + + +def test_the_checkpointer_sees_the_current_trainers(build, model_config): + strategy = build() + strategy.encoding = MinimalEncoding() + strategy.setup_models(model_config) + strategy.setup_checkpointer() + strategy.setup_trainers("cpu") + + assert strategy.checkpointer.trainer_provider() is strategy.trainers + + +def test_model_signature_requires_models(build): + with pytest.raises(ValueError, match="Models are not initialized"): + _ = build().model_signature + + +def test_model_signature_is_that_of_the_first_model(build, model_config): + strategy = build(model_count=2) + strategy.setup_models(model_config) + + assert strategy.model_signature.as_dict() == {"model_type": "minimal", "width": 3} diff --git a/tests/unit/utils/__init__.py b/tests/unit/utils/__init__.py new file mode 100644 index 00000000..406d8983 --- /dev/null +++ b/tests/unit/utils/__init__.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." diff --git a/tests/unit/utils/test_exceptions.py b/tests/unit/utils/test_exceptions.py new file mode 100644 index 00000000..06f3fd9d --- /dev/null +++ b/tests/unit/utils/test_exceptions.py @@ -0,0 +1,42 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the XANESNET exception hierarchy.""" + +import pytest + +from xanesnet.utils.exceptions import ConfigError, CriticalError, ResourceError + + +@pytest.mark.parametrize("error", [ConfigError, ResourceError]) +def test_specific_errors_are_critical_errors(error): + assert issubclass(error, CriticalError) + + +def test_config_and_resource_errors_are_distinct(): + assert not issubclass(ConfigError, ResourceError) + assert not issubclass(ResourceError, ConfigError) diff --git a/tests/unit/utils/test_filesystem.py b/tests/unit/utils/test_filesystem.py new file mode 100644 index 00000000..a04decdb --- /dev/null +++ b/tests/unit/utils/test_filesystem.py @@ -0,0 +1,213 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for filesystem helpers: listing, run-directory creation and file copying.""" + +import re +from pathlib import Path + +import pytest + +from xanesnet.utils.filesystem import ( + copy_file, + create_run_dir, + create_subfolders, + list_files, + list_filestems, + list_subdir_stems, + list_subdirs, +) + + +@pytest.fixture +def populated_dir(tmp_path: Path) -> Path: + """Directory with visible files, a hidden file and sub-directories.""" + (tmp_path / "a.json").write_text("{}") + (tmp_path / "b.json").write_text("{}") + (tmp_path / "c.txt").write_text("c") + (tmp_path / ".hidden.json").write_text("{}") + (tmp_path / "zeta").mkdir() + (tmp_path / "alpha").mkdir() + (tmp_path / ".cache").mkdir() + return tmp_path + + +############################################################################### +################################### LISTING ################################### +############################################################################### + + +def test_list_files_returns_visible_files_only(populated_dir): + assert {p.name for p in list_files(populated_dir)} == {"a.json", "b.json", "c.txt"} + + +@pytest.mark.parametrize("suffixes", [".json", (".json",)], ids=["str", "tuple"]) +def test_list_files_filters_by_suffix(populated_dir, suffixes): + assert {p.name for p in list_files(populated_dir, suffixes=suffixes)} == {"a.json", "b.json"} + + +def test_list_files_can_strip_the_extension(populated_dir): + assert {p.name for p in list_files(populated_dir, with_ext=False)} == {"a", "b", "c"} + + +def test_list_filestems(populated_dir): + assert sorted(list_filestems(populated_dir, suffixes=".json")) == ["a", "b"] + + +def test_list_subdirs_skips_hidden_directories(populated_dir): + assert {p.name for p in list_subdirs(populated_dir)} == {"alpha", "zeta"} + + +def test_list_subdir_stems_are_sorted(populated_dir): + assert list_subdir_stems(populated_dir) == ["alpha", "zeta"] + + +############################################################################### +################################ create_run_dir ############################### +############################################################################### + + +def test_count_mode_starts_at_zero_and_increments(tmp_path): + first = create_run_dir(tmp_path, name="train") + second = create_run_dir(tmp_path, name="train") + assert (first.name, second.name) == ("train_000", "train_001") + assert first.is_dir() and second.is_dir() + + +def test_count_mode_continues_after_the_highest_existing_index(tmp_path): + (tmp_path / "train_004").mkdir() + (tmp_path / "train_not_a_number").mkdir() + assert create_run_dir(tmp_path, name="train").name == "train_005" + + +def test_count_mode_counts_each_name_independently(tmp_path): + (tmp_path / "train_007").mkdir() + assert create_run_dir(tmp_path, name="infer").name == "infer_000" + + +def test_count_mode_defaults_to_run_name(tmp_path): + assert create_run_dir(tmp_path).name == "run_000" + + +def test_count_mode_creates_missing_parent_directories(tmp_path): + run_dir = create_run_dir(tmp_path / "nested" / "runs", name="x") + assert run_dir.is_dir() + assert run_dir.parent == tmp_path / "nested" / "runs" + + +def test_base_dir_may_be_given_as_a_string(tmp_path): + assert create_run_dir(str(tmp_path), name="x").parent == tmp_path + + +@pytest.mark.parametrize("name, pattern", [(None, r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$"), ("exp", r"_exp$")]) +def test_time_mode_uses_a_timestamp_with_optional_suffix(tmp_path, name, pattern): + run_dir = create_run_dir(tmp_path, name=name, mode="time") + assert re.search(pattern, run_dir.name) + assert run_dir.is_dir() + + +def test_invalid_mode_raises(tmp_path): + with pytest.raises(ValueError, match="Invalid mode"): + create_run_dir(tmp_path, mode="bogus") + + +############################################################################### +############################### create_subfolders ############################# +############################################################################### + + +def test_create_subfolders_creates_and_maps_every_name(tmp_path): + paths = create_subfolders(tmp_path, ["models", "checkpoints"]) + assert paths == {"models": tmp_path / "models", "checkpoints": tmp_path / "checkpoints"} + assert all(p.is_dir() for p in paths.values()) + + +def test_create_subfolders_is_idempotent(tmp_path): + create_subfolders(tmp_path, ["models"]) + assert create_subfolders(tmp_path, ["models"]) == {"models": tmp_path / "models"} + + +def test_create_subfolders_requires_an_existing_parent(tmp_path): + with pytest.raises(FileNotFoundError, match="Parent directory does not exist"): + create_subfolders(tmp_path / "missing", ["models"]) + + +############################################################################### +#################################### copy_file ################################ +############################################################################### + + +@pytest.fixture +def source_file(tmp_path: Path) -> Path: + src = tmp_path / "src" / "config.yaml" + src.parent.mkdir() + src.write_text("seed: 1\n") + return src + + +@pytest.fixture +def dest_dir(tmp_path: Path) -> Path: + dst = tmp_path / "dst" + dst.mkdir() + return dst + + +def test_copy_preserves_name_and_content(source_file, dest_dir): + copied = copy_file(source_file, dest_dir) + assert copied == dest_dir / "config.yaml" + assert copied.read_text() == "seed: 1\n" + assert source_file.exists() + + +def test_copy_can_rename(source_file, dest_dir): + assert copy_file(source_file, dest_dir, new_name="renamed.yaml") == dest_dir / "renamed.yaml" + + +def test_copy_accepts_string_paths(source_file, dest_dir): + assert copy_file(str(source_file), str(dest_dir)).exists() + + +def test_copy_rejects_a_disallowed_suffix(source_file, dest_dir): + with pytest.raises(ValueError, match="suffix not allowed"): + copy_file(source_file, dest_dir, allowed_suffixes={".json"}) + assert list(dest_dir.iterdir()) == [] + + +def test_copy_accepts_an_allowed_suffix(source_file, dest_dir): + assert copy_file(source_file, dest_dir, allowed_suffixes={".yaml", ".yml"}).exists() + + +@pytest.mark.parametrize("which", ["missing", "directory"]) +def test_copy_requires_a_regular_source_file(tmp_path, dest_dir, which): + src = tmp_path / "missing.yaml" if which == "missing" else tmp_path + with pytest.raises(FileNotFoundError, match="Source file does not exist"): + copy_file(src, dest_dir) + + +def test_copy_requires_an_existing_destination_directory(source_file, tmp_path): + with pytest.raises(FileNotFoundError, match="Destination directory does not exist"): + copy_file(source_file, tmp_path / "nowhere") diff --git a/tests/unit/utils/test_lightning_context.py b/tests/unit/utils/test_lightning_context.py new file mode 100644 index 00000000..d4248a70 --- /dev/null +++ b/tests/unit/utils/test_lightning_context.py @@ -0,0 +1,64 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the environment-based Lightning worker context.""" + +from pathlib import Path + +import pytest + +from xanesnet.utils.exceptions import ConfigError +from xanesnet.utils.lightning import LIGHTNING_CONTEXT_ENV, get_lightning_context_path + + +def test_absent_variable_means_no_context(monkeypatch): + monkeypatch.delenv(LIGHTNING_CONTEXT_ENV, raising=False) + assert get_lightning_context_path() is None + + +def test_absolute_path_is_returned_as_path(monkeypatch, tmp_path): + monkeypatch.setenv(LIGHTNING_CONTEXT_ENV, str(tmp_path / "context.pt")) + assert get_lightning_context_path() == tmp_path / "context.pt" + assert isinstance(get_lightning_context_path(), Path) + + +@pytest.mark.parametrize("value", ["", "relative/context.pt", "./context.pt"]) +def test_empty_or_relative_values_are_rejected(monkeypatch, value): + monkeypatch.setenv(LIGHTNING_CONTEXT_ENV, value) + with pytest.raises(ConfigError, match="absolute context path"): + get_lightning_context_path() + + +def test_reading_the_context_does_not_import_lightning(monkeypatch): + """The helper exists so non-Lightning runs never pay for (or require) the Lightning import.""" + import sys + + monkeypatch.delenv(LIGHTNING_CONTEXT_ENV, raising=False) + modules_before = {name for name in sys.modules if name.startswith(("lightning", "pytorch_lightning"))} + get_lightning_context_path() + modules_after = {name for name in sys.modules if name.startswith(("lightning", "pytorch_lightning"))} + assert modules_after == modules_before diff --git a/tests/unit/utils/test_logger.py b/tests/unit/utils/test_logger.py new file mode 100644 index 00000000..c61a3acc --- /dev/null +++ b/tests/unit/utils/test_logger.py @@ -0,0 +1,170 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for logging setup, level filtering and stdout/stderr tee-ing.""" + +import io +import logging +import sys + +import pytest + +from xanesnet.utils.logger import LevelFilter, TeeLogger, setup_file_logging, setup_logging + + +def _record(level: int) -> logging.LogRecord: + return logging.LogRecord("t", level, __file__, 1, "msg", None, None) + + +############################################################################### +################################## LevelFilter ################################ +############################################################################### + + +@pytest.mark.parametrize( + "filter_level, record_level, passes", + [ + (logging.INFO, logging.INFO, True), + (logging.INFO, logging.WARNING, False), + (logging.INFO, logging.DEBUG, False), + (logging.ERROR, logging.CRITICAL, False), + ], +) +def test_level_filter_passes_only_the_exact_level(filter_level, record_level, passes): + assert LevelFilter(filter_level).filter(_record(record_level)) is passes + + +############################################################################### +################################# setup_logging ############################### +############################################################################### + + +def test_setup_logging_replaces_existing_root_handlers(): + root = logging.getLogger() + stale = logging.NullHandler() + root.addHandler(stale) + + setup_logging(logging.INFO) + + assert stale not in root.handlers + + +def test_setup_logging_sets_the_root_level(): + setup_logging(logging.WARNING) + assert logging.getLogger().level == logging.WARNING + + +def test_setup_logging_is_idempotent(): + setup_logging() + count = len(logging.getLogger().handlers) + setup_logging() + assert len(logging.getLogger().handlers) == count + + +def test_each_level_is_emitted_exactly_once_to_the_right_stream(capsys): + setup_logging(logging.DEBUG) + logging.debug("d-msg") + logging.info("i-msg") + logging.warning("w-msg") + logging.error("e-msg") + logging.critical("c-msg") + + captured = capsys.readouterr() + for message in ("d-msg", "i-msg", "w-msg"): + assert captured.out.count(message) == 1 + assert message not in captured.err + for message in ("e-msg", "c-msg"): + assert captured.err.count(message) == 1 + assert message not in captured.out + + +def test_messages_below_the_configured_level_are_suppressed(capsys): + setup_logging(logging.WARNING) + logging.info("quiet") + logging.warning("loud") + captured = capsys.readouterr() + assert "quiet" not in captured.out + captured.err + assert "loud" in captured.out + + +############################################################################### +################################### TeeLogger ################################# +############################################################################### + + +def test_tee_logger_writes_to_stream_and_file(tmp_path): + stream = io.StringIO() + tee = TeeLogger(tmp_path / "log.txt", stream) + + tee.write("hello ") + tee.write("world") + tee.flush() + + assert stream.getvalue() == "hello world" + assert (tmp_path / "log.txt").read_text() == "hello world" + + +def test_tee_logger_appends_to_an_existing_file(tmp_path): + path = tmp_path / "log.txt" + path.write_text("old\n") + TeeLogger(path, io.StringIO()).write("new\n") + assert path.read_text() == "old\nnew\n" + + +############################################################################### +############################### setup_file_logging ############################ +############################################################################### + + +def test_file_logging_mirrors_logs_and_prints_into_out_txt(tmp_path, capsys): + setup_logging(logging.DEBUG) + setup_file_logging(tmp_path) + + logging.info("logged-info") + logging.error("logged-error") + print("plain-print") + sys.stdout.flush() + + content = (tmp_path / "out.txt").read_text() + assert "logged-info" in content + assert "logged-error" in content + assert "plain-print" in content + + +def test_file_logging_keeps_console_output(tmp_path, capsys): + setup_logging(logging.DEBUG) + setup_file_logging(tmp_path) + + print("still-visible") + + assert "still-visible" in capsys.readouterr().out + + +def test_file_logging_replaces_std_streams_with_tee_loggers(tmp_path): + setup_file_logging(tmp_path) + assert isinstance(sys.stdout, TeeLogger) + assert isinstance(sys.stderr, TeeLogger) diff --git a/tests/unit/utils/test_math.py b/tests/unit/utils/test_math.py new file mode 100644 index 00000000..6ee3283b --- /dev/null +++ b/tests/unit/utils/test_math.py @@ -0,0 +1,163 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the shared spectral math helpers (symmetric FFT and Gaussian basis).""" + +import pytest +import torch + +from xanesnet.utils.math import ( + SpectralBasis, + SpectralPost, + build_ridge_operator, + fft, + gaussian_fit, + gaussian_inverse, + inverse_fft, +) + + +@pytest.fixture +def signal() -> torch.Tensor: + generator = torch.Generator().manual_seed(0) + return torch.rand(3, 16, generator=generator) + + +@pytest.fixture +def basis() -> SpectralBasis: + energies = torch.linspace(0.0, 10.0, 40) + return SpectralBasis(energies, widths_eV=[0.5, 1.0], stride=2) + + +############################################################################### +#################################### FFT ###################################### +############################################################################### + + +@pytest.mark.parametrize("concat, factor", [(False, 2), (True, 3)]) +def test_fft_output_length(signal, concat, factor): + assert fft(signal, concat=concat).shape == (3, signal.shape[-1] * factor) + + +def test_fft_with_concat_prepends_the_original_signal(signal): + out = fft(signal, concat=True) + torch.testing.assert_close(out[..., : signal.shape[-1]], signal) + torch.testing.assert_close(out[..., signal.shape[-1] :], fft(signal, concat=False)) + + +@pytest.mark.parametrize("concat", [False, True]) +def test_inverse_fft_recovers_the_signal(signal, concat): + restored = inverse_fft(fft(signal, concat=concat), concat=concat) + torch.testing.assert_close(restored, signal, atol=1e-4, rtol=1e-4) + + +def test_fft_roundtrip_handles_unbatched_input(): + x = torch.linspace(0, 1, 8) + torch.testing.assert_close(inverse_fft(fft(x, concat=False), concat=False), x, atol=1e-4, rtol=1e-4) + + +@pytest.mark.parametrize("concat, length", [(True, 10), (False, 9)]) +def test_inverse_fft_rejects_incompatible_lengths(concat, length): + with pytest.raises(ValueError, match="divisible"): + inverse_fft(torch.zeros(length), concat=concat) + + +############################################################################### +############################### GAUSSIAN BASIS ################################ +############################################################################### + + +def test_basis_dimensions_follow_widths_and_stride(basis): + n_points, n_basis = 40, 2 * 20 + assert basis.Phi.shape == (n_points, n_basis) + assert basis.centers.shape == (n_basis,) + + +def test_basis_columns_are_normalized_by_default(basis): + dE = float(basis.E[1] - basis.E[0]) + torch.testing.assert_close(basis.Phi.sum(dim=0) * dE, torch.ones(basis.Phi.shape[1]), atol=1e-4, rtol=1e-4) + + +def test_unnormalized_basis_peaks_at_one(): + energies = torch.linspace(0.0, 10.0, 40) + plain = SpectralBasis(energies, widths_eV=[1.0], normalize_atoms=False) + assert plain.Phi.max() == pytest.approx(1.0) + + +def test_basis_buffers_are_not_trainable(basis): + assert list(basis.parameters()) == [] + + +def test_synthesize_is_linear_in_the_coefficients(basis): + coeffs = torch.rand(4, basis.Phi.shape[1]) + torch.testing.assert_close(basis.synthesize(coeffs), coeffs @ basis.Phi.T) + + +def test_device_copy_on_cpu_returns_the_same_instance(basis): + assert basis.device_copy(torch.device("cpu")) is basis + + +def test_ridge_operator_shape_and_dtype(basis): + operator = build_ridge_operator(basis.Phi) + assert operator.shape == (basis.Phi.shape[1], basis.Phi.shape[0]) + assert operator.dtype == torch.float32 + + +def test_ridge_operator_handles_a_singular_gram_matrix(): + phi = torch.ones(5, 3) # rank one, so the un-regularized Gram matrix is singular + operator = build_ridge_operator(phi, lam=1e-6) + assert torch.isfinite(operator).all() + + +def test_gaussian_fit_and_inverse_reconstruct_a_smooth_spectrum(basis): + energies = basis.E + spectrum = torch.exp(-0.5 * ((energies - 5.0) / 1.0) ** 2).unsqueeze(0) + + reconstructed = gaussian_inverse(basis, gaussian_fit(basis, spectrum)) + + assert reconstructed.shape == spectrum.shape + assert torch.nn.functional.mse_loss(reconstructed, spectrum) < 1e-3 + + +def test_gaussian_inverse_can_clamp_negative_values(basis): + coeffs = -torch.ones(1, basis.Phi.shape[1]) + assert gaussian_inverse(basis, coeffs).min() < 0 + assert gaussian_inverse(basis, coeffs.clone(), nonneg_output=True).min() >= 0 + + +def test_spectral_post_matches_basis_synthesis_and_has_no_parameters(basis): + post = SpectralPost(basis) + coeffs = torch.rand(2, basis.Phi.shape[1]) + + torch.testing.assert_close(post(coeffs), basis.synthesize(coeffs)) + torch.testing.assert_close(post.forward_from_coeffs(coeffs), post(coeffs)) + assert list(post.parameters()) == [] + + +def test_spectral_post_nonneg_option_clamps(basis): + post = SpectralPost(basis, nonneg_output=True) + assert post(-torch.ones(1, basis.Phi.shape[1])).min() >= 0 diff --git a/tests/unit/utils/test_prompts.py b/tests/unit/utils/test_prompts.py new file mode 100644 index 00000000..61bb2526 --- /dev/null +++ b/tests/unit/utils/test_prompts.py @@ -0,0 +1,139 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for confirmation prompts and the auto-yes switch.""" + +import pytest + +from xanesnet.utils import prompts +from xanesnet.utils.prompts import auto_yes, confirm_yes_no, is_auto_yes_enabled, set_auto_yes + + +@pytest.fixture(autouse=True) +def _manual_mode(): + """Start every test with auto-yes disabled (global state is restored by the root conftest).""" + set_auto_yes(False) + + +def _answer(monkeypatch, response: str) -> list[str]: + """Make ``input`` return ``response`` and record the prompts that were shown.""" + shown: list[str] = [] + + def fake_input(prompt: str = "") -> str: + shown.append(prompt) + return response + + monkeypatch.setattr("builtins.input", fake_input) + return shown + + +############################################################################### +################################# AUTO-YES MODE ############################### +############################################################################### + + +def test_auto_yes_is_disabled_by_default(): + assert is_auto_yes_enabled() is False + + +def test_set_auto_yes_toggles_the_global_mode(): + set_auto_yes(True) + assert is_auto_yes_enabled() is True + set_auto_yes(False) + assert is_auto_yes_enabled() is False + + +def test_context_manager_enables_auto_yes_only_inside_the_block(): + with auto_yes(): + assert is_auto_yes_enabled() is True + assert is_auto_yes_enabled() is False + + +def test_context_manager_can_override_a_global_enable_with_false(): + set_auto_yes(True) + with auto_yes(False): + assert is_auto_yes_enabled() is False + assert is_auto_yes_enabled() is True + + +def test_nested_contexts_restore_the_outer_value(): + with auto_yes(True): + with auto_yes(False): + assert is_auto_yes_enabled() is False + assert is_auto_yes_enabled() is True + + +def test_context_is_restored_when_the_block_raises(): + with pytest.raises(RuntimeError): + with auto_yes(): + raise RuntimeError("boom") + assert is_auto_yes_enabled() is False + + +############################################################################### +################################ confirm_yes_no ############################### +############################################################################### + + +def test_auto_yes_accepts_without_asking(monkeypatch): + monkeypatch.setattr("builtins.input", lambda *_: pytest.fail("input() must not be called in auto-yes mode")) + with auto_yes(): + assert confirm_yes_no("Proceed?", default_yes=False) is True + + +@pytest.mark.parametrize("response", ["y", "Y", "yes", "YES", " yes "]) +def test_affirmative_answers_return_true(monkeypatch, response): + _answer(monkeypatch, response) + assert confirm_yes_no("Proceed?") is True + + +@pytest.mark.parametrize("response", ["n", "no", "nope", "maybe"]) +def test_other_answers_return_false(monkeypatch, response): + _answer(monkeypatch, response) + assert confirm_yes_no("Proceed?") is False + + +@pytest.mark.parametrize("default_yes", [True, False]) +def test_empty_answer_selects_the_default(monkeypatch, default_yes): + _answer(monkeypatch, "") + assert confirm_yes_no("Proceed?", default_yes=default_yes) is default_yes + + +@pytest.mark.parametrize("default_yes, suffix", [(True, "[Y/n]"), (False, "[y/N]")]) +def test_prompt_shows_the_default_in_its_suffix(monkeypatch, default_yes, suffix): + shown = _answer(monkeypatch, "y") + confirm_yes_no("Overwrite?", default_yes=default_yes) + assert shown == [f"Overwrite? {suffix}: "] + + +def test_module_exposes_no_interactive_state_between_calls(monkeypatch): + """A previous ``auto_yes`` context must not leak into later prompts.""" + with auto_yes(): + confirm_yes_no("first") + _answer(monkeypatch, "n") + assert confirm_yes_no("second") is False + assert prompts.is_auto_yes_enabled() is False diff --git a/tests/unit/utils/test_random.py b/tests/unit/utils/test_random.py new file mode 100644 index 00000000..14387472 --- /dev/null +++ b/tests/unit/utils/test_random.py @@ -0,0 +1,88 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for ``set_global_seed``.""" + +import random + +import numpy as np +import pytest +import torch + +from xanesnet.utils.random import set_global_seed + + +def _draw() -> tuple[float, float, float]: + return random.random(), float(np.random.rand()), float(torch.rand(1)) + + +def test_explicit_seed_is_returned_and_makes_all_generators_reproducible(): + assert set_global_seed(123) == 123 + first = _draw() + set_global_seed(123) + assert _draw() == first + + +def test_different_seeds_give_different_streams(): + set_global_seed(1) + first = _draw() + set_global_seed(2) + assert _draw() != first + + +def test_none_draws_a_valid_random_seed_and_returns_it(): + seed = set_global_seed(None) + assert isinstance(seed, int) + assert 0 <= seed <= 2**32 - 1 + + # The returned seed must reproduce the stream that was just seeded. + first = _draw() + set_global_seed(seed) + assert _draw() == first + + +@pytest.mark.parametrize("seed", [0, 2**32 - 1]) +def test_boundary_seeds_are_accepted(seed): + assert set_global_seed(seed) == seed + + +def test_numpy_integers_are_accepted_and_converted_to_int(): + seed = set_global_seed(np.int64(5)) # type: ignore[arg-type] + assert seed == 5 + assert type(seed) is int + + +@pytest.mark.parametrize("seed", [-1, 2**32]) +def test_out_of_range_seed_raises_value_error(seed): + with pytest.raises(ValueError, match="between 0 and"): + set_global_seed(seed) + + +@pytest.mark.parametrize("seed", ["1", 1.5, [1]]) +def test_non_integer_seed_raises_type_error(seed): + with pytest.raises(TypeError, match="integer or None"): + set_global_seed(seed) diff --git a/tests/unit/utils/test_registry.py b/tests/unit/utils/test_registry.py new file mode 100644 index 00000000..3ec337c5 --- /dev/null +++ b/tests/unit/utils/test_registry.py @@ -0,0 +1,159 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# XANESNET +# +# Authors: Hendrik Junkawitsch, Tom J. Penfold, Thomas J. Pope, C. D. Rankine, B. Li +# +# This program is free software: you can redistribute it and/or modify it under the terms of the +# GNU General Public License as published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. +# If not, see . +# +# Citations: +# Junkawitsch et al., "XANESNET: A Modular, Extensible, and Flexible Machine Learning Framework for Spectroscopy." +# Rankine et al., "A Deep Neural Network for the Rapid Prediction of X-ray Absorption Spectra." +# Rankine et al., "Accurate, affordable, and generalizable machine learning simulations of transition metal x-ray absorption spectra using the XANESNET deep neural network." +# Penfold et al., "Field-Aware Energy-Conditioned Message Passing Neural Networks for Absorber-Centred Modelling of X-ray Spectroscopy." +# Penfold et al., "A deep neural network for valence-to-core X-ray emission spectroscopy." +# Falbo et al., "On the Analysis of X-ray Absorption Spectra for Polyoxometallates." +# Madkhali et al., "Enhancing the Analysis of Disorder in X-ray Absorption Spectra: Application of Deep Neural Networks to T-Jump X-ray Probe Experiments." +# Madkhali et al., "The Role of Structural Representation in the Performance of a Deep Neural Network for X-ray Spectroscopy." + +"""Unit tests for the generic ``Registry`` used by every XANESNET extension point.""" + +import pytest + +from xanesnet.utils.registry import Registry + + +class _Widget: + def __init__(self, size: int = 1, label: str = "w") -> None: + self.size = size + self.label = label + + +@pytest.fixture +def registry() -> Registry[type[_Widget]]: + """Case-insensitive registry, matching how production registries are configured.""" + return Registry("Widget", normalize_key=str.lower) + + +############################################################################### +############################### REGISTRATION ################################## +############################################################################### + + +def test_register_returns_the_decorated_object_unchanged(registry): + assert registry.register("a")(_Widget) is _Widget + + +def test_registered_object_is_retrievable_by_identity(registry): + registry.register("a")(_Widget) + assert registry.get("a") is _Widget + + +def test_duplicate_registration_is_rejected_and_keeps_the_first_entry(registry): + class Other(_Widget): + pass + + registry.register("a")(_Widget) + with pytest.raises(KeyError, match="Widget 'a' already registered"): + registry.register("a")(Other) + assert registry.get("a") is _Widget + + +def test_duplicate_detection_uses_the_normalized_key(registry): + registry.register("Name")(_Widget) + with pytest.raises(KeyError, match="already registered"): + registry.register("NAME")(_Widget) + + +def test_one_object_may_be_registered_under_several_aliases(registry): + registry.register("none")(registry.register("no")(_Widget)) + assert registry.get("none") is registry.get("no") is _Widget + + +############################################################################### +################################### LOOKUP #################################### +############################################################################### + + +def test_lookup_of_unknown_key_raises_with_item_name_and_key(registry): + with pytest.raises(KeyError, match="Widget 'missing' not found in registry"): + registry.get("missing") + + +@pytest.mark.parametrize("key", ["mixed", "MIXED", "Mixed"]) +def test_lookup_is_case_insensitive_when_normalizer_is_configured(registry, key): + registry.register("Mixed")(_Widget) + assert registry.get(key) is _Widget + + +def test_lookup_is_case_sensitive_without_a_normalizer(): + plain: Registry[type[_Widget]] = Registry("Widget") + plain.register("Mixed")(_Widget) + with pytest.raises(KeyError): + plain.get("mixed") + + +def test_list_returns_normalized_keys_in_registration_order(registry): + registry.register("Zeta")(_Widget) + registry.register("alpha")(_Widget) + assert registry.list() == ["zeta", "alpha"] + + +def test_list_returns_a_copy(registry): + registry.register("a")(_Widget) + registry.list().append("injected") + assert registry.list() == ["a"] + + +def test_empty_registry_lists_nothing(registry): + assert registry.list() == [] + + +############################################################################### +################################### CREATION ################################## +############################################################################### + + +def test_create_forwards_keyword_arguments_to_the_registered_factory(registry): + registry.register("a")(_Widget) + widget = registry.create("A", size=5, label="x") + assert isinstance(widget, _Widget) + assert (widget.size, widget.label) == (5, "x") + + +def test_create_with_unknown_key_raises_key_error(registry): + with pytest.raises(KeyError, match="not found"): + registry.create("missing") + + +def test_create_supports_plain_callables(registry): + registry.register("double")(lambda value: value * 2) + assert registry.create("double", value=4) == 8 + + +############################################################################### +############################ CUSTOM (TUPLE) KEYS ############################## +############################################################################### + + +def test_custom_key_normalization_and_formatting(): + registry: Registry[type[_Widget], tuple[str, str]] = Registry( + "Pair", + normalize_key=lambda key: (key[0].lower(), key[1].lower()), + format_key=lambda key: f"for {key[0]}, {key[1]}", + ) + registry.register(("Descriptor", "MLP"))(_Widget) + + assert registry.get(("descriptor", "mlp")) is _Widget + assert registry.list() == [("descriptor", "mlp")] + with pytest.raises(KeyError, match="Pair for a, b not found in registry"): + registry.get(("A", "B")) diff --git a/xanesnet/schemas/runners/runner_types.schema.yaml b/xanesnet/schemas/runners/runner_types.schema.yaml index b2aed84b..05309a1f 100644 --- a/xanesnet/schemas/runners/runner_types.schema.yaml +++ b/xanesnet/schemas/runners/runner_types.schema.yaml @@ -6,6 +6,7 @@ $defs: type: string enum: - basic + - lightning description: Trainer registry key accepted by ``TrainerRegistry.get``. inferencerType: type: string