diff --git a/.github/workflows/TestSuites.yaml b/.github/workflows/TestSuites.yaml index 7feafcc..46d74c1 100644 --- a/.github/workflows/TestSuites.yaml +++ b/.github/workflows/TestSuites.yaml @@ -125,6 +125,110 @@ jobs: - name: Build run: cmake --build AutoPasDM/build-ci --parallel 2 + - name: Build original md-flexible reference + if: matrix.config.name == 'GCC-Release-OMP-SingleSite' + run: | + CC=gcc CXX=g++ cmake -S AutoPas -B AutoPas/build-reference -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DAUTOPAS_BUILD_EXAMPLES=ON \ + -DAUTOPAS_BUILD_TESTS=OFF \ + -DAUTOPAS_BUILD_MD_LIBRARY=ON \ + -DAUTOPAS_BUILD_SPH_LIBRARY=ON \ + -DAUTOPAS_OPENMP=ON \ + -DAUTOPAS_ENABLE_ENERGY_MEASUREMENTS=OFF \ + -DAUTOPAS_INTERNODE_TUNING=ON \ + -DMD_FLEXIBLE_FUNCTOR_AUTOVEC=ON \ + -DMD_FLEXIBLE_MODE=SINGLESITE \ + -DMD_FLEXIBLE_USE_MPI=ON + cmake --build AutoPas/build-reference --target md-flexible --parallel 2 + + - name: Compare AutoPas and AutoPasDM simulations + if: matrix.config.name == 'GCC-Release-OMP-SingleSite' + run: | + python3 AutoPasDM/examples/md-flexible/tests/scripts/run_load_balancing_regression.py \ + --reference AutoPas/build-reference/examples/md-flexible/md-flexible \ + --distributed AutoPasDM/build-ci/examples/md-flexible/md-flexible \ + --config AutoPasDM/examples/md-flexible/tests/yamlTestFiles/autopasdm_load_balancing_compare.yaml \ + --ranks 8 + + - name: Compare 3D forces between AutoPas and AutoPasDM + if: matrix.config.name == 'GCC-Release-OMP-SingleSite' + run: | + python3 AutoPasDM/examples/md-flexible/tests/scripts/run_md_flexible_comparison.py \ + --reference AutoPas/build-reference/examples/md-flexible/md-flexible \ + --distributed AutoPasDM/build-ci/examples/md-flexible/md-flexible \ + --config AutoPasDM/examples/md-flexible/tests/yamlTestFiles/autopasdm_force_compare_3d.yaml \ + --ranks 8 + + - name: Compare dynamic simulations between AutoPas and AutoPasDM + if: matrix.config.name == 'GCC-Release-OMP-SingleSite' + run: | + python3 AutoPasDM/examples/md-flexible/tests/scripts/run_md_flexible_comparison.py \ + --reference AutoPas/build-reference/examples/md-flexible/md-flexible \ + --distributed AutoPasDM/build-ci/examples/md-flexible/md-flexible \ + --config AutoPasDM/examples/md-flexible/tests/yamlTestFiles/autopasdm_dynamic_compare.yaml \ + --ranks 8 + + - name: Compare thermostat between AutoPas and AutoPasDM + if: matrix.config.name == 'GCC-Release-OMP-SingleSite' + run: | + output_dir="${RUNNER_TEMP}/thermostat-comparison" + python3 AutoPasDM/examples/md-flexible/tests/scripts/run_md_flexible_comparison.py \ + --reference AutoPas/build-reference/examples/md-flexible/md-flexible \ + --distributed AutoPasDM/build-ci/examples/md-flexible/md-flexible \ + --config AutoPasDM/examples/md-flexible/tests/yamlTestFiles/autopasdm_thermostat_compare.yaml \ + --reference-ranks 1 \ + --distributed-ranks 4 \ + --keep-output "$output_dir" + python3 AutoPasDM/examples/md-flexible/tests/scripts/compare_vtk_thermostat.py \ + "$output_dir/reference" "$output_dir/distributed" + + - name: Check reflective boundaries and wall forces + if: matrix.config.name == 'GCC-Release-OMP-SingleSite' + run: | + set -euo pipefail + executable="${GITHUB_WORKSPACE}/AutoPasDM/build-ci/examples/md-flexible/md-flexible" + config="${GITHUB_WORKSPACE}/AutoPasDM/examples/md-flexible/tests/yamlTestFiles/autopasdm_reflective_compare.yaml" + output_dir="${RUNNER_TEMP}/reflective-comparison" + mkdir -p "$output_dir/np1" "$output_dir/np8" + mpirun -np 1 "$executable" --yaml-filename "$config" \ + --vtk-output-folder "$output_dir/np1" + mpirun -np 8 "$executable" --yaml-filename "$config" \ + --vtk-output-folder "$output_dir/np8" + python3 AutoPasDM/examples/md-flexible/tests/scripts/compare_vtk_forces.py \ + "$output_dir/np1" "$output_dir/np8" + python3 AutoPasDM/examples/md-flexible/tests/scripts/check_reflective_forces.py \ + "$output_dir/np8" + + - name: Build original multi-site md-flexible reference + if: matrix.config.name == 'GCC-Release-OMP-MultiSite' + run: | + CC=gcc CXX=g++ cmake -S AutoPas -B AutoPas/build-reference-multisite -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DAUTOPAS_BUILD_EXAMPLES=ON \ + -DAUTOPAS_BUILD_TESTS=OFF \ + -DAUTOPAS_BUILD_MD_LIBRARY=ON \ + -DAUTOPAS_BUILD_SPH_LIBRARY=ON \ + -DAUTOPAS_OPENMP=ON \ + -DAUTOPAS_ENABLE_ENERGY_MEASUREMENTS=OFF \ + -DAUTOPAS_INTERNODE_TUNING=ON \ + -DMD_FLEXIBLE_FUNCTOR_AUTOVEC=ON \ + -DMD_FLEXIBLE_FUNCTOR_AVX=OFF \ + -DMD_FLEXIBLE_FUNCTOR_HWY=OFF \ + -DMD_FLEXIBLE_FUNCTOR_SVE=OFF \ + -DMD_FLEXIBLE_MODE=MULTISITE \ + -DMD_FLEXIBLE_USE_MPI=ON + cmake --build AutoPas/build-reference-multisite --target md-flexible --parallel 2 + + - name: Compare multi-site simulations between AutoPas and AutoPasDM + if: matrix.config.name == 'GCC-Release-OMP-MultiSite' + run: | + python3 AutoPasDM/examples/md-flexible/tests/scripts/run_md_flexible_comparison.py \ + --reference AutoPas/build-reference-multisite/examples/md-flexible/md-flexible \ + --distributed AutoPasDM/build-ci/examples/md-flexible/md-flexible \ + --config AutoPasDM/examples/md-flexible/tests/yamlTestFiles/autopasdm_multisite_compare.yaml \ + --ranks 8 + - name: Run full CTest suite if: matrix.config.test_scope == 'full' run: | diff --git a/README.md b/README.md index 47c16fa..6a54400 100644 --- a/README.md +++ b/README.md @@ -135,10 +135,11 @@ ctest --test-dir build --output-on-failure ### md-flexible 3D force regression A small end-to-end regression input is available at -`examples/md-flexible/input/autopasdm_force_compare_3d.yaml`. It compares a single-rank -reference run with an eight-rank `2 x 2 x 2` decomposition and exercises internal +`examples/md-flexible/tests/yamlTestFiles/autopasdm_force_compare_3d.yaml`. It exercises internal face, edge, and corner interactions as well as periodic boundaries in all three -dimensions. +dimensions. The force output can be compared across AutoPasDM decompositions as shown +below. The same input is also used in CI to compare original md-flexible and AutoPasDM +with eight MPI ranks. From `build/examples/md-flexible`: @@ -147,25 +148,37 @@ rm -rf force_compare_3d/np1 force_compare_3d/np8 mkdir -p force_compare_3d/np1 force_compare_3d/np8 ./md-flexible \ - --yaml-filename input/autopasdm_force_compare_3d.yaml \ + --yaml-filename ../../../examples/md-flexible/tests/yamlTestFiles/autopasdm_force_compare_3d.yaml \ --vtk-output-folder force_compare_3d/np1 mpirun -np 8 ./md-flexible \ - --yaml-filename input/autopasdm_force_compare_3d.yaml \ + --yaml-filename ../../../examples/md-flexible/tests/yamlTestFiles/autopasdm_force_compare_3d.yaml \ --vtk-output-folder force_compare_3d/np8 -python3 scripts/compare_vtk_forces.py \ +python3 ../../../examples/md-flexible/tests/scripts/compare_vtk_forces.py \ force_compare_3d/np1 \ force_compare_3d/np8 ``` -The comparison should report the same owned-particle IDs and forces within the -configured tolerance. +The decomposition comparison should report the same owned-particle IDs and forces +within the configured tolerance. For an original-AutoPas-vs-AutoPasDM comparison, run +from the repository root after building both MPI-enabled md-flexible executables: + +```bash +python3 examples/md-flexible/tests/scripts/run_md_flexible_comparison.py \ + --reference /path/to/AutoPas/build/examples/md-flexible/md-flexible \ + --distributed /path/to/AutoPasDM/build/examples/md-flexible/md-flexible \ + --config examples/md-flexible/tests/yamlTestFiles/autopasdm_force_compare_3d.yaml \ + --ranks 8 +``` + +The comparison checks IDs, types, positions, velocities, and forces in the final +output, without requiring the same owner rank. ### md-flexible load-balancing regression -`examples/md-flexible/input/autopasdm_load_balancing_compare.yaml` and -`scripts/run_load_balancing_regression.py` compare the bundled AutoPasDM +`examples/md-flexible/tests/yamlTestFiles/autopasdm_load_balancing_compare.yaml` and +`examples/md-flexible/tests/scripts/run_load_balancing_regression.py` compare the bundled AutoPasDM integration against an MPI-enabled original md-flexible build. Both decompositions must adapt and the final global particle state is compared independently of the exact owner rank, because runtime-based work measurements can produce different adaptive @@ -174,17 +187,35 @@ split positions. For example: ```bash -python3 scripts/run_load_balancing_regression.py \ +python3 examples/md-flexible/tests/scripts/run_load_balancing_regression.py \ --reference /path/to/AutoPas/build/examples/md-flexible/md-flexible \ --distributed ./md-flexible \ - --config input/autopasdm_load_balancing_compare.yaml \ + --config examples/md-flexible/tests/yamlTestFiles/autopasdm_load_balancing_compare.yaml \ --ranks 8 ``` +The regression uses the general `run_md_flexible_comparison.py` runner and additionally +requires both load balancers to move at least one subdomain boundary. + +### md-flexible thermostat comparison + +CI compares the original one-rank thermostat run with a four-rank AutoPasDM run using +`examples/md-flexible/tests/yamlTestFiles/autopasdm_thermostat_compare.yaml`. It compares particle velocities and checks that +both results reach the expected global temperature. The runner accepts different rank +counts with `--reference-ranks` and `--distributed-ranks`. + +### md-flexible dynamic simulation comparison + +`examples/md-flexible/tests/yamlTestFiles/autopasdm_dynamic_compare.yaml` advances a small 3D system +for 100 steps with a non-zero time step. Three particles cross internal MPI boundaries +in x, y, and z, while another pair exercises Lennard-Jones force evaluation. CI runs +this input with eight ranks in both implementations and compares the final global +particle states by ID. + ### md-flexible reflective-boundary regression The single-site md-flexible example contains a reflective-wall regression input at -`examples/md-flexible/input/autopasdm_reflective_compare.yaml`. It places particles near +`examples/md-flexible/tests/yamlTestFiles/autopasdm_reflective_compare.yaml`. It places particles near all six global faces and two opposite corners. With sigma = epsilon = 1 and a wall distance of 0.5, the expected force component from each reflective wall is exactly 24. The same setup can be compared between one rank and an eight-rank `2 x 2 x 2` @@ -197,23 +228,37 @@ rm -rf reflective_compare/np1 reflective_compare/np8 mkdir -p reflective_compare/np1 reflective_compare/np8 ./md-flexible \ - --yaml-filename input/autopasdm_reflective_compare.yaml \ + --yaml-filename ../../../examples/md-flexible/tests/yamlTestFiles/autopasdm_reflective_compare.yaml \ --vtk-output-folder reflective_compare/np1 mpirun -np 8 ./md-flexible \ - --yaml-filename input/autopasdm_reflective_compare.yaml \ + --yaml-filename ../../../examples/md-flexible/tests/yamlTestFiles/autopasdm_reflective_compare.yaml \ --vtk-output-folder reflective_compare/np8 -python3 scripts/compare_vtk_forces.py \ +python3 ../../../examples/md-flexible/tests/scripts/compare_vtk_forces.py \ reflective_compare/np1 \ reflective_compare/np8 -python3 scripts/check_reflective_forces.py reflective_compare/np8 +python3 ../../../examples/md-flexible/tests/scripts/check_reflective_forces.py reflective_compare/np8 ``` The first script checks decomposition independence. The second checks the forces against the analytical values of the reflective regression setup. +The reflective Lennard-Jones wall force is an AutoPasDM application feature and is not +implemented by the original md-flexible reference. CI therefore checks this path within +AutoPasDM: it compares one-rank and eight-rank forces and checks the eight-rank result +against the analytical wall forces. + +### md-flexible multi-site comparison + +`examples/md-flexible/tests/yamlTestFiles/autopasdm_multisite_compare.yaml` contains two tri-site +molecules interacting across an internal rank corner. The short run exercises the +multi-site force calculation, torque generation, and rotational integration. CI builds +the original md-flexible reference in multi-site mode and compares the final molecular +state with an eight-rank AutoPasDM run, including quaternions, angular velocities, and +torques. + The test build can be disabled with `-DAUTOPASDM_BUILD_TESTS=OFF`. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for the current architecture, diff --git a/examples/md-flexible/CMakeLists.txt b/examples/md-flexible/CMakeLists.txt index b7a3327..1ec227a 100644 --- a/examples/md-flexible/CMakeLists.txt +++ b/examples/md-flexible/CMakeLists.txt @@ -225,7 +225,7 @@ if(AUTOPASDM_BUILD_TESTS) ${MPIEXEC_NUMPROC_FLAG} 2 ${MPIEXEC_PREFLAGS} $ - --yaml-filename "${CMAKE_CURRENT_SOURCE_DIR}/input/autopasdm_all_load_balancer.yaml" + --yaml-filename "${CMAKE_CURRENT_SOURCE_DIR}/tests/yamlTestFiles/autopasdm_all_load_balancer.yaml" ${MPIEXEC_POSTFLAGS} CONFIGURATIONS checkExamples ) @@ -249,7 +249,7 @@ if(AUTOPASDM_BUILD_TESTS) ${MPIEXEC_NUMPROC_FLAG} 2 ${MPIEXEC_PREFLAGS} $ - --yaml-filename "${CMAKE_CURRENT_SOURCE_DIR}/input/autopasdm_mpi_tuning.yaml" + --yaml-filename "${CMAKE_CURRENT_SOURCE_DIR}/tests/yamlTestFiles/autopasdm_mpi_tuning.yaml" ${MPIEXEC_POSTFLAGS} CONFIGURATIONS checkExamples ) @@ -278,7 +278,7 @@ if(AUTOPASDM_BUILD_TESTS) ${MPIEXEC_NUMPROC_FLAG} 2 ${MPIEXEC_PREFLAGS} $ - --yaml-filename "${CMAKE_CURRENT_SOURCE_DIR}/input/autopasdm_cli_checkpoint.yaml" + --yaml-filename "${CMAKE_CURRENT_SOURCE_DIR}/tests/yamlTestFiles/autopasdm_cli_checkpoint.yaml" --vtk-filename autopasdm-cli-checkpoint --vtk-output-folder "${MDFLEX_CHECKPOINT_TEST_OUTPUT_FOLDER}" --vtk-write-frequency 1 @@ -303,7 +303,7 @@ if(AUTOPASDM_BUILD_TESTS) ${MPIEXEC_NUMPROC_FLAG} 2 ${MPIEXEC_PREFLAGS} $ - --yaml-filename "${CMAKE_CURRENT_SOURCE_DIR}/input/autopasdm_cli_checkpoint_restart.yaml" + --yaml-filename "${CMAKE_CURRENT_SOURCE_DIR}/tests/yamlTestFiles/autopasdm_cli_checkpoint_restart.yaml" --checkpoint "${MDFLEX_CHECKPOINT_TEST_FILE}" --vtk-filename autopasdm-cli-checkpoint-restart --vtk-output-folder "${MDFLEX_CHECKPOINT_TEST_OUTPUT_FOLDER}" @@ -331,7 +331,7 @@ if(AUTOPASDM_BUILD_TESTS) ${MPIEXEC_NUMPROC_FLAG} 1 ${MPIEXEC_PREFLAGS} $ - --yaml-filename "${CMAKE_CURRENT_SOURCE_DIR}/input/autopasdm_cli_checkpoint_restart.yaml" + --yaml-filename "${CMAKE_CURRENT_SOURCE_DIR}/tests/yamlTestFiles/autopasdm_cli_checkpoint_restart.yaml" --checkpoint "${MDFLEX_CHECKPOINT_TEST_FILE}" --vtk-filename autopasdm-cli-checkpoint-restart-one-rank --vtk-output-folder "${MDFLEX_CHECKPOINT_TEST_OUTPUT_FOLDER}" diff --git a/examples/md-flexible/scripts/check_reflective_forces.py b/examples/md-flexible/tests/scripts/check_reflective_forces.py similarity index 100% rename from examples/md-flexible/scripts/check_reflective_forces.py rename to examples/md-flexible/tests/scripts/check_reflective_forces.py diff --git a/examples/md-flexible/scripts/compare_vtk_forces.py b/examples/md-flexible/tests/scripts/compare_vtk_forces.py similarity index 100% rename from examples/md-flexible/scripts/compare_vtk_forces.py rename to examples/md-flexible/tests/scripts/compare_vtk_forces.py diff --git a/examples/md-flexible/scripts/compare_vtk_thermostat.py b/examples/md-flexible/tests/scripts/compare_vtk_thermostat.py similarity index 100% rename from examples/md-flexible/scripts/compare_vtk_thermostat.py rename to examples/md-flexible/tests/scripts/compare_vtk_thermostat.py diff --git a/examples/md-flexible/scripts/run_load_balancing_regression.py b/examples/md-flexible/tests/scripts/run_load_balancing_regression.py similarity index 99% rename from examples/md-flexible/scripts/run_load_balancing_regression.py rename to examples/md-flexible/tests/scripts/run_load_balancing_regression.py index 078509f..4e45ce9 100755 --- a/examples/md-flexible/scripts/run_load_balancing_regression.py +++ b/examples/md-flexible/tests/scripts/run_load_balancing_regression.py @@ -9,10 +9,10 @@ 2. the final owned-particle state agrees by particle ID within tolerance. Example: - python3 scripts/run_load_balancing_regression.py \ + python3 tests/scripts/run_load_balancing_regression.py \ --reference /path/to/AutoPas/build/examples/md-flexible/md-flexible \ --distributed ./md-flexible \ - --config input/autopasdm_load_balancing_compare.yaml \ + --config tests/yamlTestFiles/autopasdm_load_balancing_compare.yaml \ --ranks 8 For SLURM, e.g. use: diff --git a/examples/md-flexible/tests/scripts/run_md_flexible_comparison.py b/examples/md-flexible/tests/scripts/run_md_flexible_comparison.py new file mode 100644 index 0000000..f0e0c42 --- /dev/null +++ b/examples/md-flexible/tests/scripts/run_md_flexible_comparison.py @@ -0,0 +1,391 @@ +#!/usr/bin/env python3 +"""Run the same md-flexible case with reference md-flexible and AutoPasDM. + +The comparison does not require identical particle owner ranks. Inverted Pressure +uses measured local computation times, so exact adaptive boundaries can differ +between implementations and runs. This regression checks that + +1. the final owned-particle state agrees by particle ID within tolerance, and +2. optionally, both runs actually move at least one subdomain boundary. + +Example: + python3 tests/scripts/run_md_flexible_comparison.py \ + --reference /path/to/AutoPas/build/examples/md-flexible/md-flexible \ + --distributed ./md-flexible \ + --config tests/yamlTestFiles/autopasdm_load_balancing_compare.yaml \ + --ranks 8 --require-load-balancing + +For SLURM, e.g. use: + --launcher 'srun -n {ranks}' +""" + +from __future__ import annotations + +import argparse +import glob +import math +import os +from pathlib import Path +import re +import shlex +import subprocess +import sys +import tempfile +import xml.etree.ElementTree as ET + + +PARTICLE_FILE_RE = re.compile(r"_Particles_(\d+)_(\d+)\.vtu$") +RANK_FILE_RE = re.compile(r"_Ranks_(\d+)_(\d+)\.vtu$") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--reference", required=True, type=Path, help="Original md-flexible executable") + parser.add_argument("--distributed", required=True, type=Path, help="AutoPasDM md-flexible executable") + parser.add_argument("--config", required=True, type=Path, help="YAML input shared by both runs") + parser.add_argument("--ranks", type=int, default=8, help="MPI ranks (default: 8)") + parser.add_argument("--reference-ranks", type=int, help="Override the reference MPI rank count") + parser.add_argument("--distributed-ranks", type=int, help="Override the AutoPasDM MPI rank count") + parser.add_argument( + "--require-load-balancing", + action="store_true", + help="require the decomposition boundaries to move in both runs", + ) + parser.add_argument( + "--launcher", + default="mpirun -np {ranks}", + help="MPI launcher command. {ranks} is replaced with --ranks (default: 'mpirun -np {ranks}')", + ) + parser.add_argument("--absolute-tolerance", type=float, default=1e-3) + parser.add_argument("--relative-tolerance", type=float, default=1e-4) + parser.add_argument("--boundary-move-tolerance", type=float, default=1e-6) + parser.add_argument( + "--keep-output", + type=Path, + help=( + "Keep both run directories below this directory instead of deleting temporary output. " + "The destination must be absent or empty; existing contents are never removed." + ), + ) + return parser.parse_args() + + +def absolute_existing_file(path: Path, description: str) -> Path: + path = path.expanduser().resolve() + if not path.is_file(): + raise RuntimeError(f"{description} does not exist: {path}") + return path + + +def launcher_command(template: str, ranks: int) -> list[str]: + if ranks <= 0: + raise RuntimeError("--ranks must be greater than zero") + return shlex.split(template.replace("{ranks}", str(ranks))) + + +def run_case(label: str, executable: Path, config: Path, run_directory: Path, launcher: list[str]) -> None: + run_directory.mkdir(parents=True, exist_ok=True) + command = [*launcher, str(executable), "--yaml-filename", str(config)] + log_file = run_directory / "run.log" + + print(f"Running {label}:") + print(" " + shlex.join(command)) + print(f" cwd: {run_directory}") + + with log_file.open("w", encoding="utf-8") as log: + result = subprocess.run(command, cwd=run_directory, stdout=log, stderr=subprocess.STDOUT, check=False) + + if result.returncode != 0: + tail = log_file.read_text(encoding="utf-8", errors="replace").splitlines()[-40:] + raise RuntimeError( + f"{label} failed with exit code {result.returncode}. Last log lines:\n" + "\n".join(tail) + ) + + +def data_array(piece: ET.Element, name: str) -> list[str]: + for element in piece.iter("DataArray"): + if element.attrib.get("Name") == name: + return (element.text or "").split() + raise RuntimeError(f'DataArray "{name}" not found') + + +def optional_data_array(piece: ET.Element, name: str) -> list[str] | None: + for element in piece.iter("DataArray"): + if element.attrib.get("Name") == name: + return (element.text or "").split() + return None + + +def point_coordinates(piece: ET.Element) -> list[float]: + points = next(piece.iter("Points"), None) + if points is None: + raise RuntimeError("Points element not found") + array = next(points.iter("DataArray"), None) + if array is None: + raise RuntimeError("Points DataArray not found") + return [float(value) for value in (array.text or "").split()] + + +def matching_files(root: Path, pattern: re.Pattern[str]) -> list[tuple[int, int, Path]]: + matches: list[tuple[int, int, Path]] = [] + for filename in glob.glob(str(root / "**" / "*.vtu"), recursive=True): + match = pattern.search(filename) + if match: + rank = int(match.group(1)) + iteration = int(match.group(2)) + matches.append((iteration, rank, Path(filename))) + if not matches: + raise RuntimeError(f"No matching VTK files found below {root}") + return matches + + +def first_and_final_iterations(root: Path, pattern: re.Pattern[str]) -> tuple[int, int]: + iterations = [iteration for iteration, _, _ in matching_files(root, pattern)] + return min(iterations), max(iterations) + + +def files_at_iteration(root: Path, pattern: re.Pattern[str], iteration: int) -> list[tuple[int, Path]]: + return sorted( + (rank, filename) + for file_iteration, rank, filename in matching_files(root, pattern) + if file_iteration == iteration + ) + + +def read_particle_state(root: Path) -> tuple[int, dict[int, dict[str, object]]]: + _, final_iteration = first_and_final_iterations(root, PARTICLE_FILE_RE) + result: dict[int, dict[str, object]] = {} + + for rank, filename in files_at_iteration(root, PARTICLE_FILE_RE, final_iteration): + tree = ET.parse(filename) + piece = next(tree.getroot().iter("Piece")) + + ids = [int(value) for value in data_array(piece, "ids")] + type_ids = [int(value) for value in data_array(piece, "typeIds")] + if len(type_ids) != len(ids): + raise RuntimeError(f"Type-ID/ID length mismatch in {filename}") + + fields: dict[str, list[float]] = {"position": point_coordinates(piece)} + required_vector_arrays = { + "velocity": ("velocities", 3), + "force": ("forces", 3), + } + optional_vector_arrays = { + "quaternion": ("quaternions", 4), + "angularVelocity": ("angularVelocities", 3), + "torque": ("torques", 3), + } + for field, (array_name, _) in required_vector_arrays.items(): + fields[field] = [float(value) for value in data_array(piece, array_name)] + for field, (array_name, _) in optional_vector_arrays.items(): + raw_values = optional_data_array(piece, array_name) + if raw_values is not None: + fields[field] = [float(value) for value in raw_values] + + for field, values in fields.items(): + components = 4 if field == "quaternion" else 3 + if len(values) != components * len(ids): + raise RuntimeError(f"{field}/ID length mismatch in {filename}") + + for index, particle_id in enumerate(ids): + if particle_id in result: + raise RuntimeError(f"Particle ID {particle_id} occurs more than once in final owned output") + particle_state: dict[str, object] = {"rank": rank, "type": type_ids[index]} + for field, values in fields.items(): + components = 4 if field == "quaternion" else 3 + begin = components * index + particle_state[field] = tuple(values[begin : begin + components]) + result[particle_id] = particle_state + + return final_iteration, result + + +def read_boxes(root: Path, iteration: int) -> dict[int, tuple[tuple[float, ...], tuple[float, ...]]]: + boxes: dict[int, tuple[tuple[float, ...], tuple[float, ...]]] = {} + for rank, filename in files_at_iteration(root, RANK_FILE_RE, iteration): + tree = ET.parse(filename) + piece = next(tree.getroot().iter("Piece")) + coordinates = point_coordinates(piece) + if len(coordinates) != 24: + raise RuntimeError(f"Expected 8 three-dimensional rank-box points in {filename}") + points = [coordinates[index : index + 3] for index in range(0, len(coordinates), 3)] + box_min = tuple(min(point[d] for point in points) for d in range(3)) + box_max = tuple(max(point[d] for point in points) for d in range(3)) + boxes[rank] = (box_min, box_max) + return boxes + + +def maximum_boundary_movement(root: Path) -> tuple[int, int, float]: + initial_iteration, final_iteration = first_and_final_iterations(root, RANK_FILE_RE) + initial_boxes = read_boxes(root, initial_iteration) + final_boxes = read_boxes(root, final_iteration) + + if set(initial_boxes) != set(final_boxes): + raise RuntimeError("Rank IDs differ between initial and final domain output") + + movement = 0.0 + for rank in initial_boxes: + for initial, final in zip(initial_boxes[rank][0] + initial_boxes[rank][1], final_boxes[rank][0] + final_boxes[rank][1]): + movement = max(movement, abs(initial - final)) + return initial_iteration, final_iteration, movement + + +def close(a: float, b: float, absolute_tolerance: float, relative_tolerance: float) -> bool: + return math.isclose(a, b, abs_tol=absolute_tolerance, rel_tol=relative_tolerance) + + +def compare_states( + reference: dict[int, dict[str, object]], + distributed: dict[int, dict[str, object]], + absolute_tolerance: float, + relative_tolerance: float, +) -> tuple[bool, int, float]: + reference_ids = set(reference) + distributed_ids = set(distributed) + if reference_ids != distributed_ids: + print("FAIL: final owned particle IDs differ.") + print(" only in reference :", sorted(reference_ids - distributed_ids)) + print(" only in distributed:", sorted(distributed_ids - reference_ids)) + return False, 0, math.inf + + ownership_changes = 0 + maximum_difference = 0.0 + failures: list[str] = [] + + for particle_id in sorted(reference_ids): + expected = reference[particle_id] + actual = distributed[particle_id] + + if expected["rank"] != actual["rank"]: + ownership_changes += 1 + if expected["type"] != actual["type"]: + failures.append(f"id={particle_id}: type {expected['type']} != {actual['type']}") + + for field in ("position", "velocity", "force", "quaternion", "angularVelocity", "torque"): + if (field in expected) != (field in actual): + failures.append(f"id={particle_id}: {field} is present in only one output") + continue + if field not in expected: + continue + expected_vector = expected[field] + actual_vector = actual[field] + if field == "quaternion": + direct_difference = max(abs(a - b) for a, b in zip(expected_vector, actual_vector)) + negated_difference = max(abs(a + b) for a, b in zip(expected_vector, actual_vector)) + if negated_difference < direct_difference: + actual_vector = tuple(-component for component in actual_vector) + for component, (a, b) in enumerate(zip(expected_vector, actual_vector)): + maximum_difference = max(maximum_difference, abs(a - b)) + if not close(a, b, absolute_tolerance, relative_tolerance): + failures.append( + f"id={particle_id}: {field}[{component}] reference={a:.12g} distributed={b:.12g}" + ) + + if failures: + print("FAIL: final particle states differ beyond tolerance.") + for failure in failures[:20]: + print(" " + failure) + if len(failures) > 20: + print(f" ... and {len(failures) - 20} more") + return False, ownership_changes, maximum_difference + + return True, ownership_changes, maximum_difference + + +def main() -> int: + args = parse_args() + + try: + reference = absolute_existing_file(args.reference, "Reference executable") + distributed = absolute_existing_file(args.distributed, "Distributed executable") + config = absolute_existing_file(args.config, "Configuration") + reference_ranks = args.reference_ranks if args.reference_ranks is not None else args.ranks + distributed_ranks = args.distributed_ranks if args.distributed_ranks is not None else args.ranks + reference_launcher = launcher_command(args.launcher, reference_ranks) + distributed_launcher = launcher_command(args.launcher, distributed_ranks) + + if args.keep_output: + work_root = args.keep_output.expanduser().resolve() + if work_root.exists(): + if not work_root.is_dir(): + raise RuntimeError(f"Output destination exists and is not a directory: {work_root}") + if next(work_root.iterdir(), None) is not None: + raise RuntimeError(f"Output destination is not empty; refusing to overwrite: {work_root}") + else: + work_root.mkdir(parents=True) + cleanup = None + else: + cleanup = tempfile.TemporaryDirectory(prefix="autopasdm_md_flexible_comparison_") + work_root = Path(cleanup.name) + + reference_root = work_root / "reference" + distributed_root = work_root / "distributed" + + run_case("reference md-flexible", reference, config, reference_root, reference_launcher) + run_case("AutoPasDM md-flexible", distributed, config, distributed_root, distributed_launcher) + + boundaries_ok = True + if args.require_load_balancing: + ref_initial, ref_final, ref_movement = maximum_boundary_movement(reference_root) + autopasdm_initial, autopasdm_final, autopasdm_movement = maximum_boundary_movement(distributed_root) + + print("\nAdaptive-domain check:") + print(f" reference iterations {ref_initial}->{ref_final}, max boundary movement {ref_movement:.12g}") + print(f" distributed iterations {autopasdm_initial}->{autopasdm_final}, max boundary movement {autopasdm_movement:.12g}") + + if ref_movement <= args.boundary_move_tolerance: + print("FAIL: reference md-flexible did not measurably change its decomposition.") + boundaries_ok = False + if autopasdm_movement <= args.boundary_move_tolerance: + print("FAIL: AutoPasDM did not measurably change its decomposition.") + boundaries_ok = False + + ref_iteration, ref_particles = read_particle_state(reference_root) + autopasdm_iteration, autopasdm_particles = read_particle_state(distributed_root) + + print("\nFinal-state comparison:") + print(f" reference final iteration : {ref_iteration}") + print(f" distributed final iteration : {autopasdm_iteration}") + print(f" reference owned particles : {len(ref_particles)}") + print(f" distributed owned particles : {len(autopasdm_particles)}") + + if ref_iteration != autopasdm_iteration: + print("FAIL: final iteration numbers differ; refusing to compare particle states.") + states_ok = False + ownership_changes = 0 + maximum_difference = math.inf + else: + states_ok, ownership_changes, maximum_difference = compare_states( + ref_particles, + autopasdm_particles, + args.absolute_tolerance, + args.relative_tolerance, + ) + print(f" particles owned by different ranks: {ownership_changes} (diagnostic only)") + print(f" maximum absolute component diff : {maximum_difference:.12g}") + print(f" absolute tolerance : {args.absolute_tolerance:.12g}") + print(f" relative tolerance : {args.relative_tolerance:.12g}") + + if boundaries_ok and states_ok: + if args.require_load_balancing: + print("\nPASS: both decompositions adapt and the final particle state agrees within tolerance.") + else: + print("\nPASS: the final particle state agrees within tolerance.") + result = 0 + else: + print("\nFAIL: md-flexible comparison failed.") + result = 1 + + if args.keep_output: + print(f"Output kept in: {work_root}") + if cleanup is not None: + cleanup.cleanup() + return result + + except (OSError, RuntimeError, subprocess.SubprocessError, ET.ParseError) as error: + print(f"ERROR: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/md-flexible/input/autopasdm_all_load_balancer.yaml b/examples/md-flexible/tests/yamlTestFiles/autopasdm_all_load_balancer.yaml similarity index 100% rename from examples/md-flexible/input/autopasdm_all_load_balancer.yaml rename to examples/md-flexible/tests/yamlTestFiles/autopasdm_all_load_balancer.yaml diff --git a/examples/md-flexible/input/autopasdm_cli_checkpoint.yaml b/examples/md-flexible/tests/yamlTestFiles/autopasdm_cli_checkpoint.yaml similarity index 100% rename from examples/md-flexible/input/autopasdm_cli_checkpoint.yaml rename to examples/md-flexible/tests/yamlTestFiles/autopasdm_cli_checkpoint.yaml diff --git a/examples/md-flexible/input/autopasdm_cli_checkpoint_restart.yaml b/examples/md-flexible/tests/yamlTestFiles/autopasdm_cli_checkpoint_restart.yaml similarity index 100% rename from examples/md-flexible/input/autopasdm_cli_checkpoint_restart.yaml rename to examples/md-flexible/tests/yamlTestFiles/autopasdm_cli_checkpoint_restart.yaml diff --git a/examples/md-flexible/tests/yamlTestFiles/autopasdm_dynamic_compare.yaml b/examples/md-flexible/tests/yamlTestFiles/autopasdm_dynamic_compare.yaml new file mode 100644 index 0000000..a9a3abe --- /dev/null +++ b/examples/md-flexible/tests/yamlTestFiles/autopasdm_dynamic_compare.yaml @@ -0,0 +1,78 @@ +# Short dynamic AutoPas-vs-AutoPasDM regression. +# +# Run both implementations with 8 MPI ranks on a 2 x 2 x 2 process grid. +# Three particles start just below an internal rank boundary and move across +# the x, y, and z boundaries. A separate pair exercises LJ force evaluation +# while the simulation advances with a non-zero time step. + +container: [DirectSum] +traversal: [ds_sequential] +data-layout: [AoS] +newton3: [enabled] +functor: lennard-jones + +cutoff: 1.5 +verlet-skin-radius: 0.0 +tuning-strategies: [] +tuning-phases: 0 + +box-min: [0.0, 0.0, 0.0] +box-max: [8.0, 8.0, 8.0] + +deltaT: 0.002 +iterations: 100 + +boundary-type: [periodic, periodic, periodic] +subdivide-dimension: [true, true, true] +load-balancer: None + +vtk-filename: autoPasDMDynamicCompare +vtk-write-frequency: 100 +no-progress-bar: true +no-end-config: true + +Sites: + 0: + epsilon: 1.0 + sigma: 1.0 + mass: 1.0 + +Objects: + CubeGrid: + # Crosses the internal x boundary at x = 4. + 0: + particles-per-dimension: [1, 1, 1] + particle-spacing: 0.2 + bottomLeftCorner: [3.95, 1.0, 1.0] + velocity: [0.5, 0.0, 0.0] + particle-type-id: 0 + + # Crosses the internal y boundary at y = 4. + 1: + particles-per-dimension: [1, 1, 1] + particle-spacing: 0.2 + bottomLeftCorner: [1.0, 3.95, 6.5] + velocity: [0.0, 0.5, 0.0] + particle-type-id: 0 + + # Crosses the internal z boundary at z = 4. + 2: + particles-per-dimension: [1, 1, 1] + particle-spacing: 0.2 + bottomLeftCorner: [6.5, 1.0, 3.95] + velocity: [0.0, 0.0, 0.5] + particle-type-id: 0 + + # Interacting LJ pair away from the internal boundaries. + 3: + particles-per-dimension: [1, 1, 1] + particle-spacing: 0.2 + bottomLeftCorner: [1.0, 6.0, 1.0] + velocity: [0.0, 0.0, 0.0] + particle-type-id: 0 + 4: + particles-per-dimension: [1, 1, 1] + particle-spacing: 0.2 + bottomLeftCorner: [2.2, 6.0, 1.0] + velocity: [0.0, 0.0, 0.0] + particle-type-id: 0 diff --git a/examples/md-flexible/input/autopasdm_force_compare.yaml b/examples/md-flexible/tests/yamlTestFiles/autopasdm_force_compare.yaml similarity index 100% rename from examples/md-flexible/input/autopasdm_force_compare.yaml rename to examples/md-flexible/tests/yamlTestFiles/autopasdm_force_compare.yaml diff --git a/examples/md-flexible/input/autopasdm_force_compare_3d.yaml b/examples/md-flexible/tests/yamlTestFiles/autopasdm_force_compare_3d.yaml similarity index 96% rename from examples/md-flexible/input/autopasdm_force_compare_3d.yaml rename to examples/md-flexible/tests/yamlTestFiles/autopasdm_force_compare_3d.yaml index 8b0ad11..7aef48c 100644 --- a/examples/md-flexible/input/autopasdm_force_compare_3d.yaml +++ b/examples/md-flexible/tests/yamlTestFiles/autopasdm_force_compare_3d.yaml @@ -13,7 +13,8 @@ # # particle-spacing is intentionally small because every CubeGrid contains only # one particle. This prevents md-flexible from enlarging the explicitly chosen -# [0, 8]^3 periodic simulation box. +# [0, 8]^3 periodic simulation box. deltaT is tiny but non-zero: original +# md-flexible skips MPI migration and halo exchange when deltaT is exactly zero. container: [DirectSum] traversal: [ds_sequential] @@ -29,7 +30,7 @@ tuning-phases: 0 box-min: [0.0, 0.0, 0.0] box-max: [8.0, 8.0, 8.0] -deltaT: 0.0 +deltaT: 1.0e-12 iterations: 1 boundary-type: [periodic, periodic, periodic] diff --git a/examples/md-flexible/input/autopasdm_load_balancing_compare.yaml b/examples/md-flexible/tests/yamlTestFiles/autopasdm_load_balancing_compare.yaml similarity index 98% rename from examples/md-flexible/input/autopasdm_load_balancing_compare.yaml rename to examples/md-flexible/tests/yamlTestFiles/autopasdm_load_balancing_compare.yaml index e70526a..2929178 100644 --- a/examples/md-flexible/input/autopasdm_load_balancing_compare.yaml +++ b/examples/md-flexible/tests/yamlTestFiles/autopasdm_load_balancing_compare.yaml @@ -1,6 +1,6 @@ # Adaptive 3D regression shared by original md-flexible and AutoPasDM. # -# Run both executables with 8 MPI ranks via scripts/run_load_balancing_regression.py. +# Run both executables with 8 MPI ranks via tests/scripts/run_load_balancing_regression.py. # The deliberately dense lower-octant block makes the initial 2 x 2 x 2 grid # strongly imbalanced, so Inverted Pressure should move at least one boundary. # diff --git a/examples/md-flexible/input/autopasdm_mpi_tuning.yaml b/examples/md-flexible/tests/yamlTestFiles/autopasdm_mpi_tuning.yaml similarity index 100% rename from examples/md-flexible/input/autopasdm_mpi_tuning.yaml rename to examples/md-flexible/tests/yamlTestFiles/autopasdm_mpi_tuning.yaml diff --git a/examples/md-flexible/tests/yamlTestFiles/autopasdm_multisite_compare.yaml b/examples/md-flexible/tests/yamlTestFiles/autopasdm_multisite_compare.yaml new file mode 100644 index 0000000..0496f4e --- /dev/null +++ b/examples/md-flexible/tests/yamlTestFiles/autopasdm_multisite_compare.yaml @@ -0,0 +1,58 @@ +# Multi-site AutoPas-vs-AutoPasDM regression. +# +# Two three-site molecules interact across the internal x/y rank corner in an +# eight-rank 2 x 2 x 2 decomposition. The off-center site forces generate +# torques, so the run exercises translational and rotational integration. + +container: [DirectSum] +traversal: [ds_sequential] +data-layout: [AoS] +newton3: [enabled] +functor: lennard-jones + +cutoff: 2.0 +verlet-skin-radius: 0.0 +tuning-strategies: [] +tuning-phases: 0 + +box-min: [0.0, 0.0, 0.0] +box-max: [8.0, 8.0, 8.0] + +deltaT: 0.001 +iterations: 20 + +boundary-type: [periodic, periodic, periodic] +subdivide-dimension: [true, true, true] +load-balancer: None + +vtk-filename: autoPasDMMultisiteCompare +vtk-write-frequency: 20 +no-progress-bar: true +no-end-config: true + +Sites: + 0: + epsilon: 1.0 + sigma: 0.6 + mass: 1.0 + +Molecules: + 0: + site-types: [0, 0, 0] + relative-site-positions: [[0.4, 0.0, 0.0], [-0.2, 0.3464101615, 0.0], [-0.2, -0.3464101615, 0.0]] + moment-of-inertia: [0.24, 0.24, 0.48] + +Objects: + CubeGrid: + 0: + particles-per-dimension: [1, 1, 1] + particle-spacing: 0.2 + bottomLeftCorner: [3.4, 3.4, 3.5] + velocity: [0.0, 0.0, 0.0] + particle-type-id: 0 + 1: + particles-per-dimension: [1, 1, 1] + particle-spacing: 0.2 + bottomLeftCorner: [4.6, 4.6, 3.5] + velocity: [0.0, 0.0, 0.0] + particle-type-id: 0 diff --git a/examples/md-flexible/input/autopasdm_reflective_compare.yaml b/examples/md-flexible/tests/yamlTestFiles/autopasdm_reflective_compare.yaml similarity index 100% rename from examples/md-flexible/input/autopasdm_reflective_compare.yaml rename to examples/md-flexible/tests/yamlTestFiles/autopasdm_reflective_compare.yaml diff --git a/examples/md-flexible/input/autopasdm_thermostat_compare.yaml b/examples/md-flexible/tests/yamlTestFiles/autopasdm_thermostat_compare.yaml similarity index 98% rename from examples/md-flexible/input/autopasdm_thermostat_compare.yaml rename to examples/md-flexible/tests/yamlTestFiles/autopasdm_thermostat_compare.yaml index a31b748..310ccd5 100644 --- a/examples/md-flexible/input/autopasdm_thermostat_compare.yaml +++ b/examples/md-flexible/tests/yamlTestFiles/autopasdm_thermostat_compare.yaml @@ -29,7 +29,7 @@ box-max: [8.6, 8.0, 8.0] deltaT: 0.000001 iterations: 1 -boundary-type: [periodic, none, none] +boundary-type: [none, none, none] subdivide-dimension: [true, false, false] load-balancer: None