示例#1
0
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)
示例#2
0
def test_materials():
    mid = molecule.new(name="Test")
    graphics.materials(molid=mid, on=True)
    graphics.material(molid=mid, name="AOShiny")

    rc = graphics.sphere(molid=mid, center=(1,1,1), radius=5.1, resolution=8)
    assert graphics.info(mid, rc) == "sphere {1.000000 1.000000 1.000000} " +\
        "radius 5.100000 resolution 8"

    with pytest.raises(ValueError):
        graphics.sphere(molid=mid, center=(1,1))

    rc = graphics.text(mid, (0,0,0), "hello world", size=4.0, width=2.0)
    with pytest.raises(ValueError):
        graphics.text(mid, 0, "oops")

    assert graphics.info(mid, rc) == "text {0.000000 0.000000 0.000000} " + \
        "{hello world} size 4.000000 thickness 2.000000"

    with pytest.raises(ValueError):
        graphics.info(mid+1, 3)
    with pytest.raises(IndexError):
        graphics.info(mid, 3000)

    graphics.delete(mid, rc)
    with pytest.raises(IndexError):
        graphics.info(mid, rc)

    molecule.delete(mid)
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)
示例#4
0
文件: builder.py 项目: drorlab/dabble
    def write(self):
        """
        Writes the final built system.

        Args:
          filename (str): Name of file
        """

        fileutils.check_write_ok(self.opts.get('output_filename'),
                                 self.out_fmt,
                                 overwrite=self.opts.get('overwrite'))
        final_id = self._build()

        print("Writing system to %s with %d atoms comprising:\n"
              "  %d lipid molecules\n"
              "  %d water molecules\n"
              % (self.opts.get('output_filename'),
                 molutils.num_atoms_remaining(molid=final_id),
                 molutils.num_lipids_remaining(final_id, self.opts.get('lipid_sel')),
                 molutils.num_waters_remaining(molid=final_id)))
        fileutils.write_final_system(out_fmt=self.out_fmt,
                                     out_name=self.opts.get('output_filename'),
                                     molid=final_id, tmp_dir=self.tmp_dir,
                                     forcefield=self.opts.get('forcefield'),
                                     extra_topos=self.opts.get('extra_topos'),
                                     extra_params=self.opts.get('extra_params'),
                                     extra_streams=self.opts.get('extra_streams'),
                                     hmassrepartition=self.opts.get('hmassrepartition'))
        molecule.delete(final_id)
示例#5
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)
示例#6
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)
示例#7
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
示例#8
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)
示例#9
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)
示例#10
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)
示例#11
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)
示例#12
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)
示例#13
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)
示例#14
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)
示例#15
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)
示例#16
0
def test_special_load(file_3nob, file_3frames, file_psf):

    # Graphics type is special
    m = molecule.load("graphics", "")
    assert molecule.numatoms(m) == 0
    molecule.delete(m)

    # Coordinates and data
    m = molecule.load(struct_type="psf", coord_type="pdb",
                      struct_file=file_psf,
                      coord_file=file_3frames)
    assert molecule.numframes(m) == 3

    # Incorrect numbers of arguments
    with pytest.raises(ValueError):
        molecule.load("psf", file_psf, coord_type="pdb")
    with pytest.raises(ValueError):
        molecule.load("psf", file_psf, coord_file=file_3frames)

    # Nonexistent files
    with pytest.raises(RuntimeError):
        molecule.load("psf", "nonexistent_file")

    with pytest.raises(RuntimeError):
        molecule.load("psf", file_psf, "pdb", "nonexistent_file")

    # Wrong number of atoms in coordinate data
    with pytest.raises(RuntimeError):
        x = molecule.load("mae", file_3nob, "pdb", file_3frames)
        print(molecule.get_filenames(x))

    molecule.delete(m)
