Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
ae596d1
Update mlp_xyzspec.yaml
shelllbw Nov 9, 2026
78f6ef8
Add dry run tests for mh_mlp, lightning, multipmgjson, and syzspec
shelllbw Nov 9, 2026
1e68d62
Restrict torch-geometric below 2.8 to keep radius_graph working with …
shelllbw Nov 9, 2026
9180dea
Add unit tests for serialization
shelllbw Nov 10, 2026
7bb314b
Add unit tests for checkpointing
shelllbw Nov 11, 2026
a28c572
Add unit tests for cli
shelllbw Nov 11, 2026
b83a4c2
Add unit tests for components and core
shelllbw Nov 11, 2026
3ac9035
Refactor unit tests for serialization
shelllbw Nov 11, 2026
2874de5
Update unit tests for cli
shelllbw Nov 11, 2026
b06147a
Update conftest.py
shelllbw Nov 11, 2026
9b3fb89
Add unit tests for implementations
shelllbw Nov 12, 2026
b2e8e21
Update README.md in tests
shelllbw Nov 12, 2026
13fb7a3
Fix dry-run and unit test isolation for cwd and auto-yes
shelllbw Nov 12, 2026
3ee798c
Add lightning to the trainerType schema enum
shelllbw Nov 12, 2026
253fadb
Add Github actions for tests and GitLab mirroring
shelllbw Nov 12, 2026
70ffa6a
Change PyTorch to 2.6 for matching PyG wheels in Github actions test
shelllbw Nov 12, 2026
2ffa126
Update tests.yml
shelllbw Nov 12, 2026
9c7b341
Track toy_data_multipmgjson
shelllbw Nov 12, 2026
7875233
Merge branch 'main' into unit-tests
shelllbw Nov 12, 2026
556880f
remove toy_data_multipmgjson (use existing multi toy data)
Junkiii Nov 12, 2026
eb6434d
added fail-fast train/infer mismatch for dry-run tests
Junkiii Nov 12, 2026
76b70cb
google-style docstrings for dry-run tests
Junkiii Nov 12, 2026
c684ca1
removed legacy config
Junkiii Nov 12, 2026
cc29d68
some cleanup
Junkiii Nov 13, 2026
158c763
more cleanup
Junkiii Nov 13, 2026
f9384ac
Hendrik github link fixed
Junkiii Nov 13, 2026
f0a0166
small main README update
Junkiii Nov 13, 2026
c7748ff
reorganized tests slightly to better separate between core and implem…
Junkiii Nov 13, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/main.yml

This file was deleted.

34 changes: 33 additions & 1 deletion .github/workflows/mirror.yml
Original file line number Diff line number Diff line change
@@ -1 +1,33 @@
# TODO
# 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 }}
1 change: 0 additions & 1 deletion .github/workflows/sphinx-build.yaml

This file was deleted.

65 changes: 65 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -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
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ __pycache__/
.pytype/
.pyre/

############################################
# Coverage
############################################
.coverage
.coverage.*
coverage.xml
htmlcov/

############################################
# ML artifacts
############################################
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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.

Expand Down
10 changes: 6 additions & 4 deletions configs/mlp xyzspec.yaml → configs/mlp_xyzspec.yaml
Original file line number Diff line number Diff line change
@@ -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]
Expand All @@ -27,6 +28,7 @@ dataset:
encodings:
- encoding_type: identity


model:
# general:
model_type: mlp
Expand Down
4 changes: 2 additions & 2 deletions docs/source/user-guide/intro.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ XANESNET features
XANESNET development team
-------------------------

XANESNET is developed by `Hendrik Junkawitsch <https://github.com/HendrikJunkawitsch>`_,
XANESNET is developed by `Hendrik Junkawitsch <https://github.com/Junkiii>`_,
the `Penfold Group <http://penfoldgroup.co.uk>`_, and the `Research Software Engineering (RSE) team <https://rse.ncldata.dev/>`_ at `Newcastle University <https://ncl.ac.uk>`_.

| Project team:
| `Prof. Thomas Penfold <https://www.ncl.ac.uk/nes/people/profile/tompenfold.html>`_ (tom.penfold@newcastle.ac.uk)
| `Hendrik Junkawitsch <https://github.com/HendrikJunkawitsch>`_ (hendrik.junkawitsch@newcastle.ac.uk)
| `Hendrik Junkawitsch <https://github.com/Junkiii>`_ (hendrik.junkawitsch@newcastle.ac.uk)
| `Dr. Thomas Pope <https://www.ncl.ac.uk/nes/people/profile/thomaspope2.html>`_ (thomas.pope2@newcastle.ac.uk)
| `Dr. Conor Rankine <https://www.york.ac.uk/chemistry/people/conor-rankine/>`_ (conor.rankine@york.ac.uk)

Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -64,6 +64,7 @@ lightning = [
dev = [
"build>=1.2",
"pytest>=8",
"pytest-cov>=5",
]
docs = [
"Sphinx>=8",
Expand Down
52 changes: 47 additions & 5 deletions tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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.
60 changes: 53 additions & 7 deletions tests/dry_runs/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down
23 changes: 23 additions & 0 deletions tests/dry_runs/infer/test_mh_mlp.yaml
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading