|
| 1 | +import json |
| 2 | +import os |
| 3 | +import sys |
| 4 | +import yaml |
| 5 | + |
| 6 | +# Add the parent directory to sys.path |
| 7 | +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) |
| 8 | + |
| 9 | +from schema.MagneticMultipoleParameters import MagneticMultipoleParameters |
| 10 | + |
| 11 | +from schema.DriftElement import DriftElement |
| 12 | +from schema.QuadrupoleElement import QuadrupoleElement |
| 13 | + |
| 14 | +from schema.Item import Item |
| 15 | +from schema.Line import Line |
| 16 | + |
| 17 | + |
| 18 | +def main(): |
| 19 | + drift1 = DriftElement( |
| 20 | + name="drift1", |
| 21 | + length=0.25, |
| 22 | + ) |
| 23 | + quad1 = QuadrupoleElement( |
| 24 | + name="quad1", |
| 25 | + length=1.0, |
| 26 | + MagneticMultipoleP=MagneticMultipoleParameters( |
| 27 | + Bn1=1.0, |
| 28 | + ), |
| 29 | + ) |
| 30 | + drift2 = DriftElement( |
| 31 | + name="drift2", |
| 32 | + length=0.5, |
| 33 | + ) |
| 34 | + quad2 = QuadrupoleElement( |
| 35 | + name="quad2", |
| 36 | + length=1.0, |
| 37 | + MagneticMultipoleP=MagneticMultipoleParameters( |
| 38 | + Bn1=-1.0, |
| 39 | + ), |
| 40 | + ) |
| 41 | + drift3 = DriftElement( |
| 42 | + name="drift3", |
| 43 | + length=0.5, |
| 44 | + ) |
| 45 | + # Create line with all elements |
| 46 | + line = Line( |
| 47 | + line=[ |
| 48 | + Item(item=drift1), |
| 49 | + Item(item=quad1), |
| 50 | + Item(item=drift2), |
| 51 | + Item(item=quad2), |
| 52 | + Item(item=drift3), |
| 53 | + ] |
| 54 | + ) |
| 55 | + # Serialize to YAML |
| 56 | + yaml_data = yaml.dump(line.model_dump(), default_flow_style=False) |
| 57 | + # Write YAML data to file |
| 58 | + yaml_file = "examples_fodo.yaml" |
| 59 | + with open(yaml_file, "w") as file: |
| 60 | + file.write(yaml_data) |
| 61 | + # Read YAML data from file |
| 62 | + with open(yaml_file, "r") as file: |
| 63 | + yaml_data = yaml.safe_load(file) |
| 64 | + # Parse YAML data |
| 65 | + loaded_line = Line(**yaml_data) |
| 66 | + # Validate loaded data |
| 67 | + assert line == loaded_line |
| 68 | + # Serialize to JSON |
| 69 | + json_data = json.dumps(line.model_dump(), sort_keys=True, indent=2) |
| 70 | + # Write JSON data to file |
| 71 | + json_file = "examples_fodo.json" |
| 72 | + with open(json_file, "w") as file: |
| 73 | + file.write(json_data) |
| 74 | + # Read JSON data from file |
| 75 | + with open(json_file, "r") as file: |
| 76 | + json_data = json.loads(file.read()) |
| 77 | + # Parse JSON data |
| 78 | + loaded_line = Line(**json_data) |
| 79 | + # Validate loaded data |
| 80 | + assert line == loaded_line |
| 81 | + |
| 82 | + |
| 83 | +if __name__ == "__main__": |
| 84 | + main() |
0 commit comments