Debian Codegraph @

goodvibes/sort.py

raw
1 """Structure sorting and duplicate detection for GoodVibes."""
2 import logging
3 import numpy as np
4
5 from .constants import KCAL_TO_AU
6
7 log = logging.getLogger('goodvibes')
8
9
10 def kabsch_rmsd(coords_a, coords_b):
11 """
12 Compute the RMSD between two Nx3 Cartesian coordinate sets after optimal rigid alignment using the Kabsch algorithm.
13
14 Parameters:
15 coords_a (array-like): Reference coordinates with shape (N, 3).
16 coords_b (array-like): Mobile coordinates with shape (N, 3).
17
18 Returns:
19 float: Root-mean-square deviation between the aligned coordinates, in the same units as the inputs.
20 """
21 a = np.array(coords_a, dtype=float)
22 b = np.array(coords_b, dtype=float)
23 # Center both structures
24 a -= a.mean(axis=0)
25 b -= b.mean(axis=0)
26 # Kabsch: find optimal rotation via SVD of cross-covariance matrix
27 H = b.T @ a
28 U, _, Vt = np.linalg.svd(H)
29 # Correct for reflection
30 d = np.linalg.det(Vt.T @ U.T)
31 sign_matrix = np.diag([1.0, 1.0, d])
32 R = Vt.T @ sign_matrix @ U.T
33 b_aligned = b @ R.T
34 return np.sqrt(np.mean((a - b_aligned) ** 2))
35
36
37 def deduplicate(thermo_data, *, e_cutoff=0.05, ro_cutoff=0.01,
38 rmsd_cutoff=None):
39 """Identify duplicate or enantiomeric structures by comparing energies,
40 rotational constants, and optionally Cartesian RMSD.
41
42 All active criteria must pass for a pair to be flagged as duplicate.
43
44 Parameters:
45 thermo_data (dict): file path → calc_bbe mapping.
46 e_cutoff (float): max absolute SCF energy difference in kcal/mol (default 0.05).
47 ro_cutoff (float): max relative difference in rotational constants as a
48 fraction, e.g. 0.01 = 1% (default 0.01).
49 rmsd_cutoff (float or None): max Cartesian RMSD in Angstrom.
50 None (default) disables RMSD comparison; 0.125 matches CREST.
51
52 Returns:
53 list: pairs [file_i, file_j] flagged as duplicates.
54 """
55 files = list(thermo_data)
56 dup_list = []
57 e_cutoff_au = e_cutoff / KCAL_TO_AU # Convert kcal/mol to Hartree
58 cutoff_msg = "\n Checking for duplicate structures. Applying: e_cutoff={} kcal/mol, ro_cutoff={}%".format(e_cutoff, ro_cutoff * 100)
59 if rmsd_cutoff is not None:
60 cutoff_msg += ", rmsd_cutoff={} A".format(rmsd_cutoff)
61 log.info("\n" + cutoff_msg)
62 for i, file in enumerate(files):
63 for j in range(0, i):
64 bbe_i, bbe_j = thermo_data[files[i]], thermo_data[files[j]]
65
66 # Energy gate (cheap): reject the pair before computing ro_diff or RMSD.
67 if not (hasattr(bbe_i, "scf_energy") and hasattr(bbe_j, "scf_energy")):
68 continue
69 if abs(bbe_i.scf_energy - bbe_j.scf_energy) >= e_cutoff_au:
70 continue
71
72 # Rotational-constants gate (microseconds): only run if energy passed.
73 if not (hasattr(bbe_i, "roconst") and hasattr(bbe_j, "roconst")):
74 continue
75 if len(bbe_i.roconst) != len(bbe_j.roconst):
76 continue
77 ri = np.array(bbe_i.roconst)
78 rj = np.array(bbe_j.roconst)
79 avg = 0.5 * (ri + rj)
80 nonzero = avg > 0
81 if np.any(nonzero):
82 ro_diff = np.max(np.abs(ri[nonzero] - rj[nonzero]) / avg[nonzero])
83 else:
84 # Both structures have all-zero rotational constants
85 # (e.g. single atoms) — treat as matching
86 ro_diff = 0.0
87 if ro_diff >= ro_cutoff:
88 continue
89
90 # Kabsch RMSD gate (most expensive): only run if e and ro both passed.
91 if rmsd_cutoff is not None:
92 if not (hasattr(bbe_i, "cartesians") and hasattr(bbe_j, "cartesians")):
93 continue
94 coords_i = np.array(bbe_i.cartesians)
95 coords_j = np.array(bbe_j.cartesians)
96 if coords_i.shape != coords_j.shape or len(coords_i) == 0:
97 continue
98 if kabsch_rmsd(coords_i, coords_j) >= rmsd_cutoff:
99 continue
100
101 dup_list.append([files[i], files[j]])
102 return dup_list
103
104
105 SORT_KEYS = {
106 'energy': 'scf_energy',
107 'gibbs': 'qh_gibbs_free_energy',
108 }
109
110
111 def sort_thermo(thermo_data, key):
112 """Return thermo_data reordered by the given energy attribute (lowest first).
113
114 Entries with linear_warning, missing the attribute, or with a None value are placed at the end.
115
116 Parameters:
117 thermo_data (dict): file path → calc_bbe mapping.
118 key (str): sort mode — 'energy' (scf_energy) or 'gibbs' (qh_gibbs_free_energy).
119
120 Returns:
121 dict: new dict with the same items in sorted order.
122 """
123 attr = SORT_KEYS[key]
124 inf = float('inf')
125
126 def sort_val(item):
127 """
128 Compute the sort key for a thermochemistry mapping item, treating flagged or missing values as infinite so they sort last.
129
130 Parameters:
131 item (tuple): A (key, calc_bbe) pair where `calc_bbe` is the object containing thermochemical attributes.
132
133 Returns:
134 float: The attribute value `getattr(calc_bbe, attr)` when present and not None; `float('inf')` if `calc_bbe.linear_warning` is truthy or the attribute is missing/None.
135 """
136 bbe = item[1]
137 if getattr(bbe, 'linear_warning', False):
138 return inf
139 val = getattr(bbe, attr, None)
140 return val if val is not None else inf
141
142 return dict(sorted(thermo_data.items(), key=sort_val))