예제 #1
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')
예제 #2
0
    def test_build(self):
        from htmd.molecule.molecule import Molecule
        from htmd.builder.solvate import solvate
        from htmd.home import home
        from htmd.util import tempname, assertSameAsReferenceDir
        import os
        import numpy as np

        # Use pre-prepared files so we can tell whether the error is in prepare or in build
        # Inputs are reference outputs of proteinprepare.
        preparedInputDir = home(dataDir='test-proteinprepare')

        pdbids = ['3PTB', '1A25', '1GZM', '1U5U']
        for pdb in pdbids:
            with self.subTest(pdb=pdb):
                print('Building {}'.format(pdb))
                inFile = os.path.join(preparedInputDir, pdb,
                                      "{}-prepared.pdb".format(pdb))
                mol = Molecule(inFile)
                mol.filter(
                    'protein')  # Fix for bad proteinPrepare hydrogen placing

                np.random.seed(1)  # Needed for ions
                smol = solvate(mol)
                topos = ['top/top_all36_prot.rtf', 'top/top_water_ions.rtf']
                params = [
                    'par/par_all36_prot_mod.prm', 'par/par_water_ions.prm'
                ]
                tmpdir = tempname()
                _ = build(smol, topo=topos, param=params, outdir=tmpdir)

                compareDir = home(
                    dataDir=os.path.join('test-charmm-build', pdb))
                assertSameAsReferenceDir(compareDir, tmpdir)
예제 #3
0
파일: amber.py 프로젝트: raimis/htmd
    def test_customDisulfideBonds(self):
        from htmd.builder.solvate import solvate

        # Test without proteinPrepare
        pdbids = [
            "1GZM",
        ]
        for pid in pdbids:
            np.random.seed(1)
            mol = Molecule(pid)
            mol.filter("protein")
            smol = solvate(mol)
            ffs = defaultFf()
            disu = [
                ["segid 1 and resid 110", "segid 1 and resid 187"],
                ["segid 0 and resid 110", "segid 0 and resid 187"],
            ]
            tmpdir = os.path.join(self.testDir, "withoutProtPrep", pid)
            _ = build(smol, ff=ffs, outdir=tmpdir, disulfide=disu)

            refdir = home(dataDir=join("test-amber-build", "nopp", pid))
            _TestAmberBuild._compareResultFolders(refdir, tmpdir, pid)

            np.random.seed(1)
            tmpdir = os.path.join(self.testDir, "withoutProtPrep", pid)
            _ = build(smol, ff=ffs, outdir=tmpdir)

            refdir = home(dataDir=join("test-amber-build", "nopp", pid))
            _TestAmberBuild._compareResultFolders(refdir, tmpdir, pid)
예제 #4
0
    def test_acemd3(self):
        from htmd.util import tempname
        from htmd.home import home
        from glob import glob
        import os

        eq = Equilibration(_version=3)
        eq.runtime = 4
        eq.timeunits = 'ns'
        eq.temperature = 300
        # keep protein on the same place during all equilibration
        from htmd.units import convert
        eq.constraintsteps = convert(eq.timeunits,
                                     'timesteps',
                                     eq.runtime,
                                     timestep=eq.acemd.timestep)
        eq.constraints = {
            'protein and name CA': 1,
            'protein and noh and not name CA': 0.1
        }
        eq.fb_reference = 'protein and name CA'
        eq.fb_selection = 'resname MOL and noh'
        eq.fb_box = [-21, 21, -19, 19, 29, 30]
        eq.fb_k = 5
        tmpdir = tempname()
        eq.write(
            home(dataDir=os.path.join('test-protocols', 'build', 'protLig')),
            tmpdir)

        # Compare with reference
        refdir = home(dataDir=os.path.join('test-protocols', 'equilibration',
                                           'acemd3', 'protLig', 'prerun'))
        files = [os.path.basename(f) for f in glob(os.path.join(refdir, '*'))]
        self._compareResultFolders(refdir, tmpdir, 'protLig')
예제 #5
0
    def test_disulfideWithInsertion(self):
        from htmd.molecule.molecule import Molecule
        from htmd.builder.solvate import solvate
        from htmd.home import home
        from htmd.util import tempname, assertSameAsReferenceDir
        import os
        import numpy as np

        # Use pre-prepared files so we can tell whether the error is in prepare or in build
        # Inputs are reference outputs of proteinprepare.
        preparedInputDir = home(dataDir='test-proteinprepare')

        pdb = '3PTB'

        print('Building {}'.format(pdb))
        inFile = os.path.join(preparedInputDir, pdb,
                              "{}-prepared.pdb".format(pdb))
        mol = Molecule(inFile)
        mol.filter('protein')  # Fix for bad proteinPrepare hydrogen placing

        np.random.seed(1)  # Needed for ions
        smol = solvate(mol)
        topos = ['top/top_all36_prot.rtf', 'top/top_water_ions.rtf']
        params = ['par/par_all36_prot_mod.prm', 'par/par_water_ions.prm']

        smol.insertion[
            smol.resid ==
            42] = 'A'  # Adding an insertion to test that disulfide bonds with insertions work
        tmpdir = tempname()
        _ = build(smol, topo=topos, param=params, outdir=tmpdir)
        compareDir = home(
            dataDir=os.path.join('test-charmm-build', '3PTB_insertion'))
        assertSameAsReferenceDir(compareDir, tmpdir)
예제 #6
0
파일: amber.py 프로젝트: raimis/htmd
    def testProteinLigand(self):
        from htmd.builder.solvate import solvate

        # 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.mol2"))
        lig.segid[:] = "L"

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

        params = defaultParam() + [
            join(refdir, "benzamidine.frcmod"),
        ]

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

        refdir = home(dataDir=join("test-amber-build", "protLig", "results"))
        _TestAmberBuild._compareResultFolders(refdir, tmpdir, "3PTB")
예제 #7
0
파일: metricdata.py 프로젝트: jhlee123/htmd
    def setUpClass(self):
        from htmd.simlist import simlist, simfilter
        from glob import glob
        from htmd.projections.metric import Metric
        from moleculekit.projections.metricdistance import MetricDistance
        from moleculekit.projections.metricdihedral import MetricDihedral
        from moleculekit.util import tempname
        from htmd.home import home
        from os.path import join

        sims = simlist(glob(join(home(dataDir='adaptive'), 'data', '*', '')),
                       glob(join(home(dataDir='adaptive'), 'input', '*')))
        fsims = simfilter(sims, tempname(), 'not water')

        metr = Metric(fsims)
        metr.set(
            MetricDistance('protein and resid 10 and name CA',
                           'resname BEN and noh',
                           metric='contacts',
                           groupsel1='residue',
                           threshold=4))
        self.data1 = metr.project()

        metr.set(MetricDihedral())
        self.data2 = metr.project()
예제 #8
0
    def test_customDisulfideBonds(self):
        from moleculekit.molecule import Molecule
        from htmd.builder.solvate import solvate
        from htmd.home import home
        from htmd.util import tempname, assertSameAsReferenceDir
        import os
        import numpy as np

        # Use pre-prepared files so we can tell whether the error is in prepare or in build
        # Inputs are reference outputs of proteinprepare.
        preparedInputDir = home(dataDir="test-proteinprepare")

        pdb = "1GZM"
        inFile = os.path.join(preparedInputDir, pdb,
                              "{}-prepared.pdb".format(pdb))
        mol = Molecule(inFile)
        mol.filter("protein")  # Fix for bad proteinPrepare hydrogen placing

        np.random.seed(1)  # Needed for ions
        smol = solvate(mol)
        topos = ["top/top_all36_prot.rtf", "top/top_water_ions.rtf"]
        params = ["par/par_all36_prot.prm", "par/par_water_ions.prm"]
        disu = [
            ["segid 1 and resid 110", "segid 1 and resid 187"],
            ["segid 0 and resid 110", "segid 0 and resid 187"],
        ]
        tmpdir = tempname()
        _ = build(smol,
                  topo=topos,
                  param=params,
                  outdir=tmpdir,
                  disulfide=disu)

        compareDir = home(dataDir=os.path.join("test-charmm-build", pdb))
        assertSameAsReferenceDir(compareDir, tmpdir)
