Esempio n. 1
0
    def test_slice(self):

        traj1 = TrajectoryIterator(filename="data/Tc5b.x",
                                   top="./data/Tc5b.top")
        frame_indices = slice(9, 6, -1)

        traj0 = pt.load(filename="./data/Tc5b.x",
                        top=pt.load_topology("./data/Tc5b.top"),
                        frame_indices=frame_indices)

        aa_eq(traj0[0].xyz, traj1[9].xyz)
        aa_eq(traj0[1].xyz, traj1[8].xyz)
        aa_eq(traj0[2].xyz, traj1[7].xyz)

        assert traj0[0].rmsd(traj1[9]) < 1E-4

        rmsdlist = []
        ref = traj1[0].copy()
        for frame in traj1:
            rmsdlist.append(frame.rmsd(ref))

        nparr = np.array(rmsdlist)

        # make sure we don't suport other frame_indices
        traj2 = Trajectory()
        traj2 = pt.load(
            filename="./data/Tc5b.x",
            top=pt.load_topology("./data/Tc5b.top"),
            frame_indices=list(range(4)) + list(range(9, 5, -1)) + [4, ])
        aa_eq(traj2[-1].xyz, traj1[4].xyz)
Esempio n. 2
0
    def test_traj_topology(self):
        traj = pt.TrajectoryIterator()
        assert traj.top.is_empty() == True
        traj.top = pt.load_topology("./data/Tc5b.top")
        assert traj.top.is_empty() == False
        traj._load("./data/Tc5b.x")

        # use toplogy
        traj = pt.TrajectoryIterator()
        assert traj.topology.is_empty() == True
        traj.topology = pt.load_topology("./data/Tc5b.top")
        assert traj.topology.is_empty() == False
        traj._load("./data/Tc5b.x")
Esempio n. 3
0
    def test_indexing(self):
        traj = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top'))
        traj2 = pt.TrajectoryIterator()
        traj2.top = pt.load_topology(fn('Tc5b.top'))
        traj2._load(fn('Tc5b.x'))
        farray = traj2[[0, 9, 1]]
        assert farray.n_frames == 3
        aa_eq(traj2[0].atom(0), farray[0].atom(0))
        aa_eq(traj2[9].atom(0), farray[1].atom(0))
        aa_eq(traj2[1].atom(0), farray[2].atom(0))

        arr = np.asarray(traj2[0]._buffer1d[:])
        frame0 = traj2[0]
        arr0 = np.asarray(frame0._buffer1d[:])

        mat0 = np.asmatrix(arr0).reshape(304, 3)
        mat0[:, 0] = np.asmatrix(list(range(304))).reshape(304, 1)
        assert frame0[0, 0] == 0.
        assert frame0[1, 0] == 1.
        assert frame0[2, 0] == 2.

        # raise if size = 0
        traj3 = pt.Trajectory()
        assert traj3.n_frames == 0, 'empty Trajectory, n_frames must be 0'
        with pytest.raises(IndexError):
            traj3[0]
        with pytest.raises(IndexError):
            traj3.__setitem__(0, traj[3])
Esempio n. 4
0
def main():
    args = get_argument()
    #check_input_data(args)
    print(f'Current working directory: {os.getcwd()}')

    #if not check_config_file(args.config, args.verbose):
    #    sys.exit(1)
    #configfile = configparser.ConfigParser()
    #configfile.read(f'{args.config}')

    #hdlr = logging.FileHandler(
    #    f'framework_{strftime("%Y-%m-%d__%H-%M-%S", localtime())}.log')
    #logging.root.addHandler(hdlr)
    #logging.root.setLevel(logging.INFO)
    #logging.root.setLevel(logging.DEBUG)
    #logging.info(f'***Output from framework*** {strftime("%Y-%m-%d__%H-%M-%S", localtime())} \n')
    #logging.info(f'#Protein : {args.protein} -> protein.pdb \n')
    #logging.info(f'#Ligand : {args.ligand}  {configfile["LIGAND"]["name"]} \n')
    #logging.info(f'#Tunnel: {args.tunnel} \n')

    pdb = pt.load("protein_with_tunnel.pdb")
    pdb_topology = pt.load_topology('protein_with_tunnel.pdb')
    restraint_residue = []

    for i in range(1, pdb_topology.n_residues):
        #print(f'\':{i} FIL T\'')
        string_index = f':{i} :FIL T'
        if pt.distance(pdb, string_index) < 12.0:
            #    simp_top = pdb_topology.simplify()
            #name = simp_top.residue()
            restraint_residue.append(f'{pdb_topology.residue(i).index},')
            #string_residues.join(f':{pdb_topology.residue(i).index}')
            #restraint_residue.append(name)
    string_residues = ' '.join([str(elem) for elem in restraint_residue])
    print(string_residues)
