Coverage for ase/calculators/dmol.py: 28.30%

311 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 DMol3. 

2 

3Contacts 

4-------- 

5Adam Arvidsson <adam.arvidsson@chalmers.se> 

6Erik Fransson <erikfr@chalmers.se> 

7Anders Hellman <anders.hellman@chalmers.se> 

8 

9 

10DMol3 environment variables 

11---------------------------- 

12DMOL_COMMAND should point to the RunDmol script and specify the number of cores 

13to prallelize over 

14 

15export DMOL_COMMAND="./RunDmol.sh -np 16" 

16 

17 

18Example 

19-------- 

20>>> from ase.build import bulk 

21>>> from ase.calculators import DMol3 

22 

23>>> atoms = bulk('Al','fcc') 

24>>> calc = DMol3() 

25>>> atoms.calc = calc 

26>>> print 'Potential energy %5.5f eV' % atoms.get_potential_energy() 

27 

28 

29DMol3 calculator functionality 

30------------------------------- 

31This calculator does support all the functionality in DMol3. 

32 

33Firstly this calculator is limited to only handling either fully 

34periodic structures (pbc = [1,1,1]) or non periodic structures (pbc=[0,0,0]). 

35 

36Internal relaxations are not supported by the calculator, 

37only support for energy and forces is implemented. 

38 

39Reading eigenvalues and kpts are supported. 

40Be careful with kpts and their directions (see internal coordinates below). 

41 

42Outputting the full electron density or specific bands to .grd files can be 

43achieved with the plot command. The .grd files can be converted to the cube 

44format using grd_to_cube(). 

45 

46 

47DMol3 internal coordinates 

48--------------------------- 

49DMol3 may change the atomic positions / cell vectors in order to satisfy 

50certain criterion ( e.g. molecule symmetry axis along z ). Specifically this 

51happens when using Symmetry on/auto. This means the forces read from .grad 

52will be in a different coordinates system compared to the atoms object used. 

53To solve this the rotation matrix that converts the dmol coordinate system 

54to the ase coordinate system is found and applied to the forces. 

55 

56For non periodic structures (pbc=[0,0,0]) the rotation matrix can be directly 

57parsed from the .rot file. 

58For fully periodic structures the rotation matrix is found by reading the 

59cell vectors and positions used by dmol and then solving the matrix problem 

60DMol_atoms * rot_mat = ase_atoms 

61 

62 

63DMol3 files 

64------------ 

65The supported DMol3 file formats are: 

66 

67car structure file - Angstrom and cellpar description of cell. 

68incoor structure file - Bohr and cellvector describption of cell. 

69 Note: incoor file not used if car file present. 

70outmol outfile from DMol3 - atomic units (Bohr and Hartree) 

71grad outfile for forces from DMol3 - forces in Hartree/Bohr 

72grd outfile for orbitals from DMol3 - cellpar in Angstrom 

73 

