예제 #1
0
파일: latest.py 프로젝트: Acellera/htmd
def compareVersions():
    from htmd.version import version
    from natsort import natsorted
    import os
    import time
    #t = time.time()
    from os.path import expanduser
    __home = expanduser("~")
    __htmdconf = os.path.join(__home, '.htmd')
    if not os.path.exists(__htmdconf):
        try:
            os.makedirs(__htmdconf)
        except:
            print('Unable to create {} folder. Will not check for new HTMD versions.'.format(__htmdconf))
            return
    __file = os.path.join(__htmdconf, '.latestversion')

    # Check if one day has passed since last version check. If yes, get new version and write to file
    if not os.path.isfile(__file) or time.time() > os.path.getmtime(__file) + 86400:
        _writeLatestVersionFile(__file)

    try:
        f = open(__file, 'r')
    except:
        print('Unable to open {} file for reading. Will not check for new HTMD versions.'.format(__file))
        return
    latestversions = f.readlines()
    f.close()

    currver = version()
    if currver != 'unpackaged' and len(latestversions) == 2:  # Supporting users which still haven't passed the one day limit. Can remove in next
        if _is_stable(currver):
            latest = latestversions[0].strip()
            verstring = 'stable'
        else:
            latest = latestversions[1].strip()
            verstring = 'devel'
    elif len(latestversions) == 1:  # Supporting users which still haven't passed the one day limit. Can remove in next version
        latest = latestversions[0].strip()
        verstring = ''
    elif currver == 'unpackaged':
        pass
    else:
        return

    if currver != 'unpackaged' and natsorted((latest, currver))[1] != currver:
        print('New {} HTMD version ({}) is available. You are currently on ({}). Use \'conda update -c acellera htmd\' to '
              'update to the new version.'.format(verstring, latest, currver))
    else:
        if currver != 'unpackaged':
            print('You are on the latest HTMD version ({}).'.format(currver))
        else:
            from htmd import home
            print('You are on the latest HTMD version ({} : {}).'.format(currver, home()))

    print("")
예제 #2
0
파일: support.py 프로젝트: Acellera/htmd
def xtc_lib():
    lib = {}
    libdir = htmd.home(libDir=True)

    import platform
    if platform.system() == "Windows":
        lib['libc'] = ct.cdll.msvcrt
        ct.cdll.LoadLibrary(os.path.join(libdir, "libgcc_s_seh-1.dll"))
        if os.path.exists(os.path.join(libdir, "psprolib.dll")):
            ct.cdll.LoadLibrary(os.path.join(libdir, "psprolib.dll"))
    else:
        # lib['libc'] = cdll.LoadLibrary("libc.so.6")
        lib['libc'] = ct.cdll.LoadLibrary("libc.{}".format("so.6" if platform.uname()[0] != "Darwin" else "dylib"))

    lib['libxtc'] = ct.cdll.LoadLibrary(os.path.join(libdir, "libxtc.so"))
    return lib
예제 #3
0
def xtc_lib():
    lib = {}
    libdir = htmd.home(libDir=True)

    import platform
    if platform.system() == "Windows":
        lib['libc'] = ct.cdll.msvcrt
        ct.cdll.LoadLibrary(os.path.join(libdir, "libgcc_s_seh-1.dll"))
        if os.path.exists(os.path.join(libdir, "psprolib.dll")):
            ct.cdll.LoadLibrary(os.path.join(libdir, "psprolib.dll"))
    else:
        # lib['libc'] = cdll.LoadLibrary("libc.so.6")
        lib['libc'] = ct.cdll.LoadLibrary("libc.{}".format(
            "so.6" if platform.uname()[0] != "Darwin" else "dylib"))

    lib['libxtc'] = ct.cdll.LoadLibrary(os.path.join(libdir, "libxtc.so"))
    return lib
예제 #4
0
        outfile = os.path.join(outputdir, self.acemd.coordinates)
        inmol.write(outfile)

    def addConstraint(self, atomselect, factor=1):
        """ Convenience function for adding a new constraint to existing constraints.

        Parameters
        ----------
        atomselect : str
            Atom selection of atoms we want to constrain
        factor : float
            The scaling factor of the constraints applied to the atoms

        Example
        -------
        >>> eq.addConstraint('chain X', 0.3)
        """
        self.constraints[atomselect] = factor


