diff --git a/.github/workflows/test_package.yml b/.github/workflows/test_package.yml index 9fbbfa5..0486546 100644 --- a/.github/workflows/test_package.yml +++ b/.github/workflows/test_package.yml @@ -51,8 +51,7 @@ jobs: - name: Test convert scripts exist run: | convert_fendl --help - convert_jeff32 --help - convert_jeff33 --help + convert_jeff --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..35f814c 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 @@ -58,17 +57,10 @@ 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' + run: convert_jeff -t 293 --cleanup - name: test default convert_endf if: inputs.script == 'convert_endf' diff --git a/README.md b/README.md index 609d98d..3b4fefa 100644 --- a/README.md +++ b/README.md @@ -89,10 +89,36 @@ 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 -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) | +| --- | --- | +| 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 | + +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. + +See `convert_jeff --help` for all options. + ### Generate cross sections | Script name | Library | Release | Processed by | @@ -122,8 +148,6 @@ A few categories of scripts are available: |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 942fab3..6c576c3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -61,8 +61,7 @@ include-package-data = false [project.scripts] convert_fendl = "openmc_data.convert.convert_fendl:main" -convert_jeff32 = "openmc_data.convert.convert_jeff32:main" -convert_jeff33 = "openmc_data.convert.convert_jeff33:main" +convert_jeff = "openmc_data.convert.convert_jeff: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 new file mode 100644 index 0000000..5d86c46 --- /dev/null +++ b/src/openmc_data/convert/convert_jeff.py @@ -0,0 +1,306 @@ +#!/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(): + choices = '; '.join( + f"{release}: {', '.join(all_release_details['jeff'][release]['neutron']['ace']['temperatures'])}" + 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=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="latest") + 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}", 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()}") + return parser + + +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"] + 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) + + +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 10c6386..0000000 --- a/src/openmc_data/convert/convert_jeff32.py +++ /dev/null @@ -1,266 +0,0 @@ -#!/usr/bin/env python3 - -""" -Download JEFF 3.2 ACE data from OECD/NEA and convert it to a multi-temperature -HDF5 library for use with OpenMC. -""" - -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") - - -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 05041a3..0000000 --- a/src/openmc_data/convert/convert_jeff33.py +++ /dev/null @@ -1,228 +0,0 @@ -#!/usr/bin/env python - -""" -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. -""" - -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") - - -if __name__ == "__main__": - 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 "