Ejemplo n.º 1
0
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("")
Ejemplo n.º 2
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
Ejemplo n.º 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
Ejemplo n.º 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')
Ejemplo n.º 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')
Ejemplo n.º 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)
Ejemplo n.º 7
0
    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
Ejemplo n.º 8
0
    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)

Ejemplo n.º 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'))
Ejemplo n.º 10
0
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()))
Ejemplo n.º 11
0
Archivo: xtc.py Proyecto: 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')
Ejemplo n.º 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)
Ejemplo n.º 13
0
Archivo: home.py Proyecto: 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)
Ejemplo n.º 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
Ejemplo n.º 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')
Ejemplo n.º 16
0
        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)

Ejemplo n.º 17
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')
Ejemplo n.º 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
Ejemplo n.º 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')
Ejemplo n.º 20
0
      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)
Ejemplo n.º 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)
Ejemplo n.º 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),
        ],
    }
Ejemplo n.º 23
0
        -------
        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
Ejemplo n.º 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]
Ejemplo n.º 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)
        ]
    }
Ejemplo n.º 26
0
        -------
        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
Ejemplo n.º 27
0
Archivo: xtc.py Proyecto: 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')
Ejemplo n.º 28
0
    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

Ejemplo n.º 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')
Ejemplo n.º 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()