예제 #1
0
    def optimize(self):
        """Run the optimization with MMTK"""
        print '\n-------------------------------------------------------------------------------'
        print '\n MMTK Optimization starts...'

        print '\t.. building universe'
        configuration = PDBConfiguration(self.temp_pdb_file)
        # Construct the nucleotide chain object. This also constructs positions
        # for the missing hydrogens, using geometrical criteria.
        chain = configuration.createNucleotideChains()[0]
        universe = InfiniteUniverse()
        universe.addObject(chain)

        restraints = self.create_restraints(chain)

        # define force field
        print '\t.. setting up force field'
        if restraints:
            ff = Amber94ForceField() + restraints
        else:
            ff = Amber94ForceField()
        universe.setForceField(ff)

        # do the minimization
        print '\t.. starting minimization with %i cycles'%self.cycles
        minimizer = ConjugateGradientMinimizer(universe)
        minimizer(steps = self.cycles)
        # write the intermediate output
        print '\t.. writing MMTK output to %s'% self.temp_pdb_file
        if self.model_passive:
            print '\t   (please note that MMTK applies a different numeration of residues.\n\t    The original one will be restored in the final output).'
        universe.writeToFile(self.mmtk_output_file)
        open(self.temp_pdb_file, 'w').write(open(self.mmtk_output_file).read())
        print '\n-------------------------------------------------------------------------------'
예제 #2
0
def minimizeEnergy(inputProteinName, outputProteinName):
    universe = InfiniteUniverse(Amber94ForceField())
    universe.protein = Protein(inputProteinName)
    minimizer = SteepestDescentMinimizer(universe)
    minimizer(steps=10)

    universe.protein.writeToFile(outputProteinName)
예제 #3
0
def atomicReconstruction(ca_pdb, atomic_pdb, out_pdb):
    universe = InfiniteUniverse(Amber94ForceField())
    universe.protein = Protein(atomic_pdb)
    initial = copy(universe.configuration())
    final = Configuration(universe)

    calpha_protein = Protein(ca_pdb, model='calpha')
    for ichain in range(len(calpha_protein)):
        chain = universe.protein[ichain]
        ca_chain = calpha_protein[ichain]
        for iresidue in range(len(ca_chain)):
            ca = chain[iresidue].peptide.C_alpha
            final[ca] = ca_chain[iresidue].position()
        for iresidue in range(len(ca_chain)):
            if iresidue == 0:
                refs = [0, 1, 2]
            elif iresidue == len(ca_chain) - 1:
                refs = [iresidue - 2, iresidue - 1, iresidue]
            else:
                refs = [iresidue - 1, iresidue, iresidue + 1]
            ref = Collection()
            for i in refs:
                ref.addObject(chain[i].peptide.C_alpha)
            tr, rms = ref.findTransformation(initial, final)
            residue = chain[iresidue]
            residue.applyTransformation(tr)
            ca = residue.peptide.C_alpha
            residue.translateBy(final[ca] - ca.position())
            for a in residue.atomList():
                final[a] = a.position()

    minimizer = SteepestDescentMinimizer(universe)
    minimizer(step=1000)

    print "Writing configuration to file ", out_pdb
    universe.writeToFile(out_pdb)
예제 #4
0
파일: modes.py 프로젝트: torkos/MMTK
# Standard normal mode calculation.
#

from MMTK import *
from MMTK.Proteins import Protein
from MMTK.ForceFields import Amber94ForceField
from MMTK.NormalModes import VibrationalModes
from MMTK.Minimization import ConjugateGradientMinimizer
from MMTK.Trajectory import StandardLogOutput
from MMTK.Visualization import view

# Construct system
universe = InfiniteUniverse(Amber94ForceField())
universe.protein = Protein('bala1')

# Minimize
minimizer = ConjugateGradientMinimizer(universe,
                                       actions=[StandardLogOutput(50)])
minimizer(convergence = 1.e-3, steps = 10000)

# Calculate normal modes
modes = VibrationalModes(universe)

# Print frequencies
for mode in modes:
    print(f"{mode}")

