def test_measure(file_3nob):
    m1 = molecule.load("mae", file_3nob)
    m2 = molecule.load("mae", file_3nob)

    with pytest.warns(SyntaxWarning):
        assert measure.bond(0, 0, m1, m2, frame=0, first=0) == [pytest.approx(0.)]

    assert measure.bond(atom1=0, atom2=10, molid=m1)[0] == pytest.approx(4.97422456)
    assert measure.bond(atom1=0, atom2=10)[0] == pytest.approx(4.97422456)

    # One atom listed multiple times
    with pytest.raises(RuntimeError):
        measure.angle(0, 0, 0)

    with pytest.warns(SyntaxWarning):
        assert measure.angle(0, 1, 2, frame=0,
                             last=1) == [pytest.approx(119.7387237548)]

    assert measure.angle(atom1=0, atom2=1, atom3=0, molid=m1, molid2=m2,
                         molid3=m1)[0] == pytest.approx(0.0)

    with pytest.raises(RuntimeError):
        measure.dihedral(0,0,0,0)

    molecule.delete(m1)
    molecule.delete(m2)
def check_result(format, outdir, solvent=True, lipid=True):
    if format == "prmtop":
        m2 = molecule.load("parm7", os.path.join(outdir, "test.prmtop"),
                           "rst7", os.path.join(outdir, "test.inpcrd"))
    elif format == "psf":
        m2 = molecule.load("psf", os.path.join(outdir, "test.psf"), "pdb",
                           os.path.join(outdir, "test.pdb"))
    # Check by reading .top file, as VMD won't parse it and .gro doesn't
    # have bond information
    elif format == "gro":
        return check_gro(os.path.join(outdir, "test.top"), lipid=lipid)

    elif format == "lammps":
        return check_lammps(os.path.join(outdir, "test.dat"))

    molecule.set_top(m2)

    assert len(set(atomsel("protein").resid)) == 282
    assert len(set(atomsel("resname ACE NMA NME").resid)) == 4
    if solvent:
        assert len(atomsel("water")) == 32106
        assert len(atomsel("same fragment as lipid")) == 12194

    # Check for the corrrect number of alprenolols
    assert len(atomsel("resname ALP")) == 420
    assert len(set(atomsel("resname ALP").resid)) == 10
    assert any(_ in set(atomsel("resname ALP").name) for _ in ["O09", "OX"])
    assert "O1" not in set(atomsel("resname ALP").name)

    # Check coordinates are unique (not zero)
    assert len(atomsel("resname ALP")) == 420
    assert 0.0 not in atomsel("resname ALP").x

    molecule.delete(m2)
Exemple #3
0
 def __init__(self,dcd=None,psf=None,first=0,last=-1,stride=1,waitfor=-1,pdb=None):
     
     self.molID=0
     if psf is not None:
             self.psf = psf
             self.molID=molecule.load('psf',psf)
     if  (pdb is None) and (dcd is not None):
         try:
             self.dcd = dcd
             self.molID=molecule.new('new')
             self.molID=molecule.load('psf',self.psf) # load trajectory
             molecule.read(self.molID,'dcd',self.dcd,stride=stride,first=first,last=last,waitfor=waitfor) 
             print ("DCD file detected id ",self.molID)
         except IOError:
             print ("Could not read dcd file or psf:", dcd)
             raise Exception()
     else:
         try:
             self.molID=molecule.new('pdb')
             self.pdb=pdb
             molecule.read(molid=self.molID,filetype ='pdb',filename=self.pdb,first=0,last=0) 
             print ("pdb file detected id ",self.molID)
         except IOError:
             print ("Could not read dcd file or psf:",pdb)
             raise Exception()
def test_multiligand_psf_opls(tmpdir):
    """
    Charmm parameters, OPLS AA/M format
    """
    from dabble.param import CharmmWriter
    p = str(tmpdir)

    molid = molecule.load("mae",
                          os.path.join(dir, "test_multiligand_correct.mae"))

    # lipid unsupported
    w = CharmmWriter(tmp_dir=p,
                     molid=molid,
                     forcefield="opls",
                     extra_topos=[os.path.join(dir, "dalp_opls.rtf")],
                     extra_params=[os.path.join(dir, "dalp_opls.prm")])
    with pytest.raises(ValueError):
        w.write(os.path.join(p, "test"))

    # No lipid should work
    molecule.delete(molid)
    molid = molecule.load("mae", os.path.join(dir, "B2AR_10ALPs.mae"))
    w = CharmmWriter(tmp_dir=p,
                     molid=molid,
                     forcefield="opls",
                     extra_topos=[os.path.join(dir, "dalp_opls.rtf")],
                     extra_params=[os.path.join(dir, "dalp_opls.prm")])
    w.write(os.path.join(p, "test"))
    check_result("psf", p, solvent=False, lipid=False)
Exemple #5
0
def test_multiple_insertion_codes(tmpdir):
    from dabble.param import CharmmWriter

    # Generate the file
    p = str(tmpdir)
    molid = molecule.load("mae", os.path.join(dir, "3PTB_1lig_prepped.mae"))
    w = CharmmWriter(molid=molid,
                     tmp_dir=p,
                     forcefield="charmm",
                     hmr=False,
                     override_defaults=False)
    w.write(os.path.join(p, "test"))

    # Load the output file and start checking it
    m2 = molecule.load("psf", os.path.join(p, "test.psf"), "pdb",
                       os.path.join(p, "test.pdb"))
    molecule.set_top(m2)

    # Check the entire protein is there and connected
    assert len(atomsel("protein or resname ACE NMA NME")) == 3229
    assert len(set(atomsel("protein or resname ACE NMA NME").fragment)) == 1

    # Check the calcium ion is present
    assert atomsel("element Ca").resname == ["CAL"]

    # Check residues with insertion codes
    assert set(atomsel("resid 184").resname) == set(["GLY", "TYR"])
    assert set(atomsel("resid 188").resname) == set(["GLY", "LYS"])
    assert set(atomsel("resid 221").resname) == set(["ALA", "GLN"])
    assert set(atomsel("resid 245").resname) == set(["ASN", "NMA"])
    assert set(atomsel("all").insertion) == set([" ", "A"])

    # Check the ligand is there
    assert len(atomsel("resname BAMI")) == 18
def test_multiligand_parameterizing(tmpdir):
    """
    Checks the parameterization of a system with multiple ligands
    """
    from vmd import atomsel, molecule
    from Dabble.param import CharmmWriter

    # Parameterize the multiple ligand system with charmm parameters
    p = str(tmpdir.mkdir("multiligand_parameterize"))
    molid = molecule.load("mae", os.path.join(dir, "test_multiligand_correct.mae"))
    w = CharmmWriter(tmp_dir=p, molid=molid, lipid_sel="lipid",
                     extra_topos=[os.path.join(dir, "alprenolol.rtf")])
    w.write(os.path.join(p, "test"))

    # Load the created file
    m2 = molecule.load("psf", os.path.join(p, "test.psf"))
    molecule.set_top(m2)

    # Check the system is intact
    assert(len(set(atomsel("protein").get("resid"))) == 282)
    assert(len(set(atomsel("resname ACE NMA").get("resid"))) == 4)
    assert(len(atomsel("water")) == 32106)
    assert(len(atomsel("lipid")) == 12194)

    # Check for the correct number of alprenolols
    assert(len(atomsel("resname ALP")) == 420)
    assert(set(atomsel("resname ALP").get("resid")) == set(range(1,11)))
Exemple #7
0
def test_measure(file_3nob):
    m1 = molecule.load("mae", file_3nob)
    m2 = molecule.load("mae", file_3nob)

    with pytest.warns(SyntaxWarning):
        assert measure.bond(0, 0, m1, m2, frame=0,
                            first=0) == [pytest.approx(0.)]

    assert measure.bond(atom1=0, atom2=10,
                        molid=m1)[0] == pytest.approx(4.97422456)
    assert measure.bond(atom1=0, atom2=10)[0] == pytest.approx(4.97422456)

    # One atom listed multiple times
    with pytest.raises(RuntimeError):
        measure.angle(0, 0, 0)

    with pytest.warns(SyntaxWarning):
        assert measure.angle(0, 1, 2, frame=0,
                             last=1) == [pytest.approx(119.7387237548)]

    assert measure.angle(atom1=0,
                         atom2=1,
                         atom3=0,
                         molid=m1,
                         molid2=m2,
                         molid3=m1)[0] == pytest.approx(0.0)

    with pytest.raises(RuntimeError):
        measure.dihedral(0, 0, 0, 0)

    molecule.delete(m1)
    molecule.delete(m2)
