| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
################################################################################ |
| 4 |
## ## |
| 5 |
## This file is part of NCrystal (see https://mctools.github.io/ncrystal/) ## |
| 6 |
## ## |
| 7 |
## Copyright 2015-2022 NCrystal developers ## |
| 8 |
## ## |
| 9 |
## Licensed under the Apache License, Version 2.0 (the "License"); ## |
| 10 |
## you may not use this file except in compliance with the License. ## |
| 11 |
## You may obtain a copy of the License at ## |
| 12 |
## ## |
| 13 |
## http://www.apache.org/licenses/LICENSE-2.0 ## |
| 14 |
## ## |
| 15 |
## Unless required by applicable law or agreed to in writing, software ## |
| 16 |
## distributed under the License is distributed on an "AS IS" BASIS, ## |
| 17 |
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## |
| 18 |
## See the License for the specific language governing permissions and ## |
| 19 |
## limitations under the License. ## |
| 20 |
## ## |
| 21 |
################################################################################ |
| 22 |
|
| 23 |
"""Script for extracting neutron scattering kernels from ENDF files and creating |
| 24 |
corresponding .ncmat files. The created files might need a bit of manual editing |
| 25 |
after creation, to correct the dummy material densities inserted, or (for |
| 26 |
crystalline materials) to remove the densities and instead add sections with |
| 27 |
information about crystal structure. For materials based on more than one |
| 28 |
scattering kernel (e.g. heavy water, D2O, where S(alpha,beta) tables are needed |
| 29 |
for both atoms), it might be necessary to manually combine two resulting files |
| 30 |
into one. |
| 31 |
|
| 32 |
Input files are read with the Python Nuclear Engineering Toolkit |
| 33 |
(http://pyne.io/), which must be first installed. |
| 34 |
|
| 35 |
Input files can for instance be downloaded from: |
| 36 |
|
| 37 |
https://www.nndc.bnl.gov/endf/b8.0/download.html |
| 38 |
|
| 39 |
(download and open zip-file from the "Thermal Neutron Scattering Sublibrary") |
| 40 |
""" |
| 41 |
|
| 42 |
################################################################################################ |
| 43 |
####### Common code for all NCrystal cmdline scripts needing to import NCrystal modules ######## |
| 44 |
import sys |
| 45 |
pyversion = sys.version_info[0:3] |
| 46 |
_minpyversion=(3,6,0) |
| 47 |
if pyversion < _minpyversion: |
| 48 |
raise SystemExit('Unsupported python version %i.%i.%i detected (needs %i.%i.%i or later).'%(pyversion+_minpyversion)) |
| 49 |
import os |
| 50 |
import pathlib |
| 51 |
|
| 52 |
def maybeThisIsConda(): |
| 53 |
return ( os.environ.get('CONDA_PREFIX',None) or |
| 54 |
os.path.exists(os.path.join(sys.base_prefix, 'conda-meta')) ) |
| 55 |
|
| 56 |
def fixSysPathAndImportNCrystal( *, allowfail = False ): |
| 57 |
thisdir = pathlib.Path( __file__ ).parent |
| 58 |
def extract_cmake_pymodloc(): |
| 59 |
p = thisdir / 'ncrystal-config' |
| 60 |
if not p.exists(): |
| 61 |
return |
| 62 |
with p.open('rt') as fh: |
| 63 |
for i,l in enumerate(fh): |
| 64 |
if i==30: |
| 65 |
break |
| 66 |
if l.startswith('#CMAKE_RELPATH_TO_PYMOD:'): |
| 67 |
l = l[24:].strip() |
| 68 |
return ( thisdir / l ) if l else None |
| 69 |
pml = extract_cmake_pymodloc() |
| 70 |
hack_syspath = pml and ( pml / 'NCrystal' / '__init__.py' ).exists() |
| 71 |
if hack_syspath: |
| 72 |
sys.path.insert(0,str(pml.absolute().resolve())) |
| 73 |
try: |
| 74 |
import NCrystal |
| 75 |
except ImportError: |
| 76 |
if allowfail: |
| 77 |
return |
| 78 |
msg = 'ERROR: Could not import the NCrystal Python module' |
| 79 |
if maybeThisIsConda(): |
| 80 |
msg += ' (if using conda it might help to close your terminal and activate your environment again)' |
| 81 |
elif not hack_syspath: |
| 82 |
msg += ' (perhaps your PYTHONPATH is misconfigured)' |
| 83 |
raise SystemExit(msg) |
| 84 |
return NCrystal |
| 85 |
################################################################################################ |
| 86 |
NC = fixSysPathAndImportNCrystal() |
| 87 |
|
| 88 |
import warnings |
| 89 |
import argparse |
| 90 |
|
| 91 |
__pynecache=[None] |
| 92 |
def import_pyne(): |
| 93 |
global __pynecache |
| 94 |
if __pynecache[0] is not None: |
| 95 |
return __pynecache[0] |
| 96 |
|
| 97 |
try: |
| 98 |
with warnings.catch_warnings(): |
| 99 |
warnings.simplefilter("ignore")#silence annoying pyne.endf QAWarning's. |
| 100 |
import pyne.endf |
| 101 |
except ImportError: |
| 102 |
raise SystemExit('ERROR: Could not "import pyne.endf". You probably need to install PyNE (see http://pyne.io/)') |
| 103 |
|
| 104 |
#Monkey-patch pyne.endf reader, which was ignoring optional sections with teff |
| 105 |
#curves of non-principal atoms (see |
| 106 |
#https://github.com/pyne/pyne/issues/1209). The fix was accepted upstream, so |
| 107 |
#eventually we can remove this monkey-patching once we think all users will have |
| 108 |
#recent enough PyNE installations: |
| 109 |
_orig_rti = pyne.endf.Evaluation._read_thermal_inelastic |
| 110 |
def _fix_rti(_self): |
| 111 |
_orig_rti(_self) |
| 112 |
inel=_self.thermal_inelastic |
| 113 |
B=inel['B'] |
| 114 |
for ii in range(len(B)//6-1): |
| 115 |
if B[6*(ii+1)]==0.0: |
| 116 |
if 'teff_%i'%(ii+1) in inel: |
| 117 |
#If upstream already includes fix, do nothing. |
| 118 |
continue |
| 119 |
_, teff = _self._get_tab1_record() |
| 120 |
inel['teff_%i'%(ii+1)] = teff#Store as teff_1, teff_2, etc. for now. |
| 121 |
pyne.endf.Evaluation._read_thermal_inelastic=_fix_rti |
| 122 |
__pynecache[0] = pyne |
| 123 |
return pyne |
| 124 |
|
| 125 |
def elementZToName(z): |
| 126 |
d = NCrystal.atomDB(z,throwOnErrors=False) |
| 127 |
return d.elementName() if d else None |
| 128 |
|
| 129 |
def guessElementFromMass(mass_amu): |
| 130 |
elem_data=[ (abs(d.averageMassAMU()-mass_amu),d) for d in [NCrystal.atomDB(z,throwOnErrors=False) for z in range(1,120)] if d ] |
| 131 |
elem_data.sort() |
| 132 |
print (f'Guessing mass={mass_amu:.8}u is element {elem_data[0][1].elementName()}') |
| 133 |
return elem_data[0][1].elementName() |
| 134 |
|
| 135 |
def guessElementName(ZA,mass_amu): |
| 136 |
Z=ZA//1000 |
| 137 |
if ZA==155: |
| 138 |
return 'Y'#YH2, whatever it is |
| 139 |
if ZA==140: |
| 140 |
return 'H'#benzene... C6H6. Guessing H is dominant. But tsl-benzene.endf is actually a compound SAB... |
| 141 |
if ZA==1002: |
| 142 |
return 'D' |
| 143 |
if ZA in (133,134): |
| 144 |
return 'H'#solid or liquid methane (CH4 happens to have mass 12+1*4=16 close to oxygen, so can't guess from mass) |
| 145 |
if ZA in (112,113): |
| 146 |
return 'D'#ortho-D or para-D |
| 147 |
guess_by_mass = guessElementFromMass(mass_amu) |
| 148 |
guess_by_z = elementZToName(Z) if (Z>0 and Z<120) else None |
| 149 |
if guess_by_z: |
| 150 |
if guess_by_z!=guess_by_mass: |
| 151 |
raise SystemExit(f"ERROR: Mass and Z guess gives different element name (Z={Z}=>'{guess_by_z}', mass={mass_amu}amu=>'{guess_by_mass}')") |
| 152 |
return guess_by_z |
| 153 |
if Z==0: |
| 154 |
return guess_by_mass |
| 155 |
raise ValueError(f'Could not determine element name from ZA={ZA}, mass={mass_amu}amu') |
| 156 |
|
| 157 |
#Custom bare-bones reader, so we can extract the data header as-is in the file: |
| 158 |
def parse_endf6(src,name=None,selectfct=None): |
| 159 |
"""Parse TSL data from ENDF-6 file according to ENDF manual. Select function can |
| 160 |
used to determine which mat,mf,mt lines to read. E.g. "selectfct=lambda |
| 161 |
mat,mf,mt:mf==7". Remember to select (mf,mt)=(1,451) for the description at |
| 162 |
the start of each material. |
| 163 |
|
| 164 |
""" |
| 165 |
if isinstance(src,str) or isinstance(src,bytes) or hasattr(src,'__fspath__'): |
| 166 |
p=pathlib.Path(src).expanduser() |
| 167 |
with p.open('rt') as srcstream: |
| 168 |
return parse_endf6(srcstream,name=p.name) |
| 169 |
#according to the manual section 0.6, each line is broken down as follows: |
| 170 |
#Columns 1-66 content, 67-70 MAT number, 71-72 MF, 73-75 MT, 76-80 [optional] NS, 81+ undefined |
| 171 |
#Content can either be one 66 char long text field, or there are 6 fields of 11 chars. |
| 172 |
|
| 173 |
errprefix = '' if not name else f'in {name}' |
| 174 |
def require(check,errmsg): |
| 175 |
if not check: |
| 176 |
raise ValueError(f'{errprefix}: {errmsg}') |
| 177 |
|
| 178 |
def parse_endf6_line(l): |
| 179 |
require(len(l)>=75,"line too short") |
| 180 |
content=l[0:66] |
| 181 |
mat=int(l[66:70]) |
| 182 |
mf=int(l[70:72]) |
| 183 |
mt=int(l[72:75]) |
| 184 |
return (content,mat,mf,mt) |
| 185 |
|
| 186 |
content,mat,mf,mt = parse_endf6_line(next(src)) |
| 187 |
require((mat,mf,mt)==(1,0,0),'Not an ENDF-6 file?') |
| 188 |
global_header=content |
| 189 |
d={}#material -> material info |
| 190 |
for l in src: |
| 191 |
#print(l) |
| 192 |
content,mat,mf,mt = parse_endf6_line(l) |
| 193 |
if mat<1: |
| 194 |
continue#Ignore dummy lines (section dividers, etc.) |
| 195 |
if selectfct and not selectfct(mat,mf,mt): |
| 196 |
continue |
| 197 |
if not mat in d: |
| 198 |
d[mat]=dict() |
| 199 |
dd=d[mat] |
| 200 |
if not mf in dd: |
| 201 |
dd[mf]={} |
| 202 |
ddd=dd[mf] |
| 203 |
if not mt in ddd: |
| 204 |
ddd[mt]=[content] |
| 205 |
else: |
| 206 |
ddd[mt]+=[content] |
| 207 |
return dict(global_header=global_header,name=name),d |
| 208 |
|
| 209 |
def extract_and_format_endf_file_header(filename): |
| 210 |
custom_parse = parse_endf6(filename,selectfct=lambda mat,mf,mt : (mf,mt)==(1,451)) |
| 211 |
mats=custom_parse[1] |
| 212 |
assert len(mats)==1,("File contains more than one material number which is not supported by the" |
| 213 |
+" present script (please contact NCrystal developers if you really need this).") |
| 214 |
material_number,material_info = next(iter(mats.items())) |
| 215 |
return dict( filename = custom_parse[0]['name'], |
| 216 |
material_number = material_number, |
| 217 |
global_header = custom_parse[0]['global_header'], |
| 218 |
infosection=material_info[1][451] ) |
| 219 |
|
| 220 |
def parse_endf_file(filename): |
| 221 |
print(f"Attempting to load ENDF file {filename}...") |
| 222 |
result={} |
| 223 |
warnings_=[] |
| 224 |
pyne = import_pyne() |
| 225 |
data=pyne.endf.Evaluation(filename) |
| 226 |
data.read() |
| 227 |
result['input_file']=pathlib.Path(filename) |
| 228 |
result['pynedata']=data |
| 229 |
print('Performing a few sanity checks...') |
| 230 |
if not hasattr(data,'thermal_inelastic') or not 'B' in data.thermal_inelastic or not 'scattering_law' in data.thermal_inelastic: |
| 231 |
raise SystemExit('Error: File does not appear to contain any inelastic neutron scattering kernel.') |
| 232 |
|
| 233 |
ti=data.thermal_inelastic |
| 234 |
|
| 235 |
if ti['ln(S)']: |
| 236 |
raise SystemExit('The ln(S) flag is enabled. For the reasons given in the ENDF manual just before' |
| 237 |
+'section 7.4.1, it is not safe to simple convert these to S-values. We need ncmat to support a logsab_scaled option first.' |
| 238 |
+' Another (easier?) alternative would be to use mpmath module here and calculate unscaled S-values and produce an ncmat file with S=...') |
| 239 |
|
| 240 |
assert ti['temperature_used'] in ('actual','0.0253 eV') |
| 241 |
if ti['temperature_used'].strip()=='actual': |
| 242 |
alphabetagrid_T0=None |
| 243 |
else: |
| 244 |
alphabetagrid_T0 = float(ti['temperature_used'].split('eV',1)[0].strip())/NCrystal.constant_boltzmann#Must stretch betagrid values relative to this |
| 245 |
|
| 246 |
#print(data.target) |
| 247 |
element_name=guessElementName(data.target['ZA'],data.target['mass']) |
| 248 |
zsymam=data.target['zsymam'].strip() |
| 249 |
if not zsymam in ['s-ch4','l-ch4','ortho-d','para-d','BENZINE'] and not 'graphit' in zsymam.lower(): |
| 250 |
assert element_name in zsymam,f"{element_name} not in {zsymam}" |
| 251 |
result['element_name_principal']=element_name |
| 252 |
|
| 253 |
lenB = len(ti['B']) |
| 254 |
B = [None] + list(ti['B'])#B-array, with fortran indexing (for easier reference with ENDF manual): |
| 255 |
A0 = float(B[3]) #Needed to unscale |
| 256 |
if B[1]==0.0: |
| 257 |
raise SystemExit('Material has no principal scatterers - thus no S(alpha,beta)') |
| 258 |
suggested_emax = B[4]#In principle... but in practice not sure if this holds! Also, data.info['energy_max'] gives a different number (5.0)?!? |
| 259 |
count_principal = B[6] |
| 260 |
num_non_principal = ti['num_non_principal'] |
| 261 |
|
| 262 |
non_principal_data = [] |
| 263 |
for i in range(num_non_principal): |
| 264 |
offset = 6*(i+1) |
| 265 |
assert lenB >= 6*(i+2) |
| 266 |
a1=B[offset+1]#0.0: SCT (short collision time approx), 1.0: free-gas, 2.0: diffusive motion. |
| 267 |
if a1!=1.0: |
| 268 |
warnings_+=['WARNING: A non-free-gas model is proposed for the first non-principal atom'] |
| 269 |
warnings_+=[' in the original file. This is currently not handled by NCrystal.'] |
| 270 |
print(warnings_[-2]) |
| 271 |
print(warnings_[-1]) |
| 272 |
effective_mass = B[offset+3]#mass in units of neutron mass |
| 273 |
count = B[offset+6]#count per molecule or unit cell |
| 274 |
theElementName = guessElementFromMass(effective_mass*NCrystal.const_neutron_mass_amu) |
| 275 |
non_principal_data+=[[theElementName,count,effective_mass]] |
| 276 |
|
| 277 |
count_total = count_principal + sum(count_ for elemname,count_,effmass in non_principal_data) |
| 278 |
format_fraction = lambda c,ctot : f'{c:.14g}/{ctot:.14g}' if c!=ctot else '1' |
| 279 |
for e in non_principal_data: |
| 280 |
elementName,thecount,effective_mass=e |
| 281 |
e += [format_fraction(thecount,count_total)] |
| 282 |
|
| 283 |
header = extract_and_format_endf_file_header(filename) |
| 284 |
result['header']=header |
| 285 |
result['warnings']=warnings_ |
| 286 |
result['non_principal_data']=non_principal_data |
| 287 |
result['count_total']=count_total |
| 288 |
result['count_principal']=count_principal |
| 289 |
result['fraction_str_principal']=format_fraction(count_principal,count_total) |
| 290 |
result['suggested_emax']=suggested_emax |
| 291 |
|
| 292 |
ndatablock = len(ti['teff'].x) |
| 293 |
result_datablocks=[] |
| 294 |
result['result_datablocks'] = result_datablocks |
| 295 |
for idatablock in range(ndatablock): |
| 296 |
result_datablock={} |
| 297 |
result_datablocks += [result_datablock] |
| 298 |
temperature=ti['teff'].x[idatablock] |
| 299 |
temperature_effective=ti['teff'].y[idatablock] |
| 300 |
result_datablock['T']=temperature |
| 301 |
result_datablock['Teff']=temperature_effective |
| 302 |
sabt=ti['scattering_law'][:,:,idatablock] #indexing t,a,b |
| 303 |
sab=sabt.T |
| 304 |
result_datablock['sab']=sab |
| 305 |
#We must .copy() alpha/beta grids due to '*=' operators below: |
| 306 |
alphagrid = ti['alpha'].copy()*A0#undo funny ENDF alpha definition which divides by A0 |
| 307 |
betagrid = ti['beta'].copy() |
| 308 |
if alphabetagrid_T0 is not None: |
| 309 |
#Undo funny ENDF scaling of grids at each temperature |
| 310 |
betagrid *= (alphabetagrid_T0/temperature) |
| 311 |
alphagrid *= (alphabetagrid_T0/temperature) |
| 312 |
result_datablock['alphagrid']=alphagrid.copy() |
| 313 |
result_datablock['betagrid']=betagrid.copy() |
| 314 |
|
| 315 |
assert ti['symmetric'] == bool(betagrid[0]>=0.0),"inconsistencies detected" |
| 316 |
|
| 317 |
warningsfmt='' |
| 318 |
if warnings_: |
| 319 |
warningsfmt='{}\n#'.format('\n# ----> '.join(['']+warnings_)) |
| 320 |
return result |
| 321 |
|
| 322 |
def format_endf_block_as_ncmatdyninfo_for_principal_element(parsed_endf_data,temperature,fraction_str=None): |
| 323 |
elem_name = parsed_endf_data["element_name_principal"] |
| 324 |
|
| 325 |
#Find block by temperature: |
| 326 |
temperature_exact,block_idx = list(sorted((abs(temperature-_["T"]),_["T"],idx) for idx,_ in enumerate(parsed_endf_data['result_datablocks'])))[0][1:] |
| 327 |
assert abs(temperature_exact-temperature)<1e-6 |
| 328 |
temperature=temperature_exact |
| 329 |
|
| 330 |
res = '@DYNINFO\n' |
| 331 |
res += f" # Scattering kernel for {elem_name} @ {temperature}K extracted from {parsed_endf_data['input_file'].name}\n" |
| 332 |
for w in parsed_endf_data['warnings']: |
| 333 |
res += f'\n # ----> {w}' |
| 334 |
res += ' #\n' |
| 335 |
res += ' # For reference the description embedded in input ENDF file (section MF1,MT451) is repeated here:\n' |
| 336 |
res += ' #\n' |
| 337 |
header=parsed_endf_data['header'] |
| 338 |
for l in [header['global_header']]+header['infosection']: |
| 339 |
res+=f' # --->{(" "+l).rstrip()}\n' |
| 340 |
|
| 341 |
datablock = parsed_endf_data['result_datablocks'][block_idx] |
| 342 |
res+=f' element {elem_name}\n' |
| 343 |
if fraction_str is None: |
| 344 |
fraction_str = parsed_endf_data["fraction_str_principal"] |
| 345 |
else: |
| 346 |
assert parsed_endf_data["fraction_str_principal"]=='1' |
| 347 |
res+=f' fraction {fraction_str}\n' |
| 348 |
res +=' type scatknl\n' |
| 349 |
res+=f' temperature {temperature:.10} #NB: ENDF file specified "effective temperature" as {datablock["Teff"]:.10}K\n' |
| 350 |
#NB: Not suggesting an emax value, since it seems to be unreliable! Same for B[4] from above... |
| 351 |
#res+=f" egrid {parsed_endf_data['pynedata'].info['energy_max']}#Value (in eV) as specified in source ENDF file.\n"#argh... e.g. D2O@300K shows this can't be trusted!!! |
| 352 |
res += NCrystal.formatVectorForNCMAT('alphagrid',datablock['alphagrid']) |
| 353 |
res += NCrystal.formatVectorForNCMAT('betagrid',datablock['betagrid']) |
| 354 |
res += NCrystal.formatVectorForNCMAT('sab_scaled',datablock['sab']) |
| 355 |
return res |
| 356 |
|
| 357 |
def _parseArgs(): |
| 358 |
descr=""" |
| 359 |
Converts neutron scattering kernels ("thermal scattering laws, tsl") found in |
| 360 |
ENDF files to NCMAT format (specifically @DYNINFO sections of NCMAT files). |
| 361 |
|
| 362 |
Note that this script exists for the benefit of experts only. Most users are |
| 363 |
recommended to simply download and use one of the pre-converted files shipped |
| 364 |
with NCrystal or found at: |
| 365 |
|
| 366 |
https://github.com/mctools/ncrystal-extra/tree/master/data |
| 367 |
|
| 368 |
Only information for NCMAT @DYNINFO sections are extracted from ENDF files, so |
| 369 |
it is recommended to provide the initial parts of the target NCMAT file in a |
| 370 |
separate file specified via the --filehdr parameter. That file should include |
| 371 |
both initial comments for the file as well as either @DENSITY or |
| 372 |
@CELL/@SPACEGROUP/@ATOMPOSITIONS/@DEBYETEMPERATUE sections, depending on whether |
| 373 |
or not the material is crystalline. Note that comments describing the origin of |
| 374 |
the @DYNINFO sections extracted from the ENDF files will be inserted in the |
| 375 |
relevant @DYNINFO sections. The --filehdr should include the string |
| 376 |
'<<STDNOTICE>>' on a separate line, which will be expanded to a notice about |
| 377 |
availability of files for other temperatures. |
| 378 |
|
| 379 |
If the --filehdr argument is not provided, a dummy header will be |
| 380 |
automatically generated, with a fake @DENSITY section, using the density of |
| 381 |
water (1g/cm3). This allows the file to be technically valid, but will of |
| 382 |
course result in incorrect physics in case the file is used for simulations. |
| 383 |
|
| 384 |
As each ENDF file contains a list of temperatures for which scattering kernels |
| 385 |
are available, one NCMAT file will be generated for each such temperature. The |
| 386 |
resulting filename will be <basename>_T<temperature>K.ncmat, where <basename> |
| 387 |
will default to the input filename unless --outbn is provided. |
| 388 |
|
| 389 |
The script internally relies on the Python Nuclear Engineering Toolkit |
| 390 |
(http://pyne.io/) for ENDF parsing, so this must be installed on the system. |
| 391 |
|
| 392 |
Input ENDF files can for instance be downloaded from: |
| 393 |
|
| 394 |
https://www.nndc.bnl.gov/endf/b8.0/download.html |
| 395 |
|
| 396 |
(download and open zip-file from the "Thermal Neutron Scattering Sublibrary"). |
| 397 |
|
| 398 |
""" |
| 399 |
|
| 400 |
parser = argparse.ArgumentParser(description=descr, |
| 401 |
formatter_class=argparse.RawTextHelpFormatter) |
| 402 |
parser.add_argument('ENDFFILE',help="Primary ENDF file with tsl data.",type=str) |
| 403 |
parser.add_argument('--secondary',metavar='ENDFFILE2:fraction', |
| 404 |
type=str, |
| 405 |
help="ENDF file for secondary element, along with the fraction of that element") |
| 406 |
parser.add_argument("--filehdr",help="File containing initial part of generated files.",type=str) |
| 407 |
parser.add_argument("--outbn",type=str,help="Basename of generated ncmat files.") |
| 408 |
parser.add_argument("--ignoretemp",type=float,nargs='+',metavar='T', |
| 409 |
help="If some temperature blocks in input should be ignored, provide the temperature values here (kelvin).") |
| 410 |
|
| 411 |
def to_path(parser,fn): |
| 412 |
_ = pathlib.Path(fn) |
| 413 |
if not _.exists(): |
| 414 |
parser.error(f'File not found: {_}') |
| 415 |
return _ |
| 416 |
|
| 417 |
|
| 418 |
args=parser.parse_args() |
| 419 |
args.ENDFFILE = to_path(parser,args.ENDFFILE) |
| 420 |
args.fraction1='1' |
| 421 |
args.fraction2=None |
| 422 |
if not args.secondary: |
| 423 |
args.ENDFFILE2=None |
| 424 |
else: |
| 425 |
if not args.secondary.count(':')==1: |
| 426 |
parser.error('Argument to --secondary must contain exactly one semicolon (:)') |
| 427 |
sn,fr2 = args.secondary.split(':',1) |
| 428 |
args.secondary = True |
| 429 |
if fr2.count('/')==1: |
| 430 |
a,b = [int(e) for e in fr2.split('/')] |
| 431 |
if b<=0 or not ( 0 < a < b ): |
| 432 |
parser.error('Invalid fraction specified in --secondary') |
| 433 |
args.fraction1=f'{b-a}/{b}' |
| 434 |
args.fraction2=f'{a}/{b}' |
| 435 |
else: |
| 436 |
args.fraction2=fr2 |
| 437 |
if not ( 0.0 < float(fr2) < 1.0): |
| 438 |
parser.error('Invalid fraction specified in --secondary') |
| 439 |
args.fraction1=f'{1.0-float(fr2):10}' |
| 440 |
args.ENDFFILE2 = to_path(parser,sn) |
| 441 |
if args.filehdr: |
| 442 |
_filehdrtxt=to_path(parser,args.filehdr).read_text() |
| 443 |
else: |
| 444 |
_filehdrtxt=f""" |
| 445 |
NCMAT v2 |
| 446 |
# |
| 447 |
# Material with scattering kernel extracted from ENDF file. |
| 448 |
# |
| 449 |
<<STDNOTICE>> |
| 450 |
# |
| 451 |
@DENSITY |
| 452 |
1 g_per_cm3 #FIX{""}ME. Dummy number!!! (update or add unit cell sections and then remove @DENSITY section) |
| 453 |
""" |
| 454 |
args.filehdr = [l.rstrip() for l in _filehdrtxt.strip().splitlines()] |
| 455 |
|
| 456 |
if not any('<<STDNOTICE>>' in l for l in args.filehdr): |
| 457 |
parser.error('ERROR: File specified with --filehdr should contain the string "<<STDNOTICE>>" on a separate line (just before the first data section)') |
| 458 |
|
| 459 |
if not args.outbn: |
| 460 |
if args.ENDFFILE2: |
| 461 |
parser.error('--outbn is required when providing two input files') |
| 462 |
else: |
| 463 |
args.outbn=args.ENDFFILE.name |
| 464 |
if args.outbn.endswith('.endf'): |
| 465 |
args.outbn=args.outbn[0:-5] |
| 466 |
assert args.outbn |
| 467 |
|
| 468 |
return args |
| 469 |
|
| 470 |
def genstdheaders(): |
| 471 |
def do_write(fn,suggestedcmdopts,content): |
| 472 |
pathlib.Path(fn).write_text(content) |
| 473 |
print(f'Wrote {fn}') |
| 474 |
progname=os.path.basename(sys.argv[0]) |
| 475 |
print( f' -> Suggested conversion cmd: {progname} {suggestedcmdopts}') |
| 476 |
|
| 477 |
fixstr='NO'+'COMM'+'IT/FI'+'XME' |
| 478 |
do_write('hdrH2O.txt', |
| 479 |
'tsl-HinH2O.endf --outbn LiquidWaterH2O --filehdr=hdrH2O.txt --ignoretemp 650 800', |
| 480 |
f"""NCMAT v2 |
| 481 |
# |
| 482 |
# Water (H2O) based on ENDF/B-VIII.0 scattering kernels by J.I. Marquez Damian, |
| 483 |
# et. al. (see below for references). Please check the @DENSITY carefully below, as |
| 484 |
# the density of liquid water depends on the material pressure. |
| 485 |
<<STDNOTICE>> |
| 486 |
# |
| 487 |
# In case your local installation does not provide all these files, they can be |
| 488 |
# downloaded from: https://github.com/mctools/ncrystal-extra/tree/master/data |
| 489 |
# |
| 490 |
@DENSITY |
| 491 |
#{fixstr}: Edit to leave just the relevant line (and the relevant comment for the reference): |
| 492 |
#NB: Density depends on pressure (value here provided by https://www.thermexcel.com/english/tables/eau_atm.htm): |
| 493 |
#Uncomment for T=283.6K: 0.99973 g_per_cm3 #(at 1atm pressure) |
| 494 |
#Uncomment for T=293.6K: 0.99820 g_per_cm3 #(at 1atm pressure) |
| 495 |
#Uncomment for T=300.0K: 0.99663 g_per_cm3 #(at 1atm pressure) |
| 496 |
#Uncomment for T=323.6K: 0.98781 g_per_cm3 #(at 1atm pressure) |
| 497 |
#Uncomment for T=350.0K: 0.97355 g_per_cm3 #(at 1atm pressure) |
| 498 |
#NB: Density depends on pressure (value here provided by engineeringtoolbox.com): |
| 499 |
#Uncomment for T=373.6K: 0.95805 g_per_cm3 #(at saturation pressure of 1.0171atm) |
| 500 |
#Uncomment for T=400.0K: 0.9376 g_per_cm3 #(at saturation pressure of 2.41atm) |
| 501 |
#Uncomment for T=423.6K: 0.9162 g_per_cm3 #(at saturation pressure of 4.77atm) |
| 502 |
#Uncomment for T=450.0K: 0.8903 g_per_cm3 #(at saturation pressure of 9.21atm) |
| 503 |
#Uncomment for T=473.6K: 0.8645 g_per_cm3 #(at saturation pressure of 15.48atm) |
| 504 |
#Uncomment for T=500.0K: 0.8315 g_per_cm3 #(at saturation pressure of 26.03atm) |
| 505 |
#Uncomment for T=523.6K: 0.7979 g_per_cm3 #(at saturation pressure of 39.55atm) |
| 506 |
#Uncomment for T=550.0K: 0.7554 g_per_cm3 #(at saturation pressure of 60.39atm) |
| 507 |
#Uncomment for T=573.6K: 0.7116 g_per_cm3 #(at saturation pressure of 85.29atm) |
| 508 |
#Uncomment for T=600.0K: 0.6499 g_per_cm3 #(at saturation pressure of 121.8atm) |
| 509 |
#Uncomment for T=623.6K: 0.5709 g_per_cm3 #(at saturation pressure of 164.06atm) |
| 510 |
1 g_per_cm3 #DUMMY {fixstr} |
| 511 |
#{fixstr}Also pick appropriate egrid max and move down to @DYNINFO(H) section: |
| 512 |
#Uncomment and place below for T=283.6K: egrid 3.92 # Value tuned manually by T. Kittelmann |
| 513 |
#Uncomment and place below for T=293.6K: egrid 4.02 # Value tuned manually by T. Kittelmann |
| 514 |
#Uncomment and place below for T=300.0K: egrid 4.04 # Value tuned manually by T. Kittelmann |
| 515 |
#Uncomment and place below for T=323.6K: egrid 4.3 # Value tuned manually by T. Kittelmann |
| 516 |
#Uncomment and place below for T=350.0K: egrid 4.65 # Value tuned manually by T. Kittelmann |
| 517 |
#Uncomment and place below for T=373.6K: egrid 4.9 # Value tuned manually by T. Kittelmann |
| 518 |
#Uncomment and place below for T=400.0K: egrid 5.4 # Value tuned manually by T. Kittelmann |
| 519 |
#Uncomment and place below for T=423.6K: egrid 5.65 # Value tuned manually by T. Kittelmann |
| 520 |
#Uncomment and place below for T=450.0K: egrid 5.95 # Value tuned manually by T. Kittelmann |
| 521 |
#Uncomment and place below for T=473.6K: egrid 6.2 # Value tuned manually by T. Kittelmann |
| 522 |
#Uncomment and place below for T=500.0K: egrid 6.55 # Value tuned manually by T. Kittelmann |
| 523 |
#Uncomment and place below for T=523.6K: egrid 6.85# Value tuned manually by T. Kittelmann |
| 524 |
#Uncomment and place below for T=550.0K: egrid 7.2 # Value tuned manually by T. Kittelmann |
| 525 |
#Uncomment and place below for T=573.6K: egrid 7.6 # Value tuned manually by T. Kittelmann |
| 526 |
#Uncomment and place below for T=600.0K: egrid 7.95 # Value tuned manually by T. Kittelmann |
| 527 |
#Uncomment and place below for T=623.6K: egrid 8.35 # Value tuned manually by T. Kittelmann |
| 528 |
""") |
| 529 |
|
| 530 |
do_write('hdrD2O.txt', |
| 531 |
'tsl-DinD2O.endf --secondary tsl-OinD2O.endf:1/3 --outbn LiquidHeavyWaterD2O --filehdr=hdrD2O.txt --ignoretemp=650', |
| 532 |
f"""NCMAT v2 |
| 533 |
# |
| 534 |
# Heavy water (D2O) based on ENDF/B-VIII.0 scattering kernels by J.I. Marquez |
| 535 |
# Damian, et. al. (see below for references). Please check the @DENSITY |
| 536 |
# carefully below, as the density of liquid water depends on the material |
| 537 |
# pressure. |
| 538 |
<<STDNOTICE>> |
| 539 |
# |
| 540 |
# In case your local installation does not provide all these files, they can be |
| 541 |
# downloaded from: https://github.com/mctools/ncrystal-extra/tree/master/data |
| 542 |
# |
| 543 |
@DENSITY |
| 544 |
#{fixstr}: Edit to leave just the relevant line (and the relevant comment for the reference): |
| 545 |
#NB: Density depends on pressure (value here provided by engineeringtoolbox.com): |
| 546 |
#Uncomment for T=283.6K: 1.10586 g_per_cm3 #(at 1atm pressure) |
| 547 |
#Uncomment for T=293.6K: 1.10526 g_per_cm3 #(at 1atm pressure) |
| 548 |
#Uncomment for T=300.0K: 1.10404 g_per_cm3 #(at 1atm pressure) |
| 549 |
#Uncomment for T=323.6K: 1.09547 g_per_cm3 #(at 1atm pressure) |
| 550 |
#Uncomment for T=350.0K: 1.08037 g_per_cm3 #(at 1atm pressure) |
| 551 |
#Uncomment for T=373.6K: 1.06312 g_per_cm3 #(at 1atm pressure) |
| 552 |
#NB: Density depends on pressure (value here from P.G., MacMillan, et. al. (1981), |
| 553 |
# "Tables of thermodynamic properties of heavy water in SI units"): |
| 554 |
#Uncomment for T=400.0K: 1.04019 g_per_cm3 #(at saturation pressure of 2.34atm) |
| 555 |
#Uncomment for T=423.6K: 1.01678 g_per_cm3 #(at saturation pressure of 4.65atm) |
| 556 |
#Uncomment for T=450.0K: 0.987245 g_per_cm3 #(at saturation pressure of 9.08atm) |
| 557 |
#Uncomment for T=473.6K: 0.957643 g_per_cm3 #(at saturation pressure of 15.4atm) |
| 558 |
#Uncomment for T=500.0K: 0.920446 g_per_cm3 #(at saturation pressure of 26.1atm) |
| 559 |
#Uncomment for T=523.6K: 0.883010 g_per_cm3 #(at saturation pressure of 39.7atm) |
| 560 |
#Uncomment for T=550.0K: 0.834808 g_per_cm3 #(at saturation pressure of 60.9atm) |
| 561 |
#Uncomment for T=573.6K: 0.783788 g_per_cm3 #(at saturation pressure of 86.3atm) |
| 562 |
#Uncomment for T=600.0K: 0.712194 g_per_cm3 #(at saturation pressure of 123.6atm) |
| 563 |
#Uncomment for T=623.6K: 0.621322 g_per_cm3 #(at saturation pressure of 166.9atm) |
| 564 |
1 g_per_cm3 #DUMMY {fixstr} |
| 565 |
#{fixstr}Also pick appropriate egrid max and move down to @DYNINFO(H) section: |
| 566 |
#Uncomment and place below for T=283.6K D: egrid 3.6 # Value tuned manually by T. Kittelmann |
| 567 |
#Uncomment and place below for T=283.6K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 568 |
#Uncomment and place below for T=293.6K D: egrid 3.7 # Value tuned manually by T. Kittelmann |
| 569 |
#Uncomment and place below for T=293.6K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 570 |
#Uncomment and place below for T=300.0K D: egrid 3.8 # Value tuned manually by T. Kittelmann |
| 571 |
#Uncomment and place below for T=300.0K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 572 |
#Uncomment and place below for T=323.6K D: egrid 4.1 # Value tuned manually by T. Kittelmann |
| 573 |
#Uncomment and place below for T=323.6K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 574 |
#Uncomment and place below for T=350.0K D: egrid 4.4 # Value tuned manually by T. Kittelmann |
| 575 |
#Uncomment and place below for T=350.0K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 576 |
#Uncomment and place below for T=373.6K D: egrid 4.7 # Value tuned manually by T. Kittelmann |
| 577 |
#Uncomment and place below for T=373.6K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 578 |
#Uncomment and place below for T=400.0K D: egrid 5.1 # Value tuned manually by T. Kittelmann |
| 579 |
#Uncomment and place below for T=400.0K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 580 |
#Uncomment and place below for T=423.6K D: egrid 5.3 # Value tuned manually by T. Kittelmann |
| 581 |
#Uncomment and place below for T=423.6K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 582 |
#Uncomment and place below for T=450.0K D: egrid 5.55 # Value tuned manually by T. Kittelmann |
| 583 |
#Uncomment and place below for T=450.0K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 584 |
#Uncomment and place below for T=473.6K D: egrid 6.1 # Value tuned manually by T. Kittelmann |
| 585 |
#Uncomment and place below for T=473.6K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 586 |
#Uncomment and place below for T=500.0K D: egrid 6.4 # Value tuned manually by T. Kittelmann |
| 587 |
#Uncomment and place below for T=500.0K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 588 |
#Uncomment and place below for T=523.6K D: egrid 6.8 # Value tuned manually by T. Kittelmann |
| 589 |
#Uncomment and place below for T=523.6K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 590 |
#Uncomment and place below for T=550.0K D: egrid 7.1 # Value tuned manually by T. Kittelmann |
| 591 |
#Uncomment and place below for T=550.0K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 592 |
#Uncomment and place below for T=573.6K D: egrid 7.4 # Value tuned manually by T. Kittelmann |
| 593 |
#Uncomment and place below for T=573.6K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 594 |
#Uncomment and place below for T=600.0K D: egrid 7.6 # Value tuned manually by T. Kittelmann |
| 595 |
#Uncomment and place below for T=600.0K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 596 |
#Uncomment and place below for T=623.6K D: egrid 8.1 # Value tuned manually by T. Kittelmann |
| 597 |
#Uncomment and place below for T=623.6K O: egrid 10.0 # Value tuned manually by T. Kittelmann |
| 598 |
""") |
| 599 |
print(f"\nNOTICE: Some files produced by above commands contain FIX{'ME'}s (might need density values updated for given temperature)") |
| 600 |
print("\nNOTICE: It might also be worth investigating each file in order to manually provide kernel egrid max via egrid keyword.") |
| 601 |
|
| 602 |
if __name__=='__main__': |
| 603 |
if '--genstdheaders' in sys.argv[1:]: |
| 604 |
#Hidden option to prepare some conversions as used for official NCrystal files. |
| 605 |
genstdheaders() |
| 606 |
sys.exit(0) |
| 607 |
args=_parseArgs() |
| 608 |
|
| 609 |
p1=parse_endf_file(args.ENDFFILE) |
| 610 |
p2=parse_endf_file(args.ENDFFILE2) if args.ENDFFILE2 else None |
| 611 |
|
| 612 |
temperatures1 = [ _["T"] for _ in p1['result_datablocks'] ] |
| 613 |
if p2: |
| 614 |
temperatures2 = [ _["T"] for _ in p2['result_datablocks'] ] |
| 615 |
temperatures_combined = [ t1 for t1 in temperatures1 if min(abs(t1-t2) for t2 in temperatures2)<1e-5 ] |
| 616 |
if len(temperatures_combined)<len(temperatures1): |
| 617 |
print(f"WARNING: {len(temperatures1)-len(temperatures_combined)} temperature blocks in {args.ENDFFILE} could not be used due to missing data in other file!") |
| 618 |
if len(temperatures_combined)<len(temperatures2): |
| 619 |
print(f"WARNING: {len(temperatures2)-len(temperatures_combined)} temperature blocks in {args.ENDFFILE} could not be used due to missing data in other file!") |
| 620 |
else: |
| 621 |
temperatures_combined = temperatures1 |
| 622 |
|
| 623 |
temperatures_combined=sorted(list(set(temperatures_combined))) |
| 624 |
for t in (args.ignoretemp or []): |
| 625 |
removed=False |
| 626 |
for _ in temperatures_combined: |
| 627 |
if abs(t-_)<1e-6: |
| 628 |
temperatures_combined.remove(_) |
| 629 |
print (f"Ignoring T={_}K as requested") |
| 630 |
removed=True |
| 631 |
break |
| 632 |
if not removed: |
| 633 |
raise SystemExit(f'ERROR: Asked to ignore T={t}K, but no such temperature was found in the input') |
| 634 |
|
| 635 |
|
| 636 |
if p2 and (p1['non_principal_data'] or p2['non_principal_data']): |
| 637 |
raise SystemExit("ERROR: When providing two ENDF files as input both must files must be without non-principal" |
| 638 |
+" elements! If you know how to handle this, You can try to convert separately and combine the" |
| 639 |
+" resulting .ncmat files manually.") |
| 640 |
|
| 641 |
for t in temperatures_combined: |
| 642 |
fn=pathlib.Path(f'{args.outbn}_T{t}K.ncmat') |
| 643 |
with fn.open('wt') as fh: |
| 644 |
print(f' -> Writing {fn}') |
| 645 |
fh.write('NCMAT v2\n') |
| 646 |
stdnotice = f'#\n# Notice: This NCMAT file is valid at T={t}K only.' |
| 647 |
if len(temperatures_combined)>1: |
| 648 |
stdnotice+=' Other files alternatively provide\n' |
| 649 |
stdnotice+='# the same material at temperatures:\n#\n' |
| 650 |
nperline=7 |
| 651 |
t_to_write=list(_ for _ in temperatures_combined if _!=t) |
| 652 |
for i in range(0,len(t_to_write),nperline): |
| 653 |
stdnotice += ('# '+' '.join((f'{_}K' for _ in t_to_write[i:i+nperline]))+'\n') |
| 654 |
for l in args.filehdr: |
| 655 |
if l.startswith('NCMAT '): |
| 656 |
continue |
| 657 |
if stdnotice and '<<STDNOTICE>>' in l: |
| 658 |
l=l.replace('<<STDNOTICE>>',stdnotice) |
| 659 |
stdnotice='' |
| 660 |
fh.write(l if l.endswith('\n') else f'{l}\n') |
| 661 |
if stdnotice: |
| 662 |
fh.write(stdnotice) |
| 663 |
for elementName,count_,effmass,fraction_str in p1['non_principal_data']: |
| 664 |
assert not p2 |
| 665 |
fh.write('@DYNINFO\n') |
| 666 |
fh.write(f' element {elementName}\n') |
| 667 |
fh.write(f' fraction {fraction_str}\n') |
| 668 |
fh.write(' type freegas\n') |
| 669 |
fh.write(format_endf_block_as_ncmatdyninfo_for_principal_element(p1,t, |
| 670 |
args.fraction1 if p2 else None)) |
| 671 |
if p2: |
| 672 |
fh.write(format_endf_block_as_ncmatdyninfo_for_principal_element(p2,t,args.fraction2)) |
| 673 |
print(' -> Testing that NCrystal can load this file') |
| 674 |
NCrystal.createScatter(f'{fn};dcutoff=0.8') |
| 675 |
print("All done.") |