if __name__ == "__main__":
    import htmd
    eq = Equilibration()
    eq.numsteps = 1000000
    eq.temperature = 300
    eq.reference = 'protein and name CA'
    eq.selection = 'segname L and noh'
    eq.box = [-20, 20, -20, 20, 43, 45]
    eq.k = 5
    eq.write(htmd.home() + '/data/equilibrate', '/tmp/equil1')
예제 #5
0
        if self.fb_k > 0:  #use TCL only for flatbottom
            mol = Molecule(os.path.join(inputdir, self.acemd.coordinates))
            self.acemd.tclforces = 'on'
            tcl = list(self.acemd.TCL)
            tcl[0] = tcl[0].format(
                NUMSTEPS=numsteps,
                KCONST=self.fb_k,
                REFINDEX=' '.join(map(str, mol.get('index',
                                                   self.fb_reference))),
                SELINDEX=' '.join(map(str, mol.get('index',
                                                   self.fb_selection))),
                BOX=' '.join(map(str, self.fb_box)))
            self.acemd.TCL = tcl[0] + tcl[1]
        else:
            self.acemd.TCL = 'set numsteps {}\n'.format(numsteps)
        self.acemd.setup(inputdir, outputdir, overwrite=True)


if __name__ == "__main__":
    md = Production()
    md.temperature = 300
    md.fb_reference = 'protein and name CA'
    md.fb_selection = 'segname L and noh'
    md.acemd.extendedsystem = None  # use different data
    md.acemd.binindex = None  # use different data
    md.fb_box = [-20, 20, -20, 20, 43, 45]
    md.fb_k = 5
    md.write(htmd.home() + '/data/equilibrate', '/tmp/prod')
    md.fb_k = 0
    md.write(htmd.home() + '/data/equilibrate', '/tmp/prod0')