Exemple #8
0
def test_pdb_amber_custom_residues(tmpdir):
    from dabble.param import AmberWriter

    p = str(tmpdir)
    molid = molecule.load("pdb", os.path.join(dir, "prepped.pdb"))
    w = AmberWriter(molid,
                    tmp_dir=p,
                    forcefield="amber",
                    hmr=False,
                    extra_topos=[
                        os.path.join(dir, "glx.off"),
                        os.path.join(dir, "lyx.off")
                    ],
                    extra_params=[
                        os.path.join(dir, "join.frcmod"),
                        os.path.join(dir, "analogies.frcmod")
                    ],
                    override_defaults=False)
    w.write(os.path.join(p, "test"))

    # Check for correctness
    m2 = molecule.load("parm7", os.path.join(p, "test.prmtop"), "rst7",
                       os.path.join(p, "test.inpcrd"))
    verify_amber(m2)
    molecule.delete(m2)
Exemple #9
0
def test_amber_params(tmpdir):
    """
    Tests writing a ligand with amber parameters
    """
    from Dabble.param import AmberWriter

    # Parameterize with amber parameters
    p = str(tmpdir.mkdir("multiligand_rename"))
    molid = molecule.load("mae", os.path.join(dir, "07HT2B_WT.mae"))
    w = AmberWriter(molid, tmp_dir=p, forcefield="amber", hmr=False,
                    extra_topos=[os.path.join(dir,"lsd.lib")],
                    extra_params=[os.path.join(dir, "lsd.frcmod")],
                    override_defaults=False)
    w.write(os.path.join(p, "test"))

    # Check output is correct
    m2 = molecule.load("parm7", os.path.join(p, "test.prmtop"),
                       "rst7", os.path.join(p, "test.inpcrd"))
    molecule.set_top(m2)

    # Check the system is correctly built
    assert(len(set(atomsel("protein or resname ACE NMA").get("resid"))) == 298)
    assert(len(atomsel("water")) == 186)
    assert(len(atomsel("ion")) == 0)

    # Check the LSD and CHL (cholesterol) are present
    assert(len(atomsel("resname LSD")) == 50)
    assert(len(atomsel("resname CHL")) == 74)

    # Check the partial charges are set
    # Here the LSD library has partial charges of 0 except +0.6 on the N2
    assert(len(set(atomsel("resname LSD").get("charge"))) == 2)
    assert(abs(atomsel("resname LSD and name N2").get("charge")[0] - 0.6) < 0.01)
    assert(abs(set(atomsel("resname LSD and not name N2").get("charge")).pop()) < 0.01)
Exemple #10
0
def test_residue_renaming(tmpdir):
    """
    Reads a mol2 of LSD with incorrect names as a VMD graph.
    Then, loads a lib file for LSD with correct names, and gaff
    atom types. Should ideally match them up correctly.
    """
    from vmd import atomsel, molecule
    from Dabble.param import AmberMatcher

    # Generate a leaprc file with correct paths
    tmpdir = str(tmpdir)
    filename = os.path.join(tmpdir, "leaprc.lsd")
    fh = open(filename, 'w')
    fh.write("source %s\n" % os.path.join(dir, "leaprc.gaff"))
    fh.write("loadOff %s\n" % os.path.join(dir, "lsd.lib"))
    fh.close()

    molecule.load("mae", os.path.join(dir, "lsd_prot.mae"))
    g = AmberMatcher([filename])
    resnaem, mdict = g.get_names(atomsel())

    # Check matching. Ignore hydrogens since those can vary
    assert set(resnaem.values()) == set(["LIG"])
    nohdict = dict((k,v) for k,v in mdict.items() if v[0] != "H")
    assert nohdict == {0: 'C13', 1: 'N2', 2: 'C12', 3: 'C11', 4: 'C15', 5: 'C7',
                       6: 'C3', 7: 'C8', 8: 'N1', 9: 'C1', 10: 'C4', 11: 'C5',
                       12: 'C2', 13: 'C6', 14: 'C9', 15: 'C10', 16: 'C14',
                       17: 'C16', 18: 'O1', 19: 'N3', 20: 'C19', 21: 'C20',
                       22: 'C17', 23: 'C18'}
Exemple #11
0
def test_amber_custom_residues(tmpdir):
    from dabble.param import AmberWriter

    # Generate the file
    p = str(tmpdir)
    molid = molecule.load("mae", os.path.join(dir, "prepped.mae"))
    w = AmberWriter(molid,
                    tmp_dir=p,
                    forcefield="amber",
                    hmr=False,
                    extra_topos=[
                        os.path.join(dir, "glx.off"),
                        os.path.join(dir, "lyx.off")
                    ],
                    extra_params=[
                        os.path.join(dir, "join.frcmod"),
                        os.path.join(dir, "analogies.frcmod")
                    ],
                    override_defaults=False)
    w.write(os.path.join(p, "test"))

    # Load the output file and start checking it
    m2 = molecule.load("parm7", os.path.join(p, "test.prmtop"), "rst7",
                       os.path.join(p, "test.inpcrd"))

    verify_amber(m2)
    molecule.delete(m2)
Exemple #12
0
def general_water(tmpdir, writerclass, forcefield, water_model):
    """
    Tests water generally
    """
    m = molecule.load("pdb", os.path.join(dir, "tip3.pdb"))
    p = str(tmpdir)

    w = writerclass(molid=m,
                    tmp_dir=p,
                    forcefield=forcefield,
                    water_model=water_model)
    w.write(os.path.join(p, "test"))

    if os.path.isfile(os.path.join(p, "test.prmtop")):
        tm = molecule.load("parm7", os.path.join(p, "test.prmtop"), "rst7",
                           os.path.join(p, "test.inpcrd"))
    else:
        tm = molecule.load("psf", os.path.join(p, "test.psf"), "pdb",
                           os.path.join(p, "test.pdb"))

    molecule.set_top(tm)
    watsel = "water or resname TIP3 TP4E TP4 SPC SPCE"
    assert len(set(atomsel(watsel).residue)) == 1
    assert len(set(atomsel(watsel).resid)) == 1

    if water_model == "tip4e":
        assert len(atomsel()) == 4
    else:  # SPC or TIP3
        assert len(atomsel()) == 3
Exemple #13
0
def load_solute(filename, tmp_dir):
    """
    Loads a molecule input file, guessing the format from the extension.

    Args:
      filename (str): Filename to load
      tmp_dir (str): Directory to put temporary files in

    Returns:
      (int) VMD molecule ID that was loaded

    Raises:
      ValueError if filetype is currently unsupported
    """
    if len(filename) < 3:
        raise ValueError("Cannot determine filetype of input file '%s'"
                         % filename)
    ext = filename[-3:]
    if ext == 'mae':
        molid = molecule.load('mae', filename)
    elif ext == 'dms':
        molid = molecule.load('dms', filename)
    elif ext == 'pdb':
        # Need to convert to MAE so concatenation will work later
        temp_mae = tempfile.mkstemp(suffix='.mae', prefix='dabble_input',
                                    dir=tmp_dir)[1]
        molid = molecule.load('pdb', filename)
        atomsel('all').write('mae', temp_mae)
        molecule.delete(molid)
        molid = molecule.load('mae', temp_mae)
    else:
        raise ValueError("Filetype '%s' currently unsupported "
                         "for input protein" % ext)
    return molid
Exemple #14
0
def test_atomsel_fit_move(file_3nob):

    m1 = molecule.load("mae", file_3nob)
    m2 = molecule.load("mae", file_3nob)

    sel1 = atomsel("protein", m1)
    sel2 = atomsel("protein", m2)

    # Move one selection over
    assert sel1.x[0] == approx(sel2.x[0])
    sel1.moveby((1.0, 0.0, 0.0))
    assert sel1.x[0] == approx(sel2.x[0] + 1.0)
    sel1.moveby([1.0, 0.0, 0.0])
    assert sel1.x[0] == approx(sel2.x[0] + 2.0)
    assert sel1.y[0] == approx(sel2.y[0])
    assert sel1.z[0] == approx(sel2.z[0])

    # Fit, no weights
    fit1 = sel1.fit(sel2)
    assert fit1[0] == approx(1.0, abs=1e-5)

    # Fit, with weights
    fit0 = sel1.fit(selection=sel2, weight=[0.0] + [1.0]*(len(sel2)-1))
    assert fit0 == approx((1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0,
                           1.0, 0.0, -2.0, 0.0, 0.0, 1.0))

    # Test selection invertible
    fit2 = np.reshape(sel2.fit(sel1), (4,4))
    assert np.linalg.inv(fit2) == approx(np.reshape(fit1, (4,4)))

    # Move
    sel1.move(fit1)
    assert sel1.x[0] == sel2.x[0]

    # Move with a numpy array - all zeros nans the array?
    sel1.move(np.zeros((16,)))
    assert sel1.y == approx(sel1.x, nan_ok=True)
    assert sel1.y != approx(sel1.x, nan_ok=False)

    # Operations on empty selection
    isel = atomsel("resname NOPE", m1)
    with pytest.raises(ValueError):
        isel.moveby((1., 2., 3.))

    with pytest.raises(ValueError):
        isel.move(fit1)

    with pytest.raises(ValueError):
        isel.fit(isel)

    molecule.delete(m1)
    with pytest.raises(ValueError):
        sel1.fit(sel2)

    molecule.delete(m2)
    with pytest.raises(ValueError):
        sel1.moveby((1,2,3))
    with pytest.raises(ValueError):
        sel2.move(fit1)
