Coverage for ase/calculators/nwchem.py: 71.74%
46 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 NWchem
3https://nwchemgit.github.io
4"""
6import os
7from pathlib import Path
9import numpy as np
11from ase import io
12from ase.calculators.calculator import FileIOCalculator
13from ase.spectrum.band_structure import BandStructure
14from ase.units import Hartree
17class NWChem(FileIOCalculator):
18 implemented_properties = [
19 'energy',
20 'free_energy',
21 'forces',
22 'stress',
23 'dipole',
24 ]
25 _legacy_default_command = 'nwchem PREFIX.nwi > PREFIX.nwo'
26 accepts_bandpath_keyword = True
27 discard_results_on_any_change = True
29 fileio_rules = FileIOCalculator.ruleset(
30 extend_argv=['{prefix}.nwi'], stdout_name='{prefix}.nwo'
31 )
33 def __init__(
34 self,
35 restart=None,
36 ignore_bad_restart_file=FileIOCalculator._deprecated,
37 label='nwchem',
38 atoms=None,
39 command=None,
40 **kwargs,
41 ):
42 """
43 NWChem keywords are specified using (potentially nested)
44 dictionaries. Consider the following input file block::
46 dft
47 odft
48 mult 2
49 convergence energy 1e-9 density 1e-7 gradient 5e-6
50 end
52 This can be generated by the NWChem calculator by using the
53 following settings:
54 >>> from ase.calculators.nwchem import NWChem
55 >>> calc = NWChem(dft={'odft': None,
56 ... 'mult': 2,
57 ... 'convergence': {'energy': 1e-9,
58 ... 'density': 1e-7,
59 ... 'gradient': 5e-6,
60 ... },
61 ... },
62 ... )
64 In addition, the calculator supports several special keywords:
66 theory: str
67 Which NWChem module should be used to calculate the
68 energies and forces. Supported values are ``'dft'``,
69 ``'scf'``, ``'mp2'``, ``'ccsd'``, ``'tce'``, ``'tddft'``,
70 ``'pspw'``, ``'band'``, and ``'paw'``. If not provided, the
71 calculator will attempt to guess which theory to use based
72 on the keywords provided by the user.
73 xc: str
74 The exchange-correlation functional to use. Only relevant
75 for DFT calculations.
76 task: str
77 What type of calculation is to be performed, e.g.
78 ``'energy'``, ``'gradient'``, ``'optimize'``, etc. When
79 using ``'SocketIOCalculator'``, ``task`` should be set
80 to ``'optimize'``. In most other circumstances, ``task``
81 should not be set manually.
82 basis: str or dict
83 Which basis set to use for gaussian-type orbital
84 calculations. Set to a string to use the same basis for all
85 elements. To use a different basis for different elements,
86 provide a dict of the form:
88 >>> calc = NWChem(...,
89 ... basis={'O': '3-21G',
90 ... 'Si': '6-31g'})
92 basispar: str
93 Additional keywords to put in the NWChem ``basis`` block,
94 e.g. ``'rel'`` for relativistic bases.
95 symmetry: int or str
96 The point group (for gaussian-type orbital calculations) or
97 space group (for plane-wave calculations) of the system.
98 Supports both group names (e.g. ``'c2v'``, ``'Fm3m'``) and
99 numbers (e.g. ``225``).
100 autosym: bool
101 Whether NWChem should automatically determine the symmetry
102 of the structure (defaults to ``False``).
103 center: bool
104 Whether NWChem should automatically center the structure
105 (defaults to ``False``). Enable at your own risk.
106 autoz: bool
107 Whether NWChem should automatically construct a Z-matrix
108 for your molecular system (defaults to ``False``).
109 geompar: str
110 Additional keywords to put in the NWChem `geometry` block,
111 e.g. ``'nucleus finite'`` for gaussian-shaped nuclear
112 charges. Do not set ``'autosym'``, ``'center'``, or
113 ``'autoz'`` in this way; instead, use the appropriate
114 keyword described above for these settings.
115 set: dict
116 Used to manually create or modify entries in the NWChem
117 rtdb. For example, the following settings enable
118 pseudopotential filtering for plane-wave calculations::
120 set nwpw:kbpp_ray .true.
121 set nwpw:kbpp_filter .true.
123 These settings are generated by the NWChem calculator by
124 passing the arguments:
126 >>> calc = NWChem(...,
127 >>> set={'nwpw:kbpp_ray': True,
128 >>> 'nwpw:kbpp_filter': True})
130 kpts: (int, int, int), or dict
131 Indicates which k-point mesh to use. Supported syntax is
132 similar to that of GPAW. Implies ``theory='band'``.
133 bandpath: BandPath object
134 The band path to use for a band structure calculation.
135 Implies ``theory='band'``.
136 pretasks: list of dict
137 Tasks used to produce a better initial guess
138 for the wavefunction.
139 These task typically use a cheaper level of theory
140 or smaller basis set (but not both).
141 The output energy and forces should remain unchanged
142 regardless of the number of tasks or their parameters,
143 but the runtime may be significantly improved.
145 For example, a MP2 calculation preceded by guesses at the
146 DFT and HF levels would be
148 >>> calc = NWChem(theory='mp2', basis='aug-cc-pvdz',
149 >>> pretasks=[
150 >>> {'dft': {'xc': 'hfexch'},
151 >>> 'set': {'lindep:n_dep': 0}},
152 >>> {'theory': 'scf', 'set': {'lindep:n_dep': 0}},
153 >>> ])
155 Each dictionary could contain any of the other parameters,
156 except those which pertain to global configurations
157 (e.g., geometry details, scratch dir).
159 The default basis set is that of the final step in the calculation,
160 or that of the previous step that which defines a basis set.
161 For example, all steps in the example will use aug-cc-pvdz
162 because the last step is the only one which defines a basis.
164 Steps which change basis set must use the same theory.
165 The following specification would perform SCF using the 3-21G
166 basis set first, then B3LYP//3-21g, and then B3LYP//6-31G(2df,p)
168 >>> calc = NWChem(theory='dft', xc='b3lyp', basis='6-31g(2df,p)',
169 >>> pretasks=[
170 >>> {'theory': 'scf', 'basis': '3-21g',
171 >>> 'set': {'lindep:n_dep': 0}},
172 >>> {'dft': {'xc': 'b3lyp'}},
173 >>> ])
175 The :code:`'set': {'lindep:n_dep': 0}` option is highly suggested
176 as a way to avoid errors relating to symmetry changes between tasks.
178 The calculator will configure appropriate options for saving
179 and loading intermediate wavefunctions, and
180 place an "ignore" task directive between each step so that
181 convergence errors in intermediate steps do not halt execution.
182 """
183 FileIOCalculator.__init__(
184 self,
185 restart,
186 ignore_bad_restart_file,
187 label,
188 atoms,
189 command,
190 **kwargs,
191 )
192 if self.prefix is None:
193 self.prefix = 'nwchem'
194 self.calc = None
196 def input_filename(self):
197 return f'{self.prefix}.nwi'
199 def output_filename(self):
200 return f'{self.prefix}.nwo'
202 def write_input(self, atoms, properties=None, system_changes=None):
203 FileIOCalculator.write_input(self, atoms, properties, system_changes)
205 # Prepare perm and scratch directories
206 perm = os.path.abspath(self.parameters.get('perm', self.label))
207 scratch = os.path.abspath(self.parameters.get('scratch', self.label))
208 os.makedirs(perm, exist_ok=True)
209 os.makedirs(scratch, exist_ok=True)
211 io.write(
212 Path(self.directory) / self.input_filename(),
213 atoms,
214 properties=properties,
215 label=self.label,
216 **self.parameters,
217 )
219 def read_results(self):
220 output = io.read(Path(self.directory) / self.output_filename())
221 self.calc = output.calc
222 self.results = output.calc.results
224 def band_structure(self):
225 self.calculate()
226 perm = self.parameters.get('perm', self.label)
227 if self.calc.get_spin_polarized():
228 alpha = np.loadtxt(os.path.join(perm, self.label + '.alpha_band'))
229 beta = np.loadtxt(os.path.join(perm, self.label + '.beta_band'))
230 energies = np.array([alpha[:, 1:], beta[:, 1:]]) * Hartree
231 else:
232 data = np.loadtxt(
233 os.path.join(perm, self.label + '.restricted_band')
234 )
235 energies = data[np.newaxis, :, 1:] * Hartree
236 eref = self.calc.get_fermi_level()
237 if eref is None:
238 eref = 0.0
239 return BandStructure(self.parameters.bandpath, energies, eref)