示例#17
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
示例#18
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
示例#19
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)
示例#20
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)
示例#21
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 == []
示例#22
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)
示例#23
0
def test_special_load(file_3nob, file_3frames, file_psf):

    # Graphics type is special
    m = molecule.load("graphics", "")
    assert molecule.numatoms(m) == 0
    molecule.delete(m)

    # Coordinates and data
    m = molecule.load(struct_type="psf",
                      coord_type="pdb",
                      struct_file=file_psf,
                      coord_file=file_3frames)
    assert molecule.numframes(m) == 3

    # Incorrect numbers of arguments
    with pytest.raises(ValueError):
        molecule.load("psf", file_psf, coord_type="pdb")
    with pytest.raises(ValueError):
        molecule.load("psf", file_psf, coord_file=file_3frames)

    # Nonexistent files
    with pytest.raises(RuntimeError):
        molecule.load("psf", "nonexistent_file")

    with pytest.raises(RuntimeError):
        molecule.load("psf", file_psf, "pdb", "nonexistent_file")

    # Wrong number of atoms in coordinate data
    with pytest.raises(RuntimeError):
        x = molecule.load("mae", file_3nob, "pdb", file_3frames)
        print(molecule.get_filenames(x))

    molecule.delete(m)
示例#24
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)
示例#25
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)
示例#26
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)
示例#27
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 == []
示例#28
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)
示例#29
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)
示例#30
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)
示例#31
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)
示例#32
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)
示例#33
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)
示例#34
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)
示例#35
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)
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)
示例#37
0
    def write(self):
        """
        Writes the final built system.

        Args:
          filename (str): Name of file
        """

        fileutils.check_write_ok(self.opts.get('output_filename'),
                                 self.out_fmt,
                                 overwrite=self.opts.get('overwrite'))
        final_id = self._build()

        print("Writing system to %s with %d atoms comprising:\n"
              "  %d lipid molecules\n"
              "  %d water molecules\n" %
              (self.opts.get('output_filename'),
               molutils.num_atoms_remaining(molid=final_id),
               molutils.num_lipids_remaining(final_id,
                                             self.opts.get('lipid_sel')),
               molutils.num_waters_remaining(molid=final_id)))
        fileutils.write_final_system(
            out_fmt=self.out_fmt,
            out_name=self.opts.get('output_filename'),
            molid=final_id,
            tmp_dir=self.tmp_dir,
            forcefield=self.opts.get('forcefield'),
            extra_topos=self.opts.get('extra_topos'),
            extra_params=self.opts.get('extra_params'),
            extra_streams=self.opts.get('extra_streams'),
            hmassrepartition=self.opts.get('hmassrepartition'),
            verbose=self.opts.get('debug_verbose'))
        molecule.delete(final_id)
def test_multiligand_building(tmpdir):
    """
    Solvates and membranes a system with multiple ligands """
    from dabble import DabbleBuilder
    p = str(tmpdir)

    # Build the system
    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.x) - min(solsel.x)
    prot_y = max(solsel.y) - min(solsel.y)
    prot_z = max(solsel.z) - min(solsel.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").resid)) == 10
    assert len(atomsel("resname ALP")) == 420

    molecule.delete(m2)
示例#39
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")
示例#40
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)
示例#41
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)
示例#42
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)
示例#43
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)
示例#44
0
def test_mutation(tmpdir):
    """
    Tests mutation of L2A in chain 0. Also as a result tests guessing
    coordinates
    """
    from psfgen import PsfGen
    p = str(tmpdir.mkdir("mutation"))
    os.chdir(dir)

    gen = PsfGen(output=os.devnull)
    gen.read_topology("top_all36_caps.rtf")
    gen.read_topology("top_all36_prot.rtf")

    gen.add_segment(segid="P0",
                    pdbfile="psf_protein_P0.pdb",
                    mutate=[("2", "ALA")])
    gen.read_coords(segid="P0", filename="psf_protein_P0.pdb")
    gen.patch(patchname="DISU", targets=[("P0", "10"), ("P0", "15")])

    # Guess coordinates for ALA mutation
    gen.guess_coords()

    # Set one specific coordinate
    gen.set_position(segid="P0",
                     resid="2",
                     atomname="HB1",
                     position=(1.0, 2.0, 3.0))

    # Regenerate
    gen.regenerate_angles()
    gen.regenerate_dihedrals()

    # Write
    os.chdir(p)
    gen.write_psf(filename="output.psf")
    gen.write_pdb(filename="output.pdb")

    # Check results with vmd-python
    m = molecule.load("psf", "output.psf", "pdb", "output.pdb")
    assert len(set(atomsel("protein").fragment)) == 1
    assert len(set(atomsel("resname ACE NMA NME").residue)) == 2

    # Test mutation happened and resid 2 is ALA not LEU
    assert set(atomsel("resid 2").resname) == set(["ALA"])

    # Check coordinate guessing happened and HB3 has a nonzero position
    assert atomsel("resid 2 and name HB3").x != [0.0]
    assert atomsel("resid 2 and name HB3").y != [0.0]
    assert atomsel("resid 2 and name HB3").z != [0.0]

    # Check manual coordinate setting happened
    assert atomsel("resid 2 and name HB1").x == [1.0]
    assert atomsel("resid 2 and name HB1").y == [2.0]
    assert atomsel("resid 2 and name HB1").z == [3.0]

    molecule.delete(m)
