Validate Configuration#
To make sure that the input data provided to pyAML has the correct format, validation is important. The validation is by default automatically performed when loading a configuration into the Accelerator, but it can also be done separately if one wishes. This guide shows how to do that.
For more details about schemas and the different types of validation, see Configuration Schemas and Validation.
The configuration can be validated using the SchemaValidator. It makes use of the schema registry to extract which schema to validate against for a specific class.
For validation to be possible the class must be registered in the schema registry.
Create the Registry#
First create the registry and register the classes you want included in the schema.
Here the discovery function is used to register all classes in pyaml and other packages which define entry points. See Use the Schema Registry for details.
from pyaml.validation import SchemaRegistry
registry = SchemaRegistry()
registry.discover()
Validate Data#
from pyaml.validation import SchemaValidator
# Create some configuration
configuration = {
"class_path": "pyaml.magnet.quadrupole.Quadrupole",
"name": "QF1",
"description": "This is the QF1 quadrupole magnet."
}
# Validate it
validated = SchemaValidator.validate(configuration)
# Print the validated ConfigurationSchema object
print(validated)
class_path='pyaml.magnet.quadrupole.Quadrupole' name='QF1' model=None lattice_names=None description='This is the QF1 quadrupole magnet.'
Validation also handles nested configuration data.
configuration = {
"class_path": "pyaml.magnet.quadrupole.Quadrupole",
"name": "QF1",
"model": {
"class_path": "pyaml.magnet.identity_model.IdentityMagnetModel",
"unit": "1/m",
"physics": ""
},
"description": "This is the QF1 quadrupole magnet."
}
validated = SchemaValidator.validate(configuration)
# Print the validated ConfigurationSchema object
print(validated)
class_path='pyaml.magnet.quadrupole.Quadrupole' name='QF1' model=IdentityMagnetModelConfigurationSchema(class_path='pyaml.magnet.identity_model.IdentityMagnetModel', powerconverter=None, physics='', unit='1/m') lattice_names=None description='This is the QF1 quadrupole magnet.'
The validated result can also be returned as a dictionary.
from pprint import pprint
validated_dict = SchemaValidator.validate_to_dict(configuration)
pprint(validated_dict )
{'class_path': 'pyaml.magnet.quadrupole.Quadrupole',
'description': 'This is the QF1 quadrupole magnet.',
'lattice_names': None,
'model': {'class_path': 'pyaml.magnet.identity_model.IdentityMagnetModel',
'physics': '',
'powerconverter': None,
'unit': '1/m'},
'name': 'QF1'}