예제 #9
0
    def test_build(self):
        from moleculekit.molecule import Molecule
        from htmd.builder.solvate import solvate
        from htmd.home import home
        from htmd.util import tempname, assertSameAsReferenceDir
        import os
        import numpy as np

        # Use pre-prepared files so we can tell whether the error is in prepare or in build
        # Inputs are reference outputs of proteinprepare.
        preparedInputDir = home(dataDir="test-proteinprepare")

        pdbids = ["3PTB", "1A25", "1GZM", "1U5U"]
        for pdb in pdbids:
            with self.subTest(pdb=pdb):
                print("Building {}".format(pdb))
                inFile = os.path.join(preparedInputDir, pdb,
                                      "{}-prepared.pdb".format(pdb))
                mol = Molecule(inFile)
                mol.filter(
                    "protein")  # Fix for bad proteinPrepare hydrogen placing

                np.random.seed(1)  # Needed for ions
                smol = solvate(mol)
                topos = ["top/top_all36_prot.rtf", "top/top_water_ions.rtf"]
                params = ["par/par_all36_prot.prm", "par/par_water_ions.prm"]
                tmpdir = tempname()
                _ = build(smol, topo=topos, param=params, outdir=tmpdir)

                compareDir = home(
                    dataDir=os.path.join("test-charmm-build", pdb))
                assertSameAsReferenceDir(compareDir, tmpdir)
예제 #10
0
파일: charmm.py 프로젝트: alejandrovr/htmd
    def test_build(self):
        from htmd.molecule.molecule import Molecule
        from htmd.builder.solvate import solvate
        from htmd.home import home
        from htmd.util import tempname, assertSameAsReferenceDir
        import os
        import numpy as np

        # Use pre-prepared files so we can tell whether the error is in prepare or in build
        # Inputs are reference outputs of proteinprepare.
        preparedInputDir = home(dataDir='test-proteinprepare')

        pdbids = ['3PTB', '1A25', '1GZM', '1U5U']
        for pdb in pdbids:
            with self.subTest(pdb=pdb):
                print('Building {}'.format(pdb))
                inFile = os.path.join(preparedInputDir, pdb, "{}-prepared.pdb".format(pdb))
                mol = Molecule(inFile)
                mol.filter('protein')  # Fix for bad proteinPrepare hydrogen placing

                np.random.seed(1)  # Needed for ions
                smol = solvate(mol)
                topos = ['top/top_all36_prot.rtf', 'top/top_water_ions.rtf']
                params = ['par/par_all36_prot_mod.prm', 'par/par_water_ions.prm']
                tmpdir = tempname()
                _ = build(smol, topo=topos, param=params, outdir=tmpdir)

                compareDir = home(dataDir=os.path.join('test-charmm-build', pdb))
                assertSameAsReferenceDir(compareDir, tmpdir)
예제 #11
0
파일: charmm.py 프로젝트: alejandrovr/htmd
    def test_disulfideWithInsertion(self):
        from htmd.molecule.molecule import Molecule
        from htmd.builder.solvate import solvate
        from htmd.home import home
        from htmd.util import tempname, assertSameAsReferenceDir
        import os
        import numpy as np

        # Use pre-prepared files so we can tell whether the error is in prepare or in build
        # Inputs are reference outputs of proteinprepare.
        preparedInputDir = home(dataDir='test-proteinprepare')

        pdb = '3PTB'

        print('Building {}'.format(pdb))
        inFile = os.path.join(preparedInputDir, pdb, "{}-prepared.pdb".format(pdb))
        mol = Molecule(inFile)
        mol.filter('protein')  # Fix for bad proteinPrepare hydrogen placing

        np.random.seed(1)  # Needed for ions
        smol = solvate(mol)
        topos = ['top/top_all36_prot.rtf', 'top/top_water_ions.rtf']
        params = ['par/par_all36_prot_mod.prm', 'par/par_water_ions.prm']

        smol.insertion[smol.resid == 42] = 'A'  # Adding an insertion to test that disulfide bonds with insertions work
        tmpdir = tempname()
        _ = build(smol, topo=topos, param=params, outdir=tmpdir)
        compareDir = home(dataDir=os.path.join('test-charmm-build', '3PTB_insertion'))
        assertSameAsReferenceDir(compareDir, tmpdir)
예제 #12
0
    def test_acemd3(self):
        from htmd.util import tempname
        from htmd.home import home
        from htmd.units import convert
        from glob import glob
        import os
        from htmd.mdengine.acemd.acemd import GroupRestraint

        eq = Equilibration()
        eq.runtime = 4
        eq.timeunits = "ns"
        eq.temperature = 300
        eq.restraintsteps = convert(
            eq.timeunits, "timesteps", eq.runtime, timestep=eq.acemd.timestep
        )
        ligres = GroupRestraint(
            "resname MOL and noh",
            [42, 38, 1],
            [(5, 0)],
            fbcentre=[-0.178, -0.178, 29.195],
        )
        eq.restraints = eq.defaultEquilRestraints(1000000) + [ligres]
        tmpdir = tempname()
        eq.write(
            home(dataDir=os.path.join("test-protocols", "build", "protLig")), tmpdir
        )

        # Compare with reference
        refdir = home(
            dataDir=os.path.join(
                "test-protocols", "equilibration", "acemd3", "protLig", "prerun"
            )
        )
        files = [os.path.basename(f) for f in glob(os.path.join(refdir, "*"))]
        self._compareResultFolders(refdir, tmpdir, "protLig")
예제 #13
0
파일: amber.py 프로젝트: alejandrovr/htmd
    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')
예제 #14
0
    def test_production(self):
        from htmd.home import home
        import filecmp
        from htmd.util import tempname
        from glob import glob

        tmpdir = tempname()
        pdbid = "3PTB"

        prod = Acemd("production")
        prod.run = "2000"
        prod.trajectoryperiod = 200
        prod.temperature = 300
        prod.write(
            home(dataDir=os.path.join("test-acemd", pdbid, "equil_out")),
            tmpdir)
        print(tmpdir)
        # Compare with reference
        refdir = home(dataDir=os.path.join("test-acemd", pdbid, "prod"))
        files = [os.path.basename(f) for f in glob(os.path.join(refdir, "*"))]
        match, mismatch, error = filecmp.cmpfiles(refdir,
                                                  tmpdir,
                                                  files,
                                                  shallow=False)

        if len(mismatch) != 0 or len(error) != 0 or len(match) != len(files):
            raise RuntimeError(
                "Different results produced by Acemd production for "
                "test {} between {} and {} in files {}.".format(
                    pdbid, refdir, tmpdir, mismatch))
예제 #15
0
파일: acemd.py 프로젝트: molsim/htmd
    def test_production(self):
        from htmd.home import home
        import filecmp
        from htmd.util import tempname
        from glob import glob

        tmpdir = tempname()
        pdbid = '3PTB'

        prod = Acemd('production')
        prod.run = '2000'
        prod.trajectoryfreq = 200
        prod.temperature = 300
        prod.write(
            home(dataDir=os.path.join('test-acemd', pdbid, 'equil_out')),
            tmpdir)
        print(tmpdir)
        # Compare with reference
        refdir = home(dataDir=os.path.join('test-acemd', pdbid, 'prod'))
        files = [os.path.basename(f) for f in glob(os.path.join(refdir, '*'))]
        match, mismatch, error = filecmp.cmpfiles(refdir,
                                                  tmpdir,
                                                  files,
                                                  shallow=False)

        if len(mismatch) != 0 or len(error) != 0 or len(match) != len(files):
            raise RuntimeError(
                'Different results produced by Acemd production for '
                'test {} between {} and {} in files {}.'.format(
                    pdbid, refdir, tmpdir, mismatch))