示例#45
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)
示例#46
0
def test_create():

    m = molecule.new(name="test", natoms=3000)
    assert molecule.name(m) == "test"
    assert molecule.numatoms(m) == 3000

    with pytest.raises(ValueError):
        m = molecule.new("test2", -2000)

    molecule.delete(m)
示例#47
0
def test_create():

    m = molecule.new(name="test", natoms=3000)
    assert molecule.name(m) == "test"
    assert molecule.numatoms(m) == 3000

    with pytest.raises(ValueError):
        m = molecule.new("test2", -2000)

    molecule.delete(m)
示例#48
0
    def generate_initial_ensemble(self):
        """
        Generates an initial ensemble of frames where one ligand
        is picked based on its hub score. This method alone does
        the exact same thing as the previous code, but will be
        extended to alter the positions of the other ligands
        to correspond to other resampled clusters.
        """

        # Choose which clusters to resample
        if self.criteria == "hub_scores":
            selected = list(
                self.msm.inverse_transform(self.scores.argsort())[0])
        elif self.criteria == "populations":
            selected = list(
                self.msm.inverse_transform(self.msm.populations_.argsort())[0])
        elif self.criteria == "counts":
            selected = self.counts  # From cluster labels, so no need for transform

        # If enforcing sample region, this will be non-None
        selstr = self.config.get("model", "sampleregion")

        # Go through all of our resamplers until the correct number
        # have been done. Use cluster list as a refilling queue.
        molids = []
        while len(molids) != self.nreps:
            # Pick a cluster from the cluster queue
            clust = selected.pop(0)
            selected.append(clust)

            # Generate a frame with this cluster and check resampled ligand
            # is in the restricted selection area, if present
            mid = -1
            failures = 0
            while mid == -1 and failures <= 3:
                mid = self.pick_random_frame(clust)
                if not self._validate_frame(mid, selstr):
                    print("        Attempt fail for cluster: %d" % clust)
                    failures += 1
                    molecule.delete(mid)
                    mid = -1

            # If this cluster didn't work, continue to the next one
            if mid == -1:
                print("  Failed to select cluster: %d" % clust)
                continue

            # Otherwise, add it to our list of sampled clusters
            molids.append(mid)

            # Save and start adding job for this
            self.save_initial_molecule(molid=mid,
                                       sampled=clust,
                                       repindex=len(molids))
示例#49
0
def test_ends(tmpdir):
    """
    Tests adding patches to the beginning and end, as well as adding
    residues in the segment
    """
    from psfgen import PsfGen
    p = str(tmpdir.mkdir("mutation"))
    os.chdir(dir)

    gen = PsfGen(output=os.devnull)
    gen.read_topology("top_all36_prot.rtf")

    # Add neutral N-terminus
    # Add an alanine then a protonated glutamate at the C-terminus.
    gen.add_segment(segid="P",
                    pdbfile="protein_nocaps.pdb",
                    first="NTER",
                    last="GLUP",
                    residues=[("25", "ALA"), ("26", "GLU")])

    # Set coordinates and regenerate angles and dihedrals
    gen.read_coords(segid="P", filename="protein_nocaps.pdb")
    gen.guess_coords()

    # Check internal state
    assert gen.get_resids("P") == [str(_) for _ in range(2, 27)]
    assert gen.get_resname(segid="P", resid=25) == "ALA"
    assert gen.get_patches(list_defaults=True) == [('GLUP', 'P', '26'),
                                                   ('NTER', 'P', '2')]
    assert gen.get_first(segid="P") == "NTER"
    assert gen.get_last(segid="P") == "GLUP"

    # Output
    os.chdir(p)
    gen.write_psf(filename="output.psf")
    gen.write_pdb(filename="output.pdb")

    # Check all resids are present and that 2 extra ones were added
    m = molecule.load("psf", "output.psf", "pdb", "output.pdb")
    assert list(set(atomsel("all").resid)) == list(range(2, 27))
    assert len(atomsel("all")) == 382
    assert set(atomsel("resid 25").resname) == set(["ALA"])

    # Check patches were applied correctly
    assert "HT1" in atomsel("resid 2").name
    assert "HN" not in atomsel("resid 2").name
    assert "HE2" in atomsel("resid 26").name

    # Check all coordinates are set
    assert 0.0 not in atomsel("all").x
    assert 0.0 not in atomsel("all").y
    assert 0.0 not in atomsel("all").z

    molecule.delete(m)
