Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating configuration name space #143

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/configuration/configuration_old.rst
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ parameter ``lum_density`` which sets the distance to :math:`\sqrt{\frac{1}{4 \pi
Config Reader
^^^^^^^^^^^^^

The YAML file is read by using a classmethod of the :meth:`~tardis.config_reader.TARDISConfiguration.from_yaml`.
The YAML file is read by using a classmethod of the :meth:`~tardis.config_reader.Configuration.from_yaml`.



Expand Down
2 changes: 1 addition & 1 deletion docs/physics/physical_quantities.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ and then run your calculation, which is based on your "my_config.yml" file
import logging
import warnings

tardis_config = config_reader.TARDISConfiguration.from_yaml("my_config.yml")
tardis_config = config_reader.Configuration.from_yaml("my_config.yml")
radial1d = model.Radial1DModel(tardis_config)
simulation.run_radial1d(radial1d)

Expand Down
2 changes: 1 addition & 1 deletion docs/running.rst
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Scripting TARDIS
from tardis import model, simulation
from tardis.io import config_reader

tardis_config = config_reader.TARDISConfiguration.from_yaml('myconfig.yml')
tardis_config = config_reader.Configuration.from_yaml('myconfig.yml')
radial1d_mdl = model.Radial1DModel(tardis_config)
simulation.run_radial1d(radial1d_mdl)

Expand Down
2 changes: 1 addition & 1 deletion scripts/tardis
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ if args.packet_log_file:
console_handler.setFormatter(packet_logging_formatter)
logger.addHandler(packet_logging_handler)

tardis_config = config_reader.TARDISConfiguration.from_yaml(args.config_fname)
tardis_config = config_reader.Configuration.from_yaml(args.config_fname)

radial1d_mdl = model.Radial1DModel(tardis_config)

Expand Down
132 changes: 111 additions & 21 deletions tardis/io/config_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from tardis.util import species_string_to_tuple, parse_quantity, \
element_symbol2atomic_number

import copy

pp = pprint.PrettyPrinter(indent=4)

Expand All @@ -28,6 +29,7 @@
'tardis_config_definition.yml')
#File parsers for different file formats:


density_structure_fileparser = {}

inv_ni56_efolding_time = 1 / (8.8 * u.day)
Expand Down Expand Up @@ -596,37 +598,125 @@ def calculate_w7_branch85_densities(velocities, time_explosion, time_0=19.999958
return densities[1:]


class TARDISConfigurationNameSpace(object):
def __init__(self, config_dict):
self.config_dict = config_dict
class ConfigurationNameSpace(dict):
"""
The configuration name space class allows to wrap a dictionary and adds
utility functions for easy access. Accesses like a.b.c are then possible

Code from http://goo.gl/KIaq8I

Parameters
----------

config_dict: ~dict
configuration dictionary

Returns
-------

config_ns: ConfigurationNameSpace
"""

marker = object()
def __init__(self, value=None):
if value is None:
pass
elif isinstance(value, dict):
for key in value:
self.__setitem__(key, value[key])
else:
raise TypeError, 'expected dict'

def __setitem__(self, key, value):
if isinstance(value, dict) and not isinstance(value,
ConfigurationNameSpace):
value = ConfigurationNameSpace(value)

if key in self and hasattr(self[key], 'unit'):
value = u.Quantity(value, self[key].unit)

dict.__setitem__(self, key, value)

def __getitem__(self, key):
return super(ConfigurationNameSpace, self).__getitem__(key)

def __getattr__(self, item):
if item in self.config_dict:
config_item = self.config_dict[item]
if isinstance(config_item, dict):
setattr(self, item, TARDISConfigurationNameSpace(config_item))
return getattr(self, item)
if item in self:
return self[item]
else:
super(ConfigurationNameSpace, self).__getattribute__(item)

__setattr__ = __setitem__

def __dir__(self):
self.keys()

def get_config_item(self, config_item_string):
"""
Get configuration items using a string of type 'a.b.param'

Parameters
----------

config_item_string: ~str
string of shape 'section1.sectionb.param1'
"""
config_item_path = config_item_string.split('.')

if len(config_item_path) == 1:
config_item = config_item_path[0]

if config_item.startswith('item'):
return self[config_item_path[0]]
else:
return self.config_dict[item]
return self[config_item]
elif len(config_item_path) == 2 and\
config_item_path[1].startswith('item'):
return self[config_item_path[0]][
int(config_item_path[1].replace('item', ''))]

else:
return super(TARDISConfigurationNameSpace, self).__getattribute__(item)
return self[config_item_path[0]].get_config_item(
'.'.join(config_item_path[1:]))

def set_config_item(self, config_item_string, value):
"""
set configuration items using a string of type 'a.b.param'

Parameters
----------

def __getitem__(self, item):
return self.config_dict.__getitem__(item)
config_item_string: ~str
string of shape 'section1.sectionb.param1'

def get(self, k, d=None):
return self.config_dict.get(k, d)
value:
value to set the parameter with it
"""

config_item_path = config_item_string.split('.')
if len(config_item_path) == 1:
self[config_item_path[0]] = value
elif len(config_item_path) == 2 and \
config_item_path[1].startswith('item'):
current_value = self[config_item_path[0]][
int(config_item_path[1].replace('item', ''))]
if hasattr(current_value, 'unit'):
self[config_item_path[0]][
int(config_item_path[1].replace('item', ''))] =\
u.Quantity(value, current_value.unit)
else:
self[config_item_path[0]][
int(config_item_path[1].replace('item', ''))] = value

def __repr__(self):
return pp.pformat(self.config_dict)
else:
self[config_item_path[0]].set_config_item(
'.'.join(config_item_path[1:]), value)

def __dir__(self):
return self.__dict__.keys() + self.config_dict.keys()
def deepcopy(self):
return ConfigurationNameSpace(copy.deepcopy(dict(self)))


class TARDISConfiguration(TARDISConfigurationNameSpace):
class Configuration(ConfigurationNameSpace):
"""
Tardis configuration class
"""
Expand Down Expand Up @@ -674,7 +764,7 @@ def from_config_dict(cls, config_dict, atom_data=None, test_parser=False,
Returns
-------

`tardis.config_reader.TARDISConfiguration`
`tardis.config_reader.Configuration`

"""

Expand Down Expand Up @@ -903,7 +993,7 @@ def from_config_dict(cls, config_dict, atom_data=None, test_parser=False,


def __init__(self, config_dict, atom_data):
super(TARDISConfiguration, self).__init__(config_dict)
super(Configuration, self).__init__(config_dict)
self.atom_data = atom_data
selected_atomic_numbers = self.abundances.index
if atom_data is not None:
Expand Down
25 changes: 13 additions & 12 deletions tardis/io/tests/test_config_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ def data_path(filename):
return os.path.join(data_dir, 'data', filename)

def test_config_namespace_attribute_test():
namespace = config_reader.TARDISConfigurationNameSpace({'param1':1})
namespace = config_reader.ConfigurationNameSpace({'param1':1})
assert namespace.param1 == 1

def test_config_namespace_attribute_test():
namespace = config_reader.TARDISConfigurationNameSpace({'param1':1})
namespace = config_reader.ConfigurationNameSpace({'param1':1})
with pytest.raises(AttributeError):
assert namespace.param2 == 1

Expand Down Expand Up @@ -74,7 +74,7 @@ class TestParsePaper1Config:

def setup(self):
#general parsing of the paper config
self.config = config_reader.TARDISConfiguration.from_yaml(data_path('paper1_tardis_configv1.yml'),
self.config = config_reader.Configuration.from_yaml(data_path('paper1_tardis_configv1.yml'),
test_parser=True)
self.yaml_data = yaml.load(open(data_path('paper1_tardis_configv1.yml')))

Expand Down Expand Up @@ -121,6 +121,7 @@ def test_spectrum_section(self):
assert self.config['spectrum']['bins'] == self.yaml_data['spectrum']['num']



def test_time_explosion(self):
assert_almost_equal(self.config['supernova']['time_explosion'],
13.0 * u.day)
Expand All @@ -130,7 +131,7 @@ class TestParseConfigV1ASCIIDensity:
def setup(self):
#general parsing of the paper config
filename = 'tardis_configv1_ascii_density.yml'
self.config = config_reader.TARDISConfiguration.from_yaml(data_path(filename),
self.config = config_reader.Configuration.from_yaml(data_path(filename),
test_parser=True)
self.yaml_data = yaml.load(open(data_path(filename)))

Expand All @@ -149,7 +150,7 @@ class TestParseConfigV1ArtisDensity:
def setup(self):
#general parsing of the paper config
filename = 'tardis_configv1_artis_density.yml'
self.config = config_reader.TARDISConfiguration.from_yaml(data_path(filename),
self.config = config_reader.Configuration.from_yaml(data_path(filename),
test_parser=True)
self.yaml_data = yaml.load(open(data_path(filename)))

Expand All @@ -176,7 +177,7 @@ def setup(self):
'filename': 'tardis/io/tests/data/artis_abundances.dat',
'filetype': 'artis'}

self.config = config_reader.TARDISConfiguration.from_config_dict(self.yaml_data,
self.config = config_reader.Configuration.from_config_dict(self.yaml_data,
test_parser=True)


Expand All @@ -199,7 +200,7 @@ def setup(self):
'filename': 'tardis/io/tests/data/artis_abundances.dat',
'filetype': 'artis'}

self.config = config_reader.TARDISConfiguration.from_config_dict(self.yaml_data,
self.config = config_reader.Configuration.from_config_dict(self.yaml_data,
test_parser=True)


Expand All @@ -221,7 +222,7 @@ def setup(self):
self.yaml_data['model']['structure']['filename'] = 'tardis/io/tests/data/density.dat'
self.yaml_data['model']['abundances']['filename'] = 'tardis/io/tests/data/abund.dat'

self.config = config_reader.TARDISConfiguration.from_config_dict(self.yaml_data,
self.config = config_reader.Configuration.from_config_dict(self.yaml_data,
test_parser=True)


Expand Down Expand Up @@ -266,8 +267,8 @@ def test_ascii_reader_power_law():

v_inner = yaml_data['model']['structure']['velocity']['start']
v_outer = yaml_data['model']['structure']['velocity']['stop']
my_conf = config_reader.TARDISConfiguration.from_yaml(data_path('tardis_configv1_density_power_law_test.yml'),test_parser=True)
structure = my_conf.config_dict['structure']
my_conf = config_reader.Configuration.from_yaml(data_path('tardis_configv1_density_power_law_test.yml'),test_parser=True)
structure = my_conf['structure']

expected_densites = [3.29072513e-14, 2.70357804e-14, 2.23776573e-14,
1.86501954e-14, 1.56435277e-14, 1.32001689e-14, 1.12007560e-14,
Expand All @@ -294,8 +295,8 @@ def test_ascii_reader_exponential_law():

v_inner = yaml_data['model']['structure']['velocity']['start']
v_outer = yaml_data['model']['structure']['velocity']['stop']
my_conf = config_reader.TARDISConfiguration.from_yaml(data_path('tardis_configv1_density_exponential_test.yml'),test_parser=True)
structure = my_conf.config_dict['structure']
my_conf = config_reader.Configuration.from_yaml(data_path('tardis_configv1_density_exponential_test.yml'),test_parser=True)
structure = my_conf['structure']

expected_densites = [5.18114795e-14, 4.45945537e-14, 3.83828881e-14, 3.30364579e-14, 2.84347428e-14, 2.44740100e-14, 2.10649756e-14, 1.81307925e-14, 1.56053177e-14, 1.34316215e-14, 1.15607037e-14, 9.95038990e-15, 8.56437996e-15, 7.37143014e-15, 6.34464872e-15, 5.46088976e-15, 4.70023138e-15, 4.04552664e-15, 3.48201705e-15, 2.99699985e-15]
expected_unit = 'g / (cm3)'
Expand Down
9 changes: 4 additions & 5 deletions tardis/io/tests/test_config_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ def test_default_parser_quantity():
return_default=return_default, return_value=return_value)




def test_default_parser_quantity_range():
example_dic = {'default': ['1 cm', '5 cm'],
'help': 'quantity for testing',
Expand Down Expand Up @@ -277,7 +279,7 @@ def test_default_parser_string():
ex = default_parser_helper(example_dic, default, wdefault, value, wvalue, container, mandatory)


def test_property_type_bundances():
def test_property_type_abundances():
example_dic = {'default': {'He': 0.4, 'Mg': 0.1, 'Pb': 0.5},
'help': 'quantity for testing',
'mandatory': True,
Expand All @@ -296,10 +298,7 @@ def test_property_type_bundances():
return_default=return_default, return_value=return_value)


#For Debug
#from tardis.io import config_validator as default_config_parser
#myconf = default_config_parser.Config.from_yaml('tardis/io/tests/data/tardis_configv1_density_exponential_test.yml','tardis/data/tardis_config_definition.yml')
#myconf = default_config_parser.Config.from_yaml('tardis/io/tests/data/conf_tes.yml','tardis/io/tests/data/conf_def.yml')




Loading