Пример #1
0
    def pred(c) :
        return inspect.isclass(c) and c.__module__ == "sgenlib.mdactions" and \
                issubclass(c,mdactions.TrajectoryAction) and \
                c.__name__ != "TrajectoryAction"

    def setup_action(cls,arguments):
        action = cls(processor)
        argparser = argparse.ArgumentParser()
        action.add_arguments(argparser)
        action.setup(argparser.parse_args(arguments))

    actionclasses = {name.lower():c
        for name,c in inspect.getmembers(sys.modules["sgenlib.mdactions"],pred)}

    processor = moldyn.TrajectoryProcessor("Analyze MD trajectories",dosubsample=True)
    processor.argparser.add_argument("-c","--commands",help="a file with analysis commands")
    processor.setup()

    with open(processor.args.commands,"r") as f :
        for line in f.readlines():
            action = line.strip().split()[0].lower()
            arguments = line.strip().split()[1:]
            try :
                cls = actionclasses[action]
            except:
                try:
                    cls = actionclasses[action+"analysis"]
                except:
                    print "Skipping unknown action %s"%action
                else:
Пример #2
0
# Author: Samuel Genheden [email protected]

"""
Program to transform a molecular dynamics trajectory.

It can
1) Make molecules whole over periodic boxes
2) Center a protein in the middle of the box
3) Align protein with an RMSD fit

Works only for rectangular boxes.

Examples:
    md_centerwhole.py -f sim.dcd -s ref.pdb
    md_centerwhole.py -f sim.dcd -s ref.pdb --noalign
"""

from sgenlib import moldyn
from sgenlib import mdactions

if __name__ == '__main__' :

  processor = moldyn.TrajectoryProcessor("Center and make a trajectory whole")
  analysis = mdactions.CenterWholeAlign(processor)
  processor.setup(printargs=True)
  processor.process()
Пример #3
0
# Author: Samuel Genheden [email protected]
"""
Program to calculate the RMSD of an atom selection

Examples:
md_rmsd.py -f md2_whole.xtc -s md1.gro
md_rmsd.py -f md2_whole.xtc -s md1.gro  --sel "protein and name CA"
"""

from sgenlib import moldyn
from sgenlib import mdactions

if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor(
        "Calculate RMSD of an atom selection")
    analysis = mdactions.RmsdAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #4
0
            1.5*(self.cbetas.positions-self.calphas.positions)
        mddist.self_distance_array(proj,
                                   box=self.processor.currbox,
                                   result=self.tempmat)
        self.contacts += self.tempmat

    def finalize(self):
        self.contacts /= float(self.processor.nprocessed)
        self.contacts *= 0.1  # To  Nm
        outmat = np.zeros([len(self.calphas), len(self.calphas)])
        k = 0
        for i in range(len(self.calphas)):
            for j in range(i + 1, len(self.calphas)):
                outmat[i, j] = self.contacts[k]
                outmat[j, i] = self.contacts[k]
                k += 1

        with open(self.out, "w") as f:
            for i in range(outmat.shape[0]):
                for j in range(outmat.shape[1]):
                    f.write("%.3f\t" % outmat[i, j])
                f.write("\n")


if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor("Calculate contact matrix")
    analysis = ContactMatrixAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #5
0
            for sel in self.solute:
                p = sel.get_positions()
                if self.zero == "xy":
                    p[:, 0:2] = 0.0
                _accumulate_density(p, refcom)

    def finalize(self):
        if len(self.solute) == 1:
            if not self.peratom:
                n = len(self.solute[0].residues)
            else:
                n = len(self.solute[0])
        else:
            n = len(self.solute) * len(self.solute[0])
        norm = 1 / float(self.processor.nprocessed * n * self.resolution)
        with open(self.out, "w") as f:
            if self.expand:
                for d, e, in zip(self.density[::-1][1:], -self.edges[::-1]):
                    f.write("%.2f %d %.6f\n" % (e, d, float(d) * norm))
            for d, e in zip(self.density[:-1], self.edges):
                f.write("%.2f %d %.6f\n" % (e, d, float(d) * norm))


