Coverage for ase/calculators/gromacs.py: 85.62%

146 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1"""This module defines an ASE interface to GROMACS. 

2 

3https://www.gromacs.org/ 

4It is VERY SLOW compared to standard Gromacs 

5(due to slow formatted io required here). 

6 

7Mainly intended to be the MM part in the ase QM/MM 

8 

9Markus.Kaukonen@iki.fi 

10 

11To be done: 

121) change the documentation for the new file-io-calculator (test works now) 

132) change gromacs program names 

14-now: hard coded 

15-future: set as dictionary in params_runs 

16 

17""" 

18 

19import os 

20import subprocess 

21from glob import glob 

22 

23import numpy as np 

24 

25from ase import units 

26from ase.calculators.calculator import ( 

27 CalculatorSetupError, 

28 FileIOCalculator, 

29 all_changes, 

30) 

31from ase.io.gromos import read_gromos, write_gromos 

32 

33 

34def parse_gromacs_version(output): 

35 import re 

36 

37 match = re.search(r'GROMACS version\:\s*(\S+)', output, re.M) 

38 return match.group(1) 

39 

40 

41def get_gromacs_version(executable): 

42 output = subprocess.check_output( 

43 [executable, '--version'], encoding='utf-8' 

44 ) 

45 return parse_gromacs_version(output) 

46 

47 

48def do_clean(name='#*'): 

49 """remove files matching wildcards""" 

50 myfiles = glob(name) 

51 for myfile in myfiles: 

52 try: 

53 os.remove(myfile) 

54 except OSError: 

55 pass 

56 

57 

58class Gromacs(FileIOCalculator): 

59 """Class for doing GROMACS calculations. 

60 Before running a gromacs calculation you must prepare the input files 

61 separately (pdb2gmx and grompp for instance.) 

62 

63 Input parameters for gromacs runs (the .mdp file) 

64 are given in self.params and can be set when initializing the calculator 

65 or by method set_own. 

66 for example:: 

67 

68 CALC_MM_RELAX = Gromacs() 

69 CALC_MM_RELAX.set_own_params('integrator', 'steep', 

70 'use steepest descent') 

71 

72 Run command line arguments for gromacs related programs: 

73 pdb2gmx, grompp, mdrun, energy, traj. These can be given as:: 

74 

75 CALC_MM_RELAX = Gromacs() 

76 CALC_MM_RELAX.set_own_params_runs('force_field', 'oplsaa') 

77 """ 

78 

79 implemented_properties = ['energy', 'forces'] 

80 discard_results_on_any_change = True 

81 

82 default_parameters = dict( 

83 define='-DFLEXIBLE', 

84 integrator='cg', 

85 nsteps='10000', 

86 nstfout='10', 

87 nstlog='10', 

88 nstenergy='10', 

89 nstlist='10', 

90 ns_type='grid', 

91 pbc='xyz', 

92 rlist='1.15', 

93 coulombtype='PME-Switch', 

94 rcoulomb='0.8', 

95 vdwtype='shift', 

96 rvdw='0.8', 

97 rvdw_switch='0.75', 

98 DispCorr='Ener', 

99 ) 

100 

101 def __init__( 

102 self, 

103 restart=None, 

104 ignore_bad_restart_file=FileIOCalculator._deprecated, 

105 label='gromacs', 

106 atoms=None, 

107 do_qmmm=False, 

108 clean=True, 

109 water_model='tip3p', 

110 force_field='oplsaa', 

111 command=None, 

112 **kwargs, 

113 ): 

114 """Construct GROMACS-calculator object. 

115 

116 Parameters 

117 ---------- 

118 label: str 

119 Prefix to use for filenames (label.in, label.txt, ...). 

120 Default is 'gromacs'. 

121 

122 do_qmmm : bool 

123 Is gromacs used as mm calculator for a qm/mm calculation 

124 

125 clean : bool 

126 Remove gromacs backup files 

127 and old gormacs.* files 

128 

129 water_model: str 

130 Water model to be used in gromacs runs (see gromacs manual) 

131 

132 force_field: str 

133 Force field to be used in gromacs runs 

134 

135 command : str 

136 Gromacs executable; if None (default), choose available one from 

137 ('gmx', 'gmx_d', 'gmx_mpi', 'gmx_mpi_d') 

138 """ 