74""" 

75 

76import os 

77import re 

78 

79import numpy as np 

80 

81from ase import Atoms 

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

83from ase.io import read 

84from ase.io.dmol import write_dmol_car, write_dmol_incoor 

85from ase.units import Bohr, Hartree 

86 

87 

88class DMol3(FileIOCalculator): 

89 """DMol3 calculator object.""" 

90 

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

92 default_parameters = {'functional': 'pbe', 'symmetry': 'on'} 

93 discard_results_on_any_change = True 

94 

95 def __init__( 

96 self, 

97 restart=None, 

98 ignore_bad_restart_file=FileIOCalculator._deprecated, 

99 label='dmol_calc/tmp', 

100 atoms=None, 

101 command=None, 

102 **kwargs, 

103 ): 

104 """Construct DMol3 calculator.""" 

105 

106 if command is None: 

107 if 'DMOL_COMMAND' in self.cfg: 

108 command = self.cfg['DMOL_COMMAND'] + ' PREFIX > PREFIX.out' 

109 

110 super().__init__( 

111 restart, 

112 ignore_bad_restart_file, 

113 label, 

114 atoms, 

115 command=command, 

116 **kwargs, 

117 ) 

118 

119 # tracks if DMol transformed coordinate system 

120 self.internal_transformation = False 

121 

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

123 

124 if not np.all(atoms.pbc) and np.any(atoms.pbc): 

125 raise RuntimeError('PBC must be all true or all false') 

126 

127 self.clean() # Remove files from old run 

128 self.internal_transformation = False 

129 self.ase_positions = atoms.positions.copy() 

130 self.ase_cell = atoms.cell.copy() 

131 

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

133 

134 if np.all(atoms.pbc): 

135 write_dmol_incoor(self.label + '.incoor', atoms) 

136 elif not np.any(atoms.pbc): 

137 write_dmol_car(self.label + '.car', atoms) 

138 

139 self.write_input_file() 

140 self.parameters.write(self.label + '.parameters.ase') 

141 

142 def write_input_file(self): 

143 """Writes the input file.""" 

144 with open(self.label + '.input', 'w') as fd: 

145 self._write_input_file(fd) 

146 

147 def _write_input_file(self, fd): 

148 fd.write('%-32s %s\n' % ('calculate', 'gradient')) 

149 

150 # if no key about eigs 

151 fd.write('%-32s %s\n' % ('print', 'eigval_last_it')) 

152 

153 for key, value in self.parameters.items(): 

154 if isinstance(value, str): 

155 fd.write('%-32s %s\n' % (key, value)) 

156 elif isinstance(value, (list, tuple)): 

157 for val in value: 

158 fd.write('%-32s %s\n' % (key, val)) 

159 else: 

160 fd.write('%-32s %r\n' % (key, value)) 

161 

162 def read(self, label): 

163 FileIOCalculator.read(self, label) 

164 geometry = self.label + '.car' 

165 output = self.label + '.outmol' 

166 force = self.label + '.grad' 

167 

168 for filename in [force, output, geometry]: 

169 if not os.path.isfile(filename): 

170 raise ReadError 

171 

172 self.atoms = read(geometry) 

173 self.parameters = Parameters.read(self.label + 'parameters.ase') 

174 self.read_results() 

175 

176 def read_results(self): 

177 finished, message = self.finished_successfully() 

178 if not finished: 

179 raise RuntimeError( 

180 'DMol3 run failed, see outmol file for' 

181 ' more info\n\n%s' % message 

182 ) 

183 

184 self.find_dmol_transformation() 

185 self.read_energy() 

186 self.read_forces() 

187 

188 def finished_successfully(self): 

189 """Reads outmol file and checks if job completed or failed. 

190 

191 Returns 

192 ------- 

193 finished (bool): True if job completed, False if something went wrong 

194 message (str): If job failed message contains parsed errors, else empty 

195 

196 """ 

197 finished = False 

198 message = '' 

199 for line in self._outmol_lines(): 

200 if line.rfind('Message: DMol3 job finished successfully') > -1: 

201 finished = True 

202 if line.startswith('Error'): 

203 message += line 

204 return finished, message 

205 

206 def find_dmol_transformation(self, tol=1e-4): 

207 """Finds rotation matrix that takes us from DMol internal 

208 coordinates to ase coordinates. 

209 

210 For pbc = [False, False, False] the rotation matrix is parsed from 

211 the .rot file, if this file doesnt exist no rotation is needed. 

212 

213 For pbc = [True, True, True] the Dmol internal cell vectors and 

214 positions are parsed and compared to self.ase_cell self.ase_positions. 

215 The rotation matrix can then be found by a call to the helper 

216 function find_transformation(atoms1, atoms2) 

217 

218 If a rotation matrix is needed then self.internal_transformation is 

219 set to True and the rotation matrix is stored in self.rotation_matrix 

220 

221 Parameters 

222 ---------- 

223 tol (float): tolerance for check if positions and cell are the same 