# Show animation of the first non-trivial mode 
view(modes[6])
예제 #5
0
파일: nma.py 프로젝트: menchant/pymol-psico
def normalmodes_mmtk(selection,
                     cutoff=12.0,
                     ff='Deformation',
                     first=7,
                     last=10,
                     prefix='mmtk',
                     states=7,
                     factor=-1,
                     quiet=1):
    '''
DESCRIPTION

    Fast normal modes for large proteins using an elastic network model (CA only)

    Based on:
    http://dirac.cnrs-orleans.fr/MMTK/using-mmtk/mmtk-example-scripts/normal-modes/
    '''
    try:
        import MMTK
    except ImportError:
        print('Failed to import MMTK, please add to PYTHONPATH')
        raise CmdException

    selection = selector.process(selection)
    cutoff = float(cutoff)
    first, last = int(first), int(last)
    states, factor, quiet = int(states), float(factor), int(quiet)

    from math import log
    from chempy import cpv

    from MMTK import InfiniteUniverse
    from MMTK.PDB import PDBConfiguration
    from MMTK.Proteins import Protein
    from MMTK.NormalModes import NormalModes

    from MMTK.ForceFields import DeformationForceField, CalphaForceField
    from MMTK.FourierBasis import FourierBasis, estimateCutoff
    from MMTK.NormalModes import NormalModes, SubspaceNormalModes

    model = 'calpha'
    ff = ff.lower()
    if 'deformationforcefield'.startswith(ff):
        forcefield = DeformationForceField(cutoff=cutoff / 10.)
    elif 'calphaforcefield'.startswith(ff):
        forcefield = CalphaForceField(cutoff=cutoff / 10.)
    elif 'amber94forcefield'.startswith(ff):
        from MMTK.ForceFields import Amber94ForceField
        forcefield = Amber94ForceField()
        model = 'all'
    else:
        raise NotImplementedError('unknown ff = ' + str(ff))
    if not quiet:
        print(' Forcefield:', forcefield.__class__.__name__)

    if model == 'calpha':
        selection = '(%s) and polymer and name CA' % (selection)

    f = StringIO(cmd.get_pdbstr(selection))
    conf = PDBConfiguration(f)
    items = conf.createPeptideChains(model)

    universe = InfiniteUniverse(forcefield)
    universe.protein = Protein(*items)

    nbasis = max(10, universe.numberOfAtoms() / 5)
    cutoff, nbasis = estimateCutoff(universe, nbasis)
    if not quiet:
        print(" Calculating %d low-frequency modes." % nbasis)

    if cutoff is None:
        modes = NormalModes(universe)
    else:
        subspace = FourierBasis(universe, cutoff)
        modes = SubspaceNormalModes(universe, subspace)

    natoms = modes.array.shape[1]
    frequencies = modes.frequencies

    if factor < 0:
        factor = log(natoms)
        if not quiet:
            print(' set factor to %.2f' % (factor))

    if True:  # cmd.count_atoms(selection) != natoms:
        import tempfile, os
        from MMTK import DCD
        filename = tempfile.mktemp(suffix='.pdb')
        sequence = DCD.writePDB(universe, None, filename)
        z = [a.index for a in sequence]
        selection = cmd.get_unused_name('_')
        cmd.load(filename, selection, zoom=0)
        os.remove(filename)

        if cmd.count_atoms(selection) != natoms:
            print('hmm... still wrong number of atoms')

    def eigenfacs_iter(mode):
        x = modes[mode - 1].array
        return iter(x.take(z, 0))

    for mode in range(first, min(last, len(modes)) + 1):
        name = prefix + '%d' % mode
        cmd.delete(name)

        if not quiet:
            print(' normalmodes: object "%s" for mode %d with freq. %.6f' % \
                    (name, mode, frequencies[mode-1]))

        for state in range(1, states + 1):
            cmd.create(name, selection, 1, state, zoom=0)
            cmd.alter_state(
                state,
                name,
                '(x,y,z) = cpv.add([x,y,z], cpv.scale(next(myit), myfac))',
                space={
                    'cpv': cpv,
                    'myit': eigenfacs_iter(mode),
                    'next': next,
                    'myfac':
                    1e2 * factor * ((state - 1.0) / (states - 1.0) - 0.5)
                })

    cmd.delete(selection)
    if model == 'calpha':
        cmd.set('ribbon_trace_atoms', 1, prefix + '*')
        cmd.show_as('ribbon', prefix + '*')
    else:
        cmd.show_as('lines', prefix + '*')
예제 #6
0
파일: solvent.py 프로젝트: torkos/MMTK
                          TranslationRemover
from MMTK.Random import randomPointInBox

# Set the number of molecules and the temperature
n_molecules = 20
temperature = 300. * Units.K

# Calculate the size of the box
density = 1. * Units.g / (Units.cm)**3
number_density = density / Molecule('water').mass()
real_size = (n_molecules / number_density)**(1. / 3.)

# Create the universe with a larger initial size
current_size = 5. * real_size
world = CubicPeriodicUniverse(
    current_size, Amber94ForceField(1.2 * Units.nm, {'method': 'ewald'}))

# Add solvent molecules at random positions, avoiding the neighbourhood
# of previously placed molecules
excluded_regions = []
for i in range(n_molecules):
    m = Molecule('water', position=randomPointInBox(current_size))
    while 1:
        s = m.boundingSphere()
        collision = 0
        for region in excluded_regions:
            if s.intersectWith(region) is not None:
                collision = 1
                break
        if not collision:
            break