예제 #6
0
    centers
    """
    centers = centers.astype(np.float64)
    channelsigmas = channelsigmas.astype(np.float64)

    nchannels = channelsigmas.shape[1]
    occus = np.zeros((centers.shape[0], nchannels))
    coords = np.squeeze(mol.coords[:, :, 0])

    occupancylib.descriptor_ext(centers.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
                       coords.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
                       channelsigmas.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
                       occus.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
                       ctypes.c_int(occus.shape[0]),  # n of centers
                       ctypes.c_int(coords.shape[0]),  # n of atoms
                       ctypes.c_int(nchannels))  # n of channels
    return occus

if __name__ == '__main__':
    from htmd.molecule.molecule import Molecule
    from htmd.home import home
    import os
    import numpy as np
    testf = os.path.join(home(), 'data', 'test-voxeldescriptors')
    resOcc, resCent, N = getVoxelDescriptors(Molecule(os.path.join(testf, '3ptb.pdbqt')), buffer=8, voxelsize=1)
    resOcc = resOcc.reshape(N[0], N[1], N[2], resOcc.shape[1])
    refOcc = np.load(os.path.join(testf, '3PTB_occ.npy'))
    refCent = np.load(os.path.join(testf, '3PTB_center.npy'))
    assert np.allclose(resOcc, refOcc)
    assert np.allclose(resCent, refCent)
예제 #7
0
파일: adaptiverun.py 프로젝트: xielm12/htmd
    def _spawn(self, ranking, N, truncated=False):
        if truncated:
            idx = np.argsort(ranking)
            idx = idx[::-1]  # decreasing sort
            errs = ranking[idx]
            H = (N * errs / np.cumsum(errs)) < 1
            ranking[idx[H]] = 0
        prob = ranking / np.sum(ranking)
        spawnmicro = np.random.multinomial(N, prob)
        return spawnmicro, prob


if __name__ == "__main__":
    from htmd import AcemdLocal
    import htmd
    from os import chdir
    from tempfile import mkdtemp

    chdir(mkdtemp())
    md = AdaptiveRun()
    md.dryrun = True
    md.nmin = 2
    md.nmax = 3
    md.nepochs = 2
    md.ticadim = 0
    md.metricsel1 = 'name CA'
    md.generatorspath = htmd.home() + '/data/dhfr'
    #md.app = AcemdLocal()
    # md.run()  # Disabled because I can't assume acemd is installed in travis machines
예제 #8
0
파일: acemd.py 프로젝트: Acellera/htmd
    def _writeBashRun(self, fname):
        with open(fname, 'w') as f:
            f.write('#!/bin/bash\nacemd >log.txt 2>&1')
        os.chmod(fname, 0o700)

    def __repr__(self):
        return self.show(quiet=True)

    def writeConf(self, fname='input'):
        """ Write an acemd configuration file

        Parameters
        ----------
        fname : output file name
        """
        text = self.show(quiet=True)
        fo = open(fname, 'w')
        fo.write(text)
        fo.close()

if __name__ == "__main__":
    #l=Acemd.protocols(quiet=True)
    acemd = Acemd()
    acemd.structure = '5dhfr_cube.psf'
    acemd.parameters = 'par_all22_prot.inp'
    homedir = htmd.home()
    acemd.coordinates = '5dhfr_cube.pdb'
    acemd.setup(homedir + '/data/dhfr', '/tmp/testdir', overwrite=True)
    print(acemd)

예제 #9
0
    import sys
    import numpy as np
    import htmd
    from htmd.projections.metricplumed2 import MetricPlumed2

    try:
        _getPlumedRoot()
    except:
        print("Tests in %s skipped because plumed executable not found." % __file__)
        sys.exit()

    import doctest
    doctest.testmod()

    # One simulation
    mol = Molecule(os.path.join(htmd.home(), 'data', '1kdx', '1kdx_0.pdb'))
    mol.read(os.path.join(htmd.home(), 'data', '1kdx', '1kdx.dcd'))

    metric = MetricPlumed2(['d1: DISTANCE ATOMS=1,200',
                            'd2: DISTANCE ATOMS=5,6'])
    #    metric = MetricPlumed2([''])  # to test exceptions
    data = metric.project(mol)
    ref = np.array([0.536674, 21.722393, 22.689391, 18.402114, 23.431387, 23.13392, 19.16376, 20.393544,
                    23.665517, 22.298349, 22.659769, 22.667669, 22.484084, 20.893447, 18.791701,
                    21.833056, 19.901318])
    assert np.all(np.abs(ref - data[:, 0]) < 0.01), 'Plumed demo calculation is broken'

    # Simlist
    # datadirs=glob(os.path.join(home(), 'data', 'adaptive', 'data', '*' )
    # fsims=simlist(glob(os.path.join(home(), 'data', 'adaptive', 'data', '*', '/')),
    #              os.path.join(home(), 'data', 'adaptive', 'generators', '1','structure.pdb'))
예제 #10
0
파일: latest.py 프로젝트: jhprinz/htmd
def compareVersions():
    from htmd.version import version
    from natsort import natsorted
    import os
    import time
    #t = time.time()
    from os.path import expanduser
    __home = expanduser("~")
    __htmdconf = os.path.join(__home, '.htmd')
    if not os.path.exists(__htmdconf):
        try:
            os.makedirs(__htmdconf)
        except:
            print(
                'Unable to create {} folder. Will not check for new HTMD versions.'
                .format(__htmdconf))
            return
    __file = os.path.join(__htmdconf, '.latestversion')

    # Check if one day has passed since last version check. If yes, get new version and write to file
    if not os.path.isfile(
            __file) or time.time() > os.path.getmtime(__file) + 86400:
        _writeLatestVersionFile(__file)

    try:
        f = open(__file, 'r')
    except:
        print(
            'Unable to open {} file for reading. Will not check for new HTMD versions.'
            .format(__file))
        return
    latestversions = f.readlines()
    f.close()

    currver = version()
    if currver != 'unpackaged' and len(
            latestversions
    ) == 2:  # Supporting users which still haven't passed the one day limit. Can remove in next
        if _is_stable(currver):
            latest = latestversions[0].strip()
            verstring = 'stable'
        else:
            latest = latestversions[1].strip()
            verstring = 'devel'
    elif len(
            latestversions
    ) == 1:  # Supporting users which still haven't passed the one day limit. Can remove in next version
        latest = latestversions[0].strip()
        verstring = ''
    elif currver == 'unpackaged':
        pass
    else:
        return

    if currver != 'unpackaged' and natsorted((latest, currver))[1] != currver:
        print(
            'New {} HTMD version ({}) is available. You are currently on ({}). Use \'conda update htmd\' to '
            'update to the new version.'.format(verstring, latest, currver))
    else:
        if currver != 'unpackaged':
            print('You are on the latest HTMD version ({}).'.format(currver))
        else:
            from htmd import home
            print('You are on the latest HTMD version ({} : {}).'.format(
                currver, home()))
예제 #11
0
파일: xtc.py 프로젝트: PabloHN/htmd
    lib = xtc_lib()
    bbox = (c_float * 3)()
    natoms = c_int(coords.shape[0])
    cstep = c_int()
    # print(coords.shape)
    for f in range(coords.shape[2]):
        cstep = c_int(step[f])
        ctime = c_float(time[f])  # TODO FIXME
        # print ( step )
        # print ( time )
        bbox[0] = box[0, f] * 0.1
        bbox[1] = box[1, f] * 0.1
        bbox[2] = box[2, f] * 0.1

        data = coords[:, :, f].astype(
            numpy.float32) * 0.1  # Convert from A to nm
        pos = data.ctypes.data_as(POINTER(c_float))
        lib['libxtc'].xtc_write(c_char_p(filename.encode("ascii")), natoms,
                                cstep, ctime, pos, bbox)
    pass


if __name__ == "__main__":
    from htmd.molecule.molecule import Molecule
    from htmd.home import home
    from os import path

    m = Molecule(path.join(home(), 'data', 'dhfr', 'dhfr.pdb'))
    m.read(path.join(home(), 'data', 'dhfr', 'dhfr.xtc'))
    m.write('/tmp/test.xtc')
예제 #12
0
    import numpy as np
    import htmd
    from htmd.projections.metricplumed2 import *

    try:
        _getPlumedRoot()
    except:
        print("Tests in %s skipped because plumed executable not found." %
              __file__)
        sys.exit()

    import doctest
    doctest.testmod()

    # Simlist
    dd = htmd.home(dataDir="adaptive")
    fsims = htmd.simlist([dd + '/data/e1s1_1/', dd + '/data/e1s2_1/'],
                         dd + '/generators/1/structure.pdb')
    metr = Metric(fsims)
    metr.projection(
        MetricPlumed2(['d1: DISTANCE ATOMS=2,3', 'd2: DISTANCE ATOMS=5,6']))
    data2 = metr.project()

    # One simulation
    testpath = os.path.join(htmd.home(), 'data', '1kdx')
    mol = Molecule(os.path.join(testpath, '1kdx_0.pdb'))
    mol.read(os.path.join(htmd.home(), 'data', '1kdx', '1kdx.dcd'))

    metric = MetricPlumed2(
        ['d1: DISTANCE ATOMS=1,200', 'd2: DISTANCE ATOMS=5,6'])
    data = metric.project(mol)
예제 #13
0
파일: home.py 프로젝트: leelasd/htmd
# (c) 2015-2016 Acellera Ltd http://www.acellera.com
# All Rights Reserved
# Distributed under HTMD Software License Agreement
# No redistribution in whole or part
#
import htmd
import os
import inspect


def home():
    return os.path.dirname(inspect.getfile(htmd))


#Don't know how to do this
# def modulehome(modname):
#    return os.path.dirname(os.path.dirname(inspect.getfile(modname)))

if __name__ == "__main__":
    h = htmd.home()
    print(h)
예제 #14
0
    import numpy as np
    import htmd
    from htmd.projections.metricplumed2 import MetricPlumed2

    try:
        _getPlumedRoot()
    except:
        print("Tests in %s skipped because plumed executable not found." %
              __file__)
        sys.exit()

    import doctest
    doctest.testmod()

    # One simulation
    mol = Molecule(os.path.join(htmd.home(), 'data', '1kdx', '1kdx_0.pdb'))
    mol.read(os.path.join(htmd.home(), 'data', '1kdx', '1kdx.dcd'))

    metric = MetricPlumed2(
        ['d1: DISTANCE ATOMS=1,200', 'd2: DISTANCE ATOMS=5,6'])
    #    metric = MetricPlumed2([''])  # to test exceptions
    data = metric.project(mol)
    ref = np.array([
        0.536674, 21.722393, 22.689391, 18.402114, 23.431387, 23.13392,
        19.16376, 20.393544, 23.665517, 22.298349, 22.659769, 22.667669,
        22.484084, 20.893447, 18.791701, 21.833056, 19.901318
    ])
    assert np.all(
        np.abs(ref - data[:, 0]) < 0.01), 'Plumed demo calculation is broken'

    # Simlist
예제 #15
0
            H = (N * errs / np.cumsum(errs)) < 1
            ranking[idx[H]] = 0
        prob = ranking / np.sum(ranking)
        spawnmicro = np.random.multinomial(N, prob)
        return spawnmicro, prob


if __name__ == "__main__":
    from htmd import AcemdLocal
    import htmd
    import os
    import shutil
    from htmd.util import tempname

    tmpdir = tempname()
    shutil.copytree(htmd.home()+'/data/adaptive/', tmpdir)
    os.chdir(tmpdir)
    md = AdaptiveMD()
    # md.dryrun = True
    md.nmin = 1
    md.nmax = 2
    md.nepochs = 3
    md.ticalag = 2
    md.ticadim = 3
    md.updateperiod = 5
    md.projection = MetricDistance('protein and name CA', 'resname BEN and noh')
    # md.generatorspath = htmd.home()+'/data/dhfr'
    # md.datapath = 'input'
    # md.app = AcemdLocal(inputfile='input.acemd')

    # md.app = AcemdLocal(datadir='data')
예제 #16
0
파일: acemd.py 프로젝트: xielm12/htmd
        else:
            return text

    def __str__(self):
        return self.show(quiet=True)

    def writeConf(self, fname='input'):
        """ Write an acemd configuration file

        Parameters
        ----------
        fname : output file name
        """
        text = self.show(quiet=True)
        fo = open(fname, 'w')
        fo.write(text)
        fo.close()

if __name__ == "__main__":
    #l=Acemd.protocols(quiet=True)
    acemd = Acemd()
    acemd.structure = '5dhfr_cube.psf'
    acemd.consref = None
    acemd.constraintscaling = None
    acemd.parameters = 'par_all22_prot.inp'
    homedir = htmd.home()
    acemd.coordinates = '5dhfr_cube.pdb'
    acemd.setup(homedir + '/data/dhfr', '/tmp/testdir', overwrite=True)
    print(acemd)

예제 #17
0
파일: adaptiverun.py 프로젝트: jhprinz/htmd
            H = (N * errs / np.cumsum(errs)) < 1
            ranking[idx[H]] = 0
        prob = ranking / np.sum(ranking)
        spawnmicro = np.random.multinomial(N, prob)
        return spawnmicro, prob


if __name__ == "__main__":
    from htmd import AcemdLocal
    import htmd
    import os
    import shutil
    from htmd.util import tempname

    tmpdir = tempname()
    shutil.copytree(htmd.home() + '/data/adaptive/', tmpdir)
    os.chdir(tmpdir)
    md = AdaptiveMD()
    # md.dryrun = True
    md.nmin = 1
    md.nmax = 2
    md.nepochs = 3
    md.ticalag = 2
    md.ticadim = 3
    md.updateperiod = 5
    md.projection = MetricDistance('protein and name CA',
                                   'resname BEN and noh')
    # md.generatorspath = htmd.home()+'/data/dhfr'
    # md.datapath = 'input'
    # md.app = AcemdLocal(inputfile='input.acemd')
예제 #18
0
from htmd.molecule.util import boundingBox
import numpy as np
import ctypes
import htmd
import os

_order = ('hydrophobic', 'aromatic', 'hbond_acceptor', 'hbond_donor', 'positive_ionizable', 'negative_ionizable', 'metal', 'occupancies')
libdir = htmd.home(libDir=True)
occupancylib = ctypes.cdll.LoadLibrary(os.path.join(libdir, "occupancy_ext.so"))


def getVoxelDescriptors(mol, buffer, voxelsize=1):
    """ Calculate descriptors of atom properties for voxels in a grid bounding the Molecule object.

    Constructs a bounding box around Molecule with some buffer space. Then it

    Parameters
    ----------
    mol :
        A Molecule object.
    buffer : float
        The buffer space to add to the bounding box. This adds zeros to the grid around the protein so that properties
        which are at the edge of the box can be found in the center of one. Should be usually set to boxsize/2.
    voxelsize : float
        The voxel size in A

    Returns
    -------
    features : np.ndarray
        A list of boxes containing voxels and their properties
    centers : np.ndarray