示例#50
0
def test_atomsel_minmax_center(file_3frames):

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

    # Minmax without radii
    assert sel.minmax() == (approx((2.497, 0.724, -0.890)),
                            approx((6.009, 4.623, 2.131)))


    # Minmax with radii
    sel.radius  = 10.0
    assert sel.minmax(radii=True) == (approx((2.497-10., 0.724-10., -0.890-10.)),
                                      approx((6.009+10., 4.623+10., 2.131+10.)))

    assert sel.center(weight=None) == approx((4.040, 2.801, 0.492), rel=1e-3)
    assert sel.center(weight=[0.]*9+ [1.]) == atomsel("index 9", m).center()

    # Wrong number of weights
    with pytest.raises(TypeError):
        sel.center(weight=3.0)
    with pytest.raises(ValueError):
        sel.center([3.,2.])


    sel = atomsel("all")
    assert sel.centerperresidue() == [approx((4.040, 2.801, 0.492), rel=1e-3),
                                      approx((7.260, 3.987, 0.000), rel=1e-3)]
    assert sel.centerperresidue(weight=None)[0] == alasel.centerperresidue()[0]


    # Centerperresidue with weights
    with pytest.raises(TypeError):
        sel.centerperresidue(weight=[True]*len(sel))
    with pytest.raises(TypeError):
        sel.centerperresidue(3)
    with pytest.raises(ValueError):
        sel.centerperresidue([1.0,2.0])

    weights = [1.0]*10 + [0.0]*6
    assert sel.centerperresidue(weight=weights)[0] == approx(alasel.center(),
                                                             rel=1e-3)
    assert all([math.isnan(x) for x in sel.centerperresidue(weights)[1]])
    molecule.delete(m)

    # Operations on deleted molecule
    with pytest.raises(ValueError):
        sel.minmax(radii=False)
    with pytest.raises(ValueError):
        sel.centerrperres()
    with pytest.raises(ValueError):
        sel.center()
示例#51
0
def test_atomsel_minmax_center(file_3frames):

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

    # Minmax without radii
    assert sel.minmax() == (approx(
        (2.497, 0.724, -0.890)), approx((6.009, 4.623, 2.131)))

    # Minmax with radii
    sel.radius = 10.0
    assert sel.minmax(radii=True) == (approx(
        (2.497 - 10., 0.724 - 10.,
         -0.890 - 10.)), approx((6.009 + 10., 4.623 + 10., 2.131 + 10.)))

    assert sel.center(weight=None) == approx((4.040, 2.801, 0.492), rel=1e-3)
    assert sel.center(weight=[0.] * 9 + [1.]) == atomsel("index 9", m).center()

    # Wrong number of weights
    with pytest.raises(TypeError):
        sel.center(weight=3.0)
    with pytest.raises(ValueError):
        sel.center([3., 2.])

    sel = atomsel("all")
    assert sel.centerperresidue() == [
        approx((4.040, 2.801, 0.492), rel=1e-3),
        approx((7.260, 3.987, 0.000), rel=1e-3)
    ]
    assert sel.centerperresidue(weight=None)[0] == alasel.centerperresidue()[0]

    # Centerperresidue with weights
    with pytest.raises(TypeError):
        sel.centerperresidue(weight=[True] * len(sel))
    with pytest.raises(TypeError):
        sel.centerperresidue(3)
    with pytest.raises(ValueError):
        sel.centerperresidue([1.0, 2.0])

    weights = [1.0] * 10 + [0.0] * 6
    assert sel.centerperresidue(weight=weights)[0] == approx(alasel.center(),
                                                             rel=1e-3)
    assert all([math.isnan(x) for x in sel.centerperresidue(weights)[1]])
    molecule.delete(m)

    # Operations on deleted molecule
    with pytest.raises(ValueError):
        sel.minmax(radii=False)
    with pytest.raises(ValueError):
        sel.centerrperres()
    with pytest.raises(ValueError):
        sel.center()