예제 #16
0
    def test_equilibration(self):
        from htmd.home import home
        import filecmp
        from htmd.util import tempname
        from glob import glob
        from moleculekit.molecule import Molecule

        tmpdir = tempname()
        pdbid = "3PTB"
        builddir = home(dataDir=os.path.join("test-acemd", pdbid, "build"))

        equil = Acemd("equilibration")
        mol = Molecule(os.path.join(builddir, "structure.pdb"))
        celldim = mol.coords.max(axis=0) - mol.coords.min(axis=0)
        equil.boxsize = " ".join(
            ["{:3.1f}".format(val) for val in celldim.squeeze()])
        equil.run = "2000"
        equil.trajectoryperiod = 200
        equil.temperature = 300

        equil.write(builddir, tmpdir)

        # Compare with reference
        refdir = home(dataDir=os.path.join("test-acemd", pdbid, "equil"))
        files = [os.path.basename(f) for f in glob(os.path.join(refdir, "*"))]
        match, mismatch, error = filecmp.cmpfiles(refdir,
                                                  tmpdir,
                                                  files,
                                                  shallow=False)

        if len(mismatch) != 0 or len(error) != 0 or len(match) != len(files):
            raise RuntimeError(
                "Different results produced by Acemd equilibration for "
                "test {} between {} and {} in files {}.".format(
                    pdbid, refdir, tmpdir, mismatch))
예제 #17
0
파일: acemd.py 프로젝트: alejandrovr/htmd
    def test_equilibration(self):
        from htmd.home import home
        import filecmp
        from htmd.util import tempname
        from glob import glob
        from htmd.molecule.molecule import Molecule

        tmpdir = tempname()
        pdbid = '3PTB'
        builddir = home(dataDir=os.path.join('test-acemd', pdbid, 'build'))

        equil = Acemd('equilibration')
        mol = Molecule(os.path.join(builddir, 'structure.pdb'))
        celldim = mol.coords.max(axis=0) - mol.coords.min(axis=0)
        equil.celldimension = ' '.join(['{:3.1f}'.format(val) for val in celldim.squeeze()])
        equil.run = '2000'
        equil.trajectoryfreq = 200
        equil.temperature = 300

        equil.write(builddir, tmpdir)

        # Compare with reference
        refdir = home(dataDir=os.path.join('test-acemd', pdbid, 'equil'))
        files = [os.path.basename(f) for f in glob(os.path.join(refdir, '*'))]
        match, mismatch, error = filecmp.cmpfiles(refdir, tmpdir, files, shallow=False)

        if len(mismatch) != 0 or len(error) != 0 or len(match) != len(files):
            raise RuntimeError('Different results produced by Acemd equilibration for '
                               'test {} between {} and {} in files {}.'.format(pdbid, refdir, tmpdir, mismatch))
예제 #18
0
파일: acemd.py 프로젝트: molsim/htmd
    def test_equilibration(self):
        from htmd.home import home
        import filecmp
        from htmd.util import tempname
        from glob import glob
        from htmd.molecule.molecule import Molecule

        tmpdir = tempname()
        pdbid = '3PTB'
        builddir = home(dataDir=os.path.join('test-acemd', pdbid, 'build'))

        equil = Acemd('equilibration')
        mol = Molecule(os.path.join(builddir, 'structure.pdb'))
        celldim = mol.coords.max(axis=0) - mol.coords.min(axis=0)
        equil.celldimension = ' '.join(
            ['{:3.1f}'.format(val) for val in celldim.squeeze()])
        equil.run = '2000'
        equil.trajectoryfreq = 200
        equil.temperature = 300

        equil.write(builddir, tmpdir)

        # Compare with reference
        refdir = home(dataDir=os.path.join('test-acemd', pdbid, 'equil'))
        files = [os.path.basename(f) for f in glob(os.path.join(refdir, '*'))]
        match, mismatch, error = filecmp.cmpfiles(refdir,
                                                  tmpdir,
                                                  files,
                                                  shallow=False)

        if len(mismatch) != 0 or len(error) != 0 or len(match) != len(files):
            raise RuntimeError(
                'Different results produced by Acemd equilibration for '
                'test {} between {} and {} in files {}.'.format(
                    pdbid, refdir, tmpdir, mismatch))
예제 #19
0
    def test_customDisulfideBonds(self):
        from htmd.builder.solvate import solvate
        # Test without proteinPrepare
        pdbids = [
            '1GZM',
        ]
        for pid in pdbids:
            np.random.seed(1)
            mol = Molecule(pid)
            mol.filter('protein')
            smol = solvate(mol)
            ffs = defaultFf()
            disu = [['segid 1 and resid 110', 'segid 1 and resid 187'],
                    ['segid 0 and resid 110', 'segid 0 and resid 187']]
            tmpdir = os.path.join(self.testDir, 'withoutProtPrep', pid)
            _ = build(smol, ff=ffs, outdir=tmpdir, disulfide=disu)

            refdir = home(dataDir=join('test-amber-build', 'nopp', pid))
            TestAmberBuild._compareResultFolders(refdir, tmpdir, pid)

            np.random.seed(1)
            tmpdir = os.path.join(self.testDir, 'withoutProtPrep', pid)
            _ = build(smol, ff=ffs, outdir=tmpdir)

            refdir = home(dataDir=join('test-amber-build', 'nopp', pid))
            TestAmberBuild._compareResultFolders(refdir, tmpdir, pid)
예제 #20
0
    def setUpClass(self):
        from htmd.simlist import simlist, simfilter
        from glob import glob
        from htmd.projections.metric import Metric
        from moleculekit.projections.metricdistance import MetricDistance
        from moleculekit.projections.metricdihedral import MetricDihedral
        from moleculekit.util import tempname
        from htmd.home import home
        from os.path import join

        sims = simlist(
            glob(join(home(dataDir="adaptive"), "data", "*", "")),
            glob(join(home(dataDir="adaptive"), "input", "*")),
        )
        fsims = simfilter(sims, tempname(), "not water")

        metr = Metric(fsims)
        metr.set(
            MetricDistance(
                "protein and resid 10 and name CA",
                "resname BEN and noh",
                periodic="selections",
                metric="contacts",
                groupsel1="residue",
                threshold=4,
            )
        )
        self.data1 = metr.project()

        metr.set(MetricDihedral())
        self.data2 = metr.project()
예제 #21
0
    def test_acemd3(self):
        from htmd.util import tempname
        from htmd.home import home
        from glob import glob
        import os

        pd = Production()
        pd.runtime = 4
        pd.timeunits = "ns"
        pd.temperature = 300
        pd.useconstraints = True
        pd.constraints = {
            "protein and name CA": 1,
            "protein and noh and not name CA": 0.1,
        }
        pd.fb_reference = "protein and name CA"
        pd.fb_selection = "resname MOL and noh"
        pd.fb_box = [-21, 21, -19, 19, 29, 30]
        pd.fb_k = 5
        tmpdir = tempname()
        pd.write(
            home(dataDir=os.path.join("test-protocols", "equilibration",
                                      "acemd3", "protLig", "postrun")),
            tmpdir,
        )

        # Compare with reference
        refdir = home(dataDir=os.path.join("test-protocols", "production",
                                           "acemd3", "protLig", "prerun"))
        files = [os.path.basename(f) for f in glob(os.path.join(refdir, "*"))]
        self._compareResultFolders(refdir, tmpdir, "protLig")
