Beispiel #1
0
def _get_initial_parameters(mol, args):

    from htmd.parameterization.fftype import fftype

    logger.info('=== Atom type and initial parameter assignment ===')
    logger.info('Method: {}'.format(args.forcefield))

    # Get RTF and PRM file names
    rtfFile, prmFile = args.rtf_prm if args.rtf_prm else None, None

    # Assing atom types and initial force field parameters
    _charge = mol.charge.copy()
    parameters, mol = fftype(mol,
                             method=args.forcefield,
                             rtfFile=rtfFile,
                             prmFile=prmFile,
                             netcharge=args.charge)
    assert np.all(mol.charge == _charge), 'fftype is meddling with charges!'

    logger.info('Atom types:')
    for name, type in zip(mol.name, mol.atomtype):
        logger.info('   {:4s} : {}'.format(name, type))

    # TODO write initial parameter to a file

    return mol, parameters
Beispiel #2
0
    def testProteinLigand(self):
        from htmd.builder.solvate import solvate
        from htmd.parameterization.fftype import fftype, FFTypeMethod
        from htmd.parameterization.writers import writeFRCMOD

        # Test protein ligand building with parametrized ligand
        refdir = home(dataDir=join('test-amber-build', 'protLig'))
        tmpdir = os.path.join(self.testDir, 'protLig')
        os.makedirs(tmpdir)

        mol = Molecule(join(refdir, '3ptb_mod.pdb'))
        lig = Molecule(join(refdir, 'benzamidine.pdb'),
                       guess=('bonds', 'angles', 'dihedrals'))
        prm, lig = fftype(lig, method=FFTypeMethod.GAFF2)
        writeFRCMOD(lig, prm, join(tmpdir, 'mol.frcmod'))
        lig.segid[:] = 'L'

        # params =
        newmol = Molecule()
        newmol.append(lig)
        newmol.append(mol)
        smol = solvate(newmol)

        params = defaultParam() + [
            join(tmpdir, 'mol.frcmod'),
        ]

        _ = build(smol, outdir=tmpdir, param=params, ionize=False)

        refdir = home(dataDir=join('test-amber-build', 'protLig', 'results'))
        TestAmberBuild._compareResultFolders(refdir, tmpdir, '3PTB')
Beispiel #3
0
    def testProteinLigand(self):
        from htmd.builder.solvate import solvate
        from htmd.parameterization.fftype import fftype, FFTypeMethod
        from htmd.parameterization.writers import writeFRCMOD

        # Test protein ligand building with parametrized ligand
        refdir = home(dataDir=join('test-amber-build', 'protLig'))
        tmpdir = os.path.join(self.testDir, 'protLig')
        os.makedirs(tmpdir)

        mol = Molecule(join(refdir, '3ptb_mod.pdb'))
        lig = Molecule(join(refdir, 'benzamidine.pdb'), guess=('bonds', 'angles', 'dihedrals'))
        prm, lig = fftype(lig, method=FFTypeMethod.GAFF2)
        writeFRCMOD(lig, prm, join(tmpdir, 'mol.frcmod'))
        lig.segid[:] = 'L'

        # params =
        newmol = Molecule()
        newmol.append(lig)
        newmol.append(mol)
        smol = solvate(newmol)

        params = defaultParam() + [join(tmpdir, 'mol.frcmod'),]

        _ = build(smol, outdir=tmpdir, param=params, ionize=False)

        refdir = home(dataDir=join('test-amber-build', 'protLig', 'results'))
        TestAmberBuild._compareResultFolders(refdir, tmpdir, '3PTB')
Beispiel #4
0
    def setUp(self):
        from htmd.home import home
        from moleculekit.molecule import Molecule
        from htmd.parameterization.detect import detectEquivalentAtoms
        from htmd.parameterization.fftype import fftype

        molFile = os.path.join(home('test-param'), 'glycol.mol2')
        mol = Molecule(molFile)
        self.equivalents = detectEquivalentAtoms(mol)
        _, self.mol = fftype(mol, method='GAFF2')
Beispiel #5
0
    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
Beispiel #6
0
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)
Beispiel #7
0
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)
Beispiel #8
0
from os.path import join
from htmd.builder.solvate import solvate
from htmd.parameterization.fftype import fftype
from htmd.parameterization.writers import writeFRCMOD
from moleculekit.molecule import Molecule
from htmd.builder.amber import defaultParam, build

# Test protein ligand building with parametrized ligand
refdir = home(dataDir=join('test-amber-build', 'protLig'))
tmpdir = './protLig'

mol = Molecule(join(refdir, '3ptb_mod.pdb'))
mol.center()
lig = Molecule(join(refdir, 'benzamidine.pdb'),
               guess=('bonds', 'angles', 'dihedrals'))
prm, lig = fftype(lig, method='GAFF2')
writeFRCMOD(lig, prm, join(tmpdir, 'mol.frcmod'))
lig.segid[:] = 'L'
lig.center()

from moleculekit.util import maxDistance
D = maxDistance(mol, 'all')
D += 6
lig.moveBy([0, 0, D])

newmol = Molecule()
newmol.append(lig)
newmol.append(mol)
smol = solvate(newmol, posz=3)

params = defaultParam() + [