Exemple #15
0
def test_atomsel_fit_move(file_3nob):

    m1 = molecule.load("mae", file_3nob)
    m2 = molecule.load("mae", file_3nob)

    sel1 = atomsel("protein", m1)
    sel2 = atomsel("protein", m2)

    # Move one selection over
    assert sel1.x[0] == approx(sel2.x[0])
    sel1.moveby((1.0, 0.0, 0.0))
    assert sel1.x[0] == approx(sel2.x[0] + 1.0)
    sel1.moveby([1.0, 0.0, 0.0])
    assert sel1.x[0] == approx(sel2.x[0] + 2.0)
    assert sel1.y[0] == approx(sel2.y[0])
    assert sel1.z[0] == approx(sel2.z[0])

    # Fit, no weights
    fit1 = sel1.fit(sel2)
    assert fit1[0] == approx(1.0, abs=1e-5)

    # Fit, with weights
    fit0 = sel1.fit(selection=sel2, weight=[0.0] + [1.0] * (len(sel2) - 1))
    assert fit0 == approx((1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0,
                           1.0, 0.0, -2.0, 0.0, 0.0, 1.0))

    # Test selection invertible
    fit2 = np.reshape(sel2.fit(sel1), (4, 4))
    assert np.linalg.inv(fit2) == approx(np.reshape(fit1, (4, 4)))

    # Move
    sel1.move(fit1)
    assert sel1.x[0] == sel2.x[0]

    # Move with a numpy array - all zeros nans the array?
    sel1.move(np.zeros((16, )))
    assert sel1.y == approx(sel1.x, nan_ok=True)
    assert sel1.y != approx(sel1.x, nan_ok=False)

    # Operations on empty selection
    isel = atomsel("resname NOPE", m1)
    with pytest.raises(ValueError):
        isel.moveby((1., 2., 3.))

    with pytest.raises(ValueError):
        isel.move(fit1)

    with pytest.raises(ValueError):
        isel.fit(isel)

    molecule.delete(m1)
    with pytest.raises(ValueError):
        sel1.fit(sel2)

    molecule.delete(m2)
    with pytest.raises(ValueError):
        sel1.moveby((1, 2, 3))
    with pytest.raises(ValueError):
        sel2.move(fit1)
Exemple #16
0
def test_atomsel_rmsd(file_3frames):

    m1 = molecule.load("pdb", file_3frames)
    m2 = molecule.load("pdb", file_3frames)
    atomsel("resname ALA", m1).moveby((4.0, 0.0, 0.0))
    atomsel("resname NMA", m1).moveby((0.0, 0.0, -4.0))

    sel1 = atomsel("resname ALA", m1)
    sel2 = atomsel("resname ALA", m2)
    assert sel1.rmsd(sel2) == approx(4.0)

    # Weights cannot be all zero
    with pytest.raises(ValueError):
        sel1.rmsd(sel2, [0.0]*len(sel1))

    # RMSDq - rotation invariant
    sel2.move(np.sin(60) * np.reshape(np.identity(4), (16,)))
    assert sel1.rmsdQCP(sel2) == approx(0.0, abs=1e-5)

    weights = [2.0]*(len(sel1)-1) + [1.0]
    assert sel1.rmsd(selection=sel2, weight=weights) == approx(4.0)
    assert sel1.rmsdQCP(sel2, weights) == approx(0.0, abs=1e-5)

    # RMSD per residue
    perres = atomsel("all", m1).rmsdperresidue(atomsel(molid=m2))
    assert len(perres) == 2
    assert perres[0] == approx(sel1.rmsd(sel2))
    assert perres[1] == approx(4.0)

    wpr = atomsel(molid=m1).rmsdperresidue(atomsel(molid=m2),
                                           weight=[1.0]*10 + [0.0]*6)
    assert wpr[0] == approx(sel1.rmsd(sel2))
    assert np.isnan(wpr[1])

    # Wrong number atoms or weights
    # Same code should catch this for rmsdQCP too
    with pytest.raises(ValueError):
        sel1.rmsd(atomsel(molid=m2))
    with pytest.raises(TypeError):
        sel1.rmsd(selection=sel2, weight=0.0)
    with pytest.raises(ValueError):
        sel1.rmsd(selection=sel2, weight="hello")
    with pytest.raises(ValueError):
        sel1.rmsd(selection=sel2, weight=[1.0, 2.0])
    with pytest.raises(ValueError):
        sel1.rmsd(selection=sel2, weight=[True, True])


    # Operations on deleted molecule
    # Same code should catch this for rmsdQCP etc
    molecule.delete(m1)
    with pytest.raises(ValueError):
        sel2.rmsd(sel1)

    molecule.delete(m2)
    with pytest.raises(ValueError):
        sel1.rmsd(sel2)
Exemple #17
0
def test_covalent_ligand_patches(tmpdir):
    """
    Tests covalently bound ligand parameterization with the graph. One
    hydrogen atom should be renamed in the palmitoylcysteine.
    Also tests for detection of phosphorylations on amino acids.
    """
    from vmd import atomsel, molecule
    from Dabble.param import CharmmWriter

    # Parameterize with charmm parameters
    p = str(tmpdir.mkdir("multiligand_rename"))
    molid = molecule.load("mae", dir + "rho_arr_CYP_prepped_aligned_dowsered.mae")
    w = CharmmWriter(tmp_dir=p, molid=molid, lipid_sel="lipid",
                     extra_topos=[dir + "CYP_v1.str"])
    w.write(os.path.join(p, "test"))

    # Load the result
    m2 = molecule.load("psf", os.path.join(p, "test.psf"))
    molecule.set_top(m2)

    # Sanity check the system was built completely
    assert(len(set(atomsel("protein or resname ACE NMA").get("resid"))) == 699)
    assert(len(set(atomsel("resname ACE NMA").get("resid"))) == 4)
    assert(len(atomsel("water")) == 654)
    assert(len(set(atomsel("all").get("fragment"))) == 220)

    # Check for palmitoylation
    assert(len(atomsel("resname CYP")) == 116)
    assert(set(atomsel("resname CYP").get("resid")) == set([322, 323]))

    # Check for protonation on Asp83
    assert(len(atomsel("resid 83 and resname ASP")) == 13)
    assert(len(atomsel("resid 331 and resname ASP")) == 12)
    assert("OH1" in atomsel("resid 83 and resname ASP").get("type"))
    assert("OH1" not in atomsel("resid 331 and resname ASP").get("type"))

    # Check for protation on Glu134A
    assert(len(atomsel("resid 134 and resname GLU")) == 16)
    assert(len(atomsel("resid 247 and resname GLU")) == 15)
    assert("OB" in atomsel("resid 134 and resname GLU").get("type"))
    assert("OB" not in atomsel("resid 331 and resname GLU").get("type"))

    # Check that Ser98 is normal
    assert(len(atomsel("resid 98 and resname SER")) == 11)
    assert("P" not in atomsel("resid 98 and resname SER").get("type"))
    assert("OH1" in atomsel("resid 98 and resname SER").get("type"))

    # Check for phosphorylation on Ser334
    assert(len(atomsel("resid 334 and resname SER")) == 14)
    assert("P" in atomsel("resid 334 and resname SER").get("type"))
    assert("OH1" not in atomsel("resid 334 and resname SER").get("type"))

    # Check for phosphorylation on Ser338
    assert(len(atomsel("resid 338 and resname SER")) == 14)
    assert("P" in atomsel("resid 338 and resname SER").get("type"))
    assert("OH1" not in atomsel("resid 338 and resname SER").get("type"))
