[docs]classConfig(CPPConfig):""" Wrapper for the C++ configuration data Allows transparent access to the values used for CPPN structure, genome mutation (:func:`Genome.mutate`), and ANN/ES-HyperNEAT parameters """OutputFunctions=_OutputFunctionsMutationRates=_MutationRates#: The set of all wrapped C++ values_dict={k:vfork,vinCPPConfig.__dict__.items()ifnotk.startswith('_')}#: Private reference to the config sections_sections=CPPConfig.__dict__['_sections']
[docs]@classmethoddefto_json(cls)->Dict:""" Convert to a json-compliant Python dictionary """dct={}forsection,itemsincls._sections.items():dct[section]={}forkinitems:attr=getattr(cls,k)ifhasattr(attr,"toJson"):attr=attr.toJson()dct[section][k]=attrpprint.pprint(dct)returndct
[docs]@classmethoddeffrom_json(cls,j:Dict):""" Restore values from a json-compliant Python dictionary :param j: the dictionary to parse values from """forsection,itemsincls._sections.items():forkinitems:attr=j[section][k]this_attr=getattr(cls,k)ifhasattr(this_attr,"fromJson"):j_attr=attrattr=type(this_attr).fromJson(j_attr)ifnotattr.isValid():raiseValueError(f"{attr} is not a valid value for {k}")try:setattr(cls,k,attr)exceptTypeErrorase:raiseTypeError(f"Failed to convert {attr}:"f" {type(attr)} -> {type(this_attr)}\n{e}")
[docs]@classmethoddefwrite(cls,path:Optional[Path]):""" Write the configuration to the specified file or stdout :param path: where to write or none to print to screen """ifpathisnotNoneandpath.exists():raiseIOError(f"Will not overwrite existing "f"file {path} with this one")json_cls=cls.to_json()ifpathisNone:pprint.pprint(json_cls)else:withopen(path,'w')asf:json.dump(json_cls,f)assertpath.exists()
[docs]@classmethoddefshow(cls):""" Write the configuration on standard output """cls.write(path=None)
[docs]@classmethoddefread(cls,path:Path):""" Try to load data from provided path :param path: Filename """ifnotpath.exists():raiseIOError(f"Input path '{path}' does not exist")withopen(path,'r')asf:cls.from_json(json.load(f))try:# Delegate relationship tests to the C++Config.test_valid()exceptValueErrorase:raiseValueError("C++ layer exception when checking"" the provided configuration") \
fromereturnpath