Example #1
0
def write_trajectory(universe, filename):
    '''A simplified method for writing trajectories
    '''
    w = Writer(filename, universe.atoms.numberOfAtoms())
    for ts in universe.trajectory:
        w.write(ts)
    w.close()
Example #2
0
def write_trajectory(universe, filename, maximum_frames=0):
    '''A simplified method for writing trajectories
    '''
    w = Writer(filename, universe.atoms.numberOfAtoms())
    frame_count = 0
    for ts in universe.trajectory:
        if(maximum_frames != 0 and frame_count == maximum_frames):
            break
        w.write(ts)
        frame_count += 1
    w.close()
def Move_2_center(top_file,trj_file,trjout_file):
    u=Universe(top_file,trj_file)
    TRAJ_FRAMES=u.trajectory.numframes
    w = Writer(trjout_file, u.trajectory.numatoms)

    atoms=Simple_atom.Get_atom_list(top_file)
    SOLUTE_COUNT = 0
    for atom_ID in atoms:
        if atoms[atom_ID].residue_name != "SOL" and atoms[atom_ID].residue_name != "WAT":
            SOLUTE_COUNT +=1
        else:
            pass

    print '''Note: this program will read the pbc condition and use the dimensions \
read from trajectory files. You should make sure the dimensions are right or \
it will create a wrong output trajectory file.'''

    START_TIME=Time.time()
    NUM_ATOMS = u.trajectory.numatoms
    # loop through the trajectory and write a frame for every step
    for ts in u.trajectory:

        dimensions=ts.dimensions


        for i in range(SOLUTE_COUNT):
            if ts._x[i] > dimensions[0]:
                ts._x[i]=ts._x[i]-dimensions[0]
            if ts._x[i] <0:
                ts._x[i]=ts._x[i]+dimensions[0]

            if ts._y[i] > dimensions[1]:
                ts._y[i]=ts._y[i]-dimensions[1]
            if ts._y[i] <0:
                ts._y[i]=ts._y[i]+dimensions[1]

            if ts._z[i] > dimensions[2]:
                ts._z[i]=ts._z[i]-dimensions[2]
            if ts._z[i] < 0:
                ts._z[i]=ts._z[i]+dimensions[2]

        NOW_TIME=Time.time()
        BIN_TIME=NOW_TIME-START_TIME
        if ts.frame % 100 == 0:
#            usage.echo("%8.4f   %8.4f   %8.4f\r" %(dimensions[0],dimensions[1],dimensions[2]))
            usage.echo(" "*40+"Converted frame %d, time used: %8.2f s, time left: %8.2f s \r" \
                % (ts.frame,BIN_TIME,BIN_TIME*(float(TRAJ_FRAMES)/ts.frame-1) ))
#    for ts in u.trajectory:
        w.write(ts)
#        usage.echo("Writting frame %d\r"  %ts.frame)
    w.close_trajectory()
    print "Converted %r --> %r" % (intrj, outtrj)
Example #4
0
def preliminaryAnalysis(obj, top):
    aligner1 = align.AlignTraj(obj, obj, verbose=True, in_memory=True)
    cAlpha = obj.select_atoms("name CA")

    #computing Radius of gyration
    print("Computing Radius of gyration along the trajectory:")
    gyro_list = list()
    for ts in obj.trajectory:
        gyro_list.append(obj.atoms.radius_of_gyration())
    s_gyro = pd.Series(gyro_list)

    #computing rmsd with first frame as reference
    print("Computing c-alphas RMSD with the first frame as reference:")
    rmsd1 = RMSD(cAlpha, verbose=True).run()
    rmsd_df = pd.DataFrame(rmsd1.rmsd)

    #computind rmsf
    print("Computing c-alphas RMSF:")
    ref_coordinates = obj.trajectory.timeseries(asel=cAlpha).mean(axis=1)
    ref = Merge(cAlpha).load_new(ref_coordinates[:, None, :], order="afc")
    re_align = align.AlignTraj(obj, ref, select="name CA").run()
    # need to write the trj to disk (issue 15)?
    with Writer("rmsfit.xtc", n_atoms=obj.atoms.n_atoms) as w:
        for ts in obj.trajectory:
            w.write(obj.atoms)
    #creating the fitted trj
    rmsfObj = Universe("rmsfit.xtc", top)
    #backboneRef = rmsfObj.select_atoms("backbone")
    rmsf = RMSF(cAlpha, verbose=True).run()
    rmsf_df = pd.DataFrame(rmsf.rmsf, index=cAlpha.resnums)

    return s_gyro, rmsd_df, rmsf_df