예제 #22
0
 def setUp(self):
     self.lfh = sys.stderr
     self.verbose = False
     self.pathPdbxDataFile = os.path.join(home(dataDir='molecule-readers'),
                                          "1kip.cif")
     self.pathBigPdbxDataFile = os.path.join(
         home(dataDir='molecule-readers'), "1ffk.cif")
     self.pathSFDataFile = os.path.join(home(dataDir='molecule-readers'),
                                        "1kip-sf.cif")
예제 #23
0
파일: test.py 프로젝트: jeiros/htmd
    def setUp(self):

        self.h2_074_file = os.path.join(home('test-qm'), 'H2-0.74.mol2')
        self.h2_074 = FFMolecule(self.h2_074_file, method=FFTypeMethod.NONE)

        molFile = os.path.join(home('test-qm'), 'H2-1.00.mol2')
        self.h2_100 = FFMolecule(molFile, method=FFTypeMethod.NONE)

        molFile = os.path.join(home('test-qm'), 'H2O2-90.mol2')
        self.h2o2_90 = FFMolecule(molFile, method=FFTypeMethod.NONE)
예제 #24
0
파일: test.py 프로젝트: prokia/htmd
    def setUp(self):

        molFile = os.path.join(home('test-qm'), 'H2-0.74.mol2')
        self.h2_074 = Molecule(molFile)

        molFile = os.path.join(home('test-qm'), 'H2-1.00.mol2')
        self.h2_100 = Molecule(molFile)

        molFile = os.path.join(home('test-qm'), 'H2O2-90.mol2')
        self.h2o2_90 = Molecule(molFile)
예제 #25
0
파일: test.py 프로젝트: alejandrovr/htmd
    def setUp(self):

        molFile = os.path.join(home('test-qm'), 'H2-0.74.mol2')
        self.h2_074 = Molecule(molFile)

        molFile = os.path.join(home('test-qm'), 'H2-1.00.mol2')
        self.h2_100 = Molecule(molFile)

        molFile = os.path.join(home('test-qm'), 'H2O2-90.mol2')
        self.h2o2_90 = Molecule(molFile)
예제 #26
0
    def setUpClass(self):
        from htmd.molecule.molecule import Molecule
        from os import path
        self.mol = Molecule(
            path.join(home(), 'data', 'metricdistance', 'filtered.pdb'))
        self.mol_skipped = self.mol.copy()

        self.mol.read(path.join(home(), 'data', 'metricdistance', 'traj.xtc'))
        self.mol_skipped.read(path.join(home(), 'data', 'metricdistance',
                                        'traj.xtc'),
                              skip=10)
예제 #27
0
    def test_simlist_auto_structure(self):
        from htmd.home import home
        from htmd.projections.metric import _singleMolfile

        sims = simlist(
            glob(path.join(home(dataDir="adaptive"), "data", "*", "")),
            glob(path.join(home(dataDir="adaptive"), "input", "*")),
        )
        x = sims[0].copy()
        assert x == sims[0]
        assert x != sims[1]
        assert len(sims[0].molfile) == 2
        assert _singleMolfile(sims)[0]
예제 #28
0
파일: util.py 프로젝트: alejandrovr/htmd
    def test_tmscore(self):
        from htmd.molecule.molecule import Molecule
        expectedTMscore = np.array([0.21418524, 0.2367377, 0.23433833, 0.21362964, 0.20935164,
                                    0.20279461, 0.27012895, 0.22675238, 0.21230793, 0.2372011])
        expectedRMSD = np.array([3.70322128, 3.43637027, 3.188193, 3.84455877, 3.53053882,
                                 3.46781854, 2.93777629, 2.97978692, 2.70792428, 2.63051318])

        mol = Molecule(os.path.join(home(dataDir='tmscore'), 'filtered.pdb'))
        mol.read(os.path.join(home(dataDir='tmscore'), 'traj.xtc'))
        ref = Molecule(os.path.join(home(dataDir='tmscore'), 'ntl9_2hbb.pdb'))
        tmscore, rmsd = molTMscore(mol, ref, mol.atomselect('protein'), ref.atomselect('protein'))

        self.assertTrue(np.allclose(tmscore, expectedTMscore))
        self.assertTrue(np.allclose(rmsd, expectedRMSD))
예제 #29
0
    def test_simlist_single_structure(self):
        from htmd.home import home
        from htmd.projections.metric import _singleMolfile

        sims = simlist(
            glob(path.join(home(dataDir="adaptive"), "data", "*", "")),
            path.join(home(dataDir="adaptive"), "input", "e1s1_1",
                      "structure.pdb"),
        )
        x = sims[0].copy()
        assert x == sims[0]
        assert x != sims[1]
        assert not isinstance(sims[0].molfile, list)
        assert _singleMolfile(sims)[0]
예제 #30
0
    def test_customDisulfideBonds(self):
        from htmd.molecule.molecule import Molecule
        from htmd.builder.solvate import solvate
        from htmd.home import home
        from htmd.util import tempname, assertSameAsReferenceDir
        import os
        import numpy as np

        # Use pre-prepared files so we can tell whether the error is in prepare or in build
        # Inputs are reference outputs of proteinprepare.
        preparedInputDir = home(dataDir='test-proteinprepare')

        pdb = '1GZM'
        inFile = os.path.join(preparedInputDir, pdb,
                              "{}-prepared.pdb".format(pdb))
        mol = Molecule(inFile)
        mol.filter('protein')  # Fix for bad proteinPrepare hydrogen placing

        np.random.seed(1)  # Needed for ions
        smol = solvate(mol)
        topos = ['top/top_all36_prot.rtf', 'top/top_water_ions.rtf']
        params = ['par/par_all36_prot_mod.prm', 'par/par_water_ions.prm']
        disu = [['segid 1 and resid 110', 'segid 1 and resid 187'],
                ['segid 0 and resid 110', 'segid 0 and resid 187']]
        tmpdir = tempname()
        _ = build(smol,
                  topo=topos,
                  param=params,
                  outdir=tmpdir,
                  disulfide=disu)

        compareDir = home(dataDir=os.path.join('test-charmm-build', pdb))
        assertSameAsReferenceDir(compareDir, tmpdir)

        # TODO: Remove this after deprecation
        from htmd.builder.builder import DisulfideBridge
        np.random.seed(1)  # Needed for ions
        disu = [
            DisulfideBridge('1', 110, '1', 187),
            DisulfideBridge('0', 110, '0', 187)
        ]
        tmpdir = tempname()
        _ = build(smol,
                  topo=topos,
                  param=params,
                  outdir=tmpdir,
                  disulfide=disu)
        compareDir = home(dataDir=os.path.join('test-charmm-build', pdb))
        assertSameAsReferenceDir(compareDir, tmpdir)
예제 #31
0
파일: latest.py 프로젝트: leelasd/htmd
def compareVersions():
    from htmd.home import home
    from htmd.version import version
    from natsort import natsorted
    import os
    import time
    #t = time.time()
    __file = os.path.join(home(), '.latestversion')

    if not os.path.isfile(__file) or time.time() > os.path.getmtime(
            __file
    ) + 86400:  #86400:  # Check if one day has passed since last version check
        _writeLatestVersionFile(__file)

    f = open(__file, 'r')
    latestver = f.read()
    f.close()
    currver = version()
    if currver != 'unpackaged' and natsorted(
        (latestver, currver))[1] != currver:
        print(
            'New HTMD version ({}) is available. You are currently on ({}). Use \'conda update htmd\' to update to the new version.'
            .format(latestver, currver))
    else:
        print('You are on the latest HTMD version ({}).'.format(currver))