예제 #19
0
            inmol.set('beta', self.constraints[sel], sel)
        outfile = os.path.join(outputdir, self.acemd.coordinates)
        inmol.write(outfile)

    def addConstraint(self, atomselect, factor=1):
        """ Convenience function for adding a new constraint to existing constraints.

        Parameters
        ----------
        atomselect : str
            Atom selection of atoms we want to constrain
        factor : float
            The scaling factor of the constraints applied to the atoms

        Example
        -------
        >>> eq.addConstraint('chain X', 0.3)
        """
        self.constraints[atomselect] = factor

if __name__ == "__main__":
    import htmd
    eq = Equilibration()
    eq.numsteps = 1000000
    eq.temperature = 300
    eq.reference = 'protein and name CA'
    eq.selection = 'segname L and noh'
    eq.box = [-20, 20, -20, 20, 43, 45]
    eq.k = 5
    eq.write(htmd.home() + '/data/equilibrate', '/tmp/equil1')
예제 #20
0
파일: home.py 프로젝트: Acellera/htmd
      pass

    if dataDir:
        return os.path.join(homeDir, "data", dataDir)
    elif libDir:
        libdir = os.path.join(homeDir, "lib", platform.system() )
        if not os.path.exists( libdir ):
            raise FileNotFoundError('Could not find libs.')
        return libdir