Example #5
0
def write_trajectory(universe, filename):
    '''A simplified method for writing trajectories
    '''
    w = Writer(filename, universe.atoms.numberOfAtoms())
    for ts in universe.trajectory:
        w.write(ts)
    w.close()
def Move_2_center(top_file, trj_file, trjout_file):
    u = Universe(top_file, trj_file)
    TRAJ_FRAMES = u.trajectory.numframes
    w = Writer(trjout_file, u.trajectory.numatoms)

    atoms = Simple_atom.Get_atom_list(top_file)
    SOLUTE_COUNT = 0
    for atom_ID in atoms:
        if atoms[atom_ID].residue_name != "SOL" and atoms[
                atom_ID].residue_name != "WAT":
            SOLUTE_COUNT += 1
        else:
            pass

    print '''Note: this program will read the pbc condition and use the dimensions \
read from trajectory files. You should make sure the dimensions are right or \
it will create a wrong output trajectory file.'''

    START_TIME = Time.time()
    NUM_ATOMS = u.trajectory.numatoms
    # loop through the trajectory and write a frame for every step
    for ts in u.trajectory:

        dimensions = ts.dimensions

        for i in range(SOLUTE_COUNT):
            if ts._x[i] > dimensions[0]:
                ts._x[i] = ts._x[i] - dimensions[0]
            if ts._x[i] < 0:
                ts._x[i] = ts._x[i] + dimensions[0]

            if ts._y[i] > dimensions[1]:
                ts._y[i] = ts._y[i] - dimensions[1]
            if ts._y[i] < 0:
                ts._y[i] = ts._y[i] + dimensions[1]

            if ts._z[i] > dimensions[2]:
                ts._z[i] = ts._z[i] - dimensions[2]
            if ts._z[i] < 0:
                ts._z[i] = ts._z[i] + dimensions[2]

        NOW_TIME = Time.time()
        BIN_TIME = NOW_TIME - START_TIME
        if ts.frame % 100 == 0:
            #            usage.echo("%8.4f   %8.4f   %8.4f\r" %(dimensions[0],dimensions[1],dimensions[2]))
            usage.echo(" "*40+"Converted frame %d, time used: %8.2f s, time left: %8.2f s \r" \
                % (ts.frame,BIN_TIME,BIN_TIME*(float(TRAJ_FRAMES)/ts.frame-1) ))
#    for ts in u.trajectory:
        w.write(ts)


#        usage.echo("Writting frame %d\r"  %ts.frame)
    w.close_trajectory()
    print "Converted %r --> %r" % (intrj, outtrj)
    traj_size = [100, 300, 600]
    for k in traj_size:  # we have 3 trajectory sizes
        # Creating the universe for doing benchmark
        u1 = mda.Universe(PSF, DCD1)
        longDCD = 'newtraj.dcd'

        # Creating big trajectory sizes from initial trajectory
        with mda.Writer(longDCD, u1.atoms.n_atoms) as W:
            for i in range(k):
                for ts in u1.trajectory:
                    W.write(u1)
        u = mda.Universe(PSF, longDCD)

        # Coverting DCD files into XTC files
        longXTC = 'newtraj.xtc'
        with Writer(longXTC, u.trajectory.n_atoms) as w:
            for ts in u.trajectory:
                w.write(ts)

        # Doing benchmarks
        ii = 1
        block_size = [1, 6, 8, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72]
        for i in block_size:  # changing blocks
            for j in range(1, 6):  # changing files (5 files per block size)
                # Create a new file
                longXTC1 = 'newtraj{}.xtc'.format(ii)
                copyfile(longXTC, longXTC1)
                # Provide the path to my file to all processes
                my_path = os.path.normpath(os.path.join(os.getcwd(), longXTC1))
                #                print (my_path)
                longXTC1 = os.path.abspath(my_path)
