Coverage for ase/calculators/amber.py: 33.79%
145 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 Amber16.
3Usage: (Tested only with Amber16, https://ambermd.org/)
5Before usage, input files (infile, topologyfile, incoordfile)
7"""
9import subprocess
11import numpy as np
12from scipy.io import netcdf_file
14import ase.units as units
15from ase.calculators.calculator import Calculator, FileIOCalculator
16from ase.io.amber import read_amber_coordinates, write_amber_coordinates
19class Amber(FileIOCalculator):
20 """Class for doing Amber classical MM calculations.
22 Example:
24 mm.in::
26 Minimization with Cartesian restraints
27 &cntrl
28 imin=1, maxcyc=200, (invoke minimization)
29 ntpr=5, (print frequency)
30 &end
31 """
33 implemented_properties = ['energy', 'forces']
34 discard_results_on_any_change = True
36 def __init__(
37 self,
38 restart=None,
39 ignore_bad_restart_file=FileIOCalculator._deprecated,
40 label='amber',
41 atoms=None,
42 command=None,
43 amber_exe='sander -O ',
44 infile='mm.in',
45 outfile='mm.out',
46 topologyfile='mm.top',
47 incoordfile='mm.crd',
48 outcoordfile='mm_dummy.crd',
49 mdcoordfile=None,
50 **kwargs,
51 ):
52 """Construct Amber-calculator object.
54 Parameters
55 ----------
56 label: str
57 Name used for all files. May contain a directory.
58 atoms: Atoms object
59 Optional Atoms object to which the calculator will be
60 attached. When restarting, atoms will get its positions and
61 unit-cell updated from file.
62 label: str
63 Prefix to use for filenames (label.in, label.txt, ...).
64 amber_exe: str
65 Name of the amber executable, one can add options like -O
66 and other parameters here
67 infile: str
68 Input filename for amber, contains instuctions about the run
69 outfile: str
70 Logfilename for amber
71 topologyfile: str
72 Name of the amber topology file
73 incoordfile: str
74 Name of the file containing the input coordinates of atoms
75 outcoordfile: str
76 Name of the file containing the output coordinates of atoms
77 this file is not used in case minisation/dynamics is done by ase.
78 It is only relevant
79 if you run MD/optimisation many steps with amber.
81 """
83 self.out = 'mm.log'
85 self.positions = None
86 self.atoms = None
88 self.set(**kwargs)
90 self.amber_exe = amber_exe
91 self.infile = infile
92 self.outfile = outfile
93 self.topologyfile = topologyfile
94 self.incoordfile = incoordfile
95 self.outcoordfile = outcoordfile
96 self.mdcoordfile = mdcoordfile
98 FileIOCalculator.__init__(
99 self,
100 restart,
101 ignore_bad_restart_file,
102 label,
103 atoms,
104 command=command,
105 **kwargs,
106 )
108 @property
109 def _legacy_default_command(self):
110 command = (
111 self.amber_exe
112 + ' -i '
113 + self.infile
114 + ' -o '
115 + self.outfile
116 + ' -p '
117 + self.topologyfile
118 + ' -c '
119 + self.incoordfile
120 + ' -r '
121 + self.outcoordfile
122 )
123 if self.mdcoordfile is not None:
124 command = command + ' -x ' + self.mdcoordfile
125 return command
127 def write_input(self, atoms=None, properties=None, system_changes=None):
128 """Write updated coordinates to a file."""
130 FileIOCalculator.write_input(self, atoms, properties, system_changes)
131 self.write_coordinates(atoms, self.incoordfile)
133 def read_results(self):
134 """read energy and forces"""
135 self.read_energy()
136 self.read_forces()
138 def write_coordinates(self, atoms, filename):
139 """write amber coordinates in netCDF format,
140 only rectangular unit cells are allowed"""
141 write_amber_coordinates(atoms, filename)
143 def read_coordinates(self, atoms):
144 """Import AMBER16 netCDF restart files.
146 Reads atom positions and
147 velocities (if available),
148 and unit cell (if available)
150 This may be useful if you have run amber many steps and
151 want to read new positions and velocities
152 """
153 # For historical reasons we edit the input atoms rather than
154 # returning new atoms.
155 _atoms = read_amber_coordinates(self.outcoordfile)
156 atoms.cell[:] = _atoms.cell
157 atoms.pbc[:] = _atoms.pbc
158 atoms.positions[:] = _atoms.positions
159 atoms.set_momenta(_atoms.get_momenta())
161 def read_energy(self, filename='mden'):
162 """read total energy from amber file"""
163 with open(filename) as fd:
164 lines = fd.readlines()
165 blocks = []
166 while 'L0' in lines[0].split()[0]:
167 blocks.append(lines[0:10])
168 lines = lines[10:]
169 if lines == []:
170 break
171 self.results['energy'] = (
172 float(blocks[-1][6].split()[2]) * units.kcal / units.mol
173 )
175 def read_forces(self, filename='mdfrc'):
176 """read forces from amber file"""
177 fd = netcdf_file(filename, 'r', mmap=False)
178 try:
179 forces = fd.variables['forces']
180 self.results['forces'] = (
181 forces[-1, :, :] / units.Ang * units.kcal / units.mol
182 )
183 finally:
184 fd.close()
186 def set_charges(self, selection, charges, parmed_filename=None):
187 """Modify amber topology charges to contain the updated
188 QM charges, needed in QM/MM.
189 Using amber's parmed program to change charges.
190 """
191 qm_list = list(selection)
192 with open(parmed_filename, 'w') as fout:
193 fout.write('# update the following QM charges \n')
194 for i, charge in zip(qm_list, charges):
195 fout.write(
196 'change charge @' + str(i + 1) + ' ' + str(charge) + ' \n'
197 )
198 fout.write('# Output the topology file \n')
199 fout.write('outparm ' + self.topologyfile + ' \n')
200 parmed_command = (
201 'parmed -O -i '
202 + parmed_filename
203 + ' -p '
204 + self.topologyfile
205 + ' > '
206 + self.topologyfile
207 + '.log 2>&1'
208 )
209 subprocess.check_call(parmed_command, shell=True, cwd=self.directory)
211 def get_virtual_charges(self, atoms):
212 with open(self.topologyfile) as fd:
213 topology = fd.readlines()
214 for n, line in enumerate(topology):
215 if '%FLAG CHARGE' in line:
216 chargestart = n + 2
217 lines1 = topology[
218 chargestart : (chargestart + (len(atoms) - 1) // 5 + 1)
219 ]
220 mm_charges = []
221 for line in lines1:
222 for el in line.split():
223 mm_charges.append(float(el) / 18.2223)
224 charges = np.array(mm_charges)
225 return charges
227 def add_virtual_sites(self, positions):
228 return positions # no virtual sites
230 def redistribute_forces(self, forces):
231 return forces
234def map(atoms, top):
235 p = np.zeros((2, len(atoms)), dtype='int')
237 elements = atoms.get_chemical_symbols()
238 unique_elements = np.unique(atoms.get_chemical_symbols())
240 for i in range(len(unique_elements)):
241 idx = 0
242 for j in range(len(atoms)):
243 if elements[j] == unique_elements[i]:
244 idx += 1
245 symbol = unique_elements[i] + np.str(idx)
246 for k in range(len(atoms)):
247 if top.atoms[k].name == symbol:
248 p[0, k] = j
249 p[1, j] = k
250 break
251 return p
254try:
255 import sander
257 have_sander = True
258except ImportError:
259 have_sander = False
262class SANDER(Calculator):
263 """
264 Interface to SANDER using Python interface
266 Requires sander Python bindings from https://ambermd.org/
267 """
269 implemented_properties = ['energy', 'forces']
271 def __init__(
272 self,
273 atoms=None,
274 label=None,
275 top=None,
276 crd=None,
277 mm_options=None,
278 qm_options=None,
279 permutation=None,
280 **kwargs,
281 ):
282 if not have_sander:
283 raise RuntimeError('sander Python module could not be imported!')
284 Calculator.__init__(self, label, atoms)
285 self.permutation = permutation
286 if qm_options is not None:
287 sander.setup(top, crd.coordinates, crd.box, mm_options, qm_options)
288 else:
289 sander.setup(top, crd.coordinates, crd.box, mm_options)
291 def calculate(self, atoms, properties, system_changes):
292 Calculator.calculate(self, atoms, properties, system_changes)
293 if system_changes:
294 if 'energy' in self.results:
295 del self.results['energy']
296 if 'forces' in self.results:
297 del self.results['forces']
298 if 'energy' not in self.results:
299 if self.permutation is None:
300 crd = np.reshape(atoms.get_positions(), (1, len(atoms), 3))
301 else:
302 crd = np.reshape(
303 atoms.get_positions()[self.permutation[0, :]],
304 (1, len(atoms), 3),
305 )
306 sander.set_positions(crd)
307 e, f = sander.energy_forces()
308 self.results['energy'] = e.tot * units.kcal / units.mol
309 if self.permutation is None:
310 self.results['forces'] = (
311 np.reshape(np.array(f), (len(atoms), 3))
312 * units.kcal
313 / units.mol
314 )
315 else:
316 ff = (
317 np.reshape(np.array(f), (len(atoms), 3))
318 * units.kcal
319 / units.mol
320 )
321 self.results['forces'] = ff[self.permutation[1, :]]
322 if 'forces' not in self.results:
323 if self.permutation is None:
324 crd = np.reshape(atoms.get_positions(), (1, len(atoms), 3))
325 else:
326 crd = np.reshape(
327 atoms.get_positions()[self.permutation[0, :]],
328 (1, len(atoms), 3),
329 )
330 sander.set_positions(crd)
331 e, f = sander.energy_forces()
332 self.results['energy'] = e.tot * units.kcal / units.mol
333 if self.permutation is None:
334 self.results['forces'] = (
335 np.reshape(np.array(f), (len(atoms), 3))
336 * units.kcal
337 / units.mol
338 )
339 else:
340 ff = (
341 np.reshape(np.array(f), (len(atoms), 3))
342 * units.kcal
343 / units.mol
344 )
345 self.results['forces'] = ff[self.permutation[1, :]]