Coverage for ase/calculators/acemolecule.py: 72.63%
95 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
1import os
2from copy import deepcopy
4from ase.calculators.calculator import FileIOCalculator, ReadError
5from ase.io import read
8class ACE(FileIOCalculator):
9 """
10 ACE-Molecule logfile reader
11 It has default parameters of each input section
12 And parameters' type = list of dictionaries
13 """
15 name = 'ace'
16 implemented_properties = ['energy', 'forces', 'excitation-energy']
17 basic_list = [
18 {
19 'Type': 'Scaling',
20 'Scaling': '0.35',
21 'Basis': 'Sinc',
22 'Grid': 'Sphere',
23 'KineticMatrix': 'Finite_Difference',
24 'DerivativesOrder': '7',
25 'GeometryFilename': None,
26 'NumElectrons': None,
27 }
28 ]
29 scf_list = [
30 {
31 'ExchangeCorrelation': {
32 'XFunctional': 'GGA_X_PBE',
33 'CFunctional': 'GGA_C_PBE',
34 },
35 'NumberOfEigenvalues': None,
36 }
37 ]
39 force_list = [{'ForceDerivative': 'Potential'}]
40 tddft_list = [
41 {
42 'SortOrbital': 'Order',
43 'MaximumOrder': '10',
44 'ExchangeCorrelation': {
45 'XFunctional': 'GGA_X_PBE',
46 'CFunctional': 'GGA_C_PBE',
47 },
48 }
49 ]
51 order_list = ['BasicInformation', 'Guess', 'Scf']
52 guess_list = [{}] # type: ignore[var-annotated]
53 default_parameters = {
54 'BasicInformation': basic_list,
55 'Guess': guess_list,
56 'Scf': scf_list,
57 'Force': force_list,
58 'TDDFT': tddft_list,
59 'order': order_list,
60 }
62 def __init__(
63 self,
64 restart=None,
65 ignore_bad_restart_file=FileIOCalculator._deprecated,
66 label='ace',
67 atoms=None,
68 command=None,
69 basisfile=None,
70 **kwargs,
71 ):
72 FileIOCalculator.__init__(
73 self,
74 restart,
75 ignore_bad_restart_file,
76 label,
77 atoms,
78 command=command,
79 **kwargs,
80 )
82 def set(self, **kwargs):
83 """Update parameters self.parameter member variable.
84 1. Add default values for repeated parameter sections with
85 self.default_parameters using order.
86 2. Also add empty dictionary as an indicator for section existence
87 if no relevant default_parameters exist.
88 3. Update parameters from arguments.
90 Returns
91 -------
92 Updated parameter
93 """
94 new_parameters = deepcopy(self.parameters)
96 changed_parameters = FileIOCalculator.set(self, **kwargs)
98 # Add default values for repeated parameter sections with
99 # self.default_parameters using order. Also add empty
100 # dictionary as an indicator for section existence if no
101 # relevant default_parameters exist.
102 if 'order' in kwargs:
103 new_parameters['order'] = kwargs['order']
104 section_sets = set(kwargs['order'])
105 for section_name in section_sets:
106 repeat = kwargs['order'].count(section_name)
107 if section_name in self.default_parameters.keys():
108 for _ in range(repeat - 1):
109 new_parameters[section_name] += deepcopy(
110 self.default_parameters[section_name]
111 )
112 else:
113 new_parameters[section_name] = []
114 for _ in range(repeat):
115 new_parameters[section_name].append({})
117 # Update parameters
118 for section in new_parameters['order']:
119 if section in kwargs:
120 if isinstance(kwargs[section], dict):
121 kwargs[section] = [kwargs[section]]
123 for i, section_param in enumerate(kwargs[section]):
124 new_parameters[section][i] = update_parameter(
125 new_parameters[section][i], section_param
126 )
127 self.parameters = new_parameters
128 return changed_parameters
130 def read(self, label):
131 FileIOCalculator.read(self, label)
132 filename = self.label + '.log'
134 with open(filename) as fd:
135 lines = fd.readlines()
136 if 'WARNING' in lines:
137 raise ReadError(f'Not convergy energy in log file {filename}.')
138 if '! total energy' not in lines:
139 raise ReadError(f'Wrong ACE-Molecule log file {filename}.')
141 if not os.path.isfile(filename):
142 raise ReadError(f'Wrong ACE-Molecule input file {filename}.')
144 self.read_results()
146 def write_input(self, atoms, properties=None, system_changes=None):
147 """Initializes input parameters and xyz files. If force calculation is
148 requested, add Force section to parameters if not exists.
150 Parameters
151 ----------
152 atoms: ASE atoms object.
153 properties: List of properties to be calculated. Should be element
154 of self.implemented_properties.
155 system_chages: Ignored.
157 """
158 FileIOCalculator.write_input(self, atoms, properties, system_changes)
159 with open(self.label + '.inp', 'w') as inputfile:
160 xyz_name = f'{self.label}.xyz'
161 atoms.write(xyz_name)
163 run_parameters = self.prepare_input(xyz_name, properties)
164 self.write_acemolecule_input(inputfile, run_parameters)
166 def prepare_input(self, geometry_filename, properties):
167 """Initialize parameters dictionary based on geometry filename and
168 calculated properties.
170 Parameters
171 ----------
172 geometry_filename: Geometry (XYZ format) file path.
173 properties: Properties to be calculated.
175 Returns
176 -------
177 Updated version of self.parameters; geometry file and
178 optionally Force section are updated.
180 """
181 copied_parameters = deepcopy(self.parameters)
182 if (
183 properties is not None
184 and 'forces' in properties
185 and 'Force' not in copied_parameters['order']
186 ):
187 copied_parameters['order'].append('Force')
188 copied_parameters['BasicInformation'][0]['GeometryFilename'] = (
189 f'{self.label}.xyz'
190 )
191 copied_parameters['BasicInformation'][0]['GeometryFormat'] = 'xyz'
192 return copied_parameters
194 def read_results(self):
195 """Read calculation results, speficied by 'quantities' variable, from
196 the log file.
198 quantities
199 =======
200 energy : obtaing single point energy(eV) from log file
201 forces : obtaing force of each atom form log file
202 excitation-energy : it able to calculate TDDFT.
203 Return value is None. Result is not used.
204 atoms : ASE atoms object
206 """
207 filename = self.label + '.log'
208 self.results = read(filename, format='acemolecule-out')
210 def write_acemolecule_section(self, fpt, section, depth=0):
211 """Write parameters in each section of input
213 Parameters
214 ----------
215 fpt: ACE-Moleucle input file object. Should be write mode.
216 section: Dictionary of a parameter section.
217 depth: Nested input depth.
218 """
219 for section, section_param in section.items():
220 if isinstance(section_param, (str, int, float)):
221 fpt.write(
222 ' ' * depth
223 + str(section)
224 + ' '
225 + str(section_param)
226 + '\n'
227 )
228 else:
229 if isinstance(section_param, dict):
230 fpt.write(' ' * depth + '%% ' + str(section) + '\n')
231 self.write_acemolecule_section(
232 fpt, section_param, depth + 1
233 )
234 fpt.write(' ' * depth + '%% End\n')
235 if isinstance(section_param, list):
236 for val in section_param:
237 fpt.write(
238 ' ' * depth
239 + str(section)
240 + ' '
241 + str(val)
242 + '\n'
243 )
245 def write_acemolecule_input(self, fpt, param, depth=0):
246 """Write ACE-Molecule input
248 ACE-Molecule input examples (not minimal)
249 %% BasicInformation
250 Type Scaling
251 Scaling 0.4
252 Basis Sinc
253 Cell 10.0
254 Grid Sphere
255 GeometryFormat xyz
256 SpinMultiplicity 3.0
257 Polarize 1
258 Centered 0
259 %% Pseudopotential
260 Pseudopotential 1
261 UsingDoubleGrid 0
262 FilterType Sinc
263 Format upf
264 PSFilePath /PATH/TO/UPF
265 PSFileSuffix .pbe-theos.UPF
266 %% End
267 GeometryFilename xyz/C.xyz
268 %% End
269 %% Guess
270 InitialGuess 3
271 InitialFilenames 001.cube
272 InitialFilenames 002.cube
273 %% End
274 %% Scf
275 IterateMaxCycle 150
276 ConvergenceType Energy
277 ConvergenceTolerance 0.00001
278 EnergyDecomposition 1
279 ComputeInitialEnergy 1
280 %% Diagonalize
281 Tolerance 0.000001
282 %% End
283 %% ExchangeCorrelation
284 XFunctional GGA_X_PBE
285 CFunctional GGA_C_PBE
286 %% End
287 %% Mixing
288 MixingMethod 1
289 MixingType Density
290 MixingParameter 0.5
291 PulayMixingParameter 0.1
292 %% End
293 %% End
295 Parameters
296 ----------
297 fpt: File object, should be write mode.
298 param: Dictionary of parameters. Also should contain
299 special 'order' section_name for parameter section ordering.
300 depth: Nested input depth.
302 Notes
303 -----
304 - Order of parameter section
305 (denoted using %% -- %% BasicInformation, %% Guess, etc.)
306 is important, because it determines calculation order.
307 For example, if Guess section comes after Scf section,
308 calculation will not run because Scf will tries to run
309 without initial Hamiltonian.
310 - Order of each parameter section-section_name pair is
311 not important unless their keys are the same.
312 - Indentation unimportant and capital letters are important.
313 """
314 prefix = ' ' * depth
316 for i in range(len(param['order'])):
317 fpt.write(prefix + '%% ' + param['order'][i] + '\n')
318 section_list = param[param['order'][i]]
319 if len(section_list) > 0:
320 section = section_list.pop(0)
321 self.write_acemolecule_section(fpt, section, 1)
322 fpt.write('%% End\n')
325def update_parameter(oldpar, newpar):
326 """Update each section of parameter (oldpar) using newpar keys and values.
327 If section of newpar exist in oldpar,
328 - Replace the section_name with newpar's section_name if
329 oldvar section_name type is not dict.
330 - Append the section_name with newpar's section_name
331 if oldvar section_name type is list.
332 - If oldpar section_name type is dict, it is subsection.
333 So call update_parameter again.
334 otherwise, add the parameter section and section_name from newpar.
336 Parameters
337 ----------
338 oldpar: dictionary of original parameters to be updated.
339 newpar: dictionary containing parameter section and values to update.
341 Return
342 ======
343 Updated parameter dictionary.
344 """
345 for section, section_param in newpar.items():
346 if section in oldpar:
347 if isinstance(section_param, dict):
348 oldpar[section] = update_parameter(
349 oldpar[section], section_param
350 )
351 else:
352 oldpar[section] = section_param
353 else:
354 oldpar[section] = section_param
355 return oldpar