Coverage for ase/calculators/demonnano.py: 43.62%

149 statements  

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

1"""This module defines an ASE interface to deMon-nano. 

2 

3Link to the open-source DFTB code deMon-nano: 

4http://demon-nano.ups-tlse.fr/ 

5 

6export ASE_DEMONNANO_COMMAND="/path/to/bin/deMon.username.x" 

7export DEMONNANO_BASIS_PATH="/path/to/basis/" 

8 

9The file 'deMon.inp' contains the input geometry and parameters 

10The file 'deMon.out' contains the results 

11 

12""" 

13 

14import os.path as op 

15 

16# import subprocess 

17import pathlib as pl 

18 

19import numpy as np 

20 

21import ase.data 

22import ase.io 

23from ase.calculators.calculator import FileIOCalculator, Parameters, ReadError 

24from ase.units import Bohr, Hartree 

25 

26 

27class DemonNanoParameters(Parameters): 

28 """Parameters class for the calculator. 

29 

30 The options here are the most important ones that the user needs to be 

31 aware of. Further options accepted by deMon can be set in the dictionary 

32 input_arguments. 

33 

34 """ 

35 

36 def __init__( 

37 self, 

38 label='.', 

39 atoms=None, 

40 command=None, 

41 basis_path=None, 

42 restart_path='.', 

43 print_out='ASE', 

44 title='deMonNano input file', 

45 forces=False, 

46 input_arguments=None, 

47 ): 

48 kwargs = locals() 

49 kwargs.pop('self') 

50 Parameters.__init__(self, **kwargs) 

51 

52 

53class DemonNano(FileIOCalculator): 

54 """Calculator interface to the deMon-nano code.""" 

55 

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

57 

58 def __init__(self, **kwargs): 

59 """ASE interface to the deMon-nano code. 

60 

61 The deMon-nano code can be obtained from http://demon-nano.ups-tlse.fr/ 

62 

63 The ASE_DEMONNANO_COMMAND environment variable must be set to run 

64 the executable, in bash it would be set along the lines of 

65 export ASE_DEMONNANO_COMMAND="pathway-to-deMon-binary/deMon.username.x" 

66 

67 Parameters 

68 ---------- 

69 

70 label : str 

71 relative path to the run directory 

72 atoms : Atoms object 

73 the atoms object 

74 command : str 

75 Command to run deMon. If not present, the environment variable 

76 ASE_DEMONNANO_COMMAND is used 

77 basis_path : str 

78 Relative path to the directory containing DFTB-SCC or DFTB-0 

79 parameters 

80 If not present, the environment variable DEMONNANO_BASIS_PATH 

81 is used 

82 restart_path : str 

83 Relative path to the deMon restart dir 

84 title : str 

85 Title in the deMon input file. 

86 forces : bool 

87 If True a force calculation is enforced 

88 print_out : str | list 

89 Options for the printing in deMon 

90 input_arguments : dict 

91 Explicitly given input arguments. The key is the input keyword 

92 and the value is either a str, a list of str 

93 (will be written on the same line as the keyword), 

94 or a list of lists of str (first list is written on the 

95 first line, the others on following lines.) 

96 """ 

97 

98 parameters = DemonNanoParameters(**kwargs) 

99 

100 # basis path 

101 basis_path = parameters['basis_path'] 

102 if basis_path is None: 

103 basis_path = self.cfg.get('DEMONNANO_BASIS_PATH') 

104 

105 if basis_path is None: 

106 mess = 'The "DEMONNANO_BASIS_PATH" environment is not defined.' 

107 raise ValueError(mess) 

108 else: 

109 parameters['basis_path'] = basis_path 

110 

111 # Call the base class. 

112 FileIOCalculator.__init__(self, **parameters) 

113 

114 def __getitem__(self, key): 

115 """Convenience method to retrieve a parameter as 

116 calculator[key] rather than calculator.parameters[key] 

117 

118 Parameters 

119 ---------- 

120 key : str, the name of the parameters to get. 

121 """ 