예제 #32
0
def listFiles():
    """ Lists all available AMBER forcefield files
    """
    try:
        tleap = check_output(['which', 'tleap'],
                             stderr=DEVNULL).decode('UTF-8').rstrip('\n')
    except:
        raise NameError(
            'tleap not found. You should either have AmberTools or ambermini installed '
            '(to install ambermini do: conda install ambermini)')

    amberhome = path.normpath(path.join(path.dirname(tleap), '../'))

    # Original AMBER FFs
    amberdir = path.join(amberhome, 'dat', 'leap', 'cmd')
    ffs = [
        f for f in os.listdir(amberdir) if path.isfile(path.join(amberdir, f))
    ]
    print('---- Forcefield files list: ' + path.join(amberdir, '') + ' ----')
    for f in ffs:
        print(f)
    # Extra AMBER FFs on HTMD
    htmdamberdir = path.join(home(), 'builder', 'amberfiles', '')
    extraffs = [
        f + '/' +
        path.basename(glob(os.path.join(htmdamberdir, f) + '/leaprc.*')[0])
        for f in os.listdir(htmdamberdir)
        if os.path.isdir(os.path.join(htmdamberdir, f))
        and len(glob(os.path.join(htmdamberdir, f) + '/leaprc.*')) == 1
    ]
    print('---- Extra forcefield files list: ' + path.join(htmdamberdir, '') +
          ' ----')
    for f in extraffs:
        print(f)
예제 #33
0
파일: amber.py 프로젝트: alejandrovr/htmd
def _locateFile(fname, type, tleap):
    amberhome = os.path.normpath(os.path.join(os.path.dirname(tleap), '../'))
    htmdamberdir = os.path.abspath(os.path.join(home(), 'builder', 'amberfiles', ''))
    if type == 'topo':
        topodir = os.path.join(amberhome, 'dat', 'leap', 'prep')
        foundfile = glob(os.path.join(topodir, fname))
        if len(foundfile) != 0:
            return foundfile[0]
        foundfile = glob(os.path.join(htmdamberdir, fname))
        if len(foundfile) != 0:
            return foundfile[0]
        logger.warning('Was not able to find topology file {}'.format(fname))
    elif type == 'param':
        parmdir = os.path.join(amberhome, 'dat', 'leap', 'parm')
        foundfile = glob(os.path.join(parmdir, fname))
        if len(foundfile) != 0:
            return foundfile[0]
        foundfile = glob(os.path.join(htmdamberdir, fname))
        if len(foundfile) != 0:
            return foundfile[0]
        logger.warning('Was not able to find parameter file {}'.format(fname))
    elif type == 'ff':
        ffdir = os.path.join(amberhome, 'dat', 'leap', 'cmd')
        foundfile = glob(os.path.join(ffdir, fname))
        if len(foundfile) != 0:
            return foundfile[0]
        foundfile = glob(os.path.join(htmdamberdir, fname))
        if len(foundfile) != 0:
            return foundfile[0]
        logger.warning('Was not able to find forcefield file {}'.format(fname))
예제 #34
0
파일: charmm.py 프로젝트: jeiros/htmd
def listFiles():
    """ Lists all available Charmm topologies and parameter files

    Examples
    --------
    >>> from htmd.builder import charmm
    >>> charmm.listFiles()             # doctest: +ELLIPSIS
    ---- Topologies files list...

    """
    from natsort import natsorted
    charmmdir = path.join(home(), 'builder', 'charmmfiles', '')  # maybe just lookup current module?
    topos = natsorted(glob(path.join(charmmdir, 'top', '*.rtf')))
    params = natsorted(glob(path.join(charmmdir, 'par', '*.prm')))
    streams = natsorted(glob(path.join(charmmdir, 'str', '*', '*.str')))
    print('---- Topologies files list: ' + path.join(charmmdir, 'top', '') + ' ----')
    for t in topos:
        t = t.replace(charmmdir, '')
        print(t)
    print('---- Parameters files list: ' + path.join(charmmdir, 'par', '') + ' ----')
    for p in params:
        p = p.replace(charmmdir, '')
        print(p)
    print('---- Stream files list: ' + path.join(charmmdir, 'str', '') + ' ----')
    for s in streams:
        s = s.replace(charmmdir, '')
        print(s)
예제 #35
0
def _locateFile(fname, type, tleap):
    amberhome = os.path.normpath(os.path.join(os.path.dirname(tleap), '../'))
    htmdamberdir = os.path.abspath(
        os.path.join(home(), 'builder', 'amberfiles', ''))
    if type == 'topo':
        topodir = os.path.join(amberhome, 'dat', 'leap', 'prep')
        foundfile = glob(os.path.join(topodir, fname))
        if len(foundfile) != 0:
            return foundfile[0]
        foundfile = glob(os.path.join(htmdamberdir, fname))
        if len(foundfile) != 0:
            return foundfile[0]
        logger.warning('Was not able to find topology file {}'.format(fname))
    elif type == 'param':
        parmdir = os.path.join(amberhome, 'dat', 'leap', 'parm')
        foundfile = glob(os.path.join(parmdir, fname))
        if len(foundfile) != 0:
            return foundfile[0]
        foundfile = glob(os.path.join(htmdamberdir, fname))
        if len(foundfile) != 0:
            return foundfile[0]
        logger.warning('Was not able to find parameter file {}'.format(fname))
    elif type == 'ff':
        ffdir = os.path.join(amberhome, 'dat', 'leap', 'cmd')
        foundfile = glob(os.path.join(ffdir, fname))
        if len(foundfile) != 0:
            return foundfile[0]
        foundfile = glob(os.path.join(htmdamberdir, fname))
        if len(foundfile) != 0:
            return foundfile[0]
        logger.warning('Was not able to find forcefield file {}'.format(fname))
예제 #36
0
파일: test.py 프로젝트: tonigi/htmd
    def setUp(self):

        self.maxDiff = None
        self.dataDir = home(dataDir='test-param')

        if os.environ.get('TRAVIS_OS_NAME') == 'osx':
            self.skipTest('Mac does not work!')
예제 #37
0
파일: license.py 프로젝트: Acellera/htmd
def licenseEntitlements():
    libdir = home(libDir=True)

    # No liblicense.so for OS X yet. Need to buy it
    if platform.system() == "Darwin":
        return dict()

    if platform.system() == "Windows":
        cdll.LoadLibrary(os.path.join(libdir, "libgcc_s_seh-1.dll"))
        if os.path.exists(os.path.join(libdir, "psprolib.dll")):
            cdll.LoadLibrary(os.path.join(libdir, "psprolib.dll"))

    lib = cdll.LoadLibrary(os.path.join(libdir, "liblicense.so"))
    arg1 = create_string_buffer(2048)
    arg2 = c_int(2048)
    lib.license_check(arg1, arg2)
    val = (arg1.value.decode("utf-8")).split(":")

    toks = dict()
    for v in val:
        x = v.split("-")
        if len(x) > 1:
            if x[0] not in toks:
                toks[x[0]] = dict()
            if (x[1] not in toks[x[0]]):
                toks[x[0]][x[1]] = 0
            try:
                toks[x[0]][x[1]] = toks[x[0]][x[1]] + int(x[2])
            except:
                pass
    return toks