예제 #7
0
    from MMTK.Proteins import Protein
    from MMTK.NormalModes import NormalModes

    from MMTK.ForceFields import DeformationForceField, CalphaForceField
    from MMTK.FourierBasis import FourierBasis, estimateCutoff
    from MMTK.NormalModes import NormalModes, SubspaceNormalModes

    model = 'calpha'
    ff = ff.lower()
    if 'deformationforcefield'.startswith(ff):
        forcefield = DeformationForceField(cutoff=cutoff / 10.)
    elif 'calphaforcefield'.startswith(ff):
        forcefield = CalphaForceField(cutoff=cutoff / 10.)
    elif 'amber94forcefield'.startswith(ff):
        from MMTK.ForceFields import Amber94ForceField
        forcefield = Amber94ForceField()
        model = 'all'
    else:
        raise NotImplementedError('unknown ff = ' + str(ff))
    if not quiet:
        print(' Forcefield:', forcefield.__class__.__name__)

    if model == 'calpha':
        selection = '(%s) and polymer and name CA' % (selection)

    f = StringIO(cmd.get_pdbstr(selection))
    conf = PDBConfiguration(f)
    items = conf.createPeptideChains(model)

    universe = InfiniteUniverse(forcefield)
    universe.protein = Protein(*items)
예제 #8
0
protein.normalizeConfiguration()

# Define density, pressure,  and temperature of the solvent.
water_density = 1.*Units.g/Units.cm**3
temperature = 300.*Units.K
pressure = 1.*Units.atm

# Calculate the box size as the boundary box of the protein plus an
# offset. Note: a much larger offset should be used in real applications.
box = protein.boundingBox()
box = box[1]-box[0]+Vector(0.5, 0.5, 0.5)

# Create a periodic universe. The force field is intentionally created with
# a rather small cutoff to speed up the solvation process.
universe = OrthorhombicPeriodicUniverse(tuple(box),
                                        Amber94ForceField(1., 1.))
universe.protein = protein

# Find the number of solvent molecules.
print(f"{MMTK.Solvation.numberOfSolventMolecules(universe,'water',water_density)} water molecules will be added")

# Scale up the universe and add the solvent molecules.
MMTK.Solvation.addSolvent(universe, 'water', water_density)
print("Solvent molecules have been added, now shrinking universe...")

# Shrink the universe back to its original size, thereby compressing
# the solvent to its real density.
MMTK.Solvation.shrinkUniverse(universe, temperature, 'solvation.nc')
print("Universe has been compressed, now equilibrating...")

# Set a better force field and add thermostat and barostat.
skipSteps = int(sys.argv[8])

print "\n--------Parameters-------------------------------"
print "Number of beads:\t" + str(nb)
print "Restraint k:\t\t" + str(k_restraint) + " kJ/mol/nm^2"
print "Restraint r0:\t\t" + str(r0_restraint) + " nm"
print "Temperature:\t\t" + str(temperature) + " K"
print "Timestep:\t\t" + str(dt) + " ps"
print "Friction:\t\t" + str(friction)
print "Equilibration Steps:\t" + str(EquilSteps)
print "Production Steps:\t" + str(ProdSteps)
print "Skip Steps:\t\t" + str(skipSteps)
print "-----------End-----------------------------------\n"

#Create Universe
universe = InfiniteUniverse(Amber94ForceField(15. * Units.Ang, None))
universe.addObject(Environment.PathIntegrals(temperature, True))

#Add 2 spcfw-q's to the universe with a separation of 3 Angstroms
ar_dist = 3.0 * Units.Ang
pos1 = Vector(0.0, 0.0, 0.0)
pos2 = Vector(ar_dist, 0.0, 0.0)
universe.addObject(Molecule('spcfw-q', position=pos1))
universe.addObject(Molecule('spcfw-q', position=pos2))

#Set the number of beads for each atom in the universe
for atom in universe.atomList():
    atom.setNumberOfBeads(nb)
universe.environmentObjectList(
    Environment.PathIntegrals)[0].include_spring_terms = False
universe._changed(True)
예제 #10
0
# coordinate origin, principal axes of inertia parallel to the coordinate axes.
protein.normalizeConfiguration()

# Define density, pressure,  and temperature of the solvent.
water_density = 1. * Units.g / Units.cm**3
temperature = 300. * Units.K
pressure = 1. * Units.atm

# Calculate the box size as the boundary box of the protein plus an
# offset. Note: a much larger offset should be used in real applications.
box = protein.boundingBox()
box = box[1] - box[0] + Vector(0.5, 0.5, 0.5)

# Create a periodic universe. The force field is intentionally created with
# a rather small cutoff to speed up the solvation process.
universe = OrthorhombicPeriodicUniverse(tuple(box), Amber94ForceField(1., 1.))
universe.protein = protein

# Find the number of solvent molecules.
print MMTK.Solvation.numberOfSolventMolecules(universe,'water',water_density),\
      "water molecules will be added"

# Scale up the universe and add the solvent molecules.
MMTK.Solvation.addSolvent(universe, 'water', water_density)
print "Solvent molecules have been added, now shrinking universe..."

# Shrink the universe back to its original size, thereby compressing
# the solvent to its real density.
MMTK.Solvation.shrinkUniverse(universe, temperature, 'solvation.nc')
print "Universe has been compressed, now equilibrating..."