Esempio n. 5
0
 def _assign_filter(self, sel_filter=None):
     if sel_filter is not None:
         print("Assigning sel_filter membership(bflt,aflt,tflt): '" +
               self.topofile + "'")
         data_len = len(self.nodes)
         pdb = pt.load_topology(self.topofile)
         H_indices = pdb.select(sel_filter)
         for i in range(1, data_len + 1):
             # Get selected atoms # in bond
             if self.nodes[i].a2 != -1:
                 self.nodes[i].bflt = 0
                 if self.nodes[i].a2 - 1 in H_indices:
                     self.nodes[i].bflt += 1
                 if self.nodes[i].a1 - 1 in H_indices:
                     self.nodes[i].bflt += 1
             # Get selected atoms # in angle
             if not (self.nodes[i].a2 == -1 or self.nodes[i].a3 == -1):
                 self.nodes[i].aflt = 0
                 if self.nodes[i].a3 - 1 in H_indices:
                     self.nodes[i].aflt += 1
                 if self.nodes[i].a1 - 1 in H_indices:
                     self.nodes[i].aflt += 1
             # Get selected atoms # in torsion
             if not (self.nodes[i].a2 == -1 or self.nodes[i].a3 == -1
                     or self.nodes[i].a4 == -1):
                 self.nodes[i].tflt = 0
                 if self.nodes[i].a1 - 1 in H_indices:
                     self.nodes[i].tflt += 1
                 if self.nodes[i].a2 - 1 in H_indices:
                     self.nodes[i].tflt += 1
                 if self.nodes[i].a3 - 1 in H_indices:
                     self.nodes[i].tflt += 1
                 if self.nodes[i].a4 - 1 in H_indices:
                     self.nodes[i].tflt += 1
Esempio n. 6
0
def test_mass_atomic_number_dict():
    top = pt.load_topology(fn("tz2.parm7"))
    mass_list = []

    for atom in top:
        mass_list.append(mass_atomic_number_dict[atom.atomic_number])
    aa_eq(mass_list, top.mass, decimal=2)
Esempio n. 7
0
    def test_indexing(self):
        traj = pt.iterload('data/Tc5b.x', 'data/Tc5b.top')
        traj2 = pt.TrajectoryIterator()
        traj2.top = pt.load_topology("./data/Tc5b.top")
        traj2._load("./data/Tc5b.x")
        farray = traj2[[0, 9, 1]]
        assert farray.n_frames == 3
        assert traj2[0].atom(0) == farray[0].atom(0)
        assert traj2[9].atom(0) == farray[1].atom(0)
        assert traj2[1].atom(0) == farray[2].atom(0)

        arr = np.asarray(traj2[0]._buffer1d[:])
        frame0 = traj2[0]
        arr0 = np.asarray(frame0._buffer1d[:])

        mat0 = np.asmatrix(arr0).reshape(304, 3)
        mat0[:, 0] = np.asmatrix(list(range(304))).reshape(304, 1)
        assert frame0[0, 0] == 0.
        assert frame0[1, 0] == 1.
        assert frame0[2, 0] == 2.

        # raise if size = 0
        traj3 = pt.Trajectory()
        assert traj3.n_frames == 0, 'empty Trajectory, n_frames must be 0'
        self.assertRaises(IndexError, lambda: traj3[0])
        self.assertRaises(IndexError, lambda: traj3.__setitem__(0, traj[3]))