Exemple #18
0
def test_atomsel_rmsd(file_3frames):

    m1 = molecule.load("pdb", file_3frames)
    m2 = molecule.load("pdb", file_3frames)
    atomsel("resname ALA", m1).moveby((4.0, 0.0, 0.0))
    atomsel("resname NMA", m1).moveby((0.0, 0.0, -4.0))

    sel1 = atomsel("resname ALA", m1)
    sel2 = atomsel("resname ALA", m2)
    assert sel1.rmsd(sel2) == approx(4.0)

    # Weights cannot be all zero
    with pytest.raises(ValueError):
        sel1.rmsd(sel2, [0.0] * len(sel1))

    # RMSDq - rotation invariant
    sel2.move(np.sin(60) * np.reshape(np.identity(4), (16, )))
    assert sel1.rmsdQCP(sel2) == approx(0.0, abs=1e-5)

    weights = [2.0] * (len(sel1) - 1) + [1.0]
    assert sel1.rmsd(selection=sel2, weight=weights) == approx(4.0)
    assert sel1.rmsdQCP(sel2, weights) == approx(0.0, abs=1e-5)

    # RMSD per residue
    perres = atomsel("all", m1).rmsdperresidue(atomsel(molid=m2))
    assert len(perres) == 2
    assert perres[0] == approx(sel1.rmsd(sel2))
    assert perres[1] == approx(4.0)

    wpr = atomsel(molid=m1).rmsdperresidue(atomsel(molid=m2),
                                           weight=[1.0] * 10 + [0.0] * 6)
    assert wpr[0] == approx(sel1.rmsd(sel2))
    assert np.isnan(wpr[1])

    # Wrong number atoms or weights
    # Same code should catch this for rmsdQCP too
    with pytest.raises(ValueError):
        sel1.rmsd(atomsel(molid=m2))
    with pytest.raises(TypeError):
        sel1.rmsd(selection=sel2, weight=0.0)
    with pytest.raises(ValueError):
        sel1.rmsd(selection=sel2, weight="hello")
    with pytest.raises(ValueError):
        sel1.rmsd(selection=sel2, weight=[1.0, 2.0])
    with pytest.raises(ValueError):
        sel1.rmsd(selection=sel2, weight=[True, True])

    # Operations on deleted molecule
    # Same code should catch this for rmsdQCP etc
    molecule.delete(m1)
    with pytest.raises(ValueError):
        sel2.rmsd(sel1)

    molecule.delete(m2)
    with pytest.raises(ValueError):
        sel1.rmsd(sel2)
Exemple #19
0
def test_load_mae(file_rho):
    from vmd import molecule, atomsel
    assert callable(atomsel)

    molecule.load('mae', file_rho)
    chrg = set(atomsel().get('charge'))
    assert chrg == set([0.0, 1.0, -1.0])

    ins = set(atomsel().get('insertion'))
    assert set(_.strip() for _ in ins) == set(['', 'A'])
Exemple #20
0
def test_load_mae():
    from vmd import molecule, atomsel
    assert callable(atomsel)

    molecule.load('mae', os.path.join(dir, "rho_test.mae"))
    chrg = set(atomsel().get('charge'))
    assert chrg == set([0.0, 1.0, -1.0])

    ins = set(atomsel().get('insertion'))
    assert ins == set([' ', 'A'])
Exemple #21
0
def test_load_mae(file_rho):
    from vmd import molecule, atomsel
    assert callable(atomsel)

    molecule.load('mae', file_rho)
    chrg = set(atomsel().get('charge'))
    assert chrg == set([0.0, 1.0, -1.0])

    ins = set(atomsel().get('insertion'))
    assert set(_.strip() for _ in ins) == set(['', 'A'])
def test_mol_attrs(file_3nob):

    m1 = molecule.load("mae", file_3nob)
    m2 = molecule.load("mae", file_3nob)

    # Get/set top
    assert molecule.get_top() == m2
    molecule.set_top(molid=m1)
    assert molecule.get_top() == m1
    with pytest.raises(ValueError):
        molecule.set_top(m2+1)

    # Get/set visibility
    molecule.set_visible(m1, visible=False)
    assert molecule.get_visible() == False
    assert molecule.get_visible(molid=m2) == True

    with pytest.warns(DeprecationWarning):
        molecule.set_visible(m1, state=True)
    assert molecule.get_visible(molid=m1) == True

    with pytest.raises(ValueError):
        molecule.set_visible(m2+1, True)
    with pytest.raises(TypeError):
        molecule.set_visible(m2, 3)
    with pytest.raises(ValueError):
        molecule.get_visible(m2+1)

    # Get/set periodic
    assert molecule.get_periodic(m2) == {'a': 1.0, 'alpha': 90.0, 'b': 1.0,
                                         'beta': 90.0, 'c': 1.0, 'gamma':
                                         90.0}
    with pytest.raises(ValueError):
        molecule.get_periodic(molid=m1, frame=3000)

    with pytest.raises(ValueError):
        molecule.set_periodic(molid=m2+1, a=2.0)
    with pytest.raises(ValueError):
        molecule.set_periodic(m1, frame=3000, a=20.0)

    molecule.set_periodic(m2, frame=0, a=90.0, b=90.0, c=90.0,
                          alpha=90.0, beta=90.0, gamma=90.0)
    assert list(molecule.get_periodic(m2, frame=0).values()) == [pytest.approx(90.0)]*6
    assert set(molecule.get_periodic(m1, frame=0).values()) != [pytest.approx(90.0)]*6
    molecule.set_periodic(c=20.0)

    assert molecule.get_periodic()["c"] == pytest.approx(20.0)

    molecule.delete(m1)
    molecule.delete(m2)
Exemple #23
0
def test_modrep(file_3nob):
    m = molecule.load("mae", file_3nob)
    r = molrep.addrep(style="Licorice",
                      color="ResID",
                      selection="noh",
                      material="AOEdgy",
                      molid=m)

    with pytest.raises(ValueError):
        molrep.modrep(m + 1, 0)

    with pytest.raises(ValueError):
        molrep.modrep(m, r + 1)

    assert molrep.get_style(m, r) == "Licorice"
    assert molrep.modrep(m, r, style="Lines")
    assert molrep.get_style(m, r) == "Lines"
    assert not molrep.modrep(m, r, style="Invalid")
    assert molrep.get_style(m, r) == "Lines"

    assert molrep.modrep(m,
                         r,
                         color="ColorID 0",
                         selection="resname TIP3",
                         material="Transparent")
    assert molrep.get_selection(m, r) == "resname TIP3"
    assert molrep.get_material(m, r) == "Transparent"
    assert molrep.get_color(m, r) == "ColorID 0"

    molecule.delete(m)
Exemple #24
0
def test_colorscale(file_3nob):
    m = molecule.load("mae", file_3nob)
    r = molrep.addrep(color="User2", selection="lipid", molid=m)

    assert molrep.get_scaleminmax(m, r) == pytest.approx((0., 0.))
    with pytest.raises(ValueError):
        molrep.get_scaleminmax(m + 1, 0)
    with pytest.raises(ValueError):
        molrep.get_scaleminmax(m, r + 1)

    molrep.set_scaleminmax(molid=m, rep=r, scale_min=-10., scale_max=200.)
    assert molrep.get_scaleminmax(m, r) == pytest.approx((-10., 200.))
    with pytest.raises(ValueError):
        molrep.set_scaleminmax(m + 1, 0, 0, 12)
    with pytest.raises(ValueError):
        molrep.set_scaleminmax(m, r + 1, 12, 13)
    with pytest.raises(RuntimeError):
        molrep.set_scaleminmax(m, r, scale_min=100, scale_max=0)

    # Test reset
    molrep.reset_scaleminmax(molid=m, rep=r)
    assert molrep.get_scaleminmax(m, r) == pytest.approx((-10., 200.))
    with pytest.raises(ValueError):
        molrep.reset_scaleminmax(m + 1, 0)
    with pytest.raises(ValueError):
        molrep.reset_scaleminmax(m, r + 1)

    # Test changing with modrep
    assert molrep.modrep(m, r, scaleminmax=(2.0, 3.0))
    assert molrep.get_scaleminmax(m, r) == pytest.approx((2.0, 3.0))
    assert molrep.modrep(m, r, scaleminmax=[-10., -5.])
    assert molrep.get_scaleminmax(m, r) == pytest.approx((-10., -5.))

    molecule.delete(m)
def test_basic_load(file_3nob):

    assert molecule.num() == 0
    assert molecule.listall() == []

    m = molecule.load("mae", file_3nob)

    assert molecule.num() == 1
    assert molecule.listall() == [m]

    assert molecule.exists(m)
    assert not molecule.exists(m+1)

    assert molecule.name(m) == "3nob.mae"
    with pytest.raises(ValueError):
        molecule.name(m+1)

    molecule.rename(m, "newname")
    assert molecule.name(m) == "newname"
    with pytest.raises(ValueError):
        molecule.rename(name="wrong id", molid=m+1)

    assert molecule.numatoms(molid=m) == 2481
    with pytest.raises(ValueError):
        molecule.numatoms(m+1)

    molecule.delete(m)
    with pytest.raises(ValueError):
        molecule.delete(m)
