| 1 |
"""Boltzmann weighting and selectivity calculations for GoodVibes.""" |
| 2 |
import fnmatch |
| 3 |
import logging |
| 4 |
import math |
| 5 |
import os.path |
| 6 |
import sys |
| 7 |
import warnings |
| 8 |
from dataclasses import dataclass |
| 9 |
from glob import glob |
| 10 |
from typing import Dict, List, Optional |
| 11 |
|
| 12 |
from .constants import GAS_CONSTANT, J_TO_AU, KCAL_TO_AU |
| 13 |
from .sort import SORT_KEYS |
| 14 |
|
| 15 |
log = logging.getLogger('goodvibes') |
| 16 |
|
| 17 |
|
| 18 |
# --------------------------------------------------------------------------- |
| 19 |
# Structured selectivity result (v4.2+) |
| 20 |
# --------------------------------------------------------------------------- |
| 21 |
|
| 22 |
@dataclass(frozen=True) |
| 23 |
class SelectivityResult: |
| 24 |
"""N-species selectivity outcome at one temperature. |
| 25 |
|
| 26 |
Numeric data only — formatting strings (e.g. "60:40", "1.5:1") are |
| 27 |
derived in the print layer from `populations`. Pairwise data are not |
| 28 |
stored here: for N=2, ee + ddG suffice; for N>2, downstream consumers |
| 29 |
derive any ratios they need from `populations`. |
| 30 |
""" |
| 31 |
temperature: float # Kelvin |
| 32 |
key: str # 'gibbs' | 'energy' |
| 33 |
labels: List[str] # ordered species names |
| 34 |
files_per_label: Dict[str, List[str]] # species -> file paths |
| 35 |
populations: Dict[str, float] # normalized: Σ = 1.0 |
| 36 |
raw_boltzmann: Dict[str, float] # un-normalized e^(-ΔG/RT) |
| 37 |
preferred: str # max-population label |
| 38 |
ee: Optional[float] = None # 2-label only: (a-b)*100, in % |
| 39 |
ddG: Optional[float] = None # 2-label only: ΔΔG‡ in Hartree |
| 40 |
|
| 41 |
|
| 42 |
# --------------------------------------------------------------------------- |
| 43 |
# Label-spec parsing |
| 44 |
# --------------------------------------------------------------------------- |
| 45 |
|
| 46 |
def parse_label_args(label_args): |
| 47 |
"""Parse repeatable --label NAME=PATTERN args into an ordered dict. |
| 48 |
|
| 49 |
Parameters: |
| 50 |
label_args (list[str] or None): values from argparse for --label. |
| 51 |
|
| 52 |
Returns: |
| 53 |
dict[str, str]: ordered mapping label -> fnmatch glob pattern. |
| 54 |
""" |
| 55 |
if not label_args: |
| 56 |
return {} |
| 57 |
spec = {} |
| 58 |
for arg in label_args: |
| 59 |
if '=' not in arg: |
| 60 |
raise ValueError( |
| 61 |
f"Invalid --label {arg!r}: expected NAME=PATTERN " |
| 62 |
"(e.g. --label R='*P_R_*')." |
| 63 |
) |
| 64 |
name, _, pattern = arg.partition('=') |
| 65 |
name = name.strip() |
| 66 |
pattern = pattern.strip() |
| 67 |
if not name or not pattern: |
| 68 |
raise ValueError( |
| 69 |
f"Invalid --label {arg!r}: NAME and PATTERN must both be " |
| 70 |
"non-empty." |
| 71 |
) |
| 72 |
if name in spec: |
| 73 |
raise ValueError(f"Duplicate --label name {name!r}.") |
| 74 |
spec[name] = pattern |
| 75 |
return spec |
| 76 |
|
| 77 |
|
| 78 |
def load_label_yaml(path): |
| 79 |
"""Load a selectivity YAML file. |
| 80 |
|
| 81 |
Supports two shapes (mutually exclusive): |
| 82 |
labels: { R: '*P_R_*', S: '*P_S_*' } # fnmatch patterns |
| 83 |
files: { R: [a.log, b.log], S: [c.log, ...] } # explicit file lists |
| 84 |
|
| 85 |
Returns: |
| 86 |
(mode, dict): mode is 'patterns' or 'files'; dict maps label to its |
| 87 |
spec (string pattern, or list of file paths). |
| 88 |
""" |
| 89 |
try: |
| 90 |
import yaml |
| 91 |
except ImportError: |
| 92 |
raise RuntimeError( |
| 93 |
"PyYAML is required for --selectivity. Install with " |
| 94 |
"`pip install pyyaml` or use --label instead." |
| 95 |
) |
| 96 |
with open(path, 'r', encoding='utf-8') as f: |
| 97 |
data = yaml.safe_load(f) or {} |
| 98 |
if 'labels' in data and 'files' in data: |
| 99 |
raise ValueError( |
| 100 |
f"{path}: provide either 'labels' (patterns) OR 'files' " |
| 101 |
"(explicit lists), not both." |
| 102 |
) |
| 103 |
if 'labels' in data: |
| 104 |
return 'patterns', dict(data['labels']) |
| 105 |
if 'files' in data: |
| 106 |
return 'files', {k: list(v) for k, v in data['files'].items()} |
| 107 |
raise ValueError( |
| 108 |
f"{path}: top-level key 'labels' or 'files' is required." |
| 109 |
) |
| 110 |
|
| 111 |
|
| 112 |
def assign_files_to_labels(files, label_patterns): |
| 113 |
"""Group file paths by fnmatch against each label's pattern. |
| 114 |
|
| 115 |
Each pattern is tested against TWO candidates per file, in order: |
| 116 |
|
| 117 |
1. the file's basename (e.g. ``DA_exo_12_i.out``) — matches when |
| 118 |
species are encoded in the filename, the v4.x default. |
| 119 |
2. the basename of the file's immediate parent directory |
| 120 |
(e.g. ``exo``) — matches when species are organized into |
| 121 |
per-species subdirectories. |
| 122 |
|
| 123 |
A file is assigned to the **first label** whose pattern matches |
| 124 |
either candidate. So a layout like ``exo/DA_*.out`` ``endo/DA_*.out`` |
| 125 |
works with ``--label exo=exo --label endo=endo`` (parent-dir |
| 126 |
match), and the original ``--label exo='*_exo_*'`` (basename |
| 127 |
match) keeps working unchanged. |
| 128 |
|
| 129 |
Parameters: |
| 130 |
files (Iterable[str]): file paths to species. |
| 131 |
label_patterns (dict): ordered label -> fnmatch glob pattern. |
| 132 |
|
| 133 |
Returns: |
| 134 |
dict[str, list[str]]: label -> list of matching file paths. |
| 135 |
""" |
| 136 |
speciess = {label: [] for label in label_patterns} |
| 137 |
for file in files: |
| 138 |
base = os.path.basename(file) |
| 139 |
parent = os.path.basename(os.path.dirname(file)) |
| 140 |
for label, pattern in label_patterns.items(): |
| 141 |
if (fnmatch.fnmatch(base, pattern) |
| 142 |
or (parent and fnmatch.fnmatch(parent, pattern))): |
| 143 |
speciess[label].append(file) |
| 144 |
break |
| 145 |
return speciess |
| 146 |
|
| 147 |
|
| 148 |
# --------------------------------------------------------------------------- |
| 149 |
# Core compute |
| 150 |
# --------------------------------------------------------------------------- |
| 151 |
|
| 152 |
def _excluded_files(dup_list): |
| 153 |
"""Set of file paths to exclude from sums based on a dup_list. |
| 154 |
|
| 155 |
Convention from `sort.deduplicate`: each pair is [duplicate, canonical]. |
| 156 |
The first element is the redundant copy that should be dropped; the |
| 157 |
second is the kept structure. Excluding only the first member matches |
| 158 |
the existing behavior of `get_boltz` and `get_selectivity` and avoids |
| 159 |
over-counting losses. |
| 160 |
""" |
| 161 |
excluded = set() |
| 162 |
if not dup_list: |
| 163 |
return excluded |
| 164 |
for pair in dup_list: |
| 165 |
if pair: |
| 166 |
excluded.add(pair[0]) |
| 167 |
return excluded |
| 168 |
|
| 169 |
|
| 170 |
def compute_selectivity(thermo_data, files_per_label, temperature, |
| 171 |
dup_list=None, key='gibbs'): |
| 172 |
"""Compute populations and (for N=2) ee + ΔΔG‡ for a labeled species set. |
| 173 |
|
| 174 |
Parameters: |
| 175 |
thermo_data (dict): file path -> calc_bbe. |
| 176 |
files_per_label (dict): ordered label -> list of file paths. |
| 177 |
temperature (float): Kelvin. |
| 178 |
dup_list (list, optional): pairs of duplicate files to exclude |
| 179 |
from sums. |
| 180 |
key (str): 'gibbs' (qh_gibbs_free_energy) or 'energy' (scf_energy). |
| 181 |
|
| 182 |
Returns: |
| 183 |
SelectivityResult. |
| 184 |
|
| 185 |
Raises: |
| 186 |
ValueError: if any label has no files, or if no files have a usable |
| 187 |
energy attribute. |
| 188 |
""" |
| 189 |
attr = SORT_KEYS[key] |
| 190 |
excluded = _excluded_files(dup_list) |
| 191 |
labels = list(files_per_label.keys()) |
| 192 |
if len(labels) < 2: |
| 193 |
raise ValueError("Selectivity needs at least two labels.") |
| 194 |
|
| 195 |
empty = [label for label in labels if not files_per_label[label]] |
| 196 |
if empty: |
| 197 |
raise ValueError( |
| 198 |
f"No files matched the following label(s): {', '.join(empty)}. " |
| 199 |
"Check the patterns or file lists in your selectivity spec." |
| 200 |
) |
| 201 |
|
| 202 |
# Find the global minimum energy (across all labeled files we'll keep) so |
| 203 |
# we can shift before exponentiating to avoid float overflow / underflow. |
| 204 |
e_min = math.inf |
| 205 |
for label in labels: |
| 206 |
for file in files_per_label[label]: |
| 207 |
if file in excluded: |
| 208 |
continue |
| 209 |
bbe = thermo_data.get(file) |
| 210 |
if bbe is None: |
| 211 |
continue |
| 212 |
val = getattr(bbe, attr, None) |
| 213 |
if val is not None and val < e_min: |
| 214 |
e_min = val |
| 215 |
if not math.isfinite(e_min): |
| 216 |
raise ValueError( |
| 217 |
"No files in any label had a usable energy attribute " |
| 218 |
f"({attr}); cannot compute selectivity." |
| 219 |
) |
| 220 |
|
| 221 |
raw = {label: 0.0 for label in labels} |
| 222 |
rt = GAS_CONSTANT * temperature # J/mol |
| 223 |
for label in labels: |
| 224 |
for file in files_per_label[label]: |
| 225 |
if file in excluded: |
| 226 |
continue |
| 227 |
bbe = thermo_data.get(file) |
| 228 |
if bbe is None: |
| 229 |
continue |
| 230 |
val = getattr(bbe, attr, None) |
| 231 |
if val is None: |
| 232 |
continue |
| 233 |
raw[label] += math.exp(-(val - e_min) * J_TO_AU / rt) |
| 234 |
|
| 235 |
total = sum(raw.values()) |
| 236 |
if total == 0.0: |
| 237 |
raise ValueError( |
| 238 |
"Boltzmann sums are zero across all labels; cannot compute " |
| 239 |
"selectivity." |
| 240 |
) |
| 241 |
|
| 242 |
populations = {label: raw[label] / total for label in labels} |
| 243 |
preferred = max(populations, key=populations.get) |
| 244 |
|
| 245 |
ee = None |
| 246 |
ddG = None |
| 247 |
if len(labels) == 2: |
| 248 |
a, b = labels |
| 249 |
pa = populations[a] |
| 250 |
pb = populations[b] |
| 251 |
ee = abs(pa - pb) * 100.0 |
| 252 |
# ΔΔG‡ = RT ln(p_major / p_minor), in Hartree, positive by convention |
| 253 |
# (the gap between major and minor TS). None when one species is |
| 254 |
# empty enough that the ratio diverges. |
| 255 |
if pa > 0 and pb > 0: |
| 256 |
ddG = rt * math.log(max(pa, pb) / min(pa, pb)) / J_TO_AU |
| 257 |
else: |
| 258 |
ddG = None |
| 259 |
|
| 260 |
return SelectivityResult( |
| 261 |
temperature=temperature, |
| 262 |
key=key, |
| 263 |
labels=labels, |
| 264 |
files_per_label={label: list(files_per_label[label]) for label in labels}, |
| 265 |
populations=populations, |
| 266 |
raw_boltzmann=raw, |
| 267 |
preferred=preferred, |
| 268 |
ee=ee, |
| 269 |
ddG=ddG, |
| 270 |
) |
| 271 |
|
| 272 |
|
| 273 |
def compute_selectivity_scan(thermo_data, files_per_label, temperatures, |
| 274 |
dup_list=None, key='gibbs'): |
| 275 |
"""Compute a SelectivityResult at each temperature in `temperatures`. |
| 276 |
|
| 277 |
Convenience wrapper that pairs naturally with --ti temperature |
| 278 |
intervals; the species grouping is fixed across temperatures. |
| 279 |
""" |
| 280 |
return [ |
| 281 |
compute_selectivity(thermo_data, files_per_label, T, |
| 282 |
dup_list=dup_list, key=key) |
| 283 |
for T in temperatures |
| 284 |
] |
| 285 |
|
| 286 |
|
| 287 |
def _lowest_per_label(thermo_data, files_per_label, dup_list, key): |
| 288 |
"""Return a {label: [single_lowest_file]} reduction of files_per_label. |
| 289 |
|
| 290 |
For each species, picks the conformer with the lowest energy attribute, |
| 291 |
skipping files in dup_list[k][0] and files with no usable energy. |
| 292 |
""" |
| 293 |
attr = SORT_KEYS[key] |
| 294 |
excluded = _excluded_files(dup_list) |
| 295 |
minimal = {} |
| 296 |
for label, files in files_per_label.items(): |
| 297 |
best, best_val = None, math.inf |
| 298 |
for f in files: |
| 299 |
if f in excluded: |
| 300 |
continue |
| 301 |
bbe = thermo_data.get(f) |
| 302 |
if bbe is None: |
| 303 |
continue |
| 304 |
val = getattr(bbe, attr, None) |
| 305 |
if val is None: |
| 306 |
continue |
| 307 |
if val < best_val: |
| 308 |
best, best_val = f, val |
| 309 |
minimal[label] = [best] if best is not None else [] |
| 310 |
return minimal |
| 311 |
|
| 312 |
|
| 313 |
def compute_selectivity_lowest_only(thermo_data, files_per_label, temperature, |
| 314 |
dup_list=None, key='gibbs'): |
| 315 |
"""Selectivity using only the most stable conformer per species. |
| 316 |
|
| 317 |
For each label, picks the file with the lowest `key` (default |
| 318 |
qh_gibbs_free_energy), drops the rest, and runs the standard |
| 319 |
Boltzmann calc on the resulting 1-conformer-per-species set. The |
| 320 |
result complements compute_selectivity by showing how much of the |
| 321 |
selectivity comes from conformer mixing versus the gap between the |
| 322 |
lowest TSs. |
| 323 |
""" |
| 324 |
minimal = _lowest_per_label(thermo_data, files_per_label, dup_list, key) |
| 325 |
return compute_selectivity(thermo_data, minimal, temperature, |
| 326 |
dup_list=dup_list, key=key) |
| 327 |
|
| 328 |
|
| 329 |
def compute_selectivity_lowest_only_scan(thermo_data, files_per_label, |
| 330 |
temperatures, dup_list=None, |
| 331 |
key='gibbs'): |
| 332 |
"""Lowest-only selectivity at each temperature in `temperatures`.""" |
| 333 |
minimal = _lowest_per_label(thermo_data, files_per_label, dup_list, key) |
| 334 |
return [compute_selectivity(thermo_data, minimal, T, |
| 335 |
dup_list=dup_list, key=key) |
| 336 |
for T in temperatures] |
| 337 |
|
| 338 |
|
| 339 |
# --------------------------------------------------------------------------- |
| 340 |
# Boltzmann weighting (unchanged) |
| 341 |
# --------------------------------------------------------------------------- |
| 342 |
|
| 343 |
def get_boltz(thermo_data, temperature, dup_list, key='gibbs'): |
| 344 |
"""Produce normalized Boltzmann populations across all files. |
| 345 |
|
| 346 |
Used by `--boltz` for the per-file population display and by the |
| 347 |
legacy `--ee` selectivity flow (which still calls `get_selectivity`). |
| 348 |
|
| 349 |
Parameters: |
| 350 |
thermo_data (dict): file path -> calc_bbe. |
| 351 |
temperature (float): Kelvin. |
| 352 |
dup_list (list): pairs [file_i, file_j]; entries whose path is the |
| 353 |
FIRST member of any pair are excluded (legacy behavior). |
| 354 |
key (str): 'gibbs' or 'energy'. |
| 355 |
|
| 356 |
Returns: |
| 357 |
dict[str, float]: file path -> normalized population (Σ = 1.0). |
| 358 |
""" |
| 359 |
attr = SORT_KEYS[key] |
| 360 |
files = list(thermo_data) |
| 361 |
boltz_facs, e_min, boltz_sum = {}, sys.float_info.max, 0.0 |
| 362 |
|
| 363 |
for file in files: # Need the most stable structure |
| 364 |
val = getattr(thermo_data[file], attr, None) |
| 365 |
if val is not None and val < e_min: |
| 366 |
e_min = val |
| 367 |
|
| 368 |
# Calculate E_rel and Boltzmann factors |
| 369 |
for file in files: |
| 370 |
duplicate = False |
| 371 |
if dup_list: |
| 372 |
for dup in dup_list: |
| 373 |
if dup[0] == file: |
| 374 |
duplicate = True |
| 375 |
if not duplicate: |
| 376 |
val = getattr(thermo_data[file], attr, None) |
| 377 |
if val is not None: |
| 378 |
boltz_facs[file] = math.exp(-(val - e_min) * J_TO_AU / GAS_CONSTANT / temperature) |
| 379 |
boltz_sum += boltz_facs[file] |
| 380 |
|
| 381 |
# Normalize to populations that sum to 1.0 |
| 382 |
if boltz_sum > 0: |
| 383 |
for file in boltz_facs: |
| 384 |
boltz_facs[file] /= boltz_sum |
| 385 |
|
| 386 |
return boltz_facs |
| 387 |
|
| 388 |
|
| 389 |
# --------------------------------------------------------------------------- |
| 390 |
# Legacy --ee shim (deprecated; remove in v5.0) |
| 391 |
# --------------------------------------------------------------------------- |
| 392 |
|
| 393 |
def get_selectivity(pattern, files, boltz_facs, temperature, dup_list): |
| 394 |
"""DEPRECATED — legacy 'a:b' colon-pattern selectivity. |
| 395 |
|
| 396 |
Forwards to `compute_selectivity` with a 2-label spec built from the |
| 397 |
glob pattern. Emits a DeprecationWarning. Use --label / --selectivity |
| 398 |
going forward. |
| 399 |
|
| 400 |
Returns the legacy 6-tuple: (ee, er, ratio, dd_free_energy, failed, |
| 401 |
pref) so the existing CLI print path keeps working unchanged. |
| 402 |
""" |
| 403 |
warnings.warn( |
| 404 |
"get_selectivity / --ee is deprecated; use --label / " |
| 405 |
"--selectivity instead. Will be removed in v5.0.", |
| 406 |
DeprecationWarning, |
| 407 |
stacklevel=2, |
| 408 |
) |
| 409 |
parts = pattern.split(':') |
| 410 |
if len(parts) != 2: |
| 411 |
raise ValueError( |
| 412 |
f"Invalid selectivity pattern '{pattern}'. " |
| 413 |
"Expected format: 'pattern_a:pattern_b' with exactly one colon." |
| 414 |
) |
| 415 |
a_regex, b_regex = parts[0].strip(), parts[1].strip() |
| 416 |
if not a_regex or not b_regex: |
| 417 |
raise ValueError( |
| 418 |
f"Invalid selectivity pattern '{pattern}'. " |
| 419 |
"Both patterns before and after ':' must be non-empty." |
| 420 |
) |
| 421 |
|
| 422 |
A = ''.join(a for a in a_regex if a.isalnum()) |
| 423 |
B = ''.join(b for b in b_regex if b.isalnum()) |
| 424 |
|
| 425 |
# Legacy behavior: glob the filesystem (one or more parent dirs), not |
| 426 |
# fnmatch against `files`. |
| 427 |
dirs = list(set(os.path.dirname(f) for f in files)) |
| 428 |
a_files, b_files = [], [] |
| 429 |
if len(dirs) > 1 or (dirs and dirs[0] != ''): |
| 430 |
for d in dirs: |
| 431 |
a_files.extend(glob(d + '/' + a_regex)) |
| 432 |
b_files.extend(glob(d + '/' + b_regex)) |
| 433 |
else: |
| 434 |
a_files.extend(glob(a_regex)) |
| 435 |
b_files.extend(glob(b_regex)) |
| 436 |
|
| 437 |
if not a_files or not b_files: |
| 438 |
log.info("\n Warning! Filenames have not been formatted correctly for determining selectivity\n") |
| 439 |
log.info(" Make sure the filename contains either " + A + " or " + B + "\n") |
| 440 |
sys.exit(" Please edit either your filenames or selectivity pattern argument and try again\n") |
| 441 |
|
| 442 |
# Restrict to files we have thermo data for, and that haven't been |
| 443 |
# marked as duplicates (legacy: only dup[0] is excluded here). |
| 444 |
excluded = set(dup[0] for dup in (dup_list or [])) |
| 445 |
a_files = [f for f in a_files if f in boltz_facs and f not in excluded] |
| 446 |
b_files = [f for f in b_files if f in boltz_facs and f not in excluded] |
| 447 |
a_sum = sum(boltz_facs[f] for f in a_files) |
| 448 |
b_sum = sum(boltz_facs[f] for f in b_files) |
| 449 |
|
| 450 |
A_round = round(a_sum * 100) |
| 451 |
B_round = round(b_sum * 100) |
| 452 |
er = f'{A_round}:{B_round}' |
| 453 |
failed = False |
| 454 |
if a_sum > b_sum: |
| 455 |
pref = A |
| 456 |
try: |
| 457 |
r = a_sum / b_sum |
| 458 |
ratio = f'{round(r, 1)}:1' if r < 3 else f'{round(r)}:1' |
| 459 |
except ZeroDivisionError: |
| 460 |
ratio = '1:0' |
| 461 |
else: |
| 462 |
pref = B |
| 463 |
try: |
| 464 |
r = b_sum / a_sum |
| 465 |
ratio = f'1:{round(r, 1)}' if r < 3 else f'1:{round(r)}' |
| 466 |
except ZeroDivisionError: |
| 467 |
ratio = '0:1' |
| 468 |
|
| 469 |
ee = (a_sum - b_sum) * 100.0 |
| 470 |
if ee == 0: |
| 471 |
log.info("\n Warning! No files found for an enantioselectivity analysis, adjust the stereodetermining step name and try again.\n") |
| 472 |
failed = True |
| 473 |
ee = abs(ee) |
| 474 |
try: |
| 475 |
dd_free_energy = GAS_CONSTANT / J_TO_AU * temperature * math.log((50 + ee / 2.0) / (50 - ee / 2.0)) * KCAL_TO_AU |
| 476 |
except (ZeroDivisionError, ValueError): |
| 477 |
dd_free_energy = 0.0 |
| 478 |
return ee, er, ratio, dd_free_energy, failed, pref |