Esempio n. 8
0
    def test_basic(self):
        '''slicing, select'''
        top = pt.load_topology(fn('Tc5b.top'))

        #
        assert isinstance(top[0], Atom)
        assert isinstance(top[:2], pt.Topology)
        assert isinstance(top[:1], pt.Topology)
        assert isinstance(top[range(10)], pt.Topology)
        assert isinstance(top[list(range(10))], pt.Topology)
        assert isinstance(top[np.array(range(10))], pt.Topology)
        assert top[0].name == top['@1'][0].name

        # mask, AtomMask, python array, list
        atm = top("@CA")
        indices = atm.indices
        for a1, a2, a3, a4 in zip(top['@CA'], top[atm], top[indices],
                                  top[list(indices)]):
            assert a1.name == a2.name == a3.name == a4.name == 'CA'

        # check len
        assert len(top[:]) == top.n_atoms
        assert len(top[:10]) == 10

        # API
        top.bond_indices
        top.angle_indices
        top.dihedral_indices
Esempio n. 9
0
    def test_0(self):
        top = pt.load_topology("./data/ala3.psf")
        reslit = top.residuelist
        atm = AtomMask("@CA")
        top.set_integer_mask(atm)

        atm.invert_mask()
        frame = Frame(atm.n_atoms)
        frame[:10] = np.asarray(array('d', list(range(30)))).reshape(10, 3)
Esempio n. 10
0
    def test_get_iter(self):
        top = pt.load_topology("./data/DOPC.parm7")
        s = [atom.name for atom in top[":PC@H*"]]
        atom0 = top[":PC@H*"][0]

        old_natoms = top.n_atoms
        self.assertRaises(ValueError, lambda: top.join(top))
        top.join(top.copy())
        assert top.n_atoms == 2 * old_natoms
Esempio n. 11
0
    def test_blind_load(self):
        top = pt.load_topology("./data/Tc5b.top")
        assert isinstance(top, Topology) == True

        traj = pt.iterload(filename="./data/Tc5b.x", top="./data/Tc5b.top")

        is_traj = (isinstance(traj, TrajectoryIterator)
                   or isinstance(traj, Trajectory))
        assert is_traj
Esempio n. 12
0
 def test_slice_basic(self):
     traj2 = pt.Trajectory()
     traj2.top = pt.load_topology("./data/Tc5b.top")
     traj2.load("./data/Tc5b.x")
     traj2.load("./data/Tc5b.x")
     traj2.load("./data/Tc5b.x")
     traj2.load("./data/Tc5b.x")
     fsub = traj2[2:10]
     fsub[0][0] = 100.
Esempio n. 13
0
def test_blind_load():
    top = pt.load_topology(tc5b_top)
    assert isinstance(top, Topology) == True

    traj = pt.iterload(filename=tc5b_trajin, top=tc5b_top)

    is_traj = (isinstance(traj, TrajectoryIterator)
               or isinstance(traj, Trajectory))
    assert is_traj
Esempio n. 14
0
    def test_get_iter(self):
        top = pt.load_topology("./data/DOPC.parm7")
        s = [atom.name for atom in top[":PC@H*"]]
        atom0 = top[":PC@H*"][0]

        old_natoms = top.n_atoms
        self.assertRaises(ValueError, lambda: top.join(top))
        top.join(top.copy())
        assert top.n_atoms == 2 * old_natoms
Esempio n. 15
0
    def test_psf(self):
        top = pt.load_topology(fn('ala3.psf'))
        list(top.residues)
        atm = AtomMask("@CA")
        top._set_integer_mask(atm)

        atm.invert_mask()
        frame = Frame(atm.n_atoms)
        frame[:10] = np.asarray(array('d', list(range(30)))).reshape(10, 3)
Esempio n. 16
0
 def test_slice_basic(self):
     traj2 = pt.Trajectory()
     traj2.top = pt.load_topology(fn('Tc5b.top'))
     traj2.load(fn('Tc5b.x'))
     traj2.load(fn('Tc5b.x'))
     traj2.load(fn('Tc5b.x'))
     traj2.load(fn('Tc5b.x'))
     fsub = traj2[2:10]
     fsub[0][0] = 100.