예제 #38
0
    def test_run_water(self):
        from htmd.util import tempname
        from htmd.home import home
        from glob import glob
        from subprocess import check_output
        import subprocess
        import shutil
        import os

        acemd3exe = shutil.which('acemd3', mode=os.X_OK)
        if not acemd3exe:
            raise NameError('Could not find acemd3, or no execute permissions are given')

        for system in ['amber-equil-completed', 'charmm-equil-completed']:
            pd = Production(_version=3)
            pd.runtime = 5
            pd.timeunits = 'steps'
            pd.temperature = 300
            pd.constraints = {}
            # Set these down for tiny box size of water
            pd.acemd.cutoff = 3
            pd.acemd.switchdistance = 2
            ######
            tmpdir = tempname()
            pd.write(home(dataDir=os.path.join('test-acemd', 'tiny-water', system)), tmpdir)
            try:
                res = check_output(['acemd3', '--platform', 'CPU', os.getenv('ACE3ARG')], cwd=tmpdir)
            except subprocess.CalledProcessError as exc:
                assert False, f'Failed to run due to error: {exc}\n\n ---> Error log:\n\n{exc.output.decode("ascii")}'
            res = res.decode('utf-8').strip()
            print(res)
            assert res.endswith('Completed simulation!'), 'Failed at system ' + system
예제 #39
0
    def _run(self, molName):

        self.molName = molName

        logger.info('Molecule: {}'.format(self.molName))

        molFile = os.path.join(home('test-charge'), self.molName + '.mol2')
        self.mol = Molecule(molFile)

        self.new_mols = {}
        self.extras = {}

        self.new_mols['Gasteiger'] = fitGasteigerCharges(self.mol)
        try:
            self.new_mols['AM1-BCC'] = fitChargesWithAntechamber(self.mol, type='bcc')
        except:
            pass

        qm = Psi4()
        qm.theory = 'B3LYP'
        qm.basis = '6-311++G**'

        workDir = os.path.join('tmp', self.molName)
        os.makedirs(workDir, exist_ok=True)

        for factor in [-10, -5, -4, -3, -2, -1]:
            logger.info('Factor: {}'.format(factor))
            key = 'ESP b {}'.format(factor)
            np.random.seed(20181114)  # Make ESP grid generation deterministic
            self.new_mols[key], self.extras[key] = fitESPCharges(self.mol, qm, workDir, restraint_factor=10**factor)
예제 #40
0
def listFiles():
    """ Lists all available Charmm topologies and parameter files

    Examples
    --------
    >>> from htmd.builder import charmm
    >>> charmm.listFiles()             # doctest: +ELLIPSIS
    ---- Topologies files list...

    """
    from natsort import natsorted
    charmmdir = path.join(home(), 'builder', 'charmmfiles',
                          '')  # maybe just lookup current module?
    topos = natsorted(glob(path.join(charmmdir, 'top', '*.rtf')))
    params = natsorted(glob(path.join(charmmdir, 'par', '*.prm')))
    streams = natsorted(glob(path.join(charmmdir, 'str', '*', '*.str')))
    print('---- Topologies files list: ' + path.join(charmmdir, 'top', '') +
          ' ----')
    for t in topos:
        t = t.replace(charmmdir, '')
        print(t)
    print('---- Parameters files list: ' + path.join(charmmdir, 'par', '') +
          ' ----')
    for p in params:
        p = p.replace(charmmdir, '')
        print(p)
    print('---- Stream files list: ' + path.join(charmmdir, 'str', '') +
          ' ----')
    for s in streams:
        s = s.replace(charmmdir, '')
        print(s)
예제 #41
0
    def test_project_align(self):
        from htmd.molecule.molecule import Molecule
        from htmd.home import home
        from os import path
        mol = Molecule(path.join(home(), 'data', 'metricdistance', 'filtered.pdb'))
        mol.read(path.join(home(), 'data', 'metricdistance', 'traj.xtc'))
        ref = mol.copy()
        ref.coords = np.atleast_3d(ref.coords[:, :, 0])
        metr = MetricCoordinate('protein and name CA', ref)
        data = metr.project(mol)

        lastcoors = np.array([6.79283285, 5.55226946, 4.49387407, 2.94484425,
                              5.36937141, 3.18590879, 5.75874281, 5.48864174,
                              1.69625032, 1.58790839, 0.57877392, -2.66498065,
                              -3.70919156, -3.33702421, -5.38465405, -8.43286991,
                              -8.15859032, -7.85062265, -10.92551327, -13.70733166], dtype=np.float32)
        assert np.all(np.abs(data[-1, -20:] - lastcoors) < 0.001), 'Coordinates calculation is broken'
예제 #42
0
    def test_project(self):
        from htmd.molecule.molecule import Molecule
        from htmd.home import home
        from os import path
        mol = Molecule(path.join(home(), 'data', 'metricdistance', 'filtered.pdb'))
        mol.read(path.join(home(), 'data', 'metricdistance', 'traj.xtc'))
        ref = mol.copy()
        ref.coords = np.atleast_3d(ref.coords[:, :, 0])
        metr = MetricCoordinate('protein and name CA')
        data = metr.project(mol)

        lastcoors = np.array([-24.77000237, -27.76000023, -30.44000244, -33.65000153,
                              -33.40999985, -36.32000351, -36.02000427, -36.38000107,
                              -39.61000061, -41.01000214, -43.80000305, -45.56000137,
                              -45.36000061, -47.13000488, -49.54000473, -50.6000061 ,
                              -50.11000061, -52.15999985, -55.1400032 , -55.73000336], dtype=np.float32)
        assert np.all(np.abs(data[-1, -20:] - lastcoors) < 0.001), 'Coordinates calculation is broken'
예제 #43
0
파일: util.py 프로젝트: Acellera/htmd
def pp_calcMinDistances(mol, sel1, sel2, metric='distances', threshold=8, pbc=True, gap=1, truncate=None):
    import os
    import ctypes
    from htmd.home import home

    # Converting non-grouped boolean atomselection to group-style atomselections
    if np.ndim(sel1) != 2:
        sel1idx = tuple(np.where(sel1)[0])
        sel1 = np.zeros((len(sel1idx), len(sel1)), dtype=bool)
        sel1[range(sel1.shape[0]), sel1idx] = True
    if np.ndim(sel2) != 2:
        sel2idx = tuple(np.where(sel2)[0])
        sel2 = np.zeros((len(sel2idx), len(sel2)), dtype=bool)
        sel2[range(sel2.shape[0]), sel2idx] = True

    box = np.array([0, 0, 0], dtype=np.float32)
    if pbc:
        if mol.box is None or np.sum(mol.box) == 0:
            raise NameError('No periodic box dimensions given in the molecule/trajectory. '
                            'If you want to calculate distance without wrapping, set the pbc option to False')
        box = mol.box[:, 0]  # TODO: make it work for varying box size
        if np.max(mol.box.T - mol.box[:, 0]) != 0:
            raise NameError('Different box sizes per frame. Still unsupported by mindist. Contact Stefan Doerr.')

    coords = mol.coords

    # Converting from 2D boolean atomselect array to 2D int array where each row starts with the indexes of the boolean
    groups1 = np.ones((sel1.shape[0], mol.numAtoms), dtype=np.int32) * -1
    groups2 = np.ones((sel2.shape[0], mol.numAtoms), dtype=np.int32) * -1
    for i in range(sel1.shape[0]):
        idx = np.where(sel1[i, :])[0]
        groups1[i, 0:len(idx)] = idx
    for i in range(sel2.shape[0]):
        idx = np.where(sel2[i, :])[0]
        groups2[i, 0:len(idx)] = idx

    # Running the actual calculations
    lib = ctypes.cdll.LoadLibrary(os.path.join(home(libDir=True), 'mindist_ext.so'))
    mindist = np.zeros((mol.numFrames, len(groups1) * len(groups2)), dtype=np.float32)  # Preparing the return array
    lib.mindist_trajectory(coords.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
                           box.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
                           groups1.ctypes.data_as(ctypes.POINTER(ctypes.c_int)),
                           groups2.ctypes.data_as(ctypes.POINTER(ctypes.c_int)),
                           ctypes.c_int(len(groups1)),
                           ctypes.c_int(len(groups2)),
                           ctypes.c_int(mol.numAtoms),
                           ctypes.c_int(mol.numFrames),
                           ctypes.c_int(int(pbc)),
                           mindist.ctypes.data_as(ctypes.POINTER(ctypes.c_float)))

    if metric == 'contacts':
        mindist = mindist <= threshold
    elif metric == 'distances':
        mindist = mindist.astype(dtype=np.float32)
    else:
        raise NameError('The metric you asked for is not supported. Check spelling and documentation')
    return mindist