Example #8
0
# coding=utf-8

"""
MDAnalysis example: Convert DCD trajectory into XTC
===================================================

This example shows how one can use MDAnalysis to convert between
different trajectory formats.

"""

from MDAnalysis.tests.datafiles import PDB_small, DCD
from MDAnalysis import Universe, Writer

import os.path

root, ext = os.path.splitext(os.path.basename(DCD))
xtcname = root + '.xtc'  # output format determined by extension

u = Universe(PDB_small, DCD)

# create a writer instance for the output trajectory
w = Writer(xtcname, u.trajectory.numatoms)

# loop through the trajectory and write a frame for every step
for ts in u.trajectory:
    w.write(ts)
    print "Converted frame {0:d}".format(ts.frame)
w.close_trajectory()
print "Converted {0!r} --> {1!r}".format(DCD, xtcname)
def Run(topol, intrj):
    ext = '.dcd'
    atom_l = Simple_atom.Get_Simple_atom_list(topol)
    new_list, store_list = Check(atom_l)

    NUM = store_list[0][2]
    for a in store_list:
        if NUM > a[2]:
            NUM = a[2]

    root, oldext = greedy_splitext(os.path.basename(intrj))
    outpdb = root + '.pdb'

    u = Universe(topol, intrj)
    NUM_ATOMS = len(new_list)

    # create a writer instance for the output trajectory
    outtrj = [root + str(i) + ext for i in range(NUM)]
    w = [Writer(outtrj[i], NUM_ATOMS) for i in range(NUM)]
    Atom_list = [copy.deepcopy(new_list) for i in range(NUM)]
    '''
    NUM copies new_list   
    '''

    # loop through the trajectory and write a frame for every step
    for ts in u.trajectory:
        for i in range(NUM_ATOMS):
            if i < store_list[0][0] - 1:
                for s in range(NUM):
                    Atom_list[s][i].atom_coor_x = ts._x[i]
                    Atom_list[s][i].atom_coor_y = ts._y[i]
                    Atom_list[s][i].atom_coor_z = ts._z[i]

            elif i > store_list[-1][1] - 1:
                LENGTH = 0
                for a in store_list:
                    LENGTH = LENGTH + (a[2] - 1) * (a[1] - a[0] + 1)
                for s in range(NUM):
                    Atom_list[s][i].atom_coor_x = ts._x[i + LENGTH]
                    Atom_list[s][i].atom_coor_y = ts._y[i + LENGTH]
                    Atom_list[s][i].atom_coor_z = ts._z[i + LENGTH]
            else:
                LENGTH = 0
                for j in range(len(store_list)):
                    if i > store_list[j][0] - 2 and i < store_list[j][1]:
                        if j > 0:
                            for a in store_list[:j]:
                                LENGTH = LENGTH + (a[2] - 1) * (a[1] - a[0] +
                                                                1)
                        else:
                            LENGTH = 0

                        for s in range(NUM):
                            Atom_list[s][i].atom_coor_x = ts._x[
                                store_list[j][0] - 1 + LENGTH + s +
                                (i + 1 - store_list[j][0]) * store_list[j][2]]
                            Atom_list[s][i].atom_coor_y = ts._y[
                                store_list[j][0] - 1 + LENGTH + s +
                                (i + 1 - store_list[j][0]) * store_list[j][2]]
                            Atom_list[s][i].atom_coor_z = ts._z[
                                store_list[j][0] - 1 + LENGTH + s +
                                (i + 1 - store_list[j][0]) * store_list[j][2]]

                for j in range(len(store_list) - 1):
                    if i > store_list[j][1] - 1 and i < store_list[j +
                                                                   1][0] - 1:
                        for a in store_list[:j + 1]:
                            LENGTH = LENGTH + (a[2] - 1) * (a[1] - a[0] + 1)

                        for s in range(NUM):
                            Atom_list[s][i].atom_coor_x = ts._x[i + LENGTH]
                            Atom_list[s][i].atom_coor_y = ts._y[i + LENGTH]
                            Atom_list[s][i].atom_coor_z = ts._z[i + LENGTH]

        new_ts = [Timestep(NUM_ATOMS) for i in range(NUM)]

        for i in range(NUM_ATOMS):
            for s in range(NUM):
                new_ts[s]._x[i] = Atom_list[s][i].atom_coor_x
                new_ts[s]._y[i] = Atom_list[s][i].atom_coor_y
                new_ts[s]._z[i] = Atom_list[s][i].atom_coor_z

        for s in range(NUM):
            w[s].write(new_ts[s])
        usage.echo("Converted frame %d\r" % ts.frame)
    for s in range(NUM):
        w[s].close_trajectory()
    print "Converted %r --> %r" % (intrj, outtrj)

    # make a pdb file as a simple 'topology'
    u.trajectory.rewind()
    for atom in Atom_list[0]:
        atom.atom_coor_x = atom.atom_coor_x / 10
        atom.atom_coor_y = atom.atom_coor_y / 10
        atom.atom_coor_z = atom.atom_coor_z / 10

    Simple_atom.Save_file(outpdb, Atom_list[0])
    print "Created %r to be used with the trajectory" % outpdb