#        if os.path.exists(os.path.join(libdir, "basic")):
#            return os.path.join(libdir, "basic", platform.system())
#        elif os.path.exists(os.path.join(libdir, "pro")):
#            return os.path.join(libdir, "pro", platform.system())
#        else:
#            raise FileNotFoundError('Could not find libs.')
    else:
        return homeDir



#Don't know how to do this
# def modulehome(modname):
#    return os.path.dirname(os.path.dirname(inspect.getfile(modname)))

if __name__ == "__main__":
    import doctest
    doctest.testmod()

    h = htmd.home()
    print(h)
예제 #21
0
    centers
    """
    centers = centers.astype(np.float64)
    channelsigmas = channelsigmas.astype(np.float64)

    nchannels = channelsigmas.shape[1]
    occus = np.zeros((centers.shape[0], nchannels))
    coords = np.squeeze(mol.coords[:, :, 0])

    occupancylib.descriptor_ext(centers.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
                       coords.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
                       channelsigmas.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
                       occus.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),
                       ctypes.c_int(occus.shape[0]),  # n of centers
                       ctypes.c_int(coords.shape[0]),  # n of atoms
                       ctypes.c_int(nchannels))  # n of channels
    return occus

if __name__ == '__main__':
    from htmd.molecule.molecule import Molecule
    from htmd.home import home
    import os
    import numpy as np
    testf = os.path.join(home(), 'data', 'test-voxeldescriptors')
    resOcc, resCent, N = getVoxelDescriptors(Molecule(os.path.join(testf, '3ptb.pdbqt')), buffer=8, voxelsize=1)
    resOcc = resOcc.reshape(N[0], N[1], N[2], resOcc.shape[1])
    refOcc = np.load(os.path.join(testf, '3PTB_occ.npy'))
    refCent = np.load(os.path.join(testf, '3PTB_center.npy'))
    assert np.allclose(resOcc, refOcc)
    assert np.allclose(resCent, refCent)
예제 #22
0
    md.updateperiod = 5
    md.projection = MetricDistance("protein and name CA",
                                   "resname BEN and noh",
                                   periodic="selections")
    # md.goalprojection = MetricRmsd(Molecule(htmd.home() + '/data/adaptive/generators/1/structure.pdb'),
    #                               'protein and name CA')
    md.goalfunction = rmsdgoal
    # md.app = LocalGPUQueue()
    # md.run()

    # Some real testing now
    from moleculekit.projections.metricsecondarystructure import (
        MetricSecondaryStructure, )
    from moleculekit.projections.metricdistance import MetricSelfDistance

    os.chdir(path.join(home(), "data", "test-adaptive"))

    goalProjectionDict = {
        "ss":
        MetricSecondaryStructure(),
        "contacts":
        MetricSelfDistance("protein and name CA",
                           metric="contacts",
                           threshold=10),
        "ss_contacts": [
            MetricSecondaryStructure(),
            MetricSelfDistance("protein and name CA",
                               metric="contacts",
                               threshold=10),
        ],
    }
예제 #23
0
파일: metricnull.py 프로젝트: PabloHN/htmd
        -------
        data : np.ndarray
            An array containing the null data.
        """

        trajlen = mol.numFrames
        data = np.zeros((trajlen, self._ndim), dtype=np.float32)

        return data


