Skip to content

Commit

Permalink
Continue process of generalisation
Browse files Browse the repository at this point in the history
  • Loading branch information
oerc0122 committed Feb 27, 2025
1 parent 53476e2 commit 7e9f5c5
Show file tree
Hide file tree
Showing 9 changed files with 235 additions and 261 deletions.
27 changes: 0 additions & 27 deletions MDANSE/Tests/CommonFunctions/compare_mdt.py

This file was deleted.

Empty file.
47 changes: 47 additions & 0 deletions MDANSE/Tests/CommonFunctions/test_helpers/compare_mdt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import numpy as np
from pathlib import Path
import h5py
from typing import Sequence

def compare_mdt(result_path: Path, benchmark_path: Path,
comparison_keys: Sequence[str], *,
startswith=False, normalised=False) -> None:
"""
Compare two h5py files by the keys given in comparison_keys.
Parameters
----------
result_path : Path
Path to output file from test run.
benchmark_path : Path
Path to benchmark results.
comparison_keys : Sequence[str]
List of keys to be present in outputs to compare.
startswith : bool
``comparison_keys`` instead define a prefix of keys in ``result`` to check.
normalised : bool
Whether data should be normalised.
"""

with h5py.File(result_path) as result, h5py.File(benchmark_path) as benchmark:

if startswith:
keys = (key for key in result.keys() if key.startswith(comparison_keys))
else:
keys = comparison_keys

for key in keys:
if isinstance(key, (tuple, list)):
key, subset = key
else:
subset = slice(None)

if normalised:
np.testing.assert_array_almost_equal(
result[f"/{key}"] * result[f"/{key}"].attrs["scaling_factor"],
benchmark[f"/{key}"][subset],
)
else:
np.testing.assert_array_almost_equal(
result[f"/{key}"], benchmark[f"/{key}"][subset],
)
38 changes: 38 additions & 0 deletions MDANSE/Tests/CommonFunctions/test_helpers/get_deep_attr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from typing import Any

def get_deep_attr(obj: Any, key: str) -> Any:
"""Get attribute from nested objects.
Parameters
----------
obj : Any
Object to get elements from.
key : str
"." separated string indexing into object.
"[x]" and "(x, y)" elements are evaluated.
Returns
-------
Any
Element at path given by key.
"""

parts = key.split(".")

new = obj
for part in parts:
part, *method = part.split("(", 1)
part, *getter = part.split("[", 1)
new = getattr(new, part)
if method:
args = method[0].strip("()")
if args:
args = args.split(",")

new = new(*map(eval, args))
if getter:
args = getter[0].strip("[]")
new = new[eval(args)]

return new
7 changes: 7 additions & 0 deletions MDANSE/Tests/CommonFunctions/test_helpers/paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from pathlib import Path

ROOT_DIR = Path(__file__).parents[2]
UNIT_TEST_DIR = ROOT_DIR / "UnitTests"
CONV_DIR = UNIT_TEST_DIR / "Converted"
DATA_DIR = UNIT_TEST_DIR / "Data"
RESULTS_DIR = UNIT_TEST_DIR / "Results"
52 changes: 18 additions & 34 deletions MDANSE/Tests/UnitTests/Analysis/test_average_structure.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,30 @@
import tempfile
import os
from os import path
import pytest

from MDANSE.Framework.InputData.HDFTrajectoryInputData import HDFTrajectoryInputData
from MDANSE.Framework.InputData.HDFTrajectoryInputData import \
HDFTrajectoryInputData
from MDANSE.Framework.Jobs.IJob import IJob
from test_helpers.paths import CONV_DIR


short_traj = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"..",
"Converted",
"short_trajectory_after_changes.mdt",
)
short_traj = CONV_DIR / "short_trajectory_after_changes.mdt"


@pytest.fixture(scope="module")
def trajectory():
trajectory = HDFTrajectoryInputData(short_traj)
yield trajectory


units = ["Angstrom", "Bohr", "nm", "pm"]
formats = ["vasp", "xyz", "turbomole", "abinit-in"]
inputs = []
for u in units:
for f in formats:
inputs.append((u, f))


@pytest.mark.parametrize("output_unit,output_format", inputs)
def test_avg_structure(trajectory, output_unit, output_format):
temp_name = tempfile.mktemp()
parameters = {}
parameters["frames"] = (0, 10, 1)
parameters["output_units"] = output_unit
parameters["fold"] = True
parameters["output_files"] = (temp_name, output_format, "INFO")
parameters["running_mode"] = ("single-core",)
parameters["trajectory"] = short_traj
@pytest.mark.parametrize("output_unit", ["Angstrom", "Bohr", "nm", "pm"])
@pytest.mark.parametrize("output_format", ["vasp", "xyz", "turbomole", "abinit-in"])
def test_avg_structure(tmp_path, trajectory, output_unit, output_format):
temp_name = tmp_path / "output"
parameters = {
"frames": (0, 10, 1),
"output_units": output_unit,
"fold": True,
"output_files": (temp_name, output_format, "INFO"),
"running_mode": ("single-core",),
"trajectory": short_traj,
}
temp = IJob.create("AverageStructure")
temp.run(parameters, status=True)
assert path.exists(temp_name)
assert path.isfile(temp_name)
os.remove(temp_name)

assert temp_name.is_file()
Loading

0 comments on commit 7e9f5c5

Please sign in to comment.