224 """ 

225 

226 if np.all(self.atoms.pbc): # [True, True, True] 

227 dmol_atoms = self.read_atoms_from_outmol() 

228 if ( 

229 np.linalg.norm(self.atoms.positions - dmol_atoms.positions) 

230 < tol 

231 ) and (np.linalg.norm(self.atoms.cell - dmol_atoms.cell) < tol): 

232 self.internal_transformation = False 

233 else: 

234 R, err = find_transformation(dmol_atoms, self.atoms) 

235 if abs(np.linalg.det(R) - 1.0) > tol: 

236 raise RuntimeError( 

237 'Error: transformation matrix does' 

238 ' not have determinant 1.0' 

239 ) 

240 if err < tol: 

241 self.internal_transformation = True 

242 self.rotation_matrix = R 

243 else: 

244 raise RuntimeError( 

245 'Error: Could not find dmol coordinate transformation' 

246 ) 

247 elif not np.any(self.atoms.pbc): # [False,False,False] 

248 try: 

249 data = np.loadtxt(self.label + '.rot') 

250 except OSError: 

251 self.internal_transformation = False 

252 else: 

253 self.internal_transformation = True 

254 self.rotation_matrix = data[1:].transpose() 

255 

256 def read_atoms_from_outmol(self): 

257 """Reads atomic positions and cell from outmol file and returns atoms 

258 object. 

259 

260 If no cell vectors are found in outmol the cell is set to np.eye(3) and 

261 pbc 000. 

262 

263 Formatting for cell in outmol : 

264 translation vector [a0] 1 5.1 0.0 5.1 

265 translation vector [a0] 2 5.1 5.1 0.0 

266 translation vector [a0] 3 0.0 5.1 5.1 

267 

268 Formatting for positions in outmol: 

269 df ATOMIC COORDINATES (au) 

270 df x y z 

271 df Si 0.0 0.0 0.0 

272 df Si 1.3 3.5 2.2 

273 df binding energy -0.2309046Ha 

274 

275 Returns 

276 ------- 

277 atoms (Atoms object): read atoms object 

278 """ 

279 

280 lines = self._outmol_lines() 

281 found_cell = False 

282 cell = np.zeros((3, 3)) 

283 symbols = [] 

284 positions = [] 

285 pattern_translation_vectors = re.compile(r'\s+translation\s+vector') 

286 pattern_atomic_coordinates = re.compile(r'df\s+ATOMIC\s+COORDINATES') 

287 

288 for i, line in enumerate(lines): 

289 if pattern_translation_vectors.match(line): 

290 cell[int(line.split()[3]) - 1, :] = np.array( 

291 [float(x) for x in line.split()[-3:]] 

292 ) 

293 found_cell = True 

294 if pattern_atomic_coordinates.match(line): 

295 for ind, j in enumerate(range(i + 2, i + 2 + len(self.atoms))): 

296 flds = lines[j].split() 

297 symbols.append(flds[1]) 

298 positions.append(flds[2:5]) 

299 atoms = Atoms(symbols=symbols, positions=positions, cell=cell) 

300 atoms.positions *= Bohr 

301 atoms.cell *= Bohr 

302 

303 if found_cell: 

304 atoms.pbc = [True, True, True] 

305 atoms.wrap() 

306 else: 

307 atoms.pbc = [False, False, False] 

308 return atoms 

309 

310 def read_energy(self): 

311 """Find and return last occurrence of Ef in outmole file.""" 

312 energy_regex = re.compile(r'^Ef\s+(\S+)Ha') 

313 found = False 

314 for line in self._outmol_lines(): 

315 match = energy_regex.match(line) 

316 if match: 

317 energy = float(match.group(1)) 

318 found = True 

319 if not found: 

320 raise RuntimeError('Could not read energy from outmol') 

321 self.results['energy'] = energy * Hartree 

322 

323 def read_forces(self): 

324 """Read forces from .grad file. Applies self.rotation_matrix if 

