From d5da47bf7145c4246b21c0856715d8140251a026 Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Thu, 2 Dec 2021 18:20:27 -0500 Subject: [PATCH] extend config init to allow YAML string and key=value pairs --- python/damask/_config.py | 9 +++++++++ python/damask/_configmaterial.py | 14 ++++++++++---- python/tests/test_Config.py | 8 ++++++++ 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/python/damask/_config.py b/python/damask/_config.py index 7b2023a47..2f5904cc6 100644 --- a/python/damask/_config.py +++ b/python/damask/_config.py @@ -38,6 +38,15 @@ class NiceDumper(yaml.SafeDumper): class Config(dict): """YAML-based configuration.""" + def __init__(self,yml=None,**kwargs): + """Initialize from YAML, dict, or key=value pairs.""" + if isinstance(yml,str): + kwargs.update(yaml.safe_load(yml)) + elif isinstance(yml,dict): + kwargs.update(yml) + + super().__init__(**kwargs) + def __repr__(self): """Show as in file.""" output = StringIO() diff --git a/python/damask/_configmaterial.py b/python/damask/_configmaterial.py index d1091aa76..1b4d4439c 100644 --- a/python/damask/_configmaterial.py +++ b/python/damask/_configmaterial.py @@ -17,18 +17,24 @@ class ConfigMaterial(Config): """ - def __init__(self,d=None): + def __init__(self,d=None,**kwargs): """ New material configuration. Parameters ---------- - d : dictionary, optional + d : dictionary or YAML string, optional Initial content. Defaults to None, in which case empty entries for - material, homogenization, and phase are created. + any missing material, homogenization, and phase entry are created. + kwargs : key=value pairs, optional + Initial content specified as pairs of key=value. """ - super().__init__({'material': [], 'homogenization': {}, 'phase': {}} if d is None else d) + if d is None: + for section,default in {'material':[],'homogenization':{},'phase':{}}.items(): + if section not in kwargs: kwargs.update({section:default}) + + super().__init__(d,**kwargs) def save(self,fname='material.yaml',**kwargs): diff --git a/python/tests/test_Config.py b/python/tests/test_Config.py index ae93b231d..e6fa2daff 100644 --- a/python/tests/test_Config.py +++ b/python/tests/test_Config.py @@ -59,3 +59,11 @@ class TestConfig: @pytest.mark.parametrize('data',[Rotation.from_random(),Orientation.from_random(lattice='cI')]) def test_rotation_orientation(self,data): assert str(Config(a=data)) == str(Config(a=data.as_quaternion())) + + def test_initialize(self): + yml = """ + a: + - 1 + - 2 + """ + assert Config(yml) == Config('{"a":[1,2]}') == Config(a=[1,2]) == Config(dict(a=[1,2]))