Пример #1
0
 def sesame_qeos_toEosDict(self):
     raise Warning('QEOS-SESAME is not ready yet!')
     try:
         op = opp.OpgSesame(self.path_in, opp.OpgSesame.SINGLE)
     except ValueError:
         op = opp.OpgSesame(self.path_in, opp.OpgSesame.DOUBLE)
     if self.args.tabnum is not None:
         eos_dict = op.toEosDict(Znum=self.args.Znum, Xnum=self.args.Xfracs, 
                                 qeos=True, log=self.args.log,
                                 tabnum=self.args.tabnum)
     else:
         eos_dict = op.toEosDict(Znum=self.args.Znum, Xnum=self.args.Xfracs, 
                                 qeos=True, log=self.args.log)
     return eos_dict
Пример #2
0
 def sesame_toEosDict(self):
     try:
         op = opp.OpgSesame(self.path_in, opp.OpgSesame.SINGLE)
     except ValueError:
         op = opp.OpgSesame(self.path_in, opp.OpgSesame.DOUBLE)
     if self.args.tabnum is not None:
         eos_dict = op.toEosDict(Znum=self.args.Znum, 
                                 Xnum=self.args.Xfracs,
                                 log=self.args.log,
                                 tabnum=self.args.tabnum)
     else:
         eos_dict = op.toEosDict(Znum=self.args.Znum, 
                                 Xnum=self.args.Xfracs,
                                 log=self.args.log)
     return eos_dict
Пример #3
0
 def setUp(self):
     self.ses_file = os.path.join(os.path.dirname(__file__),
                                  'data/matr_009999.ses')
     self.op = opp.OpgSesame(self.ses_file, opp.OpgSesame.SINGLE)
     self.eos_data = self.op.data[9999]
     # Setting intersect just in case the defaults change & testsuite
     # doesn't.
     self.md = opp.utils.EosMergeGrids(self.eos_data,
                                       filter_temps=lambda x: x > 1,
                                       filter_dens=lambda x: x > 1,
                                       intersect=['ele', 'ioncc'])
Пример #4
0
    def sesame_qeos_toEosDict(self):
        raise Warning('QEOS-SESAME is not ready yet!')
        try:
            op = opp.OpgSesame(self.path_in, opp.OpgSesame.SINGLE)
        except ValueError:
            op = opp.OpgSesame(self.path_in, opp.OpgSesame.DOUBLE)


        if len(op.data.keys()) > 1:
            raise Warning('More than one material ID found. '
                          'Use sesame-extract to create a file '
                          'with only one material first.')

        if self.args.tabnum is not None:
            eos_dict = op.toEosDict(Znum=self.args.Znum, Xnum=self.args.Xfracs,
                                    qeos=True, log=self.args.log,
                                    tabnum=self.args.tabnum)
        else:
            eos_dict = op.toEosDict(Znum=self.args.Znum, Xnum=self.args.Xfracs,
                                    qeos=True, log=self.args.log)
        return eos_dict
Пример #5
0
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]')
Пример #6
0
import os.path
import copy

import opacplot2 as opp
from opacplot2 import plot_eos_grid, plot_eos_field, plot_zbar
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import periodictable

matplotlib.rcParams.update({'savefig.dpi': 120, 'font.size': 12})

SESAME_DIR = '../../sesame/'
if 'eos_sesame' not in globals():
    eos_sesame = opp.OpgSesame(os.path.join(SESAME_DIR, "xsesame_ascii"),
                               opp.OpgSesame.SINGLE,
                               verbose=False)
    cond_sesame = opp.OpgSesame(os.path.join(SESAME_DIR, "sescu_ascii"),
                                opp.OpgSesame.DOUBLE,
                                verbose=False)

# <codecell>

# Selecting the SESAME table
#table_id = 3720
#table_id = 2140
table_id = 3717
eos_data_i = eos_sesame.data[table_id]