예제 #44
0
파일: esp.py 프로젝트: jeiros/htmd
    def setUp(self):

        from htmd.home import home
        from htmd.parameterization.ffmolecule import FFMolecule, FFTypeMethod

        molFile = os.path.join(home('test-param'), 'H2O2.mol2')
        self.mol = FFMolecule(molFile, method=FFTypeMethod.GAFF2)
        self.esp = ESP()
        self.esp.molecule = self.mol
예제 #45
0
파일: dihedral.py 프로젝트: jeiros/htmd
    def test_getEquivalentDihedrals(self):

        from htmd.home import home
        from htmd.parameterization.ffmolecule import FFMolecule, FFTypeMethod

        molFile = os.path.join(home('test-param'), 'glycol.mol2')
        self.df.molecule = FFMolecule(molFile, method=FFTypeMethod.GAFF2)

        self.assertListEqual(self.df._getEquivalentDihedrals([0, 1, 2, 3]), [[0, 1, 2, 3]])
        self.assertListEqual(self.df._getEquivalentDihedrals([4, 0, 1, 2]), [[4, 0, 1, 2]])
        self.assertListEqual(self.df._getEquivalentDihedrals([5, 1, 2, 7]), [[5, 1, 2, 7]])
예제 #46
0
파일: util.py 프로젝트: alejandrovr/htmd
    def test_guessAnglesDihedrals(self):
        from htmd.home import home
        from htmd.molecule.molecule import Molecule

        mol = Molecule(os.path.join(home(dataDir='test-molecule-utils'), 'NH4.pdb'))
        angles, dihedrals = guessAnglesAndDihedrals(mol.bonds)

        self.assertTrue(angles.dtype == np.uint32, 'Returned wrong dtype for angles')
        self.assertTrue(dihedrals.dtype == np.uint32, 'Returned wrong dtype for dihedrals')
        self.assertTrue(np.all(angles.shape == (6, 3)), 'Returned wrong number of angles')
        self.assertTrue(np.all(dihedrals.shape == (0, 4)), 'Returned wrong number of dihedrals')
예제 #47
0
파일: test.py 프로젝트: jeiros/htmd
    def setUp(self):
        if os.environ.get('TRAVIS_OS_NAME') == 'osx':
            self.skipTest('Mac does not work!')

        self.maxDiff = None
        self.dataDir = home(dataDir='test-param')
        if os.environ.get('TESTDIR') is not None:
            self.testDir = os.environ['TESTDIR']
        else:
            self.testDir = tempname()
        print('Test dir: {}'.format(self.testDir))
예제 #48
0
    def test_maximalSubstructureAlignment(self):
        from htmd.home import home
        from htmd.molecule.molecule import Molecule

        path = home(dataDir='test-molecule-graphalignment')
        ref_lig = Molecule(os.path.join(path, 'ref_lig.pdb'))
        lig2align = Molecule(os.path.join(path, 'lig2align.pdb'))
        lig_aligned = maximalSubstructureAlignment(ref_lig, lig2align)
        lig_reference = Molecule(os.path.join(path, 'lig_aligned.pdb'))

        self.assertTrue(np.allclose(lig_aligned.coords, lig_reference.coords, rtol=1e-4),
                        'maximalSubstructureAlignment produced different coords')
예제 #49
0
파일: acemd.py 프로젝트: alejandrovr/htmd
    def test_production(self):
        from htmd.home import home
        import filecmp
        from htmd.util import tempname
        from glob import glob

        tmpdir = tempname()
        pdbid = '3PTB'

        prod = Acemd('production')
        prod.run = '2000'
        prod.trajectoryfreq = 200
        prod.temperature = 300
        prod.write(home(dataDir=os.path.join('test-acemd', pdbid, 'equil_out')), tmpdir)
        print(tmpdir)
        # Compare with reference
        refdir = home(dataDir=os.path.join('test-acemd', pdbid, 'prod'))
        files = [os.path.basename(f) for f in glob(os.path.join(refdir, '*'))]
        match, mismatch, error = filecmp.cmpfiles(refdir, tmpdir, files, shallow=False)

        if len(mismatch) != 0 or len(error) != 0 or len(match) != len(files):
            raise RuntimeError('Different results produced by Acemd production for '
                               'test {} between {} and {} in files {}.'.format(pdbid, refdir, tmpdir, mismatch))
예제 #50
0
파일: charmm.py 프로젝트: alejandrovr/htmd
    def test_customDisulfideBonds(self):
        from htmd.molecule.molecule import Molecule
        from htmd.builder.solvate import solvate
        from htmd.home import home
        from htmd.util import tempname, assertSameAsReferenceDir
        import os
        import numpy as np

        # Use pre-prepared files so we can tell whether the error is in prepare or in build
        # Inputs are reference outputs of proteinprepare.
        preparedInputDir = home(dataDir='test-proteinprepare')

        pdb = '1GZM'
        inFile = os.path.join(preparedInputDir, pdb, "{}-prepared.pdb".format(pdb))
        mol = Molecule(inFile)
        mol.filter('protein')  # Fix for bad proteinPrepare hydrogen placing

        np.random.seed(1)  # Needed for ions
        smol = solvate(mol)
        topos = ['top/top_all36_prot.rtf', 'top/top_water_ions.rtf']
        params = ['par/par_all36_prot_mod.prm', 'par/par_water_ions.prm']
        disu = [['segid 1 and resid 110', 'segid 1 and resid 187'], ['segid 0 and resid 110', 'segid 0 and resid 187']]
        tmpdir = tempname()
        _ = build(smol, topo=topos, param=params, outdir=tmpdir, disulfide=disu)

        compareDir = home(dataDir=os.path.join('test-charmm-build', pdb))
        assertSameAsReferenceDir(compareDir, tmpdir)

        # TODO: Remove this after deprecation
        from htmd.builder.builder import DisulfideBridge
        np.random.seed(1)  # Needed for ions
        disu = [DisulfideBridge('1', 110, '1', 187), DisulfideBridge('0', 110, '0', 187)]
        tmpdir = tempname()
        _ = build(smol, topo=topos, param=params, outdir=tmpdir, disulfide=disu)
        compareDir = home(dataDir=os.path.join('test-charmm-build', pdb))
        assertSameAsReferenceDir(compareDir, tmpdir)
예제 #51
0
파일: amber.py 프로젝트: alejandrovr/htmd
    def test_customDisulfideBonds(self):
        from htmd.builder.solvate import solvate
        # Test without proteinPrepare
        pdbids = ['1GZM', ]
        for pid in pdbids:
            np.random.seed(1)
            mol = Molecule(pid)
            mol.filter('protein')
            smol = solvate(mol)
            ffs = defaultFf()
            disu = [['segid 1 and resid 110', 'segid 1 and resid 187'],
                    ['segid 0 and resid 110', 'segid 0 and resid 187']]
            tmpdir = os.path.join(self.testDir, 'withoutProtPrep', pid)
            _ = build(smol, ff=ffs, outdir=tmpdir, disulfide=disu)

            refdir = home(dataDir=join('test-amber-build', 'nopp', pid))
            TestAmberBuild._compareResultFolders(refdir, tmpdir, pid)

            np.random.seed(1)
            tmpdir = os.path.join(self.testDir, 'withoutProtPrep', pid)
            _ = build(smol, ff=ffs, outdir=tmpdir)

            refdir = home(dataDir=join('test-amber-build', 'nopp', pid))
            TestAmberBuild._compareResultFolders(refdir, tmpdir, pid)