Example #10
0
def Move_2_center(top_file,trj_file,trjout_file,skip=1):
    u=Universe(top_file,trj_file)
    TRAJ_FRAMES=u.trajectory.numframes
    atom_l=Simple_atom.Get_Simple_atom_list(top_file)

    while True:
        fit_residue=Simple_atom.Get_residue(top_file)
        if len(fit_residue) > 1:
            print "Only 1 residue is aviliable."
            continue
        else:
            break
    while True:
        fit_atom=Simple_atom.Get_atom(atom_l,fit_residue[0])
        if len(fit_atom) > 1:
            print "Only 1 atom is aviliable."
            continue
        else: 
            break

    fitting_group=Simple_atom.Get_residue(top_file)

    fit_atom=fit_atom[0]

    w = Writer(trjout_file, u.trajectory.numatoms)
    NUM_ATOMS=len(atom_l)

    print '''Note: this program will read the pbc condition and use the dimensions \
read from trajectory files. You should make sure the dimensions are right or \
it will create a wrong output trajectory file.'''

    START_TIME=Time.time()
    # loop through the trajectory and write a frame for every step
    for ts in u.trajectory:
        if ts.frame % skip != 1:
            break

        if ts.frame==1:
            label_coordinate=[ts._x[fit_atom],ts._y[fit_atom],ts._z[fit_atom]]

            # origin_list=list()
            # for atom in atom_l:
            #     if atom.residue_serial in fitting_group:
            #         origin_list.append([\
            #                 ts._x[atom_l.index(atom)],\
            #                 ts._y[atom_l.index(atom)],\
            #                 ts._z[atom_l.index(atom)],\
            #                 ])

        else:
            shift=[label_coordinate[0]-ts._x[fit_atom],\
                    label_coordinate[1]-ts._y[fit_atom],\
                    label_coordinate[2]-ts._z[fit_atom]]


            dimensions=ts.dimensions
            usage.echo("%8.4f   %8.4f   %8.4f\r" %(dimensions[0],dimensions[1],dimensions[2]))

            for i in range(NUM_ATOMS):
               ts._x[i] =ts._x[i]+shift[0]
               if ts._x[i] > dimensions[0]:
                   ts._x[i]=ts._x[i]-dimensions[0]
               if ts._x[i] <0:
                   ts._x[i]=ts._x[i]+dimensions[0]

               ts._y[i] =ts._y[i]+shift[1]
               if ts._y[i] > dimensions[1]:
                   ts._y[i]=ts._y[i]-dimensions[1]
               if ts._y[i] <0:
                   ts._y[i]=ts._y[i]+dimensions[1]

               ts._z[i] =ts._z[i]+shift[2]
               if ts._z[i] > dimensions[2]:
                   ts._z[i]=ts._z[i]-dimensions[2]
               if ts._z[i] < 0:
                   ts._z[i]=ts._z[i]+dimensions[2]


#             temp_list=list()
#             for atom in atom_l:
#                 if atom.residue_serial in fitting_group:
#                     temp_list.append([\
#                             ts._x[atom_l.index(atom)],\
#                             ts._y[atom_l.index(atom)],\
#                             ts._z[atom_l.index(atom)],\
#                             ])