122 return self.parameters[key] 

123 

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

125 """Write input (in)-file. 

126 See calculator.py for further details. 

127 

128 Parameters 

129 ---------- 

130 atoms : The Atoms object to write. 

131 properties : The properties which should be calculated. 

132 system_changes : List of properties changed since last run. 

133 

134 """ 

135 # Call base calculator. 

136 FileIOCalculator.write_input( 

137 self, 

138 atoms=atoms, 

139 properties=properties, 

140 system_changes=system_changes, 

141 ) 

142 

143 if system_changes is None and properties is None: 

144 return 

145 

146 filename = self.label + '/deMon.inp' 

147 

148 # Start writing the file. 

149 with open(filename, 'w') as fd: 

150 # write keyword argument keywords 

151 value = self.parameters['title'] 

152 self._write_argument('TITLE', value, fd) 

153 fd.write('\n') 

154 

155 # obtain forces through a single BOMD step 

156 # only if forces is in properties, or if keyword forces is True 

157 value = self.parameters['forces'] 

158 if 'forces' in properties or value: 

159 self._write_argument('MDYNAMICS', 'ZERO', fd) 

160 self._write_argument('MDSTEP', 'MAX=1', fd) 

161 

162 # print argument, here other options could change this 

163 value = self.parameters['print_out'] 

164 assert isinstance(value, str) 

165 

166 if len(value) != 0: 

167 self._write_argument('PRINT', value, fd) 

168 fd.write('\n') 

169 

170 # write general input arguments 

171 self._write_input_arguments(fd) 

172 

173 if 'BASISPATH' not in self.parameters['input_arguments']: 

174 value = self.parameters['basis_path'] 

175 fd.write(value) 

176 fd.write('\n') 

177 

178 # write geometry 

179 self._write_atomic_coordinates(fd, atoms) 

180 

181 # write xyz file for good measure. 

182 ase.io.write(self.label + '/deMon_atoms.xyz', self.atoms) 

183 

184 def read(self, restart_path): 

185 """Read parameters from directory restart_path.""" 

186 

187 self.set_label(restart_path) 

188 rpath = pl.Path(restart_path) 

189 

190 if not (rpath / 'deMon.inp').exists(): 

191 raise ReadError( 

192 'The restart_path file {} does not exist'.format(rpath) 

193 ) 

194 

195 self.atoms = self.deMon_inp_to_atoms(rpath / 'deMon.inp') 

196 

197 self.read_results() 

198 

199 def _write_input_arguments(self, fd): 

200 """Write directly given input-arguments.""" 

201 input_arguments = self.parameters['input_arguments'] 

202 

203 # Early return 

204 if input_arguments is None: 

205 return 

206 

207 for key, value in input_arguments.items(): 

208 self._write_argument(key, value, fd) 

209 

210 def _write_argument(self, key, value, fd): 

211 """Write an argument to file. 

212 key : a string coresponding to the input keyword 

213 value : the arguments, can be a string, a number or a list 

214 fd : and open file 

215 """ 

216 if key == 'BASISPATH': 

217 # Write a basis path to file. 

218 # Has to be in lowercase for deMon-nano to work 

219 line = value.lower() 

220 fd.write(line) 

221 fd.write('\n') 

222 elif not isinstance(value, (tuple, list)): 

223 # for only one argument, write on same line 

224 line = key.upper() 

225 line += ' ' + str(value).upper() 

226 fd.write(line) 

227 fd.write('\n') 

228 

229 # for a list, write first argument on the first line, 

230 # then the rest on new lines 

231 else: 

232 line = key 

233 if not isinstance(value[0], (tuple, list)): 

234 for i in range(len(value)): 

235 line += ' ' + str(value[i].upper()) 

236 fd.write(line) 

237 fd.write('\n') 

238 else: 

239 for i in range(len(value)): 

240 for j in range(len(value[i])): 

241 line += ' ' + str(value[i][j]).upper() 

242 fd.write(line) 

243 fd.write('\n') 

