def test_ionmix_read_write_0(): # Verify the OpacIonmix.write function abar = 1.0 zmax = 1.0 fh = opp.OpacIonmix(reference_file, abar / opp.NA, twot=True, man=True, verbose=False) fracs = (1.0, ) tmp_file = os.path.join(BASE_DIR, 'imx_sample_tmp_0.cn4') try: fh.write(tmp_file, (zmax, ), fracs, twot=True, man=True) # Open generated file to check there are no errors. fh_new = opp.OpacIonmix(tmp_file, abar / opp.NA, twot=True, man=True, verbose=False) for key in fields: yield assert_allclose, getattr(fh, key), getattr(fh_new, key) except: raise finally: if os.path.exists(tmp_file): os.remove(tmp_file)
def test_ionmix_extend_to_zero(self): eos_data_extended = opp.OpacIonmix(self.reference_file, self.abar / opp.NA, twot=True, man=True, verbose=False) eos_data_extended.extendToZero()
def test_ionmix_read(): abar = 1.0 eos_data = opp.OpacIonmix(reference_file, abar / opp.NA, twot=True, man=True, verbose=False)
def test_extend_to_zero(): abar = 1.0 eos_data = opp.OpacIonmix(reference_file, abar / opp.NA, twot=True, man=True, verbose=False) eos_data.extendToZero()
def setUp(self): # Ionmix file info. self.imx = opp.OpacIonmix(self.reference_name, self.mpi, man=self.man, twot=self.twot) self.pion = self.imx.pion self.dens = self.imx.dens self.temps = self.imx.temps self.ndens = self.imx.ndens self.ntemp = self.imx.ntemp
def ionmix_read(self): if self.verbose: print('Opening up IONMIX file {}...'.format(self.path_in)) if self.mpi is None: raise Warning('Need mpi for ionmix!') else: # TODO Add options for man and twot op = opp.OpacIonmix(self.path_in, self.mpi, man=True, twot=True) self.common_keys = [ self.ionmix_names_dict_inv[attr] for attr in dir(op) if attr in self.ionmix_names_dict_inv.keys() ] return op
def test_ionmix_write(self): # Verify the OpacIonmix.write function. try: self.eos_data.write(self.tmp_file_0, (self.zmax,), self.fracs, twot=True, man=True) # Open generated file to check there are no errors. self.eos_data_new = opp.OpacIonmix(self.tmp_file_0, self.abar/opp.NA, twot=True, man=True, verbose=False) for key in self.fields: np.testing.assert_allclose(getattr(self.eos_data, key), getattr(self.eos_data_new, key)) except: raise finally: if os.path.exists(self.tmp_file_0): os.remove(self.tmp_file_0)
def test_writeIonmixFile(self): try: pars = {key: getattr(self.eos_data, key) for key in self.fields} opp.writeIonmixFile(self.tmp_file, (self.zmax,), self.fracs, **pars) # Open generated file to check there are no errors. self.eos_data_new = opp.OpacIonmix(self.tmp_file, self.abar/opp.NA, twot=True, man=True, verbose=False) for key in self.fields: np.testing.assert_array_equal(getattr(self.eos_data, key), getattr(self.eos_data_new, key)) except: raise finally: if os.path.exists(self.tmp_file): os.remove(self.tmp_file)
def test_randomize_ionmix(self): try: opp.utils.randomize_ionmix(self.reference_file, self.tmp_file) self.random_eos_data = opp.OpacIonmix(self.tmp_file, self.abar / opp.NA, twot=True, man=True, verbose=False) for attr in self.fields: if attr not in ['ngroups']: self.assertTrue(np.any( np.not_equal(getattr(self.random_eos_data, attr), getattr(self.eos_data, attr))), msg='Checking if {0} data was' 'randomized!'.format(attr)) except: raise finally: if os.path.exists(self.tmp_file): os.remove(self.tmp_file)
def setup_radiative_grid(self, validate=False): import opacplot2 as opp rad_grid = [] for spec in self.materials: if self.data[spec]['material'] == 'vacuum': rad_grid.append(None) continue if self.data[spec]['op_table'] is None: raise ValueError('Opacity table not set for specie {}'.format(spec)) try: f = opp.OpacIonmix(self.data[spec]['op_table'], self.data[spec]['A']/opp.NA, twot=True, man=True, verbose=False) except: print('Error: failed to parse {} file!'.format(self.data[spec]['op_table'])) raise rad_grid.append(f.opac_bounds[:]) if not validate: # if not validating we just need one radiative grids break grid0 = filter(lambda x: x is not None, rad_grid)[0] if validate: # check that all the radiative grids are identical for idx, grid in enumerate(rad_grid): if grid is None: continue try: np.testing.assert_allclose(grid, grid0) except: print('Error: radiative grids are not the same!') raise self['rt_mgdBounds'] = grid0 self['rt_mgdNumGroups'] = len(grid0) - 1
import opacplot2 as opp from opacplot2 import RADCONST as AR, KB, BC_BOUND, BC_EXTRAP_ZERO import numpy as np from matplotlib import pyplot as plt mpi = 4.002602 / opp.NA heimx = opp.OpacIonmix("data/he-imx-005.cn4", mpi, twot=True, man=True, verbose=True) mpi = 26.9815386 / opp.NA alimx = opp.OpacIonmix("data/al-imx-002.cn4", mpi, twot=True, man=True, verbose=True) def pion(opimx, rho, tion, log=False): return opp.interpDT(opimx.pion, opimx.dens, opimx.temps, rho, tion, log=False, lookup=opp.INTERP_FUNC, bctmin=opp.BC_EXTRAP_ZERO, bcdmin=opp.BC_EXTRAP_ZERO)
def main(): parser = argparse.ArgumentParser(description=""" This script is used to automate EoS/opacity tables generation for FLASH. """) parser.add_argument( '-d', '--dbdir', action="store", type=str, default=os.path.abspath(os.curdir), help='Path to the database. Default: current directory.') parser.add_argument('-t', '--dbtype', action="store", type=str, default='sesame', help='Database type. Default: sesame.') parser.add_argument('-n', '--tablenum', action="store", type=int, help='Table id', required=True) parser.add_argument('-o', '--out', action="store", type=str, help='Ouput filename', default=None) args = parser.parse_args() if args.out is None: args.out = '{0}-eos-{1}'.format(args.dbtype, args.tablenum) else: args.out = os.path.splitext(args.out)[0] if args.dbtype == 'sesame': print("Parsing sesame input files.") eos_sesame = opp.OpgSesame(os.path.join(args.dbdir, "xsesame_ascii"), opp.OpgSesame.SINGLE, verbose=False) cond_sesame = opp.OpgSesame(os.path.join(args.dbdir, "sescu_ascii"), opp.OpgSesame.DOUBLE, verbose=False) eos_data_i = eos_sesame.data[args.tablenum] cond_keys = sorted([key for key, val in cond_sesame.data.iteritems()\ if val['zmax'] == eos_data_i['zmax']]) # by default select the last (i.e. newest) table avalable cond_data_i = cond_sesame.data[cond_keys[-1]] print('Presets for sesame table', args.tablenum, end='') # Merging ele and ion grids if args.tablenum in opp.presets.SESAME: eos_data = opp.adapt.EosMergeGrids( eos_data_i, **opp.presets.SESAME[args.tablenum]['merge']) fracs = opp.presets.SESAME[args.tablenum]['fracs'] print('found') else: eos_data = opp.adapt.EosMergeGrids(eos_data_i, filter_dens=lambda x: x > 0, filter_temps=lambda x: x > 0) fracs = (1.0, ) print('not found') output_file = args.out + '.cn4' print('Generating IONMIX file: {0}'.format(output_file)) numDens = opp.NA * eos_data['ele_dens'] / eos_data["abar"] print('Warning: for now zbar is set to 0.') opp.writeIonmixFile(output_file, (eos_data['zmax'], ), fracs, numDens=numDens, temps=eos_data['ele_temps'], eion=eos_data["ion_eint"], eele=eos_data["ele_eint"], pion=eos_data["ion_pres"], pele=eos_data["ele_pres"]) print('Trying to read if back... ', end='') try: ionmix = opp.OpacIonmix(output_file, eos_data["abar"] / opp.NA, twot=True, man=True, verbose=False) print('[ok]') except: print('[failed]')
import opacplot2 as opp from opacplot2 import RADCONST as AR, KB import numpy as np from matplotlib import pyplot as plt mpi = 4.002602 / opp.NA opimx = opp.OpacIonmix("examples/data/al-imx-002.cn4", mpi, twot=True, man=True, verbose=True) t1 = 0.0 t2 = 20.0 tvals = np.linspace(t1, t2, 1001) dens = 2.16 # PLOT EELE: vals = np.array([opp.interpDT(opimx.eele, opimx.dens, opimx.temps, dens, t, bctmin=opp.BC_EXTRAP_ZERO, log=False) for t in tvals]) plt.plot(tvals, vals, "r", lw=2) plt.grid(True) plt.ylabel("Electron Specific Internal Energy (ergs/g)") plt.xlabel("Electron Temperature (eV)") # PLOT CVEELE: plt.figure() vals = np.array([opp.interpDT(opimx.eele, opimx.dens, opimx.temps, dens, t, bctmin=opp.BC_EXTRAP_ZERO, log=False, lookup=opp.INTERP_DFDT) for t in tvals]) plt.plot(tvals, vals, "r", lw=2) plt.grid(True)
import opacplot2 as opp from opacplot2 import RADCONST as AR, KB, BC_BOUND, BC_EXTRAP_ZERO import numpy as np from matplotlib import pyplot as plt mpi = 4.002602 / opp.NA heimx = opp.OpacIonmix("../helium/ionmix-005/he-imx-005.cn4", mpi, twot=True, man=True, verbose=True) mpi = 26.9815386 / opp.NA alimx = opp.OpacIonmix("../aluminum/ionmix-002/al-imx-002.cn4", mpi, twot=True, man=True, verbose=True) def pion(opimx, rho, tion, log=False): return opp.interpDT(opimx.pion, opimx.dens, opimx.temps, rho, tion, log=False, lookup=opp.INTERP_FUNC, bctmin=opp.BC_EXTRAP_ZERO, bcdmin=opp.BC_EXTRAP_ZERO)
def setUp(self): self.eos_data = opp.OpacIonmix(self.reference_file, self.abar / opp.NA, twot=True, man=True, verbose=False)
# <codecell> plot_eos_field(eos_data, 'ioncc', 'pres') # <codecell> plot_eos_field(eos_data, 'ioncc', 'pres', grad='rho') # <codecell> fracs = (1.0, ) filename = 'al-ses-3717.cn4' numDens = opp.NA * eos_data['ele_dens'] / eos_data["abar"] opp.writeIonmixFile(filename, (eos_data['zmax'], ), fracs, numDens=numDens, temps=eos_data['ele_temps'], eion=np.fmax(eos_data["ioncc_eint"], 1e-10), eele=eos_data["ele_eint"], pion=eos_data["ioncc_pres"], pele=eos_data["ele_pres"], zbar=np.fmax(zbar2, 1e-3)) ionmix = opp.OpacIonmix(filename, eos_data["abar"] / opp.NA, twot=True, man=True, verbose=False) # <codecell>
print eos_o['ioncc_eint'][0,0] # writing everything to files numDens = opp.NA * eos_o['ele_dens'] / eos_o['abar'] #print mat_dict.snop.z, mat_dict.snop.fraction opp.writeIonmixFile(filename, mat_dict.snop.z, mat_dict.snop.fraction, numDens=numDens, temps=eos_o['ele_temps'], eion=eos_o["ioncc_eint"], eele=eos_o["ele_eint"], pion=eos_o["ioncc_pres"], pele=eos_o["ele_pres"], zbar=zbar_tf) # rereading the output ionmix = opp.OpacIonmix(filename, eos_o['abar']/opp.NA, twot=True, man=True, verbose=False) test_dict = {'temps': 'ele_temps', 'dens': 'ele_dens', 'pele': 'ele_pres', 'pion': 'ion_pres', 'eele': 'ele_eint', 'eion': 'ion_eint'} print 'Checking that file was correctly written: ', for attr, key in test_dict.iteritems(): print attr,'...', try: np.testing.assert_allclose(getattr(ionmix, attr), eos_o[key], atol=1e-5, rtol=1e-5) except: print 'failed' np.testing.assert_allclose(ionmix.zbar, zbar_tf, atol=1e-5, rtol=1e-5) print '' print 'Checking positivity:',
rho = np.logspace(np.log10(rho_min), np.log10(rho_max), 200) temp = np.logspace(np.log10(temp_min), np.log10(temp_max), 328) D, T = np.meshgrid(rho, temp, indices='ij') pres = tab.Pt_DT(D, T) eint = tab.Ut_DT(D, T) print(abar, zbar) numDens = opp.NA * rho / abar for filename in [ 'simulations/DavisEos/eos-vdv-davis.cn4', 'setup/eos-vdv-davis.cn4' ]: opp.writeIonmixFile(filename, [zbar], [1.0], numDens=numDens, temps=temp / eV2K_cst, eion=0.5 * eint.T, eele=0.5 * eint.T, pion=0.5 * pres.T, pele=0.5 * pres.T, zbar=zbar * np.ones(pres.shape)) # rereading the output ionmix = opp.OpacIonmix(filename, abar / opp.NA, twot=True, man=True, verbose=False)
def __init__(self, eosopac, input=None, x='dens', y='temp', g='groups', **kwargs): """ Fast interpolation for values in EoS/Opacity table Parameters ---------- eosopac : str or Eos/Opacity table in `opacplot2` - First, if `eosopac` is str, `eosopac` is used as the filename of the table. - Otherwise, if `eosopac` is instance of class`opacplot2.OpacIonmix, class`opacplot2.OpgPropaceosAscii, class`opacplot2.OpgSesame, or class`opacplot2.OpgTOPS, it is converted to eos_dict - Otherwise, if `eosopac` is dict, it is used as dict input : str or None, optional if eosopac is a filename with unrecognized extension, `input` is used to specity input format, by default None x : str, optional x variable for interpolation, by default 'dens' y : str, optional y variable for interpolation, by default 'temp' g : str, optional groups variable for interpolation, by default 'groups' **kwargs: passed to class`opacplot2.OpacIonmix or `toEosDict` """ self.x = x self.y = y self.g = g from interpolation.splines import UCGrid, eval_linear from interpolation.splines import extrap_options as xto self.eval_linear = eval_linear self.xto = xto if isinstance(eosopac, str): ext_dict = { '.cn4': 'ionmix', '.prp': 'propaceos', '.ses': 'sesame', '.html': 'tops', '.tops': 'tops', } # If the input file is compressed, choose the next extension. if os.path.splitext(eosopac)[1] == '.gz': _, ext = os.path.splitext(os.path.splitext(eosopac)[0]) else: _, ext = os.path.splitext(eosopac) # Choose the correct input type based on extension and set input if ext in ext_dict.keys(): input = ext_dict[ext] if input == 'ionmix': op = opacplot2.OpacIonmix(eosopac, **kwargs) elif input == 'propaceos': try: from opacplot2 import opg_propaceos op = opg_propaceos.OpgPropaceosAscii(eosopac) except ImportError: raise ImportError('You do not have opg_propaceos.') elif input == 'sesame': try: op = opacplot2.OpgSesame(eosopac, opacplot2.OpgSesame.SINGLE) except ValueError: op = opacplot2.OpgSesame(eosopac, opacplot2.OpgSesame.DOUBLE) elif input == 'tops': op = opacplot2.OpgTOPS(eosopac) else: raise ValueError('Unsupported input format') elif isinstance(eosopac, (opacplot2.OpacIonmix, opacplot2.OpgPropaceosAscii, opacplot2.OpgSesame, opacplot2.OpgTOPS)): op = eosopac elif isinstance(eosopac, dict): input = 'dict' else: raise ValueError('Unsupported input format') if input == 'dict': eos_dict = eosopac elif input == 'ionmix': imx_conv = { 'Znum': 'zvals', 'Xnum': 'fracs', 'idens': 'numDens', 'temp': 'temps', 'Zf_DT': 'zbar', 'Pi_DT': 'pion', 'Pec_DT': 'pele', 'Ui_DT': 'eion', 'Uec_DT': 'eele', 'groups': 'opac_bounds', 'opr_mg': 'rosseland', 'opp_mg': 'planck_absorb', 'emp_mg': 'planck_emiss' } imx_conv = {value: key for key, value in imx_conv.items()} eos_dict = {} for key in op.__dict__.keys(): if key in imx_conv.keys(): eos_dict[imx_conv[key]] = op.__dict__[key] else: eos_dict[key] = key elif input == 'propaceos': eos_dict = op.toEosDict(**kwargs) elif input == 'sesame': eos_dict = op.toEosDict(**kwargs) elif input == 'tops': eos_dict = op.toEosDict(**kwargs) else: raise ValueError('Unsupported input format') self.ucgrid = UCGrid(eos_dict[x], eos_dict[y]) self.eos_dict = eos_dict self._funcs = {}
def __init__(self, material=None, tables=[], options={}, spec=['t'], units='cgs'): """ Parameters: ----------- - material: int: 4 digit SESAME material ID - tables: list: ['table1_id', 'table2_id', ..etc] - options: dict: {'tableid_regexpr': {'opt1': optval}, etc} For example {".t_DT": {'create_tzero': True}} would apply the EOS_CREATE_TZERO option to both 'Pt_DT' and 'Ut_DT' tables. The tableid_regexpr accepts regular expressions. [see help(re) for more details]. """ self._id = -1 if 'type' in options: ftype = options['type'] else: ftype = 'ionmix' if ftype == 'ionmix': self._default_options = { 'path': None, 'type': 'ionmix', 'abar': -1., 'zbar': -1, 'rho_ref': -1, 'Modulus': 0., 'Exchange_Coeff': 0.0, 'create_tzero': "zero" } elif ftype == 'sesascii': self._default_options = { 'path': None, 'prescision': 'double', 'type': 'ionmix' } options = self._validate_options(options) self.options = self._validate_options2(options) opt = self.options if not tables: self.tables = [key for key in avalable_tabs] else: self.tables = tables if material is not None: self.material = int(material) self.info = self._get_info() info = self.info for key in [ 'type', 'path', 'zbar', 'abar', 'rho_ref', 'Modulus', 'Exchange_Coeff', 'prescision' ]: if key in opt: self.info[key] = opt[key] del opt[key] self._original_units = supported_formats[ftype][0] self._requested_units = units grid_units = self._set_units(units, 'Pt_DT') out = {} if ftype == 'ionmix': translation_dict = { 'Pe_DT': 'pele', 'Pic_DT': 'pion', 'Ue_DT': 'eele', 'Uic_DT': 'eion', 'Zf_DT': 'zbar' } import opacplot2 as opp d = opp.OpacIonmix(info['path'], info['abar'] / opp.NA, twot=True, man=True, verbose=False) D_array = d.dens * grid_units.o2r('D') T_array = d.temps * grid_units.o2r('T') for key in avalable_tabs: if 't' not in key: if 'A' not in key: out[key] = getattr( d, translation_dict[key]) * grid_units.o2r(key[0]) else: out[key] = np.zeros(d.pele.shape) out['Pt_DT'] = out['Pe_DT'] + out['Pic_DT'] out['Ut_DT'] = out['Ue_DT'] + out['Uic_DT'] out['At_DT'] = out['Ae_DT'] + out['Aic_DT'] for tab_idx, tab_key in enumerate(self.tables): this_info = deepcopy(self.info) this_info['D_Array'] = D_array self._create_tzero(D_array, T_array, out[tab_key]) if opt['create_tzero']: this_info['T_Array'] = np.concatenate( (np.zeros(1), T_array)) this_info['F_Array'] = self._create_tzero( D_array, T_array, out[tab_key], method=opt['create_tzero']) else: this_info['T_Array'] = T_array this_info['F_Array'] = out[tab_key] setattr( self, tab_key, TabulatedTable(tab_key, self._id, options=opt, info=this_info, units=units)) elif ftype == 'sesascii': spec_dict = { 't': 'total', 'e': 'electron', 'ic': 'ioncold', 'iz': 'ion' } var_dict = {'P': 'pres', 'U': 'eint', 'A': 'free'} import opacplot2 as opp from ..eospac import constants as cst d = opp.OpgSesame(info['path'], getattr(opp.OpgSesame, info['prescision'].upper()), verbose=False) data = d.data[material] for key0, key1 in [('rho0', 'Normal_Density'), ('abar', 'Mean_Atomic_Mass'), ('bulkmod', 'Modulus'), ('zmax', 'Mean_Atomic_Num'), ('excoef', 'Exchange_Coeff')]: self.info[key1] = data[key0] for spec in ['t', 'ic', 'e', 'iz']: for tab_name in cst.tables: if tab_name[0] not in var_dict or '{s}_DT'.format( s=spec) not in tab_name: continue opacplot_name = '{0}_{1}'.format(spec_dict[spec], var_dict[tab_name[0]]) if opacplot_name not in data: continue this_info = deepcopy(self.info) this_info['D_Array'] = data['{0}_dens'.format( spec_dict[spec])] * grid_units.o2r('D') this_info['T_Array'] = data['{0}_temps'.format( spec_dict[spec])] * grid_units.o2r('T') this_info['F_Array'] = data[ opacplot_name] * grid_units.o2r(tab_name[0]) setattr( self, tab_name, TabulatedTable(tab_name, self._id, options=opt, info=this_info, units=units)) self._init_base()
def opac_hdf2table(): parser = argparse.ArgumentParser(description=""" This script is used to browse various EoS/Opacity tables formats """) parser.add_argument('-t', '--ftype', action="store", type=str, choices=avalable_formats, default='multi', help='Output filetype. Default: multi') parser.add_argument('-o', '--outfile', action="store", type=str, help='Output file base name/path') parser.add_argument('input_file', action="store", type=str, help='Path to the input hdf5 file') args = parser.parse_args() basedir, filename = os.path.split(os.path.abspath(args.input_file)) basename_in, _ = os.path.splitext(filename) if args.outfile is not None: filename_out = args.outfile else: filename_out = os.path.join(basedir, basename_in) op = OpgHdf5.open_file(os.path.abspath(args.input_file)) # ====================== Writing to output format ==================== if args.ftype == 'multi': from ..opg_multi import OpgMulti, MULTI_EXT_FMT op = OpgMulti(**op) op.set_id(3717) # just a random number, shouldn't matter op.write(os.path.join(basedir, filename_out), floor=None) elif args.ftype == 'ascii': outfile = os.path.join(basedir, filename_out) + '.txt' def repr_grid(arr, label): out = [] out += ['=' * 80] out += [' {0}: {1} points'.format(label, len(arr))] out += ['=' * 80] out = '\n'.join(out) return out + '\n' + np.array2string(arr, precision=3, separator='') print(repr_grid(op['dens'][:], "Density grid [g/cc]")) print(repr_grid(op['temp'][:], 'Temperature grid [eV]')) print(repr_grid(op['idens'][:], "Ionic density grid [1/cc]")) #print repr_grid(op['groups'][:], "Photon energy groups [eV]") nu = op['groups'][:] nu = 0.5 * (nu[1:] + nu[:-1]) out_op = np.array([nu] + [ op[key + '_mg'][0, 0] * op['dens'][0] for key in ['opp', 'opr', 'emp'] ]) np.set_printoptions(threshold=1e9) print( repr_grid(out_op.T, 'Opacity: nu [eV], opp [1/cm], opr[1/cm], emp [??]')) elif args.ftype == 'vtk': outfile = os.path.join(basedir, filename_out) from ..opg_vtk import opg_op2vtk f = opg_op2vtk(op, outfile) elif args.ftype == 'ionmix': outfile = os.path.join(basedir, filename_out) opp.writeIonmixFile(outfile, op['Znum'], op['Xnum'], numDens=op['idens'][:], temps=op['temp'][:], ngroups=op.Ng, opac_bounds=op['groups'][:], planck_absorb=op['opp_mg'][:], rosseland=op['opr_mg'][:], planck_emiss=op['emp_mg'][:]) # check that we can read the file back ionmix = opp.OpacIonmix(outfile, op["Abar"] / opp.NA, twot=True, man=True, verbose=False) else: print('Error: {0} ftype not known!'.format(args.ftype))