Esempio n. 17
0
    def test_get_iter(self):
        top = pt.load_topology(fn('DOPC.parm7'))
        [atom.name for atom in top[":PC@H*"]]
        top[":PC@H*"][0]

        old_natoms = top.n_atoms
        with pytest.raises(ValueError):
            top.join(top)
        top.join(top.copy())
        assert top.n_atoms == 2 * old_natoms
Esempio n. 18
0
    def test_tleap(self):
        from pytraj.testing import amberhome

        if amberhome and os.path.exists(amberhome + '/bin/tleap'):
            from pytraj.amber_wrapper import prmtop_from_tleap
            t0 = prmtop_from_tleap('./data/tz2.pdb')
            t1 = pt.load_topology('./data/tz2.pdb')
            print(t0, t1)
            assert t0.n_atoms == t1.n_atoms
        else:
            print("does not have AMBERHOME. skip")
Esempio n. 19
0
    def test_tleap(self):
        from pytraj.testing import amberhome

        if amberhome and os.path.exists(amberhome + '/bin/tleap'):
            from pytraj.amber_wrapper import prmtop_from_tleap
            t0 = prmtop_from_tleap('./data/tz2.pdb')
            t1 = pt.load_topology('./data/tz2.pdb')
            print(t0, t1)
            assert t0.n_atoms == t1.n_atoms
        else:
            print("does not have AMBERHOME. skip")
Esempio n. 20
0
    def test_simplifed_topology(self):
        '''simplify'''
        top = pt.load_topology("./data/Tc5b.top")
        sim_top = top.simplify()

        for atom, sim_atom in zip(top.atoms, sim_top.atoms):
            assert atom.resname == sim_atom.resname, 'equal resname'
            assert atom.name == sim_atom.name, 'equal resname'
            assert atom.type == sim_atom.type, 'equal resname'
            assert atom.charge == sim_atom.charge, 'equal resname'
            assert atom.mass == sim_atom.mass, 'equal resname'
Esempio n. 21
0
    def test_simplifed_topology(self):
        '''simplify'''
        top = pt.load_topology("./data/Tc5b.top")
        sim_top = top.simplify()

        for atom, sim_atom in zip(top.atoms, sim_top.atoms):
            assert atom.resname == sim_atom.resname, 'equal resname'
            assert atom.name == sim_atom.name, 'equal resname'
            assert atom.type == sim_atom.type, 'equal resname'
            assert atom.charge == sim_atom.charge, 'equal resname'
            assert atom.mass == sim_atom.mass, 'equal resname'
Esempio n. 22
0
def pack(traj, mol, n_copies, unitcells=None, ig=8888, grid_spacing=0.2):
    '''

    Parameters
    ----------
    traj : pytraj.Trajectory
    mol : pytraj.Trajectory
    unitcells : None or np.ndarray, dim=2
        if None, use box info from traj else use it
    n_copies : number of `mol`
    ig : int
        randome seed
    grid_spacing : float
    '''
    add_to_box_exe = amberbin('AddToBox') or 'AddToBox'
    input_pdb = 'input.pdb'
    mol_pdb = 'mol.pdb'
    out_pdb = 'out.pdb'

    assert mol.n_frames == 1
    
    total_n_atoms = traj.n_atoms + mol.n_atoms * n_copies
    new_traj_xyz = np.empty((traj.n_frames, total_n_atoms, 3), dtype='f8')

    with tempfolder():
        mol.save(mol_pdb, overwrite=True)
        for index, frame in enumerate(traj):
            pytraj.write_traj(input_pdb, traj=frame, top=traj.top, overwrite=True)
            parm = parmed.load_file(input_pdb)
            if unitcells is not None:
                parm.box = unitcells[index]
            else:
                assert frame.has_box(), 'must have box info'
                parm.box = frame.box
            # add remark 290
            parm.save(input_pdb, overwrite=True)
            command = [
                add_to_box_exe,
                '-c', input_pdb,
                '-a', mol_pdb,
                '-na', str(n_copies),
                '-IG', str(ig),
                '-G', str(grid_spacing),
                '-o', out_pdb
            ]
            try:
                subprocess.check_output(command, stderr=subprocess.STDOUT)
                new_traj_xyz[index] = pytraj.load(out_pdb).xyz
            except subprocess.CalledProcessError as e:
                return e.output.decode()
        top = pytraj.load_topology(out_pdb)
    return pytraj.Trajectory(xyz=new_traj_xyz, top=top)