325 self.internal_transformation is True.""" 

326 with open(self.label + '.grad') as fd: 

327 lines = fd.readlines() 

328 

329 forces = [] 

330 for i, line in enumerate(lines): 

331 if line.startswith('$gradients'): 

332 for j in range(i + 1, i + 1 + len(self.atoms)): 

333 # force = - grad(Epot) 

334 forces.append( 

335 np.array([-float(x) for x in lines[j].split()[1:4]]) 

336 ) 

337 

338 forces = np.array(forces) * Hartree / Bohr 

339 if self.internal_transformation: 

340 forces = np.dot(forces, self.rotation_matrix) 

341 self.results['forces'] = forces 

342 

343 def get_eigenvalues(self, kpt=0, spin=0): 

344 return self.read_eigenvalues(kpt, spin, 'eigenvalues') 

345 

346 def get_occupations(self, kpt=0, spin=0): 

347 return self.read_eigenvalues(kpt, spin, 'occupations') 

348 

349 def get_k_point_weights(self): 

350 return self.read_kpts(mode='k_point_weights') 

351 

352 def get_bz_k_points(self): 

353 raise NotImplementedError 

354 

355 def get_ibz_k_points(self): 

356 return self.read_kpts(mode='ibz_k_points') 

357 

358 def get_spin_polarized(self): 

359 return self.read_spin_polarized() 

360 

361 def get_fermi_level(self): 

362 return self.read_fermi() 

363 

364 def get_energy_contributions(self): 

365 return self.read_energy_contributions() 

366 

367 def get_xc_functional(self): 

368 return self.parameters['functional'] 

369 

370 def read_eigenvalues(self, kpt=0, spin=0, mode='eigenvalues'): 

371 """Reads eigenvalues from .outmol file. 

372 

373 This function splits into two situations: 

374 1. We have no kpts just the raw eigenvalues ( Gamma point ) 

375 2. We have eigenvalues for each k-point 

376 

377 If calculation is spin_restricted then all eigenvalues 

378 will be returned no matter what spin parameter is set to. 

379 

380 If calculation has no kpts then all eigenvalues 

381 will be returned no matter what kpts parameter is set to. 

382 

383 Note DMol does usually NOT print all unoccupied eigenvalues. 

384 Meaning number of eigenvalues for different kpts can vary. 

385 """ 

386 

387 assert mode in ['eigenvalues', 'occupations'] 

388 lines = self._outmol_lines() 

389 pattern_kpts = re.compile(r'Eigenvalues for kvector\s+%d' % (kpt + 1)) 

390 for n, line in enumerate(lines): 

391 # 1. We have no kpts 

392 if line.split() == ['state', 'eigenvalue', 'occupation']: 

393 spin_key = '+' 

394 if self.get_spin_polarized(): 

395 if spin == 1: 

396 spin_key = '-' 

397 val_index = -2 

398 if mode == 'occupations': 

399 val_index = -1 

400 values = [] 

401 m = n + 3 

402 while True: 

403 if lines[m].strip() == '': 

404 break 

405 flds = lines[m].split() 

406 if flds[1] == spin_key: 

407 values.append(float(flds[val_index])) 

408 m += 1 

409 return np.array(values) 

410 

411 # 2. We have kpts 

412 if pattern_kpts.match(line): 

413 val_index = 3 

414 if self.get_spin_polarized(): 

415 if spin == 1: 

416 val_index = 6 

417 if mode == 'occupations': 

418 val_index += 1 

419 values = [] 

420 m = n + 2 

421 while True: 

422 if lines[m].strip() == '': 

423 break 

424 values.append(float(lines[m].split()[val_index])) 

425 m += 1 

426 return np.array(values) 

427 return None 

428 

429 def _outmol_lines(self): 

430 with open(self.label + '.outmol') as fd: 

431 return fd.readlines() 

432 

433 def read_kpts(self, mode='ibz_k_points'): 

434 """Returns list of kpts coordinates or kpts weights.""" 

435 

436 assert mode in ['ibz_k_points', 'k_point_weights'] 

437 lines = self._outmol_ines() 

438 

439 values = [] 

440 for n, line in enumerate(lines): 

441 if line.startswith('Eigenvalues for kvector'): 

442 if mode == 'ibz_k_points': 

443 values.append([float(k_i) for k_i in lines[n].split()[4:7]]) 

444 if mode == 'k_point_weights': 

445 values.append(float(lines[n].split()[8])) 

446 if values == []: 

447 return None 

448 return values 

449 

450 def read_spin_polarized(self): 

451 """Reads, from outmol file, if calculation is spin polarized.""" 

452 

453 lines = self._outmol_lines() 

454 for n, line in enumerate(lines): 

455 if line.rfind('Calculation is Spin_restricted') > -1: 

456 return False 

457 if line.rfind('Calculation is Spin_unrestricted') > -1: 

458 return True 

459 raise OSError('Could not read spin restriction from outmol') 

460 

461 def read_fermi(self): 

462 """Reads the Fermi level. 