def test_absolute_box(tmpdir):
    """
    Tests the absolute box size for a system with ligands far from
    the box
    """
    from vmd import atomsel, molecule
    from dabble import DabbleBuilder

    # Build the system
    p = str(tmpdir)
    b = DabbleBuilder(solute_filename=os.path.join(dir, "dor_ligs.mae"),
                      output_filename=os.path.join(p, "test.mae"),
                      user_x=75.,
                      user_y=75.,
                      user_z=115.,
                      overwrite=True,
                      tmp_dir=p,
                      exclude_sel="same fragment as resname FRAG")
    b.write()

    # Load the built system
    m2 = molecule.load("mae", os.path.join(p, "test.mae"))
    molecule.set_top(m2)

    # Check all the ligands are there
    assert len(set(atomsel("resname FRAG").residue)) == 3
Exemple #27
0
def test_basic_load(file_3nob):

    assert molecule.num() == 0
    assert molecule.listall() == []

    m = molecule.load("mae", file_3nob)

    assert molecule.num() == 1
    assert molecule.listall() == [m]

    assert molecule.exists(m)
    assert not molecule.exists(m + 1)

    assert molecule.name(m) == "3nob.mae"
    with pytest.raises(ValueError):
        molecule.name(m + 1)

    molecule.rename(m, "newname")
    assert molecule.name(m) == "newname"
    with pytest.raises(ValueError):
        molecule.rename(name="wrong id", molid=m + 1)

    assert molecule.numatoms(molid=m) == 2481
    with pytest.raises(ValueError):
        molecule.numatoms(m + 1)

    molecule.delete(m)
    with pytest.raises(ValueError):
        molecule.delete(m)
Exemple #28
0
def test_atomsel_update(file_3frames):

    m = molecule.load("pdb", file_3frames)
    atomsel("resid 1", m, frame=2).user = 1.0
    sel = atomsel("user 1.0", molid=m, frame=-1)

    assert sel.frame == -1
    assert sel.index == list(range(10))

    altersel = atomsel("index 9", m, frame=2)
    altersel.user = 0.0
    assert atomsel("index 8 9", m, frame=2).user == approx([1.0, 0.0])
    assert atomsel("index 8 9", m, frame=0).user == approx([0.0, 0.0])

    # Selection should only change if the frame is set to update
    molecule.set_frame(m, 2)
    assert sel.index == list(range(10))
    sel.update()
    assert sel.index == list(range(9))

    # Now put it back to another frame
    sel.frame = 0
    assert sel.frame == 0
    assert sel.index == list(range(9))
    sel.update()
    assert sel.index == []

    molecule.delete(m)
Exemple #29
0
def center_system(molid, tmp_dir, center_z=False):
    """
    Centers an entire system in the XY-plane, and optionally in the Z
    dimension. Needs to save and reload the file in case the current
    positions need to be concatenated to produce a new file.

    Args:
      molid (int): VMD molecule id to center
      tmp_dir (str): Directory to create temp file in
      center_z (bool): Whether or not to center along the Z axis as well

    Returns:
      (int) : VMD molecule id of centered system
    """
    # pylint: disable=invalid-name
    x, y, z = atomsel('all', molid=molid).center()

    if center_z is True:
        atomsel('all', molid=molid).moveby((-x, -y, -z))
    else:
        atomsel('all', molid=molid).moveby((-x, -y, 0))

    # Save and reload the solute to record atom positions
    temp_mae = tempfile.mkstemp(suffix='.mae',
                                prefix='dabble_centered',
                                dir=tmp_dir)[1]
    atomsel('all', molid=molid).write('mae', temp_mae)
    molecule.delete(molid)
    new_id = molecule.load('mae', temp_mae)
    return new_id
Exemple #30
0
def test_animate(file_3frames):
    m = molecule.load("pdb", file_3frames)
    assert molecule.numframes(m) == 3
    molecule.set_frame(m, 0)

    with pytest.raises(ValueError):
        animate.activate(-3000, True)

    animate.activate(molid=m, active=False)
    assert not animate.is_active(m)

    animate.activate(m, True)
    assert animate.is_active(m)

    animate.goto(0)
    display.update()
    assert molecule.get_frame(m) == 0

    animate.goto(1)
    display.update()
    assert molecule.get_frame(m) == 1

    animate.forward()
    animate.reverse()
    animate.next()
    animate.prev()
    animate.pause()

    molecule.delete(m)
Exemple #31
0
def check_built_system(p):

    from vmd import atomsel, molecule

    # Load the built system for checking
    assert os.path.isfile(os.path.join(p, "test.prmtop"))

    # Use psf so we can check HMR was done correctly
    m3 = molecule.load("parm7", os.path.join(p, "test.prmtop"))

    # Check the protein is there with correct capping groups
    assert len(atomsel("protein", m3)) == 299
    assert len(set(atomsel("resname ACE NMA NME", m3).get("resid"))) == 2

    # Check for 3 phosphoserines and no regular serines
    molecule.set_top(m3)
    assert atomsel("resname SER SEP").get("name").count("P") == 3
    assert not atomsel("resname SER SEP and not same residue as name P")

    # Check for one phosphothreonine
    assert len(set(atomsel("resname THR TPO").get("resid"))) == 3
    assert len(atomsel("resname THR TPO and name P")) == 1

    # Check HMR was done correctly
    minmasspost = min(atomsel("all", m3).get("mass"))
    assert abs(minmasspost - 1.008) > 0.0001
Exemple #32
0
def test_add_representation(file_3nob):
    m = molecule.load("mae", file_3nob)

    assert molrep.num(m) == 1
    with pytest.raises(ValueError):
        molrep.num(m+1)

    with pytest.raises(ValueError):
        molrep.addrep(molid=m, style="Invalid")

    with pytest.raises(ValueError):
        molrep.addrep(m, style="NewCartoon", color="Invalid")

    with pytest.raises(ValueError):
        molrep.addrep(m, "NewCartoon", "Type", selection="unparseable")

    with pytest.raises(ValueError):
        molrep.addrep(m, "NewCartoon", "Type", "protein", material="Invalid")

    r = molrep.addrep(style="NewCartoon", color="ResID", selection="protein",
                      material="AOShiny", molid=m)
    assert r == 1

    with pytest.raises(ValueError):
        molrep.delrep(m+1, 0)

    with pytest.raises(ValueError):
        molrep.delrep(m, rep=r+1)

    molrep.delrep(rep=r, molid=m)
    assert molrep.num(m) == 1

    molecule.delete(m)
Exemple #33
0
def test_mol_center(file_3nob):

    m = molecule.load("mae", file_3nob)

    init_center = trans.get_center(m)
    trans.set_center(m, center=(1., 1., 1.))
    assert trans.get_center(m) == pytest.approx((1., 1., 1.))
    trans.set_center(m, center=[0., 0., 0.])
    assert trans.get_center(m) == pytest.approx((0., 0., 0.))

    with pytest.raises(ValueError):
        trans.get_center(molid=m+1)

    with pytest.raises(ValueError):
        trans.set_center(m+1, (3., 2., 1.))

    with pytest.raises(TypeError):
        trans.set_center(molid=m, center=(1.))

    trans.resetview(m)
    assert trans.get_center(m) == pytest.approx(init_center)

    with pytest.raises(ValueError):
        trans.resetview(molid=m+1)

    molecule.delete(m)
def test_mol_time(file_3frames):

    m = molecule.load("pdb", file_3frames)
    assert molecule.numframes(m) == 3

    assert molecule.get_physical_time(molid=m, frame=0) == pytest.approx(0.0)
    with pytest.raises(ValueError):
        molecule.get_physical_time(m+1)

    # Test all valid combinations of default keyword arguments
    molecule.set_frame(m, 0)
    molecule.set_physical_time(molid=m, frame=2, time=20.0)
    molecule.set_physical_time(m, 10.0, frame=1)
    molecule.set_physical_time(m, 3.0)

    assert molecule.get_physical_time(m) == pytest.approx(3.0)
    molecule.set_frame(m, frame=2)
    assert molecule.get_physical_time(molid=m) == pytest.approx(20.0)
    assert molecule.get_physical_time(m, frame=1) == pytest.approx(10.0)

    with pytest.raises(ValueError):
        molecule.set_physical_time(molid=m+1, time=20.0)
    with pytest.raises(ValueError):
        molecule.set_physical_time(m, time=30.0, frame=3000)

    molecule.delete(m)