Esempio n. 23
0
def prmtop_from_tleap(filename, leapin=None, verbose=False):
    '''make prmtop file from pdb

    Parameters
    ----------
    filename : str, pdb filename
    leapin : str, optional, default None
        leap input
        if None, use::

            source leaprc.ff14SB
            set default PBradii mbondi3
            x = loadpdb {pdbfile}
            saveamberparm x {pdbfile}.prmtop {pdbfile}.rst7
            quit
    verbose : bool, default False
        if False, suppress tleap output
    '''
    import os
    import subprocess
    import pytraj as pt

    if leapin is None:
        leapin = leap_template

    amberhome = os.environ.get('AMBERHOME')
    if amberhome is None:
        raise RuntimeError('must set AMBERHOME')

    tleap = amberhome + '/bin/tleap'

    filename = os.path.abspath(filename)

    with tempfolder():
        leapin = leapin.format(pdbfile=filename)

        with open("tmp_leap.in", 'w') as f:
            f.write(leapin)

        with open(os.devnull, 'wb') as devnull:
            if not verbose:
                subprocess.check_call(
                    [tleap, ' -f tmp_leap.in'],
                    stdout=devnull,
                    stderr=subprocess.STDOUT)
            else:
                x = subprocess.check_call([tleap, ' -f tmp_leap.in'])
        if verbose:
            print(x)
        return pt.load_topology("tmp.top")
Esempio n. 24
0
    def test_0(self):
        atm = AtomMask("@CA")
        assert atm.n_atoms == 0
        top = pt.load_topology("./data/Tc5b.top")
        top.set_integer_mask(atm)
        assert atm.n_atoms == 20
        top2 = top._modify_state_by_mask(atm)
        assert top2.n_atoms == 20
        for atom in top2:
            assert atom.name == 'CA'

        atm.invert_mask()
        top3 = top._modify_state_by_mask(atm)
        assert top3.n_atoms == top.n_atoms - 20
Esempio n. 25
0
    def test_0(self):
        atm = AtomMask("@CA")
        assert atm.n_atoms == 0
        top = pt.load_topology(fn('Tc5b.top'))
        top._set_integer_mask(atm)
        assert atm.n_atoms == 20
        top2 = top._modify_state_by_mask(atm)
        assert top2.n_atoms == 20
        for atom in top2:
            assert atom.name == 'CA'

        atm.invert_mask()
        top3 = top._modify_state_by_mask(atm)
        assert top3.n_atoms == top.n_atoms - 20
Esempio n. 26
0
def get_atom_num_and_pos(topology, mask, trajectory=None):
    '''retrun an array with a list of atom positions and numbers (starting at 1)
    corresponding to a cpptraj mask rerurns a tuple of
    coords and atom_numbers'''
    if isinstance(topology, basestring) == True:
        topology = pt.load_topology(topology)

    atom_numbers = topology.select(mask)+1
    if trajectory is not None:
        if isinstance(trajectory, basestring) == True:
            trajectory = pt.iterload(trajectory, topology)
        coords = np.array(trajectory[mask][-1].xyz)
    else:
        coords = None
    return coords, atom_numbers
Esempio n. 27
0
    def test_6_speed(self):
        import numpy as np
        from pytraj import AtomMask
        # test constructor from list/array/python array
        top = pt.load_topology(fn('DOPC.parm7'))
        indices = top.select(":WAT")

        atm1 = AtomMask(indices)
        atm2 = AtomMask(list(indices))
        atm3 = AtomMask(np.asarray(indices))
        # use max_atoms
        atm4 = AtomMask(np.asarray(indices), 1000)

        import numpy as np
        assert np.all(atm1.indices == atm2.indices)
        assert np.all(atm3.indices == atm4.indices)