463 

464 Example line in outmol: 

465 Fermi Energy: -0.225556 Ha -6.138 eV xyz text 

466 """ 

467 lines = self._outmol_lines() 

468 pattern_fermi = re.compile(r'Fermi Energy:\s+(\S+)\s+Ha') 

469 for line in lines: 

470 m = pattern_fermi.match(line) 

471 if m: 

472 return float(m.group(1)) * Hartree 

473 return None 

474 

475 def read_energy_contributions(self): 

476 """Reads the different energy contributions.""" 

477 

478 lines = self._outmol_lines() 

479 energies = {} 

480 for n, line in enumerate(lines): 

481 if line.startswith('Energy components'): 

482 m = n + 1 

483 while lines[m].strip() != '': 

484 energies[lines[m].split('=')[0].strip()] = ( 

485 float(re.findall(r'[-+]?\d*\.\d+|\d+', lines[m])[0]) 

486 * Hartree 

487 ) 

488 m += 1 

489 return energies 

490 

491 def clean(self): 

492 """Cleanup after dmol calculation 

493 

494 Only removes dmol files in self.directory, 

495 does not remove the directory itself 

496 """ 

497 file_extensions = [ 

498 'basis', 

499 'car', 

500 'err', 

501 'grad', 

502 'input', 

503 'inatm', 

504 'incoor', 

505 'kpoints', 

506 'monitor', 

507 'occup', 

508 'outmol', 

509 'outatom', 

510 'rot', 

511 'sdf', 

512 'sym', 

513 'tpotl', 

514 'tpdensk', 

515 'torder', 

516 'out', 

517 'parameters.ase', 

518 ] 

519 files_to_clean = ['DMol3.log', 'stdouterr.txt', 'mpd.hosts'] 

520 

521 files = [os.path.join(self.directory, f) for f in files_to_clean] 

522 files += [''.join((self.label, '.', ext)) for ext in file_extensions] 

523 

524 for f in files: 

525 try: 

526 os.remove(f) 

527 except OSError: 

528 pass 

529 

530 

531# Helper functions 

532# ------------------ 

533 

534 

535def find_transformation(atoms1, atoms2, verbose=False, only_cell=False): 

536 """Solves Ax = B where A and B are cell and positions from atoms objects. 

537 

538 Uses numpys least square solver to solve the problem Ax = B where A and 

539 B are cell vectors and positions for atoms1 and atoms2 respectively. 

540 

541 Parameters 

542 ---------- 

543 atoms1 (Atoms object): First atoms object (A) 

544 atoms2 (Atoms object): Second atoms object (B) 

545 verbose (bool): If True prints for each i A[i], B[i], Ax[i] 

546 only_cell (bool): If True only cell in used, otherwise cell and positions. 

547 

548 Returns 

549 ------- 

550 x (np.array((3,3))): Least square solution to Ax = B 

551 error (float): The error calculated as np.linalg.norm(Ax-b) 

552 

