def _makeUniverse(self):
     from MMTK.Proteins import Protein, PeptideChain
     from MMTK.ForceFields import CalphaForceField
     self.universe = self.raw_trajectory.universe
     self.proteins = self.universe.objectList(Protein)
     universe_calpha = MMTK.InfiniteUniverse(CalphaForceField(2.5))
     calpha_map = {}
     for protein in self.proteins:
         chains_calpha = []
         for chain in protein:
             chains_calpha.append(
                 PeptideChain(chain.sequence(), model='calpha'))
         protein_calpha = Protein(chains_calpha)
         universe_calpha.addObject(protein_calpha)
         for i in range(len(protein)):
             chain = protein[i]
             chain_calpha = protein_calpha[i]
             for j in range(len(chain)):
                 calpha_map[chain[j].peptide.C_alpha] = \
                                     chain_calpha[j].peptide.C_alpha
                 chain_calpha[j].peptide.C_alpha.setMass(1.)
     conf = self.raw_trajectory[0]
     for atom, calpha in calpha_map.items():
         calpha.setPosition(conf[atom])
     self.universe_calpha = universe_calpha
     universe_calpha.configuration()
     self.map = universe_calpha.numberOfAtoms() * [None]
     for atom, calpha in calpha_map.items():
         self.map[calpha.index] = atom.index
예제 #2
0
def initialOrientation(pdb_file, map_file, label):
    
    dmap = load(map_file)
    universe = InfiniteUniverse()
    universe.protein = Protein(pdb_file, model = 'calpha')
    universe.protein.normalizeConfiguration()

    pu = principalPoints(universe)
    pd = dmap.principalPoints()
    fits = tryOrientations(pu, pd)

    initial = copy(universe.configuration())
    for i in range(len(fits)):
        universe.applyTransformation(fits[i])
        fits[i] = (dmap.fit(universe), fits[i])
        universe.setConfiguration(initial)
    fits.sort(lambda a, b: cmp(a[0], b[0]))

    best = fits[0][0]
    i = 0
    while 1:
        fit, tr = fits[i]
        if fit > 1.5*best:
            break
        universe.setConfiguration(initial)
        universe.applyTransformation(tr)
        pdb_out = label + '%d.pdb' % (i+1)
        print "Writing %s, fit error: %10.3g" % (pdb_out, fit)
        universe.writeToFile(pdb_out)
        i = i + 1
예제 #3
0
 def setUp(self):
     self.universe = InfiniteUniverse(
         AnisotropicNetworkForceField(cutoff=5.))
     protein = Protein('insulin_calpha')
     self.universe.addObject(protein)
     self.subset1 = protein[0]
     self.subset2 = protein[1]
예제 #4
0
 def setUp(self):
     self.universe = MMTK.InfiniteUniverse(HarmonicForceField())
     self.universe.peptide = Protein('bala1')
     self.emodes = NormalModes.EnergeticModes(self.universe)
     self.rm = RigidMotionSubspace(self.universe,
                                   self.universe.peptide.residues())
     self.pd = PairDistanceSubspace(self.universe, [
         (self.universe.peptide[0][0].O, self.universe.peptide[0][-1].CH3)
     ])
예제 #5
0
def get_sasa_mmtk(selection, state=-1, hydrogens='auto', quiet=1):
    '''
DESCRIPTION

    Get solvent accesible surface area using MMTK.MolecularSurface

    http://dirac.cnrs-orleans.fr/MMTK/

    This command is very picky with missing atoms and wrong atom naming.

SEE ALSO

    stub2ala, get_sasa, get_sasa_ball
    '''
    try:
        import MMTK
    except ImportError:
        print(' ImportError: please install MMTK')
        raise CmdException

    from MMTK.PDB import PDBConfiguration
    from MMTK.Proteins import Protein
    from MMTK.MolecularSurface import surfaceAndVolume

    try:
        from cStringIO import StringIO
    except ImportError:
        from io import StringIO

    selection = selector.process(selection)
    state, quiet = int(state), int(quiet)
    radius = cmd.get_setting_float('solvent_radius')

    if hydrogens == 'auto':
        if cmd.count_atoms('(%s) and hydro' % selection) > 0:
            hydrogens = 'all'
        else:
            hydrogens = 'no_hydrogens'
    elif hydrogens == 'none':
        hydrogens = 'no_hydrogens'

    conf = PDBConfiguration(StringIO(cmd.get_pdbstr(selection)))
    system = Protein(conf.createPeptideChains(hydrogens))

    try:
        area, volume = surfaceAndVolume(system, radius * 0.1)
    except:
        print(' Error: MMTK.MolecularSurface.surfaceAndVolume failed')
        raise CmdException

    if not quiet:
        print(' get_sasa_mmtk: %.3f Angstroms^2 (volume: %.3f Angstroms^3).' %
              (area * 1e2, volume * 1e3))
    return area * 1e2