Exemple #35
0
def test_atomsel_update(file_3frames):

    m = molecule.load("pdb", file_3frames)
    atomsel("resid 1", m, frame=2).user = 1.0
    sel = atomsel("user 1.0", molid=m, frame=-1)

    assert sel.frame == -1
    assert sel.index == list(range(10))

    altersel = atomsel("index 9", m, frame=2)
    altersel.user = 0.0
    assert atomsel("index 8 9", m, frame=2).user == approx([1.0, 0.0])
    assert atomsel("index 8 9", m, frame=0).user == approx([0.0, 0.0])

    # Selection should only change if the frame is set to update
    molecule.set_frame(m, 2)
    assert sel.index == list(range(10))
    sel.update()
    assert sel.index == list(range(9))

    # Now put it back to another frame
    sel.frame = 0
    assert sel.frame == 0
    assert sel.index == list(range(9))
    sel.update()
    assert sel.index == []

    molecule.delete(m)
def test_shapes():

    mid2 = molecule.load("graphics", "test")

    assert graphics.listall(mid2) == []

    with pytest.raises(ValueError):
        graphics.cone(molid=mid2+1, v1=(0,0,0), v2=(3,5,9))

    assert graphics.cone(molid=mid2, v1=(0,0,0), v2=(3,5,9)) == 0
    assert graphics.triangle(mid2, (1,0,0), (0,1,0), (0,0,1)) == 1
    assert graphics.listall(mid2) == [0, 1]

    graphics.trinorm(mid2, (1,0,0), (0,1,0), (0,0,1),
                     n1=(0,1,0), n2=(1,0,0), n3=(0,0,1))

    graphics.cylinder(mid2, v1=(10,10,0), v2=(0,10,10), radius=3.,
                      resolution=4, filled=True)

    graphics.point(mid2, (20, 3, 1))

    graphics.line(mid2, (-1,1,-3), (3,4,5))
    with pytest.raises(ValueError):
        graphics.line(mid2, (-1,1,-3), (3,4,5), style="invalid")

    assert len(graphics.listall(mid2)) == 6
    graphics.delete(mid2, "all")
    assert len(graphics.listall(mid2)) == 0
    with pytest.raises(ValueError):
        graphics.delete(mid2, "invalid")
    with pytest.raises(TypeError):
        graphics.delete(mid2, 39.0)

    molecule.delete(mid2)
Exemple #37
0
def test_basic_getset(file_3frames):

    m = molecule.load("pdb", file_3frames)
    sel = atomsel(selection="protein", molid=m, frame=1)

    assert sel.frame == 1
    assert sel.molid == m
    assert len(sel.bonds) == 10
    assert str(sel) == "protein"
    assert repr(sel) == "atomsel('protein', molid=%d, frame=%d)" % (m, 1)

    # Default selections
    molecule.set_frame(m, 2)
    molecule.set_top(m)
    sel = atomsel()
    assert repr(sel) == "atomsel('all', molid=%d, frame=-1)" % m

    # Set something without a setter
    with pytest.raises(AttributeError):
        sel.molid = m + 1

    # Invalid selection text
    with pytest.raises(ValueError):
        atomsel(selection="cannot be parsed")

    molecule.delete(m)

    # Selection on deleted molecule
    with pytest.raises(ValueError):
        assert sel.frame == 1
    with pytest.raises(ValueError):
        assert sel.molid == m
    with pytest.raises(ValueError):
        assert sel.bonds == []
Exemple #38
0
def test_mol_rotate(file_3nob):

    m = molecule.load("mae", file_3nob)

    r = trans.get_rotation(molid=m)
    assert r == pytest.approx((1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
                               0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0))

    newrot = [x + 2. for x in r]
    trans.set_rotation(m, newrot)
    assert trans.get_rotation(molid=m) == pytest.approx(newrot)

    with pytest.raises(ValueError):
        trans.get_rotation(m + 1)

    with pytest.raises(ValueError):
        trans.set_rotation(m + 1, [0.] * 16)

    with pytest.raises(TypeError):
        trans.set_rotation(molid=m, matrix=12)

    with pytest.raises(TypeError):
        trans.set_rotation(m, [True] * 16)

    trans.resetview(m)
    assert trans.get_rotation(m) == r
    molecule.delete(m)
Exemple #39
0
def test_show_fix(file_3nob):
    m = molecule.load("mae", file_3nob)

    trans.show(molid=m, shown=True)
    assert trans.is_shown(m)

    with pytest.raises(ValueError):
        trans.show(m+1, True)

    with pytest.raises(ValueError):
        trans.is_shown(m+1)

    trans.show(m, False)
    assert not trans.is_shown(molid=m)

    trans.fix(m, fixed=False)
    assert not trans.is_fixed(m)

    trans.fix(m, True)
    assert trans.is_fixed(m)

    with pytest.raises(ValueError):
        trans.fix(m+1, True)

    with pytest.raises(ValueError):
        trans.is_fixed(m+1)

    molecule.delete(m)
Exemple #40
0
def test_mol_center(file_3nob):

    m = molecule.load("mae", file_3nob)

    init_center = trans.get_center(m)
    trans.set_center(m, center=(1., 1., 1.))
    assert trans.get_center(m) == pytest.approx((1., 1., 1.))
    trans.set_center(m, center=[0., 0., 0.])
    assert trans.get_center(m) == pytest.approx((0., 0., 0.))

    with pytest.raises(ValueError):
        trans.get_center(molid=m + 1)

    with pytest.raises(ValueError):
        trans.set_center(m + 1, (3., 2., 1.))

    with pytest.raises(TypeError):
        trans.set_center(molid=m, center=(1.))

    trans.resetview(m)
    assert trans.get_center(m) == pytest.approx(init_center)

    with pytest.raises(ValueError):
        trans.resetview(molid=m + 1)

    molecule.delete(m)
Exemple #41
0
def test_mol_time(file_3frames):

    m = molecule.load("pdb", file_3frames)
    assert molecule.numframes(m) == 3

    assert molecule.get_physical_time(molid=m, frame=0) == pytest.approx(0.0)
    with pytest.raises(ValueError):
        molecule.get_physical_time(m + 1)

    # Test all valid combinations of default keyword arguments
    molecule.set_frame(m, 0)
    molecule.set_physical_time(molid=m, frame=2, time=20.0)
    molecule.set_physical_time(m, 10.0, frame=1)
    molecule.set_physical_time(m, 3.0)

    assert molecule.get_physical_time(m) == pytest.approx(3.0)
    molecule.set_frame(m, frame=2)
    assert molecule.get_physical_time(molid=m) == pytest.approx(20.0)
    assert molecule.get_physical_time(m, frame=1) == pytest.approx(10.0)

    with pytest.raises(ValueError):
        molecule.set_physical_time(molid=m + 1, time=20.0)
    with pytest.raises(ValueError):
        molecule.set_physical_time(m, time=30.0, frame=3000)

    molecule.delete(m)
Exemple #42
0
def test_show_fix(file_3nob):
    m = molecule.load("mae", file_3nob)

    trans.show(molid=m, shown=True)
    assert trans.is_shown(m)

    with pytest.raises(ValueError):
        trans.show(m + 1, True)

    with pytest.raises(ValueError):
        trans.is_shown(m + 1)

    trans.show(m, False)
    assert not trans.is_shown(molid=m)

    trans.fix(m, fixed=False)
    assert not trans.is_fixed(m)

    trans.fix(m, True)
    assert trans.is_fixed(m)

    with pytest.raises(ValueError):
        trans.fix(m + 1, True)

    with pytest.raises(ValueError):
        trans.is_fixed(m + 1)

    molecule.delete(m)
Exemple #43
0
def test_animate(file_3frames):
    m = molecule.load("pdb", file_3frames)
    assert molecule.numframes(m) == 3
    molecule.set_frame(m, 0)

    with pytest.raises(ValueError):
        animate.activate(-3000, True)

    animate.activate(molid=m, active=False)
    assert not animate.is_active(m)

    animate.activate(m, True)
    assert animate.is_active(m)

    animate.goto(0)
    display.update()
    assert molecule.get_frame(m) == 0

    animate.goto(1)
    display.update()
    assert molecule.get_frame(m) == 1

    animate.forward()
    animate.reverse()
    animate.next()
    animate.prev()
    animate.pause()

    molecule.delete(m)
