Coverage for ase/calculators/crystal.py: 13.60%
272 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 CRYSTAL14/CRYSTAL17
3https://www.crystal.unito.it/
5Written by:
7 Daniele Selli, daniele.selli@unimib.it
8 Gianluca Fazio, g.fazio3@campus.unimib.it
10The file 'fort.34' contains the input and output geometry
11and it will be updated during the crystal calculations.
12The wavefunction is stored in 'fort.20' as binary file.
14The keywords are given, for instance, as follows:
16 guess = True,
17 xc = 'PBE',
18 kpts = (2,2,2),
19 otherkeys = [ 'scfdir', 'anderson', ['maxcycles','500'],
20 ['fmixing','90']],
21 ...
24 When used for QM/MM, Crystal calculates coulomb terms
25 within all point charges. This is wrong and should be corrected by either:
27 1. Re-calculating the terms and subtracting them
28 2. Reading in the values from FORCES_CHG.DAT and subtracting
31 BOTH Options should be available, with 1 as standard, since 2 is
32 only available in a development version of CRYSTAL
34"""
36import os
38import numpy as np
40from ase.calculators.calculator import FileIOCalculator
41from ase.io import write
42from ase.units import Bohr, Hartree
45class CRYSTAL(FileIOCalculator):
46 """A crystal calculator with ase-FileIOCalculator nomenclature"""
48 implemented_properties = ['energy', 'forces', 'stress', 'charges', 'dipole']
50 def __init__(
51 self,
52 restart=None,
53 ignore_bad_restart_file=FileIOCalculator._deprecated,
54 label='cry',
55 atoms=None,
56 crys_pcc=False,
57 **kwargs,
58 ):
59 """Construct a crystal calculator."""
60 # default parameters
61 self.default_parameters = dict(
62 xc='HF',
63 spinpol=False,
64 oldgrid=False,
65 neigh=False,
66 coarsegrid=False,
67 guess=True,
68 kpts=None,
69 isp=1,
70 basis='custom',
71 smearing=None,
72 otherkeys=[],
73 )
75 self.pcpot = None
76 self.lines = None
77 self.atoms = None
78 self.crys_pcc = crys_pcc # True: Reads Coulomb Correction from file.
79 self.atoms_input = None
80 self.outfilename = 'cry.out'
82 FileIOCalculator.__init__(
83 self, restart, ignore_bad_restart_file, label, atoms, **kwargs
84 )
86 def write_crystal_in(self, filename):
87 """Write the input file for the crystal calculation.
88 Geometry is taken always from the file 'fort.34'
89 """
91 # write BLOCK 1 (only SP with gradients)
92 with open(filename, 'w', encoding='latin-1') as outfile:
93 self._write_crystal_in(outfile)
95 def _write_crystal_in(self, outfile):
96 outfile.write('Single point + Gradient crystal calculation \n')
97 outfile.write('EXTERNAL \n')
98 outfile.write('NEIGHPRT \n')
99 outfile.write('0 \n')
101 if self.pcpot:
102 outfile.write('POINTCHG \n')
103 self.pcpot.write_mmcharges('POINTCHG.INP')
105 # write BLOCK 2 from file (basis sets)
106 p = self.parameters
107 if p.basis == 'custom':
108 outfile.write('END \n')
109 with open(os.path.join(self.directory, 'basis')) as basisfile:
110 basis_ = basisfile.readlines()
111 for line in basis_:
112 outfile.write(line)
113 outfile.write('99 0 \n')
114 outfile.write('END \n')
115 else:
116 outfile.write('BASISSET \n')
117 outfile.write(p.basis.upper() + '\n')
119 # write BLOCK 3 according to parameters set as input
120 # ----- write hamiltonian
122 if self.atoms.get_initial_magnetic_moments().any():
123 p.spinpol = True
125 if p.xc == 'HF':
126 if p.spinpol:
127 outfile.write('UHF \n')
128 else:
129 outfile.write('RHF \n')
130 elif p.xc == 'MP2':
131 outfile.write('MP2 \n')
132 outfile.write('ENDMP2 \n')
133 else:
134 outfile.write('DFT \n')
135 # Standalone keywords and LDA are given by a single string.
136 if isinstance(p.xc, str):
137 xc = {
138 'LDA': 'EXCHANGE\nLDA\nCORRELAT\nVWN',
139 'PBE': 'PBEXC',
140 }.get(p.xc, p.xc)
141 outfile.write(xc.upper() + '\n')
142 # Custom xc functional are given by a tuple of string
143 else:
144 x, c = p.xc
145 outfile.write('EXCHANGE \n')
146 outfile.write(x + ' \n')
147 outfile.write('CORRELAT \n')
148 outfile.write(c + ' \n')
149 if p.spinpol:
150 outfile.write('SPIN \n')
151 if p.oldgrid:
152 outfile.write('OLDGRID \n')
153 if p.coarsegrid:
154 outfile.write('RADIAL\n')
155 outfile.write('1\n')
156 outfile.write('4.0\n')
157 outfile.write('20\n')
158 outfile.write('ANGULAR\n')
159 outfile.write('5\n')
160 outfile.write('0.1667 0.5 0.9 3.05 9999.0\n')
161 outfile.write('2 6 8 13 8\n')
162 outfile.write('END \n')
163 # When guess=True, wf is read.
164 if p.guess:
165 # wf will be always there after 2nd step.
166 if os.path.isfile('fort.20'):
167 outfile.write('GUESSP \n')
168 elif os.path.isfile('fort.9'):
169 outfile.write('GUESSP \n')
170 os.system('cp fort.9 fort.20')
172 # smearing
173 if p.smearing is not None:
174 if p.smearing[0] != 'Fermi-Dirac':
175 raise ValueError('Only Fermi-Dirac smearing is allowed.')
176 else:
177 outfile.write('SMEAR \n')
178 outfile.write(str(p.smearing[1] / Hartree) + ' \n')
180 # ----- write other CRYSTAL keywords
181 # ----- in the list otherkey = ['ANDERSON', ...] .
183 for keyword in p.otherkeys:
184 if isinstance(keyword, str):
185 outfile.write(keyword.upper() + '\n')
186 else:
187 for key in keyword:
188 outfile.write(key.upper() + '\n')
190 ispbc = self.atoms.get_pbc()
191 self.kpts = p.kpts
193 # if it is periodic, gamma is the default.
194 if any(ispbc):
195 if self.kpts is None:
196 self.kpts = (1, 1, 1)
197 else:
198 self.kpts = None
200 # explicit lists of K-points, shifted Monkhorst-
201 # Pack net and k-point density definition are
202 # not allowed.
203 if self.kpts is not None:
204 if isinstance(self.kpts, float):
205 raise ValueError('K-point density definition not allowed.')
206 if isinstance(self.kpts, list):
207 raise ValueError('Explicit K-points definition not allowed.')
208 if isinstance(self.kpts[-1], str):
209 raise ValueError('Shifted Monkhorst-Pack not allowed.')
210 outfile.write('SHRINK \n')
211 # isp is by default 1, 2 is suggested for metals.
212 outfile.write('0 ' + str(p.isp * max(self.kpts)) + ' \n')
213 if ispbc[2]:
214 outfile.write(
215 str(self.kpts[0])
216 + ' '
217 + str(self.kpts[1])
218 + ' '
219 + str(self.kpts[2])
220 + ' \n'
221 )
222 elif ispbc[1]:
223 outfile.write(
224 str(self.kpts[0]) + ' ' + str(self.kpts[1]) + ' 1 \n'
225 )
226 elif ispbc[0]:
227 outfile.write(str(self.kpts[0]) + ' 1 1 \n')
229 # GRADCAL command performs a single
230 # point and prints out the forces
231 # also on the charges
232 outfile.write('GRADCAL \n')
233 outfile.write('END \n')
235 def write_input(self, atoms, properties=None, system_changes=None):
236 FileIOCalculator.write_input(self, atoms, properties, system_changes)
237 self.write_crystal_in(os.path.join(self.directory, 'INPUT'))
238 write(os.path.join(self.directory, 'fort.34'), atoms)
239 # self.atoms is none until results are read out,
240 # then it is set to the ones at writing input
241 self.atoms_input = atoms
242 self.atoms = None
244 def read_results(self):
245 """all results are read from OUTPUT file
246 It will be destroyed after it is read to avoid
247 reading it once again after some runtime error"""
249 with open(
250 os.path.join(self.directory, 'OUTPUT'), encoding='latin-1'
251 ) as myfile:
252 self.lines = myfile.readlines()
254 self.atoms = self.atoms_input
255 # Energy line index
256 estring1 = 'SCF ENDED'
257 estring2 = 'TOTAL ENERGY + DISP'
258 for iline, line in enumerate(self.lines):
259 if line.find(estring1) >= 0:
260 index_energy = iline
261 pos_en = 8
262 break
263 else:
264 raise RuntimeError('Problem in reading energy')
265 # Check if there is dispersion corrected
266 # energy value.
267 for iline, line in enumerate(self.lines):
268 if line.find(estring2) >= 0:
269 index_energy = iline
270 pos_en = 5
272 # If there's a point charge potential (QM/MM), read corrections
273 e_coul = 0
274 if self.pcpot:
275 if self.crys_pcc:
276 self.pcpot.read_pc_corrections()
277 # also pass on to pcpot that it should read in from file
278 self.pcpot.crys_pcc = True
279 else:
280 self.pcpot.manual_pc_correct()
281 e_coul, _f_coul = self.pcpot.coulomb_corrections
283 energy = float(self.lines[index_energy].split()[pos_en]) * Hartree
284 energy -= e_coul # e_coul already in eV.
286 self.results['energy'] = energy
287 # Force line indexes
288 fstring = 'CARTESIAN FORCES'
289 gradients = []
290 for iline, line in enumerate(self.lines):
291 if line.find(fstring) >= 0:
292 index_force_begin = iline + 2
293 break
294 else:
295 raise RuntimeError('Problem in reading forces')
296 for j in range(index_force_begin, index_force_begin + len(self.atoms)):
297 word = self.lines[j].split()
298 # If GHOST atoms give problems, have a close look at this
299 if len(word) == 5:
300 gradients.append([float(word[k + 2]) for k in range(3)])
301 elif len(word) == 4:
302 gradients.append([float(word[k + 1]) for k in range(3)])
303 else:
304 raise RuntimeError('Problem in reading forces')
306 forces = np.array(gradients) * Hartree / Bohr
308 self.results['forces'] = forces
310 # stress stuff begins
311 sstring = 'STRESS TENSOR, IN'
312 have_stress = False
313 stress = []
314 for iline, line in enumerate(self.lines):
315 if sstring in line:
316 have_stress = True
317 start = iline + 4
318 end = start + 3
319 for i in range(start, end):
320 cell = [float(x) for x in self.lines[i].split()]
321 stress.append(cell)
322 if have_stress:
323 stress = -np.array(stress) * Hartree / Bohr**3
324 self.results['stress'] = stress
326 # stress stuff ends
328 # Get partial charges on atoms.
329 # In case we cannot find charges
330 # they are set to None
331 qm_charges = []
333 # ----- this for cycle finds the last entry of the
334 # ----- string search, which corresponds
335 # ----- to the charges at the end of the SCF.
336 for n, line in enumerate(self.lines):
337 if 'TOTAL ATOMIC CHARGE' in line:
338 chargestart = n + 1
339 lines1 = self.lines[
340 chargestart : (chargestart + (len(self.atoms) - 1) // 6 + 1)
341 ]
342 atomnum = self.atoms.get_atomic_numbers()
343 words = []
344 for line in lines1:
345 for el in line.split():
346 words.append(float(el))
347 i = 0
348 for atn in atomnum:
349 qm_charges.append(-words[i] + atn)
350 i = i + 1
351 charges = np.array(qm_charges)
352 self.results['charges'] = charges
354 # Read dipole moment.
355 dipole = np.zeros([1, 3])
356 for n, line in enumerate(self.lines):
357 if 'DIPOLE MOMENT ALONG' in line:
358 dipolestart = n + 2
359 dipole = np.array(
360 [float(f) for f in self.lines[dipolestart].split()[2:5]]
361 )
362 break
363 # debye to e*Ang
364 self.results['dipole'] = dipole * 0.2081943482534
366 def embed(self, mmcharges=None, directory='./'):
367 """Embed atoms in point-charges (mmcharges)"""
368 self.pcpot = PointChargePotential(mmcharges, self.directory)
369 return self.pcpot
372class PointChargePotential:
373 def __init__(self, mmcharges, directory='./'):
374 """Point-charge potential for CRYSTAL."""
375 self.mmcharges = mmcharges
376 self.directory = directory
377 self.mmpositions = None
378 self.mmforces = None
379 self.coulomb_corrections = None
380 self.crys_pcc = False
382 def set_positions(self, mmpositions):
383 self.mmpositions = mmpositions
385 def set_charges(self, mmcharges):
386 self.mmcharges = mmcharges
388 def write_mmcharges(self, filename):
389 """mok all
390 write external charges as monopoles for CRYSTAL.
392 """
393 if self.mmcharges is None:
394 print('CRYSTAL: Warning: not writing external charges ')
395 return
396 with open(os.path.join(self.directory, filename), 'w') as charge_file:
397 charge_file.write(str(len(self.mmcharges)) + ' \n')
398 for [pos, charge] in zip(self.mmpositions, self.mmcharges):
399 [x, y, z] = pos
400 charge_file.write(
401 '%12.6f %12.6f %12.6f %12.6f \n' % (x, y, z, charge)
402 )
404 def get_forces(self, calc, get_forces=True):
405 """returns forces on point charges if the flag get_forces=True"""
406 if get_forces:
407 return self.read_forces_on_pointcharges()
408 else:
409 return np.zeros_like(self.mmpositions)
411 def read_forces_on_pointcharges(self):
412 """Read Forces from CRYSTAL output file (OUTPUT)."""
413 with open(os.path.join(self.directory, 'OUTPUT')) as infile:
414 lines = infile.readlines()
416 print('PCPOT crys_pcc: ' + str(self.crys_pcc))
417 # read in force and energy Coulomb corrections
418 if self.crys_pcc:
419 self.read_pc_corrections()
420 else:
421 self.manual_pc_correct()
422 _e_coul, f_coul = self.coulomb_corrections
424 external_forces = []
425 for n, line in enumerate(lines):
426 if 'RESULTANT FORCE' in line:
427 chargeend = n - 1
428 break
429 else:
430 raise RuntimeError(
431 'Problem in reading forces on MM external-charges'
432 )
433 lines1 = lines[(chargeend - len(self.mmcharges)) : chargeend]
434 for line in lines1:
435 external_forces.append([float(i) for i in line.split()[2:]])
437 f = np.array(external_forces) - f_coul
438 f *= Hartree / Bohr
440 return f
442 def read_pc_corrections(self):
443 """Crystal calculates Coulomb forces and energies between all
444 point charges, and adds that to the QM subsystem. That needs
445 to be subtracted again.
446 This will be standard in future CRYSTAL versions ."""
448 with open(os.path.join(self.directory, 'FORCES_CHG.DAT')) as infile:
449 lines = infile.readlines()
451 e = [
452 float(x.split()[-1])
453 for x in lines
454 if 'SELF-INTERACTION ENERGY(AU)' in x
455 ][0]
457 e *= Hartree
459 f_lines = [s for s in lines if '199' in s]
460 assert len(f_lines) == len(self.mmcharges), (
461 'Mismatch in number of point charges from FORCES_CHG.dat'
462 )
464 pc_forces = np.zeros((len(self.mmcharges), 3))
465 for i, l in enumerate(f_lines):
466 first = l.split(str(i + 1) + ' 199 ')
467 assert len(first) == 2, 'Problem reading FORCES_CHG.dat'
468 f = first[-1].split()
469 pc_forces[i] = [float(x) for x in f]
471 self.coulomb_corrections = (e, pc_forces)
473 def manual_pc_correct(self):
474 """For current versions of CRYSTAL14/17, manual Coulomb correction"""
476 R = self.mmpositions / Bohr
477 charges = self.mmcharges
479 forces = np.zeros_like(R)
480 energy = 0.0
482 for m in range(len(charges)):
483 D = R[m + 1 :] - R[m]
484 d2 = (D**2).sum(1)
485 d = d2**0.5
487 e_c = charges[m + 1 :] * charges[m] / d
489 energy += np.sum(e_c)
491 F = (e_c / d2)[:, None] * D
493 forces[m] -= F.sum(0)
494 forces[m + 1 :] += F
496 energy *= Hartree
498 self.coulomb_corrections = (energy, forces)