예제 #6
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)
예제 #7
0
 def test_rotation_translation(self):
     for m in [MMTK.Molecule('water'), Protein('bala1')]:
         universe = MMTK.InfiniteUniverse()
         universe.addObject(m)
         ref_conf = universe.copyConfiguration()
         universe.translateBy(MMTK.Vector(0.1, -1.3, 1.2))
         universe.rotateAroundOrigin(MMTK.Vector(0., 1., 1.), 0.7)
         tr, rms = universe.findTransformation(ref_conf)
         self.assert_(abs(rms) < 1.e-5)
         universe.applyTransformation(tr)
         self.assert_(universe.rmsDifference(ref_conf) < 1.e-5)
         axis, angle = tr.rotation().axisAndAngle()
         self.assert_(abs(angle - 0.7) < 1.e-5)
         self.assert_(
             abs(abs(N.cos(axis.angle(MMTK.Vector(0., 1., 1.)))) -
                 1) < 1.e-5)
예제 #8
0
def run(pdb1, pdb2, trajectory, nsteps, delpdb=0):
    universe = TransitionPathUniverse(CalphaForceField(2.5))
    universe.protein = Protein(pdb1, model='calpha')
    conf1 = copy(universe.configuration())
    struct2 = PDBConfiguration(pdb2).peptide_chains
    for i in range(len(universe.protein)):
        struct2[i].applyTo(universe.protein[i])
    if delpdb:
        os.unlink(pdb1)
        os.unlink(pdb2)
    tr, rms = universe.findTransformation(conf1)
    universe.applyTransformation(tr)
    conf2 =  copy(universe.configuration())
    universe.setBoundingBox(conf1, conf2)
    path = TransitionPath(universe, conf1, conf2, step_length=0.05, nmodes=50)
    path.refine(nsteps)
    path.writeBestToTrajectory(trajectory,
                               ("Transition path after %d steps, " % nsteps) +
                               ("energy %d," % path.best_penalty))
예제 #9
0
#
from MMTK import *
from MMTK.Proteins import Protein

# Import the graphics module. You can substitute other graphics
# module names to make the example use that module, but not
# everything supports the camera object, used for view points
from Scientific.Visualization import VRML2; visualization_module = VRML2
#In fact VRML, VPython and VMD do not support cameras:-
#from Scientific.Visualization import VPython; visualization_module = VPython
#from Scientific.Visualization import VRML; visualization_module = VRML
#from Scientific.Visualization import VMD; visualization_module = VMD

print "Loading protein file"
#This can be any name from the MMTK database, or a PDB file.
protein = Protein('insulin')
#Note that by default this looks for all the atoms.  Some PDB files
#don't include the hydrogens, in which case MMTK will guess them.
#Some PDB files don't even have the positions of the side chains,
#and MMTK will not be able to guess their locations.

print "Finding centre of mass and moment of inertia"
center, inertia = protein.centerAndMomentOfInertia()

print "Creating view points"
#Use the centre of mass as the centre of the picture, with the camera
#pulled back from it.
#
#X and Y are the axis of the screen
#Y is in (-ve) and out (+ve) of the screen
#
예제 #10
0
# field with crystallographic structures.
#
# Note: the simple solution in this case is just
#       insulin = Protein('insulin.pdb')
# but the explicit form shown below is necessary when any kind of
# modification is required.
#
# Load the PDB file.
configuration = PDBConfiguration('insulin.pdb')

# Construct the peptide chain objects. This also constructs positions
# for any missing hydrogens, using geometrical criteria.
chains = configuration.createPeptideChains()

# Make the protein object.
insulin = Protein(chains)

# Write out the structure with hydrogens to a new file - we will use
# it as an input example later on.
insulin.writeToFile('insulin_with_h.pdb')


#
# Second problem: read a file with hydrogens and create a structure
# without them. This is useful for analysis; if you don't need the
# hydrogens, processing is faster without them. Or you might want
# to compare structures with and without hydrogens.
#
# Load the PDB file.
configuration = PDBConfiguration('./insulin_with_h.pdb')
예제 #11
0
# field with crystallographic structures.
#
#
# Load the PDB file.
configuration = PDBConfiguration('insulin.pdb')

# Construct the peptide chain objects. This also constructs positions
# for any missing hydrogens, using geometrical criteria.
chains = configuration.createPeptideChains()

# Make the protein object.
#insulin = Protein(chains)

# Define system
universe = InfiniteUniverse(Amber99ForceField(mod_files=['frcmod.ff99SB']))
universe.protein = Protein(chains)