139 

140 self.do_qmmm = do_qmmm 

141 self.water_model = water_model 

142 self.force_field = force_field 

143 self.clean = clean 

144 self.params_doc = {} 

145 # add comments for gromacs input file 

146 self.params_doc['define'] = 'flexible/ rigid water' 

147 self.params_doc['integrator'] = ( 

148 'md: molecular dynamics(Leapfrog), \n' 

149 + '; md-vv: molecular dynamics(Velocity Verlet), \n' 

150 + '; steep: steepest descent minimization, \n' 

151 + '; cg: conjugate cradient minimization \n' 

152 ) 

153 

154 self.positions = None 

155 self.atoms = None 

156 

157 FileIOCalculator.__init__( 

158 self, 

159 restart, 

160 ignore_bad_restart_file, 

161 label, 

162 atoms, 

163 command=command, 

164 **kwargs, 

165 ) 

166 self.set(**kwargs) 

167 # default values for runtime parameters 

168 # can be changed by self.set_own_params_runs('key', 'value') 

169 self.params_runs = {} 

170 self.params_runs['index_filename'] = 'index.ndx' 

171 self.params_runs['init_structure'] = self.label + '.pdb' 

172 self.params_runs['water'] = self.water_model 

173 self.params_runs['force_field'] = self.force_field 

174 

175 # these below are required by qm/mm 

176 self.topology_filename = self.label + '.top' 

177 

178 # clean up gromacs backups 

179 if self.clean: 

180 do_clean('gromacs.???') 

181 

182 # write input files for gromacs program energy 

183 self.write_energy_files() 

184 

185 if self.do_qmmm: 

186 self.parameters['integrator'] = 'md' 

187 self.parameters['nsteps'] = '0' 

188 

189 def _get_name(self): 

190 return 'Gromacs' 

191 

192 def _execute_gromacs(self, command): 

193 """execute gmx command 

194 Parameters 

195 ---------- 

196 command : str 

197 """ 

198 if self.command: 

199 subprocess.check_call(self.command + ' ' + command, shell=True) 

200 else: 

201 raise CalculatorSetupError('Missing gromacs executable') 

202 

203 def generate_g96file(self): 

204 """from current coordinates (self.structure_file) 

205 write a structure file in .g96 format 

206 """ 

207 # generate structure file in g96 format 

208 write_gromos(self.label + '.g96', self.atoms) 

209 

210 def run_editconf(self): 

211 """run gromacs program editconf, typically to set a simulation box 

212 writing to the input structure""" 

213 subcmd = 'editconf' 

214 command = ' '.join( 

215 [ 

216 subcmd, 

217 '-f', 

218 self.label + '.g96', 

219 '-o', 

220 self.label + '.g96', 

221 self.params_runs.get('extra_editconf_parameters', ''), 

222 f'> {self.label}.{subcmd}.log 2>&1', 

223 ] 

224 ) 

225 self._execute_gromacs(command) 

226 

227 def run_genbox(self): 

228 """Run gromacs program genbox, typically to solvate the system 

229 writing to the input structure 

230 as extra parameter you need to define the file containing the solvent 

231 

232 for instance:: 

233 

234 CALC_MM_RELAX = Gromacs() 

235 CALC_MM_RELAX.set_own_params_runs( 

236 'extra_genbox_parameters', '-cs spc216.gro') 

237 """ 

238 subcmd = 'genbox' 

239 command = ' '.join( 

240 [ 

241 subcmd, 

242 '-cp', 

243 self.label + '.g96', 

244 '-o', 

245 self.label + '.g96', 

246 '-p', 

247 self.label + '.top', 

248 self.params_runs.get('extra_genbox_parameters', ''), 

249 f'> {self.label}.{subcmd}.log 2>&1', 

250 ] 

251 ) 

