| 1 |
"""Parser for the legacy line-based PES format. |
| 2 |
|
| 3 |
The format predates v4.2; despite the `.yaml` extension it isn't valid YAML |
| 4 |
(parens in species names like `Cu(III)-S` and the `[a, b, c]` PES point |
| 5 |
lists with bare identifiers would either fail or parse strangely). |
| 6 |
|
| 7 |
Sections are introduced by `--- # NAME` comment markers: |
| 8 |
|
| 9 |
--- # PES |
| 10 |
Reaction: [Int-I + TolS, Int-II, Int-III] |
| 11 |
--- # SPECIES |
| 12 |
Int-I: Int-I_* |
| 13 |
--- # FORMAT |
| 14 |
units: kcal/mol |
| 15 |
dec: 1 |
| 16 |
zero: Int-I + TolS |
| 17 |
|
| 18 |
The parser produces a `PESSpec`; format keys it doesn't consume (graph |
| 19 |
styling — dpi, color, title, etc.) are preserved in `format_extras` so |
| 20 |
`graph_reaction_profile` can keep reading them. |
| 21 |
""" |
| 22 |
from __future__ import annotations |
| 23 |
|
| 24 |
from typing import Dict, List, Optional, Tuple |
| 25 |
|
| 26 |
from .pes_model import PESOptions |
| 27 |
from .pes_loader import PESSpec |
| 28 |
|
| 29 |
|
| 30 |
# Section terminators: a `---` line OR end of file. |
| 31 |
def _split_sections(text: str) -> Dict[str, List[str]]: |
| 32 |
"""Split the input into named sections {PES, SPECIES, FORMAT}. |
| 33 |
|
| 34 |
Lines under each section header are returned with leading/trailing |
| 35 |
whitespace and pure-comment lines stripped. Blank lines are kept so |
| 36 |
a downstream parser can tell that a list ended. |
| 37 |
""" |
| 38 |
sections: Dict[str, List[str]] = {} |
| 39 |
current: Optional[str] = None |
| 40 |
for raw in text.splitlines(): |
| 41 |
stripped = raw.strip() |
| 42 |
if stripped.startswith("---"): |
| 43 |
current = None |
| 44 |
if "#" in stripped: |
| 45 |
marker = stripped.split("#", 1)[1].strip().upper() |
| 46 |
if marker in {"PES", "SPECIES", "FORMAT"}: |
| 47 |
current = marker |
| 48 |
sections.setdefault(current, []) |
| 49 |
continue |
| 50 |
if current is None: |
| 51 |
continue |
| 52 |
if stripped.startswith("#"): |
| 53 |
continue |
| 54 |
sections[current].append(raw) |
| 55 |
return sections |
| 56 |
|
| 57 |
|
| 58 |
def _split_kv(line: str) -> Optional[Tuple[str, str]]: |
| 59 |
"""Split a `key: value` or `key = value` line. Returns None if not a kv line.""" |
| 60 |
s = line.strip() |
| 61 |
if not s: |
| 62 |
return None |
| 63 |
# Allow either separator. We replace ':' with '=' so a single split works, |
| 64 |
# but only for the first occurrence — values can contain ':' in colors etc. |
| 65 |
if ":" in s and ("=" not in s or s.index(":") < s.index("=")): |
| 66 |
key, _, value = s.partition(":") |
| 67 |
elif "=" in s: |
| 68 |
key, _, value = s.partition("=") |
| 69 |
else: |
| 70 |
return None |
| 71 |
return key.strip(), value.strip() |
| 72 |
|
| 73 |
|
| 74 |
def _parse_pathways(lines: List[str]) -> Dict[str, List[str]]: |
| 75 |
"""Parse the PES section into {pathway_name: [point_label, ...]}. |
| 76 |
|
| 77 |
Each non-blank line is `name: [p1, p2, ...]`. Blank lines and comment |
| 78 |
lines are skipped. |
| 79 |
""" |
| 80 |
pathways: Dict[str, List[str]] = {} |
| 81 |
for line in lines: |
| 82 |
kv = _split_kv(line) |
| 83 |
if kv is None: |
| 84 |
continue |
| 85 |
name, value = kv |
| 86 |
if not (value.startswith("[") and value.endswith("]")): |
| 87 |
raise ValueError( |
| 88 |
f"PES section: pathway {name!r} value must be a [bracketed list], " |
| 89 |
f"got {value!r}" |
| 90 |
) |
| 91 |
inner = value[1:-1] |
| 92 |
# Split on commas but preserve `+` — point labels are e.g. "A + B". |
| 93 |
points = [p.strip() for p in inner.split(",")] |
| 94 |
points = [p for p in points if p] |
| 95 |
if not points: |
| 96 |
raise ValueError(f"PES section: pathway {name!r} has no points") |
| 97 |
pathways[name] = points |
| 98 |
if not pathways: |
| 99 |
raise ValueError("PES section is empty or missing") |
| 100 |
return pathways |
| 101 |
|
| 102 |
|
| 103 |
def _parse_species(lines: List[str]) -> Dict[str, str]: |
| 104 |
"""Parse the SPECIES section into {species_name: pattern}. |
| 105 |
|
| 106 |
`folder: PATH` lines are ignored (legacy used these to prefix paths; |
| 107 |
the modern orchestrator already provides full paths in thermo_data). |
| 108 |
""" |
| 109 |
species: Dict[str, str] = {} |
| 110 |
for line in lines: |
| 111 |
kv = _split_kv(line) |
| 112 |
if kv is None: |
| 113 |
continue |
| 114 |
key, value = kv |
| 115 |
if key.lower() == "folder": |
| 116 |
continue |
| 117 |
if not value: |
| 118 |
raise ValueError(f"SPECIES section: empty pattern for {key!r}") |
| 119 |
species[key] = value |
| 120 |
if not species: |
| 121 |
raise ValueError("SPECIES section is empty or missing") |
| 122 |
return species |
| 123 |
|
| 124 |
|
| 125 |
def _parse_format(lines: List[str]) -> Tuple[PESOptions, Dict[str, str], Dict[str, str]]: |
| 126 |
"""Parse the FORMAT section. Returns (PESOptions, zero overrides, extras). |
| 127 |
|
| 128 |
Recognised keys: |
| 129 |
units -> options.units |
| 130 |
dec -> options.decimals |
| 131 |
zero -> applies to *all* pathways (legacy never supported per-pathway) |
| 132 |
Any other key is preserved verbatim in `extras` for downstream consumers |
| 133 |
(graph_reaction_profile reads dpi, color, title, etc.). |
| 134 |
""" |
| 135 |
options = PESOptions() |
| 136 |
zero_default: Optional[str] = None |
| 137 |
extras: Dict[str, str] = {} |
| 138 |
for line in lines: |
| 139 |
kv = _split_kv(line) |
| 140 |
if kv is None: |
| 141 |
continue |
| 142 |
key, value = kv |
| 143 |
key_lower = key.lower() |
| 144 |
if key_lower == "units": |
| 145 |
if value not in ("kcal/mol", "kJ/mol"): |
| 146 |
raise ValueError( |
| 147 |
f"FORMAT.units: expected 'kcal/mol' or 'kJ/mol', got {value!r}" |
| 148 |
) |
| 149 |
options = _replace(options, units=value) |
| 150 |
elif key_lower == "dec": |
| 151 |
try: |
| 152 |
options = _replace(options, decimals=int(value)) |
| 153 |
except ValueError: |
| 154 |
raise ValueError(f"FORMAT.dec: expected integer, got {value!r}") |
| 155 |
elif key_lower == "zero": |
| 156 |
zero_default = value |
| 157 |
else: |
| 158 |
extras[key] = value |
| 159 |
zeros: Dict[str, str] = {} |
| 160 |
if zero_default is not None: |
| 161 |
zeros["__default__"] = zero_default # applied to all pathways at build time |
| 162 |
return options, zeros, extras |
| 163 |
|
| 164 |
|
| 165 |
def _replace(options: PESOptions, **kwargs) -> PESOptions: |
| 166 |
return PESOptions( |
| 167 |
units=kwargs.get("units", options.units), |
| 168 |
decimals=kwargs.get("decimals", options.decimals), |
| 169 |
gconf=kwargs.get("gconf", options.gconf), |
| 170 |
QH=kwargs.get("QH", options.QH), |
| 171 |
spc_used=kwargs.get("spc_used", options.spc_used), |
| 172 |
lowest_only=kwargs.get("lowest_only", options.lowest_only), |
| 173 |
) |
| 174 |
|
| 175 |
|
| 176 |
def parse_legacy(text: str) -> PESSpec: |
| 177 |
"""Parse the legacy line-based PES format into a `PESSpec`.""" |
| 178 |
sections = _split_sections(text) |
| 179 |
if "PES" not in sections: |
| 180 |
raise ValueError("legacy PES file is missing the `--- # PES` section") |
| 181 |
if "SPECIES" not in sections: |
| 182 |
raise ValueError("legacy PES file is missing the `--- # SPECIES` section") |
| 183 |
|
| 184 |
pathways = _parse_pathways(sections["PES"]) |
| 185 |
species = _parse_species(sections["SPECIES"]) |
| 186 |
|
| 187 |
options = PESOptions() |
| 188 |
zero_default: Dict[str, str] = {} |
| 189 |
extras: Dict[str, str] = {} |
| 190 |
if "FORMAT" in sections: |
| 191 |
options, raw_zeros, extras = _parse_format(sections["FORMAT"]) |
| 192 |
if "__default__" in raw_zeros: |
| 193 |
zero_default = {p: raw_zeros["__default__"] for p in pathways} |
| 194 |
|
| 195 |
return PESSpec( |
| 196 |
pathways=pathways, |
| 197 |
species=species, |
| 198 |
zero=zero_default, |
| 199 |
options=options, |
| 200 |
format_extras=extras, |
| 201 |
) |