# Initialize velocities
universe.initializeVelocitiesToTemperature(50. * Units.K)
print 'Temperature: ', universe.temperature()
print 'Momentum: ', universe.momentum()
print 'Angular momentum: ', universe.angularMomentum()
file.write('Temperature: ' + str(universe.temperature()) + "\n")
file.write('Momentum: ' + str(universe.momentum()) + "\n")
file.write('Angular momentum: ' + str(universe.angularMomentum()) + "\n")

# Create integrator
integrator = VelocityVerletIntegrator(universe, delta_t=1. * Units.fs)

# Heating and equilibration
integrator(
예제 #12
0
# evaluated automatically.
#

from MMTK import *
from MMTK.PDB import PDBConfiguration
from MMTK.Proteins import Protein

# Read PDB configuration and create MMTK objects for all peptide chains.
# A C-alpha model is used to reduce the system size. You can remove
# 'model="calpha"' to get an all-atom model.
conf = PDBConfiguration('insulin.pdb')
chains = Collection(conf.createPeptideChains(model="calpha"))

# Copy and transform the objects representing the asymmetric unit in order
# to obtain the contents of the unit cell.
chains = conf.asuToUnitCell(chains)

# Construct a periodic universe representing the unit cell.
universe = conf.createUnitCellUniverse()

# Add each chain as one protein. If the unit cell contains multimers,
# the chains must be combined into protein objects by hand,
# as no corresponding information can be extracted from the PDB file.
for chain in chains:
    universe.addObject(Protein(chain))

# If VMD has been defined as the PDB viewer, this will not only show
# the molecules, but also the shape of the universe (which
# equals the unit cell).
universe.view()
proteins = universe.objectList(Protein)

# Construct an initial configuration in which the proteins are contiguous.
conf = universe.contiguousObjectConfiguration(proteins)

# Construct a C_alpha representation and a mapping from the "real"
# C_alpha atoms to their counterparts in the reduced model.
universe_calpha = InfiniteUniverse()
index = 0
map = []
for protein in proteins:
    chains_calpha = []
    for chain in protein:
        chains_calpha.append(PeptideChain(chain.sequence(),
                                          model='calpha'))
    protein_calpha = Protein(chains_calpha)
    universe_calpha.addObject(protein_calpha)
    for i in range(len(protein)):
        chain = protein[i]
        chain_calpha = protein_calpha[i]
        for j in range(len(chain)):
            r = conf[chain[j].peptide.C_alpha]
            chain_calpha[j].peptide.C_alpha.setPosition(r)
            chain_calpha[j].peptide.C_alpha.index = index
            map.append(chain[j].peptide.C_alpha.index)
            index = index + 1
universe_calpha.configuration()

# Open the new trajectory for just the interesting objects.
trajectory_calpha = Trajectory(universe_calpha, 'calpha_trajectory.nc', 'w')
예제 #14
0
from MMTK import *
from MMTK.Proteins import Protein
from MMTK.NormalModes import EnergeticModes
from MMTK.ForceFields import CalphaForceField
from MMTK.Field import AtomicVectorField
from MMTK.Database import PDBPath
from Scientific.Visualization import Chimera
import chimera

# Load the molecule into Chimera
filename = PDBPath("insulin.pdb")
chimera.runCommand("open pdb:%s" % filename)

# Create a simulation universe containing the protein
universe = InfiniteUniverse(CalphaForceField())
universe.addObject(Protein(filename, model='calpha'))

# Calculate normal modes
modes = EnergeticModes(universe)

# Create the vector field corresponding to the first non-zero mode
# using a grid spacing of 0.5 nm.
field = AtomicVectorField(universe, 0.5, modes[6])

# Create graphics objects for the vector fields.
# The arrows are yellow and their lengths are multiplied by 80.
# Only displacement vectors of lengths between 0. and 0.01 will be shown.
# (This restriction is not necessary for this example, but used for
#  illustration.)
graphics = field.graphicsObjects(color='yellow',
                                 scale=80.,
예제 #15
0
파일: two_models.py 프로젝트: torkos/MMTK
# Set up an all-atom model and a C-alpha model for the same protein,
# with a facility for copying configurations back and forth.
#

from MMTK import *
from MMTK.Proteins import Protein

# Create an all-atom universe and a c-alpha universe
universe_aa = InfiniteUniverse()
universe_ca = InfiniteUniverse()

# Add the protein to both universes
protein_aa = Protein('insulin.pdb')
universe_aa.addObject(protein_aa)
protein_ca = Protein('insulin.pdb', model='calpha')
universe_ca.addObject(protein_ca)

# Set up a dictionary mapping aa atoms to ca atoms
atom_map = {}
for ichain in range(len(protein_aa)):
    chain_aa = protein_aa[ichain]
    chain_ca = protein_ca[ichain]
    for iresidue in range(len(chain_aa)):
        ca_aa = chain_aa[iresidue].peptide.C_alpha
        ca_ca = chain_ca[iresidue].peptide.C_alpha
        atom_map[ca_aa] = ca_ca

# Copy the aa configuration to the ca configuration
for ca_aa, ca_ca in atom_map.items():
    ca_ca.setPosition(ca_aa.position())
예제 #16
0
def generate_ramachandran(pdb_id):
    rama_GENERAL = "General"
    rama_GLYCINE = "Glycine"
    rama_PROLINE = "Proline"
    rama_PRE_PRO = "Pre-Pro"
    ramachandran_types = [rama_GENERAL,rama_GLYCINE,rama_PROLINE,rama_PRE_PRO]

    # I have used the same colours as RAMPAGE
    # http://raven.bioc.cam.ac.uk/rampage.php
    rama_settings = {"General" : ([0, 0.0005, 0.02, 1],
                      ['#FFFFFF','#B3E8FF','#7FD9FF'],
                      "top500angles/pct/rama/rama500-general.data"),
                      # or rama500-general-nosec.data
         "Glycine" : ([0, 0.002,  0.02, 1],
                      ['#FFFFFF','#FFE8C5','#FFCC7F'],
                      "top500angles/pct/rama/rama500-gly-sym.data"),
                      # or rama500-gly-sym-nosec.data
         "Proline" : ([0, 0.002,  0.02, 1],
                      ['#FFFFFF','#D0FFC5','#7FFF8C'],
                      "top500angles/pct/rama/rama500-pro.data"),
         "Pre-Pro" : ([0, 0.002,  0.02, 1],
                      ['#FFFFFF','#B3E8FF','#7FD9FF'],
                      "top500angles/pct/rama/rama500-prepro.data")}
         #P.S. Also rama500-ala-nosec.data

    def load_data_file(filename) :
        STEP=2
        HALF_STEP=1
        STEP = HALF_STEP*2
        lower_bounds = range(-180, 180, STEP)
        mid_points = range(-180+HALF_STEP, 180+HALF_STEP, STEP)
        upper_bounds = range(-180+STEP, 180+STEP, STEP)

        data = numpy.array([[0.0 for x in mid_points] for y in mid_points])

        """
        # Table name/description: "Top500 General case (not Gly, Pro, or pre-Pro) B<30"
        # Number of dimensions: 2
        # For each dimension, 1 to 2: lower_bound  upper_bound  number_of_bins  wrapping
        #   x1: -180.0 180.0 180 true
        #   x2: -180.0 180.0 180 true
        # List of table coordinates and values. (Value is last number on each line.)
        -179.0 -179.0 0.0918642445114388
        -179.0 -177.0 0.07105717866463215
            ...
            """
        input_file = open(filename,"r")
        for line in input_file :
            #Strip the newline character(s) from the end of the line
            if line[-1]=="\n" : line = line[:-1]
            if line[-1]=="\r" : line = line[:-1]
            if line[0]=="#" :
                #comment
                pass
            else :
                #data
                parts = line.split()
                assert len(parts)==3
                
                x1 = float(parts[0]) #phi
                x2 = float(parts[1]) #psi
                value = float(parts[2])
                
                assert x1 == float(int(x1))
                assert x2 == float(int(x2))
                i1 = mid_points.index(int(x1))
                i2 = mid_points.index(int(x2))
                
                data[i1,i2]=value
        input_file.close()
        return (data, lower_bounds, mid_points, upper_bounds)

    #filename = "stat/rama/rama500-general.data"
    #data, lower_bounds, mid_points, upper_bounds = load_data_file(filename)
    ##print sum(sum(data))

    r.library("MASS")

    #print "Creating R function",
    r("""
    ramachandran.plot <- function(x.scatter, y.scatter,
        x.grid = seq(0, 1, len = nrow(z)), y.grid = seq(0, 1, len = ncol(z)), z.grid,
        xlim = range(x.grid, finite = TRUE), ylim = range(y.grid, finite = TRUE),
        zlim = range(z.grid, finite = TRUE), levels = pretty(zlim, nlevels),
        nlevels = 20, color.palette = cm.colors, col = color.palette(length(levels) -
            1), plot.title="", plot.axes, key.title, key.axes, asp = NA,
        xaxs = "i", yaxs = "i", las = 1, axes = TRUE, frame.plot = axes,
        ...)
    {
        if (missing(z.grid)) {
            stop("no 'z.grid' matrix specified")
        }
        else if (is.list(x.grid)) {
            y.grid <- x.grid$y
            x.grid <- x.grid$x
        }
        if (any(diff(x.grid) <= 0) || any(diff(y.grid) <= 0))
            stop("increasing 'x.grid' and 'y.grid' values expected")

        plot.new()
        plot.window(xlim, ylim, "", xaxs = xaxs, yaxs = yaxs, asp = asp)

        if (!is.matrix(z.grid) || nrow(z.grid) <= 1 || ncol(z.grid) <= 1)
            stop("no proper 'z.grid' matrix specified")
        if (!is.double(z.grid))
            storage.mode(z.grid) <- "double"
        .filled.contour(as.double(x.grid), as.double(y.grid), z.grid, as.double(levels), 
                                col = col)

        if (!(missing(x.scatter)) && !(missing(y.scatter))) {
            plot.xy(xy.coords(x.scatter,y.scatter,NULL,NULL,NULL,NULL),
                    xlim=xlim, ylim=ylim, xlab="", ylab="", asp=asp,
                    type="p", pch=20, cex=0.1)
        }
            
        if (missing(plot.axes)) {
            if (axes) {
                title(main=plot.title, xlab=expression(phi), ylab=expression(psi))
                axis(1, at=c(-180,-90,0,90,180))
                axis(2, at=c(-180,-90,0,90,180))
            }
        }
        else plot.axes
        if (frame.plot)
            box()
        if (missing(plot.title))
            title(...)
        else plot.title
        invisible()
    }
    """)
    #print "Done"


    def degrees(rad_angle) :
        """Converts and angle in radians to degrees, mapped to the range [-180,180]"""
        angle = rad_angle * 180 / math.pi
        #Note this assume the radians angle is positive as that's what MMTK does
        while angle > 180 :
            angle = angle - 360
        return angle

    def next_residue(residue) :
        """Expects an MMTK residue, returns the next residue in the chain, or None"""
        #Proteins go N terminal --> C terminal
        #The next reside is bonded to the C of this atom...
        for a in residue.peptide.C.bondedTo():
            if a.parent.parent != residue:
                return a.parent.parent
        return None


    def residue_amino(residue) :
        """Expects an MMTK residue, returns the three letter amino acid code in upper case"""
        if residue :
            return residue.name[0:3].upper()
        else :
            return None

    def residue_ramachandran_type(residue) :
        """Expects an MMTK residue, returns ramachandran 'type' (General, Glycine, Proline or Pre-Pro)"""
        if residue_amino(residue)=="GLY" :
            return rama_GLYCINE
        elif residue_amino(residue)=="PRO" :
            return rama_PROLINE
        elif residue_amino(next_residue(residue))=="PRO" :
            #exlcudes those that are Pro or Gly
            return rama_PRE_PRO
        else :
            return rama_GENERAL

    scatter_phi = dict()
    scatter_psi = dict()
    for ramachandran_type in ramachandran_types :
        scatter_phi[ramachandran_type]=[]
        scatter_psi[ramachandran_type]=[]

    pdb_filename = "../data/%s.pdb" % pdb_id

    #print "Loading PDB file: " + pdb_filename
    #protein = MMTK.Proteins.Protein("1HMP.pdb", model="no_hydrogens")
    # Load the PDB file, ignore the hydrogrens, and then build a model of the peptides:
    configuration = PDBConfiguration(pdb_filename)
    configuration.deleteHydrogens()
    protein = Protein(configuration.createPeptideChains(model = "no_hydrogens"))
    for chain in protein :
        #print chain.name
        for residue in chain :
            phi, psi = residue.phiPsi()
            #print residue.name, phi, psi
            if phi and psi :
                ramachandran_type = residue_ramachandran_type(residue)
                assert ramachandran_type in ramachandran_types
                scatter_phi[ramachandran_type].append(degrees(phi))
                scatter_psi[ramachandran_type].append(degrees(psi))
            assert len(scatter_phi) == len(scatter_psi)
        
    #print "Done"

    png_filename = "ppii%d%s.png" % (random.randint(0, 1000000), pdb_id)
    png_filepath = "../tmp/" + png_filename
    png_command = 'png("' + png_filepath + '")'

    #print 

    r(png_command)

    #To get four plots on one page, you could use :
    #
    #r.split_screen([2,2]) #split into two by two screen
    #
    #Or:
    #
    #r.layout(Numeric.array([[1,2],[3,4]]), respect=True)
    #
    #But I went for simply:

    #r.par(mfrow=[2,2])

    #for (i,ramachandran_type) in enumerate(ramachandran_types) :
    #pdf_filename = "../%s_%s.pdf" % (pdb_id, ramachandran_type)
    (rama_levels, rama_colors, rama_filename) = rama_settings["General"]
    
    #print "Loading data file: " + rama_filename,
    data, lower_bounds, mid_points, upper_bounds = load_data_file(rama_filename)
    #print "Done"

    ##print "Creating PDF output file: " + pdf_filename,
    #r.pdf(pdf_filename)
    #r.plot(scatter_phi, scatter_psi)

    #print "Generating quadrant %i, %s" % (i+1, ramachandran_type)
    #r.screen(i+1)

    #Use small margins to make the plots nice and big,
    #and specify a SQUARE plot area (to go with aspect ratio, asp=1)
    #r.par(mar = [2, 2, 2, 2], pty="s")

    #This function will do a Ramachandran plot in the next quadrant
    #which we setup using par(mfrow-...)
    r.ramachandran_plot(x_scatter=scatter_phi[ramachandran_type],
                        y_scatter=scatter_psi[ramachandran_type], 
                        x_grid=mid_points, y_grid=mid_points, z_grid=data,
                        xlim=[-180,180], ylim=[-180,180], asp=1.0,
                        plot_title="Ramachandran plot of " + pdb_id, drawlabels=False,
                        levels=rama_levels, col=rama_colors)
    #print ramachandran_type + " Done"

    r("dev.off()")
    #print "Done"
    return '<img src="/~jean/projet/tmp/' + png_filename + '"/>'
예제 #17
0
파일: rotamers.py 프로젝트: torkos/MMTK
# Modify sidechain dihedral angles
#

from MMTK import *
from MMTK.Proteins import Protein
from MMTK.Trajectory import Trajectory, SnapshotGenerator, TrajectoryOutput
from Scientific import N

# Construct system: lysozyme in vaccuum
universe = InfiniteUniverse()
universe.protein = Protein('~/hao/proteins/PDB/193l.pdb')

# Select residues to rotate
# (this particular choice here is completely arbitrary)
residues = [universe.protein[0][i] for i in [11, 35, 68, 110]]

# Create trajectory
trajectory = Trajectory(universe, "rotamers.nc", "w", "Sidechain rotations")

# Create the snapshot generator
snapshot = SnapshotGenerator(
    universe, actions=[TrajectoryOutput(trajectory, ["all"], 0, None, 1)])

# Perform sidechain rotations and write the configurations
snapshot()
for residue in residues:
    print(f"{residue}")
    chi = residue.chiAngle()
    for angle in N.arange(-N.pi, N.pi, N.pi / 10.):
        chi.setValue(angle)
        print(f"{angle}")
예제 #18
0
    # Only arrow data is stored for later extraction
    def Arrow(self, point1, point2, radius, **attributes):
        self.arrows.append((point1, point2))

    def Material(self, **attributes):
        return None

    def DiffuseMaterial(self, color):
        return None

    def EmissiveMaterial(self, color):
        return None


# Create the system
universe = InfiniteUniverse(CalphaForceField())
universe.protein = Protein('insulin', model='calpha')
# Calculate the normal modes
modes = NormalModes(universe)

# Generate the vector field for the first non-zero mode
vector_field = AtomicVectorField(universe, 0.5, modes[6])

# Generate the graphics data
graphics = DummyGraphics()
vector_field.graphicsObjects(graphics_module=graphics)

# Print the arrow coordinates
for point1, point2 in graphics.arrows:
    print(f"{point1} {point2}")
예제 #19
0
# Analyze a conformational change in terms of the contributions of
# each normal mode.
#
# Note: download 1SU4 and 1T5T from the PDB before running this script

from MMTK import *
from MMTK.PDB import PDBConfiguration
from MMTK.Proteins import Protein
from MMTK.ForceFields import CalphaForceField
from MMTK.NormalModes import EnergeticModes
import pylab
import numpy

# Make a universe for the first configuration
universe = InfiniteUniverse(CalphaForceField())
universe.protein = Protein('1SU4.pdb', model='calpha')
conf_1SU4 = universe.copyConfiguration()

# Apply the second configuration and do a rigid-body superposition fit
PDBConfiguration('1T5T.pdb').applyTo(universe.protein)
tr, rms = universe.findTransformation(conf_1SU4)
universe.applyTransformation(tr)
conf_1T5T = universe.copyConfiguration()

# Set first configuration and calculate normal modes
universe.setConfiguration(conf_1SU4)
modes = EnergeticModes(universe, 300. * Units.K)

# Calculate the normalized difference vector
diff = (conf_1T5T - conf_1SU4).scaledToNorm(1.)
예제 #20
0
 def setUp(self):
     self.universe = MMTK.InfiniteUniverse(Amber99ForceField())
     self.universe.peptide = Protein('bala1')
예제 #21
0
#
# - A molecular dynamics run at constant pressure and temperature is
#   used to put the system into a well-defined thermodynamic state.
#

from MMTK import *
from MMTK.Proteins import Protein
from MMTK.ForceFields import Amber94ForceField
from MMTK.Environment import NoseThermostat, AndersenBarostat
from MMTK.Trajectory import Trajectory, TrajectoryOutput, LogOutput
from MMTK.Dynamics import VelocityVerletIntegrator, VelocityScaler, \
                          BarostatReset, TranslationRemover
import MMTK.Solvation

# Create the solute.
protein = Protein('bala1')

# Put the solvent in a standard configuration: center of mass at the
# 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)
from MMTK import *
from MMTK.Proteins import Protein

# Import the graphics module. You can substitute other graphics
# module names to make the example use that module, but not
# everything supports the camera object, used for view points
from Scientific.Visualization import VRML2
visualization_module = VRML2
#In fact VRML, VPython and VMD do not support cameras:-
#from Scientific.Visualization import VPython; visualization_module = VPython
#from Scientific.Visualization import VRML; visualization_module = VRML
#from Scientific.Visualization import VMD; visualization_module = VMD

print "Loading protein file"
#This can be any name from the MMTK database, or a PDB file.
protein = Protein('insulin')
#Note that by default this looks for all the atoms.  Some PDB files
#don't include the hydrogens, in which case MMTK will guess them.
#Some PDB files don't even have the positions of the side chains,
#and MMTK will not be able to guess their locations.

print "Finding centre of mass and moment of inertia"
center, inertia = protein.centerAndMomentOfInertia()

print "Creating view points"
#Use the centre of mass as the centre of the picture, with the camera
#pulled back from it.
#
#X and Y are the axis of the screen
#Y is in (-ve) and out (+ve) of the screen
#
예제 #23
0
# A normal mode calculation in the subspace of a part of the total system.
#

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

from Scientific import N

# Construct system
universe = InfiniteUniverse(Amber94ForceField())
universe.protein1 = Protein('bala1')
universe.protein2 = Protein('bala1')
universe.protein2.translateBy(Vector(1., 0., 0.))


# Define normal mode subspace
class SubsetSubspace(Subspace):
    def __init__(self, universe, objects):
        vectors = []
        for a in objects.atomList():
            for d in [
                    Vector(1., 0., 0.),
                    Vector(0., 1., 0.),
                    Vector(0., 0., 1.)
            ]:
                v = ParticleProperties.ParticleVector(universe)
예제 #24
0
#
# - A molecular dynamics run at constant pressure and temperature is
#   used to put the system into a well-defined thermodynamic state.
#

from MMTK import *
from MMTK.Proteins import Protein
from MMTK.ForceFields import Amber94ForceField
from MMTK.Environment import NoseThermostat, AndersenBarostat
from MMTK.Trajectory import Trajectory, TrajectoryOutput, LogOutput
from MMTK.Dynamics import VelocityVerletIntegrator, VelocityScaler, \
                          BarostatReset, TranslationRemover
import MMTK.Solvation

# Create the solute.
protein = Protein('bala1')

# Put the solvent in a standard configuration: center of mass at the
# 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)
예제 #25
0
 def setUp(self):
     # Pick a proline residue because of its cycle
     self.protein = Protein("insulin.pdb")
     self.chain = self.protein[1]
     self.res = self.chain[27]
예제 #26
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 + '*')
예제 #27
0
        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
예제 #28
0
    the input configuration becomes an energy minimum by construction.
    The nonbonded terms are replaced by a generic short-ranged
    deformation term.

    For a description of this force field, see:
     | Hinsen & Kneller, J. Chem. Phys. 24, 10766 (1999)
    For an application to DNA, see:
     | Viduna, Hinsen & Kneller, Phys. Rev. E 3, 3986 (2000)
    """

    def __init__(self, fc_length = 0.45, cutoff = 0.6, factor = 400.):
        self.arguments = (fc_length, cutoff, factor)
        self.bonded = BondForceField(1, 1, 1)
        self.midrange = MidrangeForceField(fc_length, cutoff, factor)
        apply(CompoundForceField.__init__, (self, self.bonded, self.midrange))

    description = ForceField.description


if __name__ == '__main__':

    from MMTK import *
    from MMTK.Proteins import Protein
    from MMTK.NormalModes import NormalModes
    world = InfiniteUniverse(HarmonicForceField(bonds=1,angles=1,dihedrals=1))
    world.protein = Protein('bala1')
    print world.energy()
    modes = NormalModes(world)
    for m in modes:
        print m
예제 #29
0
from MMTK import *
from MMTK.Proteins import Protein
from MMTK.ForceFields import Amber94ForceField
import sys

pdb = sys.argv[1]
test = Protein(pdb)
universe = InfiniteUniverse(Amber94ForceField())
universe.addObject(test)

print universe.energy()
for i in universe.energyTerms():
    print i, ":",
    print universe.energyTerms()[i]

#print "angular moment:", test.angularMomentum()
print "charge :", universe.charge()
print "degrees of freedom :", universe.degreesOfFreedom()
print "dipole moment:", universe.dipole()
#print "kinetic energy :", test.kineticEnergy()
print "mas :", universe.mass()
#print "momentum :", g.momentum()
print " GroupOfAtoms numberOfAtoms:", universe.numberOfAtoms()
#print " temperature:", universe.temperature ()
 def setUp(self):
     self.universe = MMTK.InfiniteUniverse(Amber99ForceField())
     self.universe.peptide = Protein('bala1')
     self.subspace = RigidMotionSubspace(self.universe,
                                         self.universe.peptide.residues())
# Generate a protein backbone representation plus an indication
# of the principal axes of inertia by arrows.
#
from MMTK import *
from MMTK.Proteins import Protein
from Scientific import N, LA

# Import the graphics module. Substitute any other graphics
# module name to make the example use that module.
from Scientific.Visualization import VRML2
module = VRML2

# Create the protein and find its center of mass and tensor of inertia.
protein = Protein('insulin')
center, inertia = protein.centerAndMomentOfInertia()

# Diagonalize the inertia tensor and scale the axes to a suitable length.
mass = protein.mass()
diagonal, directions = LA.eigenvectors(inertia.array)
diagonal = N.sqrt(diagonal / mass)

# Generate the backbone graphics objects.
graphics = protein.graphicsObjects(graphics_module=module,
                                   model='backbone',
                                   color='red')

# Add an atomic wireframe representation of all valine sidechains
valines = protein.residuesOfType('val')
sidechains = valines.map(lambda r: r.sidechain)
graphics = graphics + sidechains.graphicsObjects(
    graphics_module=module, model='wireframe', color='blue')
예제 #32
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])
예제 #33
0
def fit(pdb_file, map_file, energy_cutoff, label, trajectory_freq):
    dmap = load(map_file)
    universe = InfiniteUniverse(CalphaForceField(2.5))
    universe.protein = Protein(pdb_file, model='calpha')
    set_distances(universe.protein)

    modes = calc_modes(universe, 3 * universe.numberOfAtoms())
    for nmodes in range(6, len(modes)):
        if modes[nmodes].frequency > energy_cutoff * modes[6].frequency:
            break

    if trajectory_freq > 0:
        trajectory_filename = 'fit_%s_m%d.nc' % (label, nmodes)
        print "Fit trajectory:", trajectory_filename
        trajectory = Trajectory(
            universe, trajectory_filename, 'w',
            'Density fit %s using %d modes' % (label, nmodes))
        actions = [
            TrajectoryOutput(trajectory, ["configuration", "fit_error"], 0,
                             None, 1)
        ]
        snapshot = SnapshotGenerator(universe, actions=actions)
        snapshot.available_data.append('fit_error')

    amplitude = 0.1
    i = 0
    fit = []
    windex = 0
    protocol_filename = 'fit_%s_m%d_fiterror.txt' % (label, nmodes)
    print "Fit error protocol file:", protocol_filename
    protocol = file(protocol_filename, 'w')

    nmc = 2 * nmodes
    modes = calc_modes(universe, nmc)
    windows = N.arange(10.) * modes[nmodes].frequency / 10.

    while 1:
        f, gradient = dmap.fitWithGradient(universe)
        fit.append(f)
        print >> protocol, i, fit[-1]
        protocol.flush()
        if len(fit) > 1 and fit[-1] > fit[-2]:
            amplitude /= 2.
        random_width = gradient.norm()*(random/100.) \
                       / N.sqrt(universe.numberOfAtoms())
        random_vector = randomParticleVector(universe, random_width)
        gradient = gradient + random_vector
        displacement = ParticleVector(universe)
        for n in range(nmodes):
            m = modes[n]
            if n < 6:
                weight = 5. * weight_function(modes[6], windows[windex])
            else:
                weight = weight_function(m, windows[windex])
            displacement = displacement + \
                           weight*m.massWeightedDotProduct(gradient)*m
        displacement = displacement * amplitude / displacement.norm()
        universe.setConfiguration(universe.configuration() + displacement)
        fix_structure(universe.protein)
        if trajectory_freq > 0 and i % trajectory_freq == 0:
            snapshot(data={'fit_error': fit[-1]})
        i = i + 1
        if i % 20 == 0:
            modes = calc_modes(universe, nmc)
        if i % 10 == 0 and i > 50:
            convergence = (fit[-1] - fit[-11]) / (fit[30] - fit[20])
            if convergence < 0.05:
                break
            if convergence < 0.2:
                windex = min(windex + 1, len(windows) - 1)
            if convergence < 0.1:
                amplitude = 0.5 * amplitude
    protocol.close()

    if trajectory_freq > 0:
        trajectory.close()

    pdb_out = 'fit_%s_m%d.pdb' % (label, nmodes)
    print "Writing final structure to", pdb_out
    universe.writeToFile(pdb_out)