Debian Codegraph @

goodvibes/validation.py

raw
1 """File validation and consistency checks for GoodVibes."""
2 import logging
3 import os.path
4 import sys
5
6 from .sort import deduplicate
7 from .utils import all_same
8 from .io import parse_qcdata, read_initial, find_spc_file
9
10 log = logging.getLogger('goodvibes')
11
12
13 def print_check_fails(check_attribute, file, attribute, option2=None):
14 """
15 Report groups of files that share differing attribute values.
16
17 Groups files by the values in check_attribute (or by (value, option2_value) when option2 is provided) and logs each distinct group. For each group the doc prints the attribute value(s) and up to the first three filenames; if more files are present the remaining count is reported.
18
19 Parameters:
20 check_attribute (list): Attribute values aligned with the files list (one value per file).
21 file (list): File identifiers aligned with check_attribute.
22 attribute (str): Human-readable name of the attribute being checked (e.g., "levels of theory").
23 option2 (list, optional): Secondary attribute values aligned with the files list; when provided groups are keyed by (check_attribute[i], option2[i]).
24 """
25 unique_attr = {}
26 for i, attr in enumerate(check_attribute):
27 if option2 is not None:
28 attr = (attr, option2[i])
29 if attr not in unique_attr:
30 unique_attr[attr] = [file[i]]
31 else:
32 unique_attr[attr].append(file[i])
33 log.info("\n\n Caution! Multiple {} found: ".format(attribute))
34 for attr in unique_attr:
35 if option2 is not None:
36 if float(attr[0]) < 0:
37 log.info('\n {} {}: '.format(attr[0], attr[1]))
38 else:
39 log.info('\n {} {}: '.format(attr[0], attr[1]))
40 else:
41 log.info('\n ✔ {}: '.format(attr))
42 filenames = unique_attr[attr]
43 if len(filenames) > 3:
44 others = len(filenames) - 3
45 log.info(f'{filenames[0]}, {filenames[1]}, {filenames[2]}, and {others} others')
46 else:
47 log.info(', '.join(filenames))
48
49
50 def collect_and_validate_files(files, options):
51 """
52 Read initial metadata for each output file, remove files that terminated with 'Error' or 'Incomplete', and verify SPC file termination when SPC mode is enabled.
53
54 When a file's initial read reports progress 'Error' or 'Incomplete', that file is removed from the returned lists and a warning is logged. If SPC mode (options.spc) is set and not 'link', the function attempts to locate corresponding SPC files; if any discovered SPC file reports 'Error' or 'Incomplete' the program exits. Returned lists remain aligned: the returned level_of_theory and solvation_model correspond to the returned files order.
55
56 Parameters:
57 files (list): Paths to output files to validate.
58 options (Namespace): Parsed CLI options. Uses the `spc` attribute to control SPC lookup behavior.
59
60 Returns:
61 tuple: (files, level_of_theory, solvation_model) — the filtered file paths, and parallel lists of each file's level of theory and solvation model.
62 """
63 level_of_theory, solvation_model, progress, spc_progress = [], [], {}, {}
64 for file in files:
65 lot_sm_prog = read_initial(file)
66 level_of_theory.append(lot_sm_prog[0])
67 solvation_model.append(lot_sm_prog[1])
68 progress[file] = lot_sm_prog[2]
69 # Check spc files for normal termination
70 if options.spc is not None and options.spc != 'link':
71 name, _ = os.path.splitext(file)
72 spc_file = find_spc_file(name, options.spc)
73 if spc_file is not None:
74 lot_sm_prog = read_initial(spc_file)
75 spc_progress[spc_file] = lot_sm_prog[2]
76
77 remove_key = []
78 # Remove problem files and print errors. Only the first ! warning gets
79 # a blank line before it; subsequent warnings stack tightly.
80 first_warning = True
81
82 def _warn_prefix():
83 nonlocal first_warning
84 prefix = "\n\n" if first_warning else "\n"
85 first_warning = False
86 return prefix
87
88 for i, key in enumerate(files):
89 if progress[key] == 'Error':
90 log.info(_warn_prefix() + " ! Error termination found in {}: omitted from further "
91 "calculations.".format(key))
92 remove_key.append([i, key])
93 elif progress[key] == 'Incomplete':
94 log.info(_warn_prefix() + " ! {} may not have terminated normally or the calculation may still be "
95 "running: omitted from further calculations.".format(key))
96 remove_key.append([i, key])
97 # Check spc files for normal termination
98 if spc_progress:
99 for key in spc_progress:
100 if spc_progress[key] == 'Error':
101 sys.exit(_warn_prefix() + " ! Error termination found in file {} calculations.".format(key))
102 elif spc_progress[key] == 'Incomplete':
103 sys.exit(_warn_prefix() + " ! File {} may not have terminated normally or the "
104 "calculation may still be running.".format(key))
105
106 for [i, key] in list(reversed(remove_key)):
107 files.remove(key)
108 del level_of_theory[i]
109 del solvation_model[i]
110 if not files:
111 sys.exit("\n\nPlease try again with normally terminated output files.\nFor help, use option '-h'\n")
112
113 return files, level_of_theory, solvation_model
114
115
116 def check_files(thermo_data, options, level_of_theory):
117 """Run consistency checks across all calculation output files.
118
119 Checks: program version, solvation model, level of theory, charge/multiplicity,
120 standard concentration, linear molecule frequencies, TS imaginary frequencies,
121 empirical dispersion, and (if --spc) single-point correction consistency.
122
123 Parameters:
124 thermo_data (dict): file path → calc_bbe mapping.
125 options (Namespace): parsed CLI options. Uses: conc, spc, duplicate.
126 level_of_theory (list): level of theory strings, one per file.
127 """
128 files = list(thermo_data)
129 STARS = " " + "*" * 128
130 log.info("\n Checks for thermochemistry calculations (frequency calculations):")
131 log.info("\n" + STARS)
132 # Check program used and version
133 version_check = [thermo_data[key].version_program for key in thermo_data]
134 file_check = [thermo_data[key].file for key in thermo_data]
135 if all_same(version_check):
136 log.info("\no Using {} in all calculations.".format(version_check[0]))
137 else:
138 print_check_fails(version_check, file_check, "programs or versions")
139
140 # Check level of theory
141 if all_same(level_of_theory):
142 log.info("\no Using {} in all calculations.".format(level_of_theory[0]))
143 else:
144 print_check_fails(level_of_theory, file_check, "levels of theory")
145
146 # Check for solvent models
147 solvent_check = [thermo_data[key].solvation_model[0] for key in thermo_data]
148 if all_same(solvent_check):
149 solvent_check = [thermo_data[key].solvation_model[1] for key in thermo_data]
150 log.info("\no Using {} in all calculations.".format(solvent_check[0]))
151 else:
152 solvent_check = [thermo_data[key].solvation_model[1] for key in thermo_data]
153 print_check_fails(solvent_check, file_check, "solvation models")
154
155 # Check for -c 1 when solvent is added
156 if all_same(solvent_check):
157 if solvent_check[0] == "gas phase" and options.conc is None:
158 log.info("\no Using a standard concentration of 1 atm for gas phase.")
159 elif solvent_check[0] == "gas phase" and options.conc is not None:
160 log.info("\n x Caution! Standard concentration is not 1 atm for gas phase (using {} M).".format(options.conc))
161 elif solvent_check[0] != "gas phase" and options.conc is None:
162 log.info("\n x Using a standard concentration of 1 atm for solvent phase (option -c 1 should be included for 1 M).")
163 elif solvent_check[0] != "gas phase" and str(options.conc) == str(1.0):
164 log.info("\no Using a standard concentration of 1 M for solvent phase.")
165 elif solvent_check[0] != "gas phase" and options.conc is not None and str(options.conc) != str(1.0):
166 log.info("\n x Caution! Standard concentration is not 1 M for solvent phase (using {} M).".format(options.conc))
167 if not all_same(solvent_check) and "gas phase" in solvent_check:
168 log.info("\n x Caution! The right standard concentration cannot be determined because the calculations use a combination of gas and solvent phases.")
169 if not all_same(solvent_check) and "gas phase" not in solvent_check:
170 log.info("\n x Caution! Different solvents used, fix this issue and use option -c 1 for a standard concentration of 1 M.")
171
172 # Check charge and multiplicity
173 charge_check = [thermo_data[key].charge for key in thermo_data]
174 multiplicity_check = [thermo_data[key].multiplicity for key in thermo_data]
175 if all_same(charge_check) and all_same(multiplicity_check):
176 log.info("\no Using charge {} and multiplicity {} in all calculations.".format(charge_check[0],
177 multiplicity_check[0]))
178 else:
179 print_check_fails(charge_check, file_check, "charge and multiplicity", multiplicity_check)
180
181 # Check for duplicate structures
182 dup_list = deduplicate(thermo_data,
183 e_cutoff=getattr(options, 'e_cutoff', 0.05),
184 ro_cutoff=getattr(options, 'ro_cutoff', 0.01),
185 rmsd_cutoff=getattr(options, 'rmsd_cutoff', None))
186 if not dup_list:
187 log.info("\no No duplicates or enantiomers found")
188 else:
189 log.info("\n x Caution! Possible duplicates or enantiomers found:")
190 for dup in dup_list:
191 log.info('\n {} and {}'.format(dup[0], dup[1]))
192
193 # Check for linear molecules with incorrect number of vibrational modes
194 linear_fails_atom, linear_fails_cart, linear_fails_files, linear_fails_list = [], [], [], []
195 frequency_list = []
196 for file in files:
197 bbe = thermo_data[file]
198 linear_fails_cart.append(bbe.cartesians)
199 linear_fails_atom.append(bbe.atom_types)
200 linear_fails_files.append(file)
201 frequency_list.append(bbe.frequency_wn)
202
203 linear_fails_list.append(linear_fails_atom)
204 linear_fails_list.append(linear_fails_cart)
205 linear_fails_list.append(frequency_list)
206 linear_fails_list.append(linear_fails_files)
207
208 linear_mol_correct, linear_mol_wrong = [], []
209 for i in range(len(linear_fails_list[0])):
210 count_linear = 0
211 if len(linear_fails_list[0][i]) == 2:
212 if len(linear_fails_list[2][i]) == 1:
213 linear_mol_correct.append(linear_fails_list[3][i])
214 else:
215 linear_mol_wrong.append(linear_fails_list[3][i])
216 if len(linear_fails_list[0][i]) == 3:
217 if linear_fails_list[0][i] == ['I', 'I', 'I'] or linear_fails_list[0][i] == ['O', 'O', 'O'] or \
218 linear_fails_list[0][i] == ['N', 'N', 'N'] or linear_fails_list[0][i] == ['H', 'C', 'N'] or \
219 linear_fails_list[0][i] == ['H', 'N', 'C'] or linear_fails_list[0][i] == ['C', 'H', 'N'] or \
220 linear_fails_list[0][i] == ['C', 'N', 'H'] or linear_fails_list[0][i] == ['N', 'H', 'C'] or \
221 linear_fails_list[0][i] == ['N', 'C', 'H']:
222 if len(linear_fails_list[2][i]) == 4:
223 linear_mol_correct.append(linear_fails_list[3][i])
224 else:
225 linear_mol_wrong.append(linear_fails_list[3][i])
226 else:
227 for j in range(len(linear_fails_list[0][i])):
228 for k in range(len(linear_fails_list[0][i])):
229 if k > j:
230 for ci in range(len(linear_fails_list[1][i][j])):
231 if linear_fails_list[0][i][j] == linear_fails_list[0][i][k]:
232 if linear_fails_list[1][i][j][ci] > (-linear_fails_list[1][i][k][ci] - 0.1) and \
233 linear_fails_list[1][i][j][ci] < (-linear_fails_list[1][i][k][ci] + 0.1):
234 count_linear = count_linear + 1
235 if count_linear == 3:
236 if len(linear_fails_list[2][i]) == 4:
237 linear_mol_correct.append(linear_fails_list[3][i])
238 else:
239 linear_mol_wrong.append(linear_fails_list[3][i])
240 if len(linear_fails_list[0][i]) == 4:
241 if linear_fails_list[0][i] == ['C', 'C', 'H', 'H'] or linear_fails_list[0][i] == ['C', 'H', 'C', 'H'] or \
242 linear_fails_list[0][i] == ['C', 'H', 'H', 'C'] or linear_fails_list[0][i] == ['H', 'C', 'C', 'H'] or \
243 linear_fails_list[0][i] == ['H', 'C', 'H', 'C'] or linear_fails_list[0][i] == ['H', 'H', 'C', 'C']:
244 if len(linear_fails_list[2][i]) == 7:
245 linear_mol_correct.append(linear_fails_list[3][i])
246 else:
247 linear_mol_wrong.append(linear_fails_list[3][i])
248 linear_correct_print = ', '.join(linear_mol_correct)
249 linear_wrong_print = ', '.join(linear_mol_wrong)
250 if not linear_mol_correct:
251 if not linear_mol_wrong:
252 log.info("\n- No linear molecules found.")
253 if linear_mol_wrong:
254 log.info("\n x Caution! Potential linear molecules with wrong number of frequencies found "
255 "(correct number = 3N-5) -{}.".format(linear_wrong_print))
256 elif linear_mol_correct:
257 if not linear_mol_wrong:
258 log.info("\no All the linear molecules have the correct number of frequencies -{}.".format(linear_correct_print))
259 if linear_mol_wrong:
260 log.info("\n x Caution! Potential linear molecules with wrong number of frequencies found -{}. Correct "
261 "number of frequencies (3N-5) found in other calculations -{}.".format(linear_wrong_print,
262 linear_correct_print))
263
264 # Checks whether any TS have > 1 imaginary frequency and any GS have any imaginary frequencies
265 for file in files:
266 bbe = thermo_data[file]
267 if bbe.job_type.find('TS') > -1 and len(bbe.im_frequency_wn) != 1:
268 log.info("\n x Caution! TS {} does not have 1 imaginary frequency greater than -50 wavenumbers.".format(file))
269 if bbe.job_type.find('GS') > -1 and bbe.job_type.find('TS') == -1 and bbe.im_frequency_wn:
270 log.info("\n x Caution: GS {} has 1 or more imaginary frequencies greater than -50 wavenumbers.".format(file))
271
272 # Check for empirical dispersion
273 dispersion_check = [thermo_data[key].empirical_dispersion for key in thermo_data]
274 if all_same(dispersion_check):
275 if dispersion_check[0] == 'No empirical dispersion detected':
276 log.info("\n- No empirical dispersion detected in any of the calculations.")
277 else:
278 log.info("\no Using " + dispersion_check[0] + " in all calculations.")
279 else:
280 print_check_fails(dispersion_check, file_check, "dispersion models")
281 log.info("\n" + STARS + "\n")
282
283 # Check for single-point corrections
284 if options.spc is not None:
285 log.info("\n Checks for single-point corrections:")
286 log.info("\n" + STARS)
287 names_spc, version_check_spc = [], []
288 for file in files:
289 name, _ = os.path.splitext(file)
290 spc_file = find_spc_file(name, options.spc)
291 if spc_file is not None:
292 names_spc.append(spc_file)
293
294 # Check SPC program versions
295 version_check_spc = [thermo_data[key].sp_version_program for key in thermo_data]
296 if all_same(version_check_spc):
297 log.info("\no Using {} in all the single-point corrections.".format(version_check_spc[0]))
298 else:
299 print_check_fails(version_check_spc, file_check, "programs or versions")
300
301 # Check SPC solvation
302 solvent_check_spc = [thermo_data[key].sp_solvation_model for key in thermo_data]
303 if all_same(solvent_check_spc):
304 if isinstance(solvent_check_spc[0],list):
305 log.info("\no Using " + solvent_check_spc[0][0] + " in all single-point corrections.")
306 else:
307 log.info("\no Using " + solvent_check_spc[0] + " in all single-point corrections.")
308 else:
309 print_check_fails(solvent_check_spc, file_check, "solvation models")
310
311 # Check SPC level of theory
312 l_o_t_spc = [level_of_theory(name) for name in names_spc]
313 if all_same(l_o_t_spc):
314 log.info("\no Using {} in all the single-point corrections.".format(l_o_t_spc[0]))
315 else:
316 print_check_fails(l_o_t_spc, file_check, "levels of theory")
317
318 # Check SPC charge and multiplicity
319 charge_spc_check = [thermo_data[key].sp_charge for key in thermo_data]
320 multiplicity_spc_check = [thermo_data[key].sp_multiplicity for key in thermo_data]
321 if all_same(charge_spc_check) and all_same(multiplicity_spc_check):
322 log.info("\no Using charge and multiplicity {} {} in all the single-point corrections.".format(
323 charge_spc_check[0], multiplicity_spc_check[0]))
324 else:
325 print_check_fails(charge_spc_check, file_check, "charge and multiplicity", multiplicity_spc_check)
326
327 # Check if the geometries of freq calculations match their corresponding structures in single-point calculations
328 geom_duplic_list, geom_duplic_list_spc, geom_duplic_cart, geom_duplic_files, geom_duplic_cart_spc, geom_duplic_files_spc = [], [], [], [], [], []
329 for file in files:
330 geom_duplic_cart.append(thermo_data[file].cartesians)
331 geom_duplic_files.append(file)
332 geom_duplic_list.append(geom_duplic_cart)
333 geom_duplic_list.append(geom_duplic_files)
334
335 for name in names_spc:
336 spc_qcdata = parse_qcdata(name)
337 geom_duplic_cart_spc.append(spc_qcdata.cartesians)
338 geom_duplic_files_spc.append(name)
339 geom_duplic_list_spc.append(geom_duplic_cart_spc)
340 geom_duplic_list_spc.append(geom_duplic_files_spc)
341 spc_mismatching = "Caution! Potential differences found between frequency and single-point geometries -"
342 if len(geom_duplic_list[0]) == len(geom_duplic_list_spc[0]):
343 for i in range(len(files)):
344 count = 1
345 for j in range(len(geom_duplic_list[0][i])):
346 if count == 1:
347 if geom_duplic_list[0][i][j] == geom_duplic_list_spc[0][i][j]:
348 pass
349 elif '{0:.3f}'.format(geom_duplic_list[0][i][j][0]) == '{0:.3f}'.format(geom_duplic_list_spc[0][i][j][0] * (-1)) or '{0:.3f}'.format(geom_duplic_list[0][i][j][0]) == '{0:.3f}'.format(geom_duplic_list_spc[0][i][j][0]):
350 if '{0:.3f}'.format(geom_duplic_list[0][i][j][1]) == '{0:.3f}'.format(geom_duplic_list_spc[0][i][j][1] * (-1)) or '{0:.3f}'.format(geom_duplic_list[0][i][j][1]) == '{0:.3f}'.format(geom_duplic_list_spc[0][i][j][1] * (-1)):
351 pass
352 if '{0:.3f}'.format(geom_duplic_list[0][i][j][2]) == '{0:.3f}'.format(geom_duplic_list_spc[0][i][j][2] * (-1)) or '{0:.3f}'.format(
353 geom_duplic_list[0][i][j][2]) == '{0:.3f}'.format(geom_duplic_list_spc[0][i][j][2] * (-1)):
354 pass
355 else:
356 spc_mismatching += ", " + geom_duplic_list[1][i]
357 count = count + 1
358 if spc_mismatching == "Caution! Potential differences found between frequency and single-point geometries -":
359 log.info("\no No potential differences found between frequency and single-point geometries (based on input coordinates).")
360 else:
361 spc_mismatching_1 = spc_mismatching[:84]
362 spc_mismatching_2 = spc_mismatching[85:]
363 log.info("\n x " + spc_mismatching_1 + spc_mismatching_2 + '.')
364 else:
365 log.info("\n x One or more geometries from single-point corrections are missing.")
366
367 # Check for SPC dispersion models
368 dispersion_check_spc = [thermo_data[key].sp_empirical_dispersion for key in thermo_data]
369 if all_same(dispersion_check_spc):
370 if dispersion_check_spc[0] == 'No empirical dispersion detected':
371 log.info("\n- No empirical dispersion detected in any of the calculations.")
372 else:
373 log.info("\no Using " + dispersion_check_spc[0] + " in all the single-point calculations.")
374 else:
375 print_check_fails(dispersion_check_spc, file_check, "dispersion models")
376 log.info("\n" + STARS + "\n")