252 self._execute_gromacs(command) 

253 

254 def run(self): 

255 """runs a gromacs-mdrun with the 

256 current atom-configuration""" 

257 

258 # clean up gromacs backups 

259 if self.clean: 

260 do_clean('#*') 

261 

262 subcmd = 'mdrun' 

263 command = [subcmd] 

264 if self.do_qmmm: 

265 command += [ 

266 '-s', 

267 self.label + '.tpr', 

268 '-o', 

269 self.label + '.trr', 

270 '-e', 

271 self.label + '.edr', 

272 '-g', 

273 self.label + '.log', 

274 '-rerun', 

275 self.label + '.g96', 

276 self.params_runs.get('extra_mdrun_parameters', ''), 

277 '> QMMM.log 2>&1', 

278 ] 

279 command = ' '.join(command) 

280 self._execute_gromacs(command) 

281 else: 

282 command += [ 

283 '-s', 

284 self.label + '.tpr', 

285 '-o', 

286 self.label + '.trr', 

287 '-e', 

288 self.label + '.edr', 

289 '-g', 

290 self.label + '.log', 

291 '-c', 

292 self.label + '.g96', 

293 self.params_runs.get('extra_mdrun_parameters', ''), 

294 '> MM.log 2>&1', 

295 ] 

296 command = ' '.join(command) 

297 self._execute_gromacs(command) 

298 

299 atoms = read_gromos(self.label + '.g96') 

300 self.atoms = atoms.copy() 

301 

302 def generate_topology_and_g96file(self): 

303 """from coordinates (self.label.+'pdb') 

304 and gromacs run input file (self.label + '.mdp) 

305 generate topology (self.label+'top') 

306 and structure file in .g96 format (self.label + '.g96') 

307 """ 

308 # generate structure and topology files 

309 # In case of predefinded topology file this is not done 

310 subcmd = 'pdb2gmx' 

311 command = ' '.join( 

312 [ 

313 subcmd, 

314 '-f', 

315 self.params_runs['init_structure'], 

316 '-o', 

317 self.label + '.g96', 

318 '-p', 

319 self.label + '.top', 

320 '-ff', 

321 self.params_runs['force_field'], 

322 '-water', 

323 self.params_runs['water'], 

324 self.params_runs.get('extra_pdb2gmx_parameters', ''), 

325 f'> {self.label}.{subcmd}.log 2>&1', 

326 ] 

327 ) 

328 self._execute_gromacs(command) 

329 

330 atoms = read_gromos(self.label + '.g96') 

331 self.atoms = atoms.copy() 

332 

333 def generate_gromacs_run_file(self): 

334 """Generates input file for a gromacs mdrun 

335 based on structure file and topology file 

336 resulting file is self.label + '.tpr 

337 """ 

338 

339 # generate gromacs run input file (gromacs.tpr) 

340 try: 

341 os.remove(self.label + '.tpr') 

342 except OSError: 

343 pass 

344 

345 subcmd = 'grompp' 

346 command = ' '.join( 

347 [ 

348 subcmd, 

349 '-f', 

350 self.label + '.mdp', 

351 '-c', 

352 self.label + '.g96', 

353 '-p', 

354 self.label + '.top', 

355 '-o', 

356 self.label + '.tpr', 

357 '-maxwarn', 

358 '100', 

359 self.params_runs.get('extra_grompp_parameters', ''), 

360 f'> {self.label}.{subcmd}.log 2>&1', 

361 ] 

362 ) 

363 self._execute_gromacs(command) 

364 

365 def write_energy_files(self): 

366 """write input files for gromacs force and energy calculations 

367 for gromacs program energy""" 

368 filename = 'inputGenergy.txt' 

369 with open(filename, 'w') as output: 

370 output.write('Potential \n') 

371 output.write(' \n') 

372 output.write(' \n') 

373 

374 filename = 'inputGtraj.txt' 

375 with open(filename, 'w') as output: 

376 output.write('System \n') 

377 output.write(' \n') 

