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
« 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.
3Link to the open-source DFTB code deMon-nano:
4http://demon-nano.ups-tlse.fr/
6export ASE_DEMONNANO_COMMAND="/path/to/bin/deMon.username.x"
7export DEMONNANO_BASIS_PATH="/path/to/basis/"
9The file 'deMon.inp' contains the input geometry and parameters
10The file 'deMon.out' contains the results
12"""
14import os.path as op
16# import subprocess
17import pathlib as pl
19import numpy as np
21import ase.data
22import ase.io
23from ase.calculators.calculator import FileIOCalculator, Parameters, ReadError
24from ase.units import Bohr, Hartree
27class DemonNanoParameters(Parameters):
28 """Parameters class for the calculator.
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.
34 """
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)
53class DemonNano(FileIOCalculator):
54 """Calculator interface to the deMon-nano code."""
56 implemented_properties = ['energy', 'forces']
58 def __init__(self, **kwargs):
59 """ASE interface to the deMon-nano code.
61 The deMon-nano code can be obtained from http://demon-nano.ups-tlse.fr/
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"
67 Parameters
68 ----------
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 """
98 parameters = DemonNanoParameters(**kwargs)
100 # basis path
101 basis_path = parameters['basis_path']
102 if basis_path is None:
103 basis_path = self.cfg.get('DEMONNANO_BASIS_PATH')
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
111 # Call the base class.
112 FileIOCalculator.__init__(self, **parameters)
114 def __getitem__(self, key):
115 """Convenience method to retrieve a parameter as
116 calculator[key] rather than calculator.parameters[key]
118 Parameters
119 ----------
120 key : str, the name of the parameters to get.
121 """
122 return self.parameters[key]
124 def write_input(self, atoms, properties=None, system_changes=None):
125 """Write input (in)-file.
126 See calculator.py for further details.
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.
134 """
135 # Call base calculator.
136 FileIOCalculator.write_input(
137 self,
138 atoms=atoms,
139 properties=properties,
140 system_changes=system_changes,
141 )
143 if system_changes is None and properties is None:
144 return
146 filename = self.label + '/deMon.inp'
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')
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)
162 # print argument, here other options could change this
163 value = self.parameters['print_out']
164 assert isinstance(value, str)
166 if len(value) != 0:
167 self._write_argument('PRINT', value, fd)
168 fd.write('\n')
170 # write general input arguments
171 self._write_input_arguments(fd)
173 if 'BASISPATH' not in self.parameters['input_arguments']:
174 value = self.parameters['basis_path']
175 fd.write(value)
176 fd.write('\n')
178 # write geometry
179 self._write_atomic_coordinates(fd, atoms)
181 # write xyz file for good measure.
182 ase.io.write(self.label + '/deMon_atoms.xyz', self.atoms)
184 def read(self, restart_path):
185 """Read parameters from directory restart_path."""
187 self.set_label(restart_path)
188 rpath = pl.Path(restart_path)
190 if not (rpath / 'deMon.inp').exists():
191 raise ReadError(
192 'The restart_path file {} does not exist'.format(rpath)
193 )
195 self.atoms = self.deMon_inp_to_atoms(rpath / 'deMon.inp')
197 self.read_results()
199 def _write_input_arguments(self, fd):
200 """Write directly given input-arguments."""
201 input_arguments = self.parameters['input_arguments']
203 # Early return
204 if input_arguments is None:
205 return
207 for key, value in input_arguments.items():
208 self._write_argument(key, value, fd)
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')
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 = ''
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')
258 for sym, pos in zip(atoms.symbols, atoms.positions):
259 fd.write('{:9s} {:10.5f} {:10.5f} {:10.5f}\n'.format(sym, *pos))
261 fd.write('\n')
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()
270 def read_energy(self):
271 """Read energy from deMon.ase output file."""
273 epath = pl.Path(self.label)
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 )
282 filename = self.label + '/deMon.ase'
284 if op.isfile(filename):
285 with open(filename) as fd:
286 lines = fd.readlines()
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
293 def read_forces(self, atoms):
294 """Read forces from the deMon.ase file."""
296 natoms = len(atoms)
297 epath = pl.Path(self.label)
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 )
306 filename = self.label + '/deMon.ase'
308 with open(filename) as fd:
309 lines = fd.readlines()
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
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)
333 def deMon_inp_to_atoms(self, filename):
334 """Routine to read deMon.inp and convert it to an atoms object."""
336 read_flag = False
337 chem_symbols = []
338 xyz = []
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'
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)
357 if coord_units == 'Bohr':
358 xyz *= Bohr
360 # set atoms object
361 atoms = ase.Atoms(symbols=chem_symbols, positions=xyz)
363 return atoms