if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor(
        "Calculate the RDF of solute in a membrane")
    analysis = SolMemRdf(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #6
0
        f.savefig(self.outpre + ".png", format="png")

    def _plot_trace(self, trace, axis, idx):
        """
        Plot the trace, but make breaks if the
        atoms pass over the periodic box so that very long lines aren't drawn
        """
        xy = [trace[0].value]
        for prevrecord, record in zip(trace[:-1], trace[1:]):
            if np.abs(prevrecord.value[0]-record.value[0]) > self.halfbox[0] or \
                np.abs(prevrecord.value[1]-record.value[1]) > self.halfbox[1] :
                xy = np.asarray(xy)
                axis.plot(xy[:, 0], xy[:, 1], "-", color=colors.color(idx))
                xy = [record.value]
            else:
                xy.append(record.value)
        xy = np.asarray(xy)
        axis.plot(xy[:, 0], xy[:, 1], "-", color=colors.color(idx))
        axis.set_xlim(0, self.box[0])
        axis.set_ylim(0, self.box[1])
        axis.set_aspect('equal')


if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor(
        "Calculate the plane trace of atoms")
    analysis = PlaneTraceAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #7
0
# Author: Samuel Genheden [email protected]
"""
Program to calculate membrane densities and bulk properties from them

Prints out the results in SI units

Examples:
    md_membulk.py -f md2.xtc -s md2.gro
"""

from sgenlib import moldyn
from sgenlib import mdactions

if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor(
        "Calculate membrane densitiy properties", dosubsample=True)
    analysis = mdactions.MemBulkAnalysis(processor)
    processor.setup()
    processor.process()
Пример #8
0
# Author: Samuel Genheden [email protected]
"""
Program to strip atoms from a trajectory

Examples:
md_strip.py -f md2_whole.xtc -s md1.gro --sel "name SOL"
"""

from sgenlib import moldyn
from sgenlib import mdactions

if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor("Strip atoms from a trajectory")
    analysis = mdactions.StripAtoms(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #9
0
# Author: Samuel Genheden [email protected]
"""
Program to calculate the orientation of a solute
Calculate the orientation for each solute, does not average

Examples:
    md_solorient.py -f sim.dcd -s ref.pdb --mask "name C1" "name C2"
    md_solorient.py -f sim.dcd -s ref.pdb --mask "name C1" "name C2" --axis 1.0 0.3 0.5
"""

from sgenlib import moldyn
from sgenlib import mdactions

if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor("Calculte the solute orientation")
    analysis = mdactions.SoluteOrientation(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #10
0
# Author: Samuel Genheden [email protected]
"""
Program to calculate angle between the principal axis
of a selection and an arbitrary vector

By default is calculates the principal axis of the CA atoms
towards the z-axis.

Examples:
    md_principal.py -f sim.dcd -s ref.pdb
"""

from sgenlib import moldyn
from sgenlib import mdactions

if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor(
        "Calculte the principcal axis of a molecule and it angles with an axis"
    )
    analysis = mdactions.PrincipalAxisAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #11
0
        r = self.water.positions - self.copper.positions
        d = sel = np.sqrt(np.sum(r * r, axis=1))
        self.wcoordination.extend([_calc_coord(self.water.positions[i,:], normal, origin) \
                    for i, d in enumerate(d) if d <= self.cutoff])
        n = np.sum(d <= self.cutoff)
        self.incontact.append(mdactions.MDRecord(self.processor.currtime, n))

    def finalize(self):
        self.records = self.bonddata
        self._write_records(postfix="_bonds.txt")

        self.records = self.incontact
        self._write_records(postfix="_wcontacts.txt")

        self.records = self.coordination
        self._write_records(postfix="_coordination.txt")

        self.wcoordination = np.asarray(self.wcoordination)
        with open(self.out + "_wcoordination.txt", "w") as f:
            for i, c in enumerate(self.wcoordination):
                f.write("%d %.3f\n" % (i + 1, c))


if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor("Analyse metal site")
    analysis = MetalSiteAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #12
0
        com = np.asarray([r.center_of_geometry() for r in self.lipid.residues])
        midz = self.head.positions[:, 2].mean()
        lowsel = com[:, 2] < midz
        uppsel = np.logical_not(lowsel)
        com[:, 2] = 0.0
        _add_distance(com[lowsel, :], self.processor.currsnap.dimensions)
        _add_distance(com[uppsel, :], self.processor.currsnap.dimensions)

    def finalize(self):
        self.samples = np.asarray(self.samples)
        edges = np.arange(self.samples.min(), self.samples.max()+ \
            self.resolution, self.resolution)
        his, b = np.histogram(self.samples, edges)
        dens, b = np.histogram(self.samples, edges, density=True)
        mid = 0.5 * (edges[1:] + edges[:-1])
        with open(self.out, "w") as f:
            f.write("# Mean = %.3f \n# Std = %.3f \n# Median = %.3f\n" %
                    (self.samples.mean(), self.samples.std(),
                     np.median(self.samples)))
            for e, h, d in zip(mid, his, dens):
                f.write("%.2f %d %.6f\n" % (e, h, d))


if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor(
        "Calculate neighbor distance distribution")
    analysis = LipidNeighborAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #13
0
    def finalize(self):
        self._write_records(".natm")
        self.records = []
        for msd  in self.msds[1:] :
            av = np.asarray(msd.value).mean()
            std = np.asarray(msd.value).std() / np.sqrt(len(msd))
            self.records.append(mdactions.MDRecord(msd.time, [av,std]))
        if self.dodiff :
            msd = np.asarray([e.value[0] for e in self.records])
            time = np.asarray([e.time for e in self.records])
            imin = int(np.floor(0.1*msd.shape[0]))
            imax = int(np.ceil(0.9*msd.shape[0]))
            if not self.inplane and not self.direction :
                ndof = 3
            elif self.inplane:
                ndof = 2
            elif self.direction:
                ndof = 1
            diff = np.polyfit(time[imin:imax],msd[imin:imax],1)[0]/(2.0*ndof) * 10
            print "Diffusion (1e^-5 cm^2/s): %.5f"%diff
        self._write_records()

if __name__ == '__main__' :

    processor = moldyn.TrajectoryProcessor("Calculate the MSD of a group of atoms",
                                            dosubsample=True)
    analysis = MsdAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #14
0
# Author: Samuel Genheden [email protected]

"""
Program to calculate the radius of gyration for a solute
Calculate the radius for each residue of the selection

Examples:
    md_gyration.py -f sim.dcd -s ref.pdb --mask "resname SOL"
"""

from sgenlib import moldyn
from sgenlib import mdactions

if __name__ == '__main__' :

    processor = moldyn.TrajectoryProcessor("Calculte the radius of gyration")
    analysis = mdactions.SoluteGyration(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #15
0
# Author: Samuel Genheden [email protected]

"""
Program to calculate RMSF of an MD trajectory

By defaults calculates the RMSF of the C, CA and N atoms

Examples:
    md_rmsf.py -f sim.dcd -s ref.pdb
"""

from sgenlib import moldyn
from sgenlib import mdactions

if __name__ == '__main__' :

    processor = moldyn.TrajectoryProcessor("Calculate the bfactor of atoms")
    analysis = mdactions.RMSFAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #16
0
        boxvol = 1.0 / self.vol
        print self.vol / self.processor.nprocessed
        radii = 0.5 * (self.edges[1:] + self.edges[:-1])
        vol = 4.0 / 3.0 * np.pi * (np.power(self.edges[1:], 3) -
                                   np.power(self.edges[:-1], 3))
        if self.usecom:
            norms = [(len(s.residues)) * boxvol * vol for s in self.sels]
        else:
            norms = [(len(s) * len(self.ref)) * boxvol * vol
                     for s in self.sels]
        print norms
        rdfs = [den / norm for den, norm in zip(self.densities, norms)]
        rdfs = np.asarray(rdfs)
        with open(self.out, 'w') as f:
            for i, rdfr in enumerate(rdfs.T):
                f.write(
                    "%.2f\t%s\n" %
                    (i * self.resolution, "\t".join(["%.3f" % r
                                                     for r in rdfr])))
        #self._write_records(postfix=".hist")


if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor(
        "Calculate the RDF of a group of atoms")
    analysis = RdfAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #17
0
# Author: Samuel Genheden [email protected]

"""
Program to perform Voronoi analysis of a membrane

At the moment it does two things:
  1) Calculate the area per lipid for each type of residue
  2) Count the number of neighbors for each pair of residue types

Examples
--------
md_memvoro.py -f md.xtc -s ref.gro --mask PO4 ROH --head PO4
"""

from sgenlib import moldyn
from sgenlib import mdactions

if __name__ == '__main__' :

    processor = moldyn.TrajectoryProcessor("Apply Voronoi analysis to membrane")
    analysis = mdactions.MemVoronoiAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #18
0
# Author: Samuel Genheden [email protected]
"""
Program to calculate S2 order parameters using iRED

By default it calculates S2 of N-H vectors

Examples:
    md_ired.py -f sim.dcd -s ref.pdb
"""

from sgenlib import moldyn
from sgenlib import mdactions

if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor(
        "Calculate the iRED order parameters", dosubsample=True)
    analysis = mdactions.IredAnalysis(processor)
    processor.setup()
    processor.process()
Пример #19
0
# Author: Samuel Genheden [email protected]
"""
Program to calculate C-C chain order parameter from MD trajectory

The carbon atoms that form the tail on which the order parameters
should be calculated are given as command-line arguments. One or
more chains can be given.

Examples
--------
md_chainorder.py -f md2_whole.xtc -s md1.gro -c POPC:C1A-D2A-C3A-C4A POPC:C1B-C2B-C3B-C4B
"""

from sgenlib import moldyn
from sgenlib import mdactions

if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor(
        "Calculate tail order parameter from MD trajectory")
    analysis = mdactions.ChainOrderAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #20
0
                            help="the output",
                            default="alcohol_len.txt")

    def setup(self, args):
        self.sel1 = self.processor.universe.select_atoms(args.sel[0])
        self.sel2 = self.processor.universe.select_atoms(args.sel[1])
        print "Group selection contains %d and %d atoms" % (len(
            self.sel1), len(self.sel2))
        self.out = args.out
        self.records = []

    def process(self):

        zlen = np.mean(
            np.abs(self.sel1.positions[:, 2] - self.sel2.positions[:, 2]))
        diff2 = np.power(self.sel1.positions - self.sel2.positions, 2)
        totlen = np.mean(np.sqrt(np.sum(diff2, axis=1)))
        self.records.append(
            mdactions.MDRecord(self.processor.currtime, [totlen, zlen]))

    def finalize(self):
        self._write_records(headers="Tot_len Z_len".split())


if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor("Measure length of alcohol")
    analysis = AlcoholLenAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #21
0
# Author: Samuel Genheden [email protected]
"""
Program to calculate angle between the a user defined vector
and the membrane plane

Examples:
    md_vectorplane.py -f sim.dcd -s ref.pdb
"""

from sgenlib import moldyn
from sgenlib import mdactions

if __name__ == '__main__':

    processor = moldyn.TrajectoryProcessor(
        "Calculate the angle between a vector and the membrane plane")
    analysis = mdactions.VectorPlaneAngleAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()
Пример #22
0
        def _accumulate_density(solutecoms, lipidcom) :
            r = np.sqrt(((solutecoms-lipidcom)**2).sum(axis=1))
            for rdig in np.digitize(r, self.edges) :
                self.density[rdig] += 1

        lipidcom = np.median(self.lipids.get_positions() ,axis=0)
        if len(self.solute) == 1 :
            solutecoms = np.asarray([r.center_of_geometry() for r in self.solute.residues])
            _accumulate_density(solutecoms, lipidcom)
        else:
            for sel in self.solute:
                _accumulate_density(sel.get_positions(), lipidcom)


    def finalize(self):
        with open(self.out, "w") as f:
            for d,e in zip(self.density[:-1], self.edges):
                if len(self.solute) == 1 :
                    n = len(self.solute.residues)
                else :
                    n = len(self.solute)*len(self.solute[0])
                gr = float(d) / float(self.processor.nprocessed*n)
                f.write("%.2f %d %.6f\n"%(e,d, gr))

if __name__ == '__main__' :

    processor = moldyn.TrajectoryProcessor("Calculate liposome RDf of a solute")
    analysis = LiposomeRdfAnalysis(processor)
    processor.setup(printargs=True)
    processor.process()