Coverage for ase/calculators/gulp.py: 25.23%
218 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 GULP.
3Written by:
5Andy Cuko <andi.cuko@upmc.fr>
6Antoni Macia <tonimacia@gmail.com>
8EXPORT ASE_GULP_COMMAND="/path/to/gulp < PREFIX.gin > PREFIX.got"
10Keywords
11Options
13"""
15import os
16import re
18import numpy as np
20from ase.calculators.calculator import FileIOCalculator, ReadError
21from ase.units import Ang, eV
24class GULPOptimizer:
25 def __init__(self, atoms, calc):
26 self.atoms = atoms
27 self.calc = calc
29 def todict(self):
30 return {'type': 'optimization', 'optimizer': 'GULPOptimizer'}
32 def run(self, fmax=None, steps=None, **gulp_kwargs):
33 if fmax is not None:
34 gulp_kwargs['gmax'] = fmax
35 if steps is not None:
36 gulp_kwargs['maxcyc'] = steps
38 self.calc.set(**gulp_kwargs)
39 self.atoms.calc = self.calc
40 self.atoms.get_potential_energy()
41 self.atoms.cell = self.calc.get_atoms().cell
42 self.atoms.positions[:] = self.calc.get_atoms().positions
45class GULP(FileIOCalculator):
46 implemented_properties = ['energy', 'free_energy', 'forces', 'stress']
47 _legacy_default_command = 'gulp < PREFIX.gin > PREFIX.got'
48 discard_results_on_any_change = True
49 default_parameters = dict(
50 keywords='conp gradients',
51 options=[],
52 shel=[],
53 library='ffsioh.lib',
54 conditions=None,
55 )
57 def get_optimizer(self, atoms):
58 gulp_keywords = self.parameters.keywords.split()
59 if 'opti' not in gulp_keywords:
60 raise ValueError(
61 'Can only create optimizer from GULP calculator '
62 'with "opti" keyword. Current keywords: {}'.format(
63 gulp_keywords
64 )
65 )
67 opt = GULPOptimizer(atoms, self)
68 return opt
70 def __init__(
71 self,
72 restart=None,
73 ignore_bad_restart_file=FileIOCalculator._deprecated,
74 label='gulp',
75 atoms=None,
76 optimized=None,
77 Gnorm=1000.0,
78 steps=1000,
79 conditions=None,
80 **kwargs,
81 ):
82 """Construct GULP-calculator object."""
83 FileIOCalculator.__init__(
84 self, restart, ignore_bad_restart_file, label, atoms, **kwargs
85 )
86 self.optimized = optimized
87 self.Gnorm = Gnorm
88 self.steps = steps
89 self.conditions = conditions
90 self.library_check()
91 self.atom_types = []
93 # GULP prints the fractional coordinates before the Final
94 # lattice vectors so they need to be stored and then atoms
95 # positions need to be set after we get the Final lattice
96 # vectors
97 self.fractional_coordinates = None
99 def write_input(self, atoms, properties=None, system_changes=None):
100 FileIOCalculator.write_input(self, atoms, properties, system_changes)
101 p = self.parameters
103 # Build string to hold .gin input file:
104 s = p.keywords
105 s += '\ntitle\nASE calculation\nend\n\n'
107 if all(self.atoms.pbc):
108 cell_params = self.atoms.cell.cellpar()
109 # Formating is necessary since Gulp max-line-length restriction
110 s += (
111 'cell\n{:9.6f} {:9.6f} {:9.6f} '
112 '{:8.5f} {:8.5f} {:8.5f}\n'.format(*cell_params)
113 )
114 s += 'frac\n'
115 coords = self.atoms.get_scaled_positions()
116 else:
117 s += 'cart\n'
118 coords = self.atoms.get_positions()
120 if self.conditions is not None:
121 c = self.conditions
122 labels = c.get_atoms_labels()
123 self.atom_types = c.get_atom_types()
124 else:
125 labels = self.atoms.get_chemical_symbols()
127 for xyz, symbol in zip(coords, labels):
128 s += ' {:2} core {:10.7f} {:10.7f} {:10.7f}\n'.format(
129 symbol, *xyz
130 )
131 if symbol in p.shel:
132 s += ' {:2} shel {:10.7f} {:10.7f} {:10.7f}\n'.format(
133 symbol, *xyz
134 )
136 if p.library:
137 s += f'\nlibrary {p.library}\n'
139 if p.options:
140 for t in p.options:
141 s += f'{t}\n'
143 gin_path = os.path.join(self.directory, self.prefix + '.gin')
144 with open(gin_path, 'w') as fd:
145 fd.write(s)
147 def read_results(self):
148 FileIOCalculator.read(self, self.label)
149 got_path = os.path.join(self.directory, self.label + '.got')
150 if not os.path.isfile(got_path):
151 raise ReadError
153 with open(got_path) as fd:
154 lines = fd.readlines()
156 cycles = -1
157 self.optimized = None
158 for i, line in enumerate(lines):
159 m = re.match(r'\s*Total lattice energy\s*=\s*(\S+)\s*eV', line)
160 if m:
161 energy = float(m.group(1))
162 self.results['energy'] = energy
163 self.results['free_energy'] = energy
165 elif line.find('Optimisation achieved') != -1:
166 self.optimized = True
168 elif line.find('Final Gnorm') != -1:
169 self.Gnorm = float(line.split()[-1])
171 elif line.find('Cycle:') != -1:
172 cycles += 1
174 elif line.find('Final Cartesian derivatives') != -1:
175 s = i + 5
176 forces = []
177 while True:
178 s = s + 1
179 if lines[s].find('------------') != -1:
180 break
181 if lines[s].find(' s ') != -1:
182 continue
183 g = lines[s].split()[3:6]
184 G = [-float(x) * eV / Ang for x in g]
185 forces.append(G)
186 forces = np.array(forces)
187 self.results['forces'] = forces
189 elif line.find('Final internal derivatives') != -1:
190 s = i + 5
191 forces = []
192 while True:
193 s = s + 1
194 if lines[s].find('------------') != -1:
195 break
196 g = lines[s].split()[3:6]
198 # Uncomment the section below to separate the numbers when
199 # there is no space between them, in the case of long
200 # numbers. This prevents the code to break if numbers are
201 # too big.
203 """for t in range(3-len(g)):
204 g.append(' ')
205 for j in range(2):
206 min_index=[i+1 for i,e in enumerate(g[j][1:])
207 if e == '-']
208 if j==0 and len(min_index) != 0:
209 if len(min_index)==1:
210 g[2]=g[1]
211 g[1]=g[0][min_index[0]:]
212 g[0]=g[0][:min_index[0]]
213 else:
214 g[2]=g[0][min_index[1]:]
215 g[1]=g[0][min_index[0]:min_index[1]]
216 g[0]=g[0][:min_index[0]]
217 break
218 if j==1 and len(min_index) != 0:
219 g[2]=g[1][min_index[0]:]
220 g[1]=g[1][:min_index[0]]"""
222 G = [-float(x) * eV / Ang for x in g]
223 forces.append(G)
224 forces = np.array(forces)
225 self.results['forces'] = forces
227 elif line.find('Final cartesian coordinates of atoms') != -1:
228 s = i + 5
229 positions = []
230 while True:
231 s = s + 1
232 if lines[s].find('------------') != -1:
233 break
234 if lines[s].find(' s ') != -1:
235 continue
236 xyz = lines[s].split()[3:6]
237 XYZ = [float(x) * Ang for x in xyz]
238 positions.append(XYZ)
239 positions = np.array(positions)
240 self.atoms.set_positions(positions)
242 elif line.find('Final stress tensor components') != -1:
243 res = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
244 for j in range(3):
245 var = lines[i + j + 3].split()[1]
246 res[j] = float(var)
247 var = lines[i + j + 3].split()[3]
248 res[j + 3] = float(var)
249 stress = np.array(res)
250 self.results['stress'] = stress
252 elif line.find('Final Cartesian lattice vectors') != -1:
253 lattice_vectors = np.zeros((3, 3))
254 s = i + 2
255 for j in range(s, s + 3):
256 temp = lines[j].split()
257 for k in range(3):
258 lattice_vectors[j - s][k] = float(temp[k])
259 self.atoms.set_cell(lattice_vectors)
260 if self.fractional_coordinates is not None:
261 self.fractional_coordinates = np.array(
262 self.fractional_coordinates
263 )
264 self.atoms.set_scaled_positions(self.fractional_coordinates)
266 elif line.find('Final fractional coordinates of atoms') != -1:
267 s = i + 5
268 scaled_positions = []
269 while True:
270 s = s + 1
271 if lines[s].find('------------') != -1:
272 break
273 if lines[s].find(' s ') != -1:
274 continue
275 xyz = lines[s].split()[3:6]
276 XYZ = [float(x) for x in xyz]
277 scaled_positions.append(XYZ)
278 self.fractional_coordinates = scaled_positions
280 self.steps = cycles
282 def get_opt_state(self):
283 return self.optimized
285 def get_opt_steps(self):
286 return self.steps
288 def get_Gnorm(self):
289 return self.Gnorm
291 def library_check(self):
292 if self.parameters['library'] is not None:
293 if 'GULP_LIB' not in self.cfg:
294 raise RuntimeError(
295 'Be sure to have set correctly $GULP_LIB '
296 'or to have the force field library.'
297 )
300class Conditions:
301 """Atomic labels for the GULP calculator.
303 This class manages an array similar to
304 atoms.get_chemical_symbols() via get_atoms_labels() method, but
305 with atomic labels in stead of atomic symbols. This is useful
306 when you need to use calculators like GULP or lammps that use
307 force fields. Some force fields can have different atom type for
308 the same element. In this class you can create a set_rule()
309 function that assigns labels according to structural criteria."""
311 def __init__(self, atoms):
312 self.atoms = atoms
313 self.atoms_symbols = atoms.get_chemical_symbols()
314 self.atoms_labels = atoms.get_chemical_symbols()
315 self.atom_types = []
317 def min_distance_rule(
318 self,
319 sym1,
320 sym2,
321 ifcloselabel1=None,
322 ifcloselabel2=None,
323 elselabel1=None,
324 max_distance=3.0,
325 ):
326 """Find pairs of atoms to label based on proximity.
328 This is for, e.g., the ffsioh or catlow force field, where we
329 would like to identify those O atoms that are close to H
330 atoms. For each H atoms, we must specially label one O atom.
332 This function is a rule that allows to define atom labels (like O1,
333 O2, O_H etc..) starting from element symbols of an Atoms
334 object that a force field can use and according to distance
335 parameters.
337 Example:
338 atoms = read('some_xyz_format.xyz')
339 a = Conditions(atoms)
340 a.set_min_distance_rule('O', 'H', ifcloselabel1='O2',
341 ifcloselabel2='H', elselabel1='O1')
342 new_atoms_labels = a.get_atom_labels()
344 In the example oxygens O are going to be labeled as O2 if they
345 are close to a hydrogen atom othewise are labeled O1.
347 """
349 if ifcloselabel1 is None:
350 ifcloselabel1 = sym1
351 if ifcloselabel2 is None:
352 ifcloselabel2 = sym2
353 if elselabel1 is None:
354 elselabel1 = sym1
356 # self.atom_types is a list of element types used instead of element
357 # symbols in orger to track the changes made. Take care of this because
358 # is very important.. gulp_read function that parse the output
359 # has to know which atom_type it has to associate with which
360 # atom_symbol
361 #
362 # Example: [['O','O1','O2'],['H', 'H_C', 'H_O']]
363 # this because Atoms oject accept only atoms symbols
364 self.atom_types.append([sym1, ifcloselabel1, elselabel1])
365 self.atom_types.append([sym2, ifcloselabel2])
367 dist_mat = self.atoms.get_all_distances()
368 index_assigned_sym1 = []
369 index_assigned_sym2 = []
371 for i in range(len(self.atoms_symbols)):
372 if self.atoms_symbols[i] == sym2:
373 dist_12 = 1000
374 index_assigned_sym2.append(i)
375 for t in range(len(self.atoms_symbols)):
376 if (
377 self.atoms_symbols[t] == sym1
378 and dist_mat[i, t] < dist_12
379 and t not in index_assigned_sym1
380 ):
381 dist_12 = dist_mat[i, t]
382 closest_sym1_index = t
383 index_assigned_sym1.append(closest_sym1_index)
385 for i1, i2 in zip(index_assigned_sym1, index_assigned_sym2):
386 if dist_mat[i1, i2] > max_distance:
387 raise ValueError(
388 'Cannot unambiguously apply minimum-distance '
389 'rule because pairings are not obvious. '
390 'If you wish to ignore this, then increase '
391 'max_distance.'
392 )
394 for s in range(len(self.atoms_symbols)):
395 if s in index_assigned_sym1:
396 self.atoms_labels[s] = ifcloselabel1
397 elif s not in index_assigned_sym1 and self.atoms_symbols[s] == sym1:
398 self.atoms_labels[s] = elselabel1
399 elif s in index_assigned_sym2:
400 self.atoms_labels[s] = ifcloselabel2
402 def get_atom_types(self):
403 return self.atom_types
405 def get_atoms_labels(self):
406 labels = np.array(self.atoms_labels)
407 return labels