Exemple #44
0
def test_autoupdates(file_3nob):
    m = molecule.load("mae", file_3nob)
    r = molrep.addrep(color="User", selection="all", molid=m)

    # Color update
    assert not molrep.get_colorupdate(m, r)
    with pytest.raises(ValueError):
        molrep.get_colorupdate(m + 1, 0)
    with pytest.raises(ValueError):
        molrep.get_colorupdate(m, r + 1)

    molrep.set_colorupdate(m, rep=r, autoupdate=True)
    assert molrep.get_colorupdate(rep=r, molid=m)
    with pytest.raises(ValueError):
        molrep.set_colorupdate(m + 1, 0, False)
    with pytest.raises(ValueError):
        molrep.set_colorupdate(m, r + 1, False)

    # Selection update
    assert not molrep.get_autoupdate(molid=m, rep=r)
    with pytest.raises(ValueError):
        molrep.get_autoupdate(m + 1, 0)
    with pytest.raises(ValueError):
        molrep.get_autoupdate(m, r + 1)

    molrep.set_autoupdate(m, rep=r, autoupdate=True)
    assert molrep.get_autoupdate(rep=r, molid=m)
    with pytest.raises(ValueError):
        molrep.set_autoupdate(m + 1, 0, False)
    with pytest.raises(ValueError):
        molrep.set_autoupdate(m, r + 1, False)

    molecule.delete(m)
Exemple #45
0
def test_vmdnumpy(file_3frames):
    m = molecule.load("pdb", file_3frames)

    # Timestep and positions are equivalent
    assert arr_equals(vmdnumpy.timestep(m, 0), vmdnumpy.positions(m, 0))

    with pytest.raises(ValueError):
        vmdnumpy.timestep(molid=m+1)

    x = vmdnumpy.atomselect(selection="index 0")
    assert x.shape == (16,)
    assert x[0] == 1
    x[0] = 0
    assert arr_equals(x, numpy.zeros(x.shape))

    with pytest.raises(ValueError):
        vmdnumpy.atomselect("garbage atomselection", molid=m, frame=0)

    assert vmdnumpy.velocities(molid=m, frame=0) is None

    # Invalid frame
    with pytest.raises(ValueError):
        assert vmdnumpy.velocities(molid=m, frame=10) is None

    # Test on deleted molecule
    molecule.delete(m)
    with pytest.raises(ValueError):
        vmdnumpy.atomselect("protein")
Exemple #46
0
def test_basic_getset(file_3frames):

    m = molecule.load("pdb", file_3frames)
    sel = atomsel(selection="protein", molid=m, frame=1)

    assert sel.frame == 1
    assert sel.molid == m
    assert len(sel.bonds) == 10
    assert str(sel) == "protein"
    assert repr(sel) == "atomsel('protein', molid=%d, frame=%d)" % (m, 1)

    # Default selections
    molecule.set_frame(m, 2)
    molecule.set_top(m)
    sel = atomsel()
    assert repr(sel) == "atomsel('all', molid=%d, frame=-1)" % m

    # Set something without a setter
    with pytest.raises(AttributeError):
        sel.molid = m+1

    # Invalid selection text
    with pytest.raises(ValueError):
        atomsel(selection="cannot be parsed")

    molecule.delete(m)

    # Selection on deleted molecule
    with pytest.raises(ValueError):
        assert sel.frame == 1
    with pytest.raises(ValueError):
        assert sel.molid == m
    with pytest.raises(ValueError):
        assert sel.bonds == []
Exemple #47
0
def test_autoupdates(file_3nob):
    m = molecule.load("mae", file_3nob)
    r = molrep.addrep(color="User", selection="all", molid=m)

    # Color update
    assert not molrep.get_colorupdate(m, r)
    with pytest.raises(ValueError):
        molrep.get_colorupdate(m+1, 0)
    with pytest.raises(ValueError):
        molrep.get_colorupdate(m, r+1)

    molrep.set_colorupdate(m, rep=r, autoupdate=True)
    assert molrep.get_colorupdate(rep=r, molid=m)
    with pytest.raises(ValueError):
        molrep.set_colorupdate(m+1, 0, False)
    with pytest.raises(ValueError):
        molrep.set_colorupdate(m, r+1, False)

    # Selection update
    assert not molrep.get_autoupdate(molid=m, rep=r)
    with pytest.raises(ValueError):
        molrep.get_autoupdate(m+1, 0)
    with pytest.raises(ValueError):
        molrep.get_autoupdate(m, r+1)

    molrep.set_autoupdate(m, rep=r, autoupdate=True)
    assert molrep.get_autoupdate(rep=r, molid=m)
    with pytest.raises(ValueError):
        molrep.set_autoupdate(m+1, 0, False)
    with pytest.raises(ValueError):
        molrep.set_autoupdate(m, r+1, False)

    molecule.delete(m)
Exemple #48
0
def test_mol_rotate(file_3nob):

    m = molecule.load("mae", file_3nob)

    r = trans.get_rotation(molid=m)
    assert r == pytest.approx((1.0, 0.0, 0.0, 0.0,
                               0.0, 1.0, 0.0, 0.0,
                               0.0, 0.0, 1.0, 0.0,
                               0.0, 0.0, 0.0, 1.0))

    newrot = [x+2. for x in r]
    trans.set_rotation(m, newrot)
    assert trans.get_rotation(molid=m) == pytest.approx(newrot)

    with pytest.raises(ValueError):
        trans.get_rotation(m+1)

    with pytest.raises(ValueError):
        trans.set_rotation(m+1, [0.]*16)

    with pytest.raises(TypeError):
        trans.set_rotation(molid=m, matrix=12)

    with pytest.raises(TypeError):
        trans.set_rotation(m, [True]*16)

    trans.resetview(m)
    assert trans.get_rotation(m) == r
    molecule.delete(m)
Exemple #49
0
def test_patches():
    """
    Tests molecule matching in CHARMM with patches
    """
    from vmd import atomsel, molecule
    from dabble.param import CharmmMatcher

    molid = molecule.load("mae", os.path.join(dir, "phosphoserine.mae"))
    g = CharmmMatcher([os.path.join(dir, "phosphoserine.str")])
    (name, patch, mdict) = g.get_patches(atomsel("resname SEP", molid=molid))
    assert name == "SER"
    assert patch == "PSEP"

    # Oxygens are interchangeable so don't compare them
    correct = {
        16: 'N',
        17: 'CA',
        18: 'CB',
        19: 'OG',
        20: 'C',
        21: 'O',
        22: 'P',
        26: 'HN',
        27: 'HA',
        28: 'HB1',
        29: 'HB2'
    }
    for i, n in correct.items():
        assert mdict[i] == n

    # Interchangeable oxygens
    assert "O" in mdict[23]
    assert "O" in mdict[24]
    assert "O" in mdict[25]
Exemple #50
0
    def _check_psf_output(self):
        """
        Scans the output psf from psfgen for atoms where the coordinate
        could not be set, indicating an unmatched atom. This checek is necessary
        because sometimes psfgen will run with no errors or warnings but will
        have unmatched atoms that are all at (0,0,0).
        """

        # Check file was written at all
        if not os.path.isfile('%s.pdb'% self.psf_name):
            print("\nERROR: psf file failed to write.\n"
                  "       Please see log above.\n")
            quit(1)

        # Open the pdb file in VMD and check for atoms with no occupancy
        fileh = molecule.load('pdb', '%s.pdb' % self.psf_name)
        errors = atomsel("occupancy=-1", molid=fileh)

        # Print out error messages
        if len(errors):
            print("\nERROR: Couldn't find the following atoms.")
            for i in range(len(errors)):
                print("  %s%s:%s" % (errors.get("resname")[i], errors.get("resid")[i],
                                     errors.get("name")[i]))

            print("Check if they are present in the original structure.\n"
                  "If they are, check dabble name translation or file a "
                  "bug report to Robin.\n")
            quit(1)
        else:
            print("\nChecked output pdb/psf has all atoms present "
                  "and correct.\n")
Exemple #51
0
def test_colorscale(file_3nob):
    m = molecule.load("mae", file_3nob)
    r = molrep.addrep(color="User2", selection="lipid", molid=m)

    assert molrep.get_scaleminmax(m, r) == pytest.approx((0., 0.))
    with pytest.raises(ValueError):
        molrep.get_scaleminmax(m+1, 0)
    with pytest.raises(ValueError):
        molrep.get_scaleminmax(m, r+1)

    molrep.set_scaleminmax(molid=m, rep=r, scale_min=-10., scale_max=200.)
    assert molrep.get_scaleminmax(m, r) == pytest.approx((-10., 200.))
    with pytest.raises(ValueError):
        molrep.set_scaleminmax(m+1, 0, 0, 12)
    with pytest.raises(ValueError):
        molrep.set_scaleminmax(m, r+1, 12, 13)
    with pytest.raises(RuntimeError):
        molrep.set_scaleminmax(m, r, scale_min=100, scale_max=0)

    # Test reset
    molrep.reset_scaleminmax(molid=m, rep=r)
    assert molrep.get_scaleminmax(m, r) == pytest.approx((-10., 200.))
    with pytest.raises(ValueError):
        molrep.reset_scaleminmax(m+1, 0)
    with pytest.raises(ValueError):
        molrep.reset_scaleminmax(m, r+1)

    # Test changing with modrep
    assert molrep.modrep(m, r, scaleminmax=(2.0, 3.0))
    assert molrep.get_scaleminmax(m, r) == pytest.approx((2.0, 3.0))
    assert molrep.modrep(m, r, scaleminmax=[-10., -5.])
    assert molrep.get_scaleminmax(m, r) == pytest.approx((-10., -5.))

    molecule.delete(m)
