Coverage for ase/calculators/qchem.py: 54.22%

83 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1import numpy as np 

2 

3import ase.units 

4from ase.calculators.calculator import FileIOCalculator, SCFError 

5 

6# Following the minimal requirements given in 

7# https://www.q-chem.com/qchem-website/manual/qchem43_manual/sect-METHOD.html 

8 

9 

10class QChem(FileIOCalculator): 

11 """ 

12 QChem calculator 

13 """ 

14 

15 name = 'QChem' 

16 

17 implemented_properties = ['energy', 'forces'] 

18 _legacy_default_command = 'qchem PREFIX.inp PREFIX.out' 

19 

20 default_parameters = { 

21 'method': 'hf', 

22 'basis': '6-31G*', 

23 'jobtype': None, 

24 'charge': 0, 

25 } 

26 

27 def __init__( 

28 self, 

29 restart=None, 

30 ignore_bad_restart_file=FileIOCalculator._deprecated, 

31 label='qchem', 

32 scratch=None, 

33 np=1, 

34 nt=1, 

35 pbs=False, 

36 basisfile=None, 

37 ecpfile=None, 

38 atoms=None, 

39 **kwargs, 

40 ): 

41 """ 

42 The scratch directory, number of processor and threads as well as a few 

43 other command line options can be set using the arguments explained 

44 below. The remaining kwargs are copied as options to the input file. 

45 The calculator will convert these options to upper case 

46 (Q-Chem standard) when writing the input file. 

47 

48 scratch: str 

49 path of the scratch directory 

50 np: int 

51 number of processors for the -np command line flag 

52 nt: int 

53 number of threads for the -nt command line flag 

54 pbs: boolean 

55 command line flag for pbs scheduler (see Q-Chem manual) 

56 basisfile: str 

57 path to file containing the basis. Use in combination with 

58 basis='gen' keyword argument. 

59 ecpfile: str 

60 path to file containing the effective core potential. Use in 

61 combination with ecp='gen' keyword argument. 

62 """ 

63 

64 FileIOCalculator.__init__( 

65 self, restart, ignore_bad_restart_file, label, atoms, **kwargs 

66 ) 

67 

68 # Augment the command by various flags 

69 if pbs: 

70 self.command = 'qchem -pbs ' 

71 else: 

72 self.command = 'qchem ' 

73 if np != 1: 

74 self.command += '-np %d ' % np 

75 if nt != 1: 

76 self.command += '-nt %d ' % nt 

77 self.command += 'PREFIX.inp PREFIX.out' 

78 if scratch is not None: 

79 self.command += f' {scratch}' 

80 

81 self.basisfile = basisfile 

82 self.ecpfile = ecpfile 

83 

84 def read(self, label): 

85 raise NotImplementedError 

86 

87 def read_results(self): 

88 filename = self.label + '.out' 

89 

90 with open(filename) as fileobj: 

91 lineiter = iter(fileobj) 

92 for line in lineiter: 

93 if 'SCF failed to converge' in line: 

94 raise SCFError() 

95 elif 'ERROR: alpha_min' in line: 

96 # Even though it is not technically a SCFError: 

97 raise SCFError() 

98 elif ' Total energy in the final basis set =' in line: 

99 convert = ase.units.Hartree 

100 self.results['energy'] = float(line.split()[8]) * convert 

101 elif ' Gradient of SCF Energy' in line: 

102 # Read gradient as 3 by N array and transpose at the end 

103 gradient = [[] for _ in range(3)] 

104 # Skip first line containing atom numbering 

105 next(lineiter) 

106 while True: 

107 # Loop over the three Cartesian coordinates 

108 for i in range(3): 

109 # Cut off the component numbering and remove 

110 # trailing characters ('\n' and stuff) 

111 line = next(lineiter)[5:].rstrip() 

112 # Cut in chunks of 12 symbols and convert into 

113 # strings. This is preferred over string.split() as 

114 # the fields may overlap for large gradients 

115 gradient[i].extend( 

116 list( 

117 map( 

118 float, 

119 [ 

120 line[i : i + 12] 

121 for i in range(0, len(line), 12) 

122 ], 

123 ) 

124 ) 

125 ) 

126 

127 # After three force components we expect either a 

128 # separator line, which we want to skip, or the end of 

129 # the gradient matrix which is characterized by the 

130 # line ' Max gradient component'. 

131 # Maybe change stopping criterion to be independent of 

132 # next line. Eg. if not lineiter.next().startswith(' ') 

133 if ' Max gradient component' in next(lineiter): 

134 # Minus to convert from gradient to force 

135 self.results['forces'] = np.array(gradient).T * ( 

136 -ase.units.Hartree / ase.units.Bohr 

137 ) 

138 break 

139 

140 def write_input(self, atoms, properties=None, system_changes=None): 

141 FileIOCalculator.write_input(self, atoms, properties, system_changes) 

142 filename = self.label + '.inp' 

143 

144 with open(filename, 'w') as fileobj: 

145 fileobj.write('$comment\n ASE generated input file\n$end\n\n') 

146 

147 fileobj.write('$rem\n') 

148 if self.parameters['jobtype'] is None: 

149 if 'forces' in properties: 

150 fileobj.write(' %-25s %s\n' % ('JOBTYPE', 'FORCE')) 

151 else: 

152 fileobj.write(' %-25s %s\n' % ('JOBTYPE', 'SP')) 

153 

154 for prm in self.parameters: 

155 if prm not in ['charge', 'multiplicity']: 

156 if self.parameters[prm] is not None: 

157 fileobj.write( 

158 ' %-25s %s\n' 

159 % (prm.upper(), self.parameters[prm].upper()) 

160 ) 

161 

162 # Not even a parameters as this is an absolute necessity 

163 fileobj.write(' %-25s %s\n' % ('SYM_IGNORE', 'TRUE')) 

164 fileobj.write('$end\n\n') 

165 

166 fileobj.write('$molecule\n') 

167 # Following the example set by the gaussian calculator 

168 if 'multiplicity' not in self.parameters: 

169 tot_magmom = atoms.get_initial_magnetic_moments().sum() 

170 mult = tot_magmom + 1 

171 else: 

172 mult = self.parameters['multiplicity'] 

173 # Default charge of 0 is defined in default_parameters 

174 fileobj.write(' %d %d\n' % (self.parameters['charge'], mult)) 

175 for a in atoms: 

176 fileobj.write( 

177 ' {} {:f} {:f} {:f}\n'.format(a.symbol, a.x, a.y, a.z) 

178 ) 

179 fileobj.write('$end\n\n') 

180 

181 if self.basisfile is not None: 

182 with open(self.basisfile) as f_in: 

183 basis = f_in.readlines() 

184 fileobj.write('$basis\n') 

185 fileobj.writelines(basis) 

186 fileobj.write('$end\n\n') 

187 

188 if self.ecpfile is not None: 

189 with open(self.ecpfile) as f_in: 

190 ecp = f_in.readlines() 

191 fileobj.write('$ecp\n') 

192 fileobj.writelines(ecp) 

193 fileobj.write('$end\n\n')