# list of all zbar tables for this element
cond_keys = sorted([
Пример #7
0
def test_opac_read():
    fh = opp.OpgSesame(os.path.join(BASE_DIR, reference_name),
                       opp.OpgSesame.SINGLE)
Пример #8
0
    def sesame_qeos_read(self):
        raise Warning('QEOS-SESAME is not ready yet!')

        if self.verbose:
            print('Opening up QEOS SESAME file {}...'.format(self.path_in))
        # Try SINGLE precision and then DOUBLE if that doesn't work.
        try:
            op = opp.OpgSesame(self.path_in, opp.OpgSesame.SINGLE)
        except ValueError:
            op = opp.OpgSesame(self.path_in, opp.OpgSesame.DOUBLE)

        if self.tabnum is not None:
            table_key = self.tabnum
        else:
            if self.verbose:
                print('Selecting the last table available...')
            # Select the last table (newest) table available.
            table_key = sorted(op.data.keys())[-1]

        # Sesame needs Znum.
        if self.znum is None:
            if 'Znum' in op.data[table_key].keys():
                self.znum = op.data[table_key]['Znum']
            else:
                raise ValueError('Znum Varray should be provided!')

        op.data[table_key]['Znum'] = np.array(self.znum, dtype='int')

        if self.verbose:
            print('Merging the Ion and '
                  'Electron temperature and density grids...')
        # We must merge ion_ and ele_ grids for qeos-sesame data.
        # Then we can calculate zbar using hedp module.
        op.data[table_key] = opp.utils.EosMergeGrids(op.data[table_key],
                                                     intersect=['ele', 'ion'],
                                                     filter_dens=lambda x:
                                                     (x > self.filters[0]),
                                                     filter_temps=lambda x:
                                                     (x > self.filters[1]),
                                                     qeos=True)

        if self.verbose:
            print('Calculating average ionization...')
        dens_arr, temp_arr = np.meshgrid(op.data[table_key]['ele_dens'],
                                         op.data[table_key]['ele_temps'])

        zbar = hedp.eos.thomas_fermi_ionization(dens_arr, temp_arr,
                                                op.data[table_key]['Znum'],
                                                op.data[table_key]['abar']).T

        op.data[table_key]['zbar'] = zbar

        if self.verbose:
            print('Calculating number densities...')
        # Add in number density key.
        op.data[table_key]['idens'] = (
            (op.data[table_key]['ele_dens'] * opp.NA) /
            op.data[table_key]['abar'])

        # Create a list of the "common dictionary format" keys.
        self.common_keys = [
            self.sesame_qeos_names_dict_inv[key]
            for key in op.data[table_key].keys()
            if key in self.sesame_qeos_names_dict_inv.keys()
        ]

        return op
Пример #9
0
#!/usr/python
# -*- coding: utf-8 -*-

# A very simple example to illistrate file convertion to the IONMIX format.

import opacplot2 as opp
import numpy as np

# Parse the input file, this part is file dependent.
# For OPAC file format the parser might be opacplot2/opg_tabop.py
# otherwise it would have to be implemented.

print dir(opp.OpgSesame)
eos_data = opp.OpgSesame("../../../eos/sesame/xsesame_ascii",
                         opp.OpgSesame.SINGLE,
                         verbose=False).data[5761]

# Write EoS/Opacity data, see opg_ionmix.py for writeIonmixFile class
# definion. When writing EoS file in 3T one has to provide eion, eele,
# pion, pele, zbar arguments. For a IONMIX file containing opacity data,
# following arguments have to be provided: ngroups, opac_bounds, rosseland,
# planck_absorb, planck_emiss. See FLASH4 manual for expected units in
# the IONMIX format.
fracs = (1.0, )
filename = 'he-ses-5761.cn4'
numDens = opp.NA * eos_data['ele_dens'] / eos_data[
    "abar"]  # convert from g.cm⁻³ to cm⁻³.
opp.writeIonmixFile(
    filename,
    (eos_data['zmax'], ),
    fracs,
Пример #10
0
    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 = {}
Пример #11
0
 def setUp(self):
     self.fh = opp.OpgSesame(
         os.path.join(self.BASE_DIR, self.reference_name),
         opp.OpgSesame.SINGLE)
     self.data = self.fh.data[self.tab_id]
Пример #12
0
    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()