Debian Codegraph @

goodvibes/pes_yaml.py

raw
1 """Parser for the new (true YAML) PES format.
2
3 Schema:
4
5 pathways:
6 Reaction: ["Int-I + TolS + TolSH", "Int-II + TolSH", "Int-III"]
7
8 species:
9 Int-I: {files: "Int-I_*.log"}
10 TolS: {files: ["TolS.log"]}
11 Int-II: {files: "Int-II_*.log"}
12
13 zero:
14 Reaction: "Int-I + TolS + TolSH" # optional; defaults to points[0]
15
16 format:
17 units: kcal/mol
18 decimals: 1
19
20 `pathways` is a dict of pathway-name → ordered list of point label strings.
21 `species` is a dict of species-name → {files: <glob string OR list>} (the
22 dict shape leaves room for per-species options later — scaling factors,
23 symmetry numbers — without breaking the schema). `zero` is optional and
24 applies per pathway. `format` parses into `PESOptions`.
25 """
26 from __future__ import annotations
27
28 from typing import Dict, List, Tuple, Union
29
30 from .pes_legacy import _replace
31 from .pes_loader import PESSpec
32 from .pes_model import PESOptions
33
34
35 def parse_yaml(text: str) -> PESSpec:
36 """Parse the YAML text into a `PESSpec`. PyYAML is required."""
37 try:
38 import yaml
39 except ImportError:
40 raise RuntimeError(
41 "PyYAML is required to read modern PES YAML files. Install with "
42 "`pip install pyyaml`, or use the legacy `--- # PES` format."
43 )
44 data = yaml.safe_load(text)
45 if not isinstance(data, dict):
46 raise ValueError("PES YAML root must be a mapping")
47
48 if "pathways" not in data:
49 raise ValueError("PES YAML must define a top-level `pathways:` block")
50 if "species" not in data:
51 raise ValueError("PES YAML must define a top-level `species:` block")
52
53 pathways = _parse_pathways(data["pathways"])
54 species = _parse_species(data["species"])
55 zero = _parse_zero(data.get("zero", {}), pathways)
56 options, extras = _parse_format(data.get("format", {}))
57
58 return PESSpec(
59 pathways=pathways,
60 species=species,
61 zero=zero,
62 options=options,
63 format_extras=extras,
64 )
65
66
67 def _parse_pathways(raw) -> Dict[str, List[str]]:
68 if not isinstance(raw, dict):
69 raise ValueError(f"`pathways` must be a mapping, got {type(raw).__name__}")
70 pathways: Dict[str, List[str]] = {}
71 for name, points in raw.items():
72 if not isinstance(points, list):
73 raise ValueError(
74 f"pathway {name!r}: points must be a list of strings, "
75 f"got {type(points).__name__}"
76 )
77 cleaned = [str(p).strip() for p in points if str(p).strip()]
78 if not cleaned:
79 raise ValueError(f"pathway {name!r} has no points")
80 pathways[str(name)] = cleaned
81 if not pathways:
82 raise ValueError("`pathways` is empty")
83 return pathways
84
85
86 def _parse_species(raw) -> Dict[str, Union[str, List[str]]]:
87 if not isinstance(raw, dict):
88 raise ValueError(f"`species` must be a mapping, got {type(raw).__name__}")
89 species: Dict[str, Union[str, List[str]]] = {}
90 for name, entry in raw.items():
91 files = _extract_files(name, entry)
92 species[str(name)] = files
93 if not species:
94 raise ValueError("`species` is empty")
95 return species
96
97
98 #: Internal prefix used to encode a "match this directory" pattern in the
99 #: same `Union[str, List[str]]` value space as file globs. Users never see
100 #: it — they write `{dir: "X"}` in YAML and the loader translates.
101 _DIR_PREFIX = "@dir:"
102
103
104 def _extract_files(name: str, entry) -> Union[str, List[str]]:
105 """A species entry can be:
106 {files: "glob"} # match by filename stem (default)
107 {files: ["a.log", "b.log", ...]}
108 {dir: "subdir"} # match files whose parent dir basename matches
109 {dirs: ["sub_a", "sub_b", ...]} # multiple directories
110 {files: [...], dir: "X"} # combined: union of both rules
111 "glob" # shorthand: bare string (file pattern)
112 ["a.log", ...] # shorthand: bare list (file patterns)
113
114 Directory entries can themselves be fnmatch globs (e.g. `dir: "TS_*"`).
115 A trailing "/*" or "/**" on a directory name is dropped automatically
116 so users can write either `dir: "X"` or `dir: "X/*"`.
117 """
118 if isinstance(entry, str):
119 return entry
120 if isinstance(entry, list):
121 return [str(x) for x in entry]
122 if isinstance(entry, dict):
123 if "files" not in entry and "dir" not in entry and "dirs" not in entry:
124 raise ValueError(
125 f"species {name!r}: needs at least one of `files:`, `dir:`, "
126 "or `dirs:`"
127 )
128 out: List[str] = []
129 if "files" in entry:
130 files = entry["files"]
131 if isinstance(files, str):
132 out.append(files)
133 elif isinstance(files, list):
134 out.extend(str(x) for x in files)
135 else:
136 raise ValueError(
137 f"species {name!r}: `files:` must be a string or list, "
138 f"got {type(files).__name__}"
139 )
140 if "dir" in entry:
141 d = entry["dir"]
142 if not isinstance(d, str):
143 raise ValueError(
144 f"species {name!r}: `dir:` must be a string, "
145 f"got {type(d).__name__}"
146 )
147 out.append(_DIR_PREFIX + _normalize_dir(d))
148 if "dirs" in entry:
149 dirs = entry["dirs"]
150 if not isinstance(dirs, list):
151 raise ValueError(
152 f"species {name!r}: `dirs:` must be a list of strings, "
153 f"got {type(dirs).__name__}"
154 )
155 for d in dirs:
156 if not isinstance(d, str):
157 raise ValueError(
158 f"species {name!r}: `dirs:` entries must be strings, "
159 f"got {type(d).__name__}"
160 )
161 out.append(_DIR_PREFIX + _normalize_dir(d))
162 # Single string vs list — preserve old single-string shape for
163 # back-compat with external code that introspects PESSpec.species.
164 return out[0] if len(out) == 1 else out
165 raise ValueError(
166 f"species {name!r}: entry must be a string, list, or mapping, "
167 f"got {type(entry).__name__}"
168 )
169
170
171 def _normalize_dir(d: str) -> str:
172 """Strip trailing slashes / globs so `dir: "X/"` / `dir: "X/*"` /
173 `dir: "X/**"` all normalize to `"X"`."""
174 d = d.strip().rstrip("/")
175 for tail in ("/**", "/*"):
176 if d.endswith(tail):
177 d = d[: -len(tail)]
178 return d
179
180
181 def _parse_zero(raw, pathways: Dict[str, List[str]]) -> Dict[str, str]:
182 if not raw:
183 return {}
184 if not isinstance(raw, dict):
185 raise ValueError(f"`zero` must be a mapping, got {type(raw).__name__}")
186 zeros: Dict[str, str] = {}
187 for path_name, label in raw.items():
188 if path_name not in pathways:
189 raise ValueError(
190 f"`zero.{path_name}` references unknown pathway "
191 f"(known: {sorted(pathways)})"
192 )
193 zeros[str(path_name)] = str(label).strip()
194 return zeros
195
196
197 def _parse_format(raw) -> Tuple[PESOptions, Dict[str, str]]:
198 if not raw:
199 return PESOptions(), {}
200 if not isinstance(raw, dict):
201 raise ValueError(f"`format` must be a mapping, got {type(raw).__name__}")
202 options = PESOptions()
203 extras: Dict[str, str] = {}
204 for key, value in raw.items():
205 key_lower = str(key).lower()
206 if key_lower == "units":
207 if value not in ("kcal/mol", "kJ/mol"):
208 raise ValueError(
209 f"format.units: expected 'kcal/mol' or 'kJ/mol', got {value!r}"
210 )
211 options = _replace(options, units=value)
212 elif key_lower in ("decimals", "dec"):
213 try:
214 options = _replace(options, decimals=int(value))
215 except (ValueError, TypeError):
216 raise ValueError(f"format.decimals: expected integer, got {value!r}")
217 else:
218 extras[str(key)] = str(value)
219 return options, extras