if __name__ == "__main__":
    import htmd
    import htmd.projections.metricnull

    dd = htmd.home(dataDir="adaptive")
    fsims = htmd.simlist([dd + '/data/e1s1_1/', dd + '/data/e1s2_1/'],
                         dd + '/generators/1/structure.pdb')

    metr2 = htmd.Metric(fsims)
    metr2.projection(htmd.projections.metricnull.MetricNull(2))
    data2 = metr2.project()
    assert data2.dat[0].shape == (6, 2)

    metr1 = htmd.Metric(fsims)
    metr1.projection(htmd.projections.metricnull.MetricNull(1))
    data1 = metr1.project()
    assert data1.dat[0].shape == (6, 1)

    pass
예제 #24
0
    md.ticalag = 2
    md.ticadim = 3
    md.updateperiod = 5
    md.projection = MetricDistance('protein and name CA', 'resname BEN and noh')
    # md.goalprojection = MetricRmsd(Molecule(htmd.home() + '/data/adaptive/generators/1/structure.pdb'),
    #                               'protein and name CA')
    md.goalfunction = rmsdgoal
    # md.app = AcemdLocal()
    # md.run()

    # Some real testing now
    from htmd.projections.metricsecondarystructure import MetricSecondaryStructure
    from htmd.projections.metricdistance import MetricSelfDistance
    import numpy as np

    os.chdir(path.join(home(), 'data', 'test-adaptive'))

    goalProjectionDict = {'ss': MetricSecondaryStructure(),
                          'contacts': MetricSelfDistance('protein and name CA', metric='contacts', threshold=10),
                          'ss_contacts': [MetricSecondaryStructure(),
                                          MetricSelfDistance('protein and name CA', metric='contacts', threshold=10)]}

    def getLongContacts(crystal, long=8):
        crystalMap = MetricSelfDistance('protein and name CA', metric='contacts', threshold=10, pbc=False).getMapping(
            crystal)
        indexes = np.vstack(crystalMap.atomIndexes.values)
        return crystal.resid[indexes[:, 1]] - crystal.resid[indexes[:, 0]] > long

    def getCrystalSS(crystal):
        return MetricSecondaryStructure().project(crystal)[0]