예제 #52
0
파일: charmm.py 프로젝트: jeiros/htmd
def search(key, name):
    """ Searches for CHARMM files containing a given definition.

    Parameters
    ----------
    key : str
        A key
    name : str
        The corresponding name
        
    Examples
    --------
    >>> charmm.search(key='RESI', name = 'CHL1')  # doctest: +SKIP
    """
    charmmdir = path.join(home(), 'builder', 'charmmfiles', '')
    os.system('find {} -type f -exec grep -n "{} {}" {{}} +'.format(charmmdir, key, name))
예제 #53
0
파일: esp.py 프로젝트: alejandrovr/htmd
    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]
예제 #54
0
파일: amber.py 프로젝트: alejandrovr/htmd
    def testWithoutProteinPrepare(self):
        from htmd.builder.solvate import solvate
        # Test without proteinPrepare
        pdbids = ['3PTB']
        # pdbids = ['3PTB', '1A25', '1GZM', '1U5U']
        for pid in pdbids:
            np.random.seed(1)
            mol = Molecule(pid)
            mol.filter('protein')
            smol = solvate(mol)
            ffs = defaultFf()
            tmpdir = os.path.join(self.testDir, 'withoutProtPrep', pid)
            _ = build(smol, ff=ffs, outdir=tmpdir)

            refdir = home(dataDir=join('test-amber-build', 'nopp', pid))
            TestAmberBuild._compareResultFolders(refdir, tmpdir, pid)
예제 #55
0
파일: acemd.py 프로젝트: alejandrovr/htmd
    def readConfig(self, configfile):
        import json

        if not os.path.exists(configfile):
            from htmd.home import home
            configfile = os.path.join(home(), 'mdengine', 'acemd', 'config', '{}.json'.format(configfile))

        with open(configfile, 'r') as f:
            config = json.load(f)

        for key in config:
            if key == 'restraints':
                self.restraints = []
                for restr in ensurelist(config[key]['value']):
                    self.restraints.append(_Restraint._fromDict(restr))
            else:
                setattr(self, key, config[key]['value'])
예제 #56
0
파일: charmm.py 프로젝트: PabloHN/htmd
def listFiles():
    """ Lists all available Charmm topologies and parameter files
    """
    charmmdir = path.join(home(), 'builder', 'charmmfiles', '')  # maybe just lookup current module?
    topos = natsorted(glob(path.join(charmmdir, 'top', '*.rtf')))
    params = natsorted(glob(path.join(charmmdir, 'par', '*.prm')))
    streams = natsorted(glob(path.join(charmmdir, 'str', '*', '*.str')))
    print('---- Topologies files list: ' + path.join(charmmdir, 'top', '') + ' ----')
    for t in topos:
        t = t.replace(charmmdir, '')
        print(t)
    print('---- Parameters files list: ' + path.join(charmmdir, 'par', '') + ' ----')
    for p in params:
        p = p.replace(charmmdir, '')
        print(p)
    print('---- Stream files list: ' + path.join(charmmdir, 'str', '') + ' ----')
    for s in streams:
        s = s.replace(charmmdir, '')
        print(s)
예제 #57
0
파일: amber.py 프로젝트: alejandrovr/htmd
    def testWithProteinPrepare(self):
        from htmd.builder.preparation import proteinPrepare
        from htmd.builder.solvate import solvate
        # Test with proteinPrepare
        pdbids = ['3PTB']
        # pdbids = ['3PTB', '1A25', '1GZM']  # '1U5U' out because it has AR0 (no parameters)
        for pid in pdbids:
            np.random.seed(1)
            mol = Molecule(pid)
            mol.filter('protein')
            mol = proteinPrepare(mol)
            mol.filter('protein')  # Fix for bad proteinPrepare hydrogen placing
            smol = solvate(mol)
            ffs = defaultFf()
            tmpdir = os.path.join(self.testDir, 'withProtPrep', pid)
            _ = build(smol, ff=ffs, outdir=tmpdir)

            refdir = home(dataDir=join('test-amber-build', 'pp', pid))
            TestAmberBuild._compareResultFolders(refdir, tmpdir, pid)
예제 #58
0
파일: readers.py 프로젝트: jeiros/htmd
def _getPDB(pdbid):
    import requests
    from htmd.molecule.support import string_to_tempfile
    from htmd.home import home
    # Try loading it from the pdb data directory
    tempfile = False
    localpdb = os.path.join(home(dataDir='pdb'), pdbid.lower() + '.pdb')
    if os.path.isfile(localpdb):
        logger.info('Using local copy for {:s}: {:s}'.format(pdbid, localpdb))
        filepath = localpdb
    else:
        # or the PDB website
        logger.info('Attempting PDB query for {:s}'.format(pdbid))
        r = requests.get('https://files.rcsb.org/download/{}.pdb'.format(pdbid))
        if r.status_code == 200:
            filepath = string_to_tempfile(r.content.decode('ascii'), 'pdb')
            tempfile = True
        else:
            raise NameError('Invalid PDB code')
    return filepath, tempfile
예제 #59
0
def listLipids():
    """ Lists all available lipids

    Examples
    --------
    >>> from htmd.membranebuilder.build_membrane import buildMembrane 
    >>> build_membrane.listLipids()
    ---- Lipids list: ...

    """

    from htmd.home import home
    import os
    from natsort import natsorted

    membranebuilderhome = os.path.join( home(), 'membranebuilder', 'lipids', '' )
    lipids = natsorted(glob( os.path.join(membranebuilderhome, '*')))
    print('---- Lipids list: ' + membranebuilderhome + ' ----')
    for l in lipids:
        l = os.path.basename(l)
        print('- ', l)
예제 #60
0
파일: amber.py 프로젝트: Acellera/htmd
def listFiles():
    """ Lists all available AMBER forcefield files
    """
    tleap = shutil.which("tleap")
    if not tleap:
        raise NameError('tleap not found. You should either have AmberTools or ambermini installed '
                        '(to install ambermini do: conda install ambermini -c acellera)')

    amberhome = path.normpath(path.join(path.dirname(tleap), '../'))

    # Original AMBER FFs
    amberdir = path.join(amberhome, 'dat', 'leap', 'cmd')
    ffs = [f for f in os.listdir(amberdir) if path.isfile(path.join(amberdir, f))]
    print('---- Forcefield files list: ' + path.join(amberdir, '') + ' ----')
    for f in ffs:
        print(f)

    amberdir = path.join(amberhome, 'dat', 'leap', 'cmd', 'oldff')
    ffs = [f for f in os.listdir(amberdir) if path.isfile(path.join(amberdir, f))]
    print('---- OLD Forcefield files list: ' + path.join(amberdir, '') + ' ----')
    for f in ffs:
        print(f)

    # FRCMOD files
    frcmoddir = path.join(amberhome, 'dat', 'leap', 'parm')
    ffs = glob(frcmoddir+"/frcmod.*")
    print('---- Parameter files list: ' + path.join(frcmoddir, '') + ' ----')
    for f in ffs:
        print(path.basename(f))

    # Extra AMBER FFs on HTMD
    htmdamberdir = path.abspath(path.join(home(), 'builder', 'amberfiles', ''))
    extraffs = [f + '/' + path.basename(glob(os.path.join(htmdamberdir, f) + '/leaprc.*')[0])
                for f in os.listdir(htmdamberdir) if os.path.isdir(os.path.join(htmdamberdir, f))
                and len(glob(os.path.join(htmdamberdir, f) + '/leaprc.*')) == 1]
    print('---- Extra forcefield files list: ' + path.join(htmdamberdir, '') + ' ----')
    for f in extraffs:
        print(f)