# #            [Rotate,shift]=least_squares_fitting.Fitting(temp_list,origin_list)


#             atom_matrix=numpy.array([[ts._x[i],ts._y[i],ts._z[i]]for i in range(NUM_ATOMS)])

# #            resu_matrix=numpy.matrix(atom_matrix) * numpy.matrix(Rotate).T 
# #            resu_matrix=numpy.array(resu_matrix)

# #            for i in range(NUM_ATOMS):
# #                atom_matrix[i,0]=resu_matrix[i,0]+shift[0]
# #                atom_matrix[i,1]=resu_matrix[i,1]+shift[1]
# #                atom_matrix[i,2]=resu_matrix[i,2]+shift[2]
 

#             for i in range(NUM_ATOMS):
#                 ts._x[i]=atom_matrix[i,0]
#                 ts._y[i]=atom_matrix[i,1]
#                 ts._z[i]=atom_matrix[i,2]
        
 
#        w.write(ts)
        NOW_TIME=Time.time()
        BIN_TIME=NOW_TIME-START_TIME
        usage.echo(" "*40+"Converted frame %d, time used: %8.2f s, time left: %8.2f s \r" \
                % (ts.frame,BIN_TIME,BIN_TIME*(float(TRAJ_FRAMES)/ts.frame-1) ))
#    for ts in u.trajectory:
        w.write(ts)
#        usage.echo("Writting frame %d\r"  %ts.frame)
    w.close_trajectory()
    print "Converted %r --> %r" % (intrj, outtrj)
Example #11
0
def Move_2_center(top_file,trj_file,index_file,trjout_file):
    u=Universe(top_file,trj_file)
    TRAJ_FRAMES=u.trajectory.numframes
    w = Writer(trjout_file, u.trajectory.numatoms)

    
    atoms=Simple_atom.Get_Simple_atom_list(top_file)
    index = Index.Read_index_to_Inclass(index_file)
    Index.Print_Index(index)
    while True:
        try:
            solute_index=int(raw_input("Choosing the group for centering:"))
            # solvent_index = int(raw_input("Choosing the solvent group:"))
            break
        except:
            print "You should input a number."
            continue
    solute_group  = index[solute_index].group_list
    # solvent_group = index[solvent_index].group_list
    solute_atoms  =len(solute_group)
    NUM_ATOMS = u.trajectory.numatoms
    # print "\t Reading %d frames from trajectory file: %s" %(nframes,traj_file)    
    START_TIME=Time.time()
    for ts in u.trajectory:
        ref_com =np.zeros((3),dtype=np.float32)    

        # sys.stderr.write("\t Reading frame %8d\r" %ts.frame)
        # sys.stderr.flush()

        for i,ai in list(enumerate(solute_group)):
            ref_com[0] += ts._x[ai-1]
            ref_com[1] += ts._y[ai-1]
            ref_com[2] += ts._z[ai-1]
        ref_com = ref_com/solute_atoms
        dimensions=ts.dimensions
        ref_com = ref_com - np.array([dimensions[0]/2, dimensions[1]/2, dimensions[2]/2])  

        
        # ref_com = np.array([sum(traj_data[:,0])/solute_atoms - dimensions[0]/2,\
            # sum(traj_data[:,1])/solute_atoms - dimensions[1]/2,\
            # sum(traj_data[:,2])/solute_atoms - dimensions[2]/2])  

        for i in range(NUM_ATOMS):
            ts._x[i] = ts._x[i] - ref_com[0] 
            ts._y[i] = ts._y[i] - ref_com[1] 
            ts._z[i] = ts._z[i] - ref_com[2] 

            if (i+1) in solute_group:
                continue

            if ts._x[i] > dimensions[0] or ts._x[i] <0:
                ts._x[i]=ts._x[i]%dimensions[0]

            if ts._y[i] > dimensions[1] or ts._y[i] <0:
                ts._y[i]=ts._y[i]%dimensions[1]

            if ts._z[i] > dimensions[2] or ts._z[i] < 0:
                ts._z[i]=ts._z[i]%dimensions[2]

        NOW_TIME=Time.time()
        BIN_TIME=NOW_TIME-START_TIME
        # if ts.frame % 10 == 0:
