Merge branch 'config-init-yaml' into 'development'

extend config init to allow YAML string and key=value pairs

See merge request damask/DAMASK!470
This commit is contained in:
Martin Diehl 2021-12-03 04:37:23 +00:00
commit 7a78a25e5c
3 changed files with 27 additions and 4 deletions

View File

@ -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()

View File

@ -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):

View File

@ -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]))