Coverage for ase/calculators/mopac.py: 85.56%
187 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""This module defines an ASE interface to MOPAC.
3Set $ASE_MOPAC_COMMAND to something like::
5 LD_LIBRARY_PATH=/path/to/lib/ \
6 MOPAC_LICENSE=/path/to/license \
7 /path/to/MOPAC2012.exe PREFIX.mop 2> /dev/null
9"""
11import os
12import re
13from collections.abc import Sequence
14from warnings import warn
16import numpy as np
17from packaging import version
19from ase import Atoms
20from ase.calculators.calculator import FileIOCalculator, Parameters, ReadError
21from ase.units import Debye, kcal, mol
24def get_version_number(lines: Sequence[str]):
25 pattern1 = r'MOPAC\s+v(\S+)'
26 pattern2 = r'MOPAC2016, Version:\s+([^,]+)'
28 for line in lines[:10]:
29 match = re.search(pattern1, line) or re.search(pattern2, line)
30 if match:
31 return match.group(1)
32 raise ValueError('Version number was not found in MOPAC output')
35class MOPAC(FileIOCalculator):
36 implemented_properties = [
37 'energy',
38 'forces',
39 'dipole',
40 'magmom',
41 'free_energy',
42 ]
43 _legacy_default_command = 'mopac PREFIX.mop 2> /dev/null'
44 discard_results_on_any_change = True
46 default_parameters = dict(
47 method='PM7', task='1SCF GRADIENTS', charge=None, relscf=0.0001
48 )
50 methods = [
51 'AM1',
52 'MNDO',
53 'MNDOD',
54 'PM3',
55 'PM6',
56 'PM6-D3',
57 'PM6-DH+',
58 'PM6-DH2',
59 'PM6-DH2X',
60 'PM6-D3H4',
61 'PM6-D3H4X',
62 'PMEP',
63 'PM7',
64 'PM7-TS',
65 'RM1',
66 ]
68 fileio_rules = FileIOCalculator.ruleset(
69 extend_argv=['{prefix}.mop'], stdout_name='{prefix}.out'
70 )
72 def __init__(
73 self,
74 restart=None,
75 ignore_bad_restart_file=FileIOCalculator._deprecated,
76 label='mopac',
77 atoms=None,
78 **kwargs,
79 ):
80 """Construct MOPAC-calculator object.
82 Parameters
83 ----------
85 label: str
86 Prefix for filenames (label.mop, label.out, ...)
88 Examples
89 --------
91 Use default values to do a single SCF calculation and print
92 the forces (task='1SCF GRADIENTS'):
94 >>> from ase.build import molecule
95 >>> from ase.calculators.mopac import MOPAC
96 >>>
97 >>> atoms = molecule('O2')
98 >>> atoms.calc = MOPAC(label='O2')
99 >>> atoms.get_potential_energy()
100 >>> eigs = atoms.calc.get_eigenvalues()
101 >>> somos = atoms.calc.get_somo_levels()
102 >>> homo, lumo = atoms.calc.get_homo_lumo_levels()
104 Use the internal geometry optimization of Mopac:
106 >>> atoms = molecule('H2')
107 >>> atoms.calc = MOPAC(label='H2', task='GRADIENTS')
108 >>> atoms.get_potential_energy()
110 Read in and start from output file:
112 >>> atoms = MOPAC.read_atoms('H2')
113 >>> atoms.calc.get_homo_lumo_levels()
115 """
116 FileIOCalculator.__init__(
117 self, restart, ignore_bad_restart_file, label, atoms, **kwargs
118 )
120 def write_input(self, atoms, properties=None, system_changes=None):
121 FileIOCalculator.write_input(self, atoms, properties, system_changes)
122 p = Parameters(self.parameters.copy())
124 # Ensure DISP so total energy is available
125 if 'DISP' not in p.task.split():
126 p.task = p.task + ' DISP'
128 # Build string to hold .mop input file:
129 s = f'{p.method} {p.task} '
131 if p.relscf:
132 s += f'RELSCF={p.relscf} '
134 # Write charge:
135 if p.charge is None:
136 charge = atoms.get_initial_charges().sum()
137 else:
138 charge = p.charge
140 if charge != 0:
141 s += f'CHARGE={int(round(charge))} '
143 magmom = int(round(abs(atoms.get_initial_magnetic_moments().sum())))
144 if magmom:
145 s += ['DOUBLET', 'TRIPLET', 'QUARTET', 'QUINTET'][
146 magmom - 1
147 ] + ' UHF '
149 s += '\nTitle: ASE calculation\n\n'
151 # Write coordinates:
152 for xyz, symbol in zip(atoms.positions, atoms.get_chemical_symbols()):
153 s += ' {:2} {} 1 {} 1 {} 1\n'.format(symbol, *xyz)
155 for v, pbc in zip(atoms.cell, atoms.pbc):
156 if pbc:
157 s += 'Tv {} {} {}\n'.format(*v)
159 with open(self.label + '.mop', 'w') as fd:
160 fd.write(s)
162 def get_spin_polarized(self):
163 return self.nspins == 2
165 def get_index(self, lines, pattern):
166 for i, line in enumerate(lines):
167 if line.find(pattern) != -1:
168 return i
170 def read(self, label):
171 FileIOCalculator.read(self, label)
172 if not os.path.isfile(self.label + '.out'):
173 raise ReadError
175 with open(self.label + '.out') as fd:
176 lines = fd.readlines()
178 self.parameters = Parameters(task='', method='')
179 p = self.parameters
180 parm_line = self.read_parameters_from_file(lines)
181 for keyword in parm_line.split():
182 if 'RELSCF' in keyword:
183 p.relscf = float(keyword.split('=')[-1])
184 elif keyword in self.methods:
185 p.method = keyword
186 else:
187 p.task += keyword + ' '
189 p.task = p.task.rstrip()
190 if 'charge' not in p:
191 p.charge = None
193 self.atoms = self.read_atoms_from_file(lines)
194 self.read_results()
196 def read_atoms_from_file(self, lines):
197 """Read the Atoms from the output file stored as list of str in lines.
198 Parameters
199 ----------
201 lines: list of str
202 """
203 # first try to read from final point (last image)
204 i = self.get_index(lines, 'FINAL POINT AND DERIVATIVES')
205 if i is None: # XXX should we read it from the input file?
206 assert 0, 'Not implemented'
208 lines1 = lines[i:]
209 i = self.get_index(lines1, 'CARTESIAN COORDINATES')
210 j = i + 2
211 symbols = []
212 positions = []
213 while not lines1[j].isspace(): # continue until we hit a blank line
214 l = lines1[j].split()
215 symbols.append(l[1])
216 positions.append([float(c) for c in l[2 : 2 + 3]])
217 j += 1
219 return Atoms(symbols=symbols, positions=positions)
221 def read_parameters_from_file(self, lines):
222 """Find and return the line that defines a Mopac calculation
224 Parameters
225 ----------
227 lines: list of str
228 """
229 for i, line in enumerate(lines):
230 if line.find('CALCULATION DONE:') != -1:
231 break
233 lines1 = lines[i:]
234 for i, line in enumerate(lines1):
235 if line.find('****') != -1:
236 return lines1[i + 1]
238 def read_results(self):
239 """Read the results, such as energy, forces, eigenvalues, etc."""
240 FileIOCalculator.read(self, self.label)
241 if not os.path.isfile(self.label + '.out'):
242 raise ReadError
244 with open(self.label + '.out') as fd:
245 lines = fd.readlines()
247 self.results['version'] = get_version_number(lines)
249 total_energy_regex = re.compile(
250 r'^\s+TOTAL ENERGY\s+\=\s+(-?\d+\.\d+) EV'
251 )
252 final_heat_regex = re.compile(
253 r'^\s+FINAL HEAT OF FORMATION\s+\=\s+(-?\d+\.\d+) KCAL/MOL'
254 )
256 for i, line in enumerate(lines):
257 if total_energy_regex.match(line):
258 self.results['total_energy'] = float(
259 total_energy_regex.match(line).groups()[0]
260 )
261 elif final_heat_regex.match(line):
262 self.results['final_hof'] = (
263 float(final_heat_regex.match(line).groups()[0]) * kcal / mol
264 )
265 elif line.find('NO. OF FILLED LEVELS') != -1:
266 self.nspins = 1
267 self.no_occ_levels = int(line.split()[-1])
268 elif line.find('NO. OF ALPHA ELECTRON') != -1:
269 self.nspins = 2
270 self.no_alpha_electrons = int(line.split()[-1])
271 self.no_beta_electrons = int(lines[i + 1].split()[-1])
272 self.results['magmom'] = abs(
273 self.no_alpha_electrons - self.no_beta_electrons
274 )
275 elif line.find('FINAL POINT AND DERIVATIVES') != -1:
276 forces = [
277 -float(line.split()[6])
278 for line in lines[i + 3 : i + 3 + 3 * len(self.atoms)]
279 ]
280 self.results['forces'] = (
281 np.array(forces).reshape((-1, 3)) * kcal / mol
282 )
283 elif line.find('EIGENVALUES') != -1:
284 if line.find('ALPHA') != -1:
285 j = i + 1
286 eigs_alpha = []
287 while not lines[j].isspace():
288 eigs_alpha += [float(eps) for eps in lines[j].split()]
289 j += 1
290 elif line.find('BETA') != -1:
291 j = i + 1
292 eigs_beta = []
293 while not lines[j].isspace():
294 eigs_beta += [float(eps) for eps in lines[j].split()]
295 j += 1
296 eigs = np.array([eigs_alpha, eigs_beta]).reshape(2, 1, -1)
297 self.eigenvalues = eigs
298 else:
299 eigs = []
300 j = i + 1
301 while not lines[j].isspace():
302 eigs += [float(e) for e in lines[j].split()]
303 j += 1
304 self.eigenvalues = np.array(eigs).reshape(1, 1, -1)
305 elif line.find('DIPOLE ') != -1:
306 self.results['dipole'] = (
307 np.array(lines[i + 3].split()[1 : 1 + 3], float) * Debye
308 )
310 # Developers recommend using final HOF as it includes dispersion etc.
311 # For backward compatibility we won't change the results of old MOPAC
312 # calculations... yet
313 if version.parse(self.results['version']) >= version.parse('22'):
314 self.results['energy'] = self.results['final_hof']
315 else:
316 warn(
317 'Using a version of MOPAC lower than v22: ASE will use '
318 'TOTAL ENERGY as the potential energy. In future, '
319 'FINAL HEAT OF FORMATION will be preferred for all versions.'
320 )
321 self.results['energy'] = self.results['total_energy']
322 self.results['free_energy'] = self.results['energy']
324 def get_eigenvalues(self, kpt=0, spin=0):
325 return self.eigenvalues[spin, kpt]
327 def get_homo_lumo_levels(self):
328 eigs = self.eigenvalues
329 if self.nspins == 1:
330 nocc = self.no_occ_levels
331 return np.array([eigs[0, 0, nocc - 1], eigs[0, 0, nocc]])
332 else:
333 na = self.no_alpha_electrons
334 nb = self.no_beta_electrons
335 if na == 0:
336 return None, self.eigenvalues[1, 0, nb - 1]
337 elif nb == 0:
338 return self.eigenvalues[0, 0, na - 1], None
339 else:
340 eah, eal = eigs[0, 0, na - 1 : na + 1]
341 ebh, ebl = eigs[1, 0, nb - 1 : nb + 1]
342 return np.array([max(eah, ebh), min(eal, ebl)])
344 def get_somo_levels(self):
345 assert self.nspins == 2
346 na, nb = self.no_alpha_electrons, self.no_beta_electrons
347 if na == 0:
348 return None, self.eigenvalues[1, 0, nb - 1]
349 elif nb == 0:
350 return self.eigenvalues[0, 0, na - 1], None
351 else:
352 return np.array(
353 [self.eigenvalues[0, 0, na - 1], self.eigenvalues[1, 0, nb - 1]]
354 )
356 def get_final_heat_of_formation(self):
357 """Final heat of formation as reported in the Mopac output file"""
358 warn(
359 "This method is deprecated, please use MOPAC.results['final_hof']",
360 DeprecationWarning,
361 )
362 return self.results['final_hof']
364 @property
365 def final_hof(self):
366 warn(
367 'This property is deprecated, please use '
368 "MOPAC.results['final_hof']",
369 DeprecationWarning,
370 )
371 return self.results['final_hof']
373 @final_hof.setter
374 def final_hof(self, new_hof):
375 warn(
376 'This property is deprecated, please use '
377 "MOPAC.results['final_hof']",
378 DeprecationWarning,
379 )
380 self.results['final_hof'] = new_hof