#            usage.echo("%8.4f   %8.4f   %8.4f\r" %(dimensions[0],dimensions[1],dimensions[2]))
        usage.echo(" "*40+"Converted frame %d, time used: %8.2f s, time left: %8.2f s \r" \
            % (ts.frame,BIN_TIME,BIN_TIME*(float(TRAJ_FRAMES)/ts.frame-1) ))
#    for ts in u.trajectory:
        w.write(ts)
        # del traj_data
#        usage.echo("Writting frame %d\r"  %ts.frame)
    w.close_trajectory()
    print "Converted %r --> %r" % (intrj, outtrj)
    if TRJ_LEN < 3:
        print "Error"
        sys.exit()

    topol =sys.argv[1] #PRMpbc
    TRJ_LIST=list()
    for i in range(TRJ_LEN-2):
        TRJ_LIST.append(sys.argv[2+i])

    outtrj = "traj.xtc"


    # create a writer instance for the output trajectory
    print "Reading trajectory %s" %TRJ_LIST[0]
    u = Universe(topol, TRJ_LIST[0])
    w = Writer(outtrj, u.trajectory.numatoms)
    FRAME=0

    for j in range(len(TRJ_LIST)):
        if u.trajectory.dt==0.0:
            print "No time step information found in the trajectoy file."
            DT=raw_input("Input a float number for the time step:")
            u.trajectory.dt=float(DT)
        else:
            print "Time step %6.4f was found and will be used in the new trajectory." %u.trajectory.dt
        for ts in u.trajectory:
            FRAME=FRAME+1
            ts.time=(FRAME-1)*u.trajectory.dt
            w.write(ts)
            if FRAME %100==0:
                echo("Converted frame %8d ,time %8.2f\r" %(ts.frame,FRAME*u.trajectory.dt))
Example #13
0
            except:
                Index[nst] = [n]
        else:
            print "Error: ", n, nst, N_str
ifile.close()

print 'number of clusters:', len(N_str)

N_str.sort()
N_str.reverse()

N_write = int(raw_input('How many clusters you want to look at (eg. 8): '))

universe = Universe(pdbfile, pdbfile)

writer = Writer(filename + '_.pdb', universe.atoms.numberOfAtoms())

k = 1
for each in N_str[:N_write]:
    if k > N_write:
        break
    percent = float(each) * 100 / sum(N_str)
    for i in Index[each]:
        print 'Writing cluster #' + str(i).ljust(3),
        universe.trajectory[i - 1]
        protein = universe.atoms
        writer.write(protein)
        print '%3i %5.0f%% %6.2f%%' % (k, percent, percent)
        k += 1

writer.close()
Example #14
0
with open('data.txt', mode='w') as file:
    traj_size = [50,150,300]
    for k in traj_size: # we have 3 trajectory sizes
        # Creating the universe for doing benchmark
        u1 = mda.Universe(PSF, DCD1)
        longDCD = 'newtraj.dcd'

        # Creating big trajectory sizes from initial trajectory (DCD file)
        with mda.Writer(longDCD, u1.atoms.n_atoms) as W:
            for i in range (k):
                for ts in u1.trajectory:
                    W.write(u1)
        u = mda.Universe(PSF, longDCD)

        # Coverting DCD files into XTC files
        with Writer('newtraj1.xtc', u.trajectory.n_atoms) as w:
             for ts in u.trajectory:
                 w.write(ts)

        # Doing benchmarks
        ii=2
        block_size = [1,2,4,6,8,10,12]
        for i in block_size:      # changing blocks
            for j in range(1,6):    # changing files (5 files per block size)
                longXTC1 = 'newtraj1.xtc'
                longXTC2 = 'newtraj{}.xtc'.format(ii)
                copyfile(longXTC1, longXTC2)
                u = mda.Universe(PSF, longXTC2)
                print(u)
                print("frames in trajectory {} for traj_size {}".format(u.trajectory.n_frames, k))
                print (len(u.trajectory))