예제 #25
0
    md.ticadim = 3
    md.updateperiod = 5
    md.projection = MetricDistance('protein and name CA',
                                   'resname BEN and noh')
    # md.goalprojection = MetricRmsd(Molecule(htmd.home() + '/data/adaptive/generators/1/structure.pdb'),
    #                               'protein and name CA')
    md.goalfunction = rmsdgoal
    # md.app = AcemdLocal()
    # md.run()

    # Some real testing now
    from htmd.projections.metricsecondarystructure import MetricSecondaryStructure
    from htmd.projections.metricdistance import MetricSelfDistance
    import numpy as np

    os.chdir(path.join(home(), 'data', 'test-adaptive'))

    goalProjectionDict = {
        'ss':
        MetricSecondaryStructure(),
        'contacts':
        MetricSelfDistance('protein and name CA',
                           metric='contacts',
                           threshold=10),
        'ss_contacts': [
            MetricSecondaryStructure(),
            MetricSelfDistance('protein and name CA',
                               metric='contacts',
                               threshold=10)
        ]
    }
예제 #26
0
파일: metricnull.py 프로젝트: jhprinz/htmd
        -------
        data : np.ndarray
            An array containing the null data.
        """

        trajlen = mol.numFrames
        data = np.zeros((trajlen, self._ndim), dtype=np.float32)

        return data


if __name__ == "__main__":
    import htmd
    import htmd.projections.metricnull

    dd = htmd.home(dataDir="adaptive")
    fsims = htmd.simlist([dd + '/data/e1s1_1/', dd + '/data/e1s2_1/'],
                         dd + '/generators/1/structure.pdb')

    metr2 = htmd.Metric(fsims)
    metr2.projection(htmd.projections.metricnull.MetricNull(2))
    data2 = metr2.project()
    assert data2.dat[0].shape == (6, 2)

    metr1 = htmd.Metric(fsims)
    metr1.projection(htmd.projections.metricnull.MetricNull(1))
    data1 = metr1.project()
    assert data1.dat[0].shape == (6, 1)

    pass
예제 #27
0
파일: xtc.py 프로젝트: andreubp/htmd
    # print(coords.shape)
    for f in range(coords.shape[2]):
        cstep = c_int(step[f])
        ctime = c_float(time[f])  # TODO FIXME
        # print ( step )
        # print ( time )
        bbox[0] = box[0, f] * 0.1
        bbox[1] = box[1, f] * 0.1
        bbox[2] = box[2, f] * 0.1

        data = coords[:, :, f].astype(numpy.float32) * 0.1  # Convert from A to nm
        pos = data.ctypes.data_as(POINTER(c_float))
        lib['libxtc'].xtc_write(
            c_char_p(filename.encode("ascii")),
            natoms,
            cstep,
            ctime,
            pos,
            bbox)
    pass


if __name__ == "__main__":
    from htmd.molecule.molecule import Molecule
    from htmd.home import home
    from os import path

    m = Molecule(path.join(home(), 'data', 'dhfr', 'dhfr.pdb'))
    m.read(path.join(home(), 'data', 'dhfr', 'dhfr.xtc'))
    m.write('/tmp/test.xtc')
예제 #28
0
파일: adaptiverun.py 프로젝트: PabloHN/htmd
    def _spawn(self, ranking, N, truncated=False):
        if truncated:
            idx = np.argsort(ranking)
            idx = idx[::-1]  # decreasing sort
            errs = ranking[idx]
            H = (N * errs / np.cumsum(errs)) < 1
            ranking[idx[H]] = 0
        prob = ranking / np.sum(ranking)
        spawnmicro = np.random.multinomial(N, prob)
        return spawnmicro, prob


if __name__ == "__main__":
    from htmd import AcemdLocal
    import htmd
    from os import chdir
    from tempfile import mkdtemp

    chdir(mkdtemp())
    md = AdaptiveRun()
    md.dryrun = True
    md.nmin = 2
    md.nmax = 3
    md.nepochs = 2
    md.ticadim = 0
    md.metricsel1 = 'name CA'
    md.generatorspath = htmd.home()+'/data/dhfr'
    #md.app = AcemdLocal()
    # md.run()  # Disabled because I can't assume acemd is installed in travis machines

예제 #29
0
        inputdir : str
            Path to a directory containing the files produced by a equilibration process.
        outputdir : str
            Directory where to write the production setup files.
        """
        self.acemd.temperature = self.temperature
        self.acemd.langevintemp = self.temperature
        if self.k > 0: #use TCL only for flatbottom
            mol = Molecule(os.path.join(inputdir, self.acemd.coordinates))
            self.acemd.tclforces = 'on'
            TCL = self._TCL
            TCL = TCL.replace('KCONST', str(self.k))
            TCL = TCL.replace('REFINDEX', ' '.join(map(str, mol.get('index', self.reference))))
            TCL = TCL.replace('SELINDEX', ' '.join(map(str, mol.get('index', self.selection))))
            TCL = TCL.replace('BOX', ' '.join(map(str, self.box)))
            self.acemd.TCL = TCL
        self.acemd.setup(inputdir, outputdir, overwrite=True)

