52def parse(config: Any, source: str = "<string>") -> PIDModel:
53 """Check the structure of a parsed PID file and reorder it to SPECIES."""
54 if not isinstance(config, dict):
55 raise PIDConfigError(f"{source}: the top level must be a mapping")
56 unknown = sorted(str(k) for k in config if k not in _KEYS)
57 if unknown:
58 raise PIDConfigError(f"{source}: unknown key(s) {', '.join(unknown)}")
59
60 species = config.get("species", list(SPECIES))
61 if not isinstance(species, list) or sorted(map(str, species)) != sorted(SPECIES):
62 raise PIDConfigError(f"{source}: 'species' must be a permutation of {', '.join(SPECIES)}, not {species!r}")
63 order = [SPECIES.index(s) for s in species]
64
65 interpolation = config.get("interpolation", "linear")
66 if interpolation not in ("linear", "log"):
67 raise PIDConfigError(f"{source}: 'interpolation' must be linear or log, not {interpolation!r}")
68
69 points = config.get("points")
70 if not isinstance(points, list) or not points:
71 raise PIDConfigError(f"{source}: 'points' must be a non-empty list of {{energy, matrix}}")
72 energies: list[float] = []
73 matrices: list[float] = []
74 for k, point in enumerate(points):
75 where = f"points[{k}]"
76 if not isinstance(point, dict) or set(point) != {"energy", "matrix"}:
77 raise PIDConfigError(f"{source}: {where} must have exactly the keys 'energy' and 'matrix'")
78 energies.append(_number(point["energy"], f"{where}.energy", source))
79 rows = point["matrix"]
80 if not isinstance(rows, list) or len(rows) != 3 or any(not isinstance(r, list) or len(r) != 3 for r in rows):
81 raise PIDConfigError(f"{source}: {where}.matrix must be 3 rows of 3 numbers")
82 matrix = [0.0] * 9
83 for i, row in enumerate(rows):
84 for j, value in enumerate(row):
85 matrix[3 * order[i] + order[j]] = _number(value, f"{where}.matrix[{i}][{j}]", source)
86 matrices.extend(matrix)
87
88 overrides: dict[int, int] = {}
89 raw = config.get("pdg_overrides") or {}
90 if not isinstance(raw, dict):
91 raise PIDConfigError(f"{source}: 'pdg_overrides' must map PDG codes to species")
92 for pdg, name in raw.items():
93 if isinstance(pdg, bool) or not isinstance(pdg, int):
94 raise PIDConfigError(f"{source}: 'pdg_overrides' keys must be PDG codes, not {pdg!r}")
95 if not isinstance(name, str) or name not in _OVERRIDE_SPECIES:
96 raise PIDConfigError(
97 f"{source}: pdg_overrides[{pdg}] must be one of {', '.join(_OVERRIDE_SPECIES)}, not {name!r}"
98 )
99
100
101 overrides[pdg] = _OVERRIDE_SPECIES[name]
102
103 return PIDModel(energies, matrices, overrides, interpolation == "log")
104
105