Example #15
0
def main():
    parser = argparse.ArgumentParser(
        description=
        'saves new topology and joined trajectory with only sel(ected) atoms.')
    parser.add_argument('-t',
                        '--topology',
                        help='the topology file (pdb, gro, psf...)')
    parser.add_argument('-sel',
                        '--selection',
                        help='the selection in MDA language')
    parser.add_argument('-o', '--output', help='output basename')
    parser.add_argument('-s',
                        '--slice',
                        help='slicing output trajectory START:END:SKIP')
    parser.add_argument('--reset_time',
                        help='make trajectory start from time 0',
                        action='store_true')
    parser.add_argument('trajectory',
                        help='the trajectory(ies) file(s). Accepts globbing',
                        nargs=argparse.REMAINDER)
    parser.add_argument('--dcd',
                        help='writes traj in dcd format',
                        action='store_true')
    parser.add_argument('-u',
                        '--unwrap',
                        action='store_true',
                        help='unwrap PBC')
    args = parser.parse_args()

    # expand input trajectory names
    traj_files = []
    for traj_arg in args.trajectory:
        tf = [tfile for tfile in glob.glob(traj_arg)]
        traj_files += tf

    traj_files.sort()
    if args.slice:
        slicer = slice(*[int(x) if x else None for x in args.slice.split(':')])
    else:
        slicer = slice(None, None, None)

    u = Universe(args.topology, *traj_files)

    if args.unwrap:
        workflow = [transformations.unwrap(u.atoms)]
        u.trajectory.add_transformations(*workflow)

    if args.reset_time:
        time_offset = u.trajectory[0].time
    else:
        time_offset = 0.0

    if args.selection:
        selection = u.select_atoms(args.selection)
    else:
        selection = u.atoms

    selection.write(f'{args.output}.pdb')

    if args.dcd:
        traj_file = f'{args.output}.dcd'
    else:
        traj_file = f'{args.output}.xtc'
    with Writer(traj_file, selection.n_atoms) as write_handle:
        for time_frame in u.trajectory[slicer]:
            time_frame.time -= time_offset
            write_handle.write(selection)
Example #16
0
from MDAnalysis.tests.datafiles import PRM, TRJ_bz2
from MDAnalysis import Universe, Writer
from MDAnalysis.core.util import greedy_splitext

import os.path

topol = PRM  # PRMpbc
intrj = TRJ_bz2  # TRJpbc_bz2
ext = '.dcd'  # output format determined by extension

root, oldext = greedy_splitext(os.path.basename(intrj))
outtrj = root + ext
outpdb = root + '.pdb'

u = Universe(topol, intrj)

# create a writer instance for the output trajectory
w = Writer(outtrj, u.trajectory.numatoms)

# loop through the trajectory and write a frame for every step
for ts in u.trajectory:
    w.write(ts)
    print "Converted frame %d" % ts.frame
w.close_trajectory()
print "Converted %r --> %r" % (intrj, outtrj)

# make a pdb file as a simple 'topology'
u.trajectory.rewind()
u.atoms.write(outpdb)
print "Created %r to be used with the trajectory" % outpdb
Example #17
0
#!/usr/bin/env python
# coding=utf-8
"""
MDAnalysis example: Convert DCD trajectory into XTC
===================================================

This example shows how one can use MDAnalysis to convert between
different trajectory formats.

"""

from MDAnalysis.tests.datafiles import PDB_small, DCD
from MDAnalysis import Universe, Writer

import os.path

root, ext = os.path.splitext(os.path.basename(DCD))
xtcname = root + '.xtc'  # output format determined by extension

u = Universe(PDB_small, DCD)

# create a writer instance for the output trajectory
w = Writer(xtcname, u.trajectory.numatoms)

# loop through the trajectory and write a frame for every step
for ts in u.trajectory:
    w.write(ts)
    print "Converted frame {0:d}".format(ts.frame)
w.close_trajectory()
print "Converted {0!r} --> {1!r}".format(DCD, xtcname)
Example #18
0
from MDAnalysis import Universe, Writer
u = Universe("protein.gro", "protein-short.xtc")
w = Writer("protein-short.dcd", u.trajectory.numatoms)
for ts in u.trajectory:
    w.write(ts)
w.close_trajectory()