553 """ 

554 

555 if only_cell: 

556 N = 3 

557 elif len(atoms1) != len(atoms2): 

558 raise RuntimeError('Atoms object must be of same length') 

559 else: 

560 N = len(atoms1) + 3 

561 

562 # Setup matrices A and B 

563 A = np.zeros((N, 3)) 

564 B = np.zeros((N, 3)) 

565 A[0:3, :] = atoms1.cell 

566 B[0:3, :] = atoms2.cell 

567 if not only_cell: 

568 A[3:, :] = atoms1.positions 

569 B[3:, :] = atoms2.positions 

570 

571 # Solve least square problem Ax = B 

572 lstsq_fit = np.linalg.lstsq(A, B, rcond=-1) 

573 x = lstsq_fit[0] 

574 error = np.linalg.norm(np.dot(A, x) - B) 

575 

576 # Print comparison between A, B and Ax 

577 if verbose: 

578 print('%17s %33s %35s %24s' % ('A', 'B', 'Ax', '|Ax-b|')) 

579 for a, b in zip(A, B): 

580 ax = np.dot(a, x) 

581 loss = np.linalg.norm(ax - b) 

582 print('(', end='') 

583 for a_i in a: 

584 print('%8.5f' % a_i, end='') 

585 print(') (', end='') 

586 for b_i in b: 

587 print('%8.5f ' % b_i, end='') 

588 print(') (', end='') 

589 for ax_i in ax: 

590 print('%8.5f ' % ax_i, end='') 

591 print(') %8.5f' % loss) 

592 

593 return x, error 

594 

595 

596def grd_to_file(atoms, grd_file, new_file): 

597 """Reads grd_file and converts data to cube format and writes to 

598 cube_file. 

599 

600 Note: content of grd_file and atoms object are assumed to match with the 

601 same orientation. 

602 

603 Parameters 

604 ----------- 

605 atoms (Atoms object): atoms object grd_file data is for 

606 grd_file (str): filename of .grd file 

607 new_file (str): filename to write grd-data to, must be ASE format 

608 that supports data argument 

609 """ 

610 from ase.io import write 

611 

612 atoms_copy = atoms.copy() 

613 data, cell, origin = read_grd(grd_file) 

614 atoms_copy.cell = cell 

615 atoms_copy.positions += origin 

616 write(new_file, atoms_copy, data=data) 

617 

618 

619def read_grd(filename): 

620 """Reads .grd file 

621 

622 Notes 

623 ----- 

624 origin_xyz is offset with half a grid point in all directions to be 

625 compatible with the cube format 

626 Periodic systems is not guaranteed to be oriented correctly 

627 """ 

628 from ase.geometry.cell import cellpar_to_cell 

629 

630 with open(filename) as fd: 

631 lines = fd.readlines() 

632 

633 cell_data = np.array([float(fld) for fld in lines[2].split()]) 

634 cell = cellpar_to_cell(cell_data) 

635 grid = [int(fld) + 1 for fld in lines[3].split()] 

636 data = np.empty(grid) 

637 

638 origin_data = [int(fld) for fld in lines[4].split()[1:]] 

639 origin_xyz = ( 

640 cell[0] * (-float(origin_data[0]) - 0.5) / (grid[0] - 1) 

641 + cell[1] * (-float(origin_data[2]) - 0.5) / (grid[1] - 1) 

642 + cell[2] * (-float(origin_data[4]) - 0.5) / (grid[2] - 1) 

643 ) 

644 

645 # Fastest index describes which index ( x or y ) varies fastest 

646 # 1: x , 3: y 

647 fastest_index = int(lines[4].split()[0]) 

648 assert fastest_index in [1, 3] 

649 if fastest_index == 3: 

650 grid[0], grid[1] = grid[1], grid[0] 

651 

652 dummy_counter = 5 

653 for i in range(grid[2]): 

654 for j in range(grid[1]): 

655 for k in range(grid[0]): # Fastest index 

656 if fastest_index == 1: 

657 data[k, j, i] = float(lines[dummy_counter]) 

658 elif fastest_index == 3: 

659 data[j, k, i] = float(lines[dummy_counter]) 

660 dummy_counter += 1 

661 

662 return data, cell, origin_xyz 

663 

664 

665if __name__ == '__main__': 

666 from ase.build import molecule 

667 

668 atoms = molecule('H2') 

669 calc = DMol3() 

670 atoms.calc = calc 

671 # ~ 60 sec calculation 

672 print('Potential energy %5.5f eV' % atoms.get_potential_energy())