"""Copyright (c) 2024 MPI-M, Clara Bayley----- CLEO -----File: readconfigfile.pyProject: cleopyCreated Date: Wednesday 17th April 2024Author: Clara Bayley (CB)Additional Contributors:-----License: BSD 3-Clause "New" or "Revised" Licensehttps://opensource.org/licenses/BSD-3-Clause-----File Description:"""fromruamel.yamlimportYAML
[docs]defextract_floats(node,floats,notfloats):"""Function to recursively searches YAML node and add any value that is convertible to a float to a dictionary with its key"""ifisinstance(node,dict):forkey,valueinnode.items():ifisinstance(value,(dict,list)):extract_floats(value,floats,notfloats)else:try:floats[key]=float(value)exceptValueError:notfloats[key]=valueelifisinstance(node,list):foriteminnode:extract_floats(item,floats,notfloats)returnfloats,notfloats
[docs]defread_configparams_into_floats(filename):"""returns dictionary of {key, values} pairs from keys from a config yaml file which can be assigned float values. Also obtains dictionary of notfloats for values that couldn't be converted and converts nspacedims to integer if found in floats."""yaml=YAML(typ="safe")withopen(filename,"r")asfile:config=yaml.load(file)floats,notfloats={},{}floats,notfloats=extract_floats(config,floats,notfloats)try:floats["nspacedims"]=int(floats["nspacedims"])# no spatial coords to SDsexceptKeyErrorase:print("Warning, ignoring error",e)passreturnfloats