244 line = '' 

245 

246 def _write_atomic_coordinates(self, fd, atoms): 

247 """Write atomic coordinates. 

248 Parameters 

249 ---------- 

250 - fd: An open file object. 

251 - atoms: An atoms object. 

252 """ 

253 # fd.write('#\n') 

254 # fd.write('# Atomic coordinates\n') 

255 # fd.write('#\n') 

256 fd.write('GEOMETRY CARTESIAN ANGSTROM\n') 

257 

258 for sym, pos in zip(atoms.symbols, atoms.positions): 

259 fd.write('{:9s} {:10.5f} {:10.5f} {:10.5f}\n'.format(sym, *pos)) 

260 

261 fd.write('\n') 

262 

263 # Analysis routines 

264 def read_results(self): 

265 """Read the results from output files.""" 

266 self.read_energy() 

267 self.read_forces(self.atoms) 

268 # self.read_eigenvalues() 

269 

270 def read_energy(self): 

271 """Read energy from deMon.ase output file.""" 

272 

273 epath = pl.Path(self.label) 

274 

275 if not (epath / 'deMon.ase').exists(): 

276 raise ReadError( 

277 'The deMonNano output file for ASE {} does not exist'.format( 

278 epath 

279 ) 

280 ) 

281 

282 filename = self.label + '/deMon.ase' 

283 

284 if op.isfile(filename): 

285 with open(filename) as fd: 

286 lines = fd.readlines() 

287 

288 for i in range(len(lines)): 

289 if lines[i].startswith(' DFTB total energy [Hartree]'): 

290 self.results['energy'] = float(lines[i + 1]) * Hartree 

291 break 

292 

293 def read_forces(self, atoms): 

294 """Read forces from the deMon.ase file.""" 

295 

296 natoms = len(atoms) 

297 epath = pl.Path(self.label) 

298 

299 if not (epath / 'deMon.ase').exists(): 

300 raise ReadError( 

301 'The deMonNano output file for ASE {} does not exist'.format( 

302 epath 

303 ) 

304 ) 

305 

306 filename = self.label + '/deMon.ase' 

307 

308 with open(filename) as fd: 

309 lines = fd.readlines() 

310 

311 # find line where the forces start 

312 flag_found = False 

313 for i in range(len(lines)): 

314 if 'DFTB gradients at 0 time step in a.u.' in lines[i]: 

315 start = i + 1 

316 flag_found = True 

317 break 

318 

319 if flag_found: 

320 self.results['forces'] = np.zeros((natoms, 3), float) 

321 for i in range(natoms): 

322 line = [ 

323 s 

324 for s in lines[i + start].strip().split(' ') 

325 if len(s) > 0 

326 ] 

327 f = -np.array([float(x) for x in line[1:4]]) 

328 # output forces in a.u. 

329 # self.results['forces'][i, :] = f 

330 # output forces with real dimension 

331 self.results['forces'][i, :] = f * (Hartree / Bohr) 

332 

333 def deMon_inp_to_atoms(self, filename): 

334 """Routine to read deMon.inp and convert it to an atoms object.""" 

335 

336 read_flag = False 

337 chem_symbols = [] 

338 xyz = [] 

339 

340 with open(filename) as fd: 

341 for line in fd: 

342 if 'GEOMETRY' in line: 

343 read_flag = True 

344 if 'ANGSTROM' in line: 

345 coord_units = 'Ang' 

346 elif 'BOHR' in line: 

347 coord_units = 'Bohr' 

348 

349 if read_flag: 

350 tokens = line.split() 

351 symbol = tokens[0] 

352 xyz_loc = np.array(tokens[1:4]).astype(float) 

353 if read_flag and tokens: 

354 chem_symbols.append(symbol) 

355 xyz.append(xyz_loc) 

356 

357 if coord_units == 'Bohr': 

358 xyz *= Bohr 

359 

360 # set atoms object 

361 atoms = ase.Atoms(symbols=chem_symbols, positions=xyz) 

362 

363 return atoms