Exemple #52
0
def test_relaxin_disulfides_charmm(tmpdir):
    """
    Tests these disulfides with charmm
    """
    from Dabble.param import CharmmWriter
    from vmd import  molecule

    # Build the system
    p = str(tmpdir.mkdir("charmm_disu"))
    molid = molecule.load("mae", os.path.join(dir, "2MV1_dowserwat.mae"))
    w = CharmmWriter(tmp_dir=p, molid=molid)
    w.write(os.path.join(p, "test"))

    # Check the built system
    m2 = molecule.load("psf", os.path.join(p, "test.psf"))
    check_correctness(m2)
Exemple #53
0
def test_water_box(tmpdir):
    """
    Tests building in a water box only
    """
    from Dabble import DabbleBuilder
    from Dabble import molutils
    from vmd import molecule

    # Build a system with well defined dimensions
    p = str(tmpdir.mkdir("po4_hmr"))
    filename = os.path.join(dir, "rho_test.mae")
    b = DabbleBuilder(solute_filename=filename,
                      output_filename=os.path.join(p, "test.mae"),
                      membrane_system="TIP3",
                      user_x=40.0,
                      user_y=35.0,
                      user_z=65.0,
                      tmp_dir=p)
    b.write()

    # Load the built system for checking
    m2 = molecule.load("mae", os.path.join(p, "test.mae"))
    molecule.set_top(m2)

    # Check the system dimensions
    assert molutils.get_system_dimensions(m2) == (40.0, 35.0, 65.0)
Exemple #54
0
def test_relaxin_disulfides_amber(tmpdir):
    """
    Tests these disulfides with amber
    """
    from Dabble.param import AmberWriter
    from vmd import molecule

    # Build the system
    p = str(tmpdir.mkdir("amber_disu"))
    molid = molecule.load("mae", os.path.join(dir, "2MV1_dowserwat.mae"))
    w = AmberWriter(molid=molid, tmp_dir=p, forcefield="amber")
    w.write(os.path.join(p, "test"))

    # Load and sanity check the built system
    m2 = molecule.load("parm7", os.path.join(p, "test.prmtop"))
    check_correctness(m2)
def test_multiligand_building(tmpdir):
    """
    Solvates and membranes a system with multiple ligands """
    from vmd import atomsel, molecule
    from Dabble import DabbleBuilder

    # Build the system
    p = str(tmpdir.mkdir("multiligand_build"))
    b = DabbleBuilder(solute_filename=os.path.join(dir, "B2AR_10ALPs.mae"),
                      output_filename=os.path.join(p, "test.mae"),
                      xy_buf=10., wat_buffer=10., overwrite=True, tmp_dir=p)
    b.write()

    # Load the built system
    m2 = molecule.load("mae", os.path.join(p, "test.mae"))
    molecule.set_top(m2)

    # Check the system dimensions are correct
    solsel = atomsel("protein or resname ACE NMA ALP")
    prot_x = max(solsel.get("x")) - min(solsel.get("x"))
    prot_y = max(solsel.get("y")) - min(solsel.get("y"))
    prot_z = max(solsel.get("z")) - min(solsel.get("z"))
    assert(abs(molecule.get_periodic(m2)["a"] - prot_x - 20.0) < 0.1)
    assert(abs(molecule.get_periodic(m2)["b"] - prot_y - 20.0) < 0.1)
    assert(abs(molecule.get_periodic(m2)["c"] - prot_z - 20.0) < 0.1)

    # Check all the alprenolols are there
    assert(len(set(atomsel("resname ALP").get("resid"))) == 10)
Exemple #56
0
def test_angles(file_3nob):
    with pytest.raises(ValueError):
        topology.angles(molid=0)

    m = molecule.load("mae", file_3nob)
    molecule.set_top(m)

    # No angles defined in a mae file
    x = topology.angles(molid=m, type=True)
    print(len(x))
    assert len(x) == 0
    assert topology.angletypes() == []

    # pass invalid molid
    with pytest.raises(ValueError):
        topology.addangle(0, 0, 0, molid=-1999)

    assert topology.addangle(i=0, j=1, k=2, molid=m) == 0
    assert topology.angles(m, True) == [(0, 1, 2, None)]

    x = topology.addangle(0, 0, 0, molid=m, type="angle2")
    assert topology.angles(m, True)[x] == (0, 0, 0, "angle2")

    assert topology.delangle(i=0, j=0, k=0, molid=m)
    assert topology.angles(m, True) == [(0, 1, 2, None)]

    assert not topology.delangle(1, 2, 3, molid=m)

    assert topology.delallangles(m) == 1
    assert topology.angletypes() == ["angle2"]

    molecule.delete(m)
def test_write(tmpdir, file_3frames):

    m = molecule.load("pdb", struct_file=file_3frames)
    tmpdir = str(tmpdir)

    # Deprecated arguments
    with pytest.warns(DeprecationWarning):
        molecule.write(m, "psf", beg=0, end=1,
                       filename=os.path.join(tmpdir, "deprecated.psf"))

    # Write with stride
    molecule.write(molid=m, filetype="pdb", first=0, stride=2,
                   filename=os.path.join(tmpdir, "2frames.pdb"))
    m2 = molecule.load("pdb", os.path.join(tmpdir, "2frames.pdb"))
    assert molecule.numframes(m2) == 2

    # Write a selection
    sel = atomsel("resname ALA", molid=m)
    molecule.write(m, "mae", selection=sel, first=0, last=0,
                   filename=os.path.join(tmpdir, "ala.mae"))
    m3 = molecule.load("mae", os.path.join(tmpdir, "ala.mae"))
    assert molecule.numframes(m3) == 1
    assert set(atomsel(molid=m3).resname) == set(["ALA"])

    # Write an invalid selection on a different molid
    sel2 = atomsel("resname ALA", molid=m3)
    with pytest.raises(ValueError):
        molecule.write(m, "mae", os.path.join(tmpdir, "badsel.mae"),
                       selection=sel2)

    # Write a nonexistent atom selection
    with pytest.raises(TypeError):
        molecule.write(m, "mae", os.path.join(tmpdir, "badsel.mae"),
                       selection=None)

    # Write zero frames
    with pytest.raises(ValueError):
        molecule.write(first=20, last=21, molid=m, filetype="psf",
                       filename=os.path.join(tmpdir, "zeroframes.psf"))

    # Write to an invalid file name (in this case, a directory)
    with pytest.raises(ValueError):
        molecule.write(m, "pdb", filename=os.path.join(tmpdir, "."))

    molecule.delete(m)
    molecule.delete(m2)
    molecule.delete(m3)
Exemple #58
0
def test_atomsel_sasa(file_3frames):

    m1 = molecule.load("pdb", file_3frames)
    m2 = molecule.load("pdb", file_3frames)
    s1 = atomsel("resname ALA", m1)
    s2 = atomsel("all", m2)

    # Invalid radius
    with pytest.raises(ValueError):
        s1.sasa(srad=-2.0)

    assert s1.sasa(srad=0.0) == approx(93.86288452)

    # Invalid samples
    with pytest.raises(ValueError):
        s1.sasa(srad=1.0, samples=0)
    with pytest.raises(ValueError):
        s1.sasa(srad=1.0, samples=-10)

    # Points object invalid
    with pytest.raises(TypeError):
        s1.sasa(srad=1.0, points=[])

    with pytest.raises(TypeError):
        s1.sasa(srad=1.0, points=(3,3))

    # Test correct calculation
    assert s1.sasa(srad=1.0) == approx(176.46739)
    assert s2.sasa(1.0, restrict=s1) == approx(142.44455)
    assert s1.sasa(0.5) == approx(s1.sasa(0.5, restrict=s1))

    # Using points object
    _, points = s1.sasa(0.5, points=True, samples=1)
    assert len(points) == 3 # Samples is an upper bound
    assert points[0] == approx((3.99603, 3.19342, 3.62426), rel=1e-3)

    # Test on deleted molecule
    molecule.delete(m1)
    with pytest.raises(ValueError):
        s1.sasa(srad=5.0)

    with pytest.raises(ValueError):
        s2.sasa(1.0, restrict=s1)

    molecule.delete(m2)