Esempio n. 28
0
    def test_6_speed(self):
        import numpy as np
        from pytraj import AtomMask
        # test constructor from list/array/python array
        top = pt.load_topology("./data/DOPC.parm7")
        indices = top.select(":WAT")

        atm1 = AtomMask(indices)
        atm2 = AtomMask(list(indices))
        atm3 = AtomMask(np.asarray(indices))
        # use max_atoms
        atm4 = AtomMask(np.asarray(indices), 1000)

        import numpy as np
        assert np.all(atm1.indices == atm2.indices)
        assert np.all(atm3.indices == atm4.indices)
Esempio n. 29
0
    def test_5_speed(self):
        top = pt.load_topology(fn('DOPC.parm7'))
        from time import time

        t0 = time()
        indices = top(":WAT").indices
        time() - t0

        t0 = time()
        _indices_view = top(":WAT")._indices_view
        time() - t0

        count = 0
        for i, j in zip(indices, _indices_view):
            if not i == j:
                count += 1
        assert count == 0
Esempio n. 30
0
    def test_5_speed(self):
        top = pt.load_topology("./data/DOPC.parm7")
        from time import time

        t0 = time()
        indices = top(":WAT").indices
        gap_0 = time() - t0

        t0 = time()
        _indices_view = top(":WAT")._indices_view
        gap_1 = time() - t0

        count = 0
        for i, j in zip(indices, _indices_view):
            if not i == j:
                count += 1
        assert count == 0
Esempio n. 31
0
    def test_1(self):
        top = pt.load_topology(tc5b_top)
        #
        top.strip("!@CA")
        assert top.n_atoms == 20

        for atom in top.atoms:
            pass

        for res in top.residues:
            pass

        for mol in top.mols:
            pass

        for idx, atom in enumerate(top.atoms):
            pass
        assert idx + 1 == top.n_atoms
Esempio n. 32
0
def test_trajectory_writer_open_close():
    farray = pt.load(
        fn("Tc5b.x"), fn("Tc5b.top"), frame_indices=list(range(10)))
    frame0 = farray[0]
    with tempfolder():
        trajout = TrajectoryWriter()
        trajout.open(filename="test.x", top=farray.top, overwrite=True)
        trajout.write(frame0)

        # add more frames
        for i in range(5, 8):
            trajout.write(farray[i])

        trajout.close()

        farray = Trajectory()
        farray.top = pt.load_topology(fn('Tc5b.top'))
        farray.load("test.x")
Esempio n. 33
0
def get_atomdicts_pytraj(topology):
    '''pytrajdict being created via top = pt.load_topology(topologyfile)
    pytrajdict = top.to_dict()'''
    top = pt.load_topology(topology)
    pytrajdict = top.to_dict()
    atom_names = pytrajdict['atom_name']
    resids = pytrajdict['resid']
    chainids = pytrajdict['mol_number']
    mydictlist = []
    for number, (name, res, chain) in enumerate(zip(atom_names,
                                                    resids,
                                                    chainids)):
        if chain+1 == 3:
            break
        mydictlist.append(dict(atom_number=str(number+1),
                               atom_name=str(name),
                               res=res+1, chain=chain+1))

    return mydictlist
Esempio n. 34
0
def to_pytraj_Topology(item, atom_indices='all', check=True):

    if check:

        digest_item(item, 'file:pdb')
        atom_indices = digest_atom_indices(atom_indices)

    try:
        from pytraj import load_topology
    except:
        raise LibraryNotFoundError('pytraj')

    from ..pytraj_Topology import extract as extract_pytraj_Topology

    tmp_item = load_topology(item)
    tmp_item = extract_pytraj_Topology(tmp_item, atom_indices=atom_indices,
            structure_indices=structure_indices, copy_if_all=False, check=False)

    return tmp_item
