mirror of
https://github.com/openmc-dev/openmc.git
synced 2026-07-29 06:35:48 -04:00
Merge pull request #2191 from shimwell/adding_main_to_scripts
added main method to scripts
This commit is contained in:
commit
35f0203000
3 changed files with 226 additions and 195 deletions
|
|
@ -28,102 +28,126 @@ import openmc.data
|
|||
from openmc.data.ace import TableType
|
||||
|
||||
|
||||
class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter,
|
||||
argparse.RawDescriptionHelpFormatter):
|
||||
pass
|
||||
def ace_to_hdf5(destination, xsdir, xsdata, libraries, metastable, libver):
|
||||
|
||||
if not destination.is_dir():
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description=__doc__,
|
||||
formatter_class=CustomFormatter
|
||||
)
|
||||
parser.add_argument('libraries', nargs='*',
|
||||
help='ACE libraries to convert to HDF5')
|
||||
parser.add_argument('-d', '--destination', type=Path, default=Path.cwd(),
|
||||
help='Directory to create new library in')
|
||||
parser.add_argument('-m', '--metastable', choices=['mcnp', 'nndc'],
|
||||
default='nndc',
|
||||
help='How to interpret ZAIDs for metastable nuclides')
|
||||
parser.add_argument('--xsdir', help='MCNP xsdir file that lists '
|
||||
'ACE libraries')
|
||||
parser.add_argument('--xsdata', help='Serpent xsdata file that lists '
|
||||
'ACE libraries')
|
||||
parser.add_argument('--libver', choices=['earliest', 'latest'],
|
||||
default='earliest', help="Output HDF5 versioning. Use "
|
||||
"'earliest' for backwards compatibility or 'latest' for "
|
||||
"performance")
|
||||
args = parser.parse_args()
|
||||
ace_libraries = []
|
||||
if xsdir is not None:
|
||||
ace_libraries.extend(openmc.data.ace.get_libraries_from_xsdir(xsdir))
|
||||
elif xsdata is not None:
|
||||
ace_libraries.extend(openmc.data.ace.get_libraries_from_xsdata(xsdata))
|
||||
else:
|
||||
ace_libraries = [Path(lib) for lib in libraries]
|
||||
|
||||
if not args.destination.is_dir():
|
||||
args.destination.mkdir(parents=True, exist_ok=True)
|
||||
converted = {}
|
||||
library = openmc.data.DataLibrary()
|
||||
|
||||
ace_libraries = []
|
||||
if args.xsdir is not None:
|
||||
ace_libraries.extend(openmc.data.ace.get_libraries_from_xsdir(args.xsdir))
|
||||
elif args.xsdata is not None:
|
||||
ace_libraries.extend(openmc.data.ace.get_libraries_from_xsdata(args.xsdata))
|
||||
else:
|
||||
ace_libraries = [Path(lib) for lib in args.libraries]
|
||||
|
||||
converted = {}
|
||||
library = openmc.data.DataLibrary()
|
||||
|
||||
for path in ace_libraries:
|
||||
# Check that ACE library exists
|
||||
if not os.path.exists(path):
|
||||
warnings.warn("ACE library '{}' does not exist.".format(path))
|
||||
continue
|
||||
|
||||
lib = openmc.data.ace.Library(path)
|
||||
for table in lib.tables:
|
||||
# Check type of the ACE table and determine appropriate class /
|
||||
# conversion function
|
||||
if table.data_type == TableType.NEUTRON_CONTINUOUS:
|
||||
name = table.zaid
|
||||
cls = openmc.data.IncidentNeutron
|
||||
converter = partial(cls.from_ace, metastable_scheme=args.metastable)
|
||||
elif table.data_type == TableType.THERMAL_SCATTERING:
|
||||
# Adjust name to be the new thermal scattering name
|
||||
name = openmc.data.get_thermal_name(table.zaid)
|
||||
cls = openmc.data.ThermalScattering
|
||||
converter = cls.from_ace
|
||||
else:
|
||||
print("Can't convert ACE table {}".format(table.name))
|
||||
for path in ace_libraries:
|
||||
# Check that ACE library exists
|
||||
if not os.path.exists(path):
|
||||
warnings.warn(f"ACE library '{path}' does not exist.")
|
||||
continue
|
||||
|
||||
if name not in converted:
|
||||
try:
|
||||
data = converter(table)
|
||||
except Exception as e:
|
||||
print('Failed to convert {}: {}'.format(table.name, e))
|
||||
lib = openmc.data.ace.Library(path)
|
||||
for table in lib.tables:
|
||||
# Check type of the ACE table and determine appropriate class /
|
||||
# conversion function
|
||||
if table.data_type == TableType.NEUTRON_CONTINUOUS:
|
||||
name = table.zaid
|
||||
cls = openmc.data.IncidentNeutron
|
||||
converter = partial(cls.from_ace, metastable_scheme=metastable)
|
||||
elif table.data_type == TableType.THERMAL_SCATTERING:
|
||||
# Adjust name to be the new thermal scattering name
|
||||
name = openmc.data.get_thermal_name(table.zaid)
|
||||
cls = openmc.data.ThermalScattering
|
||||
converter = cls.from_ace
|
||||
else:
|
||||
print(f"Can't convert ACE table {table.name}")
|
||||
continue
|
||||
|
||||
print('Converting {} (ACE) to {} (HDF5)'.format(table.name, data.name))
|
||||
if name not in converted:
|
||||
try:
|
||||
data = converter(table)
|
||||
except Exception as e:
|
||||
print(f"Failed to convert {table.name}: {e}")
|
||||
continue
|
||||
|
||||
# Determine output filename
|
||||
outfile = args.destination / (data.name.replace('.', '_') + '.h5')
|
||||
data.export_to_hdf5(outfile, 'w', libver=args.libver)
|
||||
print(f"Converting {table.name} (ACE) to {data.name} (HDF5)")
|
||||
|
||||
# Register with library
|
||||
library.register_file(outfile)
|
||||
# Determine output filename
|
||||
outfile = destination / (data.name.replace(".", "_") + ".h5")
|
||||
data.export_to_hdf5(outfile, "w", libver=libver)
|
||||
|
||||
# Add nuclide to list
|
||||
converted[name] = outfile
|
||||
else:
|
||||
# Read existing HDF5 file
|
||||
data = cls.from_hdf5(converted[name])
|
||||
# Register with library
|
||||
library.register_file(outfile)
|
||||
|
||||
# Add data for new temperature
|
||||
try:
|
||||
print('Converting {} (ACE) to {} (HDF5)'
|
||||
.format(table.name, data.name))
|
||||
data.add_temperature_from_ace(table, args.metastable)
|
||||
except Exception as e:
|
||||
print('Failed to convert {}: {}'.format(table.name, e))
|
||||
continue
|
||||
# Add nuclide to list
|
||||
converted[name] = outfile
|
||||
else:
|
||||
# Read existing HDF5 file
|
||||
data = cls.from_hdf5(converted[name])
|
||||
|
||||
# Re-export
|
||||
data.export_to_hdf5(converted[name], 'w', libver=args.libver)
|
||||
# Add data for new temperature
|
||||
try:
|
||||
print(f"Converting {table.name} (ACE) to {data.name} (HDF5)")
|
||||
data.add_temperature_from_ace(table, metastable)
|
||||
except Exception as e:
|
||||
print(f"Failed to convert {table.name}: {e}")
|
||||
continue
|
||||
|
||||
# Write cross_sections.xml
|
||||
library.export_to_xml(args.destination / 'cross_sections.xml')
|
||||
# Re-export
|
||||
data.export_to_hdf5(converted[name], "w", libver=libver)
|
||||
|
||||
# Write cross_sections.xml
|
||||
library.export_to_xml(destination / "cross_sections.xml")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
class CustomFormatter(
|
||||
argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter
|
||||
):
|
||||
pass
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description=__doc__, formatter_class=CustomFormatter
|
||||
)
|
||||
parser.add_argument("libraries", nargs="*", help="ACE libraries to convert to HDF5")
|
||||
parser.add_argument(
|
||||
"-d",
|
||||
"--destination",
|
||||
type=Path,
|
||||
default=Path.cwd(),
|
||||
help="Directory to create new library in",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-m",
|
||||
"--metastable",
|
||||
choices=["mcnp", "nndc"],
|
||||
default="nndc",
|
||||
help="How to interpret ZAIDs for metastable nuclides",
|
||||
)
|
||||
parser.add_argument("--xsdir", help="MCNP xsdir file that lists " "ACE libraries")
|
||||
parser.add_argument(
|
||||
"--xsdata", help="Serpent xsdata file that lists " "ACE libraries"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--libver",
|
||||
choices=["earliest", "latest"],
|
||||
default="earliest",
|
||||
help="Output HDF5 versioning. Use "
|
||||
"'earliest' for backwards compatibility or 'latest' "
|
||||
"for performance",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
ace_to_hdf5(
|
||||
destination=args.destination,
|
||||
xsdir=args.xsdir,
|
||||
xsdata=args.xsdata,
|
||||
libraries=args.libraries,
|
||||
metastable=args.metastable,
|
||||
libver=args.libver,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -4,96 +4,99 @@ import os
|
|||
import sys
|
||||
import glob
|
||||
import lxml.etree as etree
|
||||
from subprocess import call
|
||||
from optparse import OptionParser
|
||||
|
||||
# Command line parsing
|
||||
parser = OptionParser()
|
||||
parser.add_option('-r', '--relaxng-path', dest='relaxng',
|
||||
help="Path to RelaxNG files.")
|
||||
parser.add_option('-i', '--input-path', dest='inputs', default=os.getcwd(),
|
||||
help="Path to OpenMC input files." )
|
||||
(options, args) = parser.parse_args()
|
||||
def validate_xml(inputs, relaxng):
|
||||
|
||||
# Colored output
|
||||
if sys.stdout.isatty():
|
||||
OK = '\033[92m'
|
||||
FAIL = '\033[91m'
|
||||
NOT_FOUND = '\033[93m'
|
||||
ENDC = '\033[0m'
|
||||
BOLD = '\033[1m'
|
||||
else:
|
||||
OK = ''
|
||||
FAIL = ''
|
||||
ENDC = ''
|
||||
BOLD = ''
|
||||
NOT_FOUND = ''
|
||||
|
||||
# Get absolute paths
|
||||
if options.relaxng is not None:
|
||||
relaxng_path = os.path.abspath(options.relaxng)
|
||||
if options.inputs is not None:
|
||||
inputs_path = os.path.abspath(options.inputs)
|
||||
|
||||
# Search for relaxng path if not set
|
||||
if options.relaxng is None:
|
||||
xml_validate_path = os.path.abspath(os.path.dirname(sys.argv[0]))
|
||||
if "bin" in xml_validate_path:
|
||||
relaxng_path = os.path.join(xml_validate_path, "..", "share", "relaxng")
|
||||
elif os.path.join("src", "utils") in xml_validate_path:
|
||||
relaxng_path = os.path.join(xml_validate_path, "..", "relaxng")
|
||||
# Colored output
|
||||
if sys.stdout.isatty():
|
||||
OK = '\033[92m'
|
||||
FAIL = '\033[91m'
|
||||
NOT_FOUND = '\033[93m'
|
||||
ENDC = '\033[0m'
|
||||
BOLD = '\033[1m'
|
||||
else:
|
||||
raise Exception("Set RelaxNG path with -r command line option.")
|
||||
if not os.path.exists(relaxng_path):
|
||||
raise Exception("RelaxNG path: {0} does not exist, set with -r "
|
||||
"command line option.".format(relaxng_path))
|
||||
OK = ''
|
||||
FAIL = ''
|
||||
ENDC = ''
|
||||
BOLD = ''
|
||||
NOT_FOUND = ''
|
||||
|
||||
# Make sure there are .rng files in RelaxNG path
|
||||
rng_files = glob.glob(os.path.join(relaxng_path, "*.rng"))
|
||||
if len(rng_files) == 0:
|
||||
raise Exception("No .rng files found in RelaxNG "
|
||||
"path: {0}.".format(relaxng_path))
|
||||
# Get absolute paths
|
||||
if relaxng is not None:
|
||||
relaxng_path = os.path.abspath(relaxng)
|
||||
if inputs is not None:
|
||||
inputs_path = os.path.abspath(inputs)
|
||||
|
||||
# Get list of xml input files
|
||||
xml_files = glob.glob(os.path.join(inputs_path, "*.xml"))
|
||||
if len(xml_files) == 0:
|
||||
raise Exception("No .xml files found at input path: {0}"
|
||||
".".format(inputs_path))
|
||||
# Search for relaxng path if not set
|
||||
if relaxng is None:
|
||||
xml_validate_path = os.path.abspath(os.path.dirname(sys.argv[0]))
|
||||
if "bin" in xml_validate_path:
|
||||
relaxng_path = os.path.join(xml_validate_path, "..", "share", "relaxng")
|
||||
elif os.path.join("src", "utils") in xml_validate_path:
|
||||
relaxng_path = os.path.join(xml_validate_path, "..", "relaxng")
|
||||
else:
|
||||
raise Exception("Set RelaxNG path with -r command line option.")
|
||||
if not os.path.exists(relaxng_path):
|
||||
raise Exception(f"RelaxNG path: {relaxng_path} does not exist, set "
|
||||
"with -r command line option.")
|
||||
|
||||
# Begin loop around input files
|
||||
for xml_file in xml_files:
|
||||
# Make sure there are .rng files in RelaxNG path
|
||||
rng_files = glob.glob(os.path.join(relaxng_path, "*.rng"))
|
||||
if len(rng_files) == 0:
|
||||
raise Exception(f"No .rng files found in RelaxNG path: {relaxng_path}.")
|
||||
|
||||
text = "Validating {0}".format(os.path.basename(xml_file))
|
||||
print(text + '.'*(30 - len(text)), end="")
|
||||
# Get list of xml input files
|
||||
xml_files = glob.glob(os.path.join(inputs_path, "*.xml"))
|
||||
if len(xml_files) == 0:
|
||||
raise Exception(f"No .xml files found at input path: {inputs_path}.")
|
||||
|
||||
# Validate the XML file
|
||||
try:
|
||||
xml_tree = etree.parse(xml_file)
|
||||
except etree.XMLSyntaxError as e:
|
||||
print(BOLD + FAIL + '[XML ERROR]' + ENDC)
|
||||
print(" {0}".format(e))
|
||||
continue
|
||||
# Begin loop around input files
|
||||
for xml_file in xml_files:
|
||||
|
||||
# Get xml_filename prefix
|
||||
xml_prefix = os.path.basename(xml_file)
|
||||
xml_prefix = xml_prefix.split(".")[0]
|
||||
text = f"Validating {os.path.basename(xml_file)}"
|
||||
print(text + '.'*(30 - len(text)), end="")
|
||||
|
||||
# Search for rng file
|
||||
rng_file = os.path.join(relaxng_path, xml_prefix + ".rng")
|
||||
if rng_file in rng_files:
|
||||
|
||||
# read in RelaxNG
|
||||
relaxng_doc = etree.parse(rng_file)
|
||||
relaxng = etree.RelaxNG(relaxng_doc)
|
||||
|
||||
# validate xml file again RelaxNG
|
||||
# Validate the XML file
|
||||
try:
|
||||
relaxng.assertValid(xml_tree)
|
||||
print(BOLD + OK + '[VALID]' + ENDC)
|
||||
except (etree.DocumentInvalid, TypeError) as e:
|
||||
print(BOLD + FAIL + '[NOT VALID]' + ENDC)
|
||||
print(" {0}".format(e))
|
||||
xml_tree = etree.parse(xml_file)
|
||||
except etree.XMLSyntaxError as e:
|
||||
print(BOLD + FAIL + '[XML ERROR]' + ENDC)
|
||||
print(f" {e}")
|
||||
continue
|
||||
|
||||
# RNG file does not exist
|
||||
else:
|
||||
print(BOLD + NOT_FOUND + '[NO RELAXNG FOUND]' + ENDC)
|
||||
# Get xml_filename prefix
|
||||
xml_prefix = os.path.basename(xml_file)
|
||||
xml_prefix = xml_prefix.split(".")[0]
|
||||
|
||||
# Search for rng file
|
||||
rng_file = os.path.join(relaxng_path, xml_prefix + ".rng")
|
||||
if rng_file in rng_files:
|
||||
|
||||
# read in RelaxNG
|
||||
relaxng_doc = etree.parse(rng_file)
|
||||
relaxng = etree.RelaxNG(relaxng_doc)
|
||||
|
||||
# validate xml file again RelaxNG
|
||||
try:
|
||||
relaxng.assertValid(xml_tree)
|
||||
print(BOLD + OK + '[VALID]' + ENDC)
|
||||
except (etree.DocumentInvalid, TypeError) as e:
|
||||
print(BOLD + FAIL + '[NOT VALID]' + ENDC)
|
||||
print(f" {e}")
|
||||
|
||||
# RNG file does not exist
|
||||
else:
|
||||
print(BOLD + NOT_FOUND + '[NO RELAXNG FOUND]' + ENDC)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Command line parsing
|
||||
parser = OptionParser()
|
||||
parser.add_option('-r', '--relaxng-path', dest='relaxng',
|
||||
help="Path to RelaxNG files.")
|
||||
parser.add_option('-i', '--input-path', dest='inputs', default=os.getcwd(),
|
||||
help="Path to OpenMC input files." )
|
||||
(options, args) = parser.parse_args()
|
||||
|
||||
validate_xml(inputs=options.inputs, relaxng=options.relaxng)
|
||||
|
|
|
|||
|
|
@ -1,54 +1,46 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import struct
|
||||
import sys
|
||||
from argparse import ArgumentParser
|
||||
|
||||
import numpy as np
|
||||
import h5py
|
||||
import vtk
|
||||
|
||||
_min_version = (2, 0)
|
||||
|
||||
|
||||
def main():
|
||||
# Process command line arguments
|
||||
parser = ArgumentParser()
|
||||
parser.add_argument('voxel_file', help='Path to voxel file')
|
||||
parser.add_argument('-o', '--output', action='store',
|
||||
default='plot', help='Path to output VTK file.')
|
||||
args = parser.parse_args()
|
||||
def voxel_to_vtk(voxel_file: str, output: str):
|
||||
|
||||
# Read data from voxel file
|
||||
fh = h5py.File(args.voxel_file, 'r')
|
||||
fh = h5py.File(voxel_file, "r")
|
||||
|
||||
# check version
|
||||
version = tuple(fh.attrs['version'])
|
||||
version = tuple(fh.attrs["version"])
|
||||
if version < _min_version:
|
||||
old_version = ".".join(map(str,version))
|
||||
min_version = ".".join(map(str,_min_version))
|
||||
err_msg = "This voxel file's version is {}. This script " \
|
||||
"only supports voxel files with version {} or " \
|
||||
"higher. Please generate a new voxel file using " \
|
||||
"a newer version of OpenMC.".format(old_version, min_version)
|
||||
old_version = ".".join(map(str, version))
|
||||
min_version = ".".join(map(str, _min_version))
|
||||
err_msg = (
|
||||
"This voxel file's version is {}. This script "
|
||||
"only supports voxel files with version {} or "
|
||||
"higher. Please generate a new voxel file using "
|
||||
"a newer version of OpenMC.".format(old_version, min_version)
|
||||
)
|
||||
raise ValueError(err_msg)
|
||||
|
||||
dimension = fh.attrs['num_voxels']
|
||||
width = fh.attrs['voxel_width']
|
||||
lower_left = fh.attrs['lower_left']
|
||||
dimension = fh.attrs["num_voxels"]
|
||||
width = fh.attrs["voxel_width"]
|
||||
lower_left = fh.attrs["lower_left"]
|
||||
|
||||
nx, ny, nz = dimension
|
||||
upper_right = lower_left + width*dimension
|
||||
|
||||
grid = vtk.vtkImageData()
|
||||
grid.SetDimensions(nx+1, ny+1, nz+1)
|
||||
grid.SetDimensions(nx + 1, ny + 1, nz + 1)
|
||||
grid.SetOrigin(*lower_left)
|
||||
grid.SetSpacing(*width)
|
||||
|
||||
# transpose data from OpenMC ordering (zyx) to VTK ordering (xyz)
|
||||
# and flatten to 1-D array
|
||||
print("Reading and translating data...")
|
||||
h5data = fh['data'][...]
|
||||
h5data = fh["data"][...]
|
||||
|
||||
data = vtk.vtkIntArray()
|
||||
data.SetName("id")
|
||||
|
|
@ -62,11 +54,23 @@ def main():
|
|||
writer.SetInputData(grid)
|
||||
else:
|
||||
writer.SetInput(grid)
|
||||
if not args.output.endswith(".vti"):
|
||||
args.output += ".vti"
|
||||
writer.SetFileName(args.output)
|
||||
print("Writing VTK file {}...".format(args.output))
|
||||
if not output.endswith(".vti"):
|
||||
output += ".vti"
|
||||
writer.SetFileName(output)
|
||||
print("Writing VTK file {}...".format(output))
|
||||
writer.Write()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Process command line arguments
|
||||
parser = ArgumentParser('Converts a voxel HDF5 file to a VTK file')
|
||||
parser.add_argument("voxel_file", help="Path to voxel h5 file")
|
||||
parser.add_argument(
|
||||
"-o",
|
||||
"--output",
|
||||
action="store",
|
||||
default="plot",
|
||||
help="Path to output VTK file.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
voxel_to_vtk(args.voxel_file, args.output)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue