From 24876936665b5b72639884ab90c30872ed39ea31 Mon Sep 17 00:00:00 2001 From: shimwell <8583900+shimwell@users.noreply.github.com> Date: Tue, 20 Oct 2026 11:10:35 +0200 Subject: [PATCH 1/4] Unify JEFF ACE conversion for 3.2, 3.3, and 4.0 --- .github/workflows/test_package.yml | 1 + README.md | 50 ++- pyproject.toml | 1 + src/openmc_data/convert/convert_jeff.py | 311 +++++++++++++++ src/openmc_data/convert/convert_jeff32.py | 263 +------------ src/openmc_data/convert/convert_jeff33.py | 225 +---------- src/openmc_data/urls.py | 107 ++++-- src/openmc_data/utils.py | 26 +- tests/test_convert_jeff.py | 449 ++++++++++++++++++++++ tests/test_utils.py | 114 ++++++ 10 files changed, 1020 insertions(+), 527 deletions(-) create mode 100644 src/openmc_data/convert/convert_jeff.py create mode 100644 tests/test_convert_jeff.py diff --git a/.github/workflows/test_package.yml b/.github/workflows/test_package.yml index 9fbbfa5..f7a02c5 100644 --- a/.github/workflows/test_package.yml +++ b/.github/workflows/test_package.yml @@ -51,6 +51,7 @@ jobs: - name: Test convert scripts exist run: | convert_fendl --help + convert_jeff --help convert_jeff32 --help convert_jeff33 --help convert_lib80x --help diff --git a/README.md b/README.md index 609d98d..56007df 100644 --- a/README.md +++ b/README.md @@ -89,10 +89,56 @@ A few categories of scripts are available: |convert_endf | ENDF/B | VII.1 | NNDC | |convert_lib80x | ENDF/B | VIII.0 | LANL | |convert_fendl | FENDL | 3.2c
3.2b
3.2a
3.2
3.1d
3.1a
3.1
3.0
2.1 | -|convert_jeff32 | JEFF | 3.2 | -|convert_jeff33 | JEFF | 3.3 | +|convert_jeff | JEFF | 3.2
3.3
4.0 (default) | OECD/NEA | |convert_tendl | TENDL | 2015
2017
2019
2021 | +#### JEFF ACE conversion + +`convert_jeff --help` describes the unified neutron and thermal ACE-to-HDF5 +converter. Use `-r/--release` to select a release and `-t/--temperatures` to +select neutron archive temperatures. With no temperature option, all available +neutron temperatures for that release are processed: + +| Release | Neutron archive temperatures (K) | +| --- | --- | +| 3.2 | 293, 300, 400, 500, 600, 700, 800, 900, 1000, 1200, 1500, 1800 | +| 3.3 | 293, 600, 900, 1200, 1500, 1800 | +| 4.0 | 0.1, 293, 300, 600, 900, 1200, 1500, 1800 | + +For example, `convert_jeff -r 3.3 -t 600 900 --destination jeff-hot` does not +require 293 K neutron data. The 4.0 archive labelled 293 contains 293.6 K data; +select it with `-t 293`, not `-t 293.6`. Thermal tables have independent +temperature grids, so **all thermal temperatures** are retained regardless of +the neutron selection. Tables are grouped by ACE material identity, not filename +suffix; the UO2 temperature pairs separated by 1 K are retained. + +**JEFF-4.0 thermal coverage is the public selected subset: 12 cases and 316 +tables**, not the complete JEFF-4.0 TSL library. It covers Be, D in D2O, graphite, +H in CH2 and H2O, H in ZrH/ZrH1.5/ZrH2, O and U in UO2, and Zr in ZrH1.5/ZrH2. +The converter checks that subset's case and table counts. Unrecognized OpenMC +thermal aliases retain their ACE identity with a `c_` prefix and a warning, +rather than being guessed as another material. + +HDF5 files and the cross-section XML registry are written **directly** into +`--destination` (default: `jeff--hdf5`). Existing target files and +colliding material/temperature names are rejected. Outputs are staged until +conversion succeeds. Downloads and extracted ACE files are cached in +`jeff--download` and `jeff--ace` under the working directory. +`--no-download --no-extract` reuses those caches, while still filtering neutron +temperatures. Each discovered neutron nuclide must have every requested +temperature; empty or inconsistent input fails. The known 20 thermal material +file groups are also required for 3.3. Cached files alone cannot prove +that a nuclide absent at every temperature was originally present in an archive. +`--cleanup` removes both cache directories only after success; the default +`--no-cleanup` preserves them. ACE files are never edited to correct metastables. +Full downloads require multiple GB; files are streamed and conversion keeps only +one material's multi-temperature data in memory at a time. + +`convert_jeff32` and `convert_jeff33` remain thin compatibility aliases. They +retain their original releases, accepted `-r` values, default destinations, and +HDF5 defaults (`latest` for 3.2, `earliest` for 3.3). The unified command defaults +to release 4.0 and `--libver latest`; `--libver earliest` is also supported. + ### Generate cross sections | Script name | Library | Release | Processed by | diff --git a/pyproject.toml b/pyproject.toml index 942fab3..6bfe6c1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -61,6 +61,7 @@ include-package-data = false [project.scripts] convert_fendl = "openmc_data.convert.convert_fendl:main" +convert_jeff = "openmc_data.convert.convert_jeff:main" convert_jeff32 = "openmc_data.convert.convert_jeff32:main" convert_jeff33 = "openmc_data.convert.convert_jeff33:main" convert_lib80x = "openmc_data.convert.convert_lib80x:main" diff --git a/src/openmc_data/convert/convert_jeff.py b/src/openmc_data/convert/convert_jeff.py new file mode 100644 index 0000000..00b4c93 --- /dev/null +++ b/src/openmc_data/convert/convert_jeff.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +"""Convert OECD/NEA JEFF neutron and thermal ACE data to OpenMC HDF5. + +Temperature selections apply to neutron archives. Thermal tables use their own +temperature grids and are all retained. JEFF-4.0 supplies only the public +selected TSL subset (12 cases, 316 tables), not the complete TSL evaluation set. +""" + +import argparse +from collections import defaultdict +from dataclasses import dataclass +import math +from pathlib import Path +import re +import shutil +from tempfile import TemporaryDirectory +import warnings + +from openmc_data import ProgressTracker, all_release_details, download, extract + + +RELEASES = ("3.2", "3.3", "4.0") + + +@dataclass(frozen=True) +class TableSource: + """A lightweight index entry, never an in-memory ACE data array.""" + + path: Path + table_name: str + temperature: float + name: str + zaid: int = None + + +def _header(path): + """Read only the ASCII ACE header, including the newer 2.x header form.""" + import openmc.data + + try: + with path.open(encoding="ascii") as stream: + words = stream.readline(1024).split() + if re.fullmatch(r"\d\.\d\.\d", words[0]): + name = words[1] + temperature = float(stream.readline(1024).split()[1]) + else: + name = words[0] + temperature = float(words[2]) + temperature *= 1.e6 / openmc.data.K_BOLTZMANN + if not math.isfinite(temperature) or temperature <= 0: + raise ValueError("invalid temperature") + if not re.fullmatch(r"[^.\s]+\.\d+[ct]", name): + raise ValueError("invalid table name") + except (ValueError, IndexError, UnicodeError) as exc: + raise ValueError(f"Invalid or empty ACE header: {path}") from exc + return name, temperature + + +def _neutron_groups(root, release, temperatures): + import openmc.data + + groups = defaultdict(dict) + for path in sorted(root.rglob("*")): + if not path.is_file(): + continue + if release == "3.2": + match = re.fullmatch(r"([A-Z][a-z]?)(\d+)([mM]?)\.ACE", path.name) + if not match: + continue # Ignore .dir files and redundant *-293.ACE TSL tables. + symbol, mass, state = match.groups() + z = openmc.data.ATOMIC_NUMBER[symbol] + directory = re.fullmatch(r"ACEs_(\d+)K", path.parent.name) + if directory: + selected = directory[1] + elif path.parent == root: + selected = "293" # New 293 K archive has no enclosing directory. + else: + continue + filename_temperature = float(selected) + else: + suffix = r"\.ace" if release == "3.3" else "" + match = re.fullmatch( + r"(\d+)-([A-Z][a-z]?)-(\d+)([gm])-(\d+(?:\.\d+)?)" + suffix, + path.name, + ) + if not match: + continue + z, symbol, mass, state, temp = match.groups() + z = int(z) + filename_temperature = float(temp) + # Do not use Path.stem: 293.6 and 0.1 are not file extensions. + selected = "293" if release == "4.0" and temp == "293.6" else f"{float(temp):g}" + if selected in temperatures and release == "3.3" and path.parent.name != f"ace_{selected}": + raise ValueError(f"Inconsistent neutron temperature directory: {path}") + if selected not in temperatures: + continue + if openmc.data.ATOMIC_SYMBOL[z] != symbol: + raise ValueError(f"Inconsistent neutron identity: {path}") + mass = int(mass) + metastable = int(state.lower() == "m") + name = openmc.data.gnds_name(z, mass, metastable) + table_name, temperature = _header(path) + if not table_name.endswith("c"): + raise ValueError(f"Not a neutron ACE table: {path}") + zaid = int(table_name.split(".")[0]) + metadata = openmc.data.ace.get_metadata(zaid) + if metadata[2:4] != (z, mass): + raise ValueError(f"ACE header and filename identify different nuclides: {path}") + if not math.isclose(temperature, filename_temperature, abs_tol=1.0): + raise ValueError(f"ACE header and filename identify different temperatures: {path}") + if selected in groups[name]: + raise ValueError(f"Duplicate neutron table for {name} at {selected} K: {path}") + # Normalize every temperature in memory, including already-corrected caches + # and the MCNP Am242 exception. Never rewrite a downloaded ACE file. + corrected_zaid = 1000*z + mass + 400*metastable + groups[name][selected] = TableSource(path, table_name, temperature, name, corrected_zaid) + + if not groups: + raise FileNotFoundError(f"No requested JEFF-{release} neutron ACE tables in {root}") + for name, entries in groups.items(): + missing = set(temperatures) - entries.keys() + if missing: + raise FileNotFoundError(f"Missing neutron tables for {name} at {sorted(missing, key=float)} K") + return {name: list(entries.values()) for name, entries in groups.items()} + + +def _thermal_name(identity): + import openmc.data + + # OpenMC can fuzzy-match unknown names to *different* materials. Preserve an + # unknown identity instead, and make the unsupported alias visible to users. + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + name = openmc.data.thermal.get_thermal_name(identity) + if caught: + name = f"c_{identity}" + warnings.warn(f"Unrecognized thermal ACE identity {identity!r}; using {name!r} without fuzzy matching.") + return name + + +def _thermal_groups(root, release, details): + groups = defaultdict(list) + paths = {p for pattern in details["ace_paths"] for p in root.glob(pattern) if p.is_file()} + # Retain the old 3.3 material coverage check without using a previous + # material's data when a glob is empty. Grouping itself uses ACE identity. + missing = [group for group in details.get("required_file_groups", ()) + if not any(re.fullmatch(re.escape(group) + r".*-\d+\.ace", p.name) for p in paths)] + if missing: + raise FileNotFoundError(f"Missing JEFF-{release} thermal materials: {', '.join(missing)}") + for path in sorted(paths): + if release == "4.0" and not re.fullmatch(r"[^.]+\.\d+_\d+(?:\.\d+)?", path.name): + continue # Archive directory/index files are not ACE tables. + table_name, temperature = _header(path) + if not table_name.endswith("t"): + raise ValueError(f"Not a thermal ACE table: {path}") + identity = table_name.split(".")[0] + if release == "3.2": + identity = identity.rstrip("0123456789") # lw10.32t -> lw + groups[identity].append((path, table_name, temperature)) + if not groups: + raise FileNotFoundError(f"No JEFF-{release} thermal ACE tables in {root}") + for key, actual in (("selected_cases", len(groups)), + ("selected_tables", sum(map(len, groups.values())))): + if key in details and actual != details[key]: + raise ValueError(f"Incomplete JEFF-{release} thermal subset: {key} expected {details[key]}, found {actual}") + result = {} + for identity, entries in groups.items(): + name = _thermal_name(identity) + if name in result: + raise ValueError(f"Thermal output name collision: {identity} maps to {name}") + result[name] = [TableSource(path, table, temp, name) for path, table, temp in entries] + return result + + +def _validate_outputs(groups, destination): + """Reject silent OpenMC temperature deduplication and unsafe output names.""" + for name, entries in groups.items(): + if not re.fullmatch(r"[A-Za-z0-9_-]+", name): + raise ValueError(f"Unsafe output name: {name!r}") + entries.sort(key=lambda entry: entry.temperature) + labels = [round(entry.temperature) for entry in entries] + if len(set(labels)) != len(labels): + raise ValueError(f"Duplicate OpenMC temperature for {name}: {labels}") + for name in [f"{name}.h5" for name in groups] + ["cross_sections.xml"]: + path = destination / name + if path.exists() or path.is_symlink(): + raise FileExistsError(f"Refusing to overwrite existing output: {path}") + + +def _convert_group(entries, thermal): + import openmc.data + + cls = openmc.data.ThermalScattering if thermal else openmc.data.IncidentNeutron + data = None + for entry in entries: + # Supply the name so OpenMC reads only the indexed table, not a whole + # multi-table ACE library. Only this material is accumulated in memory. + table = openmc.data.ace.get_table(entry.path, name=entry.table_name) + if entry.zaid is not None: + table.name = f"{entry.zaid}.{table.name.split('.')[1]}" + kwargs = {"name": entry.name} if thermal else {} + if data is None: + data = cls.from_ace(table, **kwargs) + else: + data.add_temperature_from_ace(table, **kwargs) + if data.name != entry.name: + raise ValueError(f"Converted name {data.name} does not match {entry.name}: {entry.path}") + del table + if len(data.temperatures) != len(entries): + raise ValueError(f"Conversion lost temperatures for {data.name}") + return data + + +def _parser(default_release, allowed_releases, default_libver): + choices = '; '.join( + f"{release}: {', '.join(all_release_details['jeff'][release]['neutron']['ace']['temperatures'])}" + for release in allowed_releases + ) + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter, + epilog=f"Available neutron archive temperatures (K), by release: {choices}", + ) + parser.add_argument("-r", "--release", choices=allowed_releases, default=default_release) + parser.add_argument("-t", "--temperatures", nargs="+", help="Neutron archive temperatures in K; default: all available for the release") + parser.add_argument("-d", "--destination", type=Path, help="Direct output directory; default: jeff--hdf5") + parser.add_argument("--libver", choices=("earliest", "latest"), default=default_libver) + for option, default, help_text in ( + ("download", True, "Download selected neutron archives and the thermal archive"), + ("extract", True, "Extract the downloaded archives"), + ("cleanup", False, "Remove ACE and download cache directories only after success"), + ): + parser.add_argument(f"--{option}", dest=option, action="store_true", help=help_text) + parser.add_argument(f"--no-{option}", dest=option, action="store_false", help=f"Do not {help_text.lower()}") + parser.set_defaults(**{option: default}) + return parser + + +def _main(argv=None, *, default_release="4.0", allowed_releases=RELEASES, default_libver="latest"): + parser = _parser(default_release, allowed_releases, default_libver) + args = parser.parse_args(argv) + details = all_release_details["jeff"][args.release] + neutron = details["neutron"]["ace"] + thermal = details["thermal"]["ace"] + temperatures = args.temperatures if args.temperatures is not None else neutron["temperatures"] + invalid = set(temperatures) - set(neutron["temperatures"]) + if invalid: + parser.error(f"JEFF-{args.release} does not provide temperatures {sorted(invalid)}; choose from {', '.join(neutron['temperatures'])}") + temperatures = sorted(set(temperatures), key=float) + root = Path.cwd() / f"jeff-{args.release}-ace" + downloads = Path.cwd() / f"jeff-{args.release}-download" + destination = (args.destination or Path(f"jeff-{args.release}-hdf5")).resolve() + for cache in (root.resolve(), downloads.resolve()): + if destination == cache or cache in destination.parents: + parser.error("Destination must be outside the ACE and download cache directories") + + archives = [(neutron, filename, temp) for filename, temp in + zip(neutron["compressed_files"], neutron["temperatures"]) if temp in temperatures] + archives += [(thermal, filename, None) for filename in thermal["compressed_files"]] + if args.release == "4.0": + print("JEFF-4.0 thermal data: public SELECTED subset only (12 cases, 316 tables).") + if args.download: + warnings.warn("JEFF ACE archives require multiple GB of download and working space; thermal grids are downloaded in full.") + for source, filename, _ in archives: + download(source["base_url"] + filename + source.get("url_suffix", ""), + as_browser=source.get("as_browser", False), output_path=downloads, + output_filename=filename) + if args.extract: + for _, filename, temp in archives: + target = root / "ACEs_293K" if args.release == "3.2" and temp == "293" else root + extract(downloads / filename, target, del_compressed_file=False) + + neutron_groups = _neutron_groups(root, args.release, temperatures) + thermal_groups = _thermal_groups(root, args.release, thermal) + if neutron_groups.keys() & thermal_groups.keys(): + raise ValueError("Neutron and thermal output name collision") + groups = {**neutron_groups, **thermal_groups} + _validate_outputs(groups, destination) + destination.mkdir(parents=True, exist_ok=True) + + import openmc.data + + # Stage everything, including the relative-path XML, before publishing any + # outputs. Failed conversions leave caches intact and no success manifest. + with TemporaryDirectory(prefix=".jeff-", dir=destination) as temporary: + stage = Path(temporary) + library = openmc.data.DataLibrary() + tracker = ProgressTracker(len(groups)) + for name, entries in sorted(groups.items()): + tracker.starting(name) + data = _convert_group(entries, name in thermal_groups) + output = stage / f"{name}.h5" + data.export_to_hdf5(output, "w", libver=args.libver) + del data + library.register_file(output) + library.export_to_xml(stage / "cross_sections.xml") + for name in groups: + (stage / f"{name}.h5").replace(destination / f"{name}.h5") + (stage / "cross_sections.xml").replace(destination / "cross_sections.xml") + if args.cleanup: + for cache in (downloads, root): + if cache.exists(): + shutil.rmtree(cache) + + +def main(argv=None): + """Run the unified converter; importing this module never parses arguments.""" + return _main(argv) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/src/openmc_data/convert/convert_jeff32.py b/src/openmc_data/convert/convert_jeff32.py index 10c6386..f26b71a 100755 --- a/src/openmc_data/convert/convert_jeff32.py +++ b/src/openmc_data/convert/convert_jeff32.py @@ -1,265 +1,10 @@ -#!/usr/bin/env python3 +"""Compatibility alias for JEFF-3.2 (including its original HDF5 default).""" -""" -Download JEFF 3.2 ACE data from OECD/NEA and convert it to a multi-temperature -HDF5 library for use with OpenMC. -""" +from openmc_data.convert.convert_jeff import _main -import argparse -import tarfile -import zipfile -from collections import defaultdict -from pathlib import Path -from string import digits -from urllib.parse import urljoin -import openmc.data -from openmc_data import download, calculate_download_size, all_release_details, get_file_types, ProgressTracker - - -class CustomFormatter( - argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter -): - pass - - -parser = argparse.ArgumentParser(description=__doc__, formatter_class=CustomFormatter) -parser.add_argument( - "-d", - "--destination", - type=Path, - default=None, - help="Directory to create new library in", -) -parser.add_argument( - "--download", action="store_true", help="Download files files" -) -parser.add_argument( - "--no-download", - dest="download", - action="store_false", - help="Do not download files files", -) -parser.add_argument("--extract", action="store_true", help="Extract tar/zip files") -parser.add_argument( - "--no-extract", - dest="extract", - action="store_false", - help="Do not extract tar/zip files", -) -parser.add_argument( - "--libver", - choices=["earliest", "latest"], - default="latest", - help="Output HDF5 versioning. Use " - "'earliest' for backwards compatibility or 'latest' for " - "performance", -) -parser.add_argument( - "-r", - "--release", - choices=["3.2"], - default="3.2", - help="The nuclear data library release version. " - "The currently supported options are 3.2", -) -parser.add_argument( - "-t", - "--temperatures", - choices=[ - "293", - "400", - "500", - "600", - "700", - "800", - "900", - "1000", - "1200", - "1500", - "1800", - ], - default=[ - "293", - "400", - "500", - "600", - "700", - "800", - "900", - "1000", - "1200", - "1500", - "1800", - ], - help="Temperatures to download in Kelvin", - nargs="+", -) -parser.add_argument( - "--cleanup", - action="store_true", - help="Remove download directories when data has " "been processed", -) -parser.add_argument( - "--no-cleanup", - dest="cleanup", - action="store_false", - help="Do not remove download directories when data has " "been processed", -) -parser.set_defaults(download=True, extract=True, cleanup=False) -args = parser.parse_args() - - -def main(): - - library_name = "jeff" - file_types = get_file_types(['neutron']) - cwd = Path.cwd() - - ace_files_dir = cwd.joinpath("-".join([library_name, args.release, "ace"])) - download_path = cwd.joinpath("-".join([library_name, args.release, "download"])) - # the destination is decided after the release is know to avoid putting the release in a folder with a misleading name - if args.destination is None: - args.destination = Path("-".join([library_name, args.release, "hdf5"])) - - # This dictionary contains all the unique information about each release. This can be exstened to accommodated new releases - details = all_release_details[library_name][args.release]['neutron'][file_types['neutron']] - - # ============================================================================== - # DOWNLOAD FILES FROM OECD SITE - - if args.download: - calculate_download_size(library_name, args.release, ['neutron'], file_types, 'GB') - for f, t in zip(details["compressed_files"], details["temperatures"]): - if t in args.temperatures or t is None: - download( - urljoin(details["base_url"], f), - output_path=download_path, - ) - - # ============================================================================== - # EXTRACT FILES FROM TGZ - - if args.extract: - for f, t in zip(details["compressed_files"], details["temperatures"]): - if t in args.temperatures or t is None: - # Extract files - if f.endswith(".zip"): - with zipfile.ZipFile(download_path / f, "r") as zipf: - print("Extracting {}...".format(f)) - zipf.extractall(ace_files_dir) - - else: - suffix = "ACEs_293K" if t == "293" else "" - with tarfile.open(download_path / f, "r") as tgz: - print("Extracting {}...".format(f)) - tgz.extractall(ace_files_dir / suffix) - - # Remove thermal scattering tables from 293K data since they - # are redundant - if t == "293": - redundants = ace_files_dir.glob(details["redundant"]) - for path in redundants: - print(f"removing {path}") - path.unlink() - - # ============================================================================== - # CHANGE ZAID FOR METASTABLES - - metastables = ace_files_dir.rglob(details["metastables"]) - for path in metastables: - print(" Fixing {} (ensure metastable)...".format(path)) - text = open(path, "r").read() - mass_first_digit = int(text[3]) - if mass_first_digit <= 2: - text = text[:3] + str(mass_first_digit + 4) + text[4:] - open(path, "w").write(text) - - # ============================================================================== - # GENERATE HDF5 LIBRARY -- NEUTRON FILES - - # Get a list of all ACE files - neutron_files = ace_files_dir.rglob(details["neutron_files"]) - - # Group together tables for same nuclide - tables = defaultdict(list) - for filename in sorted(neutron_files): - name = filename.stem - tables[name].append(filename) - - # Sort temperatures from lowest to highest - for name, filenames in sorted(tables.items()): - filenames.sort(key=lambda x: int(x.parts[-2].split("_")[1][:-1])) - - # Create output directory if it doesn't exist - args.destination.mkdir(parents=True, exist_ok=True) - - library = openmc.data.DataLibrary() - - neutron_tables = sorted(tables.items()) - tracker = ProgressTracker(len(neutron_tables)) - for name, filenames in neutron_tables: - # Convert first temperature for the table - tracker.starting(filenames[0]) - data = openmc.data.IncidentNeutron.from_ace(filenames[0]) - - # For each higher temperature, add cross sections to the existing table - for filename in filenames[1:]: - print(f"Adding: {filename}") - data.add_temperature_from_ace(filename) - - # Export HDF5 file - h5_file = args.destination / f"{data.name}.h5" - print("Writing {}...".format(h5_file)) - data.export_to_hdf5(h5_file, "w", libver=args.libver) - - # Register with library - library.register_file(h5_file) - - # ============================================================================== - # GENERATE HDF5 LIBRARY -- S(A,B) FILES - - # Group together tables for same nuclide - tables = defaultdict(list) - sab_files = ace_files_dir.glob(details["sab_files"]) - for filename in sorted(sab_files): - name = filename.name.split("-")[0] - tables[name].append(filename) - - # Sort temperatures from lowest to highest - for name, filenames in sorted(tables.items()): - filenames.sort(key=lambda x: int(x.name.split("-")[1].split(".")[0])) - - sab_tables = sorted(tables.items()) - sab_tracker = ProgressTracker(len(sab_tables)) - for name, filenames in sab_tables: - # Convert first temperature for the table - sab_tracker.starting(filenames[0]) - - # Take numbers out of table name, e.g. lw10.32t -> lw.32t - table = openmc.data.ace.get_table(filenames[0]) - name, xs = table.name.split(".") - table.name = ".".join((name.strip(digits), xs)) - data = openmc.data.ThermalScattering.from_ace(table) - - # For each higher temperature, add cross sections to the existing table - for filename in filenames[1:]: - print(f"Adding: {filename}") - table = openmc.data.ace.get_table(filename) - name, xs = table.name.split(".") - table.name = ".".join((name.strip(digits), xs)) - data.add_temperature_from_ace(table) - - # Export HDF5 file - h5_file = args.destination / f"{data.name}.h5" - print("Writing {}...".format(h5_file)) - data.export_to_hdf5(h5_file, "w", libver=args.libver) - - # Register with library - library.register_file(h5_file) - - # Write cross_sections.xml - library.export_to_xml(args.destination / "cross_sections.xml") +def main(argv=None): + return _main(argv, default_release="3.2", allowed_releases=("3.2",), default_libver="latest") if __name__ == "__main__": diff --git a/src/openmc_data/convert/convert_jeff33.py b/src/openmc_data/convert/convert_jeff33.py index 05041a3..aaac8d2 100755 --- a/src/openmc_data/convert/convert_jeff33.py +++ b/src/openmc_data/convert/convert_jeff33.py @@ -1,227 +1,10 @@ -#!/usr/bin/env python +"""Compatibility alias for JEFF-3.3 (including its original HDF5 default).""" -""" -Convert JEFF 3.3 ACE data distributed by OECD/NEA into an HDF5 library that can -be used by OpenMC. It will download archives containing all the ACE files, -extract them, convert them, and write HDF5 files into a destination directory. -""" +from openmc_data.convert.convert_jeff import _main -import argparse -import sys -from pathlib import Path -from urllib.parse import urljoin -import openmc.data - -from openmc_data import download, extract, calculate_download_size, all_release_details, get_file_types, ProgressTracker - - -# Make sure Python version is sufficient -assert sys.version_info >= (3, 6), "Python 3.6+ is required" - - -class CustomFormatter( - argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter -): - pass - - -parser = argparse.ArgumentParser(description=__doc__, formatter_class=CustomFormatter) -parser.add_argument( - "-d", - "--destination", - type=Path, - default=Path("jeff-3.3-hdf5"), - help="Directory to create new library in", -) -parser.add_argument( - "--download", action="store_true", help="Download files" -) -parser.add_argument( - "--no-download", - dest="download", - action="store_false", - help="Do not download files", -) -parser.add_argument("--extract", action="store_true", help="Extract zip files") -parser.add_argument( - "--no-extract", - dest="extract", - action="store_false", - help="Do not extract .tgz file if it has already been extracted", -) -parser.add_argument( - "--libver", - choices=["earliest", "latest"], - default="earliest", - help="Output HDF5 versioning. Use " - "'earliest' for backwards compatibility or 'latest' for " - "performance", -) -parser.add_argument( - "-r", - "--release", - choices=["3.3"], - default="3.3", - help="The nuclear data library release version. " - "The only currently supported option is 3.3.", -) -parser.add_argument( - "-t", - "--temperatures", - choices=[ - "293", - "600", - "900", - "1200", - "1500", - "1800", - ], - default=[ - "293", - "600", - "900", - "1200", - "1500", - "1800", - ], - help="Temperatures to download in Kelvin", - nargs="+", -) -parser.add_argument( - "--cleanup", - action="store_true", - help="Remove download directories when data has " "been processed", -) -parser.add_argument( - "--no-cleanup", - dest="cleanup", - action="store_false", - help="Do not remove download directories when data has " "been processed", -) -parser.set_defaults(download=True, extract=True, cleanup=False) -args = parser.parse_args() - - -def key(p): - """Return (temperature, atomic number, mass number, metastable)""" - z, x, a, temp = p.stem.split("-") - return int(temp), int(z), int(a[:-1]), a[-1] - - -def main(): - - library_name = "jeff" - file_types = get_file_types(['neutron']) - cwd = Path.cwd() - - ace_files_dir = cwd.joinpath("-".join([library_name, args.release, "ace"])) - download_path = cwd.joinpath("-".join([library_name, args.release, "download"])) - - # This dictionary contains all the unique information about each release. - # This can be extended to accommodate new releases - details = all_release_details[library_name][args.release]['neutron'][file_types['neutron']] - - # ============================================================================== - # DOWNLOAD FILES FROM WEBSITE - - if args.download: - calculate_download_size(library_name, args.release, ['neutron'], file_types, 'GB') - for f, t in zip(details["compressed_files"], details["temperatures"]): - if t in args.temperatures or t is None: - download(urljoin(details["base_url"], f), output_path=download_path) - - # ============================================================================== - # EXTRACT FILES FROM TGZ - - if args.extract: - extract( - compressed_files=[ - download_path / f - for f, t in zip(details["compressed_files"], details["temperatures"]) - if t in args.temperatures or t is None - ], - extraction_dir=ace_files_dir, - del_compressed_file=args.cleanup, - ) - - # ============================================================================== - # CONVERT INCIDENT NEUTRON FILES - - # Create output directory if it doesn't exist - args.destination.mkdir(parents=True, exist_ok=True) - - lib = openmc.data.DataLibrary() - - neutron_paths = sorted(ace_files_dir.glob(details['neutron_files']), key=key) - tracker = ProgressTracker(len(neutron_paths)) - for p in neutron_paths: - tracker.starting(p) - temp, z, a, m = key(p) - - data = openmc.data.IncidentNeutron.from_ace(p) - if m == "m" and not data.name.endswith("_m1"): - # Correct metastable - data.metastable = 1 - data.name += "_m1" - - for T in list(filter(None, args.temperatures)): - p_add = ace_files_dir / f"ace_{T}" / (p.stem.replace("293", T) + ".ace") - print(f"Adding temperature: {p_add}") - data.add_temperature_from_ace(p_add) - - h5_file = args.destination / f"{data.name}.h5" - data.export_to_hdf5(h5_file, "w", libver=args.libver) - lib.register_file(h5_file) - - # ============================================================================== - # CONVERT THERMAL SCATTERING FILES - - thermal_mats = [ - "al-sap", - "be", - "ca-cah2", - "d-d2o", - "graph", - "h-cah2", - "h-ch2", - "h-h2o", - "h-ice", - "h-zrh", - "mesi", - "mg", - "o-d2o", - "orto-d", - "orto-h", - "o-sap", - "para-d", - "para-h", - "sili", - "tolu", - ] - - def thermal_temp(p): - return int(p.stem.split("-")[-1]) - - thermal_dir = ace_files_dir / details["thermal_files"] - - thermal_tracker = ProgressTracker(len(thermal_mats)) - for mat in thermal_mats: - for i, p in enumerate( - sorted(thermal_dir.glob(f"{mat}*.ace"), key=thermal_temp) - ): - if i == 0: - thermal_tracker.starting(p) - data = openmc.data.ThermalScattering.from_ace(p) - else: - print(f"Adding temperature: {p}") - data.add_temperature_from_ace(p) - - h5_file = args.destination / f"{data.name}.h5" - data.export_to_hdf5(h5_file, "w", libver=args.libver) - lib.register_file(h5_file) - - lib.export_to_xml(args.destination / "cross_sections.xml") +def main(argv=None): + return _main(argv, default_release="3.3", allowed_releases=("3.3",), default_libver="earliest") if __name__ == "__main__": diff --git a/src/openmc_data/urls.py b/src/openmc_data/urls.py index 4d7883c..8dcfc36 100644 --- a/src/openmc_data/urls.py +++ b/src/openmc_data/urls.py @@ -426,22 +426,14 @@ "3.2": { 'neutron': { "ace":{ - "base_url": "https://www.oecd-nea.org/dbforms/data/eva/evatapes/jeff_32/Processed/", - "compressed_files": [ - "JEFF32-ACE-293K.tar.gz", - "JEFF32-ACE-400K.tar.gz", - "JEFF32-ACE-500K.tar.gz", - "JEFF32-ACE-600K.tar.gz", - "JEFF32-ACE-700K.tar.gz", - "JEFF32-ACE-800K.zip", # Note the different suffix - "JEFF32-ACE-900K.tar.gz", - "JEFF32-ACE-1000K.tar.gz", - "JEFF32-ACE-1200K.tar.gz", - "JEFF32-ACE-1500K.tar.gz", - "JEFF32-ACE-1800K.tar.gz", - "TSLs.tar.gz"], + "base_url": "https://data.oecd-nea.org/api/records/8wvwt-vgy24/files/", + "url_suffix": "/content", + "as_browser": True, + "compressed_files": [f"JEFF32-ACE-{t}K.tar.gz" for t in + (293, 300, 400, 500, 600, 700, 800, 900, 1000, 1200, 1500, 1800)], "temperatures": [ "293", + "300", "400", "500", "600", @@ -452,44 +444,79 @@ "1200", "1500", "1800", - None ], - "neutron_files": "*.ACE", - "metastables": "*M.ACE", - "sab_files": "ANNEX_6_3_STLs/*/*.ace", - "redundant": "ACEs_293K/*-293.ACE", "compressed_file_size": 9, "uncompressed_file_size": 40, } + }, + 'thermal': { + 'ace': { + "base_url": "https://data.oecd-nea.org/api/records/z2s35-csq77/files/", + "url_suffix": "/content", + "as_browser": True, + "compressed_files": ["JEFF32-Processed-ACE-TSL.zip"], + "ace_paths": ["TSL-ACE/**/*.ace", "ANNEX_6_3_STLs/**/*.ace"], + "compressed_file_size": 0.06, + "uncompressed_file_size": 0.3, + } } }, "3.3": { 'neutron': { 'ace': { - "base_url": "http://www.oecd-nea.org/dbdata/jeff/jeff33/downloads/temperatures/", - "compressed_files": [ - "ace_293.tar.gz", - "ace_600.tar.gz", - "ace_900.tar.gz", - "ace_1200.tar.gz", - "ace_1500.tar.gz", - "ace_1800.tar.gz", - "ace_tsl.tar.gz", - ], - "temperatures": [ - "293", - "600", - "900", - "1200", - "1500", - "1800", - None - ], - "neutron_files": "ace_293/*.ace", - "thermal_files": "ace_tsl", + "base_url": "https://data.oecd-nea.org/api/records/zjcaq-2rw89/files/", + "url_suffix": "/content", + "as_browser": True, + "compressed_files": [f"ace_{t}.tar.gz" for t in (293, 600, 900, 1200, 1500, 1800)], + "temperatures": ["293", "600", "900", "1200", "1500", "1800"], "compressed_file_size": 7.7, "uncompressed_file_size": 37, } + }, + 'thermal': { + 'ace': { + "base_url": "https://data.oecd-nea.org/api/records/1rkw4-zk241/files/", + "url_suffix": "/content", + "as_browser": True, + "compressed_files": ["ace_tsl.tar.gz"], + "ace_paths": ["ace_tsl/*.ace"], + "required_file_groups": [ + "al-sap", "be", "ca-cah2", "d-d2o", "graph", "h-cah2", + "h-ch2", "h-h2o", "h-ice", "h-zrh", "mesi", "mg", + "o-d2o", "orto-d", "orto-h", "o-sap", "para-d", + "para-h", "sili", "tolu", + ], + "compressed_file_size": 0.93, + "uncompressed_file_size": 5, + } + } + }, + "4.0": { + 'neutron': { + 'ace': { + "base_url": "https://data.oecd-nea.org/api/records/0vhn5-d6t91/files/", + "url_suffix": "/content", + "as_browser": True, + "compressed_files": [f"JEFF40-Processed-Neutron-ACE-{t}K.zip" for t in + ("0.1", "293", "300", "600", "900", "1200", "1500", "1800")], + "temperatures": ["0.1", "293", "300", "600", "900", "1200", "1500", "1800"], + "compressed_file_size": 0, # Size estimate not available. + "uncompressed_file_size": 0, + } + }, + 'thermal': { + 'ace': { + "base_url": "https://data.oecd-nea.org/api/records/m3qef-tjx77/files/", + "url_suffix": "/content", + "as_browser": True, + "compressed_files": ["JEFF40-Processed-TSL-selected-ACE.zip"], + "ace_paths": ["data/*"], + # Public convenience subset, NOT the complete JEFF-4.0 TSL library. + "selected_cases": 12, + "selected_tables": 316, + "compressed_file_size": 4.39, + "uncompressed_file_size": 0, # Size estimate not available. + } } } }, diff --git a/src/openmc_data/utils.py b/src/openmc_data/utils.py index 44eebd9..b458df2 100644 --- a/src/openmc_data/utils.py +++ b/src/openmc_data/utils.py @@ -215,6 +215,15 @@ def extract( Path(compressed_file).unlink(missing_ok=True) +def _file_md5(path): + """Hash large archives without loading them into memory.""" + checksum = hashlib.md5() + with path.open('rb') as stream: + for chunk in iter(lambda: stream.read(_BLOCK_SIZE), b''): + checksum.update(chunk) + return checksum.hexdigest() + + def download( url: str, checksum=None, @@ -268,8 +277,9 @@ def download( local_path = Path(output_path) / output_filename # Check if file already downloaded - if local_path.is_file(): - if local_path.stat().st_size == file_size: + if file_size is not None and local_path.is_file(): + if (local_path.stat().st_size == file_size + and (checksum is None or _file_md5(local_path) == checksum)): print(f'Skipping {local_path}, already downloaded') return local_path @@ -283,13 +293,19 @@ def download( break fh.write(chunk) downloaded += len(chunk) - status = '{:10} [{:3.2f}%]'.format( - downloaded, downloaded * 100. / file_size) + if file_size: + status = '{:10} [{:3.2f}%]'.format( + downloaded, downloaded * 100. / file_size) + else: + status = f'{downloaded:10} bytes' print(status + '\b'*len(status), end='', flush=True) print('') + if file_size is not None and downloaded != file_size: + raise OSError(f"Incomplete download of {url}: expected {file_size} bytes, received {downloaded}") + if checksum is not None: - downloadsum = hashlib.md5(open(local_path, 'rb').read()).hexdigest() + downloadsum = _file_md5(local_path) if downloadsum != checksum: raise OSError("MD5 checksum for {} does not match. If this is " "your first time receiving this message, please " diff --git a/tests/test_convert_jeff.py b/tests/test_convert_jeff.py new file mode 100644 index 0000000..e6f7c4e --- /dev/null +++ b/tests/test_convert_jeff.py @@ -0,0 +1,449 @@ +"""Offline JEFF regression tests using small, valid ASCII ACE tables. + +The numerical readers, HDF5 writers, and XML registry are real OpenMC code. +Only archive downloads are replaced; no network or NJOY is needed. +""" + +import copy +import importlib +import os +from pathlib import Path +import subprocess +import sys +import tarfile +import zipfile + +import openmc.data +import pytest + +from openmc_data.convert import convert_jeff as converter + + +RELEASES = converter.RELEASES + + +def write_ace(path, name, temperature): + """Two incident energies, elastic-only neutron or discrete thermal data.""" + nxs, jxs = [0]*16, [0]*32 + if name.endswith("c"): + xss = [1.e-11, 20., 1., 1., 0., 0., 1., 1., 0., 0., 0.] + nxs[1:4] = [int(name.split('.')[0]), 2, 0] + jxs[0], jxs[7] = 1, 11 + else: + xss = [2., 1.e-9, 2.e-9, 2., 2., 1.e-9, -.5, .5, 2.e-9, -.5, .5] + nxs[2:4] = [1, 1] + jxs[0], jxs[2] = 1, 6 + nxs[0] = len(xss) + kT = temperature * openmc.data.K_BOLTZMANN / 1.e6 + lines = [f"{name:>10} 1.000000 {kT:.12e} synthetic", "Offline regression fixture"] + lines += ["1001 1.0 " + "0 0.0 "*3] + ["0 0.0 "*4]*3 + lines += [' '.join(map(str, nxs[i:i+8])) for i in (0, 8)] + lines += [' '.join(map(str, jxs[i:i+8])) for i in (0, 8, 16, 24)] + lines += [' '.join(f'{x:.12e}' for x in xss[i:i+4]) for i in range(0, len(xss), 4)] + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('\n'.join(lines) + '\n') + return path + + +def neutron_file(root, release, temperature, symbol="Ne", mass=20, metastable=False, encoded=False): + z = openmc.data.ATOMIC_NUMBER[symbol] + actual = 293.6 if temperature == "293" else float(temperature) + if release == "3.2": + path = root / f"ACEs_{temperature}K" / f"{symbol}{mass:03d}{'M' if metastable else ''}.ACE" + elif release == "3.3": + path = root / f"ace_{temperature}" / f"{z}-{symbol}-{mass}{'m' if metastable else 'g'}-{temperature}.ace" + else: + path = root / f"{z}-{symbol}-{mass}{'m' if metastable else 'g'}-{actual:.1f}" + zaid = 1000*z + mass + (400 if encoded else 0) + return write_ace(path, f"{zaid}.00c", actual) + + +def thermal_file(root, release, temperature=423.0, index=0, identity=None): + if release == "3.2": + identity = identity or f"lw{index:02d}" + path = root / 'TSL-ACE' / f'H2O-{temperature:g}.ace' + table = f"{identity}.32t" + elif release == "3.3": + identity = identity or "hh2o" + path = root / 'ace_tsl' / f'h-h2o-{temperature:g}.ace' + table = f"{identity}.{index:02d}t" + else: + identity = identity or "hh2o" + path = root / 'data' / f'{identity}.{index:02d}_{temperature:.2f}' + table = f"{identity}.{index:02d}t" + return write_ace(path, table, temperature) + + +@pytest.fixture(autouse=True) +def offline(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + catalog = copy.deepcopy(converter.all_release_details) + # The miniature library is deliberately not the full 12-case/316-table subset. + catalog['jeff']['4.0']['thermal']['ace'].pop('selected_cases') + catalog['jeff']['4.0']['thermal']['ace'].pop('selected_tables') + catalog['jeff']['3.3']['thermal']['ace'].pop('required_file_groups') + monkeypatch.setattr(converter, 'all_release_details', catalog) + def unexpected(*args, **kwargs): + pytest.fail('Unexpected network access') + monkeypatch.setattr(converter, 'download', unexpected) + + +def cached(release, *extra): + return ['-r', release, '--no-download', '--no-extract', *extra] + + +def root_for(release): + return Path.cwd() / f'jeff-{release}-ace' + + +@pytest.mark.parametrize('release', RELEASES) +@pytest.mark.parametrize('selected', [('600',), ('900', '600', '900')]) +def test_selection_no_293_base_sorted_no_duplicates(release, selected, monkeypatch): + root = root_for(release) + for temp in ('600', '900', '1200'): + neutron_file(root, release, temp) + # An unselected corrupt cache must not even be opened. + neutron_file(root, release, '293').write_text('corrupt cached unselected data') + thermal_file(root, release, 600, 1) + thermal_file(root, release, 423, 0) + read = openmc.data.ace.get_table + calls = [] + def record(path, name=None): + assert name is not None # Avoid loading a whole multi-table library. + calls.append(Path(path)) + return read(path, name) + monkeypatch.setattr(openmc.data.ace, 'get_table', record) + converter.main(cached(release, '-t', *selected, '--destination', 'direct')) + output = Path('direct') + data = openmc.data.IncidentNeutron.from_hdf5(output / 'Ne20.h5') + assert data.temperatures == [f'{t}K' for t in sorted(set(selected), key=float)] + thermal = openmc.data.ThermalScattering.from_hdf5(output / 'c_H_in_H2O.h5') + assert thermal.temperatures == ['423K', '600K'] + assert len(calls) == len(set(selected)) + 2 + library = openmc.data.DataLibrary.from_xml(output / 'cross_sections.xml') + assert {entry['type'] for entry in library} == {'neutron', 'thermal'} + assert all(Path(entry['path']).is_file() for entry in library) + assert not (output / f'jeff-{release}-hdf5').exists() + + +@pytest.mark.parametrize('release', RELEASES) +def test_default_all_available(release): + root = root_for(release) + temperatures = converter.all_release_details['jeff'][release]['neutron']['ace']['temperatures'] + for temp in temperatures: + neutron_file(root, release, temp) + thermal_file(root, release) + argv = cached(release) if release != '4.0' else ['--no-download', '--no-extract'] + converter.main(argv) + data = openmc.data.IncidentNeutron.from_hdf5(f'jeff-{release}-hdf5/Ne20.h5') + assert len(data.temperatures) == len(temperatures) + assert sorted(kT / openmc.data.K_BOLTZMANN for kT in data.kTs) == pytest.approx( + [293.6 if t == '293' else float(t) for t in temperatures]) + + +@pytest.mark.parametrize('release, invalid', [('3.2', '350'), ('3.3', '400'), ('4.0', '293.6')]) +def test_release_temperature_validation(release, invalid, capsys): + with pytest.raises(SystemExit, match='2'): + converter.main(['-r', release, '-t', invalid]) + assert 'choose from' in capsys.readouterr().err + assert not root_for(release).exists() + + +@pytest.mark.parametrize('release', RELEASES) +@pytest.mark.parametrize('encoded', [False, True]) +def test_metastables_all_temperatures_without_mutating_cache(release, encoded): + root = root_for(release) + originals = {} + for temp in ('600', '900'): + for metastable in (False, True): + path = neutron_file(root, release, temp, 'Am', 242, metastable, encoded and metastable) + originals[path] = path.read_bytes() + thermal_file(root, release) + converter.main(cached(release, '-t', '900', '600')) + for name, state in [('Am242', 0), ('Am242_m1', 1)]: + data = openmc.data.IncidentNeutron.from_hdf5(f'jeff-{release}-hdf5/{name}.h5') + assert (data.name, data.metastable, data.mass_number) == (name, state, 242) + assert data.temperatures == ['600K', '900K'] + assert all(path.read_bytes() == content for path, content in originals.items()) + + +@pytest.mark.parametrize('release', RELEASES) +@pytest.mark.parametrize('missing', ['all', 'temperature', 'nuclide', 'thermal', 'empty']) +def test_missing_or_empty_tables_fail(release, missing): + root = root_for(release) + thermal_file(root, release) + if missing != 'all': + path = neutron_file(root, release, '600') + if missing not in ('temperature', 'nuclide'): + neutron_file(root, release, '900') + if missing == 'nuclide': + neutron_file(root, release, '600', 'O', 16) + neutron_file(root, release, '900', 'O', 16) + if missing == 'empty': + path.write_text('') + if missing == 'thermal': + thermal_file(root, release).unlink() + with pytest.raises((FileNotFoundError, ValueError)): + converter.main(cached(release, '-t', '600', '900', '--cleanup')) + assert root.exists() + assert not Path(f'jeff-{release}-hdf5/cross_sections.xml').exists() + + +@pytest.mark.parametrize('release', RELEASES) +def test_exceptions_preserve_caches_and_publish_nothing(release, monkeypatch): + root = root_for(release) + neutron_file(root, release, '600') + thermal_file(root, release) + downloads = Path(f'jeff-{release}-download') + downloads.mkdir() + (downloads / 'keep').write_text('cache') + def fail(*args, **kwargs): + raise RuntimeError('broken thermal data') + monkeypatch.setattr(openmc.data.ThermalScattering, 'from_ace', fail) + with pytest.raises(RuntimeError, match='broken thermal'): + converter.main(cached(release, '-t', '600', '--cleanup')) + assert root.exists() and downloads.exists() + assert list(Path(f'jeff-{release}-hdf5').iterdir()) == [] + + +@pytest.mark.parametrize('release', RELEASES) +@pytest.mark.parametrize('cleanup', [False, True]) +def test_download_extract_cleanup_conventions(release, cleanup, tmp_path, monkeypatch): + source = tmp_path / 'source' + neutron_path = neutron_file(source, release, '293') + thermal_path = thermal_file(source, release) + calls = [] + def download(url, *, as_browser, output_path, output_filename): + assert as_browser is True + assert url.endswith(f'/{output_filename}/content') + assert output_filename != 'content' + calls.append(url) + output_path.mkdir(exist_ok=True) + archive = output_path / output_filename + path = thermal_path if len(calls) == 2 else neutron_path + member = path.relative_to(source) + if release == '3.2' and path == neutron_path: + member = Path(path.name) # New 293 K archive is flat. + if output_filename.endswith('.zip'): + with zipfile.ZipFile(archive, 'w') as z: + z.write(path, str(member)) + else: + with tarfile.open(archive, 'w:gz') as t: + t.add(path, arcname=str(member)) + return archive + monkeypatch.setattr(converter, 'download', download) + with pytest.warns(UserWarning, match='multiple GB'): + converter.main(['-r', release, '-t', '293', '--cleanup' if cleanup else '--no-cleanup']) + assert len(calls) == 2 + assert root_for(release).exists() is not cleanup + assert Path(f'jeff-{release}-download').exists() is not cleanup + assert Path(f'jeff-{release}-hdf5/Ne20.h5').exists() + + +@pytest.mark.parametrize('release', RELEASES) +def test_missing_archive_fails(release): + with pytest.raises(FileNotFoundError): + converter.main(['-r', release, '-t', '600', '--no-download']) + + +def test_32_flat_cache_and_legacy_thermal(): + root = root_for('3.2') + path = neutron_file(root, '3.2', '293') + path.rename(root / path.name) + thermal = thermal_file(root, '3.2') + legacy = root / 'ANNEX_6_3_STLs' / 'H2O' / thermal.name + legacy.parent.mkdir(parents=True) + thermal.rename(legacy) + (root / 'ACEs_293K' / 'H2O-293.ACE').write_text('redundant') + converter.main(cached('3.2', '-t', '293')) + assert Path('jeff-3.2-hdf5/c_H_in_H2O.h5').exists() + + +def test_40_numeric_temperatures_and_uo2_twins(): + root = root_for('4.0') + for temp in ('0.1', '293', '300'): + neutron_file(root, '4.0', temp, 'H', 1) + for index, temp in enumerate((1201., 300., 301., 1200.)): + thermal_file(root, '4.0', temp, index, 'ouo2') + (root / 'data' / 'directory').write_text('ignore') + converter.main(cached('4.0', '-t', '300', '293', '0.1')) + data = openmc.data.IncidentNeutron.from_hdf5('jeff-4.0-hdf5/H1.h5') + assert data.temperatures == ['0K', '294K', '300K'] + data = openmc.data.ThermalScattering.from_hdf5('jeff-4.0-hdf5/c_O_in_UO2.h5') + assert sorted(kT / openmc.data.K_BOLTZMANN for kT in data.kTs) == pytest.approx([300, 301, 1200, 1201]) + + +@pytest.mark.parametrize('collision', ['neutron', 'thermal', 'rounded', 'existing', 'xml']) +def test_output_collisions(collision): + root = root_for('4.0') + path = neutron_file(root, '4.0', '600') + thermal_file(root, '4.0', 423, 0, 'hh2o') + if collision == 'neutron': + duplicate = root / 'duplicate' / path.name + duplicate.parent.mkdir() + duplicate.write_bytes(path.read_bytes()) + elif collision == 'thermal': + thermal_file(root, '4.0', 600, 1, 'lwtr') + elif collision == 'rounded': + thermal_file(root, '4.0', 423.1, 1, 'hh2o') + else: + output = Path('jeff-4.0-hdf5') + output.mkdir() + (output / ('Ne20.h5' if collision == 'existing' else 'cross_sections.xml')).write_text('keep') + with pytest.raises((ValueError, FileExistsError), match='Duplicate|collision|overwrite'): + converter.main(cached('4.0', '-t', '600')) + + +def test_unknown_thermal_identity_not_fuzzy_matched(): + with pytest.warns(UserWarning, match='without fuzzy matching'): + assert converter._thermal_name('hh2onew') == 'c_hh2onew' + + +@pytest.mark.parametrize('field, expected', [('selected_cases', 12), ('selected_tables', 316)]) +def test_incomplete_40_subset_fails(field, expected): + root = root_for('4.0') + neutron_file(root, '4.0', '600') + thermal_file(root, '4.0') + converter.all_release_details['jeff']['4.0']['thermal']['ace'][field] = expected + with pytest.raises(ValueError, match='Incomplete'): + converter.main(cached('4.0', '-t', '600')) + + +@pytest.mark.parametrize('release', RELEASES) +def test_destination_in_cache_rejected(release): + with pytest.raises(SystemExit, match='2'): + converter.main(cached(release, '--destination', str(root_for(release) / 'out'))) + + +@pytest.mark.parametrize('module, release, libver', [ + ('convert_jeff32', '3.2', 'latest'), ('convert_jeff33', '3.3', 'earliest')]) +def test_alias_defaults_and_release_handling(module, release, libver, monkeypatch): + alias = importlib.import_module(f'openmc_data.convert.{module}') + temperatures = converter.all_release_details['jeff'][release]['neutron']['ace']['temperatures'] + for temp in temperatures: + neutron_file(root_for(release), release, temp) + thermal_file(root_for(release), release) + export = openmc.data.IncidentNeutron.export_to_hdf5 + versions = [] + def record(self, *args, **kwargs): + versions.append(kwargs['libver']) + return export(self, *args, **kwargs) + monkeypatch.setattr(openmc.data.IncidentNeutron, 'export_to_hdf5', record) + alias.main(['--no-download', '--no-extract']) + alias.main(['--no-download', '--no-extract', '-r', release, '-t', '600', '-d', 'explicit', '--libver', 'earliest']) + assert versions == [libver, 'earliest'] + with pytest.raises(SystemExit, match='2'): + alias.main(['-r', '4.0']) + + +@pytest.mark.parametrize('module', ['convert_jeff', 'convert_jeff32', 'convert_jeff33']) +def test_import_safe_and_module_help(module): + code = f"import sys; sys.argv = ['unrelated', '--invalid']; import openmc_data.convert.{module}" + # The fixture changes cwd; a relative PYTHONPATH would otherwise import an + # unrelated installed checkout in these child processes. + env = {**os.environ, 'PYTHONPATH': str(Path(converter.__file__).resolve().parents[2])} + subprocess.run([sys.executable, '-c', code], check=True, capture_output=True, text=True, env=env) + result = subprocess.run([sys.executable, '-m', f'openmc_data.convert.{module}', '--help'], + check=True, capture_output=True, text=True, env=env) + assert '--temperatures' in result.stdout + + +def test_ace_catalog_integrity(): + from openmc_data.urls import all_release_details + for release in RELEASES: + sources = all_release_details['jeff'][release] + neutron = sources['neutron']['ace'] + assert len(neutron['compressed_files']) == len(neutron['temperatures']) + for source in sources.values(): + ace = source['ace'] + assert ace['base_url'].startswith('https://data.oecd-nea.org/api/records/') + assert ace['url_suffix'] == '/content' + assert ace['as_browser'] is True + assert 'JEFF32-ACE-800K.tar.gz' in all_release_details['jeff']['3.2']['neutron']['ace']['compressed_files'] + assert 'JEFF32-ACE-300K.tar.gz' in all_release_details['jeff']['3.2']['neutron']['ace']['compressed_files'] + subset = all_release_details['jeff']['4.0']['thermal']['ace'] + assert (subset['selected_cases'], subset['selected_tables']) == (12, 316) + + +def test_33_missing_material_does_not_reuse_previous_data(): + root = root_for('3.3') + neutron_file(root, '3.3', '600') + thermal_file(root, '3.3') + converter.all_release_details['jeff']['3.3']['thermal']['ace']['required_file_groups'] = ['h-h2o', 'be'] + with pytest.raises(FileNotFoundError, match='thermal materials: be'): + converter.main(cached('3.3', '-t', '600')) + assert not Path('jeff-3.3-hdf5/cross_sections.xml').exists() + + +def test_33_thermal_prefixes_allow_phase_suffixes(): + root = root_for('3.3') + write_ace(root / 'ace_tsl/mesi-phii-20.ace', 'mesi.00t', 20) + write_ace(root / 'ace_tsl/tolue-phii-20.ace', 'tol.00t', 20) + details = {'ace_paths': ['ace_tsl/*.ace'], 'required_file_groups': ['mesi', 'tolu']} + groups = converter._thermal_groups(root, '3.3', details) + assert set(groups) == {'c_H_in_Mesitylene', 'c_H_in_Toluene'} + + +@pytest.mark.parametrize('release', RELEASES) +def test_download_without_extract_uses_cache(release, monkeypatch): + root = root_for(release) + neutron_file(root, release, '600') + thermal_file(root, release) + downloads = [] + monkeypatch.setattr(converter, 'download', lambda *args, **kwargs: downloads.append(kwargs['output_filename'])) + def fail(*args, **kwargs): + pytest.fail('Extraction was disabled') + monkeypatch.setattr(converter, 'extract', fail) + with pytest.warns(UserWarning, match='multiple GB'): + converter.main(['-r', release, '-t', '600', '--download', '--no-extract']) + assert len(downloads) == 2 + + +@pytest.mark.parametrize('release', RELEASES) +@pytest.mark.parametrize('problem', ['identity', 'temperature', 'type', 'thermal-empty']) +def test_inconsistent_tables_fail(release, problem): + root = root_for(release) + path = neutron_file(root, release, '600') + thermal = thermal_file(root, release) + if problem == 'identity': + write_ace(path, '8016.00c', 600) + elif problem == 'temperature': + write_ace(path, '10020.00c', 900) + elif problem == 'type': + write_ace(path, 'hh2o.00t', 600) + else: + thermal.write_text('') + with pytest.raises(ValueError): + converter.main(cached(release, '-t', '600')) + assert not Path(f'jeff-{release}-hdf5/cross_sections.xml').exists() + + +def test_new_style_header(): + path = Path('modern.ace') + kT = 293.6 * openmc.data.K_BOLTZMANN / 1.e6 + path.write_text(f'2.0.0 1001.40c\n1.0 {kT} date 3\ncomment\n') + name, temperature = converter._header(path) + assert name == '1001.40c' + assert temperature == pytest.approx(293.6) + + +@pytest.mark.parametrize('problem', ['unsafe-name', 'lost-temperature', 'wrong-name']) +def test_output_safety_checks(problem, monkeypatch): + root = root_for('3.3') + neutron_file(root, '3.3', '600') + neutron_file(root, '3.3', '900') + thermal_file(root, '3.3') + if problem == 'unsafe-name': + monkeypatch.setattr(converter, '_thermal_name', lambda _: '../unsafe') + elif problem == 'lost-temperature': + monkeypatch.setattr(openmc.data.IncidentNeutron, 'add_temperature_from_ace', lambda *a, **k: None) + else: + read = openmc.data.IncidentNeutron.from_ace + def wrong(*args, **kwargs): + data = read(*args, **kwargs) + data.name = 'wrong' + return data + monkeypatch.setattr(openmc.data.IncidentNeutron, 'from_ace', wrong) + with pytest.raises(ValueError, match='Unsafe|lost temperatures|does not match'): + converter.main(cached('3.3', '-t', '600', '900')) + assert not Path('jeff-3.3-hdf5/cross_sections.xml').exists() \ No newline at end of file diff --git a/tests/test_utils.py b/tests/test_utils.py index ddd8482..6d9f928 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,3 +1,5 @@ +import hashlib +import io import tarfile import pytest @@ -29,3 +31,115 @@ def test_process_neutron_requires_openmc(): with pytest.raises(ModuleNotFoundError, match="openmc is required"): openmc_data.process_neutron("dummy.endf", "out", "latest") + + +class Response(io.BytesIO): + def __init__(self, payload, length): + super().__init__(payload) + self.length = length + self.read_sizes = [] + + def read(self, size=-1): + assert size == utils._BLOCK_SIZE, 'Download must use bounded reads' + self.read_sizes.append(size) + return super().read(size) + + +@pytest.mark.parametrize('known_length', [False, True]) +@pytest.mark.parametrize('existing', [False, True]) +def test_download_streaming_length_and_cache(tmp_path, monkeypatch, capsys, known_length, existing): + payload = b'x' * (2*utils._BLOCK_SIZE + 17) + response = Response(payload, len(payload) if known_length else None) + target = tmp_path / 'library.zip' + if existing: + target.write_bytes(b'o' * len(payload)) + calls = [] + def urlopen(request, **kwargs): + calls.append((request, kwargs)) + return response + monkeypatch.setattr(utils, 'urlopen', urlopen) + path = utils.download('https://example.invalid/library.zip/content', as_browser=True, + output_path=tmp_path, output_filename='library.zip', timeout=10) + assert path == target + assert calls[0][0].get_header('User-agent') == 'Mozilla/5.0' + assert calls[0][1] == {'timeout': 10} + if existing and known_length: + assert target.read_bytes() == b'o' * len(payload) + assert not response.read_sizes + else: + assert target.read_bytes() == payload + assert len(response.read_sizes) == 4 + output = capsys.readouterr().out + if not known_length: + assert 'bytes' in output and '%' not in output and 'Skipping' not in output + assert response.closed + + +@pytest.mark.parametrize('length', [None, 0]) +def test_empty_download(tmp_path, monkeypatch, length): + monkeypatch.setattr(utils, 'urlopen', lambda *a, **k: Response(b'', length)) + path = utils.download('https://example.invalid/empty', output_path=tmp_path) + assert path.read_bytes() == b'' + + +def test_wrong_cached_size_redownloaded(tmp_path, monkeypatch): + (tmp_path / 'file').write_bytes(b'partial') + monkeypatch.setattr(utils, 'urlopen', lambda *a, **k: Response(b'new', 3)) + assert utils.download('https://example.invalid/file', output_path=tmp_path).read_bytes() == b'new' + + +@pytest.mark.parametrize('valid', [False, True]) +def test_unknown_length_checksum(tmp_path, monkeypatch, valid): + monkeypatch.setattr(utils, 'urlopen', lambda *a, **k: Response(b'payload', None)) + checksum = hashlib.md5(b'payload' if valid else b'wrong').hexdigest() + if valid: + assert utils.download('https://example.invalid/file', checksum=checksum, output_path=tmp_path).is_file() + else: + with pytest.raises(OSError, match='MD5 checksum'): + utils.download('https://example.invalid/file', checksum=checksum, output_path=tmp_path) + + +@pytest.mark.parametrize('valid_cache', [False, True]) +def test_known_length_cached_checksum(tmp_path, monkeypatch, valid_cache): + payload = b'payload' + target = tmp_path / 'file' + target.write_bytes(payload if valid_cache else b'invalid') + response = Response(payload, len(payload)) + monkeypatch.setattr(utils, 'urlopen', lambda *a, **k: response) + checksum = hashlib.md5(payload).hexdigest() + assert utils.download('https://example.invalid/file', checksum=checksum, + output_path=tmp_path).read_bytes() == payload + assert bool(response.read_sizes) is not valid_cache + assert response.closed + + +def test_checksum_uses_bounded_reads(tmp_path, monkeypatch): + from pathlib import Path + + payload = b'x' * (2*utils._BLOCK_SIZE + 17) + response = Response(payload, None) + monkeypatch.setattr(utils, 'urlopen', lambda *a, **k: response) + opened = Path.open + reads = [] + + def bounded(path, mode='r', *args, **kwargs): + if mode == 'rb': + stream = Response(payload, len(payload)) + reads.append(stream) + return stream + return opened(path, mode, *args, **kwargs) + + monkeypatch.setattr(Path, 'open', bounded) + utils.download('https://example.invalid/file', checksum=hashlib.md5(payload).hexdigest(), + output_path=tmp_path) + assert len(reads) == 1 + assert len(reads[0].read_sizes) == 4 + assert reads[0].closed + + +def test_truncated_download_fails(tmp_path, monkeypatch): + response = Response(b'partial', 100) + monkeypatch.setattr(utils, 'urlopen', lambda *a, **k: response) + with pytest.raises(OSError, match='Incomplete download'): + utils.download('https://example.invalid/file', output_path=tmp_path) + assert response.closed From d004e2bbc037e8afaa700da28dd47e204fc00392 Mon Sep 17 00:00:00 2001 From: shimwell <8583900+shimwell@users.noreply.github.com> Date: Tue, 20 Oct 2026 14:00:59 +0200 Subject: [PATCH 2/4] Consolidate JEFF conversion tests and documentation --- README.md | 55 +++++-------- src/openmc_data/convert/convert_jeff.py | 3 +- tests/test_convert_jeff.py | 73 +++++++---------- tests/test_utils.py | 102 ++++++++---------------- 4 files changed, 81 insertions(+), 152 deletions(-) diff --git a/README.md b/README.md index 56007df..997812e 100644 --- a/README.md +++ b/README.md @@ -94,10 +94,9 @@ A few categories of scripts are available: #### JEFF ACE conversion -`convert_jeff --help` describes the unified neutron and thermal ACE-to-HDF5 -converter. Use `-r/--release` to select a release and `-t/--temperatures` to -select neutron archive temperatures. With no temperature option, all available -neutron temperatures for that release are processed: +`convert_jeff -r 3.3 -t 600 900 --destination jeff-hot` converts neutron and +thermal ACE data without NJOY or a 293 K base. Defaults: release 4.0, all neutron +temperatures, `--libver latest`. Available neutron archive temperatures: | Release | Neutron archive temperatures (K) | | --- | --- | @@ -105,39 +104,21 @@ neutron temperatures for that release are processed: | 3.3 | 293, 600, 900, 1200, 1500, 1800 | | 4.0 | 0.1, 293, 300, 600, 900, 1200, 1500, 1800 | -For example, `convert_jeff -r 3.3 -t 600 900 --destination jeff-hot` does not -require 293 K neutron data. The 4.0 archive labelled 293 contains 293.6 K data; -select it with `-t 293`, not `-t 293.6`. Thermal tables have independent -temperature grids, so **all thermal temperatures** are retained regardless of -the neutron selection. Tables are grouped by ACE material identity, not filename -suffix; the UO2 temperature pairs separated by 1 K are retained. - -**JEFF-4.0 thermal coverage is the public selected subset: 12 cases and 316 -tables**, not the complete JEFF-4.0 TSL library. It covers Be, D in D2O, graphite, -H in CH2 and H2O, H in ZrH/ZrH1.5/ZrH2, O and U in UO2, and Zr in ZrH1.5/ZrH2. -The converter checks that subset's case and table counts. Unrecognized OpenMC -thermal aliases retain their ACE identity with a `c_` prefix and a warning, -rather than being guessed as another material. - -HDF5 files and the cross-section XML registry are written **directly** into -`--destination` (default: `jeff--hdf5`). Existing target files and -colliding material/temperature names are rejected. Outputs are staged until -conversion succeeds. Downloads and extracted ACE files are cached in -`jeff--download` and `jeff--ace` under the working directory. -`--no-download --no-extract` reuses those caches, while still filtering neutron -temperatures. Each discovered neutron nuclide must have every requested -temperature; empty or inconsistent input fails. The known 20 thermal material -file groups are also required for 3.3. Cached files alone cannot prove -that a nuclide absent at every temperature was originally present in an archive. -`--cleanup` removes both cache directories only after success; the default -`--no-cleanup` preserves them. ACE files are never edited to correct metastables. -Full downloads require multiple GB; files are streamed and conversion keeps only -one material's multi-temperature data in memory at a time. - -`convert_jeff32` and `convert_jeff33` remain thin compatibility aliases. They -retain their original releases, accepted `-r` values, default destinations, and -HDF5 defaults (`latest` for 3.2, `earliest` for 3.3). The unified command defaults -to release 4.0 and `--libver latest`; `--libver earliest` is also supported. +Select the 4.0 archive containing 293.6 K data with `-t 293`. **All native thermal +temperatures** are retained, including the 1 K UO2 pairs. **JEFF-4.0 supplies only +the public 12-case/316-table thermal subset**, not the full TSL library. +Unknown thermal aliases retain their identity with a `c_` prefix and warning. + +Output HDF5/XML goes directly into `--destination` (default `jeff--hdf5`), +staged until conversion succeeds; existing files and name/temperature collisions fail. +Downloads require multiple GB. `--no-download --no-extract` reuses working-directory +caches `jeff--download` and `jeff--ace`; `--cleanup` removes both +only after success. Metastable corrections never edit cached ACE files. +Every discovered nuclide must have every selected neutron temperature; 3.3 also +requires its 20 thermal groups. Caches cannot reveal nuclides absent at all temperatures. + +Legacy aliases `convert_jeff32`/`convert_jeff33` retain their releases, destinations +and HDF5 defaults (`latest`/`earliest`). See `convert_jeff --help` for all options. ### Generate cross sections diff --git a/src/openmc_data/convert/convert_jeff.py b/src/openmc_data/convert/convert_jeff.py index 00b4c93..5862886 100644 --- a/src/openmc_data/convert/convert_jeff.py +++ b/src/openmc_data/convert/convert_jeff.py @@ -229,9 +229,8 @@ def _parser(default_release, allowed_releases, default_libver): ("extract", True, "Extract the downloaded archives"), ("cleanup", False, "Remove ACE and download cache directories only after success"), ): - parser.add_argument(f"--{option}", dest=option, action="store_true", help=help_text) + parser.add_argument(f"--{option}", action="store_true", default=default, help=help_text) parser.add_argument(f"--no-{option}", dest=option, action="store_false", help=f"Do not {help_text.lower()}") - parser.set_defaults(**{option: default}) return parser diff --git a/tests/test_convert_jeff.py b/tests/test_convert_jeff.py index e6f7c4e..dd8ad08 100644 --- a/tests/test_convert_jeff.py +++ b/tests/test_convert_jeff.py @@ -96,6 +96,14 @@ def root_for(release): return Path.cwd() / f'jeff-{release}-ace' +def library(release, temperatures=('600',)): + root = root_for(release) + for temperature in temperatures: + neutron_file(root, release, temperature) + thermal_file(root, release) + return root + + @pytest.mark.parametrize('release', RELEASES) @pytest.mark.parametrize('selected', [('600',), ('900', '600', '900')]) def test_selection_no_293_base_sorted_no_duplicates(release, selected, monkeypatch): @@ -128,11 +136,8 @@ def record(path, name=None): @pytest.mark.parametrize('release', RELEASES) def test_default_all_available(release): - root = root_for(release) temperatures = converter.all_release_details['jeff'][release]['neutron']['ace']['temperatures'] - for temp in temperatures: - neutron_file(root, release, temp) - thermal_file(root, release) + library(release, temperatures) argv = cached(release) if release != '4.0' else ['--no-download', '--no-extract'] converter.main(argv) data = openmc.data.IncidentNeutron.from_hdf5(f'jeff-{release}-hdf5/Ne20.h5') @@ -168,7 +173,10 @@ def test_metastables_all_temperatures_without_mutating_cache(release, encoded): @pytest.mark.parametrize('release', RELEASES) -@pytest.mark.parametrize('missing', ['all', 'temperature', 'nuclide', 'thermal', 'empty']) +@pytest.mark.parametrize('missing', [ + 'all', 'temperature', 'nuclide', 'thermal', 'empty', + 'identity', 'bad-temperature', 'type', 'thermal-empty', +]) def test_missing_or_empty_tables_fail(release, missing): root = root_for(release) thermal_file(root, release) @@ -181,8 +189,16 @@ def test_missing_or_empty_tables_fail(release, missing): neutron_file(root, release, '900', 'O', 16) if missing == 'empty': path.write_text('') + elif missing in ('identity', 'bad-temperature', 'type'): + name, temperature = { + 'identity': ('8016.00c', 600), 'bad-temperature': ('10020.00c', 900), + 'type': ('hh2o.00t', 600), + }[missing] + write_ace(path, name, temperature) if missing == 'thermal': thermal_file(root, release).unlink() + elif missing == 'thermal-empty': + thermal_file(root, release).write_text('') with pytest.raises((FileNotFoundError, ValueError)): converter.main(cached(release, '-t', '600', '900', '--cleanup')) assert root.exists() @@ -191,9 +207,7 @@ def test_missing_or_empty_tables_fail(release, missing): @pytest.mark.parametrize('release', RELEASES) def test_exceptions_preserve_caches_and_publish_nothing(release, monkeypatch): - root = root_for(release) - neutron_file(root, release, '600') - thermal_file(root, release) + root = library(release) downloads = Path(f'jeff-{release}-download') downloads.mkdir() (downloads / 'keep').write_text('cache') @@ -275,9 +289,8 @@ def test_40_numeric_temperatures_and_uo2_twins(): @pytest.mark.parametrize('collision', ['neutron', 'thermal', 'rounded', 'existing', 'xml']) def test_output_collisions(collision): - root = root_for('4.0') + root = library('4.0') path = neutron_file(root, '4.0', '600') - thermal_file(root, '4.0', 423, 0, 'hh2o') if collision == 'neutron': duplicate = root / 'duplicate' / path.name duplicate.parent.mkdir() @@ -301,9 +314,7 @@ def test_unknown_thermal_identity_not_fuzzy_matched(): @pytest.mark.parametrize('field, expected', [('selected_cases', 12), ('selected_tables', 316)]) def test_incomplete_40_subset_fails(field, expected): - root = root_for('4.0') - neutron_file(root, '4.0', '600') - thermal_file(root, '4.0') + library('4.0') converter.all_release_details['jeff']['4.0']['thermal']['ace'][field] = expected with pytest.raises(ValueError, match='Incomplete'): converter.main(cached('4.0', '-t', '600')) @@ -320,9 +331,7 @@ def test_destination_in_cache_rejected(release): def test_alias_defaults_and_release_handling(module, release, libver, monkeypatch): alias = importlib.import_module(f'openmc_data.convert.{module}') temperatures = converter.all_release_details['jeff'][release]['neutron']['ace']['temperatures'] - for temp in temperatures: - neutron_file(root_for(release), release, temp) - thermal_file(root_for(release), release) + library(release, temperatures) export = openmc.data.IncidentNeutron.export_to_hdf5 versions = [] def record(self, *args, **kwargs): @@ -366,9 +375,7 @@ def test_ace_catalog_integrity(): def test_33_missing_material_does_not_reuse_previous_data(): - root = root_for('3.3') - neutron_file(root, '3.3', '600') - thermal_file(root, '3.3') + library('3.3') converter.all_release_details['jeff']['3.3']['thermal']['ace']['required_file_groups'] = ['h-h2o', 'be'] with pytest.raises(FileNotFoundError, match='thermal materials: be'): converter.main(cached('3.3', '-t', '600')) @@ -386,9 +393,7 @@ def test_33_thermal_prefixes_allow_phase_suffixes(): @pytest.mark.parametrize('release', RELEASES) def test_download_without_extract_uses_cache(release, monkeypatch): - root = root_for(release) - neutron_file(root, release, '600') - thermal_file(root, release) + library(release) downloads = [] monkeypatch.setattr(converter, 'download', lambda *args, **kwargs: downloads.append(kwargs['output_filename'])) def fail(*args, **kwargs): @@ -399,25 +404,6 @@ def fail(*args, **kwargs): assert len(downloads) == 2 -@pytest.mark.parametrize('release', RELEASES) -@pytest.mark.parametrize('problem', ['identity', 'temperature', 'type', 'thermal-empty']) -def test_inconsistent_tables_fail(release, problem): - root = root_for(release) - path = neutron_file(root, release, '600') - thermal = thermal_file(root, release) - if problem == 'identity': - write_ace(path, '8016.00c', 600) - elif problem == 'temperature': - write_ace(path, '10020.00c', 900) - elif problem == 'type': - write_ace(path, 'hh2o.00t', 600) - else: - thermal.write_text('') - with pytest.raises(ValueError): - converter.main(cached(release, '-t', '600')) - assert not Path(f'jeff-{release}-hdf5/cross_sections.xml').exists() - - def test_new_style_header(): path = Path('modern.ace') kT = 293.6 * openmc.data.K_BOLTZMANN / 1.e6 @@ -429,10 +415,7 @@ def test_new_style_header(): @pytest.mark.parametrize('problem', ['unsafe-name', 'lost-temperature', 'wrong-name']) def test_output_safety_checks(problem, monkeypatch): - root = root_for('3.3') - neutron_file(root, '3.3', '600') - neutron_file(root, '3.3', '900') - thermal_file(root, '3.3') + library('3.3', ('600', '900')) if problem == 'unsafe-name': monkeypatch.setattr(converter, '_thermal_name', lambda _: '../unsafe') elif problem == 'lost-temperature': diff --git a/tests/test_utils.py b/tests/test_utils.py index 6d9f928..4ef8b4f 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,6 +1,8 @@ import hashlib import io +from pathlib import Path import tarfile +from unittest.mock import Mock import pytest @@ -53,16 +55,13 @@ def test_download_streaming_length_and_cache(tmp_path, monkeypatch, capsys, know target = tmp_path / 'library.zip' if existing: target.write_bytes(b'o' * len(payload)) - calls = [] - def urlopen(request, **kwargs): - calls.append((request, kwargs)) - return response + urlopen = Mock(return_value=response) monkeypatch.setattr(utils, 'urlopen', urlopen) path = utils.download('https://example.invalid/library.zip/content', as_browser=True, output_path=tmp_path, output_filename='library.zip', timeout=10) assert path == target - assert calls[0][0].get_header('User-agent') == 'Mozilla/5.0' - assert calls[0][1] == {'timeout': 10} + assert urlopen.call_args.args[0].get_header('User-agent') == 'Mozilla/5.0' + assert urlopen.call_args.kwargs == {'timeout': 10} if existing and known_length: assert target.read_bytes() == b'o' * len(payload) assert not response.read_sizes @@ -75,71 +74,38 @@ def urlopen(request, **kwargs): assert response.closed -@pytest.mark.parametrize('length', [None, 0]) -def test_empty_download(tmp_path, monkeypatch, length): - monkeypatch.setattr(utils, 'urlopen', lambda *a, **k: Response(b'', length)) - path = utils.download('https://example.invalid/empty', output_path=tmp_path) - assert path.read_bytes() == b'' - - -def test_wrong_cached_size_redownloaded(tmp_path, monkeypatch): - (tmp_path / 'file').write_bytes(b'partial') - monkeypatch.setattr(utils, 'urlopen', lambda *a, **k: Response(b'new', 3)) - assert utils.download('https://example.invalid/file', output_path=tmp_path).read_bytes() == b'new' - - -@pytest.mark.parametrize('valid', [False, True]) -def test_unknown_length_checksum(tmp_path, monkeypatch, valid): - monkeypatch.setattr(utils, 'urlopen', lambda *a, **k: Response(b'payload', None)) - checksum = hashlib.md5(b'payload' if valid else b'wrong').hexdigest() - if valid: - assert utils.download('https://example.invalid/file', checksum=checksum, output_path=tmp_path).is_file() - else: - with pytest.raises(OSError, match='MD5 checksum'): - utils.download('https://example.invalid/file', checksum=checksum, output_path=tmp_path) - - -@pytest.mark.parametrize('valid_cache', [False, True]) -def test_known_length_cached_checksum(tmp_path, monkeypatch, valid_cache): - payload = b'payload' +@pytest.mark.parametrize('payload,length,cached,checksum_data,error', [ + (b'', None, None, None, None), (b'', 0, None, None, None), + (b'new', 3, b'partial', None, None), + (b'payload', None, None, b'payload', None), + (b'payload', None, None, b'wrong', 'MD5 checksum'), + (b'payload', 7, b'payload', b'payload', None), + (b'payload', 7, b'invalid', b'payload', None), + (b'partial', 100, None, None, 'Incomplete download'), +]) +def test_download_validation(tmp_path, monkeypatch, payload, length, cached, checksum_data, error): target = tmp_path / 'file' - target.write_bytes(payload if valid_cache else b'invalid') - response = Response(payload, len(payload)) - monkeypatch.setattr(utils, 'urlopen', lambda *a, **k: response) - checksum = hashlib.md5(payload).hexdigest() - assert utils.download('https://example.invalid/file', checksum=checksum, - output_path=tmp_path).read_bytes() == payload - assert bool(response.read_sizes) is not valid_cache + if cached is not None: + target.write_bytes(cached) + response = Response(payload, length) + monkeypatch.setattr(utils, 'urlopen', Mock(return_value=response)) + checksum = hashlib.md5(checksum_data).hexdigest() if checksum_data is not None else None + if error: + with pytest.raises(OSError, match=error): + utils.download('https://example.invalid/file', checksum=checksum, output_path=tmp_path) + else: + assert utils.download('https://example.invalid/file', checksum=checksum, + output_path=tmp_path).read_bytes() == payload + assert bool(response.read_sizes) is not (cached == payload) assert response.closed def test_checksum_uses_bounded_reads(tmp_path, monkeypatch): - from pathlib import Path - payload = b'x' * (2*utils._BLOCK_SIZE + 17) - response = Response(payload, None) - monkeypatch.setattr(utils, 'urlopen', lambda *a, **k: response) - opened = Path.open - reads = [] - - def bounded(path, mode='r', *args, **kwargs): - if mode == 'rb': - stream = Response(payload, len(payload)) - reads.append(stream) - return stream - return opened(path, mode, *args, **kwargs) - - monkeypatch.setattr(Path, 'open', bounded) - utils.download('https://example.invalid/file', checksum=hashlib.md5(payload).hexdigest(), - output_path=tmp_path) - assert len(reads) == 1 - assert len(reads[0].read_sizes) == 4 - assert reads[0].closed - - -def test_truncated_download_fails(tmp_path, monkeypatch): - response = Response(b'partial', 100) - monkeypatch.setattr(utils, 'urlopen', lambda *a, **k: response) - with pytest.raises(OSError, match='Incomplete download'): - utils.download('https://example.invalid/file', output_path=tmp_path) - assert response.closed + stream = Response(payload, len(payload)) + opened = Mock(return_value=stream) + monkeypatch.setattr(Path, 'open', opened) + assert utils._file_md5(tmp_path / 'file') == hashlib.md5(payload).hexdigest() + opened.assert_called_once_with('rb') + assert len(stream.read_sizes) == 4 + assert stream.closed From c99f6827fe656429e01db0aa5dee4e79610cf214 Mon Sep 17 00:00:00 2001 From: shimwell <8583900+shimwell@users.noreply.github.com> Date: Tue, 20 Oct 2026 16:31:02 +0200 Subject: [PATCH 3/4] Remove legacy JEFF conversion entry points --- .github/workflows/test_package.yml | 2 -- .github/workflows/test_processing.yml | 26 +++++++++++------------ README.md | 5 +---- pyproject.toml | 2 -- src/openmc_data/convert/convert_jeff.py | 18 ++++++---------- src/openmc_data/convert/convert_jeff32.py | 11 ---------- src/openmc_data/convert/convert_jeff33.py | 11 ---------- tests/test_convert_jeff.py | 25 ++++++++-------------- 8 files changed, 30 insertions(+), 70 deletions(-) delete mode 100755 src/openmc_data/convert/convert_jeff32.py delete mode 100755 src/openmc_data/convert/convert_jeff33.py diff --git a/.github/workflows/test_package.yml b/.github/workflows/test_package.yml index f7a02c5..0486546 100644 --- a/.github/workflows/test_package.yml +++ b/.github/workflows/test_package.yml @@ -52,8 +52,6 @@ jobs: run: | convert_fendl --help convert_jeff --help - convert_jeff32 --help - convert_jeff33 --help convert_lib80x --help convert_mcnp70 --help convert_mcnp71 --help diff --git a/.github/workflows/test_processing.yml b/.github/workflows/test_processing.yml index 6380592..a5a77db 100644 --- a/.github/workflows/test_processing.yml +++ b/.github/workflows/test_processing.yml @@ -9,8 +9,7 @@ on: type: choice options: - convert_fendl - - convert_jeff32 - - convert_jeff33 + - convert_jeff - convert_endf - convert_tendl - convert_tendl_rand @@ -19,6 +18,12 @@ on: - download_chain - add_branching_ratios - reduce_chain + jeff_release: + description: JEFF release (convert_jeff only) + required: true + type: choice + default: '4.0' + options: ['3.2', '3.3', '4.0'] jobs: @@ -58,17 +63,12 @@ jobs: run: | convert_fendl --cleanup - # this running convert_jeff32 in with default arguments produces 49GB of - # data. Hence the use of arguments to process just one temperature - - name: test default convert_jeff32 - if: inputs.script == 'convert_jeff32' - run: | - convert_jeff32 -r 3.2 -t 293 --cleanup - - - name: test default convert_jeff33 - if: inputs.script == 'convert_jeff33' - run: | - convert_jeff33 -r 3.3 -t 293 --cleanup + # Limit neutron processing to one temperature to bound disk use. + - name: test convert_jeff + if: inputs.script == 'convert_jeff' + env: + JEFF_RELEASE: ${{ inputs.jeff_release }} + run: convert_jeff -r "$JEFF_RELEASE" -t 293 --cleanup - name: test default convert_endf if: inputs.script == 'convert_endf' diff --git a/README.md b/README.md index 997812e..3b4fefa 100644 --- a/README.md +++ b/README.md @@ -117,8 +117,7 @@ only after success. Metastable corrections never edit cached ACE files. Every discovered nuclide must have every selected neutron temperature; 3.3 also requires its 20 thermal groups. Caches cannot reveal nuclides absent at all temperatures. -Legacy aliases `convert_jeff32`/`convert_jeff33` retain their releases, destinations -and HDF5 defaults (`latest`/`earliest`). See `convert_jeff --help` for all options. +See `convert_jeff --help` for all options. ### Generate cross sections @@ -149,8 +148,6 @@ and HDF5 defaults (`latest`/`earliest`). See `convert_jeff --help` for all optio |generate_endf| ENDF/B | VIII.0 | NNDC | [openmc.org](https://anl.box.com/shared/static/uhbxlrx7hvxqw27psymfbhi7bx7s6u6a.xz) | | :heavy_check_mark: | | |convert_fendl| FENDL | 2.1
3.0
3.1a
3.1d
3.2 | | [openmc.org 3.2](https://anl.box.com/shared/static/3cb7jetw7tmxaw6nvn77x6c578jnm2ey.xz) | :heavy_check_mark: | | | |generate_jendl| JENDL | 4.0 | | | | :heavy_check_mark: | | -|convert_jeff32| JEFF | 3.2 | | [openmc.org](https://anl.box.com/shared/static/pb94oxriiipezysu7w4r2qdoufc2epxv.xz) | :heavy_check_mark: | | | -|convert_jeff33| JEFF | 3.3 | | [openmc.org](https://anl.box.com/shared/static/ddetxzp0gv1buk1ev67b8ynik7f268hw.xz) | :heavy_check_mark: | | | |convert_tendl| TENDL | 2015
2017
2019
2021| | | :heavy_check_mark: | | | --> ## Produce Depletion Chain files diff --git a/pyproject.toml b/pyproject.toml index 6bfe6c1..6c576c3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -62,8 +62,6 @@ include-package-data = false [project.scripts] convert_fendl = "openmc_data.convert.convert_fendl:main" convert_jeff = "openmc_data.convert.convert_jeff:main" -convert_jeff32 = "openmc_data.convert.convert_jeff32:main" -convert_jeff33 = "openmc_data.convert.convert_jeff33:main" convert_lib80x = "openmc_data.convert.convert_lib80x:main" convert_mcnp70 = "openmc_data.convert.convert_mcnp70:main" convert_mcnp71 = "openmc_data.convert.convert_mcnp71:main" diff --git a/src/openmc_data/convert/convert_jeff.py b/src/openmc_data/convert/convert_jeff.py index 5862886..5d86c46 100644 --- a/src/openmc_data/convert/convert_jeff.py +++ b/src/openmc_data/convert/convert_jeff.py @@ -211,19 +211,19 @@ def _convert_group(entries, thermal): return data -def _parser(default_release, allowed_releases, default_libver): +def _parser(): choices = '; '.join( f"{release}: {', '.join(all_release_details['jeff'][release]['neutron']['ace']['temperatures'])}" - for release in allowed_releases + for release in RELEASES ) parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter, epilog=f"Available neutron archive temperatures (K), by release: {choices}", ) - parser.add_argument("-r", "--release", choices=allowed_releases, default=default_release) + parser.add_argument("-r", "--release", choices=RELEASES, default="4.0") parser.add_argument("-t", "--temperatures", nargs="+", help="Neutron archive temperatures in K; default: all available for the release") parser.add_argument("-d", "--destination", type=Path, help="Direct output directory; default: jeff--hdf5") - parser.add_argument("--libver", choices=("earliest", "latest"), default=default_libver) + parser.add_argument("--libver", choices=("earliest", "latest"), default="latest") for option, default, help_text in ( ("download", True, "Download selected neutron archives and the thermal archive"), ("extract", True, "Extract the downloaded archives"), @@ -234,8 +234,9 @@ def _parser(default_release, allowed_releases, default_libver): return parser -def _main(argv=None, *, default_release="4.0", allowed_releases=RELEASES, default_libver="latest"): - parser = _parser(default_release, allowed_releases, default_libver) +def main(argv=None): + """Run the converter; importing this module never parses arguments.""" + parser = _parser() args = parser.parse_args(argv) details = all_release_details["jeff"][args.release] neutron = details["neutron"]["ace"] @@ -301,10 +302,5 @@ def _main(argv=None, *, default_release="4.0", allowed_releases=RELEASES, defaul shutil.rmtree(cache) -def main(argv=None): - """Run the unified converter; importing this module never parses arguments.""" - return _main(argv) - - if __name__ == "__main__": main() \ No newline at end of file diff --git a/src/openmc_data/convert/convert_jeff32.py b/src/openmc_data/convert/convert_jeff32.py deleted file mode 100755 index f26b71a..0000000 --- a/src/openmc_data/convert/convert_jeff32.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Compatibility alias for JEFF-3.2 (including its original HDF5 default).""" - -from openmc_data.convert.convert_jeff import _main - - -def main(argv=None): - return _main(argv, default_release="3.2", allowed_releases=("3.2",), default_libver="latest") - - -if __name__ == "__main__": - main() diff --git a/src/openmc_data/convert/convert_jeff33.py b/src/openmc_data/convert/convert_jeff33.py deleted file mode 100755 index aaac8d2..0000000 --- a/src/openmc_data/convert/convert_jeff33.py +++ /dev/null @@ -1,11 +0,0 @@ -"""Compatibility alias for JEFF-3.3 (including its original HDF5 default).""" - -from openmc_data.convert.convert_jeff import _main - - -def main(argv=None): - return _main(argv, default_release="3.3", allowed_releases=("3.3",), default_libver="earliest") - - -if __name__ == "__main__": - main() diff --git a/tests/test_convert_jeff.py b/tests/test_convert_jeff.py index dd8ad08..303d0a8 100644 --- a/tests/test_convert_jeff.py +++ b/tests/test_convert_jeff.py @@ -5,7 +5,6 @@ """ import copy -import importlib import os from pathlib import Path import subprocess @@ -326,33 +325,27 @@ def test_destination_in_cache_rejected(release): converter.main(cached(release, '--destination', str(root_for(release) / 'out'))) -@pytest.mark.parametrize('module, release, libver', [ - ('convert_jeff32', '3.2', 'latest'), ('convert_jeff33', '3.3', 'earliest')]) -def test_alias_defaults_and_release_handling(module, release, libver, monkeypatch): - alias = importlib.import_module(f'openmc_data.convert.{module}') - temperatures = converter.all_release_details['jeff'][release]['neutron']['ace']['temperatures'] - library(release, temperatures) +@pytest.mark.parametrize('release', RELEASES) +@pytest.mark.parametrize('options, expected', [([], 'latest'), (['--libver', 'earliest'], 'earliest')]) +def test_hdf5_version(release, options, expected, monkeypatch): + library(release) export = openmc.data.IncidentNeutron.export_to_hdf5 versions = [] def record(self, *args, **kwargs): versions.append(kwargs['libver']) return export(self, *args, **kwargs) monkeypatch.setattr(openmc.data.IncidentNeutron, 'export_to_hdf5', record) - alias.main(['--no-download', '--no-extract']) - alias.main(['--no-download', '--no-extract', '-r', release, '-t', '600', '-d', 'explicit', '--libver', 'earliest']) - assert versions == [libver, 'earliest'] - with pytest.raises(SystemExit, match='2'): - alias.main(['-r', '4.0']) + converter.main(cached(release, '-t', '600', *options)) + assert versions == [expected] -@pytest.mark.parametrize('module', ['convert_jeff', 'convert_jeff32', 'convert_jeff33']) -def test_import_safe_and_module_help(module): - code = f"import sys; sys.argv = ['unrelated', '--invalid']; import openmc_data.convert.{module}" +def test_import_safe_and_module_help(): + code = "import sys; sys.argv = ['unrelated', '--invalid']; import openmc_data.convert.convert_jeff" # The fixture changes cwd; a relative PYTHONPATH would otherwise import an # unrelated installed checkout in these child processes. env = {**os.environ, 'PYTHONPATH': str(Path(converter.__file__).resolve().parents[2])} subprocess.run([sys.executable, '-c', code], check=True, capture_output=True, text=True, env=env) - result = subprocess.run([sys.executable, '-m', f'openmc_data.convert.{module}', '--help'], + result = subprocess.run([sys.executable, '-m', 'openmc_data.convert.convert_jeff', '--help'], check=True, capture_output=True, text=True, env=env) assert '--temperatures' in result.stdout From 6711be5b7170d0d5f2c7fd10f688d39693124e22 Mon Sep 17 00:00:00 2001 From: shimwell <8583900+shimwell@users.noreply.github.com> Date: Tue, 20 Oct 2026 17:22:11 +0200 Subject: [PATCH 4/4] Defer expanded JEFF conversion tests --- .github/workflows/test_processing.yml | 10 +- tests/test_convert_jeff.py | 425 -------------------------- tests/test_utils.py | 80 ----- 3 files changed, 1 insertion(+), 514 deletions(-) delete mode 100644 tests/test_convert_jeff.py diff --git a/.github/workflows/test_processing.yml b/.github/workflows/test_processing.yml index a5a77db..35f814c 100644 --- a/.github/workflows/test_processing.yml +++ b/.github/workflows/test_processing.yml @@ -18,12 +18,6 @@ on: - download_chain - add_branching_ratios - reduce_chain - jeff_release: - description: JEFF release (convert_jeff only) - required: true - type: choice - default: '4.0' - options: ['3.2', '3.3', '4.0'] jobs: @@ -66,9 +60,7 @@ jobs: # Limit neutron processing to one temperature to bound disk use. - name: test convert_jeff if: inputs.script == 'convert_jeff' - env: - JEFF_RELEASE: ${{ inputs.jeff_release }} - run: convert_jeff -r "$JEFF_RELEASE" -t 293 --cleanup + run: convert_jeff -t 293 --cleanup - name: test default convert_endf if: inputs.script == 'convert_endf' diff --git a/tests/test_convert_jeff.py b/tests/test_convert_jeff.py deleted file mode 100644 index 303d0a8..0000000 --- a/tests/test_convert_jeff.py +++ /dev/null @@ -1,425 +0,0 @@ -"""Offline JEFF regression tests using small, valid ASCII ACE tables. - -The numerical readers, HDF5 writers, and XML registry are real OpenMC code. -Only archive downloads are replaced; no network or NJOY is needed. -""" - -import copy -import os -from pathlib import Path -import subprocess -import sys -import tarfile -import zipfile - -import openmc.data -import pytest - -from openmc_data.convert import convert_jeff as converter - - -RELEASES = converter.RELEASES - - -def write_ace(path, name, temperature): - """Two incident energies, elastic-only neutron or discrete thermal data.""" - nxs, jxs = [0]*16, [0]*32 - if name.endswith("c"): - xss = [1.e-11, 20., 1., 1., 0., 0., 1., 1., 0., 0., 0.] - nxs[1:4] = [int(name.split('.')[0]), 2, 0] - jxs[0], jxs[7] = 1, 11 - else: - xss = [2., 1.e-9, 2.e-9, 2., 2., 1.e-9, -.5, .5, 2.e-9, -.5, .5] - nxs[2:4] = [1, 1] - jxs[0], jxs[2] = 1, 6 - nxs[0] = len(xss) - kT = temperature * openmc.data.K_BOLTZMANN / 1.e6 - lines = [f"{name:>10} 1.000000 {kT:.12e} synthetic", "Offline regression fixture"] - lines += ["1001 1.0 " + "0 0.0 "*3] + ["0 0.0 "*4]*3 - lines += [' '.join(map(str, nxs[i:i+8])) for i in (0, 8)] - lines += [' '.join(map(str, jxs[i:i+8])) for i in (0, 8, 16, 24)] - lines += [' '.join(f'{x:.12e}' for x in xss[i:i+4]) for i in range(0, len(xss), 4)] - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text('\n'.join(lines) + '\n') - return path - - -def neutron_file(root, release, temperature, symbol="Ne", mass=20, metastable=False, encoded=False): - z = openmc.data.ATOMIC_NUMBER[symbol] - actual = 293.6 if temperature == "293" else float(temperature) - if release == "3.2": - path = root / f"ACEs_{temperature}K" / f"{symbol}{mass:03d}{'M' if metastable else ''}.ACE" - elif release == "3.3": - path = root / f"ace_{temperature}" / f"{z}-{symbol}-{mass}{'m' if metastable else 'g'}-{temperature}.ace" - else: - path = root / f"{z}-{symbol}-{mass}{'m' if metastable else 'g'}-{actual:.1f}" - zaid = 1000*z + mass + (400 if encoded else 0) - return write_ace(path, f"{zaid}.00c", actual) - - -def thermal_file(root, release, temperature=423.0, index=0, identity=None): - if release == "3.2": - identity = identity or f"lw{index:02d}" - path = root / 'TSL-ACE' / f'H2O-{temperature:g}.ace' - table = f"{identity}.32t" - elif release == "3.3": - identity = identity or "hh2o" - path = root / 'ace_tsl' / f'h-h2o-{temperature:g}.ace' - table = f"{identity}.{index:02d}t" - else: - identity = identity or "hh2o" - path = root / 'data' / f'{identity}.{index:02d}_{temperature:.2f}' - table = f"{identity}.{index:02d}t" - return write_ace(path, table, temperature) - - -@pytest.fixture(autouse=True) -def offline(tmp_path, monkeypatch): - monkeypatch.chdir(tmp_path) - catalog = copy.deepcopy(converter.all_release_details) - # The miniature library is deliberately not the full 12-case/316-table subset. - catalog['jeff']['4.0']['thermal']['ace'].pop('selected_cases') - catalog['jeff']['4.0']['thermal']['ace'].pop('selected_tables') - catalog['jeff']['3.3']['thermal']['ace'].pop('required_file_groups') - monkeypatch.setattr(converter, 'all_release_details', catalog) - def unexpected(*args, **kwargs): - pytest.fail('Unexpected network access') - monkeypatch.setattr(converter, 'download', unexpected) - - -def cached(release, *extra): - return ['-r', release, '--no-download', '--no-extract', *extra] - - -def root_for(release): - return Path.cwd() / f'jeff-{release}-ace' - - -def library(release, temperatures=('600',)): - root = root_for(release) - for temperature in temperatures: - neutron_file(root, release, temperature) - thermal_file(root, release) - return root - - -@pytest.mark.parametrize('release', RELEASES) -@pytest.mark.parametrize('selected', [('600',), ('900', '600', '900')]) -def test_selection_no_293_base_sorted_no_duplicates(release, selected, monkeypatch): - root = root_for(release) - for temp in ('600', '900', '1200'): - neutron_file(root, release, temp) - # An unselected corrupt cache must not even be opened. - neutron_file(root, release, '293').write_text('corrupt cached unselected data') - thermal_file(root, release, 600, 1) - thermal_file(root, release, 423, 0) - read = openmc.data.ace.get_table - calls = [] - def record(path, name=None): - assert name is not None # Avoid loading a whole multi-table library. - calls.append(Path(path)) - return read(path, name) - monkeypatch.setattr(openmc.data.ace, 'get_table', record) - converter.main(cached(release, '-t', *selected, '--destination', 'direct')) - output = Path('direct') - data = openmc.data.IncidentNeutron.from_hdf5(output / 'Ne20.h5') - assert data.temperatures == [f'{t}K' for t in sorted(set(selected), key=float)] - thermal = openmc.data.ThermalScattering.from_hdf5(output / 'c_H_in_H2O.h5') - assert thermal.temperatures == ['423K', '600K'] - assert len(calls) == len(set(selected)) + 2 - library = openmc.data.DataLibrary.from_xml(output / 'cross_sections.xml') - assert {entry['type'] for entry in library} == {'neutron', 'thermal'} - assert all(Path(entry['path']).is_file() for entry in library) - assert not (output / f'jeff-{release}-hdf5').exists() - - -@pytest.mark.parametrize('release', RELEASES) -def test_default_all_available(release): - temperatures = converter.all_release_details['jeff'][release]['neutron']['ace']['temperatures'] - library(release, temperatures) - argv = cached(release) if release != '4.0' else ['--no-download', '--no-extract'] - converter.main(argv) - data = openmc.data.IncidentNeutron.from_hdf5(f'jeff-{release}-hdf5/Ne20.h5') - assert len(data.temperatures) == len(temperatures) - assert sorted(kT / openmc.data.K_BOLTZMANN for kT in data.kTs) == pytest.approx( - [293.6 if t == '293' else float(t) for t in temperatures]) - - -@pytest.mark.parametrize('release, invalid', [('3.2', '350'), ('3.3', '400'), ('4.0', '293.6')]) -def test_release_temperature_validation(release, invalid, capsys): - with pytest.raises(SystemExit, match='2'): - converter.main(['-r', release, '-t', invalid]) - assert 'choose from' in capsys.readouterr().err - assert not root_for(release).exists() - - -@pytest.mark.parametrize('release', RELEASES) -@pytest.mark.parametrize('encoded', [False, True]) -def test_metastables_all_temperatures_without_mutating_cache(release, encoded): - root = root_for(release) - originals = {} - for temp in ('600', '900'): - for metastable in (False, True): - path = neutron_file(root, release, temp, 'Am', 242, metastable, encoded and metastable) - originals[path] = path.read_bytes() - thermal_file(root, release) - converter.main(cached(release, '-t', '900', '600')) - for name, state in [('Am242', 0), ('Am242_m1', 1)]: - data = openmc.data.IncidentNeutron.from_hdf5(f'jeff-{release}-hdf5/{name}.h5') - assert (data.name, data.metastable, data.mass_number) == (name, state, 242) - assert data.temperatures == ['600K', '900K'] - assert all(path.read_bytes() == content for path, content in originals.items()) - - -@pytest.mark.parametrize('release', RELEASES) -@pytest.mark.parametrize('missing', [ - 'all', 'temperature', 'nuclide', 'thermal', 'empty', - 'identity', 'bad-temperature', 'type', 'thermal-empty', -]) -def test_missing_or_empty_tables_fail(release, missing): - root = root_for(release) - thermal_file(root, release) - if missing != 'all': - path = neutron_file(root, release, '600') - if missing not in ('temperature', 'nuclide'): - neutron_file(root, release, '900') - if missing == 'nuclide': - neutron_file(root, release, '600', 'O', 16) - neutron_file(root, release, '900', 'O', 16) - if missing == 'empty': - path.write_text('') - elif missing in ('identity', 'bad-temperature', 'type'): - name, temperature = { - 'identity': ('8016.00c', 600), 'bad-temperature': ('10020.00c', 900), - 'type': ('hh2o.00t', 600), - }[missing] - write_ace(path, name, temperature) - if missing == 'thermal': - thermal_file(root, release).unlink() - elif missing == 'thermal-empty': - thermal_file(root, release).write_text('') - with pytest.raises((FileNotFoundError, ValueError)): - converter.main(cached(release, '-t', '600', '900', '--cleanup')) - assert root.exists() - assert not Path(f'jeff-{release}-hdf5/cross_sections.xml').exists() - - -@pytest.mark.parametrize('release', RELEASES) -def test_exceptions_preserve_caches_and_publish_nothing(release, monkeypatch): - root = library(release) - downloads = Path(f'jeff-{release}-download') - downloads.mkdir() - (downloads / 'keep').write_text('cache') - def fail(*args, **kwargs): - raise RuntimeError('broken thermal data') - monkeypatch.setattr(openmc.data.ThermalScattering, 'from_ace', fail) - with pytest.raises(RuntimeError, match='broken thermal'): - converter.main(cached(release, '-t', '600', '--cleanup')) - assert root.exists() and downloads.exists() - assert list(Path(f'jeff-{release}-hdf5').iterdir()) == [] - - -@pytest.mark.parametrize('release', RELEASES) -@pytest.mark.parametrize('cleanup', [False, True]) -def test_download_extract_cleanup_conventions(release, cleanup, tmp_path, monkeypatch): - source = tmp_path / 'source' - neutron_path = neutron_file(source, release, '293') - thermal_path = thermal_file(source, release) - calls = [] - def download(url, *, as_browser, output_path, output_filename): - assert as_browser is True - assert url.endswith(f'/{output_filename}/content') - assert output_filename != 'content' - calls.append(url) - output_path.mkdir(exist_ok=True) - archive = output_path / output_filename - path = thermal_path if len(calls) == 2 else neutron_path - member = path.relative_to(source) - if release == '3.2' and path == neutron_path: - member = Path(path.name) # New 293 K archive is flat. - if output_filename.endswith('.zip'): - with zipfile.ZipFile(archive, 'w') as z: - z.write(path, str(member)) - else: - with tarfile.open(archive, 'w:gz') as t: - t.add(path, arcname=str(member)) - return archive - monkeypatch.setattr(converter, 'download', download) - with pytest.warns(UserWarning, match='multiple GB'): - converter.main(['-r', release, '-t', '293', '--cleanup' if cleanup else '--no-cleanup']) - assert len(calls) == 2 - assert root_for(release).exists() is not cleanup - assert Path(f'jeff-{release}-download').exists() is not cleanup - assert Path(f'jeff-{release}-hdf5/Ne20.h5').exists() - - -@pytest.mark.parametrize('release', RELEASES) -def test_missing_archive_fails(release): - with pytest.raises(FileNotFoundError): - converter.main(['-r', release, '-t', '600', '--no-download']) - - -def test_32_flat_cache_and_legacy_thermal(): - root = root_for('3.2') - path = neutron_file(root, '3.2', '293') - path.rename(root / path.name) - thermal = thermal_file(root, '3.2') - legacy = root / 'ANNEX_6_3_STLs' / 'H2O' / thermal.name - legacy.parent.mkdir(parents=True) - thermal.rename(legacy) - (root / 'ACEs_293K' / 'H2O-293.ACE').write_text('redundant') - converter.main(cached('3.2', '-t', '293')) - assert Path('jeff-3.2-hdf5/c_H_in_H2O.h5').exists() - - -def test_40_numeric_temperatures_and_uo2_twins(): - root = root_for('4.0') - for temp in ('0.1', '293', '300'): - neutron_file(root, '4.0', temp, 'H', 1) - for index, temp in enumerate((1201., 300., 301., 1200.)): - thermal_file(root, '4.0', temp, index, 'ouo2') - (root / 'data' / 'directory').write_text('ignore') - converter.main(cached('4.0', '-t', '300', '293', '0.1')) - data = openmc.data.IncidentNeutron.from_hdf5('jeff-4.0-hdf5/H1.h5') - assert data.temperatures == ['0K', '294K', '300K'] - data = openmc.data.ThermalScattering.from_hdf5('jeff-4.0-hdf5/c_O_in_UO2.h5') - assert sorted(kT / openmc.data.K_BOLTZMANN for kT in data.kTs) == pytest.approx([300, 301, 1200, 1201]) - - -@pytest.mark.parametrize('collision', ['neutron', 'thermal', 'rounded', 'existing', 'xml']) -def test_output_collisions(collision): - root = library('4.0') - path = neutron_file(root, '4.0', '600') - if collision == 'neutron': - duplicate = root / 'duplicate' / path.name - duplicate.parent.mkdir() - duplicate.write_bytes(path.read_bytes()) - elif collision == 'thermal': - thermal_file(root, '4.0', 600, 1, 'lwtr') - elif collision == 'rounded': - thermal_file(root, '4.0', 423.1, 1, 'hh2o') - else: - output = Path('jeff-4.0-hdf5') - output.mkdir() - (output / ('Ne20.h5' if collision == 'existing' else 'cross_sections.xml')).write_text('keep') - with pytest.raises((ValueError, FileExistsError), match='Duplicate|collision|overwrite'): - converter.main(cached('4.0', '-t', '600')) - - -def test_unknown_thermal_identity_not_fuzzy_matched(): - with pytest.warns(UserWarning, match='without fuzzy matching'): - assert converter._thermal_name('hh2onew') == 'c_hh2onew' - - -@pytest.mark.parametrize('field, expected', [('selected_cases', 12), ('selected_tables', 316)]) -def test_incomplete_40_subset_fails(field, expected): - library('4.0') - converter.all_release_details['jeff']['4.0']['thermal']['ace'][field] = expected - with pytest.raises(ValueError, match='Incomplete'): - converter.main(cached('4.0', '-t', '600')) - - -@pytest.mark.parametrize('release', RELEASES) -def test_destination_in_cache_rejected(release): - with pytest.raises(SystemExit, match='2'): - converter.main(cached(release, '--destination', str(root_for(release) / 'out'))) - - -@pytest.mark.parametrize('release', RELEASES) -@pytest.mark.parametrize('options, expected', [([], 'latest'), (['--libver', 'earliest'], 'earliest')]) -def test_hdf5_version(release, options, expected, monkeypatch): - library(release) - export = openmc.data.IncidentNeutron.export_to_hdf5 - versions = [] - def record(self, *args, **kwargs): - versions.append(kwargs['libver']) - return export(self, *args, **kwargs) - monkeypatch.setattr(openmc.data.IncidentNeutron, 'export_to_hdf5', record) - converter.main(cached(release, '-t', '600', *options)) - assert versions == [expected] - - -def test_import_safe_and_module_help(): - code = "import sys; sys.argv = ['unrelated', '--invalid']; import openmc_data.convert.convert_jeff" - # The fixture changes cwd; a relative PYTHONPATH would otherwise import an - # unrelated installed checkout in these child processes. - env = {**os.environ, 'PYTHONPATH': str(Path(converter.__file__).resolve().parents[2])} - subprocess.run([sys.executable, '-c', code], check=True, capture_output=True, text=True, env=env) - result = subprocess.run([sys.executable, '-m', 'openmc_data.convert.convert_jeff', '--help'], - check=True, capture_output=True, text=True, env=env) - assert '--temperatures' in result.stdout - - -def test_ace_catalog_integrity(): - from openmc_data.urls import all_release_details - for release in RELEASES: - sources = all_release_details['jeff'][release] - neutron = sources['neutron']['ace'] - assert len(neutron['compressed_files']) == len(neutron['temperatures']) - for source in sources.values(): - ace = source['ace'] - assert ace['base_url'].startswith('https://data.oecd-nea.org/api/records/') - assert ace['url_suffix'] == '/content' - assert ace['as_browser'] is True - assert 'JEFF32-ACE-800K.tar.gz' in all_release_details['jeff']['3.2']['neutron']['ace']['compressed_files'] - assert 'JEFF32-ACE-300K.tar.gz' in all_release_details['jeff']['3.2']['neutron']['ace']['compressed_files'] - subset = all_release_details['jeff']['4.0']['thermal']['ace'] - assert (subset['selected_cases'], subset['selected_tables']) == (12, 316) - - -def test_33_missing_material_does_not_reuse_previous_data(): - library('3.3') - converter.all_release_details['jeff']['3.3']['thermal']['ace']['required_file_groups'] = ['h-h2o', 'be'] - with pytest.raises(FileNotFoundError, match='thermal materials: be'): - converter.main(cached('3.3', '-t', '600')) - assert not Path('jeff-3.3-hdf5/cross_sections.xml').exists() - - -def test_33_thermal_prefixes_allow_phase_suffixes(): - root = root_for('3.3') - write_ace(root / 'ace_tsl/mesi-phii-20.ace', 'mesi.00t', 20) - write_ace(root / 'ace_tsl/tolue-phii-20.ace', 'tol.00t', 20) - details = {'ace_paths': ['ace_tsl/*.ace'], 'required_file_groups': ['mesi', 'tolu']} - groups = converter._thermal_groups(root, '3.3', details) - assert set(groups) == {'c_H_in_Mesitylene', 'c_H_in_Toluene'} - - -@pytest.mark.parametrize('release', RELEASES) -def test_download_without_extract_uses_cache(release, monkeypatch): - library(release) - downloads = [] - monkeypatch.setattr(converter, 'download', lambda *args, **kwargs: downloads.append(kwargs['output_filename'])) - def fail(*args, **kwargs): - pytest.fail('Extraction was disabled') - monkeypatch.setattr(converter, 'extract', fail) - with pytest.warns(UserWarning, match='multiple GB'): - converter.main(['-r', release, '-t', '600', '--download', '--no-extract']) - assert len(downloads) == 2 - - -def test_new_style_header(): - path = Path('modern.ace') - kT = 293.6 * openmc.data.K_BOLTZMANN / 1.e6 - path.write_text(f'2.0.0 1001.40c\n1.0 {kT} date 3\ncomment\n') - name, temperature = converter._header(path) - assert name == '1001.40c' - assert temperature == pytest.approx(293.6) - - -@pytest.mark.parametrize('problem', ['unsafe-name', 'lost-temperature', 'wrong-name']) -def test_output_safety_checks(problem, monkeypatch): - library('3.3', ('600', '900')) - if problem == 'unsafe-name': - monkeypatch.setattr(converter, '_thermal_name', lambda _: '../unsafe') - elif problem == 'lost-temperature': - monkeypatch.setattr(openmc.data.IncidentNeutron, 'add_temperature_from_ace', lambda *a, **k: None) - else: - read = openmc.data.IncidentNeutron.from_ace - def wrong(*args, **kwargs): - data = read(*args, **kwargs) - data.name = 'wrong' - return data - monkeypatch.setattr(openmc.data.IncidentNeutron, 'from_ace', wrong) - with pytest.raises(ValueError, match='Unsafe|lost temperatures|does not match'): - converter.main(cached('3.3', '-t', '600', '900')) - assert not Path('jeff-3.3-hdf5/cross_sections.xml').exists() \ No newline at end of file diff --git a/tests/test_utils.py b/tests/test_utils.py index 4ef8b4f..ddd8482 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,8 +1,4 @@ -import hashlib -import io -from pathlib import Path import tarfile -from unittest.mock import Mock import pytest @@ -33,79 +29,3 @@ def test_process_neutron_requires_openmc(): with pytest.raises(ModuleNotFoundError, match="openmc is required"): openmc_data.process_neutron("dummy.endf", "out", "latest") - - -class Response(io.BytesIO): - def __init__(self, payload, length): - super().__init__(payload) - self.length = length - self.read_sizes = [] - - def read(self, size=-1): - assert size == utils._BLOCK_SIZE, 'Download must use bounded reads' - self.read_sizes.append(size) - return super().read(size) - - -@pytest.mark.parametrize('known_length', [False, True]) -@pytest.mark.parametrize('existing', [False, True]) -def test_download_streaming_length_and_cache(tmp_path, monkeypatch, capsys, known_length, existing): - payload = b'x' * (2*utils._BLOCK_SIZE + 17) - response = Response(payload, len(payload) if known_length else None) - target = tmp_path / 'library.zip' - if existing: - target.write_bytes(b'o' * len(payload)) - urlopen = Mock(return_value=response) - monkeypatch.setattr(utils, 'urlopen', urlopen) - path = utils.download('https://example.invalid/library.zip/content', as_browser=True, - output_path=tmp_path, output_filename='library.zip', timeout=10) - assert path == target - assert urlopen.call_args.args[0].get_header('User-agent') == 'Mozilla/5.0' - assert urlopen.call_args.kwargs == {'timeout': 10} - if existing and known_length: - assert target.read_bytes() == b'o' * len(payload) - assert not response.read_sizes - else: - assert target.read_bytes() == payload - assert len(response.read_sizes) == 4 - output = capsys.readouterr().out - if not known_length: - assert 'bytes' in output and '%' not in output and 'Skipping' not in output - assert response.closed - - -@pytest.mark.parametrize('payload,length,cached,checksum_data,error', [ - (b'', None, None, None, None), (b'', 0, None, None, None), - (b'new', 3, b'partial', None, None), - (b'payload', None, None, b'payload', None), - (b'payload', None, None, b'wrong', 'MD5 checksum'), - (b'payload', 7, b'payload', b'payload', None), - (b'payload', 7, b'invalid', b'payload', None), - (b'partial', 100, None, None, 'Incomplete download'), -]) -def test_download_validation(tmp_path, monkeypatch, payload, length, cached, checksum_data, error): - target = tmp_path / 'file' - if cached is not None: - target.write_bytes(cached) - response = Response(payload, length) - monkeypatch.setattr(utils, 'urlopen', Mock(return_value=response)) - checksum = hashlib.md5(checksum_data).hexdigest() if checksum_data is not None else None - if error: - with pytest.raises(OSError, match=error): - utils.download('https://example.invalid/file', checksum=checksum, output_path=tmp_path) - else: - assert utils.download('https://example.invalid/file', checksum=checksum, - output_path=tmp_path).read_bytes() == payload - assert bool(response.read_sizes) is not (cached == payload) - assert response.closed - - -def test_checksum_uses_bounded_reads(tmp_path, monkeypatch): - payload = b'x' * (2*utils._BLOCK_SIZE + 17) - stream = Response(payload, len(payload)) - opened = Mock(return_value=stream) - monkeypatch.setattr(Path, 'open', opened) - assert utils._file_md5(tmp_path / 'file') == hashlib.md5(payload).hexdigest() - opened.assert_called_once_with('rb') - assert len(stream.read_sizes) == 4 - assert stream.closed