Esempio n. 35
0
    def test_simplifed_topology(self):
        '''simplify'''
        top = pt.load_topology(fn('Tc5b.top'))
        sim_top = top.simplify()

        assert sim_top.select('@CA').tolist() == top.select('@CA').tolist()

        for atom, sim_atom in zip(top.atoms, sim_top.atoms):
            assert atom.resname == sim_atom.resname
            assert atom.name == sim_atom.name
            assert atom.type == sim_atom.type
            assert atom.charge == sim_atom.charge
            assert atom.mass == sim_atom.mass

        # API
        atom = sim_top.atoms[0]
        atom.residue
        atom.residue.name
        atom.residue.index
        atom.bond_partners
Esempio n. 36
0
def filter_seperated(trajectory, topology, targetdir, separated_frame, masks,
                     outprefix):
    cwd = os.getcwd()
    trajectory = lib.paths_for_there(trajectory, targetdir)
    topology = lib.paths_for_there(topology, targetdir)
    separated_frame = lib.paths_for_there(separated_frame, targetdir)
    os.system('mkdir -p ' + targetdir)
    os.chdir(targetdir)

    cpptrajtext = ('parm ' + topology + ' \n'
                   'trajin ' + trajectory + ' \n'
                   'reference ' + separated_frame + ' [ref] \n'
                   'nativecontacts ' + masks + ' distance 3.3 out '
                   'contacts series ref [ref] \n'
                   'go \n')

    with open('cpptraj.in', 'w') as f:
        f.write(cpptrajtext)
    os.system('mpirun -np 4 cpptraj.MPI -i cpptraj.in')

    top = pt.load_topology(topology)
    traj = pt.iterload(trajectory, top)

    d = np.loadtxt('contacts', usecols=(0, 2), dtype=int)
    nocontact = []
    contact = []
    for i, k in d:
        if k == 0:
            nocontact.append(i - 1)
        else:
            contact.append(i - 1)

    pt.write_traj('nocont_' + outprefix + '.nc',
                  traj[nocontact],
                  top=top,
                  overwrite=True)
    conttraj = 'cont_' + outprefix + '.nc'
    pt.write_traj(conttraj, traj[contact], top=top, overwrite=True)
    os.chdir(cwd)

    return lib.paths_for_here(targetdir, conttraj)
Esempio n. 37
0
def compress_traj_pt(trajs,
                     top,
                     targetdir,
                     cutoff_fraction,
                     compression,
                     outfile_name=None):
    '''cutoff_fraction is the fraction of frames left out at the beginning
    compression = 1 will give no compression'''
    top = pt.load_topology(top)
    noexttraj = os.path.splitext(os.path.basename(trajs[0]))[0]
    traj = pt.iterload(trajs, top)
    if cutoff_fraction > 1:
        traj = traj[len(traj) / cutoff_fraction::compression]
    else:
        traj = traj[::compression]

    if outfile_name is None:
        outfile_name = 'compress_' + noexttraj + '.nc'
    os.system('mkdir -p ' + targetdir)
    traj.save(targetdir + '/' + outfile_name, overwrite=True)
    return lib.paths_for_here(targetdir, outfile_name)
Esempio n. 38
0
    def test_1(self):
        datadir = "./data/"
        filename = "./data/Tc5b.top"

        top = pt.load_topology(filename)
        #
        top.strip("!@CA")
        assert top.n_atoms == 20

        for atom in top.atoms:
            pass

        for res in top.residues:
            pass

        for mol in top.mols:
            pass

        for idx, atom in enumerate(top.atoms):
            pass
        assert idx + 1 == top.n_atoms
Esempio n. 39
0
    def test_1(self):
        datadir = "./data/"
        filename = "./data/Tc5b.top"

        top = pt.load_topology(filename)
        #
        top.strip("!@CA")
        assert top.n_atoms == 20

        for atom in top.atoms:
            pass

        for res in top.residues:
            pass

        for mol in top.mols:
            pass

        for idx, atom in enumerate(top.atoms):
            pass
        assert idx + 1 == top.n_atoms