示例#52
0
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)
示例#53
0
def test_multiple_frames(file_3frames):
    m = molecule.load("pdb", file_3frames)

    assert measure.bond(0, 1) == [pytest.approx(1.0093883275)]

    with pytest.warns(SyntaxWarning):
        assert measure.dihedral(0, 1, 2, 3, molid=m, frame=0,
                                first=1, last=2)[0] == pytest.approx(-70.578407)

    x = measure.dihedral(0, 1, 2, 3, first=0, last=-1)
    assert len(x) == 3
    assert x == [pytest.approx(-70.578407)] * 3

    molecule.delete(m)
示例#54
0
def test_rep_attributes(file_3nob):
    m = molecule.load("mae", file_3nob)

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

    # Query name
    assert molrep.get_repname(molid=m, rep=r) == "rep1"
    with pytest.raises(ValueError):
        molrep.get_repname(m+1, 0)
    with pytest.raises(ValueError):
        molrep.get_repname(m, r+1)

    # Query ID
    assert molrep.repindex(m, "rep1") == r
    assert molrep.repindex(m, "nonexistent") is None
    with pytest.raises(ValueError):
        molrep.repindex(m+1, "wrong")

    # Query style
    assert molrep.get_style(m, r) == "NewCartoon"
    with pytest.raises(ValueError):
        molrep.get_style(m+1, 0)
    with pytest.raises(ValueError):
        molrep.get_style(m, r+1)

    # Query selection
    assert molrep.get_selection(m, r) == "protein"
    with pytest.raises(ValueError):
        molrep.get_selection(m+1, 0)
    with pytest.raises(ValueError):
        molrep.get_selection(m, r+1)

    # Query color
    assert molrep.get_color(m, r) == "ResID"
    with pytest.raises(ValueError):
        molrep.get_color(m+1, 0)
    with pytest.raises(ValueError):
        molrep.get_color(m, r+1)

    # Query material
    assert molrep.get_material(m, r) == "AOShiny"
    with pytest.raises(ValueError):
        molrep.get_material(m+1, 0)
    with pytest.raises(ValueError):
        molrep.get_material(m, r+1)

    molecule.delete(m)
示例#55
0
def test_colors():
    mid = molecule.new(name="colortest")

    graphics.color(mid, 1)
    graphics.color(mid, "blue2")

    with pytest.raises(ValueError):
        graphics.color(mid, -1)

    with pytest.raises(ValueError):
        graphics.color(mid, "not a color")

    with pytest.raises(TypeError):
        graphics.color(mid, 32.0)

    molecule.delete(mid)
示例#56
0
def test_atomsel_rgyr(file_3frames):

    m = molecule.load("pdb", file_3frames)
    atomsel(molid=m, frame=0).moveby((4.0, 0.0, 0.0))
    atomsel("all", m, 1).moveby((0.0, -4.0, 0.0))

    sel = atomsel("resname ALA", m)
    assert sel.rgyr() == approx(1.71880459)

    # Empty selection
    with pytest.raises(ValueError):
        atomsel("resname NOPE", m).rgyr()

    molecule.delete(m)
    with pytest.raises(ValueError):
        sel.rgyr()
示例#57
0
def test_replace():

    mid2 = molecule.load("graphics", "heya")
    rc = graphics.point(mid2, (0,0,0))
    assert graphics.info(mid2, rc) == "point {0.000000 0.000000 0.000000}"
    rc2 = graphics.point(mid2, (1,1,1))
    assert graphics.listall(mid2) == [rc, rc2]

    graphics.replace(molid=mid2, graphic=rc)
    assert graphics.listall(mid2) == [rc2]

    rc3 = graphics.point(mid2, (2,2,2))
    assert graphics.listall(mid2) == [rc3, rc2]
    assert graphics.info(mid2, rc2) == "point {1.000000 1.000000 1.000000}"

    molecule.delete(mid2)