378 output.write(' \n') 

379 

380 def set_own_params(self, key, value, docstring=''): 

381 """Set own gromacs parameter with doc strings.""" 

382 self.parameters[key] = value 

383 self.params_doc[key] = docstring 

384 

385 def set_own_params_runs(self, key, value): 

386 """Set own gromacs parameter for program parameters 

387 Add spaces to avoid errors""" 

388 self.params_runs[key] = ' ' + value + ' ' 

389 

390 def write_input(self, atoms=None, properties=None, system_changes=None): 

391 """Write input parameters to input file.""" 

392 

393 FileIOCalculator.write_input(self, atoms, properties, system_changes) 

394 # print self.parameters 

395 with open(self.label + '.mdp', 'w') as myfile: 

396 for key, val in self.parameters.items(): 

397 if val is not None: 

398 docstring = self.params_doc.get(key, '') 

399 myfile.write( 

400 '%-35s = %s ; %s\n' % (key, val, ';' + docstring) 

401 ) 

402 

403 def update(self, atoms): 

404 """set atoms and do the calculation""" 

405 # performs an update of the atoms 

406 self.atoms = atoms.copy() 

407 # must be g96 format for accuracy, alternatively binary formats 

408 write_gromos(self.label + '.g96', atoms) 

409 # does run to get forces and energies 

410 self.calculate() 

411 

412 def calculate( 

413 self, 

414 atoms=None, 

415 properties=None, 

416 system_changes=all_changes, 

417 ): 

418 """runs a gromacs-mdrun and 

419 gets energy and forces 

420 rest below is to make gromacs calculator 

421 compactible with ase-Calculator class 

422 

423 atoms: Atoms object 

424 Contains positions, unit-cell, ... 

425 properties: list of str 

426 List of what needs to be calculated. Can be any combination 

427 of 'energy', 'forces' 

428 system_changes: list of str 

429 List of what has changed since last calculation. Can be 

430 any combination of these five: 'positions', 'numbers', 'cell', 

431 'pbc', 'initial_charges' and 'initial_magmoms'. 

432 

433 """ 

434 

435 if properties is None: 

436 properties = ['energy', 'forces'] 

437 self.run() 

438 if self.clean: 

439 do_clean('#*') 

440 # get energy 

441 try: 

442 os.remove('tmp_ene.del') 

443 except OSError: 

444 pass 

445 

446 subcmd = 'energy' 

447 command = ' '.join( 

448 [ 

449 subcmd, 

450 '-f', 

451 self.label + '.edr', 

452 '-o', 

453 self.label + '.Energy.xvg', 

454 '< inputGenergy.txt', 

455 f'> {self.label}.{subcmd}.log 2>&1', 

456 ] 

457 ) 

458 self._execute_gromacs(command) 

459 with open(self.label + '.Energy.xvg') as fd: 

460 lastline = fd.readlines()[-1] 

461 energy = float(lastline.split()[1]) 

462 # We go for ASE units ! 

463 self.results['energy'] = energy * units.kJ / units.mol 

464 # energies are about 100 times bigger in Gromacs units 

465 # when compared to ase units 

466 

467 subcmd = 'traj' 

468 command = ' '.join( 

469 [ 

470 subcmd, 

471 '-f', 

472 self.label + '.trr', 

473 '-s', 

474 self.label + '.tpr', 

475 '-of', 

476 self.label + '.Force.xvg', 

477 '< inputGtraj.txt', 

478 f'> {self.label}.{subcmd}.log 2>&1', 

479 ] 

480 ) 

481 self._execute_gromacs(command) 

482 with open(self.label + '.Force.xvg') as fd: 

483 lastline = fd.readlines()[-1] 

484 forces = np.array([float(f) for f in lastline.split()[1:]]) 

485 # We go for ASE units !gromacsForce.xvg 

486 tmp_forces = forces / units.nm * units.kJ / units.mol 

487 tmp_forces = np.reshape(tmp_forces, (-1, 3)) 

488 self.results['forces'] = tmp_forces