Esempio n. 40
0
    def test_basic(self):
        '''slicing, select'''
        top = pt.load_topology("./data/Tc5b.top")

        #
        assert isinstance(top[0], Atom)
        assert isinstance(top[:2], pt.Topology)
        assert isinstance(top[:1], pt.Topology)
        assert isinstance(top[range(10)], pt.Topology)
        assert isinstance(top[list(range(10))], pt.Topology)
        assert isinstance(top[np.array(range(10))], pt.Topology)
        assert top[0].name == top['@1'][0].name

        # mask, AtomMask, python array, list
        atm = top("@CA")
        indices = atm.indices
        for a1, a2, a3, a4 in zip(top['@CA'], top[atm], top[indices],
                                  top[list(indices)]):
            assert a1.name == a2.name == a3.name == a4.name == 'CA'

        # check len
        assert len(top[:]) == top.n_atoms
        assert len(top[:10]) == 10
Esempio n. 41
0
 def test_iter_basic(self):
     traj = pt.TrajectoryIterator()
     traj.top = pt.load_topology("./data/Tc5b.top")
     traj._load("./data/Tc5b.x")
     for frame in traj:
         pass
#!/usr/bin/env python
import os
import pytraj as pt
from glob import iglob, glob

fns = iglob('min*rst7')

parmlist = glob('*.parm7') 

if not parmlist:
    parmlist = glob('../*.parm7')

top = pt.load_topology(parmlist[0])

failed = []

for fn in fns:
    traj = pt.iterload(fn, top)
    if traj.n_frames == 0:
        failed.append(traj.filename.split('/')[-1])

print('failed', failed)

try:
    os.mkdir('old/')
except OSError:
    pass

for fn in failed:
    os.system('mv {} old/'.format(fn))
Esempio n. 43
0
 def test_3_indexing(self):
     top = pt.load_topology("./data/Tc5b.top")
     atm = AtomMask("@CA")
     top.set_integer_mask(atm)
Esempio n. 44
0
import pytraj as pt

top = pt.load_topology("../tests/data/Tc5b.top")

# save only CA atoms
pt.write_parm("./output/_Tcb5.onlyCA.top", top["@CA"])
Esempio n. 45
0
 def test_2(self):
     """test open file writen from test_0"""
     farray = Trajectory()
     farray.top = pt.load_topology('./data/Tc5b.top')
     farray.load("./output/test.x")
Esempio n. 46
0
 def test_raise_RuntimeError(self):
     self.assertRaises(RuntimeError, lambda: pt.load_topology('dummy'))
Esempio n. 47
0
 def test_select_mask(self):
     top = pt.load_topology("./data/Tc5b.top")
     arr0 = top.atom_indices("@CA")
Esempio n. 48
0
 def test_empty_top(self):
     top = Topology()
     assert top.is_empty() == True
     filename = "./data/Tc5b.top"
     top = pt.load_topology(filename)
     assert top.is_empty() == False
Esempio n. 49
0
 def test_del_top(self):
     # why here? lazy to make another file
     top = pt.load_topology("./data/Tc5b.top")
     top2 = top
     del top
import pytraj as pt
from netCDF4 import Dataset
from pytraj.testing import Timer

filename = 'GAAC3.5000frames.nc'
top_name = 'GAAC.topo'
top = pt.load_topology(top_name)

@Timer()
def load_netcdf4(filename=filename):
    with Dataset(filename, 'r') as fh:
        c= fh['coordinates']
        return c[:N]

@Timer()
def load_mutable_traj(filename=filename):
    with Dataset(filename, 'r') as fh:
        c= fh['coordinates']
        traj = pt.Trajectory(xyz=c[:N], top=top.copy())
        traj.xyz[:] = traj.xyz.astype('f8')

@Timer()
def load_immutable_traj(filename=filename, top_name=top_name):
    traj = pt.iterload(filename, top_name)
    return traj[:N]

if __name__ == '__main__':
    import sys
    from collections import OrderedDict
    from matplotlib import pyplot as plt
Esempio n. 51
0
#!/usr/bin/env python
import sys
import parmed as pmd
import pytraj as pt
from collections import Counter

fname = '3gx5.14sb.gaff.parm7'
parm  = pmd.load_file(fname)

print('resname set', set(res.name for res in parm.residues)) 
print('total charge : ', sum(atom.charge for atom in parm.atoms))

print(pmd.tools.summary(parm))
print(pt.load_topology(fname))

print(Counter(res.name for res in parm.residues))