def setUp(self): from htmd.home import home from htmd.parameterization.fftype import FFTypeMethod, fftype from htmd.parameterization.util import canonicalizeAtomNames, getEquivalentsAndDihedrals from htmd.molecule.molecule import Molecule molFile = os.path.join(home('test-param'), 'glycol.mol2') mol = Molecule(molFile) mol = canonicalizeAtomNames(mol) mol, self.equivalents, all_dihedrals = getEquivalentsAndDihedrals(mol) _, mol = fftype(mol, method=FFTypeMethod.GAFF2) self.mol = mol
def setUp(self): from htmd.home import home from htmd.parameterization.util import getEquivalentsAndDihedrals from htmd.molecule.molecule import Molecule molFile = os.path.join(home('test-param'), 'H2O2.mol2') mol = Molecule(molFile, guessNE='bonds', guess=('angles', 'dihedrals')) mol, equivalents, all_dihedrals = getEquivalentsAndDihedrals(mol) self.mol = mol self.esp = ESP() self.esp.molecule = self.mol # Precalculating here for the tests equivalents = detectEquivalentAtoms(self.esp.molecule) self.esp._equivalent_atom_groups = equivalents[0] self.esp._equivalent_group_by_atom = equivalents[2]
import re from htmd.home import home from htmd.molecule.molecule import Molecule from htmd.parameterization.writers import writeRTF, writePRM, writeFRCMOD from htmd.parameterization.util import canonicalizeAtomNames, getEquivalentsAndDihedrals # BUG: MATCH does not work on Mac! if 'TRAVIS_OS_NAME' in os.environ: if os.environ['TRAVIS_OS_NAME'] == 'osx': sys.exit(0) molFile = os.path.join(home('building-protein-ligand'), 'benzamidine.mol2') refDir = home(dataDir='test-fftype/benzamidine') mol = Molecule(molFile) mol = canonicalizeAtomNames(mol) mol, equivalents, all_dihedrals = getEquivalentsAndDihedrals(mol) with TemporaryDirectory() as tmpDir: parameters, mol = fftype(mol, method=FFTypeMethod.CGenFF_2b6) writeRTF(mol, parameters, 0, os.path.join(tmpDir, 'cgenff.rtf')) writePRM(mol, parameters, os.path.join(tmpDir, 'cgenff.prm')) parameters, mol = fftype(mol, method=FFTypeMethod.GAFF) writeFRCMOD(mol, parameters, os.path.join(tmpDir, 'gaff.frcmod')) parameters, mol = fftype(mol, method=FFTypeMethod.GAFF2) writeFRCMOD(mol, parameters, os.path.join(tmpDir, 'gaff2.frcmod')) for testFile in os.listdir(refDir): print(testFile)
def main_parameterize(arguments=None): args = getArgumentParser().parse_args(args=arguments) if not os.path.exists(args.filename): raise ValueError('File %s cannot be found' % args.filename) method_map = { 'GAFF': FFTypeMethod.GAFF, 'GAFF2': FFTypeMethod.GAFF2, 'CGENFF': FFTypeMethod.CGenFF_2b6 } methods = [method_map[method] for method in args.forcefield] # Get RTF and PRM file names rtfFile, prmFile = None, None if args.rtf_prm: rtfFile, prmFile = args.rtf_prm # Create a queue for QM if args.queue == 'local': queue = LocalCPUQueue() elif args.queue == 'Slurm': queue = SlurmQueue(_configapp=args.code.lower()) elif args.queue == 'LSF': queue = LsfQueue(_configapp=args.code.lower()) elif args.queue == 'PBS': queue = PBSQueue() # TODO: configure elif args.queue == 'AceCloud': queue = AceCloudQueue() # TODO: configure queue.groupname = args.groupname queue.hashnames = True else: raise NotImplementedError # Override default ncpus if args.ncpus: logger.info('Overriding ncpus to {}'.format(args.ncpus)) queue.ncpu = args.ncpus if args.memory: logger.info('Overriding memory to {}'.format(args.memory)) queue.memory = args.memory # Create a QM object if args.code == 'Psi4': qm = Psi4() elif args.code == 'Gaussian': qm = Gaussian() else: raise NotImplementedError # This is for debugging only! if args.fake_qm: qm = FakeQM2() logger.warning('Using FakeQM') # Get rotatable dihedral angles mol = Molecule(args.filename) mol = canonicalizeAtomNames(mol) mol, equivalents, all_dihedrals = getEquivalentsAndDihedrals(mol) netcharge = args.charge if args.charge is not None else int( round(np.sum(mol.charge))) if args.list: print('\n === Parameterizable dihedral angles of {} ===\n'.format( args.filename)) with open('torsions.txt', 'w') as fh: for dihedral in all_dihedrals: dihedral_name = '-'.join(mol.name[list(dihedral[0])]) print(' {}'.format(dihedral_name)) fh.write(dihedral_name + '\n') print() sys.exit(0) # Set up the QM object qm.theory = args.theory qm.basis = args.basis qm.solvent = args.environment qm.queue = queue qm.charge = netcharge # Select which dihedrals to fit parameterizable_dihedrals = [list(dih[0]) for dih in all_dihedrals] if len(args.dihedral) > 0: all_dihedral_names = [ '-'.join(mol.name[list(dihedral[0])]) for dihedral in all_dihedrals ] parameterizable_dihedrals = [] for dihedral_name in args.dihedral: if dihedral_name not in all_dihedral_names: raise ValueError( '%s is not recognized as a rotatable dihedral angle' % dihedral_name) parameterizable_dihedrals.append( list( all_dihedrals[all_dihedral_names.index(dihedral_name)][0])) # Print arguments print('\n === Arguments ===\n') for key, value in vars(args).items(): print('{:>12s}: {:s}'.format(key, str(value))) print('\n === Parameterizing %s ===\n' % args.filename) for method in methods: print(" === Fitting for %s ===\n" % method.name) printReport(mol, netcharge, equivalents, all_dihedrals) parameters, mol = fftype(mol, method=method, rtfFile=rtfFile, prmFile=prmFile, netcharge=args.charge) if isinstance(qm, FakeQM2): qm._parameters = parameters # Copy the molecule to preserve initial coordinates orig_coor = mol.coords.copy() # Update B3LYP to B3LYP-D3 # TODO: this is silent and not documented stuff if qm.theory == 'B3LYP': qm.correction = 'D3' # Update basis sets # TODO: this is silent and not documented stuff if netcharge < 0 and qm.solvent == 'vacuum': if qm.basis == '6-31G*': qm.basis = '6-31+G*' if qm.basis == 'cc-pVDZ': qm.basis = 'aug-cc-pVDZ' logger.info('Changing basis sets to %s' % qm.basis) # Minimize molecule if args.minimize: print('\n == Minimizing ==\n') mol = minimize(mol, qm, args.outdir) # Fit ESP charges if args.fit_charges: print('\n == Fitting ESP charges ==\n') # Set random number generator seed if args.seed: np.random.seed(args.seed) # Select the atoms with fixed charges fixed_atom_indices = getFixedChargeAtomIndices( mol, args.fix_charge) # Fit ESP charges mol, _, esp_charges, qm_dipole = fitCharges( mol, qm, args.outdir, fixed=fixed_atom_indices) # Print dipoles logger.info('QM dipole: %f %f %f; %f' % tuple(qm_dipole)) mm_dipole = getDipole(mol) if np.all(np.isfinite(mm_dipole)): logger.info('MM dipole: %f %f %f; %f' % tuple(mm_dipole)) else: logger.warning( 'MM dipole cannot be computed. Check if elements are detected correctly.' ) # Fit dihedral angle parameters if args.fit_dihedral: print('\n == Fitting dihedral angle parameters ==\n') # Set random number generator seed if args.seed: np.random.seed(args.seed) # Invent new atom types for dihedral atoms mol, originaltypes = inventAtomTypes(mol, parameterizable_dihedrals, equivalents) parameters = recreateParameters(mol, originaltypes, parameters) parameters = createMultitermDihedralTypes(parameters) if isinstance(qm, FakeQM2): qm._parameters = parameters # Fit the parameters fitDihedrals(mol, qm, method, parameters, all_dihedrals, parameterizable_dihedrals, args.outdir, geomopt=args.optimize_dihedral) # Output the FF parameters print('\n == Writing results ==\n') writeParameters(mol, parameters, qm, method, netcharge, args.outdir, original_coords=orig_coor) # Write energy file energyFile = os.path.join(args.outdir, 'parameters', method.name, _qm_method_name(qm), 'energies.txt') printEnergies(mol, parameters, energyFile) logger.info('Write energy file: %s' % energyFile)
def main_parameterize(arguments=None): args = getArgumentParser().parse_args(args=arguments) if not os.path.exists(args.filename): raise ValueError('File %s cannot be found' % args.filename) method_map = {'GAFF': FFTypeMethod.GAFF, 'GAFF2': FFTypeMethod.GAFF2, 'CGENFF': FFTypeMethod.CGenFF_2b6} methods = [method_map[method] for method in args.forcefield] # Get RTF and PRM file names rtfFile, prmFile = None, None if args.rtf_prm: rtfFile, prmFile = args.rtf_prm # Create a queue for QM if args.queue == 'local': queue = LocalCPUQueue() elif args.queue == 'Slurm': queue = SlurmQueue(_configapp=args.code.lower()) elif args.queue == 'LSF': queue = LsfQueue(_configapp=args.code.lower()) elif args.queue == 'PBS': queue = PBSQueue() # TODO: configure elif args.queue == 'AceCloud': queue = AceCloudQueue() # TODO: configure queue.groupname = args.groupname queue.hashnames = True else: raise NotImplementedError # Override default ncpus if args.ncpus: logger.info('Overriding ncpus to {}'.format(args.ncpus)) queue.ncpu = args.ncpus if args.memory: logger.info('Overriding memory to {}'.format(args.memory)) queue.memory = args.memory # Create a QM object if args.code == 'Psi4': qm = Psi4() elif args.code == 'Gaussian': qm = Gaussian() else: raise NotImplementedError # This is for debugging only! if args.fake_qm: qm = FakeQM2() logger.warning('Using FakeQM') # Get rotatable dihedral angles mol = Molecule(args.filename) mol = canonicalizeAtomNames(mol) mol, equivalents, all_dihedrals = getEquivalentsAndDihedrals(mol) netcharge = args.charge if args.charge is not None else int(round(np.sum(mol.charge))) if args.list: print('\n === Parameterizable dihedral angles of {} ===\n'.format(args.filename)) with open('torsions.txt', 'w') as fh: for dihedral in all_dihedrals: dihedral_name = '-'.join(mol.name[list(dihedral[0])]) print(' {}'.format(dihedral_name)) fh.write(dihedral_name+'\n') print() sys.exit(0) # Set up the QM object qm.theory = args.theory qm.basis = args.basis qm.solvent = args.environment qm.queue = queue qm.charge = netcharge # Select which dihedrals to fit parameterizable_dihedrals = [list(dih[0]) for dih in all_dihedrals] if len(args.dihedral) > 0: all_dihedral_names = ['-'.join(mol.name[list(dihedral[0])]) for dihedral in all_dihedrals] parameterizable_dihedrals = [] for dihedral_name in args.dihedral: if dihedral_name not in all_dihedral_names: raise ValueError('%s is not recognized as a rotatable dihedral angle' % dihedral_name) parameterizable_dihedrals.append(list(all_dihedrals[all_dihedral_names.index(dihedral_name)][0])) # Print arguments print('\n === Arguments ===\n') for key, value in vars(args).items(): print('{:>12s}: {:s}'.format(key, str(value))) print('\n === Parameterizing %s ===\n' % args.filename) for method in methods: print(" === Fitting for %s ===\n" % method.name) printReport(mol, netcharge, equivalents, all_dihedrals) parameters, mol = fftype(mol, method=method, rtfFile=rtfFile, prmFile=prmFile, netcharge=args.charge) if isinstance(qm, FakeQM2): qm._parameters = parameters # Copy the molecule to preserve initial coordinates orig_coor = mol.coords.copy() # Update B3LYP to B3LYP-D3 # TODO: this is silent and not documented stuff if qm.theory == 'B3LYP': qm.correction = 'D3' # Update basis sets # TODO: this is silent and not documented stuff if netcharge < 0 and qm.solvent == 'vacuum': if qm.basis == '6-31G*': qm.basis = '6-31+G*' if qm.basis == 'cc-pVDZ': qm.basis = 'aug-cc-pVDZ' logger.info('Changing basis sets to %s' % qm.basis) # Minimize molecule if args.minimize: print('\n == Minimizing ==\n') mol = minimize(mol, qm, args.outdir) # Fit ESP charges if args.fit_charges: print('\n == Fitting ESP charges ==\n') # Set random number generator seed if args.seed: np.random.seed(args.seed) # Select the atoms with fixed charges fixed_atom_indices = getFixedChargeAtomIndices(mol, args.fix_charge) # Fit ESP charges mol, _, esp_charges, qm_dipole = fitCharges(mol, qm, args.outdir, fixed=fixed_atom_indices) # Print dipoles logger.info('QM dipole: %f %f %f; %f' % tuple(qm_dipole)) mm_dipole = getDipole(mol) if np.all(np.isfinite(mm_dipole)): logger.info('MM dipole: %f %f %f; %f' % tuple(mm_dipole)) else: logger.warning('MM dipole cannot be computed. Check if elements are detected correctly.') # Fit dihedral angle parameters if args.fit_dihedral: print('\n == Fitting dihedral angle parameters ==\n') # Set random number generator seed if args.seed: np.random.seed(args.seed) # Invent new atom types for dihedral atoms mol, originaltypes = inventAtomTypes(mol, parameterizable_dihedrals, equivalents) parameters = recreateParameters(mol, originaltypes, parameters) parameters = createMultitermDihedralTypes(parameters) if isinstance(qm, FakeQM2): qm._parameters = parameters # Fit the parameters fitDihedrals(mol, qm, method, parameters, all_dihedrals, parameterizable_dihedrals, args.outdir, geomopt=args.optimize_dihedral) # Output the FF parameters print('\n == Writing results ==\n') writeParameters(mol, parameters, qm, method, netcharge, args.outdir, original_coords=orig_coor) # Write energy file energyFile = os.path.join(args.outdir, 'parameters', method.name, _qm_method_name(qm), 'energies.txt') printEnergies(mol, parameters, energyFile) logger.info('Write energy file: %s' % energyFile)