Coverage for ase/calculators/psi4.py: 15.65%
115 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"""
2authors: Ben Comer (Georgia Tech), Xiangyun (Ray) Lei (Georgia Tech)
4"""
6import json
7import multiprocessing
8import os
9import warnings
10from io import StringIO
12import numpy as np
14from ase import io
15from ase.calculators.calculator import (
16 Calculator,
17 CalculatorSetupError,
18 InputError,
19 ReadError,
20 all_changes,
21)
22from ase.config import cfg
23from ase.units import Bohr, Hartree
26class Psi4(Calculator):
27 """
28 An ase calculator for the popular open source Q-chem code
29 psi4.
30 method is the generic input for whatever method you wish to use, thus
31 and quantum chemistry method implemented in psi4 can be input
32 (i.e. ccsd(t))
34 also note that you can always use the in-built psi4 module through:
35 calc.psi4
36 """
38 implemented_properties = ['energy', 'forces']
39 discard_results_on_any_change = True
41 default_parameters = {
42 'basis': 'aug-cc-pvtz',
43 'method': 'hf',
44 'symmetry': 'c1',
45 }
47 def __init__(
48 self,
49 restart=None,
50 ignore_bad_restart=False,
51 label='psi4-calc',
52 atoms=None,
53 command=None,
54 **kwargs,
55 ):
56 Calculator.__init__(
57 self,
58 restart=restart,
59 ignore_bad_restart=ignore_bad_restart,
60 label=label,
61 atoms=atoms,
62 command=command,
63 **kwargs,
64 )
65 import psi4
67 self.psi4 = psi4
68 # perform initial setup of psi4 python API
69 self.set_psi4(atoms=atoms)
71 def set_psi4(self, atoms=None):
72 """
73 This function sets the imported psi4 module to the settings the user
74 defines
75 """
77 # Set the scrath directory for electronic structure files.
78 # The default is /tmp
79 if 'PSI_SCRATCH' in cfg:
80 pass
81 elif self.parameters.get('PSI_SCRATCH'):
82 # XXX We should probably not be setting envvars except
83 # if we are creating new processes.
84 os.environ['PSI_SCRATCH'] = self.parameters['PSI_SCRATCH']
86 # Input spin settings
87 if self.parameters.get('reference') is not None:
88 self.psi4.set_options({'reference': self.parameters['reference']})
89 # Memory
90 if self.parameters.get('memory') is not None:
91 self.psi4.set_memory(self.parameters['memory'])
93 # Threads
94 nthreads = self.parameters.get('num_threads', 1)
95 if nthreads == 'max':
96 nthreads = multiprocessing.cpu_count()
97 self.psi4.set_num_threads(nthreads)
99 # deal with some ASE specific inputs
100 if 'kpts' in self.parameters:
101 raise InputError(
102 'psi4 is a non-periodic code, and thus does not'
103 ' require k-points. Please remove this '
104 'argument.'
105 )
107 if self.parameters['method'] == 'LDA':
108 # svwn is equivalent to LDA
109 self.parameters['method'] = 'svwn'
111 if 'nbands' in self.parameters:
112 raise InputError('psi4 does not support the keyword "nbands"')
114 if 'smearing' in self.parameters:
115 raise InputError(
116 'Finite temperature DFT is not implemented in'
117 ' psi4 currently, thus a smearing argument '
118 'cannot be utilized. please remove this '
119 'argument'
120 )
122 if 'xc' in self.parameters:
123 raise InputError(
124 'psi4 does not accept the `xc` argument please'
125 ' use the `method` argument instead'
126 )
128 if atoms is None:
129 if self.atoms is None:
130 return
131 else:
132 atoms = self.atoms
133 if self.atoms is None:
134 self.atoms = atoms
135 # Generate the atomic input
136 geomline = '{}\t{:.15f}\t{:.15f}\t{:.15f}'
137 geom = [geomline.format(atom.symbol, *atom.position) for atom in atoms]
138 geom.append('symmetry {}'.format(self.parameters['symmetry']))
139 geom.append('units angstrom')
141 charge = self.parameters.get('charge')
142 mult = self.parameters.get('multiplicity')
143 if mult is None:
144 mult = 1
145 if charge is not None:
146 warnings.warn(
147 'A charge was provided without a spin '
148 'multiplicity. A multiplicity of 1 is assumed'
149 )
150 if charge is None:
151 charge = 0
153 geom.append(f'{charge} {mult}')
154 geom.append('no_reorient')
156 if not os.path.isdir(self.directory):
157 os.mkdir(self.directory)
158 self.molecule = self.psi4.geometry('\n'.join(geom))
160 def read(self, label):
161 """Read psi4 outputs made from this ASE calculator"""
162 filename = label + '.dat'
163 if not os.path.isfile(filename):
164 raise ReadError('Could not find the psi4 output file: ' + filename)
166 with open(filename) as fd:
167 txt = fd.read()
168 if '!ASE Information\n' not in txt:
169 raise Exception(
170 'The output file {} could not be read because '
171 'the file does not contain the "!ASE Information"'
172 ' lines inserted by this calculator. This likely'
173 ' means the output file was not made using this '
174 'ASE calculator or has since been modified and '
175 'thus cannot be read.'.format(filename)
176 )
177 info = txt.split('!ASE Information\n')[1]
178 info = info.split('!')[0]
179 saved_dict = json.loads(info)
180 # use io read to recode atoms
181 with StringIO(str(saved_dict['atoms'])) as g:
182 self.atoms = io.read(g, format='json')
183 self.parameters = saved_dict['parameters']
184 self.results = saved_dict['results']
185 # convert forces to numpy array
186 if 'forces' in self.results:
187 self.results['forces'] = np.array(self.results['forces'])
189 def calculate(
190 self,
191 atoms=None,
192 properties=None,
193 system_changes=all_changes,
194 symmetry='c1',
195 ):
197 if properties is None:
198 properties = ['energy']
199 Calculator.calculate(self, atoms=atoms)
200 if self.atoms is None:
201 raise CalculatorSetupError(
202 'An Atoms object must be provided to perform a calculation'
203 )
204 atoms = self.atoms
206 if atoms.get_initial_magnetic_moments().any():
207 self.parameters['reference'] = 'uhf'
208 self.parameters['multiplicity'] = None
209 # this inputs all the settings into psi4
210 self.set_psi4(atoms=atoms)
211 self.psi4.core.set_output_file(self.label + '.dat', False)
213 # Set up the method
214 method = self.parameters['method']
215 basis = self.parameters['basis']
217 # Do the calculations
218 if 'forces' in properties:
219 grad, wf = self.psi4.driver.gradient(
220 f'{method}/{basis}', return_wfn=True
221 )
222 # energy comes for free
223 energy = wf.energy()
224 self.results['energy'] = energy * Hartree
225 # convert to eV/A
226 # also note that the gradient is -1 * forces
227 self.results['forces'] = -1 * np.array(grad) * Hartree / Bohr
228 elif 'energy' in properties:
229 energy = self.psi4.energy(
230 f'{method}/{basis}', molecule=self.molecule
231 )
232 # convert to eV
233 self.results['energy'] = energy * Hartree
235 # dump the calculator info to the psi4 file
236 save_atoms = self.atoms.copy()
237 # use io.write to encode atoms
238 with StringIO() as fd:
239 io.write(fd, save_atoms, format='json')
240 json_atoms = fd.getvalue()
241 # convert forces to list for json storage
242 save_results = self.results.copy()
243 if 'forces' in save_results:
244 save_results['forces'] = save_results['forces'].tolist()
245 save_dict = {
246 'parameters': self.parameters,
247 'results': save_results,
248 'atoms': json_atoms,
249 }
250 self.psi4.core.print_out('!ASE Information\n')
251 self.psi4.core.print_out(json.dumps(save_dict))
252 self.psi4.core.print_out('!')