if __name__ == "__main__":
    md = Production()
    md.temperature = 300
    md.reference = 'protein and name CA'
    md.selection = 'segname L and noh'
    md.acemd.extendedsystem = None  # use different data
    md.acemd.binindex = None  # use different data
    md.box = [-20, 20, -20, 20, 43, 45]
    md.k = 5
    md.write(htmd.home() +'/data/equilibrate', '/tmp/prod')
    md.k = 0
    md.write(htmd.home() +'/data/equilibrate', '/tmp/prod0')
예제 #30
0
            mol = Molecule(os.path.join(self.inputdir, self.acemd.coordinates))
            self.acemd.tclforces = 'on'
            TCL = self._TCL
            TCL = TCL.replace('KCONST', str(self.k))
            TCL = TCL.replace(
                'REFINDEX', ' '.join(map(str, mol.get('index',
                                                      self.reference))))
            TCL = TCL.replace(
                'SELINDEX', ' '.join(map(str, mol.get('index',
                                                      self.selection))))
            TCL = TCL.replace('BOX', ' '.join(map(str, self.box)))
            self.acemd.TCL = TCL
        self.acemd.setup(self.inputdir, self.outputdir, overwrite=True)


if __name__ == "__main__":
    eq = Production()
    eq.temperature = 300
    eq.reference = 'protein and name CA'
    eq.selection = 'segname L and noh'
    eq.acemd.extendedsystem = None  # use different data
    eq.acemd.binindex = None  # use different data
    eq.box = [-20, 20, -20, 20, 43, 45]
    eq.k = 5
    eq.inputdir = htmd.home() + '/data/equilibrate'
    eq.outputdir = '/tmp/prod'
    eq.write()
    eq.k = 0
    eq.outputdir = '/tmp/prod0'
    eq.write()