Debian Codegraph @

goodvibes/pes_loader.py

raw
1 """Format-agnostic PES loading pipeline.
2
3 Three stages, each independently testable:
4
5 text ──parse_legacy()/parse_yaml()──▶ PESSpec
6 PESSpec + thermo_data ──build_pes_result()──▶ PESResult
7
8 `PESSpec` is the intermediate that both parsers produce: a description of
9 pathways, species (as file patterns), zero overrides, and options — but
10 *no* references to actual `calc_bbe` instances. The builder resolves
11 patterns against `thermo_data`, constructs `ConformerSet`s, and emits a
12 fully-realized `PESResult`.
13
14 The format dispatcher `load_pes()` sniffs the file content (presence of
15 `--- # PES`/`# SPECIES`/`# FORMAT` markers) to choose the parser; the
16 legacy path emits a `DeprecationWarning`.
17 """
18 from __future__ import annotations
19
20 import fnmatch
21 import os
22 import warnings
23 from dataclasses import dataclass, field
24 from pathlib import Path
25 from typing import Dict, List, Optional, Union
26
27 from .pes_model import (
28 ConformerSet, PESOptions, PESResult, Pathway, Point, parse_point_label,
29 )
30
31
32 # ---------------------------------------------------------------------------
33 # Intermediate: PESSpec
34 # ---------------------------------------------------------------------------
35
36 @dataclass
37 class PESSpec:
38 """Format-agnostic intermediate. Both parsers emit this.
39
40 Attributes:
41 pathways: pathway name -> ordered list of point labels.
42 species: species name -> file pattern (glob or literal) or list of patterns.
43 zero: pathway name -> point label to use as zero. Optional;
44 pathways missing from this dict default to their first point.
45 options: PESOptions parsed from the FORMAT block.
46 format_extras: any FORMAT keys not consumed by PESOptions
47 (kept verbatim so graph_reaction_profile can read them).
48 """
49 pathways: Dict[str, List[str]]
50 species: Dict[str, Union[str, List[str]]]
51 zero: Dict[str, str] = field(default_factory=dict)
52 options: PESOptions = field(default_factory=PESOptions)
53 format_extras: Dict[str, str] = field(default_factory=dict)
54
55
56 # ---------------------------------------------------------------------------
57 # Format detection
58 # ---------------------------------------------------------------------------
59
60 _LEGACY_MARKERS = {"PES", "SPECIES", "FORMAT"}
61
62
63 def is_legacy_format(text: str) -> bool:
64 """Sniff for the `--- # PES` / `# SPECIES` / `# FORMAT` markers.
65
66 Presence of any one of these markers anywhere in the file means legacy.
67 Otherwise the file is treated as true YAML.
68 """
69 for raw in text.splitlines():
70 line = raw.strip()
71 if line.startswith("---") and "#" in line:
72 comment = line.split("#", 1)[1].strip().upper()
73 if comment in _LEGACY_MARKERS:
74 return True
75 return False
76
77
78 # ---------------------------------------------------------------------------
79 # Pattern resolution
80 # ---------------------------------------------------------------------------
81
82 def _stem(path: str) -> str:
83 """Basename without final extension. 'foo/bar.log' -> 'bar'."""
84 return os.path.splitext(os.path.basename(path))[0]
85
86
87 def _parent_dir(path: str) -> str:
88 """Basename of the parent directory. 'A/B/c.log' -> 'B'; 'c.log' -> ''."""
89 parent = os.path.dirname(path)
90 return os.path.basename(parent) if parent else ""
91
92
93 def _strip_ext(pattern: str) -> str:
94 """Drop a trailing .log/.out so patterns can be written either way."""
95 for ext in (".log", ".out"):
96 if pattern.endswith(ext):
97 return pattern[: -len(ext)]
98 return pattern
99
100
101 #: Internal sentinel echoed from pes_yaml._DIR_PREFIX. Kept duplicated
102 #: rather than imported to avoid a circular import at module load.
103 _DIR_PREFIX = "@dir:"
104
105
106 def resolve_pattern(pattern: str, thermo_data: dict) -> List[str]:
107 """Resolve a species pattern against the keys of `thermo_data`.
108
109 Two pattern flavors:
110
111 * **File patterns** (default) — matched against the basename of each
112 key with the file extension stripped. Supports fnmatch globs;
113 a pattern with no glob characters must equal the stem exactly.
114
115 * **Directory patterns** — strings prefixed with `@dir:` (set
116 automatically by the YAML loader when the user writes
117 `{dir: "X"}` / `{dirs: [...]}`). Matched against the basename of
118 each key's *parent directory*. Supports fnmatch globs.
119
120 Returns the matched thermo_data keys in their original (insertion)
121 order.
122 """
123 if pattern.startswith(_DIR_PREFIX):
124 dir_pat = pattern[len(_DIR_PREFIX):].strip()
125 has_glob = any(c in dir_pat for c in "*?[")
126 matches: List[str] = []
127 for key in thermo_data:
128 parent = _parent_dir(key)
129 if has_glob:
130 if fnmatch.fnmatch(parent, dir_pat):
131 matches.append(key)
132 elif parent == dir_pat:
133 matches.append(key)
134 return matches
135
136 pat = _strip_ext(pattern.strip())
137 has_glob = any(c in pat for c in "*?[")
138 matches = []
139 for key in thermo_data:
140 stem = _stem(key)
141 if has_glob:
142 if fnmatch.fnmatch(stem, pat):
143 matches.append(key)
144 elif stem == pat:
145 matches.append(key)
146 return matches
147
148
149 def _resolve_species(
150 name: str,
151 pattern: Union[str, List[str]],
152 thermo_data: dict,
153 ) -> ConformerSet:
154 """Build a ConformerSet for one species by resolving its pattern(s)."""
155 patterns = [pattern] if isinstance(pattern, str) else list(pattern)
156 files: List[str] = []
157 for p in patterns:
158 files.extend(resolve_pattern(p, thermo_data))
159 # De-duplicate while preserving order (a species can list overlapping globs).
160 seen = set()
161 deduped = [f for f in files if not (f in seen or seen.add(f))]
162 if not deduped:
163 raise ValueError(
164 f"species {name!r}: no files matched pattern(s) {patterns!r}. "
165 f"available stems: {sorted({_stem(k) for k in thermo_data})}"
166 )
167 bbes = [thermo_data[f] for f in deduped]
168 return ConformerSet(name=name, files=deduped, bbes=bbes)
169
170
171 # ---------------------------------------------------------------------------
172 # Builder: PESSpec + thermo_data -> PESResult
173 # ---------------------------------------------------------------------------
174
175 def build_pes_result(
176 spec: PESSpec,
177 thermo_data: dict,
178 temperatures: Optional[List[float]] = None,
179 ) -> PESResult:
180 """Resolve patterns, build ConformerSets, parse point labels, return PESResult.
181
182 All species referenced (transitively) by the pathways' points must
183 resolve to at least one file in `thermo_data`; unresolved names raise
184 `KeyError`.
185 """
186 # 1. Build the species map by resolving every species mentioned anywhere.
187 needed: set = set()
188 for points in spec.pathways.values():
189 for point_label in points:
190 for _, name in parse_point_label(point_label):
191 needed.add(name)
192 for zero_label in spec.zero.values():
193 for _, name in parse_point_label(zero_label):
194 needed.add(name)
195
196 species_map: Dict[str, ConformerSet] = {}
197 for name in needed:
198 if name not in spec.species:
199 raise KeyError(
200 f"species {name!r} referenced by a pathway but not defined "
201 f"in the SPECIES block (defined: {sorted(spec.species)})"
202 )
203 species_map[name] = _resolve_species(name, spec.species[name], thermo_data)
204
205 # 2. Build pathways. For each pathway, parse every point, resolve zero.
206 pathways: List[Pathway] = []
207 for path_name, point_labels in spec.pathways.items():
208 points = [Point.from_label(label, species_map) for label in point_labels]
209 if path_name in spec.zero:
210 zero_point = Point.from_label(spec.zero[path_name], species_map)
211 else:
212 zero_point = points[0]
213 pathways.append(Pathway(name=path_name, points=points, zero=zero_point))
214
215 return PESResult(
216 pathways=pathways,
217 options=spec.options,
218 temperatures=temperatures or [298.15],
219 )
220
221
222 # ---------------------------------------------------------------------------
223 # Top-level dispatcher
224 # ---------------------------------------------------------------------------
225
226 def load_pes(
227 path: str,
228 thermo_data: dict,
229 temperatures: Optional[List[float]] = None,
230 ) -> PESResult:
231 """Read a PES definition file, parse it, and return a `PESResult`.
232
233 Sniffs the file format (legacy `--- # PES` markers vs proper YAML);
234 legacy emits a `DeprecationWarning`.
235 """
236 text = Path(path).read_text()
237 if is_legacy_format(text):
238 warnings.warn(
239 f"PES file {path!r} uses the legacy line-based format. "
240 "This format is deprecated and will be removed in v5.1; "
241 "see ROADMAP.md Sub-plan B for the new YAML schema.",
242 DeprecationWarning,
243 stacklevel=2,
244 )
245 from .pes_legacy import parse_legacy
246 spec = parse_legacy(text)
247 else:
248 from .pes_yaml import parse_yaml
249 spec = parse_yaml(text)
250 return build_pes_result(spec, thermo_data, temperatures=temperatures)